Esempio n. 1
0
    def test_submit_order(self):
        # Arrange
        strategy = TradingStrategy(order_id_tag="001")
        strategy.register_trader(
            TraderId("TESTER", "000"),
            clock=self.clock,
            uuid_factory=TestUUIDFactory(),
            logger=self.logger,
        )

        self.exec_engine.register_strategy(strategy)

        order = strategy.order_factory.market(
            AUDUSD_FXCM,
            OrderSide.BUY,
            Quantity(100000),
        )

        submit_order = SubmitOrder(
            self.venue,
            self.trader_id,
            self.account_id,
            strategy.id,
            PositionId.py_null(),
            order,
            self.uuid_factory.generate(),
            self.clock.utc_now(),
        )

        # Act
        self.exec_engine.execute(submit_order)

        # Assert
        self.assertIn(submit_order, self.exec_client.received_commands)
        self.assertTrue(self.cache.order_exists(order.cl_ord_id))
    def test_submit_order_with_default_settings_sends_to_client(self):
        # Arrange
        self.exec_engine.start()

        strategy = TradingStrategy(order_id_tag="001")
        strategy.register_trader(
            TraderId("TESTER", "000"),
            self.clock,
            self.logger,
        )

        self.exec_engine.register_strategy(strategy)

        order = strategy.order_factory.market(
            AUDUSD_SIM.id,
            OrderSide.BUY,
            Quantity(100000),
        )

        submit_order = SubmitOrder(
            order.instrument_id,
            self.trader_id,
            self.account_id,
            strategy.id,
            PositionId.null(),
            order,
            self.uuid_factory.generate(),
            self.clock.timestamp_ns(),
        )

        # Act
        self.risk_engine.execute(submit_order)

        # Assert
        assert self.exec_client.calls == ["connect", "submit_order"]
    def setUp(self):
        # Fixture Setup
        clock = TestClock()
        logger = Logger(clock)
        trader_id = TraderId("TESTER-000")
        self.order_factory = OrderFactory(
            trader_id=trader_id,
            strategy_id=StrategyId("S-001"),
            clock=TestClock(),
        )

        cache_db = BypassCacheDatabase(
            trader_id=trader_id,
            logger=logger,
        )

        cache = Cache(
            database=cache_db,
            logger=logger,
        )

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

        self.exec_engine = ExecutionEngine(
            portfolio=self.portfolio,
            cache=cache,
            clock=clock,
            logger=logger,
        )
Esempio n. 4
0
        async def run_test():
            # Arrange
            self.engine.start()

            strategy = TradingStrategy(order_id_tag="001")
            strategy.register_trader(
                TraderId("TESTER", "000"),
                self.clock,
                self.logger,
            )

            self.engine.register_strategy(strategy)

            order = strategy.order_factory.market(
                AUDUSD_SIM.id,
                OrderSide.BUY,
                Quantity(100000),
            )

            event = TestStubs.event_order_submitted(order)

            # Act
            self.engine.process(event)
            await asyncio.sleep(0.1)

            # Assert
            assert self.engine.qsize() == 0
            assert self.engine.event_count == 1

            # Tear Down
            self.engine.stop()
Esempio n. 5
0
    def setUp(self):
        # Fixture Setup

        self.trader_id = TraderId('TESTER', '000')
        self.store = LogStore(trader_id=self.trader_id)

        self.test_redis = redis.Redis(host='localhost', port=6379, db=0)
    def test_submit_bracket_order_command_to_from_dict_and_str_repr(self):
        # Arrange
        uuid = self.uuid_factory.generate()

        bracket = self.order_factory.bracket_market(
            instrument_id=AUDUSD_SIM.id,
            order_side=OrderSide.BUY,
            quantity=Quantity.from_int(100000),
            stop_loss=Price.from_str("1.00000"),
            take_profit=Price.from_str("1.00100"),
        )

        command = SubmitOrderList(
            trader_id=TraderId("TRADER-001"),
            strategy_id=StrategyId("S-001"),
            order_list=bracket,
            command_id=uuid,
            ts_init=self.clock.timestamp_ns(),
        )

        # Act, Assert
        assert SubmitOrderList.from_dict(
            SubmitOrderList.to_dict(command)) == command
        assert (
            str(command) ==
            "SubmitOrderList(instrument_id=AUD/USD.SIM, order_list=OrderList(id=1, instrument_id=AUD/USD.SIM, orders=[MarketOrder(BUY 100_000 AUD/USD.SIM MARKET GTC, status=INITIALIZED, client_order_id=O-19700101-000000-000-001-1, venue_order_id=None, tags=ENTRY), StopMarketOrder(SELL 100_000 AUD/USD.SIM STOP_MARKET @ 1.00000 GTC, status=INITIALIZED, client_order_id=O-19700101-000000-000-001-2, venue_order_id=None, tags=STOP_LOSS), LimitOrder(SELL 100_000 AUD/USD.SIM LIMIT @ 1.00100 GTC, status=INITIALIZED, client_order_id=O-19700101-000000-000-001-3, venue_order_id=None, tags=TAKE_PROFIT)]))"  # noqa
        )
        assert (
            repr(command) ==
            f"SubmitOrderList(trader_id=TRADER-001, strategy_id=S-001, instrument_id=AUD/USD.SIM, order_list=OrderList(id=1, instrument_id=AUD/USD.SIM, orders=[MarketOrder(BUY 100_000 AUD/USD.SIM MARKET GTC, status=INITIALIZED, client_order_id=O-19700101-000000-000-001-1, venue_order_id=None, tags=ENTRY), StopMarketOrder(SELL 100_000 AUD/USD.SIM STOP_MARKET @ 1.00000 GTC, status=INITIALIZED, client_order_id=O-19700101-000000-000-001-2, venue_order_id=None, tags=STOP_LOSS), LimitOrder(SELL 100_000 AUD/USD.SIM LIMIT @ 1.00100 GTC, status=INITIALIZED, client_order_id=O-19700101-000000-000-001-3, venue_order_id=None, tags=TAKE_PROFIT)]), command_id={uuid}, ts_init=0)"  # noqa
        )
    def test_submit_order_command_to_from_dict_and_str_repr(self):
        # Arrange
        uuid = self.uuid_factory.generate()

        order = self.order_factory.market(
            AUDUSD_SIM.id,
            OrderSide.BUY,
            Quantity.from_int(100000),
        )

        command = SubmitOrder(
            trader_id=TraderId("TRADER-001"),
            strategy_id=StrategyId("S-001"),
            position_id=PositionId("P-001"),
            order=order,
            command_id=uuid,
            ts_init=self.clock.timestamp_ns(),
        )

        # Act, Assert
        assert SubmitOrder.from_dict(SubmitOrder.to_dict(command)) == command
        assert (
            str(command) ==
            "SubmitOrder(instrument_id=AUD/USD.SIM, client_order_id=O-19700101-000000-000-001-1, position_id=P-001, order=BUY 100_000 AUD/USD.SIM MARKET GTC)"  # noqa
        )
        assert (
            repr(command) ==
            f"SubmitOrder(trader_id=TRADER-001, strategy_id=S-001, instrument_id=AUD/USD.SIM, client_order_id=O-19700101-000000-000-001-1, position_id=P-001, order=BUY 100_000 AUD/USD.SIM MARKET GTC, command_id={uuid}, ts_init=0)"  # noqa
        )
    def setup(self):
        # Fixture Setup
        _reset()
        self.catalog = DataCatalog(path="/root", fs_protocol="memory")
        self.order_factory = OrderFactory(
            trader_id=TraderId("T-001"),
            strategy_id=StrategyId("S-001"),
            clock=TestClock(),
        )
        self.order = self.order_factory.market(
            AUDUSD_SIM.id,
            OrderSide.BUY,
            Quantity.from_int(100000),
        )
        self.order_submitted = copy.copy(self.order)
        self.order_submitted.apply(TestStubs.event_order_submitted(self.order))

        self.order_accepted = copy.copy(self.order_submitted)
        self.order_accepted.apply(
            TestStubs.event_order_accepted(self.order_submitted))

        self.order_pending_cancel = copy.copy(self.order_accepted)
        self.order_pending_cancel.apply(
            TestStubs.event_order_pending_cancel(self.order_accepted))

        self.order_cancelled = copy.copy(self.order_pending_cancel)
        self.order_cancelled.apply(
            TestStubs.event_order_canceled(self.order_pending_cancel))
    def test_order_cancel_rejected_with_none_venue_order_id_event_to_from_dict_and_str_repr(
            self):
        # Arrange
        uuid = UUID4()
        event = OrderCancelRejected(
            trader_id=TraderId("TRADER-001"),
            strategy_id=StrategyId("SCALPER-001"),
            account_id=AccountId("SIM", "000"),
            instrument_id=InstrumentId(Symbol("BTC/USDT"), Venue("BINANCE")),
            client_order_id=ClientOrderId("O-2020872378423"),
            venue_order_id=None,
            reason="ORDER_DOES_NOT_EXIST",
            ts_event=0,
            event_id=uuid,
            ts_init=0,
        )

        # Act, Assert
        assert OrderCancelRejected.from_dict(
            OrderCancelRejected.to_dict(event)) == event
        assert (
            str(event) ==
            "OrderCancelRejected(account_id=SIM-000, instrument_id=BTC/USDT.BINANCE, client_order_id=O-2020872378423, venue_order_id=None, reason=ORDER_DOES_NOT_EXIST, ts_event=0)"  # noqa
        )
        assert (
            repr(event) ==
            f"OrderCancelRejected(trader_id=TRADER-001, strategy_id=SCALPER-001, account_id=SIM-000, instrument_id=BTC/USDT.BINANCE, client_order_id=O-2020872378423, venue_order_id=None, reason=ORDER_DOES_NOT_EXIST, event_id={uuid}, ts_event=0, ts_init=0)"  # noqa
        )
    def test_modify_order_command_with_none_venue_order_id_to_from_dict_and_str_repr(
            self):
        # Arrange
        uuid = self.uuid_factory.generate()

        command = ModifyOrder(
            trader_id=TraderId("TRADER-001"),
            strategy_id=StrategyId("S-001"),
            instrument_id=AUDUSD_SIM.id,
            client_order_id=ClientOrderId("O-123456"),
            venue_order_id=None,
            price=Price.from_str("1.00000"),
            trigger=Price.from_str("1.00010"),
            quantity=Quantity.from_int(100000),
            command_id=uuid,
            ts_init=self.clock.timestamp_ns(),
        )

        # Act, Assert
        assert ModifyOrder.from_dict(ModifyOrder.to_dict(command)) == command
        assert (
            str(command) ==
            "ModifyOrder(instrument_id=AUD/USD.SIM, client_order_id=O-123456, venue_order_id=None, quantity=100_000, price=1.00000, trigger=1.00010)"  # noqa
        )
        assert (
            repr(command) ==
            f"ModifyOrder(trader_id=TRADER-001, strategy_id=S-001, instrument_id=AUD/USD.SIM, client_order_id=O-123456, venue_order_id=None, quantity=100_000, price=1.00000, trigger=1.00010, command_id={uuid}, ts_init=0)"  # noqa
        )
Esempio n. 11
0
 def setup(self):
     # Fixture Setup
     self.order_id_generator = ClientOrderIdGenerator(
         trader_id=TraderId("TRADER-001"),
         strategy_id=StrategyId("SCALPER-001"),
         clock=TestClock(),
     )
Esempio n. 12
0
    def setUp(self):
        # Fixture Setup
        self.clock = LiveClock()
        self.uuid_factory = UUIDFactory()
        self.trader_id = TraderId("TESTER", "001")

        # Fresh isolated loop testing pattern
        self.loop = asyncio.new_event_loop()
        asyncio.set_event_loop(self.loop)

        self.logger = LiveLogger(self.clock)

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

        self.data_engine = LiveDataEngine(
            loop=self.loop,
            portfolio=self.portfolio,
            clock=self.clock,
            logger=self.logger,
        )

        database = BypassExecutionDatabase(trader_id=self.trader_id,
                                           logger=self.logger)
        self.exec_engine = LiveExecutionEngine(
            loop=self.loop,
            database=database,
            portfolio=self.portfolio,
            clock=self.clock,
            logger=self.logger,
        )
Esempio n. 13
0
 def setup(self):
     # Fixture Setup
     self.order_factory = OrderFactory(
         trader_id=TraderId("TESTER-000"),
         strategy_id=StrategyId("S-001"),
         clock=TestClock(),
     )
Esempio n. 14
0
    def test_order_initialized_event_to_from_dict_and_str_repr(self):
        # Arrange
        uuid = UUID4()
        event = OrderInitialized(
            trader_id=TraderId("TRADER-001"),
            strategy_id=StrategyId("SCALPER-001"),
            instrument_id=InstrumentId(Symbol("BTC/USDT"), Venue("BINANCE")),
            client_order_id=ClientOrderId("O-2020872378423"),
            order_side=OrderSide.BUY,
            order_type=OrderType.LIMIT,
            quantity=Quantity.from_str("0.561000"),
            time_in_force=TimeInForce.DAY,
            reduce_only=True,
            options={"price": "15200.10"},
            order_list_id=OrderListId("1"),
            parent_order_id=None,
            child_order_ids=[ClientOrderId("O-2020872378424")],
            contingency=ContingencyType.OTO,
            contingency_ids=[ClientOrderId("O-2020872378424")],
            tags="ENTRY",
            event_id=uuid,
            ts_init=0,
        )

        # Act, Assert
        assert OrderInitialized.from_dict(
            OrderInitialized.to_dict(event)) == event
        assert (
            str(event) ==
            f"OrderInitialized(instrument_id=BTC/USDT.BINANCE, client_order_id=O-2020872378423, side=BUY, type=LIMIT, quantity=0.561000, time_in_force=DAY, reduce_only=True, options={{'price': '15200.10'}}, order_list_id=1, parent_order_id=None, child_order_ids=['O-2020872378424'], contingency=OTO, contingency_ids=['O-2020872378424'], tags=ENTRY)"  # noqa
        )
        assert (
            repr(event) ==
            f"OrderInitialized(trader_id=TRADER-001, strategy_id=SCALPER-001, instrument_id=BTC/USDT.BINANCE, client_order_id=O-2020872378423, side=BUY, type=LIMIT, quantity=0.561000, time_in_force=DAY, reduce_only=True, options={{'price': '15200.10'}}, order_list_id=1, parent_order_id=None, child_order_ids=['O-2020872378424'], contingency=OTO, contingency_ids=['O-2020872378424'], tags=ENTRY, event_id={uuid}, ts_init=0)"  # noqa
        )
    def test_cancel_order_command_with_none_venue_order_id_to_from_dict_and_str_repr(
            self):
        # Arrange
        uuid = self.uuid_factory.generate()

        command = CancelOrder(
            trader_id=TraderId("TRADER-001"),
            strategy_id=StrategyId("S-001"),
            instrument_id=AUDUSD_SIM.id,
            client_order_id=ClientOrderId("O-123456"),
            venue_order_id=None,
            command_id=uuid,
            ts_init=self.clock.timestamp_ns(),
        )

        # Act, Assert
        assert CancelOrder.from_dict(CancelOrder.to_dict(command)) == command
        assert (
            str(command) ==
            "CancelOrder(instrument_id=AUD/USD.SIM, client_order_id=O-123456, venue_order_id=None)"  # noqa
        )
        assert (
            repr(command) ==
            f"CancelOrder(trader_id=TRADER-001, strategy_id=S-001, instrument_id=AUD/USD.SIM, client_order_id=O-123456, venue_order_id=None, command_id={uuid}, ts_init=0)"  # noqa
        )
Esempio n. 16
0
    def test_order_updated_event_to_from_dict_and_str_repr(self):
        # Arrange
        uuid = UUID4()
        event = OrderUpdated(
            trader_id=TraderId("TRADER-001"),
            strategy_id=StrategyId("SCALPER-001"),
            account_id=AccountId("SIM", "000"),
            instrument_id=InstrumentId(Symbol("BTC/USDT"), Venue("BINANCE")),
            client_order_id=ClientOrderId("O-2020872378423"),
            venue_order_id=VenueOrderId("123456"),
            quantity=Quantity.from_int(500000),
            price=Price.from_str("1.95000"),
            trigger=None,
            ts_event=0,
            event_id=uuid,
            ts_init=0,
        )

        # Act, Assert
        assert OrderUpdated.from_dict(OrderUpdated.to_dict(event)) == event
        assert (
            str(event) ==
            "OrderUpdated(account_id=SIM-000, instrument_id=BTC/USDT.BINANCE, client_order_id=O-2020872378423, venue_order_id=123456, quantity=500_000, price=1.95000, trigger=None, ts_event=0)"  # noqa
        )
        assert (
            repr(event) ==
            f"OrderUpdated(trader_id=TRADER-001, strategy_id=SCALPER-001, account_id=SIM-000, instrument_id=BTC/USDT.BINANCE, client_order_id=O-2020872378423, venue_order_id=123456, quantity=500_000, price=1.95000, trigger=None, event_id={uuid}, ts_event=0, ts_init=0)"  # noqa
        )
Esempio n. 17
0
    def test_order_pending_cancel_event_to_from_dict_and_str_repr(self):
        # Arrange
        uuid = UUID4()
        event = OrderPendingCancel(
            trader_id=TraderId("TRADER-001"),
            strategy_id=StrategyId("SCALPER-001"),
            account_id=AccountId("SIM", "000"),
            instrument_id=InstrumentId(Symbol("BTC/USDT"), Venue("BINANCE")),
            client_order_id=ClientOrderId("O-2020872378423"),
            venue_order_id=VenueOrderId("123456"),
            ts_event=0,
            event_id=uuid,
            ts_init=0,
        )

        # Act, Assert
        assert OrderPendingCancel.from_dict(
            OrderPendingCancel.to_dict(event)) == event
        assert (
            str(event) ==
            "OrderPendingCancel(account_id=SIM-000, instrument_id=BTC/USDT.BINANCE, client_order_id=O-2020872378423, venue_order_id=123456, ts_event=0)"  # noqa
        )
        assert (
            repr(event) ==
            f"OrderPendingCancel(trader_id=TRADER-001, strategy_id=SCALPER-001, account_id=SIM-000, instrument_id=BTC/USDT.BINANCE, client_order_id=O-2020872378423, venue_order_id=123456, event_id={uuid}, ts_event=0, ts_init=0)"  # noqa
        )
Esempio n. 18
0
    def test_order_rejected_event_to_from_dict_and_str_repr(self):
        # Arrange
        uuid = UUID4()
        event = OrderRejected(
            trader_id=TraderId("TRADER-001"),
            strategy_id=StrategyId("SCALPER-001"),
            account_id=AccountId("SIM", "000"),
            instrument_id=InstrumentId(Symbol("BTC/USDT"), Venue("BINANCE")),
            client_order_id=ClientOrderId("O-2020872378423"),
            reason="INSUFFICIENT_MARGIN",
            ts_event=0,
            event_id=uuid,
            ts_init=0,
        )

        # Act, Assert
        assert OrderRejected.from_dict(OrderRejected.to_dict(event)) == event
        assert (
            str(event) ==
            "OrderRejected(account_id=SIM-000, instrument_id=BTC/USDT.BINANCE, client_order_id=O-2020872378423, reason='INSUFFICIENT_MARGIN', ts_event=0)"  # noqa
        )
        assert (
            repr(event) ==
            f"OrderRejected(trader_id=TRADER-001, strategy_id=SCALPER-001, account_id=SIM-000, instrument_id=BTC/USDT.BINANCE, client_order_id=O-2020872378423, reason='INSUFFICIENT_MARGIN', event_id={uuid}, ts_event=0, ts_init=0)"  # noqa
        )
    def setUp(self):
        # Fixture Setup
        self.clock = TestClock()
        self.guid_factory = TestGuidFactory()
        logger = TestLogger()

        self.trader_id = TraderId('TESTER', '000')
        self.account_id = TestStubs.account_id()

        self.order_factory = OrderFactory(
            id_tag_trader=self.trader_id.order_id_tag,
            id_tag_strategy=IdTag('001'),
            clock=self.clock)

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

        self.analyzer = PerformanceAnalyzer()

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

        self.exec_engine.handle_event(TestStubs.account_event())

        self.exec_client = MockExecutionClient(self.exec_engine, logger)
        self.exec_engine.register_client(self.exec_client)
Esempio n. 20
0
    def setUp(self):
        # Fixture Setup
        clock = TestClock()
        logger = TestLogger(clock)
        self.order_factory = OrderFactory(
            trader_id=TraderId("TESTER", "000"),
            strategy_id=StrategyId("S", "001"),
            clock=TestClock(),
        )

        state = AccountState(
            account_id=AccountId("BINANCE", "1513111"),
            balances=[Money("10.00000000", BTC)],
            balances_free=[Money("0.00000000", BTC)],
            balances_locked=[Money("0.00000000", BTC)],
            info={},
            event_id=uuid4(),
            event_timestamp=UNIX_EPOCH,
        )

        self.data_cache = DataCache(logger)
        self.account = Account(state)

        self.portfolio = Portfolio(clock, logger)
        self.portfolio.register_account(self.account)
        self.portfolio.register_cache(self.data_cache)

        self.data_cache.add_instrument(AUDUSD_SIM)
        self.data_cache.add_instrument(GBPUSD_SIM)
        self.data_cache.add_instrument(BTCUSDT_BINANCE)
        self.data_cache.add_instrument(BTCUSD_BITMEX)
        self.data_cache.add_instrument(ETHUSD_BITMEX)
Esempio n. 21
0
    def test_handle_order_fill_event(self):
        # Arrange
        self.exec_engine.start()

        strategy = TradingStrategy(order_id_tag="001")
        strategy.register_trader(
            TraderId("TESTER", "000"),
            self.clock,
            self.logger,
        )

        self.exec_engine.register_strategy(strategy)

        order = strategy.order_factory.market(
            AUDUSD_SIM.symbol,
            OrderSide.BUY,
            Quantity(100000),
        )

        submit_order = SubmitOrder(
            self.venue,
            self.trader_id,
            self.account_id,
            strategy.id,
            PositionId.null(),
            order,
            self.uuid_factory.generate(),
            self.clock.utc_now(),
        )

        self.exec_engine.execute(submit_order)

        # Act
        self.exec_engine.process(TestStubs.event_order_submitted(order))
        self.exec_engine.process(TestStubs.event_order_accepted(order))
        self.exec_engine.process(
            TestStubs.event_order_filled(order, AUDUSD_SIM))

        expected_position_id = PositionId(
            "O-19700101-000000-000-001-1")  # Stubbed from order id?

        # Assert
        self.assertTrue(self.cache.position_exists(expected_position_id))
        self.assertTrue(self.cache.is_position_open(expected_position_id))
        self.assertFalse(self.cache.is_position_closed(expected_position_id))
        self.assertEqual(Position,
                         type(self.cache.position(expected_position_id)))
        self.assertIn(expected_position_id, self.cache.position_ids())
        self.assertNotIn(
            expected_position_id,
            self.cache.position_closed_ids(strategy_id=strategy.id))
        self.assertNotIn(expected_position_id,
                         self.cache.position_closed_ids())
        self.assertIn(expected_position_id,
                      self.cache.position_open_ids(strategy_id=strategy.id))
        self.assertIn(expected_position_id, self.cache.position_open_ids())
        self.assertEqual(1, self.cache.positions_total_count())
        self.assertEqual(1, self.cache.positions_open_count())
        self.assertEqual(0, self.cache.positions_closed_count())
Esempio n. 22
0
 def setUp(self):
     # Fixture Setup
     self.account_id = TestStubs.account_id()
     self.order_factory = OrderFactory(
         trader_id=TraderId("TESTER", "000"),
         strategy_id=StrategyId("S", "001"),
         clock=TestClock(),
     )
 def setUp(self):
     # Fixture Setup
     self.serializer = MsgPackOrderSerializer()
     self.order_factory = OrderFactory(
         trader_id=TraderId("TESTER", "000"),
         strategy_id=StrategyId("S", "001"),
         clock=TestClock(),
     )
 def setUp(self):
     # Fixture Setup
     self.analyzer = PerformanceAnalyzer()
     self.order_factory = OrderFactory(
         trader_id=TraderId("TESTER", "000"),
         strategy_id=StrategyId("S", "001"),
         clock=TestClock(),
     )
Esempio n. 25
0
    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 setup(self):
        # Fixture Setup
        self.clock = LiveClock()
        self.uuid_factory = UUIDFactory()
        self.trader_id = TraderId("TESTER-001")

        # Fresh isolated loop testing pattern
        self.loop = asyncio.new_event_loop()
        asyncio.set_event_loop(self.loop)
        self.executor = concurrent.futures.ThreadPoolExecutor()
        self.loop.set_default_executor(self.executor)
        self.loop.set_debug(True)

        # Setup logging
        logger = LiveLogger(
            loop=self.loop,
            clock=self.clock,
            trader_id=self.trader_id,
            level_stdout=LogLevel.DEBUG,
        )

        self.logger = LiveLogger(
            loop=self.loop,
            clock=self.clock,
        )

        self.cache = TestStubs.cache()

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

        self.data_engine = LiveDataEngine(
            loop=self.loop,
            portfolio=self.portfolio,
            cache=self.cache,
            clock=self.clock,
            logger=self.logger,
        )

        self.mock_oanda = MagicMock()

        self.client = OandaDataClient(
            client=self.mock_oanda,
            account_id="001",
            engine=self.data_engine,
            clock=self.clock,
            logger=logger,
        )

        self.data_engine.register_client(self.client)

        with open(TEST_PATH + "instruments.json") as response:
            instruments = json.load(response)

        self.mock_oanda.request.return_value = instruments
Esempio n. 27
0
 def setUp(self):
     # Fixture Setup
     self.generator = ClientOrderIdGenerator(IdTag("001"), IdTag("001"),
                                             LiveClock())
     self.order_factory = OrderFactory(
         trader_id=TraderId("TESTER", "000"),
         strategy_id=StrategyId("S", "001"),
         clock=TestClock(),
     )
Esempio n. 28
0
    def test_initialize_trader(self):
        # Arrange
        # Act
        trader_id = self.trader.id

        # Assert
        self.assertEqual(TraderId("TESTER-000"), trader_id)
        self.assertEqual(ComponentState.INITIALIZED, self.trader.state)
        self.assertEqual(2, len(self.trader.strategy_states()))
    def setUp(self):
        # Fixture Setup
        self.order_factory = OrderFactory(
            trader_id=TraderId("TESTER", "000"),
            strategy_id=StrategyId("S", "001"),
            clock=TestClock(),
        )

        self.builder = BinanceOrderBuilder()
    def setUp(self):
        # Fixture Setup
        clock = TestClock()
        logger = TestLogger(clock)

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

        self.strategy = TradingStrategy(order_id_tag="001")
        self.strategy.register_trader(
            TraderId("TESTER", "000"),
            clock,
            logger,
        )

        exec_db = BypassExecutionDatabase(trader_id=self.trader_id,
                                          logger=logger)
        self.cache = ExecutionCache(database=exec_db, logger=logger)