Skip to content

Commit

Permalink
Address the comments
Browse files Browse the repository at this point in the history
Signed-off-by: JmPotato <[email protected]>
  • Loading branch information
JmPotato committed Dec 8, 2024
1 parent 44dce94 commit 88c71f2
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 12 deletions.
13 changes: 8 additions & 5 deletions hyperliquid/info.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ def __init__(
if not skip_ws:
self.ws_manager = WebsocketManager(self.base_url)
self.ws_manager.start()
else:
self.ws_manager = None
if meta is None:
meta = self.meta()

Expand All @@ -43,6 +45,12 @@ def __init__(
if name not in self.name_to_coin:
self.name_to_coin[name] = spot_info["name"]

def disconnect_websocket(self):
if self.ws_manager is None:
raise RuntimeError("Cannot call disconnect_websocket since skip_ws was used")
else:
self.ws_manager.stop()

def user_state(self, address: str) -> Any:
"""Retrieve trading details about a user.
Expand Down Expand Up @@ -526,8 +534,3 @@ 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()
17 changes: 10 additions & 7 deletions hyperliquid/websocket_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,18 +69,26 @@ def __init__(self, base_url):
ws_url = "ws" + base_url[len("http") :] + "/ws"
self.ws = websocket.WebSocketApp(ws_url, on_message=self.on_message, on_open=self.on_open)
self.ping_sender = threading.Thread(target=self.send_ping)
self.stop_event = threading.Event()

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

def send_ping(self):
while self.ws.run_forever:
time.sleep(50)
while not self.stop_event.wait(50):
if not self.ws.keep_running:
break
logging.debug("Websocket sending ping")
self.ws.send(json.dumps({"method": "ping"}))
logging.debug("Websocket ping sender stopped")

def stop(self):
self.stop_event.set()
self.ws.close()
if self.ping_sender.is_alive():
self.ping_sender.join()

def on_message(self, _ws, message):
if message == "Websocket connection established.":
logging.debug(message)
Expand Down Expand Up @@ -137,8 +145,3 @@ 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 88c71f2

Please sign in to comment.