MM Flow
FlowScripts

Perfected FlowScript

Order Blocks

Order Blocks — SMC & Market Structure is indexed as 027_order_blocks.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

21.9 KB

Lines

547

Native Signal Candidates

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

9/9 guarded

Bull OB Formed

line 377:9

Trigger

(showOBZones && bullOBActive == 1) && (showOBLabels && bullOBBar == barCount)

Value

bullOBTop

Deps

barCount:static, bullOBActive:static, bullOBBar:static, showOBLabels:input, showOBZones:input

Bear OB Formed

line 420:9

Trigger

(showOBZones && bearOBActive == 1) && (showOBLabels && bearOBBar == barCount)

Value

bearOBTop

Deps

barCount:static, bearOBActive:static, bearOBBar:static, showOBLabels:input, showOBZones:input

Bull BOS

line 469:5

Trigger

(showBOSMarkers && bullBOSEvent)

Value

lastHigh

Deps

bullBOSEvent:var, showBOSMarkers:input

Bear BOS

line 479:5

Trigger

(showBOSMarkers && bearBOSEvent)

Value

lastLow

Deps

bearBOSEvent:var, showBOSMarkers:input

Bull ChoCH

line 489:5

Trigger

(showChoCHMarkers && bullChoCHEvent)

Value

lastHigh

Deps

bullChoCHEvent:var, showChoCHMarkers:input

Bear ChoCH

line 499:5

Trigger

(showChoCHMarkers && bearChoCHEvent)

Value

lastLow

Deps

bearChoCHEvent:var, showChoCHMarkers:input

Bull OB Mitigated

line 512:9

Trigger

(showMitigationMarkers && bullOBActive == 1 && bullOBMitigated == 1 && bullOBBar != barCount) && (lo <= bullOBTop && hi >= bullOBBot)

Value

bullOBBot

Deps

barCount:static, bullOBActive:static, bullOBBar:static, bullOBBot:static, bullOBMitigated:static, bullOBTop:static, hi:timeseries, lo:timeseries, showMitigationMarkers:input

Bear OB Mitigated

line 524:9

Trigger

(showMitigationMarkers && bearOBActive == 1 && bearOBMitigated == 1 && bearOBBar != barCount) && (hi >= bearOBBot && lo <= bearOBTop)

Value

bearOBTop

Deps

barCount:static, bearOBActive:static, bearOBBar:static, bearOBBot:static, bearOBMitigated:static, bearOBTop:static, hi:timeseries, lo:timeseries, showMitigationMarkers:input

Unlabeled shape

line 537:5

Trigger

(showTrendLabel && isLastBar)

Value

hi

Deps

isLastBar:builtin, showTrendLabel:input

027_order_blocks.flowscript

source path: kscripts/perfected/pilot/027_order_blocks.flowscript · sha256:ff070978bc7a679c234bd586caca21e83925ca33fea322381a54533f77623d02

hash verified
//@version=2
// ============================================================================
// Order Blocks — Smart Money Concepts & Market Structure
// Author: BackQuant (@BackQuant) — Perfected Edition
// Tags: CORE, #orderblock, #smc, #marketstructure, #bos, #choch, #fvg
//
// Production-grade order block detector with swing-point confirmation,
// Break of Structure (BOS), Change of Character (ChoCH), Fair Value Gap (FVG)
// detection, ATR-based zone padding, mitigation tracking, and invalidation.
//
// Academic foundations:
//  - Campbell, Ramadorai & Vuolteenaho (2005), "Caught On Tape: Institutional
//    Order Flow and Stock Returns" (NBER 11439). Regression method achieves
//    ~12% R² in predicting institutional ownership changes from trade patterns.
//    Key formula: ΔInstOwn_t = α + β₁·BuyVol_t + β₂·SellVol_t + ε_t.
//    Supports Order Blocks as institutional accumulation/distribution zones.
//  - Jones & Lipson (2005), "Are Retail Orders Different?" Countervailing
//    institutional flow: 1,000 retail shares → 400+ institutional shares opposite
//    within 5 minutes. Validates smart-money exploitation of retail liquidity.
//  - Biais, Glosten & Spatt (2005), "Market Microstructure: A Survey"
//    (J. Financial Markets, 699+ citations). Framework: latent demands
//    D(p) → realized prices/volumes via λ·ΣX_i, where λ = price impact
//    coefficient (Kyle 1985). Explains why Order Blocks and FVGs exist as
//    price-discovery inefficiencies.
//  - 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.
//  - Pecchiari (2020), "Orderflow Imbalance and High Frequency Trading"
//    (LUISS Thesis). Quantile regression: OFI_t = γ₀ + γ₁·|ΔBid_t| +
//    γ₂·|ΔAsk_t| + γ₃·Vol_t + u_t. FVGs manifest as order-flow imbalance
//    signatures.
// ============================================================================

define(title="Order Blocks — SMC & Market Structure", position="onchart", axis=false)

// === USER INPUTS ===
// --- Swing Detection ---
var pivotLen = input(name="pivotLen", type="number", defaultValue=5, label="Pivot Length (each side)", constraints={min: 2, max: 50, step: 1}, group="Swing Detection")
var showSwingLevels = input(name="showSwingLevels", type="boolean", defaultValue=true, label="Show Swing High/Low Lines", group="Swing Detection")

// --- Order Blocks ---
var searchBack = input(name="searchBack", type="number", defaultValue=10, label="OB Search Back Window", constraints={min: 3, max: 50, step: 1}, group="Order Blocks")
var atrLen = input(name="atrLen", type="number", defaultValue=14, label="ATR Length", constraints={min: 5, max: 100, step: 1}, group="Order Blocks")
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="Order Blocks")
var invalidMult = input(name="invalidMult", type="number", defaultValue=1.0, label="Invalidation Buffer (ATR Multiple)", constraints={min: 0.0, max: 5.0, step: 0.1}, group="Order Blocks")
var showOBZones = input(name="showOBZones", type="boolean", defaultValue=true, label="Show Order Block Zones", group="Order Blocks")
var showOBLabels = input(name="showOBLabels", type="boolean", defaultValue=true, label="Show OB Formation Labels", group="Order Blocks")
var showMitigated = input(name="showMitigated", type="boolean", defaultValue=true, label="Show Mitigated Zones", group="Order Blocks")
var showInvalidated = input(name="showInvalidated", type="boolean", defaultValue=true, label="Show Invalidated Zones (Gray)", group="Order Blocks")

// --- FVG ---
var showFVG = input(name="showFVG", type="boolean", defaultValue=true, label="Show Fair Value Gaps", group="FVG")
var fvgMinSize = input(name="fvgMinSize", type="number", defaultValue=0.0, label="Minimum FVG Size (price units)", constraints={min: 0.0, max: 1000.0, step: 0.1}, group="FVG")

// --- Display ---
var showBOSMarkers = input(name="showBOSMarkers", type="boolean", defaultValue=true, label="Show BOS Markers", group="Display")
var showChoCHMarkers = input(name="showChoCHMarkers", type="boolean", defaultValue=true, label="Show ChoCH Markers", group="Display")
var showMitigationMarkers = input(name="showMitigationMarkers", type="boolean", defaultValue=true, label="Show Mitigation Markers", group="Display")
var showTrendLabel = input(name="showTrendLabel", type="boolean", defaultValue=true, label="Show Trend State Label", group="Display")
var showFVGBar = input(name="showFVGBar", type="boolean", defaultValue=true, label="Show FVG Size Histogram", group="Display")

// --- Colors ---
var bullColor = input(name="bullColor", type="color", defaultValue="#26a69a", label="Bullish OB Color", group="Colors")
var bearColor = input(name="bearColor", type="color", defaultValue="#ef5350", label="Bearish OB Color", group="Colors")
var bullWeakColor = input(name="bullWeakColor", type="color", defaultValue="#4db6ac", label="Bullish OB Mitigated Color", group="Colors")
var bearWeakColor = input(name="bearWeakColor", type="color", defaultValue="#ef9a9a", label="Bearish OB Mitigated Color", group="Colors")
var invalidColor = input(name="invalidColor", type="color", defaultValue="#9e9e9e", label="Invalidated OB Color", group="Colors")
var bosColor = input(name="bosColor", type="color", defaultValue="#ffd700", label="BOS Marker Color", group="Colors")
var chochColor = input(name="chochColor", type="color", defaultValue="#ff00ff", label="ChoCH Marker Color", group="Colors")
var fvgBullColor = input(name="fvgBullColor", type="color", defaultValue="#00ff00", label="Bullish FVG Color", group="Colors")
var fvgBearColor = input(name="fvgBearColor", type="color", defaultValue="#ff0000", label="Bearish FVG 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

// 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])) {
    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 invalidBuffer = atr * invalidMult

// 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)

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

// --- STATIC STATE: Market Structure ---
// Last and previous confirmed swing levels for BOS / ChoCH detection.
static lastHigh = 0.0
static lastLow = 0.0
static prevHigh = 0.0
static prevLow = 0.0
static trend = 0  // 1 = bullish, -1 = bearish

// --- STATIC STATE: BOS / ChoCH Events ---
// Bar indices where events occurred (0 = never).
static bullBOSBar = 0
static bearBOSBar = 0
static bullChoCHBar = 0
static bearChoCHBar = 0

// --- STATIC STATE: Bullish Order Block ---
static bullOBActive = 0
static bullOBTop = 0.0
static bullOBBot = 0.0
static bullOBBar = 0
static bullOBMitigated = 0
static bullOBInvalidated = 0

// --- STATIC STATE: Bearish Order Block ---
static bearOBActive = 0
static bearOBTop = 0.0
static bearOBBot = 0.0
static bearOBBar = 0
static bearOBMitigated = 0
static bearOBInvalidated = 0

// --- STATIC STATE: Last Opposing Candle (for OB identification) ---
// After a bullish BOS, the last bearish candle before the break is the OB.
// After a bearish BOS, the last bullish candle before the break is the OB.
static lastBearHigh = 0.0
static lastBearLow = 0.0
static lastBearBar = 0
static lastBullHigh = 0.0
static lastBullLow = 0.0
static lastBullBar = 0

// --- STATIC STATE: FVG (Fair Value Gap) ---
// Three-candle imbalance pattern: bullish FVG = low[0] > high[2];
// bearish FVG = high[0] < low[2].
static fvgBullTop = 0.0
static fvgBullBot = 0.0
static fvgBullActive = 0
static fvgBearTop = 0.0
static fvgBearBot = 0.0
static fvgBearActive = 0

// FVG detection (computed every bar, but only stored on close).
var bullishFVG = !isnan(hi[2]) && lo > hi[2] && (lo - hi[2]) >= fvgMinSize
var bearishFVG = !isnan(lo[2]) && hi < lo[2] && (lo[2] - hi) >= fvgMinSize

// --- STATE UPDATE (only on bar close) ---
// All stateful transitions happen here to ensure consistency.
if (!isLiveUpdate) {
    // Track last opposing candles for OB identification.
    if (cl < op) {
        lastBearHigh = hi
        lastBearLow = lo
        lastBearBar = barCount
    }
    if (cl > op) {
        lastBullHigh = hi
        lastBullLow = lo
        lastBullBar = barCount
    }

    // Swing detection and market structure classification.
    // BOS = continuation of current trend (higher high in uptrend, lower low in downtrend).
    // ChoCH = reversal of current trend (higher high after downtrend, lower low after uptrend).
    if (isSwingHigh) {
        // Shift swing highs: previous becomes prevHigh, current becomes lastHigh.
        if (lastHigh > 0) {
            prevHigh = lastHigh
        }
        lastHigh = hi[pivotLen]

        // Determine BOS or ChoCH and spawn bullish OB from last opposing candle.
        if (trend == 1 && prevHigh > 0 && lastHigh > prevHigh) {
            bullBOSBar = barCount
            // Bullish BOS: last bearish candle within search window becomes bullish OB.
            if (lastBearBar > 0 && barCount - lastBearBar <= searchBack + pivotLen) {
                bullOBTop = lastBearHigh + atrPad
                bullOBBot = lastBearLow - atrPad
                bullOBBar = lastBearBar
                bullOBActive = 1
                bullOBMitigated = 0
                bullOBInvalidated = 0
            }
        } else if (trend == -1 && prevHigh > 0 && lastHigh > prevHigh) {
            bullChoCHBar = barCount
            trend = 1
            // Bullish ChoCH: last bearish candle within search window becomes bullish OB.
            if (lastBearBar > 0 && barCount - lastBearBar <= searchBack + pivotLen) {
                bullOBTop = lastBearHigh + atrPad
                bullOBBot = lastBearLow - atrPad
                bullOBBar = lastBearBar
                bullOBActive = 1
                bullOBMitigated = 0
                bullOBInvalidated = 0
            }
        } else if (trend == 0) {
            trend = 1
        }
    }

    if (isSwingLow) {
        // Shift swing lows: previous becomes prevLow, current becomes lastLow.
        if (lastLow > 0) {
            prevLow = lastLow
        }
        lastLow = lo[pivotLen]

        // Determine BOS or ChoCH and spawn bearish OB from last opposing candle.
        if (trend == -1 && prevLow > 0 && lastLow < prevLow) {
            bearBOSBar = barCount
            // Bearish BOS: last bullish candle within search window becomes bearish OB.
            if (lastBullBar > 0 && barCount - lastBullBar <= searchBack + pivotLen) {
                bearOBTop = lastBullHigh + atrPad
                bearOBBot = lastBullLow - atrPad
                bearOBBar = lastBullBar
                bearOBActive = 1
                bearOBMitigated = 0
                bearOBInvalidated = 0
            }
        } else if (trend == 1 && prevLow > 0 && lastLow < prevLow) {
            bearChoCHBar = barCount
            trend = -1
            // Bearish ChoCH: last bullish candle within search window becomes bearish OB.
            if (lastBullBar > 0 && barCount - lastBullBar <= searchBack + pivotLen) {
                bearOBTop = lastBullHigh + atrPad
                bearOBBot = lastBullLow - atrPad
                bearOBBar = lastBullBar
                bearOBActive = 1
                bearOBMitigated = 0
                bearOBInvalidated = 0
            }
        } else if (trend == 0) {
            trend = -1
        }
    }

    // OB Mitigation: price returns to the zone (touches or enters).
    if (bullOBActive == 1 && bullOBInvalidated == 0) {
        if (lo <= bullOBTop && hi >= bullOBBot) {
            bullOBMitigated = 1
        }
    }
    if (bearOBActive == 1 && bearOBInvalidated == 0) {
        if (hi >= bearOBBot && lo <= bearOBTop) {
            bearOBMitigated = 1
        }
    }

    // OB Invalidation: price breaks through the zone in the wrong direction
    // with an ATR-scaled buffer (Bhusal 2025 stop-hunt zone logic).
    if (bullOBActive == 1 && bullOBInvalidated == 0) {
        if (lo < bullOBBot - invalidBuffer) {
            bullOBInvalidated = 1
        }
    }
    if (bearOBActive == 1 && bearOBInvalidated == 0) {
        if (hi > bearOBTop + invalidBuffer) {
            bearOBInvalidated = 1
        }
    }

    // FVG detection and tracking.
    if (bullishFVG) {
        fvgBullTop = lo
        fvgBullBot = hi[2]
        fvgBullActive = 1
    }
    if (bearishFVG) {
        fvgBearTop = lo[2]
        fvgBearBot = hi
        fvgBearActive = 1
    }

    // FVG fill detection: gap is closed when price crosses into the imbalance zone.
    if (fvgBullActive == 1 && lo <= fvgBullBot) {
        fvgBullActive = 0
    }
    if (fvgBearActive == 1 && hi >= fvgBearTop) {
        fvgBearActive = 0
    }
}

// === EVENT FLAGS FOR PLOTTING ===
var bullBOSEvent = bullBOSBar == barCount
var bearBOSEvent = bearBOSBar == barCount
var bullChoCHEvent = bullChoCHBar == barCount
var bearChoCHEvent = bearChoCHBar == barCount

// Regime detection for color coding.
var regimeColor = trend == 1 ? bullColor : (trend == -1 ? bearColor : "#ffffff")
var regimeLabel = trend == 1 ? "BULLISH STRUCTURE" : (trend == -1 ? "BEARISH STRUCTURE" : "NEUTRAL")

// FVG size for plotBar histogram.
var fvgSize = 0.0
if (fvgBullActive == 1) {
    fvgSize = fvgBullTop - fvgBullBot
} else if (fvgBearActive == 1) {
    fvgSize = fvgBearTop - fvgBearBot
}

// === PLOTS: SWING LEVELS (plotLine) ===
if (showSwingLevels && lastHigh > 0) {
    plotLine(
        value=lastHigh,
        width=1,
        colors=["#ffffff40"],
        label=["Swing High"],
        desc=["Last confirmed swing high. Confirmed after right-side bars close below it."]
    )
}
if (showSwingLevels && lastLow > 0) {
    plotLine(
        value=lastLow,
        width=1,
        colors=["#ffffff40"],
        label=["Swing Low"],
        desc=["Last confirmed swing low. Confirmed after right-side bars close above it."]
    )
}

// === PLOTS: ORDER BLOCK ZONES (plotLine with fill — boxes) ===
// Bullish OB: supply turned demand zone. Color-coded by regime (active / mitigated / invalidated).
if (showOBZones && bullOBActive == 1) {
    var bullTopColor = bullOBInvalidated == 1 ? invalidColor : (bullOBMitigated == 1 ? bullWeakColor : bullColor)
    var bullBotColor = bullOBInvalidated == 1 ? invalidColor : (bullOBMitigated == 1 ? bullWeakColor : bullColor)
    var bullFillOpacity = bullOBInvalidated == 1 ? opacity(invalidColor, 30) : (bullOBMitigated == 1 ? opacity(bullWeakColor, 40) : opacity(bullColor, 50))

    if (bullOBInvalidated == 0 || showInvalidated) {
        // Top and bottom boundaries as a filled box (plotLine array + fill).
        plotLine(
            value=[bullOBTop, bullOBBot],
            width=1,
            colors=[bullTopColor, bullBotColor],
            fill=bullFillOpacity,
            label=["Bull OB Zone", "Bull OB Zone"],
            desc=["Top boundary of bullish order block (supply turned demand). ATR-padded.", "Bottom boundary of bullish order block."]
        )
        // Explicit boundary lines for clarity.
        plotLine(
            value=bullOBTop,
            width=1,
            colors=[bullTopColor],
            label=["Bull OB Top"],
            desc=["Top boundary of bullish order block."]
        )
        plotLine(
            value=bullOBBot,
            width=1,
            colors=[bullBotColor],
            label=["Bull OB Bot"],
            desc=["Bottom boundary of bullish order block."]
        )
    }

    if (showOBLabels && bullOBBar == barCount) {
        plotShape(
            value=bullOBTop,
            shape="rectangle",
            colorIndex=bullTopColor,
            width=4,
            label=["Bull OB Formed"],
            desc=["Bullish order block formed at break of structure. Last bearish candle before the break."]
        )
    }
}

// Bearish OB: demand turned supply zone.
if (showOBZones && bearOBActive == 1) {
    var bearTopColor = bearOBInvalidated == 1 ? invalidColor : (bearOBMitigated == 1 ? bearWeakColor : bearColor)
    var bearBotColor = bearOBInvalidated == 1 ? invalidColor : (bearOBMitigated == 1 ? bearWeakColor : bearColor)
    var bearFillOpacity = bearOBInvalidated == 1 ? opacity(invalidColor, 30) : (bearOBMitigated == 1 ? opacity(bearWeakColor, 40) : opacity(bearColor, 50))

    if (bearOBInvalidated == 0 || showInvalidated) {
        plotLine(
            value=[bearOBTop, bearOBBot],
            width=1,
            colors=[bearTopColor, bearBotColor],
            fill=bearFillOpacity,
            label=["Bear OB Zone", "Bear OB Zone"],
            desc=["Top boundary of bearish order block (demand turned supply). ATR-padded.", "Bottom boundary of bearish order block."]
        )
        plotLine(
            value=bearOBTop,
            width=1,
            colors=[bearTopColor],
            label=["Bear OB Top"],
            desc=["Top boundary of bearish order block."]
        )
        plotLine(
            value=bearOBBot,
            width=1,
            colors=[bearBotColor],
            label=["Bear OB Bot"],
            desc=["Bottom boundary of bearish order block."]
        )
    }

    if (showOBLabels && bearOBBar == barCount) {
        plotShape(
            value=bearOBTop,
            shape="rectangle",
            colorIndex=bearTopColor,
            width=4,
            label=["Bear OB Formed"],
            desc=["Bearish order block formed at break of structure. Last bullish candle before the break."]
        )
    }
}

// === PLOTS: FVG ZONES (plotLine with fill) ===
if (showFVG && fvgBullActive == 1) {
    var fvgBullFill = opacity(fvgBullColor, 40)
    plotLine(
        value=[fvgBullTop, fvgBullBot],
        width=1,
        colors=[fvgBullColor, fvgBullColor],
        fill=fvgBullFill,
        label=["Bull FVG", "Bull FVG"],
        desc=["Bullish Fair Value Gap: low[0] > high[2]. Unfilled demand imbalance.", "Bullish FVG bottom boundary."]
    )
}

if (showFVG && fvgBearActive == 1) {
    var fvgBearFill = opacity(fvgBearColor, 40)
    plotLine(
        value=[fvgBearTop, fvgBearBot],
        width=1,
        colors=[fvgBearColor, fvgBearColor],
        fill=fvgBearFill,
        label=["Bear FVG", "Bear FVG"],
        desc=["Bearish Fair Value Gap: high[0] < low[2]. Unfilled supply imbalance.", "Bearish FVG bottom boundary."]
    )
}

// === PLOTS: FVG SIZE (plotBar) ===
if (showFVGBar && fvgSize > 0) {
    var fvgBarColor = fvgBullActive == 1 ? fvgBullColor : fvgBearColor
    plotBar(
        value=fvgSize,
        colors=[fvgBarColor],
        label=["FVG Size"],
        desc=["Fair Value Gap size in price units. Three-candle imbalance signature."]
    )
}

// === PLOTS: BOS / ChoCH MARKERS (plotShape) ===
if (showBOSMarkers && bullBOSEvent) {
    plotShape(
        value=lastHigh,
        shape="triangleup",
        colorIndex=bosColor,
        width=6,
        label=["Bull BOS"],
        desc=["Bullish Break of Structure: close above previous swing high in uptrend."]
    )
}
if (showBOSMarkers && bearBOSEvent) {
    plotShape(
        value=lastLow,
        shape="rectangle",
        colorIndex=bosColor,
        width=6,
        label=["Bear BOS"],
        desc=["Bearish Break of Structure: close below previous swing low in downtrend."]
    )
}
if (showChoCHMarkers && bullChoCHEvent) {
    plotShape(
        value=lastHigh,
        shape="triangleup",
        colorIndex=chochColor,
        width=6,
        label=["Bull ChoCH"],
        desc=["Bullish Change of Character: higher high after lower lows. Trend reversal signal."]
    )
}
if (showChoCHMarkers && bearChoCHEvent) {
    plotShape(
        value=lastLow,
        shape="rectangle",
        colorIndex=chochColor,
        width=6,
        label=["Bear ChoCH"],
        desc=["Bearish Change of Character: lower low after higher highs. Trend reversal signal."]
    )
}

// === PLOTS: MITIGATION MARKERS (plotShape) ===
if (showMitigationMarkers && bullOBActive == 1 && bullOBMitigated == 1 && bullOBBar != barCount) {
    if (lo <= bullOBTop && hi >= bullOBBot) {
        plotShape(
            value=bullOBBot,
            shape="rectangle",
            colorIndex=bullWeakColor,
            width=3,
            label=["Bull OB Mitigated"],
            desc=["Price returned to bullish order block zone and respected it."]
        )
    }
}
if (showMitigationMarkers && bearOBActive == 1 && bearOBMitigated == 1 && bearOBBar != barCount) {
    if (hi >= bearOBBot && lo <= bearOBTop) {
        plotShape(
            value=bearOBTop,
            shape="rectangle",
            colorIndex=bearWeakColor,
            width=3,
            label=["Bear OB Mitigated"],
            desc=["Price returned to bearish order block zone and respected it."]
        )
    }
}

// === REGIME LABEL (plotPriceLabel) ===
if (showTrendLabel && isLastBar) {
    plotPriceLabel(
        price=hi,
        text=regimeLabel,
        type="callout",
        color="#ffffff",
        backgroundColor=regimeColor,
        size=10,
        fontWeight=700
    )
}