Spaces:
Sleeping
Sleeping
Naufal Arhab commited on
Commit ·
8fe536b
1
Parent(s): d6219d0
feat(engine): add multi-venue time-aligned CVD, whale consensus cap and 4-exchange spot-vs-futures
Browse files- backend/engine/signal_engine.py +394 -77
- tests/test_five_exchange_whale_pov.py +303 -0
backend/engine/signal_engine.py
CHANGED
|
@@ -229,6 +229,58 @@ def _is_half_rising(sorted_trades: list[dict], total_cvd: float) -> bool:
|
|
| 229 |
)
|
| 230 |
|
| 231 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 232 |
# ─────────────────────────────────────────────────────────────────────────────
|
| 233 |
# Individual signal computers
|
| 234 |
# ─────────────────────────────────────────────────────────────────────────────
|
|
@@ -308,49 +360,16 @@ def _compute_funding_rate(
|
|
| 308 |
}
|
| 309 |
|
| 310 |
|
| 311 |
-
def
|
| 312 |
-
|
| 313 |
-
|
| 314 |
ref_mark_px: float | None = None,
|
| 315 |
) -> dict[str, Any]:
|
| 316 |
"""
|
| 317 |
-
Spot vs Futures
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
- Organic Bullish Accumulation (+2): Spot CVD↑ + Futures CVD↑
|
| 321 |
-
- Leverage Trap / Fake Pump (-2): Futures CVD↑ but Spot CVD↓ (Whales dumping spot into retail futures longs)
|
| 322 |
-
- Organic Bearish Selling (-2): Spot CVD↓ + Futures CVD↓
|
| 323 |
-
- Spot Absorption / Short Squeeze (+2): Spot CVD↑ while Futures CVD↓ (Whales quietly accumulating spot while retail shorts)
|
| 324 |
"""
|
| 325 |
-
# Prefer same-venue Spot + Futures pairs before falling back across venues
|
| 326 |
-
spot_trades: list[dict] = []
|
| 327 |
-
futures_trades: list[dict] = []
|
| 328 |
-
if binance_data and binance_data.get("spot_trades") and binance_data.get("trades"):
|
| 329 |
-
spot_trades = binance_data["spot_trades"]
|
| 330 |
-
futures_trades = binance_data["trades"]
|
| 331 |
-
elif bybit_data and bybit_data.get("spot_trades") and bybit_data.get("trades"):
|
| 332 |
-
spot_trades = bybit_data["spot_trades"]
|
| 333 |
-
futures_trades = bybit_data["trades"]
|
| 334 |
-
else:
|
| 335 |
-
if binance_data and binance_data.get("spot_trades"):
|
| 336 |
-
spot_trades = binance_data["spot_trades"]
|
| 337 |
-
elif bybit_data and bybit_data.get("spot_trades"):
|
| 338 |
-
spot_trades = bybit_data["spot_trades"]
|
| 339 |
-
|
| 340 |
-
if binance_data and binance_data.get("trades"):
|
| 341 |
-
futures_trades = binance_data["trades"]
|
| 342 |
-
elif bybit_data and bybit_data.get("trades"):
|
| 343 |
-
futures_trades = bybit_data["trades"]
|
| 344 |
-
|
| 345 |
-
if not futures_trades and not spot_trades:
|
| 346 |
-
return {
|
| 347 |
-
"value": "No Data",
|
| 348 |
-
"score": 0,
|
| 349 |
-
"label": "Trade Data Unavailable",
|
| 350 |
-
"spot_cvd": None,
|
| 351 |
-
"futures_cvd": None,
|
| 352 |
-
}
|
| 353 |
-
|
| 354 |
def _sample_trade_px(trade_list: list[dict]) -> float | None:
|
| 355 |
for tr in trade_list:
|
| 356 |
try:
|
|
@@ -364,28 +383,20 @@ def _compute_spot_futures_cvd(
|
|
| 364 |
spot_px = _sample_trade_px(spot_trades)
|
| 365 |
fut_px = _sample_trade_px(futures_trades)
|
| 366 |
target_px = ref_mark_px if (ref_mark_px and ref_mark_px > 0) else fut_px
|
| 367 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 368 |
spot_scale = _get_multiplier_scale(spot_px, target_px)
|
| 369 |
-
|
| 370 |
-
if
|
| 371 |
fut_scale = _get_multiplier_scale(fut_px, target_px)
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
if not spot_trades:
|
| 375 |
-
fut_buy = sum(float(t.get("qty") or 0.0) for t in futures_trades if not t.get("is_buyer_maker", False))
|
| 376 |
-
fut_sell = sum(float(t.get("qty") or 0.0) for t in futures_trades if t.get("is_buyer_maker", False))
|
| 377 |
-
futures_cvd = fut_buy - fut_sell
|
| 378 |
-
return {
|
| 379 |
-
"value": f"Perp: {futures_cvd:+.1f} (No Spot)",
|
| 380 |
-
"score": 0,
|
| 381 |
-
"label": "Perpetual Only (Spot Market Not Listed)",
|
| 382 |
-
"spot_cvd": None,
|
| 383 |
-
"futures_cvd": round(futures_cvd, 2),
|
| 384 |
-
}
|
| 385 |
|
| 386 |
# Sort trades chronologically and intersect overlapping Spot/Futures time window when populated
|
| 387 |
-
sorted_spot = sorted(
|
| 388 |
-
sorted_fut = sorted(
|
| 389 |
|
| 390 |
spot_times = [float(t.get("time") or 0) for t in sorted_spot if float(t.get("time") or 0) > 0]
|
| 391 |
fut_times = [float(t.get("time") or 0) for t in sorted_fut if float(t.get("time") or 0) > 0]
|
|
@@ -411,11 +422,133 @@ def _compute_spot_futures_cvd(
|
|
| 411 |
futures_cvd = fut_buy - fut_sell
|
| 412 |
fut_ratio = (futures_cvd / fut_total) if fut_total > 0 else 0.0
|
| 413 |
|
| 414 |
-
# Check momentum across timestamp-midpoint halves
|
| 415 |
spot_rising = _is_half_rising(sorted_spot, spot_cvd)
|
| 416 |
fut_rising = _is_half_rising(sorted_fut, futures_cvd)
|
| 417 |
|
| 418 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 419 |
DEADBAND = 0.02
|
| 420 |
spot_bull = spot_ratio >= DEADBAND and spot_rising
|
| 421 |
spot_bear = spot_ratio <= -DEADBAND and not spot_rising
|
|
@@ -454,6 +587,8 @@ def _compute_spot_futures_cvd(
|
|
| 454 |
"futures_delta_ratio": round(fut_ratio, 4),
|
| 455 |
"score": score,
|
| 456 |
"label": label,
|
|
|
|
|
|
|
| 457 |
}
|
| 458 |
|
| 459 |
|
|
@@ -704,28 +839,114 @@ def _compute_cvd(trades: list[dict]) -> dict[str, Any]:
|
|
| 704 |
Cumulative Volume Delta = sum(aggressive_buy_vol) - sum(aggressive_sell_vol).
|
| 705 |
Uses Volume-Normalized Delta Ratio (cvd / total_vol) with a 3% deadband filter
|
| 706 |
to eliminate micro-noise on balanced order flow.
|
|
|
|
| 707 |
"""
|
| 708 |
if not trades:
|
| 709 |
return {"value": 0, "delta_ratio": 0.0, "score": 0, "rising": False, "label": "No Trade Data"}
|
| 710 |
|
| 711 |
-
|
| 712 |
-
|
| 713 |
-
|
| 714 |
-
|
| 715 |
-
|
| 716 |
-
|
| 717 |
-
|
| 718 |
-
|
| 719 |
-
|
| 720 |
-
|
| 721 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 722 |
|
| 723 |
-
|
| 724 |
-
|
| 725 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 726 |
|
| 727 |
-
|
| 728 |
-
|
|
|
|
|
|
|
| 729 |
|
| 730 |
CVD_DEADBAND = 0.03 # 3% net volume imbalance required for directional conviction
|
| 731 |
if abs(delta_ratio) < CVD_DEADBAND:
|
|
@@ -1523,6 +1744,7 @@ def _compute_whale_order_flow(
|
|
| 1523 |
unbucketed_sweeps: list[tuple[float, bool]] = []
|
| 1524 |
# Hyperliquid on-chain wallet tracker: {wallet: [buy_usd, sell_usd]}
|
| 1525 |
wallet_flows: dict[str, list[float]] = {}
|
|
|
|
| 1526 |
|
| 1527 |
if trades and mark_price > 0:
|
| 1528 |
for t in trades:
|
|
@@ -1534,6 +1756,8 @@ def _compute_whale_order_flow(
|
|
| 1534 |
usd_val = px * qty
|
| 1535 |
is_sell_taker = bool(t.get("is_buyer_maker", False))
|
| 1536 |
parsed_trades.append((usd_val, is_sell_taker))
|
|
|
|
|
|
|
| 1537 |
if is_sell_taker:
|
| 1538 |
taker_sell_vol += usd_val
|
| 1539 |
else:
|
|
@@ -1625,6 +1849,9 @@ def _compute_whale_order_flow(
|
|
| 1625 |
"retail_account_long_ratio": retail_acc_lr,
|
| 1626 |
"smart_money_delta": sm_delta,
|
| 1627 |
"whale_composite_score": comp_score,
|
|
|
|
|
|
|
|
|
|
| 1628 |
"flow_verdict": verdict,
|
| 1629 |
}
|
| 1630 |
|
|
@@ -1690,6 +1917,52 @@ def _compute_whale_order_flow(
|
|
| 1690 |
elif onchain_sell_vol_usd > onchain_buy_vol_usd * 1.4 and onchain_sell_vol_usd >= threshold:
|
| 1691 |
onchain_score = -1
|
| 1692 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1693 |
# Also check live tape Iceberg Absorption if not already triggered by klines
|
| 1694 |
if absorption_score == 0 and merged_ohlcv and total_vol >= 25_000.0 and eff_oi_chg >= 0.25:
|
| 1695 |
ref_b = (merged_ohlcv.get("15m") or merged_ohlcv.get("1h") or [])
|
|
@@ -1727,6 +2000,17 @@ def _compute_whale_order_flow(
|
|
| 1727 |
min(2, eff_block_score + eff_twap_score_main + absorption_score + onchain_score),
|
| 1728 |
)
|
| 1729 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1730 |
largest_val, largest_is_sell = max(parsed_trades, key=lambda x: x[0])
|
| 1731 |
largest_side = "SELL" if largest_is_sell else "BUY"
|
| 1732 |
|
|
@@ -1792,6 +2076,9 @@ def _compute_whale_order_flow(
|
|
| 1792 |
"retail_account_long_ratio": retail_acc_lr,
|
| 1793 |
"smart_money_delta": sm_delta,
|
| 1794 |
"whale_composite_score": whale_composite_score,
|
|
|
|
|
|
|
|
|
|
| 1795 |
"flow_verdict": verdict,
|
| 1796 |
}
|
| 1797 |
|
|
@@ -2078,7 +2365,7 @@ class SignalEngine:
|
|
| 2078 |
bitget = raw.get("bitget")
|
| 2079 |
hyperliquid = raw.get("hyperliquid")
|
| 2080 |
has_spot = bool(raw.get("has_spot", False))
|
| 2081 |
-
if
|
| 2082 |
has_spot = True
|
| 2083 |
|
| 2084 |
# ── 1. Individual signals ──────────────────────────────────────────
|
|
@@ -2119,7 +2406,9 @@ class SignalEngine:
|
|
| 2119 |
ref_mark_px = binance_mark or bybit_mark or bitget_mark or okx_mark or hl_mark_px or 0.0
|
| 2120 |
|
| 2121 |
# Institutional Alpha #1: Spot vs Futures CVD (Organic vs Leverage Trap)
|
| 2122 |
-
spot_futures_signal = _compute_spot_futures_cvd(
|
|
|
|
|
|
|
| 2123 |
if not has_spot:
|
| 2124 |
spot_futures_signal["label"] = "⚠️ PERP ONLY (Tidak Ada di Spot - Pasar Sintetis)"
|
| 2125 |
spot_futures_signal["score"] = 0
|
|
@@ -2175,6 +2464,34 @@ class SignalEngine:
|
|
| 2175 |
c_scale = _get_multiplier_scale(src_px, ref_mark_px)
|
| 2176 |
merged_ohlcv[tf] = _normalize_candles_scale(candles, c_scale)
|
| 2177 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2178 |
mtf_result = mtf_analyzer.analyze(merged_ohlcv)
|
| 2179 |
if not trades:
|
| 2180 |
ref_cvd_bars = (merged_ohlcv.get("15m") or merged_ohlcv.get("1h") or [])[-10:]
|
|
|
|
| 229 |
)
|
| 230 |
|
| 231 |
|
| 232 |
+
def _align_multi_venue_trades(trades: list[dict]) -> tuple[dict[str, list[dict]], str]:
|
| 233 |
+
"""
|
| 234 |
+
Partition trades by venue and time-align dense multi-venue feeds:
|
| 235 |
+
- Mode 'single': < 2 distinct venue keys or < 2 dense timestamped venues (len >= 5, time > 0).
|
| 236 |
+
- Mode 'overlap': >= 2 dense venues share an overlap window >= 5,000ms with >= 5 trades each.
|
| 237 |
+
- Mode 'per_venue': multi-venue without sufficient shared overlap window.
|
| 238 |
+
"""
|
| 239 |
+
if not trades:
|
| 240 |
+
return {}, "single"
|
| 241 |
+
|
| 242 |
+
venue_trades: dict[str, list[dict]] = {}
|
| 243 |
+
for t in trades:
|
| 244 |
+
v = t.get("venue")
|
| 245 |
+
if v:
|
| 246 |
+
venue_trades.setdefault(str(v), []).append(t)
|
| 247 |
+
|
| 248 |
+
if len(venue_trades) < 2:
|
| 249 |
+
return {}, "single"
|
| 250 |
+
|
| 251 |
+
# Dense timestamped venues: len >= 5 with time > 0
|
| 252 |
+
dense_venues: dict[str, list[dict]] = {}
|
| 253 |
+
venue_min_t: dict[str, float] = {}
|
| 254 |
+
venue_max_t: dict[str, float] = {}
|
| 255 |
+
|
| 256 |
+
for v, trs in venue_trades.items():
|
| 257 |
+
valid_t = [float(t.get("time") or 0) for t in trs if float(t.get("time") or 0) > 0]
|
| 258 |
+
if len(valid_t) >= 5:
|
| 259 |
+
dense_venues[v] = sorted(trs, key=lambda t: float(t.get("time") or 0))
|
| 260 |
+
venue_min_t[v] = min(valid_t)
|
| 261 |
+
venue_max_t[v] = max(valid_t)
|
| 262 |
+
|
| 263 |
+
if len(dense_venues) < 2:
|
| 264 |
+
return {}, "single"
|
| 265 |
+
|
| 266 |
+
overlap_start = max(venue_min_t.values())
|
| 267 |
+
global_max_t = max(venue_max_t.values())
|
| 268 |
+
|
| 269 |
+
if (global_max_t - overlap_start) >= 5_000:
|
| 270 |
+
aligned: dict[str, list[dict]] = {}
|
| 271 |
+
for v, trs in dense_venues.items():
|
| 272 |
+
in_window = [t for t in trs if overlap_start <= float(t.get("time") or 0) <= global_max_t]
|
| 273 |
+
if in_window:
|
| 274 |
+
aligned[v] = in_window
|
| 275 |
+
|
| 276 |
+
qualifying = [v for v, trs in aligned.items() if len(trs) >= 5]
|
| 277 |
+
if len(qualifying) >= 2:
|
| 278 |
+
return aligned, "overlap"
|
| 279 |
+
|
| 280 |
+
# Fallback to per-venue slices
|
| 281 |
+
return {v: sorted(trs, key=lambda t: float(t.get("time") or 0)) for v, trs in venue_trades.items()}, "per_venue"
|
| 282 |
+
|
| 283 |
+
|
| 284 |
# ─────────────────────────────────────────────────────────────────────────────
|
| 285 |
# Individual signal computers
|
| 286 |
# ─────────────────────────────────────────────────────────────────────────────
|
|
|
|
| 360 |
}
|
| 361 |
|
| 362 |
|
| 363 |
+
def _score_spot_futures_pair(
|
| 364 |
+
spot_trades: list[dict],
|
| 365 |
+
futures_trades: list[dict],
|
| 366 |
ref_mark_px: float | None = None,
|
| 367 |
) -> dict[str, Any]:
|
| 368 |
"""
|
| 369 |
+
Evaluate scale-normalized, time-aligned Spot vs Futures trades for a single venue pair.
|
| 370 |
+
Returns:
|
| 371 |
+
spot_cvd, fut_cvd, spot_ratio, fut_ratio, spot_rising, fut_rising, spot_usd, fut_usd
|
|
|
|
|
|
|
|
|
|
|
|
|
| 372 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 373 |
def _sample_trade_px(trade_list: list[dict]) -> float | None:
|
| 374 |
for tr in trade_list:
|
| 375 |
try:
|
|
|
|
| 383 |
spot_px = _sample_trade_px(spot_trades)
|
| 384 |
fut_px = _sample_trade_px(futures_trades)
|
| 385 |
target_px = ref_mark_px if (ref_mark_px and ref_mark_px > 0) else fut_px
|
| 386 |
+
|
| 387 |
+
s_trades = list(spot_trades)
|
| 388 |
+
f_trades = list(futures_trades)
|
| 389 |
+
|
| 390 |
+
if s_trades and target_px:
|
| 391 |
spot_scale = _get_multiplier_scale(spot_px, target_px)
|
| 392 |
+
s_trades = _normalize_trades_scale(s_trades, spot_scale)
|
| 393 |
+
if f_trades and target_px:
|
| 394 |
fut_scale = _get_multiplier_scale(fut_px, target_px)
|
| 395 |
+
f_trades = _normalize_trades_scale(f_trades, fut_scale)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 396 |
|
| 397 |
# Sort trades chronologically and intersect overlapping Spot/Futures time window when populated
|
| 398 |
+
sorted_spot = sorted(s_trades, key=lambda t: float(t.get("time") or 0))
|
| 399 |
+
sorted_fut = sorted(f_trades, key=lambda t: float(t.get("time") or 0))
|
| 400 |
|
| 401 |
spot_times = [float(t.get("time") or 0) for t in sorted_spot if float(t.get("time") or 0) > 0]
|
| 402 |
fut_times = [float(t.get("time") or 0) for t in sorted_fut if float(t.get("time") or 0) > 0]
|
|
|
|
| 422 |
futures_cvd = fut_buy - fut_sell
|
| 423 |
fut_ratio = (futures_cvd / fut_total) if fut_total > 0 else 0.0
|
| 424 |
|
|
|
|
| 425 |
spot_rising = _is_half_rising(sorted_spot, spot_cvd)
|
| 426 |
fut_rising = _is_half_rising(sorted_fut, futures_cvd)
|
| 427 |
|
| 428 |
+
spot_usd = sum(
|
| 429 |
+
float(t.get("qty") or 0.0) * (float(t.get("price") or 0.0) or target_px or 1.0)
|
| 430 |
+
for t in sorted_spot
|
| 431 |
+
)
|
| 432 |
+
fut_usd = sum(
|
| 433 |
+
float(t.get("qty") or 0.0) * (float(t.get("price") or 0.0) or target_px or 1.0)
|
| 434 |
+
for t in sorted_fut
|
| 435 |
+
)
|
| 436 |
+
|
| 437 |
+
return {
|
| 438 |
+
"spot_cvd": spot_cvd,
|
| 439 |
+
"futures_cvd": futures_cvd,
|
| 440 |
+
"spot_ratio": spot_ratio,
|
| 441 |
+
"futures_ratio": fut_ratio,
|
| 442 |
+
"spot_rising": spot_rising,
|
| 443 |
+
"futures_rising": fut_rising,
|
| 444 |
+
"spot_usd": spot_usd,
|
| 445 |
+
"fut_usd": fut_usd,
|
| 446 |
+
}
|
| 447 |
+
|
| 448 |
+
|
| 449 |
+
def _compute_spot_futures_cvd(
|
| 450 |
+
binance_data: dict | None,
|
| 451 |
+
bybit_data: dict | None,
|
| 452 |
+
okx_data: dict | None = None,
|
| 453 |
+
bitget_data: dict | None = None,
|
| 454 |
+
ref_mark_px: float | None = None,
|
| 455 |
+
) -> dict[str, Any]:
|
| 456 |
+
"""
|
| 457 |
+
Spot vs Futures CVD Divergence across up to 4 exchanges (Binance, Bybit, OKX, Bitget).
|
| 458 |
+
Pairs same-venue (spot_trades, trades), applies multiplier scale normalization & time alignment,
|
| 459 |
+
aggregates USD-notional weighted ratios/momentum, and falls back to cross-venue pairing
|
| 460 |
+
when no same-venue pairs exist.
|
| 461 |
+
"""
|
| 462 |
+
venues_input = [
|
| 463 |
+
("binance", binance_data),
|
| 464 |
+
("bybit", bybit_data),
|
| 465 |
+
("okx", okx_data),
|
| 466 |
+
("bitget", bitget_data),
|
| 467 |
+
]
|
| 468 |
+
|
| 469 |
+
# 1. Identify same-venue pairs (where both spot_trades and trades exist)
|
| 470 |
+
same_venue_pairs: list[tuple[str, dict]] = []
|
| 471 |
+
for v_name, v_data in venues_input:
|
| 472 |
+
if v_data and v_data.get("spot_trades") and v_data.get("trades"):
|
| 473 |
+
pair_res = _score_spot_futures_pair(
|
| 474 |
+
v_data["spot_trades"],
|
| 475 |
+
v_data["trades"],
|
| 476 |
+
ref_mark_px=ref_mark_px,
|
| 477 |
+
)
|
| 478 |
+
same_venue_pairs.append((v_name, pair_res))
|
| 479 |
+
|
| 480 |
+
if same_venue_pairs:
|
| 481 |
+
spot_venues = [v_name for v_name, _ in same_venue_pairs]
|
| 482 |
+
venues_count = len(spot_venues)
|
| 483 |
+
|
| 484 |
+
total_spot_usd = sum(p["spot_usd"] for _, p in same_venue_pairs)
|
| 485 |
+
total_fut_usd = sum(p["fut_usd"] for _, p in same_venue_pairs)
|
| 486 |
+
|
| 487 |
+
if total_spot_usd > 0:
|
| 488 |
+
spot_ratio = sum(p["spot_ratio"] * p["spot_usd"] for _, p in same_venue_pairs) / total_spot_usd
|
| 489 |
+
spot_rising = (sum((1.0 if p["spot_rising"] else 0.0) * p["spot_usd"] for _, p in same_venue_pairs) / total_spot_usd) > 0.5
|
| 490 |
+
else:
|
| 491 |
+
spot_ratio = sum(p["spot_ratio"] for _, p in same_venue_pairs) / venues_count
|
| 492 |
+
spot_rising = any(p["spot_rising"] for _, p in same_venue_pairs)
|
| 493 |
+
|
| 494 |
+
if total_fut_usd > 0:
|
| 495 |
+
fut_ratio = sum(p["futures_ratio"] * p["fut_usd"] for _, p in same_venue_pairs) / total_fut_usd
|
| 496 |
+
fut_rising = (sum((1.0 if p["futures_rising"] else 0.0) * p["fut_usd"] for _, p in same_venue_pairs) / total_fut_usd) > 0.5
|
| 497 |
+
else:
|
| 498 |
+
fut_ratio = sum(p["futures_ratio"] for _, p in same_venue_pairs) / venues_count
|
| 499 |
+
fut_rising = any(p["futures_rising"] for _, p in same_venue_pairs)
|
| 500 |
+
|
| 501 |
+
spot_cvd = sum(p["spot_cvd"] for _, p in same_venue_pairs)
|
| 502 |
+
futures_cvd = sum(p["futures_cvd"] for _, p in same_venue_pairs)
|
| 503 |
+
|
| 504 |
+
else:
|
| 505 |
+
# Cross-venue fallback: combine all spot trades and all futures trades
|
| 506 |
+
all_spot_trades: list[dict] = []
|
| 507 |
+
all_fut_trades: list[dict] = []
|
| 508 |
+
spot_venues = []
|
| 509 |
+
|
| 510 |
+
for v_name, v_data in venues_input:
|
| 511 |
+
if v_data and v_data.get("spot_trades"):
|
| 512 |
+
all_spot_trades.extend(v_data["spot_trades"])
|
| 513 |
+
spot_venues.append(v_name)
|
| 514 |
+
if v_data and v_data.get("trades"):
|
| 515 |
+
all_fut_trades.extend(v_data["trades"])
|
| 516 |
+
|
| 517 |
+
if not all_fut_trades and not all_spot_trades:
|
| 518 |
+
return {
|
| 519 |
+
"value": "No Data",
|
| 520 |
+
"score": 0,
|
| 521 |
+
"label": "Trade Data Unavailable",
|
| 522 |
+
"spot_cvd": None,
|
| 523 |
+
"futures_cvd": None,
|
| 524 |
+
"venues_count": 0,
|
| 525 |
+
"spot_venues": [],
|
| 526 |
+
}
|
| 527 |
+
|
| 528 |
+
if not all_spot_trades:
|
| 529 |
+
fut_buy = sum(float(t.get("qty") or 0.0) for t in all_fut_trades if not t.get("is_buyer_maker", False))
|
| 530 |
+
fut_sell = sum(float(t.get("qty") or 0.0) for t in all_fut_trades if t.get("is_buyer_maker", False))
|
| 531 |
+
futures_cvd = fut_buy - fut_sell
|
| 532 |
+
return {
|
| 533 |
+
"value": f"Perp: {futures_cvd:+.1f} (No Spot)",
|
| 534 |
+
"score": 0,
|
| 535 |
+
"label": "Perpetual Only (Spot Market Not Listed)",
|
| 536 |
+
"spot_cvd": None,
|
| 537 |
+
"futures_cvd": round(futures_cvd, 2),
|
| 538 |
+
"venues_count": 0,
|
| 539 |
+
"spot_venues": [],
|
| 540 |
+
}
|
| 541 |
+
|
| 542 |
+
# Both spot and futures exist across venues
|
| 543 |
+
fb_pair = _score_spot_futures_pair(all_spot_trades, all_fut_trades, ref_mark_px=ref_mark_px)
|
| 544 |
+
spot_cvd = fb_pair["spot_cvd"]
|
| 545 |
+
futures_cvd = fb_pair["futures_cvd"]
|
| 546 |
+
spot_ratio = fb_pair["spot_ratio"]
|
| 547 |
+
fut_ratio = fb_pair["futures_ratio"]
|
| 548 |
+
spot_rising = fb_pair["spot_rising"]
|
| 549 |
+
fut_rising = fb_pair["futures_rising"]
|
| 550 |
+
venues_count = len(spot_venues)
|
| 551 |
+
|
| 552 |
DEADBAND = 0.02
|
| 553 |
spot_bull = spot_ratio >= DEADBAND and spot_rising
|
| 554 |
spot_bear = spot_ratio <= -DEADBAND and not spot_rising
|
|
|
|
| 587 |
"futures_delta_ratio": round(fut_ratio, 4),
|
| 588 |
"score": score,
|
| 589 |
"label": label,
|
| 590 |
+
"venues_count": venues_count,
|
| 591 |
+
"spot_venues": spot_venues,
|
| 592 |
}
|
| 593 |
|
| 594 |
|
|
|
|
| 839 |
Cumulative Volume Delta = sum(aggressive_buy_vol) - sum(aggressive_sell_vol).
|
| 840 |
Uses Volume-Normalized Delta Ratio (cvd / total_vol) with a 3% deadband filter
|
| 841 |
to eliminate micro-noise on balanced order flow.
|
| 842 |
+
Supports multi-venue time alignment (overlap / per_venue) with single-venue backward compatibility.
|
| 843 |
"""
|
| 844 |
if not trades:
|
| 845 |
return {"value": 0, "delta_ratio": 0.0, "score": 0, "rising": False, "label": "No Trade Data"}
|
| 846 |
|
| 847 |
+
slices, mode = _align_multi_venue_trades(trades)
|
| 848 |
+
|
| 849 |
+
if mode == "overlap":
|
| 850 |
+
total_buy_usd = 0.0
|
| 851 |
+
total_sell_usd = 0.0
|
| 852 |
+
total_buy_qty = 0.0
|
| 853 |
+
total_sell_qty = 0.0
|
| 854 |
+
weighted_rising_sum = 0.0
|
| 855 |
+
total_venue_usd = 0.0
|
| 856 |
+
|
| 857 |
+
for v, v_trades in slices.items():
|
| 858 |
+
v_buy_usd = 0.0
|
| 859 |
+
v_sell_usd = 0.0
|
| 860 |
+
v_buy_qty = 0.0
|
| 861 |
+
v_sell_qty = 0.0
|
| 862 |
+
for t in v_trades:
|
| 863 |
+
qty = float(t.get("qty") or 0.0)
|
| 864 |
+
px = float(t.get("price") or 0.0)
|
| 865 |
+
usd = qty * px if px > 0 else qty
|
| 866 |
+
if t.get("is_buyer_maker", False):
|
| 867 |
+
v_sell_usd += usd
|
| 868 |
+
v_sell_qty += qty
|
| 869 |
+
else:
|
| 870 |
+
v_buy_usd += usd
|
| 871 |
+
v_buy_qty += qty
|
| 872 |
+
v_tot_usd = v_buy_usd + v_sell_usd
|
| 873 |
+
v_cvd_qty = v_buy_qty - v_sell_qty
|
| 874 |
+
v_rising = _is_half_rising(v_trades, v_cvd_qty)
|
| 875 |
+
|
| 876 |
+
total_buy_usd += v_buy_usd
|
| 877 |
+
total_sell_usd += v_sell_usd
|
| 878 |
+
total_buy_qty += v_buy_qty
|
| 879 |
+
total_sell_qty += v_sell_qty
|
| 880 |
+
if v_tot_usd > 0:
|
| 881 |
+
weighted_rising_sum += (1.0 if v_rising else 0.0) * v_tot_usd
|
| 882 |
+
total_venue_usd += v_tot_usd
|
| 883 |
+
|
| 884 |
+
cvd = total_buy_qty - total_sell_qty
|
| 885 |
+
total_vol = total_buy_qty + total_sell_qty
|
| 886 |
+
delta_ratio = (cvd / total_vol) if total_vol > 0 else 0.0
|
| 887 |
+
cvd_rising = (weighted_rising_sum / total_venue_usd > 0.5) if total_venue_usd > 0 else False
|
| 888 |
+
|
| 889 |
+
elif mode == "per_venue":
|
| 890 |
+
venue_stats: list[tuple[float, bool, float, float]] = [] # (delta_ratio_v, is_rising_v, vol_v, cvd_qty_v)
|
| 891 |
+
total_buy_qty = 0.0
|
| 892 |
+
total_sell_qty = 0.0
|
| 893 |
+
|
| 894 |
+
for v, v_trades in slices.items():
|
| 895 |
+
v_buy_usd = 0.0
|
| 896 |
+
v_sell_usd = 0.0
|
| 897 |
+
v_buy_qty = 0.0
|
| 898 |
+
v_sell_qty = 0.0
|
| 899 |
+
for t in v_trades:
|
| 900 |
+
qty = float(t.get("qty") or 0.0)
|
| 901 |
+
px = float(t.get("price") or 0.0)
|
| 902 |
+
usd = qty * px if px > 0 else qty
|
| 903 |
+
if t.get("is_buyer_maker", False):
|
| 904 |
+
v_sell_usd += usd
|
| 905 |
+
v_sell_qty += qty
|
| 906 |
+
else:
|
| 907 |
+
v_buy_usd += usd
|
| 908 |
+
v_buy_qty += qty
|
| 909 |
+
v_tot_usd = v_buy_usd + v_sell_usd
|
| 910 |
+
v_cvd_qty = v_buy_qty - v_sell_qty
|
| 911 |
+
v_delta_ratio = (v_buy_usd - v_sell_usd) / v_tot_usd if v_tot_usd > 0 else 0.0
|
| 912 |
+
v_rising = _is_half_rising(v_trades, v_cvd_qty)
|
| 913 |
+
venue_stats.append((v_delta_ratio, v_rising, v_tot_usd, v_cvd_qty))
|
| 914 |
+
total_buy_qty += v_buy_qty
|
| 915 |
+
total_sell_qty += v_sell_qty
|
| 916 |
+
|
| 917 |
+
vols = [st[2] for st in venue_stats if st[2] > 0]
|
| 918 |
+
sorted_vols = sorted(vols)
|
| 919 |
+
median_vol = sorted_vols[len(sorted_vols) // 2] if sorted_vols else 1.0
|
| 920 |
+
|
| 921 |
+
tot_w = 0.0
|
| 922 |
+
weighted_delta_sum = 0.0
|
| 923 |
+
weighted_rising_sum = 0.0
|
| 924 |
+
for dr_v, ris_v, vol_v, _ in venue_stats:
|
| 925 |
+
w_v = min(vol_v, median_vol * 2.0)
|
| 926 |
+
tot_w += w_v
|
| 927 |
+
weighted_delta_sum += dr_v * w_v
|
| 928 |
+
weighted_rising_sum += (1.0 if ris_v else 0.0) * w_v
|
| 929 |
+
|
| 930 |
+
delta_ratio = (weighted_delta_sum / tot_w) if tot_w > 0 else 0.0
|
| 931 |
+
cvd_rising = (weighted_rising_sum / tot_w > 0.5) if tot_w > 0 else False
|
| 932 |
+
cvd = total_buy_qty - total_sell_qty
|
| 933 |
|
| 934 |
+
else:
|
| 935 |
+
# Single-venue fallback (bit-identical to existing logic)
|
| 936 |
+
sorted_trades = sorted(trades, key=lambda t: float(t.get("time") or 0))
|
| 937 |
+
buy_vol = 0.0
|
| 938 |
+
sell_vol = 0.0
|
| 939 |
+
for t in sorted_trades:
|
| 940 |
+
qty = float(t.get("qty") or 0.0)
|
| 941 |
+
if t.get("is_buyer_maker", False):
|
| 942 |
+
sell_vol += qty
|
| 943 |
+
else:
|
| 944 |
+
buy_vol += qty
|
| 945 |
|
| 946 |
+
total_vol = buy_vol + sell_vol
|
| 947 |
+
cvd = buy_vol - sell_vol
|
| 948 |
+
delta_ratio = (cvd / total_vol) if total_vol > 0 else 0.0
|
| 949 |
+
cvd_rising = _is_half_rising(sorted_trades, cvd)
|
| 950 |
|
| 951 |
CVD_DEADBAND = 0.03 # 3% net volume imbalance required for directional conviction
|
| 952 |
if abs(delta_ratio) < CVD_DEADBAND:
|
|
|
|
| 1744 |
unbucketed_sweeps: list[tuple[float, bool]] = []
|
| 1745 |
# Hyperliquid on-chain wallet tracker: {wallet: [buy_usd, sell_usd]}
|
| 1746 |
wallet_flows: dict[str, list[float]] = {}
|
| 1747 |
+
venue_parsed: dict[str, list[tuple[float, bool]]] = {}
|
| 1748 |
|
| 1749 |
if trades and mark_price > 0:
|
| 1750 |
for t in trades:
|
|
|
|
| 1756 |
usd_val = px * qty
|
| 1757 |
is_sell_taker = bool(t.get("is_buyer_maker", False))
|
| 1758 |
parsed_trades.append((usd_val, is_sell_taker))
|
| 1759 |
+
v_name = str(t.get("venue") or "default")
|
| 1760 |
+
venue_parsed.setdefault(v_name, []).append((usd_val, is_sell_taker))
|
| 1761 |
if is_sell_taker:
|
| 1762 |
taker_sell_vol += usd_val
|
| 1763 |
else:
|
|
|
|
| 1849 |
"retail_account_long_ratio": retail_acc_lr,
|
| 1850 |
"smart_money_delta": sm_delta,
|
| 1851 |
"whale_composite_score": comp_score,
|
| 1852 |
+
"whale_venues_bull": 0,
|
| 1853 |
+
"whale_venues_bear": 0,
|
| 1854 |
+
"cross_venue_whale_aligned": False,
|
| 1855 |
"flow_verdict": verdict,
|
| 1856 |
}
|
| 1857 |
|
|
|
|
| 1917 |
elif onchain_sell_vol_usd > onchain_buy_vol_usd * 1.4 and onchain_sell_vol_usd >= threshold:
|
| 1918 |
onchain_score = -1
|
| 1919 |
|
| 1920 |
+
# Per-venue independent evaluation when >= 2 venues present
|
| 1921 |
+
active_trade_venues = [v for v, trs in venue_parsed.items() if v != "default" and trs]
|
| 1922 |
+
if not active_trade_venues and "default" in venue_parsed:
|
| 1923 |
+
active_trade_venues = ["default"]
|
| 1924 |
+
|
| 1925 |
+
whale_venues_bull = 0
|
| 1926 |
+
whale_venues_bear = 0
|
| 1927 |
+
|
| 1928 |
+
if len(active_trade_venues) >= 2:
|
| 1929 |
+
for v in active_trade_venues:
|
| 1930 |
+
v_trs = venue_parsed[v]
|
| 1931 |
+
v_vals = sorted(val for val, _ in v_trs)
|
| 1932 |
+
v_n = len(v_vals)
|
| 1933 |
+
v_vol = sum(v_vals)
|
| 1934 |
+
if v_n >= 20:
|
| 1935 |
+
v_p_idx = min(v_n - 1, int(0.95 * (v_n - 1)))
|
| 1936 |
+
v_anchor = v_vals[v_p_idx]
|
| 1937 |
+
else:
|
| 1938 |
+
v_anchor = v_vals[v_n // 2] if v_n > 0 else 0.0
|
| 1939 |
+
min_venue_thresh = max(5000.0, v_anchor, v_vol * 0.015)
|
| 1940 |
+
|
| 1941 |
+
v_buys = [val for val, is_sell in v_trs if (not is_sell) and val >= min_venue_thresh]
|
| 1942 |
+
v_sells = [val for val, is_sell in v_trs if is_sell and val >= min_venue_thresh]
|
| 1943 |
+
v_sw_buys = [val for (ven, _, is_sell), val in sweep_buckets.items() if ven == v and (not is_sell) and val >= min_venue_thresh]
|
| 1944 |
+
v_sw_sells = [val for (ven, _, is_sell), val in sweep_buckets.items() if ven == v and is_sell and val >= min_venue_thresh]
|
| 1945 |
+
v_eff_buy = max(sum(v_buys), sum(v_sw_buys))
|
| 1946 |
+
v_eff_sell = max(sum(v_sells), sum(v_sw_sells))
|
| 1947 |
+
|
| 1948 |
+
if v_eff_buy >= min_venue_thresh and (v_eff_buy > v_eff_sell * 1.2 or (len(v_buys) > 0 and len(v_sells) == 0)):
|
| 1949 |
+
whale_venues_bull += 1
|
| 1950 |
+
if v_eff_sell >= min_venue_thresh and (v_eff_sell > v_eff_buy * 1.2 or (len(v_sells) > 0 and len(v_buys) == 0)):
|
| 1951 |
+
whale_venues_bear += 1
|
| 1952 |
+
else:
|
| 1953 |
+
eff_w_buy = max(whale_buy_vol, sweep_buy_vol)
|
| 1954 |
+
eff_w_sell = max(whale_sell_vol, sweep_sell_vol)
|
| 1955 |
+
if eff_w_buy >= threshold and eff_w_buy > eff_w_sell * 1.4:
|
| 1956 |
+
whale_venues_bull = 1
|
| 1957 |
+
elif eff_w_sell >= threshold and eff_w_sell > eff_w_buy * 1.4:
|
| 1958 |
+
whale_venues_bear = 1
|
| 1959 |
+
|
| 1960 |
+
cross_venue_whale_aligned = False
|
| 1961 |
+
if whale_venues_bull >= 2 or (whale_venues_bull >= 1 and onchain_score > 0):
|
| 1962 |
+
cross_venue_whale_aligned = True
|
| 1963 |
+
elif whale_venues_bear >= 2 or (whale_venues_bear >= 1 and onchain_score < 0):
|
| 1964 |
+
cross_venue_whale_aligned = True
|
| 1965 |
+
|
| 1966 |
# Also check live tape Iceberg Absorption if not already triggered by klines
|
| 1967 |
if absorption_score == 0 and merged_ohlcv and total_vol >= 25_000.0 and eff_oi_chg >= 0.25:
|
| 1968 |
ref_b = (merged_ohlcv.get("15m") or merged_ohlcv.get("1h") or [])
|
|
|
|
| 2000 |
min(2, eff_block_score + eff_twap_score_main + absorption_score + onchain_score),
|
| 2001 |
)
|
| 2002 |
|
| 2003 |
+
# Single-venue block-only cap:
|
| 2004 |
+
# When >= 2 trade venues active and unconfirmed by cross-venue / TWAP / iceberg / onchain
|
| 2005 |
+
if (
|
| 2006 |
+
len(active_trade_venues) >= 2
|
| 2007 |
+
and not cross_venue_whale_aligned
|
| 2008 |
+
and eff_twap_score_main == 0
|
| 2009 |
+
and absorption_score == 0
|
| 2010 |
+
and onchain_score == 0
|
| 2011 |
+
):
|
| 2012 |
+
whale_composite_score = max(-1, min(1, whale_composite_score))
|
| 2013 |
+
|
| 2014 |
largest_val, largest_is_sell = max(parsed_trades, key=lambda x: x[0])
|
| 2015 |
largest_side = "SELL" if largest_is_sell else "BUY"
|
| 2016 |
|
|
|
|
| 2076 |
"retail_account_long_ratio": retail_acc_lr,
|
| 2077 |
"smart_money_delta": sm_delta,
|
| 2078 |
"whale_composite_score": whale_composite_score,
|
| 2079 |
+
"whale_venues_bull": whale_venues_bull,
|
| 2080 |
+
"whale_venues_bear": whale_venues_bear,
|
| 2081 |
+
"cross_venue_whale_aligned": cross_venue_whale_aligned,
|
| 2082 |
"flow_verdict": verdict,
|
| 2083 |
}
|
| 2084 |
|
|
|
|
| 2365 |
bitget = raw.get("bitget")
|
| 2366 |
hyperliquid = raw.get("hyperliquid")
|
| 2367 |
has_spot = bool(raw.get("has_spot", False))
|
| 2368 |
+
if any(ex and ex.get("spot_trades") for ex in (binance, bybit, okx, bitget)):
|
| 2369 |
has_spot = True
|
| 2370 |
|
| 2371 |
# ── 1. Individual signals ──────────────────────────────────────────
|
|
|
|
| 2406 |
ref_mark_px = binance_mark or bybit_mark or bitget_mark or okx_mark or hl_mark_px or 0.0
|
| 2407 |
|
| 2408 |
# Institutional Alpha #1: Spot vs Futures CVD (Organic vs Leverage Trap)
|
| 2409 |
+
spot_futures_signal = _compute_spot_futures_cvd(
|
| 2410 |
+
binance, bybit, okx_data=okx, bitget_data=bitget, ref_mark_px=ref_mark_px
|
| 2411 |
+
)
|
| 2412 |
if not has_spot:
|
| 2413 |
spot_futures_signal["label"] = "⚠️ PERP ONLY (Tidak Ada di Spot - Pasar Sintetis)"
|
| 2414 |
spot_futures_signal["score"] = 0
|
|
|
|
| 2464 |
c_scale = _get_multiplier_scale(src_px, ref_mark_px)
|
| 2465 |
merged_ohlcv[tf] = _normalize_candles_scale(candles, c_scale)
|
| 2466 |
|
| 2467 |
+
# Backfill taker_buy_volume on 15m and 1h when primary candle feed lacks it
|
| 2468 |
+
for tf in ("15m", "1h"):
|
| 2469 |
+
target_candles = merged_ohlcv.get(tf)
|
| 2470 |
+
if target_candles and not any(c.get("taker_buy_volume") is not None for c in target_candles):
|
| 2471 |
+
for aux_data, aux_mark in ohlcv_sources:
|
| 2472 |
+
aux_cand = aux_data.get("ohlcv", {}).get(tf) if aux_data else None
|
| 2473 |
+
if aux_cand and any(c.get("taker_buy_volume") is not None for c in aux_cand):
|
| 2474 |
+
aux_scale = _get_multiplier_scale(aux_mark, ref_mark_px)
|
| 2475 |
+
norm_aux = _normalize_candles_scale(aux_cand, aux_scale)
|
| 2476 |
+
aux_by_ts = {
|
| 2477 |
+
int(c.get("timestamp") or c.get("time") or 0): c
|
| 2478 |
+
for c in norm_aux
|
| 2479 |
+
if (c.get("timestamp") or c.get("time"))
|
| 2480 |
+
}
|
| 2481 |
+
for b in target_candles:
|
| 2482 |
+
ts = int(b.get("timestamp") or b.get("time") or 0)
|
| 2483 |
+
aux_c = aux_by_ts.get(ts)
|
| 2484 |
+
if aux_c and aux_c.get("taker_buy_volume") is not None:
|
| 2485 |
+
aux_tb = float(aux_c["taker_buy_volume"])
|
| 2486 |
+
aux_v = float(aux_c.get("volume", 0.0) or 0.0)
|
| 2487 |
+
b_v = float(b.get("volume", 0.0) or 0.0)
|
| 2488 |
+
if aux_v > 0 and b_v > 0:
|
| 2489 |
+
b["taker_buy_volume"] = (aux_tb / aux_v) * b_v
|
| 2490 |
+
else:
|
| 2491 |
+
b["taker_buy_volume"] = aux_tb
|
| 2492 |
+
if any(c.get("taker_buy_volume") is not None for c in target_candles):
|
| 2493 |
+
break
|
| 2494 |
+
|
| 2495 |
mtf_result = mtf_analyzer.analyze(merged_ohlcv)
|
| 2496 |
if not trades:
|
| 2497 |
ref_cvd_bars = (merged_ohlcv.get("15m") or merged_ohlcv.get("1h") or [])[-10:]
|
tests/test_five_exchange_whale_pov.py
CHANGED
|
@@ -412,3 +412,306 @@ async def test_hyperliquid_rolling_oi_ohlcv_and_silent_degradation(monkeypatch):
|
|
| 412 |
pass
|
| 413 |
finally:
|
| 414 |
await hl.close()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 412 |
pass
|
| 413 |
finally:
|
| 414 |
await hl.close()
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
def test_cvd_time_alignment_prevents_500_vs_100_trade_distortion():
|
| 418 |
+
"""
|
| 419 |
+
Module B Task 2 Test 1:
|
| 420 |
+
Verifies multi-venue CVD time alignment:
|
| 421 |
+
- Case A: Binance has 500 dense trades in [t_now - 25s, t_now] mildly net-selling (falling)
|
| 422 |
+
while OKX has 100 trades stretched over [t_now - 900s, t_now] where [t_now - 900s, t_now - 30s]
|
| 423 |
+
was heavy selling and [t_now - 25s, t_now] turned strongly buying.
|
| 424 |
+
Verifies cvd_rising reflects the shared active window (falling, False) instead of falsely
|
| 425 |
+
counting old OKX prints in first_half.
|
| 426 |
+
- Case B: Non-overlapping fallback when Binance spans < 5s vs slower OKX trades -> mode drops to 'per_venue'.
|
| 427 |
+
- Case C (Review Focus #3): Synthetic single-venue trades without 'time' or 'venue' hits ('single') mode.
|
| 428 |
+
"""
|
| 429 |
+
from engine.signal_engine import _align_multi_venue_trades, _compute_cvd
|
| 430 |
+
|
| 431 |
+
t_now = 1_700_000_000_000
|
| 432 |
+
|
| 433 |
+
# 1. Case A: Overlap window >= 5s across Binance & OKX
|
| 434 |
+
# Binance: 500 dense trades in [t_now - 25_000, t_now].
|
| 435 |
+
# Binance in [t_now - 25s, t_now] is net-selling and falling:
|
| 436 |
+
# First 250 trades: 130 buys, 120 sells. Second 250 trades: 110 buys, 140 sells.
|
| 437 |
+
binance_trades = []
|
| 438 |
+
for i in range(500):
|
| 439 |
+
t_trade = t_now - 25_000 + i * 50
|
| 440 |
+
if i < 250:
|
| 441 |
+
is_sell = (i % 25 < 12) # 12 sells, 13 buys -> 120 sells, 130 buys
|
| 442 |
+
else:
|
| 443 |
+
is_sell = (i % 25 < 14) # 14 sells, 11 buys -> 140 sells, 110 buys
|
| 444 |
+
binance_trades.append({
|
| 445 |
+
"time": t_trade,
|
| 446 |
+
"qty": 1.0,
|
| 447 |
+
"price": 50000.0,
|
| 448 |
+
"is_buyer_maker": is_sell,
|
| 449 |
+
"venue": "binance",
|
| 450 |
+
})
|
| 451 |
+
|
| 452 |
+
# OKX: 100 trades stretched over [t_now - 900_000, t_now].
|
| 453 |
+
# In [t_now - 900s, t_now - 30s]: 80 trades, all heavy selling.
|
| 454 |
+
# In [t_now - 25s, t_now]: 20 trades, strongly buying.
|
| 455 |
+
okx_trades = []
|
| 456 |
+
for i in range(80):
|
| 457 |
+
t_trade = t_now - 900_000 + i * 10_000
|
| 458 |
+
okx_trades.append({
|
| 459 |
+
"time": t_trade,
|
| 460 |
+
"qty": 0.5,
|
| 461 |
+
"price": 50000.0,
|
| 462 |
+
"is_buyer_maker": True,
|
| 463 |
+
"venue": "okx",
|
| 464 |
+
})
|
| 465 |
+
for i in range(20):
|
| 466 |
+
t_trade = t_now - 20_000 + i * 1_000
|
| 467 |
+
okx_trades.append({
|
| 468 |
+
"time": t_trade,
|
| 469 |
+
"qty": 0.5,
|
| 470 |
+
"price": 50000.0,
|
| 471 |
+
"is_buyer_maker": False,
|
| 472 |
+
"venue": "okx",
|
| 473 |
+
})
|
| 474 |
+
|
| 475 |
+
all_trades = binance_trades + okx_trades
|
| 476 |
+
aligned_slices, mode = _align_multi_venue_trades(all_trades)
|
| 477 |
+
assert mode == "overlap"
|
| 478 |
+
assert "binance" in aligned_slices
|
| 479 |
+
assert "okx" in aligned_slices
|
| 480 |
+
# OKX old 80 trades from 900s ago should be excluded from aligned slice
|
| 481 |
+
assert len(aligned_slices["okx"]) == 20
|
| 482 |
+
assert len(aligned_slices["binance"]) == 500
|
| 483 |
+
|
| 484 |
+
cvd_res = _compute_cvd(all_trades)
|
| 485 |
+
# The active window CVD reflects Binance's dominant falling flow, NOT the old OKX selloff
|
| 486 |
+
assert cvd_res["rising"] is False
|
| 487 |
+
|
| 488 |
+
# 2. Case B: Binance spans < 5s vs slower OKX trades -> mode drops to "per_venue"
|
| 489 |
+
short_binance = [
|
| 490 |
+
{
|
| 491 |
+
"time": t_now - 3000 + i * 300,
|
| 492 |
+
"qty": 1.0,
|
| 493 |
+
"price": 50000.0,
|
| 494 |
+
"is_buyer_maker": False,
|
| 495 |
+
"venue": "binance",
|
| 496 |
+
}
|
| 497 |
+
for i in range(10)
|
| 498 |
+
]
|
| 499 |
+
slices_b, mode_b = _align_multi_venue_trades(short_binance + okx_trades)
|
| 500 |
+
assert mode_b == "per_venue"
|
| 501 |
+
assert len(slices_b["binance"]) == 10
|
| 502 |
+
assert len(slices_b["okx"]) == 100
|
| 503 |
+
|
| 504 |
+
cvd_b = _compute_cvd(short_binance + okx_trades)
|
| 505 |
+
assert "score" in cvd_b
|
| 506 |
+
assert "rising" in cvd_b
|
| 507 |
+
assert isinstance(cvd_b["delta_ratio"], float)
|
| 508 |
+
|
| 509 |
+
# 3. Case C (Review Focus #3): Synthetic single-venue trades without "time" or "venue"
|
| 510 |
+
synthetic_trades = [
|
| 511 |
+
{"qty": 2.0, "is_buyer_maker": False},
|
| 512 |
+
{"qty": 1.0, "is_buyer_maker": True},
|
| 513 |
+
{"qty": 3.0, "is_buyer_maker": False},
|
| 514 |
+
]
|
| 515 |
+
slices_c, mode_c = _align_multi_venue_trades(synthetic_trades)
|
| 516 |
+
assert mode_c == "single"
|
| 517 |
+
assert slices_c == {}
|
| 518 |
+
|
| 519 |
+
cvd_c = _compute_cvd(synthetic_trades)
|
| 520 |
+
assert cvd_c["value"] == 4.0
|
| 521 |
+
assert cvd_c["delta_ratio"] == round(4.0 / 6.0, 4)
|
| 522 |
+
|
| 523 |
+
|
| 524 |
+
def test_cross_venue_whale_consensus_cap_and_100_trade_parity():
|
| 525 |
+
"""
|
| 526 |
+
Module B Task 2 Test 2:
|
| 527 |
+
Verifies cross-venue whale consensus:
|
| 528 |
+
- With >= 2 venues (binance high volume + okx 100 trades), single-venue block spike
|
| 529 |
+
without TWAP/iceberg/onchain caps whale_composite_score at ±1.
|
| 530 |
+
- Simultaneous whale blocks exceeding per-venue min_venue_thresh on Binance + OKX
|
| 531 |
+
(or Hyperliquid wallet) yields cross_venue_whale_aligned=True and ±2.
|
| 532 |
+
"""
|
| 533 |
+
from engine.signal_engine import _compute_whale_order_flow
|
| 534 |
+
|
| 535 |
+
mark_px = 50000.0
|
| 536 |
+
|
| 537 |
+
# 1. Binance has high volume ($220,000) and two huge whale buy blocks ($60,000 each)
|
| 538 |
+
binance_trades = [
|
| 539 |
+
{"time": 1000 + i * 10, "qty": 0.02, "price": mark_px, "is_buyer_maker": False, "venue": "binance"}
|
| 540 |
+
for i in range(100)
|
| 541 |
+
]
|
| 542 |
+
# Add two whale buy blocks to Binance
|
| 543 |
+
binance_trades.append({"time": 2000, "qty": 1.2, "price": mark_px, "is_buyer_maker": False, "venue": "binance"})
|
| 544 |
+
binance_trades.append({"time": 2010, "qty": 1.2, "price": mark_px, "is_buyer_maker": False, "venue": "binance"})
|
| 545 |
+
|
| 546 |
+
# OKX has 100 trades, total volume $10,000, no whale blocks (all $100 trades)
|
| 547 |
+
okx_trades = [
|
| 548 |
+
{"time": 1000 + i * 20, "qty": 0.002, "price": mark_px, "is_buyer_maker": False, "venue": "okx"}
|
| 549 |
+
for i in range(100)
|
| 550 |
+
]
|
| 551 |
+
|
| 552 |
+
combined_trades = binance_trades + okx_trades
|
| 553 |
+
flow_single_whale = _compute_whale_order_flow(combined_trades, mark_px)
|
| 554 |
+
|
| 555 |
+
# Single-venue block spike unconfirmed by OKX / TWAP / Iceberg / Onchain must cap at +1
|
| 556 |
+
assert flow_single_whale["cross_venue_whale_aligned"] is False
|
| 557 |
+
assert flow_single_whale["whale_venues_bull"] == 1
|
| 558 |
+
assert flow_single_whale["whale_venues_bear"] == 0
|
| 559 |
+
assert flow_single_whale["whale_composite_score"] == 1 # capped at +1 instead of +2
|
| 560 |
+
|
| 561 |
+
# 2. Simultaneous whale blocks on Binance + OKX
|
| 562 |
+
# OKX adds a whale buy block of $6,000 (0.12 BTC), exceeding OKX's min_venue_thresh (~$5,000)
|
| 563 |
+
okx_with_whale = list(okx_trades)
|
| 564 |
+
okx_with_whale.append({"time": 2005, "qty": 0.12, "price": mark_px, "is_buyer_maker": False, "venue": "okx"})
|
| 565 |
+
|
| 566 |
+
flow_both_whale = _compute_whale_order_flow(binance_trades + okx_with_whale, mark_px)
|
| 567 |
+
assert flow_both_whale["whale_venues_bull"] == 2
|
| 568 |
+
assert flow_both_whale["cross_venue_whale_aligned"] is True
|
| 569 |
+
assert flow_both_whale["whale_composite_score"] == 2
|
| 570 |
+
|
| 571 |
+
# 3. Confirmation via Hyperliquid On-Chain single-wallet
|
| 572 |
+
# Binance has whale buy, OKX has no whale buy, but Hyperliquid has a whale taker wallet buy of $15,000
|
| 573 |
+
hl_whale_trade = [
|
| 574 |
+
{
|
| 575 |
+
"time": 2005,
|
| 576 |
+
"qty": 0.3,
|
| 577 |
+
"price": mark_px,
|
| 578 |
+
"is_buyer_maker": False,
|
| 579 |
+
"venue": "hyperliquid",
|
| 580 |
+
"taker_wallet": "0xWhaleAlpha",
|
| 581 |
+
}
|
| 582 |
+
]
|
| 583 |
+
flow_hl_confirmed = _compute_whale_order_flow(binance_trades + okx_trades + hl_whale_trade, mark_px)
|
| 584 |
+
assert flow_hl_confirmed["cross_venue_whale_aligned"] is True
|
| 585 |
+
assert flow_hl_confirmed["whale_composite_score"] == 2
|
| 586 |
+
|
| 587 |
+
# 4. Bearish mirror: Binance has 2 huge sell blocks, OKX has no whale trades -> capped at -1
|
| 588 |
+
binance_sells = [
|
| 589 |
+
{"time": 1000 + i * 10, "qty": 0.02, "price": mark_px, "is_buyer_maker": True, "venue": "binance"}
|
| 590 |
+
for i in range(100)
|
| 591 |
+
]
|
| 592 |
+
binance_sells.append({"time": 2000, "qty": 1.2, "price": mark_px, "is_buyer_maker": True, "venue": "binance"})
|
| 593 |
+
binance_sells.append({"time": 2010, "qty": 1.2, "price": mark_px, "is_buyer_maker": True, "venue": "binance"})
|
| 594 |
+
|
| 595 |
+
flow_bear_single = _compute_whale_order_flow(binance_sells + okx_trades, mark_px)
|
| 596 |
+
assert flow_bear_single["cross_venue_whale_aligned"] is False
|
| 597 |
+
assert flow_bear_single["whale_venues_bear"] == 1
|
| 598 |
+
assert flow_bear_single["whale_composite_score"] == -1 # capped at -1 instead of -2
|
| 599 |
+
|
| 600 |
+
# Bearish simultaneous: OKX adds a $6,000 sell block
|
| 601 |
+
okx_bear_whale = list(okx_trades)
|
| 602 |
+
okx_bear_whale.append({"time": 2005, "qty": 0.12, "price": mark_px, "is_buyer_maker": True, "venue": "okx"})
|
| 603 |
+
flow_bear_both = _compute_whale_order_flow(binance_sells + okx_bear_whale, mark_px)
|
| 604 |
+
assert flow_bear_both["cross_venue_whale_aligned"] is True
|
| 605 |
+
assert flow_bear_both["whale_composite_score"] == -2
|
| 606 |
+
|
| 607 |
+
|
| 608 |
+
def test_four_exchange_spot_futures_cvd_and_twap_fallback():
|
| 609 |
+
"""
|
| 610 |
+
Module B Task 2 Test 3:
|
| 611 |
+
Verifies:
|
| 612 |
+
1. Paired Spot/Futures aggregation across OKX and Bitget with 1000x scale normalization,
|
| 613 |
+
exporting venues_count and spot_venues.
|
| 614 |
+
2. SignalEngine.compute backfills taker_buy_volume from Bitget onto merged_ohlcv['15m']
|
| 615 |
+
when Binance OHLCV lacks taker_buy_volume, allowing Layer 3 TWAP accumulation detection.
|
| 616 |
+
"""
|
| 617 |
+
from engine.signal_engine import _compute_spot_futures_cvd, SignalEngine
|
| 618 |
+
|
| 619 |
+
# 1. OKX and Bitget paired Spot/Futures CVD
|
| 620 |
+
# OKX has 1000x multiplier difference: Spot is PEPE-USDT @ 0.000010, Futures is 1000PEPE @ 0.010
|
| 621 |
+
ref_mark_px = 0.010
|
| 622 |
+
now_ms = 1_700_000_000_000
|
| 623 |
+
|
| 624 |
+
okx_spot = [
|
| 625 |
+
{"time": now_ms - 10000 + i * 1000, "qty": 1_000_000.0, "price": 0.000010, "is_buyer_maker": False}
|
| 626 |
+
for i in range(10)
|
| 627 |
+
]
|
| 628 |
+
okx_fut = [
|
| 629 |
+
{"time": now_ms - 10000 + i * 1000, "qty": 1_000.0, "price": 0.010, "is_buyer_maker": False}
|
| 630 |
+
for i in range(10)
|
| 631 |
+
]
|
| 632 |
+
|
| 633 |
+
bitget_spot = [
|
| 634 |
+
{"time": now_ms - 10000 + i * 1000, "qty": 500.0, "price": 0.010, "is_buyer_maker": False}
|
| 635 |
+
for i in range(10)
|
| 636 |
+
]
|
| 637 |
+
bitget_fut = [
|
| 638 |
+
{"time": now_ms - 10000 + i * 1000, "qty": 500.0, "price": 0.010, "is_buyer_maker": False}
|
| 639 |
+
for i in range(10)
|
| 640 |
+
]
|
| 641 |
+
|
| 642 |
+
okx_data = {"spot_trades": okx_spot, "trades": okx_fut}
|
| 643 |
+
bitget_data = {"spot_trades": bitget_spot, "trades": bitget_fut}
|
| 644 |
+
|
| 645 |
+
res_sf = _compute_spot_futures_cvd(None, None, okx_data=okx_data, bitget_data=bitget_data, ref_mark_px=ref_mark_px)
|
| 646 |
+
assert res_sf["venues_count"] == 2
|
| 647 |
+
assert set(res_sf["spot_venues"]) == {"okx", "bitget"}
|
| 648 |
+
assert res_sf["score"] == 2 # Organic Accumulation
|
| 649 |
+
assert res_sf["spot_delta_ratio"] > 0
|
| 650 |
+
assert res_sf["futures_delta_ratio"] > 0
|
| 651 |
+
|
| 652 |
+
# 2. SignalEngine.compute TWAP fallback:
|
| 653 |
+
# Binance 15m OHLCV has taker_buy_volume = None.
|
| 654 |
+
# Bitget 15m OHLCV has taker_buy_volume populated with strong buy accumulation (85% buy).
|
| 655 |
+
t_base = 1_700_000_000_000
|
| 656 |
+
binance_candles_15m = [
|
| 657 |
+
{
|
| 658 |
+
"timestamp": t_base + i * 900_000,
|
| 659 |
+
"open": 50000.0,
|
| 660 |
+
"high": 50500.0,
|
| 661 |
+
"low": 49900.0,
|
| 662 |
+
"close": 50400.0,
|
| 663 |
+
"volume": 100.0,
|
| 664 |
+
"taker_buy_volume": None, # Binance feed lacks taker volume
|
| 665 |
+
}
|
| 666 |
+
for i in range(10)
|
| 667 |
+
]
|
| 668 |
+
bitget_candles_15m = [
|
| 669 |
+
{
|
| 670 |
+
"timestamp": t_base + i * 900_000,
|
| 671 |
+
"open": 50000.0,
|
| 672 |
+
"high": 50500.0,
|
| 673 |
+
"low": 49900.0,
|
| 674 |
+
"close": 50400.0,
|
| 675 |
+
"volume": 100.0,
|
| 676 |
+
"taker_buy_volume": 85.0, # 85% taker buy volume -> strong accumulation
|
| 677 |
+
}
|
| 678 |
+
for i in range(10)
|
| 679 |
+
]
|
| 680 |
+
|
| 681 |
+
raw_payload = {
|
| 682 |
+
"symbol": "BTCUSDT",
|
| 683 |
+
"has_spot": False, # Should become True if any exchange has spot_trades
|
| 684 |
+
"binance": {
|
| 685 |
+
"mark_price_data": {"mark_price": 50000.0, "index_price": 50000.0},
|
| 686 |
+
"funding_rate_data": {"funding_rate": 0.0001},
|
| 687 |
+
"open_interest_data": {"open_interest": 1000.0, "oi_change_pct": 0.3},
|
| 688 |
+
"trades": [],
|
| 689 |
+
"ohlcv": {"15m": binance_candles_15m},
|
| 690 |
+
"orderbook": {"bids": [[49990.0, 10.0]], "asks": [[50010.0, 10.0]]},
|
| 691 |
+
},
|
| 692 |
+
"bybit": None,
|
| 693 |
+
"okx": None,
|
| 694 |
+
"bitget": {
|
| 695 |
+
"mark_price_data": {"mark_price": 50000.0, "index_price": 50000.0},
|
| 696 |
+
"funding_rate_data": {"funding_rate": 0.0001},
|
| 697 |
+
"open_interest_data": {"open_interest": 500.0, "oi_change_pct": 0.3},
|
| 698 |
+
"trades": [],
|
| 699 |
+
"spot_trades": bitget_spot,
|
| 700 |
+
"ohlcv": {"15m": bitget_candles_15m},
|
| 701 |
+
"orderbook": {"bids": [[49990.0, 5.0]], "asks": [[50010.0, 5.0]]},
|
| 702 |
+
},
|
| 703 |
+
"hyperliquid": None,
|
| 704 |
+
}
|
| 705 |
+
|
| 706 |
+
engine_res = SignalEngine().compute(raw_payload)
|
| 707 |
+
# has_spot detected from bitget spot_trades
|
| 708 |
+
assert engine_res["has_spot"] is True
|
| 709 |
+
assert engine_res["signals"]["spot_futures_cvd"]["venues_count"] >= 1
|
| 710 |
+
assert "bitget" in engine_res["signals"]["spot_futures_cvd"]["spot_venues"]
|
| 711 |
+
|
| 712 |
+
# Layer 3 TWAP picked up bitget taker_buy_volume onto merged_ohlcv["15m"]
|
| 713 |
+
whale_flow = engine_res["whale_flow"]
|
| 714 |
+
assert whale_flow["twap_delta_ratio"] > 0.5
|
| 715 |
+
assert whale_flow["twap_bias"] in ("WHALE_TWAP_LONG_BUILDUP", "TWAP_BUY_ACCUMULATION")
|
| 716 |
+
assert engine_res["confluence"]["breakdown"]["whale_order_flow"]["score"] > 0
|
| 717 |
+
|