bybit-exchange / pybit

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

Exception handling for resync system time and api check #226

Closed tengocj closed 1 week ago

tengocj commented 1 week ago

image_2024-06-19_13-54-20

Hello ser, I was wondering if you can please change the exception handling for the resync system time and api key error so one can just use normal try except block-handling for opening a new websocket connection. Right now when I am trying to except this Exception nothing is happening rather it's always getting logged and instead of modifying the library i'd be very happy if you can change that in the next pr. ty

radomir9720 commented 1 week ago

Hi. You can solve this issue pretty easy without any changes in the package. Moreover, you have two options:

  1. Provide custom message handling callback. For that you need to pass callback_function parameter to WebSocket like so:
ws = WebSocket(
    channel_type="private",
    api_key='api_key',
    api_secret='api_secret',
    callback_function=callback_function,
)
  1. Easier one - inherit from the WebSocket, and override the method, that handles the auth message:
from pybit.unified_trading import WebSocket
from pybit._websocket_stream import logger

class MyWebSocket(WebSocket):
    def _process_auth_message(self, message):
        if message.get("success") is True:
            logger.debug(f"Authorization for {self.ws_name} successful.")
            self.auth = True
        # If we get unsuccessful auth, notify user.
        elif message.get("success") is False or message.get("type") == "error":
            # Here replace exception raising with your own error handling(reconnection).
            raise Exception(
                f"Authorization for {self.ws_name} failed. Please check your "
                f"API keys and resync your system time. Raw error: {message}"
            )

ws = MyWebSocket(
    channel_type="private",
    api_key='api_key',
    api_secret='api_secret',
)

The second way is easier because you override only the auth message handling. For the first option you'll have to handle all the messages(you still can use the package methods, and replace only the auth message handling part, anyways, it requires to write more code than the 2 option).

P.S. Keep in mind that the code above is not tested.

tengocj commented 1 week ago

Appreciate that, didn't have time to go through full docs. Thank you very much for the fast reply!