MM Flow
FlowScripts

Perfected FlowScript

Volume Momentum

Volume Momentum V2 is indexed as 067_volume_momentum.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

12.3 KB

Lines

297

Native Signal Candidates

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

2/2 guarded

Extreme Bull Spike

line 241:5

Trigger

(showShapes && extremeBull)

Value

extremeDiv

Deps

extremeBull:var, showShapes:input

Extreme Bear Spike

line 251:5

Trigger

(showShapes && extremeBear)

Value

-extremeDiv

Deps

extremeBear:var, showShapes:input

067_volume_momentum.flowscript

source path: kscripts/perfected/067_volume_momentum.flowscript · sha256:80bb4fb718ca2a386a4fa7ba77bb85cb50e2d8671a661fda20fcc9c72d416fae

hash verified
//@version=2

// ============================================================================
// Volume Momentum V2 — ROC of Volume with Z-Score, Regime & Spike Detection
// Author: BackQuant (@BackQuant) | Perfected: kScript_Perfection_Engineer
// Tags: CORE, SPECIALIZED, #volume, #momentum, #zscore, #regime
//
// This indicator measures volume-driven momentum as the rate-of-change (ROC) of
// signed volume, normalised via rolling z-score and smoothed for a clean signal.
// Signed volume is positive when close > open (buy-pressure) and negative when
// close < open (sell-pressure). The momentum series is colour-coded by regime,
// and shape markers flag statistically extreme momentum spikes. Static session
// tracking counts consecutive bars in each regime for context-aware alerting.
//
// Academic foundation (exact papers & formulas):
//  1. Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events",
//     Journal of Financial Econometrics, 12(1), 47–88.
//     [Formula] OFI_t = Δq_t^b·I_{Δq_t^b>0} − Δq_t^a·I_{Δq_t^a>0}; price
//     change linearly driven by net order flow; slope ∝ 1/depth.
//     The signed-volume momentum is a proxy for this aggressive flow.
//     DOI: https://doi.org/10.1093/jjfinec/nbt003
//
//  2. Chordia, Roll & Subrahmanyam (2002), "Order Imbalance, Liquidity, and
//     Market Returns", Journal of Financial Economics, 65(1), 111–130.
//     [Formula] Order Imbalance_t = Buy_t − Sell_t; market returns strongly
//     affected by contemporaneous and lagged imbalances. Validates the
//     signed-volume approach as a directional-pressure signal.
//     DOI: https://doi.org/10.1016/S0304-405X(02)00136-8
//
//  3. Farmer, Gerig, Lillo & Waelbroeck (2013), "How Efficiency Shapes Market
//     Impact", Quantitative Finance, 13(11), 1733–1747.
//     Market impact depends on market efficiency: in efficient markets, volume
//     signals decay faster. EMA smoothing adapts to this noise filtering.
//     DOI: https://doi.org/10.1080/14697688.2013.818239
//
//  4. Jegadeesh & Titman (1993), "Returns to Buying Winners and Selling
//     Losers", Journal of Finance, 48(1), 65–91. Momentum as a premier cross-
//     sectional anomaly; validates momentum-measurement in trading signals.
//     DOI: https://doi.org/10.1111/j.1540-6261.1993.tb04702.x
//
//  5. Poterba & Summers (1988), "Mean Reversion in Stock Prices: Evidence and
//     Implications", Journal of Financial Economics, 22(1), 27–59.
//     Negative autocorrelation at medium horizons; supports z-score
//     threshold design for mean-reversion / momentum regime classification.
//     DOI: https://doi.org/10.1016/0304-405X(88)90021-9
//
//  6. Kyle (1985), "Continuous Auctions and Insider Trading", Econometrica,
//     53(6), 1315–1335. [Formula] p_t = p_{t−1} + λ·OFI_t + noise.
//     Kyle's λ establishes the linear price-impact coefficient that underpins
//     volume-based trading signals.
//     DOI: https://doi.org/10.2307/1913210
// ============================================================================

define(title="Volume Momentum V2", position="offchart", axis=true)

// ---------------------------------------------------------------------------
// 1. USER INPUTS — All grouped, all numeric inputs carry constraints
// ---------------------------------------------------------------------------

// -- Computation --
var maLen = input(name="maLen", type="number", defaultValue=20, label="Average Window (signed vol)", constraints={min: 5, max: 100, step: 1}, group="Computation")
var smoothLen = input(name="smoothLen", type="number", defaultValue=5, label="EMA Smoothing Length", constraints={min: 1, max: 50, step: 1}, group="Computation")
var rocLen = input(name="rocLen", type="number", defaultValue=5, label="Volume ROC Length (momentum)", constraints={min: 1, max: 20, step: 1}, group="Computation")
var zWindow = input(name="zWindow", type="number", defaultValue=50, label="Z-Score Window (bars)", constraints={min: 20, max: 200, step: 5}, group="Computation")
var divThreshold = input(name="divThreshold", type="number", defaultValue=2.0, label="Regime Z-Score Threshold", constraints={min: 0.5, max: 4.0, step: 0.5}, group="Computation")
var extremeDiv = input(name="extremeDiv", type="number", defaultValue=3.0, label="Extreme Z-Score Threshold", constraints={min: 2.0, max: 6.0, step: 0.5}, group="Computation")

// -- Display --
var showMomentum = input(name="showMomentum", type="boolean", defaultValue=true, label="Show Momentum Line", group="Display")
var showZScore = input(name="showZScore", type="boolean", defaultValue=true, label="Show Z-Score", group="Display")
var showHistogram = input(name="showHistogram", type="boolean", defaultValue=true, label="Show Histogram", group="Display")
var showFill = input(name="showFill", type="boolean", defaultValue=true, label="Show Fill vs Zero", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Extreme Shapes", group="Display")

// -- Colors --
var bullColor = input(name="bullColor", type="color", defaultValue="#00c853", label="Bullish Color", group="Colors")
var bearColor = input(name="bearColor", type="color", defaultValue="#d50000", label="Bearish Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#78909c", label="Neutral Color", group="Colors")
var momentumColor = input(name="momentumColor", type="color", defaultValue="#2962ff", label="Momentum Line Color", group="Colors")

// ---------------------------------------------------------------------------
// 2. DATA SOURCES — with isnan() guard on first access
// ---------------------------------------------------------------------------

timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries o = bars.open
timeseries c = bars.close
timeseries v = bars.volume

// Guard: halt until price and volume data have loaded to avoid NaN propagation
if (isnan(c[0]) || isnan(v[0])) {
    return
}

// ---------------------------------------------------------------------------
// 3. COMPUTATION
// ---------------------------------------------------------------------------

// -- 3.1 Signed volume (directional pressure proxy) --
// Positive when close > open (buy-pressure), negative when close < open (sell-pressure).
// This is the Lee-Ready tick rule applied to total volume.
timeseries dirSign = c >= o ? 1.0 : -1.0
timeseries sgnVol = dirSign * v

// -- 3.2 Volume momentum: rate of change of signed volume --
// Momentum = (sgnVol - sgnVol[rocLen]) / |sgnVol[rocLen]| for normalised ROC,
// or simple difference for raw momentum. We use the difference smoothed by EMA.
// Guard: if prior volume is zero or NaN, emit 0.
timeseries priorVol = sgnVol[rocLen]
timeseries rawMom = (!isnan(priorVol) && abs(priorVol) > 0) ? (sgnVol - priorVol) / abs(priorVol) : 0.0

// -- 3.3 Rolling average of signed volume for baseline comparison --
timeseries avgSgn = sma(sgnVol, maLen)

// -- 3.4 EMA smoothing of the momentum signal --
timeseries mom = ema(rawMom, smoothLen)

// -- 3.5 Z-score normalisation of the momentum series --
// Z_t = (mom_t − μ_t) / σ_t, where μ_t = SMA(mom, W), σ_t = StDev(mom, W).
// Guard: if σ_t == 0, emit 0 to prevent division-by-zero crashes.
timeseries momMean = sma(mom, zWindow)
timeseries momStd = stdev(mom, zWindow)
timeseries momZ = (momStd > 0) ? (mom - momMean) / momStd : 0

// -- 3.6 Regime detection (configurable thresholds, no magic numbers) --
var bullishRegime = momZ > divThreshold
var bearishRegime = momZ < -divThreshold
var extremeBull = momZ > extremeDiv
var extremeBear = momZ < -extremeDiv
var neutralRegime = !bullishRegime && !bearishRegime

// -- 3.7 Regime state tracking via static variables --
// Tracks consecutive bars in each regime for context-aware alerting.
static lastRegime = 0
static bullBars = 0
static bearBars = 0
static neutralBars = 0
static peakMom = 0.0
static troughMom = 0.0

if (bullishRegime) {
    bullBars = bullBars + 1
    bearBars = 0
    neutralBars = 0
    lastRegime = 1
} else if (bearishRegime) {
    bearBars = bearBars + 1
    bullBars = 0
    neutralBars = 0
    lastRegime = -1
} else {
    neutralBars = neutralBars + 1
    bullBars = 0
    bearBars = 0
    lastRegime = 0
}

// Track peak / trough momentum for divergence context
if (!isnan(momZ[0])) {
    if (momZ[0] > peakMom) {
        peakMom = momZ[0]
    }
    if (momZ[0] < troughMom) {
        troughMom = momZ[0]
    }
}

// -- 3.8 Zero-line helper for fill areas --
timeseries zeroLine = 0

// ---------------------------------------------------------------------------
// 4. VISUALIZATION — Multiple types: plotLine, plotShape, plotBar, fill, hline
// ---------------------------------------------------------------------------

// 4.1 Momentum line (plotLine)
if (showMomentum) {
    plotLine(
        value=mom,
        width=2,
        colors=[momentumColor],
        label=["Volume Momentum"],
        desc=["Rate of change of signed volume; >0 buy-momentum, <0 sell-momentum"]
    )
}

// 4.2 Z-score line with regime colour coding (plotLine)
if (showZScore) {
    timeseries zColor = bullishRegime ? bullColor : (bearishRegime ? bearColor : neutralColor)
    plotLine(
        value=momZ,
        width=2,
        colors=[zColor],
        label=["Volume Momentum Z-Score"],
        desc=["Rolling-window z-score of volume momentum; mean-reverting around 0"]
    )
}

// 4.3 Z-score histogram with fill vs zero (plotLine + fill)
// colorIndex maps: 0 = bullish, 1 = bearish, 2 = neutral
timeseries histColorIdx = bullishRegime ? 0 : (bearishRegime ? 1 : 2)
if (showHistogram) {
    plotLine(
        value=([momZ, zeroLine]),
        width=2,
        colors=[bullColor, bearColor, neutralColor],
        colorIndex=histColorIdx,
        label=["Volume Momentum Histogram"],
        desc=["Z-score histogram colour-coded by regime: bull / bear / neutral"],
        fill=true
    )
}

// 4.4 Histogram bars (plotBar) — regime-coloured
if (showHistogram) {
    plotBar(
        value=momZ,
        colors=[bullColor, bearColor, neutralColor],
        colorIndex=histColorIdx,
        width=1,
        label=["Volume Momentum"],
        desc=["Z-score of volume momentum as bars; positive = buy-momentum, negative = sell-momentum"]
    )
}

// 4.5 Fill between momentum and zero line (plotLine with fill)
if (showFill) {
    var fillBull = momZ >= 0
    plotLine(
        value=([momZ, zeroLine]),
        width=1,
        colors=[transparency(bullColor, 20), transparency(bearColor, 20)],
        colorIndex=fillBull ? 0 : 1,
        fill=true,
        label=["Momentum Fill"],
        desc=["Fill between momentum z-score and zero line"]
    )
}

// 4.6 Extreme momentum spike shapes (plotShape)
if (showShapes && extremeBull) {
    plotShape(
        value=extremeDiv,
        shape="triangleup",
        colorIndex=bullColor,
        width=3,
        label=["Extreme Bull Spike"],
        desc=["Buy volume momentum spike; potential buying climax / exhaustion"]
    )
}
if (showShapes && extremeBear) {
    plotShape(
        value=-extremeDiv,
        shape="triangledown",
        colorIndex=bearColor,
        width=3,
        label=["Extreme Bear Spike"],
        desc=["Sell volume momentum spike; potential selling climax / capitulation"]
    )
}

// 4.7 Reference lines (hline)
hline(value=0, color="#ffffff40", width=1)
hline(value=divThreshold, color="#ffffff20", width=1)
hline(value=-divThreshold, color="#ffffff20", width=1)
hline(value=extremeDiv, color="#ffffff15", width=1)
hline(value=-extremeDiv, color="#ffffff15", width=1)

// 4.8 Regime summary table (last bar only)
if (isLastBar) {
    var regimeText = bullishRegime ? "BULLISH" : (bearishRegime ? "BEARISH" : "NEUTRAL")
    var regimeTextColor = bullishRegime ? bullColor : (bearishRegime ? bearColor : neutralColor)

    plotTable(
        data=[
            ["Vol Mom V2 — Regime", regimeText],
            ["Raw Momentum", mom[0]],
            ["Z-Score", momZ[0]],
            ["Bull Bars", bullBars],
            ["Bear Bars", bearBars],
            ["Neutral Bars", neutralBars],
            ["Peak Z", peakMom],
            ["Trough Z", troughMom]
        ],
        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
    )
}