Websocket hangs intermittently
Hello,
I have a multiplex depth socket open for ~36 trading pairs, I have been experiencing intermittent hangs in the connection. I am not receiving any error messages from the websocket, the connection just seems to hang. I've tried running the websocket locally, on AWS, and on a Linode VPS - this issue is experienced on all of them, quite erratically.
I have a feeling this may be an issue on Binance's end; however, I would be interested in knowing if anyone else is experiencing a similar issue.
armh
Over the past ~36 hours I've either gotten 'max reconnect retries reached' or the same issue you're having. I agree that it seems to be something on Binance's end but I haven't found anyone else having this issue.
I have seen hangs anywhere from 1.5 - 10 seconds. I'm not sure how to best troubleshoot this issue, any suggestions?
@opensourcechris
I have a loop setup in my script that detects time drift between the last websocket update and the current time. If the drift becomes large, the socket is closed and reopened.
Hi @armehanh, I'm doing the exact same thing as you do when listening to several orderbook websockets: update the last update time & whenever the time drift becomes larger it will be closed and reopened. However, after many times of reopening, the connection is still unstable and it always cannot sync well with current time and I'm expecting a time drift below 3 seconds at least.
Have you solved the problem eventually? I suspect it's either Binance server issue or network speed (I'm using Azure)
Let me know we can discuss further in details. Thanks!
Hi @i3wangyi, I have not solved the problem completely but here is an approach to my solution:
In my trading script, I compared the current timestamp to the timestamp of the last updated orderbooks from the websocket. If the time drift is large (let's say 15 seconds), I don't trade, and I reinitialize the connection.
Hi @armehanh, It's what I'm doing right now. I found the problem is it's restarting quite too often and I need to wait so many restart until I could trade! Often you know you will lose the best trade opportunity by waiting the websocket update.
Here's my several approaches I'm trying to attempt:
- Have you tried other approaches connecting to websocket endpoint, like different libraries.
- Replace the running machine with a better network environment, at my home e.g 250Mbps
- Forget about websocket and just grab orderbook use normal http request API. (It sometimes has huge latency)
Do you have better ideas?
Also you know Binance has 2 different ways of getting websockets: One is to only get top 10 ask/bid books; The other one is to maintain the entire ordebook locally. They listen to different endpoints. Have you ever noticed the performance difference between them? Which one is more stable? I'm using the second approach but it's not stable at all IMO.
@i3wangyi, I am using the second approach, with the websocket library that is used in this package without too many stability issues. Perhaps you can send me some of your code and I can take a look?
OrderBookState = namedtuple('OrderBookState', ['orderbook', 'timestamp', 'is_snapshot'])
def _on_message(self, msg):
if 'e' in msg and msg['e'] == 'error':
LOGGER.error("Websocket error: " + str(msg['m']))
return
usd_pair = msg['stream'].split('@')[0].upper()
if usd_pair not in self.order_book_states:
order_book = self._get_orderbook_snapshot(usd_pair)
LOGGER.info("[Subscription][{}]: Init Order Book snapshot received.".format(usd_pair))
self.order_book_states[usd_pair] = OrderBookState(order_book, timestamp=time.time(), is_snapshot=True)
is_snapshot = self.order_book_states[usd_pair].is_snapshot
order_book = self.order_book_states[usd_pair].orderbook
last_update_id = order_book.get_update_id()
payload = msg['data']
if (is_snapshot and payload['u'] <= last_update_id) or payload['e'] != 'depthUpdate':
return
# https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md
# The first processed should have U <= lastUpdateId+1 AND u >= lastUpdateId+1
# While listening to the stream, each new event's U should be equal to the previous event's u+1
if (is_snapshot and payload['U'] <= last_update_id + 1 and payload['u'] >= last_update_id + 1) or (
payload['U'] == last_update_id + 1):
for bid in payload['b']:
price = Decimal(bid[0])
quantity = Decimal(bid[1])
if quantity == 0:
order_book.delete_bid_order(price)
else:
order_book.set_bid_order(price=price, quantity=quantity)
for ask in payload['a']:
price = Decimal(ask[0])
quantity = Decimal(ask[1])
if quantity == 0:
order_book.delete_ask_order(price)
else:
order_book.set_ask_order(price=price, quantity=quantity)
order_book.set_update_id(payload['u'])
self.order_book_states[usd_pair] = OrderBookState(order_book, is_snapshot=False, timestamp=time.time())
def start_feed(self):
streams = []
for currency in self.currency_list:
usd_pair = self.supported()[(currency, Currency.USD)]
if usd_pair is not None:
stream = usd_pair.lower() + "@depth"
streams.append(stream)
self.order_book_states[usd_pair] = OrderBookState(self._get_orderbook_snapshot(usd_pair), timestamp=time.time(), is_snapshot=True)
LOGGER.info("[Subscription][{}]: Init Order Book snapshot received.".format(usd_pair))
self.bm = BinanceSocketManager(self.client)
self.bm.start_multiplex_socket(streams, self._on_message)
self.bm.start()
def close_feed(self):
self.bm.close()
def get_current_orderbook(self, currency):
if currency in self.cached_orderbook:
return self.cached_orderbook[currency]
if (currency, Currency.USD) not in self.supported():
return
usd_pair = self.supported()[(currency, Currency.USD)]
order_book_state = copy(self.order_book_states[usd_pair])
time_delay = time.time() - order_book_state.timestamp
if time_delay > 3:
LOGGER.warning("The {} order book is out of sync for {} second(s)".format(currency, time_delay))
return
return order_book_state.orderbook
def reconnect(self):
self.close_feed()
self.start_feed()
Here's my implementation if you don't mind reviewing, just ignore several self instance properties.
Basically websocket is running in another thread, main thread will call get_current_orderbook method, if None is returned, then reconnect action will be taken.
@i3wangyi Should main thread call get_current_orderbook method periodically (say 1 second) to see if the current timestamp has a big difference with the last timestamp? Thanks.
class GetMsg(): def init (self): self.api_key = '' self.api_secret = ''
#websocket数据处理
def process_message(self,msg):
if 'e' in msg and msg['e'] == 'error':
logger.info(" Disconnect2!!")
self.binance_start()
else:
pass
#do something
#开始websocket
def binance_start(self):
try:
self.client = Client(self.api_key,self.api_secret)
self.bm = BinanceSocketManager(self.client)
self.conn_key = self.bm.start_user_socket(self.process_message)
self.bm.start()
logger.info( " Establish connection!!")
except:
logger.info( " Disconnect1!!")
time.sleep(20)
`self.binance_start()```
Has anyone solved this issue?
Set a custom timeout for the websocket connections
Example
# set a timeout of 60 seconds
bm = BinanceSocketManager(client, user_timeout=60)