Spaces:
Sleeping
Sleeping
Naufal Arhab commited on
Commit ·
d6219d0
1
Parent(s): 097634a
feat(data-parity): establish 5-exchange parity across OKX, Bitget, Hyperliquid & DataCollector
Browse files- backend/engine/data_collector.py +11 -5
- backend/engine/signal_engine.py +9 -0
- backend/exchanges/base.py +43 -13
- backend/exchanges/bitget.py +159 -39
- backend/exchanges/hyperliquid.py +75 -0
- backend/exchanges/okx.py +224 -35
- tests/test_five_exchange_whale_pov.py +414 -0
backend/engine/data_collector.py
CHANGED
|
@@ -148,14 +148,14 @@ async def check_spot_market_exists(symbol: str) -> bool:
|
|
| 148 |
class DataCollector:
|
| 149 |
def __init__(
|
| 150 |
self,
|
| 151 |
-
binance: BinanceClient,
|
| 152 |
-
bybit: BybitClient,
|
| 153 |
okx: OKXClient | None = None,
|
| 154 |
hyperliquid: HyperliquidClient | None = None,
|
| 155 |
bitget: BitgetClient | None = None,
|
| 156 |
) -> None:
|
| 157 |
-
self._binance = binance
|
| 158 |
-
self._bybit = bybit
|
| 159 |
self._okx = okx or OKXClient()
|
| 160 |
self._hyperliquid = hyperliquid or HyperliquidClient()
|
| 161 |
self._bitget = bitget or BitgetClient()
|
|
@@ -205,16 +205,22 @@ class DataCollector:
|
|
| 205 |
# Hyperliquid On-Chain DEX
|
| 206 |
async def _fetch_hl():
|
| 207 |
try:
|
| 208 |
-
market_data, orderbook, hl_trades = await asyncio.gather(
|
| 209 |
self._hyperliquid.get_market_data(symbol),
|
| 210 |
self._hyperliquid.get_orderbook(symbol, depth=20),
|
| 211 |
self._hyperliquid.get_recent_trades(symbol),
|
|
|
|
|
|
|
| 212 |
return_exceptions=True,
|
| 213 |
)
|
| 214 |
if isinstance(market_data, Exception) or not market_data:
|
| 215 |
return None
|
| 216 |
market_data["orderbook"] = orderbook if not isinstance(orderbook, Exception) else None
|
| 217 |
market_data["trades"] = hl_trades if (not isinstance(hl_trades, Exception) and isinstance(hl_trades, list)) else []
|
|
|
|
|
|
|
|
|
|
|
|
|
| 218 |
return market_data
|
| 219 |
except Exception as exc:
|
| 220 |
logger.debug("[%s] Hyperliquid collect error: %s", symbol, exc)
|
|
|
|
| 148 |
class DataCollector:
|
| 149 |
def __init__(
|
| 150 |
self,
|
| 151 |
+
binance: BinanceClient | None = None,
|
| 152 |
+
bybit: BybitClient | None = None,
|
| 153 |
okx: OKXClient | None = None,
|
| 154 |
hyperliquid: HyperliquidClient | None = None,
|
| 155 |
bitget: BitgetClient | None = None,
|
| 156 |
) -> None:
|
| 157 |
+
self._binance = binance or BinanceClient()
|
| 158 |
+
self._bybit = bybit or BybitClient()
|
| 159 |
self._okx = okx or OKXClient()
|
| 160 |
self._hyperliquid = hyperliquid or HyperliquidClient()
|
| 161 |
self._bitget = bitget or BitgetClient()
|
|
|
|
| 205 |
# Hyperliquid On-Chain DEX
|
| 206 |
async def _fetch_hl():
|
| 207 |
try:
|
| 208 |
+
market_data, orderbook, hl_trades, ohlcv_5m, ohlcv_15m = await asyncio.gather(
|
| 209 |
self._hyperliquid.get_market_data(symbol),
|
| 210 |
self._hyperliquid.get_orderbook(symbol, depth=20),
|
| 211 |
self._hyperliquid.get_recent_trades(symbol),
|
| 212 |
+
self._hyperliquid.get_ohlcv(symbol, timeframe="5m", limit=30),
|
| 213 |
+
self._hyperliquid.get_ohlcv(symbol, timeframe="15m", limit=30),
|
| 214 |
return_exceptions=True,
|
| 215 |
)
|
| 216 |
if isinstance(market_data, Exception) or not market_data:
|
| 217 |
return None
|
| 218 |
market_data["orderbook"] = orderbook if not isinstance(orderbook, Exception) else None
|
| 219 |
market_data["trades"] = hl_trades if (not isinstance(hl_trades, Exception) and isinstance(hl_trades, list)) else []
|
| 220 |
+
market_data["ohlcv"] = {
|
| 221 |
+
"5m": ohlcv_5m if (not isinstance(ohlcv_5m, Exception) and isinstance(ohlcv_5m, list)) else [],
|
| 222 |
+
"15m": ohlcv_15m if (not isinstance(ohlcv_15m, Exception) and isinstance(ohlcv_15m, list)) else [],
|
| 223 |
+
}
|
| 224 |
return market_data
|
| 225 |
except Exception as exc:
|
| 226 |
logger.debug("[%s] Hyperliquid collect error: %s", symbol, exc)
|
backend/engine/signal_engine.py
CHANGED
|
@@ -783,9 +783,17 @@ def _compute_cross_exchange(
|
|
| 783 |
if bitget_data:
|
| 784 |
p = _pct_change_5m(bitget_data)
|
| 785 |
if p is not None: rates["bitget"] = p
|
|
|
|
|
|
|
|
|
|
| 786 |
|
| 787 |
if len(rates) < 2:
|
| 788 |
return {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 789 |
"divergence_pct": 0.0,
|
| 790 |
"score": 0,
|
| 791 |
"dislocation_risk": False,
|
|
@@ -814,6 +822,7 @@ def _compute_cross_exchange(
|
|
| 814 |
"bybit_5m_pct": round(rates.get("bybit", 0.0), 4),
|
| 815 |
"okx_5m_pct": round(rates.get("okx", 0.0), 4) if "okx" in rates else None,
|
| 816 |
"bitget_5m_pct": round(rates.get("bitget", 0.0), 4) if "bitget" in rates else None,
|
|
|
|
| 817 |
"hyperliquid_basis_pct": round(hl_basis, 4) if hl_basis is not None else None,
|
| 818 |
"divergence_pct": round(max_div, 4),
|
| 819 |
"score": score,
|
|
|
|
| 783 |
if bitget_data:
|
| 784 |
p = _pct_change_5m(bitget_data)
|
| 785 |
if p is not None: rates["bitget"] = p
|
| 786 |
+
if hl_data:
|
| 787 |
+
p = _pct_change_5m(hl_data)
|
| 788 |
+
if p is not None: rates["hyperliquid"] = p
|
| 789 |
|
| 790 |
if len(rates) < 2:
|
| 791 |
return {
|
| 792 |
+
"binance_5m_pct": round(rates.get("binance", 0.0), 4) if "binance" in rates else None,
|
| 793 |
+
"bybit_5m_pct": round(rates.get("bybit", 0.0), 4) if "bybit" in rates else None,
|
| 794 |
+
"okx_5m_pct": round(rates.get("okx", 0.0), 4) if "okx" in rates else None,
|
| 795 |
+
"bitget_5m_pct": round(rates.get("bitget", 0.0), 4) if "bitget" in rates else None,
|
| 796 |
+
"hyperliquid_5m_pct": round(rates.get("hyperliquid", 0.0), 4) if "hyperliquid" in rates else None,
|
| 797 |
"divergence_pct": 0.0,
|
| 798 |
"score": 0,
|
| 799 |
"dislocation_risk": False,
|
|
|
|
| 822 |
"bybit_5m_pct": round(rates.get("bybit", 0.0), 4),
|
| 823 |
"okx_5m_pct": round(rates.get("okx", 0.0), 4) if "okx" in rates else None,
|
| 824 |
"bitget_5m_pct": round(rates.get("bitget", 0.0), 4) if "bitget" in rates else None,
|
| 825 |
+
"hyperliquid_5m_pct": round(rates.get("hyperliquid", 0.0), 4) if "hyperliquid" in rates else None,
|
| 826 |
"hyperliquid_basis_pct": round(hl_basis, 4) if hl_basis is not None else None,
|
| 827 |
"divergence_pct": round(max_div, 4),
|
| 828 |
"score": score,
|
backend/exchanges/base.py
CHANGED
|
@@ -94,21 +94,18 @@ class BaseExchange(ABC):
|
|
| 94 |
# Convenience
|
| 95 |
# ------------------------------------------------------------------
|
| 96 |
|
| 97 |
-
|
| 98 |
-
|
|
|
|
| 99 |
symbol_key: str,
|
| 100 |
current_oi: float,
|
| 101 |
window_sec: float = 300.0,
|
| 102 |
min_sample_gap_sec: float = 30.0,
|
| 103 |
max_age_sec: float = 3600.0,
|
| 104 |
-
) -> float | None:
|
| 105 |
-
"""Compute percentage OI change against
|
| 106 |
if current_oi <= 0:
|
| 107 |
-
return None
|
| 108 |
-
snaps_map = getattr(self, "_oi_snapshots", None)
|
| 109 |
-
if snaps_map is None:
|
| 110 |
-
snaps_map = {}
|
| 111 |
-
self._oi_snapshots = snaps_map
|
| 112 |
now_ts = time.time()
|
| 113 |
raw_snaps = snaps_map.get(symbol_key, [])
|
| 114 |
# Drop stale snapshots (e.g. after long idle/sleep) to avoid spurious percentage jumps
|
|
@@ -116,16 +113,49 @@ class BaseExchange(ABC):
|
|
| 116 |
snaps_map[symbol_key] = snaps
|
| 117 |
|
| 118 |
oi_change_pct = None
|
|
|
|
| 119 |
if snaps:
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
|
|
|
|
|
|
| 123 |
|
| 124 |
if not snaps or (now_ts - snaps[-1][0]) >= min_sample_gap_sec:
|
| 125 |
snaps.append((now_ts, current_oi))
|
| 126 |
if len(snaps) > 64:
|
| 127 |
del snaps[:-64]
|
| 128 |
-
return oi_change_pct
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
|
| 130 |
@staticmethod
|
| 131 |
def _compute_oi_horizons(
|
|
|
|
| 94 |
# Convenience
|
| 95 |
# ------------------------------------------------------------------
|
| 96 |
|
| 97 |
+
@staticmethod
|
| 98 |
+
def record_oi_change_with_meta(
|
| 99 |
+
snaps_map: dict[str, list[tuple[float, float]]],
|
| 100 |
symbol_key: str,
|
| 101 |
current_oi: float,
|
| 102 |
window_sec: float = 300.0,
|
| 103 |
min_sample_gap_sec: float = 30.0,
|
| 104 |
max_age_sec: float = 3600.0,
|
| 105 |
+
) -> tuple[float | None, float | None]:
|
| 106 |
+
"""Compute percentage OI change against rolling baseline and return (oi_change_pct, window_sec)."""
|
| 107 |
if current_oi <= 0:
|
| 108 |
+
return None, None
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
now_ts = time.time()
|
| 110 |
raw_snaps = snaps_map.get(symbol_key, [])
|
| 111 |
# Drop stale snapshots (e.g. after long idle/sleep) to avoid spurious percentage jumps
|
|
|
|
| 113 |
snaps_map[symbol_key] = snaps
|
| 114 |
|
| 115 |
oi_change_pct = None
|
| 116 |
+
window_sec_actual = None
|
| 117 |
if snaps:
|
| 118 |
+
anchor_pair = next(((ts, val) for ts, val in reversed(snaps) if (now_ts - ts) >= window_sec), snaps[0])
|
| 119 |
+
anchor_ts, anchor_val = anchor_pair
|
| 120 |
+
if anchor_val > 0:
|
| 121 |
+
oi_change_pct = round((current_oi - anchor_val) / anchor_val * 100.0, 4)
|
| 122 |
+
window_sec_actual = round(now_ts - anchor_ts, 2)
|
| 123 |
|
| 124 |
if not snaps or (now_ts - snaps[-1][0]) >= min_sample_gap_sec:
|
| 125 |
snaps.append((now_ts, current_oi))
|
| 126 |
if len(snaps) > 64:
|
| 127 |
del snaps[:-64]
|
| 128 |
+
return oi_change_pct, window_sec_actual
|
| 129 |
+
|
| 130 |
+
def _record_oi_change_with_meta(
|
| 131 |
+
self,
|
| 132 |
+
symbol_key: str,
|
| 133 |
+
current_oi: float,
|
| 134 |
+
window_sec: float = 300.0,
|
| 135 |
+
min_sample_gap_sec: float = 30.0,
|
| 136 |
+
max_age_sec: float = 3600.0,
|
| 137 |
+
) -> tuple[float | None, float | None]:
|
| 138 |
+
snaps_map = getattr(self, "_oi_snapshots", None)
|
| 139 |
+
if snaps_map is None:
|
| 140 |
+
snaps_map = {}
|
| 141 |
+
self._oi_snapshots = snaps_map
|
| 142 |
+
return self.record_oi_change_with_meta(
|
| 143 |
+
snaps_map, symbol_key, current_oi, window_sec, min_sample_gap_sec, max_age_sec
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
def _record_oi_change(
|
| 147 |
+
self,
|
| 148 |
+
symbol_key: str,
|
| 149 |
+
current_oi: float,
|
| 150 |
+
window_sec: float = 300.0,
|
| 151 |
+
min_sample_gap_sec: float = 30.0,
|
| 152 |
+
max_age_sec: float = 3600.0,
|
| 153 |
+
) -> float | None:
|
| 154 |
+
"""Compute percentage OI change against a rolling ~5m (or oldest recent) baseline."""
|
| 155 |
+
pct, _ = self._record_oi_change_with_meta(
|
| 156 |
+
symbol_key, current_oi, window_sec, min_sample_gap_sec, max_age_sec
|
| 157 |
+
)
|
| 158 |
+
return pct
|
| 159 |
|
| 160 |
@staticmethod
|
| 161 |
def _compute_oi_horizons(
|
backend/exchanges/bitget.py
CHANGED
|
@@ -206,6 +206,42 @@ class BitgetClient(BaseExchange):
|
|
| 206 |
logger.debug("[Bitget] Failed to fetch funding history for %s: %s", symbol, exc)
|
| 207 |
return []
|
| 208 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 209 |
async def get_open_interest(self, symbol: str) -> dict[str, Any]:
|
| 210 |
sym = self._to_bitget_symbol(symbol)
|
| 211 |
data = await self._get("/api/v2/mix/market/open-interest", {"productType": "USDT-FUTURES", "symbol": sym})
|
|
@@ -222,36 +258,79 @@ class BitgetClient(BaseExchange):
|
|
| 222 |
mp = mp_data.get("mark_price")
|
| 223 |
oi_usd = round(size_coins * float(mp), 2) if mp is not None and float(mp) > 0 else None
|
| 224 |
|
| 225 |
-
oi_change_pct = self.
|
| 226 |
|
| 227 |
return {
|
| 228 |
"open_interest": round(size_coins, 4),
|
| 229 |
"open_interest_value": oi_usd,
|
| 230 |
"oi_change_pct": oi_change_pct,
|
|
|
|
|
|
|
| 231 |
}
|
| 232 |
except (ValueError, TypeError):
|
| 233 |
return {"open_interest": None, "open_interest_value": None, "oi_change_pct": None}
|
| 234 |
|
| 235 |
async def get_long_short_ratio(self, symbol: str, period: str = "1h") -> dict[str, Any]:
|
| 236 |
-
"""Fetch Long/Short account ratio from Bitget V2 mix market."""
|
| 237 |
sym = self._to_bitget_symbol(symbol)
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 255 |
return {
|
| 256 |
"long_ratio": None,
|
| 257 |
"short_ratio": None,
|
|
@@ -261,31 +340,72 @@ class BitgetClient(BaseExchange):
|
|
| 261 |
async def get_ohlcv(self, symbol: str, timeframe: str, limit: int = 100) -> list[dict]:
|
| 262 |
sym = self._to_bitget_symbol(symbol)
|
| 263 |
granularity = TIMEFRAME_MAP.get(timeframe, "5m")
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 274 |
return []
|
| 275 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 276 |
candles = []
|
|
|
|
| 277 |
for c in data:
|
| 278 |
try:
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 289 |
except (IndexError, ValueError, TypeError):
|
| 290 |
continue
|
| 291 |
|
|
|
|
| 206 |
logger.debug("[Bitget] Failed to fetch funding history for %s: %s", symbol, exc)
|
| 207 |
return []
|
| 208 |
|
| 209 |
+
async def get_spot_trades(self, symbol: str, limit: int = 100) -> list[dict]:
|
| 210 |
+
"""Fetch spot trades from Bitget Spot market for Spot vs Futures CVD divergence analysis."""
|
| 211 |
+
from engine.symbol_resolver import strip_multiplier_prefix
|
| 212 |
+
|
| 213 |
+
clean_sym = strip_multiplier_prefix(symbol)
|
| 214 |
+
try:
|
| 215 |
+
data = await self._get(
|
| 216 |
+
"/api/v2/spot/market/fills",
|
| 217 |
+
{
|
| 218 |
+
"symbol": clean_sym,
|
| 219 |
+
"limit": str(min(limit, 100)),
|
| 220 |
+
},
|
| 221 |
+
)
|
| 222 |
+
if not data or not isinstance(data, list):
|
| 223 |
+
return []
|
| 224 |
+
|
| 225 |
+
trades = []
|
| 226 |
+
for f in data:
|
| 227 |
+
try:
|
| 228 |
+
trades.append(
|
| 229 |
+
{
|
| 230 |
+
"price": float(f["price"]),
|
| 231 |
+
"qty": float(f["size"]),
|
| 232 |
+
"is_buyer_maker": str(f.get("side", "")).strip().lower() == "sell",
|
| 233 |
+
"time": int(f.get("ts", 0)),
|
| 234 |
+
"venue": "bitget_spot",
|
| 235 |
+
}
|
| 236 |
+
)
|
| 237 |
+
except (KeyError, ValueError, TypeError):
|
| 238 |
+
continue
|
| 239 |
+
trades.sort(key=lambda x: x["time"])
|
| 240 |
+
return trades
|
| 241 |
+
except Exception as exc:
|
| 242 |
+
logger.debug("[Bitget] Failed to fetch spot trades for %s: %s", clean_sym, exc)
|
| 243 |
+
return []
|
| 244 |
+
|
| 245 |
async def get_open_interest(self, symbol: str) -> dict[str, Any]:
|
| 246 |
sym = self._to_bitget_symbol(symbol)
|
| 247 |
data = await self._get("/api/v2/mix/market/open-interest", {"productType": "USDT-FUTURES", "symbol": sym})
|
|
|
|
| 258 |
mp = mp_data.get("mark_price")
|
| 259 |
oi_usd = round(size_coins * float(mp), 2) if mp is not None and float(mp) > 0 else None
|
| 260 |
|
| 261 |
+
oi_change_pct, oi_window_sec = self._record_oi_change_with_meta(sym, size_coins)
|
| 262 |
|
| 263 |
return {
|
| 264 |
"open_interest": round(size_coins, 4),
|
| 265 |
"open_interest_value": oi_usd,
|
| 266 |
"oi_change_pct": oi_change_pct,
|
| 267 |
+
"oi_horizon": "rolling",
|
| 268 |
+
"oi_window_sec": oi_window_sec,
|
| 269 |
}
|
| 270 |
except (ValueError, TypeError):
|
| 271 |
return {"open_interest": None, "open_interest_value": None, "oi_change_pct": None}
|
| 272 |
|
| 273 |
async def get_long_short_ratio(self, symbol: str, period: str = "1h") -> dict[str, Any]:
|
| 274 |
+
"""Fetch Long/Short position ratio & account ratio from Bitget V2 mix market."""
|
| 275 |
sym = self._to_bitget_symbol(symbol)
|
| 276 |
+
tasks = [
|
| 277 |
+
self._get("/api/v2/mix/market/position-long-short", {"symbol": sym, "productType": "USDT-FUTURES"}),
|
| 278 |
+
self._get("/api/v2/mix/market/account-long-short", {"symbol": sym, "productType": "USDT-FUTURES"}),
|
| 279 |
+
self._get("/api/v2/mix/market/long-short", {"symbol": sym, "productType": "USDT-FUTURES"}),
|
| 280 |
+
]
|
| 281 |
+
results = await asyncio.gather(*tasks, return_exceptions=True)
|
| 282 |
+
res_pos, res_acct, res_ls = results[0], results[1], results[2]
|
| 283 |
+
|
| 284 |
+
top_pos_ratio = None
|
| 285 |
+
if not isinstance(res_pos, Exception) and isinstance(res_pos, list) and len(res_pos) > 0:
|
| 286 |
+
try:
|
| 287 |
+
top_pos_ratio = float(res_pos[-1].get("longRatio", 0.5))
|
| 288 |
+
except (ValueError, TypeError):
|
| 289 |
+
pass
|
| 290 |
+
|
| 291 |
+
retail_ratio = None
|
| 292 |
+
if not isinstance(res_acct, Exception) and isinstance(res_acct, list) and len(res_acct) > 0:
|
| 293 |
+
try:
|
| 294 |
+
retail_ratio = float(res_acct[-1].get("longRatio", 0.5))
|
| 295 |
+
except (ValueError, TypeError):
|
| 296 |
+
pass
|
| 297 |
+
elif not isinstance(res_ls, Exception) and isinstance(res_ls, list) and len(res_ls) > 0:
|
| 298 |
+
try:
|
| 299 |
+
retail_ratio = float(res_ls[-1].get("longRatio", 0.5))
|
| 300 |
+
except (ValueError, TypeError):
|
| 301 |
+
pass
|
| 302 |
+
|
| 303 |
+
if top_pos_ratio is not None and retail_ratio is not None:
|
| 304 |
+
whale_retail_delta = round(top_pos_ratio - retail_ratio, 4)
|
| 305 |
+
return {
|
| 306 |
+
"long_ratio": round(top_pos_ratio, 4),
|
| 307 |
+
"short_ratio": round(1.0 - top_pos_ratio, 4),
|
| 308 |
+
"top_position_long_ratio": round(top_pos_ratio, 4),
|
| 309 |
+
"retail_long_ratio": round(retail_ratio, 4),
|
| 310 |
+
"whale_retail_delta": whale_retail_delta,
|
| 311 |
+
"source": "smart_money",
|
| 312 |
+
}
|
| 313 |
+
|
| 314 |
+
if top_pos_ratio is not None:
|
| 315 |
+
return {
|
| 316 |
+
"long_ratio": round(top_pos_ratio, 4),
|
| 317 |
+
"short_ratio": round(1.0 - top_pos_ratio, 4),
|
| 318 |
+
"top_position_long_ratio": round(top_pos_ratio, 4),
|
| 319 |
+
"retail_long_ratio": None,
|
| 320 |
+
"whale_retail_delta": None,
|
| 321 |
+
"source": "top_trader",
|
| 322 |
+
}
|
| 323 |
+
|
| 324 |
+
if retail_ratio is not None:
|
| 325 |
+
return {
|
| 326 |
+
"long_ratio": round(retail_ratio, 4),
|
| 327 |
+
"short_ratio": round(1.0 - retail_ratio, 4),
|
| 328 |
+
"top_position_long_ratio": None,
|
| 329 |
+
"retail_long_ratio": round(retail_ratio, 4),
|
| 330 |
+
"whale_retail_delta": None,
|
| 331 |
+
"source": "top_trader",
|
| 332 |
+
}
|
| 333 |
+
|
| 334 |
return {
|
| 335 |
"long_ratio": None,
|
| 336 |
"short_ratio": None,
|
|
|
|
| 340 |
async def get_ohlcv(self, symbol: str, timeframe: str, limit: int = 100) -> list[dict]:
|
| 341 |
sym = self._to_bitget_symbol(symbol)
|
| 342 |
granularity = TIMEFRAME_MAP.get(timeframe, "5m")
|
| 343 |
+
tasks = [
|
| 344 |
+
self._get(
|
| 345 |
+
"/api/v2/mix/market/candles",
|
| 346 |
+
{
|
| 347 |
+
"productType": "USDT-FUTURES",
|
| 348 |
+
"symbol": sym,
|
| 349 |
+
"granularity": granularity,
|
| 350 |
+
"limit": str(min(limit, 100)),
|
| 351 |
+
},
|
| 352 |
+
),
|
| 353 |
+
]
|
| 354 |
+
fetch_taker = timeframe in ("15m", "1h")
|
| 355 |
+
if fetch_taker:
|
| 356 |
+
tasks.append(
|
| 357 |
+
self._get(
|
| 358 |
+
"/api/v2/mix/market/taker-buy-sell",
|
| 359 |
+
{
|
| 360 |
+
"symbol": sym,
|
| 361 |
+
"productType": "USDT-FUTURES",
|
| 362 |
+
"period": TIMEFRAME_MAP.get(timeframe, "15m"),
|
| 363 |
+
},
|
| 364 |
+
)
|
| 365 |
+
)
|
| 366 |
+
|
| 367 |
+
results = await asyncio.gather(*tasks, return_exceptions=True)
|
| 368 |
+
data = results[0]
|
| 369 |
+
if isinstance(data, Exception) or not data or not isinstance(data, list):
|
| 370 |
return []
|
| 371 |
|
| 372 |
+
taker_map: dict[int, float] = {}
|
| 373 |
+
if fetch_taker and len(results) > 1 and not isinstance(results[1], Exception) and isinstance(results[1], list):
|
| 374 |
+
for row in results[1]:
|
| 375 |
+
try:
|
| 376 |
+
ts = int(row.get("ts", row.get("timestamp", 0)) if isinstance(row, dict) else row[0])
|
| 377 |
+
buy_v = float(row.get("buyVol", row.get("buyVolume", 0.0)) if isinstance(row, dict) else row[1])
|
| 378 |
+
taker_map[ts] = buy_v
|
| 379 |
+
except (IndexError, ValueError, TypeError):
|
| 380 |
+
continue
|
| 381 |
+
|
| 382 |
candles = []
|
| 383 |
+
interval_ms = {"15m": 900_000, "1h": 3_600_000}.get(timeframe, 900_000)
|
| 384 |
for c in data:
|
| 385 |
try:
|
| 386 |
+
c_ts = int(c[0])
|
| 387 |
+
c_dict = {
|
| 388 |
+
"timestamp": c_ts,
|
| 389 |
+
"open": float(c[1]),
|
| 390 |
+
"high": float(c[2]),
|
| 391 |
+
"low": float(c[3]),
|
| 392 |
+
"close": float(c[4]),
|
| 393 |
+
"volume": float(c[5]),
|
| 394 |
+
}
|
| 395 |
+
if taker_map:
|
| 396 |
+
if c_ts in taker_map:
|
| 397 |
+
c_dict["taker_buy_volume"] = taker_map[c_ts]
|
| 398 |
+
else:
|
| 399 |
+
best_match = None
|
| 400 |
+
min_diff = interval_ms
|
| 401 |
+
for t_ts, buy_v in taker_map.items():
|
| 402 |
+
diff = abs(c_ts - t_ts)
|
| 403 |
+
if diff < min_diff:
|
| 404 |
+
min_diff = diff
|
| 405 |
+
best_match = buy_v
|
| 406 |
+
if best_match is not None:
|
| 407 |
+
c_dict["taker_buy_volume"] = best_match
|
| 408 |
+
candles.append(c_dict)
|
| 409 |
except (IndexError, ValueError, TypeError):
|
| 410 |
continue
|
| 411 |
|
backend/exchanges/hyperliquid.py
CHANGED
|
@@ -18,6 +18,7 @@ import httpx
|
|
| 18 |
from config import PROXY_URL
|
| 19 |
from engine.doh_resolver import enable_doh_bypass
|
| 20 |
from engine.symbol_resolver import get_symbol_variations
|
|
|
|
| 21 |
|
| 22 |
enable_doh_bypass()
|
| 23 |
|
|
@@ -42,6 +43,7 @@ class HyperliquidClient:
|
|
| 42 |
self._cached_universe: dict[str, dict] = {}
|
| 43 |
self._coin_lookup: dict[str, str] = {}
|
| 44 |
self._lock = asyncio.Lock()
|
|
|
|
| 45 |
|
| 46 |
def _format_symbol(self, symbol: str) -> str:
|
| 47 |
"""Strip delimiters & quote currency (e.g. BTC/USDT, kPEPE-USDT -> BTC, kPEPE) preserving case."""
|
|
@@ -206,11 +208,18 @@ class HyperliquidClient:
|
|
| 206 |
|
| 207 |
basis_pct = ((mark_px - oracle_px) / oracle_px * 100) if oracle_px else 0.0
|
| 208 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 209 |
return {
|
| 210 |
"coin": coin,
|
| 211 |
"funding_rate": round(fr_8h, 6),
|
| 212 |
"funding_rate_1h": round(fr_1h, 6),
|
| 213 |
"open_interest": oi,
|
|
|
|
|
|
|
|
|
|
| 214 |
"mark_price": mark_px,
|
| 215 |
"oracle_price": oracle_px,
|
| 216 |
"basis_pct": round(basis_pct, 6),
|
|
@@ -220,5 +229,71 @@ class HyperliquidClient:
|
|
| 220 |
logger.warning("[Hyperliquid] Error parsing ctx for %s: %s", coin, exc)
|
| 221 |
return None
|
| 222 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 223 |
async def close(self) -> None:
|
| 224 |
await self._client.aclose()
|
|
|
|
| 18 |
from config import PROXY_URL
|
| 19 |
from engine.doh_resolver import enable_doh_bypass
|
| 20 |
from engine.symbol_resolver import get_symbol_variations
|
| 21 |
+
from exchanges.base import BaseExchange
|
| 22 |
|
| 23 |
enable_doh_bypass()
|
| 24 |
|
|
|
|
| 43 |
self._cached_universe: dict[str, dict] = {}
|
| 44 |
self._coin_lookup: dict[str, str] = {}
|
| 45 |
self._lock = asyncio.Lock()
|
| 46 |
+
self._oi_snapshots: dict[str, list[tuple[float, float]]] = {}
|
| 47 |
|
| 48 |
def _format_symbol(self, symbol: str) -> str:
|
| 49 |
"""Strip delimiters & quote currency (e.g. BTC/USDT, kPEPE-USDT -> BTC, kPEPE) preserving case."""
|
|
|
|
| 208 |
|
| 209 |
basis_pct = ((mark_px - oracle_px) / oracle_px * 100) if oracle_px else 0.0
|
| 210 |
|
| 211 |
+
oi_change_pct, oi_window_sec = BaseExchange.record_oi_change_with_meta(
|
| 212 |
+
self._oi_snapshots, coin, oi
|
| 213 |
+
)
|
| 214 |
+
|
| 215 |
return {
|
| 216 |
"coin": coin,
|
| 217 |
"funding_rate": round(fr_8h, 6),
|
| 218 |
"funding_rate_1h": round(fr_1h, 6),
|
| 219 |
"open_interest": oi,
|
| 220 |
+
"oi_change_pct": oi_change_pct,
|
| 221 |
+
"oi_horizon": "rolling",
|
| 222 |
+
"oi_window_sec": oi_window_sec,
|
| 223 |
"mark_price": mark_px,
|
| 224 |
"oracle_price": oracle_px,
|
| 225 |
"basis_pct": round(basis_pct, 6),
|
|
|
|
| 229 |
logger.warning("[Hyperliquid] Error parsing ctx for %s: %s", coin, exc)
|
| 230 |
return None
|
| 231 |
|
| 232 |
+
async def get_ohlcv(self, symbol: str, timeframe: str = "15m", limit: int = 30) -> list[dict]:
|
| 233 |
+
"""Fetch historical OHLCV candle snapshots from Hyperliquid Info API."""
|
| 234 |
+
await self._refresh_meta()
|
| 235 |
+
coin = self.resolve_coin(symbol)
|
| 236 |
+
if not coin:
|
| 237 |
+
coin = self._format_symbol(symbol).upper()
|
| 238 |
+
if not coin:
|
| 239 |
+
return []
|
| 240 |
+
|
| 241 |
+
interval_ms = {
|
| 242 |
+
"1m": 60_000,
|
| 243 |
+
"3m": 180_000,
|
| 244 |
+
"5m": 300_000,
|
| 245 |
+
"15m": 900_000,
|
| 246 |
+
"30m": 1_800_000,
|
| 247 |
+
"1h": 3_600_000,
|
| 248 |
+
"2h": 7_200_000,
|
| 249 |
+
"4h": 14_400_000,
|
| 250 |
+
"1d": 86_400_000,
|
| 251 |
+
}.get(timeframe, 900_000)
|
| 252 |
+
|
| 253 |
+
now_ms = int(time.time() * 1000)
|
| 254 |
+
start_time = now_ms - (limit + 5) * interval_ms
|
| 255 |
+
end_time = now_ms
|
| 256 |
+
|
| 257 |
+
payload = {
|
| 258 |
+
"type": "candleSnapshot",
|
| 259 |
+
"req": {
|
| 260 |
+
"coin": coin,
|
| 261 |
+
"interval": timeframe,
|
| 262 |
+
"startTime": start_time,
|
| 263 |
+
"endTime": end_time,
|
| 264 |
+
},
|
| 265 |
+
}
|
| 266 |
+
|
| 267 |
+
try:
|
| 268 |
+
resp = await self._client.post(HYPERLIQUID_INFO_URL, json=payload)
|
| 269 |
+
if resp.status_code != 200:
|
| 270 |
+
return []
|
| 271 |
+
data = resp.json()
|
| 272 |
+
if not isinstance(data, list):
|
| 273 |
+
return []
|
| 274 |
+
|
| 275 |
+
candles = []
|
| 276 |
+
for c in data:
|
| 277 |
+
try:
|
| 278 |
+
c_dict = {
|
| 279 |
+
"timestamp": int(c.get("t", c.get("timestamp", 0))),
|
| 280 |
+
"open": float(c.get("o", c.get("open", 0.0))),
|
| 281 |
+
"high": float(c.get("h", c.get("high", 0.0))),
|
| 282 |
+
"low": float(c.get("l", c.get("low", 0.0))),
|
| 283 |
+
"close": float(c.get("c", c.get("close", 0.0))),
|
| 284 |
+
"volume": float(c.get("v", c.get("volume", 0.0))),
|
| 285 |
+
}
|
| 286 |
+
candles.append(c_dict)
|
| 287 |
+
except (IndexError, ValueError, TypeError):
|
| 288 |
+
continue
|
| 289 |
+
|
| 290 |
+
candles.sort(key=lambda x: x["timestamp"])
|
| 291 |
+
if limit > 0:
|
| 292 |
+
candles = candles[-limit:]
|
| 293 |
+
return candles
|
| 294 |
+
except Exception as exc:
|
| 295 |
+
logger.debug("[Hyperliquid] OHLCV fetch error for %s (%s): %s", coin, timeframe, exc)
|
| 296 |
+
return []
|
| 297 |
+
|
| 298 |
async def close(self) -> None:
|
| 299 |
await self._client.aclose()
|
backend/exchanges/okx.py
CHANGED
|
@@ -232,26 +232,113 @@ class OKXClient(BaseExchange):
|
|
| 232 |
logger.debug("[OKX] Failed to fetch funding history for %s: %s", symbol, exc)
|
| 233 |
return []
|
| 234 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 235 |
async def get_open_interest(self, symbol: str) -> dict[str, Any]:
|
| 236 |
inst_id = self._to_inst_id(symbol)
|
| 237 |
-
|
| 238 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 239 |
return {"open_interest": 0.0, "open_interest_value": None, "oi_change_pct": None}
|
| 240 |
-
|
|
|
|
| 241 |
# OKX returns oi (contracts), oiCcy (base coins), and oiUsd (USD notional value)
|
| 242 |
-
oi_usd =
|
| 243 |
oi_val = float(oi_usd) if oi_usd is not None and oi_usd != "" else None
|
| 244 |
|
| 245 |
-
oi_change_pct =
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 246 |
|
| 247 |
return {
|
| 248 |
"open_interest": oi,
|
| 249 |
"open_interest_value": oi_val,
|
| 250 |
"oi_change_pct": oi_change_pct,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 251 |
}
|
| 252 |
|
| 253 |
async def get_long_short_ratio(self, symbol: str, period: str = "1h") -> dict[str, Any]:
|
| 254 |
-
"""OKX Long/Short account ratio via rubik stat."""
|
| 255 |
from engine.symbol_resolver import strip_multiplier_prefix
|
| 256 |
|
| 257 |
norm = strip_multiplier_prefix(symbol)
|
|
@@ -263,46 +350,148 @@ class OKXClient(BaseExchange):
|
|
| 263 |
okx_period = {"5m": "5m", "15m": "5m", "30m": "5m", "1h": "1H", "4h": "1H", "1d": "1D"}.get(
|
| 264 |
(period or "1h").lower(), "1H"
|
| 265 |
)
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
)
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 275 |
return None
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 282 |
return {"long_ratio": None, "short_ratio": None, "source": "unavailable"}
|
| 283 |
|
| 284 |
async def get_ohlcv(self, symbol: str, timeframe: str, limit: int = 100) -> list[dict]:
|
| 285 |
inst_id = self._to_inst_id(symbol)
|
| 286 |
bar = TF_MAP.get(timeframe, "1H")
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 291 |
candles = []
|
|
|
|
| 292 |
for k in reversed(data):
|
| 293 |
# OKX returns: [ts, o, h, l, c, vol, volCcy, volCcyQuote, confirm]
|
| 294 |
# Use k[6] (volCcy) so candle volume is in normalized base coins matching Binance & Bybit
|
| 295 |
vol = float(k[6]) if len(k) > 6 and k[6] else float(k[5])
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 306 |
return candles
|
| 307 |
|
| 308 |
async def _get_ct_val(self, inst_id: str) -> float:
|
|
|
|
| 232 |
logger.debug("[OKX] Failed to fetch funding history for %s: %s", symbol, exc)
|
| 233 |
return []
|
| 234 |
|
| 235 |
+
async def get_spot_trades(self, symbol: str, limit: int = 100) -> list[dict]:
|
| 236 |
+
"""Fetch spot trades from OKX Spot market for Spot vs Futures CVD divergence analysis."""
|
| 237 |
+
from engine.symbol_resolver import strip_multiplier_prefix
|
| 238 |
+
|
| 239 |
+
norm = strip_multiplier_prefix(symbol)
|
| 240 |
+
base = norm
|
| 241 |
+
for q in ("USDT", "USDC", "USD", "BUSD", "EUR"):
|
| 242 |
+
if base.endswith(q) and len(base) > len(q):
|
| 243 |
+
base = base[:-len(q)]
|
| 244 |
+
break
|
| 245 |
+
|
| 246 |
+
probe_inst_ids = [f"{base}-USDT", f"{base}-USDC"] if base else []
|
| 247 |
+
for inst_id in probe_inst_ids:
|
| 248 |
+
try:
|
| 249 |
+
data = await self._get(
|
| 250 |
+
"/api/v5/market/trades",
|
| 251 |
+
{"instId": inst_id, "limit": str(min(limit, 100))},
|
| 252 |
+
)
|
| 253 |
+
if not data or not isinstance(data, list):
|
| 254 |
+
continue
|
| 255 |
+
trades = []
|
| 256 |
+
for t in data:
|
| 257 |
+
try:
|
| 258 |
+
side = str(t.get("side", "buy")).lower()
|
| 259 |
+
is_buyer_maker = (side == "sell")
|
| 260 |
+
trades.append({
|
| 261 |
+
"price": float(t["px"]),
|
| 262 |
+
"qty": float(t["sz"]),
|
| 263 |
+
"is_buyer_maker": is_buyer_maker,
|
| 264 |
+
"time": int(t["ts"]),
|
| 265 |
+
"venue": "okx_spot",
|
| 266 |
+
})
|
| 267 |
+
except (KeyError, ValueError, TypeError):
|
| 268 |
+
continue
|
| 269 |
+
if trades:
|
| 270 |
+
trades.sort(key=lambda x: x["time"])
|
| 271 |
+
return trades
|
| 272 |
+
except Exception:
|
| 273 |
+
continue
|
| 274 |
+
return []
|
| 275 |
+
|
| 276 |
async def get_open_interest(self, symbol: str) -> dict[str, Any]:
|
| 277 |
inst_id = self._to_inst_id(symbol)
|
| 278 |
+
tasks = [
|
| 279 |
+
self._get("/api/v5/public/open-interest", {"instType": "SWAP", "instId": inst_id}),
|
| 280 |
+
self._get("/api/v5/rubik/stat/contracts/open-interest-history", {"instId": inst_id, "period": "5m", "limit": "49"}),
|
| 281 |
+
]
|
| 282 |
+
res_oi, res_hist = await asyncio.gather(*tasks, return_exceptions=True)
|
| 283 |
+
|
| 284 |
+
if isinstance(res_oi, Exception) or not res_oi or not isinstance(res_oi, list):
|
| 285 |
return {"open_interest": 0.0, "open_interest_value": None, "oi_change_pct": None}
|
| 286 |
+
|
| 287 |
+
oi = float(res_oi[0].get("oiCcy", 0.0))
|
| 288 |
# OKX returns oi (contracts), oiCcy (base coins), and oiUsd (USD notional value)
|
| 289 |
+
oi_usd = res_oi[0].get("oiUsd")
|
| 290 |
oi_val = float(oi_usd) if oi_usd is not None and oi_usd != "" else None
|
| 291 |
|
| 292 |
+
oi_change_pct = None
|
| 293 |
+
oi_change_1h_pct = None
|
| 294 |
+
oi_change_4h_pct = None
|
| 295 |
+
oi_horizon = None
|
| 296 |
+
oi_window_sec = None
|
| 297 |
+
|
| 298 |
+
if not isinstance(res_hist, Exception) and isinstance(res_hist, list) and len(res_hist) >= 4:
|
| 299 |
+
try:
|
| 300 |
+
sorted_hist = sorted(res_hist, key=lambda x: int(x[0]))
|
| 301 |
+
oi_series = []
|
| 302 |
+
for it in sorted_hist:
|
| 303 |
+
if len(it) > 2 and it[2] is not None and it[2] != "":
|
| 304 |
+
oi_series.append(float(it[2]))
|
| 305 |
+
elif len(it) > 1 and it[1] is not None and it[1] != "":
|
| 306 |
+
oi_series.append(float(it[1]))
|
| 307 |
+
|
| 308 |
+
if len(oi_series) >= 4:
|
| 309 |
+
curr_oi = oi_series[-1]
|
| 310 |
+
prev_15m = oi_series[-4]
|
| 311 |
+
if prev_15m > 0:
|
| 312 |
+
oi_change_pct = round((curr_oi - prev_15m) / prev_15m * 100.0, 4)
|
| 313 |
+
if len(oi_series) >= 13:
|
| 314 |
+
prev_1h = oi_series[-13]
|
| 315 |
+
if prev_1h > 0:
|
| 316 |
+
oi_change_1h_pct = round((curr_oi - prev_1h) / prev_1h * 100.0, 4)
|
| 317 |
+
if len(oi_series) >= 49:
|
| 318 |
+
prev_4h = oi_series[-49]
|
| 319 |
+
if prev_4h > 0:
|
| 320 |
+
oi_change_4h_pct = round((curr_oi - prev_4h) / prev_4h * 100.0, 4)
|
| 321 |
+
oi_horizon = "15m"
|
| 322 |
+
oi_window_sec = 900.0
|
| 323 |
+
except Exception as exc:
|
| 324 |
+
logger.debug("[OKX] OI history parse error for %s: %s", symbol, exc)
|
| 325 |
+
|
| 326 |
+
if oi_horizon is None:
|
| 327 |
+
oi_change_pct, oi_window_sec = self._record_oi_change_with_meta(inst_id, oi)
|
| 328 |
+
oi_horizon = "rolling"
|
| 329 |
|
| 330 |
return {
|
| 331 |
"open_interest": oi,
|
| 332 |
"open_interest_value": oi_val,
|
| 333 |
"oi_change_pct": oi_change_pct,
|
| 334 |
+
"oi_change_1h_pct": oi_change_1h_pct,
|
| 335 |
+
"oi_change_4h_pct": oi_change_4h_pct,
|
| 336 |
+
"oi_horizon": oi_horizon,
|
| 337 |
+
"oi_window_sec": oi_window_sec,
|
| 338 |
}
|
| 339 |
|
| 340 |
async def get_long_short_ratio(self, symbol: str, period: str = "1h") -> dict[str, Any]:
|
| 341 |
+
"""OKX Long/Short account ratio & top-trader position ratio via rubik stat."""
|
| 342 |
from engine.symbol_resolver import strip_multiplier_prefix
|
| 343 |
|
| 344 |
norm = strip_multiplier_prefix(symbol)
|
|
|
|
| 350 |
okx_period = {"5m": "5m", "15m": "5m", "30m": "5m", "1h": "1H", "4h": "1H", "1d": "1D"}.get(
|
| 351 |
(period or "1h").lower(), "1H"
|
| 352 |
)
|
| 353 |
+
inst_id = self._to_inst_id(symbol)
|
| 354 |
+
|
| 355 |
+
tasks = [
|
| 356 |
+
self._get("/api/v5/rubik/stat/contracts/long-short-account-ratio", {"ccy": base_ccy, "period": okx_period}),
|
| 357 |
+
self._get("/api/v5/rubik/stat/contracts/long-short-position-ratio-contract-top-trader", {"instId": inst_id, "period": okx_period, "limit": "1"}),
|
| 358 |
+
]
|
| 359 |
+
res_acct, res_pos = await asyncio.gather(*tasks, return_exceptions=True)
|
| 360 |
+
|
| 361 |
+
retail_long_ratio = None
|
| 362 |
+
if not isinstance(res_acct, Exception) and res_acct and len(res_acct) > 0:
|
| 363 |
+
try:
|
| 364 |
+
item = res_acct[0]
|
| 365 |
+
ratio_val = float(item[1]) if isinstance(item, (list, tuple)) else float(item.get("ratio", item.get("longShortRatio", 1.0)))
|
| 366 |
+
if ratio_val < 0:
|
| 367 |
return None
|
| 368 |
+
retail_long_ratio = round(ratio_val / (1.0 + ratio_val), 4)
|
| 369 |
+
except Exception as exc:
|
| 370 |
+
logger.debug("[OKX] Account L/S ratio parse error for %s: %s", symbol, exc)
|
| 371 |
+
|
| 372 |
+
top_pos_ratio = None
|
| 373 |
+
if not isinstance(res_pos, Exception) and res_pos and len(res_pos) > 0:
|
| 374 |
+
try:
|
| 375 |
+
item = res_pos[0]
|
| 376 |
+
if isinstance(item, (list, tuple)):
|
| 377 |
+
if len(item) == 2:
|
| 378 |
+
r = float(item[1])
|
| 379 |
+
if r >= 0:
|
| 380 |
+
top_pos_ratio = round(r / (1.0 + r), 4)
|
| 381 |
+
elif len(item) >= 3:
|
| 382 |
+
v1, v2 = float(item[1]), float(item[2])
|
| 383 |
+
if v1 + v2 > 0:
|
| 384 |
+
top_pos_ratio = round(v1 / (v1 + v2), 4)
|
| 385 |
+
elif isinstance(item, dict):
|
| 386 |
+
if "longPos" in item and "shortPos" in item:
|
| 387 |
+
lp, sp = float(item["longPos"]), float(item["shortPos"])
|
| 388 |
+
if lp + sp > 0:
|
| 389 |
+
top_pos_ratio = round(lp / (lp + sp), 4)
|
| 390 |
+
elif "ratio" in item:
|
| 391 |
+
r = float(item["ratio"])
|
| 392 |
+
if r >= 0:
|
| 393 |
+
top_pos_ratio = round(r / (1.0 + r), 4)
|
| 394 |
+
elif "longShortRatio" in item:
|
| 395 |
+
r = float(item["longShortRatio"])
|
| 396 |
+
if r >= 0:
|
| 397 |
+
top_pos_ratio = round(r / (1.0 + r), 4)
|
| 398 |
+
except Exception as exc:
|
| 399 |
+
logger.debug("[OKX] Top position L/S ratio parse error for %s: %s", symbol, exc)
|
| 400 |
+
|
| 401 |
+
if retail_long_ratio is not None and top_pos_ratio is not None:
|
| 402 |
+
whale_retail_delta = round(top_pos_ratio - retail_long_ratio, 4)
|
| 403 |
+
return {
|
| 404 |
+
"long_ratio": top_pos_ratio,
|
| 405 |
+
"short_ratio": round(1.0 - top_pos_ratio, 4),
|
| 406 |
+
"top_position_long_ratio": top_pos_ratio,
|
| 407 |
+
"retail_long_ratio": retail_long_ratio,
|
| 408 |
+
"whale_retail_delta": whale_retail_delta,
|
| 409 |
+
"source": "smart_money",
|
| 410 |
+
}
|
| 411 |
+
|
| 412 |
+
if retail_long_ratio is not None:
|
| 413 |
+
return {
|
| 414 |
+
"long_ratio": retail_long_ratio,
|
| 415 |
+
"short_ratio": round(1.0 - retail_long_ratio, 4),
|
| 416 |
+
"top_position_long_ratio": None,
|
| 417 |
+
"retail_long_ratio": retail_long_ratio,
|
| 418 |
+
"whale_retail_delta": None,
|
| 419 |
+
"source": "top_trader",
|
| 420 |
+
}
|
| 421 |
+
|
| 422 |
return {"long_ratio": None, "short_ratio": None, "source": "unavailable"}
|
| 423 |
|
| 424 |
async def get_ohlcv(self, symbol: str, timeframe: str, limit: int = 100) -> list[dict]:
|
| 425 |
inst_id = self._to_inst_id(symbol)
|
| 426 |
bar = TF_MAP.get(timeframe, "1H")
|
| 427 |
+
|
| 428 |
+
tasks = [
|
| 429 |
+
self._get(
|
| 430 |
+
"/api/v5/market/candles",
|
| 431 |
+
{"instId": inst_id, "bar": bar, "limit": min(limit, 100)},
|
| 432 |
+
),
|
| 433 |
+
]
|
| 434 |
+
fetch_taker = timeframe in ("15m", "1h")
|
| 435 |
+
if fetch_taker:
|
| 436 |
+
from engine.symbol_resolver import strip_multiplier_prefix
|
| 437 |
+
norm = strip_multiplier_prefix(symbol)
|
| 438 |
+
base_ccy = norm
|
| 439 |
+
for q in ("USDT", "USDC", "USD", "BUSD", "EUR"):
|
| 440 |
+
if base_ccy.endswith(q) and len(base_ccy) > len(q):
|
| 441 |
+
base_ccy = base_ccy[:-len(q)]
|
| 442 |
+
break
|
| 443 |
+
okx_taker_period = "1H" if timeframe == "1h" else "15m"
|
| 444 |
+
tasks.append(
|
| 445 |
+
self._get(
|
| 446 |
+
"/api/v5/rubik/stat/taker-volume",
|
| 447 |
+
{"ccy": base_ccy, "instType": "CONTRACTS", "period": okx_taker_period},
|
| 448 |
+
)
|
| 449 |
+
)
|
| 450 |
+
|
| 451 |
+
results = await asyncio.gather(*tasks, return_exceptions=True)
|
| 452 |
+
data = results[0]
|
| 453 |
+
if isinstance(data, Exception) or not data or not isinstance(data, list):
|
| 454 |
+
return []
|
| 455 |
+
|
| 456 |
+
taker_map: dict[int, float] = {}
|
| 457 |
+
if fetch_taker and len(results) > 1 and not isinstance(results[1], Exception) and isinstance(results[1], list):
|
| 458 |
+
for row in results[1]:
|
| 459 |
+
try:
|
| 460 |
+
ts = int(row[0]) if isinstance(row, (list, tuple)) else int(row.get("ts", 0))
|
| 461 |
+
buy_v = float(row[1]) if isinstance(row, (list, tuple)) else float(row.get("buyVol", 0.0))
|
| 462 |
+
taker_map[ts] = buy_v
|
| 463 |
+
except (IndexError, ValueError, TypeError):
|
| 464 |
+
continue
|
| 465 |
+
|
| 466 |
candles = []
|
| 467 |
+
interval_ms = {"15m": 900_000, "1h": 3_600_000}.get(timeframe, 900_000)
|
| 468 |
for k in reversed(data):
|
| 469 |
# OKX returns: [ts, o, h, l, c, vol, volCcy, volCcyQuote, confirm]
|
| 470 |
# Use k[6] (volCcy) so candle volume is in normalized base coins matching Binance & Bybit
|
| 471 |
vol = float(k[6]) if len(k) > 6 and k[6] else float(k[5])
|
| 472 |
+
c_ts = int(k[0])
|
| 473 |
+
c_dict = {
|
| 474 |
+
"timestamp": c_ts,
|
| 475 |
+
"open": float(k[1]),
|
| 476 |
+
"high": float(k[2]),
|
| 477 |
+
"low": float(k[3]),
|
| 478 |
+
"close": float(k[4]),
|
| 479 |
+
"volume": vol,
|
| 480 |
+
}
|
| 481 |
+
if taker_map:
|
| 482 |
+
if c_ts in taker_map:
|
| 483 |
+
c_dict["taker_buy_volume"] = taker_map[c_ts]
|
| 484 |
+
else:
|
| 485 |
+
best_match = None
|
| 486 |
+
min_diff = interval_ms
|
| 487 |
+
for t_ts, buy_v in taker_map.items():
|
| 488 |
+
diff = abs(c_ts - t_ts)
|
| 489 |
+
if diff < min_diff:
|
| 490 |
+
min_diff = diff
|
| 491 |
+
best_match = buy_v
|
| 492 |
+
if best_match is not None:
|
| 493 |
+
c_dict["taker_buy_volume"] = best_match
|
| 494 |
+
candles.append(c_dict)
|
| 495 |
return candles
|
| 496 |
|
| 497 |
async def _get_ct_val(self, inst_id: str) -> float:
|
tests/test_five_exchange_whale_pov.py
ADDED
|
@@ -0,0 +1,414 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Unit and parity regression tests for Module A: 5-Exchange Data Parity
|
| 3 |
+
(OKX, Bitget, Hyperliquid, DataCollector, BaseExchange, and SignalEngine triangulation).
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import asyncio
|
| 7 |
+
import os
|
| 8 |
+
import sys
|
| 9 |
+
import time
|
| 10 |
+
from typing import Any
|
| 11 |
+
from unittest.mock import AsyncMock, patch
|
| 12 |
+
|
| 13 |
+
import pytest
|
| 14 |
+
|
| 15 |
+
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "backend")))
|
| 16 |
+
|
| 17 |
+
from engine.data_collector import DataCollector
|
| 18 |
+
from engine.signal_engine import _compute_cross_exchange
|
| 19 |
+
from exchanges.base import BaseExchange
|
| 20 |
+
from exchanges.bitget import BitgetClient
|
| 21 |
+
from exchanges.hyperliquid import HyperliquidClient
|
| 22 |
+
from exchanges.okx import OKXClient
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@pytest.mark.anyio
|
| 26 |
+
async def test_okx_parity_spot_smart_money_and_coin_oi_history():
|
| 27 |
+
"""
|
| 28 |
+
Test OKX Parity:
|
| 29 |
+
1. get_spot_trades strips multiplier prefix (1000PEPEUSDT -> PEPE-USDT) and tags venue="okx_spot".
|
| 30 |
+
2. get_long_short_ratio parses top-trader position vs retail account ratio, producing smart_money.
|
| 31 |
+
3. get_open_interest sorts reverse-chronological 5m history, uses oiCcy, tags oi_horizon="15m",
|
| 32 |
+
and computes 15m and 1h changes. Falls back silently to rolling OI when history errors.
|
| 33 |
+
"""
|
| 34 |
+
okx = OKXClient()
|
| 35 |
+
try:
|
| 36 |
+
# 1. Spot Trades
|
| 37 |
+
spot_calls: list[dict] = []
|
| 38 |
+
|
| 39 |
+
async def _mock_spot_get(path: str, params: dict | None = None):
|
| 40 |
+
spot_calls.append({"path": path, "params": params or {}})
|
| 41 |
+
if path == "/api/v5/market/trades" and params.get("instId") == "PEPE-USDT":
|
| 42 |
+
return [
|
| 43 |
+
{"px": "0.0000125", "sz": "100000", "side": "buy", "ts": "1700000002000"},
|
| 44 |
+
{"px": "0.0000124", "sz": "50000", "side": "sell", "ts": "1700000001000"},
|
| 45 |
+
]
|
| 46 |
+
if path == "/api/v5/market/trades" and params.get("instId") == "FAIL-USDT":
|
| 47 |
+
raise RuntimeError("Pair not listed on spot")
|
| 48 |
+
return []
|
| 49 |
+
|
| 50 |
+
okx._get = _mock_spot_get
|
| 51 |
+
trades = await okx.get_spot_trades("1000PEPEUSDT", limit=50)
|
| 52 |
+
assert len(trades) == 2
|
| 53 |
+
assert spot_calls[0]["params"]["instId"] == "PEPE-USDT"
|
| 54 |
+
assert trades[0]["time"] == 1700000001000 # sorted ascending
|
| 55 |
+
assert trades[0]["price"] == 0.0000124
|
| 56 |
+
assert trades[0]["qty"] == 50000.0
|
| 57 |
+
assert trades[0]["is_buyer_maker"] is True # sell side -> buyer is maker
|
| 58 |
+
assert trades[0]["venue"] == "okx_spot"
|
| 59 |
+
|
| 60 |
+
# Silent fallback on error
|
| 61 |
+
failed_trades = await okx.get_spot_trades("FAILUSDT")
|
| 62 |
+
assert failed_trades == []
|
| 63 |
+
|
| 64 |
+
# 2. Smart Money Long/Short Ratio
|
| 65 |
+
async def _mock_ls_get(path: str, params: dict | None = None):
|
| 66 |
+
if path == "/api/v5/rubik/stat/contracts/long-short-account-ratio":
|
| 67 |
+
# ratio = 1.0 -> retail_long_ratio = 1.0 / (1 + 1) = 0.5
|
| 68 |
+
return [["1700000000000", "1.0"]]
|
| 69 |
+
if path == "/api/v5/rubik/stat/contracts/long-short-position-ratio-contract-top-trader":
|
| 70 |
+
# ratio = 1.5 -> top_position_long_ratio = 1.5 / (1 + 1.5) = 0.6
|
| 71 |
+
return [["1700000000000", "1.5"]]
|
| 72 |
+
return []
|
| 73 |
+
|
| 74 |
+
okx._get = _mock_ls_get
|
| 75 |
+
ls = await okx.get_long_short_ratio("1000PEPEUSDT", period="15m")
|
| 76 |
+
assert ls is not None
|
| 77 |
+
assert ls["retail_long_ratio"] == 0.5
|
| 78 |
+
assert ls["top_position_long_ratio"] == 0.6
|
| 79 |
+
assert ls["whale_retail_delta"] == 0.1
|
| 80 |
+
assert ls["source"] == "smart_money"
|
| 81 |
+
assert ls["long_ratio"] == 0.6
|
| 82 |
+
assert ls["short_ratio"] == 0.4
|
| 83 |
+
|
| 84 |
+
# 3. Open Interest: historical 5m series with reverse-chronological order and oiCcy parity
|
| 85 |
+
now_ms = 1700000000000
|
| 86 |
+
# Return 15 bars (reverse-chronological: newest first)
|
| 87 |
+
# oiCcy increases by 10 per 5m bar: bar 0 (oldest) has 100, bar 14 (newest) has 240
|
| 88 |
+
# 15m ago is 3 bars back (bar index 11 in oldest-first, so value 210 vs 240)
|
| 89 |
+
# 1h ago is 12 bars back (bar index 2 in oldest-first, so value 120 vs 240)
|
| 90 |
+
rev_history = []
|
| 91 |
+
for i in range(14, -1, -1):
|
| 92 |
+
ts = str(now_ms - (14 - i) * 300_000)
|
| 93 |
+
oi_contracts = str(1000 + i * 100)
|
| 94 |
+
oi_ccy = str(100.0 + i * 10.0) # coin denomination
|
| 95 |
+
oi_usd = str((100.0 + i * 10.0) * 50.0)
|
| 96 |
+
rev_history.append([ts, oi_contracts, oi_ccy, oi_usd])
|
| 97 |
+
|
| 98 |
+
async def _mock_oi_get(path: str, params: dict | None = None):
|
| 99 |
+
if path == "/api/v5/public/open-interest":
|
| 100 |
+
return [{"oi": "2400", "oiCcy": "240.0", "oiUsd": "12000.0"}]
|
| 101 |
+
if path == "/api/v5/rubik/stat/contracts/open-interest-history":
|
| 102 |
+
return rev_history
|
| 103 |
+
return []
|
| 104 |
+
|
| 105 |
+
okx._get = _mock_oi_get
|
| 106 |
+
oi_res = await okx.get_open_interest("BTCUSDT")
|
| 107 |
+
assert oi_res["open_interest"] == 240.0 # coin denomination
|
| 108 |
+
assert oi_res["oi_horizon"] == "15m"
|
| 109 |
+
# 15m delta: curr=240, 3 bars back=210 -> (240 - 210) / 210 * 100 = 14.2857%
|
| 110 |
+
assert oi_res["oi_change_pct"] == pytest.approx(round((240.0 - 210.0) / 210.0 * 100.0, 4))
|
| 111 |
+
# 1h delta: curr=240, 12 bars back=120 -> (240 - 120) / 120 * 100 = 100.0%
|
| 112 |
+
assert oi_res["oi_change_1h_pct"] == pytest.approx(100.0)
|
| 113 |
+
|
| 114 |
+
# Fallback to rolling OI when history errors
|
| 115 |
+
async def _mock_oi_fallback(path: str, params: dict | None = None):
|
| 116 |
+
if path == "/api/v5/public/open-interest":
|
| 117 |
+
return [{"oi": "1000", "oiCcy": "100.0", "oiUsd": "5000.0"}]
|
| 118 |
+
raise RuntimeError("Rubik history 404")
|
| 119 |
+
|
| 120 |
+
okx._get = _mock_oi_fallback
|
| 121 |
+
fb_res = await okx.get_open_interest("ETHUSDT")
|
| 122 |
+
assert fb_res["open_interest"] == 100.0
|
| 123 |
+
assert fb_res["oi_horizon"] == "rolling"
|
| 124 |
+
assert fb_res["oi_change_1h_pct"] is None
|
| 125 |
+
finally:
|
| 126 |
+
await okx.close()
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
@pytest.mark.anyio
|
| 130 |
+
async def test_bitget_parity_spot_smart_money_taker_and_rolling_meta(monkeypatch):
|
| 131 |
+
"""
|
| 132 |
+
Test Bitget Parity:
|
| 133 |
+
1. get_spot_trades strips multiplier (1000PEPEUSDT -> PEPEUSDT) via /api/v2/spot/market/fills, tagging bitget_spot.
|
| 134 |
+
2. get_long_short_ratio fetches position-long-short and account-long-short, tagging smart_money.
|
| 135 |
+
3. get_ohlcv enriches 15m/1h candles with /api/v2/mix/market/taker-buy-sell matched by timestamp.
|
| 136 |
+
4. get_open_interest keeps empty payload exact contract untouched while tagging populated response
|
| 137 |
+
with oi_horizon="rolling" and oi_window_sec.
|
| 138 |
+
"""
|
| 139 |
+
bg = BitgetClient()
|
| 140 |
+
try:
|
| 141 |
+
# 1. Spot Trades
|
| 142 |
+
bg_calls: list[dict] = []
|
| 143 |
+
|
| 144 |
+
async def _mock_bg_get(path: str, params: dict | None = None):
|
| 145 |
+
bg_calls.append({"path": path, "params": params or {}})
|
| 146 |
+
if path == "/api/v2/spot/market/fills":
|
| 147 |
+
return [
|
| 148 |
+
{"price": "0.000012", "size": "50000", "side": "buy", "ts": "1700000002000"},
|
| 149 |
+
{"price": "0.000011", "size": "30000", "side": "sell", "ts": "1700000001000"},
|
| 150 |
+
]
|
| 151 |
+
return []
|
| 152 |
+
|
| 153 |
+
bg._get = _mock_bg_get
|
| 154 |
+
spot = await bg.get_spot_trades("1000PEPEUSDT", limit=50)
|
| 155 |
+
assert len(spot) == 2
|
| 156 |
+
assert bg_calls[0]["params"]["symbol"] == "PEPEUSDT"
|
| 157 |
+
assert spot[0]["time"] == 1700000001000 # sorted ascending
|
| 158 |
+
assert spot[0]["is_buyer_maker"] is True
|
| 159 |
+
assert spot[0]["venue"] == "bitget_spot"
|
| 160 |
+
|
| 161 |
+
# 2. Smart Money Long/Short Ratio
|
| 162 |
+
async def _mock_bg_ls(path: str, params: dict | None = None):
|
| 163 |
+
if path == "/api/v2/mix/market/position-long-short":
|
| 164 |
+
return [{"longRatio": "0.65", "shortRatio": "0.35", "ts": "1700000000000"}]
|
| 165 |
+
if path == "/api/v2/mix/market/account-long-short":
|
| 166 |
+
return [{"longRatio": "0.45", "shortRatio": "0.55", "ts": "1700000000000"}]
|
| 167 |
+
return []
|
| 168 |
+
|
| 169 |
+
bg._get = _mock_bg_ls
|
| 170 |
+
ls_res = await bg.get_long_short_ratio("BTCUSDT")
|
| 171 |
+
assert ls_res["top_position_long_ratio"] == 0.65
|
| 172 |
+
assert ls_res["retail_long_ratio"] == 0.45
|
| 173 |
+
assert ls_res["whale_retail_delta"] == 0.20
|
| 174 |
+
assert ls_res["source"] == "smart_money"
|
| 175 |
+
assert ls_res["long_ratio"] == 0.65
|
| 176 |
+
|
| 177 |
+
# 3. Taker Buy Volume enrichment in get_ohlcv
|
| 178 |
+
async def _mock_candles_get(path: str, params: dict | None = None):
|
| 179 |
+
if path == "/api/v2/mix/market/candles":
|
| 180 |
+
# Newest first
|
| 181 |
+
return [
|
| 182 |
+
["1700000900000", "100.0", "105.0", "99.0", "104.0", "1000.0"],
|
| 183 |
+
["1700000000000", "95.0", "101.0", "94.0", "100.0", "800.0"],
|
| 184 |
+
]
|
| 185 |
+
if path == "/api/v2/mix/market/taker-buy-sell":
|
| 186 |
+
return [
|
| 187 |
+
{"ts": "1700000000000", "buyVol": "500.0", "sellVol": "300.0"},
|
| 188 |
+
{"ts": "1700000900000", "buyVol": "700.0", "sellVol": "300.0"},
|
| 189 |
+
]
|
| 190 |
+
return []
|
| 191 |
+
|
| 192 |
+
bg._get = _mock_candles_get
|
| 193 |
+
candles = await bg.get_ohlcv("BTCUSDT", timeframe="15m", limit=10)
|
| 194 |
+
assert len(candles) == 2
|
| 195 |
+
assert candles[0]["timestamp"] == 1700000000000
|
| 196 |
+
assert candles[0]["taker_buy_volume"] == 500.0
|
| 197 |
+
assert candles[1]["taker_buy_volume"] == 700.0
|
| 198 |
+
|
| 199 |
+
# 4. Open Interest: empty payload exact contract preservation vs populated metadata
|
| 200 |
+
async def _mock_empty_oi(path: str, params: dict | None = None):
|
| 201 |
+
return {}
|
| 202 |
+
|
| 203 |
+
bg._get = _mock_empty_oi
|
| 204 |
+
empty_res = await bg.get_open_interest("BTCUSDT")
|
| 205 |
+
assert empty_res == {"open_interest": None, "open_interest_value": None, "oi_change_pct": None}
|
| 206 |
+
|
| 207 |
+
# Populated OI test with time progression
|
| 208 |
+
fake_now = [1000.0]
|
| 209 |
+
monkeypatch.setattr("exchanges.base.time.time", lambda: fake_now[0])
|
| 210 |
+
async def _mock_pop_oi(path: str, params: dict | None = None):
|
| 211 |
+
return {"openInterestList": [{"size": "500.0"}]}
|
| 212 |
+
|
| 213 |
+
bg._get = _mock_pop_oi
|
| 214 |
+
bg.get_mark_price = AsyncMock(return_value={"mark_price": 200.0})
|
| 215 |
+
|
| 216 |
+
# Poll 1
|
| 217 |
+
pop_res1 = await bg.get_open_interest("ETHUSDT")
|
| 218 |
+
assert pop_res1["open_interest"] == 500.0
|
| 219 |
+
assert pop_res1["open_interest_value"] == 100000.0
|
| 220 |
+
assert pop_res1["oi_horizon"] == "rolling"
|
| 221 |
+
assert pop_res1["oi_change_pct"] is None
|
| 222 |
+
|
| 223 |
+
# Poll 2 (60s later, size rises to 550)
|
| 224 |
+
fake_now[0] = 1060.0
|
| 225 |
+
async def _mock_pop_oi2(path: str, params: dict | None = None):
|
| 226 |
+
return {"openInterestList": [{"size": "550.0"}]}
|
| 227 |
+
bg._get = _mock_pop_oi2
|
| 228 |
+
pop_res2 = await bg.get_open_interest("ETHUSDT")
|
| 229 |
+
assert pop_res2["open_interest"] == 550.0
|
| 230 |
+
assert pop_res2["oi_horizon"] == "rolling"
|
| 231 |
+
assert pop_res2["oi_change_pct"] == pytest.approx(10.0)
|
| 232 |
+
assert pop_res2["oi_window_sec"] == pytest.approx(60.0)
|
| 233 |
+
finally:
|
| 234 |
+
await bg.close()
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
@pytest.fixture
|
| 238 |
+
def anyio_backend():
|
| 239 |
+
return "asyncio"
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
@pytest.mark.anyio
|
| 243 |
+
async def test_hyperliquid_rolling_oi_ohlcv_and_silent_degradation(monkeypatch):
|
| 244 |
+
"""
|
| 245 |
+
Test Hyperliquid DEX Parity & Silent Degradation:
|
| 246 |
+
1. get_market_data calculates rolling oi_change_pct via BaseExchange shared helper across polls.
|
| 247 |
+
2. get_ohlcv fetches and formats 5m/15m candleSnapshot correctly.
|
| 248 |
+
3. _compute_cross_exchange computes hyperliquid_5m_pct and incorporates it into triangulation.
|
| 249 |
+
4. DataCollector._fetch_hl and get_full_snapshot succeed gracefully when endpoints fail.
|
| 250 |
+
"""
|
| 251 |
+
hl = HyperliquidClient()
|
| 252 |
+
try:
|
| 253 |
+
current_oi = ["1000.0"]
|
| 254 |
+
candles_payload = [
|
| 255 |
+
{"t": 1700000000000, "o": "50000.0", "h": "50200.0", "l": "49900.0", "c": "50100.0", "v": "120.0"},
|
| 256 |
+
{"t": 1700000900000, "o": "50100.0", "h": "50400.0", "l": "50050.0", "c": "50300.0", "v": "150.0"},
|
| 257 |
+
]
|
| 258 |
+
|
| 259 |
+
class _MockResp:
|
| 260 |
+
def __init__(self, data):
|
| 261 |
+
self.status_code = 200
|
| 262 |
+
self._data = data
|
| 263 |
+
|
| 264 |
+
def raise_for_status(self):
|
| 265 |
+
pass
|
| 266 |
+
|
| 267 |
+
def json(self):
|
| 268 |
+
return self._data
|
| 269 |
+
|
| 270 |
+
async def _mock_post(url: str, json: dict | None = None, **kwargs):
|
| 271 |
+
req_type = (json or {}).get("type")
|
| 272 |
+
if req_type == "metaAndAssetCtxs":
|
| 273 |
+
return _MockResp([
|
| 274 |
+
{"universe": [{"name": "BTC"}]},
|
| 275 |
+
[{
|
| 276 |
+
"funding": "0.00001",
|
| 277 |
+
"openInterest": current_oi[0],
|
| 278 |
+
"markPx": "50000.0",
|
| 279 |
+
"oraclePx": "49990.0",
|
| 280 |
+
"dayNtlVlm": "10000000.0",
|
| 281 |
+
}],
|
| 282 |
+
])
|
| 283 |
+
if req_type == "candleSnapshot":
|
| 284 |
+
return _MockResp(candles_payload)
|
| 285 |
+
return _MockResp({})
|
| 286 |
+
|
| 287 |
+
hl._client.post = _mock_post
|
| 288 |
+
|
| 289 |
+
fake_now = [2000.0]
|
| 290 |
+
monkeypatch.setattr("exchanges.base.time.time", lambda: fake_now[0])
|
| 291 |
+
|
| 292 |
+
# Poll 1
|
| 293 |
+
m1 = await hl.get_market_data("BTCUSDT")
|
| 294 |
+
assert m1 is not None
|
| 295 |
+
assert m1["open_interest"] == 1000.0
|
| 296 |
+
assert m1["oi_horizon"] == "rolling"
|
| 297 |
+
assert m1["oi_change_pct"] is None
|
| 298 |
+
|
| 299 |
+
# Poll 2: 70 seconds later OI rises to 1050 (5% gain)
|
| 300 |
+
fake_now[0] = 2070.0
|
| 301 |
+
hl._cache_time = 0 # force refresh meta
|
| 302 |
+
current_oi[0] = "1050.0"
|
| 303 |
+
m2 = await hl.get_market_data("BTCUSDT")
|
| 304 |
+
assert m2 is not None
|
| 305 |
+
assert m2["open_interest"] == 1050.0
|
| 306 |
+
assert m2["oi_horizon"] == "rolling"
|
| 307 |
+
assert m2["oi_change_pct"] == pytest.approx(5.0)
|
| 308 |
+
assert m2["oi_window_sec"] == pytest.approx(70.0)
|
| 309 |
+
|
| 310 |
+
# 2. get_ohlcv candleSnapshot
|
| 311 |
+
hl_candles = await hl.get_ohlcv("BTC", timeframe="15m", limit=10)
|
| 312 |
+
assert len(hl_candles) == 2
|
| 313 |
+
assert hl_candles[0]["timestamp"] == 1700000000000
|
| 314 |
+
assert hl_candles[0]["open"] == 50000.0
|
| 315 |
+
assert hl_candles[0]["close"] == 50100.0
|
| 316 |
+
assert hl_candles[0]["volume"] == 120.0
|
| 317 |
+
|
| 318 |
+
# 3. _compute_cross_exchange triangulation with Hyperliquid 5m OHLCV
|
| 319 |
+
binance_data = {
|
| 320 |
+
"ohlcv": {
|
| 321 |
+
"5m": [
|
| 322 |
+
{"open": 50000.0, "close": 50000.0},
|
| 323 |
+
{"open": 50000.0, "close": 50100.0}, # +0.20%
|
| 324 |
+
]
|
| 325 |
+
}
|
| 326 |
+
}
|
| 327 |
+
bybit_data = {
|
| 328 |
+
"ohlcv": {
|
| 329 |
+
"5m": [
|
| 330 |
+
{"open": 50000.0, "close": 50000.0},
|
| 331 |
+
{"open": 50000.0, "close": 50110.0}, # +0.22%
|
| 332 |
+
]
|
| 333 |
+
}
|
| 334 |
+
}
|
| 335 |
+
hl_data = {
|
| 336 |
+
"basis_pct": 0.015,
|
| 337 |
+
"ohlcv": {
|
| 338 |
+
"5m": [
|
| 339 |
+
{"open": 50000.0, "close": 50000.0},
|
| 340 |
+
{"open": 50000.0, "close": 50105.0}, # +0.21%
|
| 341 |
+
]
|
| 342 |
+
},
|
| 343 |
+
}
|
| 344 |
+
cx = _compute_cross_exchange(binance_data, bybit_data, hl_data=hl_data)
|
| 345 |
+
assert cx["binance_5m_pct"] == pytest.approx(0.20)
|
| 346 |
+
assert cx["bybit_5m_pct"] == pytest.approx(0.22)
|
| 347 |
+
assert cx["hyperliquid_5m_pct"] == pytest.approx(0.21)
|
| 348 |
+
assert cx["hyperliquid_basis_pct"] == pytest.approx(0.015)
|
| 349 |
+
assert cx["dislocation_risk"] is False
|
| 350 |
+
|
| 351 |
+
# 4. Silent Degradation in DataCollector._fetch_hl and get_full_snapshot
|
| 352 |
+
mock_binance = AsyncMock()
|
| 353 |
+
mock_binance.check_symbol_exists.return_value = False
|
| 354 |
+
mock_binance.close = AsyncMock()
|
| 355 |
+
mock_bybit = AsyncMock()
|
| 356 |
+
mock_bybit.check_symbol_exists.return_value = False
|
| 357 |
+
mock_bybit.close = AsyncMock()
|
| 358 |
+
mock_okx = AsyncMock()
|
| 359 |
+
mock_okx.check_symbol_exists.return_value = False
|
| 360 |
+
mock_okx.close = AsyncMock()
|
| 361 |
+
mock_bitget = AsyncMock()
|
| 362 |
+
mock_bitget.check_symbol_exists.return_value = False
|
| 363 |
+
mock_bitget.close = AsyncMock()
|
| 364 |
+
|
| 365 |
+
collector = DataCollector(
|
| 366 |
+
binance=mock_binance,
|
| 367 |
+
bybit=mock_bybit,
|
| 368 |
+
okx=mock_okx,
|
| 369 |
+
bitget=mock_bitget,
|
| 370 |
+
hyperliquid=hl,
|
| 371 |
+
)
|
| 372 |
+
try:
|
| 373 |
+
# When get_ohlcv or recent_trades raises 400/500, _fetch_hl still returns market_data
|
| 374 |
+
hl.get_market_data = AsyncMock(return_value={"coin": "BTC", "open_interest": 1000.0})
|
| 375 |
+
hl.get_orderbook = AsyncMock(return_value={"bids": [], "asks": []})
|
| 376 |
+
hl.get_recent_trades = AsyncMock(side_effect=RuntimeError("HL Trades Network Err"))
|
| 377 |
+
hl.get_ohlcv = AsyncMock(side_effect=RuntimeError("HL OHLCV 400 Bad Request"))
|
| 378 |
+
|
| 379 |
+
with patch("engine.data_collector.check_spot_market_exists", AsyncMock(return_value=True)):
|
| 380 |
+
res = await collector.collect(
|
| 381 |
+
"BTCUSDT",
|
| 382 |
+
on_binance=False,
|
| 383 |
+
on_bybit=False,
|
| 384 |
+
on_okx=False,
|
| 385 |
+
on_bitget=False,
|
| 386 |
+
on_hyperliquid=True,
|
| 387 |
+
)
|
| 388 |
+
|
| 389 |
+
assert res is not None
|
| 390 |
+
assert res["hyperliquid"] is not None
|
| 391 |
+
assert res["hyperliquid"]["open_interest"] == 1000.0
|
| 392 |
+
assert res["hyperliquid"]["trades"] == []
|
| 393 |
+
assert res["hyperliquid"]["ohlcv"] == {"5m": [], "15m": []}
|
| 394 |
+
|
| 395 |
+
# Also verify BaseExchange.get_full_snapshot silent degradation on OKX and Bitget
|
| 396 |
+
okx = OKXClient()
|
| 397 |
+
okx.get_spot_trades = AsyncMock(side_effect=RuntimeError("Spot 500 internal server error"))
|
| 398 |
+
okx.get_mark_price = AsyncMock(return_value={"mark_price": 50000.0})
|
| 399 |
+
okx.get_funding_rate = AsyncMock(return_value={"funding_rate": 0.0001})
|
| 400 |
+
okx.get_open_interest = AsyncMock(return_value={"open_interest": 100.0})
|
| 401 |
+
okx.get_long_short_ratio = AsyncMock(return_value={"long_ratio": 0.5})
|
| 402 |
+
okx.get_recent_trades = AsyncMock(return_value=[])
|
| 403 |
+
okx.get_orderbook = AsyncMock(return_value={"bids": [], "asks": []})
|
| 404 |
+
okx.get_ohlcv = AsyncMock(side_effect=RuntimeError("OHLCV error"))
|
| 405 |
+
|
| 406 |
+
okx_snap = await okx.get_full_snapshot("BTCUSDT")
|
| 407 |
+
assert okx_snap is not None
|
| 408 |
+
assert okx_snap["spot_trades"] is None # safe caught exception
|
| 409 |
+
assert okx_snap["mark_price_data"]["mark_price"] == 50000.0
|
| 410 |
+
await okx.close()
|
| 411 |
+
finally:
|
| 412 |
+
pass
|
| 413 |
+
finally:
|
| 414 |
+
await hl.close()
|