-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
Copy pathdepthcache.py
491 lines (383 loc) · 14.2 KB
/
depthcache.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
import logging
from operator import itemgetter
import asyncio
import time
from typing import Optional, Dict, Callable
from .helpers import get_loop
from .streams import BinanceSocketManager
from .threaded_stream import ThreadedApiManager
class DepthCache(object):
def __init__(self, symbol, conv_type: Callable = float):
"""Initialise the DepthCache
:param symbol: Symbol to create depth cache for
:type symbol: string
:param conv_type: Optional type to represent price, and amount, default is float.
:type conv_type: function.
"""
self.symbol = symbol
self._bids = {}
self._asks = {}
self.update_time = None
self.conv_type: Callable = conv_type
self._log = logging.getLogger(__name__)
def add_bid(self, bid):
"""Add a bid to the cache
:param bid:
:return:
"""
self._bids[bid[0]] = self.conv_type(bid[1])
if bid[1] == "0.00000000":
del self._bids[bid[0]]
def add_ask(self, ask):
"""Add an ask to the cache
:param ask:
:return:
"""
self._asks[ask[0]] = self.conv_type(ask[1])
if ask[1] == "0.00000000":
del self._asks[ask[0]]
def get_bids(self):
"""Get the current bids
:return: list of bids with price and quantity as conv_type
.. code-block:: python
[
[
0.0001946, # Price
45.0 # Quantity
],
[
0.00019459,
2384.0
],
[
0.00019158,
5219.0
],
[
0.00019157,
1180.0
],
[
0.00019082,
287.0
]
]
"""
return DepthCache.sort_depth(self._bids, reverse=True, conv_type=self.conv_type)
def get_asks(self):
"""Get the current asks
:return: list of asks with price and quantity as conv_type.
.. code-block:: python
[
[
0.0001955, # Price
57.0' # Quantity
],
[
0.00019699,
778.0
],
[
0.000197,
64.0
],
[
0.00019709,
1130.0
],
[
0.0001971,
385.0
]
]
"""
return DepthCache.sort_depth(self._asks, reverse=False, conv_type=self.conv_type)
@staticmethod
def sort_depth(vals, reverse=False, conv_type: Callable = float):
"""Sort bids or asks by price
"""
if isinstance(vals, dict):
lst = [[conv_type(price), conv_type(quantity)] for price, quantity in vals.items()]
elif isinstance(vals, list):
lst = [[conv_type(price), conv_type(quantity)] for price, quantity in vals]
else:
raise ValueError(f'Unknown order book depth data type: {type(vals)}')
lst = sorted(lst, key=itemgetter(0), reverse=reverse)
return lst
class BaseDepthCacheManager:
DEFAULT_REFRESH = 60 * 30 # 30 minutes
TIMEOUT = 60
def __init__(self, client, symbol, loop=None, refresh_interval=None, bm=None, limit=10, conv_type=float):
"""Create a DepthCacheManager instance
:param client: Binance API client
:type client: binance.Client
:param loop:
:type loop:
:param symbol: Symbol to create depth cache for
:type symbol: string
:param refresh_interval: Optional number of seconds between cache refresh, use 0 or None to disable
:type refresh_interval: int
:param bm: Optional BinanceSocketManager
:type bm: BinanceSocketManager
:param limit: Optional number of orders to get from orderbook
:type limit: int
:param conv_type: Optional type to represent price, and amount, default is float.
:type conv_type: function.
"""
self._client = client
self._depth_cache = None
self._loop = loop or get_loop()
self._symbol = symbol
self._limit = limit
self._last_update_id = None
self._bm = bm or BinanceSocketManager(self._client)
self._refresh_interval = refresh_interval or self.DEFAULT_REFRESH
self._conn_key = None
self._conv_type = conv_type
self._log = logging.getLogger(__name__)
async def __aenter__(self):
await asyncio.gather(
self._init_cache(),
self._start_socket()
)
await self._socket.__aenter__()
return self
async def __aexit__(self, *args, **kwargs):
await self._socket.__aexit__(*args, **kwargs)
async def recv(self):
dc = None
while not dc:
try:
res = await asyncio.wait_for(self._socket.recv(), timeout=self.TIMEOUT)
except Exception as e:
self._log.warning(e)
else:
dc = await self._depth_event(res)
return dc
async def _init_cache(self):
"""Initialise the depth cache calling REST endpoint
:return:
"""
# initialise or clear depth cache
self._depth_cache = DepthCache(self._symbol, conv_type=self._conv_type)
# set a time to refresh the depth cache
if self._refresh_interval:
self._refresh_time = int(time.time()) + self._refresh_interval
async def _start_socket(self):
"""Start the depth cache socket
:return:
"""
self._socket = self._get_socket()
def _get_socket(self):
raise NotImplementedError
async def _depth_event(self, msg):
"""Handle a depth event
:param msg:
:return:
"""
if not msg:
return None
if 'e' in msg and msg['e'] == 'error':
# close the socket
await self.close()
# notify the user by returning a None value
return None
return await self._process_depth_message(msg)
async def _process_depth_message(self, msg):
"""Process a depth event message.
:param msg: Depth event message.
:return:
"""
# add any bid or ask values
self._apply_orders(msg)
# call the callback with the updated depth cache
res = self._depth_cache
# after processing event see if we need to refresh the depth cache
if self._refresh_interval and int(time.time()) > self._refresh_time:
await self._init_cache()
return res
def _apply_orders(self, msg):
assert self._depth_cache
for bid in msg.get('b', []) + msg.get('bids', []):
self._depth_cache.add_bid(bid)
for ask in msg.get('a', []) + msg.get('asks', []):
self._depth_cache.add_ask(ask)
# keeping update time
self._depth_cache.update_time = msg.get('E') or msg.get('lastUpdateId')
def get_depth_cache(self):
"""Get the current depth cache
:return: DepthCache object
"""
return self._depth_cache
async def close(self):
"""Close the open socket for this manager
:return:
"""
self._depth_cache = None
def get_symbol(self):
"""Get the symbol
:return: symbol
"""
return self._symbol
class DepthCacheManager(BaseDepthCacheManager):
def __init__(
self, client, symbol, loop=None, refresh_interval=None, bm=None, limit=500, conv_type=float, ws_interval=None
):
"""Initialise the DepthCacheManager
:param client: Binance API client
:type client: binance.Client
:param loop: asyncio loop
:param symbol: Symbol to create depth cache for
:type symbol: string
:param refresh_interval: Optional number of seconds between cache refresh, use 0 or None to disable
:type refresh_interval: int
:param limit: Optional number of orders to get from orderbook
:type limit: int
:param conv_type: Optional type to represent price, and amount, default is float.
:type conv_type: function.
:param ws_interval: Optional interval for updates on websocket, default None. If not set, updates happen every second. Must be 0, None (1s) or 100 (100ms).
:type ws_interval: int
"""
super().__init__(client, symbol, loop, refresh_interval, bm, limit, conv_type)
self._ws_interval = ws_interval
async def _init_cache(self):
"""Initialise the depth cache calling REST endpoint
:return:
"""
self._last_update_id = None
self._depth_message_buffer = []
res = await self._client.get_order_book(symbol=self._symbol, limit=self._limit)
# initialise or clear depth cache
await super()._init_cache()
# process bid and asks from the order book
self._apply_orders(res)
assert self._depth_cache
for bid in res['bids']:
self._depth_cache.add_bid(bid)
for ask in res['asks']:
self._depth_cache.add_ask(ask)
# set first update id
self._last_update_id = res['lastUpdateId']
# Apply any updates from the websocket
for msg in self._depth_message_buffer:
await self._process_depth_message(msg)
# clear the depth buffer
self._depth_message_buffer = []
async def _start_socket(self):
"""Start the depth cache socket
:return:
"""
if not getattr(self, '_depth_message_buffer', None):
self._depth_message_buffer = []
await super()._start_socket()
def _get_socket(self):
return self._bm.depth_socket(self._symbol, interval=self._ws_interval)
async def _process_depth_message(self, msg):
"""Process a depth event message.
:param msg: Depth event message.
:return:
"""
if self._last_update_id is None:
# Initial depth snapshot fetch not yet performed, buffer messages
self._depth_message_buffer.append(msg)
return
if msg['u'] <= self._last_update_id:
# ignore any updates before the initial update id
return
elif msg['U'] != self._last_update_id + 1:
# if not buffered check we get sequential updates
# otherwise init cache again
await self._init_cache()
# add any bid or ask values
self._apply_orders(msg)
# call the callback with the updated depth cache
res = self._depth_cache
self._last_update_id = msg['u']
# after processing event see if we need to refresh the depth cache
if self._refresh_interval and int(time.time()) > self._refresh_time:
await self._init_cache()
return res
class FuturesDepthCacheManager(BaseDepthCacheManager):
async def _process_depth_message(self, msg):
"""Process a depth event message.
:param msg: Depth event message.
:return:
"""
msg = msg.get('data')
return await super()._process_depth_message(msg)
def _apply_orders(self, msg):
assert self._depth_cache
self._depth_cache._bids = msg.get('b', [])
self._depth_cache._asks = msg.get('a', [])
# keeping update time
self._depth_cache.update_time = msg.get('E') or msg.get('lastUpdateId')
def _get_socket(self):
sock = self._bm.futures_depth_socket(self._symbol)
return sock
class OptionsDepthCacheManager(BaseDepthCacheManager):
def _get_socket(self):
return self._bm.options_depth_socket(self._symbol)
class ThreadedDepthCacheManager(ThreadedApiManager):
def __init__(
self, api_key: Optional[str] = None, api_secret: Optional[str] = None,
requests_params: Optional[Dict[str, str]] = None, tld: str = 'com',
testnet: bool = False
):
super().__init__(api_key, api_secret, requests_params, tld, testnet)
def _start_depth_cache(
self, dcm_class, callback: Callable, symbol: str,
refresh_interval=None, bm=None, limit=10, conv_type=float, **kwargs
) -> str:
while not self._client:
time.sleep(0.01)
dcm = dcm_class(
client=self._client,
symbol=symbol,
loop=self._loop,
refresh_interval=refresh_interval,
bm=bm,
limit=limit,
conv_type=conv_type,
**kwargs
)
path = symbol.lower() + '@depth' + str(limit)
self._socket_running[path] = True
self._loop.call_soon(asyncio.create_task, self.start_listener(dcm, path, callback))
return path
def start_depth_cache(
self, callback: Callable, symbol: str, refresh_interval=None, bm=None, limit=10, conv_type=float, ws_interval=0
) -> str:
return self._start_depth_cache(
dcm_class=DepthCacheManager,
callback=callback,
symbol=symbol,
refresh_interval=refresh_interval,
bm=bm,
limit=limit,
conv_type=conv_type,
ws_interval=ws_interval
)
def start_futures_depth_socket(
self, callback: Callable, symbol: str, refresh_interval=None, bm=None, limit=10, conv_type=float
) -> str:
return self._start_depth_cache(
dcm_class=FuturesDepthCacheManager,
callback=callback,
symbol=symbol,
refresh_interval=refresh_interval,
bm=bm,
limit=limit,
conv_type=conv_type
)
def start_options_depth_socket(
self, callback: Callable, symbol: str, refresh_interval=None, bm=None, limit=10, conv_type=float
) -> str:
return self._start_depth_cache(
dcm_class=OptionsDepthCacheManager,
callback=callback,
symbol=symbol,
refresh_interval=refresh_interval,
bm=bm,
limit=limit,
conv_type=conv_type
)