Beispiel #1
0
    def _did_create_order(self, event_tag: int, market: MarketBase,
                          evt: Union[BuyOrderCreatedEvent,
                                     SellOrderCreatedEvent]):
        if threading.current_thread() != threading.main_thread():
            self._ev_loop.call_soon_threadsafe(self._did_create_order,
                                               event_tag, market, evt)
            return

        session: Session = self.session
        base_asset, quote_asset = market.split_symbol(evt.symbol)
        timestamp: int = self.db_timestamp
        event_type: MarketEvent = self.market_event_tag_map[event_tag]
        trade_type: TradeType = TradeType.BUY if type(
            evt) == BuyOrderCreatedEvent else TradeType.SELL
        order_record: Order = Order(id=evt.order_id,
                                    config_file_path=self._config_file_path,
                                    strategy=self._strategy_name,
                                    market=market.display_name,
                                    symbol=evt.symbol,
                                    base_asset=base_asset,
                                    quote_asset=quote_asset,
                                    creation_timestamp=timestamp,
                                    order_type=evt.type.name,
                                    amount=float(evt.amount),
                                    price=float(evt.price),
                                    last_status=event_type.name,
                                    last_update_timestamp=timestamp)
        order_status: OrderStatus = OrderStatus(order=order_record,
                                                timestamp=timestamp,
                                                status=event_type.name)
        session.add(order_record)
        session.add(order_status)
        self.save_market_states(self._config_file_path, market, no_commit=True)
        session.commit()
Beispiel #2
0
    async def submit_orders(self):
        try:
            orders: List[Order] = await self.get_unsubmitted_orders()
            # only submit 5000 at a time
            formatted_orders: List[Dict[str, Any]] = [
                Order.to_bounty_api_json(order) for order in orders[:5000]
            ]

            if self._last_submitted_order_timestamp >= 0 and len(
                    formatted_orders) > 0:
                url = f"{self.LIQUIDITY_BOUNTY_REST_API}/order"
                results = await self.authenticated_request(
                    "POST", url, json={"orders": formatted_orders})
                num_submitted = results.get("orders_submitted", 0)
                num_recorded = results.get("orders_recorded", 0)
                if num_submitted != num_recorded:
                    self.logger().warning(
                        f"Failed to submit {num_submitted - num_recorded} order(s)"
                    )
                if num_recorded > 0:
                    self.logger().info(
                        f"Successfully sent {num_recorded} order(s) to claim bounty"
                    )
        except Exception:
            raise
    def _did_create_order(self, event_tag: int, market: ConnectorBase,
                          evt: Union[BuyOrderCreatedEvent,
                                     SellOrderCreatedEvent]):
        if threading.current_thread() != threading.main_thread():
            self._ev_loop.call_soon_threadsafe(self._did_create_order,
                                               event_tag, market, evt)
            return

        base_asset, quote_asset = evt.trading_pair.split("-")
        timestamp = int(evt.creation_timestamp * 1e3)
        event_type: MarketEvent = self.market_event_tag_map[event_tag]

        with self._sql_manager.get_new_session() as session:
            with session.begin():
                order_record: Order = Order(
                    id=evt.order_id,
                    config_file_path=self._config_file_path,
                    strategy=self._strategy_name,
                    market=market.display_name,
                    symbol=evt.trading_pair,
                    base_asset=base_asset,
                    quote_asset=quote_asset,
                    creation_timestamp=timestamp,
                    order_type=evt.type.name,
                    amount=Decimal(evt.amount),
                    leverage=evt.leverage if evt.leverage else 1,
                    price=Decimal(evt.price)
                    if evt.price == evt.price else Decimal(0),
                    position=evt.position
                    if evt.position else PositionAction.NIL.value,
                    last_status=event_type.name,
                    last_update_timestamp=timestamp,
                    exchange_order_id=evt.exchange_order_id)
                order_status: OrderStatus = OrderStatus(order=order_record,
                                                        timestamp=timestamp,
                                                        status=event_type.name)
                session.add(order_record)
                session.add(order_status)
                market.add_exchange_order_ids_from_market_recorder(
                    {evt.exchange_order_id: evt.order_id})
                self.save_market_states(self._config_file_path,
                                        market,
                                        session=session)
    def _did_create_order(self, event_tag: int, market: ConnectorBase,
                          evt: Union[BuyOrderCreatedEvent,
                                     SellOrderCreatedEvent]):
        if threading.current_thread() != threading.main_thread():
            self._ev_loop.call_soon_threadsafe(self._did_create_order,
                                               event_tag, market, evt)
            return

        session: Session = self.session
        base_asset, quote_asset = evt.trading_pair.split("-")
        timestamp: int = self.db_timestamp
        event_type: MarketEvent = self.market_event_tag_map[event_tag]
        order_record: Order = Order(
            id=evt.order_id,
            config_file_path=self._config_file_path,
            strategy=self._strategy_name,
            market=market.display_name,
            symbol=evt.trading_pair,
            base_asset=base_asset,
            quote_asset=quote_asset,
            creation_timestamp=timestamp,
            order_type=evt.type.name,
            amount=float(evt.amount),
            leverage=evt.leverage if evt.leverage else 1,
            price=float(evt.price) if evt.price == evt.price else 0,
            position=evt.position if evt.position else "NILL",
            last_status=event_type.name,
            last_update_timestamp=timestamp,
            exchange_order_id=evt.exchange_order_id)
        order_status: OrderStatus = OrderStatus(order=order_record,
                                                timestamp=timestamp,
                                                status=event_type.name)
        session.add(order_record)
        session.add(order_status)
        market.add_exchange_order_ids_from_market_recorder(
            {evt.exchange_order_id: evt.order_id})
        self.save_market_states(self._config_file_path, market, no_commit=True)
        session.commit()
    def test_list_trades(self, notify_mock):
        global_config_map["tables_format"].value = "psql"

        captures = []
        notify_mock.side_effect = lambda s: captures.append(s)
        self.app.strategy_file_name = f"{self.mock_strategy_name}.yml"

        trade_fee = AddedToCostTradeFee(percent=Decimal("5"))
        order_id = PaperTradeExchange.random_order_id(order_side="BUY",
                                                      trading_pair="BTC-USDT")
        with self.app.trade_fill_db.get_new_session() as session:
            o = Order(
                id=order_id,
                config_file_path=f"{self.mock_strategy_name}.yml",
                strategy=self.mock_strategy_name,
                market="binance",
                symbol="BTC-USDT",
                base_asset="BTC",
                quote_asset="USDT",
                creation_timestamp=0,
                order_type="LMT",
                amount=4,
                leverage=0,
                price=3,
                last_status="PENDING",
                last_update_timestamp=0,
            )
            session.add(o)
            for i in [1, 2]:
                t = TradeFill(
                    config_file_path=f"{self.mock_strategy_name}.yml",
                    strategy=self.mock_strategy_name,
                    market="binance",
                    symbol="BTC-USDT",
                    base_asset="BTC",
                    quote_asset="USDT",
                    timestamp=i,
                    order_id=order_id,
                    trade_type="BUY",
                    order_type="LIMIT",
                    price=i,
                    amount=2,
                    leverage=1,
                    trade_fee=trade_fee.to_json(),
                    exchange_trade_id=f"someExchangeId{i}",
                )
                session.add(t)
            session.commit()

        self.app.list_trades(start_time=0)

        self.assertEqual(1, len(captures))

        creation_time_str = str(datetime.datetime.fromtimestamp(0))

        df_str_expected = (
            f"\n  Recent trades:"
            f"\n    +---------------------+------------+----------+--------------+--------+---------+----------+------------+------------+-------+"  # noqa: E501
            f"\n    | Timestamp           | Exchange   | Market   | Order_type   | Side   |   Price |   Amount |   Leverage | Position   | Age   |"  # noqa: E501
            f"\n    |---------------------+------------+----------+--------------+--------+---------+----------+------------+------------+-------|"  # noqa: E501
            f"\n    | {creation_time_str} | binance    | BTC-USDT | limit        | buy    |       1 |        2 |          1 | NIL        | n/a   |"  # noqa: E501
            f"\n    | {creation_time_str} | binance    | BTC-USDT | limit        | buy    |       2 |        2 |          1 | NIL        | n/a   |"  # noqa: E501
            f"\n    +---------------------+------------+----------+--------------+--------+---------+----------+------------+------------+-------+"  # noqa: E501
        )

        self.assertEqual(df_str_expected, captures[0])