MM Flow
FlowScripts

Perfected FlowScript

the volume

The Volume V2 is indexed as 196_the_volume.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

318

Native Signal Candidates

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

1/1 guarded

Volume Anomaly

line 293:5

Trigger

(showAnomalies && volAnomaly)

Value

vol

Deps

showAnomalies:input, volAnomaly:var

196_the_volume.flowscript

source path: kscripts/perfected/196_the_volume.flowscript · sha256:20200c72f17e13663d5fd391bb8277ecafa32d58b48f4e1928c55d4a8c8e7c68

hash verified
//@version=2

// ============================================================================
// The Volume V2 — Multi-Factor Volume Dashboard with Z-Score, Regime & Anomalies
// Author: T (@takakiya) | Perfected: kScript_Perfection_Engineer
// Tags: CORE, ADVANCED, #volume, #delta, #zscore, #absorption, #regime
//
// A comprehensive volume-analysis panel displaying volume, delta, volume MA,
// statistical bands, z-score normalisation, absorption detection, and regime-
// flagged anomalies. Colour-codes volume by regime (low / normal / high)
// and delta by directional extremity, with shape alerts for volume spikes.
//
// Academic foundation:
//  1. Lee & Ready (1991), "Inferring Trade Direction from Intraday Data",
//     Journal of Finance, 46(2), 733–746.
//     Foundational tick-classification algorithm (85–93% accuracy) enabling
//     delta computation. DOI: 10.1111/j.1540-6261.1991.tb02683.x
//
//  2. Bouchaud, Farmer & Lillo (2009), "How Markets Slowly Digest Changes
//     in Supply and Demand", Handbook of Financial Markets: Dynamics and
//     Evolution, 57–160 (Elsevier). [Formula] Liquidity memory time explains
//     absorption: when aggressive volume fails to move price, liquidity is
//     being replenished. arXiv: 0809.0822
//
//  3. Steidlmayer & Hawkins (2003), "Steidlmayer on Markets: Trading with
//     Market Profile" (2nd ed.), Wiley Trading. Value Area (~70% of trading),
//     Point of Control (POC), volume clusters at accepted value.
//
//  4. Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events",
//     Journal of Financial Econometrics, 12(1), 47–88.
//     Order Flow Imbalance (OFI) linearly predicts short-term price changes.
//     DOI: 10.1093/jjfinec/nbt003
//
//  5. Chordia, Roll & Subrahmanyam (2002), "Order Imbalance, Liquidity,
//     and Market Returns", Journal of Financial Economics, 65(1), 111–130.
//     Extreme order imbalances predict return reversals; z-scores quantify
//     extremity. DOI: 10.1016/S0304-405X(02)00136-8
// ============================================================================

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

// ---------------------------------------------------------------------------
// 1. USER INPUTS
// ---------------------------------------------------------------------------

// -- Computation --
var volMaLen = input(name="volMaLen", type="number", defaultValue=20, label="Volume MA Length", constraints={min: 5, max: 100, step: 1}, group="Computation")
var volStdevMult = input(name="volStdevMult", type="number", defaultValue=2.0, label="Volume Stdev Multiplier", constraints={min: 1.0, max: 4.0, step: 0.5}, group="Computation")
var deltaMaLen = input(name="deltaMaLen", type="number", defaultValue=14, label="Delta MA Length", constraints={min: 5, max: 100, step: 1}, group="Computation")
var deltaStdevMult = input(name="deltaStdevMult", type="number", defaultValue=2.0, label="Delta Stdev Multiplier", constraints={min: 1.0, max: 4.0, step: 0.5}, group="Computation")
var zWindow = input(name="zWindow", type="number", defaultValue=50, label="Z-Score Window", constraints={min: 20, max: 200, step: 5}, group="Computation")
var absorptionThresh = input(name="absorptionThresh", type="number", defaultValue=0.001, label="Absorption Threshold (body%)", constraints={min: 0.0001, max: 0.01, step: 0.0001}, group="Computation")
var anomalyThreshold = input(name="anomalyThreshold", type="number", defaultValue=2.0, label="Volume Anomaly Threshold (σ)", constraints={min: 1.0, max: 4.0, step: 0.5}, group="Computation")

// -- Display --
var showVol = input(name="showVol", type="boolean", defaultValue=true, label="Show Volume", group="Display")
var showVolZ = input(name="showVolZ", type="boolean", defaultValue=true, label="Show Volume Z-Score", group="Display")
var showDelta = input(name="showDelta", type="boolean", defaultValue=true, label="Show Delta", group="Display")
var showDeltaZ = input(name="showDeltaZ", type="boolean", defaultValue=true, label="Show Delta Z-Score", group="Display")
var showAbsorb = input(name="showAbsorb", type="boolean", defaultValue=true, label="Highlight Absorption", group="Display")
var showAnomalies = input(name="showAnomalies", type="boolean", defaultValue=true, label="Show Volume Anomalies", group="Display")
var showCVD = input(name="showCVD", type="boolean", defaultValue=true, label="Show CVD", group="Display")

// -- Colors --
var volLowColor = input(name="volLowColor", type="color", defaultValue="#78909c", label="Volume Low Color", group="Colors")
var volNormColor = input(name="volNormColor", type="color", defaultValue="#2962ff", label="Volume Normal Color", group="Colors")
var volHighColor = input(name="volHighColor", type="color", defaultValue="#ff6d00", label="Volume High Color", group="Colors")
var deltaUpColor = input(name="deltaUpColor", type="color", defaultValue="#26a69a", label="Delta Up Color", group="Colors")
var deltaDnColor = input(name="deltaDnColor", type="color", defaultValue="#ef5350", label="Delta Down Color", group="Colors")
var absorbUpColor = input(name="absorbUpColor", type="color", defaultValue="#26a69a40", label="Absorption Up Color", group="Colors")
var absorbDnColor = input(name="absorbDnColor", type="color", defaultValue="#ef535040", label="Absorption Down Color", group="Colors")
var anomalyColor = input(name="anomalyColor", type="color", defaultValue="#ffd700", label="Anomaly Color", group="Colors")
var cvdColor = input(name="cvdColor", type="color", defaultValue="#9c27b0", label="CVD Color", group="Colors")

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

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

if (isnan(px[0]) || isnan(op[0]) || isnan(hi[0]) || isnan(lo[0]) || isnan(vol[0])) {
    return
}

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

// -- 3.1 Volume baseline and bands --
timeseries volMA = sma(vol, volMaLen)
timeseries volStd = stdev(vol, volMaLen)
timeseries volUpper = volMA + volStdevMult * volStd
timeseries volLower = volMA - volStdevMult * volStd

// Volume z-score
timeseries volZ = (volStd > 0) ? (vol - volMA) / volStd : 0

// -- 3.2 Buy/sell classification and delta --
timeseries upBar = px >= op
timeseries buyVol = upBar ? vol : 0
timeseries sellVol = upBar ? 0 : vol
timeseries delta = buyVol - sellVol

// Delta baseline and bands
timeseries deltaMA = sma(delta, deltaMaLen)
timeseries deltaStd = stdev(delta, deltaMaLen)
timeseries deltaUpper = deltaMA + deltaStdevMult * deltaStd
timeseries deltaLower = deltaMA - deltaStdevMult * deltaStd

// Delta z-score
timeseries deltaZ = (deltaStd > 0) ? (delta - deltaMA) / deltaStd : 0

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

// -- 3.4 Absorption detection --
// Bullish absorption: up-close but sell delta dominates (buyers absorbing supply)
// Bearish absorption: down-close but buy delta dominates (sellers absorbing demand)
timeseries body = math.abs(px - op) / math.max(px, 1e-9)
timeseries bigBody = body > absorptionThresh
timeseries bullAbsorb = upBar && delta < 0 && bigBody
timeseries bearAbsorb = !upBar && delta > 0 && bigBody

// -- 3.5 Volume regime detection --
var volHigh = vol > volUpper
var volLow = vol < volLower
var volNormal = !volHigh && !volLow

// Delta regime
var deltaBull = delta > deltaUpper
var deltaBear = delta < deltaLower
var deltaNeutral = !deltaBull && !deltaBear

// Volume anomaly (extreme z-score)
var volAnomaly = volZ > anomalyThreshold

// -- 3.6 Regime tracking via static --
static lastVolRegime = 0
static volHighBars = 0
static volLowBars = 0

if (volHigh) {
    volHighBars = volHighBars + 1
    volLowBars = 0
    lastVolRegime = 1
} else if (volLow) {
    volLowBars = volLowBars + 1
    volHighBars = 0
    lastVolRegime = -1
} else {
    volHighBars = 0
    volLowBars = 0
    lastVolRegime = 0
}

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

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

// 4.1 Volume filled histogram (plotLine with colorIndex regime coding)
// colorIndex: 0 = low, 1 = normal, 2 = high
timeseries volColorIdx = volHigh ? 2 : (volLow ? 0 : 1)
if (showVol) {
    plotLine(
        value=[vol, zeroLine],
        width=1,
        colors=[volLowColor, volNormColor, volHighColor],
        colorIndex=volColorIdx,
        label=["Volume"],
        desc=["Volume filled histogram; colour-coded by regime: low (grey), normal (blue), high (orange)"],
        fill=true
    )
}

// 4.2 Volume MA and bands (plotLine)
if (showVol) {
    plotLine(
        value=volMA,
        width=1,
        colors=["#ffffff"],
        label=["Volume MA"],
        desc=["Simple moving average of volume; baseline for regime detection"]
    )
    plotLine(
        value=volUpper,
        width=1,
        colors=["#ffffff50"],
        label=["Volume Upper Band"],
        desc=["Volume MA + σ × multiplier; above = high-volume regime"]
    )
}

// 4.3 Volume Z-Score (plotLine)
if (showVolZ) {
    plotLine(
        value=volZ,
        width=1,
        colors=[volNormColor],
        label=["Volume Z-Score"],
        desc=["Standardised volume: (vol − MA) / σ; > 2σ = statistically high volume"]
    )
}

// 4.4 Delta bars (plotBar)
if (showDelta) {
    plotBar(
        value=delta,
        colors=[deltaUpColor, deltaDnColor],
        width=1,
        label=["Delta"],
        desc=["Per-bar buy-minus-sell volume; positive = buying pressure, negative = selling pressure"]
    )
}

// 4.5 Delta MA and bands (plotLine)
if (showDelta) {
    plotLine(
        value=deltaMA,
        width=1,
        colors=["#ffffff"],
        label=["Delta MA"],
        desc=["Simple moving average of delta"]
    )
    plotLine(
        value=deltaUpper,
        width=1,
        colors=["#ffffff50"],
        label=["Delta Upper Band"],
        desc=["Delta MA + σ × multiplier"]
    )
    plotLine(
        value=deltaLower,
        width=1,
        colors=["#ffffff50"],
        label=["Delta Lower Band"],
        desc=["Delta MA − σ × multiplier"]
    )
}

// 4.6 Delta Z-Score (plotLine with colorIndex)
if (showDeltaZ) {
    timeseries deltaZColorIdx = deltaBull ? 0 : (deltaBear ? 1 : 2)
    plotLine(
        value=deltaZ,
        width=2,
        colors=[deltaUpColor, deltaDnColor, "#ffffff"],
        colorIndex=deltaZColorIdx,
        label=["Delta Z-Score"],
        desc=["Standardised delta; regime-coded by directional extremity"]
    )
    plotLine(
        value=[deltaZ, zeroLine],
        width=2,
        colors=[deltaUpColor, deltaDnColor, "#ffffff"],
        colorIndex=deltaZColorIdx,
        label=["Delta Z-Score Fill"],
        desc=["Delta z-score filled to zero; regime-coded"],
        fill=true
    )
}

// 4.7 Absorption highlight (plotLine with semi-transparent fill)
if (showAbsorb) {
    plotLine(
        value=bullAbsorb ? vol : 0,
        width=1,
        colors=[absorbUpColor],
        label=["Bullish Absorption"],
        desc=["Up-close with sell-delta dominance; buyers absorbing supply at the ask"]
    )
    plotLine(
        value=bearAbsorb ? vol : 0,
        width=1,
        colors=[absorbDnColor],
        label=["Bearish Absorption"],
        desc=["Down-close with buy-delta dominance; sellers absorbing demand at the bid"]
    )
}

// 4.8 Volume anomaly shapes (plotShape)
if (showAnomalies && volAnomaly) {
    plotShape(
        value=vol,
        shape="circle",
        color=anomalyColor,
        width=3,
        label=["Volume Anomaly"],
        desc=["Volume exceeds +2σ threshold; unusual participation spike"]
    )
}

// 4.9 CVD line (plotLine)
if (showCVD) {
    plotLine(
        value=cvd,
        width=1,
        colors=[cvdColor],
        label=["CVD"],
        desc=["Cumulative Volume Delta; static-tracked from first bar"]
    )
}

// 4.10 Reference thresholds (hline)
hline(value=0, color="#ffffff30", width=1)
hline(value=anomalyThreshold, color="#ffffff20", width=1)
hline(value=-anomalyThreshold, color="#ffffff20", width=1)