class TraderTests(unittest.TestCase):
    def setUp(self):
        # Fixture Setup
        usdjpy = InstrumentLoader.default_fx_ccy(
            TestStubs.symbol_usdjpy_fxcm())
        data = BacktestDataContainer()
        data.add_instrument(usdjpy)
        data.add_bars(usdjpy.symbol, BarAggregation.MINUTE, PriceType.BID,
                      TestDataProvider.usdjpy_1min_bid()[:2000])
        data.add_bars(usdjpy.symbol, BarAggregation.MINUTE, PriceType.ASK,
                      TestDataProvider.usdjpy_1min_ask()[:2000])

        clock = TestClock()
        uuid_factory = TestUUIDFactory()
        logger = TestLogger(clock)
        trader_id = TraderId("TESTER", "000")
        account_id = TestStubs.account_id()

        self.portfolio = Portfolio(
            clock=clock,
            uuid_factory=uuid_factory,
            logger=logger,
        )

        data_engine = BacktestDataEngine(
            data=data,
            tick_capacity=1000,
            bar_capacity=1000,
            portfolio=self.portfolio,
            clock=clock,
            logger=logger,
        )

        self.analyzer = PerformanceAnalyzer()

        self.exec_db = BypassExecutionDatabase(
            trader_id=trader_id,
            logger=logger,
        )

        self.exec_engine = ExecutionEngine(
            database=self.exec_db,
            portfolio=self.portfolio,
            clock=clock,
            uuid_factory=uuid_factory,
            logger=logger,
        )

        self.market = SimulatedMarket(
            venue=Venue("FXCM"),
            oms_type=OMSType.HEDGING,
            generate_position_ids=True,
            exec_cache=self.exec_engine.cache,
            instruments={usdjpy.symbol: usdjpy},
            config=BacktestConfig(),
            fill_model=FillModel(),
            commission_model=GenericCommissionModel(),
            clock=clock,
            uuid_factory=TestUUIDFactory(),
            logger=logger,
        )

        self.exec_client = BacktestExecClient(
            market=self.market,
            account_id=account_id,
            engine=self.exec_engine,
            logger=logger,
        )

        self.exec_engine.register_client(self.exec_client)

        strategies = [
            EmptyStrategy("001"),
            EmptyStrategy("002"),
        ]

        self.trader = Trader(
            trader_id=trader_id,
            strategies=strategies,
            data_engine=data_engine,
            exec_engine=self.exec_engine,
            clock=clock,
            uuid_factory=uuid_factory,
            logger=logger,
        )

    def test_initialize_trader(self):
        # Arrange
        # Act
        trader_id = self.trader.id

        # Assert
        self.assertEqual(TraderId("TESTER", "000"), trader_id)
        self.assertEqual(IdTag("000"), trader_id.tag)
        self.assertEqual(ComponentState.INITIALIZED, self.trader.state())
        self.assertEqual(2, len(self.trader.strategy_states()))

    def test_get_strategy_states(self):
        # Arrange
        # Act
        status = self.trader.strategy_states()

        # Assert
        self.assertTrue(StrategyId("EmptyStrategy", "001") in status)
        self.assertTrue(StrategyId("EmptyStrategy", "002") in status)
        self.assertEqual('INITIALIZED',
                         status[StrategyId("EmptyStrategy", "001")])
        self.assertEqual('INITIALIZED',
                         status[StrategyId("EmptyStrategy", "002")])
        self.assertEqual(2, len(status))

    def test_change_strategies(self):
        # Arrange
        strategies = [EmptyStrategy("003"), EmptyStrategy("004")]

        # Act
        self.trader.initialize_strategies(strategies)

        # Assert
        self.assertTrue(strategies[0].id in self.trader.strategy_states())
        self.assertTrue(strategies[1].id in self.trader.strategy_states())
        self.assertEqual(2, len(self.trader.strategy_states()))

    def test_trader_detects_none_unique_identifiers(self):
        # Arrange
        strategies = [EmptyStrategy("000"), EmptyStrategy("000")]

        # Act
        self.assertRaises(ValueError, self.trader.initialize_strategies,
                          strategies)

    def test_start_a_trader(self):
        # Arrange
        # Act
        self.trader.start()

        strategy_states = self.trader.strategy_states()

        # Assert
        self.assertEqual(ComponentState.RUNNING, self.trader.state())
        self.assertEqual('RUNNING',
                         strategy_states[StrategyId("EmptyStrategy", "001")])
        self.assertEqual('RUNNING',
                         strategy_states[StrategyId("EmptyStrategy", "002")])

    def test_stop_a_running_trader(self):
        # Arrange
        self.trader.start()

        # Act
        self.trader.stop()

        strategy_states = self.trader.strategy_states()

        # Assert
        self.assertEqual(ComponentState.STOPPED, self.trader.state())
        self.assertEqual('STOPPED',
                         strategy_states[StrategyId("EmptyStrategy", "001")])
        self.assertEqual('STOPPED',
                         strategy_states[StrategyId("EmptyStrategy", "002")])
Exemplo n.º 2
0
class TraderTests(unittest.TestCase):
    def setUp(self):
        # Fixture Setup
        clock = TestClock()
        logger = Logger(clock)

        trader_id = TraderId("TESTER", "000")
        account_id = TestStubs.account_id()

        self.portfolio = Portfolio(
            clock=clock,
            logger=logger,
        )

        self.data_engine = DataEngine(
            portfolio=self.portfolio,
            clock=clock,
            logger=logger,
            config={"use_previous_close": False},
        )

        self.portfolio.register_cache(self.data_engine.cache)
        self.analyzer = PerformanceAnalyzer()

        self.exec_db = BypassExecutionDatabase(
            trader_id=trader_id,
            logger=logger,
        )

        self.exec_engine = ExecutionEngine(
            database=self.exec_db,
            portfolio=self.portfolio,
            clock=clock,
            logger=logger,
        )

        self.exchange = SimulatedExchange(
            venue=Venue("SIM"),
            oms_type=OMSType.HEDGING,
            is_frozen_account=False,
            starting_balances=[Money(1_000_000, USD)],
            exec_cache=self.exec_engine.cache,
            instruments=[USDJPY_SIM],
            modules=[],
            fill_model=FillModel(),
            clock=clock,
            logger=logger,
        )

        self.data_client = BacktestMarketDataClient(
            instruments=[USDJPY_SIM],
            client_id=ClientId("SIM"),
            engine=self.data_engine,
            clock=clock,
            logger=logger,
        )

        self.data_engine.register_client(self.data_client)

        self.exec_client = BacktestExecClient(
            exchange=self.exchange,
            account_id=account_id,
            engine=self.exec_engine,
            clock=clock,
            logger=logger,
        )

        self.risk_engine = RiskEngine(
            exec_engine=self.exec_engine,
            portfolio=self.portfolio,
            clock=clock,
            logger=logger,
        )

        self.exec_engine.register_risk_engine(self.risk_engine)
        self.exec_engine.register_client(self.exec_client)

        strategies = [
            TradingStrategy("001"),
            TradingStrategy("002"),
        ]

        self.trader = Trader(
            trader_id=trader_id,
            strategies=strategies,
            portfolio=self.portfolio,
            data_engine=self.data_engine,
            exec_engine=self.exec_engine,
            risk_engine=self.risk_engine,
            clock=clock,
            logger=logger,
        )

    def test_initialize_trader(self):
        # Arrange
        # Act
        trader_id = self.trader.id

        # Assert
        self.assertEqual(TraderId("TESTER", "000"), trader_id)
        self.assertEqual(IdTag("000"), trader_id.tag)
        self.assertEqual(ComponentState.INITIALIZED, self.trader.state)
        self.assertEqual(2, len(self.trader.strategy_states()))

    def test_get_strategy_states(self):
        # Arrange
        # Act
        status = self.trader.strategy_states()

        # Assert
        self.assertTrue(StrategyId("TradingStrategy", "001") in status)
        self.assertTrue(StrategyId("TradingStrategy", "002") in status)
        self.assertEqual("INITIALIZED",
                         status[StrategyId("TradingStrategy", "001")])
        self.assertEqual("INITIALIZED",
                         status[StrategyId("TradingStrategy", "002")])
        self.assertEqual(2, len(status))

    def test_change_strategies(self):
        # Arrange
        strategies = [
            TradingStrategy("003"),
            TradingStrategy("004"),
        ]

        # Act
        self.trader.initialize_strategies(strategies, warn_no_strategies=True)

        # Assert
        self.assertTrue(strategies[0].id in self.trader.strategy_states())
        self.assertTrue(strategies[1].id in self.trader.strategy_states())
        self.assertEqual(2, len(self.trader.strategy_states()))

    def test_trader_detects_duplicate_identifiers(self):
        # Arrange
        strategies = [
            TradingStrategy("000"),
            TradingStrategy("000"),
        ]

        # Act
        self.assertRaises(
            ValueError,
            self.trader.initialize_strategies,
            strategies,
            True,
        )

    def test_start_a_trader(self):
        # Arrange
        # Act
        self.trader.start()

        strategy_states = self.trader.strategy_states()

        # Assert
        self.assertEqual(ComponentState.RUNNING, self.trader.state)
        self.assertEqual("RUNNING",
                         strategy_states[StrategyId("TradingStrategy", "001")])
        self.assertEqual("RUNNING",
                         strategy_states[StrategyId("TradingStrategy", "002")])

    def test_stop_a_running_trader(self):
        # Arrange
        self.trader.start()

        # Act
        self.trader.stop()

        strategy_states = self.trader.strategy_states()

        # Assert
        self.assertEqual(ComponentState.STOPPED, self.trader.state)
        self.assertEqual("STOPPED",
                         strategy_states[StrategyId("TradingStrategy", "001")])
        self.assertEqual("STOPPED",
                         strategy_states[StrategyId("TradingStrategy", "002")])
Exemplo n.º 3
0
class TraderTests(unittest.TestCase):
    def setUp(self):
        # Fixture Setup
        usdjpy = TestStubs.instrument_usdjpy()
        data = BacktestDataContainer()
        data.add_instrument(usdjpy)
        data.add_bars(usdjpy.symbol, BarStructure.MINUTE, PriceType.BID,
                      TestDataProvider.usdjpy_1min_bid()[:2000])
        data.add_bars(usdjpy.symbol, BarStructure.MINUTE, PriceType.ASK,
                      TestDataProvider.usdjpy_1min_ask()[:2000])

        clock = TestClock()
        guid_factory = TestGuidFactory()
        logger = TestLogger()
        trader_id = TraderId('TESTER', '000')
        account_id = TestStubs.account_id()

        data_client = BacktestDataClient(data=data,
                                         tick_capacity=100,
                                         clock=clock,
                                         logger=logger)

        self.portfolio = Portfolio(currency=Currency.USD,
                                   clock=clock,
                                   guid_factory=guid_factory,
                                   logger=logger)

        self.analyzer = PerformanceAnalyzer()

        self.exec_db = InMemoryExecutionDatabase(trader_id=trader_id,
                                                 logger=logger)
        self.exec_engine = ExecutionEngine(trader_id=trader_id,
                                           account_id=account_id,
                                           database=self.exec_db,
                                           portfolio=self.portfolio,
                                           clock=clock,
                                           guid_factory=guid_factory,
                                           logger=logger)

        self.exec_client = BacktestExecClient(
            exec_engine=self.exec_engine,
            instruments={usdjpy.symbol: usdjpy},
            config=BacktestConfig(),
            fill_model=FillModel(),
            clock=clock,
            guid_factory=guid_factory,
            logger=logger)
        self.exec_engine.register_client(self.exec_client)

        strategies = [EmptyStrategy('001'), EmptyStrategy('002')]

        self.trader = Trader(trader_id=trader_id,
                             account_id=account_id,
                             strategies=strategies,
                             data_client=data_client,
                             exec_engine=self.exec_engine,
                             clock=clock,
                             guid_factory=guid_factory,
                             logger=logger)

    def test_can_initialize_trader(self):
        # Arrange
        # Act
        trader_id = self.trader.id

        # Assert
        self.assertEqual(TraderId('TESTER', '000'), trader_id)
        self.assertEqual(IdTag('000'), trader_id.order_id_tag)
        self.assertFalse(self.trader.is_running)
        self.assertEqual(0, len(self.trader.started_datetimes))
        self.assertEqual(0, len(self.trader.stopped_datetimes))
        self.assertEqual(2, len(self.trader.strategy_status()))

    def test_can_get_strategy_status(self):
        # Arrange
        # Act
        status = self.trader.strategy_status()

        # Assert
        self.assertTrue(StrategyId('EmptyStrategy', '001') in status)
        self.assertTrue(StrategyId('EmptyStrategy', '002') in status)
        self.assertFalse(status[StrategyId('EmptyStrategy', '001')])
        self.assertFalse(status[StrategyId('EmptyStrategy', '002')])
        self.assertEqual(2, len(status))

    def test_can_change_strategies(self):
        # Arrange
        strategies = [EmptyStrategy('003'), EmptyStrategy('004')]

        # Act
        self.trader.initialize_strategies(strategies)

        # Assert
        self.assertTrue(strategies[0].id in self.trader.strategy_status())
        self.assertTrue(strategies[1].id in self.trader.strategy_status())
        self.assertEqual(2, len(self.trader.strategy_status()))

    def test_trader_detects_none_unique_identifiers(self):
        # Arrange
        strategies = [EmptyStrategy('000'), EmptyStrategy('000')]

        # Act
        self.assertRaises(ValueError, self.trader.initialize_strategies,
                          strategies)

    def test_can_start_a_trader(self):
        # Arrange
        # Act
        self.trader.start()

        # Assert
        self.assertTrue(self.trader.is_running)
        self.assertEqual(1, len(self.trader.started_datetimes))
        self.assertEqual(0, len(self.trader.stopped_datetimes))
        self.assertTrue(
            StrategyId('EmptyStrategy', '001') in
            self.trader.strategy_status())
        self.assertTrue(
            StrategyId('EmptyStrategy', '002') in
            self.trader.strategy_status())
        self.assertTrue(self.trader.strategy_status()[StrategyId(
            'EmptyStrategy', '001')])
        self.assertTrue(self.trader.strategy_status()[StrategyId(
            'EmptyStrategy', '002')])

    def test_can_stop_a_running_trader(self):
        # Arrange
        self.trader.start()

        # Act
        self.trader.stop()

        # Assert
        self.assertFalse(self.trader.is_running)
        self.assertEqual(1, len(self.trader.started_datetimes))
        self.assertEqual(1, len(self.trader.stopped_datetimes))
        self.assertTrue(
            StrategyId('EmptyStrategy', '001') in
            self.trader.strategy_status())
        self.assertTrue(
            StrategyId('EmptyStrategy', '002') in
            self.trader.strategy_status())
        self.assertFalse(self.trader.strategy_status()[StrategyId(
            'EmptyStrategy', '001')])
        self.assertFalse(self.trader.strategy_status()[StrategyId(
            'EmptyStrategy', '002')])