Naufal Arhab commited on
Commit
c224e9c
·
1 Parent(s): 0cd5796

fix: enforce warning label-only rule, exclude forming candle in wick sweep, resilient orderbook skew, and negative discovery caching

Browse files
backend/engine/confluence_scorer.py CHANGED
@@ -41,16 +41,10 @@ class ConfluenceScorer:
41
  directional_factors = {k: v for k, v in factors.items() if k != "fake_detector"}
42
  raw_score = sum(f.get("score", 0) for f in directional_factors.values())
43
 
44
- # 2. Manipulation penalty: dampens conviction towards 0 to prevent false breakout traps
45
  fake_detector_data = factors.get("fake_detector", {})
46
- fake_penalty_score = abs(fake_detector_data.get("score", 0))
47
-
48
- if raw_score > 0:
49
- final_score = max(0, raw_score - fake_penalty_score)
50
- elif raw_score < 0:
51
- final_score = min(0, raw_score + fake_penalty_score)
52
- else:
53
- final_score = 0
54
 
55
  # Clamp final score between -MAX_CONVICTION and +MAX_CONVICTION
56
  clamped_score = max(-config.MAX_CONVICTION, min(config.MAX_CONVICTION, final_score))
@@ -61,7 +55,7 @@ class ConfluenceScorer:
61
  "direction": direction,
62
  "score": clamped_score,
63
  "raw_score": raw_score,
64
- "fake_penalty": fake_penalty_score,
65
  "conviction": conviction,
66
  "breakdown": factors,
67
  }
 
41
  directional_factors = {k: v for k, v in factors.items() if k != "fake_detector"}
42
  raw_score = sum(f.get("score", 0) for f in directional_factors.values())
43
 
44
+ # 2. Warning is purely an informative label (no score reduction per user specification)
45
  fake_detector_data = factors.get("fake_detector", {})
46
+ fake_penalty_score = 0
47
+ final_score = raw_score
 
 
 
 
 
 
48
 
49
  # Clamp final score between -MAX_CONVICTION and +MAX_CONVICTION
50
  clamped_score = max(-config.MAX_CONVICTION, min(config.MAX_CONVICTION, final_score))
 
55
  "direction": direction,
56
  "score": clamped_score,
57
  "raw_score": raw_score,
58
+ "fake_penalty": 0,
59
  "conviction": conviction,
60
  "breakdown": factors,
61
  }
backend/engine/fake_detector.py CHANGED
@@ -23,14 +23,15 @@ ORDERBOOK_WALL_IMBALANCE_THRESHOLD = 0.70 # >70% book imbalance = wall spoofing
23
 
24
  def _wick_sweep_detected(candles: list[dict]) -> tuple[bool, str]:
25
  """
26
- Detect genuine wick sweep / liquidity grab in the last 3 candles.
27
- Filters out micro-dojis by requiring meaningful high-low range (>=0.1%)
28
- and wick dominance (>60% of total range).
29
  """
30
  if len(candles) < 3:
31
  return False, ""
32
 
33
- recent = candles[-3:]
 
34
  for c in recent:
35
  close = c.get("close", 0)
36
  if close <= 0:
@@ -196,8 +197,8 @@ class FakeDetector:
196
  else ("Minor Warnings" if warnings else "Clean (No Manipulation Detected)")
197
  )
198
 
199
- # Penalty score: -2 if is_fake (>=2 warnings), -1 if 1 warning, 0 if clean
200
- score_penalty = -2 if is_fake else (-1 if warnings else 0)
201
 
202
  return {
203
  "is_fake": is_fake,
 
23
 
24
  def _wick_sweep_detected(candles: list[dict]) -> tuple[bool, str]:
25
  """
26
+ Detect genuine wick sweep / liquidity grab in the last completed candles.
27
+ Excludes the forming/incomplete candle (candles[-1]) and requires meaningful
28
+ high-low range (>=0.1%) and wick dominance (>60% of total range).
29
  """
30
  if len(candles) < 3:
31
  return False, ""
32
 
33
+ # Evaluate completed candles only to confirm real wick sweep and close-back
34
+ recent = candles[-4:-1] if len(candles) >= 4 else candles[:-1]
35
  for c in recent:
36
  close = c.get("close", 0)
37
  if close <= 0:
 
197
  else ("Minor Warnings" if warnings else "Clean (No Manipulation Detected)")
198
  )
199
 
200
+ # Warning is informational label only; does not penalize conviction score
201
+ score_penalty = 0
202
 
203
  return {
204
  "is_fake": is_fake,
backend/engine/predictive_engine.py CHANGED
@@ -135,19 +135,26 @@ def _compute_orderbook_skew(orderbook: dict | None, mark_price: float) -> dict[s
135
  bids = orderbook.get("bids", [])
136
  asks = orderbook.get("asks", [])
137
 
138
- # Filter depth within ±1.5% of mark price with safe float casting & fair bounds
139
- try:
140
- bid_vol_usd = sum(
141
- float(p) * float(q) for p, q in bids
142
- if mark_price * 0.985 <= float(p) <= mark_price * 1.005
143
- )
144
- ask_vol_usd = sum(
145
- float(p) * float(q) for p, q in asks
146
- if mark_price * 0.995 <= float(p) <= mark_price * 1.015
147
- )
148
- except (ValueError, TypeError, IndexError):
149
- bid_vol_usd = 0.0
150
- ask_vol_usd = 0.0
 
 
 
 
 
 
 
151
 
152
  total = bid_vol_usd + ask_vol_usd
153
  if total <= 0:
 
135
  bids = orderbook.get("bids", [])
136
  asks = orderbook.get("asks", [])
137
 
138
+ # Filter depth within ±1.5% of mark price with per-item resilience
139
+ bid_vol_usd = 0.0
140
+ for item in bids:
141
+ try:
142
+ p = float(item[0])
143
+ q = float(item[1])
144
+ if mark_price * 0.985 <= p <= mark_price * 1.005:
145
+ bid_vol_usd += p * q
146
+ except (ValueError, TypeError, IndexError):
147
+ continue
148
+
149
+ ask_vol_usd = 0.0
150
+ for item in asks:
151
+ try:
152
+ p = float(item[0])
153
+ q = float(item[1])
154
+ if mark_price * 0.995 <= p <= mark_price * 1.015:
155
+ ask_vol_usd += p * q
156
+ except (ValueError, TypeError, IndexError):
157
+ continue
158
 
159
  total = bid_vol_usd + ask_vol_usd
160
  if total <= 0:
backend/exchanges/binance.py CHANGED
@@ -46,6 +46,7 @@ class BinanceClient(BaseExchange):
46
  self._client = httpx.AsyncClient(**client_kwargs)
47
  self._known_symbols: set[str] = set()
48
  self._last_symbols_load_time: float = 0.0
 
49
 
50
  # ------------------------------------------------------------------
51
  # Internal helpers
@@ -101,8 +102,19 @@ class BinanceClient(BaseExchange):
101
  if self.resolve_symbol(symbol):
102
  return True
103
 
104
- # 2. Direct lightweight probe fallback (50ms via premiumIndex)
105
- # Prevents false negatives if full exchangeInfo (1.8MB) hasn't loaded yet or timed out
 
 
 
 
 
 
 
 
 
 
 
106
  for var in get_symbol_variations(symbol):
107
  if not (var.endswith("USDT") or var.endswith("USDC")):
108
  continue
@@ -114,18 +126,13 @@ class BinanceClient(BaseExchange):
114
  except Exception:
115
  pass
116
 
117
- # 3. If known symbols empty, trigger load
118
- if not self._known_symbols:
119
- await self._load_symbols()
120
- if self.resolve_symbol(symbol):
121
- return True
122
-
123
  # 4. If cache is stale (>10 min), try reloading once
124
- import time
125
- if time.time() - self._last_symbols_load_time > 600:
126
  await self._load_symbols(force=True)
127
- return self.resolve_symbol(symbol) is not None
 
128
 
 
129
  return False
130
 
131
  async def get_mark_price(self, symbol: str) -> dict[str, Any]:
 
46
  self._client = httpx.AsyncClient(**client_kwargs)
47
  self._known_symbols: set[str] = set()
48
  self._last_symbols_load_time: float = 0.0
49
+ self._negative_cache: dict[str, float] = {}
50
 
51
  # ------------------------------------------------------------------
52
  # Internal helpers
 
102
  if self.resolve_symbol(symbol):
103
  return True
104
 
105
+ # Check negative cache to avoid spamming failed probes on every 60s loop
106
+ import time
107
+ now = time.time()
108
+ if symbol in self._negative_cache and (now - self._negative_cache[symbol] < 900):
109
+ return False
110
+
111
+ # 2. If known symbols empty, trigger bulk load first
112
+ if not self._known_symbols:
113
+ await self._load_symbols()
114
+ if self.resolve_symbol(symbol):
115
+ return True
116
+
117
+ # 3. Direct lightweight probe fallback (only if not found in known symbols)
118
  for var in get_symbol_variations(symbol):
119
  if not (var.endswith("USDT") or var.endswith("USDC")):
120
  continue
 
126
  except Exception:
127
  pass
128
 
 
 
 
 
 
 
129
  # 4. If cache is stale (>10 min), try reloading once
130
+ if now - self._last_symbols_load_time > 600:
 
131
  await self._load_symbols(force=True)
132
+ if self.resolve_symbol(symbol):
133
+ return True
134
 
135
+ self._negative_cache[symbol] = now
136
  return False
137
 
138
  async def get_mark_price(self, symbol: str) -> dict[str, Any]:
backend/exchanges/bybit.py CHANGED
@@ -42,6 +42,7 @@ class BybitClient(BaseExchange):
42
  self._client = httpx.AsyncClient(**client_kwargs)
43
  self._known_symbols: set[str] = set()
44
  self._last_symbols_load_time: float = 0.0
 
45
 
46
  # ------------------------------------------------------------------
47
  # Internal helpers
@@ -99,7 +100,19 @@ class BybitClient(BaseExchange):
99
  if self.resolve_symbol(symbol):
100
  return True
101
 
102
- # 2. Direct lightweight probe fallback (50ms via tickers)
 
 
 
 
 
 
 
 
 
 
 
 
103
  for var in get_symbol_variations(symbol):
104
  if not (var.endswith("USDT") or var.endswith("USDC")):
105
  continue
@@ -117,18 +130,13 @@ class BybitClient(BaseExchange):
117
  except Exception:
118
  pass
119
 
120
- # 3. If known symbols empty, trigger load
121
- if not self._known_symbols:
122
- await self._load_symbols()
123
- if self.resolve_symbol(symbol):
124
- return True
125
-
126
  # 4. If cache is stale (>10 min), try reloading once
127
- import time
128
- if time.time() - self._last_symbols_load_time > 600:
129
  await self._load_symbols(force=True)
130
- return self.resolve_symbol(symbol) is not None
 
131
 
 
132
  return False
133
 
134
  async def get_mark_price(self, symbol: str) -> dict[str, Any]:
 
42
  self._client = httpx.AsyncClient(**client_kwargs)
43
  self._known_symbols: set[str] = set()
44
  self._last_symbols_load_time: float = 0.0
45
+ self._negative_cache: dict[str, float] = {}
46
 
47
  # ------------------------------------------------------------------
48
  # Internal helpers
 
100
  if self.resolve_symbol(symbol):
101
  return True
102
 
103
+ # Check negative cache to avoid spamming failed probes on every 60s loop
104
+ import time
105
+ now = time.time()
106
+ if symbol in self._negative_cache and (now - self._negative_cache[symbol] < 900):
107
+ return False
108
+
109
+ # 2. If known symbols empty, trigger bulk load first
110
+ if not self._known_symbols:
111
+ await self._load_symbols()
112
+ if self.resolve_symbol(symbol):
113
+ return True
114
+
115
+ # 3. Direct lightweight probe fallback (50ms via tickers)
116
  for var in get_symbol_variations(symbol):
117
  if not (var.endswith("USDT") or var.endswith("USDC")):
118
  continue
 
130
  except Exception:
131
  pass
132
 
 
 
 
 
 
 
133
  # 4. If cache is stale (>10 min), try reloading once
134
+ if now - self._last_symbols_load_time > 600:
 
135
  await self._load_symbols(force=True)
136
+ if self.resolve_symbol(symbol):
137
+ return True
138
 
139
+ self._negative_cache[symbol] = now
140
  return False
141
 
142
  async def get_mark_price(self, symbol: str) -> dict[str, Any]:
backend/exchanges/okx.py CHANGED
@@ -54,6 +54,7 @@ class OKXClient(BaseExchange):
54
  self._client = httpx.AsyncClient(**client_kwargs)
55
  self._known_symbols: set[str] = set()
56
  self._inst_map: dict[str, str] = {}
 
57
 
58
  def resolve_inst_id(self, symbol: str) -> str | None:
59
  """Resolve any user or cross-exchange ticker to OKX's exact instId."""
@@ -110,14 +111,22 @@ class OKXClient(BaseExchange):
110
  logger.warning("[OKX] Symbol discovery failed: %s", exc)
111
 
112
  async def check_symbol_exists(self, symbol: str) -> bool:
113
- # 1. Ensure known symbols are loaded first via single bulk call
114
- if not self._known_symbols:
115
- await self._load_symbols()
116
-
117
- # 2. Fast in-memory check
118
  if self.resolve_inst_id(symbol):
119
  return True
120
 
 
 
 
 
 
 
 
 
 
 
 
 
121
  # 3. Direct lightweight probe fallback (only target most probable instrument IDs)
122
  clean = symbol.upper().replace("/", "").replace("-", "")
123
  base = clean[:-4] if clean.endswith("USDT") or clean.endswith("USDC") else clean
@@ -138,6 +147,7 @@ class OKXClient(BaseExchange):
138
  except Exception:
139
  pass
140
 
 
141
  return False
142
 
143
  async def get_mark_price(self, symbol: str) -> dict[str, Any]:
 
54
  self._client = httpx.AsyncClient(**client_kwargs)
55
  self._known_symbols: set[str] = set()
56
  self._inst_map: dict[str, str] = {}
57
+ self._negative_cache: dict[str, float] = {}
58
 
59
  def resolve_inst_id(self, symbol: str) -> str | None:
60
  """Resolve any user or cross-exchange ticker to OKX's exact instId."""
 
111
  logger.warning("[OKX] Symbol discovery failed: %s", exc)
112
 
113
  async def check_symbol_exists(self, symbol: str) -> bool:
114
+ # 1. Fast in-memory check
 
 
 
 
115
  if self.resolve_inst_id(symbol):
116
  return True
117
 
118
+ # Check negative cache to avoid spamming failed probes on every 60s loop
119
+ import time
120
+ now = time.time()
121
+ if symbol in self._negative_cache and (now - self._negative_cache[symbol] < 900):
122
+ return False
123
+
124
+ # 2. Ensure known symbols are loaded via single bulk call
125
+ if not self._known_symbols:
126
+ await self._load_symbols()
127
+ if self.resolve_inst_id(symbol):
128
+ return True
129
+
130
  # 3. Direct lightweight probe fallback (only target most probable instrument IDs)
131
  clean = symbol.upper().replace("/", "").replace("-", "")
132
  base = clean[:-4] if clean.endswith("USDT") or clean.endswith("USDC") else clean
 
147
  except Exception:
148
  pass
149
 
150
+ self._negative_cache[symbol] = now
151
  return False
152
 
153
  async def get_mark_price(self, symbol: str) -> dict[str, Any]:
tests/test_calculations.py CHANGED
@@ -202,35 +202,35 @@ def test_market_structure_cap():
202
  assert "Strong MTF Bullish Structure" in res["label"], f"Unexpected label: {res['label']}"
203
  print(" PASSED!")
204
 
205
- def test_fake_detector_penalty_dampens_confluence():
206
- print("[8] Testing FakeDetector penalty & ConfluenceScorer dampening...")
207
  from engine.confluence_scorer import ConfluenceScorer
208
  cs = ConfluenceScorer()
209
 
210
- # Case A: Raw score +4 (marginal LONG), but fake detector detected manipulation (-2)
211
  factors_manipulated = {
212
  "funding_rate": {"score": 1},
213
  "spot_futures_cvd": {"score": 1},
214
  "market_structure": {"score": 2},
215
- "fake_detector": {"score": -2, "is_fake": True, "warnings": ["Wick sweep", "Wash trading"]},
216
  }
217
  out = cs.compute(factors_manipulated)
218
  assert out["raw_score"] == 4, f"Expected raw_score 4, got {out['raw_score']}"
219
- assert out["fake_penalty"] == 2, f"Expected fake_penalty 2, got {out['fake_penalty']}"
220
- assert out["score"] == 2, f"Expected score dampened to 2, got {out['score']}"
221
- assert out["direction"] == "NEUTRAL", f"Expected direction NEUTRAL (trap avoided), got {out['direction']}"
222
 
223
- # Case B: Raw score -4 (marginal SHORT), but fake detector penalty (-2)
224
  factors_short_manipulated = {
225
  "funding_rate": {"score": -1},
226
  "spot_futures_cvd": {"score": -1},
227
  "market_structure": {"score": -2},
228
- "fake_detector": {"score": -2, "is_fake": True, "warnings": ["Wick sweep", "Wash trading"]},
229
  }
230
  out_short = cs.compute(factors_short_manipulated)
231
  assert out_short["raw_score"] == -4
232
- assert out_short["score"] == -2
233
- assert out_short["direction"] == "NEUTRAL"
234
  print(" PASSED!")
235
 
236
  if __name__ == "__main__":
@@ -244,7 +244,7 @@ if __name__ == "__main__":
244
  test_orderbook_skew_bounds()
245
  test_full_signal_engine_compute()
246
  test_market_structure_cap()
247
- test_fake_detector_penalty_dampens_confluence()
248
  print("=" * 60)
249
  print("ALL TESTS PASSED! ALL CALCULATIONS MATHEMATICALLY VERIFIED.")
250
  print("=" * 60)
 
202
  assert "Strong MTF Bullish Structure" in res["label"], f"Unexpected label: {res['label']}"
203
  print(" PASSED!")
204
 
205
+ def test_warnings_do_not_deduct_score():
206
+ print("[8] Testing that warnings do NOT deduct score (label only per user rule)...")
207
  from engine.confluence_scorer import ConfluenceScorer
208
  cs = ConfluenceScorer()
209
 
210
+ # Raw score +4 with warnings should remain +4 (LONG) without score deduction
211
  factors_manipulated = {
212
  "funding_rate": {"score": 1},
213
  "spot_futures_cvd": {"score": 1},
214
  "market_structure": {"score": 2},
215
+ "fake_detector": {"score": 0, "is_fake": True, "warnings": ["Wick sweep", "Wash trading"]},
216
  }
217
  out = cs.compute(factors_manipulated)
218
  assert out["raw_score"] == 4, f"Expected raw_score 4, got {out['raw_score']}"
219
+ assert out["fake_penalty"] == 0, f"Expected fake_penalty 0, got {out['fake_penalty']}"
220
+ assert out["score"] == 4, f"Expected score to remain 4 (not deducted), got {out['score']}"
221
+ assert out["direction"] == "LONG", f"Expected direction LONG, got {out['direction']}"
222
 
223
+ # Raw score -4 with warnings should remain -4 (SHORT) without score deduction
224
  factors_short_manipulated = {
225
  "funding_rate": {"score": -1},
226
  "spot_futures_cvd": {"score": -1},
227
  "market_structure": {"score": -2},
228
+ "fake_detector": {"score": 0, "is_fake": True, "warnings": ["Wick sweep", "Wash trading"]},
229
  }
230
  out_short = cs.compute(factors_short_manipulated)
231
  assert out_short["raw_score"] == -4
232
+ assert out_short["score"] == -4
233
+ assert out_short["direction"] == "SHORT"
234
  print(" PASSED!")
235
 
236
  if __name__ == "__main__":
 
244
  test_orderbook_skew_bounds()
245
  test_full_signal_engine_compute()
246
  test_market_structure_cap()
247
+ test_warnings_do_not_deduct_score()
248
  print("=" * 60)
249
  print("ALL TESTS PASSED! ALL CALCULATIONS MATHEMATICALLY VERIFIED.")
250
  print("=" * 60)