MM Flow
FlowScripts

Perfected FlowScript

(SMC MSS/BOS/ChoCH) Market Structure

SMC Market Structure (MSS/BOS/ChoCH) — Perfected Edition is indexed as 146_smc_mss_bos_choch_market_structure.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

18.7 KB

Lines

542

Native Signal Candidates

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

7/7 guarded

Bull BOS

line 433:5

Trigger

(showBosMarkers && bullBosEvent)

Value

lastHigh

Deps

bullBosEvent:var, showBosMarkers:input

Bear BOS

line 443:5

Trigger

(showBosMarkers && bearBosEvent)

Value

lastLow

Deps

bearBosEvent:var, showBosMarkers:input

Bull ChoCH

line 453:5

Trigger

(showChochMarkers && bullChochEvent)

Value

lastHigh

Deps

bullChochEvent:var, showChochMarkers:input

Bear ChoCH

line 463:5

Trigger

(showChochMarkers && bearChochEvent)

Value

lastLow

Deps

bearChochEvent:var, showChochMarkers:input

Bull MSS

line 473:5

Trigger

(showMssMarkers && bullMssEvent)

Value

lastHigh

Deps

bullMssEvent:var, showMssMarkers:input

Bear MSS

line 483:5

Trigger

(showMssMarkers && bearMssEvent)

Value

lastLow

Deps

bearMssEvent:var, showMssMarkers:input

Unlabeled shape

line 497:5

Trigger

(showTrendLabel && isLastBar)

Value

h

Deps

isLastBar:builtin, showTrendLabel:input

146_smc_mss_bos_choch_market_structure.flowscript

source path: kscripts/perfected/146_smc_mss_bos_choch_market_structure.flowscript · sha256:26793b1db2ff2d6365c3a4e76e91687d6ee7176b33806885907fa0b1e9136915

hash verified
//@version=2
// ============================================================================
// SMC Market Structure (MSS / BOS / ChoCH) — Perfected Edition
// Author: Alien_Algorithms (@Alien_Algorithms) | Enhanced by kScript Perfection Engineer
// Tags: CORE, #smc, #marketstructure, #bos, #choch, #mss, #swing, #ict
//
// Production-grade Smart Money Concepts market structure detector with confirmed
// fractal swing-point detection, Break of Structure (BOS), Change of Character
// (ChoCH), and Market Structure Shift (MSS) event detection, ATR-based swing
// validation, color-coded structure lines, and comprehensive shape-marked alerts.
//
// Academic foundations:
//  - Biais, Glosten & Spatt (2005), "Market Microstructure: A Survey" (J. Financial
//    Markets, 699+ citations). Canonical framework: latent demands D(p) → realized
//    prices/volumes via λ·ΣX_i. Explains why structural breaks (BOS/ChoCH) are
//    observable price-discovery phenomena, not merely narrative.
//  - Madhavan (2000), "Market Microstructure: A Practitioner's Guide" (J. Financial
//    Markets, 3(3), 205–258). The "black box" of latent demands → realized prices;
//    limit order models; liquidity as a return factor. Market structure shifts
//    occur when the balance of latent demand changes.
//  - Campbell, Ramadorai & Vuolteenaho (2005), "Caught On Tape: Institutional Order
//    Flow and Stock Returns" (NBER 11439). Regression achieves ~12% R² predicting
//    institutional ownership changes. ΔInstOwn_t = α + β₁·BuyVol_t + β₂·SellVol_t + ε_t.
//    Validates that institutions leave detectable footprints — swing points are
//    where institutional footprints cluster.
//  - 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 at
//    structural break points.
//  - 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. MSS events
//    often precede engineered liquidity sweeps.
//  - Omar, Kaplelach & Kiema (2026), "A Review of Trading Behavior, Liquidity, and
//    Price Formation" (EAFJ, 5(2)). Hybrid models best explain modern market
//    behavior. Swing-based structural break detection is a practical implementation
//    of hybrid information-inventory dynamics.
//  - ICT / Huddleston (2010–present), Inner Circle Trader methodology. BOS =
//    continuation of trend; ChoCH = first structural confirmation of reversal;
//    MSS = early reversal trigger (may or may not become full ChoCH).
// ============================================================================

define(
    title="SMC Market Structure (MSS/BOS/ChoCH) — Perfected Edition",
    position="onchart",
    axis=false
)

// ------------------------------------------------------------------------------
// 1. USER INPUTS — grouped with constraints
// ------------------------------------------------------------------------------

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

// --- ATR Validation ---
var atrLen = input(
    name="atrLen",
    type="number",
    defaultValue=14,
    label="ATR Length",
    constraints={min: 5, max: 100, step: 1},
    group="ATR Validation"
)
var useAtrFilter = input(
    name="useAtrFilter",
    type="boolean",
    defaultValue=true,
    label="Use ATR Swing Filter",
    group="ATR Validation"
)
var atrMult = input(
    name="atrMult",
    type="number",
    defaultValue=0.5,
    label="ATR Minimum Displacement Multiple",
    constraints={min: 0.1, max: 3.0, step: 0.1},
    group="ATR Validation"
)

// --- 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 showMssMarkers = input(
    name="showMssMarkers",
    type="boolean",
    defaultValue=true,
    label="Show MSS Markers",
    group="Display"
)
var showStructureLines = input(
    name="showStructureLines",
    type="boolean",
    defaultValue=true,
    label="Show Structure Lines",
    group="Display"
)
var showTrendLabel = input(
    name="showTrendLabel",
    type="boolean",
    defaultValue=true,
    label="Show Trend State Label",
    group="Display"
)

// --- Colors ---
var bullColor = input(
    name="bullColor",
    type="color",
    defaultValue="#26a69a",
    label="Bullish Color",
    group="Colors"
)
var bearColor = input(
    name="bearColor",
    type="color",
    defaultValue="#ef5350",
    label="Bearish 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 mssColor = input(
    name="mssColor",
    type="color",
    defaultValue="#00e5ff",
    label="MSS Marker Color",
    group="Colors"
)
var swingHiColor = input(
    name="swingHiColor",
    type="color",
    defaultValue="#ffffff40",
    label="Swing High Line Color",
    group="Colors"
)
var swingLoColor = input(
    name="swingLoColor",
    type="color",
    defaultValue="#ffffff40",
    label="Swing Low Line Color",
    group="Colors"
)

// ------------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// ------------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries c = bars.close
timeseries h = bars.high
timeseries l = bars.low
timeseries op = bars.open

if (isnan(c[0]) || isnan(h[0]) || isnan(l[0]) || isnan(op[0])) {
    return
}

// ------------------------------------------------------------------------------
// 3. ATR (WILDER) FOR SWING VALIDATION
// ------------------------------------------------------------------------------
// True Range = max(high − low, |high − close[1]|, |low − close[1]|)
// ATR = SMA(TR, atrLen). Used to filter out noise swings.
timeseries prevClose = isnan(c[1]) ? c : c[1]
timeseries tr1 = h - l
timeseries tr2 = math.abs(h - prevClose)
timeseries tr3 = math.abs(l - prevClose)
timeseries trueRange = math.max(tr1, math.max(tr2, tr3))
timeseries atr = sma(trueRange, atrLen)
timeseries minDisplacement = atr * atrMult

// ------------------------------------------------------------------------------
// 4. SWING DETECTION (FRACTAL PIVOTS)
// ------------------------------------------------------------------------------
// A swing high at [swingLen] bars ago is confirmed when:
//   H_{t-swingLen} == max(H_{t-2*swingLen:t}) AND H_{t-swingLen} > highest(H, swingLen)
// The second condition ensures the pivot is strictly higher than all bars that
// formed after it (including current bar). Same logic for swing low.
// Per Biais et al. (2005), these pivots are where latent demand imbalances
// resolve into observable price turns.

var isSwingHigh = h[swingLen] == highest(h, swingLen * 2 + 1) && h[swingLen] > highest(h, swingLen)
var isSwingLow = l[swingLen] == lowest(l, swingLen * 2 + 1) && l[swingLen] < lowest(l, swingLen)

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

// ------------------------------------------------------------------------------
// 5. STATIC STATE: MARKET STRUCTURE
// ------------------------------------------------------------------------------
// Last and previous confirmed swing levels for BOS / ChoCH / MSS detection.
// 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).
// MSS = early reversal trigger (break of internal structure before full ChoCH).

static trend = 0       // 1 = bullish, -1 = bearish, 0 = uninitialized
static lastHigh = 0.0  // Last confirmed swing high
static lastLow = 0.0   // Last confirmed swing low
static prevHigh = 0.0  // Previous swing high (for BOS/ChoCH comparison)
static prevLow = 0.0   // Previous swing low (for BOS/ChoCH comparison)
static internalHigh = 0.0  // Internal swing high (for MSS detection)
static internalLow = 0.0   // Internal swing low (for MSS detection)

// Event bar indices (0 = never)
static bullBosBar = 0
static bearBosBar = 0
static bullChochBar = 0
static bearChochBar = 0
static bullMssBar = 0
static bearMssBar = 0

// Swing bar indices for tracking recency
static lastHighBar = 0
static lastLowBar = 0
static prevHighBar = 0
static prevLowBar = 0

// ------------------------------------------------------------------------------
// 6. STATE UPDATE (on bar close)
// ------------------------------------------------------------------------------
// All stateful transitions happen here to ensure consistency.

if (!isLiveUpdate) {
    // --- Swing High Processing ---
    if (isSwingHigh) {
        var swingHiPrice = h[swingLen]
        var swingHiValid = true

        // ATR filter: swing must exceed minimum displacement from prior swing
        if (useAtrFilter && lastHigh > 0) {
            var displacement = math.abs(swingHiPrice - lastHigh)
            if (displacement < minDisplacement[swingLen]) {
                swingHiValid = false
            }
        }

        if (swingHiValid) {
            // Shift: previous becomes prevHigh, current becomes lastHigh
            if (lastHigh > 0) {
                prevHigh = lastHigh
                prevHighBar = lastHighBar
            }
            lastHigh = swingHiPrice
            lastHighBar = barCount - swingLen

            // Update internal high (the most recent lower high before a new high)
            if (trend == 1 && lastHigh > prevHigh && prevHigh > 0) {
                internalHigh = prevHigh
            }

            // BOS / ChoCH / MSS Detection
            if (trend == 1 && prevHigh > 0 && lastHigh > prevHigh) {
                // Bullish BOS: higher high in uptrend
                bullBosBar = barCount
            } else if (trend == -1 && prevHigh > 0 && lastHigh > prevHigh) {
                // Bullish ChoCH: higher high after downtrend = trend reversal
                bullChochBar = barCount
                trend = 1
            } else if (trend == 0) {
                // Initialize trend
                trend = 1
            }

            // MSS: break of internal high (early reversal signal)
            if (trend == -1 && internalHigh > 0 && lastHigh > internalHigh && lastHigh < prevHigh) {
                bullMssBar = barCount
            }
        }
    }

    // --- Swing Low Processing ---
    if (isSwingLow) {
        var swingLoPrice = l[swingLen]
        var swingLoValid = true

        // ATR filter
        if (useAtrFilter && lastLow > 0) {
            var displacement = math.abs(swingLoPrice - lastLow)
            if (displacement < minDisplacement[swingLen]) {
                swingLoValid = false
            }
        }

        if (swingLoValid) {
            // Shift: previous becomes prevLow, current becomes lastLow
            if (lastLow > 0) {
                prevLow = lastLow
                prevLowBar = lastLowBar
            }
            lastLow = swingLoPrice
            lastLowBar = barCount - swingLen

            // Update internal low
            if (trend == -1 && lastLow < prevLow && prevLow > 0) {
                internalLow = prevLow
            }

            // BOS / ChoCH / MSS Detection
            if (trend == -1 && prevLow > 0 && lastLow < prevLow) {
                // Bearish BOS: lower low in downtrend
                bearBosBar = barCount
            } else if (trend == 1 && prevLow > 0 && lastLow < prevLow) {
                // Bearish ChoCH: lower low after uptrend = trend reversal
                bearChochBar = barCount
                trend = -1
            } else if (trend == 0) {
                // Initialize trend
                trend = -1
            }

            // MSS: break of internal low
            if (trend == 1 && internalLow > 0 && lastLow < internalLow && lastLow > prevLow) {
                bearMssBar = barCount
            }
        }
    }

    // Update internal levels for MSS tracking
    if (trend == 1 && lastHigh > 0 && prevHigh > 0) {
        // In uptrend, internal low is the most recent higher low
        if (lastLow > internalLow && lastLow > 0) {
            internalLow = lastLow
        }
    }
    if (trend == -1 && lastLow > 0 && prevLow > 0) {
        // In downtrend, internal high is the most recent lower high
        if (lastHigh < internalHigh || internalHigh == 0) {
            internalHigh = lastHigh
        }
    }
}

// ------------------------------------------------------------------------------
// 7. EVENT FLAGS FOR PLOTTING
// ------------------------------------------------------------------------------
var bullBosEvent = bullBosBar == barCount
var bearBosEvent = bearBosBar == barCount
var bullChochEvent = bullChochBar == barCount
var bearChochEvent = bearChochBar == barCount
var bullMssEvent = bullMssBar == barCount
var bearMssEvent = bearMssBar == barCount

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

// ------------------------------------------------------------------------------
// 8. PLOTS: SWING LEVELS (plotLine)
// ------------------------------------------------------------------------------
if (showSwingLevels && lastHigh > 0) {
    plotLine(
        value=lastHigh,
        width=1,
        colors=[swingHiColor],
        label=["Swing High"],
        desc=["Last confirmed swing high. Confirmed after " + swingLen + " right-side bars."]
    )
}
if (showSwingLevels && lastLow > 0) {
    plotLine(
        value=lastLow,
        width=1,
        colors=[swingLoColor],
        label=["Swing Low"],
        desc=["Last confirmed swing low. Confirmed after " + swingLen + " right-side bars."]
    )
}

// --- Structure lines (prev swing levels, color-coded by regime) ---
if (showStructureLines && prevHigh > 0) {
    plotLine(
        value=prevHigh,
        width=1,
        colors=[transparency(bullColor, 60)],
        label=["Prev Swing High"],
        desc=["Previous swing high. BOS break above = continuation; ChoCH break above = reversal."]
    )
}
if (showStructureLines && prevLow > 0) {
    plotLine(
        value=prevLow,
        width=1,
        colors=[transparency(bearColor, 60)],
        label=["Prev Swing Low"],
        desc=["Previous swing low. BOS break below = continuation; ChoCH break below = reversal."]
    )
}

// ------------------------------------------------------------------------------
// 9. PLOTS: BOS / ChoCH / MSS MARKERS (plotShape)
// ------------------------------------------------------------------------------
if (showBosMarkers && bullBosEvent) {
    plotShape(
        value=lastHigh,
        shape="triangleup",
        colorIndex=bosColor,
        width=6,
        label=["Bull BOS"],
        desc=["Bullish Break of Structure: higher high in uptrend. Trend continuation."]
    )
}
if (showBosMarkers && bearBosEvent) {
    plotShape(
        value=lastLow,
        shape="rectangle",
        colorIndex=bosColor,
        width=6,
        label=["Bear BOS"],
        desc=["Bearish Break of Structure: lower low in downtrend. Trend continuation."]
    )
}
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."]
    )
}
if (showMssMarkers && bullMssEvent) {
    plotShape(
        value=lastHigh,
        shape="diamond",
        colorIndex=mssColor,
        width=4,
        label=["Bull MSS"],
        desc=["Bullish Market Structure Shift: break of internal high before full ChoCH. Early reversal."]
    )
}
if (showMssMarkers && bearMssEvent) {
    plotShape(
        value=lastLow,
        shape="diamond",
        colorIndex=mssColor,
        width=4,
        label=["Bear MSS"],
        desc=["Bearish Market Structure Shift: break of internal low before full ChoCH. Early reversal."]
    )
}

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

// ------------------------------------------------------------------------------
// 11. STRUCTURE TABLE (last bar only)
// ------------------------------------------------------------------------------
if (isLastBar) {
    var trendText = trend == 1 ? "BULLISH" : (trend == -1 ? "BEARISH" : "NEUTRAL")
    var trendTextColor = regimeColor

    plotTable(
        data=[
            ["SMC Market Structure — Perfected", trendText],
            ["Last Swing High", lastHigh],
            ["Last Swing Low", lastLow],
            ["Prev Swing High", prevHigh],
            ["Prev Swing Low", prevLow],
            ["Bull BOS Bar", bullBosBar > 0 ? bullBosBar : "—"],
            ["Bear BOS Bar", bearBosBar > 0 ? bearBosBar : "—"],
            ["Bull ChoCH Bar", bullChochBar > 0 ? bullChochBar : "—"],
            ["Bear ChoCH Bar", bearChochBar > 0 ? bearChochBar : "—"],
            ["Bull MSS Bar", bullMssBar > 0 ? bullMssBar : "—"],
            ["Bear MSS Bar", bearMssBar > 0 ? bearMssBar : "—"]
        ],
        position="top_right",
        headerRow=true,
        headerColumn=true,
        textColor="#e2e8f0",
        headerTextColor="#ffffff",
        backgroundColor=transparency("#0f172a", 40),
        headerBackgroundColor=transparency("#1e293b", 40),
        borderColor=transparency("#334155", 40),
        borderWidth=1,
        fontSize=10,
        cellPadding=4
    )
}