Trend Zone Flow [AxeAlgo]

AxeAlgo · study · 1808 行 · 点赞 164 · TradingView 原页

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

Pine Script

//@version=6
// ══════════════════════════════════════════════════════════════════════════════
// © AxeAlgo
//  Trend Zone Flow [AxeAlgo]
// ══════════════════════════════════════════════════════════════════════════════
//
//  WHAT THIS INDICATOR DOES
//  ------------------------
//  Trend Zone Flow combines the three core pillars of technical
//  market analysis into a single TradingView indicator. Bullish / bearish setups are
//  confirmed on bar close and do not repaint; S/R zones keep updating as new
//  structure forms.
//
//    1. TREND & REGIME (McGinley Dynamic ribbon):
//       Twelve McGinley-style adaptive curves (lengths 8, 10, 12, 15, 18, 21,
//       25, 29, 34, 39, 45, 52) sharing one fourth-power speed factor taken from
//       band 7 (length 25), drawn as a 12-line ribbon and classifying the
//       market into TREND UP, TREND DOWN,
//       RANGING, or VOLATILE / NO-TRADE with hysteresis and flip-rate filtering.
//
//    2. STRUCTURE & S/R ZONES (max 5 visible at once):
//       Detects swing pivots and clusters them into multi-touch support and
//       resistance zones, showing no more than 3–5 zones combined across
//       the entire chart. Features automated cluster merging, debounced distinct
//       touch counting (>= 5 bars), impulse rejection displacement tracking,
//       higher-timeframe swing alignment and round-number proximity (both
//       raise zone strength), early high-volume confirmation (Ⓥ), and
//       disciplined single role-reversal with immediate cleanup of broken zones.
//
//    3. VOLUME PRESSURE (ESTIMATED DELTA & CVD):
//       Estimates buying vs. selling pressure from lower-timeframe candles
//       (request.security_lower_tf) or, in lite mode, from the chart bar alone.
//       The dashboard's Data row shows which source is in use. Standard Pine
//       Script indicators do not have access to raw exchange order-book bid/ask
//       tick footprint data; delta here is estimated from where each candle
//       closes within its range, weighted by its volume.
//
//  CONFLUENCE SCORING SYSTEM (0–100 BULLISH / 0–100 BEARISH)
//  ---------------------------------------------------------
//  Computes independent Bullish and Bearish Confluence Scores from the three pillars:
//    • Trend & Regime: 35% base weight (evaluates alignment, pullback quality & extension)
//    • Structural S/R: 35% base weight (requires active reaction confirmation, not just proximity)
//    • Volume Pressure: 30% base weight (estimated delta, CVD trend, absorption & divergences)
//  If volume is unavailable, weights automatically re-balance to 50% Trend and 50% Structure.
//
//  COMPLIANCE DISCLAIMER
//  ---------------------
//  This script visualizes price structure, trend regimes and estimated volume
//  pressure for analytical context. The Confluence Score describes multi-factor
//  agreement quality and is strictly NOT a win probability, profit guarantee, or
//  automated trade signal generator.
// ══════════════════════════════════════════════════════════════════════════════
 
indicator("Trend Zone Flow [AxeAlgo]", overlay = true,
     max_boxes_count = 500, max_lines_count = 500, max_labels_count = 500)
 
// ═════════════════════════ INPUT CONFIGURATION ═════════════════════════
// Everyday settings first; fine-tuning lives in "7. Advanced" at the bottom.
 
// ───────── 1. SETUPS ─────────
gSignals = "1. Setups"
showSignals   = input.bool(true, "Show Setups", group = gSignals, tooltip = "Marks bullish ▲ and bearish ▼ setups when trend, structure and volume pressure line up. Confirmed on bar close, no repainting. Hover a marker to see why it appeared. Analytical context only, not trade advice.")
setupModeIn   = input.string("Trend + Reversals", "Setup Type", options = ["Trend + Reversals", "Trend Only", "Reversals Only", "All Setups"], group = gSignals, tooltip = "Trend + Reversals: pullbacks within a trend plus rejections at S/R zones (recommended).\nTrend Only: pullbacks in the direction of the trend.\nReversals Only: rejections at S/R zones.\nAll Setups: also adds strong momentum bursts.")
sensitivityIn = input.string("Balanced", "Sensitivity", options = ["Conservative", "Balanced", "Aggressive"], group = gSignals, tooltip = "Conservative: fewer setups, stronger agreement required.\nBalanced: recommended.\nAggressive: more setups, allows a second setup on the same trend wave.")
htfContFilter = input.bool(true, "Follow Higher-Timeframe Trend", group = gSignals, tooltip = "Trend setups only appear in the direction of the higher-timeframe trend (15m chart uses 4h, 1h uses Daily, and so on). Reversals are unaffected.")
htfReversals  = input.bool(false, "Allow Reversals on 1h+ Charts", group = gSignals, tooltip = "Reversal setups are off on 1h and higher timeframes unless enabled here. Trend setups are unaffected.")
signalStyle   = input.string("Badge (▲ ▼)", "Marker Style", options = ["Badge (▲ ▼)", "Arrow (▲ ▼)", "Diamond (◆)"], inline = "sig", group = gSignals)
signalSize    = input.string("Normal", "", options = ["Small", "Normal", "Large"], inline = "sig", group = gSignals)
showSetupLevels = input.bool(false, "Show Active Setup Levels", group = gSignals, tooltip = "Draws the latest setup's invalidation level (dotted) and the next opposing zone (dashed). Removed when the setup is invalidated, the trend flips or it expires.")
 
// ───────── 2. SUPPORT & RESISTANCE ZONES ─────────
gVisZones = "2. Support & Resistance Zones"
showZones           = input.bool(true, "Show Zones", group = gVisZones, tooltip = "Draws the S/R zone boxes. Zones still feed the market read when hidden.")
maxVisibleZones     = input.int(5, "Max Zones Shown", minval = 3, maxval = 5, group = gVisZones, tooltip = "Most relevant support + resistance zones shown at once (3–5).")
zoneLabelStyle      = input.string("Classic Badges (RES · 85)", "Zone Labels", options = ["Classic Badges (RES · 85)", "Compact (R · 85)", "Off"], group = gVisZones, tooltip = "Badge shows zone strength (0–100) and how many times price reacted there.")
showHistoricalZones = input.bool(true, "Show Past Zones When Scrolling", group = gVisZones)
showBrokenZones     = input.bool(false, "Show Broken Zones", group = gVisZones, tooltip = "Keeps broken zones on the chart in a faint dashed style.")
showMidlines        = input.bool(false, "Show Zone Centerlines", group = gVisZones)
 
// ───────── 3. TREND RIBBON ─────────
gVisRibbon = "3. Trend Ribbon"
ribbonStyle = input.string("Classic (12-Band Layered)", "Ribbon Style", options = ["Classic (12-Band Layered)", "Standard (6-Band)", "Minimal Core Line", "Off"], group = gVisRibbon, tooltip = "Ribbon colour shows the regime: gold = trend up, crimson = trend down, slate = ranging, purple = volatile.")
ribbonCloud = input.bool(true, "Ribbon Fill", group = gVisRibbon)
 
// ───────── 4. DASHBOARD ─────────
gVisHud = "4. Dashboard"
showHud       = input.bool(true, "Show Dashboard", group = gVisHud, tooltip = "Regime, trend alignment, setup status, last setup, nearest support / resistance, volume pressure and overall bias.")
hudPos        = input.string("Top Right", "Position", options = ["Top Right", "Top Left", "Bottom Right", "Bottom Left"], inline = "hud", group = gVisHud)
hudSize       = input.string("Small", "", options = ["Tiny", "Small", "Normal"], inline = "hud", group = gVisHud)
hudTheme      = input.string("Auto", "Theme", options = ["Auto", "Dark", "Light"], group = gVisHud, tooltip = "Auto matches the chart background. Also applies to zone badges.")
showScoreBars = input.bool(true, "Show Bias Meter", group = gVisHud)
showDataRow   = input.bool(true, "Show Data Source Row", group = gVisHud)
 
// ───────── 5. VOLUME PRESSURE ─────────
gFlow = "5. Volume Pressure (Estimated)"
engModeIn    = input.string("Lower Timeframe (more detail)", "Source", options = ["Lower Timeframe (more detail)", "Chart Bars (faster)"], group = gFlow, tooltip = "Buying vs. selling pressure is estimated from where candles close within their range, weighted by volume. Not true order-flow data.")
deltaMethod  = input.string("Range Position", "Estimation Method", options = ["Range Position", "Bar Polarity", "Close vs Open"], group = gFlow, tooltip = "Range Position: volume weighted by where each candle closes within its range (recommended).\nBar Polarity: close vs previous close.\nClose vs Open: candle colour.")
cvdResetMode = input.string("Daily", "Cumulative Reset", options = ["Daily", "Weekly", "Never"], group = gFlow)
showMarkers  = input.bool(false, "Show Absorption Dots", group = gFlow, tooltip = "Small dots where heavy volume met little price progress. Context only.")
 
// ───────── 6. COLORS ─────────
gVisGen = "6. Colors"
colorGold       = input.color(#D4AF37, "Bullish", inline = "c1", group = gVisGen)
colorCrimson    = input.color(#DC143C, "Bearish", inline = "c1", group = gVisGen)
colorVol        = input.color(#6B5282, "Volatile", inline = "c1", group = gVisGen)
zoneResCol      = input.color(#b22833, "Resistance Zone", inline = "c2", group = gVisGen)
colorBullAccent = input.color(#10B981, "Alt Support", inline = "c2", group = gVisGen)
supportColTheme = input.string("AxeAlgo Gold", "Support Zone Color", options = ["AxeAlgo Gold", "Emerald Teal"], group = gVisGen, tooltip = "AxeAlgo Gold uses the Bullish colour; Emerald Teal uses Alt Support.")
showWatermark   = input.bool(true, "Show Watermark", inline = "wm", group = gVisGen)
wmTheme         = input.string("Auto", "", options = ["Auto", "Dark", "Light"], inline = "wm", group = gVisGen, tooltip = "Watermark theme. Auto matches the chart background.")
 
// ───────── 7. ADVANCED (OPTIONAL) ─────────
gAdv = "7. Advanced (Optional)"
mcgK             = input.float(0.60, "Ribbon Speed (k)", minval = 0.1, maxval = 2.0, step = 0.05, group = gAdv, tooltip = "Lower = faster ribbon, higher = smoother.")
adxThreshold     = input.float(20.0, "Trend Strength Threshold (ADX)", minval = 10.0, maxval = 50.0, group = gAdv, tooltip = "ADX needed before the market counts as trending.")
autoTunePivots   = input.bool(true, "Auto Swing Length", inline = "piv", group = gAdv, tooltip = "Picks the swing length for zones from the chart timeframe. Untick to use the manual value.")
pivotLenManual   = input.int(10, "", minval = 3, maxval = 60, inline = "piv", group = gAdv)
pvRight          = input.int(3, "Swing Confirmation Bars", minval = 1, maxval = 10, group = gAdv, tooltip = "Bars after a swing before it is confirmed. Prevents repainting.")
clusterTolAtr    = input.float(0.40, "Zone Merge Distance (× ATR)", minval = 0.10, maxval = 1.5, step = 0.05, group = gAdv, tooltip = "Swings closer than this merge into one zone.")
maxRibbonDistAtr = input.float(2.2, "Max Distance From Ribbon (× ATR)", minval = 1.0, maxval = 4.0, step = 0.1, group = gAdv, tooltip = "No setup when price is stretched further than this from the ribbon core.")
 
// ───────── FIXED ENGINE PARAMETERS ─────────
// Tuned defaults kept out of the settings so they stay simple.
adxLen               = 14
natrLB               = 100
volHiPct             = 85.0
chopWindow           = 30
chopFlipThresh       = 3
maxProximityAtr      = 14.0
minZoneScore         = 35
minHeightAtr         = 0.55
maxHeightAtr         = 1.20
zoneLookback         = 80
primaryFillOpacity   = 14
secondaryFillOpacity = 7
maxHistRetained      = 35
histFillOpacity      = 4
histWindowBars       = 30
ribbonCloudOpac      = 22
midlineMode          = "Volume-Weighted Pivot Anchor"
useHtfStruct         = true
useRoundNum          = true
flipOnBreak          = true
ltfResManual         = "Auto"
useAbsorption        = true
detectDiv            = true
wTrendBase           = 35
wStructBase          = 35
wFlowBase            = 30
strongThresh         = 65
moderateThresh       = 45
enableAsymScore      = true
asymMacroPenalty     = 8
minBodyRatio         = 0.25
retestMaxDistAtr     = 1.45
signalCooldown       = 3
enableStrictReversal = true
signalLifeBars       = 100
 
// Friendly settings mapped onto the engine
string signalMode = switch setupModeIn
    "Trend Only"     => "Trend Continuation Only"
    "Reversals Only" => "Strong Reversals Only"
    "All Setups"     => "All High-Confluence"
    => "Balanced (Continuation + Confirmed Reversals)"
int minSignalScore    = sensitivityIn == "Conservative" ? 58 : sensitivityIn == "Aggressive" ? 46 : 52
int scoreDiff         = sensitivityIn == "Conservative" ? 8 : sensitivityIn == "Aggressive" ? 4 : 6
string waveDiscipline = sensitivityIn == "Aggressive" ? "Dynamic Retest (Balanced)" : "Single Anchor Per Wave (Strict 1 Max)"
string engMode        = engModeIn == "Chart Bars (faster)" ? "Bar only (lite)" : "Lower-TF Intrabar (Recommended)"
string hudDensity     = showDataRow ? "Classic Structured" : "Compact Streamlined"
 
// ═════════════════════════ PALETTE & HELPER FUNCTIONS ═════════════════════════
 
// Distinct AxeAlgo Classic Brand Styling Tokens
// Dark set on dark charts, cream set on light charts (Auto reads the chart background)
bool lightUI  = hudTheme == "Light" or (hudTheme == "Auto" and (color.r(chart.bg_color) * 299 + color.g(chart.bg_color) * 587 + color.b(chart.bg_color) * 114) / 1000 >= 128)
C_BG_DEEP     = lightUI ? color.new(#F7F1E1, 4) : color.new(#14110B, 8)   // Panel background
C_BORDER_MUTE = lightUI ? color.new(#B8860B, 60) : color.new(#D4AF37, 64)  // Gold cell borders
C_FRAME       = lightUI ? color.new(#B8860B, 45) : color.new(#D4AF37, 52)  // Gold outer frame
C_TEXT_MUTE   = lightUI ? #7A6423 : #C9B37E                                // Labels
C_TEXT_BRT    = lightUI ? #1C1A17 : #F5F5F5                                // Values
C_TITLE       = lightUI ? #8B6B00 : #FFD400                                // Title
C_BULL_TXT    = lightUI ? #8B6B00 : #E5C158                                // Bullish / support text
C_BEAR_TXT    = lightUI ? #B22833 : #FF9575                                // Bearish / resistance text
C_BADGE_RES   = lightUI ? color.new(#F6E1DA, 0) : color.new(#2D140C, 6)    // Resistance badge fill
C_BADGE_SUP   = lightUI ? color.new(#F3ECD6, 0) : color.new(#182414, 6)    // Support badge fill
 
f_clamp(float val, float minV, float maxV) =>
    math.min(math.max(val, minV), maxV)
 
f_safeLeft(int b) =>
    math.max(math.max(0, bar_index - 4900), b)
 
f_safeRight(int b) =>
    math.min(bar_index + 450, math.max(0, b))
 
f_tablePos(string p) =>
    switch p
        "Top Right"    => position.top_right
        "Top Left"     => position.top_left
        "Bottom Right" => position.bottom_right
        "Bottom Left"  => position.bottom_left
        => position.top_right
 
f_tableSize(string s) =>
    switch s
        "Tiny"   => size.tiny
        "Small"  => size.small
        "Normal" => size.normal
        => size.small
 
f_autoPivLen() =>
    s = timeframe.in_seconds(timeframe.period)
    switch
        na(s)      => 14
        s <= 60    => 8
        s <= 300   => 10
        s <= 3600  => 14
        s <= 14400 => 18
        => 24
 
f_autoLtf() =>
    s = timeframe.in_seconds(timeframe.period)
    switch
        na(s)      => "15"
        s >= 86400 => "60"
        s >= 14400 => "30"
        s >= 3600  => "15"
        s >= 900   => "3"
        s >= 180   => "1"
        => "1"
 
f_autoMtf() =>
    s = timeframe.in_seconds(timeframe.period)
    switch
        na(s)      => "W"
        s <= 60    => "5"
        s <= 300   => "15"
        s <= 900   => "60"
        s <= 3600  => "240"
        s <= 14400 => "D"
        => "W"
 
f_autoHtf() =>
    s = timeframe.in_seconds(timeframe.period)
    switch
        na(s)      => "D"
        s <= 60    => "15"
        s <= 300   => "60"
        s <= 900   => "240"
        s <= 3600  => "D"
        s <= 14400 => "W"
        => "M"
 
f_meterStr(float frac) =>
    n = int(math.round(f_clamp(frac, 0.0, 1.0) * 5))
    (n < 1 ? "" : str.repeat("▰", n)) + (n > 4 ? "" : str.repeat("▱", 5 - n))
 
// ═════════════════════════ PILLAR A: TREND & REGIME (12-BAND McGINLEY) ═════════════════════════
 
atrVal = ta.atr(14)
natr   = atrVal / math.max(math.abs(close), 1e-9)
natrPct = ta.percentrank(natr, natrLB)
[diPlus, diMinus, adx] = ta.dmi(adxLen, adxLen)
 
// 12 McGinley-style ribbon lengths
int l1  = 8
int l2  = 10
int l3  = 12
int l4  = 15
int l5  = 18
int l6  = 21
int l7  = 25 // Core Speed Driver Band
int l8  = 29
int l9  = 34
int l10 = 39
int l11 = 45
int l12 = 52
 
// Shared Speed-Factor Optimization: Driver band 7 governs the responsive 4th-power scaling
var float m7Prev = close
rCore = m7Prev > 0 ? close / m7Prev : 1.0
sharedR4 = math.pow(rCore, 4)
 
f_mcgShared(float src, float prevVal, int len, float r4) =>
    denom = float(len) * mcgK * r4
    denomSafe = denom < 1.0 ? 1.0 : denom
    prevVal + (src - prevVal) / denomSafe
 
var float m1  = close
var float m2  = close
var float m3  = close
var float m4  = close
var float m5  = close
var float m6  = close
var float m7  = close
var float m8  = close
var float m9  = close
var float m10 = close
var float m11 = close
var float m12 = close
 
m1  := f_mcgShared(close, m1,  l1,  sharedR4)
m2  := f_mcgShared(close, m2,  l2,  sharedR4)
m3  := f_mcgShared(close, m3,  l3,  sharedR4)
m4  := f_mcgShared(close, m4,  l4,  sharedR4)
m5  := f_mcgShared(close, m5,  l5,  sharedR4)
m6  := f_mcgShared(close, m6,  l6,  sharedR4)
m7  := f_mcgShared(close, m7,  l7,  sharedR4)
m8  := f_mcgShared(close, m8,  l8,  sharedR4)
m9  := f_mcgShared(close, m9,  l9,  sharedR4)
m10 := f_mcgShared(close, m10, l10, sharedR4)
m11 := f_mcgShared(close, m11, l11, sharedR4)
m12 := f_mcgShared(close, m12, l12, sharedR4)
 
m7Prev := m7
 
// Ribbon Alignment & Expansion Metrics
int upSteps = 0
int dnSteps = 0
if m1 > m2
    upSteps += 1
if m2 > m3
    upSteps += 1
if m3 > m4
    upSteps += 1
if m4 > m5
    upSteps += 1
if m5 > m6
    upSteps += 1
if m6 > m7
    upSteps += 1
if m7 > m8
    upSteps += 1
if m8 > m9
    upSteps += 1
if m9 > m10
    upSteps += 1
if m10 > m11
    upSteps += 1
if m11 > m12
    upSteps += 1
 
if m1 < m2
    dnSteps += 1
if m2 < m3
    dnSteps += 1
if m3 < m4
    dnSteps += 1
if m4 < m5
    dnSteps += 1
if m5 < m6
    dnSteps += 1
if m6 < m7
    dnSteps += 1
if m7 < m8
    dnSteps += 1
if m8 < m9
    dnSteps += 1
if m9 < m10
    dnSteps += 1
if m10 < m11
    dnSteps += 1
if m11 < m12
    dnSteps += 1
 
ribbonSpread = math.abs(m1 - m12)
ribbonSpreadAtr = ribbonSpread / math.max(atrVal, 1e-9)
 
// Trend Direction, Slope & Expansion
slopeATR = (m7 - nz(m7[5])) / math.max(atrVal, 1e-9)
isAlignedUp = upSteps >= 7
isAlignedDn = dnSteps >= 7
isAdxTrending = adx >= adxThreshold
isRibbonExpanded = ribbonSpreadAtr >= 0.50
 
// Macro Volatility & Chaos Filter
isVolatileChaos = natrPct >= volHiPct and adx < adxThreshold
 
// Regime Flips Hysteresis & Anti-Chop Buffer
var int currentRegime = 1 // 2 = Trend Up, -2 = Trend Down, 1 = Ranging, 0 = Volatile
var int pendingRegime = 1
var int[] flipBars = array.new_int(0)
 
// Count flips in rolling chop window
while array.size(flipBars) > 0 and (bar_index - array.get(flipBars, 0)) > chopWindow
    array.shift(flipBars)
 
rawRegime = 1
if not (isAlignedUp or isAlignedDn) and isVolatileChaos
    rawRegime := 0
else if isAdxTrending and (isAlignedUp or isAlignedDn) and isRibbonExpanded
    if (currentRegime == 2 and upSteps >= 5) or (currentRegime == -2 and dnSteps >= 5)
        rawRegime := currentRegime
    else
        rawRegime := upSteps >= 9 ? 2 : dnSteps >= 9 ? -2 : (slopeATR >= 0 ? 2 : -2)
else
    rawRegime := 1
 
// Hysteresis Gate: Prevents single-bar noise flips
if rawRegime == currentRegime
    pendingRegime := rawRegime
else
    if rawRegime == 0 or rawRegime == pendingRegime
        currentRegime := rawRegime
        array.push(flipBars, bar_index)
    pendingRegime := rawRegime
 
regimeCode = currentRegime
bool chopSuppressed = array.size(flipBars) >= chopFlipThresh
 
// Regime age, for "just started" display
var int regimeStartBar = 0
if regimeCode != nz(regimeCode[1], regimeCode)
    regimeStartBar := bar_index
int regimeAge = bar_index - regimeStartBar
 
// Display strength (0–100): each factor saturates gradually so 100% is rare. Signals use trendQuality below.
float strengthDisp = math.round(40.0 * (1.0 - math.exp(-math.max(adx - 15.0, 0.0) / 15.0)) + 30.0 * (1.0 - math.exp(-ribbonSpreadAtr / 1.5)) + 30.0 * (1.0 - math.exp(-math.abs(slopeATR) / 0.25)))
string strengthWord = strengthDisp >= 75 ? "strong" : strengthDisp >= 50 ? "moderate" : "weak"
f_trendTxt(string dirTxt) =>
    regimeAge < 6 ? dirTxt + " · just started" : dirTxt + " · " + strengthWord + " (" + str.tostring(strengthDisp) + "%)"
 
// Trend Quality (0–100%)
trendQuality = f_clamp((adx / 40.0) * 50.0 + (ribbonSpreadAtr / 2.0) * 30.0 + (math.abs(slopeATR) / 0.15) * 20.0, 0.0, 100.0)
 
// Pillar A Scoring (0–100 Scale)
float pillarA_Bull = 0.0
float pillarA_Bear = 0.0
 
if regimeCode == 2 // Trend Up
    float baseTrend = 40.0 + (trendQuality * 0.25)
    float rDist = (close - m7) / math.max(atrVal, 1e-9)
    if rDist > 2.5 // Overextended penalty
        pillarA_Bull := baseTrend - 20.0
        pillarA_Bear := 15.0 // Mean-reversion pressure
    else if low <= m4 and close > m7 // Clean pullback test of ribbon
        pillarA_Bull := math.min(100.0, baseTrend + 30.0)
        pillarA_Bear := 0.0
    else
        pillarA_Bull := baseTrend
        pillarA_Bear := 0.0
else if regimeCode == -2 // Trend Down
    float baseTrend = 40.0 + (trendQuality * 0.25)
    float rDist = (m7 - close) / math.max(atrVal, 1e-9)
    if rDist > 2.5 // Overextended penalty
        pillarA_Bear := baseTrend - 20.0
        pillarA_Bull := 15.0 // Mean-reversion pressure
    else if high >= m4 and close < m7 // Clean pullback test of ribbon
        pillarA_Bear := math.min(100.0, baseTrend + 30.0)
        pillarA_Bull := 0.0
    else
        pillarA_Bear := baseTrend
        pillarA_Bull := 0.0
else if regimeCode == 1 // Ranging
    pillarA_Bull := (upSteps / 11.0) * 35.0
    pillarA_Bear := (dnSteps / 11.0) * 35.0
else // Volatile
    pillarA_Bull := 5.0
    pillarA_Bear := 5.0
 
pillarA_Bull := f_clamp(pillarA_Bull, 0.0, 100.0)
pillarA_Bear := f_clamp(pillarA_Bear, 0.0, 100.0)
 
// ═════════════════════════ PILLAR B: S/R CONFLUENCE STRUCTURE ═════════════════
 
pivLen = autoTunePivots ? f_autoPivLen() : pivotLenManual
ph = ta.pivothigh(high, pivLen, pvRight)
pl = ta.pivotlow(low, pivLen, pvRight)
pvPxHi = high[pvRight]
pvPxLo = low[pvRight]
pvBar  = bar_index - pvRight
 
volSma = ta.sma(volume, 20)
// Ⓥ needs a clear spike (2× average) so it stays rare, even on tick-volume feeds
isHighVol = not na(volume) and not na(volSma) and volSma > 0 and volume > volSma * 2.0
pvVolHi = isHighVol[pvRight]
pvRawVol = nz(volume[pvRight], 0.0)
 
// HTF alignment: previous closed HTF bar only ([1] with lookahead_on), so it does not repaint
htfPeriod = f_autoHtf()
f_htfPivots() =>
    hPh = ta.pivothigh(high, 5, 2)
    hPl = ta.pivotlow(low, 5, 2)
    hHi = ta.valuewhen(not na(hPh), high[2], 0)
    hLo = ta.valuewhen(not na(hPl), low[2], 0)
    [hHi[1], hLo[1]]
 
[htfHiRaw, htfLoRaw] = request.security(syminfo.tickerid, htfPeriod, f_htfPivots(), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_on)
 
// HTF trend: McGinley core (length 25) on the higher timeframe, previous closed HTF bar only
// 1 = up (close above the core), -1 = down (close below it), 0 = no data yet
f_htfTrend() =>
    var float md = close
    md := md + (close - md) / math.max(1.0, mcgK * 25.0 * math.pow(close / md, 4))
    int dir = close > md ? 1 : close < md ? -1 : 0
    dir[1]
 
htfTrendDir = nz(request.security(syminfo.tickerid, htfPeriod, f_htfTrend(), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_on), 0)
mtfPeriod   = f_autoMtf()
mtfTrendDir = nz(request.security(syminfo.tickerid, mtfPeriod, f_htfTrend(), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_on), 0)
 
f_tfLabel(string tf) =>
    int sec = timeframe.in_seconds(tf)
    sec >= 86400 ? tf : sec >= 3600 ? str.tostring(sec / 3600) + "h" : sec >= 60 ? str.tostring(sec / 60) + "m" : str.tostring(sec) + "s"
 
// Round numbers detector
f_isRoundNear(float px, float atrV) =>
    absPx = math.abs(px)
    if absPx <= 0.0 or na(absPx) or na(atrV) or atrV <= 0
        false
    else
        mag = math.floor(math.log10(absPx))
        b01 = math.pow(10, mag) / 10.0
        n1 = math.round(absPx / b01) * b01
        n2 = math.round(absPx / (b01 / 2.0)) * (b01 / 2.0)
        math.abs(absPx - n1) <= 0.15 * atrV or math.abs(absPx - n2) <= 0.15 * atrV
 
// Zone thickness bounds: Normalizes rectangular height to prevent hairlines or oversized blocks
f_zoneBounds(float rawTop, float rawBot, float aVal) =>
    float minH = math.max(minHeightAtr * aVal, clusterTolAtr * aVal * 0.70)
    float maxH = maxHeightAtr * aVal
    float top = rawTop
    float bot = rawBot
    float curH = top - bot
    if curH < minH
        float mid = (top + bot) / 2.0
        top := mid + minH / 2.0
        bot := mid - minH / 2.0
    else if curH > maxH
        float mid = (top + bot) / 2.0
        top := mid + maxH / 2.0
        bot := mid - maxH / 2.0
    [top, bot]
 
type SRZone
    box   bx
    line  lnMid
    label lb
    float top
    float bot
    int   dir             // 1 = Resistance, -1 = Support
    int   touches         // Confirmed distinct debounced reactions
    int   flips           // Number of role-reversals
    int   bornBar         // Pivot confirmation bar
    int   lastTouchBar    // Bar index of latest reaction
    int   invalBar        // Bar index where zone was broken (-1 if alive)
    float displacementAtr // Max impulse displacement away from zone (in ATR)
    float pocPx           // Volume-weighted point of control
    float maxVol          // Peak volume recorded at pivot or touch
    bool  hasVol          // Confirmed anomalous volume
    bool  isMitigated     // True if broken cleanly
    float qualityScore    // Intrinsic structural significance (0-100)
    float relevanceScore  // Proximity & context relevance
    bool  isActive        // Selected into <= 5 active visual set
    bool  isHistorical    // Retained as a historical context shelf
    float dispScore = 0.0 // Display-only strength (spread out, 100 is rare); signals use qualityScore
 
var array<SRZone> zones = array.new<SRZone>()
 
// Zone creation helper
f_addZone(int dir, float top0, float bot0, int bornBar, bool hasVol, float pocPx, float maxVol, float initDisp) =>
    safeBorn = f_safeLeft(bornBar)
    [bTop, bBot] = f_zoneBounds(top0, bot0, atrVal)
    right0 = f_safeRight(bar_index + 16)
    bx = box.new(safeBorn, bTop, right0, bBot, border_color = color.new(color.white, 100), bgcolor = color.new(color.white, 100), border_width = 1)
    lnMid = line.new(safeBorn, pocPx, right0, pocPx, color = color.new(color.white, 100), style = line.style_dotted, width = 1)
    tag = dir == 1 ? "RES · —" : "SUP · —"
    lb = label.new(right0, pocPx, tag, style = label.style_label_left, textcolor = color.new(color.white, 100), color = color.new(color.white, 100), size = size.tiny)
    array.push(zones, SRZone.new(bx, lnMid, lb, bTop, bBot, dir, 1, 0, bornBar, bar_index, -1, initDisp, pocPx, maxVol, hasVol, false, 50.0, 50.0, false, false))
 
// Merge overlapping or tightly clustered zones to eliminate duplicate levels
f_mergeZones() =>
    if array.size(zones) > 1
        for i = array.size(zones) - 1 to 1
            zi = array.get(zones, i)
            if not zi.isMitigated
                for j = i - 1 to 0
                    zj = array.get(zones, j)
                    if zj.dir == zi.dir and not zj.isMitigated
                        overlap = math.min(zi.top, zj.top) - math.max(zi.bot, zj.bot)
                        gap = math.max(zi.bot, zj.bot) - math.min(zi.top, zj.top)
                        if overlap > 0.0 or gap <= clusterTolAtr * atrVal
                            [nt, nb] = f_zoneBounds(math.max(zi.top, zj.top), math.min(zi.bot, zj.bot), atrVal)
                            zj.top := nt
                            zj.bot := nb
                            // Keep the larger count; merging is not a new reaction
                            zj.touches := math.max(zj.touches, zi.touches)
                            zj.displacementAtr := math.max(zj.displacementAtr, zi.displacementAtr)
                            zj.lastTouchBar := math.max(zi.lastTouchBar, zj.lastTouchBar)
                            zj.bornBar := math.min(zi.bornBar, zj.bornBar)
                            zj.hasVol := zj.hasVol or zi.hasVol
                            if zi.maxVol > zj.maxVol
                                zj.maxVol := zi.maxVol
                                zj.pocPx  := zi.pocPx
                            if not na(zi.bx)
                                box.delete(zi.bx)
                            if not na(zi.lnMid)
                                line.delete(zi.lnMid)
                            if not na(zi.lb)
                                label.delete(zi.lb)
                            array.remove(zones, i)
                            break
 
// Swing extremes since the pivot bar (computed every bar, used only when a pivot confirms)
float lowSincePv  = ta.lowest(low, pvRight)
float highSincePv = ta.highest(high, pvRight)
 
// Pivot Detection & Zone Creation (Only on confirmed bars to prevent repainting)
if not na(ph) and barstate.isconfirmed
    merged = false
    float initDisp = (pvPxHi - lowSincePv) / math.max(atrVal, 1e-9)
    if array.size(zones) > 0
        for i = 0 to array.size(zones) - 1
            z = array.get(zones, i)
            if z.dir == 1 and not z.isMitigated and pvPxHi >= z.bot - (0.35 * atrVal) and pvPxHi <= z.top + (clusterTolAtr * atrVal)
                [nt, nb] = f_zoneBounds(math.max(z.top, pvPxHi), z.bot, atrVal)
                z.top := nt
                z.bot := nb
                // Same swing already counted by the retest pass when it tapped the zone
                if pvBar - z.lastTouchBar >= 5
                    z.touches += 1
                    z.lastTouchBar := bar_index
                z.displacementAtr := math.max(z.displacementAtr, initDisp)
                if pvRawVol > z.maxVol
                    z.maxVol := pvRawVol
                    z.pocPx  := pvPxHi
                // Ⓥ only from the forming swing and its first two reactions
                if z.touches <= 3
                    z.hasVol := z.hasVol or pvVolHi
                merged := true
                break
    if not merged
        float hBody = math.max(open[pvRight], close[pvRight])
        float rawTop = pvPxHi
        float rawBot = math.min(pvPxHi - (minHeightAtr * atrVal), hBody)
        [topZ, botZ] = f_zoneBounds(rawTop, rawBot, atrVal)
        f_addZone(1, topZ, botZ, pvBar, pvVolHi, pvPxHi, math.max(pvRawVol, 0.0), initDisp)
 
if not na(pl) and barstate.isconfirmed
    merged = false
    float initDisp = (highSincePv - pvPxLo) / math.max(atrVal, 1e-9)
    if array.size(zones) > 0
        for i = 0 to array.size(zones) - 1
            z = array.get(zones, i)
            if z.dir == -1 and not z.isMitigated and pvPxLo <= z.top + (0.35 * atrVal) and pvPxLo >= z.bot - (clusterTolAtr * atrVal)
                [nt, nb] = f_zoneBounds(z.top, math.min(z.bot, pvPxLo), atrVal)
                z.top := nt
                z.bot := nb
                // Same swing already counted by the retest pass when it tapped the zone
                if pvBar - z.lastTouchBar >= 5
                    z.touches += 1
                    z.lastTouchBar := bar_index
                z.displacementAtr := math.max(z.displacementAtr, initDisp)
                if pvRawVol > z.maxVol
                    z.maxVol := pvRawVol
                    z.pocPx  := pvPxLo
                if z.touches <= 3
                    z.hasVol := z.hasVol or pvVolHi
                merged := true
                break
    if not merged
        float lBody = math.min(open[pvRight], close[pvRight])
        float rawBot = pvPxLo
        float rawTop = math.max(pvPxLo + (minHeightAtr * atrVal), lBody)
        [topZ, botZ] = f_zoneBounds(rawTop, rawBot, atrVal)
        f_addZone(-1, topZ, botZ, pvBar, pvVolHi, pvPxLo, math.max(pvRawVol, 0.0), initDisp)
 
// Continuous consolidation merge
if barstate.isconfirmed
    f_mergeZones()
 
// Retest & Invalidation Pass (Only confirmed bars)
if array.size(zones) > 0 and barstate.isconfirmed
    for i = array.size(zones) - 1 to 0
        z = array.get(zones, i)
        if not z.isMitigated
            bool isBroken = false
            if z.dir == 1 and close > z.top + (0.15 * atrVal)
                isBroken := true
            else if z.dir == -1 and close < z.bot - (0.15 * atrVal)
                isBroken := true
 
            if isBroken
                if flipOnBreak and z.flips == 0
                    // Role reversal: flip once
                    z.dir := z.dir == 1 ? -1 : 1
                    z.flips := 1
                    z.touches := 1
                    z.bornBar := bar_index
                    z.lastTouchBar := bar_index
                    z.displacementAtr := 0.5
                else
                    // Permanent mitigation
                    z.isMitigated := true
                    z.invalBar := bar_index
                    if not showBrokenZones
                        if not na(z.bx)
                            box.delete(z.bx)
                            z.bx := na
                        if not na(z.lnMid)
                            line.delete(z.lnMid)
                            z.lnMid := na
                        if not na(z.lb)
                            label.delete(z.lb)
                            z.lb := na
                        array.remove(zones, i)
                        continue
 
            // Distinct Reaction Debounce (requires >= 5 bars between touch events)
            if not z.isMitigated
                if bar_index - z.lastTouchBar >= 5
                    if z.dir == 1 and high >= z.bot and high <= z.top + (0.15 * atrVal) and close < z.top
                        z.touches += 1
                        z.lastTouchBar := bar_index
                        if z.touches <= 3 and isHighVol
                            z.hasVol := true
                    else if z.dir == -1 and low <= z.top and low >= z.bot - (0.15 * atrVal) and close > z.bot
                        z.touches += 1
                        z.lastTouchBar := bar_index
                        if z.touches <= 3 and isHighVol
                            z.hasVol := true
 
                // Dynamic Impulse Displacement Tracking
                if z.dir == 1
                    pushDn = (z.top - low) / math.max(atrVal, 1e-9)
                    if pushDn > z.displacementAtr
                        z.displacementAtr := pushDn
                else
                    pushUp = (high - z.bot) / math.max(atrVal, 1e-9)
                    if pushUp > z.displacementAtr
                        z.displacementAtr := pushUp
 
// ═════════════════════════ ZONE RANKING & STRICT VISIBLE SELECTION ═════════════════════════
// Hard Visual Ceiling: Never displays more than maxVisibleZones (default: 5, range: 3–5)
 
resCandidates = array.new<int>()
supCandidates = array.new<int>()
 
float distNearestRes  = 999.0
float distNearestSup  = 999.0
float nearestResScore = 0.0
float nearestSupScore = 0.0
float nearestResTop   = na
float nearestResBot   = na
float nearestSupTop   = na
float nearestSupBot   = na
 
if array.size(zones) > 0
    for i = 0 to array.size(zones) - 1
        zi = array.get(zones, i)
        zi.isActive := false
        zi.isHistorical := not zi.isMitigated
        if not zi.isMitigated
            midI = midlineMode == "Volume-Weighted Pivot Anchor" and not na(zi.pocPx) and zi.pocPx >= zi.bot and zi.pocPx <= zi.top ? zi.pocPx : (zi.top + zi.bot) / 2.0
            distI = (midI - close) / math.max(atrVal, 1e-9)
            absDist = math.abs(distI)
 
            htfLvl = zi.dir == 1 ? htfHiRaw : htfLoRaw
            alignedHtf = useHtfStruct and not na(htfLvl) and math.abs(midI - htfLvl) <= 0.5 * atrVal
            roundNear  = useRoundNum and f_isRoundNear(midI, atrVal)
 
            // Structural Quality Ranking
            float touchScore = math.min(zi.touches, 5) * 7.0
            float dispScore  = f_clamp(zi.displacementAtr / 2.0, 0.0, 1.0) * 20.0
            float htfScore   = alignedHtf ? 15.0 : 0.0
            float volScore   = zi.hasVol ? 15.0 : 0.0
            float roundScore = roundNear ? 10.0 : 0.0
 
            zi.qualityScore := f_clamp(45.0 + touchScore + dispScore + htfScore + volScore + roundScore, 20.0, 100.0)
 
            // Display strength: diminishing returns per factor so scores spread out and 100 stays rare
            float tShow = 30.0 * (1.0 - math.exp(-math.max(zi.touches - 1, 0) / 3.0))
            float dShow = f_clamp(zi.displacementAtr / 3.0, 0.0, 1.0) * 20.0
            zi.dispScore := math.round(f_clamp(20.0 + tShow + dShow + (alignedHtf ? 15.0 : 0.0) + (zi.hasVol ? 10.0 : 0.0) + (roundNear ? 5.0 : 0.0), 0.0, 100.0))
 
            // Proximity & Relevance
            float proxScore = math.max(0.0, (1.0 - (absDist / maxProximityAtr)) * 100.0)
            zi.relevanceScore := zi.qualityScore * 0.40 + proxScore * 0.60
 
            if absDist <= maxProximityAtr and zi.qualityScore >= float(minZoneScore)
                if zi.dir == 1 and midI >= close - (0.35 * atrVal)
                    array.push(resCandidates, i)
                    if absDist < distNearestRes
                        distNearestRes  := absDist
                        nearestResScore := zi.qualityScore
                        nearestResTop   := zi.top
                        nearestResBot   := zi.bot
                else if zi.dir == -1 and midI <= close + (0.35 * atrVal)
                    array.push(supCandidates, i)
                    if absDist < distNearestSup
                        distNearestSup  := absDist
                        nearestSupScore := zi.qualityScore
                        nearestSupTop   := zi.top
                        nearestSupBot   := zi.bot
 
// Sort candidates by relevance
if array.size(resCandidates) > 1
    for p = 0 to array.size(resCandidates) - 2
        for q = p + 1 to array.size(resCandidates) - 1
            idxP = array.get(resCandidates, p)
            idxQ = array.get(resCandidates, q)
            if array.get(zones, idxQ).relevanceScore > array.get(zones, idxP).relevanceScore
                array.set(resCandidates, p, idxQ)
                array.set(resCandidates, q, idxP)
 
if array.size(supCandidates) > 1
    for p = 0 to array.size(supCandidates) - 2
        for q = p + 1 to array.size(supCandidates) - 1
            idxP = array.get(supCandidates, p)
            idxQ = array.get(supCandidates, q)
            if array.get(zones, idxQ).relevanceScore > array.get(zones, idxP).relevanceScore
                array.set(supCandidates, p, idxQ)
                array.set(supCandidates, q, idxP)
 
// Strictly balance visible allocation: Maximum 4–5 zones total
int maxAllowed = math.max(3, math.min(5, maxVisibleZones))
int nResAvail = array.size(resCandidates)
int nSupAvail = array.size(supCandidates)
 
int resSlots = 0
int supSlots = 0
 
if nResAvail > 0 and nSupAvail > 0
    resSlots := 1
    supSlots := 1
    int remaining = maxAllowed - 2
    if remaining > 0
        for r = 1 to remaining
            bool canRes = resSlots < nResAvail
            bool canSup = supSlots < nSupAvail
            if canRes and canSup
                idxR = array.get(resCandidates, resSlots)
                idxS = array.get(supCandidates, supSlots)
                if array.get(zones, idxR).relevanceScore >= array.get(zones, idxS).relevanceScore
                    resSlots += 1
                else
                    supSlots += 1
            else if canRes
                resSlots += 1
            else if canSup
                supSlots += 1
            else
                break
else if nResAvail > 0
    resSlots := math.min(maxAllowed, nResAvail)
else if nSupAvail > 0
    supSlots := math.min(maxAllowed, nSupAvail)
 
// Mark top candidate zones as active
if resSlots > 0
    for k = 0 to resSlots - 1
        zRes = array.get(zones, array.get(resCandidates, k))
        zRes.isActive := true
        zRes.isHistorical := false
 
if supSlots > 0
    for k = 0 to supSlots - 1
        zSup = array.get(zones, array.get(supCandidates, k))
        zSup.isActive := true
        zSup.isHistorical := false
 
// Synchronize Drawing Objects
if array.size(zones) > 0
    for i = 0 to array.size(zones) - 1
        zi = array.get(zones, i)
        if not na(zi.bx)
            cSupport = supportColTheme == "AxeAlgo Gold" ? colorGold : colorBullAccent
            zc = zi.dir == 1 ? zoneResCol : cSupport
            safeBorn = f_safeLeft(zi.bornBar)
            int boxLeft = safeBorn
 
            if showZones and zi.isActive
                // LAYER 1: ACTIVE ZONE (Extends forward to bar_index + 12 with active badge)
                if zoneLookback > 0
                    boxLeft := f_safeLeft(math.max(zi.bornBar, zi.lastTouchBar - zoneLookback, bar_index - 3 * zoneLookback))
                int boxRight = f_safeRight(bar_index + 12)
 
                box.set_left(zi.bx, boxLeft)
                box.set_right(zi.bx, boxRight)
                box.set_top(zi.bx, zi.top)
                box.set_bottom(zi.bx, zi.bot)
 
                bool isPrimary = (zi.dir == 1 and not na(nearestResTop) and zi.top == nearestResTop) or (zi.dir == -1 and not na(nearestSupBot) and zi.bot == nearestSupBot)
                int fillTransp = isPrimary ? (100 - primaryFillOpacity) : (100 - secondaryFillOpacity)
                // Border weight follows zone strength (★ 80+, 60+, below 60)
                int bordW = zi.dispScore >= 80 ? 3 : zi.dispScore >= 60 ? 2 : 1
                int bordTransp = zi.dispScore >= 80 ? 15 : zi.dispScore >= 60 ? 40 : 65
                if isPrimary
                    bordTransp := math.max(0, bordTransp - 15)
 
                box.set_border_color(zi.bx, color.new(zc, bordTransp))
                box.set_bgcolor(zi.bx, color.new(zc, fillTransp))
                box.set_border_width(zi.bx, bordW)
                box.set_border_style(zi.bx, line.style_solid)
 
                midPx = midlineMode == "Volume-Weighted Pivot Anchor" and not na(zi.pocPx) and zi.pocPx >= zi.bot and zi.pocPx <= zi.top ? zi.pocPx : (zi.top + zi.bot) / 2.0
 
                if showMidlines
                    line.set_x1(zi.lnMid, boxLeft)
                    line.set_x2(zi.lnMid, boxRight)
                    line.set_y1(zi.lnMid, midPx)
                    line.set_y2(zi.lnMid, midPx)
                    line.set_color(zi.lnMid, color.new(zc, isPrimary ? 50 : 75))
                    line.set_style(zi.lnMid, line.style_dotted)
                else
                    line.set_color(zi.lnMid, color.new(color.white, 100))
 
                // Zone Labels
                if zoneLabelStyle != "Off"
                    label.set_x(zi.lb, boxRight)
                    label.set_y(zi.lb, midPx)
                    tag = zi.dir == 1 ? "RES" : "SUP"
                    crown = zi.dispScore >= 80 ? "★ " : ""
                    touchTxt = str.tostring(zi.touches) + "×"
                    boosters = (zi.hasVol ? " Ⓥ" : "")
                    string lblText = ""
                    if zoneLabelStyle == "Classic Badges (RES · 85)"
                        lblText := crown + tag + " " + str.tostring(int(zi.dispScore)) + " | " + touchTxt + boosters
                    else if zoneLabelStyle == "Compact (R · 85)"
                        lblText := crown + (zi.dir == 1 ? "R" : "S") + " " + str.tostring(int(zi.dispScore))
 
                    label.set_text(zi.lb, lblText)
                    badgeBg = zi.dir == 1 ? C_BADGE_RES : C_BADGE_SUP
                    badgeTxt = zi.dir == 1 ? (isPrimary ? C_BEAR_TXT : color.new(C_BEAR_TXT, 25)) : (isPrimary ? C_BULL_TXT : color.new(C_BULL_TXT, 25))
 
                    label.set_color(zi.lb, badgeBg)
                    label.set_textcolor(zi.lb, badgeTxt)
                    label.set_size(zi.lb, size.small)
                    label.set_style(zi.lb, label.style_label_left)
                    zTip = (zi.dir == 1 ? "RESISTANCE ZONE" : "SUPPORT ZONE") + "\n" +
                           "━━━━━━━━━━━━━━━━━━━━\n" +
                           "• Strength: " + str.tostring(int(zi.dispScore)) + " / 100" + (zi.dispScore >= 80 ? " (★ major)" : "") + "\n" +
                           "• Reactions: " + str.tostring(zi.touches) + "×\n" +
                           "• Span: " + str.tostring(zi.bot, format.mintick) + " – " + str.tostring(zi.top, format.mintick) + "\n" +
                           (zi.hasVol ? "• Ⓥ Formed or retested on high volume\n" : "") +
                           (zi.flips > 0 ? "• Flipped role once (broken " + (zi.dir == 1 ? "support" : "resistance") + ")\n" : "") +
                           "Broken zones flip role once on a confirmed close."
                    label.set_tooltip(zi.lb, zTip)
                else
                    label.set_text(zi.lb, "")
                    label.set_color(zi.lb, color.new(color.white, 100))
                    label.set_textcolor(zi.lb, color.new(color.white, 100))
 
            else if showZones and showHistoricalZones and zi.isHistorical and not zi.isMitigated
                // LAYER 2: HISTORICAL SHELF
                int shelfEnd = math.max(safeBorn + 4, zi.lastTouchBar + histWindowBars)
                int histRight = math.min(bar_index - 4, shelfEnd)
                histRight := math.max(safeBorn + 2, histRight)
                int boxRight = f_safeRight(histRight)
 
                box.set_left(zi.bx, boxLeft)
                box.set_right(zi.bx, boxRight)
                box.set_top(zi.bx, zi.top)
                box.set_bottom(zi.bx, zi.bot)
                box.set_border_color(zi.bx, color.new(zc, 75))
                box.set_bgcolor(zi.bx, color.new(zc, 100 - histFillOpacity))
                box.set_border_width(zi.bx, 1)
                box.set_border_style(zi.bx, line.style_solid)
 
                line.set_color(zi.lnMid, color.new(color.white, 100))
                label.set_text(zi.lb, "")
                label.set_color(zi.lb, color.new(color.white, 100))
                label.set_textcolor(zi.lb, color.new(color.white, 100))
 
            else if showZones and showBrokenZones and zi.isMitigated and zi.invalBar > 0
                // LAYER 3: INVALIDATED SHELF
                int boxRight = f_safeRight(math.max(safeBorn + 2, zi.invalBar))
 
                box.set_left(zi.bx, boxLeft)
                box.set_right(zi.bx, boxRight)
                box.set_top(zi.bx, zi.top)
                box.set_bottom(zi.bx, zi.bot)
                box.set_border_color(zi.bx, color.new(zc, 85))
                box.set_bgcolor(zi.bx, color.new(zc, 98))
                box.set_border_width(zi.bx, 1)
                box.set_border_style(zi.bx, line.style_dashed)
 
                line.set_color(zi.lnMid, color.new(color.white, 100))
                label.set_text(zi.lb, "")
                label.set_color(zi.lb, color.new(color.white, 100))
                label.set_textcolor(zi.lb, color.new(color.white, 100))
 
            else
                box.set_border_color(zi.bx, color.new(color.white, 100))
                box.set_bgcolor(zi.bx, color.new(color.white, 100))
                line.set_color(zi.lnMid, color.new(color.white, 100))
                label.set_text(zi.lb, "")
                label.set_color(zi.lb, color.new(color.white, 100))
                label.set_textcolor(zi.lb, color.new(color.white, 100))
 
// Memory & Object Budget Pruning: Strictly caps zones array to maxHistRetained (Default: 35)
while array.size(zones) > maxHistRetained
    int dropIdx = -1
    float minRel = 999999.0
    for idx = 0 to array.size(zones) - 1
        zCheck = array.get(zones, idx)
        if not zCheck.isActive
            if zCheck.relevanceScore < minRel
                minRel := zCheck.relevanceScore
                dropIdx := idx
    if dropIdx >= 0
        zOld = array.get(zones, dropIdx)
        if not na(zOld.bx)
            box.delete(zOld.bx)
        if not na(zOld.lnMid)
            line.delete(zOld.lnMid)
        if not na(zOld.lb)
            label.delete(zOld.lb)
        array.remove(zones, dropIdx)
    else
        zOld = array.shift(zones)
        if not na(zOld.bx)
            box.delete(zOld.bx)
        if not na(zOld.lnMid)
            line.delete(zOld.lnMid)
        if not na(zOld.lb)
            label.delete(zOld.lb)
 
// Confirmed Zone Rejections
candleRange = high - low
lowerWick   = math.min(open, close) - low
upperWick   = high - math.max(open, close)
 
bool probedSup = not na(nearestSupTop) and low <= nearestSupTop + (0.15 * atrVal) and low >= nearestSupBot - (0.50 * atrVal)
bool wickRejSup = candleRange > 0 and (lowerWick >= 0.35 * candleRange) and (close >= low + 0.45 * candleRange) and (close > nearestSupBot)
bool confirmedRejSup = probedSup and wickRejSup and barstate.isconfirmed
 
bool probedRes = not na(nearestResBot) and high >= nearestResBot - (0.15 * atrVal) and high <= nearestResTop + (0.50 * atrVal)
bool wickRejRes = candleRange > 0 and (upperWick >= 0.35 * candleRange) and (close <= high - 0.45 * candleRange) and (close < nearestResTop)
bool confirmedRejRes = probedRes and wickRejRes and barstate.isconfirmed
 
// Pillar B Structural Scoring
float pillarB_Bull = 0.0
float pillarB_Bear = 0.0
 
if distNearestSup <= 2.0
    float proxFactor = 1.0 - (distNearestSup / 2.0)
    pillarB_Bull += proxFactor * 25.0 + (nearestSupScore / 100.0) * 15.0
 
if distNearestRes <= 2.0
    float proxFactor = 1.0 - (distNearestRes / 2.0)
    pillarB_Bear += proxFactor * 25.0 + (nearestResScore / 100.0) * 15.0
 
// Reaction Confirmation Boost
if confirmedRejSup
    pillarB_Bull += 45.0
else if distNearestSup <= 1.0 and close > open
    pillarB_Bull += 15.0
 
if confirmedRejRes
    pillarB_Bear += 45.0
else if distNearestRes <= 1.0 and close < open
    pillarB_Bear += 15.0
 
// Opposing Barrier Penalty
if distNearestRes < 0.35
    pillarB_Bull := math.max(0.0, pillarB_Bull - 30.0)
if distNearestSup < 0.35
    pillarB_Bear := math.max(0.0, pillarB_Bear - 30.0)
 
pillarB_Bull := f_clamp(pillarB_Bull, 0.0, 100.0)
pillarB_Bear := f_clamp(pillarB_Bear, 0.0, 100.0)
 
// ═════════════════════════ PILLAR C: VOLUME PRESSURE ENGINE ═════════════════════════
 
bool isVolAvailable = not na(volume) and volume > 0
ltfRes = ltfResManual == "Auto" ? f_autoLtf() : ltfResManual
 
// Safe resolution check: verify requested LTF is strictly lower than chart resolution
int curSec = timeframe.in_seconds(timeframe.period)
int reqSec = timeframe.in_seconds(ltfRes)
bool canUseLtf = not na(curSec) and not na(reqSec) and curSec > 60 and reqSec < curSec
 
f_calcIntrabarDelta(string tf, string method) =>
    float d = 0.0
    if not na(volume) and volume > 0
        // One request returns all five intrabar series
        [oSub, hSub, lSub, cSub, vSub] = request.security_lower_tf(syminfo.tickerid, tf, [open, high, low, close, volume])
        int szC = not na(cSub) ? array.size(cSub) : 0
        int szO = not na(oSub) ? array.size(oSub) : 0
        int szH = not na(hSub) ? array.size(hSub) : 0
        int szL = not na(lSub) ? array.size(lSub) : 0
        int szV = not na(vSub) ? array.size(vSub) : 0
        int minLen = math.min(szC, math.min(szO, math.min(szH, math.min(szL, szV))))
        if minLen > 0
            for k = 0 to minLen - 1
                cK = array.get(cSub, k)
                oK = array.get(oSub, k)
                hK = array.get(hSub, k)
                lK = array.get(lSub, k)
                vK = nz(array.get(vSub, k), 0.0)
                rngK = hK - lK
                if method == "Range Position"
                    pos = rngK > 0 ? (cK - lK) / rngK : 0.5
                    d += vK * (pos * 2.0 - 1.0)
                else if method == "Bar Polarity"
                    prevC = k > 0 ? array.get(cSub, k - 1) : oK
                    d += cK >= prevC ? vK : -vK
                else
                    d += cK >= oK ? vK : -vK
        else
            // Robust fallback to single-bar proxy when lower-TF data is exhausted in history
            rng = high - low
            if method == "Range Position"
                pos = rng > 0 ? (close - low) / rng : 0.5
                d := volume * (pos * 2.0 - 1.0)
            else if method == "Bar Polarity"
                d := close >= nz(close[1], open) ? volume : -volume
            else
                d := close >= open ? volume : -volume
    d
 
f_calcBarOnlyDelta(string method) =>
    float d = 0.0
    if not na(volume) and volume > 0
        rng = high - low
        if method == "Range Position"
            pos = rng > 0 ? (close - low) / rng : 0.5
            d := volume * (pos * 2.0 - 1.0)
        else if method == "Bar Polarity"
            d := close >= nz(close[1], open) ? volume : -volume
        else
            d := close >= open ? volume : -volume
    d
 
float barDelta = 0.0
if not isVolAvailable
    barDelta := 0.0
else if engMode == "Bar only (lite)" or not canUseLtf
    barDelta := f_calcBarOnlyDelta(deltaMethod)
else
    barDelta := f_calcIntrabarDelta(ltfRes, deltaMethod)
 
// Cumulative Volume Delta (CVD)
bool resetCVD = switch cvdResetMode
    "Daily"  => timeframe.change("D")
    "Weekly" => timeframe.change("W")
    "Never"  => false
    => false
 
var float cvd = 0.0
cvd := (resetCVD ? 0.0 : nz(cvd[1])) + nz(barDelta)
cvdMA = ta.sma(cvd, 20)
cvdRising = cvd > nz(cvd[1])
cvdAboveMA = cvd > cvdMA
 
// Confirmed Absorption & CVD Divergence
deltaSma = ta.sma(math.abs(barDelta), 20)
isHighDelta = not na(barDelta) and not na(deltaSma) and deltaSma > 0 and math.abs(barDelta) > deltaSma * 1.5
isSmallBody = candleRange > 0 and math.abs(close - open) <= candleRange * 0.35
 
isBullAbs = useAbsorption and isHighDelta and barDelta > 0 and isSmallBody and barstate.isconfirmed
isBearAbs = useAbsorption and isHighDelta and barDelta < 0 and isSmallBody and barstate.isconfirmed
 
pivCvdHigh = ta.pivothigh(high, 5, 2)
pivCvdLow  = ta.pivotlow(low, 5, 2)
var float lastPivHighPx = na
var float lastPivHighCvd = na
var float lastPivLowPx = na
var float lastPivLowCvd = na
 
bool bearCvdDiv = false
bool bullCvdDiv = false
 
if barstate.isconfirmed
    if not na(pivCvdHigh)
        p = high[2]
        c = cvd[2]
        if detectDiv and not na(lastPivHighPx) and p > lastPivHighPx and c < lastPivHighCvd
            bearCvdDiv := true
        lastPivHighPx := p
        lastPivHighCvd := c
    if not na(pivCvdLow)
        p = low[2]
        c = cvd[2]
        if detectDiv and not na(lastPivLowPx) and p < lastPivLowPx and c > lastPivLowCvd
            bullCvdDiv := true
        lastPivLowPx := p
        lastPivLowCvd := c
 
// Pillar C Scoring (0–100 scale)
float pillarC_Bull = 0.0
float pillarC_Bear = 0.0
 
if not isVolAvailable
    pillarC_Bull := 0.0
    pillarC_Bear := 0.0
else
    float deltaRatio = deltaSma > 0 ? f_clamp(barDelta / deltaSma, -2.5, 2.5) : 0.0
    float deltaScore = (deltaRatio / 2.5) * 35.0
    if deltaScore > 0
        pillarC_Bull += deltaScore
    else
        pillarC_Bear += math.abs(deltaScore)
 
    // CVD Trend & 20-SMA Alignment
    if cvdAboveMA and cvdRising
        pillarC_Bull += 30.0
    else if not cvdAboveMA and not cvdRising
        pillarC_Bear += 30.0
    else
        pillarC_Bull += 12.0
        pillarC_Bear += 12.0
 
    // Confirmed Absorption & Divergence
    if isBullAbs or bullCvdDiv
        pillarC_Bull += 35.0
    if isBearAbs or bearCvdDiv
        pillarC_Bear += 35.0
 
pillarC_Bull := f_clamp(pillarC_Bull, 0.0, 100.0)
pillarC_Bear := f_clamp(pillarC_Bear, 0.0, 100.0)
 
// ═════════════════════════ CONFLUENCE SCORING ENGINE ═════════════════════════
 
float wA = float(wTrendBase)
float wB = float(wStructBase)
float wC = float(wFlowBase)
 
if not isVolAvailable
    wA := 50.0
    wB := 50.0
    wC := 0.0
 
totW = wA + wB + wC
rawBull = (pillarA_Bull * wA + pillarB_Bull * wB + pillarC_Bull * wC) / totW
rawBear = (pillarA_Bear * wA + pillarB_Bear * wB + pillarC_Bear * wC) / totW
 
int bullScore = int(math.round(f_clamp(rawBull, 0.0, 100.0)))
int bearScore = int(math.round(f_clamp(rawBear, 0.0, 100.0)))
 
// Overall Market Bias Synthesis
string marketBias = "NEUTRAL / BALANCED"
 
if regimeCode == -2 and bullScore >= 55 and confirmedRejSup
    marketBias := "COUNTER-TREND BOUNCE"
else if regimeCode == 2 and bearScore >= 55 and confirmedRejRes
    marketBias := "COUNTER-TREND PULLBACK"
else if bullScore >= strongThresh and bullScore > bearScore + 15
    marketBias := "STRONG BULLISH"
else if bearScore >= strongThresh and bearScore > bullScore + 15
    marketBias := "STRONG BEARISH"
else if bullScore >= moderateThresh and bullScore > bearScore + 8
    marketBias := "MODERATE BULLISH"
else if bearScore >= moderateThresh and bearScore > bullScore + 8
    marketBias := "MODERATE BEARISH"
else if regimeCode == 0
    marketBias := "VOLATILE / CHOPPY"
else if regimeCode == 1
    marketBias := "RANGING / BALANCED"
else
    marketBias := regimeCode == 2 ? "LEANING BULLISH" : "LEANING BEARISH"
 
// ═════════════════════════ PILLAR SYNTHESIS: BULLISH / BEARISH SETUP ENGINE ═════════════════════
 
// Directional Pullback & Retest Tracking State Machine
var int lastBullPullbackBar = -999
var int lastBearPullbackBar = -999
var bool bullRetestPending   = false
var bool bearRetestPending   = false
 
var int lastSignalBar        = -999
var int lastSignalDir        = 0 // 1 = Bullish, -1 = Bearish
var int consecutiveSameDir   = 0
 
// Bullish Retest Check: price retraces down into ribbon core (m4/m7) or near support (distNearestSup <= 1.3) while maintaining ribbon structure
bool isBullRetest = (low <= m4 or low <= m7 or (not na(distNearestSup) and distNearestSup <= 1.3)) and (close > m12 and low >= m12 - (0.40 * atrVal))
if isBullRetest and barstate.isconfirmed
    lastBullPullbackBar := bar_index
    if lastSignalDir == 1 and bar_index > lastSignalBar
        bullRetestPending := true
 
// Bearish Retest Check: price retraces up into ribbon core (m4/m7) or near resistance (distNearestRes <= 1.3) while maintaining ribbon structure
bool isBearRetest = (high >= m4 or high >= m7 or (not na(distNearestRes) and distNearestRes <= 1.3)) and (close < m12 and high <= m12 + (0.40 * atrVal))
if isBearRetest and barstate.isconfirmed
    lastBearPullbackBar := bar_index
    if lastSignalDir == -1 and bar_index > lastSignalBar
        bearRetestPending := true
 
// Regime Invalidation: If trend regime breaks, clear pending retest and reset consecutive counter
if regimeCode != 2 and lastSignalDir == 1 and barstate.isconfirmed
    bullRetestPending := false
    consecutiveSameDir := 0
if regimeCode != -2 and lastSignalDir == -1 and barstate.isconfirmed
    bearRetestPending := false
    consecutiveSameDir := 0
 
// Asymmetric Macro Trend Gate: Requires higher score if fighting macro slope
int reqScoreBull = enableAsymScore and slopeATR < 0 ? minSignalScore + asymMacroPenalty : minSignalScore
int reqScoreBear = enableAsymScore and slopeATR > 0 ? minSignalScore + asymMacroPenalty : minSignalScore
 
// Setups allowed per trend wave (Aggressive allows a second one after a fresh retest)
int effMaxConsecutive = waveDiscipline == "Dynamic Retest (Balanced)" ? 2 : 1
 
// Dynamic Retest Ribbon Distance Limits: Initial entry allowed up to maxRibbonDistAtr (2.2), but wave re-entries require tight retest (<= 1.45)
float effMaxDistBull = (waveDiscipline == "Dynamic Retest (Balanced)" and lastSignalDir == 1 and consecutiveSameDir >= 1) ? retestMaxDistAtr : maxRibbonDistAtr
float effMaxDistBear = (waveDiscipline == "Dynamic Retest (Balanced)" and lastSignalDir == -1 and consecutiveSameDir >= 1) ? retestMaxDistAtr : maxRibbonDistAtr
 
// Candle Body Momentum Discipline (Avoids Indecision Dojis & Enforces Real Commitment)
bool bullBodyOk  = candleRange > 0 and (close - open) >= (minBodyRatio * candleRange)
bool bearBodyOk  = candleRange > 0 and (open - close) >= (minBodyRatio * candleRange)
 
// ta.* series computed every bar at global scope (Pine v6 and/or short-circuit,
// so calls inside those chains would not run on every bar)
float low5           = ta.lowest(low, 5)
float high5          = ta.highest(high, 5)
bool  crossUpCore     = ta.crossover(close, m7)
bool  crossDnCore     = ta.crossunder(close, m7)
bool  bullReclaimCore = regimeCode[1] == -2 and crossUpCore
bool  bearLostCore    = regimeCode[1] == 2 and crossDnCore
 
// 1. Trend Continuation Conditions
bool pulledBackBull = (low5 <= m4 or low5 <= m7 or (not na(distNearestSup) and distNearestSup <= 1.6)) and (close > m12 and low >= m12 - (0.40 * atrVal))
bool bullTriggerResump = close > open and close > m3 and close > nz(close[1]) and (candleRange > 0 and (close >= low + 0.40 * candleRange)) and bullBodyOk
float ribbonDistBull = (close - m7) / math.max(atrVal, 1e-9)
bool notOverextendedBull = ribbonDistBull <= effMaxDistBull
 
bool htfAllowsBull = not htfContFilter or htfTrendDir == 1
bool htfAllowsBear = not htfContFilter or htfTrendDir == -1
 
bool bullContCore = (regimeCode == 2) and (upSteps >= 7) and not chopSuppressed and pulledBackBull and bullTriggerResump and notOverextendedBull and (bullScore >= reqScoreBull) and (bullScore > bearScore + scoreDiff) and (barDelta >= -deltaSma * 0.8)
 
bool pulledBackBear = (high5 >= m4 or high5 >= m7 or (not na(distNearestRes) and distNearestRes <= 1.6)) and (close < m12 and high <= m12 + (0.40 * atrVal))
bool bearTriggerResump = close < open and close < m3 and close < nz(close[1]) and (candleRange > 0 and (close <= high - 0.40 * candleRange)) and bearBodyOk
float ribbonDistBear = (m7 - close) / math.max(atrVal, 1e-9)
bool notOverextendedBear = ribbonDistBear <= effMaxDistBear
 
// Note: Bear continuation allows dnSteps >= 6 to capture steep downside impulses before move exhausts
bool bearContCore = (regimeCode == -2) and (dnSteps >= 6) and not chopSuppressed and pulledBackBear and bearTriggerResump and notOverextendedBear and (bearScore >= reqScoreBear) and (bearScore > bullScore + scoreDiff) and (barDelta <= deltaSma * 0.8)
 
bool bullContinuation = bullContCore and htfAllowsBull
bool bearContinuation = bearContCore and htfAllowsBear
 
// 2. Structural Reversal Conditions
bool bullStructRej = confirmedRejSup or (not na(distNearestSup) and distNearestSup <= 1.5 and close > open and (close - low) >= 0.50 * candleRange) or (bullCvdDiv and isBullAbs and not na(distNearestSup) and distNearestSup <= 2.5) or (bullReclaimCore and bullScore >= strongThresh)
bool bullReversalTrigger = close > open and close > m4 and close > high[1] and bullBodyOk
bool bullReversalAllowed = not enableStrictReversal or (regimeCode != -2) or (confirmedRejSup and bullScore >= math.max(minSignalScore, strongThresh - 5))
bool bullReversal = bullStructRej and bullReversalTrigger and bullReversalAllowed and (bullScore >= reqScoreBull) and (bullScore > bearScore + scoreDiff)
 
bool bearStructRej = confirmedRejRes or (not na(distNearestRes) and distNearestRes <= 1.5 and close < open and (high - close) >= 0.50 * candleRange) or (bearCvdDiv and isBearAbs and not na(distNearestRes) and distNearestRes <= 2.5) or (bearLostCore and bearScore >= strongThresh)
bool bearReversalTrigger = close < open and close < m4 and close < low[1] and bearBodyOk
bool bearReversalAllowed = not enableStrictReversal or (regimeCode != 2) or (confirmedRejRes and bearScore >= math.max(minSignalScore, strongThresh - 5))
bool bearReversal = bearStructRej and bearReversalTrigger and bearReversalAllowed and (bearScore >= reqScoreBear) and (bearScore > bullScore + scoreDiff)
 
// 3. High-Confluence Momentum Surges (Distinct behavior for "All High-Confluence")
bool bullSurge = (bullScore >= strongThresh) and (bullScore > bearScore + scoreDiff) and notOverextendedBull and (barDelta >= -deltaSma * 0.5) and close > open and close > nz(close[1]) and (close > m3 or close > m7) and bullBodyOk
bool bearSurge = (bearScore >= strongThresh) and (bearScore > bullScore + scoreDiff) and notOverextendedBear and (barDelta <= deltaSma * 0.5) and close < open and close < nz(close[1]) and (close < m3 or close < m7) and bearBodyOk
 
// Reversals stay off on 1h+ charts unless enabled
bool revTfOk = htfReversals or nz(timeframe.in_seconds(timeframe.period), 0) < 3600
bullReversal := bullReversal and revTfOk
bearReversal := bearReversal and revTfOk
 
// 4. Signal Mode Selection & Cancellation of Conflicting Evidence
bool rawBullSig = false
bool rawBearSig = false
 
if signalMode == "Trend Continuation Only"
    rawBullSig := bullContinuation
    rawBearSig := bearContinuation
else if signalMode == "Strong Reversals Only"
    rawBullSig := bullReversal
    rawBearSig := bearReversal
else if signalMode == "All High-Confluence"
    rawBullSig := bullContinuation or bullReversal or bullSurge
    rawBearSig := bearContinuation or bearReversal or bearSurge
else // "Balanced (Continuation + Confirmed Reversals)" (Recommended Default)
    rawBullSig := bullContinuation or bullReversal
    rawBearSig := bearContinuation or bearReversal
 
// Conflicting signals on the exact same candle are mutually cancelled
if rawBullSig and rawBearSig
    rawBullSig := false
    rawBearSig := false
 
// 5. Non-Repainting State Machine, Cooldown & Wave Throttling
bool validBullSignal = false
bool validBearSignal = false
 
if barstate.isconfirmed
    if rawBullSig
        bool canFire = false
        if lastSignalDir == 1 and consecutiveSameDir >= 1
            // Secondary entry on same wave requires:
            // 1. Minimum cooldown spacing
            // 2. Wave capacity available
            // 3. A fresh, relevant bullish retest occurred strictly AFTER the prior signal
            bool freshRetestOccurred = bullRetestPending and (lastBullPullbackBar > lastSignalBar)
            canFire := (bar_index - lastSignalBar >= signalCooldown) and (consecutiveSameDir < effMaxConsecutive) and freshRetestOccurred
        else
            // Fresh wave entry or transition from bearish/neutral
            canFire := true
 
        if canFire
            validBullSignal := true
            consecutiveSameDir := (lastSignalDir == 1) ? consecutiveSameDir + 1 : 1
            lastSignalBar := bar_index
            lastSignalDir := 1
            bullRetestPending := false // Consumed! Cannot qualify another entry without a brand new retest
            bearRetestPending := false
 
    else if rawBearSig
        bool canFire = false
        if lastSignalDir == -1 and consecutiveSameDir >= 1
            // Secondary entry on same wave requires:
            // 1. Minimum cooldown spacing
            // 2. Wave capacity available
            // 3. A fresh, relevant bearish retest occurred strictly AFTER the prior signal
            bool freshRetestOccurred = bearRetestPending and (lastBearPullbackBar > lastSignalBar)
            canFire := (bar_index - lastSignalBar >= signalCooldown) and (consecutiveSameDir < effMaxConsecutive) and freshRetestOccurred
        else
            // Fresh wave entry or transition from bullish/neutral
            canFire := true
 
        if canFire
            validBearSignal := true
            consecutiveSameDir := (lastSignalDir == -1) ? consecutiveSameDir + 1 : 1
            lastSignalBar := bar_index
            lastSignalDir := -1
            bearRetestPending := false // Consumed! Cannot qualify another entry without a brand new retest
            bullRetestPending := false
 
// ═════════════════════════ VISUAL RENDERING: McGINLEY RIBBON ═════════════════════
 
bool isRibbonOn       = ribbonStyle != "Off"
bool isRibbonClassic  = ribbonStyle == "Classic (12-Band Layered)"
bool isRibbonStandard = ribbonStyle == "Standard (6-Band)"
 
// Ribbon palette per regime (AxeAlgo brand colours)
color cFast     = color.white
color cCore     = color.white
color cBase     = color.white
color cFillBase = color.white
 
if regimeCode == 2 // Bullish Trend (AxeAlgo Royal Gold Gradient)
    cFast     := #FFE082 // Light Amber Gold
    cCore     := colorGold // AxeAlgo Royal Gold (#D4AF37)
    cBase     := #7A5E14 // Deep Warm Bronze
    cFillBase := colorGold
else if regimeCode == -2 // Bearish Trend (Crimson-Rose Silk Gradient)
    cFast     := #FF8597 // Soft Coral Rose
    cCore     := colorCrimson // AxeAlgo Crimson (#DC143C)
    cBase     := #7A1526 // Deep Wine Burgundy
    cFillBase := colorCrimson
else if regimeCode == 0 // Volatile Chop
    cFast     := #D1C4E9
    cCore     := colorVol
    cBase     := #3E1F5E
    cFillBase := colorVol
else // Ranging (slate blue)
    cFast     := #B7C3E0
    cCore     := #8A9BC4
    cBase     := #4B5A85
    cFillBase := #8A9BC4
 
// Line Opacities
color col1  = isRibbonOn ? color.new(cFast, isRibbonClassic ? 35 : 40) : na
color col2  = isRibbonOn and isRibbonClassic ? color.new(cFast, 60) : na
color col3  = isRibbonOn and (isRibbonClassic or isRibbonStandard) ? color.new(cFast, 65) : na
color col4  = isRibbonOn and isRibbonClassic ? color.new(cFast, 70) : na
color col5  = isRibbonOn and (isRibbonClassic or isRibbonStandard) ? color.new(cCore, 65) : na
color col6  = isRibbonOn and isRibbonClassic ? color.new(cCore, 60) : na
color col7  = isRibbonOn ? color.new(cCore, 25) : na // Core Driver Band (Length 25)
color col8  = isRibbonOn and isRibbonClassic ? color.new(cBase, 60) : na
color col9  = isRibbonOn and (isRibbonClassic or isRibbonStandard) ? color.new(cBase, 65) : na
color col10 = isRibbonOn and isRibbonClassic ? color.new(cBase, 70) : na
color col11 = isRibbonOn and (isRibbonClassic or isRibbonStandard) ? color.new(cBase, 70) : na
color col12 = isRibbonOn ? color.new(cBase, isRibbonClassic ? 45 : 55) : na
 
// 12 McGinley Dynamic Line Plots
p1  = plot(isRibbonOn ? m1 : na, "MD 1 (Fast 8)", color = col1, linewidth = 1, display = display.pane + display.data_window)
p2  = plot(isRibbonOn and isRibbonClassic ? m2 : na, "MD 2 (10)", color = col2, linewidth = 1, display = display.pane + display.data_window)
p3  = plot(isRibbonOn and (isRibbonClassic or isRibbonStandard) ? m3 : na, "MD 3 (12)", color = col3, linewidth = 1, display = display.pane + display.data_window)
p4  = plot(isRibbonOn and isRibbonClassic ? m4 : na, "MD 4 (15)", color = col4, linewidth = 1, display = display.pane + display.data_window)
p5  = plot(isRibbonOn and (isRibbonClassic or isRibbonStandard) ? m5 : na, "MD 5 (18)", color = col5, linewidth = 1, display = display.pane + display.data_window)
p6  = plot(isRibbonOn and isRibbonClassic ? m6 : na, "MD 6 (21)", color = col6, linewidth = 1, display = display.pane + display.data_window)
p7  = plot(isRibbonOn ? m7 : na, "MD 7 (Core Driver 25)", color = col7, linewidth = 1, display = display.all)
p8  = plot(isRibbonOn and isRibbonClassic ? m8 : na, "MD 8 (29)", color = col8, linewidth = 1, display = display.pane + display.data_window)
p9  = plot(isRibbonOn and (isRibbonClassic or isRibbonStandard) ? m9 : na, "MD 9 (34)", color = col9, linewidth = 1, display = display.pane + display.data_window)
p10 = plot(isRibbonOn and isRibbonClassic ? m10 : na, "MD 10 (39)", color = col10, linewidth = 1, display = display.pane + display.data_window)
p11 = plot(isRibbonOn and (isRibbonClassic or isRibbonStandard) ? m11 : na, "MD 11 (45)", color = col11, linewidth = 1, display = display.pane + display.data_window)
p12 = plot(isRibbonOn ? m12 : na, "MD 12 (Base 52)", color = col12, linewidth = 1, display = display.pane + display.data_window)
 
// 11 inter-band ribbon fills
int tFill = isRibbonClassic ? (100 - ribbonCloudOpac) : 92
color fc1  = isRibbonOn and ribbonCloud ? color.new(cFillBase, tFill) : color.new(color.white, 100)
color fc2  = isRibbonOn and ribbonCloud ? color.new(cFillBase, math.min(100, tFill + 1)) : color.new(color.white, 100)
color fc3  = isRibbonOn and ribbonCloud ? color.new(cFillBase, math.min(100, tFill + 2)) : color.new(color.white, 100)
color fc4  = isRibbonOn and ribbonCloud ? color.new(cFillBase, math.min(100, tFill + 3)) : color.new(color.white, 100)
color fc5  = isRibbonOn and ribbonCloud ? color.new(cFillBase, math.min(100, tFill + 4)) : color.new(color.white, 100)
color fc6  = isRibbonOn and ribbonCloud ? color.new(cFillBase, math.min(100, tFill + 5)) : color.new(color.white, 100)
color fc7  = isRibbonOn and ribbonCloud ? color.new(cFillBase, math.min(100, tFill + 6)) : color.new(color.white, 100)
color fc8  = isRibbonOn and ribbonCloud ? color.new(cFillBase, math.min(100, tFill + 7)) : color.new(color.white, 100)
color fc9  = isRibbonOn and ribbonCloud ? color.new(cFillBase, math.min(100, tFill + 8)) : color.new(color.white, 100)
color fc10 = isRibbonOn and ribbonCloud ? color.new(cFillBase, math.min(100, tFill + 9)) : color.new(color.white, 100)
color fc11 = isRibbonOn and ribbonCloud ? color.new(cFillBase, math.min(100, tFill + 10)) : color.new(color.white, 100)
 
fill(p1, p2, color = fc1, title = "Ribbon Layer 1-2")
fill(p2, p3, color = fc2, title = "Ribbon Layer 2-3")
fill(p3, p4, color = fc3, title = "Ribbon Layer 3-4")
fill(p4, p5, color = fc4, title = "Ribbon Layer 4-5")
fill(p5, p6, color = fc5, title = "Ribbon Layer 5-6")
fill(p6, p7, color = fc6, title = "Ribbon Layer 6-7")
fill(p7, p8, color = fc7, title = "Ribbon Layer 7-8")
fill(p8, p9, color = fc8, title = "Ribbon Layer 8-9")
fill(p9, p10, color = fc9, title = "Ribbon Layer 9-10")
fill(p10, p11, color = fc10, title = "Ribbon Layer 10-11")
fill(p11, p12, color = fc11, title = "Ribbon Layer 11-12")
 
// ───────── AXEALGO BULLISH / BEARISH SETUPS ─────────
// Symbol only on the chart; hover it for the reasons. Drawn on confirmed bars only.
var array<label> sigLabels = array.new<label>()
 
f_pressureTxt() =>
    not isVolAvailable ? "no volume data" : cvdAboveMA and cvdRising ? "buyers leading" : not cvdAboveMA and not cvdRising ? "sellers leading" : "mixed"
 
f_regimeTxt() =>
    regimeCode == 2 ? f_trendTxt("Trend up") : regimeCode == -2 ? f_trendTxt("Trend down") : regimeCode == 0 ? "Volatile / choppy market" : "Ranging market"
 
f_lvlTxt(float px, float dist) =>
    not na(px) and dist < 900 ? str.tostring(px, format.mintick) + " (" + str.tostring(dist, "#.#") + " ATR)" : "none nearby"
 
string htfTrendTxt = htfTrendDir == 1 ? "up" : htfTrendDir == -1 ? "down" : "n/a"
// Setup is invalid beyond the recent swing (5 bars incl. the signal bar)
float invLow  = low5
float invHigh = high5
 
// Signal tracking: the latest signal stays "active" until price closes beyond its
// invalidation level, the trend flips against it, or it ages out
var int    lsDir    = 0
var int    lsBar    = na
var float  lsPx     = na
var float  lsInv    = na
var string lsType   = ""
var string lsStatus = ""
var float  lsTgt    = na // Next opposing zone edge when the setup appeared
 
if lsDir != 0 and lsStatus == "Active" and barstate.isconfirmed and bar_index > lsBar
    string endWhy = ""
    if lsDir == 1 and close < lsInv
        endWhy := "Invalidated: closed below " + str.tostring(lsInv, format.mintick)
        lsStatus := "Invalidated"
    else if lsDir == -1 and close > lsInv
        endWhy := "Invalidated: closed above " + str.tostring(lsInv, format.mintick)
        lsStatus := "Invalidated"
    else if (lsDir == 1 and regimeCode == -2) or (lsDir == -1 and regimeCode == 2)
        endWhy := "Trend flipped " + (lsDir == 1 ? "down" : "up")
        lsStatus := "Trend flipped"
    else if bar_index - lsBar >= signalLifeBars
        lsStatus := "Expired"
    if endWhy != ""
        string endTip = (lsDir == 1 ? "Bullish setup" : "Bearish setup") + " from " + str.tostring(lsPx, format.mintick) + " (" + str.tostring(bar_index - lsBar) + " bars ago)\n" + endWhy
        alert(syminfo.ticker + " · " + f_tfLabel(timeframe.period) + " · Trend Zone Flow\n" + endTip, alert.freq_once_per_bar_close)
 
if validBullSignal or validBearSignal
    bool isL = validBullSignal
    string typeTxt = isL ? (bullContinuation ? "Trend continuation" : bullReversal ? "Reversal off support" : "Momentum surge") : (bearContinuation ? "Trend continuation" : bearReversal ? "Reversal off resistance" : "Momentum surge")
    string why = ""
    if isL
        if bullContinuation
            why := "• Pulled back into the ribbon" + (distNearestSup <= 1.6 ? " / near support" : "") + " and held\n• Resumed up with a strong bullish close\n"
        else if bullReversal
            why := (confirmedRejSup ? "• Wick rejection off support\n" : bullCvdDiv and isBullAbs ? "• Bullish divergence with absorption near support\n" : bullReclaimCore ? "• Reclaimed the ribbon core after a downtrend\n" : "• Bullish reaction near support\n") + "• Closed above the previous candle's high\n"
        else
            why := "• Strong bullish confluence with momentum\n• Closed higher with a strong body\n"
    else
        if bearContinuation
            why := "• Pulled back into the ribbon" + (distNearestRes <= 1.6 ? " / near resistance" : "") + " and rejected\n• Resumed down with a strong bearish close\n"
        else if bearReversal
            why := (confirmedRejRes ? "• Wick rejection off resistance\n" : bearCvdDiv and isBearAbs ? "• Bearish divergence with absorption near resistance\n" : bearLostCore ? "• Lost the ribbon core after an uptrend\n" : "• Bearish reaction near resistance\n") + "• Closed below the previous candle's low\n"
        else
            why := "• Strong bearish confluence with momentum\n• Closed lower with a strong body\n"
    int net = bullScore - bearScore
    string tip = (isL ? "▲ BULLISH SETUP · " : "▼ BEARISH SETUP · ") + typeTxt + "\n" +
         "━━━━━━━━━━━━━━━━━━━━\n" +
         "• " + f_regimeTxt() + "\n" +
         why +
         "• " + f_tfLabel(htfPeriod) + " trend: " + htfTrendTxt + "\n" +
         "• Volume pressure (est.): " + f_pressureTxt() + "\n" +
         "• Confluence: " + (net > 0 ? "+" : "") + str.tostring(net) + " (bull " + str.tostring(bullScore) + " / bear " + str.tostring(bearScore) + ")\n" +
         "━━━━━━━━━━━━━━━━━━━━\n" +
         "Close: " + str.tostring(close, format.mintick) + "\n" +
         (isL ? "Invalid below: " + str.tostring(invLow, format.mintick) + " (recent swing low)" : "Invalid above: " + str.tostring(invHigh, format.mintick) + " (recent swing high)") + "\n" +
         (isL ? "Next resistance: " + f_lvlTxt(nearestResBot, distNearestRes) : "Next support: " + f_lvlTxt(nearestSupTop, distNearestSup)) + "\n" +
         "Confirmed on bar close. Analytical context, not trade advice."
    lsDir    := isL ? 1 : -1
    lsBar    := bar_index
    lsPx     := close
    lsInv    := isL ? invLow : invHigh
    lsType   := typeTxt
    lsStatus := "Active"
    lsTgt    := isL ? (distNearestRes < 900 ? nearestResBot : na) : (distNearestSup < 900 ? nearestSupTop : na)
    // Alert with the same reasons (create an alert with "Any alert() function call")
    alert(syminfo.ticker + " · " + f_tfLabel(timeframe.period) + " · Trend Zone Flow\n" + tip, alert.freq_once_per_bar_close)
 
    bool asBadge = signalStyle == "Badge (▲ ▼)"
    string sym = signalStyle == "Diamond (◆)" ? "◆" : (isL ? "▲" : "▼")
    // Badge text runs one size below the plain symbol so the tag stays compact
    sz = asBadge ? (signalSize == "Small" ? size.tiny : signalSize == "Large" ? size.normal : size.small) : (signalSize == "Small" ? size.normal : signalSize == "Large" ? size.huge : size.large)
    sigCol = isL ? colorGold : colorCrimson
    lStyle = asBadge ? (isL ? label.style_label_up : label.style_label_down) : label.style_none
    if showSignals
        lb = label.new(bar_index, isL ? low : high, sym, xloc = xloc.bar_index, yloc = isL ? yloc.belowbar : yloc.abovebar, style = lStyle, color = asBadge ? sigCol : color.new(color.white, 100), textcolor = asBadge ? (isL ? #14110B : #F5F5F5) : sigCol, size = sz, tooltip = tip)
        array.push(sigLabels, lb)
        // Keep the label budget for S/R zone badges
        if array.size(sigLabels) > 300
            label.delete(array.shift(sigLabels))
 
// Active setup levels (optional): one invalidation line and one next-zone line, removed when the setup ends
var int   lvlBar   = na
var line  lvlInvLn = na
var line  lvlTgtLn = na
var label lvlInvLb = na
var label lvlTgtLb = na
 
bool lvlLive = showSetupLevels and lsDir != 0 and lsStatus == "Active"
if not na(lvlBar) and (not lvlLive or lvlBar != lsBar)
    line.delete(lvlInvLn)
    line.delete(lvlTgtLn)
    label.delete(lvlInvLb)
    label.delete(lvlTgtLb)
    lvlInvLn := na
    lvlTgtLn := na
    lvlInvLb := na
    lvlTgtLb := na
    lvlBar   := na
 
if lvlLive
    int lvlRight = bar_index + 8
    color tgtCol = lsDir == 1 ? colorGold : colorCrimson
    if na(lvlBar)
        lvlBar   := lsBar
        lvlInvLn := line.new(lsBar, lsInv, lvlRight, lsInv, color = color.new(C_TEXT_MUTE, 20), style = line.style_dotted, width = 1)
        lvlInvLb := label.new(lvlRight, lsInv, "Invalid " + str.tostring(lsInv, format.mintick), style = label.style_label_left, color = color.new(color.white, 100), textcolor = C_TEXT_MUTE, size = size.tiny)
        if not na(lsTgt)
            lvlTgtLn := line.new(lsBar, lsTgt, lvlRight, lsTgt, color = color.new(tgtCol, 30), style = line.style_dashed, width = 1)
            lvlTgtLb := label.new(lvlRight, lsTgt, "Next zone " + str.tostring(lsTgt, format.mintick), style = label.style_label_left, color = color.new(color.white, 100), textcolor = tgtCol, size = size.tiny)
    else
        line.set_x2(lvlInvLn, lvlRight)
        label.set_x(lvlInvLb, lvlRight)
        if not na(lvlTgtLn)
            line.set_x2(lvlTgtLn, lvlRight)
            label.set_x(lvlTgtLb, lvlRight)
 
// Micro Markers for Confirmed Order Flow Events
plotshape(showMarkers and isBullAbs, title = "Bullish Absorption Dot", style = shape.circle, location = location.belowbar, color = colorBullAccent, size = size.tiny)
plotshape(showMarkers and isBearAbs, title = "Bearish Absorption Dot", style = shape.circle, location = location.abovebar, color = colorCrimson, size = size.tiny)
 
// ═════════════════════════ VISUAL RENDERING: DASHBOARD HUD ═════════════════════
 
var table hud = table.new(f_tablePos(hudPos), 2, 10, bgcolor = C_BG_DEEP, border_color = C_BORDER_MUTE, border_width = 1, frame_color = C_FRAME, frame_width = 1)
 
// What the engine is waiting for (plain-language, no thresholds)
f_setupTxt() =>
    string tfH = f_tfLabel(htfPeriod)
    bool revOn = signalMode != "Trend Continuation Only" and revTfOk
    string t = ""
    if regimeCode == 0
        t := "Volatile · standing aside"
    else if regimeCode == 1
        t := revOn ? "Ranging · watching zones for reversals" : "Ranging · no continuation setup"
    else if regimeCode == 2
        if signalMode == "Strong Reversals Only"
            t := "Trend up · reversal mode, watching resistance"
        else if htfContFilter and htfTrendDir == -1
            t := "Trend up · paused, " + tfH + " trend is down"
        else if chopSuppressed
            t := "Trend up · choppy, waiting to settle"
        else if lastSignalDir == 1 and consecutiveSameDir >= effMaxConsecutive
            t := "Trend up · setup already shown this wave"
        else if not notOverextendedBull
            t := "Trend up · extended, waiting for pullback"
        else if pulledBackBull
            t := "Pullback in place · waiting for bullish close"
        else
            t := "Trend up · waiting for pullback"
    else
        if signalMode == "Strong Reversals Only"
            t := "Trend down · reversal mode, watching support"
        else if htfContFilter and htfTrendDir == 1
            t := "Trend down · paused, " + tfH + " trend is up"
        else if chopSuppressed
            t := "Trend down · choppy, waiting to settle"
        else if lastSignalDir == -1 and consecutiveSameDir >= effMaxConsecutive
            t := "Trend down · setup already shown this wave"
        else if not notOverextendedBear
            t := "Trend down · extended, waiting for pullback"
        else if pulledBackBear
            t := "Pullback in place · waiting for bearish close"
        else
            t := "Trend down · waiting for pullback"
    t
 
f_arrow(int d) =>
    d == 1 ? "▲" : d == -1 ? "▼" : "–"
 
if barstate.islast
    if showHud
        tSize = f_tableSize(hudSize)
        bool isClassicHud = hudDensity == "Classic Structured"
 
        // Header Row
        table.cell(hud, 0, 0, "◆ TREND ZONE FLOW", text_color = C_TITLE, text_size = tSize, text_halign = text.align_left, tooltip = "Trend (McGinley ribbon), structure (S/R zones) and estimated volume pressure combined into one market read. Hover a setup marker on the chart to see why it appeared.")
        table.cell(hud, 1, 0, syminfo.ticker + " · " + f_tfLabel(timeframe.period), text_color = C_TEXT_BRT, text_size = tSize, text_halign = text.align_right)
 
        // Trend on three timeframes (chart · middle · higher), closed bars only for the two higher ones
        int chartDir = close > m7 ? 1 : close < m7 ? -1 : 0
        int agreeSum = chartDir + mtfTrendDir + htfTrendDir
 
        // Row 1: Market Regime (a range with all timeframes on one side shows its lean)
        string rangeLean = agreeSum == 3 ? " · leaning up" : agreeSum == -3 ? " · leaning down" : ""
        regimeTxt = regimeCode == 2 ? f_trendTxt("TREND UP") : regimeCode == -2 ? f_trendTxt("TREND DOWN") : regimeCode == 0 ? "VOLATILE / CHOPPY" : "RANGING" + rangeLean + " (ADX " + str.tostring(int(adx)) + ")"
        regimeCol = regimeCode == 2 ? C_BULL_TXT : regimeCode == -2 ? C_BEAR_TXT : regimeCode == 0 ? #9575CD : #6B7FB0
        table.cell(hud, 0, 1, "Market Regime", text_color = C_TEXT_MUTE, text_size = tSize, text_halign = text.align_left, tooltip = "Trend needs an ordered, expanding ribbon and ADX above the threshold. A range can still lean one way when price sits on the same side of the core on all three timeframes.")
        table.cell(hud, 1, 1, regimeTxt, text_color = regimeCol, text_size = tSize, text_halign = text.align_right)
 
        // Row 2: Trend Alignment
        color alignCol = agreeSum == 3 ? C_BULL_TXT : agreeSum == -3 ? C_BEAR_TXT : C_TEXT_BRT
        string alignTxt = f_tfLabel(timeframe.period) + " " + f_arrow(chartDir) + "   " + f_tfLabel(mtfPeriod) + " " + f_arrow(mtfTrendDir) + "   " + f_tfLabel(htfPeriod) + " " + f_arrow(htfTrendDir) + (math.abs(agreeSum) == 3 ? "  · aligned" : "  · mixed")
        table.cell(hud, 0, 2, "Trend Alignment", text_color = C_TEXT_MUTE, text_size = tSize, text_halign = text.align_left, tooltip = "Price vs. the McGinley core on the chart timeframe and two higher timeframes. Higher timeframes use closed candles only.")
        table.cell(hud, 1, 2, alignTxt, text_color = alignCol, text_size = tSize, text_halign = text.align_right)
 
        // Row 3: Setup status
        table.cell(hud, 0, 3, "Setup Status", text_color = C_TEXT_MUTE, text_size = tSize, text_halign = text.align_left, tooltip = "What the setup engine is waiting for right now.")
        table.cell(hud, 1, 3, f_setupTxt(), text_color = C_TEXT_BRT, text_size = tSize, text_halign = text.align_right)
 
        // Row 4: Last setup and its status
        string lastTxt = "None yet"
        color  lastCol = C_TEXT_MUTE
        if lsDir != 0
            lastTxt := (lsDir == 1 ? "Bullish " : "Bearish ") + str.tostring(lsPx, format.mintick) + " · " + str.tostring(bar_index - lsBar) + " bars ago · " + lsStatus
            lastCol := lsStatus == "Active" ? (lsDir == 1 ? C_BULL_TXT : C_BEAR_TXT) : C_TEXT_MUTE
        table.cell(hud, 0, 4, "Last Setup", text_color = C_TEXT_MUTE, text_size = tSize, text_halign = text.align_left, tooltip = lsDir != 0 ? lsType + (lsStatus == "Active" ? "\nInvalid " + (lsDir == 1 ? "below " : "above ") + str.tostring(lsInv, format.mintick) : "") : "No setup on the loaded history yet.")
        table.cell(hud, 1, 4, lastTxt, text_color = lastCol, text_size = tSize, text_halign = text.align_right)
 
        // Rows 5-6: Nearest resistance / support as prices
        resTxt = not na(nearestResBot) and distNearestRes < 900 ? str.tostring(nearestResBot, format.mintick) + "  (" + str.tostring(distNearestRes, "#.#") + " ATR away)" : "None nearby"
        supTxt = not na(nearestSupTop) and distNearestSup < 900 ? str.tostring(nearestSupTop, format.mintick) + "  (" + str.tostring(distNearestSup, "#.#") + " ATR away)" : "None nearby"
        table.cell(hud, 0, 5, "Nearest Resistance", text_color = C_TEXT_MUTE, text_size = tSize, text_halign = text.align_left)
        table.cell(hud, 1, 5, resTxt, text_color = C_BEAR_TXT, text_size = tSize, text_halign = text.align_right)
        table.cell(hud, 0, 6, "Nearest Support", text_color = C_TEXT_MUTE, text_size = tSize, text_halign = text.align_left)
        table.cell(hud, 1, 6, supTxt, text_color = C_BULL_TXT, text_size = tSize, text_halign = text.align_right)
 
        // Row 7: Volume pressure from the CVD trend (not the last candle)
        string pressTxt = "No volume data"
        color  pressCol = C_TEXT_MUTE
        if isVolAvailable
            if cvdAboveMA and cvdRising
                pressTxt := "Buyers leading"
                pressCol := C_BULL_TXT
            else if not cvdAboveMA and not cvdRising
                pressTxt := "Sellers leading"
                pressCol := C_BEAR_TXT
            else
                pressTxt := "Mixed"
                pressCol := C_TEXT_BRT
        table.cell(hud, 0, 7, "Volume Pressure (est.)", text_color = C_TEXT_MUTE, text_size = tSize, text_halign = text.align_left)
        table.cell(hud, 1, 7, pressTxt, text_color = pressCol, text_size = tSize, text_halign = text.align_right)
 
        // Row 8: Overall bias with one net reading (bullish minus bearish confluence)
        int netBias = bullScore - bearScore
        string netTxt = (netBias > 0 ? "+" : "") + str.tostring(netBias)
        string meter = showScoreBars ? "  " + f_meterStr(math.abs(netBias) / 50.0) : ""
        // Flag when the bias leans against the higher-timeframe trend, so it never contradicts Setup Status silently
        bool biasVsHtf = (netBias >= 8 and htfTrendDir == -1) or (netBias <= -8 and htfTrendDir == 1)
        color biasTxtCol = biasVsHtf ? C_TEXT_BRT : netBias >= 8 ? C_BULL_TXT : netBias <= -8 ? C_BEAR_TXT : C_TEXT_BRT
        string biasTxt = marketBias + "  " + netTxt + meter + (biasVsHtf ? "  · vs " + f_tfLabel(htfPeriod) + " trend" : "")
        table.cell(hud, 0, 8, "Overall Bias", text_color = C_TEXT_MUTE, text_size = tSize, text_halign = text.align_left, tooltip = "Net bullish minus bearish agreement on this timeframe. Flagged when it leans against the higher-timeframe trend.")
        table.cell(hud, 1, 8, biasTxt, text_color = biasTxtCol, text_size = tSize, text_halign = text.align_right)
 
        // Row 9: Data source (honest attribution)
        if isClassicHud
            statusTxt = not isVolAvailable ? "Trend + structure only (no volume)" : engMode == "Bar only (lite)" or not canUseLtf ? "Volume estimate · chart bars" : "Volume estimate · " + ltfRes + "m intrabar"
            table.cell(hud, 0, 9, "Data", text_color = C_TEXT_MUTE, text_size = tSize, text_halign = text.align_left)
            table.cell(hud, 1, 9, statusTxt, text_color = C_TEXT_MUTE, text_size = tSize, text_halign = text.align_right)
        else
            table.clear(hud, 0, 9, 1, 9)
    else
        table.clear(hud, 0, 0, 1, 9)
 
// ═════════════════════════ ALERT CONDITIONS ═════════════════════════
 
bullSignalAlert     = validBullSignal
bearSignalAlert     = validBearSignal
bullConfluenceAlert = barstate.isconfirmed and bullScore >= strongThresh and bullScore > bearScore + 15 and (bullScore[1] < strongThresh or bullScore[1] <= bearScore[1] + 15)
bearConfluenceAlert = barstate.isconfirmed and bearScore >= strongThresh and bearScore > bullScore + 15 and (bearScore[1] < strongThresh or bearScore[1] <= bullScore[1] + 15)
biasShiftAlert      = barstate.isconfirmed and marketBias != marketBias[1]
rejectionAlert      = barstate.isconfirmed and (confirmedRejSup or confirmedRejRes)
 
alertcondition(bullSignalAlert,     "TZF Bullish Setup",     "{{ticker}} {{interval}} Trend Zone Flow: Confirmed bullish setup.")
alertcondition(bearSignalAlert,     "TZF Bearish Setup",     "{{ticker}} {{interval}} Trend Zone Flow: Confirmed bearish setup.")
alertcondition(bullConfluenceAlert, "Strong Bullish Confluence", "{{ticker}} {{interval}} Trend Zone Flow: Confirmed Strong Bullish Confluence detected.")
alertcondition(bearConfluenceAlert, "Strong Bearish Confluence", "{{ticker}} {{interval}} Trend Zone Flow: Confirmed Strong Bearish Confluence detected.")
alertcondition(biasShiftAlert,      "Confluence Bias Shift",     "{{ticker}} {{interval}} Trend Zone Flow: Overall Market Bias changed.")
alertcondition(rejectionAlert,      "S/R Zone Rejection Event",  "{{ticker}} {{interval}} Trend Zone Flow: Confirmed rejection off an active S/R zone.")
 
// ═════════════════════════ WATERMARK ═════════════════════════
var table wm = table.new(position.bottom_center, 2, 1, frame_width = 1, border_width = 0)
if barstate.islast and showWatermark
    wmDark     = wmTheme == "Dark" or (wmTheme == "Auto" and (color.r(chart.bg_color) * 299 + color.g(chart.bg_color) * 587 + color.b(chart.bg_color) * 114) / 1000 < 128)
    wm_bg      = wmDark ? color.new(#14110B, 0) : color.new(#F2EAD3, 0)
    wm_dot_col = wmDark ? color.new(#D4AF37, 15) : color.new(#B8860B, 10)
    wm_txt_col = wmDark ? color.new(#C9B37E, 0)  : color.new(#7A6423, 0)
    wm_frm_col = wmDark ? color.new(#C9A227, 60) : color.new(#B8860B, 60)
    table.set_frame_color(wm, wm_frm_col)
    table.cell(wm, 0, 0, " ◆ ", bgcolor = wm_bg, text_color = wm_dot_col, text_size = size.small, text_halign = text.align_center, text_valign = text.align_center)
    table.cell(wm, 1, 0, " A X E A L G O ", bgcolor = wm_bg, text_color = wm_txt_col, text_size = size.small, text_halign = text.align_left, text_valign = text.align_center)

← 返回列表