MM Flow
FlowScripts

Perfected FlowScript

Order Flow Toxicity

Order Flow Toxicity V2 is indexed as 162_order_flow_toxicity.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

16.1 KB

Lines

337

Native Signal Candidates

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

4/4 guarded

Benign Flow

line 297:9

Trigger

(showShapes) && (crossBenign)

Value

smoothedZ

Deps

crossBenign:var, showShapes:input

Toxic Flow

line 307:9

Trigger

(showShapes) && (crossToxic)

Value

smoothedZ

Deps

crossToxic:var, showShapes:input

Extreme Toxic

line 317:9

Trigger

(showShapes) && (extremeToxicUp)

Value

smoothedZ

Deps

extremeToxicUp:var, showShapes:input

Extreme Benign

line 327:9

Trigger

(showShapes) && (extremeBenignDn)

Value

smoothedZ

Deps

extremeBenignDn:var, showShapes:input

162_order_flow_toxicity.flowscript

source path: kscripts/perfected/162_order_flow_toxicity.flowscript · sha256:8007865dcbd27b9f3bdbffa1850e3916124f96cab67d4da81585e20a100a945c

hash verified
//@version=2

// ============================================================================
// Order Flow Toxicity V2 — VPIN-Informed Trading Probability with Z-Score Regimes
// Author: D (@ddave334) | Perfected by: kScript_Perfection_Engineer
// Tags: FLOW, ADVANCED, #toxicity, #vpin, #informedtrading, #microstructure
//
// Computes a volume-synchronized probability of informed trading (VPIN-like)
// composite score, z-standardises it over a rolling window, and surfaces regime
// transitions via color-coded fills, histograms, and shape alerts. Identifies
// when order flow shifts from benign liquidity provision to toxic directional
// positioning by informed participants.
//
// FORMULA FOUNDATION:
// 1. VPIN (Easley et al. 2012): VPIN = Σ|V_buy − V_sell| / total volume in
//    equal-volume buckets. High VPIN → high probability of informed trading.
// 2. Bulk Volume Classification (BVC): Probabilistic buy/sell classification
//    using price distribution within a bar (Andersen & Bondarenko 2013 caveat:
//    BVC has systematic errors correlated with vol/volume; we supplement with
//    price-impact and persistence components).
// 3. Price Impact per Volume (Kyle 1985): λ = ΔP / V. Informed trades move
//    price disproportionately to volume; λ spikes flag toxicity.
// 4. Volume Anomaly Z-Score: Z = (V − μ_V) / σ_V. Informed arrival clusters
//    produce volume spikes beyond random flow (Abad et al. 2020).
// 5. Directional Persistence: Consecutive one-sided flow indicates HFT-toxicity
//    (Abad et al. 2020 found HFT cancellations/revisions carry information).
//
// 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), 1457–1493.
//    VPIN = Σ|V_buy − V_sell| / ΣV in volume-time buckets; predicts liquidity
//    crises and informed-trading episodes. DOI: 10.1093/rfs/hhr011
//  • Abad et al. (2020), "Order Flow Toxicity under the Microscope", Journal of
//    Financial Markets 48, 100511. HFT flow signals toxicity; non-HFT does not.
//    Cancellations/revisions carry information beyond submissions.
//  • Andersen & Bondarenko (2013), "Assessing Measures of Order Flow Toxicity
//    via Perfect Trade Classification", SSRN 2215901. BVC-VPIN forecast power
//    derives from systematic classification errors correlated with volume/vol;
//    multi-component design mitigates this bias.
//  • Kyle (1985), "Continuous Auctions and Insider Trading", Econometrica
//    53(6), 1315–1335. Kyle's λ: p_t = p_{t−1} + λ·OFI_t + noise.
//    DOI: https://doi.org/10.2307/1913210
// ============================================================================

define(
    title="Order Flow Toxicity V2",
    position="offchart",
    axis=true
)

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

// --- VPIN / Volume Configuration ---
var vpinBuckets = input(name="vpinBuckets", type="number", defaultValue=20.0, label="VPIN Volume Buckets", constraints={min: 5.0, max: 100.0, step: 5.0}, group="VPIN")
var vpinLookback = input(name="vpinLookback", type="number", defaultValue=50.0, label="VPIN Lookback (bars)", constraints={min: 20.0, max: 200.0, step: 10.0}, group="VPIN")
var useBVC = input(name="useBVC", type="boolean", defaultValue=true, label="Use BVC Classification", group="VPIN")

// --- Z-Score & Normalization ---
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 smoothLen = input(name="smoothLen", type="number", defaultValue=5.0, label="Composite EMA Smooth", constraints={min: 1.0, max: 20.0, step: 1.0}, group="Z-Score")

// --- Weights ---
var wVPIN = input(name="wVPIN", type="number", defaultValue=0.35, label="Weight: VPIN", constraints={min: 0.0, max: 1.0, step: 0.05}, group="Weights")
var wImpact = input(name="wImpact", type="number", defaultValue=0.30, label="Weight: Price Impact", constraints={min: 0.0, max: 1.0, step: 0.05}, group="Weights")
var wVolAnom = input(name="wVolAnom", type="number", defaultValue=0.20, label="Weight: Volume Anomaly", constraints={min: 0.0, max: 1.0, step: 0.05}, group="Weights")
var wPersist = input(name="wPersist", type="number", defaultValue=0.15, label="Weight: Persistence", constraints={min: 0.0, max: 1.0, step: 0.05}, group="Weights")

// --- Thresholds & Regime ---
var benignThresh = input(name="benignThresh", type="number", defaultValue=-1.0, label="Benign Regime Threshold (Z)", constraints={min: -3.0, max: 0.0, step: 0.25}, group="Thresholds")
var toxicThresh = input(name="toxicThresh", type="number", defaultValue=1.0, label="Toxic Regime Threshold (Z)", constraints={min: 0.0, max: 3.0, step: 0.25}, group="Thresholds")
var extremeThresh = input(name="extremeThresh", type="number", defaultValue=2.0, label="Extreme Toxicity Threshold (Z)", constraints={min: 1.5, max: 4.0, step: 0.25}, group="Thresholds")

// --- Display ---
var showRawScore = input(name="showRawScore", type="boolean", defaultValue=true, label="Show Raw Composite Bar", group="Display")
var showZLine = input(name="showZLine", type="boolean", defaultValue=true, label="Show Z-Score Line", group="Display")
var showVPIN = input(name="showVPIN", type="boolean", defaultValue=false, label="Show VPIN Component", 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 benignColor = input(name="benignColor", type="color", defaultValue="#26a69a", label="Benign Color", group="Colors")
var normalColor = input(name="normalColor", type="color", defaultValue="#78909c", label="Normal Color", group="Colors")
var toxicColor = input(name="toxicColor", type="color", defaultValue="#ff5252", label="Toxic Color", group="Colors")
var extremeColor = input(name="extremeColor", type="color", defaultValue="#d50000", label="Extreme Toxic Color", group="Colors")
var lineColor = input(name="lineColor", type="color", defaultValue="#42a5f5", label="Z-Line Color", group="Colors")

// ------------------------------------------------------------------------------
// Data Sources
// ------------------------------------------------------------------------------
timeseries priceBars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries close = priceBars.close
timeseries open = priceBars.open
timeseries high = priceBars.high
timeseries low = priceBars.low
timeseries volume = priceBars.volume
timeseries taker = source("taker_volume", currentSymbol, currentExchange)

// NaN guard — prevent execution before data is loaded
if (isnan(close[0]) || isnan(volume[0])) {
    return
}

// ------------------------------------------------------------------------------
// Component 1: VPIN — Volume-Synchronized Probability of Informed Trading
// ------------------------------------------------------------------------------
// Easley et al. (2012): VPIN = Σ|V_buy − V_sell| / total volume in buckets.
// We approximate volume-bucket VPIN using a rolling lookback of per-bar
// buy/sell classification, then scale into the composite.

// BVC probabilistic classification: buy proportion = (close − low) / (high − low)
// when useBVC is true; otherwise Lee-Ready tick test fallback.
timeseries rng = math.max(high - low, 0.0001)
timeseries buyProp = useBVC ? (close - low) / rng : (close > open ? 1.0 : 0.0)
timeseries sellProp = 1.0 - buyProp

timeseries buyVol = volume * buyProp
timeseries sellVol = volume * sellProp
timeseries barDelta = math.abs(buyVol - sellVol)

// Rolling VPIN approximation: sum of |delta| / sum of volume over lookback
timeseries sumDelta = sum(barDelta, vpinLookback)
timeseries sumVol = sum(volume, vpinLookback)
timeseries vpinRaw = (sumVol > 0) ? sumDelta / sumVol : 0.0

// VPIN is naturally bounded [0,1]; scale to 0-100 for composite parity
timeseries vpinScore = vpinRaw * 100.0

// ------------------------------------------------------------------------------
// Component 2: Price Impact per Volume (Kyle 1985 λ proxy)
// ------------------------------------------------------------------------------
// Informed trades move price more per unit volume than uninformed liquidity trades.
// Impact = |Δclose| / volume; normalise by EMA of impact to create a relative score.
timeseries priceChange = math.abs(close - close[1])
timeseries impactPerVol = priceChange / math.max(volume, 1.0)
timeseries impactEMA = ema(impactPerVol, 20)
timeseries impactNorm = impactPerVol / math.max(impactEMA, 0.0000001)
timeseries impactScore = math.min(impactNorm * 50.0, 100.0)

// ------------------------------------------------------------------------------
// Component 3: Volume Anomaly Z-Score
// ------------------------------------------------------------------------------
// Informed arrival is clustered; volume spikes beyond recent mean flag toxicity.
// Z = (V − μ) / σ over rolling window; |Z| > 2 is statistically unusual.
timeseries volMean = sma(volume, zWindow)
timeseries volStd = stdev(volume, zWindow)
timeseries volZ = (volStd > 0) ? (volume - volMean) / volStd : 0.0
timeseries volScore = math.min(math.abs(volZ) * 25.0, 100.0)

// ------------------------------------------------------------------------------
// Component 4: Directional Persistence (Abad et al. 2020 HFT-toxicity proxy)
// ------------------------------------------------------------------------------
// Consecutive one-sided flow indicates informed positioning rather than random
// liquidity provision. Count consecutive bars in the same direction.
var dirUp = close > close[1]
timeseries persistCount = 0.0
var k = 0
while (k < 5) {
    var pastUp = close[k] > close[k + 1]
    persistCount = dirUp
        ? persistCount + (pastUp ? 1.0 : 0.0)
        : persistCount + (pastUp ? 0.0 : 1.0)
    k = k + 1
}
timeseries persistScore = (persistCount / 5.0) * 100.0

// ------------------------------------------------------------------------------
// Composite Toxicity Score (0-100) with Weighted Aggregation
// ------------------------------------------------------------------------------
timeseries rawComposite = wVPIN * vpinScore + wImpact * impactScore + wVolAnom * volScore + wPersist * persistScore
timeseries composite = ema(rawComposite, smoothLen)
timeseries compositeFinal = math.min(math.max(composite, 0.0), 100.0)

// ------------------------------------------------------------------------------
// Z-Score Normalisation of Composite Score
// ------------------------------------------------------------------------------
// Standardise the composite to a zero-mean, unit-variance regime indicator.
// Z_t = (Score_t − μ_t) / σ_t where μ_t = SMA(Score, W), σ_t = StDev(Score, W).
timeseries scoreMean = sma(compositeFinal, zWindow)
timeseries scoreStd = stdev(compositeFinal, zWindow)
timeseries scoreZ = (scoreStd > 0) ? (compositeFinal - scoreMean) / scoreStd : 0.0
timeseries smoothedZ = ema(scoreZ, smoothLen)

// ------------------------------------------------------------------------------
// Regime Detection (four-segment model: benign / normal / toxic / extreme)
// ------------------------------------------------------------------------------
var regime = 0      // 0 = normal, 1 = benign, -1 = toxic
var extremeRegime = 0  // 0 = normal, 1 = extreme toxic, -1 = extreme benign

if (smoothedZ <= benignThresh) {
    regime = 1
} else if (smoothedZ >= toxicThresh) {
    regime = -1
}

if (smoothedZ >= extremeThresh) {
    extremeRegime = 1
} else if (smoothedZ <= -extremeThresh) {
    extremeRegime = -1
}

// ------------------------------------------------------------------------------
// Static State Tracking (Session-level persistence)
// ------------------------------------------------------------------------------
// Tracks regime transitions, session extremes, and toxic event counts for
// context-aware alerting and session statistics.
static lastRegime = 0
static regimeChangeCount = 0
static sessionHighScore = -999999.0
static sessionLowScore = 999999.0
static extremeToxicCount = 0
static extremeBenignCount = 0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

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

    if (compositeFinal > sessionHighScore) {
        sessionHighScore = compositeFinal
    }
    if (compositeFinal < sessionLowScore) {
        sessionLowScore = compositeFinal
    }

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

    if (extremeRegime == 1) {
        extremeToxicCount = extremeToxicCount + 1
    } else if (extremeRegime == -1) {
        extremeBenignCount = extremeBenignCount + 1
    }
}

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

// Horizontal guide lines — zero line and configurable threshold zones
hline(value=0, color="#ffffff30", width=1)

if (showGuides) {
    hline(value=benignThresh, color=opacity(benignColor, 30), width=1)
    hline(value=toxicThresh, color=opacity(toxicColor, 30), width=1)
    hline(value=extremeThresh, color=opacity(extremeColor, 20), width=1)
    hline(value=-extremeThresh, color=opacity(extremeColor, 20), width=1)
}

// Raw composite score as histogram bars (0-100 scale)
if (showRawScore) {
    plotBar(
        value=compositeFinal,
        colors=[benignColor, toxicColor],
        width=1,
        label=["Toxicity Score"],
        desc=["Composite informed-trading probability (0-100); high values = toxic flow"]
    )
}

// Z-score line with regime-coded fill area
if (showZLine) {
    plotLine(
        value=smoothedZ,
        width=2,
        colors=[benignColor, normalColor, toxicColor, extremeColor],
        colorIndex=extremeRegime == 1 ? 3 : (extremeRegime == -1 ? 3 : (regime == 1 ? 0 : (regime == -1 ? 2 : 1))),
        label=["Toxicity Z-Score"],
        desc=["Z-standardised composite toxicity; regime-coded: benign/normal/toxic/extreme"],
        fill=true
    )
}

// Optional VPIN component line (diagnostic)
if (showVPIN) {
    plotLine(
        value=vpinScore,
        width=1,
        colors=["#9c27b0"],
        label=["VPIN Component"],
        desc=["Volume-synchronized probability of informed trading (0-100) per Easley et al. 2012"]
    )
}

// Regime transition shapes — directional signal extraction
if (showShapes) {
    var crossBenign = smoothedZ <= benignThresh && !isnan(smoothedZ[1]) && smoothedZ[1] > benignThresh
    var crossToxic = smoothedZ >= toxicThresh && !isnan(smoothedZ[1]) && smoothedZ[1] < toxicThresh
    var extremeToxicUp = smoothedZ >= extremeThresh && !isnan(smoothedZ[1]) && smoothedZ[1] < extremeThresh
    var extremeBenignDn = smoothedZ <= -extremeThresh && !isnan(smoothedZ[1]) && smoothedZ[1] > -extremeThresh

    if (crossBenign) {
        plotShape(
            value=smoothedZ,
            shape="triangleup",
            color=benignColor,
            width=3,
            label=["Benign Flow"],
            desc=["Flow crossed into benign regime — uninformed liquidity provision dominant"]
        )
    }
    if (crossToxic) {
        plotShape(
            value=smoothedZ,
            shape="triangledown",
            color=toxicColor,
            width=3,
            label=["Toxic Flow"],
            desc=["Flow crossed into toxic regime — informed trading probability elevated"]
        )
    }
    if (extremeToxicUp) {
        plotShape(
            value=smoothedZ,
            shape="diamond",
            color=extremeColor,
            width=4,
            label=["Extreme Toxic"],
            desc=["Extreme toxicity detected — probable informed or predatory flow (Kyle 1985 λ spike)"]
        )
    }
    if (extremeBenignDn) {
        plotShape(
            value=smoothedZ,
            shape="diamond",
            color=extremeColor,
            width=4,
            label=["Extreme Benign"],
            desc=["Extreme benign flow — abnormally low informed-trading probability"]
        )
    }
}