TheStrat Suite EZ Mode - Learn TheStrat Combos, Setups & FTFC

SpinTrades · study · 3746 行 · 点赞 73 · TradingView 原页

本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。

Pine Script

//@version=6
// TheStrat Suite EZ Mode - Learn TheStrat - v0.1.0
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//
// GENERATED FILE. Do not edit by hand. Built by ez-mode/build_ez.py from TheStrat Suite
// (pine/TheStratSuite_v3.1.1.pine), so the engine is the Suite's engine. Fix the Suite, then rebuild.
//
// TheStrat was created by Rob Smith. This script is a learning tool for his method:
// every candle is a 1 (took neither side of the bar before it), a 2 (took one side) or a
// 3 (took both), read across four timeframes at once.
//
// What EZ Mode is: TheStrat Suite with the settings reduced to a handful, plus hover text
// that explains what you are looking at.
//   - Four timeframes, picked by one Timeframes setting (default: 60-minute, Day, Week, Month)
//   - Reversals and inside bar breaks always on; three optional signals, no filters
//   - Magnitude and exhaustion targets, Take Action Windows, stops, Preview Mode
//   - Bar numbers on the chart candles
//   - Data table: hover any cell or level label for a plain-English read
//   - Explain row: a one-glance summary of the table
//   - A Failing 2 is judged against the bar's own open: a 2u trading red, a 2d trading green
//
// Documentation: thestratsuite.com
 
indicator("TheStrat Suite EZ Mode - Learn TheStrat", shorttitle = "TheStrat Suite EZ", overlay = true, max_labels_count = 200, max_lines_count = 200, max_boxes_count = 200, max_bars_back = 200)
 
// GRAMMAR-LIB-1 (2026-08-18): bar classification, hammers/shooters, and FTFC now come
// from the TheStratGrammar library - one classifier, spec-tested against the Python
// reference and this file's previous inline logic (60k-bar differential, 0 mismatches).
// Everything below that used to define classification is now a thin wrapper keeping the
// original signature, so no call site changed and no behavior changed.
import SpinTrades/TheStratGrammar/1 as sg
 
// FIX NO-HA-1 (2026-10-24): refuse Heikin Ashi charts. TheStrat reads traded OHLC; Heikin
// Ashi candles are averages, so every bar type, trigger and target would be wrong - and
// because the slots request syminfo.tickerid, the HTF slots inherit Heikin Ashi prices too.
// Halting here means nothing draws and no alert fires on a chart the Suite cannot read.
if chart.is_heikinashi
    runtime.error("Heikin Ashi charts are not supported: TheStrat needs real candles. Switch the chart to Candles or Bars.")
 
// ============================================================================
// SECTION 1: HELPER FUNCTIONS
// ============================================================================
 
getTablePos(pos) =>
    result = switch pos
        "Bottom Center" => position.bottom_center
        "Bottom Left"   => position.bottom_left
        "Bottom Right"  => position.bottom_right
        "Middle Center" => position.middle_center
        "Middle Left"   => position.middle_left
        "Middle Right"  => position.middle_right
        "Top Center"    => position.top_center
        "Top Left"      => position.top_left
        "Top Right"     => position.top_right
        => position.bottom_right
    result
 
getSize(sizeStr) =>
    result = switch sizeStr
        "Tiny"   => size.tiny
        "Small"  => size.small
        "Normal" => size.normal
        "Large"  => size.large
        => size.small
    result
 
getTimeframeLabel(tf) =>
    result = switch tf
        "1" => "1m"
        "3" => "3m"
        "5" => "5m"
        "15" => "15m"
        "30" => "30m"
        "60" => "1H"
        "120" => "2H"
        "240" => "4H"
        "480" => "8H"
        "720" => "12H"
        "D" => "D"
        "1d" => "D"
        "1D" => "D"
        "W" => "W"
        "1W" => "W"
        "M" => "M"
        "1M" => "M"
        "3M" => "3M"
        "6M" => "6M"
        "12M" => "12M"
        => tf
    result
 
getLineStyle(style) =>
    style == "Solid" ? line.style_solid : style == "Dashed" ? line.style_dashed : line.style_dotted
 
 
// Update an existing line in-place or create a new one. Returns the line reference.
updateOrCreateLine(line ref, int x1, float y1, int x2, float y2, color c, int w, string style) =>
    if na(ref)
        line.new(x1, y1, x2, y2, color = c, width = w, style = style, xloc = xloc.bar_time)
    else
        line.set_xy1(ref, x1, y1)
        line.set_xy2(ref, x2, y2)
        line.set_color(ref, c)
        line.set_width(ref, w)
        line.set_style(ref, style)
        ref
 
// Update an existing box in-place or create a new one. Returns the box reference.
updateOrCreateBox(box ref, int x1, float y1, int x2, float y2, color bgc, color borderc) =>
    if na(ref)
        box.new(x1, y1, x2, y2, bgcolor = bgc, border_color = borderc, xloc = xloc.bar_time)
    else
        box.set_lefttop(ref, x1, y1)
        box.set_rightbottom(ref, x2, y2)
        box.set_bgcolor(ref, bgc)
        box.set_border_color(ref, borderc)
        ref
 
// Delete a line if it exists, return na
deleteLine(line ref) =>
    if not na(ref)
        line.delete(ref)
    line(na)
 
// Delete a box if it exists, return na
deleteBox(box ref) =>
    if not na(ref)
        box.delete(ref)
    box(na)
 
var chartTfSeconds = timeframe.in_seconds(timeframe.period)
 
// ============================================================================
// SECTION 2: INPUTS
// ============================================================================
 
// -------------------- PRESET --------------------
grpPreset = "Timeframe Preset"
// EZ-MODE: one Style input stands in for the Suite's preset and its 24 timeframe inputs.
// Four timeframes, lowest to highest. TheStrat Classic is the 60-minute, daily, weekly and
// monthly set that Full Timeframe Continuity is taught on.
grpEZSetup = "Setup"
grpEZSignals = "Extra Signals (optional)"
grpEZChart = "On The Chart"
ezStyle = input.string("TheStrat Classic", "Timeframes", options = ["TheStrat Classic", "Day Trade", "Swing Trade", "Investing", "Custom"], group = grpEZSetup, tooltip = "Picks the four timeframes to read. TheStrat Classic: 60-minute, Day, Week, Month. Day Trade: 15-minute, 60-minute, Day, Week. Swing Trade: 4-hour, Day, Week, Month. Investing: Day, Week, Month, Quarter. Custom: choose your own below. New to TheStrat? Leave this on TheStrat Classic.")
ezCustom = ezStyle == "Custom"
ezTF1 = input.timeframe("60", "Timeframe 1 (lowest)", group = grpEZSetup, active = ezCustom, tooltip = "Only used when Timeframes is set to Custom. Set the four timeframes from lowest to highest. A timeframe lower than your chart cannot be read and shows as blank.")
ezTF2 = input.timeframe("D", "Timeframe 2", group = grpEZSetup, active = ezCustom)
ezTF3 = input.timeframe("W", "Timeframe 3", group = grpEZSetup, active = ezCustom)
ezTF4 = input.timeframe("M", "Timeframe 4 (highest)", group = grpEZSetup, active = ezCustom)
tfPreset = "Custom"
labelStyleMode = "Strat Numbers"
simpleLabelMode = labelStyleMode == "Plain Words"
// FEATURE CHART-TF-1 (2026-11-05): the chart's own timeframe as one of the six slots. Lives in the
// Preset group, not Timeframes, because it works with every preset as well as Custom.
includeChartTF = input.bool(true, "Add Chart Timeframe", group = grpEZSetup, tooltip = "Adds the timeframe you are viewing as a fifth timeframe, so the candles on your chart get their own levels and a row in the table. It follows the chart when you change timeframes. If the chart timeframe is already one of your four, nothing changes.")
chartTFLineWidth = 1
chartTFShowOpen = false
customTFs = tfPreset == "Custom"  // FIX MOD-3: true only when no preset is active; gates the Timeframe rows' `active`
 
// -------------------- TIMEFRAMES --------------------
// FIX MOD-3: every Timeframe row is greyed out (active = customTFs) while a preset is selected,
// since presets override these. Direct UX signal that the manual config is inert under a preset.
grpTFs = "Timeframes"
tf1Enabled = true
tf1 = ezStyle == "TheStrat Classic" ? "60" : ezStyle == "Day Trade" ? "15" : ezStyle == "Swing Trade" ? "240" : ezStyle == "Investing" ? "D" : ezTF1
tf1LineWidth = 1
tf1ShowOpen = false
 
tf2Enabled = true
tf2 = ezStyle == "TheStrat Classic" ? "D" : ezStyle == "Day Trade" ? "60" : ezStyle == "Swing Trade" ? "D" : ezStyle == "Investing" ? "W" : ezTF2
tf2LineWidth = 2
tf2ShowOpen = false
 
tf3Enabled = true
tf3 = ezStyle == "TheStrat Classic" ? "W" : ezStyle == "Day Trade" ? "D" : ezStyle == "Swing Trade" ? "W" : ezStyle == "Investing" ? "M" : ezTF3
tf3LineWidth = 3
tf3ShowOpen = false
 
tf4Enabled = true
tf4 = ezStyle == "TheStrat Classic" ? "M" : ezStyle == "Day Trade" ? "W" : ezStyle == "Swing Trade" ? "M" : ezStyle == "Investing" ? "3M" : ezTF4
tf4LineWidth = 4
tf4ShowOpen = false
 
tf5Enabled = false
tf5 = "W"
tf5LineWidth = 3
tf5ShowOpen = false
 
tf6Enabled = false
tf6 = "M"
tf6LineWidth = 4
tf6ShowOpen = false
 
// Resolve preset overrides
// When preset != Custom, these override the individual TF inputs
usePreset = tfPreset != "Custom"
 
pTF1 = usePreset ? (tfPreset == "TheStrat Classic" ? "30"  : tfPreset == "Scalp" ? "5"   : tfPreset == "Day Trade" ? "15"  : tfPreset == "Futures/Crypto" ? "60"  : tfPreset == "Swing Trade" ? "240" : tfPreset == "Investing" ? "W"   : tf1) : tf1
pTF2 = usePreset ? (tfPreset == "TheStrat Classic" ? "60"  : tfPreset == "Scalp" ? "15"  : tfPreset == "Day Trade" ? "30"  : tfPreset == "Futures/Crypto" ? "240" : tfPreset == "Swing Trade" ? "D"   : tfPreset == "Investing" ? "M"   : tf2) : tf2
pTF3 = usePreset ? (tfPreset == "TheStrat Classic" ? "D"   : tfPreset == "Scalp" ? "30"  : tfPreset == "Day Trade" ? "60"  : tfPreset == "Futures/Crypto" ? "720" : tfPreset == "Swing Trade" ? "W"   : tfPreset == "Investing" ? "3M"  : tf3) : tf3
pTF4 = usePreset ? (tfPreset == "TheStrat Classic" ? "W"   : tfPreset == "Scalp" ? "60"  : tfPreset == "Day Trade" ? "240" : tfPreset == "Futures/Crypto" ? "D"   : tfPreset == "Swing Trade" ? "M"   : tfPreset == "Investing" ? "12M" : tf4) : tf4
pTF5 = usePreset ? (tfPreset == "TheStrat Classic" ? "M"   : tfPreset == "Scalp" ? "60"  : tfPreset == "Day Trade" ? "D"   : tfPreset == "Futures/Crypto" ? "W"   : tfPreset == "Swing Trade" ? "M"   : tfPreset == "Investing" ? "12M" : tf5) : tf5
pTF6 = usePreset ? (tfPreset == "TheStrat Classic" ? "M"   : tfPreset == "Scalp" ? "60"  : tfPreset == "Day Trade" ? "D"   : tfPreset == "Futures/Crypto" ? "W"   : tfPreset == "Swing Trade" ? "M"   : tfPreset == "Investing" ? "12M" : tf6) : tf6
 
pEN1 = usePreset ? true  : tf1Enabled
pEN2 = usePreset ? true  : tf2Enabled
pEN3 = usePreset ? true  : tf3Enabled
pEN4 = usePreset ? true  : tf4Enabled
pEN5 = usePreset ? (tfPreset == "TheStrat Classic" or tfPreset == "Futures/Crypto" or tfPreset == "Day Trade") : tf5Enabled
pEN6 = usePreset ? false : tf6Enabled
 
pLW1 = usePreset ? 1 : tf1LineWidth
pLW2 = usePreset ? (tfPreset == "TheStrat Classic" or tfPreset == "Day Trade" ? 1 : 2) : tf2LineWidth
pLW3 = usePreset ? (tfPreset == "TheStrat Classic" ? 2 : tfPreset == "Futures/Crypto" ? 2 : tfPreset == "Day Trade" ? 2 : 3) : tf3LineWidth
pLW4 = usePreset ? (tfPreset == "TheStrat Classic" ? 3 : tfPreset == "Futures/Crypto" ? 3 : tfPreset == "Day Trade" ? 3 : 4) : tf4LineWidth
pLW5 = usePreset ? 4 : tf5LineWidth
pLW6 = usePreset ? 4 : tf6LineWidth
 
pSO1 = usePreset ? false : tf1ShowOpen
pSO2 = usePreset ? false : tf2ShowOpen
pSO3 = usePreset ? false : tf3ShowOpen
pSO4 = usePreset ? false : tf4ShowOpen
pSO5 = usePreset ? false : tf5ShowOpen
pSO6 = usePreset ? false : tf6ShowOpen
 
// FEATURE CHART-TF-1 (2026-11-05): fold the chart's own timeframe into the six slots.
// The Lead Signal filter, the table and the Domino chain all read slot index as timeframe order
// (index 5 is the highest), so the chart timeframe cannot just take a fixed slot: it is inserted
// in order. Every enabled slot gets a rank by timeframe length (ties keep slot order: a lower slot
// counts with <=, a higher one with <), the chart
// timeframe is inserted at its rank, and the result is written back to slots 1-6 lowest first.
// Overflow (six slots already enabled): drop the lowest slot if it is below the chart timeframe,
// since computeSignalState never draws a lower timeframe on this chart; otherwise the highest
// slot falls off the end. A chart timeframe that is already enabled changes nothing, and with the
// toggle off (or a duplicate) the slots are exactly the preset-resolved ones, unsorted Custom
// configs included. Everything here is simple-qualified ternaries on purpose: request.security
// needs a simple timeframe, and arrays, loops and user functions would make it series.
cSec = timeframe.in_seconds(timeframe.period)
cOK = includeChartTF and not timeframe.isticks and cSec > 0
 
pSec1 = timeframe.in_seconds(pTF1)
pSec2 = timeframe.in_seconds(pTF2)
pSec3 = timeframe.in_seconds(pTF3)
pSec4 = timeframe.in_seconds(pTF4)
pSec5 = timeframe.in_seconds(pTF5)
pSec6 = timeframe.in_seconds(pTF6)
cDup = (pEN1 and pSec1 == cSec) or (pEN2 and pSec2 == cSec) or (pEN3 and pSec3 == cSec) or (pEN4 and pSec4 == cSec) or (pEN5 and pSec5 == cSec) or (pEN6 and pSec6 == cSec)
cIns = cOK and not cDup
cBelow = (pEN1 and pSec1 < cSec ? 1 : 0) + (pEN2 and pSec2 < cSec ? 1 : 0) + (pEN3 and pSec3 < cSec ? 1 : 0) + (pEN4 and pSec4 < cSec ? 1 : 0) + (pEN5 and pSec5 < cSec ? 1 : 0) + (pEN6 and pSec6 < cSec ? 1 : 0)
cEnCount = (pEN1 ? 1 : 0) + (pEN2 ? 1 : 0) + (pEN3 ? 1 : 0) + (pEN4 ? 1 : 0) + (pEN5 ? 1 : 0) + (pEN6 ? 1 : 0)
cShift = cIns and cEnCount >= 6 and cBelow > 0 ? 1 : 0
cPos = cBelow - cShift
pPos1 = (pEN2 and pSec2 < pSec1 ? 1 : 0) + (pEN3 and pSec3 < pSec1 ? 1 : 0) + (pEN4 and pSec4 < pSec1 ? 1 : 0) + (pEN5 and pSec5 < pSec1 ? 1 : 0) + (pEN6 and pSec6 < pSec1 ? 1 : 0) + (pSec1 > cSec ? 1 : 0) - cShift
pPos2 = (pEN1 and pSec1 <= pSec2 ? 1 : 0) + (pEN3 and pSec3 < pSec2 ? 1 : 0) + (pEN4 and pSec4 < pSec2 ? 1 : 0) + (pEN5 and pSec5 < pSec2 ? 1 : 0) + (pEN6 and pSec6 < pSec2 ? 1 : 0) + (pSec2 > cSec ? 1 : 0) - cShift
pPos3 = (pEN1 and pSec1 <= pSec3 ? 1 : 0) + (pEN2 and pSec2 <= pSec3 ? 1 : 0) + (pEN4 and pSec4 < pSec3 ? 1 : 0) + (pEN5 and pSec5 < pSec3 ? 1 : 0) + (pEN6 and pSec6 < pSec3 ? 1 : 0) + (pSec3 > cSec ? 1 : 0) - cShift
pPos4 = (pEN1 and pSec1 <= pSec4 ? 1 : 0) + (pEN2 and pSec2 <= pSec4 ? 1 : 0) + (pEN3 and pSec3 <= pSec4 ? 1 : 0) + (pEN5 and pSec5 < pSec4 ? 1 : 0) + (pEN6 and pSec6 < pSec4 ? 1 : 0) + (pSec4 > cSec ? 1 : 0) - cShift
pPos5 = (pEN1 and pSec1 <= pSec5 ? 1 : 0) + (pEN2 and pSec2 <= pSec5 ? 1 : 0) + (pEN3 and pSec3 <= pSec5 ? 1 : 0) + (pEN4 and pSec4 <= pSec5 ? 1 : 0) + (pEN6 and pSec6 < pSec5 ? 1 : 0) + (pSec5 > cSec ? 1 : 0) - cShift
pPos6 = (pEN1 and pSec1 <= pSec6 ? 1 : 0) + (pEN2 and pSec2 <= pSec6 ? 1 : 0) + (pEN3 and pSec3 <= pSec6 ? 1 : 0) + (pEN4 and pSec4 <= pSec6 ? 1 : 0) + (pEN5 and pSec5 <= pSec6 ? 1 : 0) + (pSec6 > cSec ? 1 : 0) - cShift
cHit1 = (cIns and cPos == 0) or (pEN1 and pPos1 == 0) or (pEN2 and pPos2 == 0) or (pEN3 and pPos3 == 0) or (pEN4 and pPos4 == 0) or (pEN5 and pPos5 == 0) or (pEN6 and pPos6 == 0)
cHit2 = (cIns and cPos == 1) or (pEN1 and pPos1 == 1) or (pEN2 and pPos2 == 1) or (pEN3 and pPos3 == 1) or (pEN4 and pPos4 == 1) or (pEN5 and pPos5 == 1) or (pEN6 and pPos6 == 1)
cHit3 = (cIns and cPos == 2) or (pEN1 and pPos1 == 2) or (pEN2 and pPos2 == 2) or (pEN3 and pPos3 == 2) or (pEN4 and pPos4 == 2) or (pEN5 and pPos5 == 2) or (pEN6 and pPos6 == 2)
cHit4 = (cIns and cPos == 3) or (pEN1 and pPos1 == 3) or (pEN2 and pPos2 == 3) or (pEN3 and pPos3 == 3) or (pEN4 and pPos4 == 3) or (pEN5 and pPos5 == 3) or (pEN6 and pPos6 == 3)
cHit5 = (cIns and cPos == 4) or (pEN1 and pPos1 == 4) or (pEN2 and pPos2 == 4) or (pEN3 and pPos3 == 4) or (pEN4 and pPos4 == 4) or (pEN5 and pPos5 == 4) or (pEN6 and pPos6 == 4)
cHit6 = (cIns and cPos == 5) or (pEN1 and pPos1 == 5) or (pEN2 and pPos2 == 5) or (pEN3 and pPos3 == 5) or (pEN4 and pPos4 == 5) or (pEN5 and pPos5 == 5) or (pEN6 and pPos6 == 5)
rTF1 = not cIns ? pTF1 : cIns and cPos == 0 ? timeframe.period : pEN1 and pPos1 == 0 ? pTF1 : pEN2 and pPos2 == 0 ? pTF2 : pEN3 and pPos3 == 0 ? pTF3 : pEN4 and pPos4 == 0 ? pTF4 : pEN5 and pPos5 == 0 ? pTF5 : pEN6 and pPos6 == 0 ? pTF6 : pTF1
rTF2 = not cIns ? pTF2 : cIns and cPos == 1 ? timeframe.period : pEN1 and pPos1 == 1 ? pTF1 : pEN2 and pPos2 == 1 ? pTF2 : pEN3 and pPos3 == 1 ? pTF3 : pEN4 and pPos4 == 1 ? pTF4 : pEN5 and pPos5 == 1 ? pTF5 : pEN6 and pPos6 == 1 ? pTF6 : pTF2
rTF3 = not cIns ? pTF3 : cIns and cPos == 2 ? timeframe.period : pEN1 and pPos1 == 2 ? pTF1 : pEN2 and pPos2 == 2 ? pTF2 : pEN3 and pPos3 == 2 ? pTF3 : pEN4 and pPos4 == 2 ? pTF4 : pEN5 and pPos5 == 2 ? pTF5 : pEN6 and pPos6 == 2 ? pTF6 : pTF3
rTF4 = not cIns ? pTF4 : cIns and cPos == 3 ? timeframe.period : pEN1 and pPos1 == 3 ? pTF1 : pEN2 and pPos2 == 3 ? pTF2 : pEN3 and pPos3 == 3 ? pTF3 : pEN4 and pPos4 == 3 ? pTF4 : pEN5 and pPos5 == 3 ? pTF5 : pEN6 and pPos6 == 3 ? pTF6 : pTF4
rTF5 = not cIns ? pTF5 : cIns and cPos == 4 ? timeframe.period : pEN1 and pPos1 == 4 ? pTF1 : pEN2 and pPos2 == 4 ? pTF2 : pEN3 and pPos3 == 4 ? pTF3 : pEN4 and pPos4 == 4 ? pTF4 : pEN5 and pPos5 == 4 ? pTF5 : pEN6 and pPos6 == 4 ? pTF6 : pTF5
rTF6 = not cIns ? pTF6 : cIns and cPos == 5 ? timeframe.period : pEN1 and pPos1 == 5 ? pTF1 : pEN2 and pPos2 == 5 ? pTF2 : pEN3 and pPos3 == 5 ? pTF3 : pEN4 and pPos4 == 5 ? pTF4 : pEN5 and pPos5 == 5 ? pTF5 : pEN6 and pPos6 == 5 ? pTF6 : pTF6
rEN1 = not cIns ? pEN1 : cHit1
rEN2 = not cIns ? pEN2 : cHit2
rEN3 = not cIns ? pEN3 : cHit3
rEN4 = not cIns ? pEN4 : cHit4
rEN5 = not cIns ? pEN5 : cHit5
rEN6 = not cIns ? pEN6 : cHit6
rLW1 = not cIns ? pLW1 : cIns and cPos == 0 ? chartTFLineWidth : pEN1 and pPos1 == 0 ? pLW1 : pEN2 and pPos2 == 0 ? pLW2 : pEN3 and pPos3 == 0 ? pLW3 : pEN4 and pPos4 == 0 ? pLW4 : pEN5 and pPos5 == 0 ? pLW5 : pEN6 and pPos6 == 0 ? pLW6 : pLW1
rLW2 = not cIns ? pLW2 : cIns and cPos == 1 ? chartTFLineWidth : pEN1 and pPos1 == 1 ? pLW1 : pEN2 and pPos2 == 1 ? pLW2 : pEN3 and pPos3 == 1 ? pLW3 : pEN4 and pPos4 == 1 ? pLW4 : pEN5 and pPos5 == 1 ? pLW5 : pEN6 and pPos6 == 1 ? pLW6 : pLW2
rLW3 = not cIns ? pLW3 : cIns and cPos == 2 ? chartTFLineWidth : pEN1 and pPos1 == 2 ? pLW1 : pEN2 and pPos2 == 2 ? pLW2 : pEN3 and pPos3 == 2 ? pLW3 : pEN4 and pPos4 == 2 ? pLW4 : pEN5 and pPos5 == 2 ? pLW5 : pEN6 and pPos6 == 2 ? pLW6 : pLW3
rLW4 = not cIns ? pLW4 : cIns and cPos == 3 ? chartTFLineWidth : pEN1 and pPos1 == 3 ? pLW1 : pEN2 and pPos2 == 3 ? pLW2 : pEN3 and pPos3 == 3 ? pLW3 : pEN4 and pPos4 == 3 ? pLW4 : pEN5 and pPos5 == 3 ? pLW5 : pEN6 and pPos6 == 3 ? pLW6 : pLW4
rLW5 = not cIns ? pLW5 : cIns and cPos == 4 ? chartTFLineWidth : pEN1 and pPos1 == 4 ? pLW1 : pEN2 and pPos2 == 4 ? pLW2 : pEN3 and pPos3 == 4 ? pLW3 : pEN4 and pPos4 == 4 ? pLW4 : pEN5 and pPos5 == 4 ? pLW5 : pEN6 and pPos6 == 4 ? pLW6 : pLW5
rLW6 = not cIns ? pLW6 : cIns and cPos == 5 ? chartTFLineWidth : pEN1 and pPos1 == 5 ? pLW1 : pEN2 and pPos2 == 5 ? pLW2 : pEN3 and pPos3 == 5 ? pLW3 : pEN4 and pPos4 == 5 ? pLW4 : pEN5 and pPos5 == 5 ? pLW5 : pEN6 and pPos6 == 5 ? pLW6 : pLW6
rSO1 = not cIns ? pSO1 : cIns and cPos == 0 ? chartTFShowOpen : pEN1 and pPos1 == 0 ? pSO1 : pEN2 and pPos2 == 0 ? pSO2 : pEN3 and pPos3 == 0 ? pSO3 : pEN4 and pPos4 == 0 ? pSO4 : pEN5 and pPos5 == 0 ? pSO5 : pEN6 and pPos6 == 0 ? pSO6 : pSO1
rSO2 = not cIns ? pSO2 : cIns and cPos == 1 ? chartTFShowOpen : pEN1 and pPos1 == 1 ? pSO1 : pEN2 and pPos2 == 1 ? pSO2 : pEN3 and pPos3 == 1 ? pSO3 : pEN4 and pPos4 == 1 ? pSO4 : pEN5 and pPos5 == 1 ? pSO5 : pEN6 and pPos6 == 1 ? pSO6 : pSO2
rSO3 = not cIns ? pSO3 : cIns and cPos == 2 ? chartTFShowOpen : pEN1 and pPos1 == 2 ? pSO1 : pEN2 and pPos2 == 2 ? pSO2 : pEN3 and pPos3 == 2 ? pSO3 : pEN4 and pPos4 == 2 ? pSO4 : pEN5 and pPos5 == 2 ? pSO5 : pEN6 and pPos6 == 2 ? pSO6 : pSO3
rSO4 = not cIns ? pSO4 : cIns and cPos == 3 ? chartTFShowOpen : pEN1 and pPos1 == 3 ? pSO1 : pEN2 and pPos2 == 3 ? pSO2 : pEN3 and pPos3 == 3 ? pSO3 : pEN4 and pPos4 == 3 ? pSO4 : pEN5 and pPos5 == 3 ? pSO5 : pEN6 and pPos6 == 3 ? pSO6 : pSO4
rSO5 = not cIns ? pSO5 : cIns and cPos == 4 ? chartTFShowOpen : pEN1 and pPos1 == 4 ? pSO1 : pEN2 and pPos2 == 4 ? pSO2 : pEN3 and pPos3 == 4 ? pSO3 : pEN4 and pPos4 == 4 ? pSO4 : pEN5 and pPos5 == 4 ? pSO5 : pEN6 and pPos6 == 4 ? pSO6 : pSO5
rSO6 = not cIns ? pSO6 : cIns and cPos == 5 ? chartTFShowOpen : pEN1 and pPos1 == 5 ? pSO1 : pEN2 and pPos2 == 5 ? pSO2 : pEN3 and pPos3 == 5 ? pSO3 : pEN4 and pPos4 == 5 ? pSO4 : pEN5 and pPos5 == 5 ? pSO5 : pEN6 and pPos6 == 5 ? pSO6 : pSO6
 
// -------------------- SIGNALS --------------------
grpSigRev = "Signals - Reversals"
showInsideReversals = true
insideRevOnlyMomo = false
insideRevRequireFTFC = false
 
showAllReversals = true
reversalsRequireActionable = false
reversalsRequireC1F2 = false
reversalsRequireFTFC = false
 
grpSigCont = "Signals - Continuations"
showInsideContinuations = true
insideContOnlyMomo = false
insideContRequireFTFC = false
 
showContinuations = input.bool(false, "2-2 Continuations", group = grpEZSignals, tooltip = "Reversals and inside bar breaks are always shown. This adds the 2-2 continuation: a 2u after a 2u, or a 2d after a 2d. The trend keeps going the same way.")
twoTwoContOnlyMomo = false
continuationsRequireFTFC = false
 
grpSigF2 = "Signals - Reclaims"
show_p3_toggle = input.bool(false, "Failing 2s", group = grpEZSignals, tooltip = "A Failing 2 is a bar that broke the prior bar's high but is now trading below its own open (red), or broke the prior low but is now trading above its own open (green). One side took the level and the other side took the bar back. If it goes on to break the other side it becomes a 3. This one switch covers everything: on, Failing 2s get their own levels and are named F2u and F2d in the table, on labels and in bar numbers. Off, they read as plain 2u and 2d everywhere.")
p3RequireFTFC = false
 
grpSigExp = "Signals - Expansions"
showRangeExpansions = input.bool(false, "3-2 Expansions", group = grpEZSignals, tooltip = "A 3 is an outside bar: it took both the high and the low of the bar before it. A 3-2 is the next bar breaking one side of that wide bar.")
rangeExpOnlyMomo = false
rangeExpansionsRequireFTFC = false
 
show3Expansions = false
threeExpRequireFTFC = false
 
// -------------------- FILTERS --------------------
grpHammerShooter = "Filters - Hammer/Shooter Detection"
logicType = "Broad (Loose)"
onlyColor = false
 
grpDomino = "Filters - Domino Setups"
minDominoTFs = 2
showDominoInTable = false
 
grpDirFilter = "Filters - Lead Signal"
enableDirectionalFilter = false
// -------------------- MAGNITUDE & EXHAUSTION --------------------
grpMagExh = "Targets - Magnitude & Exhaustion"
showMagnitude = true
magOnlyWhenInForce = false
showExhaustion = true
exhOnlyWhenInForce = false
exhRequiresMagHit = false
 
// Gate for exhaustion search: only scan for pivot-based exhaustion when targets are enabled
showAnyTargets = showMagnitude or showExhaustion
 
// -------------------- TAKE ACTION WINDOWS --------------------
grpTAW = "Targets - Take Action Windows"
showTakeActionWindows = true
tawOnlyWhenInForce = true
tawExtendToExhaustion = true
tawExhOnlyWhenInForce = true
tawFillOpacity = 8
tawBorderOpacity = 30
// -------------------- STOP LEVELS --------------------
grpStops = "Stops - Stop Levels"
showStopLevels = input.bool(false, "Stops", group = grpEZChart, tooltip = "Draws a stop level for each signal: the price where the idea is wrong. Treat it as a reference level, not a full risk plan.")
stopReference = "CC"
stopSmallestOnly = false
stopBEatMag = false
stopBEatExh = false
stopColorMode = "Opposite Signal"
colorStop = #FFFFFF
// -------------------- DISPLAY - PREVIEW MODE --------------------
grpPreview = "Display - Preview Mode"
// FIX AUTO-SESSION-1 (tooltip): states the scheduled-close rule first; the ET windows are the US closed-market schedule, not the whole rule.
previewMode = input.string("Auto", "Preview Next Bar", options = ["Off", "On", "Auto"], group = "When The Market Is Closed", tooltip = "Auto: when the market is closed, shows the levels for the next bar so you can plan ahead. The table says PREVIEW MODE while it is on. Off: never preview. Use Off with Bar Replay. On: always preview.")
 
// -------------------- DISPLAY - DATA TABLE --------------------
grpTable = "Display - Data Table"
showBarTypeTable = input.bool(true, "Data Table", inline = "ez_tbl", group = grpEZChart, tooltip = "The table of timeframes. Hover any cell for a plain-English read of what it means right now.")
tableMode = "Full"
compactCellColor = "Bar State"
tablePosition = input.string("Top Right", "", options = ["Bottom Center", "Bottom Left", "Bottom Right", "Middle Center", "Middle Left", "Middle Right", "Top Center", "Top Left", "Top Right"], inline = "ez_tbl", group = grpEZChart)
ezTableStyle = input.string("Combo", "Table Style", options = ["Combo", "Bar by Bar"], group = grpEZChart, tooltip = "Combo: one line per timeframe showing the combo, oldest bar first, with the current bar highlighted at the end. TFC shows whether each timeframe is trading above or below its open, and AS shows HAM, SHO or INS when the bar before the current one is a hammer, a shooter or an inside bar. The Explain Row names any hammer or shooter and the bar it is on. Bar by Bar: the full Suite table with a column each for C2, C1, the actionable signal and the current candle.")
ezSimpleTable = ezTableStyle == "Combo"
ezLastCol = 4
ezExplain = input.bool(true, "Explain Row", group = grpEZChart, tooltip = "Adds a short plain-English summary under the table: whether the timeframes agree, the higher timeframe trend, what is in force and the next trigger with that trend. Turn it off once you can read the table on your own.")
tableTextSize = "Small"
useDashSeparator = true
 
// -------------------- DISPLAY - LABELS --------------------
grpLabels = "Display - Labels"
showTimelineLabels = true
labelOffset = 0
showFloatingLabels = false
floatingLabelOffset = 1
showPriceInLabel = false
showHighLowInLabel = false
labelTextSize = "Small"
labelBackgroundColor = #2e2e2e
labelBackgroundTransparency = 20
 
// -------------------- DISPLAY - BAR COLORING --------------------
// FEATURE BARCOLOR-1 (2026-07-30): candle painting. Engine and rationale in SECTION 14.
grpBarColor = "Display - Bar Coloring"
barColorMode = "Off"
paintInsideBars = true
paint2Bars = true
paintOutsideBars = true
paintFailedBars = true
colorFtfcUpBar = #4caf50
colorFtfcDownBar = #f23645
colorFtfcConflictBar = #808080
paintFtfcConflict = true
paintFtfcTransitions = true
 
// -------------------- DISPLAY - BAR NUMBERS --------------------
// FEATURE BARNUM-1 (2026-10-23): per-candle Strat numbers. Engine and rationale in SECTION 15.
grpBarNum = "Display - Bar Numbers"
showBarNumbers = input.bool(true, "Bar Numbers", group = grpEZChart, tooltip = "Prints each candle's Strat number on the last 50 bars. 1: inside bar, took neither side of the bar before it. 2u: took the prior high, printed above the candle. 2d: took the prior low, printed below it. 3: outside bar, took both. Turn on Failing 2s to also mark those as F2u and F2d.")
barNumNotation = "Full"
ezFade2s = input.bool(true, "Bar Numbers: Fade Plain 2s", group = grpEZChart, active = showBarNumbers, tooltip = "On: plain 2u and 2d numbers are faded so the 1s and 3s stand out, since setups start there. Off: every number at full strength.")
barNumEmphasis = ezFade2s ? "Tiered" : "Uniform"
barNumPosition = input.string("Broken Side", "Bar Numbers: Position", options = ["Below", "Above", "Broken Side"], group = grpEZChart, active = showBarNumbers, tooltip = "Below / Above: every number on the same side, reading as one steady row.\n\nBroken Side: the number sits on the side the candle took out - 2u and F2u above, 2d and F2d below. Outside bars follow their close (3u above, 3d below); inside bars sit below.")
barNumColorMode = "Bar Type Palette"
barNumColor = #9598a1
barNumBarsShown = input.string("Last 50", "Bar Numbers: Bars Shown", options = ["Last 10", "Last 20", "Last 50", "Last 100", "Last 250", "All"], group = grpEZChart, active = showBarNumbers, tooltip = "How many of the most recent candles get a number. Last 50 keeps the numbers on the part of the chart you are reading without crowding older history; All numbers every candle on the chart. The forming candle's number is drawn lighter because it can still change (a 2u can become a 3 or fail into an F2u); it takes full strength when the candle closes.")  // FIX BARNUM-SHOWN-1: named choices, no 0 = all
 
// Auto-preview detection: activate whenever the market is not actively trading
// Equity-like (stocks, ETFs, options, indices, ADRs): outside 9:30 AM - 4:00 PM ET and weekends
// Futures-like (futures, forex, commodities): weekend closure (Fri 5PM - Sun 6PM ET) and daily maintenance (5-6PM ET)
// Crypto: 24/7, only triggers via holiday fallback
// All others: holiday fallback catches unusual closures
etHour = hour(timenow, "America/New_York")
etMinute = minute(timenow, "America/New_York")
etDOW = dayofweek(timenow, "America/New_York")
isWeekendDay = etDOW == dayofweek.saturday or etDOW == dayofweek.sunday
// Stocks/ETFs/Options: closed before 9:30 AM, after 4:00 PM, and weekends
isEquityLike = syminfo.type == "stock" or syminfo.type == "fund" or syminfo.type == "dr" or syminfo.type == "index" or syminfo.type == "option"
isStockClosed = isEquityLike and (isWeekendDay or etHour >= 16 or etHour < 9 or (etHour == 9 and etMinute < 30))
// Futures/Forex/Commodities: weekend closure (Fri 5PM through Sun 6PM) and daily maintenance window (5-6PM ET Mon-Thu)
isFuturesLike = syminfo.type == "futures" or syminfo.type == "forex" or syminfo.type == "commodity"
isFuturesWeekendClosed = etDOW == dayofweek.saturday or (etDOW == dayofweek.friday and etHour >= 17) or (etDOW == dayofweek.sunday and etHour < 18)
isFuturesMaintenance = not isWeekendDay and etDOW != dayofweek.friday and etHour >= 17 and etHour < 18
isFuturesClosed = isFuturesLike and (isFuturesWeekendClosed or isFuturesMaintenance)
// Holiday fallback: now is 4 hours past the last bar's SCHEDULED CLOSE (AUTO-SESSION-1 flattened
// the old max(3 x chart period, 4h)).
// FIX GLUE-1 (2026-07-06): measure from time_close, not time (the open). CME glues holiday
// half-sessions into the next trade date (Fri Jul 3 2026 lives inside Mon Jul 6's bar), so
// the LIVE Monday bar opened with a Thursday-evening stamp and (timenow - time) read ~87h:
// Auto preview engaged during a live session and demoted the forming week/day into C1
// ("weekly levels on the current day", D/W = "?", phantom PREVIEW MODE banner). A live bar's
// scheduled close is always in the future, so this can never fire while a session trades;
// genuinely halted markets still trip it once now exceeds the last scheduled close.
// FIX AUTO-SESSION-1 (2026-09-04): two changes, one rule - "closed" means the chart's last bar has
// passed its scheduled close and no newer bar exists. (a) Veto: Auto never arms while the last bar's
// time_close is still ahead, whatever the ET clock says. The ET windows above describe US exchanges
// only: a "stock" on LSE trades 03:00-09:30 ET and an extended-hours chart trades past 16:00, and both
// had a LIVE daily bar demoted into C1 with a "?" every day - the PREVIEW-WEEKCLOSE-1 symptom, daily.
// (b) Floor: the holiday fallback is a flat 4h past the last scheduled close. max(3 x chart period, 4h)
// was 72h on a daily chart, so an exchange holiday (Dec 25 on 1D), a 13:00 early close and a foreign
// session's afternoon never armed preview before the next open. Trade-off accepted: a thinly traded
// symbol whose first print lags its scheduled open can show a phantom preview until that print;
// intraday charts already behaved that way under the 4h floor.
bool lastBarClosed = not na(time_close) and timenow > time_close
isHolidayClosed = lastBarClosed and (timenow - time_close) > 4 * 60 * 60 * 1000
isBarReplay = bar_index < last_bar_index
marketLikelyClosed = barstate.islast and not isBarReplay and lastBarClosed and (isStockClosed or isFuturesClosed or isHolidayClosed)
previewNextPeriod = previewMode == "On" or (previewMode == "Auto" and marketLikelyClosed)
// FIX HTF-STRADDLE-1 (T1): a chart bar can straddle a higher-TF boundary (e.g. a weekly bar spanning
// a mid-week month/quarter roll). request.security maps each chart bar to the HTF bar in effect at the
// chart bar's OPEN, so the served M/3M/6M/12M data stays one period stale for the rest of that chart
// bar even while the market trades. The preview shift already fixes exactly this problem in its
// market-closed form; this flag arms the same shift for calendar TFs on the live last bar too.
// previewMode = Off still disables everything (preserves the bar-replay workaround).
// FIX HTF-STRADDLE-1: live-straddle window (market open, last bar, not replay; previewMode Off disables).
// RE-ENABLED 2026-07-02 with the corrected session-offset-aware detection (see shouldStraddle above).
bool straddleWindowOK = previewMode != "Off" and barstate.islast and not isBarReplay
 
// -------------------- STYLE --------------------
grpStyleBullish = "Style - Bullish Levels"
colorBullishActive = color.green
colorBullishHit = #9c9c9c
colorBullishPotential = #ffeb3b
colorBullish3Bar = #089981
colorBullishP3 = #81c784
 
grpStyleBearish = "Style - Bearish Levels"
colorBearishActive = color.red
colorBearishHit = #4a4a4a
colorBearishPotential = #ff9800
colorBearish3Bar = #e91e63
colorBearishP3 = #f77c80
 
var color COLOR_FAILED_2U = colorBearishP3
var color COLOR_FAILED_2D = colorBullishP3
var color COLOR_3_HIGH = colorBullish3Bar
var color COLOR_3_LOW = colorBearish3Bar
var color COLOR_INSIDE_HIGH = colorBullishPotential
var color COLOR_INSIDE_LOW = colorBearishPotential
var color COLOR_HIT_HIGH = colorBullishHit
var color COLOR_HIT_LOW = colorBearishHit
var color COLOR_BG_BLACK = color.new(color.black, 0)
var color COLOR_BG_GRAY50 = color.new(color.gray, 50)
 
colorStopHigh = stopColorMode == "Opposite Signal" ? colorBearishActive : stopColorMode == "Match Signal" ? colorBullishActive : colorStop
colorStopLow = stopColorMode == "Opposite Signal" ? colorBullishActive : stopColorMode == "Match Signal" ? colorBearishActive : colorStop
 
tawFillTransp = 100 - tawFillOpacity
tawBorderTransp = 100 - tawBorderOpacity
tawBullishFill = color.new(colorBullishActive, tawFillTransp)
tawBullishBorder = color.new(colorBullishActive, tawBorderTransp)
tawBearishFill = color.new(colorBearishActive, tawFillTransp)
tawBearishBorder = color.new(colorBearishActive, tawBorderTransp)
 
 
// -------------------- ALERTS --------------------
grpAlerts = "Alerts - Detailed"
alertTF1 = true
alertTF2 = true
alertTF3 = true
alertTF4 = true
alertTF5 = true
alertTF6 = true
alertShowFTFC = false
alertShowTrigger = false
alertShowMagnitude = false
alertShowExhaustion = false
alertShowStop = false
 
// -------------------- ADVANCED --------------------
grpAdvExh = "Advanced - Exhaustion Behavior"
exhDisablesInForce = false
exhDisablesFTFC = false
 
grpAdvOB = "Advanced - Outside Bars"
show3ExpMagnitude = true
show3ExpExhaustion = true
 
grpAdvF2 = "Advanced - Failing 2 Detection"
enableFailed2Detection = true
failed_2_method = "Open"
showF2OpenLine = false
 
grpAdvTable = "Advanced - Data Table"
colorTFWhenInForce = true
 
grpAdvTAW = "Advanced - Take Action Windows"
showP3TakeActionWindows = true
show3ExpTakeActionWindows = true
 
grpAdvDomino = "Advanced - Domino Setups"
enableDominoAlerts = false
 
// -------------------- DEBUG --------------------
grpDebug = "Debug"
showDebugPanel = false
debugTimeframe = "TF1"
 
// ============================================================================
// SECTION 2A: HELPER FUNCTIONS (POST-INPUTS)
// ============================================================================
 
// Format candle combo string with optional dash separator
// e.g., "2u2d" becomes "2u-2d" when useDashSeparator is true
formatCombo(string combo) =>
    if not useDashSeparator or str.length(combo) < 2
        combo
    else
        string result = ""
        int i = 0
        int len = str.length(combo)
        while i < len
            char = str.substring(combo, i, i + 1)
            // Check if current char is start of a bar type (digit, F, or *)
            isBarStart = char == "1" or char == "2" or char == "3" or char == "F" or char == "f" or char == "*"
            // Add dash before bar types (except first)
            if isBarStart and i > 0
                prevChar = str.substring(combo, i - 1, i)
                // Dash after completed bar types: "u"/"d" suffixed bars, or standalone "1"/"3"
                if prevChar == "u" or prevChar == "d" or prevChar == "1" or prevChar == "2" or prevChar == "3"
                    result := result + "-"
            result := result + char
            i := i + 1
        result
 
// ============================================================================
// SECTION 3: USER-DEFINED TYPES
// ============================================================================
 
type TimeframeData
    line highLine
    line lowLine
    line openLine
    line magHighLine
    line magLowLine
    line exhHighLine
    line exhLowLine
    box actionWindowBullish
    box actionWindowBearish
    float prevHigh
    float prevLow
    float currOpen
    float prevMagHigh
    float prevMagLow
    float exhHighPrice
    float exhLowPrice
    int prevTime
    int prevMagTime
    int exhHighTime
    int exhLowTime
    bool magHighCrossed
    bool magLowCrossed
    bool exhHighCrossed
    bool exhLowCrossed
    bool c1IsInside
    bool c1IsHammer
    bool c1IsShooter
    bool c1IsHighContinuation
    bool c1IsLowContinuation
    line stopHighLine       // stop for bullish signal (drawn at C1 low)
    line stopLowLine        // stop for bearish signal (drawn at C1 high)
    bool stopHighTriggered  // sticky: bullish signal was in force this period
    bool stopLowTriggered   // sticky: bearish signal was in force this period
    float stopHighPrice     // locked stop price for bullish signal
    float stopLowPrice      // locked stop price for bearish signal
    line f2OpenLine          // pre-F2: CC open shown as potential trigger when reclaim met but open not crossed
    int lastPeriodStart      // FIX P0-1: per-slot HTF period-open time (replaces the shared ta.change(time(tf)) buffer)
    bool wasPreview = false  // FIX P1-d: prior-bar preview state, used to re-latch when preview exits mid-period (default false avoids na() on series bool)
 
type SimpleLabelData
    array<float> prices
    array<string> texts
    array<color> colors
    array<int> times
 
type LabelPoolT          // FIX P1-i: reusable label pool - update-in-place instead of delete+recreate every tick
    array<label> items
    int used
 
type LineInfo
    float price
    int tfSeconds
    line lineRef
    TimeframeData owner   // FIX P1-h: owning slot, so a suppressed line's field can be nulled after delete
    int kind              // FIX P1-h: which TimeframeData line field this ref came from (see nullSuppressedLine)
 
type TFRawData
    int c1Time
    float c1H
    float c1L
    float c1O
    float c1C
    int ccTime
    float ccO
    float ccH
    float ccL
    float ccC
    int c2Time
    float c2H
    float c2L
    float c2O
    float c2C
    float c3H
    float c3L
    float c4H
    float c4L
    float exhHP
    int exhHT
    float exhLP
    int exhLT
    bool isPreview
    int realPeriodTime       // FIX P0-1: unshifted current HTF period-open time, for per-slot new-period detection
 
type ProcessingResult
    float high
    float low
    float open
    float magHigh
    float magLow
    float exhHigh
    float exhLow
    color highColor
    color lowColor
    color openColor
    color magHighColor
    color magLowColor
    color exhHighColor
    color exhLowColor
    bool drawHigh
    bool drawLow
    bool drawOpen
    bool drawMagHigh
    bool drawMagLow
    bool drawExhHigh
    bool drawExhLow
    int time
    string tfLabel
    bool isF2u
    bool isF2d
    bool c1Is3
    string c3Num
    string c2Num
    string c1Num
    string c1Type
    string ccType
    bool signalInForceHigh
    bool signalInForceLow
    float stopHigh          // bullish stop price (C1 low)
    float stopLow           // bearish stop price (C1 high)
    bool drawStopHigh
    bool drawStopLow
    bool preF2u             // pre-F2u: CC broke high, reclaimed, close still above open
    bool preF2d             // pre-F2d: CC broke low, reclaimed, close still below open
    float f2OpenPrice       // CC open price for pre-F2 line
    int ccStartTime         // CC candle start time for Domino dedup
    bool c1WasF2            // C1 was itself a Failed 2
    bool c2WasF2            // C2 was itself a Failed 2
    string highStyle        // computed style for high trigger line
    string lowStyle         // computed style for low trigger line
 
// FEATURE DEBUG-TERMS-1: every field carries a default so the panel can grow without
// maintaining a 50-argument positional constructor call.
type DebugInfo
    string tfLabel = ""
    bool c1_was_2u = false
    bool c1_was_2d = false
    bool c1_is_3 = false
    bool c2_was_2u = false
    bool c2_was_2d = false
    bool c2_was_3 = false
    bool c2_closed_up = false
    bool c2_closed_down = false
    bool isHammer = false
    bool isShooter = false
    bool isInside = false
    bool cc_is_2u = false
    bool cc_is_2d = false
    bool cc_is_3 = false
    bool cc_broke_high = false
    bool cc_broke_low = false
    bool is_f2u = false
    bool is_f2d = false
    bool pre_f2u = false
    bool pre_f2d = false
    bool ftfc_up = false
    bool ftfc_down = false
    bool is_hammer_reversal = false
    bool is_hammer_momo = false
    bool hammer_shows = false
    bool is_shooter_reversal = false
    bool is_shooter_momo = false
    bool shooter_shows = false
    bool sif_high = false
    bool sif_low = false
    bool t_insideRev_h = false
    bool t_insideRev_l = false
    bool t_insideCont_h = false
    bool t_insideCont_l = false
    bool t_hamSho_h = false
    bool t_hamSho_l = false
    bool t_rev22_h = false
    bool t_rev22_l = false
    bool t_cont22_h = false
    bool t_cont22_l = false
    bool t_exp32_h = false
    bool t_exp32_l = false
    bool t_exp3_h = false
    bool t_exp3_l = false
    bool t_f2_h = false
    bool t_f2_l = false
    bool drawHigh = false
    bool drawLow = false
    bool drawMagHigh = false
    bool drawMagLow = false
    bool drawExhHigh = false
    bool drawExhLow = false
    bool force_mag_high = false
    bool force_mag_low = false
    bool mag_high_passes_ftfc = false
    bool mag_low_passes_ftfc = false
 
type TFConfig
    bool enabled
    string tf
    int lineWidth
    bool showOpen
    string debugLabel
 
var DebugInfo debugData = DebugInfo.new()
 
// ============================================================================
// SECTION 3B: CLEANUP HELPER METHODS
// ============================================================================
 
// FIX P2-1: removed five unused cleanup methods (clearHighExtras / clearLowExtras /
// clearHighAll / clearLowAll / clearCommon). They had zero reachable call sites - the
// only callers were each other (clearHighAll -> clearHighExtras, etc.), so the whole
// cluster was transitively dead. The live suppress* methods below are unaffected.
 
// ProcessingResult flag suppression methods
method suppressHighFlags(ProcessingResult this) =>
    this.drawHigh := false
    this.drawMagHigh := false
    this.drawExhHigh := false
    this.drawStopHigh := false
 
method suppressLowFlags(ProcessingResult this) =>
    this.drawLow := false
    this.drawMagLow := false
    this.drawExhLow := false
    this.drawStopLow := false
 
method suppressAllFlags(ProcessingResult this) =>
    this.suppressHighFlags()
    this.suppressLowFlags()
 
// ============================================================================
// SECTION 4: PATTERN DETECTION FUNCTIONS
// ============================================================================
 
// GRAMMAR-LIB-1: pattern detection delegates to the library. logicType's option strings
// ("Broad (Loose)", "Classic", "Pin Bar (Strict)") are the library's accepted methods,
// and onlyColor maps to requireColor. BTC-2's strict midpoint rule lives in the library.
detectPatterns(c1_open, c1_high, c1_low, c1_close) =>
    [sg.isHammer(c1_open, c1_high, c1_low, c1_close, logicType, onlyColor), sg.isShooter(c1_open, c1_high, c1_low, c1_close, logicType, onlyColor)]
 
findExhaustionLevels() =>
    float exhHighPrice = na
    int exhHighTime = na
    float exhLowPrice = na
    int exhLowTime = na
    float nxtHighPrice = na
    int nxtHighTime = na
    float nxtLowPrice = na
    int nxtLowTime = na
    // Only calculate on recent bars - historical exhaustion is never displayed
    // Loop goes to 48, but accesses i+1, so max offset is 49
    // Require bar_index > 50 to ensure enough historical data
    if showAnyTargets and bar_index > last_bar_index - 100 and bar_index > 50
        // FIX P0-2: seed running max/min from the completed bar [1], not the forming bar [0],
        // and start the scan at i=2 so the i-1 neighbor test never reads the forming bar.
        // Under lookahead_on, high[0] in the HTF context returns the developing value live
        // but the final period value on reload, so the [0] seed made the latched exhaustion
        // level repaint. Max offset is now i+1 = 49 (loop still ends at 48).
        // DELIBERATELY NOT math.max(high[1], high[0]) for the seed: pulling the forming bar
        // back into the intact-pivot gate would re-introduce the live-vs-reload repaint this
        // fix removes. A period-open exhaustion snapshot that sits slightly behind live price
        // on a rare mid-period preview re-latch is acceptable and, crucially, reload-stable.
        // FIX EXH-PREVIEW-CHANNEL-1 (2026-09-13): one pass, two channels, neither of which consults
        // the wall clock - which channel gets USED is decided on the last-bar control path, in
        // applyPreviewShift. The CURRENT channel is P0-2 unchanged: seed [1], candidates from i=2,
        // the forming bar never touches the intact-pivot gate. The NEXT channel answers the question
        // a preview projection actually asks - what is the target for the period that has not opened
        // yet - by seeding [0] and allowing a candidate at i=1. Consuming it is safe ONLY where [0]
        // has already closed, which is exactly the gate applyPreviewShift applies.
        //
        // Why not simply re-index the single channel by time_close: that was tried and rejected
        // (Codex review, 2026-09-13). With Preview Mode Off on a closed market the slot stays on the
        // finished period, nothing re-latches, and the stored snapshot keeps the value latched at
        // that period's OPEN; a reload would re-run newPeriod with the clock now past the close and
        // latch the next period's answer instead. Live and reload would disagree on the exhaustion
        // price, its crossed state, its TAW and its break-even - the precise repaint P0-2 exists to
        // prevent. Deterministic channels plus a last-bar selector keep Rule 7 intact.
        float maxCur = high[1]
        float minCur = low[1]
        float maxNxt = high[0]
        float minNxt = low[0]
        for i = 1 to 48
            isPivotHigh = high[i] > high[i-1] and high[i] > high[i+1]
            isPivotLow = low[i] < low[i-1] and low[i] < low[i+1]
            if na(nxtHighPrice) and isPivotHigh and maxNxt < high[i]
                nxtHighPrice := high[i]
                nxtHighTime := time[i]
            if na(nxtLowPrice) and isPivotLow and minNxt > low[i]
                nxtLowPrice := low[i]
                nxtLowTime := time[i]
            if i >= 2
                if na(exhHighPrice) and isPivotHigh and maxCur < high[i]
                    exhHighPrice := high[i]
                    exhHighTime := time[i]
                if na(exhLowPrice) and isPivotLow and minCur > low[i]
                    exhLowPrice := low[i]
                    exhLowTime := time[i]
                maxCur := math.max(maxCur, high[i])
                minCur := math.min(minCur, low[i])
            maxNxt := math.max(maxNxt, high[i])
            minNxt := math.min(minNxt, low[i])
            if not na(exhHighPrice) and not na(exhLowPrice) and not na(nxtHighPrice) and not na(nxtLowPrice)
                break
    [exhHighPrice, exhHighTime, exhLowPrice, exhLowTime, nxtHighPrice, nxtHighTime, nxtLowPrice, nxtLowTime]
 
// GRAMMAR-LIB-1: stays local. It sat inside the CandleMetrics block that moved into the
// library, but the library exports no inside-bar helper - sg.structureOf() == "1" is the
// equivalent, and routing this through it would add an na-guard branch on the path that
// gates every Inside Reversal and Inside Continuation. Unchanged from v3.0.1.
isInsideBar(currH, currL, prevH, prevL) =>
    currH <= prevH and currL >= prevL
 
calcBarType(prevH, prevL, currH, currL, currO, currC) =>
    // GRAMMAR-LIB-1: combo-token rendering of sg.structureOf - bare "1", signed 3s.
    if na(currO) or na(currC)
        ""
    else
        st = sg.structureOf(prevH, prevL, currH, currL)
        st == "3" ? (currC > currO ? "3u" : "3d") : st
 
calcBarNum(prevH, prevL, currH, currL) =>
    st = sg.structureOf(prevH, prevL, currH, currL)
    st == "" ? "" : str.substring(st, 0, 1)
 
getDataWithExhaustion() =>
    // FIX EXH-PREVIEW-CHANNEL-1: both channels ride the same request.security tuple.
    [exhHP, exhHT, exhLP, exhLT, nxHP, nxHT, nxLP, nxLT] = findExhaustionLevels()
    [time, open, high, low, close, time[1], high[1], low[1], open[1], close[1], time[2], high[2], low[2], open[2], close[2], high[3], low[3], high[4], low[4], exhHP, exhHT, exhLP, exhLT, nxHP, nxHT, nxLP, nxLT]
 
calculateFTFC(tf1_en, tf1_o, tf1_c, tf2_en, tf2_o, tf2_c, tf3_en, tf3_o, tf3_c, tf4_en, tf4_o, tf4_c, tf5_en, tf5_o, tf5_c, tf6_en, tf6_o, tf6_c) =>
    // PERF-FTFC-1: deliberately NOT routed through sg.continuity. This function is called
    // unguarded at global scope - once per chart bar over all history - and again per bar
    // when FTFC bar coloring is on. The library version costs an array clear, up to six
    // pushes, a cross-module call, a loop, a STRING result and two string comparisons, all
    // per bar, where this costs six boolean branches. Continuity is a six-way boolean AND
    // reduction over the sign channel; sg.continuity remains its definition of record and
    // the two are trivially the same. Bar CLASSIFICATION still comes from the library
    // (sg.structureOf / sg.isFailed / sg.isHammer / sg.isShooter) - that is where a second
    // implementation could actually drift, and it is the reason the library exists.
    // Quirk preserved from the original: with ZERO qualifying slots (all disabled or na)
    // this returns [true, true], matching sg.continuity's empty-array case only in shape -
    // the library calls that "Conflict". Not a state a preset can produce.
    ftfc_up = true
    ftfc_down = true
    if tf1_en and not na(tf1_c) and not na(tf1_o)
        if tf1_c > tf1_o
            ftfc_down := false
        else
            ftfc_up := false
    if tf2_en and not na(tf2_c) and not na(tf2_o)
        if tf2_c > tf2_o
            ftfc_down := false
        else
            ftfc_up := false
    if tf3_en and not na(tf3_c) and not na(tf3_o)
        if tf3_c > tf3_o
            ftfc_down := false
        else
            ftfc_up := false
    if tf4_en and not na(tf4_c) and not na(tf4_o)
        if tf4_c > tf4_o
            ftfc_down := false
        else
            ftfc_up := false
    if tf5_en and not na(tf5_c) and not na(tf5_o)
        if tf5_c > tf5_o
            ftfc_down := false
        else
            ftfc_up := false
    if tf6_en and not na(tf6_c) and not na(tf6_o)
        if tf6_c > tf6_o
            ftfc_down := false
        else
            ftfc_up := false
    [ftfc_up, ftfc_down]
 
// ============================================================================
// SECTION 5: DECISION LOGIC FUNCTIONS
// ============================================================================
 
detectFailed2(c1_high, c1_low, cc_open, cc_close, cc_high, cc_low, method) =>
    cc_is_3 = cc_high > c1_high and cc_low < c1_low
    cc_is_2u = cc_high > c1_high and cc_low >= c1_low and not cc_is_3
    cc_is_2d = cc_low < c1_low and cc_high <= c1_high and not cc_is_3
    is_f2u = false
    is_f2d = false
    pre_f2u = false
    pre_f2d = false
    if enableFailed2Detection and (cc_is_2u or cc_is_2d) and not cc_is_3
        cc_inside_c1 = cc_close <= c1_high and cc_close >= c1_low
        cc_above_open = cc_close > cc_open
        if method == "Open"
            is_f2u := cc_is_2u and not cc_above_open
            is_f2d := cc_is_2d and cc_above_open
        else if method == "Reclaim"
            is_f2u := cc_is_2u and cc_inside_c1
            is_f2d := cc_is_2d and cc_inside_c1
        else if method == "Reclaim + Open"
            is_f2u := cc_is_2u and not cc_above_open and cc_inside_c1
            is_f2d := cc_is_2d and cc_above_open and cc_inside_c1
        else
            is_f2u := cc_is_2u and (not cc_above_open or cc_inside_c1)
            is_f2d := cc_is_2d and (cc_above_open or cc_inside_c1)
        // Pre-F2: CC broke range, reclaimed back inside, but close hasn't crossed open yet
        // Only relevant when method uses open condition (Open or Reclaim + Open)
        if (method == "Open" or method == "Reclaim + Open") and not is_f2u and not is_f2d
            if cc_is_2u and cc_inside_c1 and cc_above_open
                pre_f2u := true
            if cc_is_2d and cc_inside_c1 and not cc_above_open
                pre_f2d := true
    [cc_is_2u, cc_is_2d, cc_is_3, is_f2u, is_f2d, pre_f2u, pre_f2d]
 
// FIX CONT22-PRIOR-1 (2026-08-18): `c2_was_3` removed from the parameter list - it now gates
// nothing here. It is still computed in computeSignalState and still reported in the debug
// panel as diagnostic information; see the two continuation branches below.
shouldDrawC1Level(bool isBullish, c1_is_inside, c1_is_hammer, c1_is_shooter, cc_is_2u, cc_is_2d, cc_is_3, is_f2u, is_f2d, ftfc_up, ftfc_down, c1_was_2u, c1_was_2d, c1_is_3, c2_closed_up, c2_closed_down) =>
    result = false
    is_continuation = false
    cc_is_inside = not cc_is_2u and not cc_is_2d and not cc_is_3
    ftfc_blocks = isBullish ? ftfc_down : ftfc_up
    c2_same_dir = isBullish ? c2_closed_up : c2_closed_down
    c2_opp_dir = isBullish ? c2_closed_down : c2_closed_up
    momo_pattern = isBullish ? c1_is_hammer : c1_is_shooter
    cc_in_force = isBullish ? cc_is_2u : cc_is_2d
    cc_opposite = isBullish ? cc_is_2d : cc_is_2u
    c1_was_same = isBullish ? c1_was_2u : c1_was_2d
    c1_was_opp = isBullish ? c1_was_2d : c1_was_2u
    failed_same = isBullish ? is_f2u : is_f2d
    failed_opp = isBullish ? is_f2d : is_f2u
    inside_rev_ftfc_blocks = insideRevRequireFTFC and ftfc_blocks
    reversals_ftfc_blocks = reversalsRequireFTFC and ftfc_blocks
    continuations_ftfc_blocks = continuationsRequireFTFC and ftfc_blocks
    inside_cont_ftfc_blocks = insideContRequireFTFC and ftfc_blocks
    expansions_ftfc_blocks = rangeExpansionsRequireFTFC and ftfc_blocks
    threeExp_ftfc_blocks = threeExpRequireFTFC and ftfc_blocks
    p3_ftfc_blocks = p3RequireFTFC and ftfc_blocks
    inside_is_continuation = c1_is_inside and c2_same_dir
    inside_is_reversal = c1_is_inside and (c2_opp_dir or (not c2_closed_up and not c2_closed_down))
    if cc_is_3
        if show3Expansions and not threeExp_ftfc_blocks
            result := true
    else if show_p3_toggle and failed_same
        result := not p3_ftfc_blocks
    else if show_p3_toggle and failed_opp
        result := not p3_ftfc_blocks
    else if c1_is_inside
        if inside_is_reversal and showInsideReversals
            if insideRevOnlyMomo and not momo_pattern
                result := false
            else
                result := not inside_rev_ftfc_blocks
        else if inside_is_reversal and not showInsideReversals
            result := false
        else if inside_is_continuation and showInsideContinuations
            if insideContOnlyMomo and not momo_pattern
                result := false
            else
                result := not inside_cont_ftfc_blocks
                is_continuation := result
        else if inside_is_continuation and not showInsideContinuations
            result := false
        else
            if showInsideReversals
                if insideRevOnlyMomo and not momo_pattern
                    result := false
                else
                    result := not inside_rev_ftfc_blocks
    else if c1_is_3 and cc_in_force and showRangeExpansions
        if rangeExpOnlyMomo and not momo_pattern
            result := false
        else
            result := not expansions_ftfc_blocks
            is_continuation := result
    else if c1_is_3 and cc_is_inside and showRangeExpansions
        if rangeExpOnlyMomo and not momo_pattern
            result := false
        else
            result := not expansions_ftfc_blocks
            is_continuation := result
    else if momo_pattern and not (c1_is_3 and not showRangeExpansions)
        is_momo_reversal = c1_was_opp or (c2_opp_dir and not c1_was_same) or (not c1_was_2u and not c1_was_2d and not c2_same_dir)
        is_momo_cont = c1_was_same or (c2_same_dir and not c1_was_opp)
        cc_is_opp_continuation = cc_opposite and c1_was_opp
        if cc_is_opp_continuation
            result := false
        else if is_momo_reversal and not cc_opposite
            result := not reversals_ftfc_blocks       // FIX BTC-1: momo (hammer/shooter) reversal now obeys the Reversals-FTFC toggle (was wrongly using inside-reversal's)
        else if is_momo_cont and showContinuations
            result := not continuations_ftfc_blocks   // FIX BTC-1: momo continuation now obeys the Continuations-FTFC toggle (was wrongly using inside-reversal's)
            is_continuation := result
    else if c1_was_opp and cc_in_force and showAllReversals
        if momo_pattern
            result := not reversals_ftfc_blocks
        else if reversalsRequireActionable
            result := false
        else
            result := not reversals_ftfc_blocks
    else if c1_was_opp and showAllReversals and not cc_opposite
        if momo_pattern
            result := not reversals_ftfc_blocks
        else if reversalsRequireActionable
            result := false
        else
            result := not reversals_ftfc_blocks
    // FIX CONT22-PRIOR-1 (2026-08-18): the `not c2_was_3` guard is gone from both 2-2
    // continuation branches. The pattern is C1 and CC - two directional bars the same way -
    // so nothing further back gates it; a three-bar combination would name C2 explicitly the
    // way 3-2 Expansions do. The old guard dropped every continuation in a 3 -> 2u -> 2u
    // sequence, costing a level, label, alert and table cell with nothing on screen to say why.
    else if c1_was_same and cc_in_force and showContinuations
        if twoTwoContOnlyMomo and not momo_pattern
            result := false
        else
            result := not continuations_ftfc_blocks
            is_continuation := result
    // FIX CONT22-PRIOR-1: same removal, CC-inside branch.
    else if c1_was_same and cc_is_inside and showContinuations
        if twoTwoContOnlyMomo and not momo_pattern
            result := false
        else
            result := not continuations_ftfc_blocks
            is_continuation := result
    [result, is_continuation]
 
shouldDrawC1High(c1_is_inside, c1_is_hammer, c1_is_shooter, cc_is_2u, cc_is_2d, cc_is_3, is_f2u, is_f2d, ftfc_up, ftfc_down, c1_was_2u, c1_was_2d, c1_is_3, c2_closed_up, c2_closed_down) =>
    shouldDrawC1Level(true, c1_is_inside, c1_is_hammer, c1_is_shooter, cc_is_2u, cc_is_2d, cc_is_3, is_f2u, is_f2d, ftfc_up, ftfc_down, c1_was_2u, c1_was_2d, c1_is_3, c2_closed_up, c2_closed_down)
 
shouldDrawC1Low(c1_is_inside, c1_is_shooter, c1_is_hammer, cc_is_2u, cc_is_2d, cc_is_3, is_f2u, is_f2d, ftfc_up, ftfc_down, c1_was_2u, c1_was_2d, c1_is_3, c2_closed_up, c2_closed_down) =>
    shouldDrawC1Level(false, c1_is_inside, c1_is_hammer, c1_is_shooter, cc_is_2u, cc_is_2d, cc_is_3, is_f2u, is_f2d, ftfc_up, ftfc_down, c1_was_2u, c1_was_2d, c1_is_3, c2_closed_up, c2_closed_down)
shouldDrawMagnitude(c1_broke_c2, is_signal_in_force) =>
    not c1_broke_c2 and is_signal_in_force
 
// ============================================================================
// SECTION 6: DATA STRUCTURES (Array-based for loop processing)
// ============================================================================
 
var array<TimeframeData> tfDataArr = array.new<TimeframeData>(6)
if barstate.isfirst
    for i = 0 to 5
        array.set(tfDataArr, i, TimeframeData.new(na, na, na, na, na, na, na, na, na, na, na, na, na, na, na, na, na, na, na, na, false, false, false, false, false, false, false, false, false, na, na, false, false, na, na))
 
var array<TFConfig> tfConfigs = array.new<TFConfig>(6)
if barstate.isfirst
    array.set(tfConfigs, 0, TFConfig.new(rEN1, rTF1, rLW1, rSO1, "TF1"))
    array.set(tfConfigs, 1, TFConfig.new(rEN2, rTF2, rLW2, rSO2, "TF2"))
    array.set(tfConfigs, 2, TFConfig.new(rEN3, rTF3, rLW3, rSO3, "TF3"))
    array.set(tfConfigs, 3, TFConfig.new(rEN4, rTF4, rLW4, rSO4, "TF4"))
    array.set(tfConfigs, 4, TFConfig.new(rEN5, rTF5, rLW5, rSO5, "TF5"))
    array.set(tfConfigs, 5, TFConfig.new(rEN6, rTF6, rLW6, rSO6, "TF6"))
 
// Tiered calc_bars_count: Monthly+=100, Weekly=100, Daily=150, 4H+=200, intraday=250
// Minimum 100 required for exhaustion scan (bar_index > 50 gate inside security context)
// Inlined as simple int: Pine functions return series, which request.security rejects.
simple int cb1 = rTF1 == "M" or rTF1 == "1M" or rTF1 == "3M" or rTF1 == "6M" or rTF1 == "12M" ? 100 : rTF1 == "W" or rTF1 == "1W" ? 100 : rTF1 == "D" or rTF1 == "1D" ? 150 : rTF1 == "240" or rTF1 == "480" or rTF1 == "720" ? 200 : 250
simple int cb2 = rTF2 == "M" or rTF2 == "1M" or rTF2 == "3M" or rTF2 == "6M" or rTF2 == "12M" ? 100 : rTF2 == "W" or rTF2 == "1W" ? 100 : rTF2 == "D" or rTF2 == "1D" ? 150 : rTF2 == "240" or rTF2 == "480" or rTF2 == "720" ? 200 : 250
simple int cb3 = rTF3 == "M" or rTF3 == "1M" or rTF3 == "3M" or rTF3 == "6M" or rTF3 == "12M" ? 100 : rTF3 == "W" or rTF3 == "1W" ? 100 : rTF3 == "D" or rTF3 == "1D" ? 150 : rTF3 == "240" or rTF3 == "480" or rTF3 == "720" ? 200 : 250
simple int cb4 = rTF4 == "M" or rTF4 == "1M" or rTF4 == "3M" or rTF4 == "6M" or rTF4 == "12M" ? 100 : rTF4 == "W" or rTF4 == "1W" ? 100 : rTF4 == "D" or rTF4 == "1D" ? 150 : rTF4 == "240" or rTF4 == "480" or rTF4 == "720" ? 200 : 250
simple int cb5 = rTF5 == "M" or rTF5 == "1M" or rTF5 == "3M" or rTF5 == "6M" or rTF5 == "12M" ? 100 : rTF5 == "W" or rTF5 == "1W" ? 100 : rTF5 == "D" or rTF5 == "1D" ? 150 : rTF5 == "240" or rTF5 == "480" or rTF5 == "720" ? 200 : 250
simple int cb6 = rTF6 == "M" or rTF6 == "1M" or rTF6 == "3M" or rTF6 == "6M" or rTF6 == "12M" ? 100 : rTF6 == "W" or rTF6 == "1W" ? 100 : rTF6 == "D" or rTF6 == "1D" ? 150 : rTF6 == "240" or rTF6 == "480" or rTF6 == "720" ? 200 : 250
 
[tf1CurrTime, tf1O, tf1H_curr, tf1L_curr, tf1C, tf1Time, tf1H, tf1L, tf1O_C1, tf1C_C1, tf1MagTime, tf1MagH, tf1MagL, tf1O_C2, tf1C_C2, tf1H_C3, tf1L_C3, tf1H_C4, tf1L_C4, tf1ExhHP, tf1ExhHT, tf1ExhLP, tf1ExhLT, tf1NxHP, tf1NxHT, tf1NxLP, tf1NxLT] = request.security(syminfo.tickerid, rTF1, getDataWithExhaustion(), lookahead = barmerge.lookahead_on, calc_bars_count = cb1)
[tf2CurrTime, tf2O, tf2H_curr, tf2L_curr, tf2C, tf2Time, tf2H, tf2L, tf2O_C1, tf2C_C1, tf2MagTime, tf2MagH, tf2MagL, tf2O_C2, tf2C_C2, tf2H_C3, tf2L_C3, tf2H_C4, tf2L_C4, tf2ExhHP, tf2ExhHT, tf2ExhLP, tf2ExhLT, tf2NxHP, tf2NxHT, tf2NxLP, tf2NxLT] = request.security(syminfo.tickerid, rTF2, getDataWithExhaustion(), lookahead = barmerge.lookahead_on, calc_bars_count = cb2)
[tf3CurrTime, tf3O, tf3H_curr, tf3L_curr, tf3C, tf3Time, tf3H, tf3L, tf3O_C1, tf3C_C1, tf3MagTime, tf3MagH, tf3MagL, tf3O_C2, tf3C_C2, tf3H_C3, tf3L_C3, tf3H_C4, tf3L_C4, tf3ExhHP, tf3ExhHT, tf3ExhLP, tf3ExhLT, tf3NxHP, tf3NxHT, tf3NxLP, tf3NxLT] = request.security(syminfo.tickerid, rTF3, getDataWithExhaustion(), lookahead = barmerge.lookahead_on, calc_bars_count = cb3)
[tf4CurrTime, tf4O, tf4H_curr, tf4L_curr, tf4C, tf4Time, tf4H, tf4L, tf4O_C1, tf4C_C1, tf4MagTime, tf4MagH, tf4MagL, tf4O_C2, tf4C_C2, tf4H_C3, tf4L_C3, tf4H_C4, tf4L_C4, tf4ExhHP, tf4ExhHT, tf4ExhLP, tf4ExhLT, tf4NxHP, tf4NxHT, tf4NxLP, tf4NxLT] = request.security(syminfo.tickerid, rTF4, getDataWithExhaustion(), lookahead = barmerge.lookahead_on, calc_bars_count = cb4)
[tf5CurrTime, tf5O, tf5H_curr, tf5L_curr, tf5C, tf5Time, tf5H, tf5L, tf5O_C1, tf5C_C1, tf5MagTime, tf5MagH, tf5MagL, tf5O_C2, tf5C_C2, tf5H_C3, tf5L_C3, tf5H_C4, tf5L_C4, tf5ExhHP, tf5ExhHT, tf5ExhLP, tf5ExhLT, tf5NxHP, tf5NxHT, tf5NxLP, tf5NxLT] = request.security(syminfo.tickerid, rTF5, getDataWithExhaustion(), lookahead = barmerge.lookahead_on, calc_bars_count = cb5)
[tf6CurrTime, tf6O, tf6H_curr, tf6L_curr, tf6C, tf6Time, tf6H, tf6L, tf6O_C1, tf6C_C1, tf6MagTime, tf6MagH, tf6MagL, tf6O_C2, tf6C_C2, tf6H_C3, tf6L_C3, tf6H_C4, tf6L_C4, tf6ExhHP, tf6ExhHT, tf6ExhLP, tf6ExhLT, tf6NxHP, tf6NxHT, tf6NxLP, tf6NxLT] = request.security(syminfo.tickerid, rTF6, getDataWithExhaustion(), lookahead = barmerge.lookahead_on, calc_bars_count = cb6)
 
// FIX HTF-STRADDLE-1 (T3, probe-validated): completed DAILY sub-bars of the current chart bar, used
// to rebuild the true forming HTF candle for straddled slots. Constant gate: the request either always
// executes (chart above D) or never does - both legal per v6 dynamic requests; charts at/below D never
// need it (probe confirmed clean load on a 1D chart with the gate off).
bool canRecon = timeframe.in_seconds() > timeframe.in_seconds("D")
array<int> reconDT = na
array<float> reconDO = na
array<float> reconDH = na
array<float> reconDL = na
if canRecon
    [rdT, rdO, rdH, rdL] = request.security_lower_tf(syminfo.tickerid, "D", [time, open, high, low])
    reconDT := rdT
    reconDO := rdO
    reconDH := rdH
    reconDL := rdL
 
[ftfc_up, ftfc_down] = calculateFTFC(rEN1, tf1O, tf1C, rEN2, tf2O, tf2C, rEN3, tf3O, tf3C, rEN4, tf4O, tf4C, rEN5, tf5O, tf5C, rEN6, tf6O, tf6C)
 
// FIX HTF-STRADDLE-1: calendar timeframes are the only ones that can straddle a chart bar - their
// period boundaries do not have to align with chart bar opens (months/quarters roll mid-week on a
// weekly chart). Intraday/daily/weekly requests from lower charts always align on session opens.
isCalendarTF(string tf) =>
    tf == "W" or tf == "1W" or tf == "M" or tf == "1M" or tf == "3M" or tf == "6M" or tf == "12M"
 
// FIX HTF-STRADDLE-1 (corrected 2026-07-02, probe-validated): live straddle detection, session aware.
// A futures HTF bar's open is stamped at the prior-evening session (~18:00 ET), so naive month()/
// quarter() on it reads ONE calendar period early (the probe confirmed: the current Q3 quarterly bar
// is stamped 2026-06-30 18:00 -> parses as Q2). Adding +12h before parsing normalizes any period-open
// into its true calendar period, robust across futures (18:00 prior day -> next morning), equities
// (9:30 -> same day) and crypto (00:00 -> same day) without ever overshooting the day.
// Straddle fires ONLY for a calendar slot STRICTLY coarser than the chart (so the chart's own TF can
// never straddle itself) whose served bar's scheduled close has already passed (see shouldStraddle).
OFF_MS = 43200000  // 12h in ms (used by pkeyCal's session-stamp normalization for daily recon)
isStraddleTF(string tf) =>
    isCalendarTF(tf) and timeframe.in_seconds(tf) > chartTfSeconds
// FIX GLUE-2b (2026-07-06): staleness test is now purely time-based: the served HTF bar is
// stale exactly when "now" is past its SCHEDULED CLOSE. The previous calendar-key approach
// (open stamp + 12h) broke on holiday-glued bars: Monday Jul 6's WEEKLY bar opens Thursday
// Jul 2 18:00 ET (Friday's half-session belongs to Monday's trade date), ~84h before its
// true period, so it still parsed as last week and kept a phantom W straddle firing through
// the live Monday session, pinning weekly C1 to the forming week. time_close(tf) is computed
// from the same trade-date calendar that stamps the bars, so it is immune to early opens,
// needs no week-numbering, and is direction-aware (a trade-date bar running AHEAD of the
// calendar, like the glued Friday session inside next week's bar, can never fire it). The
// mid-bar calendar-roll case this feature exists for still works: once the served Q2 bar's
// Jun 30 17:00 close passes, the shift arms for the rest of the straddling chart bar. This
// also obsoletes the 07-02 double-reading hardening: a period-end-afternoon phantom cannot
// occur, because the bar's close has not passed while its session still trades.
shouldStraddle(string tf) =>
    int tc = time_close(tf)
    not na(tc) and timenow > tc
 
// FIX HTF-STRADDLE-1 (T3): comparable period key for a calendar TF from a timestamp. EVERY timestamp
// passed here must be +12h-normalized FIRST (see OFF_MS), so a session-stamped open - e.g. a futures
// period that opens ~18:00 ET on the prior calendar day - lands in its true calendar period. This
// applies to BOTH the served daily-bar opens and "now" (see FIX RECON-KEY-1 at the call site).
pkeyCal(int t, string tf) =>
    m = month(t, "America/New_York")
    y = year(t, "America/New_York")
    w = weekofyear(t, "America/New_York")
    q = m <= 3 ? 1 : m <= 6 ? 2 : m <= 9 ? 3 : 4
    tf == "12M" ? y : tf == "6M" ? y * 10 + (m <= 6 ? 1 : 2) : tf == "3M" ? y * 10 + q : tf == "W" or tf == "1W" ? y * 1000 + w : y * 100 + m
 
// Classic preview (market-closed / previewMode=On projection).
// FIX PREVIEW-WEEKCLOSE-1 (2026-09-04): the weekly slot previews once the served week's SCHEDULED
// CLOSE has passed (shouldStraddle: timenow > time_close(tf)), not on Fri/Sat/Sun by calendar. The
// old test counted all of Friday as weekend, so an Auto preview during Friday pre-market - market
// closed, but the week still had a session to trade - demoted the forming week into C1 and showed W
// as a yellow "?". Friday after the close, the weekend and Monday pre-open all sit past the close,
// so the weekend projection is unchanged. Superseded in form, not in rule, by PREVIEW-CALCLOSE-1
// below, which applies the same test to every calendar TF; the weekly rule lives on inside it.
// FIX PREVIEW-CALCLOSE-1 (2026-09-04): every calendar slot now previews by the rule the weekly branch
// adopted in PREVIEW-WEEKCLOSE-1 above: the served period's SCHEDULED CLOSE has passed
// (shouldStraddle). The old M/3M/6M/12M branches compared month()/year() of timenow against the CHART
// bar's open stamp - the calendar-arithmetic staleness test GLUE-2b retired for straddles. A session-
// stamped futures period (July's bar opens Jun 30 18:00 ET) parsed as the prior month, so the CME
// maintenance hour on the first trade date of each month demoted the current month into C1 and showed
// M as "?". Side effect, intended: month-end evenings preview from the close (16:00 ET equities)
// instead of waiting for calendar midnight. Daily and intraday slots keep the unconditional branch:
// once Auto has established the market is closed (AUTO-SESSION-1), their period is over by definition.
shouldApplyPreview(string tf, bool previewEnabled) =>
    if not previewEnabled
        false
    else if isCalendarTF(tf)
        shouldStraddle(tf)
    else
        true
 
applyPreviewShift(int c1Time, float c1H, float c1L, float c1O, float c1C, int ccTime, float ccO, float ccH, float ccL, float ccC, int c2Time, float c2H, float c2L, float c2O, float c2C, float c3H, float c3L, float c4H, float c4L, float exhHP, int exhHT, float exhLP, int exhLT, float nxHP, int nxHT, float nxLP, int nxLT, string tf, bool previewEnabled, bool straddleEnabled) =>
    // FIX HTF-STRADDLE-1: classic preview OR a session-aware live straddle (calendar slot coarser than chart).
    // FIX GLUE-2b (2026-07-06): straddle = now is past the served HTF bar's scheduled close.
    doPreview = shouldApplyPreview(tf, previewEnabled) or (straddleEnabled and isStraddleTF(tf) and shouldStraddle(tf))
    if doPreview
        newC1Time = ccTime
        newC1H = ccH
        newC1L = ccL
        newC1O = ccO
        newC1C = ccC
        newCCTime = time
        newCCO = ccC
        newCCH = ccH
        newCCL = ccL
        newCCC = (ccH + ccL) / 2
        newC2Time = c1Time
        newC2H = c1H
        newC2L = c1L
        newC2O = c1O
        newC2C = c1C
        newC3H = c2H
        newC3L = c2L
        newC4H = c3H
        newC4L = c3L
        // FIX P0-1: realPeriodTime = the unshifted real current period-open (the `ccTime` param),
        // even in preview where ccTime is reused as the synthetic C1. New-period detection uses this.
        // FIX EXH-PREVIEW-CHANNEL-1: the exhaustion snapshot has to be rebased along with C1/C2, or
        // the projection inherits a target computed BEFORE the period it just promoted. Observed on
        // AMD 1W (Sunday): the completed week of Sep 7-11 traded through the Aug 17 pivot, but the
        // served snapshot had excluded that week, so the broken pivot was still reported intact and
        // drew a weekly exhaustion BELOW the weekly trigger high, in the crossed colour.
        // Gate: shouldStraddle(tf) means the served CC has passed its scheduled close, so the NEXT
        // channel's [0] seed is a finished bar and is reload-stable. previewMode = "On" can force a
        // preview while the served CC is still forming (daily and intraday slots take the
        // unconditional branch of shouldApplyPreview); there the current channel stays, which is the
        // "snapshot slightly behind live price, but reload-stable" tradeoff P0-2 took deliberately.
        bool ccClosed = shouldStraddle(tf)
        float pExhHP = ccClosed ? nxHP : exhHP
        int pExhHT = ccClosed ? nxHT : exhHT
        float pExhLP = ccClosed ? nxLP : exhLP
        int pExhLT = ccClosed ? nxLT : exhLT
        TFRawData.new(newC1Time, newC1H, newC1L, newC1O, newC1C, newCCTime, newCCO, newCCH, newCCL, newCCC, newC2Time, newC2H, newC2L, newC2O, newC2C, newC3H, newC3L, newC4H, newC4L, pExhHP, pExhHT, pExhLP, pExhLT, true, ccTime)
    else
        TFRawData.new(c1Time, c1H, c1L, c1O, c1C, ccTime, ccO, ccH, ccL, ccC, c2Time, c2H, c2L, c2O, c2C, c3H, c3L, c4H, c4L, exhHP, exhHT, exhLP, exhLT, false, ccTime)
 
var array<TFRawData> tfRawArr = array.new<TFRawData>(6)
array.set(tfRawArr, 0, applyPreviewShift(tf1Time, tf1H, tf1L, tf1O_C1, tf1C_C1, tf1CurrTime, tf1O, tf1H_curr, tf1L_curr, tf1C, tf1MagTime, tf1MagH, tf1MagL, tf1O_C2, tf1C_C2, tf1H_C3, tf1L_C3, tf1H_C4, tf1L_C4, tf1ExhHP, tf1ExhHT, tf1ExhLP, tf1ExhLT, tf1NxHP, tf1NxHT, tf1NxLP, tf1NxLT, rTF1, previewNextPeriod, straddleWindowOK))
array.set(tfRawArr, 1, applyPreviewShift(tf2Time, tf2H, tf2L, tf2O_C1, tf2C_C1, tf2CurrTime, tf2O, tf2H_curr, tf2L_curr, tf2C, tf2MagTime, tf2MagH, tf2MagL, tf2O_C2, tf2C_C2, tf2H_C3, tf2L_C3, tf2H_C4, tf2L_C4, tf2ExhHP, tf2ExhHT, tf2ExhLP, tf2ExhLT, tf2NxHP, tf2NxHT, tf2NxLP, tf2NxLT, rTF2, previewNextPeriod, straddleWindowOK))
array.set(tfRawArr, 2, applyPreviewShift(tf3Time, tf3H, tf3L, tf3O_C1, tf3C_C1, tf3CurrTime, tf3O, tf3H_curr, tf3L_curr, tf3C, tf3MagTime, tf3MagH, tf3MagL, tf3O_C2, tf3C_C2, tf3H_C3, tf3L_C3, tf3H_C4, tf3L_C4, tf3ExhHP, tf3ExhHT, tf3ExhLP, tf3ExhLT, tf3NxHP, tf3NxHT, tf3NxLP, tf3NxLT, rTF3, previewNextPeriod, straddleWindowOK))
array.set(tfRawArr, 3, applyPreviewShift(tf4Time, tf4H, tf4L, tf4O_C1, tf4C_C1, tf4CurrTime, tf4O, tf4H_curr, tf4L_curr, tf4C, tf4MagTime, tf4MagH, tf4MagL, tf4O_C2, tf4C_C2, tf4H_C3, tf4L_C3, tf4H_C4, tf4L_C4, tf4ExhHP, tf4ExhHT, tf4ExhLP, tf4ExhLT, tf4NxHP, tf4NxHT, tf4NxLP, tf4NxLT, rTF4, previewNextPeriod, straddleWindowOK))
array.set(tfRawArr, 4, applyPreviewShift(tf5Time, tf5H, tf5L, tf5O_C1, tf5C_C1, tf5CurrTime, tf5O, tf5H_curr, tf5L_curr, tf5C, tf5MagTime, tf5MagH, tf5MagL, tf5O_C2, tf5C_C2, tf5H_C3, tf5L_C3, tf5H_C4, tf5L_C4, tf5ExhHP, tf5ExhHT, tf5ExhLP, tf5ExhLT, tf5NxHP, tf5NxHT, tf5NxLP, tf5NxLT, rTF5, previewNextPeriod, straddleWindowOK))
array.set(tfRawArr, 5, applyPreviewShift(tf6Time, tf6H, tf6L, tf6O_C1, tf6C_C1, tf6CurrTime, tf6O, tf6H_curr, tf6L_curr, tf6C, tf6MagTime, tf6MagH, tf6MagL, tf6O_C2, tf6C_C2, tf6H_C3, tf6L_C3, tf6H_C4, tf6L_C4, tf6ExhHP, tf6ExhHT, tf6ExhLP, tf6ExhLT, tf6NxHP, tf6NxHT, tf6NxLP, tf6NxLT, rTF6, previewNextPeriod, straddleWindowOK))
 
// FIX HTF-STRADDLE-1 (T3, probe-validated 2026-07-02): for a straddle-shifted slot, rebuild the TRUE
// forming HTF candle from the chart bar's daily sub-bars plus the live close, replacing the synthetic
// preview candle. The probe reproduced the finer charts' CC exactly (BTC 1W: f2d including the
// sub-C1-low wick the earlier estimate missed). Gated on shouldStraddle, so a classic next-period
// preview (weekend W/M projection, whose period has no dailies yet) is never overridden; n == 0
// leaves the "?" candle. isPreview stays TRUE: the every-tick preview re-latch is what keeps the
// shifted C1/C2 alive across realtime rollback, and alerts stay conservatively suppressed.
// FIX GLUE-2b (2026-07-06): staleness re-check is time-based (see shouldStraddle).
var array<bool> reconOKArr = array.new<bool>(6, false)
if barstate.islast
    for iS = 0 to 5
        array.set(reconOKArr, iS, false)
        cfgS = array.get(tfConfigs, iS)
        rawS = array.get(tfRawArr, iS)
        if cfgS.enabled and not na(rawS) and rawS.isPreview and canRecon and not na(reconDT) and array.size(reconDT) > 0 and isStraddleTF(cfgS.tf) and shouldStraddle(cfgS.tf)
            // FIX RECON-KEY-1 (2026-07-07, Codex review): normalize "now" by +12h too, matching the
            // daily-bar keys below. It was raw - valid only under the old +12h/raw double-reading
            // straddle test that GLUE-2b removed. Raw "now" keyed one period behind the +12h daily keys
            // for the ~7h between a period's session close and calendar midnight, so recon matched the
            // PRIOR period's dailies at each roll and painted a wrong CC as current. Both keys normalized now.
            int pNow = pkeyCal(timenow + OFF_MS, cfgS.tf)
            float rO = na
            float rH = na
            float rL = na
            int rT = na
            int n = 0
            for jS = 0 to array.size(reconDT) - 1
                if pkeyCal(array.get(reconDT, jS) + OFF_MS, cfgS.tf) == pNow
                    if n == 0
                        rO := array.get(reconDO, jS)
                        rT := array.get(reconDT, jS)
                    rH := na(rH) ? array.get(reconDH, jS) : math.max(rH, array.get(reconDH, jS))
                    rL := na(rL) ? array.get(reconDL, jS) : math.min(rL, array.get(reconDL, jS))
                    n += 1
            if n > 0
                rawS.ccTime := rT
                rawS.ccO := rO
                rawS.ccC := close
                rawS.ccH := math.max(rH, close)
                rawS.ccL := math.min(rL, close)
                array.set(reconOKArr, iS, true)
 
var array<ProcessingResult> tfResults = array.new<ProcessingResult>(6)
 
// ============================================================================
// SECTION 7: MAIN PROCESSING FUNCTION
// ============================================================================
 
// Detect bar type and Failed 2 status (used by processTimeframe and table rendering)
detectBarTypeAndFailed(prevH, prevL, currH, currL, currO, currC) =>
    // GRAMMAR-LIB-1: classification delegates to the library. The gap branches the old
    // body carried are equivalent to the library's range test (differentially verified).
    if na(prevH) or na(prevL) or na(currH) or na(currL) or na(currO) or na(currC) or currH < currL or prevH < prevL
        ["", false]
    else
        // PERF-ALLOC-3: sg.structureOf + sg.isFailed rather than sg.classify. classify
        // builds a BarState object, and this function runs once per chart bar over all
        // history when Strat Candles bar coloring is on, and per bar per slot when stops
        // are on. structureOf and isFailed are pure - the classification still comes from
        // the library, only the object does not. The three lines below are sg.notation()'s
        // projection inlined; the library method remains its definition of record.
        s = sg.structureOf(prevH, prevL, currH, currL)
        aboveOpen = currC > currO
        // FIX P1-f preserved: with Failing 2 detection off, this path shows plain 2s so the
        // table and labels never disagree with the engine.
        isFailed = enableFailed2Detection and sg.isFailed(prevH, prevL, currO, currC, s, failed_2_method)
        barType = s == "1" ? (aboveOpen ? "1u" : "1d") : s == "3" ? (aboveOpen ? "3u" : "3d") : (isFailed ? "F" : "") + s
        [barType, isFailed]
 
computeSignalState(data, tf, raw, showOpen, populateDebug, debugTfStr, syntheticCC) =>
    tfTime = raw.c1Time
    tfH = raw.c1H
    tfL = raw.c1L
    tfO_C1 = raw.c1O
    tfC_C1 = raw.c1C
    tfCurrTime = raw.ccTime
    tfO = raw.ccO
    tfH_curr = raw.ccH
    tfL_curr = raw.ccL
    tfC = raw.ccC
    tfMagTime = raw.c2Time
    tfMagH = raw.c2H
    tfMagL = raw.c2L
    tfO_C2 = raw.c2O
    tfC_C2 = raw.c2C
    tfH_C3 = raw.c3H
    tfL_C3 = raw.c3L
    tfH_C4 = raw.c4H
    tfL_C4 = raw.c4L
    tfExhHP = raw.exhHP
    tfExhHT = raw.exhHT
    tfExhLP = raw.exhLP
    tfExhLT = raw.exhLT
    isInPreview = raw.isPreview
    // FIX P0-1: detect a new HTF period PER SLOT by comparing the security-returned real
    // period-open time against a per-slot stored value. The old `ta.change(time(tf)) != 0`
    // shared ONE history buffer across all 6 loop iterations (computeSignalState has a single
    // written call site inside `for i = 5 to 0`), so its [1] compared this bar's time(tfA)
    // against the previous bar's last-iteration time(tfB) and fired on nearly every bar -
    // constantly wiping the crossed-flag "came back" memory and the sticky stops. No ta.* state.
    // FIX P1-d: also re-latch when preview has just EXITED mid-period (no real rollover);
    // otherwise the preview-shifted prevHigh/prevMag persist until the next genuine period.
    bool prevWasPreview = data.wasPreview
    newPeriod = na(data.lastPeriodStart) or raw.realPeriodTime != data.lastPeriodStart
    if newPeriod or (isInPreview and barstate.islast) or (prevWasPreview and not isInPreview)
        data.magHighCrossed := false
        data.magLowCrossed := false
        data.exhHighCrossed := false
        data.exhLowCrossed := false
        data.stopHighTriggered := false
        data.stopLowTriggered := false
        data.stopHighPrice := na
        data.stopLowPrice := na
        data.prevHigh := tfH
        data.prevLow := tfL
        data.prevTime := tfTime
        data.prevMagHigh := tfMagH
        data.prevMagLow := tfMagL
        data.prevMagTime := tfMagTime
        data.exhHighPrice := tfExhHP
        data.exhHighTime := tfExhHT
        data.exhLowPrice := tfExhLP
        data.exhLowTime := tfExhLT
        data.lastPeriodStart := raw.realPeriodTime
    data.wasPreview := isInPreview
    data.currOpen := tfO
    validTimeframe = timeframe.in_seconds() <= timeframe.in_seconds(tf)
    float retHigh = na, float retLow = na, float retOpen = na, float retMagHigh = na, float retMagLow = na, float retExhHigh = na, float retExhLow = na
    color retHighColor = na, color retLowColor = na, color retOpenColor = na, color retMagHighColor = na, color retMagLowColor = na, color retExhHighColor = na, color retExhLowColor = na
    bool retDrawHigh = false, bool retDrawLow = false, bool retDrawOpen = false, bool retDrawMagHigh = false, bool retDrawMagLow = false, bool retDrawExhHigh = false, bool retDrawExhLow = false
    int retTime = na, bool retIsF2u = false, bool retIsF2d = false, bool retC1Is3 = false
    string retC3Num = "", string retC2Num = "", string retC1Num = "", string retC1Type = "", string retCCType = ""
    bool retC1WasF2 = false, bool retC2WasF2 = false
    bool retSignalInForceHigh = false, bool retSignalInForceLow = false
    float retStopHigh = na, float retStopLow = na, bool retDrawStopHigh = false, bool retDrawStopLow = false
    bool retPreF2u = false, bool retPreF2d = false, float retF2OpenPrice = na
    string retHighStyle = "Dashed", string retLowStyle = "Dashed"
    if validTimeframe and not na(data.prevHigh)
        // FIX PREVIEW-CROSSED-1 (2026-09-13): a synthetic preview CC cannot cross anything. The
        // placeholder applyPreviewShift builds copies the promoted C1's range exactly (newCCH = ccH,
        // newCCL = ccL), so tfH_curr/tfL_curr ARE last period's extremes and these >= / <= tests
        // flagged every magnitude and exhaustion level inside that range as already crossed, on a
        // period that has not traded a tick. The flags are not only colour: they feed
        // exhDisablesInForce, break-even stops, TAW removal and exhDisablesFTFC. Reconstructed
        // straddle slots keep the tests, their CC being real daily-derived data (HTF-STRADDLE-1 T3);
        // that is exactly the distinction syntheticCC carries. isPreview itself is untouched, so the
        // realtime-rollback re-latch and the alert/Lead conservatism are unchanged.
        if not syntheticCC
            if not na(data.prevMagHigh) and not data.magHighCrossed and tfH_curr >= data.prevMagHigh
                data.magHighCrossed := true
            if not na(data.prevMagLow) and not data.magLowCrossed and tfL_curr <= data.prevMagLow
                data.magLowCrossed := true
            if not na(data.exhHighPrice) and not data.exhHighCrossed and tfH_curr >= data.exhHighPrice
                data.exhHighCrossed := true
            if not na(data.exhLowPrice) and not data.exhLowCrossed and tfL_curr <= data.exhLowPrice
                data.exhLowCrossed := true
        // FIX P1-a: run the detection + sticky-stop latch on every bar when stops are enabled,
        // not only on barstate.islast. The stop "locks for the period" semantic requires the
        // latch to have fired on the bars where the signal went in force; with the old islast
        // gate, a chart reload (those bars now historical) never re-armed the latch and the
        // locked stop vanished. Gated on showStopLevels so the common case (stops off, default)
        // keeps the original islast-only cost - no performance change unless stops are on.
        if barstate.islast or showStopLevels
            [isHammer, isShooter] = detectPatterns(tfO_C1, tfH, tfL, tfC_C1)
            isInside = isInsideBar(tfH, tfL, tfMagH, tfMagL)
            data.c1IsInside := isInside
            data.c1IsHammer := isHammer
            data.c1IsShooter := isShooter
            [cc_is_2u, cc_is_2d, cc_is_3, is_f2u, is_f2d, pre_f2u, pre_f2d] = detectFailed2(data.prevHigh, data.prevLow, tfO, tfC, tfH_curr, tfL_curr, failed_2_method)
            retIsF2u := is_f2u
            retIsF2d := is_f2d
            retC3Num := calcBarNum(tfH_C4, tfL_C4, tfH_C3, tfL_C3)
            retC2Num := calcBarNum(tfH_C3, tfL_C3, tfMagH, tfMagL)
            retC1Num := calcBarNum(tfMagH, tfMagL, tfH, tfL)
            string c1Type = calcBarType(tfMagH, tfMagL, tfH, tfL, tfO_C1, tfC_C1)
            if is_f2u
                retCCType := "F2u"
            else if is_f2d
                retCCType := "F2d"
            else if cc_is_3
                retCCType := tfC > tfO ? "3u" : "3d"
            else if cc_is_2u
                retCCType := "2u"
            else if cc_is_2d
                retCCType := "2d"
            else
                retCCType := "1"
            retC1Type := c1Type
            // Detect if C1/C2 were themselves Failed 2s (for label accuracy)
            [_c1BarType, c1f2flag] = detectBarTypeAndFailed(tfMagH, tfMagL, tfH, tfL, tfO_C1, tfC_C1)
            [_c2BarType, c2f2flag] = detectBarTypeAndFailed(tfH_C3, tfL_C3, tfMagH, tfMagL, tfO_C2, tfC_C2)
            retC1WasF2 := c1f2flag
            retC2WasF2 := c2f2flag
            cc_broke_high = tfH_curr > data.prevHigh
            cc_broke_low = tfL_curr < data.prevLow
            c1_broke_mag_high = tfH > tfMagH
            c1_broke_mag_low = tfL < tfMagL
            c1_was_2u = c1_broke_mag_high and not c1_broke_mag_low
            c1_was_2d = c1_broke_mag_low and not c1_broke_mag_high
            c2_broke_c3_high = tfMagH > tfH_C3
            c2_broke_c3_low = tfMagL < tfL_C3
            c2_was_2u = c2_broke_c3_high and not c2_broke_c3_low
            c2_was_2d = c2_broke_c3_low and not c2_broke_c3_high
            // FIX CONT22-PRIOR-1: still computed, but no longer gates 2-2 continuations.
            // Its only consumer now is the debug panel, where it stays as diagnostic context.
            c2_was_3 = c2_broke_c3_high and c2_broke_c3_low
            c2_closed_up = tfC_C2 > tfO_C2
            c2_closed_down = tfC_C2 < tfO_C2
 
            // C1 F2d (bullish): broke C2 low but closed back inside range
            // C1 F2u (bearish): broke C2 high but closed back inside range
            c1_was_f2d = c1_was_2d and tfC_C1 > tfMagL  // broke low, closed above it
            c1_was_f2u = c1_was_2u and tfC_C1 < tfMagH  // broke high, closed below it
 
            c1_was_neutral = not c1_was_2u and not c1_was_2d
            inside_bullish = isInside and c2_closed_up
            inside_bearish = isInside and c2_closed_down
            is_hammer_reversal = c1_was_2d or inside_bearish or (c1_was_neutral and not isInside)
            is_shooter_reversal = c1_was_2u or inside_bullish or (c1_was_neutral and not isInside)
            is_hammer_momo = c1_was_2u or inside_bullish
            is_shooter_momo = c1_was_2d or inside_bearish
            hammer_shows = isHammer and (is_hammer_reversal or (is_hammer_momo and showContinuations))
            shooter_shows = isShooter and (is_shooter_reversal or (is_shooter_momo and showContinuations))
            inside_cont_high_passes_momo = not insideContOnlyMomo or isHammer
            inside_cont_low_passes_momo = not insideContOnlyMomo or isShooter
            twotwo_cont_high_passes_momo = not twoTwoContOnlyMomo or isHammer
            twotwo_cont_low_passes_momo = not twoTwoContOnlyMomo or isShooter
            c1_is_3 = tfH > tfMagH and tfL < tfMagL
            retC1Is3 := c1_is_3
            is_22_cont_high = c1_was_2u and c2_was_2u and showContinuations and twotwo_cont_high_passes_momo
            is_22_cont_low = c1_was_2d and c2_was_2d and showContinuations and twotwo_cont_low_passes_momo
            is_32_cont_high = c1_is_3 and cc_is_2u and showRangeExpansions
            is_32_cont_low = c1_is_3 and cc_is_2d and showRangeExpansions
            twotwo_rev_high_passes = (not reversalsRequireActionable or isHammer) and (not reversalsRequireC1F2 or c1_was_f2d)
            twotwo_rev_low_passes = (not reversalsRequireActionable or isShooter) and (not reversalsRequireC1F2 or c1_was_f2u)
 
            p3_high_passes_ftfc = not p3RequireFTFC or ftfc_up
            p3_low_passes_ftfc = not p3RequireFTFC or ftfc_down
            // FIX CSS-1: a flat (doji) C2 counts as an inside reversal in-force, matching the draw path
            // (shouldDrawC1Level treats flat C2 as a reversal). The old strict c2_closed_down/c2_closed_up
            // left flat-C2 inside reversals drawn + alerting but never marked in-force, so the table, the
            // sticky stop latch, and the "only when in force" target/TAW gates all disagreed with the line.
            // FEATURE DEBUG-TERMS-1: the in-force terms are named rather than inlined into one
            // expression, so the debug panel reports the same booleans the signal is built from and
            // cannot drift out of sync with this line the way a re-derived copy would.
            t_insideRev_h  = isInside and not c2_closed_up and cc_is_2u
            t_insideCont_h = inside_bullish and showInsideContinuations and inside_cont_high_passes_momo and cc_is_2u
            t_hamSho_h     = hammer_shows and cc_broke_high
            t_rev22_h      = showAllReversals and c1_was_2d and cc_is_2u and twotwo_rev_high_passes
            t_cont22_h     = showContinuations and c1_was_2u and cc_is_2u and twotwo_cont_high_passes_momo   // FIX CONT22-PRIOR-1: `and not c2_was_3` removed, matching the draw branch
            t_exp32_h      = showRangeExpansions and c1_is_3 and cc_is_2u
            t_f2_h         = show_p3_toggle and is_f2d and p3_high_passes_ftfc
            // FIX OUTSIDE-IF-1 (2026-11-05): an outside bar (3) has broken both sides of C1, so it is
            // in force toward the side it closes beyond: above C1's high is bull, below C1's low is
            // bear, closed back inside C1 is neither. The "price beyond trigger" half comes from
            // currently_above/below_trigger below, and the FTFC gate from drawHigh/drawLow
            // (shouldDrawC1Level's 3 branch), exactly as for every other term. Before this, a 3 only
            // got through on the hammer/shooter path, so the Lead Signal and stops ignored it while
            // the data table lit the timeframe on any enabled 3.
            t_exp3_h       = show3Expansions and cc_is_3
            t_insideRev_l  = isInside and not c2_closed_down and cc_is_2d
            t_insideCont_l = inside_bearish and showInsideContinuations and inside_cont_low_passes_momo and cc_is_2d
            t_hamSho_l     = shooter_shows and cc_broke_low
            t_rev22_l      = showAllReversals and c1_was_2u and cc_is_2d and twotwo_rev_low_passes
            t_cont22_l     = showContinuations and c1_was_2d and cc_is_2d and twotwo_cont_low_passes_momo   // FIX CONT22-PRIOR-1: as t_cont22_h
            t_exp32_l      = showRangeExpansions and c1_is_3 and cc_is_2d
            t_f2_l         = show_p3_toggle and is_f2u and p3_low_passes_ftfc
            t_exp3_l       = show3Expansions and cc_is_3
            signal_in_force_high = t_insideRev_h or t_insideCont_h or t_hamSho_h or t_rev22_h or t_cont22_h or t_exp32_h or t_exp3_h or t_f2_h
            signal_in_force_low = t_insideRev_l or t_insideCont_l or t_hamSho_l or t_rev22_l or t_cont22_l or t_exp32_l or t_exp3_l or t_f2_l
            // For directional filter, signal is only "currently in force" if price is still beyond the trigger
            currently_above_trigger = tfC > data.prevHigh
            currently_below_trigger = tfC < data.prevLow
            three_2u_suppress_low = c1_is_3 and cc_is_2u and not is_f2u
            three_2d_suppress_high = c1_is_3 and cc_is_2d and not is_f2d
            cc_3u_suppress_low = cc_is_3 and tfC > tfO
            cc_3d_suppress_high = cc_is_3 and tfC <= tfO
            inside_breakout_suppress_low = isInside and cc_broke_high and not is_f2u and not cc_is_3
            inside_breakout_suppress_high = isInside and cc_broke_low and not is_f2d and not cc_is_3
            // F2 filter for 2-2 reversals: suppress draw when C1 wasn't itself a Failed 2
            // Skip suppression when CC has an active F2 (range reclaim signal draws both sides)
            twotwo_rev_f2_suppress_high = reversalsRequireC1F2 and c1_was_2d and not c1_was_f2d and not c1_is_3 and not isInside and not is_f2u and not is_f2d
            twotwo_rev_f2_suppress_low = reversalsRequireC1F2 and c1_was_2u and not c1_was_f2u and not c1_is_3 and not isInside and not is_f2u and not is_f2d
            [drawHighResult, isHighContinuation] = shouldDrawC1High(isInside, isHammer, isShooter, cc_is_2u, cc_is_2d, cc_is_3, is_f2u, is_f2d, ftfc_up, ftfc_down, c1_was_2u, c1_was_2d, c1_is_3, c2_closed_up, c2_closed_down)
            [drawLowResult, isLowContinuation] = shouldDrawC1Low(isInside, isShooter, isHammer, cc_is_2u, cc_is_2d, cc_is_3, is_f2u, is_f2d, ftfc_up, ftfc_down, c1_was_2u, c1_was_2d, c1_is_3, c2_closed_up, c2_closed_down)
            drawHigh = drawHighResult and not three_2d_suppress_high and not inside_breakout_suppress_high and not twotwo_rev_f2_suppress_high
            drawLow = drawLowResult and not three_2u_suppress_low and not inside_breakout_suppress_low and not twotwo_rev_f2_suppress_low
            // signalInForce must also require drawHigh/drawLow to align with user settings
            // If exhDisablesInForce is on, exhausted signals are not considered in force
            // If no exhaustion level exists, magnitude serves the same function
            // F2 signals are "in force" when the F2 detection conditions are met (per user's method),
            //         without requiring price beyond the opposite trigger. For non-F2 signals, still require
            //         price beyond trigger (currently_above/below_trigger).
            bool magFallbackHigh = na(data.exhHighPrice) and not na(data.prevMagHigh) and data.magHighCrossed
            bool magFallbackLow = na(data.exhLowPrice) and not na(data.prevMagLow) and data.magLowCrossed
            exhDisablesHigh = exhDisablesInForce and (data.exhHighCrossed or magFallbackHigh)
            exhDisablesLow = exhDisablesInForce and (data.exhLowCrossed or magFallbackLow)
            // Non-F2 in-force requires price beyond trigger; F2 in-force is confirmed by detection itself
            non_f2_in_force_high = signal_in_force_high and not is_f2d and currently_above_trigger
            f2_in_force_high = show_p3_toggle and is_f2d and drawHigh and p3_high_passes_ftfc
            non_f2_in_force_low = signal_in_force_low and not is_f2u and currently_below_trigger
            f2_in_force_low = show_p3_toggle and is_f2u and drawLow and p3_low_passes_ftfc
            // Raw in-force (before exhaustion gate) - used for stop triggers
            // Exhaustion disabling affects signal display/filtering, not protective stops
            bool rawInForceHigh = (non_f2_in_force_high or f2_in_force_high) and drawHigh
            bool rawInForceLow = (non_f2_in_force_low or f2_in_force_low) and drawLow
            retSignalInForceHigh := rawInForceHigh and not exhDisablesHigh
            retSignalInForceLow := rawInForceLow and not exhDisablesLow
            // Sticky stop triggers - once in force this period, stop persists
            // F2 signals always use CC (the failed candle defines the trade)
            // Non-F2: CC mode = breakout bar's opposite side, C1 mode = prior bar's opposite side
            // CC mode: update each bar to track running CC extreme (consistent across chart TFs)
            // C1 mode: lock on first trigger (stable, uses completed prior candle)
            useCC = stopReference == "CC"
            if rawInForceHigh and not data.stopHighTriggered
                data.stopHighTriggered := true
                data.stopHighPrice := (is_f2d or useCC) ? tfL_curr : data.prevLow
            else if data.stopHighTriggered and (is_f2d or useCC)
                data.stopHighPrice := tfL_curr
            if rawInForceLow and not data.stopLowTriggered
                data.stopLowTriggered := true
                data.stopLowPrice := (is_f2u or useCC) ? tfH_curr : data.prevHigh
            else if data.stopLowTriggered and (is_f2u or useCC)
                data.stopLowPrice := tfH_curr
            // Break even: move stop to entry trigger when magnitude/exhaustion is hit
            // Bullish stop (stopHigh) protects long → BE = prevHigh (entry level, moves stop up)
            // Bearish stop (stopLow) protects short → BE = prevLow (entry level, moves stop down)
            if data.stopHighTriggered
                bool magHitHigh = data.magHighCrossed and not na(data.prevMagHigh)
                bool exhHitHigh = data.exhHighCrossed and not na(data.exhHighPrice)
                bool noMagHigh = na(data.prevMagHigh)
                bool noExhHigh = na(data.exhHighPrice)
                bool beMagTriggerHigh = stopBEatMag and (magHitHigh or (noMagHigh and exhHitHigh))
                bool beExhTriggerHigh = stopBEatExh and (exhHitHigh or (noExhHigh and magHitHigh))
                if beMagTriggerHigh or beExhTriggerHigh
                    data.stopHighPrice := data.prevHigh
            if data.stopLowTriggered
                bool magHitLow = data.magLowCrossed and not na(data.prevMagLow)
                bool exhHitLow = data.exhLowCrossed and not na(data.exhLowPrice)
                bool noMagLow = na(data.prevMagLow)
                bool noExhLow = na(data.exhLowPrice)
                bool beMagTriggerLow = stopBEatMag and (magHitLow or (noMagLow and exhHitLow))
                bool beExhTriggerLow = stopBEatExh and (exhHitLow or (noExhLow and magHitLow))
                if beMagTriggerLow or beExhTriggerLow
                    data.stopLowPrice := data.prevLow
            data.c1IsHighContinuation := isHighContinuation
            data.c1IsLowContinuation := isLowContinuation
            cc_above_open_for_mag = tfC > tfO
            threeExp_show_mag_high = cc_is_3 and show3Expansions and show3ExpMagnitude and (not threeExpRequireFTFC or ftfc_up) and cc_above_open_for_mag
            threeExp_show_mag_low = cc_is_3 and show3Expansions and show3ExpMagnitude and (not threeExpRequireFTFC or ftfc_down) and not cc_above_open_for_mag
            // FIX CSS-2: require global showExhaustion, mirroring how outside-bar magnitude requires
            // global showMagnitude (via force_mag). Was asymmetric: OB exhaustion drew with Show Exhaustion off.
            threeExp_show_exh_high = cc_is_3 and show3Expansions and showExhaustion and show3ExpExhaustion and (not threeExpRequireFTFC or ftfc_up) and cc_above_open_for_mag
            threeExp_show_exh_low = cc_is_3 and show3Expansions and showExhaustion and show3ExpExhaustion and (not threeExpRequireFTFC or ftfc_down) and not cc_above_open_for_mag
            // Gate inside→3 mag behind show3Expansions to prevent orphan magnitude when 3-exp display is off
            inside_3u_setup = isInside and cc_is_3 and cc_above_open_for_mag and show3Expansions and (not threeExpRequireFTFC or ftfc_up)
            inside_3d_setup = isInside and cc_is_3 and not cc_above_open_for_mag and show3Expansions and (not threeExpRequireFTFC or ftfc_down)
            // Directional F2 mag/exh suppression
            // F2u (failed bullish breakout → bearish): suppress bullish mag/exh (upside failed)
            // F2d (failed bearish breakout → bullish): suppress bearish mag/exh (downside failed)
            p3_suppress_mag_high = is_f2u
            p3_suppress_mag_low = is_f2d
            cont_suppress_mag_high = is_22_cont_high or is_32_cont_high
            cont_suppress_mag_low = is_22_cont_low or is_32_cont_low
 
            high_suppress_base = three_2d_suppress_high or inside_breakout_suppress_high or cc_3d_suppress_high
            low_suppress_base = three_2u_suppress_low or inside_breakout_suppress_low or cc_3u_suppress_low
 
            exh_high_valid = not na(data.exhHighPrice) and data.exhHighPrice != data.prevHigh
            exh_low_valid = not na(data.exhLowPrice) and data.exhLowPrice != data.prevLow
 
            cont_show_exh_high = showExhaustion and drawHigh and cont_suppress_mag_high
            cont_show_exh_low = showExhaustion and drawLow and cont_suppress_mag_low
 
            force_mag_high = showMagnitude and (drawHigh or inside_3u_setup or threeExp_show_mag_high) and not p3_suppress_mag_high and not cont_suppress_mag_high
            force_mag_low = showMagnitude and (drawLow or inside_3d_setup or threeExp_show_mag_low) and not p3_suppress_mag_low and not cont_suppress_mag_low
            mag_high_passes_ftfc = true
            mag_low_passes_ftfc = true
            // FIX PREVIEW-CROSSED-1: second synthetic-hit path. These feed exhRequiresMagHit
            // independently of the magHighCrossed/magLowCrossed latches, so guarding only the
            // latches would still let a placeholder CC "hit" magnitude and unlock exhaustion.
            price_hit_mag_high = not syntheticCC and tfH_curr >= data.prevMagHigh
            price_hit_mag_low = not syntheticCC and tfL_curr <= data.prevMagLow
            exh_high_mag_filter = not exhRequiresMagHit or price_hit_mag_high
            exh_low_mag_filter = not exhRequiresMagHit or price_hit_mag_low
 
            exh_high_base_condition = showExhaustion and mag_high_passes_ftfc and exh_high_mag_filter and exh_high_valid and data.exhHighPrice != data.prevLow and data.exhHighPrice != data.prevMagLow and not high_suppress_base and not p3_suppress_mag_high
            exh_low_base_condition = showExhaustion and mag_low_passes_ftfc and exh_low_mag_filter and exh_low_valid and data.exhLowPrice != data.prevHigh and data.exhLowPrice != data.prevMagHigh and not low_suppress_base and not p3_suppress_mag_low
            drawExhHigh = ((exh_high_base_condition and drawHigh) or (exh_high_base_condition and data.exhHighCrossed) or (cont_show_exh_high and exh_high_valid) or (threeExp_show_exh_high and exh_high_valid)) and (not exhOnlyWhenInForce or rawInForceHigh)
            drawExhLow = ((exh_low_base_condition and drawLow) or (exh_low_base_condition and data.exhLowCrossed) or (cont_show_exh_low and exh_low_valid) or (threeExp_show_exh_low and exh_low_valid)) and (not exhOnlyWhenInForce or rawInForceLow)
            exh_high_same_as_mag = drawExhHigh and data.exhHighPrice == data.prevMagHigh
            exh_low_same_as_mag = drawExhLow and data.exhLowPrice == data.prevMagLow
            mag_high_same_as_trigger = data.prevMagHigh == data.prevHigh
            mag_low_same_as_trigger = data.prevMagLow == data.prevLow
            // shouldDrawMagnitude fallback requires drawHigh/drawLow to prevent orphan mag lines
            //         when signal toggles are off but signal_in_force fires
            drawMagHigh = ((force_mag_high and mag_high_passes_ftfc and not c1_broke_mag_high) or (drawHigh and shouldDrawMagnitude(c1_broke_mag_high, signal_in_force_high))) and not high_suppress_base and not exh_high_same_as_mag and not p3_suppress_mag_high and not cont_suppress_mag_high and not mag_high_same_as_trigger and (not magOnlyWhenInForce or rawInForceHigh)
            drawMagLow = ((force_mag_low and mag_low_passes_ftfc and not c1_broke_mag_low) or (drawLow and shouldDrawMagnitude(c1_broke_mag_low, signal_in_force_low))) and not low_suppress_base and not exh_low_same_as_mag and not p3_suppress_mag_low and not cont_suppress_mag_low and not mag_low_same_as_trigger and (not magOnlyWhenInForce or rawInForceLow)
            if populateDebug
                debugData.tfLabel := getTimeframeLabel(debugTfStr)
                debugData.c1_was_2u := c1_was_2u
                debugData.c1_was_2d := c1_was_2d
                debugData.c1_is_3 := c1_is_3
                debugData.c2_was_2u := c2_was_2u
                debugData.c2_was_2d := c2_was_2d
                debugData.c2_was_3 := c2_was_3
                debugData.c2_closed_up := c2_closed_up
                debugData.c2_closed_down := c2_closed_down
                debugData.isHammer := isHammer
                debugData.isShooter := isShooter
                debugData.isInside := isInside
                debugData.cc_is_2u := cc_is_2u
                debugData.cc_is_2d := cc_is_2d
                debugData.cc_is_3 := cc_is_3
                debugData.cc_broke_high := cc_broke_high
                debugData.cc_broke_low := cc_broke_low
                debugData.is_f2u := is_f2u
                debugData.is_f2d := is_f2d
                debugData.pre_f2u := pre_f2u
                debugData.pre_f2d := pre_f2d
                debugData.ftfc_up := ftfc_up
                debugData.ftfc_down := ftfc_down
                debugData.is_hammer_reversal := is_hammer_reversal
                debugData.is_hammer_momo := is_hammer_momo
                debugData.hammer_shows := hammer_shows
                debugData.is_shooter_reversal := is_shooter_reversal
                debugData.is_shooter_momo := is_shooter_momo
                debugData.shooter_shows := shooter_shows
                debugData.sif_high := signal_in_force_high
                debugData.sif_low := signal_in_force_low
                debugData.t_insideRev_h := t_insideRev_h
                debugData.t_insideRev_l := t_insideRev_l
                debugData.t_insideCont_h := t_insideCont_h
                debugData.t_insideCont_l := t_insideCont_l
                debugData.t_hamSho_h := t_hamSho_h
                debugData.t_hamSho_l := t_hamSho_l
                debugData.t_rev22_h := t_rev22_h
                debugData.t_rev22_l := t_rev22_l
                debugData.t_cont22_h := t_cont22_h
                debugData.t_cont22_l := t_cont22_l
                debugData.t_exp32_h := t_exp32_h
                debugData.t_exp32_l := t_exp32_l
                debugData.t_exp3_h := t_exp3_h
                debugData.t_exp3_l := t_exp3_l
                debugData.t_f2_h := t_f2_h
                debugData.t_f2_l := t_f2_l
                debugData.drawHigh := drawHigh
                debugData.drawLow := drawLow
                debugData.drawMagHigh := drawMagHigh
                debugData.drawMagLow := drawMagLow
                debugData.drawExhHigh := drawExhHigh
                debugData.drawExhLow := drawExhLow
                debugData.force_mag_high := force_mag_high
                debugData.force_mag_low := force_mag_low
                debugData.mag_high_passes_ftfc := mag_high_passes_ftfc
                debugData.mag_low_passes_ftfc := mag_low_passes_ftfc
            highColor = color.gray
            lowColor = color.gray
            highStyle = "Dashed"
            lowStyle = "Dashed"
            cc_is_inside = not cc_broke_high and not cc_broke_low and not cc_is_3
            if drawHigh
                if cc_is_3
                    cc_close_below = tfC < data.prevLow
                    cc_closing_up = tfC > tfO
                    highColor := COLOR_3_HIGH
                    if show3Expansions and cc_closing_up and not cc_close_below
                        highStyle := "Dashed"
                    else
                        highStyle := "Solid"
                else if is_f2d
                    highColor := COLOR_FAILED_2D
                    highStyle := "Solid"
                else if c1_is_3 and cc_is_2u
                    highColor := colorBullishActive
                    highStyle := "Dashed"
                else if c1_is_3 and cc_is_inside
                    highColor := COLOR_INSIDE_HIGH
                    highStyle := "Dashed"
                else if c1_is_3
                    highColor := COLOR_3_HIGH
                    highStyle := "Solid"
                else if cc_broke_high
                    highColor := colorBullishActive
                    highStyle := "Dashed"
                else if cc_is_inside
                    highColor := COLOR_INSIDE_HIGH
                    highStyle := "Dashed"
                else
                    highColor := colorBullishActive
                    highStyle := "Dashed"
            if drawLow
                if cc_is_3
                    cc_close_above = tfC > data.prevHigh
                    cc_closing_down = tfC < tfO
                    lowColor := COLOR_3_LOW
                    if show3Expansions and cc_closing_down and not cc_close_above
                        lowStyle := "Dashed"
                    else
                        lowStyle := "Solid"
                else if is_f2u
                    lowColor := COLOR_FAILED_2U
                    lowStyle := "Solid"
                else if c1_is_3 and cc_is_2d
                    lowColor := colorBearishActive
                    lowStyle := "Dashed"
                else if c1_is_3 and cc_is_inside
                    lowColor := COLOR_INSIDE_LOW
                    lowStyle := "Dashed"
                else if c1_is_3
                    lowColor := COLOR_3_LOW
                    lowStyle := "Solid"
                else if cc_broke_low
                    lowColor := colorBearishActive
                    lowStyle := "Dashed"
                else if cc_is_inside
                    lowColor := COLOR_INSIDE_LOW
                    lowStyle := "Dashed"
                else
                    lowColor := colorBearishActive
                    lowStyle := "Dashed"
            // F2 override: side being failed goes dashed (color preserved from pattern logic)
            if is_f2u or pre_f2u
                highStyle := "Dashed"
            if is_f2d or pre_f2d
                lowStyle := "Dashed"
            retHighStyle := highStyle
            retLowStyle := lowStyle
            // Compute phase: populate return values from draw conditions
            periodDuration = timeframe.in_seconds(tf) * 1000
            // FIX LINEEND-CLOSE-1 (2026-09-08): lines and boxes run to the served bar's SCHEDULED CLOSE
            // when that is later than open + one nominal period. ES's Labor Day bar (Sun 18:00 -> Tue
            // 17:00 ET, the holiday session glued into Tuesday's trade date) is 47h long, so open + 24h
            // ended every D line and box at Monday's reopen, a day short of the live candles: "the daily
            // levels are a day behind." The same shortfall hit 31-day months (in_seconds("M") is a
            // nominal month) and glued weekly bars. max() keeps the normal-day geometry pixel-identical
            // (open + period already reaches past the close there) and only extends on long bars.
            // Preview slots keep open + period: their ccTime is the chart bar and their served close is
            // the stale period's, so time_close(tf) would shorten the projection instead of extending it.
            int slotClose = validTimeframe and not isInPreview ? time_close(tf) : na
            lineEndTime = na(slotClose) ? tfCurrTime + periodDuration : math.max(tfCurrTime + periodDuration, slotClose)
            if drawHigh
                retHigh := data.prevHigh
                retHighColor := highColor
                retDrawHigh := true
                retTime := lineEndTime
            if drawLow
                retLow := data.prevLow
                retLowColor := lowColor
                retDrawLow := true
                retTime := lineEndTime
            bool f2SuppressesOpen = (is_f2u or is_f2d or pre_f2u or pre_f2d) and showF2OpenLine
            if showOpen and (drawHigh or drawLow) and not f2SuppressesOpen
                retOpen := data.currOpen
                retOpenColor := color.gray
                retDrawOpen := true
                retTime := lineEndTime
            if drawMagHigh
                retMagHigh := data.prevMagHigh
                retMagHighColor := data.magHighCrossed ? COLOR_HIT_HIGH : colorBullishActive
                retDrawMagHigh := true
                retTime := lineEndTime
            if drawMagLow
                retMagLow := data.prevMagLow
                retMagLowColor := data.magLowCrossed ? COLOR_HIT_LOW : colorBearishActive
                retDrawMagLow := true
                retTime := lineEndTime
            if drawExhHigh
                retExhHigh := data.exhHighPrice
                retExhHighColor := data.exhHighCrossed ? COLOR_HIT_HIGH : colorBullishActive
                retDrawExhHigh := true
                retTime := lineEndTime
            if drawExhLow
                retExhLow := data.exhLowPrice
                retExhLowColor := data.exhLowCrossed ? COLOR_HIT_LOW : colorBearishActive
                retDrawExhLow := true
                retTime := lineEndTime
            drawStopHigh = showStopLevels and data.stopHighTriggered
            drawStopLow = showStopLevels and data.stopLowTriggered
            if drawStopHigh and not na(data.stopHighPrice)
                retStopHigh := data.stopHighPrice
                retDrawStopHigh := true
            if drawStopLow and not na(data.stopLowPrice)
                retStopLow := data.stopLowPrice
                retDrawStopLow := true
            // F2 open price for pre-F2 and confirmed F2
            if pre_f2d and not na(tfO)
                retPreF2d := true
                retF2OpenPrice := tfO
            else if is_f2d and not na(tfO)
                retF2OpenPrice := tfO
            if pre_f2u and not na(tfO)
                retPreF2u := true
                retF2OpenPrice := tfO
            else if is_f2u and not na(tfO)
                retF2OpenPrice := tfO
    tfLabelStr = getTimeframeLabel(tf)
    ProcessingResult.new(retHigh, retLow, retOpen, retMagHigh, retMagLow, retExhHigh, retExhLow, retHighColor, retLowColor, retOpenColor, retMagHighColor, retMagLowColor, retExhHighColor, retExhLowColor, retDrawHigh, retDrawLow, retDrawOpen, retDrawMagHigh, retDrawMagLow, retDrawExhHigh, retDrawExhLow, retTime, tfLabelStr, retIsF2u, retIsF2d, retC1Is3, retC3Num, retC2Num, retC1Num, retC1Type, retCCType, retSignalInForceHigh, retSignalInForceLow, retStopHigh, retStopLow, retDrawStopHigh, retDrawStopLow, retPreF2u, retPreF2d, retF2OpenPrice, tfCurrTime, retC1WasF2, retC2WasF2, retHighStyle, retLowStyle)
 
 
// Render signal levels based on fully-resolved ProcessingResult flags
// Called AFTER directional filter has modified flags, so no draw-then-delete needed
renderSignalLevels(TimeframeData data, ProcessingResult r, int lineWidth, int lineEndTime) =>
    if barstate.islast and not na(r)
        // High trigger line
        if r.drawHigh
            data.highLine := updateOrCreateLine(data.highLine, data.prevTime, r.high, lineEndTime, r.high, r.highColor, lineWidth, getLineStyle(r.highStyle))
        else
            data.highLine := deleteLine(data.highLine)
        // Low trigger line
        if r.drawLow
            data.lowLine := updateOrCreateLine(data.lowLine, data.prevTime, r.low, lineEndTime, r.low, r.lowColor, lineWidth, getLineStyle(r.lowStyle))
        else
            data.lowLine := deleteLine(data.lowLine)
        // Open reference line
        if r.drawOpen
            data.openLine := updateOrCreateLine(data.openLine, r.ccStartTime, r.open, lineEndTime, r.open, color.gray, lineWidth, line.style_dotted)
        else
            data.openLine := deleteLine(data.openLine)
        // Magnitude high
        if r.drawMagHigh
            data.magHighLine := updateOrCreateLine(data.magHighLine, data.prevMagTime, r.magHigh, lineEndTime, r.magHigh, r.magHighColor, lineWidth, line.style_solid)
        else
            data.magHighLine := deleteLine(data.magHighLine)
        // Magnitude low
        if r.drawMagLow
            data.magLowLine := updateOrCreateLine(data.magLowLine, data.prevMagTime, r.magLow, lineEndTime, r.magLow, r.magLowColor, lineWidth, line.style_solid)
        else
            data.magLowLine := deleteLine(data.magLowLine)
        // Exhaustion high
        if r.drawExhHigh
            data.exhHighLine := updateOrCreateLine(data.exhHighLine, data.exhHighTime, r.exhHigh, lineEndTime, r.exhHigh, r.exhHighColor, lineWidth, line.style_solid)
        else
            data.exhHighLine := deleteLine(data.exhHighLine)
        // Exhaustion low
        if r.drawExhLow
            data.exhLowLine := updateOrCreateLine(data.exhLowLine, data.exhLowTime, r.exhLow, lineEndTime, r.exhLow, r.exhLowColor, lineWidth, line.style_solid)
        else
            data.exhLowLine := deleteLine(data.exhLowLine)
        // Stop high (bullish signal stop at C1 low)
        bool stopHighOverlaps = r.drawStopHigh and not na(r.stopHigh) and not na(r.high) and math.round(r.stopHigh / syminfo.mintick) == math.round(r.high / syminfo.mintick)
        if r.drawStopHigh and not na(r.stopHigh) and not stopHighOverlaps
            data.stopHighLine := updateOrCreateLine(data.stopHighLine, r.ccStartTime, r.stopHigh, lineEndTime, r.stopHigh, colorStopHigh, lineWidth, line.style_solid)
        else
            data.stopHighLine := deleteLine(data.stopHighLine)
        // Stop low (bearish signal stop at C1 high)
        bool stopLowOverlaps = r.drawStopLow and not na(r.stopLow) and not na(r.low) and math.round(r.stopLow / syminfo.mintick) == math.round(r.low / syminfo.mintick)
        if r.drawStopLow and not na(r.stopLow) and not stopLowOverlaps
            data.stopLowLine := updateOrCreateLine(data.stopLowLine, r.ccStartTime, r.stopLow, lineEndTime, r.stopLow, colorStopLow, lineWidth, line.style_solid)
        else
            data.stopLowLine := deleteLine(data.stopLowLine)
        // F2 open reference line
        bool f2OpenOverlapsLow = not na(r.f2OpenPrice) and not na(r.low) and math.round(r.f2OpenPrice / syminfo.mintick) == math.round(r.low / syminfo.mintick)
        bool f2OpenOverlapsHigh = not na(r.f2OpenPrice) and not na(r.high) and math.round(r.f2OpenPrice / syminfo.mintick) == math.round(r.high / syminfo.mintick)
        bool drawF2Open = showF2OpenLine and not na(r.f2OpenPrice) and (r.preF2d or r.preF2u or r.isF2d or r.isF2u)
        if drawF2Open
            color f2Color = r.preF2d ? colorBullishActive : r.isF2d ? COLOR_FAILED_2D : r.preF2u ? colorBearishActive : COLOR_FAILED_2U
            bool f2Overlaps = (r.preF2d or r.isF2d) ? f2OpenOverlapsLow : f2OpenOverlapsHigh
            if not f2Overlaps
                data.f2OpenLine := updateOrCreateLine(data.f2OpenLine, r.ccStartTime, r.f2OpenPrice, lineEndTime, r.f2OpenPrice, f2Color, lineWidth, line.style_dotted)
            else
                data.f2OpenLine := deleteLine(data.f2OpenLine)
        else
            data.f2OpenLine := deleteLine(data.f2OpenLine)
        // Action window boxes
        data.actionWindowBullish := deleteBox(data.actionWindowBullish)
        data.actionWindowBearish := deleteBox(data.actionWindowBearish)
        // FIX TAW-1: each direction must check only its OWN trigger. The old guards required
        // BOTH r.high and r.low to be non-na, but the opposite trigger is suppressed exactly when
        // a signal goes in force (inside_breakout_suppress_low/high nulls the other side, and
        // one-sided directional signals never draw it). That made the main magnitude/exhaustion
        // Take Action Window unable to render for in-force signals - the default config. Each box's
        // geometry only uses its own side (bullish: prevMagHigh..r.high; bearish: r.low..prevMagLow),
        // so requiring the opposite trigger was both unnecessary and the cause of the window vanishing.
        bool currentlyAboveTrigger = not na(r.high) and close > r.high
        bool currentlyBelowTrigger = not na(r.low) and close < r.low
        bool isF2uSignal = r.isF2u
        bool isF2dSignal = r.isF2d
        bool ccIs3 = str.startswith(r.ccType, "3")
        if showTakeActionWindows or tawExtendToExhaustion
            bool p3SuppressHigh = isF2uSignal
            bool p3SuppressLow = isF2dSignal
            mag_bullish_qualifies = showTakeActionWindows and r.drawHigh and not p3SuppressHigh and not ccIs3 and (not tawOnlyWhenInForce or r.signalInForceHigh) and currentlyAboveTrigger
            mag_bearish_qualifies = showTakeActionWindows and r.drawLow and not p3SuppressLow and not ccIs3 and (not tawOnlyWhenInForce or r.signalInForceLow) and currentlyBelowTrigger
            exh_bullish_qualifies = tawExtendToExhaustion and r.drawExhHigh and not p3SuppressHigh and not ccIs3 and (not tawExhOnlyWhenInForce or r.signalInForceHigh) and currentlyAboveTrigger
            exh_bearish_qualifies = tawExtendToExhaustion and r.drawExhLow and not p3SuppressLow and not ccIs3 and (not tawExhOnlyWhenInForce or r.signalInForceLow) and currentlyBelowTrigger
            if exh_bullish_qualifies and not na(data.exhHighPrice) and not data.exhHighCrossed
                data.actionWindowBullish := updateOrCreateBox(data.actionWindowBullish, data.prevTime, data.exhHighPrice, lineEndTime, r.high, tawBullishFill, tawBullishBorder)
            else if mag_bullish_qualifies and not na(data.prevMagHigh) and not data.magHighCrossed
                data.actionWindowBullish := updateOrCreateBox(data.actionWindowBullish, data.prevTime, data.prevMagHigh, lineEndTime, r.high, tawBullishFill, tawBullishBorder)
            if exh_bearish_qualifies and not na(data.exhLowPrice) and not data.exhLowCrossed
                data.actionWindowBearish := updateOrCreateBox(data.actionWindowBearish, data.prevTime, r.low, lineEndTime, data.exhLowPrice, tawBearishFill, tawBearishBorder)
            else if mag_bearish_qualifies and not na(data.prevMagLow) and not data.magLowCrossed
                data.actionWindowBearish := updateOrCreateBox(data.actionWindowBearish, data.prevTime, r.low, lineEndTime, data.prevMagLow, tawBearishFill, tawBearishBorder)
        if showP3TakeActionWindows and show_p3_toggle
            if isF2dSignal and r.drawHigh and not currentlyAboveTrigger and (not tawOnlyWhenInForce or r.signalInForceHigh)
                data.actionWindowBullish := updateOrCreateBox(data.actionWindowBullish, data.prevTime, r.high, lineEndTime, r.low, tawBullishFill, tawBullishBorder)
            if isF2uSignal and r.drawLow and not currentlyBelowTrigger and (not tawOnlyWhenInForce or r.signalInForceLow)
                data.actionWindowBearish := updateOrCreateBox(data.actionWindowBearish, data.prevTime, r.high, lineEndTime, r.low, tawBearishFill, tawBearishBorder)
        if show3ExpTakeActionWindows and show3Expansions and ccIs3
            bool ccExpandingUp = str.endswith(r.ccType, "u")
            if ccExpandingUp and r.drawHigh and not na(data.prevMagHigh) and not data.magHighCrossed and (not tawOnlyWhenInForce or r.signalInForceHigh)
                data.actionWindowBullish := updateOrCreateBox(data.actionWindowBullish, data.prevTime, data.prevMagHigh, lineEndTime, r.high, tawBullishFill, tawBullishBorder)
            if not ccExpandingUp and r.drawLow and not na(data.prevMagLow) and not data.magLowCrossed and (not tawOnlyWhenInForce or r.signalInForceLow)
                data.actionWindowBearish := updateOrCreateBox(data.actionWindowBearish, data.prevTime, r.low, lineEndTime, data.prevMagLow, tawBearishFill, tawBearishBorder)
    true
 
 
// ============================================================================
// EZ-MODE: TEACHING LAYER (hover text and the Explain row)
// ============================================================================
// TheStrat was created by Rob Smith. The explanations below are this script's own wording
// of his concepts. Where this script's usage differs from the classic one (3u/3d and
// exhaustion), the hover says so.
 
// Hover text for one bar-type cell. `live` is true for the forming bar.
ezBarTip(string t, string tf, bool live) =>
    string which = live ? "The current " + tf + " bar (still forming)" : "This closed " + tf + " bar"
    string openUp = live ? "It is trading above its own open." : "It closed above its own open."
    string openDn = live ? "It is trading below its own open." : "It closed below its own open."
    switch t
        "1u" => "1 = inside bar. " + which + " has not taken the high or the low of the bar before it. Price is paused and must eventually break one side. " + openUp
        "1d" => "1 = inside bar. " + which + " has not taken the high or the low of the bar before it. Price is paused and must eventually break one side. " + openDn
        "2u" => "2u = " + which + " took out the prior bar's high and not its low. Buyers were willing to pay up."
        "2d" => "2d = " + which + " took out the prior bar's low and not its high. Sellers were willing to sell down."
        "F2u" => "F2u = Failing 2u. " + which + " took out the prior bar's high, but price is back below this bar's own open (red). Buyers took the level and sellers took the bar back. If it also breaks the prior low it becomes a 3."
        "F2d" => "F2d = Failing 2d. " + which + " took out the prior bar's low, but price is back above this bar's own open (green). Sellers took the level and buyers took the bar back. If it also breaks the prior high it becomes a 3."
        "3u" => "3 = outside bar. " + which + " took out both the high and the low of the bar before it. The u means it is above its own open. (Classic usage keeps 3u for a 3 that closes above the prior bar's high.)"
        "3d" => "3 = outside bar. " + which + " took out both the high and the low of the bar before it. The d means it is below its own open. (Classic usage keeps 3d for a 3 that closes below the prior bar's low.)"
        => "No bar to read here yet."
 
// Plain name for a combo string such as 2d-2u or *3-1-2u.
ezComboName(string combo) =>
    string c = str.replace_all(str.replace_all(combo, "-", ""), "*", "")
    string n = "combo"
    if str.endswith(c, "12u") or str.endswith(c, "12d")
        n := str.startswith(c, "3") ? "3-1-2 (an outside bar, an inside bar, then the break)" : "inside bar break (price paused inside the prior bar, then picked a side)"
    else if str.endswith(c, "2d2u") or str.endswith(c, "2u2d")
        n := str.startswith(c, "1") ? "1-2-2 RevStrat (an inside bar broke one way, then price reversed)" : str.startswith(c, "3") ? "3-2-2 reversal (an outside bar, a 2 one way, then a 2 back the other way)" : "2-2 reversal (a bar trending one way, answered by a bar trending the other way)"
    else if str.endswith(c, "2u2u") or str.endswith(c, "2d2d")
        n := "2-2 continuation (the trend keeps going the same way)"
    else if str.endswith(c, "32u") or str.endswith(c, "32d")
        n := "3-2 (an outside bar, then a break of one of its sides)"
    n
 
// Hover text for one label piece. side: 1 = label above price (highs), -1 = below (lows), 0 = opens.
ezPieceTip(string piece, string px, int side) =>
    int sp = str.pos(piece, " ")
    string tf = na(sp) ? "" : str.substring(piece, 0, sp)
    string body = na(sp) ? piece : str.substring(piece, sp + 1)
    string dirWord = side == 1 ? "bullish" : "bearish"
    string out = ""
    if str.endswith(piece, "STOP")
        // A bullish signal's stop sits below price, so it is collected with the lows.
        string stopDir = side == -1 ? "bullish" : "bearish"
        string stopMove = side == -1 ? "back below" : "back above"
        out := tf == "" ? "A stop level also sits at this price." : tf + " STOP (" + px + "): the stop for the " + stopDir + " " + tf + " signal. If price trades " + stopMove + " this level, the idea is wrong. Treat it as a reference level, not a full risk plan."
    else if str.endswith(body, "OPEN")
        out := tf + " OPEN (" + px + "): where the " + tf + " bar opened. Above it the bar is green, below it red. Full Timeframe Continuity compares price with these opens."
    else if str.contains(body, "MAG") or str.contains(body, "TARGET")
        out := tf + " magnitude (" + px + "): the target for the " + dirWord + " " + tf + " signal. It is the far side of the range the signal is moving back into. Once price gets here the signal has done what it measured."
    else if str.contains(body, "EXH") or str.contains(body, "FINAL")
        out := tf + " exhaustion (" + px + "): the next prior " + (side == 1 ? "high" : "low") + " beyond magnitude, where the move may run out of room. Rob Smith used \"exhaustion risk\" for a signal running out of time or reaching its magnitude. This level is this script's price-based version of that idea."
    else if str.contains(body, "F2u") or str.contains(body, "F2d") or str.contains(body, "FAILING")
        out := tf + " Failing 2 (" + px + "): the " + tf + " bar broke this level but price is back on the wrong side of the bar's own open. The break is failing. If the bar goes on to break its other side it becomes a 3 (outside bar)."
    else if str.contains(body, "*")
        bool toOutside = str.contains(body, "3u") or str.contains(body, "3d") or str.contains(body, "OUT")
        string becomes = toOutside ? "a 3 (outside bar), because it has already taken the other side" : side == 1 ? "a 2u" : "a 2d"
        out := tf + " trigger (" + px + "), not hit yet. If price trades " + (side == 1 ? "above" : "below") + " this level, the " + tf + " bar becomes " + becomes + "." + (toOutside or simpleLabelMode ? "" : " That would put this combo in force: a " + ezComboName(body) + ".")
    else if simpleLabelMode
        string word = str.contains(body, "REV") ? "REV = reversal: a bar trending one way answered by a bar trending the other way." : str.contains(body, "CONT") ? "CONT = continuation: the trend keeps going the same way." : str.contains(body, "INS") ? "INS = inside bar break: price paused inside the prior bar, then picked a side." : str.contains(body, "EXP") ? "EXP = expansion: the range is getting wider, as with an outside bar." : "OUT = outside bar: both sides of the prior bar taken."
        out := tf + " level (" + px + "). " + word + " The arrow shows the direction a break of this level points."
    else
        bool lastUp = str.endswith(body, "2u") or str.endswith(body, "2u HAM") or str.endswith(body, "2u SHO")
        bool lastDn = str.endswith(body, "2d") or str.endswith(body, "2d HAM") or str.endswith(body, "2d SHO")
        bool last3 = str.contains(body, "3u") or str.contains(body, "3d")
        if (lastUp and side == 1) or (lastDn and side == -1)
            out := tf + " " + body + " (" + px + "): in force. The " + tf + " bar traded " + (side == 1 ? "above the prior bar's high" : "below the prior bar's low") + ", which put this combo in force: a " + ezComboName(body) + ". It stays in force while price holds " + (side == 1 ? "above" : "below") + " this level and the " + tf + " bar is still open."
        else if lastUp or lastDn
            out := tf + " (" + px + "): the other side of the " + tf + " bar. This bar has already taken the prior " + (lastUp ? "high" : "low") + ". If it also trades " + (side == 1 ? "above" : "below") + " this level it becomes a 3 (outside bar)."
        else if last3
            out := tf + " (" + px + "): the " + tf + " bar is a 3 (outside bar). It has taken both the high and the low of the bar before it, and this is the " + (side == 1 ? "high" : "low") + " it took."
        else
            out := tf + " level (" + px + ")."
    if str.contains(body, "HAM")
        out := out + " HAM: the prior bar is a hammer (long lower wick, closed near its high), which adds weight to the upside."
    if str.contains(body, "SHO")
        out := out + " SHO: the prior bar is a shooter (long upper wick, closed near its low), which adds weight to the downside."
    out
 
// Simple table: a prior bar's type without the open-side letter (1u -> 1, 3d -> 3).
ezPlain(string t) =>
    str.startswith(t, "1") ? "1" : str.startswith(t, "3") ? "3" : t
 
// Hover text for a whole label. Labels at the same price are joined with " + ".
ezLabelTip(string txt, float price, int side) =>
    string px = str.tostring(price, format.mintick)
    string out = ""
    for piece in str.split(txt, " + ")
        out := out + (out == "" ? "" : "\n\n") + ezPieceTip(piece, px, side)
    out
 
// ============================================================================
// SECTION 8: LABEL COLLECTION & CONSOLIDATION
// ============================================================================
 
var SimpleLabelData highLabels = SimpleLabelData.new(array.new<float>(), array.new<string>(), array.new<color>(), array.new<int>())
var SimpleLabelData lowLabels = SimpleLabelData.new(array.new<float>(), array.new<string>(), array.new<color>(), array.new<int>())
var SimpleLabelData openLabels = SimpleLabelData.new(array.new<float>(), array.new<string>(), array.new<color>(), array.new<int>())
// FIX P1-i: label pool replaces the delete-all-and-recreate-every-tick pattern. Labels are
// updated in place via setters; surplus pooled labels are trimmed after each render. acquireLabel
// takes the pool object by reference so it can advance the cursor (functions cannot mutate globals).
var LabelPoolT lblPool = LabelPoolT.new(array.new<label>(), 0)
 
// FIX LABELTEXT-1: a label's text color is its LINE's color - but the line is drawn on the
// chart background while the text sits on the label's own background, and nothing ever
// checked that the two read against each other. The bearish "Crossed" default (#4a4a4a) as
// text on the default label background (#2e2e2e) is 1.53:1, invisible: crossing a low-side
// magnitude or exhaustion level turned its label into a black tab. Only the low side broke -
// the bullish Crossed default (#9c9c9c) happens to pass at 4.95:1. Line colors are untouched;
// only text is lifted, and only when it would not read, so every existing visual cue survives.
// Threshold is 3.0:1 - WCAG AA for large text and UI components, the right bar for a chart
// label rather than the 4.5:1 body-text bar.
//
// Measured against labelBackgroundColor as configured, NOT against that color alpha-composited
// over chart.bg_color. The composite is more correct in theory and was tried first; it was
// rejected on evidence. Two reasons. It predicts that most of the palette is unreadable on a
// light chart (3_LOW 1.85:1, gray 2.03, bearish Signal 2.06, 3_HIGH 2.25), which the actual
// chart contradicts - those labels read fine, only the one gray does not. And once composited
// there is no single threshold that isolates the broken color on both light and dark charts:
// it would have to sit above 1.64 (broken, dark chart) and below 1.85 (next-worst, light
// chart), a 0.21-wide window, which is not a threshold, it is a coincidence. Against the
// configured background the same separation is 1.53 vs 3.12, so 3.0 sits in a 1.59-wide gap.
// If a future report flags the missing composite, this is why. That distinction decides the whole fix: against
// the default label background #4a4a4a sits at 1.53:1 while all eleven other palette colors
// sit at 3.12:1 or better, so 3.0 rescues the one broken color and leaves the rest bit-for-bit
// untouched. A 4.5 threshold repaints the entire palette pastel to fix one gray.
srgbLin(float v) =>
    v <= 0.03928 ? v / 12.92 : math.pow((v + 0.055) / 1.055, 2.4)
 
// 255.0, not 255: if color.r/g/b ever hand back an int, int/int is integer division and every
// channel collapses to 0 - every color would read as black, contrast would compute as ~1.0
// against anything, and the guard below would repaint every label white. The float literal
// makes the division float regardless of what the built-ins return.
relLum(color c) =>
    0.2126 * srgbLin(color.r(c) / 255.0) + 0.7152 * srgbLin(color.g(c) / 255.0) + 0.0722 * srgbLin(color.b(c) / 255.0)
 
contrastOn(color fg, color bg) =>
    lf = relLum(fg)
    lb = relLum(bg)
    (math.max(lf, lb) + 0.05) / (math.min(lf, lb) + 0.05)
 
// Walk the text color toward white (or black, on a light background) until it clears the bar.
// Returns fg unchanged when it already reads, so a passing palette is bit-for-bit untouched.
readableOn(color fg, color bg) =>
    color out = fg
    // Hysteresis on purpose: only intervene below 3.0, but once intervening climb to 3.5.
    // Stopping the instant it clears 3.0 leaves the rescued color sitting on the threshold
    // (#4a4a4a lands at 3.03:1, still hard to read); 3.5 gives it real margin.
    if contrastOn(fg, bg) < 3.0
        float tr = relLum(bg) < 0.18 ? 255.0 : 0.0
        float srcR = color.r(fg)
        float srcG = color.g(fg)
        float srcB = color.b(fg)
        for i = 1 to 12
            k = i / 12.0
            cand = color.rgb(srcR + (tr - srcR) * k, srcG + (tr - srcG) * k, srcB + (tr - srcB) * k, 0)
            out := cand
            if contrastOn(cand, bg) >= 3.5
                break
    out
 
acquireLabel(pool, int x, float y, string txt, bool useBarIndex, color bg, color txtCol, sz, string tip) =>
    xl = useBarIndex ? xloc.bar_index : xloc.bar_time
    label lbl = na
    if pool.used < array.size(pool.items)
        lbl := array.get(pool.items, pool.used)
        label.set_xloc(lbl, x, xl)
        label.set_y(lbl, y)
        label.set_text(lbl, txt)
        label.set_color(lbl, bg)
        label.set_textcolor(lbl, txtCol)
        label.set_size(lbl, sz)
        label.set_style(lbl, label.style_label_left)
    else
        lbl := label.new(x, y, txt, xloc = xl, style = label.style_label_left, color = bg, textcolor = txtCol, size = sz)
        array.push(pool.items, lbl)
    label.set_tooltip(lbl, tip)  // EZ-MODE
    pool.used += 1
    lbl
 
collectTimeframeLabels(TimeframeData data, ProcessingResult r) =>
    ccIsInside = r.ccType == "1"
    ccIs3 = str.startswith(r.ccType, "3")
    // Detect if stop is at break even (same price as trigger level)
    bool stopHighAtBE = r.drawStopHigh and not na(r.stopHigh) and not na(r.high) and math.round(r.stopHigh / syminfo.mintick) == math.round(r.high / syminfo.mintick)
    bool stopLowAtBE = r.drawStopLow and not na(r.stopLow) and not na(r.low) and math.round(r.stopLow / syminfo.mintick) == math.round(r.low / syminfo.mintick)
    if r.drawHigh or r.drawLow
        patternSuffixHigh = data.c1IsHammer ? " HAM" : ""
        patternSuffixLow = data.c1IsShooter ? " SHO" : ""
        string comboStrHigh = ""
        string comboStrLow = ""
        bool c1IsInside = r.c1Num == "1"
        bool is22Pattern = r.c1Num == "2"
        bool is32Pattern = r.c1Num == "3"
        bool isDoubleInside = r.c1Num == "1" and r.c2Num == "1"
        // F2-aware display strings for label accuracy
        string c1TypeF2 = (r.c1WasF2 and show_p3_toggle ? "F" : "") + r.c1Type
        string c1NumF2 = (r.c1WasF2 and show_p3_toggle ? "F" : "") + r.c1Num
        string c2NumF2 = (r.c2WasF2 and show_p3_toggle ? "F" : "") + r.c2Num
        if simpleLabelMode
            // Universal labels: ↑/↓ direction + REV, CONT, INS, OUT, EXP, and the FAILING overlay.
            // Abbreviated 2026-08-03 - consolidated labels stack several timeframes on one line.
            string simpleHigh = ""
            string simpleLow = ""
            bool ccIs2u = str.startswith(r.ccType, "2u")
            bool ccIs2d = str.startswith(r.ccType, "2d")
            // Step 1: Base labels from pattern type
            if ccIs3
                simpleHigh := "↑EXP"
                simpleLow := "↓EXP"
            else if is32Pattern and ccIs2u
                simpleHigh := "↑EXP"
                simpleLow := "*OUT"
            else if is32Pattern and ccIs2d
                simpleHigh := "*OUT"
                simpleLow := "↓EXP"
            else if is32Pattern
                simpleHigh := "↑EXP"
                simpleLow := "↓EXP"
            else if c1IsInside
                if ccIsInside
                    simpleHigh := "*↑INS"
                    simpleLow := "*↓INS"
                else
                    simpleHigh := "↑INS"
                    simpleLow := "↓INS"
            else if ccIsInside
                simpleHigh := data.c1IsHighContinuation ? "*↑CONT" : "*↑REV"
                simpleLow := data.c1IsLowContinuation ? "*↓CONT" : "*↓REV"
            else
                simpleHigh := data.c1IsHighContinuation ? "↑CONT" : "↑REV"
                simpleLow := data.c1IsLowContinuation ? "↓CONT" : "↓REV"
            // Step 2: Apply ◆ confidence indicator to base label (before FAILING overlay)
            if data.c1IsHammer
                simpleHigh := simpleHigh + "◆"
            if data.c1IsShooter
                simpleLow := simpleLow + "◆"
            // Step 3: F2 overlay - failing side keeps base label + FAILING, opposite side is potential outside
            if show_p3_toggle and (r.isF2u or r.preF2u)
                // Bullish breakout failing: high label appends FAILING, low is potential outside
                simpleHigh := simpleHigh + " FAILING"
                simpleLow := "*OUT"
            else if show_p3_toggle and (r.isF2d or r.preF2d)
                // Bearish breakout failing: low label appends FAILING, high is potential outside
                simpleLow := simpleLow + " FAILING"
                simpleHigh := "*OUT"
            comboStrHigh := simpleHigh
            comboStrLow := simpleLow
            // Diamond already applied above, clear suffix to avoid doubling
            patternSuffixHigh := ""
            patternSuffixLow := ""
        else
            // Full combo mode
            if ccIsInside
                if isDoubleInside
                    comboStrHigh := "*" + r.c3Num + c2NumF2 + c1NumF2 + "2u"
                    comboStrLow := "*" + r.c3Num + c2NumF2 + c1NumF2 + "2d"
                else if c1IsInside
                    comboStrHigh := "*" + c2NumF2 + c1NumF2 + "2u"
                    comboStrLow := "*" + c2NumF2 + c1NumF2 + "2d"
                else if is32Pattern
                    comboStrHigh := "*32u"
                    comboStrLow := "*32d"
                else
                    if r.c2Num == "3"
                        comboStrHigh := "*3" + c1TypeF2 + "2u"
                        comboStrLow := "*3" + c1TypeF2 + "2d"
                    // FEATURE REVSTRAT-122-1 (2026-11-13): an inside C2 names the 1-2-2 RevStrat
                    // the same way a C2 3 names the 3-2-2, so a pending 1-2d waiting on CC reads *1-2d-2u.
                    else if r.c2Num == "1"
                        comboStrHigh := "*1" + c1TypeF2 + "2u"
                        comboStrLow := "*1" + c1TypeF2 + "2d"
                    else
                        comboStrHigh := "*" + c1TypeF2 + "2u"
                        comboStrLow := "*" + c1TypeF2 + "2d"
            else
                // Strip F2 prefix from ccType for base combo (F2 overlay handles it separately)
                string baseCCType = r.ccType
                if r.isF2u
                    baseCCType := "2u"
                else if r.isF2d
                    baseCCType := "2d"
                string defaultCombo = ""
                // FEATURE REVSTRAT-122-1: C2 inside (1) leads the combo like C2 3 does, so a 1-2-2
                // RevStrat labels 1-2d-2u instead of 2d-2u. Labels only: signal logic, levels and
                // inputs are unchanged (the 2-2 Reversals row already trades it). F2 labels below
                // keep their C1-prior-only form.
                string c2Prefix = is22Pattern and (r.c2Num == "3" or r.c2Num == "1") ? r.c2Num : ""
                if is22Pattern
                    defaultCombo := c2Prefix + c1TypeF2 + baseCCType
                else if is32Pattern
                    defaultCombo := "3" + baseCCType
                else if isDoubleInside
                    defaultCombo := r.c3Num + c2NumF2 + c1NumF2 + baseCCType
                else
                    defaultCombo := c2NumF2 + c1NumF2 + baseCCType
                // F2 labels: failing side = c1Type + F2 tag, opposite side = potential outside
                // NOTATION-1: canonical uppercase F2 (case no longer marks liveness)
                if show_p3_toggle and r.isF2u
                    comboStrHigh := c1TypeF2 + "F2u"
                    comboStrLow := "*" + c1TypeF2 + "3d"
                else if show_p3_toggle and r.isF2d
                    comboStrLow := c1TypeF2 + "F2d"
                    comboStrHigh := "*" + c1TypeF2 + "3u"
                else
                    comboStrHigh := defaultCombo
                    comboStrLow := defaultCombo
        if r.drawHigh
            string highText = r.tfLabel + " " + formatCombo(comboStrHigh) + patternSuffixHigh + (showHighLowInLabel ? " H" : "") + (stopHighAtBE ? " + STOP" : "")
            array.push(highLabels.prices, r.high)
            array.push(highLabels.texts, highText)
            array.push(highLabels.colors, r.highColor)
            array.push(highLabels.times, r.time)
        if r.drawLow
            string lowText = r.tfLabel + " " + formatCombo(comboStrLow) + patternSuffixLow + (showHighLowInLabel ? " L" : "") + (stopLowAtBE ? " + STOP" : "")
            array.push(lowLabels.prices, r.low)
            array.push(lowLabels.texts, lowText)
            array.push(lowLabels.colors, r.lowColor)
            array.push(lowLabels.times, r.time)
    if r.drawOpen
        array.push(openLabels.prices, r.open)
        array.push(openLabels.texts, r.tfLabel + " OPEN")
        array.push(openLabels.colors, r.openColor)
        array.push(openLabels.times, r.time)
    if r.drawMagHigh
        array.push(highLabels.prices, r.magHigh)
        array.push(highLabels.texts, r.tfLabel + (simpleLabelMode ? " TARGET" : " MAG") + (showHighLowInLabel ? " H" : ""))
        array.push(highLabels.colors, r.magHighColor)
        array.push(highLabels.times, r.time)
    if r.drawMagLow
        array.push(lowLabels.prices, r.magLow)
        array.push(lowLabels.texts, r.tfLabel + (simpleLabelMode ? " TARGET" : " MAG") + (showHighLowInLabel ? " L" : ""))
        array.push(lowLabels.colors, r.magLowColor)
        array.push(lowLabels.times, r.time)
    if r.drawExhHigh
        array.push(highLabels.prices, r.exhHigh)
        array.push(highLabels.texts, r.tfLabel + (simpleLabelMode ? " FINAL" : " EXH") + (showHighLowInLabel ? " H" : ""))
        array.push(highLabels.colors, r.exhHighColor)
        array.push(highLabels.times, r.time)
    if r.drawExhLow
        array.push(lowLabels.prices, r.exhLow)
        array.push(lowLabels.texts, r.tfLabel + (simpleLabelMode ? " FINAL" : " EXH") + (showHighLowInLabel ? " L" : ""))
        array.push(lowLabels.colors, r.exhLowColor)
        array.push(lowLabels.times, r.time)
    // Stop labels - bullish stop at C1 low (lowLabels), bearish stop at C1 high (highLabels)
    // Skip when at break even (consolidated into trigger label above)
    if r.drawStopHigh and not stopHighAtBE
        array.push(lowLabels.prices, r.stopHigh)
        array.push(lowLabels.texts, r.tfLabel + " STOP")
        array.push(lowLabels.colors, colorStopHigh)
        array.push(lowLabels.times, r.time)
    if r.drawStopLow and not stopLowAtBE
        array.push(highLabels.prices, r.stopLow)
        array.push(highLabels.texts, r.tfLabel + " STOP")
        array.push(highLabels.colors, colorStopLow)
        array.push(highLabels.times, r.time)
    // Pre-F2: CC open shown as potential trigger level
    // Skip if open price matches C1 level (FAILING label already marks that price)
    // NOTATION-1: pre-F2 uses the standard '*' potential prefix (*F2d/*F2u), confirmed drops it
    if showF2OpenLine and r.preF2d and not na(r.f2OpenPrice)
        bool preF2dOpenOverlaps = math.round(r.f2OpenPrice / syminfo.mintick) == math.round(r.low / syminfo.mintick)
        if not preF2dOpenOverlaps
            array.push(highLabels.prices, r.f2OpenPrice)
            array.push(highLabels.texts, r.tfLabel + (simpleLabelMode ? " OPEN" : " *F2d"))
            array.push(highLabels.colors, colorBullishActive)
            array.push(highLabels.times, r.time)
    if showF2OpenLine and r.preF2u and not na(r.f2OpenPrice)
        bool preF2uOpenOverlaps = math.round(r.f2OpenPrice / syminfo.mintick) == math.round(r.high / syminfo.mintick)
        if not preF2uOpenOverlaps
            array.push(lowLabels.prices, r.f2OpenPrice)
            array.push(lowLabels.texts, r.tfLabel + (simpleLabelMode ? " OPEN" : " *F2u"))
            array.push(lowLabels.colors, colorBearishActive)
            array.push(lowLabels.times, r.time)
    // Confirmed F2: CC open as trigger reference (dotted line needs label)
    // Gate: show if at least one side is drawing (trend-aligned F2 keeps one side,
    // counter-trend suppresses both via directional filter)
    if showF2OpenLine and r.isF2d and not r.preF2d and not na(r.f2OpenPrice) and (r.drawHigh or r.drawLow)
        bool f2dOpenOverlaps = math.round(r.f2OpenPrice / syminfo.mintick) == math.round(r.low / syminfo.mintick)
        if not f2dOpenOverlaps
            array.push(highLabels.prices, r.f2OpenPrice)
            array.push(highLabels.texts, r.tfLabel + (simpleLabelMode ? " OPEN" : " F2d"))
            array.push(highLabels.colors, COLOR_FAILED_2D)
            array.push(highLabels.times, r.time)
    if showF2OpenLine and r.isF2u and not r.preF2u and not na(r.f2OpenPrice) and (r.drawHigh or r.drawLow)
        bool f2uOpenOverlaps = math.round(r.f2OpenPrice / syminfo.mintick) == math.round(r.high / syminfo.mintick)
        if not f2uOpenOverlaps
            array.push(lowLabels.prices, r.f2OpenPrice)
            array.push(lowLabels.texts, r.tfLabel + (simpleLabelMode ? " OPEN" : " F2u"))
            array.push(lowLabels.colors, COLOR_FAILED_2U)
            array.push(lowLabels.times, r.time)
 
consolidateAndCreate(labelData, pool, int ezSide) =>
    numLabels = array.size(labelData.prices)
    if numLabels > 0
        consolidatedPrices = array.new<float>()
        consolidatedTexts = array.new<string>()
        consolidatedColors = array.new<color>()
        consolidatedTimes = array.new<int>()
        // v2.2.0: Map-based dedup replaces O(n^2) inner loop
        var priceToIndex = map.new<float, int>()
        map.clear(priceToIndex)
        for i = 0 to numLabels - 1
            currentPrice = array.get(labelData.prices, i)
            currentText = array.get(labelData.texts, i)
            currentColor = array.get(labelData.colors, i)
            currentTime = array.get(labelData.times, i)
            roundedCurrentPrice = math.round(currentPrice / syminfo.mintick) * syminfo.mintick
            if map.contains(priceToIndex, roundedCurrentPrice)
                idx = map.get(priceToIndex, roundedCurrentPrice)
                existingText = array.get(consolidatedTexts, idx)
                array.set(consolidatedTexts, idx, existingText + " + " + currentText)
            else
                map.put(priceToIndex, roundedCurrentPrice, array.size(consolidatedPrices))
                array.push(consolidatedPrices, currentPrice)
                array.push(consolidatedTexts, currentText)
                array.push(consolidatedColors, currentColor)
                array.push(consolidatedTimes, currentTime)
        labelBgColor = color.new(labelBackgroundColor, labelBackgroundTransparency)
        finalSize = array.size(consolidatedPrices)
        tfSeconds = timeframe.in_seconds() * 1000
        for i = 0 to finalSize - 1
            price = array.get(consolidatedPrices, i)
            labelText = array.get(consolidatedTexts, i)
            labelColor = array.get(consolidatedColors, i)
            labelTime = array.get(consolidatedTimes, i)
            displayText = showPriceInLabel ? labelText + " " + str.tostring(price, format.mintick) : labelText
            lblSize = getSize(labelTextSize)
            labelTextColor = readableOn(labelColor, labelBackgroundColor)  // FIX LABELTEXT-1
            string ezTip = ezLabelTip(labelText, price, ezSide)  // EZ-MODE
            if showTimelineLabels
                acquireLabel(pool, labelTime + (labelOffset * tfSeconds), price, displayText, false, labelBgColor, labelTextColor, lblSize, ezTip)
            if showFloatingLabels
                acquireLabel(pool, bar_index + floatingLabelOffset, price, displayText, true, labelBgColor, labelTextColor, lblSize, ezTip)
 
if barstate.islast
    array.clear(highLabels.prices)
    array.clear(highLabels.texts)
    array.clear(highLabels.colors)
    array.clear(highLabels.times)
    array.clear(lowLabels.prices)
    array.clear(lowLabels.texts)
    array.clear(lowLabels.colors)
    array.clear(lowLabels.times)
    array.clear(openLabels.prices)
    array.clear(openLabels.texts)
    array.clear(openLabels.colors)
    array.clear(openLabels.times)
    lblPool.used := 0  // FIX P1-i: reset pool cursor; labels are reused in place, surplus trimmed after render
 
showAnyLabels = showTimelineLabels or showFloatingLabels
 
// ============================================================================
// SECTION 9: MAIN PROCESSING LOOP (with Lead Signal Filter)
// ============================================================================
 
getSignalDirection(ProcessingResult r) =>
    int direction = 0
    if not na(r)
        // Use signalInForce which checks both that signal qualifies AND price is currently beyond trigger
        if r.signalInForceHigh and r.signalInForceLow
            // Both directions in force (rare). FIX LEAD-F2-TIEBREAK-2: F2u is bearish and F2d is bullish,
            // so resolve those explicitly first. The generic close-suffix test below maps "F2u" -> +1 (bull),
            // which is inverted and would flip the Lead anchor (and all counter-trend suppression).
            if r.isF2u
                direction := -1
            else if r.isF2d
                direction := 1
            else if str.endswith(r.ccType, "u")
                direction := 1
            else
                direction := -1
        else if r.signalInForceHigh
            direction := 1
        else if r.signalInForceLow
            direction := -1
    direction
 
for i = 5 to 0
    cfg = array.get(tfConfigs, i)
    if cfg.enabled
        data = array.get(tfDataArr, i)
        raw = array.get(tfRawArr, i)
        isDebugTF = showDebugPanel and debugTimeframe == cfg.debugLabel
        // FIX OPENLINE-PREVIEW-1 (2026-09-04): gate the open line per slot only. previewNextPeriod says
        // the market-wide Auto mechanism is armed, not that THIS slot's open is a proxy; it was hiding
        // the W and M open lines on unshifted slots every pre-market. HTF-STRADDLE-1's per-slot guard
        // (raw.isPreview: no open line for a straddled/previewed slot, its open is synthetic) stays.
        // FIX PREVIEW-CROSSED-1: reconOKArr is filled above, so the loop can tell a synthetic
        // placeholder CC from a reconstructed one; only the synthetic one suppresses hit-testing.
        result = computeSignalState(data, cfg.tf, raw, cfg.showOpen and not raw.isPreview, isDebugTF, cfg.tf, raw.isPreview and not array.get(reconOKArr, i))
        array.set(tfResults, i, result)
 
var int anchorIndex = -1
var int anchorDirection = 0
 
if barstate.islast and enableDirectionalFilter
    anchorIndex := -1
    anchorDirection := 0
    for i = 5 to 0
        cfg = array.get(tfConfigs, i)
        rawA = array.get(tfRawArr, i)
        // FIX LEAD-PREVIEW-1 (2026-09-04): a preview/straddled slot never anchors the Lead. Its CC is
        // synthetic or estimate-grade - alerts already treat it so (slotPreview) - but the anchor scan
        // read its result anyway, so a reconstructed M in force became "Lead: M" and suppressed a real
        // lower slot's lines AND alerts. Reconstructed slots stay excluded: isPreview is the trust
        // flag; reconOK only governs how the table renders.
        bool slotPreviewA = not na(rawA) and rawA.isPreview
        if cfg.enabled and anchorIndex == -1 and not slotPreviewA
            r = array.get(tfResults, i)
            dir = getSignalDirection(r)
            if dir != 0
                anchorIndex := i
                anchorDirection := dir
 
if barstate.islast and enableDirectionalFilter and anchorIndex > 0 and anchorDirection != 0
    for i = 0 to anchorIndex - 1
        cfg = array.get(tfConfigs, i)
        if cfg.enabled
            data = array.get(tfDataArr, i)
            r = array.get(tfResults, i)
            if not na(r)
                // Unified directional filter: modify flags only (render phase handles drawing)
                bool suppressHigh = anchorDirection == -1
                bool isCounterF2 = (suppressHigh ? r.isF2d : r.isF2u) and not r.c1Is3
                bool isTrendF2 = (suppressHigh ? r.isF2u : r.isF2d) and not r.c1Is3
                if isCounterF2
                    // Counter-trend confirmed F2: suppress ALL flags
                    r.suppressAllFlags()
                    r.drawOpen := false
                    // FIX LEAD-TABLE-1 (2026-08-03, supersedes P1-g): the Lead Signal filter is a
                    // CHART filter. It no longer clears signalInForce, so the data table keeps
                    // reporting what the market is actually doing on every timeframe. P1-g cleared
                    // these to make the table agree with the hidden lines, which inverted the
                    // table's job: it is the true multi-timeframe reference you check BECAUSE the
                    // chart is filtered. Drawing is unaffected - every line, label, target, stop
                    // and TAW consumer is gated on the draw flags cleared just above, never on
                    // signalInForce.
                else if isTrendF2
                    // Trend-aligned confirmed F2: suppress counter-side extras only
                    if suppressHigh
                        r.drawMagHigh := false
                        r.drawExhHigh := false
                        r.drawStopHigh := false
                    else
                        r.drawMagLow := false
                        r.drawExhLow := false
                        r.drawStopLow := false
                else
                    // Regular signal or pre-F2: suppress counter-trend side
                    if suppressHigh
                        r.suppressHighFlags()   // FIX LEAD-TABLE-1: draw flags only; table still reports the truth
                    else
                        r.suppressLowFlags()    // FIX LEAD-TABLE-1
                    // Pre-F2: suppress open line (not a confirmed reversal yet)
                    if r.preF2d or r.preF2u
                        r.preF2u := false
                        r.preF2d := false
                    // If active side not drawing, open is orphaned
                    bool activeSideDraw = suppressHigh ? r.drawLow : r.drawHigh
                    if not activeSideDraw
                        r.drawOpen := false
                // Blanket catch: if both sides suppressed by any path, clean up open
                if not r.drawHigh and not r.drawLow
                    r.drawOpen := false
                    if not na(data.openLine)
                        line.delete(data.openLine)
                        data.openLine := na
 
// FEATURE STOP-SMALLEST-1 (2026-08-02): Smallest Timeframe Only for stops.
// Runs AFTER the Lead Signal Filter so a lead-suppressed stop cannot claim the smallest
// slot, and BEFORE the render phase so larger-TF stop lines are deleted, not just skipped.
// Display-only: stop prices, sticky latches, break-even, and alert content are untouched.
// "Smallest" is the lowest eligible slot index - slot order is size order, the same
// convention the Lead Signal filter anchors on.
if barstate.islast and showStopLevels and stopSmallestOnly
    int smallestStopIdx = -1
    for i = 0 to 5
        cfg = array.get(tfConfigs, i)
        if cfg.enabled and smallestStopIdx == -1
            r = array.get(tfResults, i)
            if not na(r)
                if (r.drawStopHigh and not na(r.stopHigh)) or (r.drawStopLow and not na(r.stopLow))
                    smallestStopIdx := i
    if smallestStopIdx != -1
        for i = 0 to 5
            cfg = array.get(tfConfigs, i)
            if cfg.enabled and i != smallestStopIdx
                r = array.get(tfResults, i)
                if not na(r)
                    r.drawStopHigh := false
                    r.drawStopLow := false
 
// Render phase: draw/update/delete all lines and boxes based on final flag state
if barstate.islast
    for i = 5 to 0
        cfg = array.get(tfConfigs, i)
        if cfg.enabled
            data = array.get(tfDataArr, i)
            r = array.get(tfResults, i)
            if not na(r)
                periodDuration = timeframe.in_seconds(cfg.tf) * 1000
                raw = array.get(tfRawArr, i)
                // FIX LINEEND-CLOSE-1: same rule as computeSignalState (scheduled close wins on long bars).
                int slotCloseR = not raw.isPreview ? time_close(cfg.tf) : na
                lineEndTime = na(slotCloseR) ? raw.ccTime + periodDuration : math.max(raw.ccTime + periodDuration, slotCloseR)
                renderSignalLevels(data, r, cfg.lineWidth, lineEndTime)
 
if barstate.islast and showAnyLabels
    for i = 5 to 0
        cfg = array.get(tfConfigs, i)
        if cfg.enabled
            data = array.get(tfDataArr, i)
            r = array.get(tfResults, i)
            if not na(r)
                // Label suppression matching line deletion logic (unified direction)
                bool skipHighLabels = false
                bool skipLowLabels = false
                if enableDirectionalFilter and i < anchorIndex
                    bool suppressHigh = anchorDirection == -1
                    bool isCounterF2 = (suppressHigh ? r.isF2d : r.isF2u) and not r.c1Is3
                    bool isTrendF2 = (suppressHigh ? r.isF2u : r.isF2d) and not r.c1Is3
                    if isCounterF2
                        skipHighLabels := true
                        skipLowLabels := true
                    else if not isTrendF2
                        // Regular: suppress counter-trend side labels
                        if suppressHigh
                            skipHighLabels := true
                        else
                            skipLowLabels := true
                if not skipHighLabels and not skipLowLabels
                    collectTimeframeLabels(data, r)
                else
                    modifiedResult = ProcessingResult.new(skipHighLabels ? na : r.high, skipLowLabels ? na : r.low, r.open, skipHighLabels ? na : r.magHigh, skipLowLabels ? na : r.magLow, skipHighLabels ? na : r.exhHigh, skipLowLabels ? na : r.exhLow, r.highColor, r.lowColor, r.openColor, r.magHighColor, r.magLowColor, r.exhHighColor, r.exhLowColor, skipHighLabels ? false : r.drawHigh, skipLowLabels ? false : r.drawLow, r.drawOpen and ((not skipHighLabels and r.drawHigh) or (not skipLowLabels and r.drawLow)), skipHighLabels ? false : r.drawMagHigh, skipLowLabels ? false : r.drawMagLow, skipHighLabels ? false : r.drawExhHigh, skipLowLabels ? false : r.drawExhLow, r.time, r.tfLabel, r.isF2u, r.isF2d, r.c1Is3, r.c3Num, r.c2Num, r.c1Num, r.c1Type, r.ccType, r.signalInForceHigh, r.signalInForceLow, skipHighLabels ? na : r.stopHigh, skipLowLabels ? na : r.stopLow, skipHighLabels ? false : r.drawStopHigh, skipLowLabels ? false : r.drawStopLow, skipHighLabels ? false : r.preF2u, skipLowLabels ? false : r.preF2d, r.f2OpenPrice, r.ccStartTime, r.c1WasF2, r.c2WasF2)
                    collectTimeframeLabels(data, modifiedResult)
 
// ============================================================================
// SECTION 10: LINE SUPPRESSION
// ============================================================================
 
collectLinesFromTF(TimeframeData data, string tf, array<LineInfo> highLines, array<LineInfo> lowLines, array<LineInfo> openLines) =>
    tfSec = timeframe.in_seconds(tf)
    // FIX P1-h: each LineInfo now carries its owner slot + a kind code so suppression can
    // null the originating field after deleting the line. Kinds: 0=high 1=low 2=magHigh
    // 3=magLow 4=exhHigh 5=exhLow 6=open 7=f2Open.
    if not na(data.highLine) and not na(data.prevHigh)
        array.push(highLines, LineInfo.new(data.prevHigh, tfSec, data.highLine, data, 0))
    if not na(data.lowLine) and not na(data.prevLow)
        array.push(lowLines, LineInfo.new(data.prevLow, tfSec, data.lowLine, data, 1))
    if not na(data.magHighLine) and not na(data.prevMagHigh)
        array.push(highLines, LineInfo.new(data.prevMagHigh, tfSec, data.magHighLine, data, 2))
    if not na(data.magLowLine) and not na(data.prevMagLow)
        array.push(lowLines, LineInfo.new(data.prevMagLow, tfSec, data.magLowLine, data, 3))
    if not na(data.exhHighLine) and not na(data.exhHighPrice)
        array.push(highLines, LineInfo.new(data.exhHighPrice, tfSec, data.exhHighLine, data, 4))
    if not na(data.exhLowLine) and not na(data.exhLowPrice)
        array.push(lowLines, LineInfo.new(data.exhLowPrice, tfSec, data.exhLowLine, data, 5))
    if not na(data.openLine) and not na(data.currOpen)
        array.push(openLines, LineInfo.new(data.currOpen, tfSec, data.openLine, data, 6))
    if not na(data.f2OpenLine) and not na(data.currOpen)
        array.push(openLines, LineInfo.new(data.currOpen, tfSec, data.f2OpenLine, data, 7))
    // Stop lines are intentionally excluded from line suppression.
    //         Stops must always remain visible for risk management regardless of
    //         overlapping trigger, magnitude, or exhaustion levels.
 
// FIX P1-h: null the owning TimeframeData line field after a suppressed line is deleted,
// so the render phase recreates it via line.new() next time (instead of calling line.set_*
// on a deleted id - undefined behavior), and a suppressed line can reappear once the price
// collision clears. Kinds match collectLinesFromTF.
nullSuppressedLine(TimeframeData d, int kind) =>
    if kind == 0
        d.highLine := na
    else if kind == 1
        d.lowLine := na
    else if kind == 2
        d.magHighLine := na
    else if kind == 3
        d.magLowLine := na
    else if kind == 4
        d.exhHighLine := na
    else if kind == 5
        d.exhLowLine := na
    else if kind == 6
        d.openLine := na
    else if kind == 7
        d.f2OpenLine := na
 
suppressLowerTFLines(array<LineInfo> lines) =>
    numLines = array.size(lines)
    if numLines > 1
        var priceToMaxTF = map.new<float, int>()
        var priceToInfo = map.new<float, LineInfo>()
        map.clear(priceToMaxTF)
        map.clear(priceToInfo)
        for i = 0 to numLines - 1
            lineI = array.get(lines, i)
            roundedPrice = math.round(lineI.price / syminfo.mintick) * syminfo.mintick
            if map.contains(priceToMaxTF, roundedPrice)
                existingTF = map.get(priceToMaxTF, roundedPrice)
                existingInfo = map.get(priceToInfo, roundedPrice)
                if lineI.tfSeconds > existingTF
                    // current is higher-TF: delete the previously-kept lower-TF line and null its field
                    line.delete(existingInfo.lineRef)
                    nullSuppressedLine(existingInfo.owner, existingInfo.kind)
                    map.put(priceToMaxTF, roundedPrice, lineI.tfSeconds)
                    map.put(priceToInfo, roundedPrice, lineI)
                else
                    // current loses: delete it and null its field
                    line.delete(lineI.lineRef)
                    nullSuppressedLine(lineI.owner, lineI.kind)
            else
                map.put(priceToMaxTF, roundedPrice, lineI.tfSeconds)
                map.put(priceToInfo, roundedPrice, lineI)
    true
 
if barstate.islast
    var highLines = array.new<LineInfo>()
    var lowLines = array.new<LineInfo>()
    var openLines = array.new<LineInfo>()
    array.clear(highLines)
    array.clear(lowLines)
    array.clear(openLines)
    for i = 5 to 0
        cfg = array.get(tfConfigs, i)
        if cfg.enabled
            data = array.get(tfDataArr, i)
            collectLinesFromTF(data, cfg.tf, highLines, lowLines, openLines)
    suppressLowerTFLines(highLines)
    suppressLowerTFLines(lowLines)
    suppressLowerTFLines(openLines)
 
if barstate.islast and showAnyLabels
    consolidateAndCreate(highLabels, lblPool, 1)
    consolidateAndCreate(lowLabels, lblPool, -1)
    consolidateAndCreate(openLabels, lblPool, 0)
// FIX P1-i: trim the pool to the number of labels actually used this bar. When labels are
// disabled, lblPool.used stays 0 (consolidate did not run), so all pooled labels are deleted.
// Runs every islast regardless of showAnyLabels so toggling labels off clears them.
if barstate.islast
    while array.size(lblPool.items) > lblPool.used
        label.delete(array.pop(lblPool.items))
 
// ============================================================================
// SECTION 11: DATA TABLE
// ============================================================================
 
getBarTypeColor(barType) =>
    switch barType
        "1u" => color.new(#ffeb3b, 0)
        "1d" => color.new(#ff9800, 0)
        "2u" => color.new(#4caf50, 0)
        "2d" => color.new(#f23645, 0)
        "F2u" => color.new(COLOR_FAILED_2U, 0)
        "F2d" => color.new(COLOR_FAILED_2D, 0)
        "3u" => color.new(colorBullish3Bar, 0)
        "3d" => color.new(colorBearish3Bar, 0)
        => COLOR_BG_GRAY50
 
getBarTypeTextColor(barType) =>
    switch barType
        "1u" => #ffeb3b
        "1d" => #ff9800
        "2u" => #4caf50
        "2d" => #f23645
        "F2u" => COLOR_FAILED_2U
        "F2d" => COLOR_FAILED_2D
        "3u" => colorBullish3Bar
        "3d" => colorBearish3Bar
        => color.gray
 
var table barTypeTable = na
var int enabledTFCount = 0
isCompactMode = tableMode == "Compact"
compactByBarState = compactCellColor == "Bar State"  // FEATURE TABLE-COMPACT-COLOR-1
 
if barstate.isfirst
    enabledTFCount := (rEN1 ? 1 : 0) + (rEN2 ? 1 : 0) + (rEN3 ? 1 : 0) + (rEN4 ? 1 : 0) + (rEN5 ? 1 : 0) + (rEN6 ? 1 : 0)
    if showBarTypeTable and enabledTFCount > 0
        if isCompactMode
            // Compact table: horizontal row of TFs + rows for FTFC, Filter, Domino, Preview + padding
            barTypeTable := table.new(getTablePos(tablePosition), enabledTFCount, 5, bgcolor = COLOR_BG_BLACK, frame_color = color.gray, frame_width = 1, border_color = #333333, border_width = 1)
        else
            // Full table: vertical with columns
            barTypeTable := table.new(getTablePos(tablePosition), 5, enabledTFCount + 5, bgcolor = COLOR_BG_BLACK, frame_color = color.gray, frame_width = 1, border_color = #333333, border_width = 1)
 
populateBarTypeRow(table tbl, int row, string tf, TimeframeData data, TFRawData raw, ProcessingResult pResult, string textSize, bool reconOK) =>
    tfSeconds = timeframe.in_seconds(tf)
    isLowerTF = tfSeconds < chartTfSeconds
    tfLabelStr = getTimeframeLabel(tf)
    sz = getSize(textSize)
    if isLowerTF
        table.cell(tbl, 0, row, tfLabelStr, text_color = #555555, bgcolor = #111111, text_size = sz, tooltip = tfLabelStr + " is a lower timeframe than this chart, so it cannot be read here. Switch the chart to " + tfLabelStr + " or lower to see it.")
        table.cell(tbl, 1, row, "", text_color = color.gray, bgcolor = COLOR_BG_BLACK, text_size = sz)
        table.cell(tbl, 2, row, "", text_color = color.gray, bgcolor = COLOR_BG_BLACK, text_size = sz)
        table.cell(tbl, 3, row, "", text_color = color.gray, bgcolor = COLOR_BG_BLACK, text_size = sz)
        table.cell(tbl, 4, row, "", text_color = color.gray, bgcolor = COLOR_BG_BLACK, text_size = sz)
    else
        [barType_CC, _isFailed_CC] = detectBarTypeAndFailed(raw.c1H, raw.c1L, raw.ccH, raw.ccL, raw.ccO, raw.ccC)
        [barType_C1, _isFailed_C1] = detectBarTypeAndFailed(raw.c2H, raw.c2L, raw.c1H, raw.c1L, raw.c1O, raw.c1C)
        [barType_C2, _isFailed_C2] = detectBarTypeAndFailed(raw.c3H, raw.c3L, raw.c2H, raw.c2L, raw.c2O, raw.c2C)
        if not show_p3_toggle  // EZ-MODE
            barType_CC := str.replace(barType_CC, "F", "")
            barType_C1 := str.replace(barType_C1, "F", "")
            barType_C2 := str.replace(barType_C2, "F", "")
        // Use centralized signalInForce from processing result (matches compact table behavior)
        bool isBullInForce = not na(pResult) and pResult.signalInForceHigh
        bool isBearInForce = not na(pResult) and pResult.signalInForceLow
        isInForce = colorTFWhenInForce and (isBullInForce or isBearInForce)
        // FIX TFCOLOR-1 (2026-07-07): an inside bar (1u/1d) is by definition NOT in force, so it must
        // not highlight the TF column under "Color TF When In-Force". The old ccIsInsideBar term lit the
        // TF on every inside bar (the common case) - "coloring everything". Inside bars remain colored
        // in the CC cell only.
        // FIX OUTSIDE-IF-1 (2026-11-05): the separate "any enabled 3" term is gone. signalInForceHigh/Low
        // now count an outside bar closing beyond C1 (t_exp3_h/l), so the table, Lead Signal and stops
        // share one rule; a 3 that closed back inside C1 (contested) stays dark.
        bool highlightTF = isInForce
        tfBgColor = highlightTF ? getBarTypeColor(barType_CC) : #111111
        tfTextColor = highlightTF ? color.black : color.white
        // EZ-MODE: hover text for the row.
        string ezTfTip = "Nothing is in force on " + tfLabelStr + " right now. This cell lights up when a signal triggers."
        if isBullInForce
            ezTfTip := tfLabelStr + " has a signal in force to the upside: it triggered, and price is holding above its trigger (" + str.tostring(pResult.high, format.mintick) + "). A signal stays in force only while its bar is open."
        else if isBearInForce
            ezTfTip := tfLabelStr + " has a signal in force to the downside: it triggered, and price is holding below its trigger (" + str.tostring(pResult.low, format.mintick) + "). A signal stays in force only while its bar is open."
        table.cell(tbl, 0, row, tfLabelStr, text_color = tfTextColor, bgcolor = tfBgColor, text_size = sz, tooltip = ezTfTip)
        table.cell(tbl, 1, row, barType_C2, text_color = getBarTypeTextColor(barType_C2), bgcolor = COLOR_BG_BLACK, text_size = sz, tooltip = "C2, two bars back. " + ezBarTip(barType_C2, tfLabelStr, false))
        table.cell(tbl, 2, row, barType_C1, text_color = getBarTypeTextColor(barType_C1), bgcolor = COLOR_BG_BLACK, text_size = sz, tooltip = "C1, the previous bar. " + ezBarTip(barType_C1, tfLabelStr, false))
        asText = data.c1IsHammer ? "HAM" : data.c1IsShooter ? "SHO" : data.c1IsInside ? "INS" : ""
        string ezAsTip = data.c1IsHammer ? "HAM = hammer. The previous " + tfLabelStr + " bar has a long lower wick and closed near its high: sellers pushed down and lost. A break above its high is the trigger." : data.c1IsShooter ? "SHO = shooter. The previous " + tfLabelStr + " bar has a long upper wick and closed near its low: buyers pushed up and lost. A break below its low is the trigger." : data.c1IsInside ? "INS = inside bar. The previous " + tfLabelStr + " bar stayed inside the bar before it. A break of its high or its low is the trigger." : "No actionable signal on the previous " + tfLabelStr + " bar. This column shows HAM (hammer), SHO (shooter) or INS (inside bar) when there is one."
        table.cell(tbl, 3, row, asText, text_color = color.white, bgcolor = COLOR_BG_BLACK, text_size = sz, tooltip = ezAsTip)
        ccRawText = barType_CC  // NOTATION-1: CC cell shows canonical F2u/F2d (lowercase live-'f' retired)
        // FIX HTF-STRADDLE-1 (T3): a straddled slot whose forming candle was rebuilt from real daily
        // sub-bars (reconOK) renders normally - it is true data matching finer charts. Only a preview
        // slot WITHOUT reconstruction (classic preview, or no new-period dailies yet) shows "?".
        bool ccUnknown = raw.isPreview and not reconOK
        ccDisplayText = ccUnknown ? "?" : ccRawText
        ccBgColor = ccUnknown ? COLOR_BG_BLACK : getBarTypeColor(barType_CC)
        ccTextColor = ccUnknown ? color.yellow : barType_CC != "" ? color.black : color.white
        table.cell(tbl, 4, row, ccDisplayText, text_color = ccTextColor, bgcolor = ccBgColor, text_size = sz, tooltip = ccUnknown ? "Preview Mode: the next " + tfLabelStr + " bar has not started trading, so there is nothing to read yet." : "CC, the current bar. " + ezBarTip(barType_CC, tfLabelStr, true))
        if ezSimpleTable
            // EZ-MODE: Simple table. TF | TFC | Combo | AS.
            // TFC: is this timeframe trading above or below its own open (what FTFC compares).
            // Combo reads across two cells that sit flush: the bars leading in (right-aligned,
            // ending in a dash) and the current bar (left-aligned, in its bar color).
            // AS: the actionable signal on the bar before the current one (HAM, SHO, INS).
            // C2 is named only when it is part of the combo: an inside C1 (2-1-2, 3-1-2), or
            // a 1 or 3 ahead of a 2 (1-2-2, 3-2-2), the same rule the level labels use.
            string ezC1 = ezPlain(barType_C1)
            string ezC2 = ezPlain(barType_C2)
            bool ezC1Is2 = str.contains(ezC1, "2")
            bool ezNeedC2 = ezC2 != "" and (ezC1 == "1" or (ezC1Is2 and (ezC2 == "1" or ezC2 == "3")))
            string ezBefore = (ezNeedC2 ? ezC2 + "-" : "") + ezC1
            string ezNow = ccUnknown ? "?" : ezPlain(barType_CC)
            string ezName = ezComboName(ezBefore + ezNow)
            string ezCombo = ezBefore + "-" + ezNow
            string ezRead = "The " + tfLabelStr + " combo is " + ezCombo + ". Read it left to right, oldest bar first. The highlighted bar at the end is the current one, still forming." + (ezNow == "1" ? " It is waiting on the current bar to break one side." : ezName != "combo" ? " That is a " + ezName + "." : "")
            string ezBeforeTip = ezRead + " The bar before the current one: " + ezBarTip(barType_C1, tfLabelStr, false)
            string ezNowTip = ccUnknown ? "Preview Mode: the next " + tfLabelStr + " bar has not started trading, so there is nothing to read yet." : ezRead + " The current bar: " + ezBarTip(barType_CC, tfLabelStr, true)
            bool ezBarUp = raw.ccC > raw.ccO
            string ezTrend = ccUnknown ? "?" : ezBarUp ? "▲" : "▼"
            color ezTrendColor = ccUnknown ? color.yellow : ezBarUp ? color.green : color.red
            string ezTrendTip = ccUnknown ? "Preview Mode: the next " + tfLabelStr + " bar has not started trading, so it has no direction yet." : "The current " + tfLabelStr + " bar is trading " + (ezBarUp ? "above" : "below") + " its open (" + str.tostring(raw.ccO, format.mintick) + "), so " + tfLabelStr + " is " + (ezBarUp ? "up" : "down") + " for now. When every arrow in this column points the same way, the timeframes agree. That is Full Timeframe Continuity."
            table.clear(tbl, 1, row, 4, row)
            table.cell(tbl, 1, row, ezTrend, text_color = ezTrendColor, bgcolor = COLOR_BG_BLACK, text_size = sz, tooltip = ezTrendTip)
            table.cell(tbl, 2, row, ezBefore + "-", text_color = #b2b5be, bgcolor = COLOR_BG_BLACK, text_size = sz, text_halign = text.align_right, tooltip = ezBeforeTip)
            table.cell(tbl, 3, row, ezNow, text_color = ccTextColor, bgcolor = ccBgColor, text_size = sz, text_halign = text.align_center, text_formatting = text.format_bold, tooltip = ezNowTip)
            table.cell(tbl, 4, row, asText, text_color = color.white, bgcolor = COLOR_BG_BLACK, text_size = sz, tooltip = ezAsTip)
 
// Domino calculation - CC is inside across consecutive TFs with same direction
// Runs every bar (not just islast) so alertconditions work. Table reads on islast.
int dominoBestRun = 0
string dominoBestTFs = ""
int currentRunBull = 0
int currentRunBear = 0
int bestRunBull = 0
int bestRunBear = 0
string currentTFsBull = ""
string currentTFsBear = ""
string bestTFsBull = ""
string bestTFsBear = ""
int prevCCTimeBull = na
int prevCCTimeBear = na
for i = 5 to 0
    cfg = array.get(tfConfigs, i)
    if cfg.enabled
        result = array.get(tfResults, i)
        tfLabel = getTimeframeLabel(cfg.tf)
        rawD = array.get(tfRawArr, i)
        // FIX DOMINO-PREVIEW-1 (2026-09-04): a preview/straddled slot breaks the Domino chain. Its
        // synthetic CC (open = promoted close, close = midpoint, range = C1's) ALWAYS classifies inside,
        // so every weekend the shifted W/M slots counted as inside-bar links, showed a Domino row and
        // fired the Domino alertcondition - the one alert path slotPreview and okA1-okA6 never covered.
        bool slotPreviewD = not na(rawD) and rawD.isPreview
        ccIsInside = not na(result) and not slotPreviewD and str.startswith(result.ccType, "1")
        hasBullSetup = not na(result) and result.drawHigh
        hasBearSetup = not na(result) and result.drawLow
        int thisCCTime = not na(result) ? result.ccStartTime : na
        // Bullish Domino: skip if same candle as previous TF in run
        bool bullSameCandle = not na(thisCCTime) and not na(prevCCTimeBull) and thisCCTime == prevCCTimeBull
        if ccIsInside and hasBullSetup and not bullSameCandle
            currentRunBull += 1
            currentTFsBull := currentTFsBull == "" ? tfLabel : tfLabel + "+" + currentTFsBull
            prevCCTimeBull := thisCCTime
            if currentRunBull > bestRunBull
                bestRunBull := currentRunBull
                bestTFsBull := currentTFsBull
        else if ccIsInside and hasBullSetup and bullSameCandle
            // Same candle: don't increment count, just update prevTime to maintain chain
            prevCCTimeBull := thisCCTime
        else
            currentRunBull := 0
            currentTFsBull := ""
            prevCCTimeBull := na
        // Bearish Domino: skip if same candle as previous TF in run
        bool bearSameCandle = not na(thisCCTime) and not na(prevCCTimeBear) and thisCCTime == prevCCTimeBear
        if ccIsInside and hasBearSetup and not bearSameCandle
            currentRunBear += 1
            currentTFsBear := currentTFsBear == "" ? tfLabel : tfLabel + "+" + currentTFsBear
            prevCCTimeBear := thisCCTime
            if currentRunBear > bestRunBear
                bestRunBear := currentRunBear
                bestTFsBear := currentTFsBear
        else if ccIsInside and hasBearSetup and bearSameCandle
            prevCCTimeBear := thisCCTime
        else
            currentRunBear := 0
            currentTFsBear := ""
            prevCCTimeBear := na
if bestRunBull >= bestRunBear
    dominoBestRun := bestRunBull
    dominoBestTFs := bestTFsBull
else
    dominoBestRun := bestRunBear
    dominoBestTFs := bestTFsBear
 
// Calculate shared values for table (FTFC)
var string tableFtfcText = ""
var color tableFtfcTextColor = color.gray
var color tableFtfcBgColor = color.gray
 
if barstate.islast
    // Modified FTFC calculation - exclude exhausted TFs if setting is enabled
    // ftfc_up = true means all TFs closed bullish; ftfc_down = true means all TFs closed bearish
    bool modFtfcUp = ftfc_up
    bool modFtfcDown = ftfc_down
    if exhDisablesFTFC
        modFtfcUp := true
        modFtfcDown := true
        for i = 5 to 0
            cfg = array.get(tfConfigs, i)
            if cfg.enabled
                tfSeconds = timeframe.in_seconds(cfg.tf)
                isLowerTF = tfSeconds < chartTfSeconds
                if not isLowerTF
                    raw = array.get(tfRawArr, i)
                    data = array.get(tfDataArr, i)
                    if not na(raw) and not na(data)
                        ccClosedUp = raw.ccC > raw.ccO
                        // If bullish TF hit high exhaustion, don't let it block ftfc_up (bullish setups)
                        // If bearish TF hit low exhaustion, don't let it block ftfc_down (bearish setups)
                        // If no exhaustion exists, magnitude crossed serves same function
                        bool bullMagFallback = na(data.exhHighPrice) and not na(data.prevMagHigh) and data.magHighCrossed
                        bool bearMagFallback = na(data.exhLowPrice) and not na(data.prevMagLow) and data.magLowCrossed
                        bullExhausted = ccClosedUp and (data.exhHighCrossed or bullMagFallback)
                        bearExhausted = not ccClosedUp and (data.exhLowCrossed or bearMagFallback)
                        if ccClosedUp and not bullExhausted
                            // FIX P1-e (doc): this affects the DATA TABLE FTFC cell ONLY. It does
                            // NOT gate signal drawing or alerts - those use the raw ftfc_up/ftfc_down
                            // from calculateFTFC(). A non-exhausted bullish TF keeps the table cell
                            // from reading "FTFC Down". (Wiring exhDisablesFTFC into signal gating is
                            // a deliberate, separately-validated change - see review notes.)
                            modFtfcDown := false
                        if not ccClosedUp and not bearExhausted
                            // FIX P1-e (doc): table-display only (see above); not signal gating.
                            modFtfcUp := false
    tableFtfcText := modFtfcUp ? (simpleLabelMode ? "Trend Up" : "FTFC Up") : modFtfcDown ? (simpleLabelMode ? "Trend Down" : "FTFC Down") : (simpleLabelMode ? "No Trend" : "Conflict")
    tableFtfcTextColor := modFtfcUp ? color.green : modFtfcDown ? color.red : color.gray
    tableFtfcBgColor := modFtfcUp ? color.new(color.green, 80) : modFtfcDown ? color.new(color.red, 80) : color.new(color.gray, 80)
 
// Shared Lead row values (used by both compact and standard table modes)
var string leadRowText = "No Lead"
var color leadRowTextColor = color.gray
var color leadRowBgColor = color.new(color.gray, 85)
// FIX LEADROW-1 (2026-08-03): the Lead row only renders when a Lead actually exists.
// "No Lead" is the resting state most of the session and told you nothing - the filter
// being on is already visible in the settings, so an empty row was pure noise.
var bool hasLead = false
if barstate.islast and enableDirectionalFilter
    string leadTfLabel = ""
    if anchorIndex >= 0 and anchorIndex <= 5
        leadCfg = array.get(tfConfigs, anchorIndex)
        leadTfLabel := getTimeframeLabel(leadCfg.tf)
    string leadDirText = anchorDirection == 1 ? "BULL" : anchorDirection == -1 ? "BEAR" : ""
    hasLead := leadTfLabel != "" and leadDirText != ""
    leadRowText := hasLead ? "Lead: " + leadTfLabel + " " + leadDirText : "No Lead"
    leadRowTextColor := anchorDirection == 1 ? color.green : anchorDirection == -1 ? color.red : color.gray
    leadRowBgColor := anchorDirection == 1 ? color.new(color.green, 85) : anchorDirection == -1 ? color.new(color.red, 85) : color.new(color.gray, 85)
 
if barstate.islast and showBarTypeTable and not na(barTypeTable)
    textSize = getSize(tableTextSize)
    if isCompactMode
        // COMPACT MODE
        table.clear(barTypeTable, 0, 0, enabledTFCount - 1, 4)
        // TF labels row
        col = 0
        for i = 5 to 0
            cfg = array.get(tfConfigs, i)
            if cfg.enabled
                tfSeconds = timeframe.in_seconds(cfg.tf)
                isLowerTF = tfSeconds < chartTfSeconds
                tfLabelStr = getTimeframeLabel(cfg.tf)
                raw = array.get(tfRawArr, i)
                result = array.get(tfResults, i)
                // Determine cell color: bar state, or signals in force (see Compact Cell Color)
                color cellBg = #111111
                color cellText = #555555
                if not isLowerTF and not na(raw) and not na(result)
                    // FEATURE TABLE-COMPACT-COLOR-1: the compact row condenses the Full table,
                    // so its two coloring modes reuse the Full table's own classifier and palette
                    // rather than inventing a third scheme - the same barType the CC column shows.
                    [ccTypeCompact, _f2Compact] = detectBarTypeAndFailed(raw.c1H, raw.c1L, raw.ccH, raw.ccL, raw.ccO, raw.ccC)
                    if raw.isPreview and not array.get(reconOKArr, i)  // FIX HTF-STRADDLE-1 (T3): reconstructed slots color normally
                        cellText := color.yellow
                    else if compactByBarState
                        // Mirrors the Full table's CC column: every cell carries its bar state.
                        cellBg := getBarTypeColor(ccTypeCompact)
                        cellText := ccTypeCompact != "" ? color.black : color.white
                    else
                        // Mirrors the Full table's TF column: colored only while a signal is in
                        // force (FIX TFCOLOR-1, FIX OUTSIDE-IF-1). An inside bar, or a 3 that
                        // closed back inside C1, is not in force and stays dark.
                        bool highlightCompact = result.signalInForceHigh or result.signalInForceLow
                        cellBg := highlightCompact ? getBarTypeColor(ccTypeCompact) : #111111
                        cellText := highlightCompact ? color.black : color.white
                table.cell(barTypeTable, col, 0, tfLabelStr, text_color = cellText, bgcolor = cellBg, text_size = textSize)
                col += 1
        // Subsequent rows: Domino, FTFC, Filter, Preview
        compactRow = 1
        if showDominoInTable and dominoBestRun >= minDominoTFs
            table.merge_cells(barTypeTable, 0, compactRow, enabledTFCount - 1, compactRow)
            table.cell(barTypeTable, 0, compactRow, "Domino: " + dominoBestTFs, text_color = color.black, bgcolor = color.white, text_size = textSize)
            compactRow += 1
        // Row 2: FTFC
        table.merge_cells(barTypeTable, 0, compactRow, enabledTFCount - 1, compactRow)
        table.cell(barTypeTable, 0, compactRow, tableFtfcText, text_color = tableFtfcTextColor, bgcolor = tableFtfcBgColor, text_size = textSize)
        compactRow += 1
        // Row 3: Lead (only when one exists - FIX LEADROW-1)
        if enableDirectionalFilter and hasLead
            table.merge_cells(barTypeTable, 0, compactRow, enabledTFCount - 1, compactRow)
            table.cell(barTypeTable, 0, compactRow, leadRowText, text_color = leadRowTextColor, bgcolor = leadRowBgColor, text_size = textSize)
            compactRow += 1
        // Row 4: Preview mode (if enabled)
        if previewNextPeriod
            table.merge_cells(barTypeTable, 0, compactRow, enabledTFCount - 1, compactRow)
            table.cell(barTypeTable, 0, compactRow, "PREVIEW MODE", text_color = color.yellow, bgcolor = color.new(color.yellow, 85), text_size = textSize)
            compactRow += 1
    else
        // STANDARD MODE
        table.clear(barTypeTable, 0, 0, 4, enabledTFCount + 4)
        table.cell(barTypeTable, 0, 0, "TF", text_color = #888888, bgcolor = #1a1a1a, text_size = textSize, tooltip = "TF = timeframe. Each row is one timeframe, highest at the top. The cell lights up while a signal is in force on that timeframe. Hover any cell for what it means right now. TheStrat was created by Rob Smith.")
        table.cell(barTypeTable, 1, 0, "C2", text_color = #888888, bgcolor = #1a1a1a, text_size = textSize, tooltip = "C2 = the candle two bars back on each timeframe. Every bar is a 1 (took neither side of the bar before it), a 2 (took one side) or a 3 (took both).")
        table.cell(barTypeTable, 2, 0, "C1", text_color = #888888, bgcolor = #1a1a1a, text_size = textSize, tooltip = "C1 = the previous candle on each timeframe. Its high and low are the triggers the current bar can break.")
        table.cell(barTypeTable, 3, 0, "AS", text_color = #888888, bgcolor = #1a1a1a, text_size = textSize, tooltip = "AS = actionable signal on the previous candle: HAM (hammer), SHO (shooter) or INS (inside bar). Blank when there is none.")
        table.cell(barTypeTable, 4, 0, "CC", text_color = #888888, bgcolor = #1a1a1a, text_size = textSize, tooltip = "CC = the current candle on each timeframe, still forming. Read C2, C1, CC left to right to get the combo, for example 2d-2u.")
        if ezSimpleTable
            table.clear(barTypeTable, 1, 0, 4, 0)
            table.cell(barTypeTable, 1, 0, "TFC", text_color = #888888, bgcolor = #1a1a1a, text_size = textSize, tooltip = "TFC = Timeframe Continuity: is each timeframe trading above its open (▲ up) or below it (▼ down). Read down the column: when every arrow points the same way, the timeframes agree. That is Full Timeframe Continuity. The rows at the top are the higher timeframes, and they set the trend the lower ones trade into.")
            table.merge_cells(barTypeTable, 2, 0, 3, 0)
            table.cell(barTypeTable, 2, 0, "Combo", text_color = #888888, bgcolor = #1a1a1a, text_size = textSize, tooltip = "Combo = the last few bars on each timeframe, oldest first. The highlighted bar at the end is the current one, still forming. Every bar is a 1 (took neither side of the bar before it), a 2 (2u took the high, 2d took the low) or a 3 (took both). So 3-1-2u is an outside bar, an inside bar, then the current bar breaking up. Hover a row for its read.")
            table.cell(barTypeTable, 4, 0, "AS", text_color = #888888, bgcolor = #1a1a1a, text_size = textSize, tooltip = "AS = actionable signal. It describes the bar before the current one, the last bar in the combo that has closed: HAM (hammer), SHO (shooter) or INS (inside bar). A break of that bar is the trigger. Blank when there is none. A timeframe with a signal in force lights up its TF cell.")
        string ezUp = ""
        string ezDn = ""
        int ezN = 0
        int ezNUp = 0
        int ezHtf = 0
        string ezHtfNames = ""
        float ezTrigUp = na
        float ezTrigDn = na
        string ezTrigUpTf = ""
        string ezWatch = ""
        string ezTrigDnTf = ""
        row = 1
        for i = 5 to 0
            cfg = array.get(tfConfigs, i)
            if cfg.enabled
                data = array.get(tfDataArr, i)
                raw = array.get(tfRawArr, i)
                result = array.get(tfResults, i)
                populateBarTypeRow(barTypeTable, row, cfg.tf, data, raw, result, tableTextSize, array.get(reconOKArr, i))
                row += 1
                // EZ-MODE: rows run highest to lowest, so prepend to list lowest first.
                bool ezReadable = not na(result) and not na(raw) and timeframe.in_seconds(cfg.tf) >= chartTfSeconds and not (raw.isPreview and not array.get(reconOKArr, i))
                if ezReadable
                    string ezLbl = getTimeframeLabel(cfg.tf)
                    bool ezRowUp = raw.ccC > raw.ccO
                    ezN += 1
                    if ezRowUp
                        ezNUp += 1
                    if ezN <= 2
                        ezHtf += ezRowUp ? 1 : -1
                        ezHtfNames := ezHtfNames == "" ? ezLbl : ezHtfNames + ", " + ezLbl
                    if result.signalInForceHigh
                        ezUp := ezUp == "" ? ezLbl : ezLbl + ", " + ezUp
                    else if result.signalInForceLow
                        ezDn := ezDn == "" ? ezLbl : ezLbl + ", " + ezDn
                    // Name a hammer or shooter in words, with the bar it is on, while its break is still ahead.
                    if data.c1IsHammer and not result.signalInForceHigh and close < raw.c1H
                        ezWatch := "\n" + ezLbl + " hammer: above " + str.tostring(raw.c1H, format.mintick) + ezWatch
                    else if data.c1IsShooter and not result.signalInForceLow and close > raw.c1L
                        ezWatch := "\n" + ezLbl + " shooter: below " + str.tostring(raw.c1L, format.mintick) + ezWatch
                    // The lowest timeframe whose trigger has not been hit wins: the loop runs downward.
                    if result.drawHigh and not na(result.high) and close < result.high
                        ezTrigUp := result.high
                        ezTrigUpTf := ezLbl
                    if result.drawLow and not na(result.low) and close > result.low
                        ezTrigDn := result.low
                        ezTrigDnTf := ezLbl
        if showDominoInTable and dominoBestRun >= minDominoTFs
            string dominoText = "Domino: " + dominoBestTFs
            table.merge_cells(barTypeTable, 0, row, ezLastCol, row)
            table.cell(barTypeTable, 0, row, dominoText, text_color = color.black, bgcolor = color.white, text_size = textSize)
            row += 1
        table.merge_cells(barTypeTable, 0, row, ezLastCol, row)
        table.cell(barTypeTable, 0, row, tableFtfcText, text_color = tableFtfcTextColor, bgcolor = tableFtfcBgColor, text_size = textSize, tooltip = "Full Timeframe Continuity (FTFC) compares the current price with the open of every timeframe in the table. Up: price is above all of them. Down: below all of them. Conflict: the timeframes disagree. Signals in the direction of continuity have the higher timeframes behind them.")
        row += 1
        if ezExplain  // EZ-MODE
            string ezAlign = ezN == 0 ? "No timeframe to read yet." : ezNUp == ezN ? (ezN == 1 ? "The timeframe is up." : "All " + str.tostring(ezN) + " timeframes are up.") : ezNUp == 0 ? (ezN == 1 ? "The timeframe is down." : "All " + str.tostring(ezN) + " timeframes are down.") : str.tostring(ezNUp) + " of " + str.tostring(ezN) + " up, " + str.tostring(ezN - ezNUp) + " down."
            string ezTrendLine = ezN < 2 ? "" : "\nHigher TFs (" + ezHtfNames + "): " + (ezHtf == 2 ? "up." : ezHtf == -2 ? "down." : "disagree.")
            string ezForce = (ezUp != "" ? "\nIn force up: " + ezUp : "") + (ezDn != "" ? "\nIn force down: " + ezDn : "")
            if ezForce == ""
                ezForce := "\nNothing in force yet."
            string ezNext = ""
            if ezN >= 2 and ezHtf == 2 and not na(ezTrigUp)
                ezNext := "\nNext up: " + ezTrigUpTf + " above " + str.tostring(ezTrigUp, format.mintick)
            else if ezN >= 2 and ezHtf == -2 and not na(ezTrigDn)
                ezNext := "\nNext down: " + ezTrigDnTf + " below " + str.tostring(ezTrigDn, format.mintick)
            table.merge_cells(barTypeTable, 0, row, ezLastCol, row)
            table.cell(barTypeTable, 0, row, ezAlign + ezTrendLine + ezForce + ezWatch + ezNext, text_color = #cccccc, bgcolor = #111111, text_size = textSize, text_halign = text.align_left, tooltip = "A plain-English read of the table, in the order to ask the questions. 1: do the timeframes agree. 2: which way are the higher timeframes going. 3: what is in force, meaning a signal has triggered and price is holding beyond its trigger. A line such as 1H hammer: above 204.10 means the last closed 1H bar is a hammer and a break above that price is its trigger. 4: Next up or Next down is the next trigger in the direction of the higher timeframes, on the lowest timeframe that has one. That is the level to watch, not a recommendation to trade. Turn this row off in the settings (Explain Row) once you no longer need it. TheStrat was created by Rob Smith.")
            row += 1
        if enableDirectionalFilter and hasLead   // FIX LEADROW-1
            table.merge_cells(barTypeTable, 0, row, ezLastCol, row)
            table.cell(barTypeTable, 0, row, leadRowText, text_color = leadRowTextColor, bgcolor = leadRowBgColor, text_size = textSize)
            row += 1
        if previewNextPeriod
            table.merge_cells(barTypeTable, 0, row, ezLastCol, row)
            table.cell(barTypeTable, 0, row, "PREVIEW MODE", text_color = color.yellow, bgcolor = color.new(color.yellow, 85), text_size = textSize, tooltip = "The market is closed, so the chart is showing the levels for the next bar to help you plan. A ? means that bar has not started trading. Set Preview Next Bar to Off for Bar Replay.")
            row += 1
 
// ============================================================================
// SECTION 12: DEBUG PANEL
// ============================================================================
 
debugBoolStr(b) => b ? "YES" : "NO"
debugBoolBg(b) => b ? color.new(#00aa00, 20) : color.new(#aa0000, 20)
debugBoolText(b) => b ? color.white : color.new(color.gray, 35)  // FIX P2-3: false branch was also white (dead ternary); now dimmed for contrast
debugHeaderBg = color.new(#333333, 0)
debugRowBg = color.new(#1a1a1a, 0)
debugLabelColor = #aaaaaa
 
// FEATURE DEBUG-TERMS-1: two panes side by side. The left pane reads the bars - what C1,
// C2 and CC actually are, and the patterns on them. The right pane reads the decision -
// which in-force term fired, what gated it, what got drawn. Row helpers replace the
// duplicated table.cell pairs the panel used to spell out one row at a time.
debugHdr(t, c, r, label) =>
    table.cell(t, c, r, label, text_color = color.white, bgcolor = debugHeaderBg, text_size = size.small, text_halign = text.align_center)
    table.cell(t, c + 1, r, "", bgcolor = debugHeaderBg, text_size = size.small)
 
debugRow(t, c, r, label, v) =>
    table.cell(t, c, r, label, text_color = debugLabelColor, bgcolor = debugRowBg, text_size = size.small, text_halign = text.align_left)
    table.cell(t, c + 1, r, debugBoolStr(v), text_color = debugBoolText(v), bgcolor = debugBoolBg(v), text_size = size.small, text_halign = text.align_center)
 
// One row per bidirectional term, read as high-side / low-side.
debugPair(t, c, r, label, h, l) =>
    table.cell(t, c, r, label, text_color = debugLabelColor, bgcolor = debugRowBg, text_size = size.small, text_halign = text.align_left)
    table.cell(t, c + 1, r, (h ? "Y" : "-") + " / " + (l ? "Y" : "-"), text_color = debugBoolText(h or l), bgcolor = debugBoolBg(h or l), text_size = size.small, text_halign = text.align_center)
 
var table debugTable = na
if barstate.isfirst and showDebugPanel
    debugTable := table.new(position.middle_left, 4, 27, bgcolor = color.new(#0d0d0d, 0), frame_color = color.orange, frame_width = 2, border_color = color.new(#333333, 0), border_width = 1)
 
if barstate.islast and showDebugPanel and not na(debugTable)
    dbg = debugData
    // Left pane: what the bars are
    table.cell(debugTable, 0, 0, "DEBUG: " + dbg.tfLabel, text_color = color.orange, bgcolor = debugHeaderBg, text_size = size.small, text_halign = text.align_left)
    table.cell(debugTable, 1, 0, "", bgcolor = debugHeaderBg, text_size = size.small)
    debugHdr(debugTable, 0, 1, "C1 Bar Type")
    debugRow(debugTable, 0, 2, "c1_was_2u", dbg.c1_was_2u)
    debugRow(debugTable, 0, 3, "c1_was_2d", dbg.c1_was_2d)
    debugRow(debugTable, 0, 4, "c1_is_3", dbg.c1_is_3)
    debugHdr(debugTable, 0, 5, "C2 Bar Type")
    debugRow(debugTable, 0, 6, "c2_was_2u", dbg.c2_was_2u)
    debugRow(debugTable, 0, 7, "c2_was_2d", dbg.c2_was_2d)
    debugRow(debugTable, 0, 8, "c2_was_3", dbg.c2_was_3)
    debugRow(debugTable, 0, 9, "c2_closed_up", dbg.c2_closed_up)
    debugRow(debugTable, 0, 10, "c2_closed_down", dbg.c2_closed_down)
    debugHdr(debugTable, 0, 11, "CC Bar Type")
    debugRow(debugTable, 0, 12, "cc_is_2u", dbg.cc_is_2u)
    debugRow(debugTable, 0, 13, "cc_is_2d", dbg.cc_is_2d)
    debugRow(debugTable, 0, 14, "cc_is_3", dbg.cc_is_3)
    debugRow(debugTable, 0, 15, "cc_broke_high", dbg.cc_broke_high)
    debugRow(debugTable, 0, 16, "cc_broke_low", dbg.cc_broke_low)
    debugHdr(debugTable, 0, 17, "Patterns")
    debugRow(debugTable, 0, 18, "isHammer", dbg.isHammer)
    debugRow(debugTable, 0, 19, "isShooter", dbg.isShooter)
    debugRow(debugTable, 0, 20, "isInside", dbg.isInside)
    debugHdr(debugTable, 0, 21, "Failed 2s")
    debugRow(debugTable, 0, 22, "is_f2u", dbg.is_f2u)
    debugRow(debugTable, 0, 23, "is_f2d", dbg.is_f2d)
    debugRow(debugTable, 0, 24, "pre_f2u", dbg.pre_f2u)
    debugRow(debugTable, 0, 25, "pre_f2d", dbg.pre_f2d)
    // Right pane: why it did or did not fire
    debugHdr(debugTable, 2, 0, "In Force")
    debugRow(debugTable, 2, 1, "sif_high", dbg.sif_high)
    debugRow(debugTable, 2, 2, "sif_low", dbg.sif_low)
    debugHdr(debugTable, 2, 3, "Terms  H / L")
    debugPair(debugTable, 2, 4, "Inside Rev", dbg.t_insideRev_h, dbg.t_insideRev_l)
    debugPair(debugTable, 2, 5, "Inside Cont", dbg.t_insideCont_h, dbg.t_insideCont_l)
    debugPair(debugTable, 2, 6, "Ham/Sho", dbg.t_hamSho_h, dbg.t_hamSho_l)
    debugPair(debugTable, 2, 7, "2-2 Rev", dbg.t_rev22_h, dbg.t_rev22_l)
    debugPair(debugTable, 2, 8, "2-2 Cont", dbg.t_cont22_h, dbg.t_cont22_l)
    debugPair(debugTable, 2, 9, "3-2 Exp", dbg.t_exp32_h, dbg.t_exp32_l)
    debugPair(debugTable, 2, 10, "Outside 3", dbg.t_exp3_h, dbg.t_exp3_l)
    debugPair(debugTable, 2, 11, "Failing 2", dbg.t_f2_h, dbg.t_f2_l)
    debugHdr(debugTable, 2, 12, "Gates")
    debugRow(debugTable, 2, 13, "hammer_shows", dbg.hammer_shows)
    debugRow(debugTable, 2, 14, "shooter_shows", dbg.shooter_shows)
    debugRow(debugTable, 2, 15, "ftfc_up", dbg.ftfc_up)
    debugRow(debugTable, 2, 16, "ftfc_down", dbg.ftfc_down)
    debugHdr(debugTable, 2, 17, "Draw Decisions")
    debugRow(debugTable, 2, 18, "drawHigh", dbg.drawHigh)
    debugRow(debugTable, 2, 19, "drawLow", dbg.drawLow)
    debugRow(debugTable, 2, 20, "drawMagHigh", dbg.drawMagHigh)
    debugRow(debugTable, 2, 21, "drawMagLow", dbg.drawMagLow)
    debugRow(debugTable, 2, 22, "drawExhHigh", dbg.drawExhHigh)
    debugRow(debugTable, 2, 23, "drawExhLow", dbg.drawExhLow)
    debugHdr(debugTable, 2, 24, "Magnitude")
    debugPair(debugTable, 2, 25, "force_mag", dbg.force_mag_high, dbg.force_mag_low)
    debugPair(debugTable, 2, 26, "mag_ftfc", dbg.mag_high_passes_ftfc, dbg.mag_low_passes_ftfc)
 
// ============================================================================
// SECTION 13: ALERTS
// ============================================================================
isSetupBull(ProcessingResult r) =>
    bool result = false
    if not na(r) and r.drawHigh and not r.isF2d
        is3Bar = str.startswith(r.ccType, "3")
        if is3Bar
            result := r.ccType == "3u"
        else
            result := r.ccType == "2u"
    result
 
isSetupBear(ProcessingResult r) =>
    bool result = false
    if not na(r) and r.drawLow and not r.isF2u
        is3Bar = str.startswith(r.ccType, "3")
        if is3Bar
            result := r.ccType == "3d"
        else
            result := r.ccType == "2d"
    result
 
isF2Bull(ProcessingResult r) =>
    // FIX P0-3: gate on show_p3_toggle so F2 (Range Reclaim) alerts do not fire when
    // Failing 2s are toggled OFF. The in-force state (f2_in_force_high) already gates on
    // show_p3_toggle, so without this the alert fired while the table said "not in force".
    show_p3_toggle and not na(r) and r.drawHigh and r.isF2d
 
isF2Bear(ProcessingResult r) =>
    show_p3_toggle and not na(r) and r.drawLow and r.isF2u
 
buildAlertLabel(ProcessingResult r, bool isBullish, TimeframeData data, ProcessingResult r_full) =>
    string result = ""
    if not na(r)
        string patternSuffix = ""
        if simpleLabelMode
            patternSuffix := (isBullish and data.c1IsHammer) ? "◆" : (not isBullish and data.c1IsShooter) ? "◆" : ""
        else
            patternSuffix := (isBullish and data.c1IsHammer) ? " HAM" : (not isBullish and data.c1IsShooter) ? " SHO" : ""
        string combo = ""
        c1IsInside = r.c1Num == "1"
        is32Pattern = r.c1Is3
        ccIs3 = str.startswith(r.ccType, "3")
        ccIsInsideAlert = r.ccType == "1"
        string c1TypeF2a = (r.c1WasF2 and show_p3_toggle ? "F" : "") + r.c1Type
        string c1NumF2a = (r.c1WasF2 and show_p3_toggle ? "F" : "") + r.c1Num
        string c2NumF2a = (r.c2WasF2 and show_p3_toggle ? "F" : "") + r.c2Num
        string dirArrow = ""
        if simpleLabelMode
            dirArrow := isBullish ? "↑" : "↓"
            // Simple mode for alerts
            if ccIs3 or is32Pattern
                combo := dirArrow + "EXP"
            else if (r.isF2d and isBullish) or (r.isF2u and not isBullish)
                combo := dirArrow + "FAILING"
            else if c1IsInside
                combo := dirArrow + "INS"
            else if ccIsInsideAlert
                // CC inside: potential setup (alerts rarely fire here)
                isCont = (isBullish and data.c1IsHighContinuation) or (not isBullish and data.c1IsLowContinuation)
                combo := isCont ? dirArrow + "CONT" : dirArrow + "REV"
            else if isBullish and data.c1IsHighContinuation
                combo := dirArrow + "CONT"
            else if not isBullish and data.c1IsLowContinuation
                combo := dirArrow + "CONT"
            else
                combo := dirArrow + "REV"
        else
            // F2 labels: only show C1 prior. NOTATION-1: canonical F2d/F2u (case no longer marks liveness)
            if r.isF2d and isBullish
                combo := c1TypeF2a + "F2d"
            else if r.isF2u and not isBullish
                combo := c1TypeF2a + "F2u"
            else if is32Pattern
                combo := "3" + r.ccType
            else if c1IsInside
                combo := c2NumF2a + c1NumF2a + r.ccType
            else
                // FEATURE REVSTRAT-122-1: alert text matches the chart label (1-2d-2u, 3-2d-2u)
                string c2PrefixA = (r.c2Num == "3" or r.c2Num == "1") and r.c1Num == "2" ? r.c2Num : ""
                combo := c2PrefixA + c1TypeF2a + r.ccType
        string side = showHighLowInLabel ? (isBullish ? " H" : " L") : ""
        string emoji = isBullish ? " 🟢" : " 🔴"
        result := r.tfLabel + " " + formatCombo(combo) + patternSuffix + side + emoji
        // FIX P1-j: build detail fields into a separate string and only append the " | "
        // separator when at least one field is actually present. The old code appended the
        // pipe unconditionally whenever any toggle was on, producing a dangling "... | " (and
        // double-pipes after TF consolidation) when every field was na - contradicting the
        // tooltip's "omitted automatically" promise. Single-space joins, no trailing space.
        string details = ""
        if alertShowTrigger
            float trigPrice = isBullish ? r_full.high : r_full.low
            if not na(trigPrice)
                details := details + (details == "" ? "" : " ") + "@ " + str.tostring(trigPrice, format.mintick)
        if alertShowMagnitude
            float magPrice = isBullish ? r_full.magHigh : r_full.magLow
            if not na(magPrice)
                details := details + (details == "" ? "" : " ") + "MAG " + str.tostring(magPrice, format.mintick)
        if alertShowExhaustion
            float exhPrice = isBullish ? r_full.exhHigh : r_full.exhLow
            if not na(exhPrice)
                details := details + (details == "" ? "" : " ") + "EXH " + str.tostring(exhPrice, format.mintick)
        if alertShowStop
            float stopPrice = isBullish ? r_full.stopHigh : r_full.stopLow
            if not na(stopPrice)
                details := details + (details == "" ? "" : " ") + "STOP " + str.tostring(stopPrice, format.mintick)
        if details != ""
            result := result + " | " + details
    result
 
isPotentialBull(ProcessingResult r) =>
    bool result = false
    if not na(r) and r.drawHigh
        result := r.ccType == "1"  // FIX P2-5: ccType only ever emits 1/2u/2d/3u/3d/F2u/F2d; "1u"/"1d" were dead disjuncts
    result
 
isPotentialBear(ProcessingResult r) =>
    bool result = false
    if not na(r) and r.drawLow
        result := r.ccType == "1"  // FIX P2-5: removed unreachable "1u"/"1d" comparisons
    result
var array<bool> wasSetupBull = array.from(false, false, false, false, false, false)
var array<bool> wasSetupBear = array.from(false, false, false, false, false, false)
var array<bool> wasF2Bull = array.from(false, false, false, false, false, false)
var array<bool> wasF2Bear = array.from(false, false, false, false, false, false)
var array<bool> wasPotentialBull = array.from(false, false, false, false, false, false)
var array<bool> wasPotentialBear = array.from(false, false, false, false, false, false)
var array<int> alertLastPeriodStart = array.new<int>(6, na)  // FIX P1-c: last-seen HTF period-start per slot, to reset was-state on a new period
 
var bool any_newly_in_force = false
var bool any_newly_potential = false
var string alertMsg = ""
 
any_newly_in_force := false
any_newly_potential := false
alertMsg := ""
 
// FIX P1-c: reset per-slot was-state at the start of a new HTF period, so a brand-new
// signal that opens already in force (e.g. a gap-through new period that ended the prior
// period in force) still produces a false->true edge and alerts, instead of being masked
// by the prior period's true->true (no edge). Runs BEFORE the snapshot below so both the
// consolidated alert and the per-TF alertconditions observe the reset.
// Keyed off raw.realPeriodTime (the unshifted real period-open, same value P0-1 uses), NOT
// ccStartTime: ccStartTime is rewritten to the chart-bar time in preview and would force a
// reset every bar. The store sits OUTSIDE the reset guard so the slot latches on first sight
// (na seed) and the boundary test works thereafter; first-sight reset is a no-op (was-state
// is already false at init).
for pi = 0 to 5
    rawp = array.get(tfRawArr, pi)
    if not na(rawp)
        int sp = rawp.realPeriodTime
        if not na(sp)
            prevSp = array.get(alertLastPeriodStart, pi)
            if na(prevSp) or prevSp != sp
                array.set(wasSetupBull, pi, false)
                array.set(wasSetupBear, pi, false)
                array.set(wasF2Bull, pi, false)
                array.set(wasF2Bear, pi, false)
                array.set(wasPotentialBull, pi, false)
                array.set(wasPotentialBear, pi, false)
            array.set(alertLastPeriodStart, pi, sp)
 
// Snapshot was-state before loop updates it (alertconditions read after loop)
bool wasSetBull0 = array.get(wasSetupBull, 0), bool wasSetBear0 = array.get(wasSetupBear, 0)
bool wasSetBull1 = array.get(wasSetupBull, 1), bool wasSetBear1 = array.get(wasSetupBear, 1)
bool wasSetBull2 = array.get(wasSetupBull, 2), bool wasSetBear2 = array.get(wasSetupBear, 2)
bool wasSetBull3 = array.get(wasSetupBull, 3), bool wasSetBear3 = array.get(wasSetupBear, 3)
bool wasSetBull4 = array.get(wasSetupBull, 4), bool wasSetBear4 = array.get(wasSetupBear, 4)
bool wasSetBull5 = array.get(wasSetupBull, 5), bool wasSetBear5 = array.get(wasSetupBear, 5)
bool wasF2B0 = array.get(wasF2Bull, 0), bool wasF2Br0 = array.get(wasF2Bear, 0)
bool wasF2B1 = array.get(wasF2Bull, 1), bool wasF2Br1 = array.get(wasF2Bear, 1)
bool wasF2B2 = array.get(wasF2Bull, 2), bool wasF2Br2 = array.get(wasF2Bear, 2)
bool wasF2B3 = array.get(wasF2Bull, 3), bool wasF2Br3 = array.get(wasF2Bear, 3)
bool wasF2B4 = array.get(wasF2Bull, 4), bool wasF2Br4 = array.get(wasF2Bear, 4)
bool wasF2B5 = array.get(wasF2Bull, 5), bool wasF2Br5 = array.get(wasF2Bear, 5)
 
for i = 0 to 5
    cfg = array.get(tfConfigs, i)
    if cfg.enabled
        bool alertEnabled = switch i
            0 => alertTF1
            1 => alertTF2
            2 => alertTF3
            3 => alertTF4
            4 => alertTF5
            5 => alertTF6
            => true
        r = array.get(tfResults, i)
        d = array.get(tfDataArr, i)
        // FIX HTF-STRADDLE-1: never emit alerts from a preview/straddled slot - its CC is synthetic
        // or estimate-grade. Was-state still updates (U2 pattern), and the P1-c period reset re-arms
        // cleanly when the slot exits preview, so the first real bar of the new period alerts normally.
        rawAl = array.get(tfRawArr, i)
        bool slotPreview = straddleWindowOK and not na(rawAl) and rawAl.isPreview
        bool suppressBull = enableDirectionalFilter and anchorDirection == -1 and i < anchorIndex
        bool suppressBear = enableDirectionalFilter and anchorDirection == 1 and i < anchorIndex
 
        // Check setups (non-F2)
        isNowSetupBull = suppressBull ? false : isSetupBull(r)
        isNowSetupBear = suppressBear ? false : isSetupBear(r)
        wasSetBull = array.get(wasSetupBull, i)
        wasSetBear = array.get(wasSetupBear, i)
 
        // Check F2s separately
        isNowF2Bull = suppressBull ? false : isF2Bull(r)
        isNowF2Bear = suppressBear ? false : isF2Bear(r)
        wasF2B = array.get(wasF2Bull, i)
        wasF2Br = array.get(wasF2Bear, i)
 
        // FIX U2: only the consolidated alert() MESSAGE is gated by this TF's alert checkbox.
        // The was-state arrays below are updated UNCONDITIONALLY (was: an early `continue`
        // skipped them), so the per-TF alertconditions - which read the pre-loop snapshots -
        // detect true edges instead of firing every bar when a TF is enabled but its alert
        // checkbox is off.
        if alertEnabled and not slotPreview
            // Alert on new setup (independent of F2 state)
            if isNowSetupBull and not wasSetBull
                any_newly_in_force := true
                newLabel = buildAlertLabel(r, true, d, r)
                alertMsg := alertMsg == "" ? newLabel : alertMsg + " | " + newLabel
            if isNowSetupBear and not wasSetBear
                any_newly_in_force := true
                newLabel = buildAlertLabel(r, false, d, r)
                alertMsg := alertMsg == "" ? newLabel : alertMsg + " | " + newLabel
            // Alert on new F2 (independent of setup state)
            if isNowF2Bull and not wasF2B
                any_newly_in_force := true
                newLabel = buildAlertLabel(r, true, d, r)
                alertMsg := alertMsg == "" ? newLabel : alertMsg + " | " + newLabel
            if isNowF2Bear and not wasF2Br
                any_newly_in_force := true
                newLabel = buildAlertLabel(r, false, d, r)
                alertMsg := alertMsg == "" ? newLabel : alertMsg + " | " + newLabel
 
        // Update state (unconditional - keeps per-TF alertcondition snapshots accurate)
        array.set(wasSetupBull, i, isNowSetupBull)
        array.set(wasSetupBear, i, isNowSetupBear)
        array.set(wasF2Bull, i, isNowF2Bull)
        array.set(wasF2Bear, i, isNowF2Bear)
 
        // Potential signals
        isPotBull = isPotentialBull(r)
        isPotBear = isPotentialBear(r)
        wasPotBull = array.get(wasPotentialBull, i)
        wasPotBear = array.get(wasPotentialBear, i)
        if alertEnabled and not slotPreview and ((isPotBull and not wasPotBull) or (isPotBear and not wasPotBear))
            any_newly_potential := true
        array.set(wasPotentialBull, i, isPotBull)
        array.set(wasPotentialBear, i, isPotBear)
 
if any_newly_in_force and str.length(alertMsg) > 0
    if alertShowFTFC
        string ftfcState = ftfc_up ? "FTFC Up" : ftfc_down ? "FTFC Down" : "Conflict"
        alertMsg := alertMsg + " | " + ftfcState
    alert(alertMsg, alert.freq_once_per_bar)
 
var string lastDominoCombo = ""
var bool dominoAlertTriggered = false
dominoAlertTriggered := false
 
// Domino alert (uses shared dominoBestRun/dominoBestTFs computed before table section)
if dominoBestRun >= minDominoTFs and dominoBestTFs != lastDominoCombo
    dominoAlertTriggered := true
    if enableDominoAlerts
        alert("Domino: " + dominoBestTFs, alert.freq_once_per_bar)
    lastDominoCombo := dominoBestTFs
else if dominoBestRun < minDominoTFs
    lastDominoCombo := ""
 
r1 = array.get(tfResults, 0)
r2 = array.get(tfResults, 1)
r3 = array.get(tfResults, 2)
r4 = array.get(tfResults, 3)
r5 = array.get(tfResults, 4)
r6 = array.get(tfResults, 5)
 
// FIX HTF-STRADDLE-1: per-TF alertconditions also skip preview/straddled slots
bool okA1 = not (straddleWindowOK and array.get(tfRawArr, 0).isPreview)
bool okA2 = not (straddleWindowOK and array.get(tfRawArr, 1).isPreview)
bool okA3 = not (straddleWindowOK and array.get(tfRawArr, 2).isPreview)
bool okA4 = not (straddleWindowOK and array.get(tfRawArr, 3).isPreview)
bool okA5 = not (straddleWindowOK and array.get(tfRawArr, 4).isPreview)
bool okA6 = not (straddleWindowOK and array.get(tfRawArr, 5).isPreview)
 
// Per-TF alertconditions use pre-loop snapshots to detect transitions correctly
tf1_newly_bull = rEN1 and okA1 and ((isSetupBull(r1) and not wasSetBull0) or (isF2Bull(r1) and not wasF2B0))
tf1_newly_bear = rEN1 and okA1 and ((isSetupBear(r1) and not wasSetBear0) or (isF2Bear(r1) and not wasF2Br0))
tf2_newly_bull = rEN2 and okA2 and ((isSetupBull(r2) and not wasSetBull1) or (isF2Bull(r2) and not wasF2B1))
tf2_newly_bear = rEN2 and okA2 and ((isSetupBear(r2) and not wasSetBear1) or (isF2Bear(r2) and not wasF2Br1))
tf3_newly_bull = rEN3 and okA3 and ((isSetupBull(r3) and not wasSetBull2) or (isF2Bull(r3) and not wasF2B2))
tf3_newly_bear = rEN3 and okA3 and ((isSetupBear(r3) and not wasSetBear2) or (isF2Bear(r3) and not wasF2Br2))
tf4_newly_bull = rEN4 and okA4 and ((isSetupBull(r4) and not wasSetBull3) or (isF2Bull(r4) and not wasF2B3))
tf4_newly_bear = rEN4 and okA4 and ((isSetupBear(r4) and not wasSetBear3) or (isF2Bear(r4) and not wasF2Br3))
tf5_newly_bull = rEN5 and okA5 and ((isSetupBull(r5) and not wasSetBull4) or (isF2Bull(r5) and not wasF2B4))
tf5_newly_bear = rEN5 and okA5 and ((isSetupBear(r5) and not wasSetBear4) or (isF2Bear(r5) and not wasF2Br4))
tf6_newly_bull = rEN6 and okA6 and ((isSetupBull(r6) and not wasSetBull5) or (isF2Bull(r6) and not wasF2B5))
tf6_newly_bear = rEN6 and okA6 and ((isSetupBear(r6) and not wasSetBear5) or (isF2Bear(r6) and not wasF2Br5))
 
var bool was_ftfc_up = false
var bool was_ftfc_down = false
ftfc_shifted_up = ftfc_up and not was_ftfc_up
ftfc_shifted_down = ftfc_down and not was_ftfc_down
ftfc_shifted_conflict = not ftfc_up and not ftfc_down and (was_ftfc_up or was_ftfc_down)
ftfc_shifted = ftfc_shifted_up or ftfc_shifted_down or ftfc_shifted_conflict
was_ftfc_up := ftfc_up
was_ftfc_down := ftfc_down
 
alertcondition(any_newly_in_force, "Signal In-Force (Any)", "Signal In-Force")
alertcondition(tf1_newly_bull or tf2_newly_bull or tf3_newly_bull or tf4_newly_bull or tf5_newly_bull or tf6_newly_bull, "Signal In-Force (Bullish)", "Bullish In-Force")
alertcondition(tf1_newly_bear or tf2_newly_bear or tf3_newly_bear or tf4_newly_bear or tf5_newly_bear or tf6_newly_bear, "Signal In-Force (Bearish)", "Bearish In-Force")
alertcondition(any_newly_potential, "New Potential (Any)", "New Potential Signal")
alertcondition(ftfc_shifted, "FTFC Shifted", "FTFC Shifted")
alertcondition(ftfc_shifted_up, "FTFC Up", "FTFC Up")
alertcondition(ftfc_shifted_down, "FTFC Down", "FTFC Down")
alertcondition(ftfc_shifted_conflict, "FTFC Conflict", "FTFC Conflict")
 
// ============================================================================
// SECTION 14: BAR COLORING
// ============================================================================
// FEATURE BARCOLOR-1 (2026-07-30): paint chart candles by their Strat classification or
// by Full Timeframe Continuity - the price-action painting from the pre-Suite standalone
// scripts, folded in for v3.
//
// Strat Candles reuses detectBarTypeAndFailed - the exact classifier behind the data
// table's CC cell - on the chart bar itself, so candle paint and table notation cannot
// disagree, and the Failing 2 method/enable settings govern candles automatically (the
// P1-f consistency rule). Family colors come from the existing Style inputs, so a custom
// palette hits lines, labels, and candles together.
//
// FTFC Candles deliberately does NOT read ftfc_up/ftfc_down: under lookahead_on their
// HTF closes are FINAL period values on historical bars, so painting history with them
// would color every bar of an up-closing day green from the open - prophetic hindsight.
// Instead calculateFTFC is re-run with the chart bar's own close against the served HTF
// opens (period-stable under lookahead_on: an open never changes after its period
// starts), grading every historical bar exactly as continuity stood at that bar's close.
// On the live bar the served HTF close IS the live close, so this equals
// ftfc_up/ftfc_down and the candle always agrees with the table's FTFC row. (The
// exhDisablesFTFC read-out is table-display only per FIX P1-e and is not mirrored here.)
 
color chartCandleColor = na
 
// Strat Candles: family colors follow the Style inputs. An F2 whose family toggle is off
// falls back to its plain directional color (an F2u IS a 2u, shown without failure paint).
getChartBarColor(string barType) =>
    switch barType
        "1u"  => paintInsideBars ? colorBullishPotential : color(na)
        "1d"  => paintInsideBars ? colorBearishPotential : color(na)
        "2u"  => paint2Bars ? colorBullishActive : color(na)
        "2d"  => paint2Bars ? colorBearishActive : color(na)
        "F2u" => paintFailedBars ? COLOR_FAILED_2U : paint2Bars ? colorBullishActive : color(na)
        "F2d" => paintFailedBars ? COLOR_FAILED_2D : paint2Bars ? colorBearishActive : color(na)
        "3u"  => paintOutsideBars ? COLOR_3_HIGH : color(na)
        "3d"  => paintOutsideBars ? COLOR_3_LOW : color(na)
        => color(na)
 
// FEATURE BARNUM-1: one classification per bar shared by Strat Candles and Bar Numbers
// (SECTION 15), so the two can never disagree and turning both on costs one call, not two.
string chartBarType = ""
if barColorMode == "Strat Candles" or showBarNumbers
    [chartBarTypeNow, _chartBarIsFailed] = detectBarTypeAndFailed(high[1], low[1], high, low, open, close)
    chartBarType := chartBarTypeNow
if barColorMode == "Strat Candles"
    chartCandleColor := getChartBarColor(chartBarType)
 
// FTFC Candles: per-slot Failing 2 state for the flip highlight. The served ccH/ccL are
// final period values on historical bars (the same lookahead leak as above), so the HTF
// bar's range-so-far is rebuilt from chart bars: running H/L keyed on the served
// period-open time, which is stable under lookahead_on (P0-1's realPeriodTime relies on
// the same property). detectFailed2 then grades served C1 range vs served open vs chart
// close - the same engine the signal path uses, on honestly-reconstructed inputs. Six
// independent call sites (one per slot) so each keeps its own var state - never called
// from a loop (the P0-1 shared-buffer lesson).
paintSlotFailed2(bool en, int ccTime, float c1H, float c1L, float ccO) =>
    var float runH = na
    var float runL = na
    var int lastP = na
    if not na(ccTime)
        if na(lastP) or ccTime != lastP
            runH := high
            runL := low
            lastP := ccTime
        else
            runH := math.max(runH, high)
            runL := math.min(runL, low)
    bool f2u = false
    bool f2d = false
    if en and not na(c1H) and not na(c1L) and not na(ccO) and not na(runH) and not na(runL)
        [_is2u, _is2d, _is3, isF2u, isF2d, _preU, _preD] = detectFailed2(c1H, c1L, ccO, close, runH, runL, failed_2_method)
        f2u := isF2u
        f2d := isF2d
    [f2u, f2d]
 
var bool wasPaintFtfcUp = false
var bool wasPaintFtfcDown = false
if barColorMode == "FTFC Candles"
    [paintFtfcUp, paintFtfcDown] = calculateFTFC(rEN1, tf1O, close, rEN2, tf2O, close, rEN3, tf3O, close, rEN4, tf4O, close, rEN5, tf5O, close, rEN6, tf6O, close)
    bool paintFlipUp = paintFtfcUp and not wasPaintFtfcUp
    bool paintFlipDown = paintFtfcDown and not wasPaintFtfcDown
    wasPaintFtfcUp := paintFtfcUp
    wasPaintFtfcDown := paintFtfcDown
    bool paintAnyF2u = false
    bool paintAnyF2d = false
    if paintFtfcTransitions
        [slotF2u1, slotF2d1] = paintSlotFailed2(rEN1 and timeframe.in_seconds(rTF1) >= chartTfSeconds, tf1CurrTime, tf1H, tf1L, tf1O)
        [slotF2u2, slotF2d2] = paintSlotFailed2(rEN2 and timeframe.in_seconds(rTF2) >= chartTfSeconds, tf2CurrTime, tf2H, tf2L, tf2O)
        [slotF2u3, slotF2d3] = paintSlotFailed2(rEN3 and timeframe.in_seconds(rTF3) >= chartTfSeconds, tf3CurrTime, tf3H, tf3L, tf3O)
        [slotF2u4, slotF2d4] = paintSlotFailed2(rEN4 and timeframe.in_seconds(rTF4) >= chartTfSeconds, tf4CurrTime, tf4H, tf4L, tf4O)
        [slotF2u5, slotF2d5] = paintSlotFailed2(rEN5 and timeframe.in_seconds(rTF5) >= chartTfSeconds, tf5CurrTime, tf5H, tf5L, tf5O)
        [slotF2u6, slotF2d6] = paintSlotFailed2(rEN6 and timeframe.in_seconds(rTF6) >= chartTfSeconds, tf6CurrTime, tf6H, tf6L, tf6O)
        paintAnyF2u := slotF2u1 or slotF2u2 or slotF2u3 or slotF2u4 or slotF2u5 or slotF2u6
        paintAnyF2d := slotF2d1 or slotF2d2 or slotF2d3 or slotF2d4 or slotF2d5 or slotF2d6
    // Only paint where served HTF data exists: beyond the calc_bars_count horizon every
    // slot returns na and skips inside calculateFTFC, leaving the untouched true/true
    // seed - which would read as "up" and paint deep history solid green.
    bool paintFtfcHasData = (rEN1 and not na(tf1O)) or (rEN2 and not na(tf2O)) or (rEN3 and not na(tf3O)) or (rEN4 and not na(tf4O)) or (rEN5 and not na(tf5O)) or (rEN6 and not na(tf6O))
    if paintFtfcHasData
        // A flip bar driven by a live reclaim paints in the reclaim's color; otherwise
        // plain continuity colors. A flip to up rides a BULLISH reclaim (F2d), and vice versa.
        if paintFtfcTransitions and paintFlipUp and paintAnyF2d
            chartCandleColor := COLOR_FAILED_2D
        else if paintFtfcTransitions and paintFlipDown and paintAnyF2u
            chartCandleColor := COLOR_FAILED_2U
        else if paintFtfcUp
            chartCandleColor := colorFtfcUpBar
        else if paintFtfcDown
            chartCandleColor := colorFtfcDownBar
        else if paintFtfcConflict
            chartCandleColor := colorFtfcConflictBar
 
barcolor(chartCandleColor, title = "Strat / FTFC Candles")
 
// ============================================================================
// SECTION 15: BAR NUMBERS
// ============================================================================
// FEATURE BARNUM-1 (2026-10-23): print each chart candle's Strat number beside it.
//
// Rendered with plotshape, not label.new. plotshape draws on every bar of history at no
// cost to max_labels_count, which the level labels already spend; labels would cap the
// numbers near the budget and TradingView garbage-collects the OLDEST labels first, which
// could delete a level label. The price is fixed text size: plotshape's size sizes the
// (invisible) shape, never the text. plotshape text must be a const string, so there is one
// call per token, and location is input-qualified, so tokens whose side depends on the bar
// ("3" in Classic, "2" in Numbers) get an up-side and a down-side call. 11 calls in all.
//
// Like Strat Candles (SECTION 14) this runs on every bar - it is history, not islast
// rendering - and it is repaint-safe for the same reason (repaint-prevention.md Rule 8): it
// reads only the chart bar's own OHLC and the prior bar's high/low, which evaluate
// identically live and on reload. The forming bar is drawn lighter until it confirms.
//
// Classification is chartBarType from SECTION 14 (detectBarTypeAndFailed, the CC
// classifier), so numbers, candle paint and the table share one engine and one Failing 2
// method (the P1-f consistency rule). Booleans, not built strings, keep the per-bar cost
// to a few string compares (the PERF-FTFC-1 lesson).
 
bool bnOn = showBarNumbers and chartBarType != ""
bool bnFull = barNumNotation == "Full"
bool bnF2 = bnFull and show_p3_toggle  // EZ-MODE
bool bnNumbers = barNumNotation == "Numbers"
bool bnKeyOnly = barNumEmphasis == "Key Bars Only"
 
bool bnIs1 = chartBarType == "1u" or chartBarType == "1d"
bool bnIs3u = chartBarType == "3u"
bool bnIs3d = chartBarType == "3d"
bool bnIsF2u = chartBarType == "F2u"
bool bnIsF2d = chartBarType == "F2d"
// A Failing 2 renders as its plain 2 outside Full notation (as Strat Candles does with F2 paint off).
bool bnPlain2u = chartBarType == "2u" or (bnIsF2u and not bnF2)
bool bnPlain2d = chartBarType == "2d" or (bnIsF2d and not bnF2)
 
// Text color: family color from the Style inputs (or the single color), then emphasis
// tiering, then lightened on the forming bar.
color bnPalette = switch chartBarType
    "1u"  => colorBullishPotential
    "1d"  => colorBearishPotential
    "2u"  => colorBullishActive
    "2d"  => colorBearishActive
    "F2u" => bnF2 ? COLOR_FAILED_2U : colorBullishActive
    "F2d" => bnF2 ? COLOR_FAILED_2D : colorBearishActive
    "3u"  => COLOR_3_HIGH
    "3d"  => COLOR_3_LOW
    => color(na)
color bnBase = barNumColorMode == "Single Color" ? barNumColor : bnPalette
float bnTransp = barNumEmphasis == "Tiered" and (bnPlain2u or bnPlain2d) ? 65 : 0
if barstate.islast and not barstate.isconfirmed
    bnTransp := bnTransp + (100 - bnTransp) / 2
color bnTextColor = color.new(bnBase, bnTransp)
color bnShapeColor = color.new(color.black, 100)
 
// Placement. Up-side tokens (2u, F2u, 3u) and down-side tokens (2d, F2d, 3d) only split
// under Broken Side; inside bars sit with the down side.
string bnLocUp = barNumPosition == "Below" ? location.belowbar : location.abovebar
string bnLocDown = barNumPosition == "Above" ? location.abovebar : location.belowbar
// FIX BARNUM-SHOWN-1 (2026-11-06): Bars Shown is a dropdown of named counts, default Last 50,
// instead of an integer where 0 meant every candle. show_last needs an input-qualified int, which
// this ternary chain of input-derived values still is.
int bnShowLast = barNumBarsShown == "Last 10" ? 10 : barNumBarsShown == "Last 20" ? 20 : barNumBarsShown == "Last 50" ? 50 : barNumBarsShown == "Last 100" ? 100 : barNumBarsShown == "Last 250" ? 250 : na
 
plotshape(bnOn and bnIs1, "Bar # 1", shape.circle, bnLocDown, bnShapeColor, text = "1", textcolor = bnTextColor, size = size.tiny, show_last = bnShowLast, display = display.pane, editable = false)
plotshape(bnOn and not bnNumbers and not bnKeyOnly and bnPlain2u, "Bar # 2u", shape.circle, bnLocUp, bnShapeColor, text = "2u", textcolor = bnTextColor, size = size.tiny, show_last = bnShowLast, display = display.pane, editable = false)
plotshape(bnOn and not bnNumbers and not bnKeyOnly and bnPlain2d, "Bar # 2d", shape.circle, bnLocDown, bnShapeColor, text = "2d", textcolor = bnTextColor, size = size.tiny, show_last = bnShowLast, display = display.pane, editable = false)
plotshape(bnOn and bnNumbers and not bnKeyOnly and bnPlain2u, "Bar # 2 (up)", shape.circle, bnLocUp, bnShapeColor, text = "2", textcolor = bnTextColor, size = size.tiny, show_last = bnShowLast, display = display.pane, editable = false)
plotshape(bnOn and bnNumbers and not bnKeyOnly and bnPlain2d, "Bar # 2 (down)", shape.circle, bnLocDown, bnShapeColor, text = "2", textcolor = bnTextColor, size = size.tiny, show_last = bnShowLast, display = display.pane, editable = false)
plotshape(bnOn and bnF2 and bnIsF2u, "Bar # F2u", shape.circle, bnLocUp, bnShapeColor, text = "F2u", textcolor = bnTextColor, size = size.tiny, show_last = bnShowLast, display = display.pane, editable = false)
plotshape(bnOn and bnF2 and bnIsF2d, "Bar # F2d", shape.circle, bnLocDown, bnShapeColor, text = "F2d", textcolor = bnTextColor, size = size.tiny, show_last = bnShowLast, display = display.pane, editable = false)
plotshape(bnOn and bnFull and bnIs3u, "Bar # 3u", shape.circle, bnLocUp, bnShapeColor, text = "3u", textcolor = bnTextColor, size = size.tiny, show_last = bnShowLast, display = display.pane, editable = false)
plotshape(bnOn and bnFull and bnIs3d, "Bar # 3d", shape.circle, bnLocDown, bnShapeColor, text = "3d", textcolor = bnTextColor, size = size.tiny, show_last = bnShowLast, display = display.pane, editable = false)
plotshape(bnOn and not bnFull and bnIs3u, "Bar # 3 (up)", shape.circle, bnLocUp, bnShapeColor, text = "3", textcolor = bnTextColor, size = size.tiny, show_last = bnShowLast, display = display.pane, editable = false)
plotshape(bnOn and not bnFull and bnIs3d, "Bar # 3 (down)", shape.circle, bnLocDown, bnShapeColor, text = "3", textcolor = bnTextColor, size = size.tiny, show_last = bnShowLast, display = display.pane, editable = false)

← 返回列表