from binance.websocket.spot.websocket_stream import SpotWebsocketStreamClient
from websocket._exceptions import WebSocketTimeoutException
import threading
import traceback
mutex = threading.Lock()
class Bot:
def __init__(self):
self.ws = SpotWebsocketStreamClient(
'wss://testnet.binance.vision/ws',
on_message=self.message_handler
)
self.websocket_reconnect = True
self.count = 0
def message_handler(self, _, payload):
with mutex:
try:
self.count += 1
print(self.count)
if self.count > 10:
self.count = 0
raise WebSocketTimeoutException
except WebSocketTimeoutException as e:
print(traceback.format_exc(chain=False))
raise
def load_websocket(self):
self.ws.book_ticker('BTCUSDT')
def run(self):
while True:
try:
if self.websocket_reconnect:
self.load_websocket()
self.websocket_reconnect = False
except WebSocketTimeoutException as e:
print('Enter')
print(traceback.format_exc_info(chain=False))
self.ws.stop()
print('---------- RESTARTING WEBSOCKET ----------')
self.websocket_reconnect = True
if __name__ == '__main__':
Bot().run()
The explanation for this code is, i want to raise a WebSocketTimeoutException
exception when self.count > 10
while i am catching it in the run
method, the thing is that it doesn’t get caught there, and i trying to deal with the websocket._exceptions.WebSocketTimeoutException: Connection timed out
that is raised when binance closes the connection. What am i missing?