forked from nambo35/Hyperliquid-Data-Layer-API
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
1476 lines (1271 loc) · 58.1 KB
/
api.py
File metadata and controls
1476 lines (1271 loc) · 58.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
🌙 Moon Dev's API Handler
Built with love by Moon Dev 🚀
API Documentation: https://moondev.com/docs
Available Endpoints:
-------------------
CORE:
- /health - Service health check (no auth)
- /api/liquidations/{timeframe}.json - Liquidation data (10m, 1h, 4h, 12h, 24h, 2d, 7d, 14d, 30d)
- /api/liquidations/stats.json - Aggregated liquidation stats
- /api/positions.json - Top 50 longs/shorts across ALL symbols (updates every 1s)
- /api/positions/all.json - All 148 symbols with top 50 positions each (500KB, updates every 60s)
- /api/whales.json - Recent whale trades ($25k+)
- /api/whale_addresses.txt - Plain text whale address list
- /api/events.json - Real-time blockchain events
- /api/contracts.json - Contract registry with metadata
TICK DATA:
- /api/ticks/stats.json - Collection stats and summary
- /api/ticks/latest.json - Current prices for all symbols
- /api/ticks/{symbol}_{timeframe}.json - Historical ticks (symbols: btc, eth, hype, sol, xrp)
(timeframes: 10m, 1h, 4h, 24h, 7d)
ORDER FLOW & TRADES (tracking: BTC, ETH, HYPE, SOL, XRP):
- /api/trades.json - Recent 500 trades (real-time)
- /api/large_trades.json - Large trades >$100k (24h)
- /api/orderflow.json - Order flow imbalance by timeframe + per coin
- /api/orderflow/stats.json - Service stats (uptime, trades/sec)
- /api/imbalance/5m.json - 5-min buy/sell imbalance
- /api/imbalance/15m.json - 15-min imbalance
- /api/imbalance/1h.json - 1-hour imbalance
- /api/imbalance/4h.json - 4-hour imbalance
- /api/imbalance/24h.json - 24-hour imbalance
SMART MONEY:
- /api/smart_money/rankings.json - Top 100 smart + Bottom 100 dumb money
- /api/smart_money/leaderboard.json - Top 50 performers with details
- /api/smart_money/signals_10m.json - Trading signals (10 min)
- /api/smart_money/signals_1h.json - Trading signals (1 hour)
- /api/smart_money/signals_24h.json - Trading signals (24 hour)
MULTI-EXCHANGE LIQUIDATIONS:
- /api/all_liquidations/{timeframe}.json - Combined liquidations from ALL exchanges
- /api/all_liquidations/stats.json - Combined stats across all exchanges
- /api/binance_liquidations/{timeframe}.json - Binance Futures liquidations
- /api/bybit_liquidations/{timeframe}.json - Bybit liquidations
- /api/okx_liquidations/{timeframe}.json - OKX liquidations
(timeframes: 10m, 1h, 4h, 12h, 24h, 2d, 7d, 14d, 30d)
HIP3 LIQUIDATIONS (Stocks, Commodities, Indices, FX):
- /api/hip3_liquidations/{timeframe}.json - HIP3 liquidations (10m, 1h, 24h, 7d)
- /api/hip3_liquidations/stats.json - HIP3 liquidation statistics
Categories: Stocks (TSLA, NVDA, AAPL, etc.), Commodities (GOLD, SILVER, OIL),
Indices (XYZ100), FX (EUR, JPY)
HIP3 MARKET DATA (Multi-Dex: Stocks, Commodities, Indices, FX, Crypto):
- /api/hip3/meta - All 51 symbols from all 4 dexes with current prices
- /api/hip3_ticks/stats.json - Tick collector stats with dex breakdown
- /api/hip3_ticks/{dex}_{ticker}.json - Individual tick data (e.g., xyz_tsla.json, hyna_btc.json)
Dexes: xyz (27 stocks/commodities/FX), flx (7), hyna (12 crypto), km (5 US indices)
HYPERLIQUID USER DATA:
- get_user_positions(address) - Get positions via Hyperliquid API (direct)
MOON DEV USER API (from local node - FAST!):
- /api/user/{address}/positions - Get positions via Moon Dev API
- /api/user/{address}/fills - Get historical fills (limit: 100-2000, -1 for all)
MARKET DATA (replaces Hyperliquid rate-limited calls!):
- /api/prices - All 224 coin prices + funding rates + open interest
- /api/price/{coin} - Quick price for single coin (best bid/ask/mid/spread)
- /api/orderbook/{coin} - Full L2 orderbook (~20 levels each side)
- /api/account/{address} - Full account state (positions, margin, withdrawable)
- /api/fills/{address} - Trade fills in Hyperliquid-compatible format
- /api/candles/{coin} - OHLCV candles (1m, 5m, 15m, 1h, 4h, 1d)
HLP (HYPERLIQUIDITY PROVIDER) DATA:
- /api/hlp/positions - All 7 HLP strategy positions + combined net exposure
(optional: ?include_strategies=false for summary only)
- /api/hlp/trades - Historical HLP trade fills (5,000+ collected)
- /api/hlp/trades/stats - Trade volume/fee statistics
- /api/hlp/positions/history - Position snapshots over time
- /api/hlp/liquidators - Liquidator activation events
- /api/hlp/deltas - Net exposure changes over time
- /api/hlp/sentiment - THE BIG ONE! Net delta with z-scores and signals
- /api/hlp/liquidators/status - Real-time liquidator status (active/idle + PnL)
- /api/hlp/market-maker - Strategy B tracker for BTC/ETH/SOL
- /api/hlp/timing - Hourly/session profitability analysis
- /api/hlp/correlation - Delta-price correlation by coin
Authentication:
--------------
- Header (recommended): X-API-Key: YOUR_API_KEY
- Query param: ?api_key=YOUR_API_KEY
Rate Limits: 3,600 requests/min | Data updates every 30 seconds | 60-day retention
Need an API key? https://moondev.com
"""
import os
import requests
from datetime import datetime
from dotenv import load_dotenv
load_dotenv()
class MoonDevAPI:
"""🌙 Moon Dev's API Client"""
def __init__(self, api_key=None, base_url="https://api.moondev.com"):
self.api_key = api_key or os.getenv('MOONDEV_API_KEY')
self.base_url = base_url
self.headers = {'X-API-Key': self.api_key} if self.api_key else {}
self.session = requests.Session()
def _get(self, endpoint, auth_required=True):
"""Make GET request to API"""
url = f"{self.base_url}{endpoint}"
headers = self.headers if auth_required else {}
response = self.session.get(url, headers=headers, timeout=30)
response.raise_for_status()
return response
# ==================== HEALTH ====================
def health(self):
"""Check API health status (no auth required)"""
response = self._get("/health", auth_required=False)
return response.json()
# ==================== LIQUIDATIONS ====================
def get_liquidations(self, timeframe="1h"):
"""Get liquidation data for specified timeframe (10m, 1h, 4h, 12h, 24h, 2d, 7d, 14d, 30d)"""
response = self._get(f"/api/liquidations/{timeframe}.json")
return response.json()
def get_liquidation_stats(self):
"""Get aggregated liquidation stats across all timeframes"""
response = self._get("/api/liquidations/stats.json")
return response.json()
# ==================== POSITIONS ====================
def get_positions(self):
"""Get large positions near liquidation ($200k+) - top 50 across ALL symbols"""
response = self._get("/api/positions.json")
return response.json()
def get_all_positions(self):
"""Get ALL positions for all 148 symbols - top 50 longs/shorts per symbol
Returns dict with symbols key containing all symbol data.
Access specific symbol: data['symbols']['BTC'], data['symbols']['HYPE'], etc.
"""
response = self._get("/api/positions/all.json")
return response.json()
# ==================== WHALES ====================
def get_whales(self):
"""Get recent whale trades ($25k+)"""
response = self._get("/api/whales.json")
return response.json()
def get_whale_addresses(self):
"""Get plain text list of known whale addresses"""
response = self._get("/api/whale_addresses.txt")
addresses = response.text.strip().split('\n')
return [addr.strip() for addr in addresses if addr.strip()]
def get_buyers(self):
"""Get recent $5k+ buyers on HYPE/SOL/XRP/ETH (buyers only, no sells)"""
response = self._get("/api/buyers.json")
return response.json()
def get_depositors(self):
"""Get all Hyperliquid depositors - canonical list of every address that bridged USDC"""
response = self._get("/api/depositors.json")
return response.json()
# ==================== EVENTS ====================
def get_events(self):
"""Get real-time blockchain events (Transfers, Swaps, Deposits, etc.)"""
response = self._get("/api/events.json")
return response.json()
# ==================== CONTRACTS ====================
def get_contracts(self):
"""Get contract registry with metadata and activity tracking"""
response = self._get("/api/contracts.json")
return response.json()
# ==================== TICK DATA ====================
def get_tick_stats(self):
"""Get tick data collection stats and summary"""
response = self._get("/api/ticks/stats.json")
return response.json()
def get_tick_latest(self):
"""Get latest prices for all symbols"""
response = self._get("/api/ticks/latest.json")
return response.json()
def get_ticks(self, symbol="BTC", duration="1h", limit=10000, start_time=None, end_time=None):
"""
Get historical tick data for any of 80 tracked symbols.
Args:
symbol: Any tracked symbol (BTC, ETH, SOL, DOGE, FARTCOIN, TRUMP, etc.)
Use get_candle_symbols() to see all 80 available symbols
duration: Time window - 10m, 1h, 4h, 24h, 7d (default: 1h)
limit: Max ticks to return (default: 10000)
start_time: Start time in Unix ms (optional, overrides duration)
end_time: End time in Unix ms (optional)
Returns:
dict with:
- symbol: Symbol queried
- duration: Time window
- tick_count: Number of ticks returned
- latest_price: Most recent price
- ticks: List of tick objects [{t, p, dt}, ...]
"""
params = [f"duration={duration}", f"limit={limit}"]
if start_time is not None:
params.append(f"startTime={start_time}")
if end_time is not None:
params.append(f"endTime={end_time}")
query = "?" + "&".join(params)
response = self._get(f"/api/ticks/{symbol.upper()}{query}")
return response.json()
# ==================== ORDER FLOW & TRADES ====================
def get_trades(self):
"""Get recent 500 trades (real-time)"""
response = self._get("/api/trades.json")
return response.json()
def get_large_trades(self):
"""Get large trades >$100k (24h)"""
response = self._get("/api/large_trades.json")
return response.json()
def get_orderflow(self):
"""Get order flow imbalance by timeframe + per coin"""
response = self._get("/api/orderflow.json")
return response.json()
def get_orderflow_stats(self):
"""Get order flow service stats (uptime, trades/sec)"""
response = self._get("/api/orderflow/stats.json")
return response.json()
def get_imbalance(self, timeframe="1h"):
"""Get buy/sell imbalance (5m, 15m, 1h, 4h, 24h)"""
response = self._get(f"/api/imbalance/{timeframe}.json")
return response.json()
# ==================== USER POSITIONS (HYPERLIQUID) ====================
def get_user_positions(self, address):
"""
Get all open positions for a specific Hyperliquid wallet address.
Args:
address: Hyperliquid wallet address (e.g., "0x...")
Returns:
dict with 'assetPositions' list and 'marginSummary'
Example response structure:
{
'assetPositions': [
{
'position': {
'coin': 'BTC',
'szi': '0.5', # size (positive=long, negative=short)
'entryPx': '45000.0',
'positionValue': '22500.0',
'unrealizedPnl': '500.0',
'liquidationPx': '40000.0',
'leverage': {'value': 10}
}
}
],
'marginSummary': {
'accountValue': '50000.0',
'totalNtlPos': '22500.0'
}
}
"""
url = "https://api.hyperliquid.xyz/info"
payload = {"type": "clearinghouseState", "user": address}
print(f"📡 Moon Dev: Fetching positions for {address[:6]}...{address[-4:]}")
response = self.session.post(url, json=payload, timeout=30)
response.raise_for_status()
return response.json()
# ==================== MOON DEV USER API (LOCAL NODE) ====================
def get_user_positions_api(self, address):
"""
Get all open positions for a Hyperliquid wallet via Moon Dev's API.
This uses Moon Dev's local node data - faster and includes additional processing.
Args:
address: Hyperliquid wallet address (e.g., "0x...")
Returns:
dict with positions, margin summary, and account details
"""
response = self._get(f"/api/user/{address}/positions")
return response.json()
def get_user_fills(self, address, limit=100):
"""
Get historical fills/trades for a Hyperliquid wallet via Moon Dev's API.
This uses Moon Dev's local node data - scans hourly fill archives.
Extremely fast: ~300ms even for 32,000+ fills!
Args:
address: Hyperliquid wallet address (e.g., "0x...")
limit: Number of fills to return (default: 100, max: 2000, use -1 for ALL fills)
Returns:
dict with:
- fills: list of fill objects with trade details
- total: total number of fills found
- limit: limit that was applied
- address: wallet address queried
Example fill object:
{
'coin': 'BTC',
'px': '45000.0', # execution price
'sz': '0.1', # size
'side': 'B', # B=Buy, S=Sell
'time': 1704067200000, # timestamp ms
'startPosition': '0.5', # position before
'dir': 'Open Long', # direction description
'closedPnl': '0', # realized PnL if closing
'hash': 'abc123...', # transaction hash
'tid': 12345, # trade ID
'fee': '1.5' # fee paid
}
"""
params = f"?limit={limit}" if limit != 100 else ""
response = self._get(f"/api/user/{address}/fills{params}")
return response.json()
# ==================== MARKET DATA (NO RATE LIMITS!) ====================
def get_prices(self):
"""
Get all coin prices, funding rates, and open interest.
This replaces Hyperliquid's rate-limited metaAndAssetCtxs call.
No rate limits - goes through Moon Dev's node!
Returns:
dict with:
- timestamp: When data was fetched
- count: Number of coins (224)
- prices: Dict of coin -> price (e.g., {"BTC": "93200.0", "ETH": "3175.0"})
- funding_rates: Dict of coin -> funding rate
- open_interest: Dict of coin -> open interest
"""
response = self._get("/api/prices")
return response.json()
def get_price(self, coin):
"""
Get quick price for a single coin.
Args:
coin: Coin symbol (e.g., "BTC", "ETH", "SOL")
Returns:
dict with:
- coin: Symbol
- timestamp: When data was fetched
- best_bid: Best bid price
- best_ask: Best ask price
- best_bid_size: Size at best bid
- best_ask_size: Size at best ask
- mid_price: (bid + ask) / 2
- spread: ask - bid
- spread_bps: Spread in basis points
"""
response = self._get(f"/api/price/{coin}")
return response.json()
def get_orderbook(self, coin):
"""
Get full L2 orderbook for a coin (~20 levels each side).
This replaces Hyperliquid's rate-limited l2Book call.
No rate limits - goes through Moon Dev's node!
Args:
coin: Coin symbol (e.g., "BTC", "ETH", "SOL")
Returns:
dict with:
- coin: Symbol
- timestamp: When data was fetched
- levels: [[bids], [asks]] - bids sorted high->low, asks sorted low->high
Each level: {"px": price, "sz": size, "n": order_count}
- best_bid: Best bid price
- best_ask: Best ask price
- mid_price: (bid + ask) / 2
- spread: ask - bid
- spread_bps: Spread in basis points
- bid_depth: Number of bid levels
- ask_depth: Number of ask levels
"""
response = self._get(f"/api/orderbook/{coin}")
return response.json()
def get_account(self, address):
"""
Get full account state for any Hyperliquid wallet.
This replaces Hyperliquid's rate-limited clearinghouseState call.
No rate limits - goes through Moon Dev's node!
Args:
address: Wallet address (e.g., "0x...")
Returns:
dict with:
- address: Wallet address
- timestamp: When data was fetched
- marginSummary: Account value, total position, margin used
- crossMarginSummary: Cross margin details
- assetPositions: List of all open positions with full details
- withdrawable: Available to withdraw
"""
response = self._get(f"/api/account/{address}")
return response.json()
def get_fills(self, address, limit=100):
"""
Get trade fills for any wallet in Hyperliquid-compatible format.
This is the DROP-IN REPLACEMENT for Hyperliquid's userFills call.
Uses Moon Dev's local node - faster and no rate limits!
Args:
address: Wallet address (e.g., "0x...")
limit: Number of fills to return (default: 100)
Returns:
list of fill objects in Hyperliquid format:
[
{
"tid": 293951512222, # Trade ID
"time": 1768392000752, # Timestamp (ms)
"coin": "BTC", # Symbol
"side": "B" or "A", # B=Buy, A=Sell (Ask)
"px": "94000.0", # Price
"sz": "0.1", # Size
"closedPnl": "100.50", # Realized PnL
"dir": "Open Long", # Direction description
"crossed": false, # Whether crossed the spread
"fee": "1.5", # Fee paid
"oid": 293951512222 # Order ID
}
]
"""
params = f"?limit={limit}" if limit != 100 else ""
response = self._get(f"/api/fills/{address}{params}")
return response.json()
def get_candle_symbols(self):
"""
Get list of all 80 tracked symbols available for candles/ticks.
Symbols are selected based on $750k+ daily volume.
Returns:
dict with:
- symbols: List of symbol strings (e.g., ["AAVE", "BTC", "DOGE", ...])
- count: Number of tracked symbols (80)
- volume_threshold: Minimum daily volume for inclusion ($750k)
- intervals: Available candle intervals (1m, 5m, 15m, 1h, 4h, 1d)
- symbol_details: Dict with per-symbol metadata
"""
response = self._get("/api/candles/symbols")
return response.json()
def get_candles(self, coin, interval="5m", start_time=None, end_time=None):
"""
Get OHLCV candles for any of 80 tracked symbols in Hyperliquid-compatible format.
80 symbols tracked including majors, DeFi, L2s, and memes.
Use get_candle_symbols() to see full list.
Categories:
- Major: BTC, ETH, SOL, XRP, DOGE, LTC, ADA, DOT, LINK, AVAX, BNB...
- DeFi: AAVE, UNI, CRV, LDO, PENDLE, JUP, MORPHO, ONDO, ENA...
- L2/Alt L1: ARB, OP, SUI, SEI, APT, NEAR, TON, TIA, MOVE, BERA...
- Memes: HYPE, FARTCOIN, PUMP, WIF, POPCAT, PENGU, TRUMP...
Args:
coin: Any tracked symbol (use get_candle_symbols() for full list)
interval: Candle interval - 1m, 5m, 15m, 1h, 4h, 1d (default: 5m)
start_time: Start timestamp in ms (optional)
end_time: End timestamp in ms (optional)
Returns:
list of candle objects:
[
{
"t": 1767787200000, # Open time (ms)
"T": 1767790799999, # Close time (ms)
"s": "BTC", # Symbol
"i": "5m", # Interval
"o": "92194.5", # Open price
"h": "92232.5", # High price
"l": "92049.5", # Low price
"c": "92056.5", # Close price
"v": "0", # Volume (from ticks, may be 0)
"n": 239 # Number of price updates
}
]
"""
params = [f"interval={interval}"]
if start_time is not None:
params.append(f"startTime={start_time}")
if end_time is not None:
params.append(f"endTime={end_time}")
query = "?" + "&".join(params) if params else ""
response = self._get(f"/api/candles/{coin}{query}")
return response.json()
# ==================== HLP (HYPERLIQUIDITY PROVIDER) ====================
def get_hlp_positions(self, include_strategies=True):
"""
Get all HLP (HyperLiquidity Provider) positions across all 7 strategies.
This endpoint provides a comprehensive view of Hyperliquid's market-making
strategies including combined net exposure calculations.
Args:
include_strategies: If True, include individual strategy breakdowns.
If False, return summary only (faster response).
Returns:
dict with:
- summary: Total account value (~$210M), position counts, net exposure
- combined_positions: NET positions across all strategies (longs - shorts)
- strategies: Individual HLP strategy details (if include_strategies=True)
HLP Strategies tracked:
- HLP Strategy A (main market maker)
- HLP Strategy B (secondary market maker)
- HLP Liquidator 1-4 (liquidation bots)
- HLP Strategy X (experimental)
Example combined_position:
{
'coin': 'BTC',
'net_size': 10.5, # positive=net long, negative=net short
'net_value': 500000.0, # USD value of net position
'long_strategies': ['HLP Strategy A'],
'short_strategies': ['HLP Strategy B'],
'total_long': 15.0,
'total_short': 4.5
}
"""
params = "" if include_strategies else "?include_strategies=false"
response = self._get(f"/api/hlp/positions{params}")
return response.json()
def get_hlp_trades(self, limit=100):
"""
Get historical HLP trade fills across all strategies.
Args:
limit: Number of trades to return (default: 100)
Returns:
dict with:
- trades: List of trade fill objects
- total: Total trades available
- strategies: Which strategies have trades
"""
params = f"?limit={limit}" if limit != 100 else ""
response = self._get(f"/api/hlp/trades{params}")
return response.json()
def get_hlp_trade_stats(self):
"""
Get HLP trade volume and fee statistics.
Returns:
dict with:
- total_trades: Total number of trades collected
- total_volume: Total USD volume traded
- total_fees: Total fees paid
- date_range: First and last trade timestamps
- by_strategy: Volume breakdown by strategy
- by_coin: Volume breakdown by coin
"""
response = self._get("/api/hlp/trades/stats")
return response.json()
def get_hlp_position_history(self, hours=24):
"""
Get historical position snapshots over time.
Args:
hours: Number of hours of history (default: 24)
Returns:
dict with:
- snapshots: List of position snapshots with timestamps
- interval: Time between snapshots
"""
params = f"?hours={hours}" if hours != 24 else ""
response = self._get(f"/api/hlp/positions/history{params}")
return response.json()
def get_hlp_liquidators(self):
"""
Get HLP liquidator activation events.
Monitors when liquidator accounts become active (non-idle).
Returns:
dict with:
- events: List of liquidator activation events
- liquidators: Current status of each liquidator account
"""
response = self._get("/api/hlp/liquidators")
return response.json()
def get_hlp_deltas(self, hours=24):
"""
Get HLP net exposure (delta) changes over time.
Args:
hours: Number of hours of history (default: 24)
Returns:
dict with:
- deltas: Time series of net exposure values
- current: Current net exposure
- change_24h: 24-hour change in exposure
"""
params = f"?hours={hours}" if hours != 24 else ""
response = self._get(f"/api/hlp/deltas{params}")
return response.json()
def get_hlp_sentiment(self):
"""
Get HLP sentiment indicator - THE BIG ONE!
Returns z-scores showing how positioned HLP is vs historical norms.
Z-score of 2.2 = HLP is 2.2σ more long than usual = retail heavily SHORT.
Returns:
dict with:
- net_delta: Current net exposure
- z_score: Standard deviations from mean
- signal: Human readable signal (e.g., "Retail heavily SHORT")
- percentile: Where current delta falls historically
"""
response = self._get("/api/hlp/sentiment")
return response.json()
def get_hlp_liquidator_status(self):
"""
Get real-time HLP liquidator status.
Shows which liquidators are active/idle and their PnL.
Returns:
dict with liquidator addresses, status (active/idle), and PnL data
"""
response = self._get("/api/hlp/liquidators/status")
return response.json()
def get_hlp_market_maker(self):
"""
Get HLP Strategy B market maker tracker for BTC/ETH/SOL.
Returns:
dict with market maker positions and activity for major coins
"""
response = self._get("/api/hlp/market-maker")
return response.json()
def get_hlp_timing(self):
"""
Get HLP timing analysis - hourly/session profitability.
Returns:
dict with profitability breakdown by hour and trading session
"""
response = self._get("/api/hlp/timing")
return response.json()
def get_hlp_correlation(self):
"""
Get HLP delta-price correlation analysis by coin.
Returns:
dict with correlation data showing how HLP delta relates to price moves
"""
response = self._get("/api/hlp/correlation")
return response.json()
def get_hlp_delta(self):
"""
Get live HLP net delta calculation.
Shows real-time HLP positioning across all vaults.
Polls every 30 seconds, snapshots every 60 seconds.
Returns:
dict with:
- net_delta: Current net exposure (positive=LONG, negative=SHORT)
- long_exposure: Total long exposure in USD
- short_exposure: Total short exposure in USD
- position_count: Number of positions across vaults
- timestamp: Last update time
"""
response = self._get("/api/hlp/delta")
return response.json()
def get_hlp_flips(self):
"""
Get historical HLP flip events (when delta crosses zero).
A flip occurs when HLP's net delta crosses from long to short
or vice versa. Each flip is recorded with BTC/ETH price context.
Returns:
list of flip events:
[
{
"datetime": "2026-01-14T15:30:00Z",
"from_direction": "long",
"to_direction": "short",
"from_delta": 500000,
"to_delta": -200000,
"hold_duration_hours": 4.5,
"btc_price": 95000,
"eth_price": 3300
}
]
"""
response = self._get("/api/hlp/flips")
return response.json()
def get_hlp_flip_stats(self):
"""
Get aggregated HLP flip statistics.
Provides analysis of historical flip patterns including
average hold durations, flip frequency, and performance metrics.
Returns:
dict with:
- total_flips: Number of recorded flips
- avg_hold_duration_hours: Average time between flips
- long_to_short_count: Number of long→short flips
- short_to_long_count: Number of short→long flips
- current_direction: Current HLP direction (long/short)
- current_hold_hours: Hours in current direction
"""
response = self._get("/api/hlp/flip-stats")
return response.json()
# ==================== SMART MONEY ====================
def get_smart_money_rankings(self):
"""Get Top 100 smart money + Bottom 100 dumb money rankings"""
response = self._get("/api/smart_money/rankings.json")
return response.json()
def get_smart_money_leaderboard(self):
"""Get Top 50 performers with details"""
response = self._get("/api/smart_money/leaderboard.json")
return response.json()
def get_smart_money_signals(self, timeframe="1h"):
"""Get smart money trading signals (10m, 1h, 24h)"""
response = self._get(f"/api/smart_money/signals_{timeframe}.json")
return response.json()
# ==================== MULTI-EXCHANGE LIQUIDATIONS ====================
def get_all_liquidations(self, timeframe="1h"):
"""
Get COMBINED liquidation data from ALL exchanges (Hyperliquid, Binance, Bybit, OKX).
Args:
timeframe: 10m, 1h, 4h, 12h, 24h, 2d, 7d, 14d, 30d
Returns:
dict with liquidation events from all exchanges, sorted by USD value
"""
response = self._get(f"/api/all_liquidations/{timeframe}.json")
return response.json()
def get_all_liquidation_stats(self):
"""
Get combined liquidation stats across ALL exchanges.
Returns:
dict with:
- total_count: Total liquidations across all exchanges
- total_volume: Combined USD volume
- by_exchange: Breakdown by exchange (hyperliquid, binance, bybit, okx)
- by_side: Long vs short breakdown
"""
response = self._get("/api/all_liquidations/stats.json")
return response.json()
def get_binance_liquidations(self, timeframe="1h"):
"""
Get Binance Futures liquidation data.
Args:
timeframe: 10m, 1h, 4h, 12h, 24h, 2d, 7d, 14d, 30d
"""
response = self._get(f"/api/binance_liquidations/{timeframe}.json")
return response.json()
def get_bybit_liquidations(self, timeframe="1h"):
"""
Get Bybit liquidation data.
Args:
timeframe: 10m, 1h, 4h, 12h, 24h, 2d, 7d, 14d, 30d
"""
response = self._get(f"/api/bybit_liquidations/{timeframe}.json")
return response.json()
def get_okx_liquidations(self, timeframe="1h"):
"""
Get OKX liquidation data.
Args:
timeframe: 10m, 1h, 4h, 12h, 24h, 2d, 7d, 14d, 30d
"""
response = self._get(f"/api/okx_liquidations/{timeframe}.json")
return response.json()
# ==================== HIP3 LIQUIDATIONS ====================
def get_hip3_liquidations(self, timeframe="1h"):
"""
Get HIP3 liquidation data (Stocks, Commodities, Indices, FX).
HIP3 covers traditional finance assets on Hyperliquid:
- Stocks: TSLA, NVDA, AAPL, META, MSFT, GOOGL, AMZN, AMD, INTC, PLTR,
COIN, HOOD, MSTR, ORCL, MU, NFLX, RIVN, BABA
- Commodities: GOLD, SILVER, COPPER, CL (Oil), NATGAS, URANIUM
- Indices: XYZ100 (Nasdaq proxy)
- FX: EUR, JPY
Args:
timeframe: 10m, 1h, 24h, 7d
Returns:
list of liquidation events with:
- symbol: Asset symbol (TSLA, GOLD, etc.)
- side: 'long' or 'short'
- size: Position size
- price: Liquidation price
- value_usd: USD value of liquidation
- category: 'stocks', 'commodities', 'indices', or 'fx'
- timestamp: Event timestamp
"""
response = self._get(f"/api/hip3_liquidations/{timeframe}.json")
return response.json()
def get_hip3_liquidation_stats(self):
"""
Get HIP3 liquidation statistics.
Returns:
dict with:
- total_count: Total liquidations
- total_volume: Total USD volume liquidated
- long_count: Number of long liquidations
- short_count: Number of short liquidations
- long_volume: USD volume of long liquidations
- short_volume: USD volume of short liquidations
- by_category: Breakdown by category (stocks, commodities, indices, fx)
- by_symbol: Breakdown by individual symbol
- top_symbols: Top symbols by liquidation volume
"""
response = self._get("/api/hip3_liquidations/stats.json")
return response.json()
# ==================== HIP3 MARKET DATA (Multi-Dex) ====================
def get_hip3_meta(self, include_delisted=False):
"""
Get all HIP3 symbols from all 4 dexes with current prices.
51 symbols across 4 dexes:
- xyz (27): Stocks, commodities, FX, indices (TSLA, NVDA, GOLD, EUR, XYZ100)
- flx (7): Stocks, commodities, XMR (XMR, GOLD, SILVER, OIL)
- hyna (12): Crypto (BTC, ETH, HYPE, SOL, FARTCOIN, PUMP)
- km (5): US indices (US500, USTECH, SMALL2000)
Args:
include_delisted: If True, includes delisted symbols (default: False)
Returns:
dict with:
- count: Total number of symbols
- dexes: Dict organized by dex prefix
- symbols: List of all symbol objects with prices
- categories: Breakdown by category (stocks, indices, commodities, fx, crypto)
Symbol format: {dex}:{ticker} (e.g., xyz:TSLA, hyna:BTC, km:US500)
"""
params = "?include_delisted=true" if include_delisted else ""
response = self._get(f"/api/hip3/meta{params}")
return response.json()
def get_hip3_tick_stats(self):
"""
Get HIP3 tick collector statistics with dex breakdown.
Returns:
dict with:
- total_symbols: Total symbols being tracked
- total_ticks: Total ticks collected
- by_dex: Breakdown by dex (xyz, flx, hyna, km)
- by_category: Breakdown by category
- last_update: Last collection timestamp
"""
response = self._get("/api/hip3_ticks/stats.json")
return response.json()
def get_hip3_ticks(self, dex, ticker):
"""
Get raw tick data for a specific HIP3 symbol.
Args:
dex: Dex prefix (xyz, flx, hyna, km)
ticker: Symbol ticker (tsla, btc, gold, us500, etc.) - case insensitive
Returns:
dict/list with tick data for the symbol
Examples:
get_hip3_ticks("xyz", "tsla") # Tesla stock
get_hip3_ticks("xyz", "gold") # Gold commodity
get_hip3_ticks("hyna", "btc") # Bitcoin
get_hip3_ticks("km", "us500") # S&P 500 index
"""
response = self._get(f"/api/hip3_ticks/{dex.lower()}_{ticker.lower()}.json")
return response.json()
# ==================== TEST SUITE ====================
def test_all():
"""🌙 Moon Dev API Mass Test Suite"""
print("=" * 60)
print("🌙 Moon Dev API Mass Test Suite 🚀")
print("=" * 60)
api = MoonDevAPI()
if not api.api_key:
print("❌ No API key found! Set MOONDEV_API_KEY in .env")
return
print(f"✅ API Key loaded (ends with ...{api.api_key[-4:]})")
print()
# ==================== 1. HEALTH CHECK ====================
print("=" * 60)
print("🏥 1. HEALTH CHECK")
print("=" * 60)
try:
health = api.health()
print(f"✅ Health: {health}")
except Exception as e:
print(f"❌ Health check failed: {e}")
print()
# ==================== 2. LIQUIDATIONS ====================
print("=" * 60)
print("💥 2. LIQUIDATION DATA")
print("=" * 60)
timeframes = ["10m", "1h", "4h", "24h"]
for tf in timeframes:
try:
data = api.get_liquidations(tf)
if isinstance(data, dict):
stats = data.get('stats', data)