|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +import os |
| 4 | +import sys |
| 5 | + |
| 6 | +root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) |
| 7 | +sys.path.append(root) |
| 8 | + |
| 9 | +import asyncio |
| 10 | +import logging |
| 11 | +from binance import AsyncClient |
| 12 | +from binance.ws.depthcache import DepthCacheManager |
| 13 | + |
| 14 | +logging.basicConfig(level=logging.DEBUG) |
| 15 | +logger = logging.getLogger(__name__) |
| 16 | + |
| 17 | +async def main(): |
| 18 | + # Initialize the client |
| 19 | + client = await AsyncClient.create() |
| 20 | + |
| 21 | + # Symbol to monitor |
| 22 | + symbol = 'BTCUSDT' |
| 23 | + |
| 24 | + # Create a depth cache manager instance |
| 25 | + async with DepthCacheManager( |
| 26 | + client=client, |
| 27 | + symbol=symbol, |
| 28 | + ) as dcm: |
| 29 | + logger.info(f"Started depth cache for {symbol}") |
| 30 | + |
| 31 | + # Monitor depth cache updates for 1 minute |
| 32 | + for _ in range(100): # 6 iterations * 10 seconds = 1 minute |
| 33 | + depth_cache = await dcm.recv() |
| 34 | + if isinstance(depth_cache, dict) and depth_cache.get('e') == 'error': |
| 35 | + logger.error(f"Received depth cache error in callback: {depth_cache}") |
| 36 | + if type == 'BinanceWebsocketClosed': |
| 37 | + # ignore as attempts to reconnect |
| 38 | + continue |
| 39 | + break |
| 40 | + |
| 41 | + # Get current bids and asks |
| 42 | + bids = depth_cache.get_bids()[:5] # Top 5 bids |
| 43 | + asks = depth_cache.get_asks()[:5] # Top 5 asks |
| 44 | + |
| 45 | + logger.info("Top 5 bids:") |
| 46 | + for bid in bids: |
| 47 | + logger.info(f"Price: {bid[0]}, Quantity: {bid[1]}") |
| 48 | + |
| 49 | + logger.info("Top 5 asks:") |
| 50 | + for ask in asks: |
| 51 | + logger.info(f"Price: {ask[0]}, Quantity: {ask[1]}") |
| 52 | + |
| 53 | + logger.info(f"Last update time: {depth_cache.update_time}") |
| 54 | + |
| 55 | + # Close the client |
| 56 | + await client.close_connection() |
| 57 | + |
| 58 | +if __name__ == '__main__': |
| 59 | + # Run the async example |
| 60 | + asyncio.run(main()) |
0 commit comments