MM Flow
FlowScripts

Perfected FlowScript

CVD & Divergence (On-Chart)

CVD Divergence On-Chart V2 is indexed as 210_cvd_divergence_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

13.2 KB

Lines

292

Native Signal Candidates

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

4/4 guarded

Bearish Divergence

line 223:5

Trigger

(showDivShapes && bearDiv)

Value

bars.high * 1.002

Deps

bearDiv:timeseries, showDivShapes:input

Bullish Divergence

line 234:5

Trigger

(showDivShapes && bullDiv)

Value

bars.low * 0.998

Deps

bullDiv:timeseries, showDivShapes:input

Bull Regime

line 261:9

Trigger

(showDivShapes) && (crossUp)

Value

cvdZSmooth

Deps

crossUp:var, showDivShapes:input

Bear Regime

line 271:9

Trigger

(showDivShapes) && (crossDn)

Value

cvdZSmooth

Deps

crossDn:var, showDivShapes:input

210_cvd_divergence_on_chart.flowscript

source path: kscripts/perfected/210_cvd_divergence_on_chart.flowscript · sha256:ef535e9b005525dbe412d500f53137d833bae64d7362f72795e0d6d2265929e7

hash verified
//@version=2

// ============================================================================
// CVD Divergence On-Chart V2 — Price-CVD Divergence with Regime Detection
// Author: H (@heyyawn47) | Perfected: kScript_Perfection_Engineer
// Tags: CORE, #CVD, #divergence, #orderflow
//
// This on-chart indicator computes Cumulative Volume Delta (CVD) from native
// orderflow data (buy volume minus sell volume), plots it anchored to the
// price chart, and detects price-CVD structural divergence. Bullish divergence
// occurs when price makes a new low while CVD fails to confirm; bearish
// divergence when price makes a new high while CVD lags. Regime detection,
// z-score normalization, shape markers, and fill areas provide a complete
// microstructure divergence toolkit.
//
// 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_bid^i − E_ask^i); CVD = ΣOFI_t.
//     Cumulative OFI linearly predicts short-term price changes:
//     Δp_t = λ·OFI_t + ε_t, where λ ∝ 1/depth.
//     DOI: https://doi.org/10.1093/jjfinec/nbt003
//
//  2. 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 divergence-threshold design.
//     DOI: https://doi.org/10.1016/S0304-405X(02)00136-8
//
//  3. 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; cumulative measures
//     (CVD) capture persistent pressure that per-bar delta misses.
//
//  4. Lee & Ready (1991), "Inferring Trade Direction from Intraday Data",
//     Journal of Finance, 46(2), 733–746. Foundational tick-classification
//     algorithm (85–93% accuracy). Lee-Ready fallback: close > open → buy.
//     DOI: https://doi.org/10.1111/j.1540-6261.1991.tb02683.x
//
//  5. 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 Divergence On-Chart V2", position="onchart", axis=false)

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

// -- Computation --
var pivotWindow = input(name="pivotWindow", type="number", defaultValue=5, label="Pivot Window (bars)", constraints={min: 3, max: 21, step: 1}, group="Computation")
var cvdAnchor = input(name="cvdAnchor", type="string", defaultValue="0", label="CVD Anchor Price (0 = auto)", group="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="CVD EMA Smooth", constraints={min: 1, max: 20, step: 1}, group="Computation")
var divThreshold = input(name="divThreshold", type="number", defaultValue=2.0, label="Divergence Z-Score Threshold", constraints={min: 0.5, max: 4.0, step: 0.5}, group="Computation")

// -- Display --
var showCVD = input(name="showCVD", type="boolean", defaultValue=true, label="Show CVD Line", group="Display")
var showCVDZ = input(name="showCVDZ", type="boolean", defaultValue=true, label="Show CVD Z-Score", group="Display")
var showDivShapes = input(name="showDivShapes", type="boolean", defaultValue=true, label="Show Divergence Shapes", group="Display")
var showRegime = input(name="showRegime", type="boolean", defaultValue=true, label="Show Regime Fill", group="Display")
var showRawDelta = input(name="showRawDelta", type="boolean", defaultValue=false, label="Show Raw Delta Bars", group="Display")

// -- Colors --
var cvdColor = input(name="cvdColor", type="color", defaultValue="#ffffff", label="CVD Line 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")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#78909c", label="Neutral Color", group="Colors")
var upColor = input(name="upColor", type="color", defaultValue="#26a69a", label="Positive Delta Color", group="Colors")
var dnColor = input(name="dnColor", type="color", defaultValue="#ef5350", label="Negative Delta Color", group="Colors")

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

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

// Guard: halt until external feed has loaded to avoid NaN propagation
if (isnan(bars.close[0])) {
    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 upBar = bars.close >= bars.open
timeseries buyVol = isnum(taker.buy) ? taker.buy : (upBar ? bars.volume : 0)
timeseries sellVol = isnum(taker.sell) ? taker.sell : (upBar ? 0 : bars.volume)
timeseries delta = buyVol - sellVol

// -- 3.2 Cumulative CVD via static state (true cumulative, persists across bars) --
// static persists across bars; we guard each increment against NaN.
static cvd = 0.0
if (!isnan(delta[0])) {
    cvd = cvd + delta[0]
}

// -- 3.3 Rolling-window CVD (stationary approximation for z-score) --
// CVD_t = Σ_{i=0}^{W-1} Δ_{t-i} ; keeps the series mean-reverting for
// z-score standardisation. Complements the true cumulative cvd above.
timeseries rollingCVD = sum(delta, zWindow)

// -- 3.4 Z-score normalisation of rolling CVD (all denominators guarded) --
// Z_t = (CVD_t − μ_t) / σ_t. If σ_t == 0 emit 0 to prevent division-by-zero.
timeseries cvdMean = sma(rollingCVD, zWindow)
timeseries cvdStd  = stdev(rollingCVD, zWindow)
timeseries cvdZ = (cvdStd > 0) ? (rollingCVD - cvdMean) / cvdStd : 0

// -- 3.5 Smoothed CVD Z for cleaner regime reads --
timeseries cvdZSmooth = ema(cvdZ, smoothLen)

// -- 3.6 Anchor offset to position the CVD line on chart --
// Default anchor: current close price; user can override with a fixed value.
timeseries anchorPx = float(cvdAnchor) != 0 ? float(cvdAnchor) : bars.close

// Normalised CVD for plotting on chart: scale relative to CVD volatility and
// offset by anchor price so the line sits near price action.
timeseries cvdNorm = cvd / math.max(sma(source=math.abs(cvd), period=zWindow), 1e-9) * bars.close * 0.05 + anchorPx

// -- 3.7 Pivot detection on price and CVD --
// Price pivot high: current high equals highest over pivotWindow and not equal to prev high.
timeseries pricePivotHi = bars.high == highest(source=bars.high, period=pivotWindow) and bars.high[1] != highest(source=bars.high, period=pivotWindow)
timeseries pricePivotLo = bars.low == lowest(source=bars.low, period=pivotWindow) and bars.low[1] != lowest(source=bars.low, period=pivotWindow)

// CVD pivot detection on the rolling CVD series (not the anchored plot line)
timeseries cvdPivotHi = rollingCVD == highest(source=rollingCVD, period=pivotWindow)
timeseries cvdPivotLo = rollingCVD == lowest(source=rollingCVD, period=pivotWindow)

// -- 3.8 Divergence detection --
// Bearish divergence: price makes new high but CVD fails to confirm (weaker buying pressure).
// Bullish divergence: price makes new low but CVD fails to confirm (weaker selling pressure).
timeseries bearDiv = pricePivotHi and not cvdPivotHi
timeseries bullDiv = pricePivotLo and not cvdPivotLo

// -- 3.9 Regime detection on CVD Z-score --
// Configurable thresholds; no magic numbers. Divergence regimes flag when
// CVD Z-score is significantly positive (buy pressure) or negative (sell pressure).
var bullRegime = cvdZSmooth > divThreshold
var bearRegime = cvdZSmooth < -divThreshold
var neutralRegime = !bullRegime && !bearRegime

// -- 3.10 Static state tracking (session-level persistence) --
// Tracks divergence counts, regime duration, and last-detected divergence bar
// for context-aware alerting and confluence analysis.
static lastDivBar = 0
static bullDivCount = 0
static bearDivCount = 0
static lastRegime = 0
static bullRegimeBars = 0
static bearRegimeBars = 0

var currentBarIndex = bar_index[0]

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

    if (bullDiv) {
        bullDivCount = bullDivCount + 1
    }
    if (bearDiv) {
        bearDivCount = bearDivCount + 1
    }

    if (bullRegime) {
        bullRegimeBars = bullRegimeBars + 1
        bearRegimeBars = 0
        lastRegime = 1
    } else if (bearRegime) {
        bearRegimeBars = bearRegimeBars + 1
        bullRegimeBars = 0
        lastRegime = -1
    } else {
        bullRegimeBars = 0
        bearRegimeBars = 0
        lastRegime = 0
    }
}

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

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

// 4.1 Anchored CVD line (plotLine)
if (showCVD) {
    plotLine(
        value=cvdNorm,
        width=2,
        colors=[cvdColor],
        label=["CVD (anchored)"],
        desc=["Cumulative Volume Delta normalised and anchored near price; tracks net aggressive flow"]
    )
}

// 4.2 CVD Z-score (plotLine) with regime-coded fill area
// colorIndex maps: 0 = bullish, 1 = bearish, 2 = neutral
timeseries cvdZColorIdx = bullRegime ? 0 : (bearRegime ? 1 : 2)
if (showCVDZ) {
    plotLine(
        value=([cvdZSmooth, zeroLine]),
        width=2,
        colors=[bullDivColor, bearDivColor, neutralColor],
        colorIndex=cvdZColorIdx,
        label=["CVD Z-Score"],
        desc=["Rolling-window CVD standardised to z-score; filled histogram colour-coded by regime"],
        fill=true
    )
}

// 4.3 Divergence shape markers (plotShape)
// Bearish divergence: price high, CVD weak → potential top / distribution.
if (showDivShapes && bearDiv) {
    plotShape(
        value=bars.high * 1.002,
        shape="triangledown",
        color=bearDivColor,
        width=3,
        label=["Bearish Divergence"],
        desc=["Price made new high while CVD failed to confirm; weakening buy pressure / distribution"]
    )
}
// Bullish divergence: price low, CVD strong → potential bottom / accumulation.
if (showDivShapes && bullDiv) {
    plotShape(
        value=bars.low * 0.998,
        shape="triangleup",
        color=bullDivColor,
        width=3,
        label=["Bullish Divergence"],
        desc=["Price made new low while CVD held firm; weakening sell pressure / accumulation"]
    )
}

// 4.4 Raw per-bar delta as bars (plotBar) — sign-based colouring
if (showRawDelta) {
    plotBar(
        value=delta,
        colors=[upColor, dnColor],
        width=1,
        label=["Volume Delta"],
        desc=["Per-bar buy minus sell volume (positive = buyer-initiated, negative = seller-initiated)"]
    )
}

// 4.5 Regime transition shapes (plotShape) — CVD Z-score crosses threshold
if (showDivShapes) {
    var crossUp = cvdZSmooth >= divThreshold && !isnan(cvdZSmooth[1]) && cvdZSmooth[1] < divThreshold
    var crossDn = cvdZSmooth <= -divThreshold && !isnan(cvdZSmooth[1]) && cvdZSmooth[1] > -divThreshold

    if (crossUp) {
        plotShape(
            value=cvdZSmooth,
            shape="triangleup",
            color=bullDivColor,
            width=3,
            label=["Bull Regime"],
            desc=["CVD Z-Score crossed into bullish regime — buy pressure building"]
        )
    }
    if (crossDn) {
        plotShape(
            value=cvdZSmooth,
            shape="triangledown",
            color=bearDivColor,
            width=3,
            label=["Bear Regime"],
            desc=["CVD Z-Score crossed into bearish regime — sell pressure building"]
        )
    }
}

// 4.6 Reference thresholds (hline)
hline(value=0, color="#ffffff30", width=1)
if (showRegime) {
    hline(value=divThreshold, color=opacity(bullDivColor, 30), width=1)
    hline(value=-divThreshold, color=opacity(bearDivColor, 30), width=1)
}

// 4.7 Optional: divergence count label (plotText via plotLine value trick)
// Not directly available in kScript v2, but we expose the counts as series
// that can be plotted offchart by a companion indicator.