MM Flow
FlowScripts

Perfected FlowScript

CVD Z-Score

CVD Z-Score V2 — Perfected Edition is indexed as 255_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

15.1 KB

Lines

328

Native Signal Candidates

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

2/2 guarded

Extreme Buy Climax

line 258:5

Trigger

(showShapes && volConfirmedExtBull)

Value

sig3

Deps

showShapes:input, volConfirmedExtBull:var

Extreme Sell Climax

line 268:5

Trigger

(showShapes && volConfirmedExtBear)

Value

-sig3

Deps

showShapes:input, volConfirmedExtBear:var

255_cvd_z_score.flowscript

source path: kscripts/perfected/255_cvd_z_score.flowscript · sha256:0345bee5e75b01e21bc21ade94b17cb7eb7609ec4f6a6f3c65741f99267c5b2d

hash verified
//@version=2

// ============================================================================
// CVD Z-Score V2 — Perfected Edition
// Author: I (@IronEYan) | Perfected: kScript_Perfection_Engineer
// Tags: ADVANCED, CORE, #cvd, #zscore, #regime, #orderflow
//
// This indicator computes Cumulative Volume Delta (CVD) and normalizes it via
// rolling-window z-score, producing a stationary oscillator that signals when
// buying or selling pressure deviates significantly from its local mean.
// Regime detection across ±1σ/±2σ/±3σ bands, color-coded histogram fills,
// volume-confirmed extreme-event shape markers, and session statistics
// provide a complete orderflow toolkit.
//
// Academic foundation (exact papers & formulas):
//  1. 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.
//     [Formula] VPIN = σ_μ / (μ_b + μ_s); CVD builds the signed cumulative
//     of Δ = buy − sell volume. VPIN > 0.9 predicts short-term volatility.
//     DOI: https://doi.org/10.1093/rfs/hhr103
//
//  2. 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}
//     Cumulative OFI (CVD) linearly predicts short-term price changes:
//     Δp_t = λ·OFI_t + ε_t, where λ is inversely proportional to depth.
//     DOI: https://doi.org/10.1093/jjfinec/nbt003
//
//  3. Zhao & Palomar (2018), "Mean-Reverting Portfolio with Budget Constraint",
//     IEEE Trans. Signal Processing. Z-score entry/exit thresholds (±2σ, ±3σ)
//     are statistically optimal for mean-reverting series.
//
//  4. Lillo & Farmer (2004), "The Long Memory of the Efficient Market",
//     Studies in Nonlinear Dynamics & Econometrics. CVD exhibits long-memory
//     autocorrelation, justifying cumulative construction and rolling-window
//     standardisation.
//
//  5. Chordia, Roll & Subrahmanyam (2002), "Order Imbalance, Liquidity,
//     and Market Returns", JFE 65(1), 111–130. Extreme order imbalance predicts
//     return reversals. Directly motivates the σ-band regime design.
//     DOI: https://doi.org/10.1016/S0304-405X(02)00136-8
//
//  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 — Perfected Edition", position="offchart", axis=true)

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

// -- 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 smoothLen = input(name="smoothLen", type="number", defaultValue=3, label="EMA Smooth Length", constraints={min: 1, max: 20, step: 1}, group="Computation")
var sig1 = input(name="sig1", type="number", defaultValue=1.0, label="±1σ Moderate Threshold", constraints={min: 0.5, max: 2.0, step: 0.5}, group="Computation")
var sig2 = input(name="sig2", type="number", defaultValue=2.0, label="±2σ Significant Threshold", constraints={min: 1.0, max: 3.0, step: 0.5}, group="Computation")
var sig3 = input(name="sig3", type="number", defaultValue=3.0, label="±3σ Extreme Threshold", constraints={min: 2.0, max: 5.0, step: 0.5}, group="Computation")
var useVolConfirm = input(name="useVolConfirm", type="boolean", defaultValue=true, label="Use Volume Confirmation", group="Computation")
var volLookback = input(name="volLookback", type="number", defaultValue=20, label="Volume SMA Lookback", constraints={min: 5, max: 100, step: 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 showFill = input(name="showFill", type="boolean", defaultValue=true, label="Show Fill Between Z and Zero", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Extreme Shape Markers", group="Display")
var showBands = input(name="showBands", type="boolean", defaultValue=true, label="Show Sigma Band Lines", group="Display")
var showCVD = input(name="showCVD", type="boolean", defaultValue=false, label="Show Raw CVD Line", group="Display")
var showRegime = input(name="showRegime", type="boolean", defaultValue=true, label="Show Regime Table", group="Display")

// -- Colors --
var bullColor = input(name="bullColor", type="color", defaultValue="#26a69a", label="Bullish Color", group="Colors")
var bearColor = input(name="bearColor", type="color", defaultValue="#ef5350", label="Bearish Color", group="Colors")
var modBullColor = input(name="modBullColor", type="color", defaultValue="#4caf50", label="Moderate Bull Color", group="Colors")
var modBearColor = input(name="modBearColor", type="color", defaultValue="#e57373", label="Moderate Bear Color", group="Colors")
var sigBullColor = input(name="sigBullColor", type="color", defaultValue="#00e676", label="Significant Bull Color", group="Colors")
var sigBearColor = input(name="sigBearColor", type="color", defaultValue="#ff5252", label="Significant Bear Color", group="Colors")
var extBullColor = input(name="extBullColor", type="color", defaultValue="#00ff00", label="Extreme Bull Color", group="Colors")
var extBearColor = input(name="extBearColor", type="color", defaultValue="#ff0000", label="Extreme Bear Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#78909c", label="Neutral Color", group="Colors")
var cvdColor = input(name="cvdColor", type="color", defaultValue="#2962ff", label="CVD Line Color", group="Colors")

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

timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries buySell = buy_sell_volume(symbol=currentSymbol, exchange=currentExchange)

// Guard: halt until all external feeds have loaded to avoid NaN propagation
if (isnan(bars.close[0]) || !isnum(buySell.buy_volume) || !isnum(buySell.sell_volume)) {
    return
}

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

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

// -- 3.2 True cumulative CVD via static state (tracked for optional raw display) --
static cvdCum = 0.0
if (!isnan(delta[0])) {
    cvdCum = cvdCum + delta[0]
}

// -- 3.3 Rolling-window CVD (stationary approximation for z-score) --
// CVD_t = Σ_{i=0}^{W-1} Δ_{t-i}; we keep a rolling window so the series remains
// mean-reverting and amenable to z-score standardisation.
timeseries cvdWindow = sum(delta, zWindow)

// -- 3.4 Z-score normalisation (all denominators guarded against zero) --
// Z_t = (CVD_t − μ_t) / σ_t, where μ_t = SMA(CVD, W), σ_t = StDev(CVD, W).
// Guards: if σ_t == 0 we emit 0 to prevent division-by-zero crashes.
timeseries cvdMean = sma(cvdWindow, zWindow)
timeseries cvdStd = stdev(cvdWindow, zWindow)
timeseries cvdZ = (cvdStd > 0) ? (cvdWindow - cvdMean) / cvdStd : 0

// -- 3.5 Smooth the z-score for visual clarity --
timeseries cvdZSmooth = ema(cvdZ, smoothLen)

// -- 3.6 Volume confirmation (relative volume vs SMA) --
timeseries volSMA = sma(bars.volume, volLookback)
timeseries volRatio = (volSMA > 0) ? bars.volume / volSMA : 1
var volConfirm = (volRatio > 1.2) ? true : false

// -- 3.7 Regime detection (±1σ / ±2σ / ±3σ bands) --
var regimeExtBull = cvdZSmooth > sig3
var regimeExtBear = cvdZSmooth < -sig3
var regimeSigBull = cvdZSmooth > sig2 && !regimeExtBull
var regimeSigBear = cvdZSmooth < -sig2 && !regimeExtBear
var regimeModBull = cvdZSmooth > sig1 && !regimeSigBull && !regimeExtBull
var regimeModBear = cvdZSmooth < -sig1 && !regimeSigBear && !regimeExtBear
var regimeNeutral = !regimeModBull && !regimeModBear && !regimeSigBull && !regimeSigBear && !regimeExtBull && !regimeExtBear

// -- 3.8 Regime state tracking via static variables --
static lastRegime = 0
static regimeBullBars = 0
static regimeBearBars = 0
static regimeExtBullBars = 0
static regimeExtBearBars = 0
static totalExtBull = 0
static totalExtBear = 0

if (regimeExtBull) {
    regimeExtBullBars = regimeExtBullBars + 1
    regimeExtBearBars = 0
    regimeBearBars = 0
    regimeBullBars = regimeBullBars + 1
    lastRegime = 3
    totalExtBull = totalExtBull + 1
} else if (regimeExtBear) {
    regimeExtBearBars = regimeExtBearBars + 1
    regimeExtBullBars = 0
    regimeBullBars = 0
    regimeBearBars = regimeBearBars + 1
    lastRegime = -3
    totalExtBear = totalExtBear + 1
} else if (regimeSigBull) {
    regimeExtBullBars = 0
    regimeExtBearBars = 0
    regimeBearBars = 0
    regimeBullBars = regimeBullBars + 1
    lastRegime = 2
} else if (regimeSigBear) {
    regimeExtBullBars = 0
    regimeExtBearBars = 0
    regimeBullBars = 0
    regimeBearBars = regimeBearBars + 1
    lastRegime = -2
} else if (regimeModBull) {
    regimeExtBullBars = 0
    regimeExtBearBars = 0
    regimeBearBars = 0
    regimeBullBars = regimeBullBars + 1
    lastRegime = 1
} else if (regimeModBear) {
    regimeExtBullBars = 0
    regimeExtBearBars = 0
    regimeBullBars = 0
    regimeBearBars = regimeBearBars + 1
    lastRegime = -1
} else {
    regimeExtBullBars = 0
    regimeExtBearBars = 0
    regimeBullBars = 0
    regimeBearBars = 0
    lastRegime = 0
}

// -- 3.9 Color index for multi-level regime coloring --
// 0=extBull, 1=sigBull, 2=modBull, 3=neutral, 4=modBear, 5=sigBear, 6=extBear
var colorIdx = regimeExtBull ? 0 : (regimeSigBull ? 1 : (regimeModBull ? 2 : (regimeModBear ? 4 : (regimeSigBear ? 5 : (regimeExtBear ? 6 : 3)))))

// -- 3.10 Volume-confirmed extreme signals --
var volConfirmedExtBull = regimeExtBull && volConfirm
var volConfirmedExtBear = regimeExtBear && volConfirm

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

// ---------------------------------------------------------------------------
// 4. VISUALIZATION
// ---------------------------------------------------------------------------

// 4.1 Z-Score line (regime-colored)
if (showZLine) {
    plotLine(
        value=cvdZSmooth,
        width=2,
        colors=[extBullColor, sigBullColor, modBullColor, neutralColor, modBearColor, sigBearColor, extBearColor],
        colorIndex=colorIdx,
        label=["CVD Z-Score"],
        desc=["Smoothed CVD z-score; regime-colored by sigma level"]
    )
}

// 4.2 Histogram (plotBar) — multi-level regime coloring
if (showHistogram) {
    plotBar(
        value=cvdZSmooth,
        colors=[extBullColor, sigBullColor, modBullColor, neutralColor, modBearColor, sigBearColor, extBearColor],
        colorIndex=colorIdx,
        width=1,
        label=["CVD Z Histogram"],
        desc=["CVD z-score histogram; color-coded by sigma regime"]
    )
}

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

// 4.4 Extreme divergence shapes (plotShape)
if (showShapes && volConfirmedExtBull) {
    plotShape(
        value=sig3,
        shape="triangleup",
        colorIndex=extBullColor,
        width=3,
        label=["Extreme Buy Climax"],
        desc=["Volume-confirmed CVD Z > +3σ; potential buying climax / short squeeze"]
    )
}
if (showShapes && volConfirmedExtBear) {
    plotShape(
        value=-sig3,
        shape="triangledown",
        colorIndex=extBearColor,
        width=3,
        label=["Extreme Sell Climax"],
        desc=["Volume-confirmed CVD Z < −3σ; potential selling climax / long liquidation"]
    )
}

// 4.5 Optional raw CVD line (true cumulative from static state)
if (showCVD) {
    plotLine(
        value=cvdCum,
        width=1,
        colors=[cvdColor],
        label=["CVD (Raw Cumulative)"],
        desc=["True cumulative CVD from first bar"]
    )
}

// 4.6 Sigma band reference lines (hline)
if (showBands) {
    hline(value=0, color="#ffffff30", width=1)
    hline(value=sig1, color=transparency(modBullColor, 60), width=1)
    hline(value=-sig1, color=transparency(modBearColor, 60), width=1)
    hline(value=sig2, color=transparency(sigBullColor, 60), width=1)
    hline(value=-sig2, color=transparency(sigBearColor, 60), width=1)
    hline(value=sig3, color=transparency(extBullColor, 60), width=1)
    hline(value=-sig3, color=transparency(extBearColor, 60), width=1)
}

// 4.7 Regime table (last bar only)
if (showRegime && isLastBar) {
    var regimeText = regimeExtBull ? "EXTREME BULL" : (regimeExtBear ? "EXTREME BEAR" : (regimeSigBull ? "SIG BULL" : (regimeSigBear ? "SIG BEAR" : (regimeModBull ? "MOD BULL" : (regimeModBear ? "MOD BEAR" : "NEUTRAL")))))
    var regimeTextColor = regimeExtBull ? extBullColor : (regimeExtBear ? extBearColor : (regimeSigBull ? sigBullColor : (regimeSigBear ? sigBearColor : (regimeModBull ? modBullColor : (regimeModBear ? modBearColor : neutralColor)))))
    var volConfirmText = volConfirm ? "CONFIRMED" : "UNCONFIRMED"

    plotTable(
        data=[
            ["CVD Z-Score V2", regimeText],
            ["Z-Score", cvdZSmooth[0]],
            ["Volume Ratio", volRatio[0]],
            ["Volume", volConfirmText],
            ["Ext Bull Events", totalExtBull],
            ["Ext Bear Events", totalExtBear]
        ],
        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
    )
}