python-binance icon indicating copy to clipboard operation
python-binance copied to clipboard

Adding disconnect function to webSockets

Open yoavweber opened this issue 3 years ago • 2 comments

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):

  • Python version: 3.8
  • Virtual Env: [e.g. virtualenv, conda]
  • OS: Ubuntu
  • python-binance version: 1.0.14

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

yoavweber avatar Jul 27 '22 14:07 yoavweber

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

AlessandroRuggiero avatar Aug 22 '22 11:08 AlessandroRuggiero

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?

imansyaefulloh avatar Feb 28 '24 06:02 imansyaefulloh