MM Flow
FlowScripts

Perfected FlowScript

Supply and Demand Reaction Zones

Supply & Demand Reaction Zones — SMC Perfected is indexed as 044_supply_and_demand_reaction_zones.flowscript. The exact FlowScript is viewable here; chart observe and trading automation use the current mmflow chart/recipe signal proxy until FlowScript v2 transpilation is available.

This exact FlowScript uses the v2 source dialect. It is viewable and connected to the chart/automation proxy, but direct editor execution needs the FlowScript v2 transpiler.

Dialect

flowscript-v2

Compatibility

flowscript-v2-needs-transpile

Position

onchart

Axis

false

Size

26.4 KB

Lines

659

Native Signal Candidates

11 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.

11/11 guarded

Demand Zone Formed — Strength: " + math.round(d0_strength) + "%

line 348:13

Trigger

(showZones && d0_active == 1) && (!d0_isBroken || showBroken) && (showLabels && d0_bar == barCount - pivotLen)

Value

d0_top

Deps

barCount:static, d0_active:static, d0_bar:static, d0_isBroken:var, pivotLen:input, showBroken:input, showLabels:input, showZones:input

Demand Zone 2 Formed — Strength: " + math.round(d1_strength) + "%

line 391:13

Trigger

(showZones && maxZones >= 2 && d1_active == 1) && (!d1_isBroken || showBroken) && (showLabels && d1_bar == barCount - pivotLen)

Value

d1_top

Deps

barCount:static, d1_active:static, d1_bar:static, d1_isBroken:var, maxZones:input, pivotLen:input, showBroken:input, showLabels:input, showZones:input

Demand Zone 3 Formed — Strength: " + math.round(d2_strength) + "%

line 434:13

Trigger

(showZones && maxZones >= 3 && d2_active == 1) && (!d2_isBroken || showBroken) && (showLabels && d2_bar == barCount - pivotLen)

Value

d2_top

Deps

barCount:static, d2_active:static, d2_bar:static, d2_isBroken:var, maxZones:input, pivotLen:input, showBroken:input, showLabels:input, showZones:input

Supply Zone Formed — Strength: " + math.round(s0_strength) + "%

line 477:13

Trigger

(showZones && s0_active == 1) && (!s0_isBroken || showBroken) && (showLabels && s0_bar == barCount - pivotLen)

Value

s0_top

Deps

barCount:static, pivotLen:input, s0_active:static, s0_bar:static, s0_isBroken:var, showBroken:input, showLabels:input, showZones:input

Supply Zone 2 Formed — Strength: " + math.round(s1_strength) + "%

line 520:13

Trigger

(showZones && maxZones >= 2 && s1_active == 1) && (!s1_isBroken || showBroken) && (showLabels && s1_bar == barCount - pivotLen)

Value

s1_top

Deps

barCount:static, maxZones:input, pivotLen:input, s1_active:static, s1_bar:static, s1_isBroken:var, showBroken:input, showLabels:input, showZones:input

Supply Zone 3 Formed — Strength: " + math.round(s2_strength) + "%

line 563:13

Trigger

(showZones && maxZones >= 3 && s2_active == 1) && (!s2_isBroken || showBroken) && (showLabels && s2_bar == barCount - pivotLen)

Value

s2_top

Deps

barCount:static, maxZones:input, pivotLen:input, s2_active:static, s2_bar:static, s2_isBroken:var, showBroken:input, showLabels:input, showZones:input

Bull Breakout

line 579:9

Trigger

(showBreakoutShapes) && (s0_active == 1 && s0_broken == 0 && cl > s0_top + breakBuffer)

Value

cl

Deps

breakBuffer:timeseries, cl:timeseries, s0_active:static, s0_broken:static, s0_top:static, showBreakoutShapes:input

Bear Breakout

line 590:9

Trigger

(showBreakoutShapes) && (d0_active == 1 && d0_broken == 0 && cl < d0_bot - breakBuffer)

Value

cl

Deps

breakBuffer:timeseries, cl:timeseries, d0_active:static, d0_bot:static, d0_broken:static, showBreakoutShapes:input

Demand Mitigated

line 605:13

Trigger

(showMitigationShapes) && (d0_active == 1 && d0_mitigated == 1 && d0_broken == 0 && barCount - d0_bar >= minZoneBars) && (lo <= d0_top && hi >= d0_bot)

Value

d0_bot

Deps

barCount:static, d0_active:static, d0_bar:static, d0_bot:static, d0_broken:static, d0_mitigated:static, d0_top:static, hi:timeseries, lo:timeseries, minZoneBars:input, showMitigationShapes:input

Supply Mitigated

line 617:13

Trigger

(showMitigationShapes) && (s0_active == 1 && s0_mitigated == 1 && s0_broken == 0 && barCount - s0_bar >= minZoneBars) && (hi >= s0_bot && lo <= s0_top)

Value

s0_top

Deps

barCount:static, hi:timeseries, lo:timeseries, minZoneBars:input, s0_active:static, s0_bar:static, s0_bot:static, s0_broken:static, s0_mitigated:static, s0_top:static, showMitigationShapes:input

Unlabeled shape

line 649:5

Trigger

(showStrengthLabel && isLastBar)

Value

hi

Deps

isLastBar:builtin, showStrengthLabel:input

044_supply_and_demand_reaction_zones.flowscript

source path: kscripts/perfected/044_supply_and_demand_reaction_zones.flowscript · sha256:5dfd867805eee5871626804df618b2b2f974348cafe0a2425becfad733c36c5d

hash verified
//@version=2
// ============================================================================
// Supply and Demand Reaction Zones — Smart Money Concepts & Market Structure
// Author: BackQuant (@BackQuant) — Perfected by kScript_Perfection_Engineer
// Tags: CORE, #supplydemand, #smc, #reactionzones, #zonedetection, #volumeconfirmation
//
// Production-grade supply/demand zone detector with pivot-point confirmation,
// volume-validated zone formation, zone strength scoring, breakout detection,
// mitigation tracking, and ATR-based dynamic padding. Tracks up to 3 active
// demand and 3 active supply zones simultaneously with full state management.
//
// Academic foundations:
//  - Campbell, Ramadorai & Vuolteenaho (2005), "Caught On Tape: Institutional
//    Order Flow and Stock Returns" (NBER 11439). Regression method achieves
//    ~12% R² predicting institutional ownership changes from trade patterns.
//    Key formula: ΔInstOwn_t = α + β₁·BuyVol_t + β₂·SellVol_t + ε_t.
//    Validates that institutional footprints concentrate at supply/demand zones.
//  - Jones & Lipson (2005), "Are Retail Orders Different?" Countervailing
//    institutional flow: 1,000 retail shares → 400+ institutional shares opposite
//    within 5 minutes. Zones represent areas where smart money accumulates/distributes.
//  - Biais, Glosten & Spatt (2005), "Market Microstructure: A Survey"
//    (J. Financial Markets, 699+ citations). Framework: latent demands D(p) →
//    realized prices/volumes via λ·ΣX_i. Explains why supply/demand zones exist
//    as price-discovery inefficiencies where liquidity is absorbed.
//  - Bhusal (2025), "Timing the Trap: Stop Hunt Zones & Price Manipulation"
//    (SSRN 5276088). Documents engineered liquidity traps and inducement
//    phases; validates stop-hunting as observable microstructure phenomenon.
//    Zone invalidation logic mirrors Bhusal's stop-hunt buffer framework.
//  - Frykmer & Johnsson (2019), "Pivot Point Trading in the Foreign Exchange
//    Market" (Lund University). Finds exchange rates tend to stop trending at
//    pivot levels—a novel finding supporting zone-based reaction detection.
//  - Madhavan (2000), "Market Microstructure: A Practitioner's Guide" (JFM).
//    Emphasizes liquidity provider positioning and how volume concentrates at
//    key price levels, forming the microstructural basis for supply/demand zones.
// ============================================================================

define(title="Supply & Demand Reaction Zones — SMC Perfected", position="onchart", axis=false)

// === USER INPUTS ===
// --- Pivot Detection ---
var pivotLen = input(name="pivotLen", type="number", defaultValue=5, label="Pivot Length (each side)", constraints={min: 2, max: 50, step: 1}, group="Pivot Detection")
var volConfirm = input(name="volConfirm", type="boolean", defaultValue=true, label="Require Volume Confirmation", group="Pivot Detection")
var volMult = input(name="volMult", type="number", defaultValue=1.5, label="Volume Threshold (× Avg)", constraints={min: 1.0, max: 5.0, step: 0.1}, group="Pivot Detection")

// --- Zone Configuration ---
var maxZones = input(name="maxZones", type="number", defaultValue=3, label="Max Active Zones (each side)", constraints={min: 1, max: 5, step: 1}, group="Zone Configuration")
var atrLen = input(name="atrLen", type="number", defaultValue=14, label="ATR Length", constraints={min: 5, max: 100, step: 1}, group="Zone Configuration")
var padMult = input(name="padMult", type="number", defaultValue=0.5, label="Zone Padding (ATR Multiple)", constraints={min: 0.0, max: 3.0, step: 0.1}, group="Zone Configuration")
var breakMult = input(name="breakMult", type="number", defaultValue=1.0, label="Break Threshold (ATR Multiple)", constraints={min: 0.0, max: 5.0, step: 0.1}, group="Zone Configuration")
var minZoneBars = input(name="minZoneBars", type="number", defaultValue=3, label="Min Bars Before Mitigation", constraints={min: 1, max: 20, step: 1}, group="Zone Configuration")

// --- Display ---
var showZones = input(name="showZones", type="boolean", defaultValue=true, label="Show Supply/Demand Zones", group="Display")
var showLabels = input(name="showLabels", type="boolean", defaultValue=true, label="Show Zone Formation Labels", group="Display")
var showMitigated = input(name="showMitigated", type="boolean", defaultValue=true, label="Show Mitigated Zones", group="Display")
var showBroken = input(name="showBroken", type="boolean", defaultValue=true, label="Show Broken Zones (Gray)", group="Display")
var showBreakoutShapes = input(name="showBreakoutShapes", type="boolean", defaultValue=true, label="Show Breakout Shapes", group="Display")
var showMitigationShapes = input(name="showMitigationShapes", type="boolean", defaultValue=true, label="Show Mitigation Shapes", group="Display")
var showStrengthLabel = input(name="showStrengthLabel", type="boolean", defaultValue=true, label="Show Zone Strength Label", group="Display")

// --- Colors ---
var demandColor = input(name="demandColor", type="color", defaultValue="#26a69a", label="Demand Zone Color", group="Colors")
var supplyColor = input(name="supplyColor", type="color", defaultValue="#ef5350", label="Supply Zone Color", group="Colors")
var demandWeakColor = input(name="demandWeakColor", type="color", defaultValue="#4db6ac", label="Demand Mitigated Color", group="Colors")
var supplyWeakColor = input(name="supplyWeakColor", type="color", defaultValue="#ef9a9a", label="Supply Mitigated Color", group="Colors")
var brokenColor = input(name="brokenColor", type="color", defaultValue="#9e9e9e", label="Broken Zone Color", group="Colors")
var breakoutBullColor = input(name="breakoutBullColor", type="color", defaultValue="#00ff00", label="Bullish Breakout Color", group="Colors")
var breakoutBearColor = input(name="breakoutBearColor", type="color", defaultValue="#ff0000", label="Bearish Breakout Color", group="Colors")

// === DATA SOURCES ===
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries hi = bars.high
timeseries lo = bars.low
timeseries cl = bars.close
timeseries op = bars.open
timeseries vol = bars.volume

// isnan guard on first use of external data — prevents NaN propagation on startup
if (isnan(cl[0]) || isnan(hi[0]) || isnan(lo[0]) || isnan(op[0]) || isnan(vol[0])) {
    return
}

// === COMPUTATION ===
// ATR (Wilder) using proper True Range formula:
// TR = max(high - low, |high - close[1]|, |low - close[1]|)
// ATR = SMA(TR, atrLen)
// Guard against isnan(close[1]) on the first bar by substituting current close.
timeseries prevClose = isnan(cl[1]) ? cl : cl[1]
timeseries tr1 = hi - lo
timeseries tr2 = math.abs(hi - prevClose)
timeseries tr3 = math.abs(lo - prevClose)
timeseries trueRange = math.max(tr1, math.max(tr2, tr3))
timeseries atr = sma(trueRange, atrLen)
timeseries atrPad = atr * padMult
timeseries breakBuffer = atr * breakMult

// Volume average for confirmation
timeseries avgVol = sma(vol, 20)

// Swing detection: pivot at [pivotLen] bars ago confirmed when current bar
// completes the right-side lookback. Formula: P_high = H_{t-p} == max(H_{t-p:t+p})
// and P_low = L_{t-p} == min(L_{t-p:t+p}).
// The second condition ensures the pivot is strictly higher/lower than all bars
// that formed after it (including the current bar).
var isSwingHigh = hi[pivotLen] == highest(hi, pivotLen * 2 + 1) && hi[pivotLen] > highest(hi, pivotLen)
var isSwingLow = lo[pivotLen] == lowest(lo, pivotLen * 2 + 1) && lo[pivotLen] < lowest(lo, pivotLen)

// Volume confirmation at pivot
timeseries pivotVol = vol[pivotLen]
var volConfirmed = !volConfirm || (pivotVol >= avgVol[pivotLen] * volMult)

// Bar counter for event tracking and right-extension.
static barCount = 0
if (!isLiveUpdate) {
    barCount = barCount + 1
}

// --- STATIC STATE: Demand Zones (up to maxZones) ---
// Each zone: top, bot, bar, active, mitigated, broken, strength (0-100)
static d0_top = 0.0
static d0_bot = 0.0
static d0_bar = 0
static d0_active = 0
static d0_mitigated = 0
static d0_broken = 0
static d0_strength = 0.0

static d1_top = 0.0
static d1_bot = 0.0
static d1_bar = 0
static d1_active = 0
static d1_mitigated = 0
static d1_broken = 0
static d1_strength = 0.0

static d2_top = 0.0
static d2_bot = 0.0
static d2_bar = 0
static d2_active = 0
static d2_mitigated = 0
static d2_broken = 0
static d2_strength = 0.0

// --- STATIC STATE: Supply Zones (up to maxZones) ---
static s0_top = 0.0
static s0_bot = 0.0
static s0_bar = 0
static s0_active = 0
static s0_mitigated = 0
static s0_broken = 0
static s0_strength = 0.0

static s1_top = 0.0
static s1_bot = 0.0
static s1_bar = 0
static s1_active = 0
static s1_mitigated = 0
static s1_broken = 0
static s1_strength = 0.0

static s2_top = 0.0
static s2_bot = 0.0
static s2_bar = 0
static s2_active = 0
static s2_mitigated = 0
static s2_broken = 0
static s2_strength = 0.0

// --- STATE UPDATE (only on bar close) ---
// All stateful transitions happen here to ensure consistency.
if (!isLiveUpdate) {
    // Check existing demand zones for mitigation and breakage
    // Demand zone mitigation: price returns to zone (touches or enters)
    // Demand zone breakage: price closes below zone bottom minus buffer
    if (d0_active == 1 && d0_broken == 0) {
        if (barCount - d0_bar >= minZoneBars) {
            if (lo <= d0_top && hi >= d0_bot) {
                d0_mitigated = 1
            }
        }
        if (cl < d0_bot - breakBuffer) {
            d0_broken = 1
        }
    }
    if (d1_active == 1 && d1_broken == 0) {
        if (barCount - d1_bar >= minZoneBars) {
            if (lo <= d1_top && hi >= d1_bot) {
                d1_mitigated = 1
            }
        }
        if (cl < d1_bot - breakBuffer) {
            d1_broken = 1
        }
    }
    if (d2_active == 1 && d2_broken == 0) {
        if (barCount - d2_bar >= minZoneBars) {
            if (lo <= d2_top && hi >= d2_bot) {
                d2_mitigated = 1
            }
        }
        if (cl < d2_bot - breakBuffer) {
            d2_broken = 1
        }
    }

    // Check existing supply zones for mitigation and breakage
    // Supply zone mitigation: price returns to zone
    // Supply zone breakage: price closes above zone top plus buffer
    if (s0_active == 1 && s0_broken == 0) {
        if (barCount - s0_bar >= minZoneBars) {
            if (hi >= s0_bot && lo <= s0_top) {
                s0_mitigated = 1
            }
        }
        if (cl > s0_top + breakBuffer) {
            s0_broken = 1
        }
    }
    if (s1_active == 1 && s1_broken == 0) {
        if (barCount - s1_bar >= minZoneBars) {
            if (hi >= s1_bot && lo <= s1_top) {
                s1_mitigated = 1
            }
        }
        if (cl > s1_top + breakBuffer) {
            s1_broken = 1
        }
    }
    if (s2_active == 1 && s2_broken == 0) {
        if (barCount - s2_bar >= minZoneBars) {
            if (hi >= s2_bot && lo <= s2_top) {
                s2_mitigated = 1
            }
        }
        if (cl > s2_top + breakBuffer) {
            s2_broken = 1
        }
    }

    // New demand zone formation on swing low with volume confirmation
    if (isSwingLow && volConfirmed) {
        // Shift demand zones down (new zone at index 0)
        if (maxZones >= 3) {
            d2_top = d1_top
            d2_bot = d1_bot
            d2_bar = d1_bar
            d2_active = d1_active
            d2_mitigated = d1_mitigated
            d2_broken = d1_broken
            d2_strength = d1_strength
        }
        if (maxZones >= 2) {
            d1_top = d0_top
            d1_bot = d0_bot
            d1_bar = d0_bar
            d1_active = d0_active
            d1_mitigated = d0_mitigated
            d1_broken = d0_broken
            d1_strength = d0_strength
        }
        // Calculate strength based on move-away, volume, ATR-relative size, freshness
        var pivotL = lo[pivotLen]
        var pivotH = hi[pivotLen]
        var pivotV = vol[pivotLen]
        var moveStrength = math.min(100, (cl - pivotH) / (atr * 2) * 100)
        var volStrength = volConfirm ? math.min(100, pivotV / (avgVol * volMult) * 50) : 50
        var sizeStrength = math.min(100, (pivotH - pivotL) / atr * 50)
        var freshness = math.max(0, 100)
        d0_strength = (moveStrength + volStrength + sizeStrength + freshness) / 4
        d0_top = pivotH + atrPad[pivotLen]
        d0_bot = pivotL - atrPad[pivotLen]
        d0_bar = barCount - pivotLen
        d0_active = 1
        d0_mitigated = 0
        d0_broken = 0
    }

    // New supply zone formation on swing high with volume confirmation
    if (isSwingHigh && volConfirmed) {
        // Shift supply zones down (new zone at index 0)
        if (maxZones >= 3) {
            s2_top = s1_top
            s2_bot = s1_bot
            s2_bar = s1_bar
            s2_active = s1_active
            s2_mitigated = s1_mitigated
            s2_broken = s1_broken
            s2_strength = s1_strength
        }
        if (maxZones >= 2) {
            s1_top = s0_top
            s1_bot = s0_bot
            s1_bar = s0_bar
            s1_active = s0_active
            s1_mitigated = s0_mitigated
            s1_broken = s0_broken
            s1_strength = s0_strength
        }
        // Calculate strength based on move-away, volume, ATR-relative size, freshness
        var pivotL = lo[pivotLen]
        var pivotH = hi[pivotLen]
        var pivotV = vol[pivotLen]
        var moveStrength = math.min(100, (pivotL - cl) / (atr * 2) * 100)
        var volStrength = volConfirm ? math.min(100, pivotV / (avgVol * volMult) * 50) : 50
        var sizeStrength = math.min(100, (pivotH - pivotL) / atr * 50)
        var freshness = math.max(0, 100)
        s0_strength = (moveStrength + volStrength + sizeStrength + freshness) / 4
        s0_top = pivotH + atrPad[pivotLen]
        s0_bot = pivotL - atrPad[pivotLen]
        s0_bar = barCount - pivotLen
        s0_active = 1
        s0_mitigated = 0
        s0_broken = 0
    }
}

// === PLOTS: DEMAND ZONE 0 ===
if (showZones && d0_active == 1) {
    var d0_isBroken = d0_broken == 1
    var d0_isMitigated = d0_mitigated == 1 && !d0_isBroken
    if (!d0_isBroken || showBroken) {
        var d0_topColor = d0_isBroken ? brokenColor : (d0_isMitigated ? demandWeakColor : demandColor)
        var d0_botColor = d0_topColor
        var d0_fillOpacity = d0_isBroken ? opacity(brokenColor, 20) : (d0_isMitigated ? opacity(demandWeakColor, 35) : opacity(demandColor, 45))
        plotLine(
            value=[d0_top, d0_bot],
            width=1,
            colors=[d0_topColor, d0_botColor],
            fill=d0_fillOpacity,
            label=["Demand Zone 1", "Demand Zone 1"],
            desc=["Top boundary of demand zone 1 (buying interest). ATR-padded.", "Bottom boundary of demand zone 1."]
        )
        plotLine(
            value=d0_top,
            width=1,
            colors=[d0_topColor],
            label=["Demand Zone 1 Top"],
            desc=["Top boundary of demand zone 1."]
        )
        plotLine(
            value=d0_bot,
            width=1,
            colors=[d0_botColor],
            label=["Demand Zone 1 Bot"],
            desc=["Bottom boundary of demand zone 1."]
        )
        if (showLabels && d0_bar == barCount - pivotLen) {
            plotShape(
                value=d0_top,
                shape="rectangle",
                colorIndex=d0_topColor,
                width=4,
                label=["Demand Zone Formed — Strength: " + math.round(d0_strength) + "%"],
                desc=["Demand zone formed at pivot low with volume confirmation. Strength: " + d0_strength + "%"]
            )
        }
    }
}

// === PLOTS: DEMAND ZONE 1 ===
if (showZones && maxZones >= 2 && d1_active == 1) {
    var d1_isBroken = d1_broken == 1
    var d1_isMitigated = d1_mitigated == 1 && !d1_isBroken
    if (!d1_isBroken || showBroken) {
        var d1_topColor = d1_isBroken ? brokenColor : (d1_isMitigated ? demandWeakColor : demandColor)
        var d1_botColor = d1_topColor
        var d1_fillOpacity = d1_isBroken ? opacity(brokenColor, 20) : (d1_isMitigated ? opacity(demandWeakColor, 35) : opacity(demandColor, 45))
        plotLine(
            value=[d1_top, d1_bot],
            width=1,
            colors=[d1_topColor, d1_botColor],
            fill=d1_fillOpacity,
            label=["Demand Zone 2", "Demand Zone 2"],
            desc=["Top boundary of demand zone 2.", "Bottom boundary of demand zone 2."]
        )
        plotLine(
            value=d1_top,
            width=1,
            colors=[d1_topColor],
            label=["Demand Zone 2 Top"],
            desc=["Top boundary of demand zone 2."]
        )
        plotLine(
            value=d1_bot,
            width=1,
            colors=[d1_botColor],
            label=["Demand Zone 2 Bot"],
            desc=["Bottom boundary of demand zone 2."]
        )
        if (showLabels && d1_bar == barCount - pivotLen) {
            plotShape(
                value=d1_top,
                shape="rectangle",
                colorIndex=d1_topColor,
                width=4,
                label=["Demand Zone 2 Formed — Strength: " + math.round(d1_strength) + "%"],
                desc=["Demand zone 2 formed at pivot low. Strength: " + d1_strength + "%"]
            )
        }
    }
}

// === PLOTS: DEMAND ZONE 2 ===
if (showZones && maxZones >= 3 && d2_active == 1) {
    var d2_isBroken = d2_broken == 1
    var d2_isMitigated = d2_mitigated == 1 && !d2_isBroken
    if (!d2_isBroken || showBroken) {
        var d2_topColor = d2_isBroken ? brokenColor : (d2_isMitigated ? demandWeakColor : demandColor)
        var d2_botColor = d2_topColor
        var d2_fillOpacity = d2_isBroken ? opacity(brokenColor, 20) : (d2_isMitigated ? opacity(demandWeakColor, 35) : opacity(demandColor, 45))
        plotLine(
            value=[d2_top, d2_bot],
            width=1,
            colors=[d2_topColor, d2_botColor],
            fill=d2_fillOpacity,
            label=["Demand Zone 3", "Demand Zone 3"],
            desc=["Top boundary of demand zone 3.", "Bottom boundary of demand zone 3."]
        )
        plotLine(
            value=d2_top,
            width=1,
            colors=[d2_topColor],
            label=["Demand Zone 3 Top"],
            desc=["Top boundary of demand zone 3."]
        )
        plotLine(
            value=d2_bot,
            width=1,
            colors=[d2_botColor],
            label=["Demand Zone 3 Bot"],
            desc=["Bottom boundary of demand zone 3."]
        )
        if (showLabels && d2_bar == barCount - pivotLen) {
            plotShape(
                value=d2_top,
                shape="rectangle",
                colorIndex=d2_topColor,
                width=4,
                label=["Demand Zone 3 Formed — Strength: " + math.round(d2_strength) + "%"],
                desc=["Demand zone 3 formed at pivot low. Strength: " + d2_strength + "%"]
            )
        }
    }
}

// === PLOTS: SUPPLY ZONE 0 ===
if (showZones && s0_active == 1) {
    var s0_isBroken = s0_broken == 1
    var s0_isMitigated = s0_mitigated == 1 && !s0_isBroken
    if (!s0_isBroken || showBroken) {
        var s0_topColor = s0_isBroken ? brokenColor : (s0_isMitigated ? supplyWeakColor : supplyColor)
        var s0_botColor = s0_topColor
        var s0_fillOpacity = s0_isBroken ? opacity(brokenColor, 20) : (s0_isMitigated ? opacity(supplyWeakColor, 35) : opacity(supplyColor, 45))
        plotLine(
            value=[s0_top, s0_bot],
            width=1,
            colors=[s0_topColor, s0_botColor],
            fill=s0_fillOpacity,
            label=["Supply Zone 1", "Supply Zone 1"],
            desc=["Top boundary of supply zone 1 (selling pressure). ATR-padded.", "Bottom boundary of supply zone 1."]
        )
        plotLine(
            value=s0_top,
            width=1,
            colors=[s0_topColor],
            label=["Supply Zone 1 Top"],
            desc=["Top boundary of supply zone 1."]
        )
        plotLine(
            value=s0_bot,
            width=1,
            colors=[s0_botColor],
            label=["Supply Zone 1 Bot"],
            desc=["Bottom boundary of supply zone 1."]
        )
        if (showLabels && s0_bar == barCount - pivotLen) {
            plotShape(
                value=s0_top,
                shape="rectangle",
                colorIndex=s0_topColor,
                width=4,
                label=["Supply Zone Formed — Strength: " + math.round(s0_strength) + "%"],
                desc=["Supply zone formed at pivot high with volume confirmation. Strength: " + s0_strength + "%"]
            )
        }
    }
}

// === PLOTS: SUPPLY ZONE 1 ===
if (showZones && maxZones >= 2 && s1_active == 1) {
    var s1_isBroken = s1_broken == 1
    var s1_isMitigated = s1_mitigated == 1 && !s1_isBroken
    if (!s1_isBroken || showBroken) {
        var s1_topColor = s1_isBroken ? brokenColor : (s1_isMitigated ? supplyWeakColor : supplyColor)
        var s1_botColor = s1_topColor
        var s1_fillOpacity = s1_isBroken ? opacity(brokenColor, 20) : (s1_isMitigated ? opacity(supplyWeakColor, 35) : opacity(supplyColor, 45))
        plotLine(
            value=[s1_top, s1_bot],
            width=1,
            colors=[s1_topColor, s1_botColor],
            fill=s1_fillOpacity,
            label=["Supply Zone 2", "Supply Zone 2"],
            desc=["Top boundary of supply zone 2.", "Bottom boundary of supply zone 2."]
        )
        plotLine(
            value=s1_top,
            width=1,
            colors=[s1_topColor],
            label=["Supply Zone 2 Top"],
            desc=["Top boundary of supply zone 2."]
        )
        plotLine(
            value=s1_bot,
            width=1,
            colors=[s1_botColor],
            label=["Supply Zone 2 Bot"],
            desc=["Bottom boundary of supply zone 2."]
        )
        if (showLabels && s1_bar == barCount - pivotLen) {
            plotShape(
                value=s1_top,
                shape="rectangle",
                colorIndex=s1_topColor,
                width=4,
                label=["Supply Zone 2 Formed — Strength: " + math.round(s1_strength) + "%"],
                desc=["Supply zone 2 formed at pivot high. Strength: " + s1_strength + "%"]
            )
        }
    }
}

// === PLOTS: SUPPLY ZONE 2 ===
if (showZones && maxZones >= 3 && s2_active == 1) {
    var s2_isBroken = s2_broken == 1
    var s2_isMitigated = s2_mitigated == 1 && !s2_isBroken
    if (!s2_isBroken || showBroken) {
        var s2_topColor = s2_isBroken ? brokenColor : (s2_isMitigated ? supplyWeakColor : supplyColor)
        var s2_botColor = s2_topColor
        var s2_fillOpacity = s2_isBroken ? opacity(brokenColor, 20) : (s2_isMitigated ? opacity(supplyWeakColor, 35) : opacity(supplyColor, 45))
        plotLine(
            value=[s2_top, s2_bot],
            width=1,
            colors=[s2_topColor, s2_botColor],
            fill=s2_fillOpacity,
            label=["Supply Zone 3", "Supply Zone 3"],
            desc=["Top boundary of supply zone 3.", "Bottom boundary of supply zone 3."]
        )
        plotLine(
            value=s2_top,
            width=1,
            colors=[s2_topColor],
            label=["Supply Zone 3 Top"],
            desc=["Top boundary of supply zone 3."]
        )
        plotLine(
            value=s2_bot,
            width=1,
            colors=[s2_botColor],
            label=["Supply Zone 3 Bot"],
            desc=["Bottom boundary of supply zone 3."]
        )
        if (showLabels && s2_bar == barCount - pivotLen) {
            plotShape(
                value=s2_top,
                shape="rectangle",
                colorIndex=s2_topColor,
                width=4,
                label=["Supply Zone 3 Formed — Strength: " + math.round(s2_strength) + "%"],
                desc=["Supply zone 3 formed at pivot high. Strength: " + s2_strength + "%"]
            )
        }
    }
}

// === PLOTS: BREAKOUT SHAPES ===
if (showBreakoutShapes) {
    // Demand zone bullish breakout (price closes above supply zone top + buffer)
    if (s0_active == 1 && s0_broken == 0 && cl > s0_top + breakBuffer) {
        plotShape(
            value=cl,
            shape="triangleup",
            colorIndex=breakoutBullColor,
            width=5,
            label=["Bull Breakout"],
            desc=["Price broke above supply zone with ATR-confirmed momentum. Demand exceeds supply."]
        )
    }
    // Supply zone bearish breakout (price closes below demand zone bottom - buffer)
    if (d0_active == 1 && d0_broken == 0 && cl < d0_bot - breakBuffer) {
        plotShape(
            value=cl,
            shape="triangledown",
            colorIndex=breakoutBearColor,
            width=5,
            label=["Bear Breakout"],
            desc=["Price broke below demand zone with ATR-confirmed momentum. Supply exceeds demand."]
        )
    }
}

// === PLOTS: MITIGATION SHAPES ===
if (showMitigationShapes) {
    if (d0_active == 1 && d0_mitigated == 1 && d0_broken == 0 && barCount - d0_bar >= minZoneBars) {
        if (lo <= d0_top && hi >= d0_bot) {
            plotShape(
                value=d0_bot,
                shape="rectangle",
                colorIndex=demandWeakColor,
                width=3,
                label=["Demand Mitigated"],
                desc=["Price returned to demand zone and respected it. Institutional buying interest confirmed."]
            )
        }
    }
    if (s0_active == 1 && s0_mitigated == 1 && s0_broken == 0 && barCount - s0_bar >= minZoneBars) {
        if (hi >= s0_bot && lo <= s0_top) {
            plotShape(
                value=s0_top,
                shape="rectangle",
                colorIndex=supplyWeakColor,
                width=3,
                label=["Supply Mitigated"],
                desc=["Price returned to supply zone and respected it. Institutional selling pressure confirmed."]
            )
        }
    }
}

// === REGIME / STRENGTH LABEL (plotPriceLabel) ===
if (showStrengthLabel && isLastBar) {
    var activeDemand = d0_active == 1 && d0_broken == 0
    var activeSupply = s0_active == 1 && s0_broken == 0
    var labelText = ""
    var labelColor = "#ffffff"
    var bgColor = "#333333"
    if (activeDemand && activeSupply) {
        labelText = "CONFLUENCE: D=" + math.round(d0_strength) + "% | S=" + math.round(s0_strength) + "%"
        bgColor = d0_strength > s0_strength ? demandColor : supplyColor
    } else if (activeDemand) {
        labelText = "DEMAND ACTIVE — Strength " + math.round(d0_strength) + "%"
        bgColor = demandColor
    } else if (activeSupply) {
        labelText = "SUPPLY ACTIVE — Strength " + math.round(s0_strength) + "%"
        bgColor = supplyColor
    } else {
        labelText = "NO ACTIVE ZONES"
        bgColor = "#666666"
    }
    plotPriceLabel(
        price=hi,
        text=labelText,
        type="callout",
        color="#ffffff",
        backgroundColor=bgColor,
        size=10,
        fontWeight=700
    )
}