MM Flow
FlowScripts

Perfected FlowScript

Volume-Weighted Momentum

Volume-Weighted Momentum Pro — Perfected Edition is indexed as 298_volume_weighted_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.4 KB

Lines

413

Native Signal Candidates

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

4/4 guarded

Extreme Bull

line 342:9

Trigger

(showShapes) && (extremeBull)

Value

zScore

Deps

extremeBull:var, showShapes:input

Extreme Bear

line 352:9

Trigger

(showShapes) && (extremeBear)

Value

zScore

Deps

extremeBear:var, showShapes:input

Zero Cross Up

line 362:9

Trigger

(showShapes) && (crossUpZero)

Value

0

Deps

crossUpZero:var, showShapes:input

Zero Cross Down

line 372:9

Trigger

(showShapes) && (crossDownZero)

Value

0

Deps

crossDownZero:var, showShapes:input

298_volume_weighted_momentum.flowscript

source path: kscripts/perfected/298_volume_weighted_momentum.flowscript · sha256:2eae60278f0e4aa51984d7a4d290f3c5e9092e6f0eb7a7da09062d74ee3ea84a

hash verified
//@version=2
// ============================================================================
// Volume-Weighted Momentum Pro — Perfected Edition
// Author: D (@ddave334) | Enhanced by kScript_Perfection_Engineer
// Tags: CORE, #momentum, #volume, #vwap, #zscore, #regime
//
// Production-quality volume-weighted momentum oscillator. Computes VWMA-based
// momentum relative to VWAP, normalizes via rolling z-score, and surfaces
// regime states as color-coded histograms with fill bands and shape alerts.
//
// Research papers underpinning this design:
//  1. Berkowitz, Logue & Noser (1988), "The Total Cost of Transactions on
//     the NYSE": Introduced VWAP as the institutional benchmark for fair
//     value. Measuring momentum relative to VWAP filters out low-conviction
//     moves — VWAP represents the "true" average price weighted by market
//     participation.
//  2. Madhavan (2002), "VWAP Strategies": Examined when VWAP is a sensible
//     benchmark and how traders should measure performance against it.
//     Volume-weighted momentum is essentially a relative-strength measure
//     against the VWAP benchmark.
//  3. Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events":
//     Price changes are linearly driven by order flow imbalance, with slope
//     inversely proportional to depth. Volume-weighted momentum directly
//     captures this relationship — high-volume moves have greater significance.
//  4. Jegadeesh & Titman (1993), "Returns to Buying Winners and Selling
//     Losers": Established momentum as a premier cross-sectional anomaly,
//     validating the momentum measurement role of volume-weighted indicators.
//  5. Chordia, Roll & Subrahmanyam (2002), "Order Imbalance, Liquidity, and
//     Market Returns": Extreme order imbalances predict return reversals,
//     motivating the z-score normalization and divergence-threshold design.
//  6. Lee & Ready (1991), "Inferring Trade Direction from Intraday Data":
//     Foundational trade classification algorithm (85–93% accuracy) enabling
//     volume delta decomposition into buy-initiated vs. sell-initiated flow.
// ============================================================================

define(
    title="Volume-Weighted Momentum Pro — Perfected Edition",
    position="offchart",
    axis=true
)

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

// --- VWMA / Momentum Settings ---
var maLen = input(
    name="maLen",
    type="number",
    defaultValue=20,
    label="VWMA Length",
    constraints={min: 2, max: 100, step: 1},
    group="VWMA / Momentum"
)
var momLen = input(
    name="momLen",
    type="number",
    defaultValue=14,
    label="Momentum Lookback",
    constraints={min: 2, max: 50, step: 1},
    group="VWMA / Momentum"
)
var vwapLen = input(
    name="vwapLen",
    type="number",
    defaultValue=20,
    label="VWAP Lookback",
    constraints={min: 5, max: 100, step: 1},
    group="VWMA / Momentum"
)

// --- Z-Score Normalization ---
var zWindow = input(
    name="zWindow",
    type="number",
    defaultValue=50,
    label="Z-Score Window",
    constraints={min: 10, max: 200, step: 5},
    group="Z-Score"
)
var zSmooth = input(
    name="zSmooth",
    type="number",
    defaultValue=3,
    label="Z-Score EMA Smooth",
    constraints={min: 1, max: 20, step: 1},
    group="Z-Score"
)
var zThreshold = input(
    name="zThreshold",
    type="number",
    defaultValue=2.0,
    label="Extreme Z Threshold",
    constraints={min: 0.5, max: 4.0, step: 0.5},
    group="Z-Score"
)

// --- Regime Thresholds ---
var strongLvl = input(
    name="strongLvl",
    type="number",
    defaultValue=1.5,
    label="Strong Momentum Threshold",
    constraints={min: 0.5, max: 3.0, step: 0.5},
    group="Regime Thresholds"
)
var weakLvl = input(
    name="weakLvl",
    type="number",
    defaultValue=-1.5,
    label="Weak Momentum Threshold",
    constraints={min: -3.0, max: -0.5, step: 0.5},
    group="Regime Thresholds"
)

// --- Display ---
var showVwma = input(
    name="showVwma",
    type="boolean",
    defaultValue=true,
    label="Show VWMA Line",
    group="Display"
)
var showVwap = input(
    name="showVwap",
    type="boolean",
    defaultValue=true,
    label="Show VWAP Line",
    group="Display"
)
var showHistogram = input(
    name="showHistogram",
    type="boolean",
    defaultValue=true,
    label="Show Z-Score Histogram",
    group="Display"
)
var showRibbon = input(
    name="showRibbon",
    type="boolean",
    defaultValue=true,
    label="Show Momentum Ribbon",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Extreme Shapes",
    group="Display"
)

// --- Colors ---
var upColor = input(
    name="upColor",
    type="color",
    defaultValue="#26a69a",
    label="Bullish Color",
    group="Colors"
)
var dnColor = input(
    name="dnColor",
    type="color",
    defaultValue="#ef5350",
    label="Bearish Color",
    group="Colors"
)
var neutralColor = input(
    name="neutralColor",
    type="color",
    defaultValue="#9e9e9e",
    label="Neutral Color",
    group="Colors"
)
var vwmaColor = input(
    name="vwmaColor",
    type="color",
    defaultValue="#ff9800",
    label="VWMA Color",
    group="Colors"
)
var vwapColor = input(
    name="vwapColor",
    type="color",
    defaultValue="#2962ff",
    label="VWAP Color",
    group="Colors"
)

// -----------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// -----------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries px = bars.close
timeseries vol = bars.volume

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

// -----------------------------------------------------------------------------
// 3. COMPUTATION — VWMA, VWAP, and Momentum
// -----------------------------------------------------------------------------
// Typical price for volume weighting
timeseries typical = (bars.high + bars.low + px) / 3.0

// Volume-weighted moving average (VWMA)
timeseries vwma = sma(typical * vol, maLen) / math.max(sma(vol, maLen), 1.0)

// Rolling VWAP benchmark
timeseries cumVP = sma(typical * vol, vwapLen)
timeseries cumV = sma(vol, vwapLen)
timeseries vwap = (cumV > 0) ? (cumVP / cumV) : typical

// Momentum of VWMA relative to VWAP, expressed in percent units
timeseries devPct = (vwap > 0) ? ((vwma - vwap) / vwap * 100.0) : 0.0
timeseries momentum = devPct - (devPct[1] == na ? 0 : devPct[1])

// -----------------------------------------------------------------------------
// 4. Z-SCORE NORMALIZATION
// -----------------------------------------------------------------------------
// Z_t = (momentum_t - mu_t) / sigma_t, where mu_t = SMA(momentum, W),
// sigma_t = StDev(momentum, W). Guards: if sigma_t == 0 we emit 0.
timeseries momMean = sma(momentum, zWindow)
timeseries momStd = stdev(momentum, zWindow)
timeseries zRaw = (momStd > 0) ? ((momentum - momMean) / momStd) : 0
timeseries zScore = ema(zRaw, zSmooth)

// -----------------------------------------------------------------------------
// 5. REGIME DETECTION
// -----------------------------------------------------------------------------
// Regime classification based on z-score thresholds
var regimeBull = zScore > strongLvl
var regimeBear = zScore < weakLvl
var regimeNeutral = !regimeBull && !regimeBear

var regimeColor = regimeBull ? upColor : (regimeBear ? dnColor : neutralColor)

// -----------------------------------------------------------------------------
// 6. STATIC TRACKING — regime persistence and transitions
// -----------------------------------------------------------------------------
static bullBars = 0
static bearBars = 0
static lastRegime = 0

if (regimeBull) {
    bullBars = bullBars + 1
    bearBars = 0
    lastRegime = 1
} else if (regimeBear) {
    bearBars = bearBars + 1
    bullBars = 0
    lastRegime = -1
} else {
    bullBars = 0
    bearBars = 0
    lastRegime = 0
}

// Extreme events
var extremeBull = zScore > zThreshold
var extremeBear = zScore < -zThreshold

// Crossovers of zero line
var crossUpZero = zScore > 0 && zScore[1] <= 0
var crossDownZero = zScore < 0 && zScore[1] >= 0

// -----------------------------------------------------------------------------
// 7. PLOTTING
// -----------------------------------------------------------------------------

// --- Zero line ---
hline(value=0, color="#ffffff30", width=1)

// --- Threshold lines ---
hline(value=strongLvl, color=transparency(upColor, 60), width=1)
hline(value=weakLvl, color=transparency(dnColor, 60), width=1)
hline(value=zThreshold, color=transparency(upColor, 40), width=1)
hline(value=-zThreshold, color=transparency(dnColor, 40), width=1)

// --- Z-Score Histogram (color-coded by regime) ---
if (showHistogram) {
    var histColorIdx = regimeBull ? 0 : (regimeBear ? 1 : 2)
    plotBar(
        value=zScore,
        colors=[transparency(upColor, 60), transparency(dnColor, 60), transparency(neutralColor, 50)],
        colorIndex=histColorIdx,
        width=1,
        label=["VWM Z-Score"],
        desc=["Volume-weighted momentum z-score histogram (regime-colored)"]
    )
}

// --- Z-Score Line (smoothed) ---
plotLine(
    value=zScore,
    width=2,
    colors=[regimeColor],
    label=["VWM Z-Score"],
    desc=["Smoothed z-score of volume-weighted momentum (regime-colored)"]
)

// --- Momentum Ribbon (fill between z-score and zero) ---
if (showRibbon) {
    var ribbonBull = zScore > 0
    plotLine(
        value=[zScore, 0],
        width=1,
        colors=[transparency(upColor, 20), transparency(dnColor, 20)],
        colorIndex=ribbonBull ? 0 : 1,
        fill=true,
        label=["Z-Score", "Zero"],
        desc=["Momentum ribbon fill between z-score and zero line"]
    )
}

// --- VWMA Line ---
if (showVwma) {
    plotLine(
        value=vwma,
        width=2,
        colors=[vwmaColor],
        label=["VWMA"],
        desc=["Volume-weighted moving average (" + maLen + ")"]
    )
}

// --- VWAP Line ---
if (showVwap) {
    plotLine(
        value=vwap,
        width=2,
        colors=[vwapColor],
        label=["VWAP"],
        desc=["Volume-weighted average price (" + vwapLen + ")"]
    )
}

// --- Extreme Shapes ---
if (showShapes) {
    if (extremeBull) {
        plotShape(
            value=zScore,
            shape="triangleup",
            colorIndex=upColor,
            width=2,
            label=["Extreme Bull"],
            desc=["Z-score exceeded +" + zThreshold + "σ — extreme bullish momentum"]
        )
    }
    if (extremeBear) {
        plotShape(
            value=zScore,
            shape="triangledown",
            colorIndex=dnColor,
            width=2,
            label=["Extreme Bear"],
            desc=["Z-score exceeded -" + zThreshold + "σ — extreme bearish momentum"]
        )
    }
    if (crossUpZero) {
        plotShape(
            value=0,
            shape="circle",
            colorIndex=upColor,
            width=2,
            label=["Zero Cross Up"],
            desc=["Z-score crossed above zero — bullish momentum shift"]
        )
    }
    if (crossDownZero) {
        plotShape(
            value=0,
            shape="circle",
            colorIndex=dnColor,
            width=2,
            label=["Zero Cross Down"],
            desc=["Z-score crossed below zero — bearish momentum shift"]
        )
    }
}

// -----------------------------------------------------------------------------
// 8. REGIME TABLE (last bar only)
// -----------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = regimeBull ? "BULLISH" : (regimeBear ? "BEARISH" : "NEUTRAL")
    var regimeTextColor = regimeBull ? upColor : (regimeBear ? dnColor : neutralColor)

    plotTable(
        data=[
            ["VWM Pro", regimeText],
            ["VWMA", vwma[0]],
            ["VWAP", vwap[0]],
            ["Momentum %", devPct[0]],
            ["Z-Score", zScore[0]],
            ["Bull Bars", bullBars],
            ["Bear Bars", bearBars]
        ],
        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
    )
}