async def get_tracking_pairs(self) -> Dict[str, OrderBookTrackerEntry]:
        async with aiohttp.ClientSession() as client:
            trading_pairs: Optional[List[str]] = await self.get_trading_pairs()
            assert trading_pairs is not None
            retval: Dict[str, OrderBookTrackerEntry] = {}
            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, 20)
                    snapshot_timestamp = snapshot['timestamp']
                    snapshot_msg: OrderBookMessage = BeaxyOrderBook.snapshot_message_from_exchange(
                        snapshot,
                        snapshot_timestamp,
                        metadata={'trading_pair': trading_pair})
                    order_book: OrderBook = self.order_book_create_function()
                    active_order_tracker: BeaxyActiveOrderTracker = BeaxyActiveOrderTracker(
                    )
                    bids, asks = active_order_tracker.convert_snapshot_message_to_order_book_row(
                        snapshot_msg)
                    order_book.apply_snapshot(bids, asks,
                                              snapshot_msg.update_id)
                    retval[trading_pair] = BeaxyOrderBookTrackerEntry(
                        trading_pair, snapshot_timestamp, order_book,
                        active_order_tracker)

                    self.logger().info(
                        f'Initialized order book for {trading_pair}. '
                        f'{index+1}/{number_of_pairs} completed.')
                except Exception:
                    self.logger().error(
                        f'Error getting snapshot for {trading_pair}. ',
                        exc_info=True)
                    await asyncio.sleep(5.0)
            return retval
    async def listen_for_order_book_snapshots(self, ev_loop: asyncio.BaseEventLoop, output: asyncio.Queue):
        while True:
            try:
                # at Beaxy all pairs listed without splitter
                trading_pairs = [trading_pair_to_symbol(p) for p in self._trading_pairs]

                ws_path: str = '/'.join([f'{trading_pair}@depth20' for trading_pair in trading_pairs])
                stream_url: str = f'{BeaxyConstants.PublicApi.WS_BASE_URL}/book/{ws_path}'

                async with websockets.connect(stream_url) as ws:
                    ws: websockets.WebSocketClientProtocol = ws
                    async for raw_msg in self._inner_messages(ws):
                        msg = json.loads(raw_msg)  # ujson may round floats uncorrectly
                        msg_type = msg['type']
                        if msg_type == ORDERBOOK_MESSAGE_DIFF:
                            order_book_message: OrderBookMessage = BeaxyOrderBook.diff_message_from_exchange(
                                msg, msg['timestamp'])
                            output.put_nowait(order_book_message)
                        if msg_type == ORDERBOOK_MESSAGE_SNAPSHOT:
                            order_book_message: OrderBookMessage = BeaxyOrderBook.snapshot_message_from_exchange(
                                msg, msg['timestamp'])
                            output.put_nowait(order_book_message)
            except asyncio.CancelledError:
                raise
            except Exception:
                self.logger().error('Unexpected error with WebSocket connection. Retrying after 30 seconds...',
                                    exc_info=True)
                await asyncio.sleep(30.0)
Пример #3
0
    def test_snapshot(self):
        active_tracker = BeaxyActiveOrderTracker()
        insert_message = BeaxyOrderBook.snapshot_message_from_exchange(FixtureBeaxy.SNAPSHOT_MSG, float(12345))

        active_tracker.convert_snapshot_message_to_order_book_row(insert_message)

        self.assertEqual(len(active_tracker.active_asks), 9)
 async def get_new_order_book(self, trading_pair: str) -> OrderBook:
     async with aiohttp.ClientSession() as client:
         snapshot: Dict[str, Any] = await self.get_snapshot(client, trading_pair, 20)
         snapshot_timestamp = snapshot['timestamp']
         snapshot_msg: OrderBookMessage = BeaxyOrderBook.snapshot_message_from_exchange(
             snapshot,
             snapshot_timestamp,
             metadata={'trading_pair': trading_pair}
         )
         order_book: OrderBook = self.order_book_create_function()
         active_order_tracker: BeaxyActiveOrderTracker = BeaxyActiveOrderTracker()
         bids, asks = active_order_tracker.convert_snapshot_message_to_order_book_row(snapshot_msg)
         order_book.apply_snapshot(bids, asks, snapshot_msg.update_id)
         return order_book