Spaces:
Sleeping
Sleeping
Naufal Arhab commited on
Commit ·
65ccdcd
1
Parent(s): 054ee3f
fix: resolve deep-audit bugs across exchanges, flow consensus, sweep gating, db init, and backtester
Browse files- backend/database/db.py +10 -14
- backend/engine/backtester.py +7 -5
- backend/engine/data_collector.py +15 -0
- backend/engine/fake_detector.py +28 -13
- backend/engine/signal_engine.py +118 -59
- backend/engine/symbol_resolver.py +1 -1
- backend/exchanges/base.py +3 -3
- backend/exchanges/bitget.py +34 -20
- backend/exchanges/hyperliquid.py +9 -1
- backend/exchanges/okx.py +24 -13
- tests/test_backtester.py +24 -0
- tests/test_five_exchange_whale_pov.py +486 -1
backend/database/db.py
CHANGED
|
@@ -155,23 +155,19 @@ def init_db() -> None:
|
|
| 155 |
cur.execute(CREATE_JOURNAL_INDEX)
|
| 156 |
conn.commit()
|
| 157 |
logger.info("Created trade_journal and damian_memory tables.")
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
|
|
|
| 164 |
try:
|
| 165 |
cur.execute(_LEGACY_ALTER_COLUMNS_SQL)
|
| 166 |
-
cur.execute("CREATE INDEX IF NOT EXISTS idx_signals_symbol_created ON signals (symbol, created_at DESC);")
|
| 167 |
-
cur.execute("CREATE INDEX IF NOT EXISTS idx_pairs_active ON pairs (is_active);")
|
| 168 |
-
cur.execute(CREATE_SIGNAL_PREDICTIONS_TABLE)
|
| 169 |
-
cur.execute(CREATE_SIGNAL_PREDICTIONS_PENDING_INDEX)
|
| 170 |
-
cur.execute(CREATE_SIGNAL_PREDICTIONS_EVAL_INDEX)
|
| 171 |
-
cur.execute(CREATE_SIGNAL_PREDICTIONS_SHADOW_INDEX)
|
| 172 |
conn.commit()
|
| 173 |
-
except Exception:
|
| 174 |
-
|
|
|
|
| 175 |
return
|
| 176 |
|
| 177 |
# 2. Schema does not exist: acquire advisory lock so only 1 worker creates tables
|
|
|
|
| 155 |
cur.execute(CREATE_JOURNAL_INDEX)
|
| 156 |
conn.commit()
|
| 157 |
logger.info("Created trade_journal and damian_memory tables.")
|
| 158 |
+
cur.execute(CREATE_SIGNAL_PREDICTIONS_TABLE)
|
| 159 |
+
cur.execute(CREATE_SIGNAL_PREDICTIONS_PENDING_INDEX)
|
| 160 |
+
cur.execute(CREATE_SIGNAL_PREDICTIONS_EVAL_INDEX)
|
| 161 |
+
cur.execute(CREATE_SIGNAL_PREDICTIONS_SHADOW_INDEX)
|
| 162 |
+
cur.execute("CREATE INDEX IF NOT EXISTS idx_signals_symbol_created ON signals (symbol, created_at DESC);")
|
| 163 |
+
cur.execute("CREATE INDEX IF NOT EXISTS idx_pairs_active ON pairs (is_active);")
|
| 164 |
+
conn.commit()
|
| 165 |
try:
|
| 166 |
cur.execute(_LEGACY_ALTER_COLUMNS_SQL)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 167 |
conn.commit()
|
| 168 |
+
except Exception as e:
|
| 169 |
+
conn.rollback()
|
| 170 |
+
logger.warning("Postgres schema add column to existing tables note: %s", e)
|
| 171 |
return
|
| 172 |
|
| 173 |
# 2. Schema does not exist: acquire advisory lock so only 1 worker creates tables
|
backend/engine/backtester.py
CHANGED
|
@@ -212,11 +212,13 @@ class CausalBacktester:
|
|
| 212 |
funding_sorted = sorted(funding_history or [], key=lambda x: int(x["timestamp"]))
|
| 213 |
funding_ts = [int(x["timestamp"]) for x in funding_sorted]
|
| 214 |
|
| 215 |
-
oi_sorted =
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
|
|
|
|
|
|
| 220 |
oi_ts = (
|
| 221 |
[int(x.get("timestamp") or x.get("time") or 0) for x in oi_sorted]
|
| 222 |
if oi_sorted
|
|
|
|
| 212 |
funding_sorted = sorted(funding_history or [], key=lambda x: int(x["timestamp"]))
|
| 213 |
funding_ts = [int(x["timestamp"]) for x in funding_sorted]
|
| 214 |
|
| 215 |
+
oi_sorted = None
|
| 216 |
+
if oi_history:
|
| 217 |
+
dedup_oi: dict[int, dict] = {}
|
| 218 |
+
for item in oi_history:
|
| 219 |
+
ts_val = int(item.get("timestamp") or item.get("time") or 0)
|
| 220 |
+
dedup_oi[ts_val] = item
|
| 221 |
+
oi_sorted = [dedup_oi[ts_val] for ts_val in sorted(dedup_oi.keys())]
|
| 222 |
oi_ts = (
|
| 223 |
[int(x.get("timestamp") or x.get("time") or 0) for x in oi_sorted]
|
| 224 |
if oi_sorted
|
backend/engine/data_collector.py
CHANGED
|
@@ -256,4 +256,19 @@ class DataCollector:
|
|
| 256 |
if results.get("binance") and results["binance"].get("spot_trades"):
|
| 257 |
results["has_spot"] = True
|
| 258 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 259 |
return results
|
|
|
|
| 256 |
if results.get("binance") and results["binance"].get("spot_trades"):
|
| 257 |
results["has_spot"] = True
|
| 258 |
|
| 259 |
+
# Drop 100% empty-shell snapshots (e.g. unlisted coins where every sub-endpoint failed)
|
| 260 |
+
for exch_key in ("binance", "bybit", "okx", "bitget"):
|
| 261 |
+
snap = results.get(exch_key)
|
| 262 |
+
if isinstance(snap, dict) and (
|
| 263 |
+
snap.get("mark_price_data") is None
|
| 264 |
+
and snap.get("funding_rate_data") is None
|
| 265 |
+
and snap.get("open_interest_data") is None
|
| 266 |
+
and snap.get("ls_ratio_data") is None
|
| 267 |
+
and snap.get("orderbook") is None
|
| 268 |
+
and not snap.get("trades")
|
| 269 |
+
and not snap.get("spot_trades")
|
| 270 |
+
and not any((snap.get("ohlcv") or {}).values())
|
| 271 |
+
):
|
| 272 |
+
results[exch_key] = None
|
| 273 |
+
|
| 274 |
return results
|
backend/engine/fake_detector.py
CHANGED
|
@@ -30,9 +30,9 @@ def _wick_sweep_detected(candles: list[dict]) -> tuple[bool, str]:
|
|
| 30 |
if len(candles) < 3:
|
| 31 |
return False, ""
|
| 32 |
|
| 33 |
-
# Evaluate completed candles only
|
| 34 |
recent = candles[-4:-1] if len(candles) >= 4 else candles[:-1]
|
| 35 |
-
for c in recent:
|
| 36 |
high = c.get("high")
|
| 37 |
low = c.get("low")
|
| 38 |
open_p = c.get("open")
|
|
@@ -72,15 +72,22 @@ def _wash_trade_detected(candles: list[dict]) -> bool:
|
|
| 72 |
cand_vol = float(cand.get("volume") or 0)
|
| 73 |
cand_open = float(cand.get("open") or 0)
|
| 74 |
cand_close = float(cand.get("close") or 0)
|
|
|
|
|
|
|
| 75 |
if cand_vol > avg_vol * MIN_VOLUME_SPIKE_MULTIPLIER:
|
| 76 |
if cand_open > 0:
|
| 77 |
price_move_pct = abs(cand_close - cand_open) / cand_open
|
| 78 |
-
|
|
|
|
| 79 |
return True
|
| 80 |
return False
|
| 81 |
|
| 82 |
|
| 83 |
-
def _orderbook_imbalance_detected(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
"""Detect extreme order book depth imbalance / spoofing walls."""
|
| 85 |
if not orderbook:
|
| 86 |
return False, ""
|
|
@@ -101,12 +108,18 @@ def _orderbook_imbalance_detected(orderbook: dict | None, cvd_matches_price: boo
|
|
| 101 |
|
| 102 |
imbalance = (bid_vol - ask_vol) / total_vol
|
| 103 |
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
|
| 111 |
return False, ""
|
| 112 |
|
|
@@ -152,6 +165,7 @@ class FakeDetector:
|
|
| 152 |
cvd_matches_price: bool,
|
| 153 |
orderbook: dict | None = None,
|
| 154 |
venue_prices: dict[str, float] | None = None,
|
|
|
|
| 155 |
) -> dict[str, Any]:
|
| 156 |
"""
|
| 157 |
Parameters
|
|
@@ -176,8 +190,9 @@ class FakeDetector:
|
|
| 176 |
warnings: list[str] = []
|
| 177 |
score_penalty = 0
|
| 178 |
|
| 179 |
-
# 1. Wick sweep
|
| 180 |
-
|
|
|
|
| 181 |
if sweep_detected:
|
| 182 |
warnings.append(f"Wick sweep detected ({sweep_dir}) — potential liquidity sweep")
|
| 183 |
score_penalty -= 1
|
|
@@ -217,7 +232,7 @@ class FakeDetector:
|
|
| 217 |
score_penalty -= 1
|
| 218 |
|
| 219 |
# 5. Orderbook depth spoofing wall
|
| 220 |
-
ob_spoof, ob_msg = _orderbook_imbalance_detected(orderbook, cvd_matches_price)
|
| 221 |
if ob_spoof:
|
| 222 |
warnings.append(ob_msg)
|
| 223 |
score_penalty -= 1
|
|
|
|
| 30 |
if len(candles) < 3:
|
| 31 |
return False, ""
|
| 32 |
|
| 33 |
+
# Evaluate completed candles only (newest first so latest liquidity sweep wins)
|
| 34 |
recent = candles[-4:-1] if len(candles) >= 4 else candles[:-1]
|
| 35 |
+
for c in reversed(recent):
|
| 36 |
high = c.get("high")
|
| 37 |
low = c.get("low")
|
| 38 |
open_p = c.get("open")
|
|
|
|
| 72 |
cand_vol = float(cand.get("volume") or 0)
|
| 73 |
cand_open = float(cand.get("open") or 0)
|
| 74 |
cand_close = float(cand.get("close") or 0)
|
| 75 |
+
cand_high = float(cand.get("high") or 0)
|
| 76 |
+
cand_low = float(cand.get("low") or 0)
|
| 77 |
if cand_vol > avg_vol * MIN_VOLUME_SPIKE_MULTIPLIER:
|
| 78 |
if cand_open > 0:
|
| 79 |
price_move_pct = abs(cand_close - cand_open) / cand_open
|
| 80 |
+
cand_rng_pct = max(0.0, cand_high - cand_low) / cand_open
|
| 81 |
+
if price_move_pct < MAX_PRICE_MOVE_FOR_WASHTRADING and cand_rng_pct < 0.015:
|
| 82 |
return True
|
| 83 |
return False
|
| 84 |
|
| 85 |
|
| 86 |
+
def _orderbook_imbalance_detected(
|
| 87 |
+
orderbook: dict | None,
|
| 88 |
+
cvd_matches_price: bool,
|
| 89 |
+
cvd_rising: bool | None = None,
|
| 90 |
+
) -> tuple[bool, str]:
|
| 91 |
"""Detect extreme order book depth imbalance / spoofing walls."""
|
| 92 |
if not orderbook:
|
| 93 |
return False, ""
|
|
|
|
| 108 |
|
| 109 |
imbalance = (bid_vol - ask_vol) / total_vol
|
| 110 |
|
| 111 |
+
if cvd_rising is not None:
|
| 112 |
+
# True aggressive-flow check catches spoofs even when price & CVD drop together
|
| 113 |
+
if imbalance >= ORDERBOOK_WALL_IMBALANCE_THRESHOLD and not cvd_rising:
|
| 114 |
+
return True, f"Bid Wall Imbalance ({imbalance:.1%}) with Selling Pressure — Possible Wall Spoof"
|
| 115 |
+
if imbalance <= -ORDERBOOK_WALL_IMBALANCE_THRESHOLD and cvd_rising:
|
| 116 |
+
return True, f"Ask Wall Imbalance ({abs(imbalance):.1%}) with Buying Pressure — Possible Wall Spoof"
|
| 117 |
+
else:
|
| 118 |
+
# Backward-compatible fallback when caller does not pass cvd_rising
|
| 119 |
+
if imbalance >= ORDERBOOK_WALL_IMBALANCE_THRESHOLD and not cvd_matches_price:
|
| 120 |
+
return True, f"Bid Wall Imbalance ({imbalance:.1%}) with Selling Pressure — Possible Wall Spoof"
|
| 121 |
+
if imbalance <= -ORDERBOOK_WALL_IMBALANCE_THRESHOLD and not cvd_matches_price:
|
| 122 |
+
return True, f"Ask Wall Imbalance ({abs(imbalance):.1%}) with Buying Pressure — Possible Wall Spoof"
|
| 123 |
|
| 124 |
return False, ""
|
| 125 |
|
|
|
|
| 165 |
cvd_matches_price: bool,
|
| 166 |
orderbook: dict | None = None,
|
| 167 |
venue_prices: dict[str, float] | None = None,
|
| 168 |
+
cvd_rising: bool | None = None,
|
| 169 |
) -> dict[str, Any]:
|
| 170 |
"""
|
| 171 |
Parameters
|
|
|
|
| 190 |
warnings: list[str] = []
|
| 191 |
score_penalty = 0
|
| 192 |
|
| 193 |
+
# 1. Wick sweep (fallback to 5m when 1m has < 3 bars)
|
| 194 |
+
sweep_candles = ohlcv_1m if (ohlcv_1m and len(ohlcv_1m) >= 3) else ohlcv_5m
|
| 195 |
+
sweep_detected, sweep_dir = _wick_sweep_detected(sweep_candles)
|
| 196 |
if sweep_detected:
|
| 197 |
warnings.append(f"Wick sweep detected ({sweep_dir}) — potential liquidity sweep")
|
| 198 |
score_penalty -= 1
|
|
|
|
| 232 |
score_penalty -= 1
|
| 233 |
|
| 234 |
# 5. Orderbook depth spoofing wall
|
| 235 |
+
ob_spoof, ob_msg = _orderbook_imbalance_detected(orderbook, cvd_matches_price, cvd_rising=cvd_rising)
|
| 236 |
if ob_spoof:
|
| 237 |
warnings.append(ob_msg)
|
| 238 |
score_penalty -= 1
|
backend/engine/signal_engine.py
CHANGED
|
@@ -275,7 +275,7 @@ def _align_multi_venue_trades(trades: list[dict]) -> tuple[dict[str, list[dict]]
|
|
| 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"
|
|
@@ -502,17 +502,50 @@ def _compute_spot_futures_cvd(
|
|
| 502 |
futures_cvd = sum(p["futures_cvd"] for _, p in same_venue_pairs)
|
| 503 |
|
| 504 |
else:
|
| 505 |
-
# Cross-venue fallback:
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 513 |
spot_venues.append(v_name)
|
| 514 |
if v_data and v_data.get("trades"):
|
| 515 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 516 |
|
| 517 |
if not all_fut_trades and not all_spot_trades:
|
| 518 |
return {
|
|
@@ -817,7 +850,7 @@ def _compute_oi_divergence(
|
|
| 817 |
oi_4h_changes.append(float(oi_data["oi_change_4h_pct"]))
|
| 818 |
oi_4h_weights.append(w)
|
| 819 |
|
| 820 |
-
if not price_changes:
|
| 821 |
return {
|
| 822 |
"value": "No Data",
|
| 823 |
"score": 0,
|
|
@@ -828,7 +861,7 @@ def _compute_oi_divergence(
|
|
| 828 |
"oi_horizon_used": "none",
|
| 829 |
}
|
| 830 |
|
| 831 |
-
avg_price_change = _oi_weighted_average(price_changes, price_weights)
|
| 832 |
|
| 833 |
if hist_15m_oi_changes:
|
| 834 |
avg_oi_change = _oi_weighted_average(hist_15m_oi_changes, hist_15m_oi_weights)
|
|
@@ -970,8 +1003,9 @@ def _compute_cvd(trades: list[dict]) -> dict[str, Any]:
|
|
| 970 |
total_venue_usd += v_tot_usd
|
| 971 |
|
| 972 |
cvd = total_buy_qty - total_sell_qty
|
| 973 |
-
|
| 974 |
-
|
|
|
|
| 975 |
cvd_rising = (weighted_rising_sum / total_venue_usd > 0.5) if total_venue_usd > 0 else False
|
| 976 |
|
| 977 |
elif mode == "per_venue":
|
|
@@ -2010,8 +2044,10 @@ def _compute_whale_order_flow(
|
|
| 2010 |
if not active_trade_venues and "default" in venue_parsed:
|
| 2011 |
active_trade_venues = ["default"]
|
| 2012 |
|
| 2013 |
-
|
| 2014 |
-
|
|
|
|
|
|
|
| 2015 |
|
| 2016 |
if len(active_trade_venues) >= 2:
|
| 2017 |
for v in active_trade_venues:
|
|
@@ -2034,22 +2070,34 @@ def _compute_whale_order_flow(
|
|
| 2034 |
v_eff_sell = max(sum(v_sells), sum(v_sw_sells))
|
| 2035 |
|
| 2036 |
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)):
|
| 2037 |
-
|
|
|
|
|
|
|
|
|
|
| 2038 |
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)):
|
| 2039 |
-
|
|
|
|
|
|
|
|
|
|
| 2040 |
else:
|
| 2041 |
eff_w_buy = max(whale_buy_vol, sweep_buy_vol)
|
| 2042 |
eff_w_sell = max(whale_sell_vol, sweep_sell_vol)
|
|
|
|
| 2043 |
if eff_w_buy >= threshold and eff_w_buy > eff_w_sell * 1.4:
|
| 2044 |
-
|
|
|
|
|
|
|
|
|
|
| 2045 |
elif eff_w_sell >= threshold and eff_w_sell > eff_w_buy * 1.4:
|
| 2046 |
-
|
|
|
|
|
|
|
|
|
|
| 2047 |
|
| 2048 |
-
|
| 2049 |
-
|
| 2050 |
-
|
| 2051 |
-
|
| 2052 |
-
cross_venue_whale_aligned = True
|
| 2053 |
|
| 2054 |
# Also check live tape Iceberg Absorption if not already triggered by klines
|
| 2055 |
if absorption_score == 0 and merged_ohlcv and total_vol >= 25_000.0 and eff_oi_chg >= 0.25:
|
|
@@ -2744,6 +2792,7 @@ class SignalEngine:
|
|
| 2744 |
cvd_matches_price=cvd_matches_price,
|
| 2745 |
orderbook=orderbook,
|
| 2746 |
venue_prices=scaled_venue_marks,
|
|
|
|
| 2747 |
)
|
| 2748 |
|
| 2749 |
if not has_spot:
|
|
@@ -2940,7 +2989,7 @@ class SignalEngine:
|
|
| 2940 |
primary_raw_dir, primary_ac = _apply_anti_chasing(primary_conf, primary_stretch)
|
| 2941 |
|
| 2942 |
# Live multi-factor confirmation check (>= 2 aligned factors required when live)
|
| 2943 |
-
if
|
| 2944 |
for h_conf, h_facs in [
|
| 2945 |
(primary_conf, factors_primary),
|
| 2946 |
(intraday_conf, factors_intraday),
|
|
@@ -2964,13 +3013,55 @@ class SignalEngine:
|
|
| 2964 |
else:
|
| 2965 |
h_conf["unconfirmed_single_factor"] = False
|
| 2966 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2967 |
# Select primary active horizon for top-level backward-compatible Signal fields:
|
| 2968 |
-
# Intraday leads
|
|
|
|
| 2969 |
intra_chased_dir = intra_raw_dir if (intra_ac["blocked"] and intra_raw_dir in ("LONG", "SHORT")) else None
|
| 2970 |
-
if intraday_conf["direction"] in ("LONG", "SHORT"):
|
| 2971 |
confluence = dict(intraday_conf)
|
| 2972 |
active_horizon_key = "intraday"
|
| 2973 |
-
elif swing_conf["direction"] in ("LONG", "SHORT") and
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2974 |
confluence = dict(swing_conf)
|
| 2975 |
active_horizon_key = "swing"
|
| 2976 |
else:
|
|
@@ -3047,6 +3138,7 @@ class SignalEngine:
|
|
| 3047 |
conviction=confluence["conviction"],
|
| 3048 |
funding_rate=funding_signal.get("value"),
|
| 3049 |
)
|
|
|
|
| 3050 |
|
| 3051 |
# Primary-venue orderbook liquidity guard (tight ±1.5% depth & top-of-book spread)
|
| 3052 |
primary_venue_ob = valid_obs[0] if valid_obs else None
|
|
@@ -3055,7 +3147,6 @@ class SignalEngine:
|
|
| 3055 |
# ── 7. Horizon Trade Plans & Instant Verdict ───────────────────────
|
| 3056 |
intraday_candles = merged_ohlcv.get("1h") or merged_ohlcv.get("15m") or []
|
| 3057 |
swing_candles = merged_ohlcv.get("4h") or merged_ohlcv.get("1h") or []
|
| 3058 |
-
sf_score = spot_futures_signal.get("score", 0)
|
| 3059 |
is_fake_flag = fake_result.get("is_fake", False)
|
| 3060 |
|
| 3061 |
swing_chased_dir = swing_raw_dir if (swing_ac["blocked"] and swing_raw_dir in ("LONG", "SHORT")) else None
|
|
@@ -3066,39 +3157,7 @@ class SignalEngine:
|
|
| 3066 |
else (intra_chased_dir or swing_chased_dir or primary_conf.get("direction", "NEUTRAL"))
|
| 3067 |
)
|
| 3068 |
|
| 3069 |
-
# Primary-horizon sweep override evaluation (
|
| 3070 |
-
sweep_dir = fake_result.get("sweep_direction")
|
| 3071 |
-
has_non_sweep = fake_result.get("has_non_sweep_manipulation", True)
|
| 3072 |
-
dislocation_risk = bool(cross_signal.get("dislocation_risk", False))
|
| 3073 |
-
absorption_type = whale_flow_data.get("absorption_type")
|
| 3074 |
-
orig_is_fake = bool(fake_result.get("is_fake", False))
|
| 3075 |
-
|
| 3076 |
-
def _horizon_sweep_confirmed(h_dir: str) -> bool:
|
| 3077 |
-
if not (
|
| 3078 |
-
has_spot is True
|
| 3079 |
-
and orig_is_fake is True
|
| 3080 |
-
and sweep_dir in ("LOWER_SWEEP", "UPPER_SWEEP")
|
| 3081 |
-
and (not has_non_sweep)
|
| 3082 |
-
and (not dislocation_risk)
|
| 3083 |
-
):
|
| 3084 |
-
return False
|
| 3085 |
-
if h_dir == "LONG" and sweep_dir == "LOWER_SWEEP":
|
| 3086 |
-
return (
|
| 3087 |
-
sf_score >= 1
|
| 3088 |
-
or absorption_type == "BULLISH_ICEBERG_ABSORPTION"
|
| 3089 |
-
or whale_score >= 1
|
| 3090 |
-
)
|
| 3091 |
-
if h_dir == "SHORT" and sweep_dir == "UPPER_SWEEP":
|
| 3092 |
-
return (
|
| 3093 |
-
sf_score <= -1
|
| 3094 |
-
or absorption_type == "BEARISH_ICEBERG_ABSORPTION"
|
| 3095 |
-
or whale_score <= -1
|
| 3096 |
-
)
|
| 3097 |
-
return False
|
| 3098 |
-
|
| 3099 |
-
intra_is_fake = bool(orig_is_fake and not _horizon_sweep_confirmed(intraday_conf["direction"]))
|
| 3100 |
-
swing_is_fake = bool(orig_is_fake and not _horizon_sweep_confirmed(swing_conf["direction"]))
|
| 3101 |
-
primary_is_fake = bool(orig_is_fake and not _horizon_sweep_confirmed(primary_conf["direction"]))
|
| 3102 |
candidate_sweep_ok = _horizon_sweep_confirmed(candidate_dir)
|
| 3103 |
is_fake_flag = bool(orig_is_fake and not candidate_sweep_ok)
|
| 3104 |
|
|
@@ -3345,7 +3404,7 @@ class SignalEngine:
|
|
| 3345 |
ohlcv_1h=intraday_candles,
|
| 3346 |
spot_futures_score=sf_score,
|
| 3347 |
conviction=max(3, int(intraday_conf.get("conviction") or 3)),
|
| 3348 |
-
predictive_data=
|
| 3349 |
is_fake=False,
|
| 3350 |
sl_min_pct=0.008,
|
| 3351 |
sl_max_pct=0.04,
|
|
@@ -3362,7 +3421,7 @@ class SignalEngine:
|
|
| 3362 |
ohlcv_1h=swing_candles,
|
| 3363 |
spot_futures_score=sf_score,
|
| 3364 |
conviction=max(3, int(swing_conf.get("conviction") or 3)),
|
| 3365 |
-
predictive_data=
|
| 3366 |
is_fake=False,
|
| 3367 |
sl_min_pct=0.015,
|
| 3368 |
sl_max_pct=0.08,
|
|
|
|
| 275 |
|
| 276 |
qualifying = [v for v, trs in aligned.items() if len(trs) >= 5]
|
| 277 |
if len(qualifying) >= 2:
|
| 278 |
+
return {v: aligned[v] for v in qualifying}, "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"
|
|
|
|
| 502 |
futures_cvd = sum(p["futures_cvd"] for _, p in same_venue_pairs)
|
| 503 |
|
| 504 |
else:
|
| 505 |
+
# Cross-venue fallback: normalize each venue to common price scale before combining
|
| 506 |
all_spot_trades: list[dict] = []
|
| 507 |
all_fut_trades: list[dict] = []
|
| 508 |
spot_venues = []
|
| 509 |
|
| 510 |
+
fallback_ref = ref_mark_px if (ref_mark_px and ref_mark_px > 0) else None
|
| 511 |
+
if not fallback_ref:
|
| 512 |
+
for _, v_data in venues_input:
|
| 513 |
+
if v_data and v_data.get("mark_price_data") and (v_data["mark_price_data"].get("mark_price") or 0) > 0:
|
| 514 |
+
fallback_ref = float(v_data["mark_price_data"]["mark_price"])
|
| 515 |
+
break
|
| 516 |
+
if not fallback_ref:
|
| 517 |
+
for _, v_data in venues_input:
|
| 518 |
+
for tr in ((v_data or {}).get("trades") or []) + ((v_data or {}).get("spot_trades") or []):
|
| 519 |
+
if (tr.get("price") or 0) > 0:
|
| 520 |
+
fallback_ref = float(tr["price"])
|
| 521 |
+
break
|
| 522 |
+
if fallback_ref:
|
| 523 |
+
break
|
| 524 |
+
|
| 525 |
+
def _first_px(trs: list[dict]) -> float | None:
|
| 526 |
+
for tr in trs:
|
| 527 |
+
try:
|
| 528 |
+
p = float(tr.get("price") or 0.0)
|
| 529 |
+
if p > 0:
|
| 530 |
+
return p
|
| 531 |
+
except (TypeError, ValueError):
|
| 532 |
+
continue
|
| 533 |
+
return None
|
| 534 |
+
|
| 535 |
for v_name, v_data in venues_input:
|
| 536 |
if v_data and v_data.get("spot_trades"):
|
| 537 |
+
s_list = v_data["spot_trades"]
|
| 538 |
+
if fallback_ref:
|
| 539 |
+
s_scale = _get_multiplier_scale(_first_px(s_list), fallback_ref)
|
| 540 |
+
s_list = _normalize_trades_scale(s_list, s_scale)
|
| 541 |
+
all_spot_trades.extend(s_list)
|
| 542 |
spot_venues.append(v_name)
|
| 543 |
if v_data and v_data.get("trades"):
|
| 544 |
+
f_list = v_data["trades"]
|
| 545 |
+
if fallback_ref:
|
| 546 |
+
f_scale = _get_multiplier_scale(_first_px(f_list), fallback_ref)
|
| 547 |
+
f_list = _normalize_trades_scale(f_list, f_scale)
|
| 548 |
+
all_fut_trades.extend(f_list)
|
| 549 |
|
| 550 |
if not all_fut_trades and not all_spot_trades:
|
| 551 |
return {
|
|
|
|
| 850 |
oi_4h_changes.append(float(oi_data["oi_change_4h_pct"]))
|
| 851 |
oi_4h_weights.append(w)
|
| 852 |
|
| 853 |
+
if not price_changes and not price_4h_changes:
|
| 854 |
return {
|
| 855 |
"value": "No Data",
|
| 856 |
"score": 0,
|
|
|
|
| 861 |
"oi_horizon_used": "none",
|
| 862 |
}
|
| 863 |
|
| 864 |
+
avg_price_change = _oi_weighted_average(price_changes, price_weights) if price_changes else 0.0
|
| 865 |
|
| 866 |
if hist_15m_oi_changes:
|
| 867 |
avg_oi_change = _oi_weighted_average(hist_15m_oi_changes, hist_15m_oi_weights)
|
|
|
|
| 1003 |
total_venue_usd += v_tot_usd
|
| 1004 |
|
| 1005 |
cvd = total_buy_qty - total_sell_qty
|
| 1006 |
+
cvd_usd = total_buy_usd - total_sell_usd
|
| 1007 |
+
total_vol_usd = total_buy_usd + total_sell_usd
|
| 1008 |
+
delta_ratio = (cvd_usd / total_vol_usd) if total_vol_usd > 0 else 0.0
|
| 1009 |
cvd_rising = (weighted_rising_sum / total_venue_usd > 0.5) if total_venue_usd > 0 else False
|
| 1010 |
|
| 1011 |
elif mode == "per_venue":
|
|
|
|
| 2044 |
if not active_trade_venues and "default" in venue_parsed:
|
| 2045 |
active_trade_venues = ["default"]
|
| 2046 |
|
| 2047 |
+
non_hl_bull = 0
|
| 2048 |
+
non_hl_bear = 0
|
| 2049 |
+
hl_block_bull = False
|
| 2050 |
+
hl_block_bear = False
|
| 2051 |
|
| 2052 |
if len(active_trade_venues) >= 2:
|
| 2053 |
for v in active_trade_venues:
|
|
|
|
| 2070 |
v_eff_sell = max(sum(v_sells), sum(v_sw_sells))
|
| 2071 |
|
| 2072 |
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)):
|
| 2073 |
+
if v == "hyperliquid":
|
| 2074 |
+
hl_block_bull = True
|
| 2075 |
+
else:
|
| 2076 |
+
non_hl_bull += 1
|
| 2077 |
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)):
|
| 2078 |
+
if v == "hyperliquid":
|
| 2079 |
+
hl_block_bear = True
|
| 2080 |
+
else:
|
| 2081 |
+
non_hl_bear += 1
|
| 2082 |
else:
|
| 2083 |
eff_w_buy = max(whale_buy_vol, sweep_buy_vol)
|
| 2084 |
eff_w_sell = max(whale_sell_vol, sweep_sell_vol)
|
| 2085 |
+
is_only_hl = active_trade_venues == ["hyperliquid"]
|
| 2086 |
if eff_w_buy >= threshold and eff_w_buy > eff_w_sell * 1.4:
|
| 2087 |
+
if is_only_hl:
|
| 2088 |
+
hl_block_bull = True
|
| 2089 |
+
else:
|
| 2090 |
+
non_hl_bull = 1
|
| 2091 |
elif eff_w_sell >= threshold and eff_w_sell > eff_w_buy * 1.4:
|
| 2092 |
+
if is_only_hl:
|
| 2093 |
+
hl_block_bear = True
|
| 2094 |
+
else:
|
| 2095 |
+
non_hl_bear = 1
|
| 2096 |
|
| 2097 |
+
# Treat Hyperliquid (DEX block trades + on-chain wallet flow) as a single venue vote to prevent self-confirmation
|
| 2098 |
+
whale_venues_bull = non_hl_bull + (1 if (hl_block_bull or onchain_score > 0) else 0)
|
| 2099 |
+
whale_venues_bear = non_hl_bear + (1 if (hl_block_bear or onchain_score < 0) else 0)
|
| 2100 |
+
cross_venue_whale_aligned = (whale_venues_bull >= 2 or whale_venues_bear >= 2)
|
|
|
|
| 2101 |
|
| 2102 |
# Also check live tape Iceberg Absorption if not already triggered by klines
|
| 2103 |
if absorption_score == 0 and merged_ohlcv and total_vol >= 25_000.0 and eff_oi_chg >= 0.25:
|
|
|
|
| 2792 |
cvd_matches_price=cvd_matches_price,
|
| 2793 |
orderbook=orderbook,
|
| 2794 |
venue_prices=scaled_venue_marks,
|
| 2795 |
+
cvd_rising=(bool(cvd_signal.get("rising", False)) if has_cvd_data else None),
|
| 2796 |
)
|
| 2797 |
|
| 2798 |
if not has_spot:
|
|
|
|
| 2989 |
primary_raw_dir, primary_ac = _apply_anti_chasing(primary_conf, primary_stretch)
|
| 2990 |
|
| 2991 |
# Live multi-factor confirmation check (>= 2 aligned factors required when live)
|
| 2992 |
+
if not horizon_thresholds:
|
| 2993 |
for h_conf, h_facs in [
|
| 2994 |
(primary_conf, factors_primary),
|
| 2995 |
(intraday_conf, factors_intraday),
|
|
|
|
| 3013 |
else:
|
| 3014 |
h_conf["unconfirmed_single_factor"] = False
|
| 3015 |
|
| 3016 |
+
# Evaluate per-horizon WHALE_SWEEP_ENTRY eligibility before active horizon selection
|
| 3017 |
+
# so an intraday setup opposing a sweep never vetoes an aligned swing WHALE_SWEEP_ENTRY.
|
| 3018 |
+
sf_score = spot_futures_signal.get("score", 0)
|
| 3019 |
+
sweep_dir = fake_result.get("sweep_direction")
|
| 3020 |
+
has_non_sweep = fake_result.get("has_non_sweep_manipulation", True)
|
| 3021 |
+
dislocation_risk = bool(cross_signal.get("dislocation_risk", False))
|
| 3022 |
+
absorption_type = whale_flow_data.get("absorption_type")
|
| 3023 |
+
orig_is_fake = bool(fake_result.get("is_fake", False))
|
| 3024 |
+
|
| 3025 |
+
def _horizon_sweep_confirmed(h_dir: str) -> bool:
|
| 3026 |
+
if not (
|
| 3027 |
+
has_spot is True
|
| 3028 |
+
and orig_is_fake is True
|
| 3029 |
+
and sweep_dir in ("LOWER_SWEEP", "UPPER_SWEEP")
|
| 3030 |
+
and (not has_non_sweep)
|
| 3031 |
+
and (not dislocation_risk)
|
| 3032 |
+
):
|
| 3033 |
+
return False
|
| 3034 |
+
if h_dir == "LONG" and sweep_dir == "LOWER_SWEEP":
|
| 3035 |
+
return (
|
| 3036 |
+
sf_score >= 1
|
| 3037 |
+
or absorption_type == "BULLISH_ICEBERG_ABSORPTION"
|
| 3038 |
+
or whale_score >= 1
|
| 3039 |
+
)
|
| 3040 |
+
if h_dir == "SHORT" and sweep_dir == "UPPER_SWEEP":
|
| 3041 |
+
return (
|
| 3042 |
+
sf_score <= -1
|
| 3043 |
+
or absorption_type == "BEARISH_ICEBERG_ABSORPTION"
|
| 3044 |
+
or whale_score <= -1
|
| 3045 |
+
)
|
| 3046 |
+
return False
|
| 3047 |
+
|
| 3048 |
+
intra_is_fake = bool(orig_is_fake and not _horizon_sweep_confirmed(intraday_conf["direction"]))
|
| 3049 |
+
swing_is_fake = bool(orig_is_fake and not _horizon_sweep_confirmed(swing_conf["direction"]))
|
| 3050 |
+
primary_is_fake = bool(orig_is_fake and not _horizon_sweep_confirmed(primary_conf["direction"]))
|
| 3051 |
+
|
| 3052 |
# Select primary active horizon for top-level backward-compatible Signal fields:
|
| 3053 |
+
# Intraday leads unless fake-vetoed while swing confirms WHALE_SWEEP_ENTRY;
|
| 3054 |
+
# else Swing unless Intraday was blocked by ANTI_CHASING_EXTREME in the same direction.
|
| 3055 |
intra_chased_dir = intra_raw_dir if (intra_ac["blocked"] and intra_raw_dir in ("LONG", "SHORT")) else None
|
| 3056 |
+
if intraday_conf["direction"] in ("LONG", "SHORT") and (not intra_is_fake or swing_is_fake or swing_conf["direction"] == "NEUTRAL"):
|
| 3057 |
confluence = dict(intraday_conf)
|
| 3058 |
active_horizon_key = "intraday"
|
| 3059 |
+
elif swing_conf["direction"] in ("LONG", "SHORT") and not swing_is_fake and (
|
| 3060 |
+
intra_chased_dir is None or swing_conf["direction"] != intra_chased_dir
|
| 3061 |
+
):
|
| 3062 |
+
confluence = dict(swing_conf)
|
| 3063 |
+
active_horizon_key = "swing"
|
| 3064 |
+
elif swing_conf["direction"] in ("LONG", "SHORT") and swing_conf["direction"] != intra_chased_dir and intraday_conf["direction"] == "NEUTRAL":
|
| 3065 |
confluence = dict(swing_conf)
|
| 3066 |
active_horizon_key = "swing"
|
| 3067 |
else:
|
|
|
|
| 3138 |
conviction=confluence["conviction"],
|
| 3139 |
funding_rate=funding_signal.get("value"),
|
| 3140 |
)
|
| 3141 |
+
orig_predictive_data = dict(predictive_data)
|
| 3142 |
|
| 3143 |
# Primary-venue orderbook liquidity guard (tight ±1.5% depth & top-of-book spread)
|
| 3144 |
primary_venue_ob = valid_obs[0] if valid_obs else None
|
|
|
|
| 3147 |
# ── 7. Horizon Trade Plans & Instant Verdict ───────────────────────
|
| 3148 |
intraday_candles = merged_ohlcv.get("1h") or merged_ohlcv.get("15m") or []
|
| 3149 |
swing_candles = merged_ohlcv.get("4h") or merged_ohlcv.get("1h") or []
|
|
|
|
| 3150 |
is_fake_flag = fake_result.get("is_fake", False)
|
| 3151 |
|
| 3152 |
swing_chased_dir = swing_raw_dir if (swing_ac["blocked"] and swing_raw_dir in ("LONG", "SHORT")) else None
|
|
|
|
| 3157 |
else (intra_chased_dir or swing_chased_dir or primary_conf.get("direction", "NEUTRAL"))
|
| 3158 |
)
|
| 3159 |
|
| 3160 |
+
# Primary-horizon sweep override evaluation (precomputed above for horizon selection)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3161 |
candidate_sweep_ok = _horizon_sweep_confirmed(candidate_dir)
|
| 3162 |
is_fake_flag = bool(orig_is_fake and not candidate_sweep_ok)
|
| 3163 |
|
|
|
|
| 3404 |
ohlcv_1h=intraday_candles,
|
| 3405 |
spot_futures_score=sf_score,
|
| 3406 |
conviction=max(3, int(intraday_conf.get("conviction") or 3)),
|
| 3407 |
+
predictive_data=orig_predictive_data,
|
| 3408 |
is_fake=False,
|
| 3409 |
sl_min_pct=0.008,
|
| 3410 |
sl_max_pct=0.04,
|
|
|
|
| 3421 |
ohlcv_1h=swing_candles,
|
| 3422 |
spot_futures_score=sf_score,
|
| 3423 |
conviction=max(3, int(swing_conf.get("conviction") or 3)),
|
| 3424 |
+
predictive_data=orig_predictive_data,
|
| 3425 |
is_fake=False,
|
| 3426 |
sl_min_pct=0.015,
|
| 3427 |
sl_max_pct=0.08,
|
backend/engine/symbol_resolver.py
CHANGED
|
@@ -15,7 +15,7 @@ def _strip_multiplier_from_base(raw_base: str) -> str:
|
|
| 15 |
"""Strip exchange multiplier prefixes without mangling tickers that start with 'K' (e.g. KAVA, KAS, KSM)."""
|
| 16 |
if not raw_base:
|
| 17 |
return ""
|
| 18 |
-
stripped = re.sub(r'^(1000000000|1000000|100000|10000|1000)(?=.)', '', raw_base)
|
| 19 |
if stripped != raw_base:
|
| 20 |
return stripped.upper()
|
| 21 |
if raw_base.startswith("k") and len(raw_base) > 1 and raw_base[1].isupper():
|
|
|
|
| 15 |
"""Strip exchange multiplier prefixes without mangling tickers that start with 'K' (e.g. KAVA, KAS, KSM)."""
|
| 16 |
if not raw_base:
|
| 17 |
return ""
|
| 18 |
+
stripped = re.sub(r'^(1000000000|1000000|100000|10000|1000|1M|1m)(?=.)', '', raw_base)
|
| 19 |
if stripped != raw_base:
|
| 20 |
return stripped.upper()
|
| 21 |
if raw_base.startswith("k") and len(raw_base) > 1 and raw_base[1].isupper():
|
backend/exchanges/base.py
CHANGED
|
@@ -161,7 +161,7 @@ class BaseExchange(ABC):
|
|
| 161 |
def _compute_oi_horizons(
|
| 162 |
oi_series_oldest_first: list[float],
|
| 163 |
) -> tuple[float | None, float | None, float | None]:
|
| 164 |
-
"""Compute 15m, 1h (>=5 bars), and 4h (>=
|
| 165 |
if len(oi_series_oldest_first) < 2:
|
| 166 |
return None, None, None
|
| 167 |
|
|
@@ -176,8 +176,8 @@ class BaseExchange(ABC):
|
|
| 176 |
oi_1h = round(((curr_oi - prev_1h) / prev_1h) * 100.0, 4)
|
| 177 |
|
| 178 |
oi_4h = None
|
| 179 |
-
if len(oi_series_oldest_first) >=
|
| 180 |
-
prev_4h = oi_series_oldest_first[
|
| 181 |
if prev_4h > 0:
|
| 182 |
oi_4h = round(((curr_oi - prev_4h) / prev_4h) * 100.0, 4)
|
| 183 |
|
|
|
|
| 161 |
def _compute_oi_horizons(
|
| 162 |
oi_series_oldest_first: list[float],
|
| 163 |
) -> tuple[float | None, float | None, float | None]:
|
| 164 |
+
"""Compute 15m, 1h (>=5 bars), and 4h (>=17 bars) OI % changes without mislabeling short history."""
|
| 165 |
if len(oi_series_oldest_first) < 2:
|
| 166 |
return None, None, None
|
| 167 |
|
|
|
|
| 176 |
oi_1h = round(((curr_oi - prev_1h) / prev_1h) * 100.0, 4)
|
| 177 |
|
| 178 |
oi_4h = None
|
| 179 |
+
if len(oi_series_oldest_first) >= 17:
|
| 180 |
+
prev_4h = oi_series_oldest_first[-17]
|
| 181 |
if prev_4h > 0:
|
| 182 |
oi_4h = round(((curr_oi - prev_4h) / prev_4h) * 100.0, 4)
|
| 183 |
|
backend/exchanges/bitget.py
CHANGED
|
@@ -78,30 +78,35 @@ class BitgetClient(BaseExchange):
|
|
| 78 |
return resolved
|
| 79 |
return symbol.upper().replace("/", "").replace("-", "").replace("_", "").replace(" ", "").strip()
|
| 80 |
|
| 81 |
-
async def
|
| 82 |
-
|
| 83 |
-
|
|
|
|
| 84 |
try:
|
| 85 |
resp = await self._client.get(path, params=params)
|
| 86 |
if 400 <= resp.status_code < 500:
|
| 87 |
-
|
| 88 |
resp.raise_for_status()
|
| 89 |
resp.raise_for_status()
|
| 90 |
data = resp.json()
|
| 91 |
code = str(data.get("code", ""))
|
| 92 |
if code == "00000":
|
| 93 |
-
return data.get("data")
|
| 94 |
if code in ("40019", "40034", "40017", "40725"):
|
| 95 |
-
|
| 96 |
logger.debug("[Bitget] Non-zero code for %s: %s", path, data.get("msg"))
|
| 97 |
-
return None
|
| 98 |
except Exception as exc:
|
| 99 |
if isinstance(exc, httpx.HTTPStatusError) and exc.response is not None and 400 <= exc.response.status_code < 500:
|
| 100 |
-
|
| 101 |
else:
|
| 102 |
-
|
| 103 |
logger.debug("[Bitget] GET %s failed: %s", path, exc)
|
| 104 |
-
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
|
| 106 |
async def _refresh_symbols_universe(self) -> None:
|
| 107 |
async with self._lock:
|
|
@@ -227,20 +232,29 @@ class BitgetClient(BaseExchange):
|
|
| 227 |
return []
|
| 228 |
|
| 229 |
try:
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 239 |
if isinstance(data, list) and len(data) == 0:
|
| 240 |
self._mark_spot_unlisted(clean_sym)
|
| 241 |
return []
|
| 242 |
if not data or not isinstance(data, list):
|
| 243 |
-
if
|
| 244 |
self._mark_spot_unlisted(clean_sym)
|
| 245 |
return []
|
| 246 |
|
|
|
|
| 78 |
return resolved
|
| 79 |
return symbol.upper().replace("/", "").replace("-", "").replace("_", "").replace(" ", "").strip()
|
| 80 |
|
| 81 |
+
async def _get_with_status(self, path: str, params: dict | None = None) -> tuple[Any, bool, bool]:
|
| 82 |
+
"""Fetch Bitget JSON payload returning (data, is_unlisted, is_transient) without shared mutable state."""
|
| 83 |
+
is_unlisted = False
|
| 84 |
+
is_transient = False
|
| 85 |
try:
|
| 86 |
resp = await self._client.get(path, params=params)
|
| 87 |
if 400 <= resp.status_code < 500:
|
| 88 |
+
is_unlisted = True
|
| 89 |
resp.raise_for_status()
|
| 90 |
resp.raise_for_status()
|
| 91 |
data = resp.json()
|
| 92 |
code = str(data.get("code", ""))
|
| 93 |
if code == "00000":
|
| 94 |
+
return data.get("data"), False, False
|
| 95 |
if code in ("40019", "40034", "40017", "40725"):
|
| 96 |
+
is_unlisted = True
|
| 97 |
logger.debug("[Bitget] Non-zero code for %s: %s", path, data.get("msg"))
|
| 98 |
+
return None, is_unlisted, False
|
| 99 |
except Exception as exc:
|
| 100 |
if isinstance(exc, httpx.HTTPStatusError) and exc.response is not None and 400 <= exc.response.status_code < 500:
|
| 101 |
+
is_unlisted = True
|
| 102 |
else:
|
| 103 |
+
is_transient = True
|
| 104 |
logger.debug("[Bitget] GET %s failed: %s", path, exc)
|
| 105 |
+
return None, is_unlisted, is_transient
|
| 106 |
+
|
| 107 |
+
async def _get(self, path: str, params: dict | None = None) -> Any:
|
| 108 |
+
data, _, _ = await self._get_with_status(path, params)
|
| 109 |
+
return data
|
| 110 |
|
| 111 |
async def _refresh_symbols_universe(self) -> None:
|
| 112 |
async with self._lock:
|
|
|
|
| 232 |
return []
|
| 233 |
|
| 234 |
try:
|
| 235 |
+
if "_get" in self.__dict__:
|
| 236 |
+
# Preserve monkeypatched self._get in isolated unit tests
|
| 237 |
+
data = await self._get(
|
| 238 |
+
"/api/v2/spot/market/fills",
|
| 239 |
+
{
|
| 240 |
+
"symbol": clean_sym,
|
| 241 |
+
"limit": str(min(limit, 100)),
|
| 242 |
+
},
|
| 243 |
+
)
|
| 244 |
+
is_unlisted, is_transient = False, False
|
| 245 |
+
else:
|
| 246 |
+
data, is_unlisted, is_transient = await self._get_with_status(
|
| 247 |
+
"/api/v2/spot/market/fills",
|
| 248 |
+
{
|
| 249 |
+
"symbol": clean_sym,
|
| 250 |
+
"limit": str(min(limit, 100)),
|
| 251 |
+
},
|
| 252 |
+
)
|
| 253 |
if isinstance(data, list) and len(data) == 0:
|
| 254 |
self._mark_spot_unlisted(clean_sym)
|
| 255 |
return []
|
| 256 |
if not data or not isinstance(data, list):
|
| 257 |
+
if is_unlisted and not is_transient:
|
| 258 |
self._mark_spot_unlisted(clean_sym)
|
| 259 |
return []
|
| 260 |
|
backend/exchanges/hyperliquid.py
CHANGED
|
@@ -234,7 +234,15 @@ class HyperliquidClient:
|
|
| 234 |
await self._refresh_meta()
|
| 235 |
coin = self.resolve_coin(symbol)
|
| 236 |
if not coin:
|
| 237 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 238 |
if not coin:
|
| 239 |
return []
|
| 240 |
|
|
|
|
| 234 |
await self._refresh_meta()
|
| 235 |
coin = self.resolve_coin(symbol)
|
| 236 |
if not coin:
|
| 237 |
+
if self._cached_universe:
|
| 238 |
+
return []
|
| 239 |
+
raw_coin = self._format_symbol(symbol)
|
| 240 |
+
if not raw_coin:
|
| 241 |
+
return []
|
| 242 |
+
if raw_coin.startswith("k") and len(raw_coin) > 1:
|
| 243 |
+
coin = f"k{raw_coin[1:].upper()}"
|
| 244 |
+
else:
|
| 245 |
+
coin = raw_coin.upper()
|
| 246 |
if not coin:
|
| 247 |
return []
|
| 248 |
|
backend/exchanges/okx.py
CHANGED
|
@@ -143,9 +143,16 @@ class OKXClient(BaseExchange):
|
|
| 143 |
return True
|
| 144 |
|
| 145 |
# 3. Direct lightweight probe fallback (only target most probable instrument IDs)
|
|
|
|
|
|
|
| 146 |
clean = sym_key
|
|
|
|
| 147 |
base = clean[:-4] if clean.endswith("USDT") or clean.endswith("USDC") else clean
|
| 148 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 149 |
for inst_cand in candidates:
|
| 150 |
try:
|
| 151 |
resp = await self._client.get(
|
|
@@ -180,15 +187,19 @@ class OKXClient(BaseExchange):
|
|
| 180 |
t = ticker_res[0]
|
| 181 |
last = float(t.get("last", 0))
|
| 182 |
|
|
|
|
| 183 |
if not isinstance(mp_res, Exception) and mp_res:
|
| 184 |
try:
|
| 185 |
mark = float(mp_res[0].get("markPx", last))
|
|
|
|
|
|
|
|
|
|
| 186 |
except (ValueError, TypeError, IndexError):
|
| 187 |
mark = last
|
|
|
|
| 188 |
else:
|
| 189 |
mark = last
|
| 190 |
|
| 191 |
-
index = last
|
| 192 |
basis_pct = ((mark - index) / index * 100) if index else 0.0
|
| 193 |
return {
|
| 194 |
"mark_price": mark,
|
|
@@ -385,14 +396,16 @@ class OKXClient(BaseExchange):
|
|
| 385 |
]
|
| 386 |
res_acct, res_pos = await asyncio.gather(*tasks, return_exceptions=True)
|
| 387 |
|
|
|
|
| 388 |
retail_long_ratio = None
|
| 389 |
if not isinstance(res_acct, Exception) and res_acct and len(res_acct) > 0:
|
| 390 |
try:
|
| 391 |
item = res_acct[0]
|
| 392 |
ratio_val = float(item[1]) if isinstance(item, (list, tuple)) else float(item.get("ratio", item.get("longShortRatio", 1.0)))
|
| 393 |
if ratio_val < 0:
|
| 394 |
-
|
| 395 |
-
|
|
|
|
| 396 |
except Exception as exc:
|
| 397 |
logger.debug("[OKX] Account L/S ratio parse error for %s: %s", symbol, exc)
|
| 398 |
|
|
@@ -400,15 +413,10 @@ class OKXClient(BaseExchange):
|
|
| 400 |
if not isinstance(res_pos, Exception) and res_pos and len(res_pos) > 0:
|
| 401 |
try:
|
| 402 |
item = res_pos[0]
|
| 403 |
-
if isinstance(item, (list, tuple)):
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
top_pos_ratio = round(r / (1.0 + r), 4)
|
| 408 |
-
elif len(item) >= 3:
|
| 409 |
-
v1, v2 = float(item[1]), float(item[2])
|
| 410 |
-
if v1 + v2 > 0:
|
| 411 |
-
top_pos_ratio = round(v1 / (v1 + v2), 4)
|
| 412 |
elif isinstance(item, dict):
|
| 413 |
if "longPos" in item and "shortPos" in item:
|
| 414 |
lp, sp = float(item["longPos"]), float(item["shortPos"])
|
|
@@ -425,6 +433,9 @@ class OKXClient(BaseExchange):
|
|
| 425 |
except Exception as exc:
|
| 426 |
logger.debug("[OKX] Top position L/S ratio parse error for %s: %s", symbol, exc)
|
| 427 |
|
|
|
|
|
|
|
|
|
|
| 428 |
if retail_long_ratio is not None and top_pos_ratio is not None:
|
| 429 |
whale_retail_delta = round(top_pos_ratio - retail_long_ratio, 4)
|
| 430 |
return {
|
|
|
|
| 143 |
return True
|
| 144 |
|
| 145 |
# 3. Direct lightweight probe fallback (only target most probable instrument IDs)
|
| 146 |
+
from engine.symbol_resolver import strip_multiplier_prefix
|
| 147 |
+
|
| 148 |
clean = sym_key
|
| 149 |
+
stripped = strip_multiplier_prefix(clean)
|
| 150 |
base = clean[:-4] if clean.endswith("USDT") or clean.endswith("USDC") else clean
|
| 151 |
+
stripped_base = stripped[:-4] if stripped.endswith("USDT") or stripped.endswith("USDC") else stripped
|
| 152 |
+
candidates: list[str] = []
|
| 153 |
+
for cand in (f"{base}-USDT-SWAP", f"{stripped_base}-USDT-SWAP", f"{clean}-SWAP"):
|
| 154 |
+
if cand not in candidates:
|
| 155 |
+
candidates.append(cand)
|
| 156 |
for inst_cand in candidates:
|
| 157 |
try:
|
| 158 |
resp = await self._client.get(
|
|
|
|
| 187 |
t = ticker_res[0]
|
| 188 |
last = float(t.get("last", 0))
|
| 189 |
|
| 190 |
+
index = last
|
| 191 |
if not isinstance(mp_res, Exception) and mp_res:
|
| 192 |
try:
|
| 193 |
mark = float(mp_res[0].get("markPx", last))
|
| 194 |
+
raw_idx = mp_res[0].get("idxPx")
|
| 195 |
+
if raw_idx is not None and raw_idx != "":
|
| 196 |
+
index = float(raw_idx)
|
| 197 |
except (ValueError, TypeError, IndexError):
|
| 198 |
mark = last
|
| 199 |
+
index = last
|
| 200 |
else:
|
| 201 |
mark = last
|
| 202 |
|
|
|
|
| 203 |
basis_pct = ((mark - index) / index * 100) if index else 0.0
|
| 204 |
return {
|
| 205 |
"mark_price": mark,
|
|
|
|
| 396 |
]
|
| 397 |
res_acct, res_pos = await asyncio.gather(*tasks, return_exceptions=True)
|
| 398 |
|
| 399 |
+
saw_invalid_neg_acct = False
|
| 400 |
retail_long_ratio = None
|
| 401 |
if not isinstance(res_acct, Exception) and res_acct and len(res_acct) > 0:
|
| 402 |
try:
|
| 403 |
item = res_acct[0]
|
| 404 |
ratio_val = float(item[1]) if isinstance(item, (list, tuple)) else float(item.get("ratio", item.get("longShortRatio", 1.0)))
|
| 405 |
if ratio_val < 0:
|
| 406 |
+
saw_invalid_neg_acct = True
|
| 407 |
+
else:
|
| 408 |
+
retail_long_ratio = round(ratio_val / (1.0 + ratio_val), 4)
|
| 409 |
except Exception as exc:
|
| 410 |
logger.debug("[OKX] Account L/S ratio parse error for %s: %s", symbol, exc)
|
| 411 |
|
|
|
|
| 413 |
if not isinstance(res_pos, Exception) and res_pos and len(res_pos) > 0:
|
| 414 |
try:
|
| 415 |
item = res_pos[0]
|
| 416 |
+
if isinstance(item, (list, tuple)) and len(item) >= 2:
|
| 417 |
+
r = float(item[1])
|
| 418 |
+
if r >= 0:
|
| 419 |
+
top_pos_ratio = round(r / (1.0 + r), 4)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 420 |
elif isinstance(item, dict):
|
| 421 |
if "longPos" in item and "shortPos" in item:
|
| 422 |
lp, sp = float(item["longPos"]), float(item["shortPos"])
|
|
|
|
| 433 |
except Exception as exc:
|
| 434 |
logger.debug("[OKX] Top position L/S ratio parse error for %s: %s", symbol, exc)
|
| 435 |
|
| 436 |
+
if saw_invalid_neg_acct and top_pos_ratio is None:
|
| 437 |
+
return None
|
| 438 |
+
|
| 439 |
if retail_long_ratio is not None and top_pos_ratio is not None:
|
| 440 |
whale_retail_delta = round(top_pos_ratio - retail_long_ratio, 4)
|
| 441 |
return {
|
tests/test_backtester.py
CHANGED
|
@@ -468,3 +468,27 @@ def test_backtester_cli_walk_forward_and_multi_symbols(tmp_path, capsys, monkeyp
|
|
| 468 |
assert "oos_retention_ratio" in out_multi["symbols"]["BTCUSDT"]
|
| 469 |
|
| 470 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 468 |
assert "oos_retention_ratio" in out_multi["symbols"]["BTCUSDT"]
|
| 469 |
|
| 470 |
|
| 471 |
+
def test_backtester_oi_history_deduplicates_timestamps():
|
| 472 |
+
"""Duplicate OI timestamps must deduplicate rather than collapsing series[-1] == series[-2] to 0% delta."""
|
| 473 |
+
from engine.backtester import CausalBacktester
|
| 474 |
+
|
| 475 |
+
candles = _make_candles(40, base_price=50000.0)
|
| 476 |
+
t_eval = candles[32]["timestamp"]
|
| 477 |
+
oi_history = [
|
| 478 |
+
{"timestamp": t_eval - 900_000, "open_interest": 1000.0},
|
| 479 |
+
{"timestamp": t_eval, "open_interest": 1100.0},
|
| 480 |
+
{"timestamp": t_eval, "open_interest": 1100.0}, # duplicate timestamp
|
| 481 |
+
]
|
| 482 |
+
captured_oi_pct: list[float | None] = []
|
| 483 |
+
|
| 484 |
+
def _inspect_signal(raw):
|
| 485 |
+
oi_data = raw["binance"]["open_interest_data"]
|
| 486 |
+
if oi_data and candles[32]["timestamp"] == raw["binance"]["ohlcv"]["1h"][-1]["timestamp"]:
|
| 487 |
+
captured_oi_pct.append(oi_data.get("oi_change_pct"))
|
| 488 |
+
return {"direction": "NEUTRAL", "conviction": 0, "sniper_grade": "WAIT", "trade_levels": None}
|
| 489 |
+
|
| 490 |
+
bt = CausalBacktester(warmup_bars=30)
|
| 491 |
+
bt.run(symbol="BTCUSDT", candles_1h=candles, oi_history=oi_history, signal_fn=_inspect_signal)
|
| 492 |
+
assert captured_oi_pct == [pytest.approx(10.0)]
|
| 493 |
+
|
| 494 |
+
|
tests/test_five_exchange_whale_pov.py
CHANGED
|
@@ -8,7 +8,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 |
|
|
@@ -1817,6 +1817,491 @@ def test_backtester_print_summary_walk_forward_and_compare_ab(capsys):
|
|
| 1817 |
assert "Delta Expectancy R" in out
|
| 1818 |
|
| 1819 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1820 |
|
| 1821 |
|
| 1822 |
|
|
|
|
| 8 |
import sys
|
| 9 |
import time
|
| 10 |
from typing import Any
|
| 11 |
+
from unittest.mock import AsyncMock, MagicMock, patch
|
| 12 |
|
| 13 |
import pytest
|
| 14 |
|
|
|
|
| 1817 |
assert "Delta Expectancy R" in out
|
| 1818 |
|
| 1819 |
|
| 1820 |
+
@pytest.mark.anyio
|
| 1821 |
+
async def test_audit_fixes_okx_top_pos_ratio_3elem_idxpx_1000x_probe_and_base_oi_4h():
|
| 1822 |
+
"""Verify OKX top_pos 3-elem safety, neg acct non-blocking, idxPx, 1000x probe, 1M prefix, and >=17-bar 4h OI."""
|
| 1823 |
+
from exchanges.base import BaseExchange
|
| 1824 |
+
from exchanges.okx import OKXClient
|
| 1825 |
+
from engine.symbol_resolver import strip_multiplier_prefix
|
| 1826 |
+
|
| 1827 |
+
# 1. 1M multiplier stripping
|
| 1828 |
+
assert strip_multiplier_prefix("1MBABYDOGEUSDT") == "BABYDOGEUSDT"
|
| 1829 |
+
|
| 1830 |
+
# 2. _compute_oi_horizons requires >= 17 bars for 4h (13 bars is only 3h)
|
| 1831 |
+
c15_13, c1h_13, c4h_13 = BaseExchange._compute_oi_horizons([100.0 + i for i in range(13)])
|
| 1832 |
+
assert c15_13 is not None
|
| 1833 |
+
assert c1h_13 is not None
|
| 1834 |
+
assert c4h_13 is None
|
| 1835 |
+
|
| 1836 |
+
okx = OKXClient()
|
| 1837 |
+
try:
|
| 1838 |
+
# 3. OKX top_pos 3-elem tuple & negative account-ratio preserves valid top_pos_ratio
|
| 1839 |
+
async def _mock_okx_ls(path: str, params: dict | None = None):
|
| 1840 |
+
if "long-short-account-ratio" in path:
|
| 1841 |
+
return [["1700000000000", "-1"]]
|
| 1842 |
+
if "long-short-position-ratio-contract-top-trader" in path:
|
| 1843 |
+
return [["1700000000000", "1.5", "1699996400000"]]
|
| 1844 |
+
return []
|
| 1845 |
+
|
| 1846 |
+
okx._get = _mock_okx_ls
|
| 1847 |
+
ls = await okx.get_long_short_ratio("BTCUSDT", period="1h")
|
| 1848 |
+
assert ls is not None
|
| 1849 |
+
assert ls["source"] == "top_trader"
|
| 1850 |
+
assert ls["top_position_long_ratio"] == pytest.approx(0.6)
|
| 1851 |
+
|
| 1852 |
+
# 4. OKX get_mark_price honors idxPx when present
|
| 1853 |
+
async def _mock_okx_mp(path: str, params: dict | None = None):
|
| 1854 |
+
if path == "/api/v5/market/ticker":
|
| 1855 |
+
return [{"last": "50005.0"}]
|
| 1856 |
+
if path == "/api/v5/public/mark-price":
|
| 1857 |
+
return [{"markPx": "50010.0", "idxPx": "50000.0"}]
|
| 1858 |
+
return []
|
| 1859 |
+
|
| 1860 |
+
okx._get = _mock_okx_mp
|
| 1861 |
+
mp = await okx.get_mark_price("BTCUSDT")
|
| 1862 |
+
assert mp["mark_price"] == 50010.0
|
| 1863 |
+
assert mp["index_price"] == 50000.0
|
| 1864 |
+
assert mp["basis_pct"] == pytest.approx(0.02, abs=1e-4)
|
| 1865 |
+
|
| 1866 |
+
# 5. OKX check_symbol_exists fallback strips 1000x prefix (1000PEPEUSDT -> PEPE-USDT-SWAP)
|
| 1867 |
+
okx._known_symbols.clear()
|
| 1868 |
+
okx._inst_map.clear()
|
| 1869 |
+
okx._negative_cache.clear()
|
| 1870 |
+
probed_insts: list[str] = []
|
| 1871 |
+
|
| 1872 |
+
async def _mock_probe(path: str, params: dict | None = None, timeout: float = 3.0):
|
| 1873 |
+
inst = (params or {}).get("instId", "")
|
| 1874 |
+
probed_insts.append(inst)
|
| 1875 |
+
resp = MagicMock()
|
| 1876 |
+
resp.status_code = 200
|
| 1877 |
+
if inst == "PEPE-USDT-SWAP":
|
| 1878 |
+
resp.json.return_value = {"code": "0", "data": [{"instId": "PEPE-USDT-SWAP"}]}
|
| 1879 |
+
else:
|
| 1880 |
+
resp.json.return_value = {"code": "51001", "data": []}
|
| 1881 |
+
return resp
|
| 1882 |
+
|
| 1883 |
+
okx._load_symbols = AsyncMock(return_value=None)
|
| 1884 |
+
okx._client.get = _mock_probe
|
| 1885 |
+
assert await okx.check_symbol_exists("1000PEPEUSDT") is True
|
| 1886 |
+
assert "PEPE-USDT-SWAP" in probed_insts
|
| 1887 |
+
finally:
|
| 1888 |
+
await okx.close()
|
| 1889 |
+
|
| 1890 |
+
|
| 1891 |
+
@pytest.mark.anyio
|
| 1892 |
+
async def test_audit_fixes_hyperliquid_unlisted_ohlcv_bitget_concurrency_and_empty_shell():
|
| 1893 |
+
"""Verify HL unlisted get_ohlcv skips POST, Bitget concurrency doesn't poison spot cache, and empty shells drop to None."""
|
| 1894 |
+
from exchanges.bitget import BitgetClient
|
| 1895 |
+
from exchanges.hyperliquid import HyperliquidClient
|
| 1896 |
+
from engine.data_collector import DataCollector
|
| 1897 |
+
|
| 1898 |
+
# 1. Hyperliquid get_ohlcv skips POST when universe is populated & coin not listed
|
| 1899 |
+
hl = HyperliquidClient()
|
| 1900 |
+
try:
|
| 1901 |
+
hl._cached_universe = {"BTC": {"markPx": "50000.0"}}
|
| 1902 |
+
hl._coin_lookup = {"BTC": "BTC"}
|
| 1903 |
+
hl._cache_time = time.time()
|
| 1904 |
+
hl._client.post = AsyncMock()
|
| 1905 |
+
candles = await hl.get_ohlcv("NOTONHLUSDT", timeframe="5m", limit=10)
|
| 1906 |
+
assert candles == []
|
| 1907 |
+
hl._client.post.assert_not_called()
|
| 1908 |
+
finally:
|
| 1909 |
+
await hl.close()
|
| 1910 |
+
|
| 1911 |
+
# 2. Bitget concurrent HTTP calls must not race shared _last_get_unlisted flag
|
| 1912 |
+
bg = BitgetClient()
|
| 1913 |
+
try:
|
| 1914 |
+
async def _mock_client_get(path: str, params: dict | None = None):
|
| 1915 |
+
resp = MagicMock()
|
| 1916 |
+
if path == "/api/v2/spot/market/fills":
|
| 1917 |
+
await asyncio.sleep(0.02)
|
| 1918 |
+
resp.status_code = 200
|
| 1919 |
+
resp.raise_for_status = MagicMock()
|
| 1920 |
+
resp.json.return_value = {"code": "00000", "data": None}
|
| 1921 |
+
return resp
|
| 1922 |
+
await asyncio.sleep(0.005)
|
| 1923 |
+
resp.status_code = 400
|
| 1924 |
+
resp.raise_for_status = MagicMock(side_effect=RuntimeError("unrelated 400"))
|
| 1925 |
+
return resp
|
| 1926 |
+
|
| 1927 |
+
bg._client.get = _mock_client_get
|
| 1928 |
+
spot_res, _ = await asyncio.gather(
|
| 1929 |
+
bg.get_spot_trades("BTCUSDT"),
|
| 1930 |
+
bg._get("/api/v2/mix/market/funding-time", {"symbol": "NOTONBG"}),
|
| 1931 |
+
)
|
| 1932 |
+
assert spot_res == []
|
| 1933 |
+
assert not bg._is_spot_unlisted("BTCUSDT")
|
| 1934 |
+
finally:
|
| 1935 |
+
await bg.close()
|
| 1936 |
+
|
| 1937 |
+
# 3. DataCollector drops 100% empty-shell exchange snapshots to None
|
| 1938 |
+
mock_bin = AsyncMock()
|
| 1939 |
+
mock_bin.get_full_snapshot = AsyncMock(return_value={
|
| 1940 |
+
"symbol": "HYPEUSDT",
|
| 1941 |
+
"exchange": "binance",
|
| 1942 |
+
"mark_price_data": None,
|
| 1943 |
+
"funding_rate_data": None,
|
| 1944 |
+
"open_interest_data": None,
|
| 1945 |
+
"ls_ratio_data": None,
|
| 1946 |
+
"ohlcv": {"5m": [], "15m": [], "1h": []},
|
| 1947 |
+
"trades": [],
|
| 1948 |
+
"spot_trades": [],
|
| 1949 |
+
"orderbook": None,
|
| 1950 |
+
})
|
| 1951 |
+
mock_bin.close = AsyncMock()
|
| 1952 |
+
collector = DataCollector(
|
| 1953 |
+
binance=mock_bin,
|
| 1954 |
+
bybit=AsyncMock(),
|
| 1955 |
+
okx=AsyncMock(),
|
| 1956 |
+
bitget=AsyncMock(),
|
| 1957 |
+
hyperliquid=AsyncMock(),
|
| 1958 |
+
)
|
| 1959 |
+
with patch("engine.data_collector.check_spot_market_exists", AsyncMock(return_value=False)):
|
| 1960 |
+
res = await collector.collect(
|
| 1961 |
+
"HYPEUSDT",
|
| 1962 |
+
on_binance=True,
|
| 1963 |
+
on_bybit=False,
|
| 1964 |
+
on_okx=False,
|
| 1965 |
+
on_bitget=False,
|
| 1966 |
+
on_hyperliquid=False,
|
| 1967 |
+
)
|
| 1968 |
+
assert res["binance"] is None
|
| 1969 |
+
|
| 1970 |
+
|
| 1971 |
+
def test_audit_fixes_whale_double_count_spot_1000x_overlap_filter_and_4h_oi_only():
|
| 1972 |
+
"""Verify HL DEX single-vote consensus, cross-venue spot 1000x scaling, overlap min_trades filter, and 4h-only OI."""
|
| 1973 |
+
from engine.signal_engine import (
|
| 1974 |
+
_align_multi_venue_trades,
|
| 1975 |
+
_compute_oi_divergence,
|
| 1976 |
+
_compute_spot_futures_cvd,
|
| 1977 |
+
_compute_whale_order_flow,
|
| 1978 |
+
)
|
| 1979 |
+
|
| 1980 |
+
now_ms = int(time.time() * 1000)
|
| 1981 |
+
|
| 1982 |
+
# 1. HL DEX double-counting check: HL block trade + HL wallet alone must NOT mark 2 venues aligned
|
| 1983 |
+
hl_only_flat = (
|
| 1984 |
+
[
|
| 1985 |
+
{"price": 100.0, "qty": 1500.0, "is_buyer_maker": False, "time": now_ms - 5000 + i * 100, "venue": "hyperliquid", "taker_wallet": "0xWHALE1"}
|
| 1986 |
+
for i in range(6)
|
| 1987 |
+
]
|
| 1988 |
+
+ [
|
| 1989 |
+
{"price": 100.0, "qty": 1.0, "is_buyer_maker": False, "time": now_ms - 5000 + i * 100, "venue": "binance"}
|
| 1990 |
+
for i in range(6)
|
| 1991 |
+
]
|
| 1992 |
+
)
|
| 1993 |
+
res_hl_only = _compute_whale_order_flow(trades=hl_only_flat, mark_price=100.0)
|
| 1994 |
+
assert res_hl_only["onchain_whale_wallets"] >= 1
|
| 1995 |
+
assert res_hl_only["whale_venues_bull"] == 1
|
| 1996 |
+
assert res_hl_only["cross_venue_whale_aligned"] is False
|
| 1997 |
+
|
| 1998 |
+
# Adding a second real exchange confirms cross_venue_whale_aligned
|
| 1999 |
+
both_flat = (
|
| 2000 |
+
[
|
| 2001 |
+
{"price": 100.0, "qty": 1500.0, "is_buyer_maker": False, "time": now_ms - 5000 + i * 100, "venue": "hyperliquid", "taker_wallet": "0xWHALE1"}
|
| 2002 |
+
for i in range(6)
|
| 2003 |
+
]
|
| 2004 |
+
+ [
|
| 2005 |
+
{"price": 100.0, "qty": 1500.0, "is_buyer_maker": False, "time": now_ms - 5000 + i * 100, "venue": "binance"}
|
| 2006 |
+
for i in range(6)
|
| 2007 |
+
]
|
| 2008 |
+
)
|
| 2009 |
+
res_two = _compute_whale_order_flow(trades=both_flat, mark_price=100.0)
|
| 2010 |
+
assert res_two["whale_venues_bull"] == 2
|
| 2011 |
+
assert res_two["cross_venue_whale_aligned"] is True
|
| 2012 |
+
|
| 2013 |
+
# 2. _align_multi_venue_trades overlap mode filters out venues with <5 trades inside the overlap window
|
| 2014 |
+
overlap_trades = (
|
| 2015 |
+
[{"price": 100.0, "qty": 1.0, "time": now_ms - 10_000 + i * 500, "venue": "binance"} for i in range(20)]
|
| 2016 |
+
+ [{"price": 100.0, "qty": 1.0, "time": now_ms - 10_000 + i * 500, "venue": "okx"} for i in range(20)]
|
| 2017 |
+
+ (
|
| 2018 |
+
[{"price": 100.0, "qty": 1.0, "time": now_ms - 25_000 + i * 1000, "venue": "bybit"} for i in range(4)]
|
| 2019 |
+
+ [{"price": 100.0, "qty": 1.0, "time": now_ms - 5_000 + i * 500, "venue": "bybit"} for i in range(2)]
|
| 2020 |
+
)
|
| 2021 |
+
)
|
| 2022 |
+
aligned_overlap, overlap_mode = _align_multi_venue_trades(overlap_trades)
|
| 2023 |
+
assert overlap_mode == "overlap"
|
| 2024 |
+
assert "binance" in aligned_overlap
|
| 2025 |
+
assert "okx" in aligned_overlap
|
| 2026 |
+
assert "bybit" not in aligned_overlap
|
| 2027 |
+
|
| 2028 |
+
# 3. _compute_spot_futures_cvd cross-venue fallback scales 1000x venues per venue
|
| 2029 |
+
# No single venue has BOTH spot_trades and trades -> triggers cross-venue fallback
|
| 2030 |
+
binance_spot_only = {
|
| 2031 |
+
"mark_price_data": {"mark_price": 0.012},
|
| 2032 |
+
"trades": [],
|
| 2033 |
+
"spot_trades": [{"price": 0.000012, "qty": 50_000_000.0, "is_buyer_maker": False, "time": now_ms - 1000 + i * 10} for i in range(6)],
|
| 2034 |
+
}
|
| 2035 |
+
bybit_1000x_fut_only = {
|
| 2036 |
+
"mark_price_data": {"mark_price": 0.012},
|
| 2037 |
+
"trades": [{"price": 0.012, "qty": 50_000.0, "is_buyer_maker": False, "time": now_ms - 1000 + i * 10} for i in range(6)],
|
| 2038 |
+
"spot_trades": [],
|
| 2039 |
+
}
|
| 2040 |
+
okx_1x_fut_only = {
|
| 2041 |
+
"mark_price_data": {"mark_price": 0.000012},
|
| 2042 |
+
"trades": [{"price": 0.000012, "qty": 50_000_000.0, "is_buyer_maker": True, "time": now_ms - 1000 + i * 10} for i in range(6)],
|
| 2043 |
+
"spot_trades": [],
|
| 2044 |
+
}
|
| 2045 |
+
sfc_res = _compute_spot_futures_cvd(
|
| 2046 |
+
binance_data=binance_spot_only,
|
| 2047 |
+
bybit_data=bybit_1000x_fut_only,
|
| 2048 |
+
okx_data=okx_1x_fut_only,
|
| 2049 |
+
bitget_data=None,
|
| 2050 |
+
ref_mark_px=0.012,
|
| 2051 |
+
)
|
| 2052 |
+
# Bybit 1000x buy ($3,600) + OKX 1x sell ($3,600) are equal-USD opposites -> normalized futures_delta_ratio ~ 0.0
|
| 2053 |
+
assert abs(sfc_res["futures_delta_ratio"]) < 0.05
|
| 2054 |
+
|
| 2055 |
+
# 4. _compute_oi_divergence computes swing_score even when short 15m/1h price_changes are empty
|
| 2056 |
+
oi_div_res = _compute_oi_divergence(
|
| 2057 |
+
binance_data={
|
| 2058 |
+
"ohlcv": {
|
| 2059 |
+
"15m": [],
|
| 2060 |
+
"4h": [{"close": 100.0}, {"close": 103.0}],
|
| 2061 |
+
},
|
| 2062 |
+
"open_interest_data": {"open_interest": 10000.0, "oi_change_4h_pct": 5.0},
|
| 2063 |
+
},
|
| 2064 |
+
bybit_data=None,
|
| 2065 |
+
)
|
| 2066 |
+
assert oi_div_res["score"] == 0
|
| 2067 |
+
assert oi_div_res["swing_score"] > 0
|
| 2068 |
+
|
| 2069 |
+
|
| 2070 |
+
def test_audit_fixes_fake_detector_and_whale_sweep_swing_survival():
|
| 2071 |
+
"""Verify FakeDetector sweep recency, partial 1m fallback, range wash guard, dump spoof, and swing WHALE_SWEEP_ENTRY survival."""
|
| 2072 |
+
from engine.fake_detector import FakeDetector
|
| 2073 |
+
from engine.signal_engine import SignalEngine
|
| 2074 |
+
|
| 2075 |
+
fd = FakeDetector()
|
| 2076 |
+
|
| 2077 |
+
# 1. Newest sweep wins: completed bar[-4] lower sweep, completed bar[-2] upper sweep -> UPPER_SWEEP
|
| 2078 |
+
candles_newest = [
|
| 2079 |
+
{"open": 100.0, "high": 100.5, "low": 97.0, "close": 100.2, "volume": 100.0},
|
| 2080 |
+
{"open": 100.2, "high": 100.4, "low": 99.9, "close": 100.1, "volume": 100.0},
|
| 2081 |
+
{"open": 100.1, "high": 103.5, "low": 100.0, "close": 100.05, "volume": 100.0},
|
| 2082 |
+
{"open": 100.05, "high": 100.2, "low": 99.9, "close": 100.1, "volume": 50.0}, # forming candle
|
| 2083 |
+
]
|
| 2084 |
+
res_rec = fd.detect(
|
| 2085 |
+
ohlcv_1m=candles_newest,
|
| 2086 |
+
ohlcv_5m=[],
|
| 2087 |
+
binance_mark=None,
|
| 2088 |
+
bybit_mark=None,
|
| 2089 |
+
cvd_matches_price=True,
|
| 2090 |
+
orderbook={"bids": [], "asks": []},
|
| 2091 |
+
)
|
| 2092 |
+
assert res_rec["sweep_direction"] == "UPPER_SWEEP"
|
| 2093 |
+
|
| 2094 |
+
# 2. Partial 1m (< 3 bars) falls back to ohlcv_5m for wick sweep detection
|
| 2095 |
+
candles_1m_partial = [
|
| 2096 |
+
{"open": 100.0, "high": 100.1, "low": 99.9, "close": 100.0, "volume": 10.0},
|
| 2097 |
+
{"open": 100.0, "high": 100.1, "low": 99.9, "close": 100.0, "volume": 10.0},
|
| 2098 |
+
]
|
| 2099 |
+
candles_5m_sweep = [
|
| 2100 |
+
{"open": 100.0, "high": 100.2, "low": 99.8, "close": 100.0, "volume": 10.0},
|
| 2101 |
+
{"open": 100.0, "high": 100.2, "low": 99.8, "close": 100.1, "volume": 10.0},
|
| 2102 |
+
{"open": 100.1, "high": 100.2, "low": 97.0, "close": 100.0, "volume": 10.0},
|
| 2103 |
+
{"open": 100.0, "high": 100.1, "low": 99.9, "close": 100.05, "volume": 5.0}, # forming
|
| 2104 |
+
]
|
| 2105 |
+
res_fb = fd.detect(
|
| 2106 |
+
ohlcv_1m=candles_1m_partial,
|
| 2107 |
+
ohlcv_5m=candles_5m_sweep,
|
| 2108 |
+
binance_mark=None,
|
| 2109 |
+
bybit_mark=None,
|
| 2110 |
+
cvd_matches_price=True,
|
| 2111 |
+
orderbook={"bids": [], "asks": []},
|
| 2112 |
+
)
|
| 2113 |
+
assert res_fb["sweep_direction"] == "LOWER_SWEEP"
|
| 2114 |
+
|
| 2115 |
+
# 3. High-volatility pinbar (6.5% range) must NOT be flagged as wash trading
|
| 2116 |
+
pinbar_candles = [
|
| 2117 |
+
{"open": 100.0, "high": 100.5, "low": 99.5, "close": 100.2, "volume": 10.0}
|
| 2118 |
+
for _ in range(20)
|
| 2119 |
+
] + [
|
| 2120 |
+
{"open": 100.0, "high": 106.0, "low": 99.5, "close": 100.05, "volume": 60.0},
|
| 2121 |
+
{"open": 100.05, "high": 100.2, "low": 99.9, "close": 100.1, "volume": 10.0},
|
| 2122 |
+
]
|
| 2123 |
+
res_pin = fd.detect(
|
| 2124 |
+
ohlcv_1m=[],
|
| 2125 |
+
ohlcv_5m=pinbar_candles,
|
| 2126 |
+
binance_mark=None,
|
| 2127 |
+
bybit_mark=None,
|
| 2128 |
+
cvd_matches_price=True,
|
| 2129 |
+
orderbook={"bids": [], "asks": []},
|
| 2130 |
+
)
|
| 2131 |
+
assert not any("wash trading" in w.lower() for w in res_pin["warnings"])
|
| 2132 |
+
|
| 2133 |
+
# 4. Big bid wall during correlated price+CVD dump still flagged when cvd_rising=False
|
| 2134 |
+
spoof_ob = {"bids": [[100.0, 900.0]], "asks": [[100.1, 100.0]]}
|
| 2135 |
+
res_spoof = fd.detect(
|
| 2136 |
+
ohlcv_1m=[],
|
| 2137 |
+
ohlcv_5m=[],
|
| 2138 |
+
binance_mark=None,
|
| 2139 |
+
bybit_mark=None,
|
| 2140 |
+
cvd_matches_price=True,
|
| 2141 |
+
orderbook=spoof_ob,
|
| 2142 |
+
cvd_rising=False,
|
| 2143 |
+
)
|
| 2144 |
+
assert res_spoof["has_non_sweep_manipulation"] is True
|
| 2145 |
+
assert any("bid" in w.lower() for w in res_spoof["warnings"])
|
| 2146 |
+
|
| 2147 |
+
# 5. Swing WHALE_SWEEP_ENTRY survives when intraday opposes LOWER_SWEEP
|
| 2148 |
+
engine = SignalEngine()
|
| 2149 |
+
now_ms = int(time.time() * 1000)
|
| 2150 |
+
raw = {
|
| 2151 |
+
"symbol": "BTCUSDT",
|
| 2152 |
+
"binance": {
|
| 2153 |
+
"mark_price_data": {"mark_price": 50000.0, "index_price": 50000.0, "basis_pct": 0.0},
|
| 2154 |
+
"funding_rate_data": {"funding_rate": 0.0001},
|
| 2155 |
+
"open_interest_data": {"open_interest": 10000.0, "oi_change_pct": 1.0, "oi_change_1h_pct": 2.0, "oi_change_4h_pct": 4.0},
|
| 2156 |
+
"ls_ratio_data": {"long_ratio": 0.5, "short_ratio": 0.5, "whale_retail_delta": 0.1},
|
| 2157 |
+
"trades": [{"price": 50000.0, "qty": 10.0, "is_buyer_maker": False, "time": now_ms - 500 + i * 50} for i in range(10)],
|
| 2158 |
+
"spot_trades": [{"price": 50000.0, "qty": 10.0, "is_buyer_maker": False, "time": now_ms - 500 + i * 50} for i in range(10)],
|
| 2159 |
+
"orderbook": {
|
| 2160 |
+
"bids": [[50000.0 - i, 100.0] for i in range(10)],
|
| 2161 |
+
"asks": [[50001.0 + i, 20.0] for i in range(10)],
|
| 2162 |
+
},
|
| 2163 |
+
"ohlcv": {
|
| 2164 |
+
"1m": [{"timestamp": now_ms - 180_000 + i * 60_000, "open": 50000.0, "high": 50050.0, "low": 49950.0, "close": 50000.0, "volume": 100.0} for i in range(5)],
|
| 2165 |
+
"5m": [{"timestamp": now_ms - 1_500_000 + i * 300_000, "open": 50000.0, "high": 50050.0, "low": 49950.0, "close": 50000.0, "volume": 100.0} for i in range(5)],
|
| 2166 |
+
"15m": [{"timestamp": now_ms - 9_000_000 + i * 900_000, "open": 50000.0, "high": 50100.0, "low": 49900.0, "close": 50000.0, "volume": 100.0} for i in range(10)],
|
| 2167 |
+
"1h": [{"timestamp": now_ms - 36_000_000 + i * 3_600_000, "open": 50000.0, "high": 50200.0, "low": 49800.0, "close": 50000.0, "volume": 100.0} for i in range(10)],
|
| 2168 |
+
"4h": [{"timestamp": now_ms - 144_000_000 + i * 14_400_000, "open": 50000.0, "high": 50500.0, "low": 49500.0, "close": 50000.0, "volume": 100.0} for i in range(10)],
|
| 2169 |
+
},
|
| 2170 |
+
},
|
| 2171 |
+
"bybit": None, "okx": None, "bitget": None, "hyperliquid": None, "has_spot": True,
|
| 2172 |
+
}
|
| 2173 |
+
from engine import signal_engine as se_mod
|
| 2174 |
+
|
| 2175 |
+
mock_intra = {
|
| 2176 |
+
"score": -4, "direction": "SHORT", "confidence": "MEDIUM", "conviction": 2,
|
| 2177 |
+
"aligned_factors": 2, "factor_details": {}, "effective_threshold": 3,
|
| 2178 |
+
"sniper_grade": "SNIPER_B", "sniper_label": "Setup",
|
| 2179 |
+
}
|
| 2180 |
+
mock_swing = {
|
| 2181 |
+
"score": 6, "direction": "LONG", "confidence": "HIGH", "conviction": 4,
|
| 2182 |
+
"aligned_factors": 3, "factor_details": {}, "effective_threshold": 3,
|
| 2183 |
+
"sniper_grade": "SNIPER_A_PLUS", "sniper_label": "Sniper A+",
|
| 2184 |
+
}
|
| 2185 |
+
mock_mtf_clean = {
|
| 2186 |
+
"active_timeframe": "15m", "regime": "trending", "market_condition": "trending",
|
| 2187 |
+
"score": 2, "intraday_structure": -2, "swing_structure": 2,
|
| 2188 |
+
"label": "Split structure",
|
| 2189 |
+
"structure_per_tf": {"15m": "bearish", "1h": "bearish", "4h": "bullish", "1d": "bullish"},
|
| 2190 |
+
"intraday_atr_stretch": 0.5, "swing_atr_stretch": 0.5,
|
| 2191 |
+
}
|
| 2192 |
+
with patch("engine.signal_engine.mtf_analyzer.analyze", return_value=mock_mtf_clean), patch(
|
| 2193 |
+
"engine.signal_engine.confluence_scorer.compute",
|
| 2194 |
+
side_effect=lambda *_a, **kw: dict(mock_intra if kw.get("horizon") == "intraday" else mock_swing),
|
| 2195 |
+
), patch("engine.signal_engine.fake_detector.detect", return_value={
|
| 2196 |
+
"is_fake": True, "score": -2, "label": "Fake / Sweep Warning",
|
| 2197 |
+
"warnings": ["Wick Sweep Detected: lower_wick_sweep"], "sweep_direction": "LOWER_SWEEP",
|
| 2198 |
+
"has_non_sweep_manipulation": False,
|
| 2199 |
+
}):
|
| 2200 |
+
sig = engine.compute(raw, horizon_thresholds={"intraday": 3, "swing": 3, "primary": 3})
|
| 2201 |
+
|
| 2202 |
+
assert sig["direction"] == "LONG"
|
| 2203 |
+
assert sig["signals"]["fake_detector"].get("sweep_override") == "WHALE_SWEEP_ENTRY"
|
| 2204 |
+
assert sig["horizons"]["swing"]["direction"] == "LONG"
|
| 2205 |
+
assert sig["horizons"]["swing"]["trade_levels"] is not None
|
| 2206 |
+
assert sig["horizons"]["intraday"]["direction"] == "NEUTRAL"
|
| 2207 |
+
assert sig["horizons"]["intraday"]["veto_reason"] == "FAKE_DETECTOR"
|
| 2208 |
+
|
| 2209 |
+
# 6. Neutral veto overwrite preserves orig_predictive_data for _shadow_trade_levels
|
| 2210 |
+
real_analyze = se_mod.predictive_engine.analyze
|
| 2211 |
+
real_plan_fn = se_mod._compute_trade_plan
|
| 2212 |
+
orig_calls: list[str] = []
|
| 2213 |
+
shadow_pred_seen: list[float] = []
|
| 2214 |
+
|
| 2215 |
+
def _spy_analyze(*args, **kwargs):
|
| 2216 |
+
orig_calls.append(kwargs.get("direction", "NEUTRAL"))
|
| 2217 |
+
out = real_analyze(*args, **kwargs)
|
| 2218 |
+
if kwargs.get("direction") == "LONG":
|
| 2219 |
+
out["predicted_target"] = 51500.0
|
| 2220 |
+
out["target_type"] = "Bullish Test Magnet"
|
| 2221 |
+
else:
|
| 2222 |
+
out["predicted_target"] = 49900.0
|
| 2223 |
+
out["target_type"] = "Neutral Range"
|
| 2224 |
+
return out
|
| 2225 |
+
|
| 2226 |
+
def _spy_plan(*args, **kwargs):
|
| 2227 |
+
if kwargs.get("sl_min_pct") in (0.008, 0.015) and kwargs.get("predictive_data"):
|
| 2228 |
+
shadow_pred_seen.append(kwargs["predictive_data"].get("predicted_target"))
|
| 2229 |
+
return real_plan_fn(*args, **kwargs)
|
| 2230 |
+
|
| 2231 |
+
with patch("engine.signal_engine.mtf_analyzer.analyze", return_value=mock_mtf_clean), patch(
|
| 2232 |
+
"engine.signal_engine.confluence_scorer.compute",
|
| 2233 |
+
side_effect=lambda *_a, **_kw: dict(mock_swing),
|
| 2234 |
+
), patch("engine.signal_engine.fake_detector.detect", return_value={
|
| 2235 |
+
"is_fake": True, "score": -2, "label": "Manipulation", "warnings": ["Wash trading", "Ask spoof"],
|
| 2236 |
+
"sweep_direction": "NONE", "has_non_sweep_manipulation": True,
|
| 2237 |
+
}), patch.object(se_mod.predictive_engine, "analyze", side_effect=_spy_analyze), patch(
|
| 2238 |
+
"engine.signal_engine._compute_trade_plan", side_effect=_spy_plan
|
| 2239 |
+
):
|
| 2240 |
+
sig_vetoed = engine.compute(raw, horizon_thresholds={"intraday": 3, "swing": 3, "primary": 3})
|
| 2241 |
+
|
| 2242 |
+
assert sig_vetoed["direction"] == "NEUTRAL"
|
| 2243 |
+
assert sig_vetoed["veto_reason"] == "FAKE_DETECTOR"
|
| 2244 |
+
assert orig_calls == ["LONG", "NEUTRAL"]
|
| 2245 |
+
assert shadow_pred_seen and all(p == 51500.0 for p in shadow_pred_seen)
|
| 2246 |
+
shadow_intra = sig_vetoed.get("_shadow_trade_levels", {}).get("intraday") or {}
|
| 2247 |
+
assert shadow_intra.get("take_profit_1", 0.0) > 50000.0
|
| 2248 |
+
|
| 2249 |
+
|
| 2250 |
+
def test_audit_fixes_init_db_legacy_migration_ordering(monkeypatch):
|
| 2251 |
+
"""Verify init_db executes CREATE TABLE IF NOT EXISTS signal_predictions before ALTER TABLE signal_predictions."""
|
| 2252 |
+
import database.db as db_mod
|
| 2253 |
+
|
| 2254 |
+
executed_sql: list[str] = []
|
| 2255 |
+
|
| 2256 |
+
class FakeCursor:
|
| 2257 |
+
def __init__(self):
|
| 2258 |
+
self._one = None
|
| 2259 |
+
|
| 2260 |
+
def execute(self, sql, params=None):
|
| 2261 |
+
s = str(sql)
|
| 2262 |
+
executed_sql.append(s)
|
| 2263 |
+
if "information_schema.tables" in s and ("'pairs'" in s or "'trade_journal'" in s):
|
| 2264 |
+
# Legacy DB already has pairs and trade_journal
|
| 2265 |
+
self._one = (1,)
|
| 2266 |
+
else:
|
| 2267 |
+
self._one = None
|
| 2268 |
+
|
| 2269 |
+
def fetchone(self):
|
| 2270 |
+
return self._one
|
| 2271 |
+
|
| 2272 |
+
def __enter__(self):
|
| 2273 |
+
return self
|
| 2274 |
+
|
| 2275 |
+
def __exit__(self, *args):
|
| 2276 |
+
return False
|
| 2277 |
+
|
| 2278 |
+
class FakeConn:
|
| 2279 |
+
def cursor(self):
|
| 2280 |
+
return FakeCursor()
|
| 2281 |
+
|
| 2282 |
+
def commit(self):
|
| 2283 |
+
pass
|
| 2284 |
+
|
| 2285 |
+
def rollback(self):
|
| 2286 |
+
pass
|
| 2287 |
+
|
| 2288 |
+
def __enter__(self):
|
| 2289 |
+
return self
|
| 2290 |
+
|
| 2291 |
+
def __exit__(self, *args):
|
| 2292 |
+
return False
|
| 2293 |
+
|
| 2294 |
+
monkeypatch.setattr(db_mod, "DATABASE_URL", "postgres://fake")
|
| 2295 |
+
monkeypatch.setattr(db_mod, "get_connection", lambda: FakeConn())
|
| 2296 |
+
db_mod.init_db()
|
| 2297 |
+
|
| 2298 |
+
create_sp_idx = next(i for i, s in enumerate(executed_sql) if "CREATE TABLE IF NOT EXISTS signal_predictions" in s)
|
| 2299 |
+
alter_sp_indices = [i for i, s in enumerate(executed_sql) if "ALTER TABLE signal_predictions" in s]
|
| 2300 |
+
assert alter_sp_indices, "Expected legacy ALTER statements for signal_predictions"
|
| 2301 |
+
assert create_sp_idx < min(alter_sp_indices)
|
| 2302 |
+
|
| 2303 |
+
|
| 2304 |
+
|
| 2305 |
|
| 2306 |
|
| 2307 |
|