MM Flow
FlowScripts

Perfected FlowScript

Volume Delta

Volume Delta V2 is indexed as 101_volume_delta.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

13.8 KB

Lines

311

Native Signal Candidates

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

4/4 guarded

Buy Pressure

line 271:9

Trigger

(showShapes) && (crossUp)

Value

cvdZSmooth

Deps

crossUp:var, showShapes:input

Sell Pressure

line 281:9

Trigger

(showShapes) && (crossDn)

Value

cvdZSmooth

Deps

crossDn:var, showShapes:input

Extreme Buy

line 291:9

Trigger

(showShapes) && (extremeUp)

Value

cvdZSmooth

Deps

extremeUp:var, showShapes:input

Extreme Sell

line 301:9

Trigger

(showShapes) && (extremeDn)

Value

cvdZSmooth

Deps

extremeDn:var, showShapes:input

101_volume_delta.flowscript

source path: kscripts/perfected/101_volume_delta.flowscript · sha256:c8dcddb83ae4130bd7b01b5533b2187a17c2b9a2f7081eb69cf883cc867918f3

hash verified
//@version=2
// ============================================================================
// Volume Delta V2 — Production-Quality Volume Delta with Z-Score & Regime Detection
// Author: N (@neongrace)  |  Perfected by: kScript Perfection Engineer
// Tags: FLOW, #volume, #delta, #cvd, #zscore, #regime, #microstructure
//
// Per-bar volume delta with buy/sell classification, rolling-window z-score
// normalization, regime detection, and color-coded visualization.
//
// FORMULA FOUNDATION:
// 1. Volume Delta: ΔV = BuyVol − SellVol per bar  [Lee & Ready 1991]
// 2. Cumulative Volume Delta (CVD): CVD_t = ΣΔV_i  [Cont et al. 2014]
// 3. Z-Score Normalization: Z_t = (CVD_t − μ_t) / σ_t  [Zhao & Palomar 2018]
// 4. Regime Segmentation: Exhaustion (|Z| > extreme), Elevated (|Z| > threshold),
//    Normal otherwise  [Chordia, Roll & Subrahmanyam 2002]
// 5. Lee-Ready Classification: close > open → buyer-initiated; else seller-initiated
//    [Lee & Ready 1991, ~85–93% accuracy]
// 6. Bulk Volume Classification (BVC): probabilistic bar-level classification
//    [Easley, López de Prado & O'Hara 2012]
//
// RESEARCH BASIS:
//  • Lee & Ready (1991), "Inferring Trade Direction from Intraday Data",
//    Journal of Finance, 46(2), 733–746. Foundational tick-classification
//    algorithm achieving ~85–93% accuracy on NYSE TORQ data.
//  • Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events",
//    J. Financial Econometrics 12(1), 47–88. OFI explains ~65% of variance
//    in contemporaneous mid-price changes; linear price-impact model.
//  • Chordia, Roll & Subrahmanyam (2002), "Order Imbalance, Liquidity, and
//    Market Returns", J. Financial Economics 65(1), 111–130. Extreme order
//    imbalances predict return reversals; market returns reverse after high-
//    negative-imbalance days.
//  • Bouchaud, Farmer & Lillo (2009), "How Markets Slowly Digest Changes in
//    Supply and Demand", Handbook of Financial Markets. Square-root impact
//    law; liquidity memory explains absorption vs. exhaustion.
//  • Easley, López de Prado & O'Hara (2012), "Bulk Classification of Trading
//    Activity", SSRN. BVC method — probabilistic volume classification robust
//    in HFT environments where tick-rules break down.
//  • Lillo & Farmer (2004), "The Long Memory of the Efficient Market", Studies
//    in Nonlinear Dynamics & Econometrics 8(3). Order flow autocorrelations
//    decay as power law; cumulative measures capture sustained pressure.
// ============================================================================

define(
    title="Volume Delta V2",
    position="offchart",
    axis=true
)

// ------------------------------------------------------------------------------
// User Inputs — grouped and constrained per production spec
// ------------------------------------------------------------------------------

// --- Classification ---
var useBVC = input(name="useBVC", type="boolean", defaultValue=true, label="Use BVC Classification", group="Classification")
var bvcWindow = input(name="bvcWindow", type="number", defaultValue=20, label="BVC Lookback Window", constraints={min: 5, max: 100, step: 1}, group="Classification")

// --- Z-Score ---
var zWindow = input(name="zWindow", type="number", defaultValue=50, label="Z-Score Window (bars)", constraints={min: 20, max: 200, step: 5}, group="Z-Score")
var smoothLen = input(name="smoothLen", type="number", defaultValue=5, label="Z-Score EMA Smooth", constraints={min: 1, max: 50, step: 1}, group="Z-Score")
var divThreshold = input(name="divThreshold", type="number", defaultValue=1.5, label="Elevated Regime Threshold (σ)", constraints={min: 0.5, max: 4.0, step: 0.5}, group="Z-Score")
var extremeThresh = input(name="extremeThresh", type="number", defaultValue=2.5, label="Extreme Regime Threshold (σ)", constraints={min: 2.0, max: 6.0, step: 0.5}, group="Z-Score")

// --- Display ---
var showRawDelta = input(name="showRawDelta", type="boolean", defaultValue=true, label="Show Raw Per-Bar Delta", group="Display")
var showCVD = input(name="showCVD", type="boolean", defaultValue=true, label="Show CVD Line", group="Display")
var showZScore = input(name="showZScore", type="boolean", defaultValue=true, label="Show Z-Score", group="Display")
var showZBars = input(name="showZBars", type="boolean", defaultValue=true, label="Show Z-Score Histogram", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Regime Shapes", group="Display")
var showBands = input(name="showBands", type="boolean", defaultValue=true, label="Show Sigma Bands", group="Display")

// --- Colors ---
var bidColor = input(name="bidColor", type="color", defaultValue="#26a69a", label="Buy-Dominant Color", group="Colors")
var askColor = input(name="askColor", type="color", defaultValue="#ef5350", label="Sell-Dominant Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#9e9e9e", label="Neutral Color", group="Colors")
var extremeBidColor = input(name="extremeBidColor", type="color", defaultValue="#00e676", label="Extreme Buy Color", group="Colors")
var extremeAskColor = input(name="extremeAskColor", type="color", defaultValue="#ff1744", label="Extreme Sell Color", group="Colors")
var cvdColor = input(name="cvdColor", type="color", defaultValue="#2962ff", label="CVD Line Color", group="Colors")

// ------------------------------------------------------------------------------
// Data Sources — with isnan() guard on first external access
// ------------------------------------------------------------------------------
timeseries ohlcvData = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries close = ohlcvData.close
timeseries open = ohlcvData.open
timeseries vol = ohlcvData.volume
timeseries taker = source("taker_volume", currentSymbol, currentExchange)

// Guard: halt until price data is loaded to avoid NaN propagation
if (isnan(close[0]) || isnan(vol[0])) {
    return
}

// ------------------------------------------------------------------------------
// Volume Delta Computation
// ------------------------------------------------------------------------------
// Per-bar buy/sell classification using Lee-Ready (1991) tick test as fallback
// when taker feed is unavailable. BVC (Easley et al. 2012) when enabled.

// Direct taker feed preferred for highest accuracy
timeseries buyVol = isnum(taker.buy) ? taker.buy : (close > open ? vol : 0)
timeseries sellVol = isnum(taker.sell) ? taker.sell : (close <= open ? vol : 0)

// BVC-style probabilistic enhancement: when enabled, weight by bar range position
// (simplified BVC: volume closer to high = more buy-weighted; closer to low = more sell-weighted)
var barRange = close - open
var barHighLow = ohlcvData.high - ohlcvData.low
var barRangeGuard = barHighLow > 0 ? barHighLow : 1.0

var bvcBuyWeight = useBVC ? (close - ohlcvData.low) / barRangeGuard : 1.0
var bvcSellWeight = useBVC ? (ohlcvData.high - close) / barRangeGuard : 1.0

var buyVolBVC = useBVC ? buyVol * bvcBuyWeight + sellVol * (1.0 - bvcSellWeight) : buyVol
var sellVolBVC = useBVC ? sellVol * bvcSellWeight + buyVol * (1.0 - bvcBuyWeight) : sellVol

var barDelta = buyVolBVC - sellVolBVC

// ------------------------------------------------------------------------------
// Cumulative Volume Delta (CVD) — rolling window for stationarity
// ------------------------------------------------------------------------------
// CVD captures sustained pressure via long-memory order flow [Lillo & Farmer 2004]
static cvdCum = 0.0

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

// Rolling-window CVD (mean-reverting, amenable to z-score)
timeseries cvdRolling = sum(barDelta, zWindow)

// ------------------------------------------------------------------------------
// Z-Score Normalization (Zhao & Palomar 2018)
// ------------------------------------------------------------------------------
// Z_t = (CVD_t − μ_t) / σ_t, all denominators guarded against zero
timeseries cvdMean = sma(cvdRolling, zWindow)
timeseries cvdStd = stdev(cvdRolling, zWindow)
timeseries cvdZ = (cvdStd > 0) ? (cvdRolling - cvdMean) / cvdStd : 0

var cvdZSmooth = ema(cvdZ, smoothLen)

// ------------------------------------------------------------------------------
// Regime Detection (Chordia et al. 2002 extreme-imbalance reversal framework)
// ------------------------------------------------------------------------------
// Regime segmentation:
//   Extreme buy:  Z ≥ extremeThresh
//   Elevated buy: divThreshold ≤ Z < extremeThresh
//   Neutral:      −divThreshold < Z < divThreshold
//   Elevated sell: −extremeThresh < Z ≤ −divThreshold
//   Extreme sell: Z ≤ −extremeThresh

var regime = 0      // 0 = neutral, 1 = elevated bull, 2 = extreme bull, -1 = elevated bear, -2 = extreme bear

if (cvdZSmooth >= extremeThresh) {
    regime = 2
} else if (cvdZSmooth >= divThreshold) {
    regime = 1
} else if (cvdZSmooth <= -extremeThresh) {
    regime = -2
} else if (cvdZSmooth <= -divThreshold) {
    regime = -1
}

// ------------------------------------------------------------------------------
// Static State Tracking (Session-level persistence)
// ------------------------------------------------------------------------------
// Tracks regime transitions, session extremes, and extreme-event counts

static lastRegime = 0
static regimeChangeCount = 0
static sessionHighZ = -999999.0
static sessionLowZ = 999999.0
static extremeBuyCount = 0
static extremeSellCount = 0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
    // New bar — update session tracking
    lastBarIndex = currentBarIndex

    if (cvdZSmooth > sessionHighZ) {
        sessionHighZ = cvdZSmooth
    }
    if (cvdZSmooth < sessionLowZ) {
        sessionLowZ = cvdZSmooth
    }

    if (lastRegime != regime) {
        lastRegime = regime
        regimeChangeCount = regimeChangeCount + 1
    }

    if (regime == 2) {
        extremeBuyCount = extremeBuyCount + 1
    } else if (regime == -2) {
        extremeSellCount = extremeSellCount + 1
    }
}

// ------------------------------------------------------------------------------
// Plots — Multiple Visualization Types (Line, Bar, Shape, Fill, HLine)
// ------------------------------------------------------------------------------

// Zero line and threshold guides
hline(value=0, color="#ffffff30", width=1)

if (showBands) {
    hline(value=divThreshold, color=opacity(bidColor, 30), width=1)
    hline(value=-divThreshold, color=opacity(askColor, 30), width=1)
    hline(value=extremeThresh, color=opacity(extremeBidColor, 20), width=1)
    hline(value=-extremeThresh, color=opacity(extremeAskColor, 20), width=1)
}

// Raw per-bar delta as color-coded histogram
if (showRawDelta) {
    plotBar(
        value=barDelta,
        colors=[bidColor, askColor],
        width=1,
        label=["Bar Delta"],
        desc=["Per-bar volume delta (positive = buyer-initiated, negative = seller-initiated)"]
    )
}

// CVD line (rolling window)
if (showCVD) {
    plotLine(
        value=cvdRolling,
        width=2,
        colors=[cvdColor],
        label=["CVD Rolling"],
        desc=["Rolling-window cumulative volume delta; mean-reverting around 0"]
    )
}

// Z-Score line with regime-coded fill area
if (showZScore) {
    var colorIdx = regime > 0 ? (regime == 2 ? 3 : 0) : (regime < 0 ? (regime == -2 ? 4 : 1) : 2)
    plotLine(
        value=cvdZSmooth,
        width=2,
        colors=[bidColor, askColor, neutralColor, extremeBidColor, extremeAskColor],
        colorIndex=colorIdx,
        label=["CVD Z-Score"],
        desc=["Z-score normalized CVD. Regime: extreme bull / elevated bull / neutral / elevated bear / extreme bear."],
        fill=true
    )
}

// Z-Score bars (color-coded histogram)
if (showZBars) {
    var barColorIdx = regime > 0 ? (regime == 2 ? 3 : 0) : (regime < 0 ? (regime == -2 ? 4 : 1) : 2)
    plotBar(
        value=cvdZSmooth,
        colors=[bidColor, askColor, neutralColor, extremeBidColor, extremeAskColor],
        colorIndex=barColorIdx,
        width=1,
        label=["Z-Score Bars"],
        desc=["Z-score as color-coded bars (positive = buy pressure, negative = sell pressure)"]
    )
}

// Regime transition shapes — directional signal extraction
if (showShapes) {
    var crossUp = cvdZSmooth >= divThreshold && !isnan(cvdZSmooth[1]) && cvdZSmooth[1] < divThreshold
    var crossDn = cvdZSmooth <= -divThreshold && !isnan(cvdZSmooth[1]) && cvdZSmooth[1] > -divThreshold
    var extremeUp = cvdZSmooth >= extremeThresh && !isnan(cvdZSmooth[1]) && cvdZSmooth[1] < extremeThresh
    var extremeDn = cvdZSmooth <= -extremeThresh && !isnan(cvdZSmooth[1]) && cvdZSmooth[1] > -extremeThresh

    if (crossUp) {
        plotShape(
            value=cvdZSmooth,
            shape="triangleup",
            color=extremeBidColor,
            width=3,
            label=["Buy Pressure"],
            desc=["Volume delta Z crossed into elevated buy regime — buyer dominance detected"]
        )
    }
    if (crossDn) {
        plotShape(
            value=cvdZSmooth,
            shape="triangledown",
            color=extremeAskColor,
            width=3,
            label=["Sell Pressure"],
            desc=["Volume delta Z crossed into elevated sell regime — seller dominance detected"]
        )
    }
    if (extremeUp) {
        plotShape(
            value=cvdZSmooth,
            shape="diamond",
            color=extremeBidColor,
            width=4,
            label=["Extreme Buy"],
            desc=["Extreme buy pressure — potential exhaustion or squeeze zone per Chordia et al. 2002"]
        )
    }
    if (extremeDn) {
        plotShape(
            value=cvdZSmooth,
            shape="diamond",
            color=extremeAskColor,
            width=4,
            label=["Extreme Sell"],
            desc=["Extreme sell pressure — potential capitulation or absorption zone per Chordia et al. 2002"]
        )
    }
}