MM Flow
FlowScripts

Perfected FlowScript

Volume Delta Pro (Fork)

Volume Delta Pro (Fork) V2 is indexed as 214_volume_delta_pro_fork.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

12.3 KB

Lines

267

Native Signal Candidates

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

2/2 guarded

Extreme Bull Delta

line 228:5

Trigger

(showShapes && extremeBull)

Value

dSmooth

Deps

extremeBull:var, showShapes:input

Extreme Bear Delta

line 238:5

Trigger

(showShapes && extremeBear)

Value

dSmooth

Deps

extremeBear:var, showShapes:input

214_volume_delta_pro_fork.flowscript

source path: kscripts/perfected/214_volume_delta_pro_fork.flowscript · sha256:3820e4928e927b7ffde7e11e79c5c6a696ba9f50bb582e1010b50b7cc7e30b1c

hash verified
//@version=2
// Source: kiyotaka.ai/hub/kscript (original) — Perfected by kScript_Perfection_Engineer

// ============================================================================
// Volume Delta Pro (Fork) V2 — Perfected
// Author: Mohammed Adamu — Perfected by kScript_Perfection_Engineer
// Tags: ADVANCED, CORE, #volumedelta, #orderflow, #cvd, #zscore, #regime
//
// Sophisticated order flow tool measuring buy vs. sell pressure intensity with
// statistical context. Implements both Lee-Ready tick classification and direct
// taker-volume feeds, rolling-window CVD, z-score normalisation, and regime
// divergence detection with colour-coded histograms and extreme shape alerts.
//
// Research papers underpinning this design:
//  1. Lee & Ready (1991), "Inferring Trade Direction from Intraday Data",
//     Journal of Finance, 46(2), 733–746.
//     [Formula] Tick test: close > open → buyer-initiated; else seller-initiated.
//     Accuracy 85–93% on NYSE TORQ data. Bedrock of all volume delta calc.
//     DOI: https://doi.org/10.1111/j.1540-6261.1991.tb02683.x
//
//  2. 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}
//     CVD linearly predicts short-term price changes: Δp = λ·OFI + ε.
//     DOI: https://doi.org/10.1093/jjfinec/nbt003
//
//  3. 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 underpinning
//     every delta-based trading signal.
//     DOI: https://doi.org/10.2307/1913210
//
//  4. Easley, López de Prado & O'Hara (2012), "Bulk Classification of
//     Trading Activity": BVC method classifies volume in aggregate buckets
//     using the distribution of price changes within a bar. Superior to
//     Lee-Ready in high-frequency / crypto environments.
//     URL: https://ssrn.com/abstract=1989555
//
//  5. 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 divergence-threshold design.
//     DOI: https://doi.org/10.1016/S0304-405X(02)00136-8
//
//  6. Ellis, Michaely & O'Hara (2000), "The Accuracy of Trade Classification
//     Rules: Evidence from Nasdaq", Journal of Financial and Quantitative
//     Analysis, 35(4), 529–551. Validated classification accuracy bounds
//     (76–81%) and informs delta-as-relative, not absolute, measure.
// ============================================================================

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

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

// -- Computation --
var mode = input(name="mode", type="select", defaultValue="Per-bar", label="Calculation Mode", options=["Per-bar", "Rolling"], group="Computation")
var rollLen = input(name="rollLen", type="number", defaultValue=20, label="Rolling Window (bars)", constraints={min: 5, max: 100, step: 1}, group="Computation")
var useUSD = input(name="useUSD", type="boolean", defaultValue=false, label="Use USD Notional", group="Computation")
var smoothLen = input(name="smoothLen", type="number", defaultValue=3, label="Delta EMA Smooth", constraints={min: 1, max: 20, step: 1}, group="Computation")

// -- Sigma / Z-Score --
var sdLookback = input(name="sdLookback", type="number", defaultValue=50, label="Sigma Lookback", constraints={min: 20, max: 200, step: 5}, group="Sigma Bands")
var sdMult1 = input(name="sdMult1", type="number", defaultValue=1.0, label="Sigma Band 1", constraints={min: 0.5, max: 4.0, step: 0.1}, group="Sigma Bands")
var sdMult2 = input(name="sdMult2", type="number", defaultValue=2.0, label="Sigma Band 2", constraints={min: 0.5, max: 5.0, step: 0.1}, group="Sigma Bands")
var sdMult3 = input(name="sdMult3", type="number", defaultValue=3.0, label="Sigma Band 3", constraints={min: 0.5, max: 6.0, step: 0.1}, group="Sigma Bands")

// -- Regime --
var divThreshold = input(name="divThreshold", type="number", defaultValue=2.0, label="Divergence Regime Threshold", constraints={min: 0.5, max: 4.0, step: 0.5}, group="Regime")
var extremeDiv = input(name="extremeDiv", type="number", defaultValue=3.0, label="Extreme Divergence Threshold", constraints={min: 2.0, max: 6.0, step: 0.5}, group="Regime")

// -- Display --
var showDelta = input(name="showDelta", type="boolean", defaultValue=true, label="Show Delta Histogram", group="Display")
var showRawCVD = input(name="showRawCVD", type="boolean", defaultValue=false, label="Show Raw CVD Lines", group="Display")
var showSigma = input(name="showSigma", type="boolean", defaultValue=true, label="Show Sigma Bands", group="Display")
var showZScore = input(name="showZScore", type="boolean", defaultValue=true, label="Show Delta Z-Score", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Extreme Shapes", group="Display")

// -- 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 band2Color = input(name="band2Color", type="color", defaultValue="#ff9800", label="2σ Color", group="Colors")
var band3Color = input(name="band3Color", type="color", defaultValue="#d50000", label="3σ Color", group="Colors")
var zScoreColor = input(name="zScoreColor", type="color", defaultValue="#2962ff", label="Z-Score 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 bars and taker feeds have loaded
if (isnan(bars.close[0]) || isnan(bars.volume[0])) {
    return
}

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

// -- 3.1 Per-bar volume delta (Lee-Ready fallback when taker feed is unavailable) --
// Lee-Ready (1991) tick test: close > open → buyer-initiated; else seller-initiated.
// When taker.buy/sell is available, prefer 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 USD notional conversion (optional) --
timeseries px = bars.close
timeseries deltaUSD = delta * px
timeseries dRaw = useUSD ? deltaUSD : delta

// -- 3.3 Mode: per-bar vs rolling window --
// Rolling sum of delta over rollLen bars (stationary CVD)
timeseries dMode = mode == "Per-bar" ? dRaw : sum(dRaw, rollLen)

// -- 3.4 True cumulative CVD via static state (tracked for optional raw display) --
// static persists across bars; guard each increment against NaN.
static cvdCum = 0.0
if (!isnan(dRaw[0])) {
    cvdCum = cvdCum + dRaw[0]
}

// -- 3.5 Sigma bands (rolling mean ± N standard deviations) --
timeseries dMean = sma(source=dMode, period=sdLookback)
timeseries dStd = stdev(source=dMode, period=sdLookback)
// Guard against zero std to prevent division-by-zero
timeseries dStdSafe = math.max(dStd, 1e-9)

timeseries upper1 = dMean + sdMult1 * dStd
timeseries lower1 = dMean - sdMult1 * dStd
timeseries upper2 = dMean + sdMult2 * dStd
timeseries lower2 = dMean - sdMult2 * dStd
timeseries upper3 = dMean + sdMult3 * dStd
timeseries lower3 = dMean - sdMult3 * dStd

// -- 3.6 Smoothed delta for visual clarity --
timeseries dSmooth = ema(source=dMode, period=smoothLen)

// -- 3.7 Z-score normalisation of delta --
// Z_t = (dMode_t − μ_t) / σ_t, where μ_t = SMA(dMode, W), σ_t = StDev(dMode, W).
timeseries deltaZ = (dMode - dMean) / dStdSafe

// -- 3.8 Regime detection --
// Bullish divergence: delta > +1σ threshold (buying pressure dominates)
// Bearish divergence: delta < −1σ threshold (selling pressure dominates)
// Neutral: within normal range
var bullishDiv = deltaZ > divThreshold
var bearishDiv = deltaZ < -divThreshold
var extremeBull = deltaZ > extremeDiv
var extremeBear = deltaZ < -extremeDiv
var neutralRegime = !bullishDiv && !bearishDiv

// -- 3.9 Divergence state tracking via static variables --
// Tracks consecutive bars in each regime for context-aware alerting.
static lastRegime = 0
static divBullBars = 0
static divBearBars = 0
static divNeutralBars = 0

if (bullishDiv) {
    divBullBars = divBullBars + 1
    divBearBars = 0
    divNeutralBars = 0
    lastRegime = 1
} else if (bearishDiv) {
    divBearBars = divBearBars + 1
    divBullBars = 0
    divNeutralBars = 0
    lastRegime = -1
} else {
    divNeutralBars = divNeutralBars + 1
    divBullBars = 0
    divBearBars = 0
    lastRegime = 0
}

// Colour index: 0 = bullish, 1 = bearish, 2 = neutral
var divColorIdx = bullishDiv ? 0 : (bearishDiv ? 1 : 2)

// -- 3.10 Extreme detection for shapes --
var isExtreme3 = math.abs(dSmooth - dMean) > sdMult3 * dStd
var isExtreme2 = math.abs(dSmooth - dMean) > sdMult2 * dStd

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

// 4.1 Delta histogram (plotBar, regime-coloured)
if (showDelta) {
    plotBar(
        value=dSmooth,
        colors=[upColor, dnColor, "#78909c"],
        colorIndex=divColorIdx,
        label=["Volume Delta"],
        desc=["Smoothed buy/sell delta; colour-coded by divergence regime"]
    )
}

// 4.2 Delta Z-Score (plotLine, colour-coded by regime)
if (showZScore) {
    plotLine(
        value=deltaZ,
        width=2,
        colors=[upColor, dnColor, zScoreColor],
        colorIndex=divColorIdx,
        label=["Delta Z-Score"],
        desc=["Z-score of delta: (delta − μ) / σ; > threshold = buying pressure, < −threshold = selling pressure"]
    )
}

// 4.3 Sigma bands (plotLine)
if (showSigma) {
    plotLine(value=upper1, width=1, colors=["#9e9e9e"], label=["+1σ"], desc=["Upper sigma band at 1σ"])
    plotLine(value=lower1, width=1, colors=["#9e9e9e"], label=["-1σ"], desc=["Lower sigma band at 1σ"])
    plotLine(value=upper2, width=1, colors=[band2Color], label=["+2σ"], desc=["Upper sigma band at 2σ"])
    plotLine(value=lower2, width=1, colors=[band2Color], label=["-2σ"], desc=["Lower sigma band at 2σ"])
    plotLine(value=upper3, width=1, colors=[band3Color], label=["+3σ"], desc=["Upper sigma band at 3σ"])
    plotLine(value=lower3, width=1, colors=[band3Color], label=["-3σ"], desc=["Lower sigma band at 3σ"])
}

// 4.4 Extreme divergence shapes (plotShape)
if (showShapes && extremeBull) {
    plotShape(
        value=dSmooth,
        shape="triangleup",
        colorIndex=upColor,
        width=3,
        label=["Extreme Bull Delta"],
        desc=["Delta Z-score exceeds extreme threshold; aggressive buying pressure detected"]
    )
}
if (showShapes && extremeBear) {
    plotShape(
        value=dSmooth,
        shape="triangledown",
        colorIndex=dnColor,
        width=3,
        label=["Extreme Bear Delta"],
        desc=["Delta Z-score below extreme threshold; aggressive selling pressure detected"]
    )
}

// 4.5 Optional raw CVD lines (true cumulative from static state)
if (showRawCVD) {
    plotLine(
        value=cvdCum,
        width=1,
        colors=[upColor],
        label=["CVD (Raw)"],
        desc=["True cumulative delta from first bar"]
    )
}

// 4.6 Reference hlines
hline(value=0, color="#ffffff30", width=1)
if (showZScore) {
    hline(value=divThreshold, color="#ffffff20", width=1)
    hline(value=-divThreshold, color="#ffffff20", width=1)
    hline(value=extremeDiv, color="#ffffff15", width=1)
    hline(value=-extremeDiv, color="#ffffff15", width=1)
}