@@ -137,7 +137,7 @@ def __init__(self, client, symbol, callback=None, refresh_interval=_default_refr
137137 self ._client = client
138138 self ._symbol = symbol
139139 self ._callback = callback
140- self ._first_update_id = None
140+ self ._last_update_id = None
141141 self ._depth_message_buffer = []
142142 self ._bm = None
143143 self ._depth_cache = DepthCache (self ._symbol )
@@ -151,7 +151,7 @@ def _init_cache(self):
151151
152152 :return:
153153 """
154- self ._first_update_id = None
154+ self ._last_update_id = None
155155 self ._depth_message_buffer = []
156156
157157 res = self ._client .get_order_book (symbol = self ._symbol , limit = 500 )
@@ -163,15 +163,15 @@ def _init_cache(self):
163163 self ._depth_cache .add_ask (ask )
164164
165165 # set first update id
166- self ._first_update_id = res ['lastUpdateId' ]
166+ self ._last_update_id = res ['lastUpdateId' ]
167167
168168 # set a time to refresh the depth cache
169169 if self ._refresh_interval :
170170 self ._refresh_time = int (time .time ()) + self ._refresh_interval
171171
172172 # Apply any updates from the websocket
173173 for msg in self ._depth_message_buffer :
174- self ._process_depth_message (msg )
174+ self ._process_depth_message (msg , buffer = True )
175175
176176 # clear the depth buffer
177177 del self ._depth_message_buffer
@@ -199,22 +199,27 @@ def _depth_event(self, msg):
199199
200200 """
201201
202- if self ._first_update_id is None :
202+ if self ._last_update_id is None :
203203 # Initial depth snapshot fetch not yet performed, buffer messages
204204 self ._depth_message_buffer .append (msg )
205205 else :
206206 self ._process_depth_message (msg )
207207
208- def _process_depth_message (self , msg ):
208+ def _process_depth_message (self , msg , buffer = False ):
209209 """Process a depth event message.
210210
211211 :param msg: Depth event message.
212212 :return:
213213
214214 """
215- # ignore any updates before the initial update id
216- if msg ['u' ] <= self ._first_update_id :
215+
216+ if buffer and msg ['u' ] <= self ._last_update_id :
217+ # ignore any updates before the initial update id
217218 return
219+ elif msg ['U' ] != self ._last_update_id + 1 :
220+ # if not buffered check we get sequential updates
221+ # otherwise init cache again
222+ self ._init_cache ()
218223
219224 # add any bid or ask values
220225 for bid in msg ['b' ]:
@@ -226,6 +231,8 @@ def _process_depth_message(self, msg):
226231 if self ._callback :
227232 self ._callback (self ._depth_cache )
228233
234+ self ._last_update_id = msg ['u' ]
235+
229236 # after processing event see if we need to refresh the depth cache
230237 if self ._refresh_interval and int (time .time ()) > self ._refresh_time :
231238 self ._init_cache ()
0 commit comments