Exemple #1
0
    def __init__(self, config: BacktestConfig):
        logger = logging.getLogger(__name__)
        logger.info('Serenity backtester starting up')

        sys.path.append(str(config.get_strategy_basedir()))

        bt_env = config.get_env()

        exchange_id = bt_env.getenv('EXCHANGE_ID', 'autofill')
        instance_id = bt_env.getenv('EXCHANGE_INSTANCE', 'prod')
        account = bt_env.getenv('EXCHANGE_ACCOUNT', 'Main')

        self.logger.info('Connecting to Serenity database')
        conn = connect_serenity_db()
        conn.autocommit = True
        cur = conn.cursor()

        self.scheduler = HistoricNetworkScheduler(
            config.get_start_time_millis(), config.get_end_time_millis())
        instrument_cache = InstrumentCache(cur, TypeCodeCache(cur))

        oms = OrderManagerService(self.scheduler)

        md_service = AzureHistoricMarketdataService(
            self.scheduler, bt_env.getenv('AZURE_CONNECT_STR'))
        mark_service = MarketdataMarkService(self.scheduler.get_network(),
                                             md_service)
        op_service = OrderPlacerService(self.scheduler, oms)
        op_service.register_order_placer(
            f'{exchange_id}:{instance_id}',
            AutoFillOrderPlacer(self.scheduler, oms, md_service, account))

        xps = NullExchangePositionService(self.scheduler)

        extra_outputs_txt = bt_env.getenv('EXTRA_OUTPUTS')
        if extra_outputs_txt is None:
            extra_outputs = []
        else:
            extra_outputs = extra_outputs_txt.split(',')
        self.dcs = HDF5DataCaptureService(Mode.BACKTEST, self.scheduler,
                                          extra_outputs)

        # wire up orders and fills from OMS
        Do(self.scheduler.get_network(), oms.get_orders(),
           lambda: self.dcs.capture_order(oms.get_orders().get_value()))
        Do(self.scheduler.get_network(), oms.get_order_events(),
           lambda: self.dcs.capture_fill(oms.get_order_events().get_value()))

        self.strategy_name = config.get_strategy_name()
        strategy_env = config.get_strategy_env()
        ctx = StrategyContext(self.scheduler, instrument_cache, md_service,
                              mark_service, op_service,
                              PositionService(self.scheduler, oms), xps,
                              self.dcs, strategy_env.values)
        strategy_instance = config.get_strategy_instance()
        strategy_instance.init(ctx)
        strategy_instance.start()