def start_up(self, env, mod_config): # type: (Environment, Any) -> None FuturePosition.enable_position_validator = mod_config.validate_future_position StockPosition.dividend_reinvestment = mod_config.dividend_reinvestment StockPosition.cash_return_by_stock_delisted = mod_config.cash_return_by_stock_delisted StockPosition.t_plus_enabled = mod_config.stock_t1 StockPosition.enable_position_validator = mod_config.validate_stock_position if DEFAULT_ACCOUNT_TYPE.FUTURE in env.config.base.accounts: # 注入期货API # noinspection PyUnresolvedReferences from .api import api_future if DEFAULT_ACCOUNT_TYPE.STOCK in env.config.base.accounts: # 注入股票API # noinspection PyUnresolvedReferences from .api import api_stock for instrument_type in INST_TYPE_IN_STOCK_ACCOUNT: Portfolio.register_instrument_type(instrument_type, DEFAULT_ACCOUNT_TYPE.STOCK, StockPosition, order_stock, StockPositionProxy) Portfolio.register_instrument_type(INSTRUMENT_TYPE.FUTURE, DEFAULT_ACCOUNT_TYPE.FUTURE, FuturePosition, order_future, FuturePositionProxy)
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