Files
hyper/live_market_utils.py
2025-10-21 15:09:53 +02:00

50 lines
1.8 KiB
Python

import logging
import json
import time
from hyperliquid.info import Info
from hyperliquid.utils import constants
from logging_utils import setup_logging
def on_message(message, shared_prices_dict):
"""
Callback function to process incoming 'allMids' messages and update the
shared memory dictionary directly.
"""
try:
if message.get("channel") == "allMids":
new_prices = message.get("data", {}).get("mids", {})
# Update the shared dictionary with the new price data
shared_prices_dict.update(new_prices)
except Exception as e:
# It's important to log errors inside the process
logging.error(f"Error in WebSocket on_message: {e}")
def start_live_feed(shared_prices_dict, log_level='off'):
"""
Main function for the WebSocket process. It takes a shared dictionary
and continuously feeds it with live market data.
"""
setup_logging(log_level, 'LiveMarketFeed')
# The Info object manages the WebSocket connection.
info = Info(constants.MAINNET_API_URL, skip_ws=False)
# We need to wrap the callback in a lambda to pass our shared dictionary
callback = lambda msg: on_message(msg, shared_prices_dict)
# Subscribe to the allMids channel
subscription = {"type": "allMids"}
info.subscribe(subscription, callback)
logging.info("Subscribed to 'allMids' for live mark prices.")
logging.info("Starting live price feed process. Press Ctrl+C in main app to stop.")
try:
# The background thread in the SDK handles messages. This loop just keeps the process alive.
while True:
time.sleep(1)
except KeyboardInterrupt:
logging.info("Stopping WebSocket listener...")
info.ws_manager.stop()
logging.info("Listener stopped.")