Perps-Terminal / backend /exchanges /hyperliquid.py
Naufal Arhab
perf(whale,db): add HL maker_wallet discovery, 2-tier scout DB gate & dirty-check, bounded RAM, and non-locking accuracy query
7088133
Raw History Blame Contribute Delete
15.5 kB
"""
Hyperliquid Info API client (Public read-only).
Docs: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint
Provides:
- On-chain DEX Funding Rate (converted to 8h equivalent)
- On-chain Open Interest & 24h Notional Volume
- Oracle price vs Mark price premium
"""
import asyncio
import logging
import time
from typing import Any
import httpx
from config import PROXY_URL
from engine.doh_resolver import enable_doh_bypass
from engine.symbol_resolver import get_symbol_variations
from exchanges.base import BaseExchange
enable_doh_bypass()
logger = logging.getLogger(__name__)
HYPERLIQUID_INFO_URL = "https://api.hyperliquid.xyz/info"
class HyperliquidClient(BaseExchange):
name = "hyperliquid"
def __init__(self) -> None:
client_kwargs = {
"timeout": 10.0,
"headers": {"Content-Type": "application/json", "Accept": "application/json"},
"verify": True,
}
if PROXY_URL:
client_kwargs["proxy"] = PROXY_URL
self._client = httpx.AsyncClient(**client_kwargs)
self._cache_time: float = 0
self._cached_universe: dict[str, dict] = {}
self._coin_lookup: dict[str, str] = {}
self._lock = asyncio.Lock()
self._oi_snapshots: dict[str, list[tuple[float, float]]] = {}
def _format_symbol(self, symbol: str) -> str:
"""Strip delimiters & quote currency (e.g. BTC/USDT, kPEPE-USDT -> BTC, kPEPE) preserving case."""
sym = str(symbol).replace("/", "").replace("-", "").replace("_", "").strip()
for q in ("USDT", "USDC", "USD", "BUSD", "EUR"):
if sym.upper().endswith(q) and len(sym) > len(q):
return sym[:-len(q)]
return sym
def resolve_coin(self, symbol: str) -> str | None:
"""Resolve symbol or multiplier variations to exact Hyperliquid coin name."""
if not self._cached_universe:
return None
# 1. Direct formatted
direct = self._format_symbol(symbol).upper()
if direct in self._coin_lookup:
return self._coin_lookup[direct]
# 2. Check candidate variations
for v in get_symbol_variations(symbol):
v_fmt = self._format_symbol(v).upper()
if v_fmt in self._coin_lookup:
return self._coin_lookup[v_fmt]
return None
async def _refresh_meta(self) -> None:
async with self._lock:
now = time.time()
# Cache for 15 seconds across all pairs
if now - self._cache_time < 15 and self._cached_universe:
return
try:
resp = await self._client.post(HYPERLIQUID_INFO_URL, json={"type": "metaAndAssetCtxs"})
resp.raise_for_status()
data = resp.json()
universe = data[0].get("universe", [])
ctxs = data[1] if len(data) > 1 else []
new_cache = {}
new_lookup = {}
for i, u in enumerate(universe):
if u.get("isDelisted"):
continue
coin = u.get("name")
if coin and i < len(ctxs):
new_cache[coin] = ctxs[i]
new_lookup[coin.upper()] = coin
self._cached_universe = new_cache
self._coin_lookup = new_lookup
self._cache_time = now
except Exception as exc:
logger.warning("[Hyperliquid] Meta fetch failed: %s", exc)
async def check_symbol_exists(self, symbol: str) -> bool:
await self._refresh_meta()
return self.resolve_coin(symbol) is not None
async def get_orderbook(self, symbol: str, depth: int = 20) -> dict[str, Any]:
"""
Fetch on-chain L2 orderbook from Hyperliquid CLOB DEX.
Returns:
{"bids": [[price, qty], ...], "asks": [[price, qty], ...]}
"""
await self._refresh_meta()
coin = self.resolve_coin(symbol)
if not coin:
return {"bids": [], "asks": []}
try:
resp = await self._client.post(
HYPERLIQUID_INFO_URL,
json={"type": "l2Book", "coin": coin},
)
resp.raise_for_status()
data = resp.json()
levels = data.get("levels", [])
if len(levels) < 2:
return {"bids": [], "asks": []}
raw_bids = levels[0]
raw_asks = levels[1]
bids = [[float(b["px"]), float(b["sz"])] for b in raw_bids[:depth] if "px" in b and "sz" in b]
asks = [[float(a["px"]), float(a["sz"])] for a in raw_asks[:depth] if "px" in a and "sz" in a]
return {"bids": bids, "asks": asks}
except Exception as exc:
logger.debug("[Hyperliquid] Error fetching orderbook for %s: %s", coin, exc)
return {"bids": [], "asks": []}
async def get_recent_trades(self, symbol: str, limit: int = 500) -> list[dict]:
"""
Fetch recent on-chain trades from Hyperliquid DEX including wallet addresses (`users`).
"""
await self._refresh_meta()
coin = self.resolve_coin(symbol)
if not coin:
return []
try:
resp = await self._client.post(
HYPERLIQUID_INFO_URL,
json={"type": "recentTrades", "coin": coin},
)
resp.raise_for_status()
data = resp.json()
if not isinstance(data, list):
return []
trades = []
for t in data:
try:
px = float(t.get("px", 0.0))
sz = float(t.get("sz", 0.0))
if px <= 0 or sz <= 0:
continue
side_str = str(t.get("side", "B")).upper()
# In Hyperliquid: 'B' = Bid/Buy aggressor (is_buyer_maker=False), 'A' = Ask/Sell aggressor (is_buyer_maker=True)
is_buyer_maker = side_str in ("A", "SELL", "S")
users = t.get("users")
taker_wallet = None
maker_wallet = None
if isinstance(users, list) and len(users) >= 2:
# Hyperliquid users tuple is [buyer, seller]:
# sell aggressor (is_buyer_maker=True) -> taker=users[1], maker=users[0]
# buy aggressor (is_buyer_maker=False) -> taker=users[0], maker=users[1]
raw_taker = users[1] if is_buyer_maker else users[0]
raw_maker = users[0] if is_buyer_maker else users[1]
if raw_taker:
taker_wallet = str(raw_taker)
if raw_maker:
maker_wallet = str(raw_maker)
trades.append({
"price": px,
"qty": sz,
"is_buyer_maker": is_buyer_maker,
"time": int(t.get("time", 0) or 0),
"venue": "hyperliquid",
"taker_wallet": taker_wallet,
"maker_wallet": maker_wallet,
})
except (ValueError, TypeError):
continue
trades.sort(key=lambda x: x["time"])
if limit > 0 and len(trades) > limit:
trades = trades[-limit:]
return trades
except Exception as exc:
logger.debug("[Hyperliquid] Error fetching recentTrades for %s: %s", coin, exc)
return []
async def get_market_data(self, symbol: str) -> dict[str, Any] | None:
"""
Fetch funding rate, open interest, mark price, and premium for symbol.
"""
await self._refresh_meta()
coin = self.resolve_coin(symbol)
if not coin:
return None
ctx = self._cached_universe.get(coin)
if not ctx:
return None
try:
# Hyperliquid provides 1-hour funding rate; standard CEX uses 8-hour
fr_1h = float(ctx.get("funding") or 0.0)
fr_8h = fr_1h * 8.0
# metaAndAssetCtxs.openInterest sums both long & short (double-sided); halve to 1x unilateral base OI
raw_oi = float(ctx.get("openInterest") or 0.0)
oi = raw_oi * 0.5
mark_px = float(ctx.get("markPx") or 0.0)
oracle_px = float(ctx.get("oraclePx") or 0.0)
day_ntl_vlm = float(ctx.get("dayNtlVlm") or 0.0)
prev_day_px = float(ctx.get("prevDayPx") or 0.0)
impact_pxs = ctx.get("impactPxs")
impact_spread_bps = 0.0
if isinstance(impact_pxs, list) and len(impact_pxs) >= 2 and mark_px > 0:
try:
bid_imp = float(impact_pxs[0])
ask_imp = float(impact_pxs[1])
if ask_imp >= bid_imp and bid_imp > 0:
impact_spread_bps = round(((ask_imp - bid_imp) / mark_px) * 10000.0, 4)
except (ValueError, TypeError):
pass
basis_pct = ((mark_px - oracle_px) / oracle_px * 100) if oracle_px else 0.0
oi_value = round(oi * mark_px, 2) if (oi > 0 and mark_px > 0) else (0.0 if oi == 0 else None)
oi_change_pct, oi_window_sec = BaseExchange.record_oi_change_with_meta(
self._oi_snapshots, coin, oi
)
return {
"coin": coin,
"funding_rate": round(fr_8h, 6),
"funding_rate_1h": round(fr_1h, 6),
"open_interest": oi,
"open_interest_value": oi_value,
"oi_change_pct": oi_change_pct,
"oi_horizon": "rolling",
"oi_window_sec": oi_window_sec,
"mark_price": mark_px,
"index_price": oracle_px,
"oracle_price": oracle_px,
"basis_pct": round(basis_pct, 6),
"day_notional_volume": round(day_ntl_vlm, 2),
"prev_day_px": prev_day_px,
"impact_spread_bps": impact_spread_bps,
}
except Exception as exc:
logger.warning("[Hyperliquid] Error parsing ctx for %s: %s", coin, exc)
return None
async def get_mark_price(self, symbol: str) -> dict[str, Any]:
md = await self.get_market_data(symbol)
if not md:
return {"mark_price": None, "index_price": None, "basis_pct": None}
return {
"mark_price": md["mark_price"],
"index_price": md["index_price"],
"basis_pct": md["basis_pct"],
}
async def get_funding_rate(self, symbol: str) -> dict[str, Any]:
md = await self.get_market_data(symbol)
if not md:
return {"funding_rate": None, "next_funding_time": None}
return {"funding_rate": md["funding_rate"], "next_funding_time": None}
async def get_open_interest(self, symbol: str) -> dict[str, Any]:
md = await self.get_market_data(symbol)
if not md:
return {"open_interest": 0.0, "open_interest_value": None, "oi_change_pct": None}
return {
"open_interest": md["open_interest"],
"open_interest_value": md["open_interest_value"],
"oi_change_pct": md["oi_change_pct"],
"oi_horizon": md["oi_horizon"],
"oi_window_sec": md["oi_window_sec"],
}
async def get_long_short_ratio(self, symbol: str, period: str = "1h") -> dict[str, Any]:
return {"long_ratio": None, "short_ratio": None, "source": "unavailable"}
async def get_ohlcv(self, symbol: str, timeframe: str = "15m", limit: int = 30) -> list[dict]:
"""Fetch historical OHLCV candle snapshots from Hyperliquid Info API."""
await self._refresh_meta()
coin = self.resolve_coin(symbol)
if not coin:
if self._cached_universe:
return []
raw_coin = self._format_symbol(symbol)
if not raw_coin:
return []
upper_coin = raw_coin.upper()
known_k = {
"KPEPE": "kPEPE",
"KBONK": "kBONK",
"KSHIB": "kSHIB",
"KFLOKI": "kFLOKI",
"KLUNC": "kLUNC",
"KDOGS": "kDOGS",
"KNEIRO": "kNEIRO",
}
if upper_coin in known_k:
coin = known_k[upper_coin]
elif upper_coin.startswith("1000") and len(upper_coin) > 4:
coin = f"k{upper_coin[4:]}"
elif raw_coin.startswith("k") and len(raw_coin) > 1 and raw_coin[1:].isupper():
coin = raw_coin
else:
coin = upper_coin
if not coin:
return []
interval_ms = {
"1m": 60_000,
"3m": 180_000,
"5m": 300_000,
"15m": 900_000,
"30m": 1_800_000,
"1h": 3_600_000,
"2h": 7_200_000,
"4h": 14_400_000,
"1d": 86_400_000,
}.get(timeframe, 900_000)
now_ms = int(time.time() * 1000)
start_time = now_ms - (limit + 5) * interval_ms
end_time = now_ms
payload = {
"type": "candleSnapshot",
"req": {
"coin": coin,
"interval": timeframe,
"startTime": start_time,
"endTime": end_time,
},
}
try:
resp = await self._client.post(HYPERLIQUID_INFO_URL, json=payload)
if resp.status_code != 200:
return []
data = resp.json()
if not isinstance(data, list):
return []
candles = []
for c in data:
try:
c_dict = {
"timestamp": int(c.get("t", c.get("timestamp", 0))),
"open": float(c.get("o", c.get("open", 0.0))),
"high": float(c.get("h", c.get("high", 0.0))),
"low": float(c.get("l", c.get("low", 0.0))),
"close": float(c.get("c", c.get("close", 0.0))),
"volume": float(c.get("v", c.get("volume", 0.0))),
}
candles.append(c_dict)
except (IndexError, ValueError, TypeError):
continue
candles.sort(key=lambda x: x["timestamp"])
if limit > 0:
candles = candles[-limit:]
return candles
except Exception as exc:
logger.debug("[Hyperliquid] OHLCV fetch error for %s (%s): %s", coin, timeframe, exc)
return []
async def get_clearinghouse_state(self, user: str) -> dict[str, Any]:
"""Fetch user clearinghouse state (marginSummary and assetPositions)."""
try:
resp = await self._client.post(
HYPERLIQUID_INFO_URL,
json={"type": "clearinghouseState", "user": user},
)
resp.raise_for_status()
return resp.json()
except Exception as exc:
logger.debug("[Hyperliquid] clearinghouseState failed for %s: %s", user, exc)
return {}
async def close(self) -> None:
await self._client.aclose()