MM Flow
FlowScripts

Perfected FlowScript

Volumetric Support and Resistance

Volumetric Support and Resistance V2 is indexed as 012_volumetric_support_and_resistance.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

25.4 KB

Lines

668

Native Signal Candidates

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

8/8 guarded

Res Pivot

line 548:5

Trigger

(showPivots && newResEvent)

Value

hi[pivotLen]

Deps

newResEvent:var, showPivots:input

Sup Pivot

line 559:5

Trigger

(showPivots && newSupEvent)

Value

lo[pivotLen]

Deps

newSupEvent:var, showPivots:input

R1 Break

line 574:5

Trigger

(showBreaks && res1BreakEvent)

Value

px

Deps

res1BreakEvent:var, showBreaks:input

R2 Break

line 584:5

Trigger

(showBreaks && res2BreakEvent)

Value

px

Deps

res2BreakEvent:var, showBreaks:input

R3 Break

line 594:5

Trigger

(showBreaks && res3BreakEvent)

Value

px

Deps

res3BreakEvent:var, showBreaks:input

S1 Break

line 604:5

Trigger

(showBreaks && sup1BreakEvent)

Value

px

Deps

showBreaks:input, sup1BreakEvent:var

S2 Break

line 614:5

Trigger

(showBreaks && sup2BreakEvent)

Value

px

Deps

showBreaks:input, sup2BreakEvent:var

S3 Break

line 624:5

Trigger

(showBreaks && sup3BreakEvent)

Value

px

Deps

showBreaks:input, sup3BreakEvent:var

012_volumetric_support_and_resistance.flowscript

source path: kscripts/perfected/012_volumetric_support_and_resistance.flowscript · sha256:4ede809d78839491522e6ab44663597393895c030cd700f98fdbe2deed957b2e

hash verified
//@version=2
// ============================================================================
// Volumetric Support and Resistance V2 — Production-Grade Dynamic S/R Indicator
// Author: BackQuant (@BackQuant)  |  Perfected by: kScript Perfection Engineer
// Tags: SPECIALIZED, CORE, #support, #resistance, #volume, #pivot, #atr
//
// Dynamic support and resistance zones drawn from volume-confirmed pivot highs
// and lows. ATR-based zone thickness, volume-weighted strength scoring, break
// detection with shape markers, and minimum-distance enforcement between levels.
// Tracks up to 3 support and 3 resistance levels with state-machine persistence.
//
// FORMULA FOUNDATION:
// 1. Pivot Detection: P_high = H_{t−p} == max(H_{t−2p:t}) && vol_{t−p} > avgVol × mult
//    Volume confirmation filters noise and ensures institutional participation.
// 2. ATR-Based Zone Thickness: Zone = Pivot ± (ATR × padMult)
//    per Wilder (1978) volatility-adaptive band methodology.
// 3. Volume-Weighted Strength Score: Strength = (pivotVol / avgVol) × (1 / (1 + barsSince))
//    Higher volume and recency increase level significance (Fazen Capital 2026).
// 4. Minimum Distance Enforcement: |price_i − price_j| > minDistPct × close
//    Prevents visual clutter from clustered levels (Kirkpatrick & Dahlquist 2010).
// 5. Break Detection: Price closes beyond zone in breakout direction with
//    volume > avgVol × breakMult.
//
// RESEARCH BASIS:
//  • Fazen Capital / TrueData (2026), "Volume Profile Trading": HVN (high
//    volume nodes) act as fair-value S/R; volume validates the strength.
//    Key components: POC (Point of Control), Value Area (70% of volume),
//    HVN = support/resistance, LVN = breakout zones.
//  • FasterCapital (2024), "Volume Speaks Volumes": When HVN-aligned historical
//    S/R levels align, significance is reinforced. Breakouts above HVN signal
//    strength; breakdowns below signal weakness.
//  • CMT Association / CFA Institute (2016), "Technical Analysis: Modern
//    Perspectives": VBSR (Volatility-Based Support Resistance) uses volatility
//    extremes for S/R quantification. Event testing validates signal quality.
//  • Kirkpatrick & Dahlquist (2010), "Technical Analysis: The Complete Resource".
//    Support/resistance levels rated 4.41/5 among practitioners — among the most
//    valued technical tools. Volume confirmation improves reliability.
//  • arXiv:2103.12419 (2021), "Explainable ML-driven Strategy for Automated
//    Trading Pattern Extraction": Volume-based patterns outperform price-based
//    patterns in liquid markets (S&P E-mini) because large players make price
//    less noisy. POC serves as classification target.
//  • Wilder (1978), "New Concepts in Technical Trading Systems": ATR = SMA(TR, N)
//    where TR = max(high−low, |high−close[1]|, |low−close[1]|). Adaptive
//    volatility bands are the canonical method for dynamic S/R thickness.
//  • Bhusal (2025), "Timing the Trap" (SSRN 5276088): Stop-hunt zones and
//    engineered liquidity traps around S/R levels; ATR-based invalidation buffer
//    prevents false breakouts from stop hunts.
// ============================================================================

define(title="Volumetric Support and Resistance V2", position="onchart", axis=false)

// ------------------------------------------------------------------------------
// User Inputs — grouped and constrained per production spec
// ------------------------------------------------------------------------------

// --- 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 volLookback = input(name="volLookback", type="number", defaultValue=20, label="Volume Averaging Period", constraints={min: 5, max: 100, step: 1}, group="Pivot Detection")
var volMult = input(name="volMult", type="number", defaultValue=1.5, label="Volume Confirmation Multiplier", constraints={min: 1.0, max: 5.0, step: 0.1}, group="Pivot Detection")

// --- 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 minDistPct = input(name="minDistPct", type="number", defaultValue=1.0, label="Min Distance Between Zones (%)", constraints={min: 0.1, max: 10.0, step: 0.1}, group="Zone Configuration")
var breakMult = input(name="breakMult", type="number", defaultValue=1.0, label="Break Confirmation Volume Multiplier", constraints={min: 0.5, max: 3.0, step: 0.1}, group="Zone Configuration")
var maxAgeBars = input(name="maxAgeBars", type="number", defaultValue=100, label="Max Level Age (bars)", constraints={min: 20, max: 500, step: 10}, group="Zone Configuration")

// --- Display ---
var showZones = input(name="showZones", type="boolean", defaultValue=true, label="Show S/R Zones", group="Display")
var showPivots = input(name="showPivots", type="boolean", defaultValue=true, label="Show Pivot Markers", group="Display")
var showBreaks = input(name="showBreaks", type="boolean", defaultValue=true, label="Show Break Markers", group="Display")
var showStrength = input(name="showStrength", type="boolean", defaultValue=true, label="Show Strength Score", group="Display")
var showLabels = input(name="showLabels", type="boolean", defaultValue=true, label="Show Level Labels", group="Display")

// --- Colors ---
var supColor = input(name="supColor", type="color", defaultValue="#26a69a", label="Support Color", group="Colors")
var resColor = input(name="resColor", type="color", defaultValue="#ef5350", label="Resistance Color", group="Colors")
var supWeakColor = input(name="supWeakColor", type="color", defaultValue="#4db6ac", label="Support Weak Color", group="Colors")
var resWeakColor = input(name="resWeakColor", type="color", defaultValue="#ef9a9a", label="Resistance Weak Color", group="Colors")
var breakColor = input(name="breakColor", type="color", defaultValue="#ffd700", label="Break Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#9e9e9e", label="Neutral Color", group="Colors")

// ------------------------------------------------------------------------------
// Data Sources
// ------------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries px = bars.close
timeseries hi = bars.high
timeseries lo = bars.low
timeseries vol = bars.volume

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

// ------------------------------------------------------------------------------
// 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(px[1]) ? px : px[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

// ------------------------------------------------------------------------------
// Volume Average and Pivot Detection
// ------------------------------------------------------------------------------
timeseries avgVol = sma(vol, volLookback)

// Volume-confirmed pivot detection:
// Pivot high = high at [pivotLen] exceeds all highs in [pivotLen*2+1] window
// AND the pivot bar's volume exceeds the rolling average × multiplier.
// This filters out low-participation noise pivots (Fazen Capital 2026).

var isSwingHigh = hi[pivotLen] == highest(hi, pivotLen * 2 + 1) && hi[pivotLen] > highest(hi, pivotLen) && vol[pivotLen] >= avgVol[pivotLen] * volMult
var isSwingLow = lo[pivotLen] == lowest(lo, pivotLen * 2 + 1) && lo[pivotLen] < lowest(lo, pivotLen) && vol[pivotLen] >= avgVol[pivotLen] * volMult

// Bar counter for event tracking and age calculation
static barCount = 0
if (!isLiveUpdate) {
    barCount = barCount + 1
}

// ------------------------------------------------------------------------------
// Static State: S/R Level Tracking (up to 3 resistance + 3 support levels)
// ------------------------------------------------------------------------------
// Each level stores: price, top, bottom, strength, bar formed, active flag, broken flag

// --- Resistance Levels ---
static res1Price = 0.0
static res1Top = 0.0
static res1Bot = 0.0
static res1Str = 0.0
static res1Bar = 0
static res1Vol = 0.0
static res1Active = 0
static res1Broken = 0

static res2Price = 0.0
static res2Top = 0.0
static res2Bot = 0.0
static res2Str = 0.0
static res2Bar = 0
static res2Vol = 0.0
static res2Active = 0
static res2Broken = 0

static res3Price = 0.0
static res3Top = 0.0
static res3Bot = 0.0
static res3Str = 0.0
static res3Bar = 0
static res3Vol = 0.0
static res3Active = 0
static res3Broken = 0

// --- Support Levels ---
static sup1Price = 0.0
static sup1Top = 0.0
static sup1Bot = 0.0
static sup1Str = 0.0
static sup1Bar = 0
static sup1Vol = 0.0
static sup1Active = 0
static sup1Broken = 0

static sup2Price = 0.0
static sup2Top = 0.0
static sup2Bot = 0.0
static sup2Str = 0.0
static sup2Bar = 0
static sup2Vol = 0.0
static sup2Active = 0
static sup2Broken = 0

static sup3Price = 0.0
static sup3Top = 0.0
static sup3Bot = 0.0
static sup3Str = 0.0
static sup3Bar = 0
static sup3Vol = 0.0
static sup3Active = 0
static sup3Broken = 0

// ------------------------------------------------------------------------------
// Helper: Minimum Distance Check
// ------------------------------------------------------------------------------
// Returns true if newPrice is at least minDistPct away from all existing active levels

var minDist = px * minDistPct / 100.0

function isFarFromExisting(newPrice, existingPrice) {
    return existingPrice == 0.0 || math.abs(newPrice - existingPrice) > minDist
}

function canAddResistance(newPrice) {
    return isFarFromExisting(newPrice, res1Price) && isFarFromExisting(newPrice, res2Price) && isFarFromExisting(newPrice, res3Price)
}

function canAddSupport(newPrice) {
    return isFarFromExisting(newPrice, sup1Price) && isFarFromExisting(newPrice, sup2Price) && isFarFromExisting(newPrice, sup3Price)
}

// ------------------------------------------------------------------------------
// Helper: Volume-Weighted Strength Score
// ------------------------------------------------------------------------------
// Strength = (pivotVolume / avgVolume) × recencyDecay
// where recencyDecay = max(0.3, 1 − barsSince / maxAgeBars)

function calcStrength(pivotVol, pivotBar, currentBar) {
    var volRatio = avgVol > 0 ? pivotVol / avgVol : 1.0
    var barsSince = currentBar - pivotBar
    var recencyDecay = barsSince < maxAgeBars ? 1.0 - (barsSince / maxAgeBars) * 0.7 : 0.3
    return volRatio * recencyDecay
}

// ------------------------------------------------------------------------------
// Helper: Shift levels (FIFO eviction for new level)
// ------------------------------------------------------------------------------

function shiftResLevels() {
    res3Price = res2Price
    res3Top = res2Top
    res3Bot = res2Bot
    res3Str = res2Str
    res3Bar = res2Bar
    res3Vol = res2Vol
    res3Active = res2Active
    res3Broken = res2Broken

    res2Price = res1Price
    res2Top = res1Top
    res2Bot = res1Bot
    res2Str = res1Str
    res2Bar = res1Bar
    res2Vol = res1Vol
    res2Active = res1Active
    res2Broken = res1Broken
}

function shiftSupLevels() {
    sup3Price = sup2Price
    sup3Top = sup2Top
    sup3Bot = sup2Bot
    sup3Str = sup2Str
    sup3Bar = sup2Bar
    sup3Vol = sup2Vol
    sup3Active = sup2Active
    sup3Broken = sup2Broken

    sup2Price = sup1Price
    sup2Top = sup1Top
    sup2Bot = sup1Bot
    sup2Str = sup1Str
    sup2Bar = sup1Bar
    sup2Vol = sup1Vol
    sup2Active = sup1Active
    sup2Broken = sup1Broken
}

// ------------------------------------------------------------------------------
// Helper: Age-based invalidation (levels expire after maxAgeBars)
// ------------------------------------------------------------------------------

function invalidateOldLevels(currentBar) {
    if (res1Active == 1 && currentBar - res1Bar > maxAgeBars) {
        res1Active = 0
    }
    if (res2Active == 1 && currentBar - res2Bar > maxAgeBars) {
        res2Active = 0
    }
    if (res3Active == 1 && currentBar - res3Bar > maxAgeBars) {
        res3Active = 0
    }
    if (sup1Active == 1 && currentBar - sup1Bar > maxAgeBars) {
        sup1Active = 0
    }
    if (sup2Active == 1 && currentBar - sup2Bar > maxAgeBars) {
        sup2Active = 0
    }
    if (sup3Active == 1 && currentBar - sup3Bar > maxAgeBars) {
        sup3Active = 0
    }
}

// ------------------------------------------------------------------------------
// Helper: Break detection
// ------------------------------------------------------------------------------
// Break confirmed when price closes beyond zone boundary AND volume > avgVol × breakMult

function checkBreaks() {
    // Resistance breaks: close above top with volume confirmation
    if (res1Active == 1 && res1Broken == 0 && px > res1Top && vol >= avgVol * breakMult) {
        res1Broken = 1
    }
    if (res2Active == 1 && res2Broken == 0 && px > res2Top && vol >= avgVol * breakMult) {
        res2Broken = 1
    }
    if (res3Active == 1 && res3Broken == 0 && px > res3Top && vol >= avgVol * breakMult) {
        res3Broken = 1
    }
    // Support breaks: close below bottom with volume confirmation
    if (sup1Active == 1 && sup1Broken == 0 && px < sup1Bot && vol >= avgVol * breakMult) {
        sup1Broken = 1
    }
    if (sup2Active == 1 && sup2Broken == 0 && px < sup2Bot && vol >= avgVol * breakMult) {
        sup2Broken = 1
    }
    if (sup3Active == 1 && sup3Broken == 0 && px < sup3Bot && vol >= avgVol * breakMult) {
        sup3Broken = 1
    }
}

// ------------------------------------------------------------------------------
// State Update (only on bar close to ensure consistency)
// ------------------------------------------------------------------------------

if (!isLiveUpdate) {
    // Age-based invalidation first
    invalidateOldLevels(barCount)

    // Break detection
    checkBreaks()

    // New resistance level formation on confirmed swing high
    if (isSwingHigh) {
        var swingPrice = hi[pivotLen]
        var swingVol = vol[pivotLen]

        if (canAddResistance(swingPrice)) {
            shiftResLevels()
            res1Price = swingPrice
            res1Top = swingPrice + atrPad
            res1Bot = swingPrice - atrPad
            res1Str = calcStrength(swingVol, barCount - pivotLen, barCount)
            res1Bar = barCount - pivotLen
            res1Vol = swingVol
            res1Active = 1
            res1Broken = 0
        }
    }

    // New support level formation on confirmed swing low
    if (isSwingLow) {
        var swingPrice = lo[pivotLen]
        var swingVol = vol[pivotLen]

        if (canAddSupport(swingPrice)) {
            shiftSupLevels()
            sup1Price = swingPrice
            sup1Top = swingPrice + atrPad
            sup1Bot = swingPrice - atrPad
            sup1Str = calcStrength(swingVol, barCount - pivotLen, barCount)
            sup1Bar = barCount - pivotLen
            sup1Vol = swingVol
            sup1Active = 1
            sup1Broken = 0
        }
    }

    // Update strength scores on every bar (recency decay)
    if (res1Active == 1) {
        res1Str = calcStrength(res1Vol, res1Bar, barCount)
    }
    if (res2Active == 1) {
        res2Str = calcStrength(res2Vol, res2Bar, barCount)
    }
    if (res3Active == 1) {
        res3Str = calcStrength(res3Vol, res3Bar, barCount)
    }
    if (sup1Active == 1) {
        sup1Str = calcStrength(sup1Vol, sup1Bar, barCount)
    }
    if (sup2Active == 1) {
        sup2Str = calcStrength(sup2Vol, sup2Bar, barCount)
    }
    if (sup3Active == 1) {
        sup3Str = calcStrength(sup3Vol, sup3Bar, barCount)
    }
}

// ------------------------------------------------------------------------------
// Event Flags for Plotting
// ------------------------------------------------------------------------------

var newResEvent = isSwingHigh && barCount > pivotLen
var newSupEvent = isSwingLow && barCount > pivotLen

var res1BreakEvent = res1Broken == 1 && barCount - res1Bar <= maxAgeBars && px > res1Top && vol >= avgVol * breakMult
var res2BreakEvent = res2Broken == 1 && barCount - res2Bar <= maxAgeBars && px > res2Top && vol >= avgVol * breakMult
var res3BreakEvent = res3Broken == 1 && barCount - res3Bar <= maxAgeBars && px > res3Top && vol >= avgVol * breakMult
var sup1BreakEvent = sup1Broken == 1 && barCount - sup1Bar <= maxAgeBars && px < sup1Bot && vol >= avgVol * breakMult
var sup2BreakEvent = sup2Broken == 1 && barCount - sup2Bar <= maxAgeBars && px < sup2Bot && vol >= avgVol * breakMult
var sup3BreakEvent = sup3Broken == 1 && barCount - sup3Bar <= maxAgeBars && px < sup3Bot && vol >= avgVol * breakMult

// ------------------------------------------------------------------------------
// Plots: Resistance Zones (plotLine with fill)
// ------------------------------------------------------------------------------

if (showZones && res1Active == 1) {
    var r1Color = res1Broken == 1 ? resWeakColor : resColor
    var r1FillOpacity = res1Broken == 1 ? opacity(resWeakColor, 20) : opacity(resColor, 30)
    plotLine(
        value=[res1Top, res1Bot],
        width=1,
        colors=[r1Color, r1Color],
        fill=r1FillOpacity,
        label=["R1 Zone", "R1 Zone"],
        desc=["Resistance zone 1 top (ATR-padded, volume-confirmed pivot)", "Resistance zone 1 bottom"]
    )
    if (showLabels) {
        plotLine(
            value=res1Price,
            width=1,
            colors=[r1Color],
            label=["R1"],
            desc=["Resistance level 1: volume-confirmed pivot high with ATR padding"]
        )
    }
}

if (showZones && res2Active == 1) {
    var r2Color = res2Broken == 1 ? resWeakColor : resColor
    var r2FillOpacity = res2Broken == 1 ? opacity(resWeakColor, 20) : opacity(resColor, 25)
    plotLine(
        value=[res2Top, res2Bot],
        width=1,
        colors=[r2Color, r2Color],
        fill=r2FillOpacity,
        label=["R2 Zone", "R2 Zone"],
        desc=["Resistance zone 2 top (ATR-padded, volume-confirmed pivot)", "Resistance zone 2 bottom"]
    )
    if (showLabels) {
        plotLine(
            value=res2Price,
            width=1,
            colors=[r2Color],
            label=["R2"],
            desc=["Resistance level 2: volume-confirmed pivot high with ATR padding"]
        )
    }
}

if (showZones && res3Active == 1) {
    var r3Color = res3Broken == 1 ? resWeakColor : resColor
    var r3FillOpacity = res3Broken == 1 ? opacity(resWeakColor, 20) : opacity(resColor, 20)
    plotLine(
        value=[res3Top, res3Bot],
        width=1,
        colors=[r3Color, r3Color],
        fill=r3FillOpacity,
        label=["R3 Zone", "R3 Zone"],
        desc=["Resistance zone 3 top (ATR-padded, volume-confirmed pivot)", "Resistance zone 3 bottom"]
    )
    if (showLabels) {
        plotLine(
            value=res3Price,
            width=1,
            colors=[r3Color],
            label=["R3"],
            desc=["Resistance level 3: volume-confirmed pivot high with ATR padding"]
        )
    }
}

// ------------------------------------------------------------------------------
// Plots: Support Zones (plotLine with fill)
// ------------------------------------------------------------------------------

if (showZones && sup1Active == 1) {
    var s1Color = sup1Broken == 1 ? supWeakColor : supColor
    var s1FillOpacity = sup1Broken == 1 ? opacity(supWeakColor, 20) : opacity(supColor, 30)
    plotLine(
        value=[sup1Top, sup1Bot],
        width=1,
        colors=[s1Color, s1Color],
        fill=s1FillOpacity,
        label=["S1 Zone", "S1 Zone"],
        desc=["Support zone 1 top (ATR-padded, volume-confirmed pivot)", "Support zone 1 bottom"]
    )
    if (showLabels) {
        plotLine(
            value=sup1Price,
            width=1,
            colors=[s1Color],
            label=["S1"],
            desc=["Support level 1: volume-confirmed pivot low with ATR padding"]
        )
    }
}

if (showZones && sup2Active == 1) {
    var s2Color = sup2Broken == 1 ? supWeakColor : supColor
    var s2FillOpacity = sup2Broken == 1 ? opacity(supWeakColor, 20) : opacity(supColor, 25)
    plotLine(
        value=[sup2Top, sup2Bot],
        width=1,
        colors=[s2Color, s2Color],
        fill=s2FillOpacity,
        label=["S2 Zone", "S2 Zone"],
        desc=["Support zone 2 top (ATR-padded, volume-confirmed pivot)", "Support zone 2 bottom"]
    )
    if (showLabels) {
        plotLine(
            value=sup2Price,
            width=1,
            colors=[s2Color],
            label=["S2"],
            desc=["Support level 2: volume-confirmed pivot low with ATR padding"]
        )
    }
}

if (showZones && sup3Active == 1) {
    var s3Color = sup3Broken == 1 ? supWeakColor : supColor
    var s3FillOpacity = sup3Broken == 1 ? opacity(supWeakColor, 20) : opacity(supColor, 20)
    plotLine(
        value=[sup3Top, sup3Bot],
        width=1,
        colors=[s3Color, s3Color],
        fill=s3FillOpacity,
        label=["S3 Zone", "S3 Zone"],
        desc=["Support zone 3 top (ATR-padded, volume-confirmed pivot)", "Support zone 3 bottom"]
    )
    if (showLabels) {
        plotLine(
            value=sup3Price,
            width=1,
            colors=[s3Color],
            label=["S3"],
            desc=["Support level 3: volume-confirmed pivot low with ATR padding"]
        )
    }
}

// ------------------------------------------------------------------------------
// Plots: Pivot Markers (plotShape)
// ------------------------------------------------------------------------------

if (showPivots && newResEvent) {
    plotShape(
        value=hi[pivotLen],
        shape="triangleup",
        color=resColor,
        width=3,
        label=["Res Pivot"],
        desc=["Volume-confirmed resistance pivot: high exceeds surrounding bars with above-average volume"]
    )
}

if (showPivots && newSupEvent) {
    plotShape(
        value=lo[pivotLen],
        shape="triangledown",
        color=supColor,
        width=3,
        label=["Sup Pivot"],
        desc=["Volume-confirmed support pivot: low below surrounding bars with above-average volume"]
    )
}

// ------------------------------------------------------------------------------
// Plots: Break Markers (plotShape)
// ------------------------------------------------------------------------------

if (showBreaks && res1BreakEvent) {
    plotShape(
        value=px,
        shape="cross",
        color=breakColor,
        width=4,
        label=["R1 Break"],
        desc=["Resistance level 1 broken with volume confirmation — bullish breakout signal"]
    )
}
if (showBreaks && res2BreakEvent) {
    plotShape(
        value=px,
        shape="cross",
        color=breakColor,
        width=4,
        label=["R2 Break"],
        desc=["Resistance level 2 broken with volume confirmation — bullish breakout signal"]
    )
}
if (showBreaks && res3BreakEvent) {
    plotShape(
        value=px,
        shape="cross",
        color=breakColor,
        width=4,
        label=["R3 Break"],
        desc=["Resistance level 3 broken with volume confirmation — bullish breakout signal"]
    )
}
if (showBreaks && sup1BreakEvent) {
    plotShape(
        value=px,
        shape="cross",
        color=breakColor,
        width=4,
        label=["S1 Break"],
        desc=["Support level 1 broken with volume confirmation — bearish breakdown signal"]
    )
}
if (showBreaks && sup2BreakEvent) {
    plotShape(
        value=px,
        shape="cross",
        color=breakColor,
        width=4,
        label=["S2 Break"],
        desc=["Support level 2 broken with volume confirmation — bearish breakdown signal"]
    )
}
if (showBreaks && sup3BreakEvent) {
    plotShape(
        value=px,
        shape="cross",
        color=breakColor,
        width=4,
        label=["S3 Break"],
        desc=["Support level 3 broken with volume confirmation — bearish breakdown signal"]
    )
}

// ------------------------------------------------------------------------------
// Plots: Strength Score (plotBar histogram)
// ------------------------------------------------------------------------------
// Displays the combined strength of active S/R levels as a background indicator.

if (showStrength) {
    var totalStrength = 0.0
    if (res1Active == 1 && res1Broken == 0) {
        totalStrength = totalStrength + res1Str
    }
    if (res2Active == 1 && res2Broken == 0) {
        totalStrength = totalStrength + res2Str
    }
    if (res3Active == 1 && res3Broken == 0) {
        totalStrength = totalStrength + res3Str
    }
    if (sup1Active == 1 && sup1Broken == 0) {
        totalStrength = totalStrength + sup1Str
    }
    if (sup2Active == 1 && sup2Broken == 0) {
        totalStrength = totalStrength + sup2Str
    }
    if (sup3Active == 1 && sup3Broken == 0) {
        totalStrength = totalStrength + sup3Str
    }

    plotBar(
        value=totalStrength,
        colors=[neutralColor],
        width=1,
        label=["S/R Strength"],
        desc=["Combined volume-weighted strength of active S/R levels (recency-decayed)"]
    )
}