gionuibk commited on
Commit
3dffdfd
·
verified ·
1 Parent(s): 55ff9e2

Upload adapters/history_loader.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. adapters/history_loader.py +72 -0
adapters/history_loader.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import requests
3
+ import time
4
+ from datetime import datetime
5
+ from decimal import Decimal
6
+ from nautilus_trader.common.enums import LogColor
7
+
8
+ class HyperliquidHistoryLoader:
9
+ """
10
+ Fetches historical candles from HyperLiquid REST API to hydrate Strategy buffers.
11
+ Eliminates "Warmup" time on restart.
12
+ """
13
+ BASE_URL = "https://api.hyperliquid.xyz/info"
14
+
15
+ @staticmethod
16
+ def fetch_candles(instrument_id: str, interval_mins: int = 1, lookback: int = 100):
17
+ """
18
+ Fetch last N candles properly.
19
+ Returns list of dicts: {'close': float, 'high': float, ...} sorted by time.
20
+ """
21
+ # Parse Symbol (e.g. ETH-USDC-PERP -> ETH)
22
+ # Hyperliquid uses "ETH" for PERP.
23
+ symbol = instrument_id.split("-")[0]
24
+
25
+ # Calculate Start Time (ms)
26
+ # We fetch a bit more than needed to be safe
27
+ now_ms = int(time.time() * 1000)
28
+ start_time = now_ms - (lookback * interval_mins * 60 * 1000 * 2)
29
+
30
+ payload = {
31
+ "type": "candleSnapshot",
32
+ "req": {
33
+ "coin": symbol,
34
+ "interval": "1m", # Nautilus mostly uses 1m bar aggregations
35
+ "startTime": start_time,
36
+ "endTime": now_ms
37
+ }
38
+ }
39
+
40
+ try:
41
+ print(f"📖 HistoryLoader: Fetching {lookback} candles for {symbol}...")
42
+ resp = requests.post(HyperliquidHistoryLoader.BASE_URL, json=payload, timeout=5)
43
+ data = resp.json()
44
+
45
+ if not isinstance(data, list):
46
+ print(f"⚠️ HistoryLoader: Unexpected response format: {data}")
47
+ return []
48
+
49
+ # Hyperliquid format: {'t': 170..., 'o': '1.1', 'h': '1.2', 'l': '1.0', 'c': '1.1', 'v': '100'}
50
+ # Sort by time
51
+ data = sorted(data, key=lambda x: x['t'])
52
+
53
+ # Take last N
54
+ last_n = data[-lookback:]
55
+
56
+ converted = []
57
+ for c in last_n:
58
+ converted.append({
59
+ "open": float(c['o']),
60
+ "high": float(c['h']),
61
+ "low": float(c['l']),
62
+ "close": float(c['c']),
63
+ "volume": float(c['v']),
64
+ "timestamp": c['t']
65
+ })
66
+
67
+ print(f"✅ HistoryLoader: Loaded {len(converted)} historical candles.")
68
+ return converted
69
+
70
+ except Exception as e:
71
+ print(f"❌ HistoryLoader Failed: {e}")
72
+ return []