bybit-exchange / pybit

Official Python3 API connector for Bybit's HTTP and WebSockets APIs.
Other
340 stars 113 forks source link

Question: How do I properly catch websocket streaming errors? #223

Closed programmdesign closed 1 week ago

programmdesign commented 2 weeks ago

Hi. At times, the websocket client disconnects (e.g., due to networking issues). I get for instance the following error message:

WebSocket Unified V5 (Auth) (wss://stream-testnet.bybit.com/v5/public/linear) encountered error: ping/pong timed out.
WebSocket Unified V5 (Auth) (wss://stream-testnet.bybit.com/v5/private) encountered error: ping/pong timed out.

How do I catch this error message? I already have try/except-blocks around my functions -- even the main function. however, this error seems not to be caught. I'd like to re-initialize my trading setup, in case such an error occurs.

Any hint how I can properly catch and handle such errors is highly appreciated. Couldn't find anything in the docs nor by looking at the WebSocket Manager implementations.

Thanks!

radomir9720 commented 1 week ago
from pybit.unified_trading import WebSocket

class MyWebSocket(WebSocket):
    def _on_error(self, error):
        # Here you can do whatever you want with the error

        # Also you can call the super method to keep the default behaviour
        # (error handling, reconnection, etc.)
        return super()._on_error(error)

Here you can find the default implementation of _on_error(), and by calling super()._on_error(error) this code will be also executed. So you can either implement your custom logic, or you can add your logic to the default behaviour(by calling super method).

And then you need to initialize the websocket using the MyWebSocket class instead of WebSocket.