# encoding: utf-8

from threading import Thread
import time
import datetime
import redis
import sys

'''
from .server.redisConfig import redisConf,jsonList
from .BT import engine2
from .util.kySDK import *
from .BT.evaluator import evaluator
'''

import os
#sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
#print(sys.path) 
from .server.redisConfig import redisConf,jsonList
from .BT.engine2 import Engine
from .util.kySDK import *
from .BT.evaluator import evaluator

import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.CRITICAL)
import multiprocessing as mp

class BTRobot():
    def __init__(self):
        self.r = redis.StrictRedis(host=redisConf['host'], port=redisConf['port'], db=0)
        self.robotNum = 0

    def cleanQueue(self):
        print('先清空队列,队列长度为: %d'%self.r.llen(jsonList))
        while self.r.llen(jsonList) != 0:
            self.r.rpop(jsonList)

    def process_task(self):
    # 从队列中取参数
        while True:
            try:
                params = self.r.brpop(jsonList)
                params = eval(params[1].decode())
                print('params',type(params),params)
                myBT = Engine(params) #initialize engine
                if myBT.stockPicker['pick'] == False: 
                    myBT.backTesting()
                    evaluator(myBT.strategyID,myBT.BTRecords,myBT.IndexRecords,plot = False)
                elif myBT.stockPicker['pick'] == True:
                    for day in myBT.stockPicker['dateList']:
                        myBT.stockPicking(day) #是选的哪一天的？？？
            except Exception as e:
                print(e)
    
    def turnOn(self,processNum):
        self.cleanQueue()
        print('开启 %d 个机器人'%processNum)
        processes = [mp.Process(target=self.process_task()) for x in range(processNum)]
        
        # Run processes
        for p in processes:
            p.start()
                 

        # Exit the completed processes
        for p in processes:
            p.join()
        
    
if __name__ == '__main__': 
    myRobot = BTRobot()
    myRobot.turnOn(20)
    

    

