MM Flow
FlowScripts

Perfected FlowScript

Reset-Rolling CVD (AccumLength Cummulative Volume Delta) [Bars]

Reset-Rolling CVD [Bars] Perfected is indexed as 065_reset_rolling_cvd_bars.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.8 KB

Lines

273

Native Signal Candidates

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

2/2 guarded

CVD Cross Up

line 230:5

Trigger

(showZeroCross && zeroCrossUp)

Value

cvdSm

Deps

showZeroCross:input, zeroCrossUp:var

CVD Cross Down

line 240:5

Trigger

(showZeroCross && zeroCrossDown)

Value

cvdSm

Deps

showZeroCross:input, zeroCrossDown:var

065_reset_rolling_cvd_bars.flowscript

source path: kscripts/perfected/065_reset_rolling_cvd_bars.flowscript · sha256:87a3fd5d8dc98fcdb5ca9a891e2cd4f27b6ca06c39c4d56753a38bab12c4449e

hash verified
//@version=2
// ============================================================================
// Reset-Rolling CVD (Cumulative Volume Delta) [Bars] — Perfected Edition
// Author: moeKiwiSAMA (@moeKiwiSAMA) | Perfected: kScript_Perfection_Engineer
// Tags: ADVANCED, CORE, #VolumeDelta, #CVD, #Reset-Rolling, #LeeReady
//
// Production-grade cumulative volume delta with explicit bar-based reset logic,
// Lee-Ready volume classification, color-coded fill, zero-cross shapes, and
// static state tracking for reset consistency.
//
// Academic foundations:
//  - 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); linear price-impact model:
//    Δp_t = λ·OFI_t + ε_t. Validates that cumulative order flow imbalance
//    drives short-term price changes.
//    DOI: https://doi.org/10.1093/jjfinec/nbt003
//
//  - Lillo & Farmer (2004), "The Long Memory of the Efficient Market".
//    Order flow autocorrelations decay as a power law; cumulative measures
//    capture sustained pressure and institutional footprint.
//
//  - Easley, López de Prado & O'Hara (2012), "Bulk Classification of Trading
//    Activity" (BVC). Probabilistic volume classification: buyVol = V·(C−L)/(H−L);
//    sellVol = V·(H−C)/(H−L). Used as fallback when tick-level taker data
//    is unavailable.
//
//  - Lee & Ready (1991), "Inferring Trade Direction from Intraday Data",
//    Journal of Finance, 46(2), 733–746.
//    Quote-rule classification: trade at ask = buyer-initiated (+),
//    at bid = seller-initiated (−). Tick-test fallback: close vs previous
//    close. 85–93% accuracy on NYSE TAQ data.
//    DOI: https://doi.org/10.1111/j.1540-6261.1991.tb02683.x
//
//  - Bouchaud, Farmer & Lillo (2009), "How Markets Slowly Digest Changes
//    in Supply and Demand", Nature, 200. Liquidity memory framework explains
//    why CVD is useful for detecting accumulation/distribution phases.
// ============================================================================

define(
    title="Reset-Rolling CVD [Bars] Perfected",
    position="offchart",
    axis=true
)

// ---------------------------------------------------------------------------
// User Inputs — all grouped, all numeric inputs carry constraints
// ---------------------------------------------------------------------------

// --- Computation ---
var resetLen = input(name="resetLen", type="number", defaultValue=24, label="Reset Length (bars)", constraints={min: 2, max: 500, step: 1}, group="Computation")
var smoothLen = input(name="smoothLen", type="number", defaultValue=2, label="Smoothing Length (EMA)", constraints={min: 1, max: 50, step: 1}, group="Computation")
var classifyMethod = input(name="classifyMethod", type="select", defaultValue="Lee-Ready", label="Volume Classification", options=["Lee-Ready", "Tick Rule", "BVC (Range)"], group="Computation")

// --- Display ---
var showFill = input(name="showFill", type="boolean", defaultValue=true, label="Show Fill vs Zero", group="Display")
var showZeroCross = input(name="showZeroCross", type="boolean", defaultValue=true, label="Show Zero-Cross Shapes", group="Display")
var showDelta = input(name="showDelta", type="boolean", defaultValue=false, label="Show Raw Delta Bars", group="Display")
var showCumul = input(name="showCumul", type="boolean", defaultValue=false, label="Show True Cumulative CVD", group="Display")
var lineWidth = input(name="lineWidth", type="number", defaultValue=2, label="Line Width", constraints={min: 1, max: 4, step: 1}, group="Display")
var shapeSize = input(name="shapeSize", type="number", defaultValue=2, label="Shape Size", constraints={min: 1, max: 4, step: 1}, group="Display")

// --- Colors ---
var upColor = input(name="upColor", type="color", defaultValue="#26a69a", label="Bullish Color", group="Colors")
var dnColor = input(name="dnColor", type="color", defaultValue="#ef5350", label="Bearish Color", group="Colors")
var lineColor = input(name="lineColor", type="color", defaultValue="#ffffff", label="Line Color", group="Colors")
var crossUpColor = input(name="crossUpColor", type="color", defaultValue="#00c853", label="Cross Up Color", group="Colors")
var crossDownColor = input(name="crossDownColor", type="color", defaultValue="#d50000", label="Cross Down Color", group="Colors")

// ---------------------------------------------------------------------------
// Data Sources
// ---------------------------------------------------------------------------
timeseries pxTS = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries o = pxTS.open
timeseries c = pxTS.close
timeseries h = pxTS.high
timeseries l = pxTS.low
timeseries v = pxTS.volume

// isnan guard: prevent computation on incomplete data
if (isnan(c[0]) || isnan(h[0]) || isnan(l[0]) || isnan(o[0]) || isnan(v[0])) {
    return
}

// ---------------------------------------------------------------------------
// Lee-Ready Volume Classification
// ---------------------------------------------------------------------------
// Lee-Ready (1991) algorithm adapted for OHLCV bar data:
//   1. Quote-rule proxy: close vs midpoint of (high, low).
//   2. Tick-test fallback: close vs previous close.
//   3. Static persistence: repeat last classification for indeterminate bars.
//
// When taker-buy/sell data is available via the `source` API, it is preferred
// for higher accuracy. This script uses the Lee-Ready proxy as the default.
// ---------------------------------------------------------------------------

timeseries mid = (h + l) / 2.0
timeseries prevClose = isnan(c[1]) ? c : c[1]
timeseries range_ = h - l

// Static state for Lee-Ready tie-breaking (persists across bars)
static prevLeeReady = true  // true = buy, false = sell
static trueCumul = 0.0      // true cumulative CVD (never resets, for reference)

// --- Classification ---
timeseries buyVol = 0.0
timeseries sellVol = 0.0

if (classifyMethod == "Lee-Ready") {
    // Lee-Ready: midpoint test → tick test → static fallback
    var leeReadyBuy = false
    if (c > mid) {
        leeReadyBuy = true
    } else if (c < mid) {
        leeReadyBuy = false
    } else if (c > prevClose) {
        leeReadyBuy = true
    } else if (c < prevClose) {
        leeReadyBuy = false
    } else {
        leeReadyBuy = prevLeeReady
    }
    buyVol = leeReadyBuy ? v : 0.0
    sellVol = leeReadyBuy ? 0.0 : v
    if (!isLiveUpdate) {
        prevLeeReady = leeReadyBuy
    }
} else if (classifyMethod == "Tick Rule") {
    // Classic tick rule: close > open = buyer-initiated
    buyVol = c > o ? v : 0.0
    sellVol = c <= o ? v : 0.0
} else if (classifyMethod == "BVC (Range)") {
    // Bulk Volume Classification (Easley et al. 2012)
    // buyVol = V * (close − low) / (high − low)
    // sellVol = V * (high − close) / (high − low)
    buyVol = range_ > 0 ? v * (c - l) / range_ : v * 0.5
    sellVol = range_ > 0 ? v * (h - c) / range_ : v * 0.5
}

// Per-bar delta: buy volume minus sell volume
timeseries delta = buyVol - sellVol

// ---------------------------------------------------------------------------
// Rolling CVD with Reset (static bar counter for reset tracking)
// ---------------------------------------------------------------------------
// The CVD resets every `resetLen` bars using a static counter. On reset,
// the counter returns to 1 and accumulation begins anew. The `sum` function
// computes the rolling sum of the last `barCount` deltas, which is
// equivalent to cumulative delta from the reset point.
// ---------------------------------------------------------------------------

static barCount = 0
barCount = barCount + 1
if (barCount > resetLen) {
    barCount = 1
}

// Rolling sum of delta over the current reset window
timeseries cvd = sum(delta, barCount)

// True cumulative CVD (never resets, for optional reference display)
if (!isLiveUpdate && !isnan(delta[0])) {
    trueCumul = trueCumul + delta[0]
}

// EMA smoothing
timeseries cvdSm = smoothLen > 1 ? ema(cvd, smoothLen) : cvd

// ---------------------------------------------------------------------------
// Regime Detection & Zero-Cross Detection
// ---------------------------------------------------------------------------
// Color coding by sign: positive = bullish (buy pressure),
// negative = bearish (sell pressure).
// ---------------------------------------------------------------------------

timeseries zeroLine = 0.0
timeseries fillColorIdx = cvdSm >= 0 ? 0 : 1

// Zero-cross detection with NaN guard on first bar
timeseries prevCvdSm = isnan(cvdSm[1]) ? 0.0 : cvdSm[1]
var zeroCrossUp = prevCvdSm < 0 && cvdSm >= 0
var zeroCrossDown = prevCvdSm > 0 && cvdSm <= 0

// Static state for consecutive regime tracking
static bullBars = 0
static bearBars = 0

if (!isLiveUpdate) {
    if (cvdSm > 0) {
        bullBars = bullBars + 1
        bearBars = 0
    } else if (cvdSm < 0) {
        bearBars = bearBars + 1
        bullBars = 0
    } else {
        bullBars = 0
        bearBars = 0
    }
}

// ---------------------------------------------------------------------------
// Visualization
// ---------------------------------------------------------------------------

// --- CVD Line (regime-colored) ---
plotLine(
    value=cvdSm,
    width=lineWidth,
    colors=[upColor, dnColor],
    colorIndex=fillColorIdx,
    label=["CVD"],
    desc=["Reset-rolling cumulative volume delta (Lee-Ready classified)"]
)

// --- Fill between CVD and zero (regime-colored, reduced opacity) ---
if (showFill) {
    plotLine(
        value=([cvdSm, zeroLine]),
        width=1,
        colors=[opacity(upColor, 20), opacity(dnColor, 20)],
        colorIndex=fillColorIdx,
        fill=true,
        label=["CVD Fill"],
        desc=["Fill between CVD and zero line, colored by sign"]
    )
}

// --- Zero-Cross Shape Markers ---
if (showZeroCross && zeroCrossUp) {
    plotShape(
        value=cvdSm,
        shape="triangleup",
        colorIndex=crossUpColor,
        width=shapeSize,
        label=["CVD Cross Up"],
        desc=["CVD crossed above zero; buy pressure turning dominant"]
    )
}
if (showZeroCross && zeroCrossDown) {
    plotShape(
        value=cvdSm,
        shape="triangledown",
        colorIndex=crossDownColor,
        width=shapeSize,
        label=["CVD Cross Down"],
        desc=["CVD crossed below zero; sell pressure turning dominant"]
    )
}

// --- Raw Delta Bars (optional) ---
if (showDelta) {
    plotBar(
        value=delta,
        colors=[upColor, dnColor],
        label=["Delta"],
        desc=["Per-bar volume delta (buy − sell) before cumulative summation"]
    )
}

// --- True Cumulative CVD (optional reference) ---
if (showCumul) {
    plotLine(
        value=trueCumul,
        width=1,
        colors=["#9e9e9e"],
        label=["CVD (Cumulative)"],
        desc=["True cumulative CVD from first bar (never resets)"]
    )
}

// --- Reference Lines ---
hline(value=0, color="#88888860", width=1)