//@version=5 // ============================================================================= // LEAN J3P v1.0 — the quiet chart. LOGIC = J3P v2.6.9, UNTOUCHED. // ----------------------------------------------------------------------------- // Built 2026-07-30 per the Lean spec. Every entry gate, state machine, ladder, // tracker and alert payload is byte-for-byte v2.6.9 behavior. What changed is // ONLY what the chart shows and when: // 1. ARMING DOTS: one dot per setup CYCLE (first arm only — re-arms refresh the // latch silently). Dot carries a hover tooltip: play + what confirmation is // still missing. Dot is DELETED if the setup expires or invalidates. NEW: // quiet dots for the Pull-In dip and VWAP-Fail squeeze arms too. // 2. NO CHASE: once per warning cycle (arm-window cooldown), tooltip carries // the reason. Never creates an entry (unchanged). // 3. REGIME: compact badge (POWER TREND / TREND UP / BACKSIDE / NEUTRAL), // Lean view only. Background tint now defaults OFF (toggle kept). The // regime CALC always runs — alerts and NO CHASE still use it when hidden. // 4. W/L RESULT TAGS: hidden in Lean view. The outcome tracker still runs // (one-position latch + webhook events depend on it); labels + outcome // table appear in DEBUG view only. // 5. INVALIDATION: one tiny × marker when an armed setup dies — tooltip says // SETUP EXPIRED (window ran out) vs SETUP INVALIDATED (level taken out). // TREND BREAK now has a cooldown (min bars between breaks) so chop can't // machine-gun the marker (the NVDA 2026-07-29 defect). // View mode: LEAN (default, the 7-item hierarchy) | DEBUG (everything: // tables, W/L tags, pb-held dots, gate diagnostics). // BUGFIX vs the v2.6.9 file as saved: f_px() was called in the exit labels // but never defined — did not compile. Defined here (mintick-formatted px). // ============================================================================= // JAMES THREE PLAYS v2.6.9 (logic base) // Four entry plays + trend-as-environment. Intraday, session-anchored VWAP. // Play 1 vwap_pull_in LONG shakeout below VWAP -> reclaim // Play 1S vwap_pull_in_short SHORT squeeze above VWAP -> loses VWAP (provisional slug) // Play 3 backside_scalp SHORT extended leg -> rejection arms -> MA curl fires // Play 3B backside_long LONG 2-leg flush <= -2s -> capitulation hold -> MA curl // Play 2 trend_trade ENVIRONMENT ONLY (enable_trend = false): regime tint, // "held" dots, one TREND BREAK marker. Not an entry. // Guards: RTH-only signals | one-position latch | grade gate | R:R floor | warmup. // Pine is the VISUAL / ALERT layer. Ladders + ratchets are ANNOTATIONS - KITE executes. // Alerts: alert() with JSON payloads. In TradingView create ONE alert on this // indicator, condition "Any alert() function call", webhook -> AMS ingest. // evt values: entry | arm | no_chase | trend_break | pb_held // v2.6.3: FAST-MA DIRECTION GATE (by request) -- new group "Fast-MA Direction Gate", // ON by default. LONG plays only fire while the fast MA (5) is rising; SHORT // plays only while it is falling ("entries only in the direction of the fast // MA"). Modes: Slope (MA5 vs 2 bars ago -- same test the backside curl uses), // Price side (close above/below MA5), or Both. Redundant for Backside/Rubber // Band (their curl trigger already enforces it); the real effect is on the // Pull-In long and VWAP Fail short, which could previously fire counter to // the 5. Tradeoff: on a fast V-reclaim the reclaim bar can print 1-2 bars // before the 5 turns -- gate makes you slightly later or skips that one. // Switch to "Price side" for the looser version. No other logic touched. // v2.6.4: MASTER TABLE SWITCH (by request) -- "Show tables (master)" in Visuals. // One click hides ALL tables at once (live state + outcome + TF notice). // The per-table toggles still work when the master is ON. Visual only. // v2.6.5: SLOPE LOOKBACK for the fast-MA gate (real TSLA 2m feedback: a RUBBER BAND // long fired into a falling tape). Root cause: the v2.6.3 Slope test was // MA5 now vs 2 bars ago -- the same micro-curl the RB trigger already uses, // so a one-bar capitulation bounce read as "rising" while the DRAWN 5-MA // slope was clearly down. New input "Slope lookback (bars)", default 6 // (12 min on 2m): the 5-MA must be above where it was N bars ago -- the // slope your eye sees, not a 2-bar twitch. Tradeoff: fades (Rubber Band / // Backside) live in falling tapes, so they fire later (second leg) or skip // the fastest snaps. Set back to 2 for the old curl behavior. // v2.6.6: HEAD-OF-SLOPE mode (James: "by the time the entire slope catches up, the // trade could be over"). New "Slope test" style, default HEAD: the 5-MA must // make N CONSECUTIVE steps in the trade's direction (default 2). One bounce // bar = one up-step with a down-step behind it -> still blocked (yesterday's // TSLA rubber-band fake); two bars in a row -> gate opens, ~1 bar later than // the old curl instead of waiting for the whole 6-bar window to flip. // "Window" style keeps the v2.6.5 body test (now vs lookback) if wanted. // v2.6.7: REVERSE-PLAY EXIT (James: "if we got a trigger for a reverse play, // shouldn't the existing trade be closed?"). The one-position latch still // suppresses opposite ENTRIES (markers/alerts) while a trade is open -- but // the plays now keep evaluating silently, and if one fires AGAINST the open // trade, the trade closes on that bar's close (W/L label tagged ·OPP, evt // "opp_exit" in the webhook). A valid opposite trigger = the market said the // trade is over. After the flat bar the reverse play can fire organically on // its next valid bar (backside/rubber-band arm latches persist ~20 bars; the // one-shot reclaim/fail triggers may not repeat). Toggle: exit_on_opp. // STOP still wins a same-bar tie (checked first). // v2.6.8: VWAP-FAIL (1S) GRADE REBUILD — the short mirror never received the // v2.6.2 long-side grade fix (TSLA 5m: two clean open/afternoon breakdown // shorts silently blocked). Old defects, mirror-image of v2.6.2's: grade A // demanded gap<-3% and B gap<-2% (a non-gap-down day could NEVER grade A/B), // every grade demanded the FULL bear stack 5<20<50 (the 50 hasn't rolled at // the FIRST breakdown — exactly when the trade exists), and tier/grade were // coupled. Now mirrors the long: depth IMPROVES grade instead of gating it, // structure test = ma20 < ma50 only where confluence-relevant (A/B), C needs // just rvol >= 1.0, gap matters ONLY if pull_req_gap is toggled ON. // v2.6.9: PLAN-SANITY GATE + NAMED EXITS (real TSLA 5m gap-down: a VWAP FAIL short // fired minutes after the open with T1/-2s and T2/-4s ABOVE the entry -- // newborn-session sigma was so small the bands hugged VWAP above the flush // close; the ladder even printed "R:R(T1) -0.41" and traded it anyway. The // LONG side got this guard 2026-07-01 (SMCI fix); the short mirror didn't.) // (1) pull_min_rr gate on the whole pull-in family (Pull-In / VWAP Fail / // Trend): at trigger the FROZEN plan must have T1 on the profitable side of // entry AND R:R(T1) >= pull_min_rr (default 1.0; 0 = only require positive). // Fails the test -> NOT a signal: no marker, no alert, no tracker entry. // Backside/Rubber Band already have their own room + R:R floors. // (2) Tracker exit labels upgraded: named + priced (W/L R ·STOP @ px / ·T2 / // ·OPP @ px, size small) so exits are findable on a multi-day chart. // Full version history lives in the chat log, not here - this header was 260 lines. // ============================================================================= indicator("Lean J3P v1.1 — Five Plays · Quiet Chart (logic v2.6.9)", shorttitle="LEAN-J3P", overlay=true, max_lines_count=60, max_labels_count=500) // ============================================================================= // COMMON INPUTS // ============================================================================= g_common = "Common" pivot_lookback = input.int(5, "Pivot Lookback", minval=1, maxval=50, group=g_common, tooltip="Bars left/right for pivot high/low detection (used by Trend & Backside).") rvol_threshold = input.float(1.5, "RVOL Threshold (min)", minval=0.1, step=0.1, group=g_common, tooltip="Relative volume floor (vol / sma(vol,20)). 1.5 = 50% above 20-bar avg.") atr_period = input.int(14, "ATR Period", minval=1, maxval=100, group=g_common, tooltip="ATR lookback for stop buffer and floors.") vwap_anchor = input.string("session", "VWAP Anchor", options=["session","week","month"], group=g_common, tooltip="Anchor period for the VWAP calculation.") vwap_src = input.source(ohlc4, "VWAP Source", group=g_common, tooltip="Default is OHLC4 = (open + high + low + close) / 4. Change this if you want HLC3, close, etc.") sd_mult_1 = input.float(0.5, "VWAP SD Band 1 (±0.5σ)", minval=0.1, step=0.1, group=g_common) sd_mult_2 = input.float(1.0, "VWAP SD Band 2 (±1σ)", minval=0.1, step=0.1, group=g_common) sd_mult_3 = input.float(2.0, "VWAP SD Band 3 (±2σ)", minval=0.1, step=0.1, group=g_common) sd_mult_4 = input.float(3.0, "VWAP SD Band 4 (±3σ)", minval=0.1, step=0.1, group=g_common) sd_mult_5 = input.float(4.0, "VWAP SD Band 5 (±4σ target)", minval=0.1, step=0.1, group=g_common) // ============================================================================= // v2.6.3 — FAST-MA DIRECTION GATE ("entries only in the direction of the fast MA") // ============================================================================= g_fastgate = "Fast-MA Direction Gate" fast_gate_on = input.bool(true, "Entries only WITH the fast MA", group=g_fastgate, tooltip="LONG plays only fire while the fast MA (5) is rising; SHORT plays only while it is falling. Kills counter-trend triggers against the fast intraday MA. Redundant for Backside/Rubber Band (their curl trigger already does this) - the real effect is on Pull-In long and VWAP Fail short.") fast_gate_mode = input.string("Slope", "Direction test", options=["Slope","Price side","Both"], group=g_fastgate, tooltip="Slope: the MA5's own direction (style below). Price side: close above/below the MA5 (looser - counts even if the slope has not flipped yet). Both: strictest, latest.") fast_slope_style = input.string("Head (consecutive steps)", "Slope test style", options=["Head (consecutive steps)","Window (now vs lookback)"], group=g_fastgate, tooltip="v2.6.6. HEAD (default): the LEADING EDGE of the 5-MA must make N consecutive steps in the trade's direction (N below). Catches the turn 1-2 bars in - a single bounce bar can NOT fake it, because its up-step still has a down-step behind it. WINDOW: the v2.6.5 body test (MA5 now vs N bars ago) - steadiest, but the whole window must flip, which can be after the move is over.") fast_head_steps = input.int(2, "Head: consecutive steps needed", minval=1, maxval=5, group=g_fastgate, tooltip="v2.6.6, Head style only. How many back-to-back rising (falling) MA5 steps open the gate for a long (short). 2 (default) = two bars in a row - the single-bar twitch is filtered, the turn is caught almost immediately. 1 = the old micro-curl (fastest, fakeable). 3+ = sturdier, later.") fast_slope_lb = input.int(6, "Window: lookback (bars)", minval=1, maxval=30, group=g_fastgate, tooltip="Window style only. MA5 now vs MA5 N bars ago. 6 on a 2-min chart = the 5-MA must be higher than 12 minutes ago - the slope your eye sees, but the latest to open.") // ============================================================================= // PLAY 1 — VWAP PULL-IN (LONG) // ============================================================================= g_play1 = "Play 1 — VWAP Pull-In (Long)" enable_pullin = input.bool(true, "Enable VWAP Pull-In", group=g_play1) gap_pct_min = input.float(0.02, "Gap-Up Minimum %", minval=0.0, step=0.005, group=g_play1, tooltip="Spec: gap > 2% (0.02). Aggressive tier: 0.03.") pullin_use_lb3_stop = input.bool(false, "Long stop: use LB3 band instead of shakeout low", group=g_play1, tooltip="OFF (default): structural stop just below the shakeout low — paired with the recapture entry. ON: LB3 −2σ band stop (legacy 467-grid pick, run against the OLD −1SD entry; NOT validated for the recapture entry — A/B backtest only).") atr_buf_mult = input.float(0.1, "ATR Stop Buffer Mult", minval=0.0, step=0.05, group=g_play1, tooltip="Stop buffer below the stop level = mult * ATR(atr_period). Spec default 0.1.") min_stop_atr = input.float(0.5, "Min stop distance (ATR)", minval=0.0, step=0.1, group=g_play1, tooltip="Floor on the stop (both directions): never tighter than this many ATR from entry. Prevents noise-width stops and fake huge R:R from shallow shakeouts. Set 0 to disable the floor.") pull_req_side = input.bool(true, "Require side-of-VWAP context", group=g_play1, tooltip="v2.4.2. LONG requires a FRONT-side session (price has spent most of the day above VWAP) - the shakeout-and-reclaim thesis assumes VWAP is being DEFENDED. SHORT mirror requires a BACK-side session. Off = legacy: reclaims fire on backside days too, where they are usually fades, not entries.") side_min_pct = input.float(55.0, "Side ratio minimum (%)", minval=50.0, maxval=95.0, step=5.0, group=g_play1, tooltip="Percent of session bars that must have closed on the trade's side of VWAP. First 10 bars of the session pass automatically (no meaningful ratio yet).") max_shakeout_bars = input.int(12, "Max shakeout duration (bars)", minval=1, maxval=60, group=g_play1, tooltip="A shakeout is BRIEF: the dip below VWAP (or squeeze above, for the short) must reclaim within N bars or the latch expires - a longer stay is a base/breakdown, a different trade. 12 bars = 24 min on 2-min.") pull_min_rr = input.float(1.0, "Min R:R to T1 (Pull-In / VWAP Fail / Trend)", minval=0.0, step=0.25, group=g_play1, tooltip="*** THE VISIBILITY KNOB — bench-measured 2026-07-30, 4,920 symbol-days of 2-min bars ***\nThis single input is why the chart looks empty. At 1.0 the pull-in family fires 68 times per 2,400 symbol-days (~once a quarter on ONE stock). At 0 it fires 308 times — 4.5x more — and the SAME 4.5x held out-of-sample (75 -> 311 over a separate 2,520 symbol-days), so the frequency effect is real, not a fluke.\nIt also changes the KIND of trade: at 1.0 the win rate is 32% in-sample / 12% out (rare lottery tickets, median -1R). At 0 it is 65% in-sample / 56% out (base hits, median +0.09R) — because demanding R:R>=1.0 to T1 systematically throws away the high-probability setups with nearer targets.\nHONESTY: neither setting was PROFITABLE out-of-sample (control -0.344R/trade, floor-0 -0.103R/trade). Loosening this does NOT buy edge — it buys visibility and a trade profile that matches how you actually trade. Default stays 1.0 because that is the tested v2.6.9 value; set 0 deliberately if you want to SEE the plays.\n\nORIGINAL v2.6.9 NOTE — PLAN-SANITY GATE. At trigger, the frozen plan must have T1 on the PROFITABLE side of entry and (T1-to-entry)/(entry-to-stop) at least this. Kills the early-session degenerate case where newborn sigma puts the -2s/-4s targets ABOVE a short entry (or +2s below a long) - a structurally guaranteed loser that previously still fired with a negative R:R printed on its own label. 0 = only require the R:R to be POSITIVE (T1 beyond entry). Backside / Rubber Band have their own room + R:R floors and are not affected by this input.") // ============================================================================= // PLAY 1S — VWAP FAIL (SHORT) — v2.4.2 mirror of the pull-in. // Backside day. A squeeze ABOVE VWAP "sucks in longs" (the mirror of the shakeout), // then price loses VWAP again -> short the fail. Shares the pull-in's side-ratio, // duration and stop-floor inputs. Ladder mirrors the long: T1 -2σ, T2 -4σ, runner. // ============================================================================= g_play1s = "Play 1S — VWAP Fail (Short mirror)" enable_pullin_s = input.bool(true, "Enable VWAP Fail SHORT", group=g_play1s, tooltip="The mirror trade. PROVISIONAL playbook slug 'vwap_pull_in_short' - per the locked taxonomy rules, do NOT journal this to AMS under a new canonical slug until the strategy registry decision is made. Pine label only.") // ============================================================================= // PLAY 2 — TREND CONTINUATION (LONG) — v2.4.2b REBUILD, Dale model. // The 9-EMA trigger is gone. This is the queued rebuild: first pullback into the // first deviation band AFTER the trend is established, resumption bar fires it. // Regime context is a ROLLING window (not full-session), so a V-reversal day // hands off correctly: morning reclaim = not this trade; by the time the rolling // window reads front-side, the FIRST PULLBACK is exactly this trade. // ============================================================================= g_play2 = "Play 2 — Trend Continuation (Long, Dale rebuild)" enable_trend = input.bool(false, "Trend Continuation as a TRADE", group=g_play2, tooltip="OFF (v2.6.2, by request): trend continuation is ENVIRONMENT, not entry. The pullback machine still runs and annotates holds/fails; your entries live at the turns (Pull-In, Rubber Band, Backside, VWAP Fail). Turn ON to restore TREND entries with ladder + tracker.") trend_annotate = input.bool(true, "Annotate pullback holds (environment)", group=g_play2, tooltip="v2.6.2. With the trade OFF, the pullback state machine keeps running as a NARRATOR: a small 'held' mark prints when a pullback into the MA20/+1σ zone resumes — the tell that the trend is intact and your risk on an open long can trail beneath it. Fails are covered by TREND BREAK.") trend_ctx_lb = input.int(30, "Regime window (bars)", minval=10, maxval=120, group=g_play2, tooltip="Rolling window for trend context. 30 bars = 60 min on 2-min. Unlike the pull-in's full-session ratio, this rolls — so an afternoon trend after a morning flush qualifies once the reclaim has HELD this long.") trend_ctx_pct = input.float(70.0, "Regime: % bars above VWAP", minval=50.0, maxval=100.0, step=5.0, group=g_play2, tooltip="At least this % of the window's bars must close above VWAP, and VWAP slope must be up. The trend must be PROVEN before a pullback is buyable — no turn-catching.") trend_pb_band = input.string("MA20 or +1σ", "Pullback must reach", options=["MA20 or +1σ","+1σ","+0.5σ","VWAP","MA20"], group=g_play2, tooltip="Support the pullback low must touch to arm. Default: whichever of MA20 / +1sigma sits HIGHER - in a strong trend the 20 rides above the bands and the pullback holds MA 1 without reaching +1sigma. No touch = no trade. See header v2.4.3.") trend_fresh_bars = input.int(8, "Pullback must follow a fresh high (bars)", minval=1, maxval=40, group=g_play2, tooltip="The pullback only ARMS if the regime window high printed within the last N bars - the leg must have just EXTENDED before its pullback is buyable. Sideways drift with lower highs never arms. See header v2.4.2e.") trend_cooldown = input.int(10, "Cooldown between entries (bars)", minval=0, maxval=60, group=g_play2, tooltip="v2.4.2e. Minimum bars after a trend fire before the next one may fire. Stops the arm-fire-rearm machine gun in chop. 10 bars = 20 min on 2-min.") show_regime = input.bool(false, "Shade trend regime background", group=g_play2, tooltip="LEAN v1.0: default OFF — the compact regime badge replaces the tint (spec: tint = visual noise). Flip ON for the old subtle teal wash. The regime CALCULATION always runs either way — NO CHASE, alerts and the badge all read it even when the tint is hidden.") trend_est_bars = input.int(6, "Regime established after (bars)", minval=1, maxval=40, group=g_play2, tooltip="The front-side regime must hold this many consecutive RTH bars before it counts as ESTABLISHED. Only an established regime can later print a TREND BREAK.") trend_break_cool = input.int(20, "Min bars between TREND BREAKs", minval=0, maxval=120, group=g_play2, tooltip="LEAN v1.0 (ported from the field fix): NVDA 2026-07-29 printed FOUR TREND BREAK markers inside ~30 minutes — a break clears the regime, 6 front-side chop bars re-establish it, and it breaks again. One marker per event means a cooldown. 20 bars = 40 min on 2-min: at most one break per window. Display/annotation guard only — no entry logic reads this.") trend_pb_max = input.int(15, "Max pullback duration (bars)", minval=2, maxval=60, group=g_play2, tooltip="Pullback must resume within N bars of arming or the latch expires (drift sideways that long = the trend is in question). A close BELOW VWAP also kills it instantly — that hands the moment to the Pull-In shakeout machine instead, which is the correct owner of a lost VWAP.") // ============================================================================= // PLAY 3 — BACKSIDE SCALP (SHORT) — tiered σ-extension entry // ============================================================================= g_play3 = "Play 3 — Backside Scalp (Short)" enable_backside = input.bool(true, "Enable Backside Scalp", group=g_play3) backside_ext_min = input.float(2.0, "Extension from VWAP (σ)", minval=0.5, step=0.1, group=g_play3, tooltip="The bar's HIGH must be N standard deviations above VWAP to qualify as 'backside' (v2.4.1a: measured on the HIGH, not the close — a rejection bar closes off its high by definition, so close-based σ was self-disqualifying). σ-based so it shares the long's bands. Grades toward +4σ.") backside_arm_tier = input.string("Aggressive", "Trigger tier", options=["Aggressive","Moderate","Conservative"], group=g_play3, tooltip="Which confirmation FIRES an armed setup. Aggressive = fast MA curls down. Moderate = curl + break of prior swing low. Conservative = + 20MA rolls + close back inside +1σ — most confirmed, latest, gives back the most. Grade still rewards deeper confirmation regardless of trigger tier.") back_ext_lb = input.int(12, "Extension lookback (bars)", minval=1, maxval=50, group=g_play3, tooltip="Arm test: did the HIGH reach the sigma threshold within the last N bars, AND is THIS bar a rejection? Rounded tops peak first and reject a few bars later. 12 bars = 24 min on 2-min. See header v2.4.1b note.") back_arm_window = input.int(20, "Arm window (bars)", minval=1, maxval=100, group=g_play3, tooltip="v2.4.1 ARM/TRIGGER SPLIT. The extended rejection bar ARMS the setup and freezes the failed high; the trade fires when the trigger tier confirms within this many bars. 20 bars = 40 min on a 2-min chart. The latch dies early if the failed high is taken out.") back_min_bars = input.int(15, "Session warmup (bars)", minval=1, maxval=60, group=g_play3, tooltip="No arming until N session bars (never fewer than the extension lookback). A newborn VWAP has near-zero variance - opening hi-sigma readings are fake - and this keeps the leg lookback from reaching into YESTERDAY. See header v2.4.2c.") back_trig_min = input.float(1.0, "Min extension at trigger (σ)", minval=0.0, step=0.25, group=g_play3, tooltip="Trigger close must still be N sigma above VWAP - entry stays above T1 so cover-into-VWAP has room. Price already AT VWAP is not a backside (that is Play 1S territory). 0 disables. See header v2.4.2c.") back_min_rr = input.float(2.0, "Min R:R to VWAP (trigger gate)", minval=0.0, step=0.25, group=g_play3, tooltip="v2.4.2d. At trigger, (entry - VWAP) / (stop - entry) must be at least this. Stop = frozen failed high + buffer; target for the test = VWAP (the signature cover, T2). Below the floor the signal does NOT populate at all - no marker, no alert, no tracker entry. 0 disables.") back_no_chase = input.bool(true, "Trend mode = NO CHASE (suppress backside)", group=g_play3, tooltip="The locked framework rule: while the front-side trend regime is active, an extended rejection is a no-chase/no-adds WARNING (yellow marker + alert), not a short. Bella Fade is for when the front side is OVER. See header v2.4.3.") back_req_rvol = input.bool(false, "Require RVOL at arm", group=g_play3, tooltip="OFF (default): no RVOL floor on the arm bar — midday backside tops are low-volume by nature, the same reason the pull-in's RVOL gate defaults off. Grade A/B still reward hot RVOL. ON: restores the old rvol >= threshold gate.") // ============================================================================= // PLAY 3B — RUBBER BAND (LONG) — v2.5, the queued `backside-long`. // Canonical per the 2026-05-04 taxonomy resolution: Rubber Band = band-anchored long // mean reversion to VWAP (never "Bella Fade long"). Full mirror of the backside // short: extension leg <= -2σ BELOW VWAP, capitulation bar holds a new low, MAs // curl UP, entry on the trigger tier, stop under the frozen failed LOW, ladder // 30% @ -1σ / 50% @ VWAP / 20% runner toward +1σ. Shares ALL of Play 3's numeric // inputs (extension σ, leg lookback, arm window, warmup, trigger floor, R:R floor, // trigger tier) so the KITE parameter surface stays one set, mirrored. // NOTE: swang-rubberband (>3 ATR + RVOL>5 + Double Bar Break) is a SEPARATE tracked // variant — this is the base play only. // ============================================================================= g_play3b = "Play 3B — Rubber Band (Long, backside-long)" enable_rubber = input.bool(true, "Enable Rubber Band LONG", group=g_play3b, tooltip="Canonical slug backside_long (2026-05-04 resolution). Mirror of the backside scalp: buy the held capitulation low below -2σ, cover into VWAP.") rb_min_legs = input.int(2, "Min legs down to arm", minval=1, maxval=5, group=g_play3b, tooltip="v2.6.2. Touching -2σ is a LOCATION; the Rubber Band thesis is an EXHAUSTION, and exhaustion has structure: leg down, bounce, LOWER low. A leg ends when price closes back above the 5MA while below VWAP; a new leg starts on the break to a lower low. Default 2 = the classic two-leg flush. Set 1 to disable the structure test (legacy single-dip arming). Straight one-leg gap-flushes will NOT arm at 2 - intended cost; A/B it in KITE as rb_min_legs 1 vs 2.") // ============================================================================= // VISUAL / STYLE INPUTS — USER-CUSTOMIZABLE // ============================================================================= g_viz = "Visuals — Toggles" i_show_vwap = input.bool(true, "Show VWAP", group=g_viz) i_show_bands = input.bool(true, "Show VWAP Bands", group=g_viz) i_show_band_clouds = input.bool(true, "Show VWAP Band Clouds", group=g_viz) i_show_ma_stack = input.bool(true, "Show MA Stack", group=g_viz) i_show_entry_lines = input.bool(true, "Show Trend Entry/Stop/Target lines", group=g_viz) i_show_signal_marks = input.bool(true, "Show Signal Markers", group=g_viz) i_show_info_table = input.bool(true, "Show Live State Table", group=g_viz) i_show_tables = input.bool(true, "Show tables (master)", group=g_viz, tooltip="v2.6.4. OFF hides ALL tables at once — the live state table, the outcome table, and the timeframe notice. The individual table toggles still apply when this is ON.") // LEAN v1.0 — THE VIEW MODE. This is the one switch that makes the chart quiet. // LEAN: the 7-item hierarchy only — entry trigger, entry/stop ladder, grade, // NO CHASE, one arming dot per cycle, regime badge, one break/invalid marker. // DEBUG: everything the full J3P showed — live state table, gate diagnostics, // outcome table, W/L result tags, pb-held narration dots. view_mode = input.string("Lean", "View mode", options=["Lean","Debug"], group=g_viz, tooltip="LEAN (default): quiet chart, decisions only. DEBUG: full diagnostics — state table, outcome table + W/L tags, pb-held dots, expiry markers for the pull-in/squeeze machines. Logic is IDENTICAL in both modes; only the display changes.") debug_mode = view_mode == "Debug" show_badge = input.bool(true, "Show regime badge (Lean view)", group=g_viz, tooltip="Compact top-right badge: POWER TREND / TREND UP / BACKSIDE / NEUTRAL, plus today's honest signal tally and an OPEN-trade row while a tracked position is on. Lean view only — Debug's full table already carries this.") badge_pos = input.string(position.top_right, "Regime badge position", options=[position.top_right, position.top_left, position.bottom_right, position.bottom_left], group=g_viz) // LEAN v1.1 — EVIDENCE MARKS (trust is earned, not asked for). After a NO CHASE // warning or a pullback-hold, the chart comes back N bars later and GRADES ITS OWN // CALL: teal ✓ = the call aged well, gray ✗ = it didn't. Both print — the point is // an honest running record you can watch accumulate, not a highlight reel. show_verify = input.bool(true, "Follow-through ✓/✗ (grade my own calls)", group=g_viz, tooltip="N bars after a NO CHASE warning: ✓ if price is still higher (the guard saved you a losing short), ✗ if the trend cracked anyway. N bars after a pullback-hold: ✓ if the trend made a new high (the hold paid), ✗ if it failed. Honest both ways — the ✓s are what earn trust, the ✗s are what keep it honest.") verify_bars = input.int(10, "Follow-through check after (bars)", minval=3, maxval=60, group=g_viz, tooltip="How long the chart waits before grading its own call. 10 bars = 20 minutes on a 2-min chart.") // ============================================================================= // TIMEFRAME GATE — intraday only. // ----------------------------------------------------------------------------- // This is an INTRADAY session-anchored VWAP system. On 30m and above the session // VWAP resets every few bars, the σ bands are meaningless, and the clouds smear the // whole pane. Rather than trust discipline, the script simply refuses to draw. // // The gate is DISPLAY-ONLY by design: signal logic, grades and alertconditions still // compile and evaluate on every timeframe. If you ever attach an alert to this script // on a daily chart it WILL still fire even though nothing is drawn. Flip // gate_alerts_too ON to shut that door as well. // ============================================================================= g_tf = "Timeframe Gate" max_tf_min = input.float(15.0, "Max timeframe (minutes)", minval=0.1, step=1.0, group=g_tf, tooltip="Indicator draws on this timeframe and below. 15 = 15m and lower, down to 1-second charts. Set 1440 to allow daily.") show_tf_notice = input.bool(true, "Show 'hidden' notice when gated out", group=g_tf, tooltip="Small top-center note so a blank chart reads as 'gated', not 'broken'.") gate_alerts_too = input.bool(false, "Also suppress signals/alerts above max TF", group=g_tf, tooltip="OFF (default): the gate is cosmetic — signals still evaluate everywhere. ON: pullin/trend/backside entries are forced false above the max timeframe, so alerts and the outcome tracker go quiet too.") rth_only = input.bool(true, "Signals in regular hours only (9:30-16:00 ET)", group=g_tf, tooltip="Extended-hours charts anchor VWAP at 4 AM - premarket sigma and RVOL are fiction (Peak hi-sigma printed 233,308 on TSLA premarket). ON: no play acts outside RTH. Bands still draw for context. See header v2.4.3.") tf_sec = nz(timeframe.in_seconds(), 0) tf_ok = tf_sec > 0 and tf_sec <= max_tf_min * 60.0 // tick charts report 0 → gated out rth_h = hour(time, "America/New_York") rth_m = minute(time, "America/New_York") rth_now = (rth_h > 9 or (rth_h == 9 and rth_m >= 30)) and rth_h < 16 sig_ok = (tf_ok or not gate_alerts_too) and (not rth_only or rth_now) // Effective toggles: every visual is ANDed with the gate. show_vwap = i_show_vwap and tf_ok show_bands = i_show_bands and tf_ok show_band_clouds = i_show_band_clouds and tf_ok show_ma_stack = i_show_ma_stack and tf_ok show_entry_lines = i_show_entry_lines and tf_ok show_signal_marks = i_show_signal_marks and tf_ok show_info_table = i_show_info_table and i_show_tables and tf_ok and debug_mode // LEAN: full table is a Debug tool g_ma = "MA Stack — Custom Values" ma_type = input.string("SMA", "MA Type", options=["SMA", "EMA"], group=g_ma) ma_src = input.source(close, "MA Source", group=g_ma) ma_fast_len = input.int(5, "Fast MA Length", minval=1, maxval=500, group=g_ma) ma_mid_len = input.int(20, "Middle MA Length", minval=1, maxval=500, group=g_ma) ma_slow_len = input.int(50, "Slow MA Length", minval=1, maxval=500, group=g_ma) dash_ma_lines = input.bool(true, "Dashed MA appearance", group=g_ma) g_col_core = "Colors — Core Lines" c_vwap = input.color(#673AB7, "Daily VWAP", group=g_col_core, tooltip="Spec: Daily VWAP #673AB7.") c_ub5 = input.color(color.red, "UB5 / +4σ Target", group=g_col_core, tooltip="Band 5 (±4σ) is NOT in the color spec — this is the long's T2 target, kept loud on purpose.") c_lb5 = input.color(color.green, "LB5 / -4σ Mirror", group=g_col_core, tooltip="Band 5 (±4σ) is NOT in the color spec.") c_ma_fast = input.color(#D98E1E, "Fast MA — 5 DMA", group=g_col_core, tooltip="Spec: 5 DMA #D98E1E.") c_ma_mid = input.color(#E72406, "Middle MA — MA 1", group=g_col_core, tooltip="Spec: MA 1 #E72406 (the 20).") c_ma_slow = input.color(#1848CC, "Slow MA — MA 2", group=g_col_core, tooltip="Spec: MA 2 #1848CC (the 50). MA 3 #089981 is the 200 — this script only plots three MAs.") g_col_bands = "Colors — VWAP Bands" c_band1 = input.color(#673AB7, "Band 1 (±0.5σ)", group=g_col_bands, tooltip="Spec: Upper/Lower Band 1 #673AB7.") c_band2 = input.color(#EA09D5, "Band 2 (±1σ)", group=g_col_bands, tooltip="Spec: Upper/Lower Band 2 #EA09D5. Load-bearing: backside T1 and runner target.") c_band3 = input.color(#089981, "Band 3 (±2σ)", group=g_col_bands, tooltip="Spec: Upper/Lower Band 3 #089981. Load-bearing: long T1 (+2σ) and long band-stop (−2σ).") vwap_width = input.int(3, "VWAP line width", minval=1, maxval=5, group=g_col_bands, tooltip="Spec: VWAP is bold 3.") band_width = input.int(1, "Band 1 / 2 line width", minval=1, maxval=5, group=g_col_bands, tooltip="Spec: Bands 1 and 2 are width 1.") band3_width = input.int(2, "Band 3 line width", minval=1, maxval=5, group=g_col_bands, tooltip="Spec: Band 3 (±2σ) is width 2 — its own thickness selector shows the 2nd notch, unlike Bands 1 and 2. It is also the long's T1 and band-stop, so the extra weight is doing real work.") g_col_cloud = "Colors — VWAP Clouds" c_zone1 = input.color(#673AB7, "Zone 1 Fill (VWAP↔±0.5σ)", group=g_col_cloud, tooltip="Band 1 purple, most opaque. The saturated core band on the reference chart.") c_zone2 = input.color(#673AB7, "Zone 2 Fill (±0.5σ↔±1σ)", group=g_col_cloud, tooltip="Same purple as Zone 1, lighter — reads as lavender. NOT magenta: on the reference chart Zone 2 stays in the purple family even though its outer band is magenta.") c_zone3 = input.color(#089981, "Zone 3 Fill (±1σ↔±2σ)", group=g_col_cloud, tooltip="Band 3 teal, lightest — the pale mint outer cloud.") zone1_transp = input.int(45, "Zone 1 Transparency", minval=0, maxval=100, group=g_col_cloud, tooltip="Lower = darker. Zone 1 sits right on VWAP where price spends most of the day — if candle bodies start washing out, this is the first one to raise back up.") zone2_transp = input.int(68, "Zone 2 Transparency", minval=0, maxval=100, group=g_col_cloud, tooltip="Lower = darker.") zone3_transp = input.int(75, "Zone 3 Transparency", minval=0, maxval=100, group=g_col_cloud, tooltip="Lower = darker.") band_transp = input.int(70, "Band Line Transparency", minval=0, maxval=100, group=g_col_cloud) g_col_sig = "Colors — Signals / Trade Plan" c_pullin_marker = input.color(color.lime, "Pull-In Marker", group=g_col_sig) c_trend_marker = input.color(color.aqua, "Trend Marker", group=g_col_sig) c_back_marker = input.color(color.fuchsia, "Backside Marker", group=g_col_sig) c_pulls_marker = input.color(color.orange, "VWAP Fail Marker", group=g_col_sig) c_rb_marker = input.color(color.yellow, "Rubber Band Marker", group=g_col_sig) c_long_entry = input.color(color.teal, "Long Entry Line", group=g_col_sig) c_short_entry = input.color(color.fuchsia, "Short Entry Line", group=g_col_sig) c_stop_line = input.color(color.red, "Stop Line", group=g_col_sig) c_target_line = input.color(color.green, "Target Line", group=g_col_sig) c_runner_line = input.color(color.green, "Runner / T2 Line", group=g_col_sig) g_table_style = "Table / Label Style" table_pos_str = input.string(position.top_right, "Live Table Position", options=[position.top_right, position.top_left, position.bottom_right, position.bottom_left, position.middle_right, position.middle_left], group=g_table_style) outcome_pos_str = input.string(position.bottom_right, "Outcome Table Position", options=[position.top_right, position.top_left, position.bottom_right, position.bottom_left, position.middle_right, position.middle_left], group=g_table_style) table_txt_size = input.string("Small", "Table Text Size", options=["Tiny", "Small", "Normal"], group=g_table_style) label_txt_size = input.string("Small", "Label Text Size", options=["Tiny", "Small", "Normal"], group=g_table_style) c_table_bg = input.color(#131722, "Table Background", group=g_table_style) c_table_header = input.color(#2A2E39, "Table Header", group=g_table_style) c_table_frame = input.color(color.gray, "Table Border / Frame", group=g_table_style) c_text = input.color(color.white, "Table Text", group=g_table_style) c_good = input.color(color.lime, "Good / Grade A", group=g_table_style) c_warn = input.color(color.yellow, "Warning / Grade B", group=g_table_style) c_bad = input.color(color.red, "Bad / Loss / Stop", group=g_table_style) c_neutral = input.color(color.gray, "Neutral", group=g_table_style) // Helper functions for style choices. f_ma(_src, _len) => ma_type == "EMA" ? ta.ema(_src, _len) : ta.sma(_src, _len) f_dash(_src) => dash_ma_lines ? ((bar_index % 4) < 2 ? _src : na) : _src f_txt_size(_s) => _s == "Tiny" ? size.tiny : _s == "Normal" ? size.normal : size.small // Dash mask for the Band 1 lines. Pine's plot() has NO dashed/dotted style — only // line.new() and hline() do — so a dash is faked by blanking every other pair of bars // and drawing with plot.style_linebr. Same trick f_dash() uses on the MA stack. // 4-bar period: 2 bars drawn, 2 bars blank. f_dashseries(_src) => (bar_index % 4) < 2 ? _src : na // JSON-safe number: na becomes null so the ingest never parses "NaN". f_num(_x) => na(_x) ? "null" : str.tostring(_x, "#.####") // Signed R string, e.g. +1.35R / -1.00R. Avoids relying on a "+0.00" format token. f_sr(_x) => (_x >= 0 ? "+" : "") + str.tostring(_x, "0.00") + "R" // LEAN v1.0 BUGFIX: f_px was CALLED by the v2.6.9 exit labels (·STOP px / ·OPP px) // but never defined — the v2.6.9 file as saved did not compile. Tick-formatted price. f_px(_x) => na(_x) ? "—" : str.tostring(_x, format.mintick) // Shared JSON head for every alert payload. v2.6.7: declared up here (was in the // ALERTS section) because the outcome tracker's opp_exit alert fires before that // section is reached in source order. j_head = '{"v":"2.6.9-lean1","sym":"' + syminfo.tickerid + '","tf":"' + timeframe.period + '","ts":' + str.tostring(time) // ============================================================================= // PULL-IN FILTER RELAXATION (so the recapture trade fires on low-gap / MIXED days) // ============================================================================= g_relax = "Pull-In Filters (relaxed)" pull_req_gap = input.bool(false, "Require gap > min", group=g_relax, tooltip="OFF: ABBV-type setups gap < 2% but are still A+ VWAP pull-ins. Confluence (VWAP not falling) stays ON.") pull_req_stack = input.bool(false, "Require strict 5>20>50", group=g_relax, tooltip="OFF: on a pull-in the 5 dips under the 20 — this gate fights the setup (it blocked ABBV).") pull_req_rvol = input.bool(false, "Require RVOL on entry bar",group=g_relax, tooltip="OFF: the quiet pull-in bar is low-volume by nature.") // ============================================================================= // FROZEN DUAL-TRADE LADDER — % splits + RATCHET (shared by both plays' ladders) // ============================================================================= g_frz = "Frozen Trade Ladder" i_show_frozen = input.bool(true, "Show frozen trade ladder", group=g_frz) show_frozen = i_show_frozen and tf_ok recapture_lb = input.int(6, "Shakeout lookback (UNUSED since v2.4.2)", minval=2, group=g_frz, tooltip="DEPRECATED. The shakeout state machine now tracks the dip's true low directly; this fixed lookback is no longer read anywhere. Kept only so saved chart settings don't break.") pl_t1_pct = input.int(30, "Scale: % off at T1", minval=0, maxval=100, group=g_frz, tooltip="First scale. LONG T1 = +2σ. BACKSIDE T1 = +1σ.") pl_t2_pct = input.int(50, "Scale: % off at T2", minval=0, maxval=100, group=g_frz, tooltip="Second scale. LONG T2 = +4σ. BACKSIDE T2 = VWAP. Whatever is left after T1+T2 is the runner.") runner_be = input.bool(true, "Ratchet stop on each scale (BE after T1, lock T1 after T2)", group=g_frz, tooltip="Intraday risk-off. Once T1 fills the remainder can't lose (stop→entry/BE). Once T2 fills the runner locks a gain (stop→T1 level). This — not the % split — is what stops the runner round-tripping. ANNOTATION ONLY — port to KITE to execute.") bk_stop_buf = input.float(0.25, "Backside stop buffer (ATR above failed high)", step=0.05, group=g_frz) anno_len = input.int(40, "Ladder line length (bars)", minval=5, group=g_frz) pl_runner_pct = math.max(0, 100 - pl_t1_pct - pl_t2_pct) // ============================================================================= // OUTCOME TRACKER inputs // ============================================================================= g_outcome = "Trade Outcome Tracker" i_show_outcomes = input.bool(true, "Track + annotate prior signals (blended R)", group=g_outcome, tooltip="Walks each signal forward through the 30/50/20 ladder WITH the ratchets and books a size-weighted blended R. One trade at a time. Models the ladder — no longer a single-lot exit.") i_show_outcome_table = input.bool(true, "Show Outcome Table", group=g_outcome) // LEAN spec item 4: the tracker ALWAYS runs (latch + webhook depend on it) but the // W/L labels and outcome table are review tools, not live-decision tools — Debug only. show_outcomes = i_show_outcomes and tf_ok and debug_mode show_outcome_table = i_show_outcome_table and i_show_tables and tf_ok and debug_mode // ============================================================================= // POSITION SIZING inputs — risk-based share count on each signal. // ============================================================================= g_size = "Position Sizing" acct_daily_stop = input.float(500.0, "Daily stop ($)", minval=0.0, step=50.0, group=g_size, tooltip="Your max daily loss budget. Base risk per trade is a % of this.") risk_per_trade_pct = input.float(10.0, "Risk per trade (% of daily stop)", minval=0.0, step=1.0, group=g_size, tooltip="Base $ risked on one trade = daily stop × this %. Grade scaling (below) multiplies it.") use_grade_sizing = input.bool(true, "Grade-scaled sizing (off = flat)", group=g_size, tooltip="ON: multiply base risk by the grade multiplier (A/B/C). OFF: same risk on every grade (linear).") one_trade_latch = input.bool(true, "One trade at a time (suppress signals while open)", group=g_size, tooltip="v2.4.3 - the non-negotiable, applied to SIGNALS. While the tracked position is open (not yet stopped/closed), NO play arms a new entry: no marker, no alert. Previously only the tracker refused re-entry; the chart kept printing triangles into a live trade.") require_grade = input.bool(true, "Block ungraded signals", group=g_size, tooltip="ON (default): a setup grading dash (fails every A/B/C bar) does not fire at all - no marker, alert, or tracker entry. Previously these printed but sized to ZERO shares, polluting the stats. OFF: legacy. See header v2.4.1 note.") size_mult_A = input.float(1.5, "Grade A size ×", minval=0.0, step=0.1, group=g_size) size_mult_B = input.float(1.0, "Grade B size ×", minval=0.0, step=0.1, group=g_size) size_mult_C = input.float(0.5, "Grade C size ×", minval=0.0, step=0.1, group=g_size) // ============================================================================= // v2.6.7 — REVERSE-PLAY EXIT // ============================================================================= g_opp = "Reverse-play exit" exit_on_opp = input.bool(true, "Exit when an OPPOSITE play triggers", group=g_opp, tooltip="v2.6.7 (by request). While a trade is open the plays keep evaluating SILENTLY (the one-position latch still suppresses their markers/alerts). If a play triggers in the OPPOSITE direction of the open trade, the trade closes on that bar's close -- a valid reverse trigger means the market said this trade is over. Booked as a normal blended-R outcome, W/L label tagged ·OPP, webhook evt 'opp_exit'. STOP still wins a same-bar tie. After the flat bar, the opposite setup fires organically on its next valid bar (backside/rubber-band arms persist; one-shot reclaim/fail triggers may not repeat). OFF = old behavior (opposite triggers ignored while in a trade).") // ============================================================================= // CORE CALCULATIONS — VWAP + Bands + MA Stack + RVOL + ATR + Gap // ============================================================================= anchor_change = vwap_anchor == "session" ? ta.change(time("D")) != 0 : vwap_anchor == "week" ? ta.change(time("W")) != 0 : ta.change(time("M")) != 0 src = vwap_src var float sum_pv = na var float sum_v = na var float sum_p2v = na if anchor_change or na(sum_v) sum_pv := src * volume sum_v := volume sum_p2v := src * src * volume else sum_pv := sum_pv + src * volume sum_v := sum_v + volume sum_p2v := sum_p2v + src * src * volume vwap_val = sum_pv / sum_v variance = math.max(0.0, (sum_p2v / sum_v) - (vwap_val * vwap_val)) stdev_val = math.sqrt(variance) // BAND MAP (load-bearing — the ladders reference these by σ): // upper_band2 = +1σ | upper_band3 = +2σ | upper_band5 = +4σ // lower_band2 = −1σ | lower_band3 = −2σ // COLOR MAP (spec): // band1 #673AB7 | band2 #EA09D5 | band3 #089981 | band4 #000000 | band5 (unspecified) upper_band1 = vwap_val + sd_mult_1 * stdev_val // +0.5σ upper_band2 = vwap_val + sd_mult_2 * stdev_val // +1σ upper_band3 = vwap_val + sd_mult_3 * stdev_val // +2σ upper_band4 = vwap_val + sd_mult_4 * stdev_val // +3σ upper_band5 = vwap_val + sd_mult_5 * stdev_val // +4σ lower_band1 = vwap_val - sd_mult_1 * stdev_val // −0.5σ lower_band2 = vwap_val - sd_mult_2 * stdev_val // −1σ lower_band3 = vwap_val - sd_mult_3 * stdev_val // −2σ lower_band4 = vwap_val - sd_mult_4 * stdev_val // −3σ (added so Band 4 has a lower half) lower_band5 = vwap_val - sd_mult_5 * stdev_val // −4σ ma5 = f_ma(ma_src, ma_fast_len) ma20 = f_ma(ma_src, ma_mid_len) ma50 = f_ma(ma_src, ma_slow_len) ma_stack_alignment = ma5 > ma20 and ma20 > ma50 ma_stack_slope = ma20[5] != 0 ? (ma20 - ma20[5]) / ma20[5] : 0.0 vwap_slope = vwap_val[10] != 0 ? (vwap_val - vwap_val[10]) / vwap_val[10] : 0.0 // v2.6.3 FAST-MA DIRECTION GATE: longs need the 5 rising (or price above it), shorts // the mirror. v2.6.5 measured the slope over a window (steady but late). v2.6.6 HEAD // style (default): the MA5's leading edge must step the trade's way N bars in a row -- // a lone bounce bar has a down-step right behind its up-step, so it cannot fake the // gate, and the turn is caught 1-2 bars in instead of waiting for the window to flip. f_head_dir(int _steps) => bool _up = true bool _dn = true for _i = 0 to _steps - 1 _up := _up and ma5[_i] > ma5[_i + 1] _dn := _dn and ma5[_i] < ma5[_i + 1] [_up, _dn] [head_up, head_dn] = f_head_dir(fast_head_steps) bool slope_up = fast_slope_style == "Head (consecutive steps)" ? head_up : ma5 > ma5[fast_slope_lb] bool slope_dn = fast_slope_style == "Head (consecutive steps)" ? head_dn : ma5 < ma5[fast_slope_lb] fast_long_ok = not fast_gate_on or (fast_gate_mode == "Slope" ? slope_up : fast_gate_mode == "Price side" ? close > ma5 : slope_up and close > ma5) fast_short_ok = not fast_gate_on or (fast_gate_mode == "Slope" ? slope_dn : fast_gate_mode == "Price side" ? close < ma5 : slope_dn and close < ma5) avg_vol = ta.sma(volume, 20) rvol = avg_vol > 0 ? volume / avg_vol : 0.0 atr_val = ta.atr(atr_period) atr_buffer = atr_buf_mult * atr_val prev_close = request.security(syminfo.tickerid, "D", close[1], lookahead=barmerge.lookahead_on) day_open = request.security(syminfo.tickerid, "D", open, lookahead=barmerge.lookahead_on) gap_pct = (day_open / prev_close) - 1 hour_et = hour(time, "America/New_York") min_et = minute(time, "America/New_York") tod_late = (hour_et == 14 and min_et >= 30) or (hour_et == 15 and min_et <= 55) tod_open = (hour_et == 9 and min_et >= 30) or (hour_et == 10) band_spread = vwap_val != 0 ? (upper_band3 - lower_band3) / vwap_val : 0.0 // σ-distance of price from VWAP. // ext_sigma (CLOSE-based) — general state readout. // ext_sigma_hi (HIGH-based) — the BACKSIDE ARM test. v2.4.1a fix: rejection_bar // requires close < high − 40% of range, so on the exact bar that qualifies as a // rejection the CLOSE-based σ is mechanically depressed below the HIGH's σ — the // arm condition was disqualifying itself. The top's extension is the high's extension. ext_sigma = stdev_val > 0 ? (close - vwap_val) / stdev_val : 0.0 ext_sigma_hi = stdev_val > 0 ? (high - vwap_val) / stdev_val : 0.0 // Session side-of-VWAP tally (v2.4.2): what fraction of today's bars closed above VWAP. // Front-side context for the pull-in long; back-side context for the fail short. var int sess_n = 0 var int sess_up = 0 if anchor_change sess_n := 0 sess_up := 0 // v2.6.2: count RTH bars only. Previously every premarket bar incremented sess_n, // so back_warm_ok was satisfied before the open and the ARM could fire on // premarket-inflated sigma (the 9:30 pink dot at 309.5 on TSLA 2026-07-29). // The RTH gate lived in sig_ok, which gates TRIGGERS - it never gated ARMS. if not rth_only or rth_now sess_n := sess_n + 1 sess_up := sess_up + (close > vwap_val ? 1 : 0) frontside_ok = not pull_req_side or sess_n < 10 or sess_up * 100.0 >= side_min_pct * sess_n backside_ok = not pull_req_side or sess_n < 10 or (sess_n - sess_up) * 100.0 >= side_min_pct * sess_n // One-position latch (v2.4.3): in_trade is updated by the tracker at the bottom of // the script, so reading it here sees the state as of the END of the prior bar - // which is exactly right: a trade opened on bar N blocks new signals from bar N+1 // until it resolves. Declared here so every play below can gate on it. var bool in_trade = false // v2.6.2 STALE-POSITION FIX. in_trade persisted across session boundaries and // across SYMBOL CHANGES - TSLA 2026-07-29 showed "backside_scalp OPEN" with entry // 379.82 while price was 302, a phantom from another instrument. A held position // blocks every play via pos_free, so the whole afternoon went silent. Any new // session flattens the tracker: an intraday play cannot be open across the bell. pos_free = not (one_trade_latch and in_trade) // ============================================================================= // PLAY 1 — VWAP PULL-IN ENTRY LOGIC (unchanged core; recapture entry) // ============================================================================= pullin_gap_ok = not pull_req_gap or gap_pct > gap_pct_min pullin_stack_ok = not pull_req_stack or ma_stack_alignment pullin_rvol_ok = not pull_req_rvol or rvol >= rvol_threshold pullin_conf_ok = vwap_slope >= 0 // ----------------------------------------------------------------------------- // v2.4.2 SHAKEOUT STATE MACHINE (long). Same arm/trigger philosophy as the backside. // The dip below VWAP ARMS the trade and tracks the ACTUAL shakeout low while below. // The close back above VWAP TRIGGERS it - but only if the dip stayed brief enough to // BE a shakeout (max_shakeout_bars). A long grind below VWAP expires the latch: its // eventual reclaim is a different trade, and it does not fire here. // This replaces two defects: (a) the old cross-detector `close[1] <= vwap_val` // compared the PRIOR close against the CURRENT bar's VWAP (an actual bug), and // (b) `ta.lowest(low, 6)` measured a fixed window that could catch lows from before // the dip, or miss the real low of a longer dip. The state machine measures the dip. // pl_state: 0 = above VWAP (idle) | 1 = below, armed | 2 = below too long, expired // ----------------------------------------------------------------------------- var int pl_state = 0 var float pl_sh_low = na var int pl_arm_barL = na // LEAN v1.2 REGRESSION FIX — nothing survives the bell. The v2.6.9 lineage LOST the // session resets that the 2.6.6 branch carries, and this one actively suppresses // entries: a dip still open at 3:58pm leaves pl_sh_low holding YESTERDAY's low, so // the next morning's reclaim freezes a stop miles away -> R:R collapses -> the // v2.6.9 plan-sanity gate rejects it -> NO SIGNAL, silently. if anchor_change pl_state := 0 pl_sh_low := na below_vwap = close < vwap_val recapture_trig = false if below_vwap if pl_state == 0 pl_state := 1 pl_sh_low := low pl_arm_barL := bar_index else pl_sh_low := math.min(pl_sh_low, low) if pl_state == 1 and bar_index - pl_arm_barL > max_shakeout_bars pl_state := 2 else recapture_trig := pl_state == 1 pl_state := 0 // LEAN v1.0: one quiet dot when the dip ARMS (state 0→1 transition, once per cycle), // one Debug-only expiry event when it overstays (state 1→2). Display flags only. bool pl_dip_new = pl_state == 1 and nz(pl_state[1]) != 1 and enable_pullin and frontside_ok and sig_ok bool pl_dip_expired = pl_state == 2 and nz(pl_state[1]) == 1 pullin_base_ok = enable_pullin and pullin_gap_ok and pullin_stack_ok and pullin_rvol_ok and pullin_conf_ok and frontside_ok recapture = pullin_base_ok and recapture_trig shakeout_low_n = pl_sh_low // the dip's true low, frozen by the state machine aggressive_long = recapture and shakeout_low_n > lower_band2 moderate_long = recapture and shakeout_low_n <= lower_band2 and shakeout_low_n > lower_band3 conservative_long = recapture and shakeout_low_n <= lower_band3 // v2.4.1: grade is computed BEFORE the entry so the entry can be GATED on it. // Previously an ungraded recapture (MIXED stack, cold RVOL) fired as a signal, then // grade '—' → size ×0 → zero shares. The tracker scored 110 of those at 30.9% WR. // With require_grade ON, "the sizer would give it zero shares" now means "it is not // a signal" — every recapture must clear at least Grade C (RVOL ≥ 1.5 + aligned stack). // v2.6.3: + fast_long_ok — no pull-in long while the 5 is still falling. // v2.6.7: _pre = the trigger WITHOUT the one-position latch (feeds the reverse-exit). // v2.6.9: plan-sanity — the frozen plan (stop below, T1 +2σ above) must be structurally // profitable at trigger, with R:R(T1) ≥ pull_min_rr. Uses the same stop math the entry // will freeze (struct-or-band choice + ATR floor). float pl_stop_raw = math.min(pullin_use_lb3_stop ? lower_band3 - atr_buffer : shakeout_low_n - atr_buffer, close - min_stop_atr * atr_val) float pl_rr_raw = close > pl_stop_raw ? (upper_band3 - close) / (close - pl_stop_raw) : -1.0 bool pullin_plan_ok = pl_rr_raw > 0 and (pull_min_rr <= 0 or pl_rr_raw >= pull_min_rr) pullin_cand_pre = (aggressive_long or moderate_long or conservative_long) and sig_ok and fast_long_ok and pullin_plan_ok pullin_cand = pullin_cand_pre and pos_free // v2.6.2 GRADE REBUILD. Two defects removed: // 1) TIER/GRADE COUPLING WAS BACKWARDS. Each tier could reach exactly one grade, // and A/B additionally demanded a gap. Net effect with require_grade ON: a deep // shakeout to -2s on a non-gapping stock could not fire AT ALL (ineligible for // A without the gap, ineligible for B/C by tier), while the shallowest dip fired // freely. Depth now IMPROVES grade instead of restricting eligibility - any tier // can earn any grade. // 2) THE RELAXATION TOGGLES WERE DEAD LETTERS. pull_req_gap/stack/rvol default OFF // by design (the ABBV note: "on a pull-in the 5 dips under the 20 - this gate // fights the setup"), but every grade required rvol>=1.5 AND full 5>20>50 // alignment, silently reinstating them. Structure now tests ma20 > ma50 - the // part a pull-in does NOT violate - never the full stack. Gap is gone from the // grades entirely: if you want it required, flip pull_req_gap ON. One decision, // one place. grade_A_pullin = pullin_cand and rvol >= 2.0 and not aggressive_long and ma20 > ma50 and ma_stack_slope > 0 and band_spread >= 0.015 grade_B_pullin = pullin_cand and rvol >= 1.5 and ma20 > ma50 and not grade_A_pullin grade_C_pullin = pullin_cand and rvol >= 1.0 and not grade_A_pullin and not grade_B_pullin pullin_grade = grade_A_pullin ? "A" : grade_B_pullin ? "B" : grade_C_pullin ? "C" : "—" pullin_tier = conservative_long ? "band3" : moderate_long ? "band2" : aggressive_long ? "band1" : "—" pullin_entry = pullin_cand and (not require_grade or pullin_grade != "—") pullin_stop_struct = shakeout_low_n - atr_buffer pullin_stop_band = lower_band3 - atr_buffer pullin_stop_pre = pullin_use_lb3_stop ? pullin_stop_band : pullin_stop_struct pullin_stop = pullin_entry ? math.min(pullin_stop_pre, close - min_stop_atr * atr_val) : na // Canonical pull-in plan. Entry = signal-bar close. Primary target / R:R = T1 (+2σ). pullin_entry_price = pullin_entry ? close : na pullin_target = pullin_entry ? upper_band3 : na // +2σ = T1 // ============================================================================= // PLAY 1S — VWAP FAIL (SHORT) ENTRY LOGIC — the mirror state machine. // Squeeze ABOVE VWAP arms and tracks the squeeze HIGH; losing VWAP triggers. // Backside session context. Tier by how deep the squeeze reached into the upper // bands (deeper trap = more fuel). Stop above the squeeze high with the ATR floor. // ============================================================================= ma_stack_bear = ma5 < ma20 and ma20 < ma50 var int ps_state = 0 var float ps_sq_high = na var int ps_arm_bar = na // LEAN v1.2: same fix, mirrored — a stale squeeze high from yesterday inflates the // short's risk and the plan-sanity gate silently eats the VWAP FAIL signal. if anchor_change ps_state := 0 ps_sq_high := na above_vwap = close > vwap_val fail_trig = false if above_vwap if ps_state == 0 ps_state := 1 ps_sq_high := high ps_arm_bar := bar_index else ps_sq_high := math.max(ps_sq_high, high) if ps_state == 1 and bar_index - ps_arm_bar > max_shakeout_bars ps_state := 2 else fail_trig := ps_state == 1 ps_state := 0 // LEAN v1.0: mirror narration — one dot when the squeeze arms, Debug expiry event. bool ps_sq_new = ps_state == 1 and nz(ps_state[1]) != 1 and enable_pullin_s and backside_ok and sig_ok bool ps_sq_expired = ps_state == 2 and nz(ps_state[1]) == 1 pulls_gap_ok = not pull_req_gap or gap_pct < -gap_pct_min pulls_stack_ok = not pull_req_stack or ma_stack_bear pulls_conf_ok = vwap_slope <= 0 pulls_base_ok = enable_pullin_s and pulls_gap_ok and pulls_stack_ok and pullin_rvol_ok and pulls_conf_ok and backside_ok vwap_fail = pulls_base_ok and fail_trig squeeze_high_n = ps_sq_high // the squeeze's true high, frozen by the state machine aggr_ps = vwap_fail and squeeze_high_n < upper_band2 mod_ps = vwap_fail and squeeze_high_n >= upper_band2 and squeeze_high_n < upper_band3 consv_ps = vwap_fail and squeeze_high_n >= upper_band3 // v2.6.3: + fast_short_ok — no VWAP-fail short while the 5 is still rising. // v2.6.9: plan-sanity — THE FIX for the gap-down open trade whose -2σ/-4σ covers sat // ABOVE the entry (newborn-session σ). Short plan: stop above squeeze high, T1 -2σ // BELOW entry, R:R(T1) ≥ pull_min_rr — else it is not a signal. float ps_stop_raw = math.max(squeeze_high_n + atr_buffer, close + min_stop_atr * atr_val) float ps_rr_raw = ps_stop_raw > close ? (close - lower_band3) / (ps_stop_raw - close) : -1.0 bool pullin_s_plan_ok = ps_rr_raw > 0 and (pull_min_rr <= 0 or ps_rr_raw >= pull_min_rr) pullin_s_cand_pre = (aggr_ps or mod_ps or consv_ps) and sig_ok and fast_short_ok and pullin_s_plan_ok pullin_s_cand = pullin_s_cand_pre and pos_free // v2.6.8 GRADE REBUILD — mirror of the long side's v2.6.2 fix. Removed: the gap<-2%/-3% // requirements (a no-gap day could never grade A/B; gap is pull_req_gap's job), the // full 5<20<50 bear-stack demand on every grade (the 50 hasn't rolled over at the // FIRST breakdown — the exact moment this play exists), and the tier/grade coupling // (depth now IMPROVES grade instead of restricting eligibility). grade_A_ps = pullin_s_cand and rvol >= 2.0 and not aggr_ps and ma20 < ma50 and ma_stack_slope < 0 and band_spread >= 0.015 grade_B_ps = pullin_s_cand and rvol >= 1.5 and ma5 < ma20 and not grade_A_ps grade_C_ps = pullin_s_cand and rvol >= 1.0 and not grade_A_ps and not grade_B_ps pullin_s_grade = grade_A_ps ? "A" : grade_B_ps ? "B" : grade_C_ps ? "C" : "—" pullin_s_tier = consv_ps ? "band3+" : mod_ps ? "band2" : aggr_ps ? "band1" : "—" pullin_s_entry = pullin_s_cand and (not require_grade or pullin_s_grade != "—") pullin_s_stop_pre = squeeze_high_n + atr_buffer pullin_s_stop = pullin_s_entry ? math.max(pullin_s_stop_pre, close + min_stop_atr * atr_val) : na pullin_s_entry_price = pullin_s_entry ? close : na pullin_s_target = pullin_s_entry ? lower_band3 : na // -2σ = T1 // ============================================================================= // PLAY 2 — TREND CONTINUATION ENTRY LOGIC (v2.4.2b, Dale first-deviation-band model) // ============================================================================= // State machine #4, same grammar as the other three: // REGIME : rolling window mostly above VWAP + VWAP slope up (the trend is proven). // ARM : from that regime, price pulls back and TOUCHES the chosen band zone. // The pullback's true low is tracked while it develops. // TRIGGER : resumption bar — an up-close taking out the prior bar's high while // still above VWAP. Buy the resumption, not the dip. // DEATH : close below VWAP (no longer a trend pullback — the Pull-In shakeout // machine owns that moment) or pullback drags past trend_pb_max bars. // No pullback into the zone = no trade. Riding the upper bands is never chased. trend_pb_zone = trend_pb_band == "+1σ" ? upper_band2 : trend_pb_band == "+0.5σ" ? upper_band1 : trend_pb_band == "VWAP" ? vwap_val : trend_pb_band == "MA20" ? ma20 : math.max(ma20, upper_band2) trend_above_n = math.sum(close > vwap_val ? 1.0 : 0.0, trend_ctx_lb) // front_regime is the market state (used by the backside no-chase filter too); // trend_regime is that state PLUS the play being enabled. front_regime = vwap_slope > 0 and trend_above_n * 100.0 >= trend_ctx_pct * trend_ctx_lb trend_regime = enable_trend and front_regime // v2.4.4 REGIME LAYER: identify the trend ONCE, stay quiet, announce the BREAK. // Established = front_regime held trend_est_bars consecutive signal-eligible bars. // Break = an established regime loses VWAP on a close, or the regime window decays. // One marker at the break instead of narrating the whole fade with entry triangles. // The break moment is the HANDOFF: close below VWAP is the exact bar the Pull-In // shakeout machine arms (reclaim play) and the VWAP Fail short starts watching. var int regime_run = 0 var bool regime_est = false // LEAN v1.2: regime does not survive the bell either — yesterday's established // trend must not print a TREND BREAK on this morning's first bar. if anchor_change regime_run := 0 regime_est := false regime_run := (front_regime and sig_ok) ? regime_run + 1 : 0 if regime_run >= trend_est_bars regime_est := true // LEAN v1.0: one break per cooldown window (the NVDA machine-gun fix). var int tb_last = na tb_cool_ok = na(tb_last) or bar_index - tb_last >= trend_break_cool trend_break = regime_est and sig_ok and tb_cool_ok and (close < vwap_val or not front_regime) if trend_break tb_last := bar_index if trend_break or not sig_ok regime_est := false // POWER TREND tier (v2.6.2, Minervini-style read): an established regime whose leg // has tagged >= +2σ within the regime window — expansion off VWAP into the outer // bands, pullbacks holding the MA. Shown as a deeper background tint. Environment // only: manage risk under the MA while it holds; the break is still one marker. regime_leg_hi = ta.highest(ext_sigma_hi, trend_ctx_lb) power_regime = regime_est and regime_leg_hi >= 2.0 // Fresh-high test: how many bars since the regime window's high was printed. // A pullback is only buyable if the leg JUST extended (Dale: new high, first pullback, // resume). ta.highestbars returns a negative offset; 0 = this bar is the window high. trend_bars_since_hi = -ta.highestbars(high, trend_ctx_lb) trend_fresh_ok = trend_bars_since_hi <= trend_fresh_bars var int tr_state = 0 // 0 = idle | 1 = pullback armed var float tr_pb_low = na var int tr_pb_bar = na var int tr_last_fire = na // LEAN v1.2: a pullback armed into the close must not resume against yesterday's low, // and yesterday's cooldown must not block this morning's first trend entry. if anchor_change tr_state := 0 tr_pb_low := na tr_last_fire := na trend_cool_ok = na(tr_last_fire) or bar_index - tr_last_fire >= trend_cooldown trend_resume = false if close < vwap_val tr_state := 0 // lost VWAP: the pull-in machine owns it now else if tr_state == 0 if (trend_regime or (trend_annotate and front_regime)) and trend_fresh_ok and low <= trend_pb_zone tr_state := 1 tr_pb_low := low tr_pb_bar := bar_index else tr_pb_low := math.min(tr_pb_low, low) if bar_index - tr_pb_bar > trend_pb_max tr_state := 0 // drifted too long — trend in question, latch dies else if close > high[1] and close > open trend_resume := true // resumption bar tr_state := 0 // one-shot // v2.6.3: + fast_long_ok — the resumption must fire with the 5 rising, not against it. // v2.6.9: plan-sanity — resumption close must still have T1 (+2σ) above it with room. float tr_stop_raw = math.min(tr_pb_low - atr_buffer, close - min_stop_atr * atr_val) float tr_rr_raw = close > tr_stop_raw ? (upper_band3 - close) / (close - tr_stop_raw) : -1.0 bool trend_plan_ok = tr_rr_raw > 0 and (pull_min_rr <= 0 or tr_rr_raw >= pull_min_rr) trend_cand_pre = trend_resume and enable_trend and trend_cool_ok and sig_ok and fast_long_ok and trend_plan_ok trend_cand = trend_cand_pre and pos_free if trend_cand tr_last_fire := bar_index // Environment narration (v2.6.2): the same resumption event, as information only — // no ladder, no tracker, no position. "The pullback held" = the trend is intact. pb_held_note = trend_resume and not enable_trend and trend_annotate and sig_ok // Tier by pullback depth (frozen true low vs the bands at resumption): // held +0.5σ — shallowest, strongest trend // held VWAP — reached deeper but VWAP never lost on a close // tagged VWAP — the LOW poked under VWAP while closes held above trend_tier = not trend_cand ? "—" : tr_pb_low > upper_band1 ? "held .5σ" : tr_pb_low > vwap_val ? "held vwap" : "tag vwap" grade_A_trend = trend_cand and tr_pb_low > upper_band1 and rvol >= 1.5 and ma_stack_alignment and ma_stack_slope > 0 and vwap_slope > 0 grade_B_trend = trend_cand and rvol >= 1.0 and ma5 > ma20 and not grade_A_trend grade_C_trend = trend_cand and rvol >= 0.8 and vwap_slope > 0 and not grade_A_trend and not grade_B_trend trend_grade = grade_A_trend ? "A" : grade_B_trend ? "B" : grade_C_trend ? "C" : "—" trend_entry = trend_cand and (not require_grade or trend_grade != "—") // Entry = resumption close. Stop = under the pullback's TRUE low, ATR floor applies. // Ladder: shares the long ladder — T1 +2σ (30%), T2 +4σ (50%), 20% runner, ratchets. trend_entry_price = trend_entry ? close : na trend_stop_pre = tr_pb_low - atr_buffer trend_stop = trend_entry ? math.min(trend_stop_pre, close - min_stop_atr * atr_val) : na trend_target = trend_entry ? upper_band3 : na // +2σ = T1 // ============================================================================= // PLAY 3 — BACKSIDE SCALP ENTRY LOGIC (TIERED σ-extension short) // ============================================================================= // Extension is now σ-based: price ≥ backside_ext_min σ above VWAP (shares the long's bands). // v2.4.1b: extension is a RECENT-WINDOW condition, not a same-bar condition. // ext_leg_sigma = best high-based σ over the last back_ext_lb bars (the extension leg). // ext_leg_high = the leg's highest high — this becomes the frozen failed high on arm, // so the stop anchors to the ACTUAL top of the leg even when the rejection candle // prints a few bars after it. ext_leg_sigma = ta.highest(ext_sigma_hi, back_ext_lb) ext_leg_high = ta.highest(high, back_ext_lb) extended_above = ext_leg_sigma >= backside_ext_min recent_high = ta.highest(high, pivot_lookback) rejection_bar = high >= recent_high[1] and close < open and close < (high - (high - low) * 0.4) // Confirmation ladder (each tier stacks onto the one above): // MA1 rolling = fast MA losing slope (ma5 < ma5[2]) // MA1 guilty = fast MA broke a prior swing low (breaks prior N-bar low) // MA2 + 1SD = 20MA rolling AND close back inside +1σ ma1_rolling = ma5 < ma5[2] ma1_guilty = close < ta.lowest(low, pivot_lookback)[1] // broke prior swing low ma2_rolling = ma20 < ma20[2] back_inside_1 = close < upper_band2 // re-entered inside +1σ // ----------------------------------------------------------------------------- // v2.4.1 ARM / TRIGGER SPLIT. // The old v2.4 logic demanded extension + rejection + MA curl + (tier extras) on ONE // bar. But rejection_bar requires the entry bar to itself print a new 5-bar high — so // by the time the MA had curled and lows broke (the trade as actually played), the // condition was structurally false. Deeper tiers fired LESS, not later. Same defect // shape as the VCET direction-lock: state captured at the wrong moment. // // Now: the extended rejection bar ARMS a latch and freezes the failed high + the // extension σ at that moment. The trade FIRES when the trigger tier confirms within // the arm window. The latch dies on expiry or if the failed high is taken out (a new // high over the frozen level = the top is not in; a fresh rejection can re-arm). // One-shot: firing consumes the latch. Stop = frozen failed high + buffer, NOT the // rolling 5-bar high at trigger time — the risk anchors to the top that failed. // ----------------------------------------------------------------------------- back_rvol_ok = not back_req_rvol or rvol >= rvol_threshold // Warmup: enough session bars for a meaningful σ AND for the leg lookback to sit // entirely inside today (never reaches yesterday's prints). back_warm_ok = sess_n >= math.max(back_min_bars, back_ext_lb) back_arm_raw = enable_backside and (not rth_only or rth_now) and back_warm_ok and extended_above and rejection_bar and back_rvol_ok no_chase_warn = back_arm_raw and back_no_chase and front_regime back_arm_sig = back_arm_raw and not (back_no_chase and front_regime) // Session diagnostics: peak extension seen today + bars since the last rejection bar. // These exist so the table can answer "which gate is blocking?" without guesswork. var float bk_sess_peak_sigma = 0.0 var int bk_last_rej_bar = na if anchor_change bk_sess_peak_sigma := 0.0 bk_last_rej_bar := na if not rth_only or rth_now bk_sess_peak_sigma := math.max(bk_sess_peak_sigma, ext_sigma_hi) if rejection_bar bk_last_rej_bar := bar_index var bool bk_armed = false var float bk_failed_high = na var float bk_arm_sigma = na var int bk_arm_bar = na // LEAN v1.2: an armed backside must not survive to fire next morning against a // stale failed high (the risk anchor would be yesterday's price). if anchor_change bk_armed := false bk_failed_high := na bk_arm_sigma := na // LEAN v1.0: capture pre-bar state so the FIRST arm of a cycle is distinguishable // from a silent re-arm (re-arms refresh the latch but print nothing). bool bk_was_armed = bk_armed bool bk_expired = false bool bk_invalid = false // Re-arm on every qualifying rejection (a later rejection = fresher failed high). if back_arm_sig bk_armed := true bk_failed_high := ext_leg_high // the extension LEG's top = the failed high bk_arm_sigma := ext_leg_sigma // the leg's best σ (grades off the actual top) bk_arm_bar := bar_index bk_arm_first = back_arm_sig and not bk_was_armed // Latch death — same conditions as v2.6.9, now CLASSIFIED for the × marker: // level taken out = INVALIDATED (top is not in) | window ran out = EXPIRED. if bk_armed and not back_arm_sig if high > bk_failed_high bk_armed := false bk_invalid := true else if bar_index - bk_arm_bar > back_arm_window bk_armed := false bk_expired := true // Trigger ladder, evaluated WHILE ARMED (same bar as arm allowed — if the rejection // bar itself already shows the curl, the old v2.4 near-the-top fill still happens): aggr_trig = ma1_rolling mod_trig = aggr_trig and ma1_guilty consv_trig = mod_trig and ma2_rolling and back_inside_1 tier_trig = backside_arm_tier == "Aggressive" ? aggr_trig : backside_arm_tier == "Moderate" ? mod_trig : consv_trig // Trigger location floor: the close must still be extended - there has to be meat // left between entry and VWAP for "cover into VWAP" to be a trade. back_room_ok = back_trig_min <= 0.0 or ext_sigma >= back_trig_min // R:R floor at trigger (v2.4.2d): risk = frozen stop vs this close, reward = close vs // VWAP (the signature T2 cover). Under the floor, the trade does not exist. back_rsk_pre = (bk_failed_high + bk_stop_buf * atr_val) - close back_rwd_pre = close - vwap_val back_rr_ok = back_min_rr <= 0.0 or (back_rsk_pre > 0 and back_rwd_pre / back_rsk_pre >= back_min_rr) // v2.6.3: + fast_short_ok — redundant with the Aggressive curl trigger (ma5= 3.0 and ma1_guilty and rvol >= 2.0 and tod_late grade_B_back = backside_cand and bk_arm_sigma >= 2.0 and rvol >= 1.5 and not grade_A_back grade_C_back = backside_cand and not grade_A_back and not grade_B_back backside_grade = grade_A_back ? "A" : grade_B_back ? "B" : grade_C_back ? "C" : "—" backside_tier = backside_arm_tier == "Aggressive" ? "aggr" : backside_arm_tier == "Moderate" ? "mod" : "consv" backside_entry = backside_cand and (not require_grade or backside_grade != "—") // One-shot: the fire consumes the latch. if backside_entry bk_armed := false // Entry = signal close; STOP = above the FROZEN failed high + buffer. // Ladder: T1 = +1σ (upper_band2), T2 = VWAP, runner toward −1σ (lower_band2). backside_entry_price = backside_entry ? close : na backside_stop = backside_entry ? (bk_failed_high + bk_stop_buf * atr_val) : na backside_t1 = backside_entry ? upper_band2 : na // +1σ backside_t2 = backside_entry ? vwap_val : na // VWAP backside_target = backside_entry ? vwap_val : na // signature "cover into VWAP" (T2) for the table // ============================================================================= // PLAY 3B — RUBBER BAND (LONG) ENTRY LOGIC — full mirror of the backside machine. // ============================================================================= ext_sigma_lo = stdev_val > 0 ? (low - vwap_val) / stdev_val : 0.0 ext_leg_sig_dn = ta.lowest(ext_sigma_lo, back_ext_lb) // most NEGATIVE σ of the leg ext_leg_low = ta.lowest(low, back_ext_lb) // the leg's capitulation low extended_below = ext_leg_sig_dn <= -backside_ext_min recent_low_rb = ta.lowest(low, pivot_lookback) // Capitulation-hold bar: prints at/under a new 5-bar low, closes UP, in the upper 60%. hold_bar = low <= recent_low_rb[1] and close > open and close > (low + (high - low) * 0.4) // Trigger ladder (mirror): MA1 curling UP / broke prior swing HIGH / MA2 up + reclaimed -1σ ma1_curl_up = ma5 > ma5[2] ma1_guilty_up = close > recent_high[1] // broke prior swing high ma2_up = ma20 > ma20[2] back_inside_dn = close > lower_band2 // reclaimed -1σ // Session peak-low diagnostic (mirror of peak hi-σ), RTH-gated like the hi side. var float rb_sess_peak_lo = 0.0 if anchor_change rb_sess_peak_lo := 0.0 if not rth_only or rth_now rb_sess_peak_lo := math.min(rb_sess_peak_lo, ext_sigma_lo) // LEG STRUCTURE COUNTER (v2.6.2): quantifies the decline's legs while below VWAP. // Leg boundary = a close back above the 5MA (bounce) followed by a LOWER low (new // leg). Reset the moment price closes above VWAP (the decline is over). rb_legs = 1 // on the first push down; each bounce->lower-low sequence increments it. var int rb_legs = 0 var float rb_prevlow = na var float rb_curlow = na var bool rb_bounce = false if close > vwap_val rb_legs := 0 rb_prevlow := na rb_curlow := na rb_bounce := false else if na(rb_curlow) rb_curlow := low rb_legs := 1 if not rb_bounce rb_curlow := math.min(rb_curlow, low) if close > ma5 rb_bounce := true rb_prevlow := rb_curlow else if low < rb_prevlow rb_bounce := false rb_legs := rb_legs + 1 rb_curlow := low rb_legs_ok = rb_legs >= rb_min_legs // ARM: capitulation-hold while the leg is extended below. Freezes the leg LOW + leg σ. // No no-chase mirror here ON PURPOSE: the Rubber Band exists to fire on flush days — // a "suppress during down-regime" rule would suppress the play's entire habitat. rb_arm_sig = enable_rubber and (not rth_only or rth_now) and back_warm_ok and extended_below and rb_legs_ok and hold_bar var bool rb_armed = false var float rb_failed_low = na var float rb_arm_sigma = na var int rb_arm_bar = na // LEAN v1.2: mirror — clear the armed flush AND the leg counter at the bell, so // yesterday's two legs don't pre-satisfy today's exhaustion test. if anchor_change rb_armed := false rb_failed_low := na rb_arm_sigma := na rb_legs := 0 rb_curlow := na rb_bounce := false // LEAN v1.0: first-arm detection + classified latch death (mirror of the backside). bool rb_was_armed = rb_armed bool rb_expired = false bool rb_invalid = false if rb_arm_sig rb_armed := true rb_failed_low := ext_leg_low rb_arm_sigma := ext_leg_sig_dn rb_arm_bar := bar_index rb_arm_first = rb_arm_sig and not rb_was_armed if rb_armed and not rb_arm_sig if low < rb_failed_low rb_armed := false rb_invalid := true else if bar_index - rb_arm_bar > back_arm_window rb_armed := false rb_expired := true rb_aggr_trig = ma1_curl_up rb_mod_trig = rb_aggr_trig and ma1_guilty_up rb_consv_trig = rb_mod_trig and ma2_up and back_inside_dn rb_tier_trig = backside_arm_tier == "Aggressive" ? rb_aggr_trig : backside_arm_tier == "Moderate" ? rb_mod_trig : rb_consv_trig // Trigger location floor (mirror): the close must still be extended BELOW — entry // stays under T1 (-1σ) so "cover into VWAP" has room. rb_room_ok = back_trig_min <= 0.0 or ext_sigma <= -back_trig_min // R:R floor (mirror): reward = VWAP - close, risk = close - frozen stop. rb_rsk_pre = close - (rb_failed_low - bk_stop_buf * atr_val) rb_rwd_pre = vwap_val - close rb_rr_ok = back_min_rr <= 0.0 or (rb_rsk_pre > 0 and rb_rwd_pre / rb_rsk_pre >= back_min_rr) // v2.6.3: + fast_long_ok — redundant with the curl-up trigger on Slope mode, load- // bearing on "Price side"/"Both". rubber_cand_pre = rb_armed and rb_tier_trig and rb_room_ok and rb_rr_ok and sig_ok and fast_long_ok rubber_cand = rubber_cand_pre and pos_free grade_A_rb = rubber_cand and rb_arm_sigma <= -3.0 and ma1_guilty_up and rvol >= 2.0 and tod_late grade_B_rb = rubber_cand and rb_arm_sigma <= -2.0 and rvol >= 1.5 and not grade_A_rb grade_C_rb = rubber_cand and not grade_A_rb and not grade_B_rb rubber_grade = grade_A_rb ? "A" : grade_B_rb ? "B" : grade_C_rb ? "C" : "—" rubber_tier = backside_arm_tier == "Aggressive" ? "aggr" : backside_arm_tier == "Moderate" ? "mod" : "consv" rubber_entry = rubber_cand and (not require_grade or rubber_grade != "—") if rubber_entry rb_armed := false // Entry = trigger close; STOP under the FROZEN capitulation low. // Ladder: T1 = -1σ (30% off, →BE), T2 = VWAP (50%, →-1σ), 20% runner toward +1σ. rubber_entry_price = rubber_entry ? close : na rubber_stop = rubber_entry ? (rb_failed_low - bk_stop_buf * atr_val) : na rubber_target = rubber_entry ? vwap_val : na // signature cover into VWAP // ============================================================================= // SETUP_GRADE / PLAYBOOK_TYPE EMISSION (SMB classification) // ============================================================================= setup_grade = pullin_entry ? pullin_grade : trend_entry ? trend_grade : backside_entry ? backside_grade : pullin_s_entry ? pullin_s_grade : rubber_entry ? rubber_grade : "—" // 'vwap_pull_in_short' is a PROVISIONAL Pine-only label (locked taxonomy rule: no new // canonical slugs without registry validation). Do not journal it to AMS as canonical. // backside_long = Rubber Band, CANONICAL per the 2026-05-04 registry resolution. playbook_type = pullin_entry ? "vwap_pull_in" : trend_entry ? "trend_trade" : backside_entry ? "backside_scalp" : pullin_s_entry ? "vwap_pull_in_short" : rubber_entry ? "backside_long" : "—" active_entry = pullin_entry ? pullin_entry_price : trend_entry ? trend_entry_price : backside_entry ? backside_entry_price : pullin_s_entry ? pullin_s_entry_price : rubber_entry ? rubber_entry_price : na active_stop = pullin_entry ? pullin_stop : trend_entry ? trend_stop : backside_entry ? backside_stop : pullin_s_entry ? pullin_s_stop : rubber_entry ? rubber_stop : na active_target = pullin_entry ? pullin_target : trend_entry ? trend_target : backside_entry ? backside_target : pullin_s_entry ? pullin_s_target : rubber_entry ? rubber_target : na active_risk = math.abs(active_entry - active_stop) active_reward = math.abs(active_target - active_entry) active_rr = active_risk > 0 ? active_reward / active_risk : na base_risk_dollars = acct_daily_stop * risk_per_trade_pct / 100.0 grade_size_mult = not use_grade_sizing ? 1.0 : setup_grade == "A" ? size_mult_A : setup_grade == "B" ? size_mult_B : setup_grade == "C" ? size_mult_C : 0.0 trade_risk_dollars = base_risk_dollars * grade_size_mult plan_shares = (active_risk > 0 and trade_risk_dollars > 0) ? math.floor(trade_risk_dollars / active_risk) : na // LEAN v1.2 — TODAY's scoreboard state. Declared HERE (before the signal counter // below increments s_sigs) because Pine resolves identifiers in source order. var int s_wins = 0 var int s_losses = 0 var float s_rsum = 0.0 var int s_sigs = 0 // signals fired today (0 = quiet, not broken) var float last_entry = na var float last_stop = na var float last_tgt = na var float last_rr = na var float last_risk_d = na var float last_shares = na var string last_play = "—" // v2.6.2: the "last" rows are per-session too, so a new day never displays // yesterday's (or another symbol's) entry/stop/target. if anchor_change last_entry := na last_stop := na last_tgt := na last_rr := na last_risk_d := na last_shares := na last_play := "—" if pullin_entry or trend_entry or backside_entry or pullin_s_entry or rubber_entry s_sigs := s_sigs + 1 last_entry := active_entry last_stop := active_stop last_tgt := active_target last_rr := active_rr last_risk_d := trade_risk_dollars last_shares := plan_shares last_play := playbook_type // ============================================================================= // TRADE OUTCOME TRACKER — 30/50/20 LADDER with RATCHETS, size-weighted blended R. // ----------------------------------------------------------------------------- // Per open trade we freeze entry, initial stop, T1, T2, direction and the % splits. // Walk forward: book f1 at T1 (ratchet stop→BE), book f2 at T2 (ratchet stop→T1), // runner exits at whatever the (ratcheted) stop is when price returns to it. // Stop is checked FIRST each bar using the stop as it stood at bar open, so a fill // bar can't also stop its own runner. Blended R = Σ(leg fraction × leg R). // Win = blended R > 0. Trend play (no ladder) falls back to 100% at its single target. // One trade at a time (matches holding one position). // ============================================================================= new_signal = pullin_entry or trend_entry or backside_entry or pullin_s_entry or rubber_entry active_dir = (pullin_entry or trend_entry or rubber_entry) ? 1 : (backside_entry or pullin_s_entry) ? -1 : 0 // +1 long, −1 short // v2.6.7: opposite-trigger feeds for the reverse-play exit — the latch-free _pre // signals, so plays "seen but suppressed" during a trade can still close it. opp_long_trig = pullin_cand_pre or trend_cand_pre or rubber_cand_pre opp_short_trig = pullin_s_cand_pre or backside_cand_pre var float t_entry = na var float t_stop = na // ratchets over the trade's life var float t_t1 = na var float t_t2 = na var float t_risk = na var float t_f1 = na var float t_f2 = na var float t_fr = na var int t_dir = 0 var int t_bar = na var bool t_fill1 = false var bool t_fill2 = false var float t_booked = 0.0 // R booked from filled legs so far var int o_wins = 0 var int o_losses = 0 var float o_rsum = 0.0 // sum of blended R over resolved trades // LEAN v1.1: TODAY's tally (session-reset) — feeds the badge scoreboard so the // evidence is about the day in front of you, not the whole loaded history. // (s_wins / s_losses / s_rsum / s_sigs are declared ABOVE the "last …" block — // Pine needs them declared before the signal counter increments them.) // v2.6.2: flatten on session change BEFORE evaluating - no position survives the bell. if anchor_change in_trade := false t_fill1 := false t_fill2 := false t_booked := 0.0 s_wins := 0 s_losses := 0 s_rsum := 0.0 s_sigs := 0 // v2.4.3: the tracker ALWAYS runs (the one-position latch depends on in_trade); // show_outcomes now gates only the W/L labels, not the state machine. if barstate.isconfirmed if new_signal and not in_trade and active_dir != 0 and not na(active_stop) in_trade := true t_entry := active_entry t_stop := active_stop t_dir := active_dir t_bar := bar_index t_fill1 := false t_fill2 := false t_booked := 0.0 // Ladder levels + splits per play bool is_longlad = pullin_entry or trend_entry // both longs ride T1 +2σ / T2 +4σ bool is_back = backside_entry bool is_ps = pullin_s_entry bool is_rb = rubber_entry // long, but rides the MIRROR ladder up t_t1 := is_longlad ? upper_band3 : is_back ? upper_band2 : is_ps ? lower_band3 : is_rb ? lower_band2 : active_target // +2σ / +1σ / -2σ / -1σ t_t2 := is_longlad ? upper_band5 : is_back ? vwap_val : is_ps ? lower_band5 : is_rb ? vwap_val : active_target // +4σ / VWAP / -4σ / VWAP t_f1 := pl_t1_pct / 100.0 t_f2 := pl_t2_pct / 100.0 t_fr := pl_runner_pct / 100.0 t_risk := math.abs(t_entry - t_stop) else if in_trade and bar_index > t_bar float stop_at_open = t_stop bool resolved = false // 1) STOP first, using the stop as it stood entering this bar. bool hit_stop = t_dir == 1 ? low <= stop_at_open : high >= stop_at_open if hit_stop and t_risk > 0 float rem = t_fill2 ? t_fr : t_fill1 ? (t_f2 + t_fr) : 1.0 float exitR = t_dir == 1 ? (stop_at_open - t_entry) / t_risk : (t_entry - stop_at_open) / t_risk float blended = t_booked + rem * exitR bool won = blended > 0 if show_outcomes // v2.6.9: named + priced exit (was a bare tiny W/L tag — unfindable on multi-day charts) label.new(bar_index, won ? high : low, text=(won ? "W " : "L ") + f_sr(blended) + " ·STOP " + f_px(stop_at_open), yloc=yloc.price, style=won ? label.style_label_down : label.style_label_up, color=won ? color.new(c_good, 0) : color.new(c_bad, 0), textcolor=c_text, size=size.small) if won o_wins := o_wins + 1 s_wins := s_wins + 1 else o_losses := o_losses + 1 s_losses := s_losses + 1 o_rsum := o_rsum + blended s_rsum := s_rsum + blended in_trade := false resolved := true // 2) Fills (only if not stopped this bar). Ratchets take effect next bar. if not resolved and t_risk > 0 if not t_fill1 bool hitT1 = t_dir == 1 ? high >= t_t1 : low <= t_t1 if hitT1 float legR = t_dir == 1 ? (t_t1 - t_entry) / t_risk : (t_entry - t_t1) / t_risk t_booked := t_booked + t_f1 * legR t_fill1 := true if runner_be t_stop := t_entry // → break-even if t_fill1 and not t_fill2 bool hitT2 = t_dir == 1 ? high >= t_t2 : low <= t_t2 if hitT2 float legR = t_dir == 1 ? (t_t2 - t_entry) / t_risk : (t_entry - t_t2) / t_risk t_booked := t_booked + t_f2 * legR t_fill2 := true if runner_be t_stop := t_t1 // → lock T1 level // If there is NO runner (f_runner == 0) and both legs filled, close it out at T2. if t_fill1 and t_fill2 and t_fr <= 0.0 bool won = t_booked > 0 if show_outcomes label.new(bar_index, won ? high : low, text=(won ? "W " : "L ") + f_sr(t_booked) + " ·T2", yloc=yloc.price, style=won ? label.style_label_down : label.style_label_up, color=won ? color.new(c_good, 0) : color.new(c_bad, 0), textcolor=c_text, size=size.small) if won o_wins := o_wins + 1 s_wins := s_wins + 1 else o_losses := o_losses + 1 s_losses := s_losses + 1 o_rsum := o_rsum + t_booked s_rsum := s_rsum + t_booked in_trade := false // 3) v2.6.7 REVERSE-PLAY EXIT — an opposite play triggered this bar: the // market said the trade is over. Close the remainder at this bar's close. // STOP already had first claim above; fills booked this bar stay booked. if in_trade and not resolved and exit_on_opp and t_risk > 0 and ((t_dir == 1 and opp_short_trig) or (t_dir == -1 and opp_long_trig)) float rem_o = t_fill2 ? t_fr : t_fill1 ? (t_f2 + t_fr) : 1.0 float exitR_o = t_dir == 1 ? (close - t_entry) / t_risk : (t_entry - close) / t_risk float blend_o = t_booked + rem_o * exitR_o bool won_o = blend_o > 0 if show_outcomes label.new(bar_index, won_o ? high : low, text=(won_o ? "W " : "L ") + f_sr(blend_o) + " ·OPP " + f_px(close), yloc=yloc.price, style=won_o ? label.style_label_down : label.style_label_up, color=won_o ? color.new(c_good, 0) : color.new(c_bad, 0), textcolor=c_text, size=size.small) if won_o o_wins := o_wins + 1 s_wins := s_wins + 1 else o_losses := o_losses + 1 s_losses := s_losses + 1 o_rsum := o_rsum + blend_o s_rsum := s_rsum + blend_o in_trade := false alert(j_head + ',"evt":"opp_exit","dir":' + str.tostring(t_dir) + ',"px":' + f_num(close) + ',"blended_r":' + f_num(blend_o) + '}', alert.freq_once_per_bar_close) // ============================================================================= // PLOTS — VWAP, Bands, Clouds, MA Stack, Signal Markers // ============================================================================= // VWAP — solid, bold 3 (spec). p_vwap = plot((show_vwap or show_bands or show_band_clouds) ? vwap_val : na, "VWAP", color=color.new(c_vwap, 0), linewidth=vwap_width) band_plot_on = show_bands or show_band_clouds c_anchor = color.new(color.gray, 100) // ----------------------------------------------------------------------------- // BAND LINES + FILL ANCHORS (v1.6.2 of J3P plot-budget rework, unchanged). // ----------------------------------------------------------------------------- p_ub1 = plot(band_plot_on ? upper_band1 : na, "UB1 anchor (hidden)", color=c_anchor, editable=false, display=display.pane) p_lb1 = plot(band_plot_on ? lower_band1 : na, "LB1 anchor (hidden)", color=c_anchor, editable=false, display=display.pane) plot(show_bands ? f_dashseries(upper_band1) : na, "UB1 (+0.5σ)", color=color.new(c_band1, band_transp), style=plot.style_linebr, linewidth=band_width) plot(show_bands ? f_dashseries(lower_band1) : na, "LB1 (-0.5σ)", color=color.new(c_band1, band_transp), style=plot.style_linebr, linewidth=band_width) p_ub2 = plot(band_plot_on ? upper_band2 : na, "UB2 (+1σ)", color=show_bands ? color.new(c_band2, band_transp) : color.new(c_band2, 100), style=plot.style_circles, linewidth=band_width) p_lb2 = plot(band_plot_on ? lower_band2 : na, "LB2 (-1σ)", color=show_bands ? color.new(c_band2, band_transp) : color.new(c_band2, 100), style=plot.style_circles, linewidth=band_width) p_ub3 = plot(band_plot_on ? upper_band3 : na, "UB3 (+2σ)", color=show_bands ? color.new(c_band3, band_transp) : color.new(c_band3, 100), linewidth=band3_width) p_lb3 = plot(band_plot_on ? lower_band3 : na, "LB3 (-2σ)", color=show_bands ? color.new(c_band3, band_transp) : color.new(c_band3, 100), linewidth=band3_width) // Band 5 (±4σ) — not in the color spec. Long's T2 target and its mirror. plot(show_bands ? upper_band5 : na, "UB5 (+4σ tgt)", color=color.new(c_ub5, 0), style=plot.style_circles) plot(show_bands ? lower_band5 : na, "LB5 (-4σ)", color=color.new(c_lb5, 0), style=plot.style_circles) fill(p_vwap, p_ub1, color=show_band_clouds ? color.new(c_zone1, zone1_transp) : na, title="Up Zone 1") fill(p_vwap, p_lb1, color=show_band_clouds ? color.new(c_zone1, zone1_transp) : na, title="Down Zone 1") fill(p_ub1, p_ub2, color=show_band_clouds ? color.new(c_zone2, zone2_transp) : na, title="Up Zone 2") fill(p_lb1, p_lb2, color=show_band_clouds ? color.new(c_zone2, zone2_transp) : na, title="Down Zone 2") fill(p_ub2, p_ub3, color=show_band_clouds ? color.new(c_zone3, zone3_transp) : na, title="Up Zone 3") fill(p_lb2, p_lb3, color=show_band_clouds ? color.new(c_zone3, zone3_transp) : na, title="Down Zone 3") plot(show_ma_stack ? f_dash(ma5) : na, "MA Fast (5 DMA)", color=color.new(c_ma_fast, 0), style=plot.style_linebr, linewidth=1) plot(show_ma_stack ? f_dash(ma20) : na, "MA Mid (MA 1)", color=color.new(c_ma_mid, 0), style=plot.style_linebr, linewidth=1) plot(show_ma_stack ? f_dash(ma50) : na, "MA Slow (MA 2)", color=color.new(c_ma_slow, 0), style=plot.style_linebr, linewidth=1) // ----------------------------------------------------------------------------- // SIGNAL MARKERS — v2.6.2: LABELS, not plotshapes (labels don't count vs the 64 cap). // ----------------------------------------------------------------------------- bgcolor(show_regime and regime_est and tf_ok ? color.new(#089981, power_regime ? 88 : 94) : na, title="Trend regime (deeper = power trend)") // ----------------------------------------------------------------------------- // LEAN v1.0 MARKER DISCIPLINE. // Entry labels: unchanged (hierarchy #1 + #3 — the trigger and its grade). // Arming dots: ONE per setup cycle, tooltip = play + missing confirmation, handle // kept so the dot is DELETED when the setup dies. Re-arms refresh silently. // NO CHASE: once per warning cycle (arm-window cooldown), reason in the tooltip. // Latch deaths: one tiny × — tooltip distinguishes EXPIRED vs INVALIDATED. // pb-held narration dots + pull-in/squeeze expiry ×: Debug view only. // ----------------------------------------------------------------------------- var label bk_dot = na var label rb_dot = na var label pl_dot = na var label ps_dot = na var int nc_last = na // LEAN v1.1 — follow-through verification state (grade-my-own-calls). var int nc_vbar = na var float nc_vpx = na var int pb_vbar = na var float pb_vpx = na // ta.* must be evaluated on EVERY bar, never inside a conditional branch — inside an // `if` it silently returns stale values. Hoisted here so the ✓/✗ check reads a series // that has been maintained continuously. float hi_recent = ta.highest(high, verify_bars) if anchor_change nc_vbar := na pb_vbar := na // The confirmation each backside/rubber-band tier is still waiting for (tooltip text). string bk_need = backside_arm_tier == "Aggressive" ? "5-MA curl DOWN" : backside_arm_tier == "Moderate" ? "5-MA curl down + break of prior swing low" : "curl + swing-low break + 20-MA rolling + close back inside +1σ" string rb_need = backside_arm_tier == "Aggressive" ? "5-MA curl UP" : backside_arm_tier == "Moderate" ? "5-MA curl up + break of prior swing high" : "curl + swing-high break + 20-MA turning up + close back above −1σ" if show_signal_marks // ---- ENTRIES (unchanged from v2.6.9) ---- if pullin_entry label.new(bar_index, low, text="PULL-IN " + pullin_grade, yloc=yloc.belowbar, color=color.new(c_pullin_marker,0), textcolor=color.black, style=label.style_label_up, size=size.small) if trend_entry label.new(bar_index, low, text="TREND " + trend_grade, yloc=yloc.belowbar, color=color.new(c_trend_marker,0), textcolor=color.black, style=label.style_label_up, size=size.small) if rubber_entry label.new(bar_index, low, text="RUBBER BAND " + rubber_grade, yloc=yloc.belowbar, color=color.new(c_rb_marker,0), textcolor=color.black, style=label.style_label_up, size=size.small) if backside_entry label.new(bar_index, high, text="BACKSIDE " + backside_grade, yloc=yloc.abovebar, color=color.new(c_back_marker,0), textcolor=color.white, style=label.style_label_down, size=size.small) if pullin_s_entry label.new(bar_index, high, text="VWAP FAIL " + pullin_s_grade, yloc=yloc.abovebar, color=color.new(c_pulls_marker,0), textcolor=color.black, style=label.style_label_down, size=size.small) // ---- ARMING DOTS — first arm of the cycle only, with hover tooltips ---- if bk_arm_first label.delete(bk_dot) bk_dot := label.new(bar_index, high, yloc=yloc.abovebar, color=color.new(c_back_marker,55), style=label.style_circle, size=size.tiny, tooltip="BACKSIDE arming — rejection at +" + str.tostring(bk_arm_sigma, "#.#") + "σ, failed high " + f_px(bk_failed_high) + ".\nStill missing: " + bk_need + ".\nWindow: " + str.tostring(back_arm_window) + " bars. Dies if the failed high is taken out.") if rb_arm_first label.delete(rb_dot) rb_dot := label.new(bar_index, low, yloc=yloc.belowbar, color=color.new(c_rb_marker,55), style=label.style_circle, size=size.tiny, tooltip="RUBBER BAND arming — capitulation hold at " + str.tostring(rb_arm_sigma, "#.#") + "σ (legs: " + str.tostring(rb_legs) + "), flush low " + f_px(rb_failed_low) + ".\nStill missing: " + rb_need + ".\nWindow: " + str.tostring(back_arm_window) + " bars. Dies if the flush low breaks.") if pl_dip_new label.delete(pl_dot) pl_dot := label.new(bar_index, low, yloc=yloc.belowbar, color=color.new(c_pullin_marker,70), style=label.style_circle, size=size.tiny, tooltip="PULL-IN arming — dip below VWAP on a front-side day.\nStill missing: a close BACK ABOVE VWAP within " + str.tostring(max_shakeout_bars) + " bars, with the 5-MA rising.\nStays below that long = breakdown, not a shakeout.") if ps_sq_new label.delete(ps_dot) ps_dot := label.new(bar_index, high, yloc=yloc.abovebar, color=color.new(c_pulls_marker,70), style=label.style_circle, size=size.tiny, tooltip="VWAP FAIL arming — squeeze above VWAP on a back-side day.\nStill missing: a close BACK BELOW VWAP within " + str.tostring(max_shakeout_bars) + " bars, with the 5-MA falling.\nHolds above that long = reclaim, not a squeeze.") // ---- DOT CLEANUP + LATCH-DEATH MARKERS (hierarchy #7 — one per event) ---- if bk_expired or bk_invalid label.delete(bk_dot) label.new(bar_index, high, text="×", yloc=yloc.abovebar, color=color.new(color.gray,60), textcolor=chart.fg_color, style=label.style_label_down, size=size.tiny, tooltip=bk_invalid ? "BACKSIDE SETUP INVALIDATED — the failed high was taken out (top is not in). A fresh rejection can re-arm." : "BACKSIDE SETUP EXPIRED — no confirmation within " + str.tostring(back_arm_window) + " bars.") if rb_expired or rb_invalid label.delete(rb_dot) label.new(bar_index, low, text="×", yloc=yloc.belowbar, color=color.new(color.gray,60), textcolor=chart.fg_color, style=label.style_label_up, size=size.tiny, tooltip=rb_invalid ? "RUBBER BAND SETUP INVALIDATED — the flush low broke (capitulation failed). A fresh hold can re-arm." : "RUBBER BAND SETUP EXPIRED — no confirmation within " + str.tostring(back_arm_window) + " bars.") if pl_state == 0 and nz(pl_state[1]) == 1 label.delete(pl_dot) // dip resolved (reclaim) — dot's job is done if ps_state == 0 and nz(ps_state[1]) == 1 label.delete(ps_dot) // squeeze resolved — dot's job is done if pl_dip_expired label.delete(pl_dot) if debug_mode label.new(bar_index, low, text="×", yloc=yloc.belowbar, color=color.new(color.gray,60), textcolor=chart.fg_color, style=label.style_label_up, size=size.tiny, tooltip="PULL-IN SETUP EXPIRED — below VWAP more than " + str.tostring(max_shakeout_bars) + " bars: base/breakdown, not a shakeout.") if ps_sq_expired label.delete(ps_dot) if debug_mode label.new(bar_index, high, text="×", yloc=yloc.abovebar, color=color.new(color.gray,60), textcolor=chart.fg_color, style=label.style_label_down, size=size.tiny, tooltip="VWAP FAIL SETUP EXPIRED — above VWAP more than " + str.tostring(max_shakeout_bars) + " bars: reclaim, not a squeeze.") // ---- PULLBACK HELD — one dot per resumption (a one-shot event, not spam). // LEAN v1.1: back in the Lean view by request — this is the trend-trust builder, // and the ✓/✗ that follows it is the evidence. if pb_held_note label.new(bar_index, low, yloc=yloc.belowbar, color=color.new(c_trend_marker,35), style=label.style_circle, size=size.tiny, tooltip="Pullback HELD — the dip into the trend zone just resumed. The trend is intact.\nWatch for the ✓/✗ " + str.tostring(verify_bars) + " bars from now: did holding actually pay?") pb_vbar := bar_index pb_vpx := high // ---- NO CHASE — once per warning cycle, reason in the tooltip ---- if no_chase_warn and (na(nc_last) or bar_index - nc_last >= back_arm_window) nc_last := bar_index nc_vbar := bar_index nc_vpx := close label.new(bar_index, high, text="NO CHASE", yloc=yloc.abovebar, color=color.new(c_warn,20), textcolor=color.black, style=label.style_label_down, size=size.tiny, tooltip="Extended +" + str.tostring(ext_leg_sigma, "#.#") + "σ but the front-side trend is STILL ACTIVE — no short, no adds.\nBackside is for when the front side is over. This warning never creates an entry.\nWatch for the ✓/✗ " + str.tostring(verify_bars) + " bars from now: did the guard save you?") if trend_break label.new(bar_index, high, text="TREND BREAK", yloc=yloc.abovebar, color=color.new(c_trend_marker,0), textcolor=color.black, style=label.style_label_down, size=size.small, tooltip="Established trend regime lost VWAP (or decayed). Handoff moment: the Pull-In machine arms on the reclaim; VWAP Fail starts watching.") // ---- FOLLOW-THROUGH ✓/✗ — the chart grades its own calls, honest both ways ---- if show_verify and not na(nc_vbar) and bar_index - nc_vbar >= verify_bars bool nc_right = close > nc_vpx label.new(bar_index, high, text=nc_right ? "✓" : "✗", yloc=yloc.abovebar, style=label.style_none, textcolor=nc_right ? color.new(#089981, 0) : color.new(color.gray, 30), size=size.normal, tooltip=nc_right ? "NO CHASE VERIFIED — price is HIGHER than at the warning (" + f_px(nc_vpx) + "). The short you didn't take was a loser. The guard paid." : "NO CHASE aged badly — the trend cracked within " + str.tostring(verify_bars) + " bars. The guard cost a fade this time. Both get counted.") nc_vbar := na if show_verify and not na(pb_vbar) and bar_index - pb_vbar >= verify_bars bool pb_right = hi_recent > pb_vpx label.new(bar_index, low, text=pb_right ? "✓" : "✗", yloc=yloc.belowbar, style=label.style_none, textcolor=pb_right ? color.new(#089981, 0) : color.new(color.gray, 30), size=size.normal, tooltip=pb_right ? "PULLBACK-HOLD VERIFIED — the trend made a NEW HIGH after the hold (above " + f_px(pb_vpx) + "). Holding the trend paid." : "Pullback-hold did NOT follow through — no new high within " + str.tostring(verify_bars) + " bars. Both get counted.") pb_vbar := na // ----------------------------------------------------------------------------- // FROZEN LADDER HANDLES + CROSS-PLAY CLEANUP (v2.5.1). // One trade at a time means ONE plan on screen. Every play's annotation handles are // declared here; on ANY new signal, ALL plays' ladders are wiped before the firing // play redraws its own. Previously a stale backside ladder could sit next to a fresh // trend ladder and the chart read as two simultaneous plans. // (line/label.delete on an already-deleted or na id is a no-op — safe.) // ----------------------------------------------------------------------------- var line pl_e = na var line pl_s = na var line pl_t1 = na var line pl_t2 = na var label pl_elab = na var label pl_slab = na var label pl_t1lab = na var label pl_t2lab = na var line bk_e = na var line bk_s = na var line bk_t1 = na var line bk_t2 = na var label bk_elab = na var label bk_slab = na var label bk_t1lab = na var label bk_t2lab = na var line ps_e = na var line ps_s = na var line ps_t1 = na var line ps_t2 = na var label ps_elab = na var label ps_slab = na var label ps_t1lab = na var label ps_t2lab = na var line rb_e = na var line rb_s = na var line rb_t1 = na var line rb_t2 = na var label rb_elab = na var label rb_slab = na var label rb_t1lab = na var label rb_t2lab = na if show_frozen and new_signal line.delete(pl_e), line.delete(pl_s), line.delete(pl_t1), line.delete(pl_t2) label.delete(pl_elab), label.delete(pl_slab), label.delete(pl_t1lab), label.delete(pl_t2lab) line.delete(bk_e), line.delete(bk_s), line.delete(bk_t1), line.delete(bk_t2) label.delete(bk_elab), label.delete(bk_slab), label.delete(bk_t1lab), label.delete(bk_t2lab) line.delete(ps_e), line.delete(ps_s), line.delete(ps_t1), line.delete(ps_t2) label.delete(ps_elab), label.delete(ps_slab), label.delete(ps_t1lab), label.delete(ps_t2lab) line.delete(rb_e), line.delete(rb_s), line.delete(rb_t1), line.delete(rb_t2) label.delete(rb_elab), label.delete(rb_slab), label.delete(rb_t1lab), label.delete(rb_t2lab) // ----------------------------------------------------------------------------- // LONG PULL-IN — FROZEN 30/50/20 ladder with ratchet annotations. // entry @ VWAP recapture | stop below shakeout low (→BE after T1) // T1 +2σ (30% off) | T2 +4σ (50% off) | 20% runner (stop→+2σ after T2) // ----------------------------------------------------------------------------- if show_frozen and (pullin_entry or trend_entry) line.delete(pl_e) line.delete(pl_s) line.delete(pl_t1) line.delete(pl_t2) label.delete(pl_elab) label.delete(pl_slab) label.delete(pl_t1lab) label.delete(pl_t2lab) float fE = pullin_entry ? pullin_entry_price : trend_entry_price float fS = pullin_entry ? pullin_stop : trend_stop float fT1 = upper_band3 // +2σ float fT2 = upper_band5 // +4σ int px2 = bar_index + anno_len pl_e := line.new(bar_index, fE, px2, fE, color=color.new(c_long_entry,0), style=line.style_solid, width=2) pl_s := line.new(bar_index, fS, px2, fS, color=color.new(c_stop_line,0), style=line.style_dashed, width=1) pl_t1 := line.new(bar_index, fT1, px2, fT1, color=color.new(c_target_line,0), style=line.style_dashed, width=2) pl_t2 := line.new(bar_index, fT2, px2, fT2, color=color.new(c_runner_line,45), style=line.style_dotted, width=1) float fRR1 = (fE - fS) != 0 ? (fT1 - fE) / (fE - fS) : na string t1txt = "T1 +2σ · " + str.tostring(pl_t1_pct) + "% off · R:R " + str.tostring(fRR1, "#.##") + (runner_be ? " · stop→BE" : "") string t2txt = "T2 +4σ · " + str.tostring(pl_t2_pct) + "% off · " + str.tostring(pl_runner_pct) + "% runner" + (runner_be ? " · stop→+2σ" : "") string fEtxt = pullin_entry ? "LONG entry @ VWAP recapture" : "LONG entry @ pullback resume" string fStxt = pullin_entry ? "stop · below shakeout low" : "stop · below pullback low" pl_elab := label.new(px2, fE, text=fEtxt + " · R:R(T1) " + str.tostring(fRR1, "#.##"), color=color.new(c_long_entry,0), textcolor=c_text, style=label.style_label_left, size=f_txt_size(label_txt_size)) pl_slab := label.new(px2, fS, text=fStxt + (runner_be ? " (→BE after T1)" : ""), color=color.new(c_stop_line,0), textcolor=c_text, style=label.style_label_left, size=f_txt_size(label_txt_size)) pl_t1lab := label.new(px2, fT1, text=t1txt, color=color.new(c_target_line,0), textcolor=c_text, style=label.style_label_left, size=f_txt_size(label_txt_size)) pl_t2lab := label.new(px2, fT2, text=t2txt, color=color.new(c_target_line,0), textcolor=c_text, style=label.style_label_left, size=f_txt_size(label_txt_size)) // ----------------------------------------------------------------------------- // BACKSIDE SHORT — FROZEN 30/50/20 mirror ladder with ratchet annotations. // entry (rejection) | stop above failed high (→BE after T1) // T1 +1σ (30% cover) | T2 VWAP (50% cover) | 20% runner toward −1σ (stop→+1σ after T2) // ----------------------------------------------------------------------------- if show_frozen and backside_entry line.delete(bk_e) line.delete(bk_s) line.delete(bk_t1) line.delete(bk_t2) label.delete(bk_elab) label.delete(bk_slab) label.delete(bk_t1lab) label.delete(bk_t2lab) float gE = backside_entry_price float gS = backside_stop // above failed high float gT1 = upper_band2 // +1σ float gT2 = vwap_val // VWAP int qx2 = bar_index + anno_len bk_e := line.new(bar_index, gE, qx2, gE, color=color.new(c_short_entry,0), style=line.style_solid, width=2) bk_s := line.new(bar_index, gS, qx2, gS, color=color.new(c_stop_line,0), style=line.style_dashed, width=1) bk_t1 := line.new(bar_index, gT1, qx2, gT1, color=color.new(c_target_line,0), style=line.style_dashed, width=2) bk_t2 := line.new(bar_index, gT2, qx2, gT2, color=color.new(c_runner_line,45),style=line.style_dotted, width=1) float gRR1 = (gS - gE) != 0 ? (gE - gT1) / (gS - gE) : na string bt1txt = "T1 +1σ · " + str.tostring(pl_t1_pct) + "% cover · R:R " + str.tostring(gRR1, "#.##") + (runner_be ? " · stop→BE" : "") string bt2txt = "T2 VWAP · " + str.tostring(pl_t2_pct) + "% cover · " + str.tostring(pl_runner_pct) + "% runner → −1σ" + (runner_be ? " · stop→+1σ" : "") bk_elab := label.new(qx2, gE, text="BACKSIDE short entry · R:R(T1) " + str.tostring(gRR1, "#.##"), color=color.new(c_short_entry,0), textcolor=c_text, style=label.style_label_left, size=f_txt_size(label_txt_size)) bk_slab := label.new(qx2, gS, text="stop · above failed high" + (runner_be ? " (→BE after T1)" : ""), color=color.new(c_stop_line,0), textcolor=c_text, style=label.style_label_left, size=f_txt_size(label_txt_size)) bk_t1lab := label.new(qx2, gT1, text=bt1txt, color=color.new(c_target_line,0), textcolor=c_text, style=label.style_label_left, size=f_txt_size(label_txt_size)) bk_t2lab := label.new(qx2, gT2, text=bt2txt, color=color.new(c_target_line,0), textcolor=c_text, style=label.style_label_left, size=f_txt_size(label_txt_size)) // ----------------------------------------------------------------------------- // VWAP FAIL SHORT — FROZEN 30/50/20 mirror ladder annotation. // entry @ VWAP loss | stop above squeeze high (→BE after T1) // T1 -2σ (30% cover) | T2 -4σ (50% cover) | 20% runner (stop→-2σ after T2) // ----------------------------------------------------------------------------- if show_frozen and pullin_s_entry line.delete(ps_e) line.delete(ps_s) line.delete(ps_t1) line.delete(ps_t2) label.delete(ps_elab) label.delete(ps_slab) label.delete(ps_t1lab) label.delete(ps_t2lab) float hE = pullin_s_entry_price float hS = pullin_s_stop float hT1 = lower_band3 // -2σ float hT2 = lower_band5 // -4σ int rx2 = bar_index + anno_len ps_e := line.new(bar_index, hE, rx2, hE, color=color.new(c_pulls_marker,0), style=line.style_solid, width=2) ps_s := line.new(bar_index, hS, rx2, hS, color=color.new(c_stop_line,0), style=line.style_dashed, width=1) ps_t1 := line.new(bar_index, hT1, rx2, hT1, color=color.new(c_target_line,0), style=line.style_dashed, width=2) ps_t2 := line.new(bar_index, hT2, rx2, hT2, color=color.new(c_runner_line,45), style=line.style_dotted, width=1) float hRR1 = (hS - hE) != 0 ? (hE - hT1) / (hS - hE) : na string ht1txt = "T1 -2σ · " + str.tostring(pl_t1_pct) + "% cover · R:R " + str.tostring(hRR1, "#.##") + (runner_be ? " · stop→BE" : "") string ht2txt = "T2 -4σ · " + str.tostring(pl_t2_pct) + "% cover · " + str.tostring(pl_runner_pct) + "% runner" + (runner_be ? " · stop→-2σ" : "") ps_elab := label.new(rx2, hE, text="SHORT entry @ VWAP fail · R:R(T1) " + str.tostring(hRR1, "#.##"), color=color.new(c_pulls_marker,0), textcolor=c_text, style=label.style_label_left, size=f_txt_size(label_txt_size)) ps_slab := label.new(rx2, hS, text="stop · above squeeze high" + (runner_be ? " (→BE after T1)" : ""), color=color.new(c_stop_line,0), textcolor=c_text, style=label.style_label_left, size=f_txt_size(label_txt_size)) ps_t1lab := label.new(rx2, hT1, text=ht1txt, color=color.new(c_target_line,0), textcolor=c_text, style=label.style_label_left, size=f_txt_size(label_txt_size)) ps_t2lab := label.new(rx2, hT2, text=ht2txt, color=color.new(c_target_line,0), textcolor=c_text, style=label.style_label_left, size=f_txt_size(label_txt_size)) // ----------------------------------------------------------------------------- // RUBBER BAND LONG — FROZEN 30/50/20 mirror ladder annotation. // entry (capitulation hold, MA curl) | stop under frozen failed low (→BE after T1) // T1 -1σ (30% off) | T2 VWAP (50% off) | 20% runner toward +1σ (stop→-1σ after T2) // ----------------------------------------------------------------------------- if show_frozen and rubber_entry line.delete(rb_e) line.delete(rb_s) line.delete(rb_t1) line.delete(rb_t2) label.delete(rb_elab) label.delete(rb_slab) label.delete(rb_t1lab) label.delete(rb_t2lab) float jE = rubber_entry_price float jS = rubber_stop float jT1 = lower_band2 // -1σ float jT2 = vwap_val // VWAP int jx2 = bar_index + anno_len rb_e := line.new(bar_index, jE, jx2, jE, color=color.new(c_rb_marker,0), style=line.style_solid, width=2) rb_s := line.new(bar_index, jS, jx2, jS, color=color.new(c_stop_line,0), style=line.style_dashed, width=1) rb_t1 := line.new(bar_index, jT1, jx2, jT1, color=color.new(c_target_line,0), style=line.style_dashed, width=2) rb_t2 := line.new(bar_index, jT2, jx2, jT2, color=color.new(c_runner_line,45),style=line.style_dotted, width=1) float jRR1 = (jE - jS) != 0 ? (jT1 - jE) / (jE - jS) : na string jt1txt = "T1 -1σ · " + str.tostring(pl_t1_pct) + "% off · R:R " + str.tostring(jRR1, "#.##") + (runner_be ? " · stop→BE" : "") string jt2txt = "T2 VWAP · " + str.tostring(pl_t2_pct) + "% off · " + str.tostring(pl_runner_pct) + "% runner → +1σ" + (runner_be ? " · stop→-1σ" : "") rb_elab := label.new(jx2, jE, text="RUBBER BAND long entry · R:R(T1) " + str.tostring(jRR1, "#.##"), color=color.new(c_rb_marker,0), textcolor=color.black, style=label.style_label_left, size=f_txt_size(label_txt_size)) rb_slab := label.new(jx2, jS, text="stop · under capitulation low" + (runner_be ? " (→BE after T1)" : ""), color=color.new(c_stop_line,0), textcolor=c_text, style=label.style_label_left, size=f_txt_size(label_txt_size)) rb_t1lab := label.new(jx2, jT1, text=jt1txt, color=color.new(c_target_line,0), textcolor=c_text, style=label.style_label_left, size=f_txt_size(label_txt_size)) rb_t2lab := label.new(jx2, jT2, text=jt2txt, color=color.new(c_target_line,0), textcolor=c_text, style=label.style_label_left, size=f_txt_size(label_txt_size)) // ============================================================================= // ALERTS — alert() with structured JSON (see header). One TV alert, webhook -> AMS. // evt values for slicing: entry | arm | no_chase | trend_break | pb_held // ============================================================================= sig_t1 = (pullin_entry or trend_entry) ? upper_band3 : backside_entry ? upper_band2 : pullin_s_entry ? lower_band3 : rubber_entry ? lower_band2 : na sig_t2 = (pullin_entry or trend_entry) ? upper_band5 : backside_entry ? vwap_val : pullin_s_entry ? lower_band5 : rubber_entry ? vwap_val : na tier_now = pullin_entry ? pullin_tier : trend_entry ? trend_tier : backside_entry ? backside_tier : pullin_s_entry ? pullin_s_tier : rubber_entry ? rubber_tier : "none" regime_now = power_regime ? "power" : regime_est ? "trend" : "none" // (j_head is declared up top with the helpers since v2.6.7 — evt values now: // entry | arm | no_chase | trend_break | pb_held | opp_exit) if new_signal alert(j_head + ',"evt":"entry","play":"' + playbook_type + '","grade":"' + setup_grade + '","tier":"' + tier_now + '","dir":' + str.tostring(active_dir) + ',"entry":' + f_num(active_entry) + ',"stop":' + f_num(active_stop) + ',"t1":' + f_num(sig_t1) + ',"t2":' + f_num(sig_t2) + ',"rr":' + f_num(active_rr) + ',"shares":' + f_num(plan_shares) + ',"risk_usd":' + f_num(trade_risk_dollars) + ',"rvol":' + f_num(rvol) + ',"ext_sigma":' + f_num(ext_sigma) + ',"vwap":' + f_num(vwap_val) + ',"regime":"' + regime_now + '"}', alert.freq_once_per_bar_close) if back_arm_sig alert(j_head + ',"evt":"arm","play":"backside_scalp","arm_sigma":' + f_num(bk_arm_sigma) + ',"failed_high":' + f_num(bk_failed_high) + ',"rvol":' + f_num(rvol) + ',"regime":"' + regime_now + '"}', alert.freq_once_per_bar_close) if rb_arm_sig alert(j_head + ',"evt":"arm","play":"backside_long","arm_sigma":' + f_num(rb_arm_sigma) + ',"failed_low":' + f_num(rb_failed_low) + ',"legs":' + str.tostring(rb_legs) + ',"rvol":' + f_num(rvol) + ',"regime":"' + regime_now + '"}', alert.freq_once_per_bar_close) if no_chase_warn alert(j_head + ',"evt":"no_chase","play":"backside_scalp","leg_sigma":' + f_num(ext_leg_sigma) + ',"regime":"' + regime_now + '"}', alert.freq_once_per_bar_close) if trend_break alert(j_head + ',"evt":"trend_break","vwap":' + f_num(vwap_val) + ',"close":' + f_num(close) + '}', alert.freq_once_per_bar_close) if pb_held_note alert(j_head + ',"evt":"pb_held","pb_low":' + f_num(tr_pb_low) + ',"zone":' + f_num(trend_pb_zone) + ',"regime":"' + regime_now + '"}', alert.freq_once_per_bar_close) // ============================================================================= // TABLE — Live state readout // ============================================================================= var table info = table.new(table_pos_str, 2, 19, bgcolor=color.new(c_table_bg, 0), frame_color=color.new(c_table_frame, 40), frame_width=1, border_color=color.new(c_table_frame, 60), border_width=1) if show_info_table and barstate.islast table.cell(info, 0, 0, "LEAN-J3P 1.0 · DEBUG", bgcolor=color.new(c_table_header, 0), text_color=c_good, text_size=f_txt_size(table_txt_size)) table.cell(info, 1, 0, "Value", bgcolor=color.new(c_table_header, 0), text_color=c_text, text_size=f_txt_size(table_txt_size)) table.cell(info, 0, 1, "Playbook", text_color=c_text, text_size=f_txt_size(table_txt_size)) string pb_txt = new_signal ? playbook_type : in_trade ? last_play + " · OPEN" : "—" table.cell(info, 1, 1, pb_txt, text_color=in_trade and not new_signal ? c_warn : c_text, text_size=f_txt_size(table_txt_size)) table.cell(info, 0, 2, "Grade", text_color=c_text, text_size=f_txt_size(table_txt_size)) table.cell(info, 1, 2, setup_grade, text_color=setup_grade == "A" ? c_good : setup_grade == "B" ? c_warn : c_neutral, text_size=f_txt_size(table_txt_size)) table.cell(info, 0, 3, "Tier", text_color=c_text, text_size=f_txt_size(table_txt_size)) string tier_bk = "bk ARMED " + str.tostring(back_arm_window - (bar_index - bk_arm_bar)) + "b" string tier_shk = "shakeout " + str.tostring(bar_index - pl_arm_barL) + "b" string tier_sqz = "squeeze " + str.tostring(bar_index - ps_arm_bar) + "b" string tier_pb = "pullback " + str.tostring(bar_index - tr_pb_bar) + "b" string tier_rb = "rb ARMED " + str.tostring(back_arm_window - (bar_index - rb_arm_bar)) + "b" string tier_txt = pullin_entry ? pullin_tier : trend_entry ? trend_tier : backside_entry ? backside_tier : pullin_s_entry ? pullin_s_tier : rubber_entry ? rubber_tier : bk_armed ? tier_bk : rb_armed ? tier_rb : tr_state == 1 ? tier_pb : pl_state == 1 ? tier_shk : ps_state == 1 and sess_n >= 10 ? tier_sqz : "—" table.cell(info, 1, 3, tier_txt, text_color=bk_armed and not backside_entry ? c_warn : c_text, text_size=f_txt_size(table_txt_size)) table.cell(info, 0, 4, "RVOL", text_color=c_text, text_size=f_txt_size(table_txt_size)) table.cell(info, 1, 4, str.tostring(rvol, "#.##"), text_color=c_text, text_size=f_txt_size(table_txt_size)) table.cell(info, 0, 5, "Ext (σ)", text_color=c_text, text_size=f_txt_size(table_txt_size)) table.cell(info, 1, 5, str.tostring(ext_sigma, "#.##") + " hi " + str.tostring(ext_sigma_hi, "#.##"), text_color=ext_sigma_hi >= 3 ? c_good : ext_sigma_hi >= 2 ? c_warn : c_neutral, text_size=f_txt_size(table_txt_size)) table.cell(info, 0, 6, "VWAP Slope", text_color=c_text, text_size=f_txt_size(table_txt_size)) table.cell(info, 1, 6, str.tostring(vwap_slope * 100, "#.###") + "%", text_color=c_text, text_size=f_txt_size(table_txt_size)) table.cell(info, 0, 7, "MA Stack", text_color=c_text, text_size=f_txt_size(table_txt_size)) // v2.6.3: show the fast-MA gate state right where the stack is read. // v2.6.6: readout mirrors the gate exactly -- head-N or window-N, whichever is live. string fast_style_txt = fast_slope_style == "Head (consecutive steps)" ? "head" + str.tostring(fast_head_steps) : "win" + str.tostring(fast_slope_lb) + "b" string fast_txt = not fast_gate_on ? "gate off" : (slope_up ? "5▲" : slope_dn ? "5▼" : "5–") + " " + fast_style_txt + " " + fast_gate_mode table.cell(info, 1, 7, (ma_stack_alignment ? "ALIGNED" : "MIXED") + " · " + fast_txt, text_color=ma_stack_alignment ? c_good : c_neutral, text_size=f_txt_size(table_txt_size)) table.cell(info, 0, 8, "MA Settings", text_color=c_text, text_size=f_txt_size(table_txt_size)) table.cell(info, 1, 8, ma_type + " " + str.tostring(ma_fast_len) + "/" + str.tostring(ma_mid_len) + "/" + str.tostring(ma_slow_len), text_color=c_text, text_size=f_txt_size(table_txt_size)) table.cell(info, 0, 9, "Entry (last)", text_color=c_text, text_size=f_txt_size(table_txt_size)) table.cell(info, 1, 9, not na(last_entry) ? str.tostring(last_entry, "#.##") : "—", text_color=c_text, text_size=f_txt_size(table_txt_size)) table.cell(info, 0, 10, "Stop (last)", text_color=c_text, text_size=f_txt_size(table_txt_size)) table.cell(info, 1, 10, not na(last_stop) ? str.tostring(last_stop, "#.##") : "—", text_color=c_stop_line, text_size=f_txt_size(table_txt_size)) table.cell(info, 0, 11, "Target (last)", text_color=c_text, text_size=f_txt_size(table_txt_size)) table.cell(info, 1, 11, not na(last_tgt) ? str.tostring(last_tgt, "#.##") : "—", text_color=c_target_line, text_size=f_txt_size(table_txt_size)) table.cell(info, 0, 12, "R:R (last)", text_color=c_text, text_size=f_txt_size(table_txt_size)) table.cell(info, 1, 12, not na(last_rr) ? str.tostring(last_rr, "#.##") + " (" + last_play + ")" : "—", text_color=na(last_rr) ? c_neutral : last_rr >= 2 ? c_good : last_rr >= 1 ? c_warn : color.orange, text_size=f_txt_size(table_txt_size)) table.cell(info, 0, 13, "Risk $ (last)", text_color=c_text, text_size=f_txt_size(table_txt_size)) table.cell(info, 1, 13, not na(last_risk_d) ? "$" + str.tostring(last_risk_d, "#.##") : "—", text_color=c_text, text_size=f_txt_size(table_txt_size)) table.cell(info, 0, 14, "Shares (last)", text_color=c_text, text_size=f_txt_size(table_txt_size)) table.cell(info, 1, 14, not na(last_shares) ? str.tostring(last_shares, "#") : "—", text_color=c_trend_marker, text_size=f_txt_size(table_txt_size)) // ---- Backside gate diagnostic: which arm gate is blocking, RIGHT NOW ---- string g_ext = (extended_above ? "EXT ok" : "EXT x") + " (" + str.tostring(ext_leg_sigma, "#.#") + ")" string g_rej = rejection_bar ? "REJ ok" : na(bk_last_rej_bar) ? "REJ x" : "REJ " + str.tostring(bar_index - bk_last_rej_bar) + "b ago" string g_rvl = back_rvol_ok ? "RVOL ok" : "RVOL x" string g_arm = not back_warm_ok ? "warmup" : bk_armed ? "ARMED" : "idle" table.cell(info, 0, 15, "BK gates", text_color=c_text, text_size=f_txt_size(table_txt_size)) table.cell(info, 1, 15, g_ext + " " + g_rej + " " + g_rvl + " | " + g_arm, text_color=bk_armed ? c_warn : extended_above ? c_text : c_neutral, text_size=f_txt_size(table_txt_size)) table.cell(info, 0, 16, "Peak hi-σ today", text_color=c_text, text_size=f_txt_size(table_txt_size)) table.cell(info, 1, 16, str.tostring(bk_sess_peak_sigma, "#.##") + " / need " + str.tostring(backside_ext_min, "#.#"), text_color=bk_sess_peak_sigma >= backside_ext_min ? c_good : c_bad, text_size=f_txt_size(table_txt_size)) string pl_side = (frontside_ok ? "FRONT ok" : "FRONT x") + " (" + str.tostring(sess_n > 0 ? 100.0 * sess_up / sess_n : 0.0, "#") + "%)" string pl_shk2 = pl_state == 1 ? "dip " + str.tostring(bar_index - pl_arm_barL) + "b" : pl_state == 2 ? "expired" : "above" table.cell(info, 0, 18, "PL gates", text_color=c_text, text_size=f_txt_size(table_txt_size)) table.cell(info, 1, 18, pl_side + " " + pl_shk2 + " G:" + pullin_grade, text_color=frontside_ok ? c_text : c_neutral, text_size=f_txt_size(table_txt_size)) table.cell(info, 0, 17, "Peak lo-σ today", text_color=c_text, text_size=f_txt_size(table_txt_size)) table.cell(info, 1, 17, str.tostring(rb_sess_peak_lo, "#.##") + " / need -" + str.tostring(backside_ext_min, "#.#") + " · legs " + str.tostring(rb_legs), text_color=rb_sess_peak_lo <= -backside_ext_min and rb_legs_ok ? c_good : c_bad, text_size=f_txt_size(table_txt_size)) // Outcome tally — live win-rate / blended avg-R from the laddered tracker above. var table otbl = table.new(outcome_pos_str, 2, 6, bgcolor=color.new(c_table_bg, 0), frame_color=color.new(c_table_frame, 40), frame_width=1, border_color=color.new(c_table_frame, 60), border_width=1) if show_outcomes and show_outcome_table and barstate.islast int o_total = o_wins + o_losses float o_wr = o_total > 0 ? 100.0 * o_wins / o_total : na float o_avgr = o_total > 0 ? o_rsum / o_total : na table.cell(otbl, 0, 0, "Outcomes", bgcolor=color.new(c_table_header, 0), text_color=c_text, text_size=f_txt_size(table_txt_size)) table.cell(otbl, 1, 0, in_trade ? "1 open" : "flat", bgcolor=color.new(c_table_header, 0), text_color=c_text, text_size=f_txt_size(table_txt_size)) table.cell(otbl, 0, 1, "Resolved", text_color=c_text, text_size=f_txt_size(table_txt_size)) table.cell(otbl, 1, 1, str.tostring(o_total), text_color=c_text, text_size=f_txt_size(table_txt_size)) table.cell(otbl, 0, 2, "Wins", text_color=c_text, text_size=f_txt_size(table_txt_size)) table.cell(otbl, 1, 2, str.tostring(o_wins), text_color=c_good, text_size=f_txt_size(table_txt_size)) table.cell(otbl, 0, 3, "Losses", text_color=c_text, text_size=f_txt_size(table_txt_size)) table.cell(otbl, 1, 3, str.tostring(o_losses), text_color=c_bad, text_size=f_txt_size(table_txt_size)) table.cell(otbl, 0, 4, "Win %", text_color=c_text, text_size=f_txt_size(table_txt_size)) table.cell(otbl, 1, 4, not na(o_wr) ? str.tostring(o_wr, "#.#") + "%" : "—", text_color=na(o_wr) ? c_neutral : o_wr >= 50 ? c_good : color.orange, text_size=f_txt_size(table_txt_size)) table.cell(otbl, 0, 5, "Avg R (blend)", text_color=c_text, text_size=f_txt_size(table_txt_size)) table.cell(otbl, 1, 5, not na(o_avgr) ? f_sr(o_avgr) : "—", text_color=na(o_avgr) ? c_neutral : o_avgr > 0 ? c_good : color.orange, text_size=f_txt_size(table_txt_size)) // ============================================================================= // LEAN v1.0 — REGIME BADGE (hierarchy #6: compact regime status). // Replaces the background tint as the default regime display. Reads the SAME // regime state the logic uses — nothing new is calculated here. Lean view only: // Debug's full table already reports regime, and the two would collide top-right. // POWER TREND — established regime whose leg tagged ≥ +2σ (deep conviction) // TREND UP — established front-side regime (NO CHASE is armed for shorts) // BACKSIDE — session has spent ≥ side-ratio% of bars BELOW VWAP (fade habitat) // NEUTRAL — none of the above (chop / undecided) // Second row appears only while the tracker holds an open trade. // ============================================================================= var table badge = table.new(badge_pos, 1, 3, bgcolor=color.new(c_table_bg, 100)) if barstate.islast table.clear(badge, 0, 0, 0, 2) if show_badge and tf_ok and not debug_mode bool backside_day = sess_n >= 10 and (sess_n - sess_up) * 100.0 >= side_min_pct * sess_n string b_txt = power_regime ? "POWER TREND" : regime_est ? "TREND UP" : backside_day ? "BACKSIDE" : "NEUTRAL" color b_bg = power_regime ? color.new(#089981, 0) : regime_est ? color.new(#089981, 25) : backside_day ? color.new(#E72406, 25) : color.new(color.gray, 40) table.cell(badge, 0, 0, " " + b_txt + " ", bgcolor=b_bg, text_color=color.white, text_size=f_txt_size(table_txt_size)) // LEAN v1.1 — today's honest tally: what the system's OWN rules scored today // (laddered, ratcheted, one trade at a time). Wins AND losses, always. // ALWAYS show a status row. Zero signals is a legitimate answer (the gates are // strict on purpose) — but a blank chart with no explanation reads as "broken", // so the badge says which it is, in words. string tally = s_sigs == 0 ? "No setup yet today" : str.tostring(s_sigs) + " signal" + (s_sigs == 1 ? "" : "s") + (s_wins + s_losses > 0 ? " · " + str.tostring(s_wins) + "W " + str.tostring(s_losses) + "L · " + f_sr(s_rsum) : " · working") table.cell(badge, 0, 1, tally, bgcolor=color.new(c_table_bg, 0), text_color=s_sigs == 0 ? c_neutral : s_rsum > 0 ? c_good : s_rsum < 0 ? color.orange : c_text, text_size=f_txt_size(table_txt_size)) if in_trade table.cell(badge, 0, 2, "OPEN · " + last_play, bgcolor=color.new(c_table_bg, 0), text_color=c_warn, text_size=f_txt_size(table_txt_size)) // ============================================================================= // TIMEFRAME NOTICE — so a blank pane reads as "gated", not "broken". // chart.fg_color keeps it legible on both light and dark themes. // ============================================================================= var table tftbl = table.new(position.top_center, 1, 1) if barstate.islast table.clear(tftbl, 0, 0) if show_tf_notice and i_show_tables and not tf_ok table.cell(tftbl, 0, 0, "J3P — intraday only · hidden above " + str.tostring(max_tf_min, "#.##") + "m", text_color=chart.fg_color, text_size=size.small)