Naufal Arhab commited on
Commit
ec3e8eb
·
1 Parent(s): 849a1f3

feat(engine): optimize long/short decision logic with MTF score cap and fake detector dampening

Browse files
backend/engine/confluence_scorer.py CHANGED
@@ -41,10 +41,16 @@ 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. Warnings are informational/label-only: zero score penalty
45
  fake_detector_data = factors.get("fake_detector", {})
46
- fake_penalty = 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,7 +61,7 @@ class ConfluenceScorer:
55
  "direction": direction,
56
  "score": clamped_score,
57
  "raw_score": raw_score,
58
- "fake_penalty": 0,
59
  "conviction": conviction,
60
  "breakdown": factors,
61
  }
 
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
  "direction": direction,
62
  "score": clamped_score,
63
  "raw_score": raw_score,
64
+ "fake_penalty": fake_penalty_score,
65
  "conviction": conviction,
66
  "breakdown": factors,
67
  }
backend/engine/fake_detector.py CHANGED
@@ -196,10 +196,13 @@ class FakeDetector:
196
  else ("Minor Warnings" if warnings else "Clean (No Manipulation Detected)")
197
  )
198
 
 
 
 
199
  return {
200
  "is_fake": is_fake,
201
  "warnings": warnings,
202
  "divergence_pct": divergence_pct,
203
- "score": 0, # Warning is informational/label-only, does not deduct pair score
204
  "label": label,
205
  }
 
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,
204
  "warnings": warnings,
205
  "divergence_pct": divergence_pct,
206
+ "score": score_penalty,
207
  "label": label,
208
  }
backend/engine/mtf_analyzer.py CHANGED
@@ -196,18 +196,16 @@ class MTFAnalyzer:
196
  if struct_5m == "bullish": score += 1
197
  elif struct_5m == "bearish": score -= 1
198
 
199
- # Clamp between -3 and +3
200
- score = max(-3, min(3, score))
201
 
202
  active_structure = structure_per_tf.get(active_tf, "ranging")
203
  label_map = {
204
- 3: "Strong MTF Bullish Alignment (1D+4H+1H)",
205
- 2: "Bullish Structure (HTF Aligned)",
206
- 1: "Mildly Bullish",
207
  0: "Ranging / Mixed Structure",
208
- -1: "Mildly Bearish",
209
- -2: "Bearish Structure (HTF Aligned)",
210
- -3: "Strong MTF Bearish Alignment (1D+4H+1H)",
211
  }
212
  label = label_map.get(score, "Ranging / Mixed Structure")
213
 
 
196
  if struct_5m == "bullish": score += 1
197
  elif struct_5m == "bearish": score -= 1
198
 
199
+ # Clamp between -2 and +2 to prevent MTF from dominating confluence
200
+ score = max(-2, min(2, score))
201
 
202
  active_structure = structure_per_tf.get(active_tf, "ranging")
203
  label_map = {
204
+ 2: "Strong MTF Bullish Structure (HTF Aligned)",
205
+ 1: "Mildly Bullish Structure",
 
206
  0: "Ranging / Mixed Structure",
207
+ -1: "Mildly Bearish Structure",
208
+ -2: "Strong MTF Bearish Structure (HTF Aligned)",
 
209
  }
210
  label = label_map.get(score, "Ranging / Mixed Structure")
211
 
backend/engine/signal_engine.py CHANGED
@@ -526,6 +526,7 @@ def _compute_trade_plan(
526
  spot_futures_score: int,
527
  conviction: int,
528
  predictive_data: dict | None = None,
 
529
  ) -> dict[str, Any]:
530
  """
531
  Actionable trade setup & instant 1-second verdict for lazy traders:
@@ -657,8 +658,12 @@ def _compute_trade_plan(
657
 
658
  else: # NEUTRAL
659
  trade_levels = None
660
- action = "DO NOT TRADE / WAIT"
661
- verdict = "Struktur pasar sideways/chop atau sinyal bursa belum konvergen. Disarankan 'Wait-and-See' menunggu momentum jelas."
 
 
 
 
662
 
663
  return {
664
  "trade_levels": trade_levels,
@@ -878,6 +883,7 @@ class SignalEngine:
878
  spot_futures_score=spot_futures_signal.get("score", 0),
879
  conviction=confluence["conviction"],
880
  predictive_data=predictive_data,
 
881
  )
882
 
883
  # Keep verdict clean without clumsy bracket tags (badges already displayed in UI)
 
526
  spot_futures_score: int,
527
  conviction: int,
528
  predictive_data: dict | None = None,
529
+ is_fake: bool = False,
530
  ) -> dict[str, Any]:
531
  """
532
  Actionable trade setup & instant 1-second verdict for lazy traders:
 
658
 
659
  else: # NEUTRAL
660
  trade_levels = None
661
+ if is_fake:
662
+ action = "WAIT / MANIPULATION ALERT"
663
+ verdict = "Terdeteksi sinyal manipulasi harga / wick sweep. Disarankan 'Wait-and-See' untuk menghindari jebakan likuiditas."
664
+ else:
665
+ action = "DO NOT TRADE / WAIT"
666
+ verdict = "Struktur pasar sideways/chop atau sinyal bursa belum konvergen. Disarankan 'Wait-and-See' menunggu momentum jelas."
667
 
668
  return {
669
  "trade_levels": trade_levels,
 
883
  spot_futures_score=spot_futures_signal.get("score", 0),
884
  conviction=confluence["conviction"],
885
  predictive_data=predictive_data,
886
+ is_fake=fake_result.get("is_fake", False),
887
  )
888
 
889
  # Keep verdict clean without clumsy bracket tags (badges already displayed in UI)
tests/test_calculations.py CHANGED
@@ -185,6 +185,54 @@ def test_full_signal_engine_compute():
185
  print(f" Signal computed successfully: Direction={result['direction']}, Conviction={result['conviction']}, Score={result['score']}")
186
  print(" PASSED!")
187
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
188
  if __name__ == "__main__":
189
  print("=" * 60)
190
  print("STARTING TEST SUITE: ENGINE CALCULATION AUDIT")
@@ -195,6 +243,8 @@ if __name__ == "__main__":
195
  test_wash_trade_forming_candle()
196
  test_orderbook_skew_bounds()
197
  test_full_signal_engine_compute()
 
 
198
  print("=" * 60)
199
  print("ALL TESTS PASSED! ALL CALCULATIONS MATHEMATICALLY VERIFIED.")
200
  print("=" * 60)
 
185
  print(f" Signal computed successfully: Direction={result['direction']}, Conviction={result['conviction']}, Score={result['score']}")
186
  print(" PASSED!")
187
 
188
+ def test_market_structure_cap():
189
+ print("[7] Testing MTF Analyzer score cap at +/-2...")
190
+ mtf = MTFAnalyzer()
191
+ # High bullish candles on all timeframes
192
+ bullish_candles = [{"open": float(i), "high": float(i + 2), "low": float(i), "close": float(i + 1.8), "volume": 100.0} for i in range(30)]
193
+ ohlcv = {
194
+ "1d": bullish_candles,
195
+ "4h": bullish_candles,
196
+ "1h": bullish_candles,
197
+ "15m": bullish_candles,
198
+ "5m": bullish_candles,
199
+ }
200
+ res = mtf.analyze(ohlcv)
201
+ assert res["score"] == 2, f"MTF score should be capped at +2, got {res['score']}"
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__":
237
  print("=" * 60)
238
  print("STARTING TEST SUITE: ENGINE CALCULATION AUDIT")
 
243
  test_wash_trade_forming_candle()
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)