I am using this library (https://github.com/sammchardy/python-binance) to download data from binance. I get the following error after running data collection script for 3 days or so.
INFO:root:{"e": "error", "type": "ConnectionClosedOK", "m": "received 1001 (going away); then sent 1001 (going away)"}
I want to reconnect the websocket without rerunning the file with code for data collection. Can anyone help?
My code is shown here:
import time
import logging
from binance import ThreadedWebsocketManager, BinanceSocketManager
import json
api_key = "api_key"
api_secret = "api_secret"
def main():
symbol = 'DOGEUSDT'
logging.basicConfig(filename='example_multiplex_{}_{}.log'.format(symbol, int(time.time())),level=logging.DEBUG)
twm = ThreadedWebsocketManager(api_key=api_key, api_secret=api_secret)
# start is required to initialise its internal loop
twm.start()
def handle_socket_message(msg):
# print(f"message type: {msg['e']}")
print(msg)
logging.info(json.dumps(msg))
twm.start_depth_socket(callback=handle_socket_message, depth = 20, symbol=symbol)
twm.join()
if __name__ == "__main__":
main()
1 Answer 1
ConnectionClosedOK with code 1001 (going away) is a normal close of the WebSocket, not a bug in your code. Binance explicitly states that a single WebSocket connection is only valid for 24 hours, so after running for a long time (days) you should expect the server to disconnect you and you must implement reconnection logic on the client side.