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, 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)
                    snapshot_timestamp: float = time.time()
                    snapshot_msg: OrderBookMessage = KucoinOrderBook.snapshot_message_from_exchange(
                        snapshot,
                        snapshot_timestamp,
                        metadata={"symbol": trading_pair})
                    order_book: OrderBook = self.order_book_create_function()
                    order_book.apply_snapshot(snapshot_msg.bids,
                                              snapshot_msg.asks,
                                              snapshot_msg.update_id)
                    retval[trading_pair] = OrderBookTrackerEntry(
                        trading_pair, snapshot_timestamp, order_book)
                    self.logger().info(
                        f"Initialized order book for {trading_pair}. "
                        f"{index+1}/{number_of_pairs} completed.")
                    # Kucoin rate limit is 100 https requests per 10 seconds
                    await asyncio.sleep(0.4)
                except Exception:
                    self.logger().error(
                        f"Error getting snapshot for {trading_pair}. ",
                        exc_info=True)
                    await asyncio.sleep(5)
            return retval
 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)
         snapshot_timestamp: float = time.time()
         snapshot_msg: OrderBookMessage = KucoinOrderBook.snapshot_message_from_exchange(
             snapshot,
             snapshot_timestamp,
             metadata={"symbol": trading_pair})
         order_book: OrderBook = self.order_book_create_function()
         active_order_tracker: KucoinActiveOrderTracker = KucoinActiveOrderTracker(
         )
         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
Exemple #3
0
    async def listen_for_trades(self, ev_loop: asyncio.BaseEventLoop,
                                output: asyncio.Queue):
        websocket_data: Dict[str, Any] = await self.ws_connect_data()
        kucoin_ws_uri: str = websocket_data["data"]["instanceServers"][0][
            "endpoint"] + "?token=" + websocket_data["data"][
                "token"] + "&acceptUserMessage=true"
        while True:
            try:
                trading_pairs: List[str] = await self.get_trading_pairs()
                async with websockets.connect(kucoin_ws_uri) as ws:
                    ws: websockets.WebSocketClientProtocol = ws
                    for trading_pair in trading_pairs:
                        subscribe_request: Dict[str, Any] = {
                            "id": int(time.time()),
                            "type": "subscribe",
                            "topic": f"/market/match:{trading_pair}",
                            "privateChannel": False,
                            "response": True
                        }
                        await ws.send(json.dumps(subscribe_request))

                    async for raw_msg in self._inner_messages(ws):
                        msg: Dict[str, Any] = json.loads(raw_msg)
                        if msg["type"] == "pong" or msg["type"] == "ack":
                            pass
                        elif msg["type"] == "message":
                            trading_pair = msg["data"]["symbol"]
                            data = msg["data"]
                            trade_message: OrderBookMessage = KucoinOrderBook.trade_message_from_exchange(
                                data, metadata={"trading_pair": trading_pair})
                            output.put_nowait(trade_message)
                        else:
                            self.logger().debug(
                                f"Unrecognized message received from Kucoin websocket: {msg}"
                            )
            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)
Exemple #4
0
 async def listen_for_order_book_snapshots(self,
                                           ev_loop: asyncio.BaseEventLoop,
                                           output: asyncio.Queue):
     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: OrderBookMessage = KucoinOrderBook.snapshot_message_from_exchange(
                             snapshot,
                             snapshot_timestamp,
                             metadata={"symbol": trading_pair})
                         output.put_nowait(snapshot_msg)
                         self.logger().debug(
                             f"Saved order book snapshot for {trading_pair}"
                         )
                         await asyncio.sleep(5.0)
                     except asyncio.CancelledError:
                         raise
                     except Exception:
                         self.logger().error("Unexpected error.",
                                             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().error("Unexpected error.", exc_info=True)
             await asyncio.sleep(5.0)