class BitcoinComWebsocketUnitTest(unittest.TestCase): auth = BitcoinComAuth(conf.bitcoin_com_api_key, conf.bitcoin_com_secret_key) ws = BitcoinComWebsocket() # balances = None @classmethod def setUpClass(cls): cls.ev_loop: asyncio.BaseEventLoop = asyncio.get_event_loop() cls.ev_loop.run_until_complete(cls.wait_til_ready()) @classmethod async def wait_til_ready(cls): while True: await cls.ws.connect() if cls.ws._client.open is True: print("Websocket connection established.") return await asyncio.sleep(1) def test_open(self): """ Tests if websocket connection is opened succesfully """ self.assertTrue(self.ws._client.open)
async def listen_for_trades(self, ev_loop: asyncio.BaseEventLoop, output: asyncio.Queue): """ Listen for trades using websocket "updateTrades" method """ while True: try: ws = BitcoinComWebsocket() await ws.connect() trading_pairs: List[str] = await self.get_trading_pairs() for trading_pair in trading_pairs: await ws.subscribe( "subscribeTrades", { "symbol": trading_pair, "limit": 1 # we only care about updates, this sets the initial snapshot limit }) async for response in ws.on("updateTrades"): if (response["error"] is not None): self.logger().error(response["error"]) continue trades = response["data"]["data"] for trade in trades: trade_timestamp: float = pd.Timestamp( trade["timestamp"]).timestamp() trade_msg: OrderBookMessage = BitcoinComOrderBook.trade_message_from_exchange( add_event_type(EventTypes.TradesUpdate, trade), trade_timestamp, metadata={"trading_pair": trading_pair}) output.put_nowait(trade_msg) except asyncio.CancelledError: raise except Exception: self.logger().error("Unexpected error.", exc_info=True) await asyncio.sleep(5.0) finally: await ws.disconnect()
async def listen_for_order_book_diffs(self, ev_loop: asyncio.BaseEventLoop, output: asyncio.Queue): """ Listen for orderbook diffs using websocket "updateOrderbook" method """ while True: try: ws = BitcoinComWebsocket() await ws.connect() trading_pairs: List[str] = await self.get_trading_pairs() for trading_pair in trading_pairs: await ws.subscribe("subscribeOrderbook", {"symbol": trading_pair}) async for response in ws.on("updateOrderbook"): if (response["error"] is not None): self.logger().error(response["error"]) continue diff = response["data"] diff_timestamp: float = pd.Timestamp( diff["timestamp"]).timestamp() orderbook_msg: OrderBookMessage = BitcoinComOrderBook.diff_message_from_exchange( add_event_type(EventTypes.OrderbookUpdate, diff), diff_timestamp, metadata={"trading_pair": trading_pair}) output.put_nowait(orderbook_msg) except asyncio.CancelledError: raise except Exception: self.logger().network( f"Unexpected error with WebSocket connection.", exc_info=True, app_warning_msg= f"Unexpected error with WebSocket connection. Retrying in 30 seconds. " f"Check network connection.") await asyncio.sleep(30.0) finally: await ws.disconnect()
async def _listen_to_reports(self) -> AsyncIterable[Any]: """ Subscribe to reports via web socket """ try: ws = BitcoinComWebsocket() await ws.connect() async for authenticated in ws.authenticate(self._bitcoin_com_auth.api_key, self._bitcoin_com_auth.secret_key): await ws.subscribe("subscribeReports", {}) async for msg in ws._messages(): if (msg["method"] not in ["activeOrders", "report"]): continue yield msg except Exception as e: raise e finally: await ws.disconnect()