0
# Depth Caching
1
2
Efficient real-time order book management with automatic synchronization from WebSocket streams. Provides sorted bid/ask access and maintains consistent order book state with configurable precision and conversion types.
3
4
## Capabilities
5
6
### DepthCacheManager
7
8
Main class for managing real-time order book caches with automatic WebSocket synchronization.
9
10
```python { .api }
11
class DepthCacheManager:
12
def __init__(
13
self,
14
client: AsyncClient,
15
symbol: str,
16
refresh_interval: Optional[int] = None,
17
bm: Optional[BinanceSocketManager] = None,
18
limit: int = 500,
19
conv_type: Callable = float
20
): ...
21
22
async def __aenter__(self): ...
23
async def __aexit__(self, exc_type, exc_val, exc_tb): ...
24
def get_depth_cache(self) -> DepthCache: ...
25
```
26
27
#### Usage Examples
28
29
```python
30
import asyncio
31
from binance import AsyncClient, DepthCacheManager
32
33
async def main():
34
# Initialize async client
35
client = await AsyncClient.create()
36
37
try:
38
# Create depth cache manager
39
async with DepthCacheManager(client, symbol='BTCUSDT') as dcm:
40
# Get the depth cache
41
depth_cache = dcm.get_depth_cache()
42
43
# Monitor order book changes
44
for i in range(100):
45
await asyncio.sleep(1)
46
47
# Get current best bid/ask
48
bids = depth_cache.get_bids()[:5] # Top 5 bids
49
asks = depth_cache.get_asks()[:5] # Top 5 asks
50
51
if bids and asks:
52
print(f"Best bid: {bids[0][0]} ({bids[0][1]})")
53
print(f"Best ask: {asks[0][0]} ({asks[0][1]})")
54
print(f"Spread: {float(asks[0][0]) - float(bids[0][0]):.2f}")
55
print(f"Update time: {depth_cache.update_time}")
56
print("---")
57
58
finally:
59
await client.close_connection()
60
61
asyncio.run(main())
62
```
63
64
### DepthCache
65
66
Individual order book cache for managing bids and asks.
67
68
```python { .api }
69
class DepthCache:
70
def __init__(self, symbol, conv_type: Callable = float): ...
71
72
def add_bid(self, bid): ...
73
def add_ask(self, ask): ...
74
def get_bids(self) -> List[List]: ...
75
def get_asks(self) -> List[List]: ...
76
def get_top_bids(self, k: int) -> List[List]: ...
77
def get_top_asks(self, k: int) -> List[List]: ...
78
@staticmethod
79
def sort_depth(depth_dict, reverse: bool = False, conv_type: Callable = float) -> List[List]: ...
80
```
81
82
#### Usage Examples
83
84
```python
85
from binance.ws import DepthCache
86
87
# Create depth cache with custom conversion type
88
from decimal import Decimal
89
depth_cache = DepthCache('BTCUSDT', conv_type=Decimal)
90
91
# Manually add bids and asks (normally done automatically)
92
depth_cache.add_bid(['50000.00', '0.5'])
93
depth_cache.add_bid(['49950.00', '1.0'])
94
depth_cache.add_ask(['50050.00', '0.3'])
95
depth_cache.add_ask(['50100.00', '0.8'])
96
97
# Get sorted order book data
98
bids = depth_cache.get_bids()
99
asks = depth_cache.get_asks()
100
101
print("Bids (price, quantity):")
102
for bid in bids[:10]:
103
print(f" {bid[0]} @ {bid[1]}")
104
105
print("Asks (price, quantity):")
106
for ask in asks[:10]:
107
print(f" {ask[0]} @ {ask[1]}")
108
109
# Get top N levels
110
top_5_bids = depth_cache.get_top_bids(5)
111
top_5_asks = depth_cache.get_top_asks(5)
112
113
# Calculate order book statistics
114
total_bid_volume = sum(float(bid[1]) for bid in bids)
115
total_ask_volume = sum(float(ask[1]) for ask in asks)
116
117
print(f"Total bid volume: {total_bid_volume}")
118
print(f"Total ask volume: {total_ask_volume}")
119
```
120
121
### ThreadedDepthCacheManager
122
123
Thread-based depth cache manager for easier integration with non-async code.
124
125
```python { .api }
126
class ThreadedDepthCacheManager:
127
def __init__(
128
self,
129
api_key: str,
130
api_secret: str,
131
symbol: str,
132
refresh_interval: Optional[int] = None,
133
testnet: bool = False
134
): ...
135
136
def start(self): ...
137
def stop(self): ...
138
def get_depth_cache(self) -> DepthCache: ...
139
```
140
141
#### Usage Examples
142
143
```python
144
import time
145
from binance.ws import ThreadedDepthCacheManager
146
147
def main():
148
# Initialize threaded depth cache manager
149
dcm = ThreadedDepthCacheManager(
150
api_key='your_key',
151
api_secret='your_secret',
152
symbol='BTCUSDT'
153
)
154
155
try:
156
# Start the manager
157
dcm.start()
158
159
# Wait for initial synchronization
160
time.sleep(2)
161
162
# Monitor order book
163
for i in range(60): # Monitor for 1 minute
164
depth_cache = dcm.get_depth_cache()
165
166
if depth_cache:
167
bids = depth_cache.get_bids()[:3]
168
asks = depth_cache.get_asks()[:3]
169
170
print(f"Time: {time.time()}")
171
print(f"Top 3 bids: {bids}")
172
print(f"Top 3 asks: {asks}")
173
174
if bids and asks:
175
spread = float(asks[0][0]) - float(bids[0][0])
176
print(f"Spread: {spread:.2f}")
177
178
print("---")
179
180
time.sleep(1)
181
182
finally:
183
dcm.stop()
184
185
if __name__ == "__main__":
186
main()
187
```
188
189
### Specialized Depth Cache Managers
190
191
Different managers for various market types.
192
193
```python { .api }
194
class FuturesDepthCacheManager:
195
def __init__(
196
self,
197
client: AsyncClient,
198
symbol: str,
199
refresh_interval: Optional[int] = None,
200
bm: Optional[BinanceSocketManager] = None,
201
limit: int = 500,
202
conv_type: Callable = float
203
): ...
204
205
class OptionsDepthCacheManager:
206
def __init__(
207
self,
208
client: AsyncClient,
209
symbol: str,
210
refresh_interval: Optional[int] = None,
211
bm: Optional[BinanceSocketManager] = None,
212
limit: int = 500,
213
conv_type: Callable = float
214
): ...
215
```
216
217
#### Specialized Usage Examples
218
219
```python
220
from binance import AsyncClient, FuturesDepthCacheManager, OptionsDepthCacheManager
221
222
async def futures_depth_monitoring():
223
client = await AsyncClient.create()
224
225
try:
226
# Monitor futures order book
227
async with FuturesDepthCacheManager(client, symbol='BTCUSDT') as dcm:
228
depth_cache = dcm.get_depth_cache()
229
230
for i in range(60):
231
await asyncio.sleep(1)
232
233
bids = depth_cache.get_bids()[:5]
234
asks = depth_cache.get_asks()[:5]
235
236
print(f"Futures BTCUSDT - Best bid: {bids[0] if bids else 'N/A'}")
237
print(f"Futures BTCUSDT - Best ask: {asks[0] if asks else 'N/A'}")
238
239
finally:
240
await client.close_connection()
241
242
async def options_depth_monitoring():
243
client = await AsyncClient.create()
244
245
try:
246
# Monitor options order book
247
async with OptionsDepthCacheManager(client, symbol='BTC-240329-70000-C') as dcm:
248
depth_cache = dcm.get_depth_cache()
249
250
for i in range(60):
251
await asyncio.sleep(1)
252
253
bids = depth_cache.get_bids()[:3]
254
asks = depth_cache.get_asks()[:3]
255
256
print(f"Options - Best bid: {bids[0] if bids else 'N/A'}")
257
print(f"Options - Best ask: {asks[0] if asks else 'N/A'}")
258
259
finally:
260
await client.close_connection()
261
```
262
263
### Advanced Depth Cache Configuration
264
265
#### Custom Conversion Types
266
267
```python
268
from decimal import Decimal
269
import asyncio
270
from binance import AsyncClient, DepthCacheManager
271
272
async def high_precision_monitoring():
273
client = await AsyncClient.create()
274
275
try:
276
# Use Decimal for high precision
277
async with DepthCacheManager(
278
client,
279
symbol='BTCUSDT',
280
conv_type=Decimal # High precision arithmetic
281
) as dcm:
282
depth_cache = dcm.get_depth_cache()
283
284
await asyncio.sleep(2) # Wait for sync
285
286
bids = depth_cache.get_bids()[:5]
287
asks = depth_cache.get_asks()[:5]
288
289
print("High precision order book:")
290
for i, (bid, ask) in enumerate(zip(bids, asks)):
291
print(f"Level {i+1}: Bid {bid[0]} ({bid[1]}) | Ask {ask[0]} ({ask[1]})")
292
293
# Calculate precise spread
294
spread = ask[0] - bid[0]
295
print(f" Spread: {spread}")
296
297
finally:
298
await client.close_connection()
299
300
asyncio.run(high_precision_monitoring())
301
```
302
303
#### Custom Refresh Intervals
304
305
```python
306
async def custom_refresh_monitoring():
307
client = await AsyncClient.create()
308
309
try:
310
# Refresh order book snapshot every 10 seconds
311
async with DepthCacheManager(
312
client,
313
symbol='BTCUSDT',
314
refresh_interval=10 # Seconds
315
) as dcm:
316
depth_cache = dcm.get_depth_cache()
317
318
# Monitor for changes
319
for i in range(120): # 2 minutes
320
await asyncio.sleep(1)
321
322
if i % 10 == 0: # Print every 10 seconds
323
bids = depth_cache.get_bids()[:3]
324
asks = depth_cache.get_asks()[:3]
325
326
print(f"Refresh cycle {i//10}: Update time {depth_cache.update_time}")
327
print(f"Bids: {bids}")
328
print(f"Asks: {asks}")
329
330
finally:
331
await client.close_connection()
332
```
333
334
### Order Book Analysis
335
336
#### Market Depth Analysis
337
338
```python
339
async def market_depth_analysis():
340
client = await AsyncClient.create()
341
342
try:
343
async with DepthCacheManager(client, symbol='BTCUSDT') as dcm:
344
depth_cache = dcm.get_depth_cache()
345
346
await asyncio.sleep(3) # Wait for sync
347
348
bids = depth_cache.get_bids()
349
asks = depth_cache.get_asks()
350
351
# Calculate cumulative volumes
352
cumulative_bid_volume = 0
353
cumulative_ask_volume = 0
354
355
print("Market Depth Analysis:")
356
print("Level | Bid Price | Bid Vol | Cum Bid | Ask Price | Ask Vol | Cum Ask | Spread")
357
print("-" * 80)
358
359
for i in range(min(10, len(bids), len(asks))):
360
bid_price, bid_vol = bids[i]
361
ask_price, ask_vol = asks[i]
362
363
cumulative_bid_volume += float(bid_vol)
364
cumulative_ask_volume += float(ask_vol)
365
366
spread = float(ask_price) - float(bid_price)
367
368
print(f"{i+1:5d} | {bid_price:9s} | {bid_vol:7s} | {cumulative_bid_volume:7.3f} | {ask_price:9s} | {ask_vol:7s} | {cumulative_ask_volume:7.3f} | {spread:6.2f}")
369
370
# Calculate market impact for different order sizes
371
print("\nMarket Impact Analysis:")
372
test_sizes = [0.1, 0.5, 1.0, 5.0, 10.0] # BTC amounts
373
374
for size in test_sizes:
375
# Calculate average execution price for market buy
376
remaining_size = size
377
total_cost = 0
378
379
for ask_price, ask_vol in asks:
380
if remaining_size <= 0:
381
break
382
383
vol_to_take = min(remaining_size, float(ask_vol))
384
total_cost += vol_to_take * float(ask_price)
385
remaining_size -= vol_to_take
386
387
if remaining_size <= 0:
388
avg_price = total_cost / size
389
market_price = float(asks[0][0])
390
impact = ((avg_price - market_price) / market_price) * 100
391
print(f"Buy {size:4.1f} BTC: Avg price {avg_price:8.2f}, Impact {impact:5.2f}%")
392
393
finally:
394
await client.close_connection()
395
396
asyncio.run(market_depth_analysis())
397
```
398
399
### Error Handling and Monitoring
400
401
```python
402
import asyncio
403
import logging
404
from binance import AsyncClient, DepthCacheManager
405
from binance.exceptions import BinanceWebsocketUnableToConnect
406
407
logging.basicConfig(level=logging.INFO)
408
409
async def robust_depth_monitoring():
410
client = await AsyncClient.create()
411
412
retry_count = 0
413
max_retries = 5
414
415
while retry_count < max_retries:
416
try:
417
async with DepthCacheManager(client, symbol='BTCUSDT') as dcm:
418
depth_cache = dcm.get_depth_cache()
419
420
consecutive_errors = 0
421
max_consecutive_errors = 10
422
423
for i in range(300): # 5 minutes
424
try:
425
await asyncio.sleep(1)
426
427
bids = depth_cache.get_bids()
428
asks = depth_cache.get_asks()
429
430
if not bids or not asks:
431
consecutive_errors += 1
432
if consecutive_errors > max_consecutive_errors:
433
raise Exception("Too many consecutive empty order book updates")
434
continue
435
436
consecutive_errors = 0
437
438
# Normal processing
439
if i % 10 == 0: # Log every 10 seconds
440
print(f"Status OK: Best bid {bids[0][0]}, Best ask {asks[0][0]}")
441
442
except Exception as e:
443
logging.error(f"Error during monitoring: {e}")
444
break
445
446
# If we get here, monitoring completed successfully
447
break
448
449
except BinanceWebsocketUnableToConnect as e:
450
retry_count += 1
451
logging.error(f"WebSocket connection failed (attempt {retry_count}): {e}")
452
if retry_count < max_retries:
453
await asyncio.sleep(2 ** retry_count) # Exponential backoff
454
else:
455
logging.error("Max retries reached, giving up")
456
break
457
458
except Exception as e:
459
logging.error(f"Unexpected error: {e}")
460
break
461
462
await client.close_connection()
463
464
asyncio.run(robust_depth_monitoring())
465
```
466
467
The depth cache system provides efficient real-time order book management with automatic synchronization, flexible precision control, and comprehensive market depth analysis capabilities for all Binance market types.