MM Flow
FlowScripts

Perfected FlowScript

Trade Clustering Coefficient

Trade Clustering Coefficient V2 is indexed as 231_trade_clustering_coefficient.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

15.4 KB

Lines

352

Native Signal Candidates

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

4/4 guarded

Algo Regime

line 277:9

Trigger

(showShapes) && (crossAlgo)

Value

zScore

Deps

crossAlgo:var, showShapes:input

Organic Regime

line 287:9

Trigger

(showShapes) && (crossOrganic)

Value

zScore

Deps

crossOrganic:var, showShapes:input

Extreme Algo

line 297:9

Trigger

(showShapes) && (extremeAlgo)

Value

zScore

Deps

extremeAlgo:var, showShapes:input

Extreme Organic

line 307:9

Trigger

(showShapes) && (extremeOrganic)

Value

zScore

Deps

extremeOrganic:var, showShapes:input

231_trade_clustering_coefficient.flowscript

source path: kscripts/perfected/231_trade_clustering_coefficient.flowscript · sha256:019c0af871d90b538dbcff74e3eee03f013245d4e0a249ea8a260b224672d873

hash verified
//@version=2
// ============================================================================
// Trade Clustering Coefficient V2 — Production-Quality Algorithmic Flow Detector
// Author: D (@ddave334) | Perfected by: kScript Perfection Engineer
// Tags: FLOW, #volume, #clustering, #algorithmic, #microstructure, #zscore
//
// Detects algorithmic vs. organic trading flow using network-theory clustering
// metrics with z-score normalization, regime detection, and comprehensive
// visualization. High values indicate HFT/institutional execution patterns;
// low values indicate organic retail flow.
//
// FORMULA FOUNDATION:
// 1. Temporal Clustering: rolling coefficient of variation (CV) of volume
//    Low CV = uniform/clustered (algorithmic); high CV = organic/heterogeneous.
// 2. Size Clustering: CV of buy/sell ratio — stable ratio = clustered execution.
// 3. Composite Clustering: (tempClust + sizeClust) / 2, smoothed.
// 4. Z-Score Normalization: (composite − rollingMean) / rollingStd per
//    Zhao & Palomar (2018), mean-reversion threshold detection.
// 5. Regime Segmentation: Algo Clustered (z > 1), Neutral (−1 ≤ z ≤ 1),
//    Organic Retail (z < −1) per Easley, López de Prado & O'Hara (2012 BVC).
//
// RESEARCH BASIS:
//  • Cartea, Jaimungal & Penalva (2015), "Algorithmic and High-Frequency
//    Trading" — Cambridge UP. HFT order-splitting creates temporal clustering.
//  • Anagnostidis et al. (2016), "Liquidity Provision, Commonality and HFT" —
//    SAFE WP. >90% of best quotes from HFT DMMs; quote clustering analysis.
//  • Abad et al. (2020), "Order Flow Toxicity under the Microscope" — JFM 48.
//    HFT cancellations/revisions carry information; toxic flow detection.
//  • Easley, López de Prado & O'Hara (2012), "Bulk Classification of Trading
//    Activity" — BVC method. Probabilistic volume classification robust to HFT.
//  • Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint" —
//    IEEE TSP. Z-score normalization for threshold-based regime detection.
//  • Lillo & Farmer (2004), "The Long Memory of the Efficient Market" — SNDE 8(3).
//    Order flow persistence justifies rolling-window clustering measures.
// ============================================================================

define(
    title="Trade Clustering Coefficient V2",
    position="offchart",
    axis=true
)

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

// --- Clustering Configuration ---
var windowLen = input(name="windowLen", type="number", defaultValue=20, label="Rolling Window Length", constraints={min: 5, max: 100, step: 1}, group="Clustering")
var timeThreshold = input(name="timeThreshold", type="number", defaultValue=3, label="Time Proximity (bars)", constraints={min: 1, max: 20, step: 1}, group="Clustering")
var sizeThreshold = input(name="sizeThreshold", type="number", defaultValue=0.2, label="Size Proximity (fraction)", constraints={min: 0.05, max: 1.0, step: 0.05}, group="Clustering")

// --- Smoothing ---
var smoothLen = input(name="smoothLen", type="number", defaultValue=5, label="SMA Smoothing Length", constraints={min: 1, max: 50, step: 1}, group="Smoothing")
var useZScore = input(name="useZScore", type="boolean", defaultValue=true, label="Use Z-Score Normalization", group="Smoothing")
var zLookback = input(name="zLookback", type="number", defaultValue=20, label="Z-Score Lookback", constraints={min: 10, max: 100, step: 1}, group="Smoothing")

// --- Thresholds & Regime ---
var algoThresh = input(name="algoThresh", type="number", defaultValue=1.0, label="Algorithmic Z-Score Threshold", constraints={min: 0.5, max: 3.0, step: 0.1}, group="Thresholds")
var organicThresh = input(name="organicThresh", type="number", defaultValue=-1.0, label="Organic Z-Score Threshold", constraints={min: -3.0, max: -0.5, step: 0.1}, group="Thresholds")
var extremeThresh = input(name="extremeThresh", type="number", defaultValue=2.0, label="Extreme Clustering Z-Score", constraints={min: 1.5, max: 4.0, step: 0.1}, group="Thresholds")

// --- Display ---
var showRaw = input(name="showRaw", type="boolean", defaultValue=true, label="Show Raw Clustering Histogram", group="Display")
var showZScore = input(name="showZScore", type="boolean", defaultValue=true, label="Show Z-Score Line", group="Display")
var showSignal = input(name="showSignal", type="boolean", defaultValue=true, label="Show Signal Fill", 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 algoColor = input(name="algoColor", type="color", defaultValue="#ef5350", label="Algorithmic Color", group="Colors")
var retailColor = input(name="retailColor", type="color", defaultValue="#26a69a", label="Organic Retail Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#9e9e9e", label="Neutral Color", group="Colors")
var extremeAlgoColor = input(name="extremeAlgoColor", type="color", defaultValue="#ff1744", label="Extreme Algorithmic Color", group="Colors")
var extremeRetailColor = input(name="extremeRetailColor", type="color", defaultValue="#00e676", label="Extreme Organic Color", group="Colors")

// ------------------------------------------------------------------------------
// Data Sources & NaN Guard
// ------------------------------------------------------------------------------
timeseries ohlcvTS = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries close = ohlcvTS.close
timeseries volume = ohlcvTS.volume
timeseries buySell = buy_sell_volume(symbol=currentSymbol, exchange=currentExchange)

// NaN guard — prevent execution before data is loaded (Cont et al. 2014 data-integrity best practice)
if (isnan(close[0]) || isnan(volume[0])) {
    return
}

// ------------------------------------------------------------------------------
// Volume Clustering Computation (Easley et al. 2012 BVC-inspired)
// ------------------------------------------------------------------------------
// Temporal clustering: rolling CV of volume
// Low CV = uniform/clustered (algorithmic); high CV = organic/heterogeneous

timeseries volMean = sma(source=volume, period=windowLen)
timeseries volStd = stddev(source=volume, period=windowLen)
timeseries volCV = volMean > 0 ? volStd / volMean : 0

// Size clustering: rolling CV of buy vs sell volume ratio
// Stable ratio = clustered execution (HFT order splitting per Cartea et al. 2015)
timeseries buyV = buySell.buy_volume
timeseries sellV = buySell.sell_volume
timeseries ratio = sellV > 0 ? buyV / sellV : 1
timeseries ratioMean = sma(source=ratio, period=windowLen)
timeseries ratioStd = stddev(source=ratio, period=windowLen)
timeseries ratioCV = ratioMean > 0 ? ratioStd / ratioMean : 0

// Composite clustering: invert CV so high = clustered (algorithmic), low = organic
// 1 − CV maps [0,1] where 1 = perfectly clustered, 0 = perfectly dispersed
timeseries tempClust = 1 - math.min(volCV, 1.0)
timeseries sizeClust = 1 - math.min(ratioCV, 1.0)
timeseries composite = (tempClust + sizeClust) / 2.0

// Smoothed composite
timeseries smooth = sma(source=composite, period=smoothLen)

// ------------------------------------------------------------------------------
// Z-Score Normalization (Zhao & Palomar 2018)
// ------------------------------------------------------------------------------
// Standardizes the clustering coefficient for threshold-based regime detection.
// z = (value − mean) / stddev over rolling lookback window.

timeseries rollingMean = sma(source=smooth, period=zLookback)
timeseries rollingStd = stddev(source=smooth, period=zLookback)

timeseries zScore = useZScore && rollingStd > 0 ? (smooth - rollingMean) / rollingStd : 0

// Plot value: zScore if enabled, otherwise raw composite normalized to [0,1]
timeseries plotValue = useZScore ? zScore : (smooth - 0.5) * 4.0

// ------------------------------------------------------------------------------
// Regime Detection (BVC-inspired three-regime model)
// ------------------------------------------------------------------------------
// Regime classification based on z-score thresholds:
//   Algo Clustered: z > algoThresh (high clustering, HFT/institutional)
//   Neutral: organicThresh ≤ z ≤ algoThresh (mixed flow)
//   Organic Retail: z < organicThresh (dispersed, retail-dominated)
//   Extreme Algo: z > extremeThresh (very high clustering, toxic flow)
//   Extreme Organic: z < -extremeThresh (very low clustering, exhaustion)

var regime = 0      // 0 = neutral, 1 = algo, -1 = organic
var extremeRegime = 0  // 0 = normal, 1 = extreme algo, -1 = extreme organic

if (useZScore) {
    if (zScore >= algoThresh) {
        regime = 1
    } else if (zScore <= organicThresh) {
        regime = -1
    }
    if (zScore >= extremeThresh) {
        extremeRegime = 1
    } else if (zScore <= -extremeThresh) {
        extremeRegime = -1
    }
} else {
    // Fallback for raw composite (0-1 scale)
    var highThresh = 0.65
    var lowThresh = 0.35
    if (smooth >= highThresh) {
        regime = 1
    } else if (smooth <= lowThresh) {
        regime = -1
    }
    if (smooth >= 0.85) {
        extremeRegime = 1
    } else if (smooth <= 0.15) {
        extremeRegime = -1
    }
}

var regimeColor = regime == 1 ? algoColor : (regime == -1 ? retailColor : neutralColor)

// ------------------------------------------------------------------------------
// Static State Tracking (Session-level persistence)
// ------------------------------------------------------------------------------
// Stateful computation for anchoring, session tracking, and counters.
// Tracks regime transitions, session extremes, and extreme-event counts.

static lastRegime = 0
static regimeChangeCount = 0
static sessionHighZ = -999999.0
static sessionLowZ = 999999.0
static extremeAlgoCount = 0
static extremeOrganicCount = 0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

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

    var val = useZScore ? zScore : smooth
    if (val > sessionHighZ) {
        sessionHighZ = val
    }
    if (val < sessionLowZ) {
        sessionLowZ = val
    }

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

    if (extremeRegime == 1) {
        extremeAlgoCount = extremeAlgoCount + 1
    } else if (extremeRegime == -1) {
        extremeOrganicCount = extremeOrganicCount + 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) {
    if (useZScore) {
        hline(value=algoThresh, color=opacity(algoColor, 30), width=1)
        hline(value=organicThresh, color=opacity(retailColor, 30), width=1)
        hline(value=extremeThresh, color=opacity(extremeAlgoColor, 20), width=1)
        hline(value=-extremeThresh, color=opacity(extremeRetailColor, 20), width=1)
    } else {
        hline(value=0.5, color=neutralColor, width=1)
    }
}

// Raw clustering as histogram (algorithmic/organic pressure visualization)
if (showRaw) {
    plotBar(
        value=plotValue,
        colors=[algoColor, retailColor],
        width=1,
        label=["Clustering Coefficient"],
        desc=["Trade clustering coefficient: positive=algo clustered, negative=organic retail"]
    )
}

// Z-Score line with regime-coded fill area
if (showZScore) {
    plotLine(
        value=zScore,
        width=2,
        colors=[algoColor, retailColor, neutralColor],
        colorIndex=regime == 1 ? 0 : (regime == -1 ? 1 : 2),
        label=["Z-Score Clustering"],
        desc=["Z-score normalized clustering coefficient. Regime: algo/neutral/organic."],
        fill=true
    )
}

// Signal fill (raw vs zero reference)
if (showSignal) {
    var signalBull = plotValue >= 0
    plotLine(
        value=[plotValue, 0],
        width=1,
        colors=[opacity(algoColor, 20), opacity(retailColor, 20)],
        colorIndex=signalBull ? 0 : 1,
        fill=true,
        label=["Clustering Signal", "Zero Line"],
        desc=["Fill between clustering coefficient and zero reference"]
    )
}

// Regime transition shapes — directional signal extraction (Abad et al. 2020)
if (showShapes) {
    var crossAlgo = zScore >= algoThresh && !isnan(zScore[1]) && zScore[1] < algoThresh
    var crossOrganic = zScore <= organicThresh && !isnan(zScore[1]) && zScore[1] > organicThresh
    var extremeAlgo = zScore >= extremeThresh && !isnan(zScore[1]) && zScore[1] < extremeThresh
    var extremeOrganic = zScore <= -extremeThresh && !isnan(zScore[1]) && zScore[1] > -extremeThresh

    if (crossAlgo) {
        plotShape(
            value=zScore,
            shape="triangleup",
            color=extremeAlgoColor,
            width=3,
            label=["Algo Regime"],
            desc=["Clustering crossed into algorithmic regime (HFT/institutional detected)"]
        )
    }
    if (crossOrganic) {
        plotShape(
            value=zScore,
            shape="triangledown",
            color=extremeRetailColor,
            width=3,
            label=["Organic Regime"],
            desc=["Clustering crossed into organic retail regime (dispersed flow)"]
        )
    }
    if (extremeAlgo) {
        plotShape(
            value=zScore,
            shape="diamond",
            color=extremeAlgoColor,
            width=4,
            label=["Extreme Algo"],
            desc=["Extreme algorithmic clustering detected — potential toxic flow / predatory activity"]
        )
    }
    if (extremeOrganic) {
        plotShape(
            value=zScore,
            shape="diamond",
            color=extremeRetailColor,
            width=4,
            label=["Extreme Organic"],
            desc=["Extreme organic flow detected — potential exhaustion / capitulation signal"]
        )
    }
}

// ------------------------------------------------------------------------------
// Regime Table (last bar only)
// ------------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = regime == 1 ? "ALGORITHMIC" : (regime == -1 ? "ORGANIC" : "NEUTRAL")
    var regimeTextColor = regime == 1 ? algoColor : (regime == -1 ? retailColor : neutralColor)

    plotTable(
        data=[
            ["Clustering Coefficient V2", regimeText],
            ["Z-Score", zScore[0]],
            ["Raw Composite", composite[0]],
            ["Smooth", smooth[0]],
            ["Vol CV", volCV[0]],
            ["Ratio CV", ratioCV[0]],
            ["Session High Z", sessionHighZ],
            ["Session Low Z", sessionLowZ],
            ["Regime Changes", regimeChangeCount],
            ["Extreme Algo Count", extremeAlgoCount],
            ["Extreme Organic Count", extremeOrganicCount]
        ],
        position="top_right",
        headerRow=true,
        headerColumn=true,
        textColor="#e2e8f0",
        headerTextColor="#ffffff",
        backgroundColor=transparency("#0f172a", 40),
        headerBackgroundColor=transparency("#1e293b", 40),
        borderColor=transparency("#334155", 40),
        borderWidth=1,
        fontSize=10,
        cellPadding=4
    )
}