MM Flow
FlowScripts

Perfected FlowScript

CVD Z Score

CVD Z-Score V2 is indexed as 028_cvd_z_score.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

10.9 KB

Lines

240

Native Signal Candidates

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

2/2 guarded

Extreme Buy Flow

line 210:5

Trigger

(showShapes && bullExtreme)

Value

zSmoothed

Deps

bullExtreme:var, showShapes:input

Extreme Sell Flow

line 220:5

Trigger

(showShapes && bearExtreme)

Value

zSmoothed

Deps

bearExtreme:var, showShapes:input

028_cvd_z_score.flowscript

source path: kscripts/perfected/028_cvd_z_score.flowscript · sha256:bc0ee1c46cee9e490557fa2578b22faf39f926b171e8ec7b83e6fd329ff8f4e3

hash verified
//@version=2

// ============================================================================
// CVD Z-Score V2 — Cumulative Volume Delta Standardization
// Author: BackQuant (@BackQuant) | Perfected: kScript_Perfection_Engineer
// Tags: CORE, ADVANCED, #cvd, #buysell, #delta, #zscore, #orderflow
//
// Computes a true cumulative CVD (not just per-bar delta) and standardizes it
// via rolling-window z-score.  ±1/2σ bands with fill, regime-coded color,
// and mean-reversion shape markers expose when order flow is statistically
// extreme relative to recent history — often flagging trend exhaustion or
// continuation points.
//
// 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 = Σ(E_i × ΔP_i); ΔP ≈ λ·OFI where λ ∝ 1/depth.
//     Cumulative OFI (CVD) linearly predicts short-term price changes.
//     DOI: https://doi.org/10.1093/jjfinec/nbt003
//
//  2. Lillo & Farmer (2004), "The Long Memory of the Efficient Market",
//     Studies in Nonlinear Dynamics & Econometrics, 8(3), 1–35.
//     Order flow autocorrelations decay as power law; long memory justifies
//     cumulative aggregation (CVD) over per-bar delta.  arXiv:cond-mat/0311053
//
//  3. Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint".
//     [Formula] z̄_t = (z_t − μ_z) / σ_z; entry/exit at Δ = d·σ_z (d=1,2).
//     Directly underpins the z-score normalization and band design.
//
//  4. Chordia, Roll & Subrahmanyam (2002), "Order Imbalance, Liquidity,
//     and Market Returns", Journal of Financial Economics, 65(1), 111–130.
//     Extreme order imbalances predict return reversals.  Motivates the
//     mean-reversion shape markers when |z| > 2σ.
//     DOI: https://doi.org/10.1016/S0304-405X(02)00136-8
//
//  5. Easley, López de Prado & O'Hara (2012), "Flow Toxicity and Liquidity
//     in a High-Frequency World", Review of Financial Studies, 25(5), 1457–1493.
//     VPIN volume-bucket approach and bulk classification improve CVD
//     robustness in HFT environments.  DOI: https://doi.org/10.1093/rfs/hhs053
//
//  6. Lee & Ready (1991), "Inferring Trade Direction from Intraday Data",
//     Journal of Finance, 46(2), 733–746.  Foundational tick-classification
//     algorithm (85–93% accuracy): classify as buy if close > open, else sell.
//     DOI: https://doi.org/10.1111/j.1540-6261.1991.tb02683.x
//
//  7. Kyle (1985), "Continuous Auctions and Insider Trading", Econometrica,
//     53(6), 1315–1335.  p_t = p_{t−1} + λ·OFI_t + noise.  Kyle's λ is the
//     price-impact coefficient underpinning every delta-based signal.
//     DOI: https://doi.org/10.2307/1913210
// ============================================================================

define(title="CVD Z-Score V2", position="offchart", axis=true)

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

// -- Computation --
var winLen = input(name="winLen", type="number", defaultValue=50, label="Z-Score Window (bars)", constraints={min: 20, max: 200, step: 5}, group="Computation")
var smoothType = input(name="smoothType", type="select", defaultValue="EMA", label="Smoothing Type", options=["EMA", "SMA", "None"], group="Computation")
var smoothLen = input(name="smoothLen", type="number", defaultValue=3, label="Smoothing Length", constraints={min: 1, max: 20, step: 1}, group="Computation")
var divThreshold = input(name="divThreshold", type="number", defaultValue=2.0, label="Mean-Reversion Threshold (σ)", constraints={min: 1.0, max: 4.0, step: 0.5}, group="Computation")

// -- Display --
var showZLine = input(name="showZLine", type="boolean", defaultValue=true, label="Show Z-Score Line", group="Display")
var showHistogram = input(name="showHistogram", type="boolean", defaultValue=true, label="Show Histogram", group="Display")
var showBands = input(name="showBands", type="boolean", defaultValue=true, label="Show ±1/2σ Bands", group="Display")
var showFill = input(name="showFill", type="boolean", defaultValue=true, label="Show Fill Areas", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Mean-Reversion Shapes", group="Display")
var showCumLine = input(name="showCumLine", type="boolean", defaultValue=false, label="Show Raw CVD Line", group="Display")

// -- Colors --
var bullColor = input(name="bullColor", type="color", defaultValue="#26a69a", label="Positive Z Color", group="Colors")
var bearColor = input(name="bearColor", type="color", defaultValue="#ef5350", label="Negative Z Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#78909c", label="Neutral Color", group="Colors")
var extremeColor = input(name="extremeColor", type="color", defaultValue="#ff9100", label="Extreme Event Color", group="Colors")

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

timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries taker = source("taker_volume", currentSymbol, currentExchange)
timeseries px = bars.close

// Guard: halt until OHLCV and taker data have loaded
if (isnan(px[0]) || (!isnum(taker.buy) && !isnum(taker.sell))) {
    return
}

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

// -- 3.1 Per-bar volume delta (Lee-Ready fallback when taker feed unavailable) --
// Lee-Ready (1991) tick test: close > open → buyer-initiated; else seller-initiated.
// When taker.buy/sell is available, prefer the direct feed for higher accuracy.
timeseries buyVol = isnum(taker.buy) ? taker.buy : (bars.close > bars.open ? bars.volume : 0)
timeseries sellVol = isnum(taker.sell) ? taker.sell : (bars.close <= bars.open ? bars.volume : 0)
timeseries delta = buyVol - sellVol

// -- 3.2 True cumulative CVD via static state (persistent across bars) --
// CVD_t = Σ_{i=0}^{t} Δ_i.  static persists across bars; guard each increment.
static cumCVD = 0.0

if (!isnan(delta[0])) {
    cumCVD = cumCVD + delta[0]
}

// -- 3.3 Rolling CVD (stationary approximation for z-score computation) --
// We also compute a rolling-window CVD so the z-score has a mean-reverting basis.
timeseries rollCVD = sum(delta, winLen)

// -- 3.4 Z-score normalization of CVD (all denominators guarded against zero) --
// Z_t = (CVD_t − μ_t) / σ_t, where μ_t = SMA(CVD, W), σ_t = StDev(CVD, W).
// Guard: if σ_t == 0 emit 0 to prevent division-by-zero crashes.
timeseries meanCVD = sma(rollCVD, winLen)
timeseries stdCVD = stdev(rollCVD, winLen)
timeseries zRaw = (stdCVD > 0) ? (rollCVD - meanCVD) / stdCVD : 0

// -- 3.5 Optional smoothing (EMA/SMA/None) --
timeseries zSmoothed = smoothType == "EMA" ? ema(zRaw, smoothLen) : (smoothType == "SMA" ? sma(zRaw, smoothLen) : zRaw)

// -- 3.6 Regime detection (configurable thresholds, no magic numbers) --
var bullExtreme = zSmoothed > divThreshold
var bearExtreme = zSmoothed < -divThreshold
var neutralRegime = !bullExtreme && !bearExtreme

// -- 3.7 Session tracking via static variables --
// Tracks session extremes, consecutive extreme bars, and mean-reversion events.
static sessionHighZ = -999999.0
static sessionLowZ = 999999.0
static extremeCount = 0
static lastBarIdx = 0
static maxConsecutiveExtreme = 0
static currentConsecutiveExtreme = 0

var currentBarIdx = bar_index[0]

if (!isnan(currentBarIdx) && currentBarIdx != lastBarIdx) {
    lastBarIdx = currentBarIdx

    if (zSmoothed > sessionHighZ) {
        sessionHighZ = zSmoothed
    }
    if (zSmoothed < sessionLowZ) {
        sessionLowZ = zSmoothed
    }

    if (bullExtreme || bearExtreme) {
        extremeCount = extremeCount + 1
        currentConsecutiveExtreme = currentConsecutiveExtreme + 1
        if (currentConsecutiveExtreme > maxConsecutiveExtreme) {
            maxConsecutiveExtreme = currentConsecutiveExtreme
        }
    } else {
        currentConsecutiveExtreme = 0
    }
}

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

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

// 4.1 ±1/2σ horizontal reference lines
hline(value=0, color="#ffffff30", width=1)
if (showBands) {
    hline(value=2, color="#ffffff20", width=1)
    hline(value=-2, color="#ffffff20", width=1)
    hline(value=1, color="#ffffff10", width=1)
    hline(value=-1, color="#ffffff10", width=1)
}

// 4.2 Z-score line with regime-coded fill (plotLine + fill)
// colorIndex maps: 0 = positive z (bullish flow / buy pressure), 1 = negative z (bearish flow / sell pressure)
// When in extreme regime, use extreme color.
var zColorIdx = zSmoothed >= 0 ? 0 : 1
var zLineColors = [bullColor, bearColor]
if (showZLine) {
    plotLine(
        value=([zSmoothed, zeroLine]),
        width=2,
        colors=zLineColors,
        colorIndex=zColorIdx,
        label=["CVD Z-Score"],
        desc=["Rolling z-score of cumulative volume delta; extreme values flag order-flow extremes"],
        fill=showFill
    )
}

// 4.3 Z-score histogram (plotBar) — color-coded by direction and regime
if (showHistogram) {
    var histColors = bullExtreme || bearExtreme ? [extremeColor, extremeColor] : [bullColor, bearColor]
    plotBar(
        value=zSmoothed,
        colors=histColors,
        width=1,
        label=["CVD Z Histogram"],
        desc=["CVD z-score as histogram bars; orange = statistically extreme regime"]
    )
}

// 4.4 Mean-reversion shape markers (plotShape)
// Fires when z-score crosses into extreme regime (>+2σ or <-2σ), signaling
// potential trend exhaustion per Chordia, Roll & Subrahmanyam (2002).
if (showShapes && bullExtreme) {
    plotShape(
        value=zSmoothed,
        shape="triangleup",
        color=extremeColor,
        width=3,
        label=["Extreme Buy Flow"],
        desc=["CVD z-score > +2σ: buy pressure statistically extreme; potential mean-reversion / exhaustion"]
    )
}
if (showShapes && bearExtreme) {
    plotShape(
        value=zSmoothed,
        shape="triangledown",
        color=extremeColor,
        width=3,
        label=["Extreme Sell Flow"],
        desc=["CVD z-score < -2σ: sell pressure statistically extreme; potential mean-reversion / exhaustion"]
    )
}

// 4.5 Optional raw cumulative CVD line (plotLine)
if (showCumLine) {
    plotLine(
        value=cumCVD,
        width=1,
        colors=[neutralColor],
        label=["CVD (Raw Cumulative)"],
        desc=["True cumulative CVD from first bar; non-stationary, for reference only"]
    )
}