MM Flow
FlowScripts

Perfected FlowScript

Delta Bars

Delta Bars V2 is indexed as 195_delta_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

9.7 KB

Lines

237

Native Signal Candidates

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

2/2 guarded

Extreme Buy Delta

line 200:5

Trigger

(showShapes && extremeBull)

Value

extremeDiv

Deps

extremeBull:var, showShapes:input

Extreme Sell Delta

line 210:5

Trigger

(showShapes && extremeBear)

Value

-extremeDiv

Deps

extremeBear:var, showShapes:input

195_delta_bars.flowscript

source path: kscripts/perfected/195_delta_bars.flowscript · sha256:e6cfaad8cea7a1aeecd4e5fbfaec92ba2a34273cc63b39ddf8e80a7b40d0e742

hash verified
//@version=2

// ============================================================================
// Delta Bars V2 — Per-Bar Buy/Sell Pressure with CVD, Z-Score & Regime Detection
// Author: BackQuant (@BackQuant) | Perfected: kScript_Perfection_Engineer
// Tags: FLOW, ADVANCED, CORE, #delta, #cvd, #bars, #zscore
//
// Visualizes aggressive buying versus selling pressure on each bar, computes
// cumulative volume delta (CVD) via static state, standardises both per-bar
// delta and rolling-window CVD via z-score, and flags extreme regimes with
// color-coded histograms, filled areas, and shape alerts.
//
// Academic foundation:
//  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.
//     Classification accuracy ~85–93%. DOI: 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_t = λ·OFI_t + ε_t.
//     DOI: 10.1093/jjfinec/nbt003
//
//  3. Lillo & Farmer (2004), "The Long Memory of the Efficient Market",
//     Studies in Nonlinear Dynamics & Econometrics, 8(3), 1–35.
//     Order flow exhibits long-memory (power-law autocorrelation decay);
//     cumulative measures like CVD capture sustained pressure that drives trends.
//     arXiv: cond-mat/0311053
//
//  4. 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 signals. DOI: 10.2307/1913210
//
//  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 extreme-delta threshold design.
//     DOI: 10.1016/S0304-405X(02)00136-8
// ============================================================================

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

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

// -- 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="Delta EMA Smooth", constraints={min: 1, max: 20, step: 1}, group="Computation")
var divThreshold = input(name="divThreshold", type="number", defaultValue=2.0, label="Delta Regime Threshold", constraints={min: 0.5, max: 4.0, step: 0.5}, group="Computation")
var extremeDiv = input(name="extremeDiv", type="number", defaultValue=3.0, label="Extreme Delta Threshold", constraints={min: 2.0, max: 6.0, step: 0.5}, group="Computation")

// -- Display --
var showDeltaBars = input(name="showDeltaBars", type="boolean", defaultValue=true, label="Show Delta Bars", group="Display")
var showCVD = input(name="showCVD", type="boolean", defaultValue=true, label="Show CVD Z-Score", group="Display")
var showDeltaZ = input(name="showDeltaZ", 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")
var showFill = input(name="showFill", type="boolean", defaultValue=true, label="Show Fill Areas", group="Display")
var showRawCVD = input(name="showRawCVD", type="boolean", defaultValue=false, label="Show Raw CVD Line", group="Display")

// -- Colors --
var bullColor = input(name="bullColor", type="color", defaultValue="#26a69a", label="Bullish Color", group="Colors")
var bearColor = input(name="bearColor", type="color", defaultValue="#ef5350", label="Bearish Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#78909c", label="Neutral Color", group="Colors")
var cvdColor = input(name="cvdColor", type="color", defaultValue="#2962ff", label="CVD Z-Score Color", group="Colors")
var extremeBullColor = input(name="extremeBullColor", type="color", defaultValue="#00c853", label="Extreme Bull Color", group="Colors")
var extremeBearColor = input(name="extremeBearColor", type="color", defaultValue="#d50000", label="Extreme Bear Color", group="Colors")

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

timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries px = bars.close
timeseries op = bars.open
timeseries vol = bars.volume

// Guard: halt until external feeds have loaded to avoid NaN propagation
if (isnan(px[0]) || isnan(op[0]) || isnan(vol[0])) {
    return
}

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

// -- 3.1 Per-bar volume delta (Lee-Ready tick test) --
// Close >= Open → buyer-initiated volume; else seller-initiated.
timeseries buyVol = px >= op ? vol : 0
timeseries sellVol = px < op ? vol : 0
timeseries delta = buyVol - sellVol

// -- 3.2 Cumulative Volume Delta (CVD) via static state --
static cvd = 0.0
if (!isnan(delta[0])) {
    cvd = cvd + delta
}

// -- 3.3 Rolling-window CVD for z-score (stationary approximation) --
timeseries rollCVD = sum(delta, zWindow)

// -- 3.4 Z-score normalisation (all denominators guarded against zero) --
timeseries cvdMean = sma(rollCVD, zWindow)
timeseries cvdStd = stdev(rollCVD, zWindow)
timeseries cvdZ = (cvdStd > 0) ? (rollCVD - cvdMean) / cvdStd : 0

timeseries deltaMean = sma(delta, zWindow)
timeseries deltaStd = stdev(delta, zWindow)
timeseries deltaZ = (deltaStd > 0) ? (delta - deltaMean) / deltaStd : 0

// -- 3.5 Smoothed CVD z-score for cleaner regime reading --
timeseries cvdZSmooth = ema(cvdZ, smoothLen)

// -- 3.6 Regime detection --
var bullishDelta = deltaZ > divThreshold
var bearishDelta = deltaZ < -divThreshold
var extremeBull = deltaZ > extremeDiv
var extremeBear = deltaZ < -extremeDiv
var neutralRegime = !bullishDelta && !bearishDelta

// -- 3.7 Regime duration tracking via static --
static lastRegime = 0
static bullBars = 0
static bearBars = 0

if (bullishDelta) {
    bullBars = bullBars + 1
    bearBars = 0
    lastRegime = 1
} else if (bearishDelta) {
    bearBars = bearBars + 1
    bullBars = 0
    lastRegime = -1
} else {
    bullBars = 0
    bearBars = 0
    lastRegime = 0
}

// -- 3.8 Zero-line helper --
timeseries zeroLine = 0

// ---------------------------------------------------------------------------
// 4. VISUALIZATION
// ---------------------------------------------------------------------------

// 4.1 Delta Z-Score (plotLine with colorIndex regime coding)
// colorIndex: 0 = bullish, 1 = bearish, 2 = neutral
timeseries deltaZColorIdx = bullishDelta ? 0 : (bearishDelta ? 1 : 2)
if (showDeltaZ) {
    plotLine(
        value=deltaZ,
        width=2,
        colors=[bullColor, bearColor, neutralColor],
        colorIndex=deltaZColorIdx,
        label=["Delta Z-Score"],
        desc=["Standardised per-bar delta; mean-reverting around 0. Regime-coded by threshold."]
    )
}

// 4.2 Delta Z-Score filled histogram (plotLine + fill to zero)
if (showDeltaZ && showFill) {
    plotLine(
        value=[deltaZ, zeroLine],
        width=2,
        colors=[bullColor, bearColor, neutralColor],
        colorIndex=deltaZColorIdx,
        label=["Delta Z-Score Fill"],
        desc=["Delta z-score filled histogram; colour-coded by regime"],
        fill=true
    )
}

// 4.3 CVD Z-Score (plotLine)
if (showCVD) {
    plotLine(
        value=cvdZSmooth,
        width=2,
        colors=[cvdColor],
        label=["CVD Z-Score"],
        desc=["Rolling-window CVD standardised; captures sustained order-flow pressure"]
    )
}

// 4.4 Raw Delta Bars (plotBar)
if (showDeltaBars) {
    plotBar(
        value=delta,
        colors=[bullColor, bearColor],
        width=1,
        label=["Delta Bars"],
        desc=["Per-bar buy-minus-sell volume; positive = buying pressure, negative = selling pressure"]
    )
}

// 4.5 Extreme divergence shapes (plotShape)
if (showShapes && extremeBull) {
    plotShape(
        value=extremeDiv,
        shape="triangleup",
        color=extremeBullColor,
        width=3,
        label=["Extreme Buy Delta"],
        desc=["Aggressive buying volume exceeds +3σ; potential short-term top or absorption zone"]
    )
}
if (showShapes && extremeBear) {
    plotShape(
        value=-extremeDiv,
        shape="triangledown",
        color=extremeBearColor,
        width=3,
        label=["Extreme Sell Delta"],
        desc=["Aggressive selling volume exceeds -3σ; potential short-term bottom or exhaustion zone"]
    )
}

// 4.6 Optional raw CVD line (true cumulative from static state)
if (showRawCVD) {
    plotLine(
        value=cvd,
        width=1,
        colors=[cvdColor],
        label=["CVD (Raw)"],
        desc=["True cumulative volume delta from first bar; static state tracking"]
    )
}

// 4.7 Reference thresholds (hline)
hline(value=0, color="#ffffff30", width=1)
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)