MM Flow
FlowScripts

Perfected FlowScript

vol_expansion

Volume & Volatility Expansion V2 is indexed as 338_vol_expansion.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

14.1 KB

Lines

321

Native Signal Candidates

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

4/4 guarded

Extreme Expansion

line 249:9

Trigger

(showShapes) && (extremeExpCross)

Value

composite

Deps

extremeExpCross:var, showShapes:input

Expansion

line 258:9

Trigger

(showShapes) && (expCross)

Value

composite

Deps

expCross:var, showShapes:input

Extreme Compression

line 269:9

Trigger

(showShapes) && (extremeCompCross)

Value

composite

Deps

extremeCompCross:var, showShapes:input

Compression

line 278:9

Trigger

(showShapes) && (compCross)

Value

composite

Deps

compCross:var, showShapes:input

338_vol_expansion.flowscript

source path: kscripts/perfected/338_vol_expansion.flowscript · sha256:938e4cc4bf3c018bb8c0b01e59b53e5f634504ed0099dc678a5d1166ffdbaee0

hash verified
//@version=2
// ============================================================================
// Volume Expansion V2 — Volume Spike & Volatility Expansion Detector
// Author: M (@Muhammad Dinaev)  |  Perfected by: kScript Perfection Engineer
// Tags: CORE, #volume, #expansion, #volatility, #spike, #regime, #zscore
//
// Dual-engine expansion detector combining volume z-score spike detection with
// ATR-based volatility expansion, producing a composite expansion index with
// full regime detection, color-coded visualization, and session tracking.
//
// FORMULA FOUNDATION:
// 1. Volume Z-Score: zVol = (Vol − μ_Vol) / σ_Vol  [Wilder 1978; Bollinger 2001]
// 2. ATR Expansion Ratio: ATR_short / ATR_long  [Bouchaud, Farmer & Lillo 2009]
// 3. Composite Expansion Index: weighted average of volume z-score and
//    normalized ATR z-score, smoothed with EMA.
// 4. Regime Detection: Expansion (>1σ), Normal (−1σ to +1σ), Compression (<−1σ)
//    per Bollinger Squeeze framework and Bouchaud liquidity-memory.
//
// RESEARCH BASIS:
//  • Wilder (1978), "New Concepts in Technical Trading Systems". TR and ATR
//    as canonical volatility measures; RMA smoothing for persistence.
//  • Bollinger (2001), "Bollinger on Bollinger Bands". Squeeze concept: when
//    short-term volatility exceeds long-term baseline, market is in expansion;
//    the inverse signals compression ("Squeeze").
//  • Bouchaud, Farmer & Lillo (2009), "How Markets Slowly Digest Changes
//    in Supply and Demand". Liquidity-memory framework: volatility expansion
//    follows temporary liquidity depletion; volume spikes predict volatility.
//  • Chordia, Roll & Subrahmanyam (2002), "Order Imbalance, Liquidity, and
//    Market Returns". Volume spikes correlate with order flow imbalances and
//    predict near-term volatility regimes.
//  • Poterba & Summers (1988), "Mean Reversion in Stock Prices". Volatility
//    regimes exhibit mean-reverting tendencies; extreme expansions revert.
// ============================================================================

define(
    title="Volume & Volatility Expansion V2",
    position="offchart",
    axis=true
)

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

// --- Volume Parameters ---
var volLookback = input(name="volLookback", type="number", defaultValue=20, label="Volume Lookback", constraints={min: 5, max: 100, step: 1}, group="Volume")
var volSmooth = input(name="volSmooth", type="number", defaultValue=5, label="Volume Smoothing", constraints={min: 1, max: 50, step: 1}, group="Volume")
var volWeight = input(name="volWeight", type="number", defaultValue=0.6, label="Volume Weight", constraints={min: 0.0, max: 1.0, step: 0.05}, group="Volume")

// --- ATR Parameters ---
var atrShortLen = input(name="atrShortLen", type="number", defaultValue=9, label="Short ATR Length", constraints={min: 2, max: 50, step: 1}, group="ATR")
var atrLongLen = input(name="atrLongLen", type="number", defaultValue=384, label="Long ATR Length", constraints={min: 20, max: 500, step: 1}, group="ATR")
var atrWeight = input(name="atrWeight", type="number", defaultValue=0.4, label="ATR Weight", constraints={min: 0.0, max: 1.0, step: 0.05}, group="ATR")

// --- Thresholds ---
var expThresh = input(name="expThresh", type="number", defaultValue=1.0, label="Expansion Threshold (σ)", constraints={min: 0.5, max: 5.0, step: 0.1}, group="Thresholds")
var compThresh = input(name="compThresh", type="number", defaultValue=-1.0, label="Compression Threshold (σ)", constraints={min: -5.0, max: -0.5, step: 0.1}, group="Thresholds")
var extremeThresh = input(name="extremeThresh", type="number", defaultValue=2.0, label="Extreme Threshold (σ)", constraints={min: 1.5, max: 5.0, step: 0.1}, group="Thresholds")

// --- Display ---
var showHistogram = input(name="showHistogram", type="boolean", defaultValue=true, label="Show Expansion Histogram", group="Display")
var showLine = input(name="showLine", type="boolean", defaultValue=true, label="Show Expansion Line", group="Display")
var showVolZ = input(name="showVolZ", type="boolean", defaultValue=false, label="Show Volume Z-Score", group="Display")
var showAtrZ = input(name="showAtrZ", type="boolean", defaultValue=false, label="Show ATR Z-Score", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Event Shapes", group="Display")
var showGuides = input(name="showGuides", type="boolean", defaultValue=true, label="Show Guide Lines", group="Display")

// --- Colors ---
var expColor = input(name="expColor", type="color", defaultValue="#26a69a", label="Expansion Color", group="Colors")
var compColor = input(name="compColor", type="color", defaultValue="#ef5350", label="Compression Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#9e9e9e", label="Neutral Color", group="Colors")
var extremeExpColor = input(name="extremeExpColor", type="color", defaultValue="#00e676", label="Extreme Expansion Color", group="Colors")
var extremeCompColor = input(name="extremeCompColor", type="color", defaultValue="#ff1744", label="Extreme Compression Color", group="Colors")

// ------------------------------------------------------------------------------
// Data Sources & NaN Guard
// ------------------------------------------------------------------------------
timeseries priceBars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries px = priceBars.close
timeseries vol = priceBars.volume

if (isnan(px[0]) || isnan(vol[0])) {
    return
}

// ------------------------------------------------------------------------------
// Volume Z-Score Computation
// ------------------------------------------------------------------------------
// Standardizes volume relative to its rolling mean and standard deviation.
// Volume spikes (high z-scores) often precede volatility expansions and
// directional moves as informed order flow enters the market.

timeseries volMean = sma(vol, volLookback)
timeseries volStd = stddev(vol, volLookback)
timeseries volZ = volStd > 0 ? (vol - volMean) / volStd : 0.0

// ------------------------------------------------------------------------------
// ATR-Based Volatility Expansion Computation
// ------------------------------------------------------------------------------
// True Range per bar (Wilder 1978 canonical definition)
timeseries tr = math.max(high - low, math.max(math.abs(high - close[1]), math.abs(low - close[1])))

// Short and long ATR using RMA (Wilder's smoother)
timeseries atrS = rma(tr, atrShortLen)
timeseries atrL = rma(tr, atrLongLen)

// ATR expansion ratio: short-term volatility vs. long-term baseline
// A ratio > 1 indicates expansion; < 1 indicates compression.
timeseries atrRatio = atrL > 0 ? atrS / atrL : 1.0

// Normalize ATR ratio to z-score-like units for combination with volume z-score
timeseries atrMean = sma(atrRatio, volLookback)
timeseries atrStd = stddev(atrRatio, volLookback)
timeseries atrZ = atrStd > 0 ? (atrRatio - atrMean) / atrStd : 0.0

// ------------------------------------------------------------------------------
// Composite Expansion Index
// ------------------------------------------------------------------------------
// Weighted combination of volume z-score and ATR z-score, then EMA-smoothed.
// Default weighting: 60% volume, 40% ATR. Volume leads volatility; ATR confirms.

var totalWeight = volWeight + atrWeight
timeseries compositeRaw = totalWeight > 0 ? (volWeight * volZ + atrWeight * atrZ) / totalWeight : 0.0
timeseries composite = ema(compositeRaw, volSmooth)

// ------------------------------------------------------------------------------
// Regime Detection (Five-tier classification)
// ------------------------------------------------------------------------------
//  2 = extreme expansion
//  1 = expansion
//  0 = normal
// -1 = compression
// -2 = extreme compression

var regime = 0
if (composite >= extremeThresh) {
    regime = 2
} else if (composite >= expThresh) {
    regime = 1
} else if (composite <= -extremeThresh) {
    regime = -2
} else if (composite <= compThresh) {
    regime = -1
}

// ------------------------------------------------------------------------------
// Static State Tracking (Session-level persistence)
// ------------------------------------------------------------------------------
static lastRegime = 0
static regimeChangeCount = 0
static sessionHighExp = -999999.0
static sessionLowExp = 999999.0
static extremeExpCount = 0
static extremeCompCount = 0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
    lastBarIndex = currentBarIndex
    if (composite > sessionHighExp) {
        sessionHighExp = composite
    }
    if (composite < sessionLowExp) {
        sessionLowExp = composite
    }
    if (lastRegime != regime) {
        lastRegime = regime
        regimeChangeCount = regimeChangeCount + 1
    }
    if (regime == 2) {
        extremeExpCount = extremeExpCount + 1
    } else if (regime == -2) {
        extremeCompCount = extremeCompCount + 1
    }
}

// ------------------------------------------------------------------------------
// Plots — Multiple Visualization Types (Line, Bar, Shape, Fill, HLine)
// ------------------------------------------------------------------------------

// Horizontal guide lines
hline(value=0, color="#ffffff30", width=1)

if (showGuides) {
    hline(value=expThresh, color=transparency(expColor, 40), width=1)
    hline(value=compThresh, color=transparency(compColor, 40), width=1)
    hline(value=extremeThresh, color=transparency(extremeExpColor, 20), width=1)
    hline(value=-extremeThresh, color=transparency(extremeCompColor, 20), width=1)
}

// Expansion histogram with regime color coding
if (showHistogram) {
    plotBar(
        value=composite,
        colors=[extremeExpColor, expColor, neutralColor, compColor, extremeCompColor],
        colorIndex=regime + 2,
        width=1,
        label=["Expansion Index"],
        desc=["Composite volume + volatility expansion index with regime coloring"]
    )
}

// Expansion line with regime-coded fill area
if (showLine) {
    plotLine(
        value=composite,
        width=2,
        colors=[extremeExpColor, expColor, neutralColor, compColor, extremeCompColor],
        colorIndex=regime + 2,
        label=["Expansion Index"],
        desc=["Composite expansion index with regime coloring and fill"],
        fill=true
    )
}

// Volume Z-Score auxiliary line
if (showVolZ) {
    plotLine(
        value=volZ,
        width=1,
        colors=[expColor, compColor, neutralColor],
        colorIndex=volZ > expThresh ? 0 : (volZ < compThresh ? 1 : 2),
        label=["Volume Z-Score"],
        desc=["Volume z-score relative to rolling mean and stddev (" + volLookback + "-period)"]
    )
}

// ATR Z-Score auxiliary line
if (showAtrZ) {
    plotLine(
        value=atrZ,
        width=1,
        colors=[expColor, compColor, neutralColor],
        colorIndex=atrZ > expThresh ? 0 : (atrZ < compThresh ? 1 : 2),
        label=["ATR Z-Score"],
        desc=["ATR ratio normalized to z-score units (" + atrShortLen + "/" + atrLongLen + ")"]
    )
}

// Event shapes — expansion and compression crossings
if (showShapes) {
    var expCross = composite >= expThresh && !isnan(composite[1]) && composite[1] < expThresh
    var compCross = composite <= compThresh && !isnan(composite[1]) && composite[1] > compThresh
    var extremeExpCross = composite >= extremeThresh && !isnan(composite[1]) && composite[1] < extremeThresh
    var extremeCompCross = composite <= -extremeThresh && !isnan(composite[1]) && composite[1] > -extremeThresh

    if (extremeExpCross) {
        plotShape(
            value=composite,
            shape="diamond",
            color=extremeExpColor,
            width=4,
            label=["Extreme Expansion"],
            desc=["Extreme volume + volatility expansion detected — liquidity event likely"]
        )
    } else if (expCross) {
        plotShape(
            value=composite,
            shape="triangleup",
            color=expColor,
            width=3,
            label=["Expansion"],
            desc=["Volume + volatility expansion detected — elevated activity regime"]
        )
    }

    if (extremeCompCross) {
        plotShape(
            value=composite,
            shape="diamond",
            color=extremeCompColor,
            width=4,
            label=["Extreme Compression"],
            desc=["Extreme compression detected — potential squeeze / breakout setup"]
        )
    } else if (compCross) {
        plotShape(
            value=composite,
            shape="triangledown",
            color=compColor,
            width=3,
            label=["Compression"],
            desc=["Volume + volatility compression detected — low activity regime"]
        )
    }
}

// ------------------------------------------------------------------------------
// Regime Table (last bar only)
// ------------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = regime == 2 ? "EXTREME EXP" : (regime == 1 ? "EXPANSION" : (regime == -1 ? "COMPRESSION" : (regime == -2 ? "EXTREME COMP" : "NORMAL")))
    var regimeTextColor = regime > 0 ? expColor : (regime < 0 ? compColor : neutralColor)

    plotTable(
        data=[
            ["Volume Expansion V2", regimeText],
            ["Composite Index", composite[0]],
            ["Volume Z-Score", volZ[0]],
            ["ATR Z-Score", atrZ[0]],
            ["Session High", sessionHighExp],
            ["Session Low", sessionLowExp],
            ["Regime Changes", regimeChangeCount],
            ["Extreme Exp Bars", extremeExpCount],
            ["Extreme Comp Bars", extremeCompCount]
        ],
        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
    )
}