| 16 | |
| 17 | |
| 18 | class FixedMainEngine(MainEngine): |
| 19 | def __init__(self, broker, need_data='ht.json', quotation_engines=[FixedDataEngine], |
| 20 | log_handler=DefaultLogHandler(), ext_stocks=[]): |
| 21 | super(FixedMainEngine, self).__init__(broker, need_data, [], log_handler) |
| 22 | if type(quotation_engines) != list: |
| 23 | quotation_engines = [quotation_engines] |
| 24 | self.quotation_engines = [] |
| 25 | # 修改时间缓存 |
| 26 | self._cache = {} |
| 27 | # 文件进程映射 |
| 28 | self._process_map = {} |
| 29 | # 文件模块映射 |
| 30 | self._modules = {} |
| 31 | self._names = None |
| 32 | # 加载锁 |
| 33 | self.lock = Lock() |
| 34 | # 加载线程 |
| 35 | self._watch_thread = Thread(target=self._load_strategy, name="FixedMainEngine.watch_reload_strategy") |
| 36 | positions = [p['stock_code'] for p in self.user.position] |
| 37 | positions.extend(ext_stocks) |
| 38 | for quotation_engine in quotation_engines: |
| 39 | self.quotation_engines.append(quotation_engine(self.event_engine, self.clock_engine, positions)) |
| 40 | |
| 41 | def load(self, names, strategy_file): |
| 42 | with self.lock: |
| 43 | mtime = os.path.getmtime(os.path.join('strategies', strategy_file)) |
| 44 | |
| 45 | # 是否需要重新加载 |
| 46 | reload = False |
| 47 | strategy_module_name = os.path.basename(strategy_file)[:-3] |
| 48 | if self._cache.get(strategy_file, None) == mtime: |
| 49 | return |
| 50 | elif self._cache.get(strategy_file, None) is not None: |
| 51 | # 原有进程退出 |
| 52 | _process = self._process_map.get(strategy_file) |
| 53 | self.unbind_event(_process) |
| 54 | _process.stop() |
| 55 | self.log.info(u'卸载策略: %s' % strategy_module_name) |
| 56 | time.sleep(2) |
| 57 | reload = True |
| 58 | # 重新加载 |
| 59 | if reload: |
| 60 | strategy_module = importlib.reload(self._modules[strategy_file]) |
| 61 | else: |
| 62 | strategy_module = importlib.import_module('.' + strategy_module_name, 'strategies') |
| 63 | self._modules[strategy_file] = strategy_module |
| 64 | |
| 65 | strategy_class = getattr(strategy_module, 'Strategy') |
| 66 | if names is None or strategy_class.name in names: |
| 67 | self.strategies[strategy_module_name] = strategy_class |
| 68 | # 进程包装 |
| 69 | _process = ProcessWrapper(strategy_class(self.user, log_handler=self.log, main_engine=self)) |
| 70 | # 缓存加载信息 |
| 71 | self._process_map[strategy_file] = _process |
| 72 | self.strategy_list.append(_process) |
| 73 | self._cache[strategy_file] = mtime |
| 74 | self.bind_event(_process) |
| 75 | self.log.info(u'加载策略: %s' % strategy_module_name) |
nothing calls this directly
no outgoing calls
no test coverage detected