MM Flow
FlowScripts

Perfected FlowScript

CVD ON- CHART

CVD On-Chart V2 is indexed as 018_cvd_on_chart.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

onchart

Axis

false

Size

12.9 KB

Lines

280

Native Signal Candidates

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

2/2 guarded

Bull Div

line 245:9

Trigger

(showDivergence) && (bullishDiv)

Value

bars.low

Deps

bullishDiv:var, showDivergence:input

Bear Div

line 255:9

Trigger

(showDivergence) && (bearishDiv)

Value

bars.high

Deps

bearishDiv:var, showDivergence:input

018_cvd_on_chart.flowscript

source path: kscripts/perfected/018_cvd_on_chart.flowscript · sha256:9b1c7b74fef24f29fa080cab2e6b97f8d5258793531f18cc5dc028790957f83d

hash verified
//@version=2

// ============================================================================
// CVD On-Chart V2 — Production-Quality Cumulative Volume Delta with Divergence
// Author: L (@leader56)  |  Perfected by: kScript Perfection Engineer
// Tags: CORE, #CVD, #Cumulative, #Volume, #Delta, #Divergence, #OnChart
//
// Cumulative Volume Delta (CVD) plotted directly on the price chart with
// divergence detection, color coding by slope (acceleration), fill areas
// between CVD and a signal line, and shape markers for divergence signals.
//
// FORMULA FOUNDATION:
// 1. CVD_t = Σ_{i=0}^{t} Δ_i where Δ_i = BuyVol_i − SellVol_i (Lee-Ready 1991).
// 2. Divergence Detection: price makes higher high but CVD makes lower high →
//    bearish divergence (distribution). Price lower low + CVD higher low →
//    bullish divergence (accumulation). Per Chordia et al. (2002) and NexusFi
//    community research on the four CVD states.
// 3. Slope Color Coding: CVD slope > 0 and increasing = green (accelerating up);
//    CVD slope < 0 and decreasing = red (accelerating down). Per Cont et al.
//    (2014) linear price-impact model: ΔP ∝ λ × OFI, so slope acceleration
//    flags strengthening or weakening pressure.
// 4. Signal Line: EMA(CVD, smoothLen) — fill area between CVD and signal
//    line shows momentum divergence / convergence.
//
// RESEARCH BASIS:
//  • Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events",
//    J. Financial Econometrics 12(1), 47–88. DOI: 10.1093/jjfinec/nbt003
//    OFI linearly predicts short-term price changes; cumulative OFI = CVD.
//  • Lillo & Farmer (2004), "The Long Memory of the Efficient Market", Studies
//    in Nonlinear Dynamics & Econometrics 8(3), 1–35. Order flow long memory
//    justifies cumulative measures over per-bar delta. arXiv: cond-mat/0311053
//  • Chordia, Roll & Subrahmanyam (2002), "Order Imbalance, Liquidity, and
//    Market Returns", J. Financial Economics 65(1), 111–130. Extreme imbalances
//    predict return reversals; divergence between CVD and price flags reversals.
//    DOI: 10.1016/S0304-405X(02)00136-8
//  • Kyle (1985), "Continuous Auctions and Insider Trading", Econometrica 53(6),
//    1315–1335. Kyle's λ: price-impact coefficient. CVD slope ∝ order flow.
//    DOI: 10.2307/1913210
//  • Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint".
//    Z-score triggers for divergence detection: z̄_t = (CVD_t − μ_CVD) / σ_CVD.
//  • NexusFi (2026), "Delta Analysis & Cumulative Volume Delta (CVD)". Four CVD
//    states: (1) confirms price, (2) diverges from price, (3) builds while price
//    stalls, (4) fails to confirm. Community-validated divergence framework.
// ============================================================================

define(title="CVD On-Chart V2", position="onchart", axis=false)

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

// --- Computation ---
var smoothLen = input(name="smoothLen", type="number", defaultValue=5, label="Signal Line EMA Length", constraints={min: 1, max: 50, step: 1}, group="Computation")
var divLookback = input(name="divLookback", type="number", defaultValue=10, label="Divergence Lookback (bars)", constraints={min: 3, max: 50, step: 1}, group="Computation")
var zWindow = input(name="zWindow", type="number", defaultValue=50, label="CVD Z-Score Window", constraints={min: 10, max: 200, step: 5}, group="Computation")

// --- Display ---
var showCVDLine = input(name="showCVDLine", type="boolean", defaultValue=true, label="Show CVD Line", group="Display")
var showSignalLine = input(name="showSignalLine", type="boolean", defaultValue=true, label="Show Signal Line (EMA)", group="Display")
var showFill = input(name="showFill", type="boolean", defaultValue=true, label="Show Fill Between CVD & Signal", group="Display")
var showDivergence = input(name="showDivergence", type="boolean", defaultValue=true, label="Show Divergence Shapes", group="Display")
var showSlopeColors = input(name="showSlopeColors", type="boolean", defaultValue=true, label="Show Slope Color Coding", group="Display")
var showCVDZ = input(name="showCVDZ", type="boolean", defaultValue=false, label="Show CVD Z-Score (offchart)", group="Display")

// --- Colors ---
var bullColor = input(name="bullColor", type="color", defaultValue="#26a69a", label="Bullish CVD Color", group="Colors")
var bearColor = input(name="bearColor", type="color", defaultValue="#ef5350", label="Bearish CVD Color", group="Colors")
var accelUpColor = input(name="accelUpColor", type="color", defaultValue="#00e676", label="Accelerating Up Color", group="Colors")
var accelDnColor = input(name="accelDnColor", type="color", defaultValue="#ff1744", label="Accelerating Down Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#9e9e9e", label="Neutral Color", group="Colors")
var bullDivColor = input(name="bullDivColor", type="color", defaultValue="#00c853", label="Bullish Divergence Color", group="Colors")
var bearDivColor = input(name="bearDivColor", type="color", defaultValue="#d50000", label="Bearish Divergence 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)

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

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

// -- 3.1 Per-bar buy/sell volume (Lee-Ready 1991 classification) --
// When taker.buy/sell is available, prefer direct feed. Otherwise tick test.

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 Cumulative Volume Delta (CVD) via static state --
// CVD_t = Σ_{i=0}^{t} Δ_i ; static persists across bars.
// Per Cont et al. (2014) and Lillo & Farmer (2004): cumulative measures capture
// sustained order-flow pressure that drives trends.

static cvdCum = 0.0

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

// -- 3.3 Signal line (EMA of CVD) --
// Smoothing the CVD gives a reference line for fill areas and divergence.
timeseries signalLine = ema(cvdCum, smoothLen)

// -- 3.4 CVD slope (first difference) for acceleration coloring --
// Slope_t = CVD_t − CVD_{t−1} ≈ Δ_t (the per-bar delta)
// Slope change = Slope_t − Slope_{t−1} = acceleration
timeseries cvdSlope = !isnan(cvdCum[1]) ? cvdCum - cvdCum[1] : 0
timeseries slopeChange = !isnan(cvdSlope[1]) ? cvdSlope - cvdSlope[1] : 0

// Acceleration regime:
//  accelUp   = slope > 0 and slope increasing  (green = strengthening buy pressure)
//  accelDn   = slope < 0 and slope decreasing  (red = strengthening sell pressure)
//  decelUp   = slope > 0 and slope decreasing  (fading buy pressure)
//  decelDn   = slope < 0 and slope increasing  (fading sell pressure)
var accelUp = cvdSlope > 0 && slopeChange > 0
var accelDn = cvdSlope < 0 && slopeChange < 0
var decelUp = cvdSlope > 0 && slopeChange <= 0
var decelDn = cvdSlope < 0 && slopeChange >= 0

// Color index for slope: 0=accelUp, 1=decelUp, 2=neutral, 3=decelDn, 4=accelDn
var slopeColorIdx = accelUp ? 0 : (decelUp ? 1 : (decelDn ? 3 : (accelDn ? 4 : 2)))

// -- 3.5 Divergence detection (CVD vs price) --
// Bullish divergence: price makes lower low, CVD makes higher low
// Bearish divergence: price makes higher high, CVD makes lower high
// Per Chordia et al. (2002): extreme imbalances predict reversals.
// Per NexusFi (2026): four CVD states — divergence is the reversal state.

// Price swing highs / lows over lookback window
var priceHigh = highest(bars.high, divLookback)
var priceLow = lowest(bars.low, divLookback)
var pricePrevHigh = highest(bars.high[1], divLookback)
var pricePrevLow = lowest(bars.low[1], divLookback)

// CVD swing highs / lows over lookback window
var cvdHigh = highest(cvdCum, divLookback)
var cvdLow = lowest(cvdCum, divLookback)
var cvdPrevHigh = highest(cvdCum[1], divLookback)
var cvdPrevLow = lowest(cvdCum[1], divLookback)

// Bearish divergence: price higher high, CVD lower high
var bearishDiv = bars.high >= priceHigh && cvdCum < cvdPrevHigh && !isnan(cvdCum[1])

// Bullish divergence: price lower low, CVD higher low
var bullishDiv = bars.low <= priceLow && cvdCum > cvdPrevLow && !isnan(cvdCum[1])

// -- 3.6 CVD z-score (for optional offchart display) --
// Z_t = (CVD_t − μ_t) / σ_t over rolling window.
// Per Zhao & Palomar (2018): standardized deviations from equilibrium.
timeseries cvdMean = sma(cvdCum, zWindow)
timeseries cvdStd = stdev(cvdCum, zWindow)
timeseries cvdZ = cvdStd > 0 ? (cvdCum - cvdMean) / cvdStd : 0

// -- 3.7 Static state tracking (session-level persistence) --
// Tracks divergence counts, CVD extremes, and slope regime persistence.

static lastBarIndex = 0
static bullishDivCount = 0
static bearishDivCount = 0
static sessionHighCVD = -999999999999.0
static sessionLowCVD = 999999999999.0
static lastSlopeRegime = 2  // 0=accelUp, 1=decelUp, 2=neutral, 3=decelDn, 4=accelDn
static regimeChangeCount = 0

var currentBarIndex = bar_index[0]

if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
    lastBarIndex = currentBarIndex

    if (cvdCum > sessionHighCVD) {
        sessionHighCVD = cvdCum
    }
    if (cvdCum < sessionLowCVD) {
        sessionLowCVD = cvdCum
    }

    if (bullishDiv) {
        bullishDivCount = bullishDivCount + 1
    }
    if (bearishDiv) {
        bearishDivCount = bearishDivCount + 1
    }

    if (lastSlopeRegime != slopeColorIdx) {
        lastSlopeRegime = slopeColorIdx
        regimeChangeCount = regimeChangeCount + 1
    }
}

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

// 4.1 CVD line with slope-based color coding
// Color by acceleration: green=accelerating up, red=accelerating down,
// lighter shades = decelerating (fading pressure)
if (showCVDLine) {
    plotLine(
        value=cvdCum,
        width=3,
        colors=[accelUpColor, bullColor, neutralColor, bearColor, accelDnColor],
        colorIndex=slopeColorIdx,
        label=["CVD"],
        desc=["Cumulative Volume Delta (CVD). Color = slope acceleration: green=accel up, red=accel down, light=decelerating. Kyle (1985) λ model."]
    )
}

// 4.2 Signal line (EMA of CVD)
if (showSignalLine) {
    plotLine(
        value=signalLine,
        width=2,
        colors=[neutralColor],
        label=["Signal Line"],
        desc=["EMA of CVD — reference line for momentum divergence / convergence detection"]
    )
}

// 4.3 Fill area between CVD and signal line
// Positive fill when CVD above signal (buy pressure building)
// Negative fill when CVD below signal (sell pressure building)
if (showFill) {
    var fillColor = cvdCum > signalLine ? opacity(bullColor, 30) : opacity(bearColor, 30)
    plotLine(
        value=([cvdCum, signalLine]),
        width=1,
        colors=[fillColor],
        label=["CVD Fill"],
        desc=["Fill between CVD and signal line; opacity indicates momentum divergence magnitude"],
        fill=true
    )
}

// 4.4 Divergence shape markers (Chordia et al. 2002 reversal signals)
if (showDivergence) {
    if (bullishDiv) {
        plotShape(
            value=bars.low,
            shape="triangleup",
            color=bullDivColor,
            width=3,
            label=["Bull Div"],
            desc=["Bullish divergence: price lower low + CVD higher low — accumulation signal (Chordia et al. 2002)"]
        )
    }
    if (bearishDiv) {
        plotShape(
            value=bars.high,
            shape="triangledown",
            color=bearDivColor,
            width=3,
            label=["Bear Div"],
            desc=["Bearish divergence: price higher high + CVD lower high — distribution signal (Chordia et al. 2002)"]
        )
    }
}

// 4.5 CVD Z-score line (optional offchart display)
if (showCVDZ) {
    plotLine(
        value=cvdZ,
        width=2,
        colors=[bullColor, bearColor, neutralColor],
        colorIndex=cvdZ > 1.0 ? 0 : (cvdZ < -1.0 ? 1 : 2),
        label=["CVD Z-Score"],
        desc=["Standardized CVD deviation from mean (Zhao & Palomar 2018); |z|>2 = statistically significant"]
    )
    hline(value=0, color="#ffffff30", width=1)
    hline(value=2, color="#ffffff20", width=1)
    hline(value=-2, color="#ffffff20", width=1)
}