sammchardy / python-binance

Binance Exchange API python implementation for automated trading
https://python-binance.readthedocs.io/en/latest/
MIT License
5.96k stars 2.19k forks source link

Adding disconnect function to webSockets #1224

Open yoavweber opened 2 years ago

yoavweber commented 2 years ago

Describe the bug Currently, there is no option to disconnect from a websocket connection.

Expected behavior Add a function a disconnect function

Environment (please complete the following information):

Logs or Additional context To close the connection, I am using the _kill_read_loop . I am also happy to contribute if this would be approved as a bug/feature request

AlessandroRuggiero commented 2 years ago

Are you using the ThreadedWebsocketManager or the BinanceSocketManager?

If you are using the ThreadedWebsocketManager the disconnect function is not on the socket itself but on the ThreadedWebsocketManager, to close a socket just call

twm.stop_socket(stream_name)

if you are using the BinanceSocketManager the socket will be closed automatically once the code exits the context manager, to force disconnect the socket you could call

socket.__aexit__()

but it is a bad idea and should generally not be done explicitly

imansyaefulloh commented 6 months ago

Hi @AlessandroRuggiero, in case of error happen in websocket

i caught it like this

if msg['e'] == 'error':
        # close and restart the socket
        self.twm.stop_socket(self.kline_socket)
        self.twm.stop()

        time.sleep(5)
        self.kline_socket = self.twm.start_kline_futures_socket(callback = self.stream_candles,
                                            symbol = self.symbol, interval = self.timeframe)
        self.twm.join()

error message that i got from logs

@binance.streams [ERROR]: Max reconnections 5 reached: @root [INFO]: {'e': 'error', 'm': 'Max reconnect retries reached'}

but i got

RuntimeError: cannot join current thread

any solution to solve this issue?