async def listen_for_trades(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( [trading_pair for trading_pair in trading_pairs]) stream_url: str = f'{BeaxyConstants.PublicApi.WS_BASE_URL}/trades/{ws_path}' async with websockets.connect(stream_url) as ws: ws: websockets.WebSocketClientProtocol = ws async for raw_msg in self._inner_messages(ws): msg = ujson.loads(raw_msg) trade_msg: OrderBookMessage = BeaxyOrderBook.trade_message_from_exchange( msg) output.put_nowait(trade_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)
async def get_snapshot(client: aiohttp.ClientSession, trading_pair: str, depth: int = 20) -> Dict[str, Any]: assert depth in [5, 10, 20] # at Beaxy all pairs listed without splitter symbol = trading_pair_to_symbol(trading_pair) async with client.get( BeaxyConstants.PublicApi.ORDER_BOOK_URL.format( symbol=symbol, depth=depth)) as response: response: aiohttp.ClientResponse if response.status != 200: raise IOError( f'Error fetching Beaxy market snapshot for {trading_pair}. ' f'HTTP status is {response.status}.') if not await response.text( ): # if test is empty it marks that there is no rows return { 'timestamp': 1, 'entries': [], 'sequenceNumber': 1, } data: Dict[str, Any] = await response.json() return data
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)
def get_mid_price(trading_pair: str) -> Optional[Decimal]: symbol = trading_pair_to_symbol(trading_pair) resp = requests.get(url=BeaxyConstants.PublicApi.RATE_URL.format( symbol=symbol)) record = resp.json() return (Decimal(record['bid']) + Decimal(record['ask'])) / Decimal('2')
async def last_price_for_pair(trading_pair): symbol = trading_pair_to_symbol(trading_pair) async with aiohttp.ClientSession() as client: async with client.get(BeaxyConstants.PublicApi.RATE_URL.format(symbol=symbol)) as response: response: aiohttp.ClientResponse if response.status != 200: raise IOError(f'Error fetching Beaxy market trade for {trading_pair}. ' f'HTTP status is {response.status}.') data: Dict[str, Any] = await response.json() return trading_pair, float(data['price'])