MM Flow
FlowScripts

Perfected FlowScript

cumulative volume delta z-score

CVD Z-Score — Perfected Edition is indexed as 185_cumulative_volume_delta_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

14.6 KB

Lines

371

Native Signal Candidates

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

4/4 guarded

Extreme Buy

line 285:9

Trigger

(showShapes) && (extBuy && extBullBars <= 2)

Value

sigma3

Deps

extBullBars:static, extBuy:var, showShapes:input

Extreme Sell

line 296:9

Trigger

(showShapes) && (extSell && extBearBars <= 2)

Value

-sigma3

Deps

extBearBars:static, extSell:var, showShapes:input

Strong Buy

line 307:9

Trigger

(showShapes) && (strBuy && !extBuy && extBullBars <= 1)

Value

sigma2

Deps

extBullBars:static, extBuy:var, showShapes:input, strBuy:var

Strong Sell

line 317:9

Trigger

(showShapes) && (strSell && !extSell && extBearBars <= 1)

Value

-sigma2

Deps

extBearBars:static, extSell:var, showShapes:input, strSell:var

185_cumulative_volume_delta_z_score.flowscript

source path: kscripts/perfected/185_cumulative_volume_delta_z_score.flowscript · sha256:c609fb6966cebbfcd5790b8dde69162cb2c0e6c960c9537abab3d89ec48c7182

hash verified
//@version=2

// ============================================================================
// Cumulative Volume Delta Z-Score — Perfected Edition
// Author: O (@Osifls K) | Perfected: kScript_Perfection_Engineer
// Tags: CORE, ADVANCED, #cvd, #volume, #zscore, #delta, #regime
//
// Z-score normalization applied to Cumulative Volume Delta (CVD) to identify
// statistical extremes in buying/selling pressure. Rolling-window CVD is
// standardized to produce a mean-reverting oscillator with ±1σ, ±2σ, ±3σ bands,
// regime detection, color-coded fills, and shape alerts at statistical extremes.
//
// 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}
//     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
//
//  2. Lillo & Farmer (2004), "The Long Memory of the Efficient Market".
//     Order flow has long-memory properties (power-law autocorrelations).
//     Supports using cumulative delta as a persistent signal rather than
//     per-bar noise.
//
//  3. Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint".
//     [Formula] z = (CVD − μ) / σ with threshold-based entry/exit at
//     ±1σ, ±2σ. Directly motivates the multi-band sigma design.
//
//  4. Chordia, Roll & Subrahmanyam (2002), "Order Imbalance, Liquidity,
//     and Market Returns", Journal of Financial Economics, 65(1), 111–130.
//     [Formula] Imbalance_t = Buy_t − Sell_t; extreme |Imbalance| predicts
//     return reversals. Directly motivates the extreme-threshold shape alerts.
//     DOI: https://doi.org/10.1016/S0304-405X(02)00136-8
//
//  5. Lee & Ready (1991), "Inferring Trade Direction from Intraday Data",
//     Journal of Finance, 46(2), 733–746. Foundational tick-classification
//     algorithm (85–93% accuracy) used when granular taker-buy/sell data
//     is unavailable: classify as buy if close > open, else sell.
//     DOI: https://doi.org/10.1111/j.1540-6261.1991.tb02683.x
//
//  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
//     every delta-based trading signal.
//     DOI: https://doi.org/10.2307/1913210
// ============================================================================

define(title="CVD Z-Score — Perfected Edition", position="offchart", axis=true)

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

// -- Computation --
var zLen = input(name="zLen", type="number", defaultValue=60, label="Z 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 cvdWindow = input(name="cvdWindow", type="number", defaultValue=500, label="CVD Rolling Window",
    constraints={min: 100, max: 1000, step: 50}, group="Computation")

// -- Thresholds --
var sigma1 = input(name="sigma1", type="number", defaultValue=1.0, label="±1σ Band",
    constraints={min: 0.5, max: 2.0, step: 0.5}, group="Thresholds")
var sigma2 = input(name="sigma2", type="number", defaultValue=2.0, label="±2σ Band",
    constraints={min: 1.0, max: 3.0, step: 0.5}, group="Thresholds")
var sigma3 = input(name="sigma3", type="number", defaultValue=3.0, label="±3σ Band",
    constraints={min: 2.0, max: 4.0, step: 0.5}, group="Thresholds")

// -- Display --
var showLine = input(name="showLine", type="boolean", defaultValue=true, label="Show Z Line", group="Display")
var showBars = input(name="showBars", type="boolean", defaultValue=true, label="Show Z Histogram", group="Display")
var showBandFill = input(name="showBandFill", type="boolean", defaultValue=true, label="Show Sigma Band Fill", group="Display")
var showZFill = input(name="showZFill", type="boolean", defaultValue=true, label="Show Zero-Line Fill", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Extreme Shapes", group="Display")
var showTaker = input(name="showTaker", type="boolean", defaultValue=false, label="Use Taker Volume (if available)", group="Display")

// -- Colors --
var lineColor = input(name="lineColor", type="color", defaultValue="#42a5f5", label="Z Line Color", group="Colors")
var upColor = input(name="upColor", type="color", defaultValue="#26a69a", label="Positive Color", group="Colors")
var dnColor = input(name="dnColor", type="color", defaultValue="#ef5350", label="Negative Color", group="Colors")
var bullColor = input(name="bullColor", type="color", defaultValue="#00c853", label="Bull Regime Color", group="Colors")
var bearColor = input(name="bearColor", type="color", defaultValue="#d50000", label="Bear Regime Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#78909c", label="Neutral Color", group="Colors")

// ---------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// ---------------------------------------------------------------------------
timeseries price = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries close = price.close
timeseries open = price.open
timeseries high = price.high
timeseries low = price.low
timeseries volume = price.volume

// Optional taker volume feed (preferred over estimation when available)
timeseries takerVol = source("taker_volume", currentSymbol, currentExchange)

if (isnan(close[0]) || isnan(volume[0])) {
    return
}

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

// -- 3.1 Per-bar volume delta --
// Lee-Ready (1991) fallback when taker feed is unavailable:
// close > open → buyer-initiated; else seller-initiated.
// When taker.buy/sell is available, prefer direct feed for higher accuracy.
timeseries delta
if (showTaker && isnum(takerVol.buy) && isnum(takerVol.sell)) {
    delta = takerVol.buy - takerVol.sell
} else {
    // Bulk Volume Classification (BVC) proxy: estimate buy/sell from close position within bar
    timeseries rng = math.max(high - low, 0.0001)
    timeseries closePos = (close - low) / rng
    delta = (closePos - 0.5) * 2 * volume  // scale to [-volume, +volume]
}

// -- 3.2 Rolling-window CVD (stationary approximation) --
// CVD_t = Σ_{i=0}^{W-1} Δ_{t-i} ; rolling window keeps series mean-reverting.
timeseries cvd = sum(delta, cvdWindow)

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

// ---------------------------------------------------------------------------
// 4. Z-SCORE NORMALIZATION
// ---------------------------------------------------------------------------
// Z_t = (CVD_t − μ_t) / σ_t, where μ_t = SMA(CVD, W), σ_t = StDev(CVD, W).
// All denominators guarded against zero.
timeseries cvdMean = sma(cvd, zLen)
timeseries cvdStd = stdev(cvd, zLen)
timeseries rawZ = (cvdStd > 0) ? (cvd - cvdMean) / cvdStd : 0
timeseries zSmooth = ema(rawZ, smoothLen)

// ---------------------------------------------------------------------------
// 5. REGIME DETECTION
// ---------------------------------------------------------------------------
// Regime classification by sigma bands:
//   Extreme Buy:  z > +3σ
//   Strong Buy:   +2σ < z ≤ +3σ
//   Buy:          +1σ < z ≤ +2σ
//   Neutral:      −1σ ≤ z ≤ +1σ
//   Sell:         −2σ ≤ z < −1σ
//   Strong Sell:  −3σ ≤ z < −2σ
//   Extreme Sell: z < −3σ

var extBuy = zSmooth > sigma3
var strBuy = zSmooth > sigma2 && zSmooth <= sigma3
var buyRegime = zSmooth > sigma1 && zSmooth <= sigma2
var neutralRegime = zSmooth >= -sigma1 && zSmooth <= sigma1
var sellRegime = zSmooth < -sigma1 && zSmooth >= -sigma2
var strSell = zSmooth < -sigma2 && zSmooth >= -sigma3
var extSell = zSmooth < -sigma3

// ---------------------------------------------------------------------------
// 6. STATIC STATE TRACKING — Consecutive bars in regime
// ---------------------------------------------------------------------------
static bullBars = 0
static bearBars = 0
static extBullBars = 0
static extBearBars = 0

if (zSmooth > 0) {
    bullBars = bullBars + 1
    bearBars = 0
} else {
    bearBars = bearBars + 1
    bullBars = 0
}

if (extBuy) {
    extBullBars = extBullBars + 1
} else {
    extBullBars = 0
}

if (extSell) {
    extBearBars = extBearBars + 1
} else {
    extBearBars = 0
}

// ---------------------------------------------------------------------------
// 7. VISUALIZATION
// ---------------------------------------------------------------------------

// 7.1 Z-Score line (regime-colored)
if (showLine) {
    timeseries zLineColorVal = extBuy ? bullColor : (extSell ? bearColor : (zSmooth > 0 ? upColor : dnColor))
    plotLine(
        value=zSmooth,
        width=2,
        colors=[zLineColorVal],
        label=["CVD Z-Score"],
        desc=["Smoothed z-score of rolling CVD; mean-reverting around 0"]
    )
}

// 7.2 Z-Score histogram (regime-colored bars)
if (showBars) {
    // Color index: 0=extreme buy, 1=strong buy, 2=buy, 3=neutral, 4=sell, 5=strong sell, 6=extreme sell
    timeseries barColorIdx
    if (extBuy) {
        barColorIdx = 0
    } else if (strBuy) {
        barColorIdx = 1
    } else if (buyRegime) {
        barColorIdx = 2
    } else if (neutralRegime) {
        barColorIdx = 3
    } else if (sellRegime) {
        barColorIdx = 4
    } else if (strSell) {
        barColorIdx = 5
    } else {
        barColorIdx = 6
    }

    plotBar(
        value=zSmooth,
        colors=[bullColor, upColor, upColor, neutralColor, dnColor, dnColor, bearColor],
        colorIndex=barColorIdx,
        width=1,
        label=["CVD Z Histogram"],
        desc=["Z-score histogram colored by sigma regime"]
    )
}

// 7.3 Zero-line fill (positive vs negative)
if (showZFill) {
    var isPos = zSmooth > 0
    plotLine(
        value=[zSmooth, 0],
        width=1,
        colors=[transparency(upColor, 20), transparency(dnColor, 20)],
        colorIndex=isPos ? 0 : 1,
        fill=true,
        label=["Z Fill"],
        desc=["Fill between z-score and zero line"]
    )
}

// 7.4 Sigma band fills (±1σ, ±2σ, ±3σ)
if (showBandFill) {
    // ±1σ band (lightest)
    plotLine(
        value=[sigma1, -sigma1],
        width=1,
        colors=[transparency(neutralColor, 90)],
        fill=true,
        label=["±1σ Band"],
        desc=["±1 standard deviation band (68% confidence)"]
    )
    // ±2σ band (medium)
    plotLine(
        value=[sigma2, -sigma2],
        width=1,
        colors=[transparency(upColor, 85)],
        fill=true,
        label=["±2σ Band"],
        desc=["±2 standard deviation band (95% confidence)"]
    )
    // ±3σ band (strongest)
    plotLine(
        value=[sigma3, -sigma3],
        width=1,
        colors=[transparency(bullColor, 80)],
        fill=true,
        label=["±3σ Band"],
        desc=["±3 standard deviation band (99.7% confidence)"]
    )
}

// 7.5 Extreme shape alerts
if (showShapes) {
    // Extreme buy shape (≥ +3σ)
    if (extBuy && extBullBars <= 2) {
        plotShape(
            value=sigma3,
            shape="triangleup",
            colorIndex=bullColor,
            width=3,
            label=["Extreme Buy"],
            desc=["CVD Z-Score exceeded +" + sigma3 + "σ; extreme buying pressure — potential exhaustion / top"]
        )
    }
    // Extreme sell shape (≤ −3σ)
    if (extSell && extBearBars <= 2) {
        plotShape(
            value=-sigma3,
            shape="triangledown",
            colorIndex=bearColor,
            width=3,
            label=["Extreme Sell"],
            desc=["CVD Z-Score exceeded −" + sigma3 + "σ; extreme selling pressure — potential exhaustion / bottom"]
        )
    }
    // ±2σ threshold shapes (second-tier alert)
    if (strBuy && !extBuy && extBullBars <= 1) {
        plotShape(
            value=sigma2,
            shape="arrowup",
            colorIndex=upColor,
            width=2,
            label=["Strong Buy"],
            desc=["CVD Z-Score above +" + sigma2 + "σ; strong buying pressure"]
        )
    }
    if (strSell && !extSell && extBearBars <= 1) {
        plotShape(
            value=-sigma2,
            shape="arrowdown",
            colorIndex=dnColor,
            width=2,
            label=["Strong Sell"],
            desc=["CVD Z-Score below −" + sigma2 + "σ; strong selling pressure"]
        )
    }
}

// ---------------------------------------------------------------------------
// 8. REFERENCE HORIZONTAL LINES
// ---------------------------------------------------------------------------
hline(value=0,       color="#ffffff30", width=1)
hline(value=sigma1,  color="#ffffff20", width=1)
hline(value=-sigma1, color="#ffffff20", width=1)
hline(value=sigma2,  color="#ffeb3b20", width=1)
hline(value=-sigma2, color="#ffeb3b20", width=1)
hline(value=sigma3,  color="#ff525220", width=1)
hline(value=-sigma3, color="#00e67620", width=1)

// ---------------------------------------------------------------------------
// 9. REGIME TABLE (last bar only)
// ---------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = extBuy ? "EXTREME BUY" : (strBuy ? "STRONG BUY" : (buyRegime ? "BUY" : (extSell ? "EXTREME SELL" : (strSell ? "STRONG SELL" : (sellRegime ? "SELL" : "NEUTRAL")))))
    var regimeTextColor = extBuy ? bullColor : (extSell ? bearColor : (zSmooth > 0 ? upColor : dnColor))

    plotTable(
        data=[
            ["CVD Z-Score — Perfected", regimeText],
            ["Z-Score", zSmooth[0]],
            ["CVD (rolling)", cvd[0]],
            ["CVD (cumulative)", cvdCum],
            ["Bull Bars", bullBars],
            ["Bear Bars", bearBars],
            ["±1σ Band", "±" + sigma1],
            ["±2σ Band", "±" + sigma2],
            ["±3σ Band", "±" + sigma3]
        ],
        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
    )
}