Skip to content

Commit 44dce94

Browse files
committed
Add graceful shutdown logic for WebSocket
Signed-off-by: JmPotato <[email protected]>
1 parent 2e7abba commit 44dce94

File tree

2 files changed

+13
-2
lines changed

2 files changed

+13
-2
lines changed

hyperliquid/info.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -526,3 +526,8 @@ def unsubscribe(self, subscription: Subscription, subscription_id: int) -> bool:
526526

527527
def name_to_asset(self, name: str) -> int:
528528
return self.coin_to_asset[self.name_to_coin[name]]
529+
530+
def close(self):
531+
if not hasattr(self, "ws_manager") or self.ws_manager is None:
532+
return
533+
self.ws_manager.stop()

hyperliquid/websocket_manager.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -71,14 +71,15 @@ def __init__(self, base_url):
7171
self.ping_sender = threading.Thread(target=self.send_ping)
7272

7373
def run(self):
74-
self.ping_sender.start()
7574
self.ws.run_forever()
75+
self.ping_sender.start()
7676

7777
def send_ping(self):
78-
while True:
78+
while self.ws.run_forever:
7979
time.sleep(50)
8080
logging.debug("Websocket sending ping")
8181
self.ws.send(json.dumps({"method": "ping"}))
82+
logging.debug("Websocket ping sender stopped")
8283

8384
def on_message(self, _ws, message):
8485
if message == "Websocket connection established.":
@@ -136,3 +137,8 @@ def unsubscribe(self, subscription: Subscription, subscription_id: int) -> bool:
136137
self.ws.send(json.dumps({"method": "unsubscribe", "subscription": subscription}))
137138
self.active_subscriptions[identifier] = new_active_subscriptions
138139
return len(active_subscriptions) != len(new_active_subscriptions)
140+
141+
def stop(self):
142+
if not self.ws.keep_running:
143+
return
144+
self.ws.close()

0 commit comments

Comments
 (0)