hyperliquid_client.py 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659
  1. #!/usr/bin/env python3
  2. """
  3. Hyperliquid CLI Tool for Hermes Agent
  4. -------------------------------------
  5. Queries the Hyperliquid info endpoint for market and account data.
  6. Uses only Python standard library - no external packages required.
  7. Usage:
  8. python3 hyperliquid_client.py dexs
  9. python3 hyperliquid_client.py markets [--dex DEX] [--limit N]
  10. python3 hyperliquid_client.py spots [--limit N]
  11. python3 hyperliquid_client.py candles <coin> [--interval 1h] [--hours 24]
  12. python3 hyperliquid_client.py funding <coin> [--hours 72]
  13. python3 hyperliquid_client.py l2 <coin> [--levels 10]
  14. python3 hyperliquid_client.py state [address] [--dex DEX]
  15. python3 hyperliquid_client.py spot-balances [address]
  16. python3 hyperliquid_client.py fills [address] [--hours N] [--limit N]
  17. python3 hyperliquid_client.py orders [address] [--limit N]
  18. python3 hyperliquid_client.py review [address] [--coin COIN] [--hours N]
  19. python3 hyperliquid_client.py export <coin> [--interval 1h] [--hours N]
  20. Environment:
  21. HYPERLIQUID_API_URL Override API base URL
  22. (default: https://api.hyperliquid.xyz)
  23. HYPERLIQUID_USER_ADDRESS Default address for state/fills/orders/review commands
  24. """
  25. from __future__ import annotations
  26. import argparse
  27. import datetime as dt
  28. import json
  29. import os
  30. import sys
  31. import time
  32. import urllib.error
  33. import urllib.request
  34. from collections import Counter
  35. from pathlib import Path
  36. from typing import Any, Dict, Iterable, List, Optional
  37. USER_AGENT = "HermesAgent/1.0"
  38. DEFAULT_USER_ENV = "HYPERLIQUID_USER_ADDRESS"
  39. DEFAULT_API_BASE = "https://api.hyperliquid.xyz"
  40. def _hermes_home() -> Path:
  41. return Path(os.environ.get("HERMES_HOME", "~/.hermes")).expanduser()
  42. def _dotenv_paths() -> list[Path]:
  43. paths: list[Path] = []
  44. project_env = Path.cwd() / ".env"
  45. if project_env.exists():
  46. paths.append(project_env)
  47. user_env = _hermes_home() / ".env"
  48. if user_env.exists():
  49. paths.append(user_env)
  50. return paths
  51. def _load_dotenv_values() -> dict[str, str]:
  52. values: dict[str, str] = {}
  53. for env_path in _dotenv_paths():
  54. try:
  55. lines = env_path.read_text(encoding="utf-8").splitlines()
  56. except UnicodeDecodeError:
  57. lines = env_path.read_text(encoding="latin-1").splitlines()
  58. for raw_line in lines:
  59. line = raw_line.strip()
  60. if not line or line.startswith("#") or "=" not in line:
  61. continue
  62. key, _, value = raw_line.partition("=")
  63. key = key.strip()
  64. value = value.strip()
  65. if value.startswith('"') and value.endswith('"') and len(value) >= 2:
  66. value = value[1:-1].replace('\\"', '"').replace('\\\\', '\\')
  67. values[key] = value
  68. return values
  69. def _env_lookup(key: str, default: str = "") -> str:
  70. value = os.environ.get(key, "").strip()
  71. if value:
  72. return value
  73. dotenv_value = _load_dotenv_values().get(key, "").strip()
  74. if dotenv_value:
  75. return dotenv_value
  76. return default
  77. def _api_base() -> str:
  78. return _env_lookup("HYPERLIQUID_API_URL", DEFAULT_API_BASE).rstrip("/")
  79. def _info_url() -> str:
  80. api_base = _api_base()
  81. if api_base.endswith("/info"):
  82. return api_base
  83. return f"{api_base}/info"
  84. def _resolve_user(user: Optional[str]) -> str:
  85. candidate = (user or "").strip()
  86. if candidate:
  87. return candidate
  88. env_value = _env_lookup(DEFAULT_USER_ENV, "")
  89. if env_value:
  90. return env_value
  91. sys.exit(
  92. "Missing Hyperliquid address. Pass <address> explicitly or set "
  93. f"{DEFAULT_USER_ENV} in your environment or {_hermes_home() / '.env'}."
  94. )
  95. def _post_info(payload: dict[str, Any], timeout: int = 20, retries: int = 2) -> Any:
  96. data = json.dumps(payload).encode("utf-8")
  97. headers = {
  98. "Content-Type": "application/json",
  99. "Accept": "application/json",
  100. "User-Agent": USER_AGENT,
  101. }
  102. for attempt in range(retries + 1):
  103. request = urllib.request.Request(_info_url(), data=data, headers=headers, method="POST")
  104. try:
  105. with urllib.request.urlopen(request, timeout=timeout) as response:
  106. body = json.load(response)
  107. return body
  108. except urllib.error.HTTPError as exc:
  109. if exc.code == 429 and attempt < retries:
  110. time.sleep(1.5 * (attempt + 1))
  111. continue
  112. sys.exit(f"Hyperliquid HTTP error: {exc}")
  113. except urllib.error.URLError as exc:
  114. sys.exit(f"Hyperliquid connection error: {exc}")
  115. except json.JSONDecodeError as exc:
  116. sys.exit(f"Hyperliquid response was not valid JSON: {exc}")
  117. return None
  118. def _safe_float(value: Any) -> Optional[float]:
  119. try:
  120. if value is None or value == "":
  121. return None
  122. return float(value)
  123. except (TypeError, ValueError):
  124. return None
  125. def _limit_items(items: list[dict[str, Any]], limit: int) -> list[dict[str, Any]]:
  126. if limit <= 0:
  127. return items
  128. return items[:limit]
  129. def _hours_ago_ms(hours: float, now_ms: Optional[int] = None) -> int:
  130. end_ms = now_ms if now_ms is not None else int(time.time() * 1000)
  131. return end_ms - int(hours * 60 * 60 * 1000)
  132. def _format_timestamp_ms(value: Any) -> str:
  133. try:
  134. ts_ms = int(value)
  135. except (TypeError, ValueError):
  136. return "-"
  137. return dt.datetime.fromtimestamp(ts_ms / 1000, dt.UTC).strftime("%Y-%m-%d %H:%M:%S UTC")
  138. def _compact_number(value: Any, decimals: int = 2) -> str:
  139. number = _safe_float(value)
  140. if number is None:
  141. return "-"
  142. sign = "-" if number < 0 else ""
  143. number = abs(number)
  144. if number >= 1_000_000_000:
  145. return f"{sign}{number / 1_000_000_000:.{decimals}f}B"
  146. if number >= 1_000_000:
  147. return f"{sign}{number / 1_000_000:.{decimals}f}M"
  148. if number >= 1_000:
  149. return f"{sign}{number / 1_000:.{decimals}f}K"
  150. if number >= 100:
  151. return f"{sign}{number:.2f}"
  152. if number >= 1:
  153. return f"{sign}{number:.4f}".rstrip("0").rstrip(".")
  154. return f"{sign}{number:.6f}".rstrip("0").rstrip(".")
  155. def _format_price(value: Any) -> str:
  156. number = _safe_float(value)
  157. if number is None:
  158. return "-"
  159. if abs(number) >= 1000:
  160. return f"{number:,.2f}"
  161. if abs(number) >= 1:
  162. return f"{number:,.4f}".rstrip("0").rstrip(".")
  163. return f"{number:,.6f}".rstrip("0").rstrip(".")
  164. def _format_percent(value: Any, decimals: int = 2) -> str:
  165. number = _safe_float(value)
  166. if number is None:
  167. return "-"
  168. return f"{number:+.{decimals}f}%"
  169. def _format_fraction_percent(value: Any, decimals: int = 4) -> str:
  170. number = _safe_float(value)
  171. if number is None:
  172. return "-"
  173. return f"{number * 100:+.{decimals}f}%"
  174. def _percent_change(current: Any, previous: Any) -> Optional[float]:
  175. curr = _safe_float(current)
  176. prev = _safe_float(previous)
  177. if curr is None or prev is None or prev == 0:
  178. return None
  179. return ((curr - prev) / prev) * 100
  180. def _short_address(address: Any) -> str:
  181. if not isinstance(address, str) or len(address) < 12:
  182. return str(address)
  183. return f"{address[:6]}...{address[-4:]}"
  184. def _render_table(headers: list[tuple[str, str]], rows: list[dict[str, Any]]) -> str:
  185. if not rows:
  186. return "(no data)"
  187. prepared_rows: list[list[str]] = []
  188. widths = [len(label) for label, _ in headers]
  189. for row in rows:
  190. rendered = []
  191. for index, (_label, key) in enumerate(headers):
  192. value = row.get(key, "")
  193. text = str(value)
  194. rendered.append(text)
  195. widths[index] = max(widths[index], len(text))
  196. prepared_rows.append(rendered)
  197. lines = []
  198. header_line = " ".join(label.ljust(widths[idx]) for idx, (label, _key) in enumerate(headers))
  199. separator = " ".join("-" * widths[idx] for idx in range(len(headers)))
  200. lines.extend([header_line, separator])
  201. for rendered in prepared_rows:
  202. lines.append(" ".join(rendered[idx].ljust(widths[idx]) for idx in range(len(rendered))))
  203. return "\n".join(lines)
  204. def _normalize_dexs(payload: Any) -> list[dict[str, Any]]:
  205. rows: list[dict[str, Any]] = []
  206. if not isinstance(payload, list):
  207. return rows
  208. for index, item in enumerate(payload):
  209. if item is None:
  210. rows.append(
  211. {
  212. "index": index,
  213. "name": "",
  214. "label": "first-perp-dex",
  215. "full_name": "First perp dex",
  216. "deployer": "-",
  217. "asset_caps": 0,
  218. }
  219. )
  220. continue
  221. if not isinstance(item, dict):
  222. continue
  223. caps = item.get("assetToStreamingOiCap") or []
  224. rows.append(
  225. {
  226. "index": index,
  227. "name": item.get("name", ""),
  228. "label": item.get("name") or "first-perp-dex",
  229. "full_name": item.get("fullName") or "-",
  230. "deployer": item.get("deployer") or "-",
  231. "asset_caps": len(caps) if isinstance(caps, list) else 0,
  232. }
  233. )
  234. return rows
  235. def _normalize_perp_markets(payload: Any) -> list[dict[str, Any]]:
  236. if not isinstance(payload, list) or len(payload) < 2:
  237. return []
  238. meta = payload[0] if isinstance(payload[0], dict) else {}
  239. ctxs = payload[1] if isinstance(payload[1], list) else []
  240. universe = meta.get("universe") if isinstance(meta, dict) else []
  241. if not isinstance(universe, list):
  242. return []
  243. rows: list[dict[str, Any]] = []
  244. for index, spec in enumerate(universe):
  245. if not isinstance(spec, dict):
  246. continue
  247. ctx = ctxs[index] if index < len(ctxs) and isinstance(ctxs[index], dict) else {}
  248. mark_px = ctx.get("markPx") or ctx.get("midPx") or ctx.get("oraclePx")
  249. row = {
  250. "coin": spec.get("name", f"asset-{index}"),
  251. "mark_px": mark_px,
  252. "mid_px": ctx.get("midPx"),
  253. "oracle_px": ctx.get("oraclePx"),
  254. "prev_day_px": ctx.get("prevDayPx"),
  255. "change_pct": _percent_change(mark_px, ctx.get("prevDayPx")),
  256. "funding": ctx.get("funding"),
  257. "premium": ctx.get("premium"),
  258. "open_interest": ctx.get("openInterest"),
  259. "day_ntl_vlm": ctx.get("dayNtlVlm"),
  260. "day_base_vlm": ctx.get("dayBaseVlm"),
  261. "max_leverage": spec.get("maxLeverage"),
  262. "sz_decimals": spec.get("szDecimals"),
  263. "is_delisted": bool(spec.get("isDelisted")),
  264. "only_isolated": bool(spec.get("onlyIsolated")),
  265. "margin_mode": spec.get("marginMode") or "-",
  266. }
  267. rows.append(row)
  268. return rows
  269. def _normalize_spot_markets(payload: Any) -> list[dict[str, Any]]:
  270. if not isinstance(payload, list) or len(payload) < 2:
  271. return []
  272. meta = payload[0] if isinstance(payload[0], dict) else {}
  273. ctxs = payload[1] if isinstance(payload[1], list) else []
  274. pairs = meta.get("universe") if isinstance(meta, dict) else []
  275. tokens = meta.get("tokens") if isinstance(meta, dict) else []
  276. token_lookup = {}
  277. if isinstance(tokens, list):
  278. for token in tokens:
  279. if isinstance(token, dict) and "index" in token:
  280. token_lookup[token["index"]] = token.get("name", str(token["index"]))
  281. rows: list[dict[str, Any]] = []
  282. if not isinstance(pairs, list):
  283. return rows
  284. for index, pair in enumerate(pairs):
  285. if not isinstance(pair, dict):
  286. continue
  287. ctx = ctxs[index] if index < len(ctxs) and isinstance(ctxs[index], dict) else {}
  288. raw_name = pair.get("name", f"@{index}")
  289. tokens_for_pair = pair.get("tokens") if isinstance(pair.get("tokens"), list) else []
  290. display_name = raw_name
  291. if "/" not in raw_name and len(tokens_for_pair) == 2:
  292. base = token_lookup.get(tokens_for_pair[0], str(tokens_for_pair[0]))
  293. quote = token_lookup.get(tokens_for_pair[1], str(tokens_for_pair[1]))
  294. display_name = f"{base}/{quote} ({raw_name})"
  295. mark_px = ctx.get("markPx") or ctx.get("midPx")
  296. rows.append(
  297. {
  298. "pair": raw_name,
  299. "display_name": display_name,
  300. "mark_px": mark_px,
  301. "mid_px": ctx.get("midPx"),
  302. "prev_day_px": ctx.get("prevDayPx"),
  303. "change_pct": _percent_change(mark_px, ctx.get("prevDayPx")),
  304. "day_ntl_vlm": ctx.get("dayNtlVlm"),
  305. }
  306. )
  307. return rows
  308. def _normalize_candles(payload: Any) -> list[dict[str, Any]]:
  309. rows: list[dict[str, Any]] = []
  310. if not isinstance(payload, list):
  311. return rows
  312. for candle in payload:
  313. if not isinstance(candle, dict):
  314. continue
  315. rows.append(
  316. {
  317. "time": candle.get("t") or candle.get("time"),
  318. "open": candle.get("o"),
  319. "high": candle.get("h"),
  320. "low": candle.get("l"),
  321. "close": candle.get("c"),
  322. "volume": candle.get("v"),
  323. "trades": candle.get("n"),
  324. }
  325. )
  326. rows.sort(key=lambda item: int(item.get("time") or 0))
  327. return rows
  328. def _normalize_funding_history(payload: Any) -> list[dict[str, Any]]:
  329. rows: list[dict[str, Any]] = []
  330. if not isinstance(payload, list):
  331. return rows
  332. for item in payload:
  333. if not isinstance(item, dict):
  334. continue
  335. rows.append(
  336. {
  337. "coin": item.get("coin", "-"),
  338. "funding_rate": item.get("fundingRate"),
  339. "premium": item.get("premium"),
  340. "time": item.get("time"),
  341. }
  342. )
  343. rows.sort(key=lambda item: int(item.get("time") or 0))
  344. return rows
  345. def _normalize_book_levels(payload: Any) -> dict[str, list[dict[str, Any]]]:
  346. if not isinstance(payload, dict):
  347. return {"bids": [], "asks": []}
  348. levels = payload.get("levels")
  349. if not isinstance(levels, list) or len(levels) < 2:
  350. return {"bids": [], "asks": []}
  351. def convert(side: Iterable[Any]) -> list[dict[str, Any]]:
  352. converted = []
  353. for entry in side:
  354. if isinstance(entry, dict):
  355. converted.append(
  356. {
  357. "px": entry.get("px"),
  358. "sz": entry.get("sz"),
  359. "orders": entry.get("n"),
  360. }
  361. )
  362. elif isinstance(entry, (list, tuple)) and len(entry) >= 2:
  363. converted.append(
  364. {
  365. "px": entry[0],
  366. "sz": entry[1],
  367. "orders": entry[2] if len(entry) > 2 else None,
  368. }
  369. )
  370. return converted
  371. return {"bids": convert(levels[0]), "asks": convert(levels[1])}
  372. def _normalize_positions(payload: Any) -> dict[str, Any]:
  373. if not isinstance(payload, dict):
  374. return {"summary": {}, "positions": []}
  375. positions: list[dict[str, Any]] = []
  376. for item in payload.get("assetPositions", []):
  377. if not isinstance(item, dict):
  378. continue
  379. position = item.get("position") if isinstance(item.get("position"), dict) else item
  380. if not isinstance(position, dict):
  381. continue
  382. leverage = position.get("leverage") if isinstance(position.get("leverage"), dict) else {}
  383. positions.append(
  384. {
  385. "coin": position.get("coin", "-"),
  386. "size": position.get("szi"),
  387. "entry_px": position.get("entryPx"),
  388. "position_value": position.get("positionValue"),
  389. "unrealized_pnl": position.get("unrealizedPnl"),
  390. "return_on_equity": position.get("returnOnEquity"),
  391. "liquidation_px": position.get("liquidationPx"),
  392. "margin_used": position.get("marginUsed"),
  393. "leverage": leverage.get("value"),
  394. "leverage_type": leverage.get("type"),
  395. }
  396. )
  397. positions.sort(
  398. key=lambda item: abs(_safe_float(item.get("position_value")) or 0.0),
  399. reverse=True,
  400. )
  401. summary = payload.get("marginSummary") if isinstance(payload.get("marginSummary"), dict) else {}
  402. cross_summary = (
  403. payload.get("crossMarginSummary") if isinstance(payload.get("crossMarginSummary"), dict) else {}
  404. )
  405. return {
  406. "summary": {
  407. "account_value": summary.get("accountValue"),
  408. "total_ntl_pos": summary.get("totalNtlPos"),
  409. "total_raw_usd": summary.get("totalRawUsd"),
  410. "withdrawable": payload.get("withdrawable"),
  411. "cross_account_value": cross_summary.get("accountValue"),
  412. },
  413. "positions": positions,
  414. }
  415. def _normalize_spot_balances(payload: Any) -> list[dict[str, Any]]:
  416. if not isinstance(payload, dict):
  417. return []
  418. rows: list[dict[str, Any]] = []
  419. for item in payload.get("balances", []):
  420. if not isinstance(item, dict):
  421. continue
  422. rows.append(
  423. {
  424. "coin": item.get("coin", item.get("token", "-")),
  425. "total": item.get("total"),
  426. "hold": item.get("hold"),
  427. "entry_ntl": item.get("entryNtl"),
  428. }
  429. )
  430. rows.sort(key=lambda item: abs(_safe_float(item.get("entry_ntl")) or 0.0), reverse=True)
  431. return rows
  432. def _normalize_fills(payload: Any) -> list[dict[str, Any]]:
  433. rows: list[dict[str, Any]] = []
  434. if not isinstance(payload, list):
  435. return rows
  436. for item in payload:
  437. if not isinstance(item, dict):
  438. continue
  439. fill = item.get("fill") if isinstance(item.get("fill"), dict) else item
  440. rows.append(
  441. {
  442. "coin": fill.get("coin", "-"),
  443. "dir": fill.get("dir") or fill.get("side") or "-",
  444. "px": fill.get("px"),
  445. "sz": fill.get("sz"),
  446. "closed_pnl": fill.get("closedPnl"),
  447. "fee": fill.get("fee"),
  448. "fee_token": fill.get("feeToken"),
  449. "start_position": fill.get("startPosition"),
  450. "time": fill.get("time"),
  451. "hash": fill.get("hash"),
  452. "oid": fill.get("oid"),
  453. "twap_id": item.get("twapId"),
  454. }
  455. )
  456. rows.sort(key=lambda item: int(item.get("time") or 0), reverse=True)
  457. return rows
  458. def _normalize_orders(payload: Any) -> list[dict[str, Any]]:
  459. rows: list[dict[str, Any]] = []
  460. if not isinstance(payload, list):
  461. return rows
  462. for item in payload:
  463. if not isinstance(item, dict):
  464. continue
  465. order = item.get("order") if isinstance(item.get("order"), dict) else item
  466. rows.append(
  467. {
  468. "coin": order.get("coin", "-"),
  469. "side": order.get("side", "-"),
  470. "limit_px": order.get("limitPx") or order.get("px"),
  471. "size": order.get("sz") or order.get("origSz"),
  472. "timestamp": item.get("statusTimestamp")
  473. or order.get("timestamp")
  474. or order.get("time"),
  475. "status": item.get("status") or order.get("status") or "-",
  476. "oid": order.get("oid"),
  477. "order_type": order.get("orderType") or "-",
  478. }
  479. )
  480. rows.sort(key=lambda item: int(item.get("timestamp") or 0), reverse=True)
  481. return rows
  482. def _direction_bucket(direction: Any) -> str:
  483. text = str(direction or "").strip().lower()
  484. if "open" in text and "long" in text:
  485. return "open_long"
  486. if "close" in text and "long" in text:
  487. return "close_long"
  488. if "open" in text and "short" in text:
  489. return "open_short"
  490. if "close" in text and "short" in text:
  491. return "close_short"
  492. if text in {"b", "buy"}:
  493. return "buy"
  494. if text in {"s", "sell"}:
  495. return "sell"
  496. return "other"
  497. def _average(values: Iterable[Optional[float]]) -> Optional[float]:
  498. clean_values = [value for value in values if value is not None]
  499. if not clean_values:
  500. return None
  501. return round(sum(clean_values) / len(clean_values), 12)
  502. def _is_spot_coin(coin: str) -> bool:
  503. return "/" in coin or coin.startswith("@")
  504. def _safe_info_query(payload: dict[str, Any]) -> Any:
  505. try:
  506. return _post_info(payload)
  507. except SystemExit:
  508. return None
  509. def _market_context_for_coin(coin: str, interval: str, start_ms: int, end_ms: int) -> dict[str, Any]:
  510. candles = _normalize_candles(
  511. _safe_info_query(
  512. {
  513. "type": "candleSnapshot",
  514. "req": {
  515. "coin": coin,
  516. "interval": interval,
  517. "startTime": start_ms,
  518. "endTime": end_ms,
  519. },
  520. }
  521. )
  522. )
  523. funding_history: list[dict[str, Any]] = []
  524. if not _is_spot_coin(coin):
  525. funding_history = _normalize_funding_history(
  526. _safe_info_query(
  527. {
  528. "type": "fundingHistory",
  529. "coin": coin,
  530. "startTime": start_ms,
  531. "endTime": end_ms,
  532. }
  533. )
  534. )
  535. candle_change = None
  536. if candles:
  537. candle_change = _percent_change(candles[-1].get("close"), candles[0].get("open"))
  538. funding_average = _average(_safe_float(item.get("funding_rate")) for item in funding_history)
  539. return {
  540. "coin": coin,
  541. "interval": interval,
  542. "candle_count": len(candles),
  543. "price_change_pct": candle_change,
  544. "window_open": candles[0].get("open") if candles else None,
  545. "window_close": candles[-1].get("close") if candles else None,
  546. "average_funding_rate": funding_average,
  547. "funding_samples": len(funding_history),
  548. }
  549. def _build_coin_review(coin: str, fills: list[dict[str, Any]], interval: str, start_ms: int, end_ms: int) -> dict[str, Any]:
  550. pnl_values = [_safe_float(fill.get("closed_pnl")) for fill in fills]
  551. fee_values = [_safe_float(fill.get("fee")) for fill in fills]
  552. scored = [value for value in pnl_values if value is not None]
  553. wins = [value for value in scored if value > 0]
  554. losses = [value for value in scored if value < 0]
  555. breakeven = [value for value in scored if value == 0]
  556. direction_counts = Counter(_direction_bucket(fill.get("dir")) for fill in fills)
  557. market_context = _market_context_for_coin(coin, interval, start_ms, end_ms)
  558. total_pnl = sum(value for value in pnl_values if value is not None)
  559. total_fees = sum(value for value in fee_values if value is not None)
  560. net_after_fees = total_pnl - total_fees
  561. if direction_counts["open_long"] > direction_counts["open_short"]:
  562. open_bias = "long"
  563. elif direction_counts["open_short"] > direction_counts["open_long"]:
  564. open_bias = "short"
  565. elif direction_counts["open_long"] or direction_counts["open_short"]:
  566. open_bias = "mixed"
  567. else:
  568. open_bias = "none"
  569. return {
  570. "coin": coin,
  571. "fill_count": len(fills),
  572. "realized_pnl": total_pnl,
  573. "total_fees": total_fees,
  574. "net_after_fees": net_after_fees,
  575. "wins": len(wins),
  576. "losses": len(losses),
  577. "breakeven": len(breakeven),
  578. "win_rate_pct": (len(wins) / (len(wins) + len(losses)) * 100) if (len(wins) + len(losses)) else None,
  579. "open_long_count": direction_counts["open_long"],
  580. "open_short_count": direction_counts["open_short"],
  581. "close_long_count": direction_counts["close_long"],
  582. "close_short_count": direction_counts["close_short"],
  583. "open_bias": open_bias,
  584. "market_context": market_context,
  585. }
  586. def _review_findings(summary: dict[str, Any], coin_reviews: list[dict[str, Any]]) -> list[str]:
  587. findings: list[str] = []
  588. if summary["fill_count"] == 0:
  589. return ["No fills were found in the requested review window."]
  590. if summary["outcome_fill_count"] == 0:
  591. findings.append("Most fills in this window look like opens or adjustments, so realized-outcome review is limited until positions close.")
  592. if summary["net_after_fees"] < 0:
  593. findings.append(
  594. f"Net realized PnL after fees was negative ({_compact_number(summary['net_after_fees'])} USDC-equivalent units in reported fill terms)."
  595. )
  596. elif summary["net_after_fees"] > 0:
  597. findings.append(
  598. f"Net realized PnL after fees was positive ({_compact_number(summary['net_after_fees'])} USDC-equivalent units in reported fill terms)."
  599. )
  600. realized_abs = abs(summary["realized_pnl"])
  601. if summary["total_fees"] > 0:
  602. if realized_abs == 0:
  603. findings.append("Fees were non-trivial while realized PnL stayed flat, which usually means churn without enough edge.")
  604. elif summary["total_fees"] / realized_abs >= 0.25:
  605. ratio_pct = (summary["total_fees"] / realized_abs) * 100
  606. findings.append(f"Fees consumed about {ratio_pct:.1f}% of absolute realized PnL, so execution efficiency is materially affecting results.")
  607. if summary["fill_count"] >= 20 and summary["net_after_fees"] < 0:
  608. win_rate = summary.get("win_rate_pct")
  609. if win_rate is None or win_rate < 45:
  610. findings.append("Activity was high relative to results, which suggests overtrading in this review window.")
  611. if coin_reviews:
  612. worst_coin = min(coin_reviews, key=lambda item: item["net_after_fees"])
  613. best_coin = max(coin_reviews, key=lambda item: item["net_after_fees"])
  614. if worst_coin["net_after_fees"] < 0:
  615. findings.append(
  616. f"The weakest coin was {worst_coin['coin']} with net after fees of {_compact_number(worst_coin['net_after_fees'])}."
  617. )
  618. if best_coin["net_after_fees"] > 0 and best_coin["coin"] != worst_coin["coin"]:
  619. findings.append(
  620. f"The strongest coin was {best_coin['coin']} with net after fees of {_compact_number(best_coin['net_after_fees'])}."
  621. )
  622. for item in coin_reviews:
  623. market_change = item["market_context"].get("price_change_pct")
  624. if item["net_after_fees"] >= 0 or market_change is None:
  625. continue
  626. if market_change > 2 and item["open_short_count"] > item["open_long_count"]:
  627. findings.append(f"{item['coin']}: losses came while leaning short into a rising market window.")
  628. elif market_change < -2 and item["open_long_count"] > item["open_short_count"]:
  629. findings.append(f"{item['coin']}: losses came while leaning long into a falling market window.")
  630. deduped: list[str] = []
  631. for finding in findings:
  632. if finding not in deduped:
  633. deduped.append(finding)
  634. return deduped[:6]
  635. def _recent_fill_rows(fills: list[dict[str, Any]], limit: int) -> list[dict[str, Any]]:
  636. rows = []
  637. for fill in _limit_items(fills, limit):
  638. rows.append(
  639. {
  640. "time": fill.get("time"),
  641. "coin": fill.get("coin"),
  642. "dir": fill.get("dir"),
  643. "px": fill.get("px"),
  644. "sz": fill.get("sz"),
  645. "closed_pnl": fill.get("closed_pnl"),
  646. "fee": fill.get("fee"),
  647. "fee_token": fill.get("fee_token"),
  648. }
  649. )
  650. return rows
  651. def _coin_slug(coin: str) -> str:
  652. slug = str(coin or "market").strip().lower()
  653. for old, new in (("/", "-"), (":", "-"), ("@", "spot-"), (" ", "-")):
  654. slug = slug.replace(old, new)
  655. return slug or "market"
  656. def _default_export_path(coin: str, interval: str, hours: float) -> Path:
  657. hour_label = str(int(hours)) if float(hours).is_integer() else str(hours).replace(".", "p")
  658. filename = f"hyperliquid-{_coin_slug(coin)}-{interval}-{hour_label}h.json"
  659. return Path.cwd() / filename
  660. def _write_json_file(path: Path, payload: dict[str, Any]) -> None:
  661. path.parent.mkdir(parents=True, exist_ok=True)
  662. path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8")
  663. def _export_summary(candles: list[dict[str, Any]], funding_history: list[dict[str, Any]]) -> dict[str, Any]:
  664. candle_change = None
  665. if candles:
  666. candle_change = _percent_change(candles[-1].get("close"), candles[0].get("open"))
  667. return {
  668. "candle_count": len(candles),
  669. "funding_count": len(funding_history),
  670. "window_open": candles[0].get("open") if candles else None,
  671. "window_close": candles[-1].get("close") if candles else None,
  672. "price_change_pct": candle_change,
  673. "average_funding_rate": _average(_safe_float(item.get("funding_rate")) for item in funding_history),
  674. }
  675. def run_dexs(_args: argparse.Namespace) -> dict[str, Any]:
  676. payload = _post_info({"type": "perpDexs"})
  677. rows = _normalize_dexs(payload)
  678. return {"api_url": _info_url(), "count": len(rows), "dexs": rows}
  679. def run_markets(args: argparse.Namespace) -> dict[str, Any]:
  680. payload: dict[str, Any] = {"type": "metaAndAssetCtxs"}
  681. if args.dex:
  682. payload["dex"] = args.dex
  683. rows = _normalize_perp_markets(_post_info(payload))
  684. if args.sort == "name":
  685. rows.sort(key=lambda item: item["coin"])
  686. elif args.sort == "oi":
  687. rows.sort(key=lambda item: _safe_float(item.get("open_interest")) or 0.0, reverse=True)
  688. elif args.sort == "funding_abs":
  689. rows.sort(key=lambda item: abs(_safe_float(item.get("funding")) or 0.0), reverse=True)
  690. elif args.sort == "change_abs":
  691. rows.sort(key=lambda item: abs(_safe_float(item.get("change_pct")) or 0.0), reverse=True)
  692. else:
  693. rows.sort(key=lambda item: _safe_float(item.get("day_ntl_vlm")) or 0.0, reverse=True)
  694. return {
  695. "dex": args.dex or "",
  696. "count": len(rows),
  697. "sort": args.sort,
  698. "markets": _limit_items(rows, args.limit),
  699. }
  700. def run_spots(args: argparse.Namespace) -> dict[str, Any]:
  701. rows = _normalize_spot_markets(_post_info({"type": "spotMetaAndAssetCtxs"}))
  702. if args.sort == "name":
  703. rows.sort(key=lambda item: item["display_name"])
  704. elif args.sort == "change_abs":
  705. rows.sort(key=lambda item: abs(_safe_float(item.get("change_pct")) or 0.0), reverse=True)
  706. else:
  707. rows.sort(key=lambda item: _safe_float(item.get("day_ntl_vlm")) or 0.0, reverse=True)
  708. return {"count": len(rows), "sort": args.sort, "pairs": _limit_items(rows, args.limit)}
  709. def run_candles(args: argparse.Namespace) -> dict[str, Any]:
  710. end_ms = int(time.time() * 1000)
  711. start_ms = _hours_ago_ms(args.hours, end_ms)
  712. payload = {
  713. "type": "candleSnapshot",
  714. "req": {
  715. "coin": args.coin,
  716. "interval": args.interval,
  717. "startTime": start_ms,
  718. "endTime": end_ms,
  719. },
  720. }
  721. candles = _normalize_candles(_post_info(payload))
  722. summary = {}
  723. if candles:
  724. highs = [_safe_float(item.get("high")) for item in candles]
  725. lows = [_safe_float(item.get("low")) for item in candles]
  726. clean_highs = [value for value in highs if value is not None]
  727. clean_lows = [value for value in lows if value is not None]
  728. summary = {
  729. "first_time": candles[0]["time"],
  730. "last_time": candles[-1]["time"],
  731. "open": candles[0]["open"],
  732. "close": candles[-1]["close"],
  733. "high": max(clean_highs) if clean_highs else None,
  734. "low": min(clean_lows) if clean_lows else None,
  735. "change_pct": _percent_change(candles[-1]["close"], candles[0]["open"]),
  736. }
  737. return {
  738. "coin": args.coin,
  739. "interval": args.interval,
  740. "hours": args.hours,
  741. "count": len(candles),
  742. "summary": summary,
  743. "candles": _limit_items(candles, args.limit),
  744. }
  745. def run_funding(args: argparse.Namespace) -> dict[str, Any]:
  746. end_ms = int(time.time() * 1000)
  747. start_ms = _hours_ago_ms(args.hours, end_ms)
  748. payload = {"type": "fundingHistory", "coin": args.coin, "startTime": start_ms, "endTime": end_ms}
  749. rows = _normalize_funding_history(_post_info(payload))
  750. avg_rate = None
  751. if rows:
  752. values = [_safe_float(item.get("funding_rate")) for item in rows]
  753. clean_values = [value for value in values if value is not None]
  754. if clean_values:
  755. avg_rate = sum(clean_values) / len(clean_values)
  756. return {
  757. "coin": args.coin,
  758. "hours": args.hours,
  759. "count": len(rows),
  760. "average_funding_rate": avg_rate,
  761. "history": _limit_items(list(reversed(rows)), args.limit),
  762. }
  763. def run_l2(args: argparse.Namespace) -> dict[str, Any]:
  764. payload: dict[str, Any] = {"type": "l2Book", "coin": args.coin}
  765. if args.n_sig_figs is not None:
  766. payload["nSigFigs"] = args.n_sig_figs
  767. if args.mantissa is not None:
  768. payload["mantissa"] = args.mantissa
  769. raw = _post_info(payload)
  770. levels = _normalize_book_levels(raw)
  771. return {
  772. "coin": args.coin,
  773. "time": raw.get("time") if isinstance(raw, dict) else None,
  774. "bids": _limit_items(levels["bids"], args.levels),
  775. "asks": _limit_items(levels["asks"], args.levels),
  776. }
  777. def run_state(args: argparse.Namespace) -> dict[str, Any]:
  778. user = _resolve_user(args.user)
  779. payload: dict[str, Any] = {"type": "clearinghouseState", "user": user}
  780. if args.dex:
  781. payload["dex"] = args.dex
  782. normalized = _normalize_positions(_post_info(payload))
  783. return {
  784. "user": user,
  785. "dex": args.dex or "",
  786. "summary": normalized["summary"],
  787. "positions": normalized["positions"],
  788. }
  789. def run_spot_balances(args: argparse.Namespace) -> dict[str, Any]:
  790. user = _resolve_user(args.user)
  791. payload = {"type": "spotClearinghouseState", "user": user}
  792. rows = _normalize_spot_balances(_post_info(payload))
  793. return {"user": user, "count": len(rows), "balances": _limit_items(rows, args.limit)}
  794. def run_fills(args: argparse.Namespace) -> dict[str, Any]:
  795. user = _resolve_user(args.user)
  796. payload: dict[str, Any] = {"user": user}
  797. if args.hours is not None:
  798. payload["type"] = "userFillsByTime"
  799. payload["startTime"] = _hours_ago_ms(args.hours)
  800. else:
  801. payload["type"] = "userFills"
  802. if args.aggregate_by_time:
  803. payload["aggregateByTime"] = True
  804. rows = _normalize_fills(_post_info(payload))
  805. return {
  806. "user": user,
  807. "hours": args.hours,
  808. "aggregate_by_time": args.aggregate_by_time,
  809. "count": len(rows),
  810. "fills": _limit_items(rows, args.limit),
  811. }
  812. def run_orders(args: argparse.Namespace) -> dict[str, Any]:
  813. user = _resolve_user(args.user)
  814. payload = {"type": "historicalOrders", "user": user}
  815. rows = _normalize_orders(_post_info(payload))
  816. return {"user": user, "count": len(rows), "orders": _limit_items(rows, args.limit)}
  817. def run_review(args: argparse.Namespace) -> dict[str, Any]:
  818. user = _resolve_user(args.user)
  819. end_ms = int(time.time() * 1000)
  820. start_ms = _hours_ago_ms(args.hours, end_ms)
  821. payload: dict[str, Any] = {"type": "userFillsByTime", "user": user, "startTime": start_ms}
  822. if args.aggregate_by_time:
  823. payload["aggregateByTime"] = True
  824. fills = _normalize_fills(_post_info(payload))
  825. if args.coin:
  826. target = args.coin.lower()
  827. fills = [fill for fill in fills if str(fill.get("coin", "")).lower() == target]
  828. fills = _limit_items(fills, args.fills)
  829. grouped: dict[str, list[dict[str, Any]]] = {}
  830. for fill in fills:
  831. grouped.setdefault(fill.get("coin", "-"), []).append(fill)
  832. coin_reviews = [
  833. _build_coin_review(coin, coin_fills, args.interval, start_ms, end_ms)
  834. for coin, coin_fills in sorted(grouped.items(), key=lambda item: len(item[1]), reverse=True)
  835. ]
  836. pnl_values = [_safe_float(fill.get("closed_pnl")) for fill in fills]
  837. fee_values = [_safe_float(fill.get("fee")) for fill in fills]
  838. scored = [value for value in pnl_values if value is not None]
  839. wins = [value for value in scored if value > 0]
  840. losses = [value for value in scored if value < 0]
  841. direction_counts = Counter(_direction_bucket(fill.get("dir")) for fill in fills)
  842. total_pnl = sum(value for value in pnl_values if value is not None)
  843. total_fees = sum(value for value in fee_values if value is not None)
  844. summary = {
  845. "fill_count": len(fills),
  846. "scored_fill_count": len(scored),
  847. "outcome_fill_count": len(wins) + len(losses),
  848. "unique_coins": len(grouped),
  849. "realized_pnl": total_pnl,
  850. "total_fees": total_fees,
  851. "net_after_fees": total_pnl - total_fees,
  852. "wins": len(wins),
  853. "losses": len(losses),
  854. "breakeven": len([value for value in scored if value == 0]),
  855. "win_rate_pct": (len(wins) / (len(wins) + len(losses)) * 100) if (len(wins) + len(losses)) else None,
  856. "open_long_count": direction_counts["open_long"],
  857. "open_short_count": direction_counts["open_short"],
  858. "close_long_count": direction_counts["close_long"],
  859. "close_short_count": direction_counts["close_short"],
  860. }
  861. return {
  862. "user": user,
  863. "coin_filter": args.coin,
  864. "hours": args.hours,
  865. "interval": args.interval,
  866. "fills_requested": args.fills,
  867. "summary": summary,
  868. "findings": _review_findings(summary, coin_reviews),
  869. "coin_reviews": coin_reviews,
  870. "recent_fills": _recent_fill_rows(fills, args.recent),
  871. }
  872. def run_export(args: argparse.Namespace) -> dict[str, Any]:
  873. end_ms = args.end_time_ms if args.end_time_ms is not None else int(time.time() * 1000)
  874. start_ms = _hours_ago_ms(args.hours, end_ms)
  875. candle_payload = {
  876. "type": "candleSnapshot",
  877. "req": {
  878. "coin": args.coin,
  879. "interval": args.interval,
  880. "startTime": start_ms,
  881. "endTime": end_ms,
  882. },
  883. }
  884. candles = _normalize_candles(_post_info(candle_payload))
  885. funding_history: list[dict[str, Any]] = []
  886. if not _is_spot_coin(args.coin):
  887. funding_history = _normalize_funding_history(
  888. _safe_info_query(
  889. {
  890. "type": "fundingHistory",
  891. "coin": args.coin,
  892. "startTime": start_ms,
  893. "endTime": end_ms,
  894. }
  895. )
  896. )
  897. output_path = Path(args.output) if args.output else _default_export_path(args.coin, args.interval, args.hours)
  898. payload = {
  899. "schema_version": "hyperliquid-market-export-v1",
  900. "source": {
  901. "api_url": _info_url(),
  902. "interval": args.interval,
  903. "coin": args.coin,
  904. "market_type": "spot" if _is_spot_coin(args.coin) else "perp",
  905. },
  906. "window": {
  907. "start_time_ms": start_ms,
  908. "end_time_ms": end_ms,
  909. "hours": args.hours,
  910. },
  911. "summary": _export_summary(candles, funding_history),
  912. "candles": candles,
  913. "funding_history": funding_history,
  914. }
  915. _write_json_file(output_path, payload)
  916. return {
  917. "coin": args.coin,
  918. "interval": args.interval,
  919. "hours": args.hours,
  920. "output_path": str(output_path),
  921. "summary": payload["summary"],
  922. "schema_version": payload["schema_version"],
  923. }
  924. def render_dexs(data: dict[str, Any]) -> str:
  925. rows = [
  926. {
  927. "label": item["label"],
  928. "full_name": item["full_name"],
  929. "deployer": _short_address(item["deployer"]),
  930. "asset_caps": item["asset_caps"],
  931. }
  932. for item in data["dexs"]
  933. ]
  934. return "\n".join(
  935. [
  936. f"API: {data['api_url']}",
  937. f"Perp dexs: {data['count']}",
  938. "",
  939. _render_table(
  940. [
  941. ("Dex", "label"),
  942. ("Full Name", "full_name"),
  943. ("Deployer", "deployer"),
  944. ("Asset Caps", "asset_caps"),
  945. ],
  946. rows,
  947. ),
  948. ]
  949. )
  950. def render_markets(data: dict[str, Any]) -> str:
  951. rows = [
  952. {
  953. "coin": item["coin"],
  954. "mark_px": _format_price(item["mark_px"]),
  955. "change_pct": _format_percent(item["change_pct"]),
  956. "funding": _format_fraction_percent(item["funding"]),
  957. "open_interest": _compact_number(item["open_interest"]),
  958. "day_ntl_vlm": _compact_number(item["day_ntl_vlm"]),
  959. }
  960. for item in data["markets"]
  961. ]
  962. lines = [
  963. f"Dex: {data['dex'] or 'first-perp-dex'}",
  964. f"Markets returned: {len(data['markets'])} of {data['count']}",
  965. "",
  966. _render_table(
  967. [
  968. ("Coin", "coin"),
  969. ("Mark", "mark_px"),
  970. ("Chg", "change_pct"),
  971. ("Funding", "funding"),
  972. ("OI", "open_interest"),
  973. ("24h Vol", "day_ntl_vlm"),
  974. ],
  975. rows,
  976. ),
  977. ]
  978. return "\n".join(lines)
  979. def render_spots(data: dict[str, Any]) -> str:
  980. rows = [
  981. {
  982. "pair": item["display_name"],
  983. "mark_px": _format_price(item["mark_px"]),
  984. "change_pct": _format_percent(item["change_pct"]),
  985. "day_ntl_vlm": _compact_number(item["day_ntl_vlm"]),
  986. }
  987. for item in data["pairs"]
  988. ]
  989. return "\n".join(
  990. [
  991. f"Spot pairs returned: {len(data['pairs'])} of {data['count']}",
  992. "",
  993. _render_table(
  994. [
  995. ("Pair", "pair"),
  996. ("Mark", "mark_px"),
  997. ("Chg", "change_pct"),
  998. ("24h Vol", "day_ntl_vlm"),
  999. ],
  1000. rows,
  1001. ),
  1002. ]
  1003. )
  1004. def render_candles(data: dict[str, Any]) -> str:
  1005. rows = [
  1006. {
  1007. "time": _format_timestamp_ms(item["time"]),
  1008. "open": _format_price(item["open"]),
  1009. "high": _format_price(item["high"]),
  1010. "low": _format_price(item["low"]),
  1011. "close": _format_price(item["close"]),
  1012. "volume": _compact_number(item["volume"]),
  1013. }
  1014. for item in data["candles"]
  1015. ]
  1016. summary = data.get("summary") or {}
  1017. lines = [
  1018. f"Coin: {data['coin']}",
  1019. f"Interval: {data['interval']}",
  1020. f"Hours: {data['hours']}",
  1021. f"Candles returned: {len(data['candles'])} of {data['count']}",
  1022. ]
  1023. if summary:
  1024. lines.extend(
  1025. [
  1026. f"Open -> Close: {_format_price(summary.get('open'))} -> {_format_price(summary.get('close'))}",
  1027. f"Range: {_format_price(summary.get('low'))} to {_format_price(summary.get('high'))}",
  1028. f"Change: {_format_percent(summary.get('change_pct'))}",
  1029. ]
  1030. )
  1031. lines.extend(
  1032. [
  1033. "",
  1034. _render_table(
  1035. [
  1036. ("Time", "time"),
  1037. ("Open", "open"),
  1038. ("High", "high"),
  1039. ("Low", "low"),
  1040. ("Close", "close"),
  1041. ("Volume", "volume"),
  1042. ],
  1043. rows,
  1044. ),
  1045. ]
  1046. )
  1047. return "\n".join(lines)
  1048. def render_funding(data: dict[str, Any]) -> str:
  1049. rows = [
  1050. {
  1051. "time": _format_timestamp_ms(item["time"]),
  1052. "coin": item["coin"],
  1053. "funding": _format_fraction_percent(item["funding_rate"]),
  1054. "premium": _format_fraction_percent(item["premium"]),
  1055. }
  1056. for item in data["history"]
  1057. ]
  1058. lines = [
  1059. f"Coin: {data['coin']}",
  1060. f"Hours: {data['hours']}",
  1061. f"Entries returned: {len(data['history'])} of {data['count']}",
  1062. f"Average funding: {_format_fraction_percent(data['average_funding_rate'])}",
  1063. "",
  1064. _render_table(
  1065. [
  1066. ("Time", "time"),
  1067. ("Coin", "coin"),
  1068. ("Funding", "funding"),
  1069. ("Premium", "premium"),
  1070. ],
  1071. rows,
  1072. ),
  1073. ]
  1074. return "\n".join(lines)
  1075. def render_l2(data: dict[str, Any]) -> str:
  1076. bid_rows = [
  1077. {"px": _format_price(item["px"]), "sz": _compact_number(item["sz"]), "orders": item["orders"] or "-"}
  1078. for item in data["bids"]
  1079. ]
  1080. ask_rows = [
  1081. {"px": _format_price(item["px"]), "sz": _compact_number(item["sz"]), "orders": item["orders"] or "-"}
  1082. for item in data["asks"]
  1083. ]
  1084. lines = [
  1085. f"Coin: {data['coin']}",
  1086. f"Book time: {_format_timestamp_ms(data['time'])}",
  1087. "",
  1088. "Bids",
  1089. _render_table([("Price", "px"), ("Size", "sz"), ("Orders", "orders")], bid_rows),
  1090. "",
  1091. "Asks",
  1092. _render_table([("Price", "px"), ("Size", "sz"), ("Orders", "orders")], ask_rows),
  1093. ]
  1094. return "\n".join(lines)
  1095. def render_state(data: dict[str, Any]) -> str:
  1096. summary = data["summary"]
  1097. position_rows = [
  1098. {
  1099. "coin": item["coin"],
  1100. "size": item["size"],
  1101. "entry_px": _format_price(item["entry_px"]),
  1102. "position_value": _compact_number(item["position_value"]),
  1103. "unrealized_pnl": _compact_number(item["unrealized_pnl"]),
  1104. "roe": _format_fraction_percent(item["return_on_equity"], 2),
  1105. "liq": _format_price(item["liquidation_px"]),
  1106. "lev": f"{item['leverage'] or '-'}x",
  1107. }
  1108. for item in data["positions"]
  1109. ]
  1110. lines = [
  1111. f"User: {data['user']}",
  1112. f"Dex: {data['dex'] or 'first-perp-dex'}",
  1113. f"Account value: {summary.get('account_value') or '-'}",
  1114. f"Total notional position: {summary.get('total_ntl_pos') or '-'}",
  1115. f"Withdrawable: {summary.get('withdrawable') or '-'}",
  1116. f"Positions: {len(data['positions'])}",
  1117. ]
  1118. if position_rows:
  1119. lines.extend(
  1120. [
  1121. "",
  1122. _render_table(
  1123. [
  1124. ("Coin", "coin"),
  1125. ("Size", "size"),
  1126. ("Entry", "entry_px"),
  1127. ("Pos Val", "position_value"),
  1128. ("uPnL", "unrealized_pnl"),
  1129. ("ROE", "roe"),
  1130. ("Liq", "liq"),
  1131. ("Lev", "lev"),
  1132. ],
  1133. position_rows,
  1134. ),
  1135. ]
  1136. )
  1137. return "\n".join(lines)
  1138. def render_spot_balances(data: dict[str, Any]) -> str:
  1139. rows = [
  1140. {
  1141. "coin": item["coin"],
  1142. "total": _compact_number(item["total"]),
  1143. "hold": _compact_number(item["hold"]),
  1144. "entry_ntl": _compact_number(item["entry_ntl"]),
  1145. }
  1146. for item in data["balances"]
  1147. ]
  1148. return "\n".join(
  1149. [
  1150. f"User: {data['user']}",
  1151. f"Balances returned: {len(data['balances'])} of {data['count']}",
  1152. "",
  1153. _render_table(
  1154. [
  1155. ("Coin", "coin"),
  1156. ("Total", "total"),
  1157. ("Hold", "hold"),
  1158. ("Entry Ntl", "entry_ntl"),
  1159. ],
  1160. rows,
  1161. ),
  1162. ]
  1163. )
  1164. def render_fills(data: dict[str, Any]) -> str:
  1165. rows = [
  1166. {
  1167. "time": _format_timestamp_ms(item["time"]),
  1168. "coin": item["coin"],
  1169. "dir": item["dir"],
  1170. "px": _format_price(item["px"]),
  1171. "sz": _compact_number(item["sz"]),
  1172. "closed_pnl": _compact_number(item["closed_pnl"]),
  1173. "fee": f"{_compact_number(item['fee'])} {item['fee_token'] or ''}".strip(),
  1174. }
  1175. for item in data["fills"]
  1176. ]
  1177. lines = [
  1178. f"User: {data['user']}",
  1179. f"Aggregate by time: {data['aggregate_by_time']}",
  1180. f"Fills returned: {len(data['fills'])} of {data['count']}",
  1181. "",
  1182. _render_table(
  1183. [
  1184. ("Time", "time"),
  1185. ("Coin", "coin"),
  1186. ("Dir", "dir"),
  1187. ("Px", "px"),
  1188. ("Sz", "sz"),
  1189. ("Closed PnL", "closed_pnl"),
  1190. ("Fee", "fee"),
  1191. ],
  1192. rows,
  1193. ),
  1194. ]
  1195. return "\n".join(lines)
  1196. def render_orders(data: dict[str, Any]) -> str:
  1197. rows = [
  1198. {
  1199. "time": _format_timestamp_ms(item["timestamp"]),
  1200. "coin": item["coin"],
  1201. "side": item["side"],
  1202. "limit_px": _format_price(item["limit_px"]),
  1203. "size": _compact_number(item["size"]),
  1204. "status": item["status"],
  1205. "oid": item["oid"] or "-",
  1206. }
  1207. for item in data["orders"]
  1208. ]
  1209. return "\n".join(
  1210. [
  1211. f"User: {data['user']}",
  1212. f"Orders returned: {len(data['orders'])} of {data['count']}",
  1213. "",
  1214. _render_table(
  1215. [
  1216. ("Time", "time"),
  1217. ("Coin", "coin"),
  1218. ("Side", "side"),
  1219. ("Px", "limit_px"),
  1220. ("Sz", "size"),
  1221. ("Status", "status"),
  1222. ("OID", "oid"),
  1223. ],
  1224. rows,
  1225. ),
  1226. ]
  1227. )
  1228. def render_review(data: dict[str, Any]) -> str:
  1229. summary = data["summary"]
  1230. coin_rows = [
  1231. {
  1232. "coin": item["coin"],
  1233. "fills": item["fill_count"],
  1234. "net": _compact_number(item["net_after_fees"]),
  1235. "win_rate": _format_percent(item["win_rate_pct"]),
  1236. "trend": _format_percent(item["market_context"].get("price_change_pct")),
  1237. "funding": _format_fraction_percent(item["market_context"].get("average_funding_rate")),
  1238. "bias": item["open_bias"],
  1239. }
  1240. for item in data["coin_reviews"]
  1241. ]
  1242. recent_rows = [
  1243. {
  1244. "time": _format_timestamp_ms(item["time"]),
  1245. "coin": item["coin"],
  1246. "dir": item["dir"],
  1247. "px": _format_price(item["px"]),
  1248. "sz": _compact_number(item["sz"]),
  1249. "closed_pnl": _compact_number(item["closed_pnl"]),
  1250. "fee": f"{_compact_number(item['fee'])} {item['fee_token'] or ''}".strip(),
  1251. }
  1252. for item in data["recent_fills"]
  1253. ]
  1254. lines = [
  1255. f"User: {data['user']}",
  1256. f"Review window: {data['hours']} hours",
  1257. f"Coin filter: {data['coin_filter'] or 'all traded coins'}",
  1258. f"Fills analyzed: {summary['fill_count']}",
  1259. f"Unique coins: {summary['unique_coins']}",
  1260. f"Realized PnL: {_compact_number(summary['realized_pnl'])}",
  1261. f"Fees: {_compact_number(summary['total_fees'])}",
  1262. f"Net after fees: {_compact_number(summary['net_after_fees'])}",
  1263. f"Win rate: {_format_percent(summary['win_rate_pct'])}",
  1264. ]
  1265. if data["findings"]:
  1266. lines.extend(["", "Findings"])
  1267. for finding in data["findings"]:
  1268. lines.append(f"- {finding}")
  1269. if coin_rows:
  1270. lines.extend(
  1271. [
  1272. "",
  1273. "Coin Breakdown",
  1274. _render_table(
  1275. [
  1276. ("Coin", "coin"),
  1277. ("Fills", "fills"),
  1278. ("Net", "net"),
  1279. ("Win Rate", "win_rate"),
  1280. ("Trend", "trend"),
  1281. ("Funding", "funding"),
  1282. ("Bias", "bias"),
  1283. ],
  1284. coin_rows,
  1285. ),
  1286. ]
  1287. )
  1288. if recent_rows:
  1289. lines.extend(
  1290. [
  1291. "",
  1292. "Recent Fills",
  1293. _render_table(
  1294. [
  1295. ("Time", "time"),
  1296. ("Coin", "coin"),
  1297. ("Dir", "dir"),
  1298. ("Px", "px"),
  1299. ("Sz", "sz"),
  1300. ("Closed PnL", "closed_pnl"),
  1301. ("Fee", "fee"),
  1302. ],
  1303. recent_rows,
  1304. ),
  1305. ]
  1306. )
  1307. return "\n".join(lines)
  1308. def render_export(data: dict[str, Any]) -> str:
  1309. summary = data["summary"]
  1310. return "\n".join(
  1311. [
  1312. f"Coin: {data['coin']}",
  1313. f"Interval: {data['interval']}",
  1314. f"Hours: {data['hours']}",
  1315. f"Schema: {data['schema_version']}",
  1316. f"Output: {data['output_path']}",
  1317. f"Candles: {summary['candle_count']}",
  1318. f"Funding samples: {summary['funding_count']}",
  1319. f"Window open -> close: {_format_price(summary.get('window_open'))} -> {_format_price(summary.get('window_close'))}",
  1320. f"Price change: {_format_percent(summary.get('price_change_pct'))}",
  1321. f"Average funding: {_format_fraction_percent(summary.get('average_funding_rate'))}",
  1322. ]
  1323. )
  1324. def _add_json_flag(parser: argparse.ArgumentParser) -> None:
  1325. parser.add_argument("--json", action="store_true", help="Print raw JSON output")
  1326. def build_parser() -> argparse.ArgumentParser:
  1327. parser = argparse.ArgumentParser(description="Hyperliquid CLI Tool for Hermes Agent")
  1328. subparsers = parser.add_subparsers(dest="command", required=True)
  1329. dexs = subparsers.add_parser("dexs", help="List available perpetual dexs")
  1330. _add_json_flag(dexs)
  1331. dexs.set_defaults(func=run_dexs, renderer=render_dexs)
  1332. markets = subparsers.add_parser("markets", help="List perpetual market contexts")
  1333. markets.add_argument("--dex", default="", help="Perp dex name; empty means first perp dex")
  1334. markets.add_argument("--limit", type=int, default=20, help="Rows to display; 0 means all")
  1335. markets.add_argument(
  1336. "--sort",
  1337. choices=["volume", "oi", "funding_abs", "change_abs", "name"],
  1338. default="volume",
  1339. help="Sort mode",
  1340. )
  1341. _add_json_flag(markets)
  1342. markets.set_defaults(func=run_markets, renderer=render_markets)
  1343. spots = subparsers.add_parser("spots", help="List spot market contexts")
  1344. spots.add_argument("--limit", type=int, default=20, help="Rows to display; 0 means all")
  1345. spots.add_argument(
  1346. "--sort",
  1347. choices=["volume", "change_abs", "name"],
  1348. default="volume",
  1349. help="Sort mode",
  1350. )
  1351. _add_json_flag(spots)
  1352. spots.set_defaults(func=run_spots, renderer=render_spots)
  1353. candles = subparsers.add_parser("candles", help="Fetch candle history for a market")
  1354. candles.add_argument("coin", help='Coin name, e.g. "BTC" or "PURR/USDC" or "mydex:BTC"')
  1355. candles.add_argument("--interval", default="1h", help="Candle interval, e.g. 1m, 15m, 1h, 4h, 1d")
  1356. candles.add_argument("--hours", type=float, default=24.0, help="Lookback window in hours")
  1357. candles.add_argument("--limit", type=int, default=20, help="Rows to display; 0 means all")
  1358. _add_json_flag(candles)
  1359. candles.set_defaults(func=run_candles, renderer=render_candles)
  1360. funding = subparsers.add_parser("funding", help="Fetch funding history for a perp market")
  1361. funding.add_argument("coin", help='Coin name, e.g. "BTC" or "mydex:COIN"')
  1362. funding.add_argument("--hours", type=float, default=72.0, help="Lookback window in hours")
  1363. funding.add_argument("--limit", type=int, default=20, help="Rows to display; 0 means all")
  1364. _add_json_flag(funding)
  1365. funding.set_defaults(func=run_funding, renderer=render_funding)
  1366. l2 = subparsers.add_parser("l2", help="Inspect the current L2 book for a market")
  1367. l2.add_argument("coin", help='Coin name, e.g. "BTC" or "PURR/USDC"')
  1368. l2.add_argument("--levels", type=int, default=10, help="Levels per side to display")
  1369. l2.add_argument("--n-sig-figs", type=int, default=None, help="Optional server-side book aggregation")
  1370. l2.add_argument("--mantissa", type=int, default=None, help="Optional mantissa when using nSigFigs")
  1371. _add_json_flag(l2)
  1372. l2.set_defaults(func=run_l2, renderer=render_l2)
  1373. state = subparsers.add_parser("state", help="Inspect a user's perp account state")
  1374. state.add_argument("user", nargs="?", default="", help=f"Optional address; falls back to ${DEFAULT_USER_ENV}")
  1375. state.add_argument("--dex", default="", help="Perp dex name; empty means first perp dex")
  1376. _add_json_flag(state)
  1377. state.set_defaults(func=run_state, renderer=render_state)
  1378. spot_balances = subparsers.add_parser("spot-balances", help="Inspect a user's spot token balances")
  1379. spot_balances.add_argument("user", nargs="?", default="", help=f"Optional address; falls back to ${DEFAULT_USER_ENV}")
  1380. spot_balances.add_argument("--limit", type=int, default=20, help="Rows to display; 0 means all")
  1381. _add_json_flag(spot_balances)
  1382. spot_balances.set_defaults(func=run_spot_balances, renderer=render_spot_balances)
  1383. fills = subparsers.add_parser("fills", help="Inspect a user's recent fills")
  1384. fills.add_argument("user", nargs="?", default="", help=f"Optional address; falls back to ${DEFAULT_USER_ENV}")
  1385. fills.add_argument("--hours", type=float, default=None, help="Optional time window; uses userFillsByTime")
  1386. fills.add_argument("--limit", type=int, default=20, help="Rows to display; 0 means all")
  1387. fills.add_argument(
  1388. "--aggregate-by-time",
  1389. action="store_true",
  1390. help="Aggregate partial fills when the API supports it",
  1391. )
  1392. _add_json_flag(fills)
  1393. fills.set_defaults(func=run_fills, renderer=render_fills)
  1394. orders = subparsers.add_parser("orders", help="Inspect a user's historical orders")
  1395. orders.add_argument("user", nargs="?", default="", help=f"Optional address; falls back to ${DEFAULT_USER_ENV}")
  1396. orders.add_argument("--limit", type=int, default=20, help="Rows to display; 0 means all")
  1397. _add_json_flag(orders)
  1398. orders.set_defaults(func=run_orders, renderer=render_orders)
  1399. review = subparsers.add_parser("review", help="Generate a lightweight post-trade review from recent fills")
  1400. review.add_argument("user", nargs="?", default="", help=f"Optional address; falls back to ${DEFAULT_USER_ENV}")
  1401. review.add_argument("--coin", default="", help="Optional exact coin filter, e.g. BTC or PURR/USDC")
  1402. review.add_argument("--hours", type=float, default=72.0, help="Lookback window in hours")
  1403. review.add_argument("--fills", type=int, default=50, help="Maximum fills to analyze")
  1404. review.add_argument("--recent", type=int, default=10, help="Recent fills to display in the review")
  1405. review.add_argument("--interval", default="1h", help="Candle interval for market context")
  1406. review.add_argument(
  1407. "--aggregate-by-time",
  1408. action="store_true",
  1409. help="Aggregate partial fills when the API supports it",
  1410. )
  1411. _add_json_flag(review)
  1412. review.set_defaults(func=run_review, renderer=render_review)
  1413. export = subparsers.add_parser("export", help="Export normalized candles and funding history to a JSON file")
  1414. export.add_argument("coin", help='Coin name, e.g. "BTC" or "PURR/USDC" or "mydex:BTC"')
  1415. export.add_argument("--interval", default="1h", help="Candle interval for the exported dataset")
  1416. export.add_argument("--hours", type=float, default=168.0, help="Lookback window in hours")
  1417. export.add_argument("--end-time-ms", type=int, default=None, help="Optional fixed end time for reproducible exports")
  1418. export.add_argument("--output", default="", help="Path to the JSON export file")
  1419. _add_json_flag(export)
  1420. export.set_defaults(func=run_export, renderer=render_export)
  1421. return parser
  1422. def main(argv: Optional[list[str]] = None) -> int:
  1423. parser = build_parser()
  1424. args = parser.parse_args(argv)
  1425. payload = args.func(args)
  1426. if args.json:
  1427. print(json.dumps(payload, indent=2))
  1428. else:
  1429. print(args.renderer(payload))
  1430. return 0
  1431. if __name__ == "__main__":
  1432. raise SystemExit(main())