def before_trading_(self, event): self._stage = 'before_trading' for day_rule, time_rule, func in self._registry: if day_rule() and time_rule(): with ExecutionContext(EXECUTION_PHASE.BEFORE_TRADING): with ModifyExceptionFromType(EXC_TYPE.USER_EXC): func(self.ucontext, None) self._stage = None
def init(self): if self._init: with ExecutionContext(EXECUTION_PHASE.ON_INIT): with ModifyExceptionFromType(EXC_TYPE.USER_EXC): self._init(self._user_context) Environment.get_instance().event_bus.publish_event( Event(EVENT.POST_USER_INIT))
def next_bar_(self, event): bars = event.bar_dict self._current_minute = self._minutes_since_midnight( self.ucontext.now.hour, self.ucontext.now.minute) for day_rule, time_rule, func in self._registry: if day_rule() and time_rule(): with ExecutionContext(EXECUTION_PHASE.SCHEDULED): with ModifyExceptionFromType(EXC_TYPE.USER_EXC): func(self.ucontext, bars) self._last_minute = self._current_minute
def run(config, source_code=None, user_funcs=None): env = Environment(config) persist_helper = None init_succeed = False mod_handler = ModHandler() try: # avoid register handlers everytime # when running in ipython set_loggers(config) init_rqdatac(getattr(config.base, 'rqdatac_uri', None)) system_log.debug("\n" + pformat(config.convert_to_dict())) env.set_strategy_loader( init_strategy_loader(env, source_code, user_funcs, config)) mod_handler.set_env(env) mod_handler.start_up() if not env.data_source: env.set_data_source( BaseDataSource(config.base.data_bundle_path, getattr(config.base, "future_info", {}))) if env.price_board is None: from rqalpha.data.bar_dict_price_board import BarDictPriceBoard env.price_board = BarDictPriceBoard() env.set_data_proxy(DataProxy(env.data_source, env.price_board)) _adjust_start_date(env.config, env.data_proxy) ctx = ExecutionContext(const.EXECUTION_PHASE.GLOBAL) ctx._push() # FIXME start_dt = datetime.datetime.combine(config.base.start_date, datetime.datetime.min.time()) env.calendar_dt = start_dt env.trading_dt = start_dt assert env.broker is not None assert env.event_source is not None if env.portfolio is None: from rqalpha.portfolio import Portfolio env.set_portfolio( Portfolio(config.base.accounts, config.base.init_positions)) env.event_bus.publish_event(Event(EVENT.POST_SYSTEM_INIT)) scope = create_base_scope() scope.update({"g": env.global_vars}) scope.update(get_strategy_apis()) scope = env.strategy_loader.load(scope) if config.extra.enable_profiler: enable_profiler(env, scope) ucontext = StrategyContext() executor = Executor(env) persist_helper = init_persist_helper(env, ucontext, executor, config) user_strategy = Strategy(env.event_bus, scope, ucontext) env.user_strategy = user_strategy env.event_bus.publish_event(Event(EVENT.BEFORE_STRATEGY_RUN)) if persist_helper: with LogCapture(user_log) as log_capture: user_strategy.init() else: user_strategy.init() if config.extra.context_vars: for k, v in config.extra.context_vars.items(): if isinstance(v, RqAttrDict): v = v.__dict__ setattr(ucontext, k, v) if persist_helper: env.event_bus.publish_event(Event(EVENT.BEFORE_SYSTEM_RESTORED)) restored_obj_state = persist_helper.restore(None) check_key = ["global_vars", "user_context", "executor", "universe"] kept_current_init_data = not any( v for k, v in restored_obj_state.items() if k in check_key) system_log.debug( "restored_obj_state: {}".format(restored_obj_state)) system_log.debug( "kept_current_init_data: {}".format(kept_current_init_data)) if kept_current_init_data: # 未能恢复init相关数据 保留当前策略初始化变量(展示当前策略初始化日志) log_capture.replay() else: user_system_log.info(_('system restored')) env.event_bus.publish_event(Event(EVENT.POST_SYSTEM_RESTORED)) init_succeed = True bar_dict = BarMap(env.data_proxy, config.base.frequency) executor.run(bar_dict) env.event_bus.publish_event(Event(EVENT.POST_STRATEGY_RUN)) if env.profile_deco: output_profile_result(env) release_print(scope) except CustomException as e: if init_succeed and persist_helper and env.config.base.persist_mode == const.PERSIST_MODE.ON_CRASH: persist_helper.persist() code = _exception_handler(e) mod_handler.tear_down(code, e) except Exception as e: system_log.error(traceback.format_exc()) if init_succeed and persist_helper and env.config.base.persist_mode == const.PERSIST_MODE.ON_CRASH: persist_helper.persist() exc_type, exc_val, exc_tb = sys.exc_info() user_exc = create_custom_exception(exc_type, exc_val, exc_tb, config.base.strategy_file) code = _exception_handler(user_exc) mod_handler.tear_down(code, user_exc) else: if persist_helper and env.config.base.persist_mode == const.PERSIST_MODE.ON_NORMAL_EXIT: persist_helper.persist() result = mod_handler.tear_down(const.EXIT_CODE.EXIT_SUCCESS) system_log.debug(_(u"strategy run successfully, normal exit")) return result
def handle_bar(self, event): bar_dict = event.bar_dict with ExecutionContext(EXECUTION_PHASE.ON_BAR): with ModifyExceptionFromType(EXC_TYPE.USER_EXC): self._handle_bar(self._user_context, bar_dict)
def before_trading(self, event): with ExecutionContext(EXECUTION_PHASE.BEFORE_TRADING): with ModifyExceptionFromType(EXC_TYPE.USER_EXC): self._before_trading(self._user_context)
def wrapped_handler(event): with ExecutionContext(EXECUTION_PHASE.GLOBAL): with ModifyExceptionFromType(EXC_TYPE.USER_EXC): return handler(self._user_context, event)
def after_trading(self, event): with ExecutionContext(EXECUTION_PHASE.AFTER_TRADING): with ModifyExceptionFromType(EXC_TYPE.USER_EXC): self._after_trading(self._user_context)
def handle_tick(self, event): tick = event.tick with ExecutionContext(EXECUTION_PHASE.ON_TICK): with ModifyExceptionFromType(EXC_TYPE.USER_EXC): self._handle_tick(self._user_context, tick)
def open_auction(self, event): bar_dict = event.bar_dict with ExecutionContext(EXECUTION_PHASE.OPEN_AUCTION): with ModifyExceptionFromType(EXC_TYPE.USER_EXC): self._open_auction(self._user_context, bar_dict)