Skip to content

Commit

Permalink
Add graceful shutdown logic for WebSocket
Browse files Browse the repository at this point in the history
Signed-off-by: JmPotato <[email protected]>
  • Loading branch information
JmPotato committed Dec 5, 2024
1 parent 239e5f1 commit c59c47c
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
5 changes: 5 additions & 0 deletions hyperliquid/info.py
Original file line number Diff line number Diff line change
Expand Up @@ -526,3 +526,8 @@ def unsubscribe(self, subscription: Subscription, subscription_id: int) -> bool:

def name_to_asset(self, name: str) -> int:
return self.coin_to_asset[self.name_to_coin[name]]

def close(self):
if not hasattr(self, "ws_manager") or self.ws_manager is None:
return
self.ws_manager.stop()
10 changes: 8 additions & 2 deletions hyperliquid/websocket_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,14 +71,15 @@ def __init__(self, base_url):
self.ping_sender = threading.Thread(target=self.send_ping)

def run(self):
self.ping_sender.start()
self.ws.run_forever()
self.ping_sender.start()

def send_ping(self):
while True:
while self.ws.run_forever:
time.sleep(50)
logging.debug("Websocket sending ping")
self.ws.send(json.dumps({"method": "ping"}))
logging.debug("Websocket ping sender stopped")

def on_message(self, _ws, message):
if message == "Websocket connection established.":
Expand Down Expand Up @@ -136,3 +137,8 @@ def unsubscribe(self, subscription: Subscription, subscription_id: int) -> bool:
self.ws.send(json.dumps({"method": "unsubscribe", "subscription": subscription}))
self.active_subscriptions[identifier] = new_active_subscriptions
return len(active_subscriptions) != len(new_active_subscriptions)

def stop(self):
if not self.ws.keep_running:
return
self.ws.close()

0 comments on commit c59c47c

Please sign in to comment.