def get_mid_price(trading_pair: str) -> Optional[Decimal]: exchange_trading_pair = convert_to_exchange_trading_pair(trading_pair) resp = requests.get( url= f"https://api-pub.bitfinex.com/v2/ticker/{exchange_trading_pair}") record = resp.json() result = (Decimal(record[0]) + Decimal(record[2])) / Decimal("2") return result
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() for trading_pair in trading_pairs: async with websockets.connect(BITFINEX_WS_URI) as ws: payload: Dict[str, Any] = { "event": "subscribe", "channel": "book", "prec": "P0", "symbol": convert_to_exchange_trading_pair(trading_pair), } await ws.send(ujson.dumps(payload)) await asyncio.wait_for(ws.recv(), timeout=self.MESSAGE_TIMEOUT ) # response await asyncio.wait_for(ws.recv(), timeout=self.MESSAGE_TIMEOUT ) # subscribe info raw_snapshot = await asyncio.wait_for( ws.recv(), timeout=self.MESSAGE_TIMEOUT) # snapshot snapshot = self._prepare_snapshot( trading_pair, [ BookStructure(*i) for i in ujson.loads(raw_snapshot)[1] ]) snapshot_timestamp: float = time.time() snapshot_msg: OrderBookMessage = BitfinexOrderBook.snapshot_message_from_exchange( snapshot, snapshot_timestamp) output.put_nowait(snapshot_msg) async for raw_msg in self._get_response(ws): msg = self._parse_raw_update(trading_pair, raw_msg) if msg is not None: output.put_nowait(msg) except Exception as err: self.logger().error(err) self.logger().network( "Unexpected error with WebSocket connection.", exc_info=True, app_warning_msg= "Unexpected error with WebSocket connection. " f"Retrying in {int(self.MESSAGE_TIMEOUT)} seconds. " "Check network connection.") await asyncio.sleep(5)
async def listen_for_trades(self, ev_loop: asyncio.BaseEventLoop, output: asyncio.Queue): while True: try: trading_pairs: List[str] = await self.get_trading_pairs() for trading_pair in trading_pairs: async with websockets.connect(BITFINEX_WS_URI) as ws: payload: Dict[str, Any] = { "event": "subscribe", "channel": "trades", "symbol": convert_to_exchange_trading_pair(trading_pair), } await ws.send(ujson.dumps(payload)) await asyncio.wait_for(ws.recv(), timeout=self.MESSAGE_TIMEOUT ) # response await asyncio.wait_for(ws.recv(), timeout=self.MESSAGE_TIMEOUT ) # subscribe info await asyncio.wait_for(ws.recv(), timeout=self.MESSAGE_TIMEOUT ) # snapshot async for raw_msg in self._get_response(ws): msg = self._prepare_trade(raw_msg) if msg: msg_book: OrderBookMessage = BitfinexOrderBook.trade_message_from_exchange( msg, metadata={"symbol": f"{trading_pair}"}) output.put_nowait(msg_book) except Exception as err: self.logger().error(err) self.logger().network( "Unexpected error with WebSocket connection.", exc_info=True, app_warning_msg= "Unexpected error with WebSocket connection. " f"Retrying in {int(self.MESSAGE_TIMEOUT)} seconds. " "Check network connection.") await asyncio.sleep(5)