Exemplo n.º 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=evt.amount,
                                    price=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()
    def _update_order_status(self, event_tag: int, market: ConnectorBase,
                             evt: Union[OrderCancelledEvent,
                                        MarketOrderFailureEvent,
                                        BuyOrderCompletedEvent,
                                        SellOrderCompletedEvent,
                                        OrderExpiredEvent]):
        if threading.current_thread() != threading.main_thread():
            self._ev_loop.call_soon_threadsafe(self._update_order_status,
                                               event_tag, market, evt)
            return

        timestamp: int = self.db_timestamp
        event_type: MarketEvent = self.market_event_tag_map[event_tag]
        order_id: str = evt.order_id

        with self._sql_manager.get_new_session() as session:
            with session.begin():
                order_record: Optional[Order] = session.query(Order).filter(
                    Order.id == order_id).one_or_none()

                if order_record is not None:
                    order_record.last_status = event_type.name
                    order_record.last_update_timestamp = timestamp
                    order_status: OrderStatus = OrderStatus(
                        order_id=order_id,
                        timestamp=timestamp,
                        status=event_type.name)
                    session.add(order_status)
                    self.save_market_states(self._config_file_path,
                                            market,
                                            session=session)
Exemplo n.º 3
0
    def _update_order_status(self, event_tag: int, market: MarketBase,
                             evt: Union[OrderCancelledEvent,
                                        MarketOrderFailureEvent,
                                        BuyOrderCompletedEvent,
                                        SellOrderCompletedEvent,
                                        OrderExpiredEvent]):
        if threading.current_thread() != threading.main_thread():
            self._ev_loop.call_soon_threadsafe(self._update_order_status,
                                               event_tag, market, evt)
            return

        session: Session = self.session
        timestamp: int = self.db_timestamp
        event_type: MarketEvent = self.market_event_tag_map[event_tag]
        order_id: str = evt.order_id
        order_record: Optional[Order] = session.query(Order).filter(
            Order.id == order_id).one_or_none()

        if order_record is not None:
            order_record.last_status = event_type.name
            order_record.last_update_timestamp = timestamp
            order_status: OrderStatus = OrderStatus(order_id=order_id,
                                                    timestamp=timestamp,
                                                    status=event_type.name)
            session.add(order_status)
            self.save_market_states(self._config_file_path,
                                    market,
                                    no_commit=True)
            session.commit()
        else:
            session.rollback()
Exemplo n.º 4
0
 async def submit_order_statuses(self):
     try:
         order_statuses: List[
             OrderStatus] = await self.get_unsubmitted_order_statuses()
         # only submit 5000 at a time
         formatted_order_statuses: List[Dict[str, Any]] = [
             OrderStatus.to_bounty_api_json(order_status)
             for order_status in order_statuses[:5000]
         ]
         if self._last_submitted_order_status_timestamp >= 0 and len(
                 formatted_order_statuses) > 0:
             url = f"{self.LIQUIDITY_BOUNTY_REST_API}/order_status"
             results = await self.authenticated_request(
                 "POST",
                 url,
                 json={"order_statuses": formatted_order_statuses})
             self.logger().debug(results)
             num_submitted = results.get("order_status_submitted", 0)
             num_recorded = results.get("order_status_recorded", 0)
             if num_submitted != num_recorded:
                 self.logger().warning(
                     f"Failed to submit {num_submitted - num_recorded} order status(es)"
                 )
             if num_recorded > 0:
                 self.logger().info(
                     f"Successfully sent {num_recorded} order status(es) to claim bounty"
                 )
     except Exception:
         raise
Exemplo n.º 5
0
 def _did_create_order(self,
                       event_tag: int,
                       market: MarketBase,
                       evt: Union[BuyOrderCreatedEvent, SellOrderCreatedEvent]):
     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]
     order_record: Order = Order(id=evt.order_id,
                                 config_file_path=self._config_file_path,
                                 strategy=self._strategy_name,
                                 market=market.name,
                                 symbol=evt.symbol,
                                 base_asset=base_asset,
                                 quote_asset=quote_asset,
                                 creation_timestamp=timestamp,
                                 order_type=evt.type.name,
                                 amount=evt.amount,
                                 price=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()
Exemplo n.º 6
0
    def _did_fill_order(self, event_tag: int, market: ConnectorBase,
                        evt: OrderFilledEvent):
        if threading.current_thread() != threading.main_thread():
            self._ev_loop.call_soon_threadsafe(self._did_fill_order, event_tag,
                                               market, evt)
            return

        base_asset, quote_asset = evt.trading_pair.split("-")
        timestamp: int = self.db_timestamp
        event_type: MarketEvent = self.market_event_tag_map[event_tag]
        order_id: str = evt.order_id

        with self._sql_manager.get_new_session() as session:
            with session.begin():
                # Try to find the order record, and update it if necessary.
                order_record: Optional[Order] = session.query(Order).filter(
                    Order.id == order_id).one_or_none()
                if order_record is not None:
                    order_record.last_status = event_type.name
                    order_record.last_update_timestamp = timestamp

                # Order status and trade fill record should be added even if the order record is not found, because it's
                # possible for fill event to come in before the order created event for market orders.
                order_status: OrderStatus = OrderStatus(order_id=order_id,
                                                        timestamp=timestamp,
                                                        status=event_type.name)

                trade_fill_record: TradeFill = TradeFill(
                    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,
                    timestamp=timestamp,
                    order_id=order_id,
                    trade_type=evt.trade_type.name,
                    order_type=evt.order_type.name,
                    price=Decimal(evt.price)
                    if evt.price == evt.price else Decimal(0),
                    amount=Decimal(evt.amount),
                    leverage=evt.leverage if evt.leverage else 1,
                    trade_fee=evt.trade_fee.to_json(),
                    exchange_trade_id=evt.exchange_trade_id,
                    position=evt.position
                    if evt.position else PositionAction.NIL.value,
                )
                session.add(order_status)
                session.add(trade_fill_record)
                self.save_market_states(self._config_file_path,
                                        market,
                                        session=session)

                market.add_trade_fills_from_market_recorder({
                    TradeFillOrderDetails(trade_fill_record.market,
                                          trade_fill_record.exchange_trade_id,
                                          trade_fill_record.symbol)
                })
                self.append_to_csv(trade_fill_record)
Exemplo n.º 7
0
    def _did_fill_order(self, event_tag: int, market: MarketBase,
                        evt: OrderFilledEvent):
        if threading.current_thread() != threading.main_thread():
            self._ev_loop.call_soon_threadsafe(self._did_fill_order, event_tag,
                                               market, evt)
            return

        session: Session = self.session
        base_asset, quote_asset = market.split_trading_pair(evt.trading_pair)
        timestamp: int = self.db_timestamp
        event_type: MarketEvent = self.market_event_tag_map[event_tag]
        order_id: str = evt.order_id

        # Try to find the order record, and update it if necessary.
        order_record: Optional[Order] = session.query(Order).filter(
            Order.id == order_id).one_or_none()
        if order_record is not None:
            order_record.last_status = event_type.name
            order_record.last_update_timestamp = timestamp

        # Order status and trade fill record should be added even if the order record is not found, because it's
        # possible for fill event to come in before the order created event for market orders.
        order_status: OrderStatus = OrderStatus(order_id=order_id,
                                                timestamp=timestamp,
                                                status=event_type.name)
        trade_fill_record: TradeFill = TradeFill(
            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,
            timestamp=timestamp,
            order_id=order_id,
            trade_type=evt.trade_type.name,
            order_type=evt.order_type.name,
            price=float(evt.price) if evt.price == evt.price else 0,
            amount=float(evt.amount),
            trade_fee=TradeFee.to_json(evt.trade_fee),
            exchange_trade_id=evt.exchange_trade_id)
        session.add(order_status)
        session.add(trade_fill_record)
        self.save_market_states(self._config_file_path, market, no_commit=True)
        session.commit()
        self.append_to_csv(trade_fill_record)
    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)
Exemplo n.º 9
0
    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()