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_trading_pair(evt.trading_pair) 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), price=float(evt.price) if evt.price == evt.price else 0, 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 _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)