abyXsmart commited on
Commit
eb7bb56
Β·
verified Β·
1 Parent(s): edde456

v8 Step 2: Stage-4 leading-fact brain (sticky model + latched grade + fuse/promote-on-trigger) behind SMART_STAGE4_ENABLED

Browse files
Files changed (2) hide show
  1. Log.md +23 -0
  2. app.py +167 -0
Log.md CHANGED
@@ -2701,3 +2701,26 @@ STEP 1 DONE β€” `structural_read()` shared module + unit tests (no wiring yet):
2701
  break then reclaim-into-FVG -> choch_with. ALL PASS. py_compile app.py OK.
2702
  NEXT: Step 2 β€” wire Stage 4 (sticky model + leading-fact latched grade + fuse-not-AND +
2703
  promote-on-trigger) behind SMART_STAGE4_ENABLED; run S4-* incl. MELANIA replay.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2701
  break then reclaim-into-FVG -> choch_with. ALL PASS. py_compile app.py OK.
2702
  NEXT: Step 2 β€” wire Stage 4 (sticky model + leading-fact latched grade + fuse-not-AND +
2703
  promote-on-trigger) behind SMART_STAGE4_ENABLED; run S4-* incl. MELANIA replay.
2704
+
2705
+ ## SESSION 24 β€” STEP 2 DONE: Stage-4 v8 wiring (behind SMART_STAGE4_ENABLED)
2706
+ Wired the v8 Stage-4 brain. Legacy v7.5 path fully intact below the flag (instant rollback).
2707
+ - ADDED SetupState latches: v8_grade, v8_model(+label/entry/sl/ok/reasons). Cleared in the
2708
+ reset block alongside the v7.5 conviction fields.
2709
+ - ADDED classify_entry_model_sticky() (before classify_entry_model): scans last
2710
+ em_reaction_window CLOSED candles by re-running the existing single-candle classifier over
2711
+ truncated slices, keeps+LATCHES the STRONGEST model (rank via _EM_RANK). Fixes R4.1
2712
+ (sharded-scan single-candle blindness). Legacy classify_entry_model untouched.
2713
+ - INSERTED v8 override in evaluate_pre_entry_conviction right after min_conf/strong_conf:
2714
+ gated by smart_engine_v8 AND smart_stage4_enabled; calls structural_read for LEADING facts
2715
+ + sticky model; builds the SAME 7 user-facing fact names from structural_read values;
2716
+ LATCHED leading-fact grade (A reachable in-zone: strong_react AND htf_location AND
2717
+ (ob_overlap OR flow_with) AND not btc_block; B = model+count>=min_conf); FUSE-not-AND +
2718
+ promote-on-trigger (A now / B+strong_react now / ambiguous-B waits streak); WS-8 gates still
2719
+ apply; plain-words verdict; early-returns so legacy block is skipped when flag on.
2720
+ - TESTS /data/workspace/tests/s4_tests.py (real async path, deps stubbed, structural_read
2721
+ patched for the controlled cases): MELANIA replay on synthetic in-zone bars => grade A WHILE
2722
+ IN ZONE (6/7) + promote on trigger (THE user complaint, fixed); S4-A A->promote same cycle;
2723
+ S4-B model+5/7 no strong_react -> waits streak then promotes; S4-block btc_block -> never
2724
+ promotes + verdict cites BTC. ALL PASS. py_compile OK. SR-1..4 still green.
2725
+ NEXT: Step 3 β€” Stage-5 structural verdict + reversible hysteresis; make Drive/Risk display-
2726
+ only; grep-prove + delete _select_verdict; behind SMART_STAGE5_ENABLED; run S5-*.
app.py CHANGED
@@ -598,6 +598,17 @@ class SetupState:
598
  # --- v7.4 STAGE-5 CHIP STABILITY: per-chip debounce so a status only flips after the
599
  # new state persists. Maps chip key -> {"ok":bool, "cand":bool, "streak":int}.
600
  g_chip_state: Dict[str, Dict] = field(default_factory=dict)
 
 
 
 
 
 
 
 
 
 
 
601
 
602
 
603
  @dataclass
@@ -2474,6 +2485,15 @@ def _reset_state(st: SetupState, reason: str = ""):
2474
  st.entry_model_label = ""
2475
  st.conviction_grade = ""
2476
  st.conviction_reasons = []
 
 
 
 
 
 
 
 
 
2477
  st.pe_left_zone = False
2478
  # WS-4: drop the persisted zone-anchored footprint so a recycled symbol never
2479
  # inherits a stale cumulative delta / OI series from a previous setup.
@@ -3933,6 +3953,49 @@ def _pre_entry_resolution(direction: str, setup: Dict, bars: List[Candle], a: fl
3933
  # (ride the start of the move), vs. models that should wait for a confirmation candle.
3934
  _EM_STRONG = {"wick_rejection", "impulse_reclaim", "failed_reclaim"}
3935
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3936
 
3937
  def classify_entry_model(st: "SetupState", bars: List[Candle], a: float,
3938
  want_up: bool, fp: Dict) -> Dict:
@@ -4225,6 +4288,110 @@ async def evaluate_pre_entry_conviction(session: aiohttp.ClientSession, st: "Set
4225
  min_conf = CFG["conviction_min_confluence"]
4226
  strong_conf = CFG["conviction_strong_confluence"]
4227
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4228
  # === WS-7 β€” ENTRY-MODEL RECOGNITION (the human read) =================================
4229
  if CFG.get("entry_model_enabled", True):
4230
  em = classify_entry_model(st, bars, a, want_up, fp)
 
598
  # --- v7.4 STAGE-5 CHIP STABILITY: per-chip debounce so a status only flips after the
599
  # new state persists. Maps chip key -> {"ok":bool, "cand":bool, "streak":int}.
600
  g_chip_state: Dict[str, Dict] = field(default_factory=dict)
601
+ # --- v8 SMART ENGINE Stage-4 latches (only used when smart_stage4_enabled). The grade
602
+ # and sticky model are LATCHED for the life of the setup so a trigger that fired 1-2
603
+ # candles ago still counts (R4.1) and the grade cannot silently drift C->A after the
604
+ # move is over (R4.3). All cleared on any setup reset alongside the v7.5 fields.
605
+ v8_grade: str = "" # best leading-fact grade seen while in zone (A>B>C)
606
+ v8_model: str = "" # strongest entry model latched in-zone
607
+ v8_model_label: str = ""
608
+ v8_model_entry: Optional[float] = None
609
+ v8_model_sl: Optional[float] = None
610
+ v8_model_ok: bool = False
611
+ v8_model_reasons: List[str] = field(default_factory=list)
612
 
613
 
614
  @dataclass
 
2485
  st.entry_model_label = ""
2486
  st.conviction_grade = ""
2487
  st.conviction_reasons = []
2488
+ # v8 Stage-4 latches β€” cleared so a recycled symbol never inherits a stale latched
2489
+ # grade or sticky entry model from a previous setup.
2490
+ st.v8_grade = ""
2491
+ st.v8_model = ""
2492
+ st.v8_model_label = ""
2493
+ st.v8_model_entry = None
2494
+ st.v8_model_sl = None
2495
+ st.v8_model_ok = False
2496
+ st.v8_model_reasons = []
2497
  st.pe_left_zone = False
2498
  # WS-4: drop the persisted zone-anchored footprint so a recycled symbol never
2499
  # inherits a stale cumulative delta / OI series from a previous setup.
 
3953
  # (ride the start of the move), vs. models that should wait for a confirmation candle.
3954
  _EM_STRONG = {"wick_rejection", "impulse_reclaim", "failed_reclaim"}
3955
 
3956
+ # v8: relative strength of each model so the window scan can keep the STRONGEST trigger
3957
+ # found, not just whatever happened on the very last closed candle.
3958
+ _EM_RANK = {"none": 0, "fvg_tap": 1, "consolidation_break": 1,
3959
+ "failed_reclaim": 2, "impulse_reclaim": 2, "wick_rejection": 2}
3960
+
3961
+
3962
+ def classify_entry_model_sticky(st: "SetupState", bars: List[Candle], a: float,
3963
+ want_up: bool, fp: Dict) -> Dict:
3964
+ """v8 sticky model recognition (fixes R4.1 β€” single-candle blindness).
3965
+
3966
+ Scans the last `em_reaction_window` CLOSED candles by re-running the existing
3967
+ single-candle classifier over truncated bar slices (so each recent candle gets a turn
3968
+ as the trigger), keeps the STRONGEST model found while price interacted with the zone,
3969
+ and LATCHES it on the state. A textbook reaction that printed 2 candles ago therefore
3970
+ still reads as a model instead of decaying to 'No Clear Model'. The legacy
3971
+ classify_entry_model is left untouched so SMART_STAGE4 off = exact v7.5 behaviour."""
3972
+ W = max(1, int(CFG.get("em_reaction_window", 3)))
3973
+ best = {"model": "none", "label": "No Clear Model", "entry": None, "sl": None,
3974
+ "ok": False, "reasons": []}
3975
+ best_rank = 0
3976
+ for off in range(0, W):
3977
+ sub = bars if off == 0 else bars[:len(bars) - off]
3978
+ if len(sub) < 6:
3979
+ continue
3980
+ em = classify_entry_model(st, sub, a, want_up, fp)
3981
+ r = _EM_RANK.get(em.get("model"), 0)
3982
+ if r > best_rank:
3983
+ best, best_rank = em, r
3984
+ prev_rank = _EM_RANK.get(st.v8_model, 0)
3985
+ if best_rank > 0 and best_rank >= prev_rank:
3986
+ st.v8_model = best.get("model", "")
3987
+ st.v8_model_label = best.get("label", "")
3988
+ st.v8_model_entry = best.get("entry")
3989
+ st.v8_model_sl = best.get("sl")
3990
+ st.v8_model_ok = bool(best.get("ok"))
3991
+ st.v8_model_reasons = list(best.get("reasons") or [])
3992
+ return best
3993
+ if prev_rank > 0: # return the latched model from an earlier cycle
3994
+ return {"model": st.v8_model, "label": st.v8_model_label,
3995
+ "entry": st.v8_model_entry, "sl": st.v8_model_sl,
3996
+ "ok": st.v8_model_ok, "reasons": list(st.v8_model_reasons or [])}
3997
+ return best
3998
+
3999
 
4000
  def classify_entry_model(st: "SetupState", bars: List[Candle], a: float,
4001
  want_up: bool, fp: Dict) -> Dict:
 
4288
  min_conf = CFG["conviction_min_confluence"]
4289
  strong_conf = CFG["conviction_strong_confluence"]
4290
 
4291
+ # ======================================================================================
4292
+ # === v8 SMART STAGE 4 β€” "Is The Thesis Forming?" (leading facts, decide in-zone) =======
4293
+ # Replaces the lagging AND-chain with EVIDENCE FUSION on LEADING structure read by
4294
+ # structural_read, a STICKY in-zone model, and a LATCHED grade so A is reachable WHILE
4295
+ # price is still in the FVG (fixes R4.1-R4.4). BTC-impulse is the only hard veto. When the
4296
+ # flag is off, this block is skipped and the exact v7.5 path below runs (instant rollback).
4297
+ if CFG.get("smart_engine_v8", True) and CFG.get("smart_stage4_enabled", True):
4298
+ sr = structural_read(st, bars, a, want_up, fp)
4299
+ sem = classify_entry_model_sticky(st, bars, a, want_up, fp)
4300
+ st.entry_model = sem.get("model", "")
4301
+ st.entry_model_label = sem.get("label", "")
4302
+ if st.setup is not None and sem.get("entry") is not None:
4303
+ st.setup["model_entry"] = sem.get("entry")
4304
+ st.setup["model_sl"] = sem.get("sl")
4305
+ st.setup["entry_model"] = sem.get("model")
4306
+ st.setup["entry_model_label"] = sem.get("label")
4307
+ model_present = sem.get("model") not in ("", "none")
4308
+ btc_block = bool(sr["btc_block"] or btc_hard)
4309
+ strong_react = bool(sr["sweep_reclaim"] or sr["displacement"]) # the leading "A" tell
4310
+
4311
+ # 7 user-facing fact NAMES unchanged (UI + history compatible) β€” now sourced from
4312
+ # structural_read LEADING values instead of the lagging legacy reads.
4313
+ facts = [
4314
+ ("HTF Location", sr["htf_location"]),
4315
+ ("Swept + Reclaimed", sr["sweep_reclaim"]),
4316
+ ("OB + FVG Overlap", sr["ob_overlap"]),
4317
+ ("Displacement Origin", sr["displacement"]),
4318
+ ("Footprint With Us", sr["flow_with"]),
4319
+ ("BTC Permission", not btc_block),
4320
+ ("Clear Path To TP", sr["clear_path"]),
4321
+ ]
4322
+ members = [name for name, ok in facts if ok]
4323
+ count = len(members)
4324
+ st.confluence_count = count
4325
+ st.confluence_members = members
4326
+
4327
+ # Leading-fact grade. A is reachable IN-ZONE before the move; grade is LATCHED at its
4328
+ # best so it can rise as evidence builds but never silently drifts back down (R4.3).
4329
+ if strong_react and sr["htf_location"] and (sr["ob_overlap"] or sr["flow_with"]) and not btc_block:
4330
+ grade_now = "A"
4331
+ elif model_present and count >= min_conf and not btc_block:
4332
+ grade_now = "B"
4333
+ else:
4334
+ grade_now = "C"
4335
+ _rank = {"C": 0, "B": 1, "A": 2}
4336
+ if _rank.get(grade_now, 0) >= _rank.get(st.v8_grade or "C", 0):
4337
+ st.v8_grade = grade_now
4338
+ grade = st.v8_grade or grade_now
4339
+ st.conviction_grade = grade
4340
+ st.conviction_reasons = list(sem.get("reasons") or [])[:3]
4341
+
4342
+ # Streak is reserved for the genuinely ambiguous middle (B without a decisive trigger).
4343
+ if not btc_block and model_present and count >= min_conf:
4344
+ st.conviction_streak += 1
4345
+ else:
4346
+ st.conviction_streak = 0
4347
+
4348
+ # FUSE, don't AND (R4.2) + promote ON THE TRIGGER while still in the zone (R4.4).
4349
+ hard_block = btc_block
4350
+ promote = (not hard_block) and (
4351
+ grade == "A"
4352
+ or (grade == "B" and strong_react)
4353
+ or (grade == "B" and count >= min_conf and st.conviction_streak >= CFG["conviction_confirm_cycles"])
4354
+ )
4355
+ passed = promote
4356
+
4357
+ # WS-8 pre-trade survival gates still apply to anything that cleared fusion.
4358
+ ws8_reason = ""
4359
+ if passed:
4360
+ ok8, ws8_reason = _ws8_gate(st, su, bars, direction, btc_trend)
4361
+ if not ok8:
4362
+ passed = False
4363
+
4364
+ # Plain-words verdict (Title Case). Final Β§6 dictionary swap lands in build step 4.
4365
+ if hard_block:
4366
+ verdict, vclass = "Blocked β€” BTC Against Us", "warn"
4367
+ elif dead:
4368
+ verdict, vclass = "Skip β€” Market Dead Here", "reject"
4369
+ elif passed and grade == "A":
4370
+ verdict, vclass = "Strong Setup β€” Entering Now", "strong"
4371
+ elif passed:
4372
+ verdict, vclass = "Good Setup β€” Entering Now", "strong"
4373
+ elif ws8_reason:
4374
+ verdict, vclass = "Holding Back β€” " + ws8_reason, "warn"
4375
+ elif grade == "B":
4376
+ verdict, vclass = "Thesis Forming β€” Watching The Zone", "good"
4377
+ else:
4378
+ verdict, vclass = "Studying The Zone", "good"
4379
+
4380
+ st.conviction = conv
4381
+ st.conviction_raw = int(raw)
4382
+ st.conviction_verdict = verdict
4383
+ st.conviction_class = vclass
4384
+ reason = "Promoted" if passed else (
4385
+ ws8_reason if ws8_reason else
4386
+ ("BTC impulsing against" if hard_block else
4387
+ f"Smart grade {grade}, {count}/{len(facts)} leading facts (need {min_conf})"))
4388
+ return {"items": items, "conviction": conv, "raw": int(raw), "passed": passed,
4389
+ "verdict": verdict, "vclass": vclass, "reason": reason, "gate_ok": not hard_block,
4390
+ "confluence": count, "confluence_members": members, "grade": grade,
4391
+ "entry_model": st.entry_model, "entry_model_label": st.entry_model_label,
4392
+ "reasons": st.conviction_reasons}
4393
+ # === end v8 Stage-4 override; the exact v7.5 path runs below when the flag is off ======
4394
+
4395
  # === WS-7 β€” ENTRY-MODEL RECOGNITION (the human read) =================================
4396
  if CFG.get("entry_model_enabled", True):
4397
  em = classify_entry_model(st, bars, a, want_up, fp)