hip3pulse 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
hip3pulse/__init__.py
ADDED
|
@@ -0,0 +1,780 @@
|
|
|
1
|
+
"""HIP3Pulse v0.2.0 — Zero-dependency Python SDK for Hyperliquid HIP-3 dislocation & hedging intelligence."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import math
|
|
7
|
+
import time
|
|
8
|
+
import urllib.request
|
|
9
|
+
from datetime import datetime, timedelta, timezone
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
try:
|
|
13
|
+
from zoneinfo import ZoneInfo
|
|
14
|
+
except ImportError: # pragma: no cover
|
|
15
|
+
ZoneInfo = None # type: ignore
|
|
16
|
+
|
|
17
|
+
__version__ = "0.2.0"
|
|
18
|
+
|
|
19
|
+
HL_API = "https://api.hyperliquid.xyz/info"
|
|
20
|
+
SOLANA_RPC = "https://api.mainnet-beta.solana.com"
|
|
21
|
+
|
|
22
|
+
NASDAQ_HEADERS = {
|
|
23
|
+
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36",
|
|
24
|
+
"Accept": "application/json, text/plain, */*",
|
|
25
|
+
"Origin": "https://www.nasdaq.com",
|
|
26
|
+
"Referer": "https://www.nasdaq.com/",
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
XSTOCKS_MINTS: dict[str, dict[str, str]] = {
|
|
30
|
+
"NVDAx": {"hl": "xyz:NVDA", "mint": "Xsc9qvGR1efVDFGLrVsmkzv3qi45LTBjeUKSPmx9qEh"},
|
|
31
|
+
"TSLAx": {"hl": "xyz:TSLA", "mint": "XsDoVfqeBukxuZHWhdvWHBhgEHjGNst4MLodqsJHzoB"},
|
|
32
|
+
"GOOGLx": {"hl": "xyz:GOOGL", "mint": "XsCPL9dNWBMvFtTmwcCA5v3xWPSMEBCszbQdiLLq6aN"},
|
|
33
|
+
"CRCLx": {"hl": "xyz:CRCL", "mint": "XsueG8BtpquVJX9LVLLEGuViXUungE6WmK5YZ3p3bd1"},
|
|
34
|
+
"METAx": {"hl": "xyz:META", "mint": "Xsa62P5mvPszXL1krVUnU5ar38bBSVcWAB6fmPCo5Zu"},
|
|
35
|
+
"AAPLx": {"hl": "xyz:AAPL", "mint": "XsbEhLAtcf6HdfpFZ5xEMdqW8nfAvcsP5bdudRLJzJp"},
|
|
36
|
+
"MSFTx": {"hl": "xyz:MSFT", "mint": "XspzcW1PRtgf6Wj92HCiZdjzKCyFekVD8P5Ueh3dRMX"},
|
|
37
|
+
"AMZNx": {"hl": "xyz:AMZN", "mint": "Xs3eBt7uRfJX8QUs4suhyU8p2M6DoUDrJyWBa8LLZsg"},
|
|
38
|
+
"COINx": {"hl": "xyz:COIN", "mint": "Xs7ZdzSHLU9ftNJsii5fCeJhoRWSC32SQGzGQtePxNu"},
|
|
39
|
+
"MSTRx": {"hl": "xyz:MSTR", "mint": "XsP7xzNPvEHS1m6qfanPUGjNmdnmsLKEoNAnHjdxxyZ"},
|
|
40
|
+
"HOODx": {"hl": "xyz:HOOD", "mint": "XsvNBAYkrDRNhA7wPHQfX3ZUXZyZLdnCQDfHZ56bzpg"},
|
|
41
|
+
"PLTRx": {"hl": "xyz:PLTR", "mint": "XsoBhf2ufR8fTyNSjqfU71DYGaE6Z3SUGAidpzriAA4"},
|
|
42
|
+
"AVGOx": {"hl": "xyz:AVGO", "mint": "XsgSaSvNSqLTtFuyWPBhK9196Xb9Bbdyjj4fH3cPJGo"},
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
PRE_IPO_SYMBOLS = {
|
|
46
|
+
"OURA", "PAPER", "ANTH", "OAI", "OPENAI", "SPACEX", "STRIPE",
|
|
47
|
+
"DATABRICKS", "ANTHROPIC", "XAI", "ANDURIL", "KRAKEN", "PERPLEXITY",
|
|
48
|
+
}
|
|
49
|
+
CN_STAR_SYMBOLS = {"UNITREE", "CXMT", "GIGADEV", "ZHIPU", "MINIMAX", "DEEPSEEK", "CAMBRICON"}
|
|
50
|
+
HK_SYMBOLS = {"SHEIN", "HSI", "TENCENT", "MEITUAN", "XIAOMI", "BYD"}
|
|
51
|
+
IN_SYMBOLS = {"JIO", "NIFTY", "RELIANCE"}
|
|
52
|
+
KR_SYMBOLS = {"SKHX", "SKHY", "SMSN", "HYUNDAI", "KR200"}
|
|
53
|
+
JP_SYMBOLS = {"KIOXIA", "SOFTBANK", "JP225"}
|
|
54
|
+
FUTURES_MACRO_SYMBOLS = {
|
|
55
|
+
"SP500", "XYZ100", "GOLD", "SILVER", "PLATINUM", "PALLADIUM", "COPPER",
|
|
56
|
+
"CL", "BRENTOIL", "NATGAS", "USDJPY", "EURUSD", "GBPUSD", "PAXG",
|
|
57
|
+
"2Y", "10Y", "30Y", "BVIV", "SMALL2000", "DXY",
|
|
58
|
+
}
|
|
59
|
+
US_JP_SEMI_SYMBOLS = {
|
|
60
|
+
"NVDA", "AMD", "AVGO", "MU", "SNDK", "KIOXIA", "TSM", "INTC", "QCOM", "AMAT", "LRCX", "ASML", "SOXL",
|
|
61
|
+
}
|
|
62
|
+
OIL_SYMBOLS = {"CL", "BRENTOIL"}
|
|
63
|
+
METAL_SYMBOLS = {"GOLD", "SILVER", "PLATINUM", "PALLADIUM", "PAXG"}
|
|
64
|
+
|
|
65
|
+
IN_HOLIDAYS = {"2026-11-24", "2026-12-25"}
|
|
66
|
+
KR_HOLIDAYS = {"2026-12-25"}
|
|
67
|
+
JP_HOLIDAYS = {"2026-11-23", "2026-12-31"}
|
|
68
|
+
CN_HOLIDAYS: set[str] = set()
|
|
69
|
+
HK_HOLIDAYS = {"2026-12-25", "2026-12-26"}
|
|
70
|
+
US_FULL_HOLIDAYS = {"2026-11-26", "2026-12-25"}
|
|
71
|
+
US_EARLY_CLOSE_1300 = {"2026-11-27", "2026-12-24"}
|
|
72
|
+
US_OVERNIGHT_CLOSED_DATES = {"2026-11-25", "2026-11-26", "2026-12-24", "2026-12-25"}
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _http_json(url: str, payload: dict[str, Any] | None = None, headers: dict[str, str] | None = None, timeout: float = 12.0) -> Any:
|
|
76
|
+
hdrs = headers or {"Content-Type": "application/json", "User-Agent": f"hip3pulse-py/{__version__}"}
|
|
77
|
+
data = json.dumps(payload).encode("utf-8") if payload is not None else None
|
|
78
|
+
req = urllib.request.Request(url, data=data, headers=hdrs)
|
|
79
|
+
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
80
|
+
return json.loads(resp.read().decode("utf-8"))
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _hl_post(payload: dict[str, Any], timeout: float = 12.0) -> Any:
|
|
84
|
+
return _http_json(HL_API, payload=payload, timeout=timeout)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _tz_now(now_utc: datetime, tz_name: str) -> tuple[str, int, int]:
|
|
88
|
+
"""Return (YYYY-MM-DD, python_weekday Mon=0..Sun=6, minutes_since_midnight)."""
|
|
89
|
+
if ZoneInfo is not None:
|
|
90
|
+
dt = now_utc.astimezone(ZoneInfo(tz_name))
|
|
91
|
+
else: # pragma: no cover
|
|
92
|
+
offsets = {
|
|
93
|
+
"Asia/Shanghai": 8,
|
|
94
|
+
"Asia/Hong_Kong": 8,
|
|
95
|
+
"Asia/Kolkata": 5.5,
|
|
96
|
+
"Asia/Seoul": 9,
|
|
97
|
+
"Asia/Tokyo": 9,
|
|
98
|
+
"America/New_York": -5,
|
|
99
|
+
}
|
|
100
|
+
dt = now_utc.astimezone(timezone(timedelta(hours=offsets.get(tz_name, 0))))
|
|
101
|
+
return dt.strftime("%Y-%m-%d"), dt.weekday(), dt.hour * 60 + dt.minute
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _base_ticker(coin: str) -> str:
|
|
105
|
+
return coin.split(":")[1].upper() if ":" in coin else coin.upper()
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def classify_session(coin: str, funding_multiplier: float | None = None, now_utc: datetime | None = None) -> dict[str, Any]:
|
|
109
|
+
now = now_utc or datetime.now(timezone.utc)
|
|
110
|
+
sym = _base_ticker(coin)
|
|
111
|
+
|
|
112
|
+
if (funding_multiplier is not None and 0 < funding_multiplier <= 0.02) or sym in PRE_IPO_SYMBOLS:
|
|
113
|
+
return {
|
|
114
|
+
"sessionClass": "PRE_IPO_INTERNAL",
|
|
115
|
+
"sessionState": "PRE_IPO_INTERNAL",
|
|
116
|
+
"subState": "INTERNAL_EMA_ONLY",
|
|
117
|
+
"label": "PRE-IPO (Internal EMA Only)",
|
|
118
|
+
"isExternalOpen": False,
|
|
119
|
+
"isOffHoursMeanReversionEligible": False,
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
if sym in CN_STAR_SYMBOLS:
|
|
123
|
+
d_str, wd, mins = _tz_now(now, "Asia/Shanghai")
|
|
124
|
+
is_open = wd <= 4 and d_str not in CN_HOLIDAYS and ((570 <= mins < 690) or (780 <= mins < 900))
|
|
125
|
+
return {
|
|
126
|
+
"sessionClass": "CN_STAR_EQUITY",
|
|
127
|
+
"sessionState": "EXTERNAL_OPEN" if is_open else "INTERNAL_30M_EMA",
|
|
128
|
+
"subState": "CN_CASH_OPEN" if is_open else "CN_OFF_HOURS",
|
|
129
|
+
"label": "CN STAR Open" if is_open else "CN STAR Off-Hours (30m EMA)",
|
|
130
|
+
"isExternalOpen": is_open,
|
|
131
|
+
"isOffHoursMeanReversionEligible": not is_open,
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
if sym in HK_SYMBOLS:
|
|
135
|
+
d_str, wd, mins = _tz_now(now, "Asia/Hong_Kong")
|
|
136
|
+
is_open = wd <= 4 and d_str not in HK_HOLIDAYS and ((570 <= mins < 720) or (780 <= mins < 960))
|
|
137
|
+
return {
|
|
138
|
+
"sessionClass": "HK_EQUITY",
|
|
139
|
+
"sessionState": "EXTERNAL_OPEN" if is_open else "INTERNAL_30M_EMA",
|
|
140
|
+
"subState": "HK_CASH_OPEN" if is_open else "HK_OFF_HOURS",
|
|
141
|
+
"label": "HKEX Open" if is_open else "HKEX Off-Hours (30m EMA)",
|
|
142
|
+
"isExternalOpen": is_open,
|
|
143
|
+
"isOffHoursMeanReversionEligible": not is_open,
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
if sym in IN_SYMBOLS:
|
|
147
|
+
d_str, wd, mins = _tz_now(now, "Asia/Kolkata")
|
|
148
|
+
is_hol = d_str in IN_HOLIDAYS
|
|
149
|
+
is_open = wd <= 4 and not is_hol and (555 <= mins < 930)
|
|
150
|
+
return {
|
|
151
|
+
"sessionClass": "IN_EQUITY",
|
|
152
|
+
"sessionState": "EXTERNAL_OPEN" if is_open else "INTERNAL_30M_EMA",
|
|
153
|
+
"subState": "IN_HOLIDAY" if is_hol else ("NSE_OPEN" if is_open else "NSE_OFF_HOURS"),
|
|
154
|
+
"label": "India Holiday (30m EMA)" if is_hol else ("NSE Open" if is_open else "NSE Off-Hours (30m EMA)"),
|
|
155
|
+
"isExternalOpen": is_open,
|
|
156
|
+
"isOffHoursMeanReversionEligible": not is_open,
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
if sym in KR_SYMBOLS:
|
|
160
|
+
d_str, wd, mins = _tz_now(now, "Asia/Seoul")
|
|
161
|
+
is_open = wd <= 4 and d_str not in KR_HOLIDAYS and ((541 <= mins < 920) or (965 <= mins < 1200))
|
|
162
|
+
return {
|
|
163
|
+
"sessionClass": "KR_EQUITY",
|
|
164
|
+
"sessionState": "EXTERNAL_OPEN" if is_open else "INTERNAL_30M_EMA",
|
|
165
|
+
"subState": "KRX_OPEN" if is_open else "KRX_OFF_HOURS",
|
|
166
|
+
"label": "KRX Open" if is_open else "KRX Off-Hours (30m EMA)",
|
|
167
|
+
"isExternalOpen": is_open,
|
|
168
|
+
"isOffHoursMeanReversionEligible": not is_open,
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
if sym in JP_SYMBOLS:
|
|
172
|
+
d_str, wd, mins = _tz_now(now, "Asia/Tokyo")
|
|
173
|
+
is_open = wd <= 4 and d_str not in JP_HOLIDAYS and ((500 <= mins < 990) or (1020 <= mins < 1439))
|
|
174
|
+
return {
|
|
175
|
+
"sessionClass": "JP_EQUITY",
|
|
176
|
+
"sessionState": "EXTERNAL_OPEN" if is_open else "INTERNAL_30M_EMA",
|
|
177
|
+
"subState": "TSE_OPEN" if is_open else "TSE_OFF_HOURS",
|
|
178
|
+
"label": "TSE Open" if is_open else "TSE Off-Hours (30m EMA)",
|
|
179
|
+
"isExternalOpen": is_open,
|
|
180
|
+
"isOffHoursMeanReversionEligible": not is_open,
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
if sym in FUTURES_MACRO_SYMBOLS:
|
|
184
|
+
d_str, wd, mins = _tz_now(now, "America/New_York")
|
|
185
|
+
if d_str == "2026-12-25":
|
|
186
|
+
is_open = False
|
|
187
|
+
elif d_str == "2026-11-26":
|
|
188
|
+
is_open = mins < 13 * 60
|
|
189
|
+
elif d_str == "2026-11-27":
|
|
190
|
+
is_open = mins < 13 * 60 + 45
|
|
191
|
+
elif wd == 6: # Sunday
|
|
192
|
+
is_open = mins >= 18 * 60
|
|
193
|
+
elif 0 <= wd <= 3: # Mon-Thu
|
|
194
|
+
is_open = not (17 * 60 <= mins < 18 * 60)
|
|
195
|
+
elif wd == 4: # Friday
|
|
196
|
+
is_open = mins < 17 * 60
|
|
197
|
+
else:
|
|
198
|
+
is_open = False
|
|
199
|
+
return {
|
|
200
|
+
"sessionClass": "FUTURES_MACRO",
|
|
201
|
+
"sessionState": "EXTERNAL_OPEN" if is_open else "INTERNAL_30M_EMA",
|
|
202
|
+
"subState": "CME_GLOBEX_OPEN" if is_open else "FUTURES_MAINT_OR_WEEKEND",
|
|
203
|
+
"label": "Futures/FX Open" if is_open else "Futures Closed (30m EMA)",
|
|
204
|
+
"isExternalOpen": is_open,
|
|
205
|
+
"isOffHoursMeanReversionEligible": not is_open,
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
d_str, wd, mins = _tz_now(now, "America/New_York")
|
|
209
|
+
if sym == "URNM":
|
|
210
|
+
close_min = 13 * 60 if d_str in US_EARLY_CLOSE_1300 else 16 * 60
|
|
211
|
+
is_open = wd <= 4 and d_str not in US_FULL_HOLIDAYS and (570 <= mins < close_min)
|
|
212
|
+
return {
|
|
213
|
+
"sessionClass": "US_EQUITY_24_5",
|
|
214
|
+
"sessionState": "EXTERNAL_OPEN" if is_open else "INTERNAL_30M_EMA",
|
|
215
|
+
"subState": "US_REGULAR" if is_open else "URNM_OFF_HOURS",
|
|
216
|
+
"label": "US Regular (URNM)" if is_open else "URNM Off-Hours (30m EMA)",
|
|
217
|
+
"isExternalOpen": is_open,
|
|
218
|
+
"isOffHoursMeanReversionEligible": not is_open,
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
if d_str in US_FULL_HOLIDAYS:
|
|
222
|
+
return {
|
|
223
|
+
"sessionClass": "US_EQUITY_24_5",
|
|
224
|
+
"sessionState": "INTERNAL_30M_EMA",
|
|
225
|
+
"subState": "US_HOLIDAY_CLOSED",
|
|
226
|
+
"label": f"US Holiday Closed ({d_str})",
|
|
227
|
+
"isExternalOpen": False,
|
|
228
|
+
"isOffHoursMeanReversionEligible": True,
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
if d_str in US_EARLY_CLOSE_1300:
|
|
232
|
+
if 570 <= mins < 780:
|
|
233
|
+
return {
|
|
234
|
+
"sessionClass": "US_EQUITY_24_5",
|
|
235
|
+
"sessionState": "EXTERNAL_OPEN",
|
|
236
|
+
"subState": "US_REGULAR",
|
|
237
|
+
"label": "US Regular (Early Close 13:00 ET)",
|
|
238
|
+
"isExternalOpen": True,
|
|
239
|
+
"isOffHoursMeanReversionEligible": False,
|
|
240
|
+
}
|
|
241
|
+
if d_str == "2026-11-27" and 240 <= mins < 570:
|
|
242
|
+
return {
|
|
243
|
+
"sessionClass": "US_EQUITY_24_5",
|
|
244
|
+
"sessionState": "EXTERNAL_OPEN",
|
|
245
|
+
"subState": "US_OVERNIGHT_24_5",
|
|
246
|
+
"label": "US Pre-Market (Early Close Day)",
|
|
247
|
+
"isExternalOpen": True,
|
|
248
|
+
"isOffHoursMeanReversionEligible": False,
|
|
249
|
+
}
|
|
250
|
+
return {
|
|
251
|
+
"sessionClass": "US_EQUITY_24_5",
|
|
252
|
+
"sessionState": "INTERNAL_30M_EMA",
|
|
253
|
+
"subState": "US_HOLIDAY_EARLY_CLOSE",
|
|
254
|
+
"label": f"US Early Close / Off-Hours ({d_str})",
|
|
255
|
+
"isExternalOpen": False,
|
|
256
|
+
"isOffHoursMeanReversionEligible": True,
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
if d_str in US_OVERNIGHT_CLOSED_DATES and mins >= 20 * 60:
|
|
260
|
+
return {
|
|
261
|
+
"sessionClass": "US_EQUITY_24_5",
|
|
262
|
+
"sessionState": "INTERNAL_30M_EMA",
|
|
263
|
+
"subState": "US_HOLIDAY_EVE_CLOSED",
|
|
264
|
+
"label": f"US Overnight Holiday Closed ({d_str})",
|
|
265
|
+
"isExternalOpen": False,
|
|
266
|
+
"isOffHoursMeanReversionEligible": True,
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
if wd == 6: # Sunday
|
|
270
|
+
is_open = mins >= 20 * 60 + 5
|
|
271
|
+
sub = "US_OVERNIGHT_24_5" if is_open else "US_WEEKEND_CLOSED"
|
|
272
|
+
elif 0 <= wd <= 3:
|
|
273
|
+
is_open = True
|
|
274
|
+
sub = "US_REGULAR" if 570 <= mins < 960 else "US_OVERNIGHT_24_5"
|
|
275
|
+
elif wd == 4:
|
|
276
|
+
is_open = mins < 20 * 60
|
|
277
|
+
sub = "US_REGULAR" if 570 <= mins < 960 else ("US_OVERNIGHT_24_5" if is_open else "US_WEEKEND_CLOSED")
|
|
278
|
+
else:
|
|
279
|
+
is_open = False
|
|
280
|
+
sub = "US_WEEKEND_CLOSED"
|
|
281
|
+
|
|
282
|
+
return {
|
|
283
|
+
"sessionClass": "US_EQUITY_24_5",
|
|
284
|
+
"sessionState": "EXTERNAL_OPEN" if is_open else "INTERNAL_30M_EMA",
|
|
285
|
+
"subState": sub,
|
|
286
|
+
"label": "US Regular" if sub == "US_REGULAR" else ("US 24/5 Extended" if is_open else "US Closed (30m EMA)"),
|
|
287
|
+
"isExternalOpen": is_open,
|
|
288
|
+
"isOffHoursMeanReversionEligible": not is_open,
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def compute_hip3_fee_bps(market_meta: dict[str, Any], is_core_perp: bool = False) -> dict[str, Any]:
|
|
293
|
+
if is_core_perp:
|
|
294
|
+
return {"takerBps": 4.5, "makerBps": 1.5, "deployerFeeScale": 0.0, "growthMode": False}
|
|
295
|
+
scale = float(market_meta.get("deployerFeeScale", 1.0) or 1.0)
|
|
296
|
+
mult = (1.0 + scale) if scale <= 1.0 else (2.0 * scale)
|
|
297
|
+
disc = 0.1 if market_meta.get("growthMode") == "enabled" else 1.0
|
|
298
|
+
return {
|
|
299
|
+
"takerBps": round(4.5 * mult * disc, 3),
|
|
300
|
+
"makerBps": round(1.5 * mult * disc, 3),
|
|
301
|
+
"deployerFeeScale": scale,
|
|
302
|
+
"growthMode": market_meta.get("growthMode") == "enabled",
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def discover_active_dexs() -> dict[str, dict[str, Any]]:
|
|
307
|
+
raw = _hl_post({"type": "perpDexs"})
|
|
308
|
+
active: dict[str, dict[str, Any]] = {}
|
|
309
|
+
for idx, d in enumerate(raw):
|
|
310
|
+
if idx == 0 or not isinstance(d, dict) or not d.get("name"):
|
|
311
|
+
continue
|
|
312
|
+
name = d["name"]
|
|
313
|
+
try:
|
|
314
|
+
ma = _hl_post({"type": "metaAndAssetCtxs", "dex": name})
|
|
315
|
+
universe = ma[0].get("universe", [])
|
|
316
|
+
live_cnt = sum(1 for m in universe if not m.get("isDelisted"))
|
|
317
|
+
if live_cnt > 0:
|
|
318
|
+
active[name] = {
|
|
319
|
+
"name": name,
|
|
320
|
+
"perpDexIndex": idx,
|
|
321
|
+
"liveCount": live_cnt,
|
|
322
|
+
"oiCapMap": {k: float(v) for k, v in (d.get("assetToStreamingOiCap") or [])},
|
|
323
|
+
"fmMap": {k: float(v) for k, v in (d.get("assetToFundingMultiplier") or [])},
|
|
324
|
+
}
|
|
325
|
+
except Exception:
|
|
326
|
+
continue
|
|
327
|
+
return active
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def _derive_impact_gap_bps(ctx: dict[str, Any], oracle: float) -> float:
|
|
331
|
+
prem = ctx.get("premium")
|
|
332
|
+
if prem is not None:
|
|
333
|
+
try:
|
|
334
|
+
return float(prem) * 10000.0
|
|
335
|
+
except (TypeError, ValueError):
|
|
336
|
+
pass
|
|
337
|
+
ip = ctx.get("impactPxs")
|
|
338
|
+
if isinstance(ip, list) and len(ip) >= 2 and oracle > 0:
|
|
339
|
+
imp_mid = (float(ip[0]) + float(ip[1])) / 2.0
|
|
340
|
+
if imp_mid > 0:
|
|
341
|
+
return ((imp_mid - oracle) / oracle) * 10000.0
|
|
342
|
+
return 0.0
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def fetch_dex_markets(dex: str = "xyz", active_registry: dict[str, dict[str, Any]] | None = None) -> list[dict[str, Any]]:
|
|
346
|
+
is_core = not dex or dex == "core"
|
|
347
|
+
dex_info = None
|
|
348
|
+
if not is_core:
|
|
349
|
+
reg = active_registry if active_registry is not None else discover_active_dexs()
|
|
350
|
+
dex_info = reg.get(dex)
|
|
351
|
+
data = _hl_post({"type": "metaAndAssetCtxs"}) if is_core else _hl_post({"type": "metaAndAssetCtxs", "dex": dex})
|
|
352
|
+
universe = data[0].get("universe", []) if isinstance(data, list) and len(data) >= 2 else []
|
|
353
|
+
ctxs = data[1] if isinstance(data, list) and len(data) >= 2 else []
|
|
354
|
+
now_utc = datetime.now(timezone.utc)
|
|
355
|
+
out: list[dict[str, Any]] = []
|
|
356
|
+
|
|
357
|
+
for i, (m, c) in enumerate(zip(universe, ctxs)):
|
|
358
|
+
if m.get("isDelisted"):
|
|
359
|
+
continue
|
|
360
|
+
mark = float(c.get("markPx") or 0.0)
|
|
361
|
+
oracle = float(c.get("oraclePx") or 0.0)
|
|
362
|
+
mid = float(c.get("midPx") or mark or 0.0)
|
|
363
|
+
if oracle <= 0.0:
|
|
364
|
+
continue
|
|
365
|
+
fr_hr = float(c.get("funding") or 0.0)
|
|
366
|
+
ann_fr = fr_hr * 24.0 * 365.0 * 100.0
|
|
367
|
+
oi_usd = float(c.get("openInterest") or 0.0) * mark
|
|
368
|
+
vol_usd = float(c.get("dayNtlVlm") or 0.0)
|
|
369
|
+
mid_gap_bps = ((mid - oracle) / oracle) * 10000.0
|
|
370
|
+
impact_gap_bps = _derive_impact_gap_bps(c, oracle)
|
|
371
|
+
wide_noise = abs(mid_gap_bps) >= 30.0 and abs(impact_gap_bps) < 10.0
|
|
372
|
+
|
|
373
|
+
oi_cap_usd = dex_info["oiCapMap"].get(m["name"]) if dex_info else None
|
|
374
|
+
oi_cap_pct = round((oi_usd / oi_cap_usd) * 100.0, 2) if oi_cap_usd and oi_cap_usd > 0 else None
|
|
375
|
+
fm = dex_info["fmMap"].get(m["name"]) if dex_info else None
|
|
376
|
+
session = classify_session(m["name"], fm, now_utc)
|
|
377
|
+
fees = compute_hip3_fee_bps(m, is_core)
|
|
378
|
+
only_iso = bool(m.get("onlyIsolated") is True or m.get("marginMode") == "noCross")
|
|
379
|
+
max_lev = int(m.get("maxLeverage") or 10)
|
|
380
|
+
asset_id = i if is_core else (100000 + dex_info["perpDexIndex"] * 10000 + i if dex_info else None)
|
|
381
|
+
|
|
382
|
+
out.append(
|
|
383
|
+
{
|
|
384
|
+
"coin": m["name"],
|
|
385
|
+
"dex": "core" if is_core else dex,
|
|
386
|
+
"assetId": asset_id,
|
|
387
|
+
"midPx": round(mid, 4),
|
|
388
|
+
"oraclePx": round(oracle, 4),
|
|
389
|
+
"impactGapBps": round(impact_gap_bps, 2),
|
|
390
|
+
"midOracleGapBps": round(mid_gap_bps, 2),
|
|
391
|
+
"wideSpreadNoise": wide_noise,
|
|
392
|
+
"fundingHourlyPct": round(fr_hr * 100.0, 5),
|
|
393
|
+
"fundingHourlyRaw": fr_hr,
|
|
394
|
+
"fundingAnnualizedPct": round(ann_fr, 2),
|
|
395
|
+
"fundingMultiplier": fm,
|
|
396
|
+
"openInterestUsd": round(oi_usd),
|
|
397
|
+
"oiCapUsd": round(oi_cap_usd) if oi_cap_usd else None,
|
|
398
|
+
"oiCapUtilizationPct": oi_cap_pct,
|
|
399
|
+
"oiCapWarning": "⚠️ OI CAP >= 90%" if (oi_cap_pct is not None and oi_cap_pct >= 90.0) else None,
|
|
400
|
+
"volume24hUsd": round(vol_usd),
|
|
401
|
+
"growthMode90PctFeeDiscount": fees["growthMode"],
|
|
402
|
+
"takerFeeBps": fees["takerBps"],
|
|
403
|
+
"makerFeeBps": fees["makerBps"],
|
|
404
|
+
"onlyIsolated": only_iso,
|
|
405
|
+
"adlWarning": "⚠️ ISOLATED-ONLY (Direct ADL Risk)" if only_iso else None,
|
|
406
|
+
"maxLeverage": max_lev,
|
|
407
|
+
"instantBoundPct": round(100.0 / max_lev, 2),
|
|
408
|
+
"szDecimals": int(m.get("szDecimals", 2)),
|
|
409
|
+
"session": session,
|
|
410
|
+
}
|
|
411
|
+
)
|
|
412
|
+
return out
|
|
413
|
+
|
|
414
|
+
|
|
415
|
+
def fetch_corporate_actions(days: int = 4) -> dict[str, Any]:
|
|
416
|
+
now_utc = datetime.now(timezone.utc)
|
|
417
|
+
et_date_str, _, _ = _tz_now(now_utc, "America/New_York")
|
|
418
|
+
base_dt = datetime.strptime(et_date_str, "%Y-%m-%d")
|
|
419
|
+
dates = [(base_dt + timedelta(days=i)).strftime("%Y-%m-%d") for i in range(days)]
|
|
420
|
+
by_symbol: dict[str, dict[str, Any]] = {}
|
|
421
|
+
|
|
422
|
+
def ensure(sym: str) -> dict[str, Any]:
|
|
423
|
+
if sym not in by_symbol:
|
|
424
|
+
by_symbol[sym] = {
|
|
425
|
+
"dividends": [],
|
|
426
|
+
"splits": [],
|
|
427
|
+
"earnings": [],
|
|
428
|
+
"hasDividend": False,
|
|
429
|
+
"hasSplitHalt": False,
|
|
430
|
+
"hasEarnings": False,
|
|
431
|
+
"flags": [],
|
|
432
|
+
}
|
|
433
|
+
return by_symbol[sym]
|
|
434
|
+
|
|
435
|
+
seen_div: set[str] = set()
|
|
436
|
+
seen_split: set[str] = set()
|
|
437
|
+
seen_earn: set[str] = set()
|
|
438
|
+
now_ms = int(time.time() * 1000)
|
|
439
|
+
|
|
440
|
+
for dt in dates:
|
|
441
|
+
try:
|
|
442
|
+
j = _http_json(f"https://api.nasdaq.com/api/calendar/dividends?date={dt}", headers=NASDAQ_HEADERS, timeout=9.0)
|
|
443
|
+
for r in ((j.get("data") or {}).get("calendar") or {}).get("rows") or []:
|
|
444
|
+
sym = str(r.get("symbol") or "").strip().upper()
|
|
445
|
+
ex = str(r.get("dividend_Ex_Date") or "").strip()
|
|
446
|
+
if not sym or f"{sym}|{ex}" in seen_div:
|
|
447
|
+
continue
|
|
448
|
+
seen_div.add(f"{sym}|{ex}")
|
|
449
|
+
rec = ensure(sym)
|
|
450
|
+
rec["dividends"].append({"symbol": sym, "exDate": ex, "rate": float(r.get("dividend_Rate") or 0.0)})
|
|
451
|
+
rec["hasDividend"] = True
|
|
452
|
+
if "EX_DIVIDEND" not in rec["flags"]:
|
|
453
|
+
rec["flags"].append("EX_DIVIDEND")
|
|
454
|
+
except Exception:
|
|
455
|
+
pass
|
|
456
|
+
|
|
457
|
+
try:
|
|
458
|
+
j = _http_json(f"https://api.nasdaq.com/api/calendar/splits?date={dt}", headers=NASDAQ_HEADERS, timeout=9.0)
|
|
459
|
+
for r in (j.get("data") or {}).get("rows") or []:
|
|
460
|
+
sym = str(r.get("symbol") or "").strip().upper()
|
|
461
|
+
ex = str(r.get("executionDate") or "").strip()
|
|
462
|
+
if not sym or f"{sym}|{ex}" in seen_split:
|
|
463
|
+
continue
|
|
464
|
+
seen_split.add(f"{sym}|{ex}")
|
|
465
|
+
hours_until = None
|
|
466
|
+
try:
|
|
467
|
+
mm, dd, yyyy = map(int, ex.split("/"))
|
|
468
|
+
exec_ms = int(datetime(yyyy, mm, dd, 14, 30, tzinfo=timezone.utc).timestamp() * 1000)
|
|
469
|
+
hours_until = round((exec_ms - now_ms) / 3600000.0, 1)
|
|
470
|
+
except Exception:
|
|
471
|
+
pass
|
|
472
|
+
halt = hours_until is not None and -24.0 <= hours_until <= 48.0
|
|
473
|
+
rec = ensure(sym)
|
|
474
|
+
rec["splits"].append({"symbol": sym, "ratio": r.get("ratio"), "executionDate": ex, "hoursUntilExecution": hours_until, "splitSettlementHalt": halt})
|
|
475
|
+
if halt:
|
|
476
|
+
rec["hasSplitHalt"] = True
|
|
477
|
+
if "SPLIT_SETTLEMENT_HALT" not in rec["flags"]:
|
|
478
|
+
rec["flags"].append("SPLIT_SETTLEMENT_HALT")
|
|
479
|
+
except Exception:
|
|
480
|
+
pass
|
|
481
|
+
|
|
482
|
+
try:
|
|
483
|
+
j = _http_json(f"https://api.nasdaq.com/api/calendar/earnings?date={dt}", headers=NASDAQ_HEADERS, timeout=9.0)
|
|
484
|
+
for r in (j.get("data") or {}).get("rows") or []:
|
|
485
|
+
sym = str(r.get("symbol") or "").strip().upper()
|
|
486
|
+
if not sym or f"{sym}|{dt}" in seen_earn:
|
|
487
|
+
continue
|
|
488
|
+
seen_earn.add(f"{sym}|{dt}")
|
|
489
|
+
rec = ensure(sym)
|
|
490
|
+
rec["earnings"].append({"symbol": sym, "date": dt, "time": r.get("time"), "epsForecast": r.get("epsForecast")})
|
|
491
|
+
rec["hasEarnings"] = True
|
|
492
|
+
if "EARNINGS_WINDOW" not in rec["flags"]:
|
|
493
|
+
rec["flags"].append("EARNINGS_WINDOW")
|
|
494
|
+
except Exception:
|
|
495
|
+
pass
|
|
496
|
+
|
|
497
|
+
return {"windowDatesET": dates, "bySymbol": by_symbol}
|
|
498
|
+
|
|
499
|
+
|
|
500
|
+
def _estimate_l2_slippage(coin: str, mid_px: float, is_buy: bool, notional_usd: float = 10000.0) -> dict[str, Any]:
|
|
501
|
+
book = _hl_post({"type": "l2Book", "coin": coin})
|
|
502
|
+
levels = (book.get("levels") or [[], []])[1 if is_buy else 0]
|
|
503
|
+
rem, cost, qty = float(notional_usd), 0.0, 0.0
|
|
504
|
+
for lv in levels:
|
|
505
|
+
px, sz = float(lv["px"]), float(lv["sz"])
|
|
506
|
+
take = min(rem, px * sz)
|
|
507
|
+
cost += take
|
|
508
|
+
qty += take / px
|
|
509
|
+
rem -= take
|
|
510
|
+
if rem <= 0:
|
|
511
|
+
break
|
|
512
|
+
slip = round((abs((cost / qty) - mid_px) / mid_px) * 10000.0, 2) if rem <= 0 and qty > 0 else None
|
|
513
|
+
return {"bookCanFillNotional": rem <= 0, "estimatedOneWaySlippageBps": slip}
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
def _fetch_1h_candles_14d(coin: str) -> dict[int, float]:
|
|
517
|
+
now_ms = int(time.time() * 1000)
|
|
518
|
+
start_ms = now_ms - 14 * 24 * 3600 * 1000
|
|
519
|
+
raw = _hl_post({"type": "candleSnapshot", "req": {"coin": coin, "interval": "1h", "startTime": start_ms, "endTime": now_ms}})
|
|
520
|
+
return {int(c["t"]): float(c["c"]) for c in (raw or []) if float(c.get("c") or 0) > 0}
|
|
521
|
+
|
|
522
|
+
|
|
523
|
+
def _log_return_regression(primary_map: dict[int, float], hedge_map: dict[int, float]) -> dict[str, Any]:
|
|
524
|
+
ts = sorted(set(primary_map) & set(hedge_map))
|
|
525
|
+
rx, ry = [], []
|
|
526
|
+
for i in range(1, len(ts)):
|
|
527
|
+
if ts[i] - ts[i - 1] == 3600000:
|
|
528
|
+
rx.append(math.log(hedge_map[ts[i]] / hedge_map[ts[i - 1]]))
|
|
529
|
+
ry.append(math.log(primary_map[ts[i]] / primary_map[ts[i - 1]]))
|
|
530
|
+
n = len(rx)
|
|
531
|
+
if n < 48:
|
|
532
|
+
return {"samples": n, "beta": None, "rho": None, "r2": None}
|
|
533
|
+
mx, my = sum(rx) / n, sum(ry) / n
|
|
534
|
+
cov = sum((a - mx) * (b - my) for a, b in zip(rx, ry))
|
|
535
|
+
vx = sum((a - mx) ** 2 for a in rx)
|
|
536
|
+
vy = sum((b - my) ** 2 for b in ry)
|
|
537
|
+
if vx <= 0 or vy <= 0:
|
|
538
|
+
return {"samples": n, "beta": None, "rho": None, "r2": None}
|
|
539
|
+
beta = cov / vx
|
|
540
|
+
rho = cov / math.sqrt(vx * vy)
|
|
541
|
+
return {"samples": n, "beta": round(beta, 4), "rho": round(rho, 4), "r2": round(rho * rho, 4)}
|
|
542
|
+
|
|
543
|
+
|
|
544
|
+
def _candidate_hedges_for(coin: str) -> list[str]:
|
|
545
|
+
sym = _base_ticker(coin)
|
|
546
|
+
if sym in OIL_SYMBOLS:
|
|
547
|
+
cands = ["xyz:BRENTOIL", "xyz:CL"]
|
|
548
|
+
elif sym in METAL_SYMBOLS:
|
|
549
|
+
cands = ["PAXG", "xyz:GOLD", "xyz:SILVER"]
|
|
550
|
+
elif sym == "KR200":
|
|
551
|
+
cands = ["xyz:EWY", "xyz:SKHX", "xyz:XYZ100"]
|
|
552
|
+
elif sym in KR_SYMBOLS:
|
|
553
|
+
cands = ["xyz:KR200", "xyz:EWY", "xyz:SKHY", "xyz:MU", "xyz:XYZ100"]
|
|
554
|
+
elif sym in US_JP_SEMI_SYMBOLS:
|
|
555
|
+
cands = ["xyz:SOXL", "xyz:XYZ100", "xyz:SP500"]
|
|
556
|
+
elif sym in CN_STAR_SYMBOLS or sym in HK_SYMBOLS or sym in IN_SYMBOLS:
|
|
557
|
+
cands = ["xyz:XYZ100", "xyz:SP500", "xyz:EWY"]
|
|
558
|
+
else:
|
|
559
|
+
cands = ["xyz:XYZ100", "xyz:SP500"]
|
|
560
|
+
return [c for c in cands if c.lower() != coin.lower()]
|
|
561
|
+
|
|
562
|
+
|
|
563
|
+
def _find_market(coin: str, reg: dict[str, dict[str, Any]] | None = None) -> dict[str, Any] | None:
|
|
564
|
+
dex = coin.split(":")[0] if ":" in coin else "core"
|
|
565
|
+
mkts = fetch_dex_markets(dex=dex, active_registry=reg)
|
|
566
|
+
return next((m for m in mkts if m["coin"].lower() == coin.lower()), None)
|
|
567
|
+
|
|
568
|
+
|
|
569
|
+
def scan_dislocations(
|
|
570
|
+
dex: str = "xyz",
|
|
571
|
+
min_oi_usd: float = 500_000.0,
|
|
572
|
+
min_abs_gap_bps: float = 15.0,
|
|
573
|
+
exclude_noise: bool = True,
|
|
574
|
+
limit: int = 15,
|
|
575
|
+
) -> list[dict[str, Any]]:
|
|
576
|
+
reg = discover_active_dexs()
|
|
577
|
+
targets = list(reg.keys()) if dex.lower() == "all" else [dex.lower()]
|
|
578
|
+
markets: list[dict[str, Any]] = []
|
|
579
|
+
for d in targets:
|
|
580
|
+
try:
|
|
581
|
+
markets.extend(fetch_dex_markets(dex=d, active_registry=reg))
|
|
582
|
+
except Exception:
|
|
583
|
+
continue
|
|
584
|
+
filtered = [
|
|
585
|
+
m
|
|
586
|
+
for m in markets
|
|
587
|
+
if m["openInterestUsd"] >= min_oi_usd
|
|
588
|
+
and abs(m["impactGapBps"]) >= min_abs_gap_bps
|
|
589
|
+
and (not exclude_noise or (not m["wideSpreadNoise"] and m["session"]["sessionClass"] != "PRE_IPO_INTERNAL"))
|
|
590
|
+
]
|
|
591
|
+
filtered.sort(key=lambda m: abs(m["impactGapBps"]), reverse=True)
|
|
592
|
+
for m in filtered:
|
|
593
|
+
m.pop("fundingHourlyRaw", None)
|
|
594
|
+
return filtered[:limit]
|
|
595
|
+
|
|
596
|
+
|
|
597
|
+
def diagnose_contract(coin: str, notional_usd: float = 10_000.0) -> dict[str, Any]:
|
|
598
|
+
reg = discover_active_dexs()
|
|
599
|
+
info = _find_market(coin, reg)
|
|
600
|
+
if not info:
|
|
601
|
+
raise ValueError(f"Contract {coin!r} not found on active HIP-3 DEXs")
|
|
602
|
+
|
|
603
|
+
is_discount = info["impactGapBps"] < 0 if info["impactGapBps"] != 0 else info["midOracleGapBps"] < 0
|
|
604
|
+
slip = _estimate_l2_slippage(info["coin"], info["midPx"], is_discount, notional_usd)
|
|
605
|
+
corp = fetch_corporate_actions()
|
|
606
|
+
ca = corp["bySymbol"].get(_base_ticker(info["coin"])) or {
|
|
607
|
+
"dividends": [],
|
|
608
|
+
"splits": [],
|
|
609
|
+
"earnings": [],
|
|
610
|
+
"hasDividend": False,
|
|
611
|
+
"hasSplitHalt": False,
|
|
612
|
+
"hasEarnings": False,
|
|
613
|
+
"flags": [],
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
slip_val = slip["estimatedOneWaySlippageBps"] if slip["estimatedOneWaySlippageBps"] is not None else 10.0
|
|
617
|
+
est_single_rt = round(2.0 * (info["takerFeeBps"] + slip_val), 2)
|
|
618
|
+
info_out = {k: v for k, v in info.items() if k != "fundingHourlyRaw"}
|
|
619
|
+
|
|
620
|
+
return {
|
|
621
|
+
"version": __version__,
|
|
622
|
+
"contract": info_out,
|
|
623
|
+
"feeSchedule": {
|
|
624
|
+
"takerFeeBps": info["takerFeeBps"],
|
|
625
|
+
"makerFeeBps": info["makerFeeBps"],
|
|
626
|
+
"growthMode90PctFeeDiscount": info["growthMode90PctFeeDiscount"],
|
|
627
|
+
},
|
|
628
|
+
"bookCheck": {
|
|
629
|
+
"notionalUsd": notional_usd,
|
|
630
|
+
"bookCanFillNotional": slip["bookCanFillNotional"],
|
|
631
|
+
"estimatedOneWaySlippageBps": slip["estimatedOneWaySlippageBps"],
|
|
632
|
+
"estSingleLegRoundTripCostBps": est_single_rt,
|
|
633
|
+
},
|
|
634
|
+
"corporateActions": ca,
|
|
635
|
+
"onlyIsolated": info["onlyIsolated"],
|
|
636
|
+
"adlWarning": info["adlWarning"],
|
|
637
|
+
"oiCapWarning": info["oiCapWarning"],
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
|
|
641
|
+
def scan_xstocks_spread() -> list[dict[str, Any]]:
|
|
642
|
+
entries = list(XSTOCKS_MINTS.items())
|
|
643
|
+
mints = [cfg["mint"] for _, cfg in entries]
|
|
644
|
+
now_sec = int(time.time())
|
|
645
|
+
|
|
646
|
+
hl_markets = fetch_dex_markets("xyz")
|
|
647
|
+
hl_map = {m["coin"]: m for m in hl_markets}
|
|
648
|
+
sol = _http_json(
|
|
649
|
+
SOLANA_RPC,
|
|
650
|
+
payload={"jsonrpc": "2.0", "id": 1, "method": "getMultipleAccounts", "params": [mints, {"encoding": "jsonParsed"}]},
|
|
651
|
+
)
|
|
652
|
+
ds = _http_json(f"https://api.dexscreener.com/latest/dex/tokens/{','.join(mints)}")
|
|
653
|
+
accounts = (sol.get("result") or {}).get("value") or []
|
|
654
|
+
pairs = ds.get("pairs") or []
|
|
655
|
+
out: list[dict[str, Any]] = []
|
|
656
|
+
|
|
657
|
+
for i, (ticker, cfg) in enumerate(entries):
|
|
658
|
+
acc = accounts[i] if i < len(accounts) else None
|
|
659
|
+
exts = (((acc or {}).get("data") or {}).get("parsed") or {}).get("info", {}).get("extensions") or []
|
|
660
|
+
sc = next((e.get("state") for e in exts if e.get("extension") == "scaledUiAmountConfig"), None)
|
|
661
|
+
|
|
662
|
+
active_mult = 1.0
|
|
663
|
+
upcoming_rebase = None
|
|
664
|
+
if sc:
|
|
665
|
+
old_m = float(sc.get("multiplier") or 1.0)
|
|
666
|
+
new_m = float(sc.get("newMultiplier") or old_m)
|
|
667
|
+
eff_ts = int(sc.get("newMultiplierEffectiveTimestamp") or 0)
|
|
668
|
+
if eff_ts > 0 and now_sec >= eff_ts:
|
|
669
|
+
active_mult = new_m
|
|
670
|
+
elif eff_ts > now_sec:
|
|
671
|
+
active_mult = old_m
|
|
672
|
+
upcoming_rebase = {"effectiveUnix": eff_ts, "nextMultiplier": new_m}
|
|
673
|
+
else:
|
|
674
|
+
active_mult = old_m
|
|
675
|
+
|
|
676
|
+
matching = sorted(
|
|
677
|
+
[p for p in pairs if p.get("chainId") == "solana" and (p.get("baseToken") or {}).get("address") == cfg["mint"] and float((p.get("liquidity") or {}).get("usd") or 0) >= 20000],
|
|
678
|
+
key=lambda p: float((p.get("liquidity") or {}).get("usd") or 0),
|
|
679
|
+
reverse=True,
|
|
680
|
+
)
|
|
681
|
+
hl = hl_map.get(cfg["hl"])
|
|
682
|
+
if not matching or not hl:
|
|
683
|
+
continue
|
|
684
|
+
top = matching[0]
|
|
685
|
+
raw_px = float(top.get("priceUsd") or 0.0)
|
|
686
|
+
if raw_px <= 0:
|
|
687
|
+
continue
|
|
688
|
+
true_px = raw_px / active_mult
|
|
689
|
+
basis_bps = ((hl["midPx"] - true_px) / true_px) * 10000.0
|
|
690
|
+
out.append(
|
|
691
|
+
{
|
|
692
|
+
"xStock": ticker,
|
|
693
|
+
"hyperliquidCoin": cfg["hl"],
|
|
694
|
+
"rawTokenPriceUsd": round(raw_px, 4),
|
|
695
|
+
"activeMultiplier": round(active_mult, 8),
|
|
696
|
+
"upcomingRebase": upcoming_rebase,
|
|
697
|
+
"trueSharePriceUsd": round(true_px, 4),
|
|
698
|
+
"hyperliquidMidUsd": hl["midPx"],
|
|
699
|
+
"hlMinusSolBasisBps": round(basis_bps, 2),
|
|
700
|
+
"solanaLiquidityUsd": round(float((top.get("liquidity") or {}).get("usd") or 0)),
|
|
701
|
+
}
|
|
702
|
+
)
|
|
703
|
+
out.sort(key=lambda r: abs(r["hlMinusSolBasisBps"]), reverse=True)
|
|
704
|
+
return out
|
|
705
|
+
|
|
706
|
+
|
|
707
|
+
def build_beta_hedged_plan(coin: str, notional_usd: float = 2500.0, hedge_coin: str = "auto") -> dict[str, Any]:
|
|
708
|
+
reg = discover_active_dexs()
|
|
709
|
+
primary = _find_market(coin, reg)
|
|
710
|
+
if not primary:
|
|
711
|
+
raise ValueError(f"Primary contract {coin!r} not found")
|
|
712
|
+
|
|
713
|
+
cands = [hedge_coin] if hedge_coin and hedge_coin.lower() != "auto" else _candidate_hedges_for(primary["coin"])
|
|
714
|
+
p_candles = _fetch_1h_candles_14d(primary["coin"])
|
|
715
|
+
long_primary = primary["impactGapBps"] < 0 if primary["impactGapBps"] != 0 else primary["midOracleGapBps"] < 0
|
|
716
|
+
|
|
717
|
+
evaluated = []
|
|
718
|
+
for hc in cands:
|
|
719
|
+
hm = _find_market(hc, reg)
|
|
720
|
+
if not hm:
|
|
721
|
+
continue
|
|
722
|
+
h_candles = _fetch_1h_candles_14d(hm["coin"])
|
|
723
|
+
stats = _log_return_regression(p_candles, h_candles)
|
|
724
|
+
hedge_buy = long_primary if (stats["beta"] is not None and stats["beta"] < 0) else (not long_primary)
|
|
725
|
+
slip = _estimate_l2_slippage(hm["coin"], hm["midPx"], hedge_buy, 10000.0)
|
|
726
|
+
sb = slip["estimatedOneWaySlippageBps"]
|
|
727
|
+
ok_slip = slip["bookCanFillNotional"] and sb is not None and sb <= 10.0
|
|
728
|
+
ok_r2 = stats["r2"] is not None and stats["r2"] >= 0.35
|
|
729
|
+
score = (stats["r2"] - sb * 0.004 - (0.03 if hm["onlyIsolated"] else 0.0)) if (ok_r2 and ok_slip) else -1.0
|
|
730
|
+
evaluated.append({"coin": hm["coin"], "meta": hm, **stats, "slippage10kBps": sb, "passesR2": ok_r2, "passesSlip": ok_slip, "score": round(score, 5)})
|
|
731
|
+
|
|
732
|
+
evaluated.sort(key=lambda e: (e["score"], e["r2"] or -1.0), reverse=True)
|
|
733
|
+
best = next((e for e in evaluated if e["passesR2"] and e["passesSlip"]), None)
|
|
734
|
+
if not best:
|
|
735
|
+
return {
|
|
736
|
+
"version": __version__,
|
|
737
|
+
"status": "HEDGE_REJECTED_LOW_R2",
|
|
738
|
+
"hedgeApproved": False,
|
|
739
|
+
"primaryCoin": primary["coin"],
|
|
740
|
+
"evaluatedCandidates": [{k: v for k, v in e.items() if k != "meta"} for e in evaluated],
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
hm = best["meta"]
|
|
744
|
+
beta = best["beta"]
|
|
745
|
+
abs_beta = abs(beta)
|
|
746
|
+
n1 = float(notional_usd)
|
|
747
|
+
n2 = n1 * abs_beta
|
|
748
|
+
s1 = 1 if long_primary else -1
|
|
749
|
+
s2 = (-1 if beta >= 0 else 1) * s1
|
|
750
|
+
slip1 = _estimate_l2_slippage(primary["coin"], primary["midPx"], s1 > 0, max(n1, 1000.0))
|
|
751
|
+
slip2 = _estimate_l2_slippage(hm["coin"], hm["midPx"], s2 > 0, max(n2, 1000.0))
|
|
752
|
+
s1_bps = slip1["estimatedOneWaySlippageBps"] if slip1["estimatedOneWaySlippageBps"] is not None else 10.0
|
|
753
|
+
s2_bps = slip2["estimatedOneWaySlippageBps"] if slip2["estimatedOneWaySlippageBps"] is not None else 10.0
|
|
754
|
+
rt_bps = round(2.0 * (primary["takerFeeBps"] + s1_bps) + 2.0 * abs_beta * (hm["takerFeeBps"] + s2_bps), 2)
|
|
755
|
+
net_carry = n1 * (-s1 * primary["fundingHourlyRaw"]) + n2 * (-s2 * hm["fundingHourlyRaw"])
|
|
756
|
+
|
|
757
|
+
return {
|
|
758
|
+
"version": __version__,
|
|
759
|
+
"status": "HEDGE_PLAN_READY",
|
|
760
|
+
"hedgeApproved": True,
|
|
761
|
+
"regression14d1h": {"benchmark": hm["coin"], "samples": best["samples"], "beta": beta, "rho": best["rho"], "r2": best["r2"]},
|
|
762
|
+
"leg1Primary": {"coin": primary["coin"], "side": "BUY" if s1 > 0 else "SELL", "notionalUsd": round(n1, 2), "takerFeeBps": primary["takerFeeBps"], "onlyIsolated": primary["onlyIsolated"]},
|
|
763
|
+
"leg2Hedge": {"coin": hm["coin"], "side": "BUY" if s2 > 0 else "SELL", "notionalUsd": round(n2, 2), "betaRatio": abs_beta, "takerFeeBps": hm["takerFeeBps"], "onlyIsolated": hm["onlyIsolated"]},
|
|
764
|
+
"roundTripCostBps": rt_bps,
|
|
765
|
+
"netFundingCarryUsdPerHour": round(net_carry, 4),
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
|
|
769
|
+
__all__ = [
|
|
770
|
+
"__version__",
|
|
771
|
+
"classify_session",
|
|
772
|
+
"compute_hip3_fee_bps",
|
|
773
|
+
"discover_active_dexs",
|
|
774
|
+
"fetch_dex_markets",
|
|
775
|
+
"fetch_corporate_actions",
|
|
776
|
+
"scan_dislocations",
|
|
777
|
+
"diagnose_contract",
|
|
778
|
+
"scan_xstocks_spread",
|
|
779
|
+
"build_beta_hedged_plan",
|
|
780
|
+
]
|
hip3pulse/cli.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""Command-line interface for hip3pulse v0.2.0."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import sys
|
|
8
|
+
|
|
9
|
+
from . import (
|
|
10
|
+
__version__,
|
|
11
|
+
build_beta_hedged_plan,
|
|
12
|
+
diagnose_contract,
|
|
13
|
+
scan_dislocations,
|
|
14
|
+
scan_xstocks_spread,
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def main(argv: list[str] | None = None) -> int:
|
|
19
|
+
parser = argparse.ArgumentParser(
|
|
20
|
+
prog="hip3pulse",
|
|
21
|
+
description="Hyperliquid HIP-3 v0.2.0 off-hours dislocation, corp-action risk & β/R² hedge CLI.",
|
|
22
|
+
)
|
|
23
|
+
parser.add_argument("--version", action="version", version=f"hip3pulse {__version__}")
|
|
24
|
+
sub = parser.add_subparsers(dest="command")
|
|
25
|
+
|
|
26
|
+
p_scan = sub.add_parser("scan", help="Scan live HIP-3 impactGapBps dislocations across active DEXs")
|
|
27
|
+
p_scan.add_argument("--dex", default="xyz", help="Active HIP-3 DEX (xyz, io, para, mkts, or all)")
|
|
28
|
+
p_scan.add_argument("--min-oi", type=float, default=500_000.0)
|
|
29
|
+
p_scan.add_argument("--min-gap", type=float, default=15.0)
|
|
30
|
+
p_scan.add_argument("--limit", type=int, default=15)
|
|
31
|
+
|
|
32
|
+
p_diag = sub.add_parser("diagnose", help="Inspect exact fees, L2 slippage, session & corp-actions for a contract")
|
|
33
|
+
p_diag.add_argument("coin", help="Contract symbol, e.g. xyz:GOLD, xyz:COST, xyz:NVDA")
|
|
34
|
+
p_diag.add_argument("--notional", type=float, default=10_000.0)
|
|
35
|
+
|
|
36
|
+
sub.add_parser("xstocks", help="Compare 13 Solana Token-2022 xStocks active-multiplier prices vs HIP-3")
|
|
37
|
+
|
|
38
|
+
p_hedge = sub.add_parser("hedge", help="Compute 14-day 1h empirical β/R² hedge plan")
|
|
39
|
+
p_hedge.add_argument("coin", help="Primary contract, e.g. xyz:NVDA, xyz:CL, xyz:UNITREE")
|
|
40
|
+
p_hedge.add_argument("--notional", type=float, default=2_500.0)
|
|
41
|
+
p_hedge.add_argument("--hedge-coin", default="auto")
|
|
42
|
+
|
|
43
|
+
args = parser.parse_args(argv)
|
|
44
|
+
if args.command == "scan":
|
|
45
|
+
print(json.dumps(scan_dislocations(dex=args.dex, min_oi_usd=args.min_oi, min_abs_gap_bps=args.min_gap, limit=args.limit), indent=2))
|
|
46
|
+
return 0
|
|
47
|
+
if args.command == "diagnose":
|
|
48
|
+
print(json.dumps(diagnose_contract(coin=args.coin, notional_usd=args.notional), indent=2))
|
|
49
|
+
return 0
|
|
50
|
+
if args.command == "xstocks":
|
|
51
|
+
print(json.dumps(scan_xstocks_spread(), indent=2))
|
|
52
|
+
return 0
|
|
53
|
+
if args.command == "hedge":
|
|
54
|
+
print(json.dumps(build_beta_hedged_plan(coin=args.coin, notional_usd=args.notional, hedge_coin=args.hedge_coin), indent=2))
|
|
55
|
+
return 0
|
|
56
|
+
|
|
57
|
+
parser.print_help()
|
|
58
|
+
return 0
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
if __name__ == "__main__":
|
|
62
|
+
sys.exit(main())
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: hip3pulse
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Hyperliquid HIP-3 ($7B+/day) off-hours dislocation radar, Nasdaq corp-action risk, 13 Solana xStocks active-multiplier basis, and dynamic β/R² hedge Python SDK & CLI.
|
|
5
|
+
Author-email: HIP3Pulse <HIP3Pulse@users.noreply.github.com>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://hip3pulse.pages.dev
|
|
8
|
+
Project-URL: Repository, https://github.com/HIP3Pulse/hip3pulse
|
|
9
|
+
Project-URL: Telegram Alerts, https://t.me/HIP3Pulse
|
|
10
|
+
Project-URL: X (Twitter), https://x.com/HIP3Pulse
|
|
11
|
+
Keywords: hyperliquid,hip-3,hip3,rwa,xstocks,arbitrage,funding-rate,mcp,trading,defi
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Financial and Insurance Industry
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Topic :: Office/Business :: Financial :: Investment
|
|
17
|
+
Requires-Python: >=3.9
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
|
|
20
|
+
# hip3pulse (`v0.2.0`)
|
|
21
|
+
|
|
22
|
+
**Zero-dependency Python SDK & CLI for Hyperliquid HIP-3 (`$7B+/day` on-chain US equities, Gold, Oil, FX & Asian indices) and 13 Solana Token-2022 `xStocks`.**
|
|
23
|
+
|
|
24
|
+
- **Live Web Terminal**: https://hip3pulse.pages.dev
|
|
25
|
+
- **24/7 Telegram Alert Channel (Read-Only)**: https://t.me/HIP3Pulse
|
|
26
|
+
- **X (Twitter)**: https://x.com/HIP3Pulse
|
|
27
|
+
- **GitHub**: https://github.com/HIP3Pulse/hip3pulse
|
|
28
|
+
- **MCP Server (Claude / Cursor / Antigravity)**: `npx -y hip3pulse`
|
|
29
|
+
|
|
30
|
+
## Installation
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
pip install hip3pulse
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
## CLI Quick Start
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
# Dynamically discover active HIP-3 DEXs (xyz, io, para, mkts) and scan real impactGapBps dislocations
|
|
40
|
+
hip3pulse scan --dex xyz --min-oi 500000 --min-gap 15 --limit 10
|
|
41
|
+
|
|
42
|
+
# Full contract diagnostic (exact 9.0 vs 0.9 bps fees, Nasdaq corp-action guard, onlyIsolated ADL, L2 slippage)
|
|
43
|
+
hip3pulse diagnose xyz:GOLD --notional 10000
|
|
44
|
+
hip3pulse diagnose xyz:COST --notional 10000
|
|
45
|
+
|
|
46
|
+
# 13 Solana xStocks live active-multiplier basis vs Hyperliquid HIP-3
|
|
47
|
+
hip3pulse xstocks
|
|
48
|
+
|
|
49
|
+
# 14-day 1h empirical β/R² hedge planner (auto asset-class routing, rejects R² < 0.35)
|
|
50
|
+
hip3pulse hedge xyz:NVDA --notional 2500
|
|
51
|
+
hip3pulse hedge xyz:CL --notional 2500
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
## Python SDK
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
from hip3pulse import scan_dislocations, diagnose_contract, scan_xstocks_spread, build_beta_hedged_plan
|
|
58
|
+
|
|
59
|
+
top = scan_dislocations(dex="xyz", min_oi_usd=500_000, min_abs_gap_bps=15.0, limit=5)
|
|
60
|
+
diag = diagnose_contract("xyz:GOLD", notional_usd=10_000)
|
|
61
|
+
plan = build_beta_hedged_plan("xyz:NVDA", notional_usd=2_500)
|
|
62
|
+
xstocks = scan_xstocks_spread()
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
## Disclaimer
|
|
66
|
+
|
|
67
|
+
Read-only analytical utility. Never requests or handles private keys. Off-hours perpetual price gaps can reflect genuine overnight news, earnings, ex-dividends, or splits — always verify catalysts before trading.
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
hip3pulse/__init__.py,sha256=JNqz8wQQxvFCOI_Wm-7i6SYe50f4CvGn1HEk38MD7FQ,34305
|
|
2
|
+
hip3pulse/cli.py,sha256=7rj0pRoytNbNmIdHT9-qsTPuaaq1jQxbocNmhy0gb-k,2481
|
|
3
|
+
hip3pulse-0.2.0.dist-info/METADATA,sha256=OhRu-7K0JyDjxm6PdfZgUSJNfmwnpWuIZEFLPYfpKls,2741
|
|
4
|
+
hip3pulse-0.2.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
|
|
5
|
+
hip3pulse-0.2.0.dist-info/entry_points.txt,sha256=KxHsB9CUssN3nRiThOsw3HZnn63NK6nBk1PxAxCZLA4,49
|
|
6
|
+
hip3pulse-0.2.0.dist-info/top_level.txt,sha256=W-GPQFM9SVfI94jcOZ9UDQTJVoem91BQdK0FscMZz2I,10
|
|
7
|
+
hip3pulse-0.2.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
hip3pulse
|