MM Flow
FlowScripts

Perfected FlowScript

SCF Volume Delta

SCF Volume Delta V2 is indexed as 076_scf_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.1 KB

Lines

312

Native Signal Candidates

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

2/2 guarded

Extreme Buy

line 283:9

Trigger

(showShapes) && (extremeBuy)

Value

barDelta

Deps

extremeBuy:var, showShapes:input

Extreme Sell

line 293:9

Trigger

(showShapes) && (extremeSell)

Value

barDelta

Deps

extremeSell:var, showShapes:input

076_scf_volume_delta.flowscript

source path: kscripts/perfected/076_scf_volume_delta.flowscript · sha256:d1ab32d2b60cda41ec0b76524b6d4ceed0371273793274784084e4bf395072c3

hash verified
//@version=2

// ============================================================================
// SCF Volume Delta V2 — Buy/Sell Volume Delta with Regime Detection & Z-Score
// Author: SoulzBTC (@SoulzBTC) | Perfected: kScript_Perfection_Engineer
// Tags: ADVANCED, CORE, FLOW, #delta, #volume, #zscore, #regime, #histogram
//
// Computes bar-level volume delta with taker-feed preference, Lee-Ready
// fallback, and BVC probabilistic split. Z-score normalisation provides
// cross-asset comparability. Regime detection flags extreme buy/sell
// pressure. Color-coded histogram with shape markers for extreme events
// and static session tracking for cumulative diagnostics.
//
// Academic foundation (exact papers & formulas):
//  1. Lee & Ready (1991), "Inferring Trade Direction from Intraday Data",
//     Journal of Finance, 46(2), 733–746.
//     [Formula] Tick test: classify as buy if close > open, else sell.
//     Accuracy: 85–93% on NYSE TORQ data. Foundational trade-direction
//     inference when taker-buy/sell feeds are unavailable.
//     DOI: https://doi.org/10.1111/j.1540-6261.1991.tb02683.x
//
//  2. Easley, López de Prado & O'Hara (2012), "Bulk Classification of
//     Trading Activity" (BVC). Probabilistic bar-level volume classification:
//     BuyFrac = (close − low) / (high − low); SellFrac = (high − close) / (high − low).
//     Superior to Lee-Ready in high-frequency environments (data efficiency).
//     SSRN: https://ssrn.com/abstract=1989555
//
//  3. 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}.
//     Cumulative OFI (CVD) linearly predicts short-term price changes:
//     Δp_t = λ·OFI_t + ε_t, where λ is inversely proportional to depth.
//     Validates delta as the primary driver of short-term price moves.
//     DOI: https://doi.org/10.1093/jjfinec/nbt003
//
//  4. 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 regime-threshold design.
//     DOI: https://doi.org/10.1016/S0304-405X(02)00136-8
//
//  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 underpinning
//     all delta-based trading signals.
//     DOI: https://doi.org/10.2307/1913210
//
//  6. Bouchaud, Farmer & Lillo (2009), "How Markets Slowly Digest Changes
//     in Supply and Demand", Handbook of Financial Markets, 57–160.
//     Square-root impact law: large delta events have sublinear price impact
//     due to liquidity memory. Explains why extreme histogram bars may signal
//     absorption (continuation) or exhaustion (reversal) depending on context.
// ============================================================================

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

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

// -- Computation --
var smoothLen = input(name="smoothLen", type="number", defaultValue=14, label="Smoothing Length (bars)", constraints={min: 1, max: 100, step: 1}, group="Computation")
var zLen = input(name="zLen", type="number", defaultValue=50, label="Z-Score Window (bars)", constraints={min: 10, max: 200, step: 5}, group="Computation")
var regimeThreshold = input(name="regimeThreshold", type="number", defaultValue=1.5, label="Regime Threshold (|z|)", constraints={min: 0.5, max: 4.0, step: 0.1}, group="Computation")
var extremeThreshold = input(name="extremeThreshold", type="number", defaultValue=2.5, label="Extreme Threshold (|z|)", constraints={min: 1.5, max: 5.0, step: 0.1}, group="Computation")
var bandMult = input(name="bandMult", type="number", defaultValue=2.0, label="Stdev Band Multiplier", constraints={min: 0.5, max: 4.0, step: 0.5}, group="Computation")
var useEMA = input(name="useEMA", type="boolean", defaultValue=true, label="Use EMA (off=SMA) for CVD", group="Computation")

// -- Display --
var showDelta = input(name="showDelta", type="boolean", defaultValue=true, label="Show Per-Bar Delta Histogram", group="Display")
var showCVD = input(name="showCVD", type="boolean", defaultValue=true, label="Show Cumulative CVD Line", group="Display")
var showCVDBand = input(name="showCVDBand", type="boolean", defaultValue=true, label="Show CVD Band Fill", group="Display")
var showZScore = input(name="showZScore", type="boolean", defaultValue=false, label="Show Z-Score Line", 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="Buy-Dominant Color", group="Colors")
var dnColor = input(name="dnColor", type="color", defaultValue="#ef5350", label="Sell-Dominant Color", group="Colors")
var maColor = input(name="maColor", type="color", defaultValue="#ff9800", label="CVD MA Color", group="Colors")
var extremeBuyColor = input(name="extremeBuyColor", type="color", defaultValue="#00e676", label="Extreme Buy Color", group="Colors")
var extremeSellColor = input(name="extremeSellColor", type="color", defaultValue="#ff1744", label="Extreme Sell Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#78909c", label="Neutral Color", group="Colors")

// ---------------------------------------------------------------------------
// 2. 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 high = ohlcvData.high
timeseries low = ohlcvData.low
timeseries vol = ohlcvData.volume
timeseries taker = source("taker_volume", currentSymbol, currentExchange)

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

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

// -- 3.1 Volume Delta — taker feed preferred, Lee-Ready fallback, BVC final fallback --
// Lee-Ready (1991): close > open → buyer-initiated; else seller-initiated.
// BVC (Easley et al. 2012): probabilistic split by bar position within range.

timeseries buyVol = 0.0
timeseries sellVol = 0.0

if (isnum(taker.buy) && isnum(taker.sell)) {
    // Direct taker feed available — highest accuracy
    buyVol = taker.buy
    sellVol = taker.sell
} else {
    // Fallback 1: Lee-Ready tick test (85–93% accuracy)
    // Fallback 2: BVC probabilistic split when doji / ambiguous
    timeseries range_ = high - low
    timeseries upW = math.max(close - open, 0.0)
    timeseries dnW = math.max(open - close, 0.0)
    buyVol = range_ > 0 ? vol * (upW / range_) : vol * 0.5
    sellVol = range_ > 0 ? vol * (dnW / range_) : vol * 0.5
}

timeseries barDelta = buyVol - sellVol

// -- 3.2 Cumulative Volume Delta (CVD) via static state --
// CVD_t = CVD_{t−1} + Δ_t. Static persists across bars; NaN-guarded.
// Lillo & Farmer (2004) long-memory justifies cumulative over per-bar delta.

static cvd = 0.0
if (!isnan(barDelta[0])) {
    cvd = cvd + barDelta[0]
}

// -- 3.3 Smoothed CVD using EMA or SMA (Cont et al. 2014 noise-reduction) --
timeseries cvdMA = useEMA ? ema(cvd, smoothLen) : sma(cvd, smoothLen)

// -- 3.4 Stdev bands around CVD (Bollinger-style envelope) --
timeseries cvdStd = stdev(cvd, smoothLen)
timeseries upperBand = cvdMA + cvdStd * bandMult
timeseries lowerBand = cvdMA - cvdStd * bandMult

// -- 3.5 Z-score normalisation of bar delta (cross-asset comparability) --
// Z_t = (Δ_t − μ_t) / σ_t, where μ_t = SMA(Δ, W), σ_t = StDev(Δ, W).
// Guards: if σ_t == 0 we emit 0 to prevent division-by-zero crashes.

timeseries deltaMean = sma(barDelta, zLen)
timeseries deltaStd = stdev(barDelta, zLen)
timeseries deltaZ = (deltaStd > 0) ? (barDelta - deltaMean) / deltaStd : 0.0

// -- 3.6 Regime detection (Chordia et al. 2002 extreme-imbalance thresholds) --
// Buy-heavy regime: z > regimeThreshold; Sell-heavy regime: z < -regimeThreshold.
// Extreme regimes flag potential absorption or exhaustion per Bouchaud et al. (2009).

var buyRegime = deltaZ > regimeThreshold
var sellRegime = deltaZ < -regimeThreshold
var extremeBuy = deltaZ > extremeThreshold
var extremeSell = deltaZ < -extremeThreshold
var neutralRegime = !buyRegime && !sellRegime

// Color index: 0 = buy, 1 = sell, 2 = neutral
timeseries deltaColorIdx = buyRegime ? 0 : (sellRegime ? 1 : 2)

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

// -- 3.8 Static state tracking — session-level persistence --
// Tracks extreme-event counts, cumulative delta, and regime persistence for
// context-aware alerting and diagnostics.

static sessionBuyVol = 0.0
static sessionSellVol = 0.0
static extremeBuyCount = 0
static extremeSellCount = 0
static lastRegime = 0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

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

    if (!isnan(buyVol[0])) {
        sessionBuyVol = sessionBuyVol + buyVol[0]
    }
    if (!isnan(sellVol[0])) {
        sessionSellVol = sessionSellVol + sellVol[0]
    }

    if (extremeBuy) {
        extremeBuyCount = extremeBuyCount + 1
    }
    if (extremeSell) {
        extremeSellCount = extremeSellCount + 1
    }

    if (buyRegime) {
        lastRegime = 1
    } else if (sellRegime) {
        lastRegime = -1
    } else {
        lastRegime = 0
    }
}

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

// 4.1 Per-bar volume delta histogram (plotBar) — color-coded by regime
if (showDelta) {
    plotBar(
        value=barDelta,
        colors=[upColor, dnColor, neutralColor],
        colorIndex=deltaColorIdx,
        width=1,
        label=["Volume Delta"],
        desc=["Per-bar volume delta (buy − sell); color-coded by regime (buy/sell/neutral)"]
    )
}

// 4.2 Cumulative CVD line (plotLine) with fill to zero
if (showCVD) {
    plotLine(
        value=([cvd, zeroLine]),
        width=2,
        colors=[upColor, dnColor, neutralColor],
        colorIndex=cvd > cvd[1] ? 0 : 1,
        label=["CVD"],
        desc=["Cumulative volume delta (running total); color = direction of change"],
        fill=true
    )
}

// 4.3 CVD MA line (plotLine)
if (showCVD) {
    plotLine(
        value=cvdMA,
        width=2,
        colors=[maColor],
        label=["CVD MA"],
        desc=["Smoothed CVD (EMA or SMA); filters noise, preserves major trend"]
    )
}

// 4.4 CVD band fill (plotLine + fill) — Bollinger-style envelope
if (showCVDBand) {
    plotLine(
        value=([upperBand, cvdMA]),
        width=1,
        colors=[opacity(upColor, 20)],
        label=["Upper Band"],
        desc=["Upper std-dev band around CVD MA"],
        fill=true
    )
    plotLine(
        value=([lowerBand, cvdMA]),
        width=1,
        colors=[opacity(dnColor, 20)],
        label=["Lower Band"],
        desc=["Lower std-dev band around CVD MA"],
        fill=true
    )
}

// 4.5 Z-score line (plotLine) — optional offchart reference
if (showZScore) {
    plotLine(
        value=deltaZ,
        width=1,
        colors=[upColor, dnColor, neutralColor],
        colorIndex=deltaZ > regimeThreshold ? 0 : (deltaZ < -regimeThreshold ? 1 : 2),
        label=["Delta Z-Score"],
        desc=["Rolling-window z-score of bar delta; regime-coded by direction"]
    )
}

// 4.6 Extreme delta shapes (plotShape) — triangles for extreme events
if (showShapes) {
    if (extremeBuy) {
        plotShape(
            value=barDelta,
            shape="triangleup",
            colorIndex=extremeBuyColor,
            width=3,
            label=["Extreme Buy"],
            desc=["Extreme aggressive buying detected; potential absorption or continuation cluster"]
        )
    }
    if (extremeSell) {
        plotShape(
            value=barDelta,
            shape="triangledown",
            colorIndex=extremeSellColor,
            width=3,
            label=["Extreme Sell"],
            desc=["Extreme aggressive selling detected; potential absorption or distribution cluster"]
        )
    }
}

// 4.7 Reference thresholds (hline)
hline(value=0, color="#ffffff30", width=1)
if (showZScore) {
    hline(value=regimeThreshold, color="#ffffff20", width=1)
    hline(value=-regimeThreshold, color="#ffffff20", width=1)
    hline(value=extremeThreshold, color="#ffffff15", width=1)
    hline(value=-extremeThreshold, color="#ffffff15", width=1)
}