File size: 15,526 Bytes
712f4ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
05163ad
712f4ea
d87b18a
d6219d0
712f4ea
 
 
 
 
 
 
 
48f60d7
712f4ea
 
 
05163ad
 
 
740fcec
05163ad
 
 
 
712f4ea
 
d87b18a
712f4ea
d6219d0
712f4ea
 
80df99b
 
d87b18a
80df99b
d87b18a
712f4ea
 
d87b18a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
712f4ea
05163ad
 
 
 
 
 
 
 
 
 
 
 
 
 
d87b18a
05163ad
48f60d7
 
05163ad
 
 
d87b18a
05163ad
 
d87b18a
05163ad
 
 
712f4ea
 
 
d87b18a
712f4ea
48f60d7
b38dd6b
 
 
 
 
 
 
 
48f60d7
b38dd6b
 
 
 
 
 
 
 
 
48f60d7
b38dd6b
 
 
 
 
 
 
 
 
 
48f60d7
b38dd6b
80df99b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7088133
80df99b
7088133
 
 
 
 
 
 
 
 
80df99b
 
 
 
 
 
 
7088133
80df99b
 
 
 
 
 
 
 
 
 
 
712f4ea
 
 
 
 
d87b18a
 
 
712f4ea
 
 
 
 
 
48f60d7
712f4ea
 
48f60d7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
712f4ea
 
48f60d7
712f4ea
d6219d0
 
 
 
712f4ea
 
 
 
 
48f60d7
d6219d0
 
 
712f4ea
48f60d7
712f4ea
 
 
48f60d7
 
712f4ea
 
 
 
 
48f60d7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d6219d0
 
 
 
 
65ccdcd
 
 
 
 
48f60d7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65ccdcd
48f60d7
d6219d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48f60d7
 
 
 
 
 
 
 
 
 
 
 
 
712f4ea
05163ad
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
"""
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()