MM Flow
FlowScripts

Perfected FlowScript

VPIN

VPIN V2 is indexed as 234_vpin.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

14.2 KB

Lines

321

Native Signal Candidates

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

5/5 guarded

High Toxicity

line 271:9

Trigger

(showShapes) && (crossHigh)

Value

vpinSmooth

Deps

crossHigh:var, showShapes:input

Medium Toxicity

line 281:9

Trigger

(showShapes) && (crossMed)

Value

vpinSmooth

Deps

crossMed:var, showShapes:input

Low Toxicity

line 291:9

Trigger

(showShapes) && (crossLow)

Value

vpinSmooth

Deps

crossLow:var, showShapes:input

Extreme Toxicity

line 301:9

Trigger

(showShapes) && (extremeHighZ)

Value

vpinSmooth

Deps

extremeHighZ:var, showShapes:input

Extreme Benign

line 311:9

Trigger

(showShapes) && (extremeLowZ)

Value

vpinSmooth

Deps

extremeLowZ:var, showShapes:input

234_vpin.flowscript

source path: kscripts/perfected/234_vpin.flowscript · sha256:1d364bc9c6863122fe2639df500a55e6d1cccd63df629b05328f4c8b97ab7bee

hash verified
//@version=2
// ============================================================================
// VPIN V2 — Volume-Synchronized Probability of Informed Trading
// Author: L (@Luv Chen)  |  Perfected by: kScript_Perfection_Engineer
// Tags: ADVANCED, #volume, #vpin, #toxicity, #microstructure
//
// Production-quality implementation of the Volume-Synchronized Probability
// of Informed Trading (VPIN) metric with z-score normalization, regime
// detection, and session-level static tracking.
//
// FORMULA FOUNDATION:
// 1. VPIN = Σ|BuyVolume − SellVolume| / Σ(BuyVolume + SellVolume)
//    over volume-synchronized buckets (Easley, López de Prado & O'Hara 2012).
// 2. Bulk Volume Classification (BVC): trade direction inferred from volume
//    distribution relative to bar range when direct buy/sell data unavailable.
// 3. Z-Score Normalization: Z_t = (VPIN_t − μ_t) / σ_t for regime-relative
//    toxicity readings (Andersen & Bondarenko 2013).
// 4. Regime Segmentation: Low-toxicity (< μ − 0.5σ), Medium (μ ± 0.5σ),
//    High-toxicity (> μ + 0.5σ), Extreme (> μ + 1.5σ).
//
// RESEARCH BASIS:
//  • Easley, López de Prado & O'Hara (2012), "Flow Toxicity and Liquidity in
//    a High-Frequency World", Review of Financial Studies 25(5), 1547–1574.
//    The seminal VPIN paper. VPIN reached historically high levels >1 hour
//    before the May 6, 2010 Flash Crash. DOI: 10.1093/rfs/hhr093
//  • Abad & Yagüe (2012), "From PIN to VPIN: An Introduction to Order Flow
//    Toxicity", Spanish Review of Financial Economics 10(2), 74–83.
//    Four key innovations: broader information definition, volume-time sampling,
//    bulk classification, and trade size incorporation.
//  • Andersen & Bondarenko (2013), "Assessing Measures of Order Flow Toxicity
//    via Perfect Trade Classification", CREATES Research Paper 2013-43.
//    Found BVC is inferior to direct classification; we prefer direct
//    buy_sell_volume feed when available, with Lee-Ready (1991) fallback.
//  • Lee & Ready (1991), "Inferring Trade Direction from Intraday Data",
//    Journal of Finance 46(2), 733–746. Tick-test classification: buy if
//    close > open, else sell. 85–93% accuracy. DOI: 10.1111/j.1540-6261.1991.tb02683.x
//  • Chordia, Roll & Subrahmanyam (2002), "Order Imbalance, Liquidity, and
//    Market Returns", JFE 65(1), 111–130. Extreme |imbalance| predicts
//    return reversals. DOI: 10.1016/S0304-405X(02)00136-8
// ============================================================================

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

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

// --- Bucket Configuration ---
var bucketSize = input(name="bucketSize", type="number", defaultValue=20.0, label="Bucket Size (bars)", constraints={min: 5.0, max: 100.0, step: 1.0}, group="Bucket")
var numBuckets = input(name="numBuckets", type="number", defaultValue=50.0, label="Number of Buckets (lookback)", constraints={min: 10.0, max: 200.0, step: 5.0}, group="Bucket")
var smoothLen = input(name="smoothLen", type="number", defaultValue=5.0, label="VPIN Smoothing Length", constraints={min: 1.0, max: 50.0, step: 1.0}, group="Bucket")

// --- Z-Score ---
var zWindow = input(name="zWindow", type="number", defaultValue=50.0, label="Z-Score Window (bars)", constraints={min: 20.0, max: 200.0, step: 5.0}, group="Z-Score")
var useZScore = input(name="useZScore", type="boolean", defaultValue=true, label="Use Z-Score Normalization", group="Z-Score")

// --- Thresholds & Regime ---
var highThresh = input(name="highThresh", type="number", defaultValue=0.7, label="High Toxicity Threshold", constraints={min: 0.3, max: 0.95, step: 0.05}, group="Thresholds")
var medThresh = input(name="medThresh", type="number", defaultValue=0.5, label="Medium Toxicity Threshold", constraints={min: 0.1, max: 0.9, step: 0.05}, group="Thresholds")
var extremeZ = input(name="extremeZ", type="number", defaultValue=2.0, label="Extreme Z-Score Threshold", constraints={min: 1.0, max: 4.0, step: 0.5}, group="Thresholds")

// --- Display ---
var showRawVPIN = input(name="showRawVPIN", type="boolean", defaultValue=false, label="Show Raw VPIN", group="Display")
var showSmoothVPIN = input(name="showSmoothVPIN", type="boolean", defaultValue=true, label="Show Smoothed VPIN", group="Display")
var showZScore = input(name="showZScore", type="boolean", defaultValue=true, label="Show Z-Score Line", group="Display")
var showHistogram = input(name="showHistogram", type="boolean", defaultValue=true, label="Show Toxicity Histogram", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Regime Shapes", group="Display")
var showGuides = input(name="showGuides", type="boolean", defaultValue=true, label="Show Guide Lines", group="Display")

// --- Colors ---
var highColor = input(name="highColor", type="color", defaultValue="#ef5350", label="High Toxicity Color", group="Colors")
var medColor = input(name="medColor", type="color", defaultValue="#ff9800", label="Medium Toxicity Color", group="Colors")
var lowColor = input(name="lowColor", type="color", defaultValue="#26a69a", label="Low Toxicity Color", group="Colors")
var extremeColor = input(name="extremeColor", type="color", defaultValue="#d500f9", label="Extreme Toxicity Color", group="Colors")
var zScoreColor = input(name="zScoreColor", type="color", defaultValue="#42a5f5", label="Z-Score Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#9e9e9e", label="Neutral Color", group="Colors")

// ------------------------------------------------------------------------------
// Data Sources
// ------------------------------------------------------------------------------
timeseries priceBars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries px = priceBars.close
timeseries buySell = buy_sell_volume(symbol=currentSymbol, exchange=currentExchange)

// NaN guard — prevent execution before data is loaded
if (isnan(px[0]) || !isnum(buySell.buy_volume)) {
    return
}

// ------------------------------------------------------------------------------
// Buy/Sell Volume Classification
// ------------------------------------------------------------------------------
// Prefer direct buy_sell_volume feed; fall back to Lee-Ready (1991) tick test
// when unavailable: close > open → buyer-initiated; else seller-initiated.

timeseries buyV = isnum(buySell.buy_volume) ? buySell.buy_volume : (priceBars.close > priceBars.open ? priceBars.volume : 0)
timeseries sellV = isnum(buySell.sell_volume) ? buySell.sell_volume : (priceBars.close <= priceBars.open ? priceBars.volume : 0)
timeseries totalVol = buyV + sellV
timeseries absImb = math.abs(buyV - sellV)

// Volume availability check — prevents NaN/undefined propagation
var volAvailable = isnum(buyV) && isnum(sellV) && totalVol > 0

// ------------------------------------------------------------------------------
// Volume-Synchronized VPIN Computation
// ------------------------------------------------------------------------------
// VPIN = Σ|Buy − Sell| / Σ(Buy + Sell) over equal-volume buckets.
// We approximate volume-time buckets using a rolling window of bars,
// with the bucket size configurable in bars (practical approximation for
// chart-based implementation per Easley et al. 2012).

// Rolling-window sums over bucketSize bars
var bucketSumImb = sum(absImb, bucketSize)
var bucketSumTot = sum(totalVol, bucketSize)

// Raw VPIN ratio with zero-division guard
timeseries rawVPIN = volAvailable && bucketSumTot > 0 ? bucketSumImb / bucketSumTot : 0.0

// Smoothed VPIN (noise reduction per Andersen & Bondarenko 2013)
timeseries vpinSmooth = sma(rawVPIN, smoothLen)

// ------------------------------------------------------------------------------
// Z-Score Normalization (Andersen & Bondarenko 2013)
// ------------------------------------------------------------------------------
// Z_t = (VPIN_t − μ_t) / σ_t, where μ_t = SMA(VPIN, W), σ_t = StDev(VPIN, W).
// Normalized VPIN allows regime-relative toxicity detection across assets
// and time periods.

timeseries vpinMean = sma(vpinSmooth, zWindow)
timeseries vpinStd = stdev(vpinSmooth, zWindow)
timeseries vpinZ = (vpinStd > 0) ? (vpinSmooth - vpinMean) / vpinStd : 0.0

// ------------------------------------------------------------------------------
// Regime Detection (4-tier toxicity classification)
// ------------------------------------------------------------------------------
// Low-toxicity:   VPIN < medThresh
// Medium-toxicity: medThresh ≤ VPIN < highThresh
// High-toxicity:   VPIN ≥ highThresh
// Extreme:         |Z| ≥ extremeZ (statistically rare, per standard normal)

var regime = 2      // 0 = extreme high, 1 = high, 2 = medium, 3 = low
var extremeRegime = 0  // 0 = normal, 1 = extreme high toxicity, -1 = extreme low

if (vpinSmooth >= highThresh) {
    regime = 1
} else if (vpinSmooth >= medThresh) {
    regime = 2
} else {
    regime = 3
}

if (vpinZ >= extremeZ) {
    extremeRegime = 1
} else if (vpinZ <= -extremeZ) {
    extremeRegime = -1
}

// ------------------------------------------------------------------------------
// Static State Tracking (Session-level persistence)
// ------------------------------------------------------------------------------
// Tracks VPIN extremes, regime transitions, and extreme-event counts for
// context-aware alerting and session diagnostics.

static lastRegime = 0
static regimeChangeCount = 0
static sessionHighVPIN = 0.0
static sessionLowVPIN = 999999.0
static extremeHighCount = 0
static extremeLowCount = 0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

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

    if (vpinSmooth > sessionHighVPIN) {
        sessionHighVPIN = vpinSmooth
    }
    if (vpinSmooth < sessionLowVPIN) {
        sessionLowVPIN = vpinSmooth
    }

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

    if (extremeRegime == 1) {
        extremeHighCount = extremeHighCount + 1
    } else if (extremeRegime == -1) {
        extremeLowCount = extremeLowCount + 1
    }
}

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

// Horizontal guide lines — zero line and configurable threshold zones
if (showGuides) {
    hline(value=highThresh, color=opacity(highColor, 30), width=1)
    hline(value=medThresh, color=opacity(medColor, 30), width=1)
    hline(value=0, color="#ffffff20", width=1)
}

// Raw VPIN line (optional, for diagnostics)
if (showRawVPIN) {
    plotLine(
        value=rawVPIN,
        width=1,
        colors=[opacity(neutralColor, 50)],
        label=["Raw VPIN"],
        desc=["Unsmoothed VPIN: |Buy − Sell| / (Buy + Sell) over bucket window"]
    )
}

// Smoothed VPIN with regime-coded fill area
if (showSmoothVPIN) {
    var vpinColorIdx = regime == 1 ? 0 : (regime == 2 ? 1 : 2)
    plotLine(
        value=vpinSmooth,
        width=2,
        colors=[highColor, medColor, lowColor],
        colorIndex=vpinColorIdx,
        label=["VPIN"],
        desc=["Volume-Synchronized Probability of Informed Trading (smoothed). Regime: high/medium/low toxicity."],
        fill=true
    )
}

// Z-Score line (regime-relative toxicity)
if (showZScore && useZScore) {
    plotLine(
        value=vpinZ,
        width=2,
        colors=[zScoreColor],
        label=["VPIN Z-Score"],
        desc=["Z-score normalized VPIN: (VPIN − μ) / σ. Values > 2 or < −2 are statistically extreme."]
    )
}

// Toxicity histogram (plotBar) — regime-based colouring
if (showHistogram) {
    var barColors = [extremeColor, highColor, medColor, lowColor]
    var barIdx = extremeRegime == 1 ? 0 : (regime == 1 ? 1 : (regime == 2 ? 2 : 3))
    plotBar(
        value=vpinSmooth,
        colors=barColors,
        colorIndex=barIdx,
        width=1,
        label=["VPIN Histogram"],
        desc=["Volume-synchronized toxicity histogram (extreme/high/medium/low)"]
    )
}

// Regime transition shapes — extreme toxicity alerts (Easley et al. 2012)
if (showShapes) {
    var crossHigh = vpinSmooth >= highThresh && !isnan(vpinSmooth[1]) && vpinSmooth[1] < highThresh
    var crossMed = vpinSmooth >= medThresh && !isnan(vpinSmooth[1]) && vpinSmooth[1] < medThresh
    var crossLow = vpinSmooth < medThresh && !isnan(vpinSmooth[1]) && vpinSmooth[1] >= medThresh
    var extremeHighZ = vpinZ >= extremeZ && !isnan(vpinZ[1]) && vpinZ[1] < extremeZ
    var extremeLowZ = vpinZ <= -extremeZ && !isnan(vpinZ[1]) && vpinZ[1] > -extremeZ

    if (crossHigh) {
        plotShape(
            value=vpinSmooth,
            shape="triangleup",
            color=highColor,
            width=3,
            label=["High Toxicity"],
            desc=["VPIN crossed into high-toxicity regime — informed trading may be accelerating"]
        )
    }
    if (crossMed) {
        plotShape(
            value=vpinSmooth,
            shape="circle",
            color=medColor,
            width=2,
            label=["Medium Toxicity"],
            desc=["VPIN crossed into medium-toxicity regime"]
        )
    }
    if (crossLow) {
        plotShape(
            value=vpinSmooth,
            shape="triangledown",
            color=lowColor,
            width=2,
            label=["Low Toxicity"],
            desc=["VPIN dropped into low-toxicity regime — benign flow conditions"]
        )
    }
    if (extremeHighZ) {
        plotShape(
            value=vpinSmooth,
            shape="diamond",
            color=extremeColor,
            width=4,
            label=["Extreme Toxicity"],
            desc=["VPIN Z-Score exceeded extreme threshold — statistically rare toxic flow event"]
        )
    }
    if (extremeLowZ) {
        plotShape(
            value=vpinSmooth,
            shape="diamond",
            color=extremeColor,
            width=4,
            label=["Extreme Benign"],
            desc=["VPIN Z-Score below extreme negative threshold — unusually benign flow conditions"]
        )
    }
}