async def listen_for_order_book_diffs(self, ev_loop: asyncio.BaseEventLoop, output: asyncio.Queue):
     while True:
         try:
             trading_pairs: List[str] = await self.get_trading_pairs()
             async with websockets.connect(WS_URL) as ws:
                 ws: websockets.WebSocketClientProtocol = ws
                 request: Dict[str, any] = {
                     "type": "subscribe",
                     "channels": [{
                         "name": "full",
                         "marketIds": trading_pairs
                     }]
                 }
                 await ws.send(ujson.dumps(request))
                 async for raw_msg in self._inner_messages(ws):
                     msg = ujson.loads(raw_msg)
                     # only process receive and done diff messages from DDEX
                     if msg["type"] in ["receive", "done"]:
                         diff_msg: DDEXOrderBookMessage = DDEXOrderBook.diff_message_from_exchange(msg)
                         output.put_nowait(diff_msg)
                     elif msg["type"] == "trade":
                         trade_msg: DDEXOrderBookMessage = DDEXOrderBook.trade_message_from_exchange(msg)
                         output.put_nowait(trade_msg)
         except asyncio.CancelledError:
             raise
         except Exception:
             self.logger().network(
                 f"Error getting order book diff messages.",
                 exc_info=True,
                 app_warning_msg=f"Error getting order book diff messages. Check network connection."
             )
             await asyncio.sleep(30.0)
Example #2
0
 async def listen_for_order_book_snapshots(self,
                                           ev_loop: asyncio.BaseEventLoop,
                                           output: asyncio.Queue):
     await self._get_tracking_pair_done_event.wait()
     while True:
         try:
             trading_pairs: List[str] = await self.get_trading_pairs()
             async with aiohttp.ClientSession() as client:
                 for trading_pair in trading_pairs:
                     try:
                         snapshot: Dict[str, any] = await self.get_snapshot(
                             client, trading_pair)
                         snapshot_timestamp: float = time.time()
                         snapshot_msg: DDEXOrderBookMessage = DDEXOrderBook.snapshot_message_from_exchange(
                             snapshot, snapshot_timestamp,
                             {"marketId": trading_pair})
                         output.put_nowait(snapshot_msg)
                         self.logger().debug(
                             f"Saved order book snapshot for {trading_pair} at {snapshot_timestamp}"
                         )
                         await asyncio.sleep(5.0)
                     except asyncio.CancelledError:
                         raise
                     except IOError:
                         self.logger().network(
                             f"Error getting snapshot for {trading_pair}.",
                             exc_info=True,
                             app_warning_msg=
                             f"Error getting snapshot for {trading_pair}. Check network connection."
                         )
                         await asyncio.sleep(5.0)
                     except Exception:
                         self.logger().error(
                             f"Error processing snapshot for {trading_pair}.",
                             exc_info=True)
                         await asyncio.sleep(5.0)
                 this_hour: pd.Timestamp = pd.Timestamp.utcnow().replace(
                     minute=0, second=0, microsecond=0)
                 next_hour: pd.Timestamp = this_hour + pd.Timedelta(hours=1)
                 delta: float = next_hour.timestamp() - time.time()
                 await asyncio.sleep(delta)
         except asyncio.CancelledError:
             raise
         except Exception:
             self.logger().network(
                 f"Unexpected error listening for order book snapshot.",
                 exc_info=True,
                 app_warning_msg=
                 f"Unexpected error listening for order book snapshot. Check network connection."
             )
             await asyncio.sleep(5.0)
Example #3
0
    async def get_tracking_pairs(self) -> Dict[str, OrderBookTrackerEntry]:
        # Get the currently active markets
        async with aiohttp.ClientSession() as client:
            trading_pairs: List[str] = await self.get_trading_pairs()
            retval: Dict[str, DDEXOrderBookTrackerEntry] = {}
            number_of_pairs: int = len(trading_pairs)
            for index, trading_pair in enumerate(trading_pairs):
                try:
                    snapshot: Dict[str, any] = await self.get_snapshot(
                        client, trading_pair, 3)
                    snapshot_timestamp: float = time.time()
                    snapshot_msg: DDEXOrderBookMessage = DDEXOrderBook.snapshot_message_from_exchange(
                        snapshot, snapshot_timestamp,
                        {"marketId": trading_pair})
                    ddex_order_book: OrderBook = self.order_book_create_function(
                    )
                    ddex_active_order_tracker: DDEXActiveOrderTracker = DDEXActiveOrderTracker(
                    )
                    bids, asks = ddex_active_order_tracker.convert_snapshot_message_to_order_book_row(
                        snapshot_msg)
                    ddex_order_book.apply_snapshot(bids, asks,
                                                   snapshot_msg.update_id)

                    retval[trading_pair] = DDEXOrderBookTrackerEntry(
                        trading_pair, snapshot_timestamp, ddex_order_book,
                        ddex_active_order_tracker)

                    self.logger().info(
                        f"Initialized order book for {trading_pair}. "
                        f"{index+1}/{number_of_pairs} completed.")
                    await asyncio.sleep(1.3)
                except IOError:
                    self.logger().network(
                        f"Error getting snapshot for {trading_pair}.",
                        exc_info=True,
                        app_warning_msg=
                        f"Error getting snapshot for {trading_pair}. Check network connection."
                    )
                    await asyncio.sleep(5.0)
                except Exception:
                    self.logger().error(
                        f"Error initializing order book for {trading_pair}.",
                        exc_info=True)
                    await asyncio.sleep(5.0)

            self._get_tracking_pair_done_event.set()
            return retval