MM Flow
FlowScripts

Perfected FlowScript

Breakout Probability

Breakout Probability — Perfected Edition is indexed as 359_breakout_probability.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

offchart

Axis

true

Size

19.9 KB

Lines

630

Native Signal Candidates

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

9/9 guarded

High P(Up)

line 500:9

Trigger

(showShapes) && (probUpBreak)

Value

probUpVal

Deps

probUpBreak:var, showShapes:input

High P(Down)

line 510:9

Trigger

(showShapes) && (probDownBreak)

Value

probDownVal

Deps

probDownBreak:var, showShapes:input

Extreme P(Up)

line 520:9

Trigger

(showShapes) && (probUpExtreme)

Value

probUpVal

Deps

probUpExtreme:var, showShapes:input

Extreme P(Down)

line 530:9

Trigger

(showShapes) && (probDownExtreme)

Value

probDownVal

Deps

probDownExtreme:var, showShapes:input

Squeeze Start

line 542:9

Trigger

(showShapes) && (squeezeStart)

Value

0.5

Deps

showShapes:input, squeezeStart:var

Squeeze End

line 552:9

Trigger

(showShapes) && (squeezeEnd)

Value

0.5

Deps

showShapes:input, squeezeEnd:var

Vol Spike

line 564:9

Trigger

(showShapes) && (volSpikeEvent)

Value

probSpread

Deps

showShapes:input, volSpikeEvent:var

Donchian Up

line 576:9

Trigger

(showShapes) && (donchianBreakUp)

Value

probUpVal

Deps

donchianBreakUp:var, showShapes:input

Donchian Down

line 586:9

Trigger

(showShapes) && (donchianBreakDown)

Value

probDownVal

Deps

donchianBreakDown:var, showShapes:input

359_breakout_probability.flowscript

source path: kscripts/perfected/359_breakout_probability.flowscript · sha256:9e912206f92527ee364b2724ac38a94eaf9be31ad72b628b03a05161ab693229

hash verified
//@version=2
// ============================================================================
// Breakout Probability — Perfected Edition
// Author: A (@ali_rayyan97) | Enhanced by kScript Perfection Engineer
// Tags: CORE, #breakout, #probability, #range, #squeeze, #volume, #regime
//
// Production-quality multi-factor breakout probability model combining
// range-width z-score, volatility squeeze detection, Bollinger/Keltner
// channel analysis, volume confirmation, and trend-aligned probability
// estimation. Outputs a calibrated probability band in [0, 1] with regime
// classification and comprehensive shape markers.
//
// Research papers underpinning this design:
//  1. Crabel (1990), "Playing the Opening Range Breakout": foundational
//     practitioner work on breakout mechanics. "Stretch" = average of prior
//     10 days' |Open − nearest extreme|; narrow-range day breakouts (IDnr4,
//     NR7) are especially reliable.
//  2. SFI / Concretum Group (2024), "A Profitable Day Trading Strategy For
//     The U.S. Equity Market": 5-minute ORB across 7,000+ US stocks (2016–
//     2023); top 20 "Stocks in Play" achieved >1,600% total net return,
//     Sharpe 2.81. Validates breakout strategies when filtered for activity
//     and volatility.
//  3. Bollinger (2001), "Bollinger on Bollinger Bands": BandWidth measures
//     volatility squeeze. %B shows position within bands. Squeeze precedes
//     expansion in ~80% of cases per practitioner observation.
//  4. Bhusal (2025), "Timing the Trap" (SSRN 5276088): documents engineered
//     liquidity traps and false breaks. Genuine breakouts require follow-through
//     volume and close confirmation; traps lack both.
//  5. Wilder (1978), "New Concepts in Technical Trading Systems": ATR enables
//     cross-instrument range normalization. True Range = max(H−L, |H−C[1]|,
//     |L−C[1]|).
//  6. Keltner (1960) / Raschke (1980s): Keltner Channels use ATR for smoother
//     bands than Bollinger. Breakouts above/below channel signal trend
//     continuation rather than reversal.
//  7. Campbell, Ramadorai & Vuolteenaho (2005), NBER 11439: institutional
//     order flow leaves detectable footprints. Volume spikes validate genuine
//     breakouts as informed trading signatures.
// ============================================================================

define(
    title="Breakout Probability — Perfected Edition",
    position="offchart",
    axis=true
)

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

// --- Range Analysis ---
var rangeLen = input(
    name="rangeLen",
    type="number",
    defaultValue=20,
    label="Range Lookback (Donchian)",
    constraints={min: 5, max: 200, step: 1},
    group="Range Analysis"
)
var rangeAvgLen = input(
    name="rangeAvgLen",
    type="number",
    defaultValue=50,
    label="Range Average Lookback",
    constraints={min: 10, max: 500, step: 1},
    group="Range Analysis"
)

// --- ATR / Volatility ---
var atrLen = input(
    name="atrLen",
    type="number",
    defaultValue=14,
    label="ATR Length",
    constraints={min: 5, max: 100, step: 1},
    group="Volatility"
)
var slowAtrLen = input(
    name="slowAtrLen",
    type="number",
    defaultValue=100,
    label="Slow ATR Length",
    constraints={min: 20, max: 500, step: 1},
    group="Volatility"
)
var bbLen = input(
    name="bbLen",
    type="number",
    defaultValue=20,
    label="Bollinger Length",
    constraints={min: 5, max: 100, step: 1},
    group="Volatility"
)
var bbMult = input(
    name="bbMult",
    type="number",
    defaultValue=2.0,
    label="Bollinger Multiplier",
    constraints={min: 0.5, max: 5.0, step: 0.1},
    group="Volatility"
)

// --- Squeeze Detection ---
var squeezeLook = input(
    name="squeezeLook",
    type="number",
    defaultValue=50,
    label="Squeeze Lookback",
    constraints={min: 10, max: 500, step: 1},
    group="Squeeze"
)
var squeezeThreshold = input(
    name="squeezeThreshold",
    type="number",
    defaultValue=-1.0,
    label="Squeeze Z-Score Threshold",
    constraints={min: -3.0, max: 0.0, step: 0.1},
    group="Squeeze"
)

// --- Volume Confirmation ---
var useVolume = input(
    name="useVolume",
    type="boolean",
    defaultValue=true,
    label="Use Volume Confirmation",
    group="Volume"
)
var volLookback = input(
    name="volLookback",
    type="number",
    defaultValue=20,
    label="Volume Average Lookback",
    constraints={min: 5, max: 100, step: 1},
    group="Volume"
)
var volBoostThreshold = input(
    name="volBoostThreshold",
    type="number",
    defaultValue=1.5,
    label="Volume Boost Threshold (× avg)",
    constraints={min: 1.0, max: 5.0, step: 0.1},
    group="Volume"
)

// --- Probability Calibration ---
var probBase = input(
    name="probBase",
    type="number",
    defaultValue=0.5,
    label="Base Probability",
    constraints={min: 0.0, max: 1.0, step: 0.05},
    group="Probability"
)
var trendAlignBoost = input(
    name="trendAlignBoost",
    type="number",
    defaultValue=1.2,
    label="Trend-Alignment Boost",
    constraints={min: 1.0, max: 2.0, step: 0.05},
    group="Probability"
)
var squeezeBoost = input(
    name="squeezeBoost",
    type="number",
    defaultValue=1.3,
    label="Squeeze Boost",
    constraints={min: 1.0, max: 2.0, step: 0.05},
    group="Probability"
)

// --- Display ---
var showProbBands = input(
    name="showProbBands",
    type="boolean",
    defaultValue=true,
    label="Show Probability Bands",
    group="Display"
)
var showSqueezeFlag = input(
    name="showSqueezeFlag",
    type="boolean",
    defaultValue=true,
    label="Show Squeeze Flag",
    group="Display"
)
var showVolConfirm = input(
    name="showVolConfirm",
    type="boolean",
    defaultValue=true,
    label="Show Volume Confirmation",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Shape Markers",
    group="Display"
)
var showTable = input(
    name="showTable",
    type="boolean",
    defaultValue=true,
    label="Show Info Table",
    group="Display"
)

// --- Colors ---
var probUpColor = input(
    name="probUpColor",
    type="color",
    defaultValue="#26a69a",
    label="Upside Probability Color",
    group="Colors"
)
var probDownColor = input(
    name="probDownColor",
    type="color",
    defaultValue="#ef5350",
    label="Downside Probability Color",
    group="Colors"
)
var neutralColor = input(
    name="neutralColor",
    type="color",
    defaultValue="#9e9e9e",
    label="Neutral Color",
    group="Colors"
)
var squeezeColor = input(
    name="squeezeColor",
    type="color",
    defaultValue="#ab47bc",
    label="Squeeze Color",
    group="Colors"
)
var breakColor = input(
    name="breakColor",
    type="color",
    defaultValue="#ffd700",
    label="Breakout Alert Color",
    group="Colors"
)

// ---------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// ---------------------------------------------------------------------------
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

if (isnan(cl[0]) || isnan(hi[0]) || isnan(lo[0]) || isnan(vol[0])) {
    return
}

// ---------------------------------------------------------------------------
// 3. RANGE ANALYSIS
// ---------------------------------------------------------------------------
// Donchian-style range: highest high / lowest low over lookback
timeseries hh = highest(hi, rangeLen)
timeseries ll = lowest(lo, rangeLen)
timeseries rangeW = hh - ll

// Range width z-score: how narrow is the current range vs history?
timeseries rangeMean = sma(rangeW, rangeAvgLen)
timeseries rangeStd = stddev(rangeW, rangeAvgLen)
timeseries rangeZ = rangeStd > 0 ? (rangeW - rangeMean) / rangeStd : 0

// Range position: where is close within the recent range [0, 1]
timeseries rangePos = (hh - ll) > 0 ? (cl - ll) / (hh - ll) : 0.5

// ---------------------------------------------------------------------------
// 4. VOLATILITY ANALYSIS
// ---------------------------------------------------------------------------
// True Range and ATR (Wilder)
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 = rma(trueRange, atrLen)
timeseries slowAtr = rma(trueRange, slowAtrLen)

// Volatility expansion: short ATR vs long ATR
timeseries volExpansion = slowAtr > 0 ? atr / slowAtr : 1.0

// Bollinger BandWidth (proxy using SMA + stddev)
timeseries bbMid = sma(cl, bbLen)
timeseries bbStd = stddev(cl, bbLen)
timeseries bbUpper = bbMid + bbMult * bbStd
timeseries bbLower = bbMid - bbMult * bbStd
timeseries bbWidth = bbMid > 0 ? (bbUpper - bbLower) / bbMid : 0

// BandWidth z-score: squeeze when width is narrow vs history
timeseries bbWidthMean = sma(bbWidth, squeezeLook)
timeseries bbWidthStd = stddev(bbWidth, squeezeLook)
timeseries bbWidthZ = bbWidthStd > 0 ? (bbWidth - bbWidthMean) / bbWidthStd : 0

// Squeeze detection: range AND bandwidth both compressed
var isSqueeze = rangeZ < squeezeThreshold && bbWidthZ < squeezeThreshold

// ---------------------------------------------------------------------------
// 5. VOLUME CONFIRMATION
// ---------------------------------------------------------------------------
timeseries volAvg = sma(vol, volLookback)
timeseries volRatio = volAvg > 0 ? vol / volAvg : 1.0
var volSpike = volRatio > volBoostThreshold
var volConfirm = volRatio > 1.0

// Volume-adjusted range: high volume on narrow range = accumulation
timeseries volRange = vol > 0 ? rangeW / vol : 0

// ---------------------------------------------------------------------------
// 6. TREND BIAS
// ---------------------------------------------------------------------------
// Simple trend alignment: close vs mid-range, plus slope of range midpoint
timeseries rangeMid = (hh + ll) / 2
var aboveMid = cl > rangeMid
var belowMid = cl < rangeMid

// Range slope: is the range shifting upward or downward?
timeseries rangeMidSlope = rangeMid - rangeMid[5]
var rangeRising = rangeMidSlope > 0
var rangeFalling = rangeMidSlope < 0

// Trend alignment score: 1 = aligned with range direction, 0 = neutral
timeseries trendAlign = 0.0
if (aboveMid && rangeRising) {
    trendAlign = 1.0
} else if (belowMid && rangeFalling) {
    trendAlign = -1.0
} else if (aboveMid && rangeFalling) {
    trendAlign = 0.3
} else if (belowMid && rangeRising) {
    trendAlign = -0.3
} else {
    trendAlign = 0.0
}

// ---------------------------------------------------------------------------
// 7. BREAKOUT PROBABILITY MODEL
// ---------------------------------------------------------------------------
// Base probability: position within range (0 = at support, 1 = at resistance)
timeseries baseUp = rangePos
timeseries baseDown = 1 - rangePos

// Squeeze boost: when range is compressed, breakout probability rises
var squeezeFactor = isSqueeze ? squeezeBoost : 1.0

// Volatility boost: expansion increases breakout likelihood
var volFactor = volExpansion > 1.1 ? 1.15 : (volExpansion < 0.9 ? 0.85 : 1.0)

// Volume boost: high volume near extremes increases probability
var volUpBoost = volSpike && aboveMid ? volBoostThreshold : 1.0
var volDownBoost = volSpike && belowMid ? volBoostThreshold : 1.0

// Trend alignment boost: price aligned with range direction gets extra probability
var alignFactorUp = trendAlign > 0 ? trendAlignBoost : 1.0
var alignFactorDown = trendAlign < 0 ? trendAlignBoost : 1.0

// Combined probability (clamped to [0, 1])
timeseries probUpRaw = baseUp * squeezeFactor * volFactor * volUpBoost * alignFactorUp
timeseries probDownRaw = baseDown * squeezeFactor * volFactor * volDownBoost * alignFactorDown

timeseries probUpVal = math.max(0, math.min(1, probUpRaw))
timeseries probDownVal = math.max(0, math.min(1, probDownRaw))

// Net probability spread (bullish bias positive)
timeseries probSpread = probUpVal - probDownVal

// ---------------------------------------------------------------------------
// 8. REGIME DETECTION
// ---------------------------------------------------------------------------
var regimeSqueeze = isSqueeze
var regimeExpansion = volExpansion > 1.2 && !isSqueeze
var regimeTrending = trendAlign != 0 && volExpansion > 1.0
var regimeNeutral = !regimeSqueeze && !regimeExpansion && !regimeTrending

var regimeColor = regimeSqueeze ? squeezeColor : (regimeTrending ? (probSpread > 0 ? probUpColor : probDownColor) : neutralColor)
var regimeLabel = regimeSqueeze ? "SQUEEZE" : (regimeExpansion ? "EXPANDING" : (regimeTrending ? "TRENDING" : "NEUTRAL"))

// ---------------------------------------------------------------------------
// 9. ALERT CONDITIONS & SHAPE MARKERS
// ---------------------------------------------------------------------------
// Breakout probability threshold events
var probUpBreak = probUpVal > 0.7 && probUpVal[1] <= 0.7
var probDownBreak = probDownVal > 0.7 && probDownVal[1] <= 0.7
var probUpExtreme = probUpVal > 0.9 && probUpVal[1] <= 0.9
var probDownExtreme = probDownVal > 0.9 && probDownVal[1] <= 0.9

// Squeeze start / end
var squeezeStart = isSqueeze && !isSqueeze[1]
var squeezeEnd = !isSqueeze && isSqueeze[1]

// Volume spike event
var volSpikeEvent = volSpike && !volSpike[1]

// Range breakout: close outside Donchian channel
var donchianBreakUp = cl > hh[1] && cl[1] <= hh[1]
var donchianBreakDown = cl < ll[1] && cl[1] >= ll[1]

// ---------------------------------------------------------------------------
// 10. STATIC STATE TRACKING
// ---------------------------------------------------------------------------
static lastSqueezeBar = 0
static squeezeCount = 0
static lastBreakoutBar = 0
static breakoutCount = 0

if (!isLiveUpdate) {
    if (squeezeStart) {
        lastSqueezeBar = barCount
        squeezeCount = squeezeCount + 1
    }
    if (donchianBreakUp || donchianBreakDown) {
        lastBreakoutBar = barCount
        breakoutCount = breakoutCount + 1
    }
}

// ---------------------------------------------------------------------------
// 11. PLOTTING
// ---------------------------------------------------------------------------

// --- Reference lines ---
hline(value=0.5, color="#ffffff40", width=1)
hline(value=0.7, color=transparency(probUpColor, 60), width=1)
hline(value=0.3, color=transparency(probDownColor, 60), width=1)

// --- Probability Bands (filled area) ---
if (showProbBands) {
    plotLine(
        value=[probUpVal, probDownVal],
        width=1,
        colors=[transparency(probUpColor, 40), transparency(probDownColor, 40)],
        fill=true,
        label=["P(Break Up)", "P(Break Down)"],
        desc=["Estimated probability of upside breakout", "Estimated probability of downside breakout"]
    )

    // Individual probability lines
    plotLine(
        value=probUpVal,
        width=2,
        colors=[probUpColor],
        label=["P(Up)"],
        desc=["Upside breakout probability (0..1)"]
    )
    plotLine(
        value=probDownVal,
        width=2,
        colors=[probDownColor],
        label=["P(Down)"],
        desc=["Downside breakout probability (0..1)"]
    )
}

// --- Probability Spread (net bias) ---
plotLine(
    value=probSpread,
    width=1,
    colors=[regimeColor],
    label=["Prob Spread"],
    desc=["Net breakout bias: P(Up) − P(Down)"]
)

// --- Squeeze Flag ---
if (showSqueezeFlag) {
    var squeezeVal = isSqueeze ? 1 : 0
    plotBar(
        value=squeezeVal,
        colors=[transparency(squeezeColor, 60)],
        width=1,
        label=["Squeeze"],
        desc=["Volatility squeeze detected: range + BB width compressed"]
    )
}

// --- Volume Confirmation ---
if (showVolConfirm && useVolume) {
    var volConfirmVal = volConfirm ? volRatio : 0
    var volBull = volConfirmVal > 0
    plotBar(
        value=volConfirmVal,
        colors=[transparency(probUpColor, 40), transparency(probDownColor, 40)],
        colorIndex=volBull ? 0 : 1,
        width=1,
        label=["Vol Confirm"],
        desc=["Volume confirmation ratio vs " + volLookback + "-period average"]
    )
}

// --- Shape Markers ---
if (showShapes) {
    // Probability threshold breaks
    if (probUpBreak) {
        plotShape(
            value=probUpVal,
            shape="triangleup",
            colorIndex=breakColor,
            width=2,
            label=["High P(Up)"],
            desc=["Upside breakout probability crossed above 0.7"]
        )
    }
    if (probDownBreak) {
        plotShape(
            value=probDownVal,
            shape="triangledown",
            colorIndex=breakColor,
            width=2,
            label=["High P(Down)"],
            desc=["Downside breakout probability crossed above 0.7"]
        )
    }
    if (probUpExtreme) {
        plotShape(
            value=probUpVal,
            shape="arrowup",
            colorIndex=probUpColor,
            width=2,
            label=["Extreme P(Up)"],
            desc=["Upside breakout probability > 0.9 — extreme bullish bias"]
        )
    }
    if (probDownExtreme) {
        plotShape(
            value=probDownVal,
            shape="arrowdown",
            colorIndex=probDownColor,
            width=2,
            label=["Extreme P(Down)"],
            desc=["Downside breakout probability > 0.9 — extreme bearish bias"]
        )
    }

    // Squeeze events
    if (squeezeStart) {
        plotShape(
            value=0.5,
            shape="diamond",
            colorIndex=squeezeColor,
            width=2,
            label=["Squeeze Start"],
            desc=["Volatility squeeze started: compressed range + BB width"]
        )
    }
    if (squeezeEnd) {
        plotShape(
            value=0.5,
            shape="circle",
            colorIndex=squeezeColor,
            width=2,
            label=["Squeeze End"],
            desc=["Volatility squeeze ended: expansion likely imminent"]
        )
    }

    // Volume spike
    if (volSpikeEvent) {
        plotShape(
            value=probSpread,
            shape="xcross",
            colorIndex=breakColor,
            width=2,
            label=["Vol Spike"],
            desc=["Volume spike detected: " + volRatio[0] + "× average"]
        )
    }

    // Donchian breakout
    if (donchianBreakUp) {
        plotShape(
            value=probUpVal,
            shape="triangleup",
            colorIndex=probUpColor,
            width=2,
            label=["Donchian Up"],
            desc=["Price broke above " + rangeLen + "-period Donchian high"]
        )
    }
    if (donchianBreakDown) {
        plotShape(
            value=probDownVal,
            shape="triangledown",
            colorIndex=probDownColor,
            width=2,
            label=["Donchian Down"],
            desc=["Price broke below " + rangeLen + "-period Donchian low"]
        )
    }
}

// ---------------------------------------------------------------------------
// 12. REGIME TABLE (last bar only)
// ---------------------------------------------------------------------------
if (showTable && isLastBar) {
    var tableTextColor = probSpread > 0 ? probUpColor : probDownColor

    plotTable(
        data=[
            ["Breakout Probability — Perfected", regimeLabel],
            ["P(Up)", probUpVal[0]],
            ["P(Down)", probDownVal[0]],
            ["Net Spread", probSpread[0]],
            ["Range Z", rangeZ[0]],
            ["BB Width Z", bbWidthZ[0]],
            ["Vol Expansion", volExpansion[0]],
            ["Vol Ratio", volRatio[0]],
            ["Trend Align", trendAlign[0]],
            ["Squeezes Count", squeezeCount],
            ["Breakouts Count", breakoutCount]
        ],
        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
    )
}