22
33import zlib
44from collections import OrderedDict
5- from typing import Dict , List
5+ from typing import Any , Dict , List , cast
66
77from bfxapi import Client
88from bfxapi .types import TradingPairRawBook
@@ -15,8 +15,6 @@ def __init__(self, symbols: List[str]):
1515 symbol : {"bids" : OrderedDict (), "asks" : OrderedDict ()} for symbol in symbols
1616 }
1717
18- self .cooldown : Dict [str , bool ] = {symbol : False for symbol in symbols }
19-
2018 def update (self , symbol : str , data : TradingPairRawBook ) -> None :
2119 order_id , price , amount = data .order_id , data .price , data .amount
2220
@@ -66,6 +64,15 @@ def verify(self, symbol: str, checksum: int) -> bool:
6664
6765 return crc32 == checksum
6866
67+ def is_verifiable (self , symbol : str ) -> bool :
68+ return (
69+ len (self .__raw_order_book [symbol ]["bids" ]) >= 25
70+ and len (self .__raw_order_book [symbol ]["asks" ]) >= 25
71+ )
72+
73+ def clear (self , symbol : str ) -> None :
74+ self .__raw_order_book [symbol ] = {"bids" : OrderedDict (), "asks" : OrderedDict ()}
75+
6976
7077SYMBOLS = ["tLTCBTC" , "tETHUSD" , "tETHBTC" ]
7178
@@ -100,17 +107,20 @@ def on_t_raw_book_update(subscription: Book, data: TradingPairRawBook):
100107async def on_checksum (subscription : Book , value : int ):
101108 symbol = subscription ["symbol" ]
102109
103- if raw_order_book .verify (symbol , value ):
104- raw_order_book .cooldown [symbol ] = False
105- elif not raw_order_book .cooldown [symbol ]:
106- print (
107- "Mismatch between local and remote checksums: "
108- f"restarting book for symbol <{ symbol } >..."
109- )
110+ if raw_order_book .is_verifiable (symbol ):
111+ if not raw_order_book .verify (symbol , value ):
112+ print (
113+ "Mismatch between local and remote checksums: "
114+ f"restarting book for symbol <{ symbol } >..."
115+ )
116+
117+ _subscription = cast (Dict [str , Any ], subscription .copy ())
118+
119+ await bfx .wss .unsubscribe (sub_id = _subscription .pop ("sub_id" ))
110120
111- await bfx .wss .resubscribe ( sub_id = subscription [ "sub_id" ] )
121+ await bfx .wss .subscribe ( ** _subscription )
112122
113- raw_order_book .cooldown [ symbol ] = True
123+ raw_order_book .clear ( symbol )
114124
115125
116126bfx .wss .run ()
0 commit comments