def __init__(self, engine, user, strategy, name, symbols, time_frame, id=None, parent=None): """ 信号对象,每一个信号即为策略代码中不以init为名的任意最外层函数,订阅某些品种的行情数据,运行于特定时间框架下。 通过两个EventPacker(事件打包器)接受StrategyEngine中的DataCache(数据中转器)发出的行情事件来管理Bar数据的结构。 :param engine:挂载运行的策略引擎 :param symbols:所订阅行情数据的品种列表 :param time_frame:所订阅行情数据的事件框架 :param id:不需要传入,由SignalFactory自动管理。 """ Runnable.__init__(self) APIInterface.__init__(self) ConfigInterface.__init__(self, parent=parent) self._id = id self._user = user self._strategy = strategy self._name = name self._event_update = Event.create_event_type('SignalUpdate.%s.%s.%s' % (self._user, self._strategy, self._name), priority=1).get_id() self._event_completed = Event.create_event_type( 'SignalCompleted.%s.%s.%s' % (self._user, self._strategy, self._name), priority=2).get_id() self._update = SymbolBarUpdateEventsPacker(engine, symbols, time_frame, self._event_update) self._completed = SymbolBarCompletedEventsPacker(engine, symbols, time_frame, self._event_completed) self._parameters = OrderedDict() self._symbols = symbols self._time_frame = time_frame self._engine = engine self._handler = None self._generator = None self._gene_instance = None self._bar_num = 0 # 暂时使用在LocalsInjector中改写的方式 self._environment = None
def __onTimer(self): """向事件队列中存入计时器事件""" # 创建计时器事件 event = Event(type=EVENT_TIMER) # 向队列中存入计时器事件 self.put(event)
def __init__(self, engine, user, strategy, name, symbols, time_frame, id=None, parent=None): """ 信号对象,每一个信号即为策略代码中不以init为名的任意最外层函数,订阅某些品种的行情数据,运行于特定时间框架下。 通过两个EventPacker(事件打包器)接受StrategyEngine中的DataCache(数据中转器)发出的行情事件来管理Bar数据的结构。 :param engine:挂载运行的策略引擎 :param symbols:所订阅行情数据的品种列表 :param time_frame:所订阅行情数据的事件框架 :param id:不需要传入,由SignalFactory自动管理。 """ Runnable.__init__(self) APIInterface.__init__(self) ConfigInterface.__init__(self, parent=parent) self._id = id self._user = user self._strategy = strategy self._name = name self._event_update = Event.create_event_type( 'SignalUpdate.%s.%s.%s' % (self._user, self._strategy, self._name), priority=1).get_id() self._event_completed = Event.create_event_type( 'SignalCompleted.%s.%s.%s' % (self._user, self._strategy, self._name), priority=2).get_id() self._update = SymbolBarUpdateEventsPacker(engine, symbols, time_frame, self._event_update) self._completed = SymbolBarCompletedEventsPacker( engine, symbols, time_frame, self._event_completed) self._parameters = OrderedDict() self._symbols = symbols self._time_frame = time_frame self._engine = engine self._handler = None self._generator = None self._gene_instance = None self._bar_num = 0 # 暂时使用在LocalsInjector中改写的方式 self._environment = None
def update_bar(self, bar: Bar): symbol = bar.symbol time_frame = bar.time_frame quotation = self._data_view.find(symbol, time_frame) self.current_time = bar.close_time if not self.current_time else max(self.current_time, bar.close_time) last_time = quotation.timestamp[0] if quotation.timestamp else 0 if self.config.trading_mode == TradingMode.on_tick: quotation.tick_open = bar.open if bar.timestamp - last_time >= tf2s(time_frame): # 当last_time = 0时,该条件显然成立 for field in ['open', 'high', 'low', 'close', 'datetime', 'timestamp', 'volume']: getattr(quotation, field).appendleft(getattr(bar, field)) self._engine.put_event(Event(EVENT_SYMBOL_BAR_COMPLETED[symbol][time_frame])) else: quotation.high[0] = max(quotation.high[0], bar.high) quotation.low[0] = min(quotation.low[0], bar.low) quotation.volume[0] += bar.volume for field in ["datetime", "timestamp", "close"]: getattr(quotation, field)[0] = getattr(bar, field) self._engine.put_event(Event(EVENT_SYMBOL_BAR_UPDATE[symbol][time_frame]))
def init(self): if self.__initialized: return True assert isinstance(self._config, BfConfig) # 判断初始化前是否设置好了基本参数 self.__strategy_engine = StrategyEngine(parent=self) self.__strategy = Strategy(self.__strategy_engine, self.__code, parent=self) self.__strategy_engine.add_strategy(self.__strategy) self.__rt_data_generator = TickDataGenerator( lambda x: self.__strategy_engine.put_event(x.to_event()), partial(self.__strategy_engine.put_event, Event(EVENT_FINISH)), parent=self) self.__tb_data_generator = DataGenerator( lambda x: self.__strategy_engine.put_event(x.to_event()), partial(self.__strategy_engine.put_event, Event(EVENT_EMPTY, message="traceback over")), parent=self) if DEBUG: self.logger.setLevel(logging.DEBUG) else: self.logger.setLevel(logging.INFO) self.__initialized = True
def init(self): if self.__initialized: return None assert self._config is not None # 判断初始化前是否设置好了基本参数 self.__strategy_engine = StrategyEngine(parent=self) self.__strategy = Strategy(self.__strategy_engine, self.__code, parent=self) self.__strategy_engine.add_strategy(self.__strategy) self.__data_generator = DataGenerator( lambda x: self.__strategy_engine.put_event(x.to_event()), lambda: self.__strategy_engine.put_event(Event(EVENT_FINISH)), parent=self) if DEBUG: self.logger.setLevel(logging.DEBUG) else: self.logger.setLevel(logging.INFO) self.__initialized = True
def __run(self): """引擎运行""" self.logger.debug("事件引擎开始运行") while self.__active: try: *_, event = self.__queue.get(block=True, timeout=0.5) # 获取事件的阻塞时间设为0.5秒 self.__process(event) except Empty: self.put(Event(EVENT_EMPTY, message=None)) # 标志队列已空 time.sleep(0) except Exception as e: self.__exc_type, self.__exc_value, self.__exc_traceback = sys.exc_info( ) self.logger.error("\n" + traceback.format_exc()) self.__active = False self.stop() for file in self.__file_opened: if not file.closed: file.flush() file.close() self.__file_opened.clear() self.logger.debug("事件引擎停止运行")
def out(self): if self.events_out: self.engine.put_event(Event(type=self.events_out))
def target(*args, **kwargs): result = func(*args, **kwargs) event = Event( EVENT_ASYNC, {'func': partial(callback, *result[0], **result[1])}) engine.put(event)
def to_event(self): event = Event(EVENT_SYMBOL_BAR_RAW[self.symbol][self.time_frame], data=self) return event
def to_event(cls, bar): event = Event(EVENT_SYMBOL_BAR_RAW[bar.symbol][bar.time_frame], data=bar) return event
def to_event(self): event = Event(EVENT_SYMBOL_TICK_RAW[self.symbol], data=self) return event
def to_event(self): event = Event(EVENT_BAR_SYMBOL[self.symbol][self.time_frame], {'data': self}) return event
def write_log(self, log): """写日志""" self.__event_engine.put(Event(type=EVENT_LOG, log=log))