MM Flow
FlowScripts

Perfected FlowScript

Microstructure Regime Detector

Microstructure Regime Detector V2 is indexed as 247_microstructure_regime_detector.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

19.0 KB

Lines

387

Native Signal Candidates

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

4/4 guarded

Accumulation

line 347:9

Trigger

(showShapes) && (crossAccum)

Value

compositeScore

Deps

crossAccum:var, showShapes:input

Distribution

line 357:9

Trigger

(showShapes) && (crossDist)

Value

compositeScore

Deps

crossDist:var, showShapes:input

Market Making

line 367:9

Trigger

(showShapes) && (crossMM)

Value

compositeScore

Deps

crossMM:var, showShapes:input

Cascade

line 377:9

Trigger

(showShapes) && (crossCascade)

Value

compositeScore

Deps

crossCascade:var, showShapes:input

247_microstructure_regime_detector.flowscript

source path: kscripts/perfected/247_microstructure_regime_detector.flowscript · sha256:87d148dcf1a9ae0ac6e70408048f5a37c3cbaa831b0d13bffeab5322a10315f5

hash verified
//@version=2
// ============================================================================
// Microstructure Regime Detector V2 — Production-Quality Regime Classifier
// Author: D (@ddave334)  |  Perfected by: kScript Perfection Engineer
// Tags: FLOW, #microstructure, #regime, #orderbook, #volatility, #imbalance
//
// Multi-factor market microstructure regime detector combining spread analysis,
// bid/ask depth imbalance, volatility detection, and directional pressure
// into a composite score. Classifies five distinct market states with
// academic microstructure foundations.
//
// FORMULA FOUNDATION:
// 1. Spread Balance: (bestAsk − bestBid) / midPrice × 10000  [basis points]
//    per Biais, Glosten & Spatt (2005) — spread as proxy for adverse selection.
// 2. Depth Imbalance OBI: (BidVol − AskVol) / (BidVol + AskVol)  [−1, +1]
//    per Cont, Kukanov & Stoikov (2014) — linear price-impact model.
// 3. Volatility Regime: z-score of bar range vs. rolling average
//    per Harris (1986) — intraday volatility clustering.
// 4. Directional Pressure: (close − mid) / (high − low)  [−1, +1]
//    per Gellert & Schlögl (2021) — directional pressure from price location.
// 5. Composite Score: weighted combination of the four factors, normalized.
//
// RESEARCH BASIS:
//  • Biais, Glosten & Spatt (2005), "Market Microstructure: A Survey",
//    J. Financial Markets. Five market states: equilibrium, information arrival,
//    inventory adjustment, stress/crisis, liquidity provision.
//  • Gellert & Schlögl (2021), "Parameter Learning and Change Detection",
//    Risks 9(12), 228. Particle filter for rapid regime-shift adaptation.
//  • Mehl et al. (2019), "Fast Trading and the Virtue of Entropy", ECB WP 2300.
//    Shannon entropy quantifies orderbook structure; high entropy = uniform
//    (Market Making/Neutral), low entropy = concentrated (Liquidation Cascade).
//  • Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events",
//    J. Financial Econometrics 12(1), 47–88. OFI = Σ(E_i × ΔP_i); slope ∝ 1/depth.
//  • Cartea, Donnelly & Jaimungal (2018), "Enhancing Trading Strategies with
//    Order Book Signals", Appl. Math. Finance 25(1), 1–35. Three-regime
//    segmentation: Sell-heavy (−1,−1/3), Neutral (−1/3,1/3), Buy-heavy (1/3,1).
// ============================================================================

define(
    title="Microstructure Regime Detector V2",
    position="offchart",
    axis=true
)

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

// --- Spread Analysis ---
var spreadLookback = input(name="spreadLookback", type="number", defaultValue=20, label="Spread Lookback", constraints={min: 5, max: 100, step: 1}, group="Spread")
var spreadSmoothLen = input(name="spreadSmooth", type="number", defaultValue=5, label="Spread EMA Smoothing", constraints={min: 1, max: 50, step: 1}, group="Spread")
var spreadWeight = input(name="spreadWeight", type="number", defaultValue=0.25, label="Spread Weight", constraints={min: 0.0, max: 1.0, step: 0.05}, group="Spread")

// --- Depth Imbalance ---
var depth1 = input(name="depth1", type="number", defaultValue=1.0, label="Depth Band 1 (%)", constraints={min: 0.1, max: 50.0, step: 0.1}, group="Depth")
var depth2 = input(name="depth2", type="number", defaultValue=2.5, label="Depth Band 2 (%)", constraints={min: 0.1, max: 50.0, step: 0.1}, group="Depth")
var depth3 = input(name="depth3", type="number", defaultValue=5.0, label="Depth Band 3 (%)", constraints={min: 0.1, max: 50.0, step: 0.1}, group="Depth")
var depth4 = input(name="depth4", type="number", defaultValue=10.0, label="Depth Band 4 (%)", constraints={min: 0.1, max: 50.0, step: 0.1}, group="Depth")
var useDepthWeighting = input(name="useDepthWeighting", type="boolean", defaultValue=true, label="Use Depth-Decaying Weights", group="Depth")
var weightDecay = input(name="weightDecay", type="number", defaultValue=0.75, label="Weight Decay Factor", constraints={min: 0.0, max: 1.0, step: 0.05}, group="Depth")
var depthWeight = input(name="depthWeight", type="number", defaultValue=0.30, label="Depth Weight", constraints={min: 0.0, max: 1.0, step: 0.05}, group="Depth")

// --- Volatility ---
var volLookback = input(name="volLookback", type="number", defaultValue=20, label="Volatility Lookback", constraints={min: 5, max: 100, step: 1}, group="Volatility")
var volSmoothLen = input(name="volSmooth", type="number", defaultValue=5, label="Volatility EMA Smoothing", constraints={min: 1, max: 50, step: 1}, group="Volatility")
var volWeight = input(name="volWeight", type="number", defaultValue=0.25, label="Volatility Weight", constraints={min: 0.0, max: 1.0, step: 0.05}, group="Volatility")

// --- Directional Pressure ---
var pressureLookback = input(name="pressureLookback", type="number", defaultValue=10, label="Pressure Lookback", constraints={min: 5, max: 50, step: 1}, group="Pressure")
var pressureSmoothLen = input(name="pressureSmooth", type="number", defaultValue=5, label="Pressure EMA Smoothing", constraints={min: 1, max: 50, step: 1}, group="Pressure")
var pressureWeight = input(name="pressureWeight", type="number", defaultValue=0.20, label="Pressure Weight", constraints={min: 0.0, max: 1.0, step: 0.05}, group="Pressure")

// --- Thresholds & Regime ---
var mmThresh = input(name="mmThresh", type="number", defaultValue=0.15, label="Market Making Threshold", constraints={min: 0.05, max: 0.5, step: 0.05}, group="Thresholds")
var accumThresh = input(name="accumThresh", type="number", defaultValue=0.35, label="Accumulation Threshold", constraints={min: 0.2, max: 0.8, step: 0.05}, group="Thresholds")
var distThresh = input(name="distThresh", type="number", defaultValue=-0.35, label="Distribution Threshold", constraints={min: -0.8, max: -0.2, step: 0.05}, group="Thresholds")
var cascadeVolThresh = input(name="cascadeVolThresh", type="number", defaultValue=2.0, label="Cascade Volatility Z-Score", constraints={min: 1.0, max: 5.0, step: 0.5}, group="Thresholds")

// --- Display ---
var showGuides = input(name="showGuides", type="boolean", defaultValue=true, label="Show Guide Lines", group="Display")
var showRawBars = input(name="showRawBars", type="boolean", defaultValue=true, label="Show Composite Score Histogram", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Regime Shapes", group="Display")
var showComposite = input(name="showComposite", type="boolean", defaultValue=true, label="Show Composite Line", group="Display")
var showComponents = input(name="showComponents", type="boolean", defaultValue=false, label="Show Individual Components", group="Display")

// --- Colors ---
var mmColor = input(name="mmColor", type="color", defaultValue="#26a69a", label="Market Making Color", group="Colors")
var accumColor = input(name="accumColor", type="color", defaultValue="#2962ff", label="Accumulation Color", group="Colors")
var distColor = input(name="distColor", type="color", defaultValue="#ff6d00", label="Distribution Color", group="Colors")
var cascadeColor = input(name="cascadeColor", type="color", defaultValue="#ef5350", label="Cascade Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#9e9e9e", label="Neutral Color", group="Colors")
var spreadColor = input(name="spreadColor", type="color", defaultValue="#ab47bc", label="Spread Component Color", group="Colors")
var depthColor = input(name="depthColor", type="color", defaultValue="#42a5f5", label="Depth Component Color", group="Colors")
var volColor = input(name="volColor", type="color", defaultValue="#ffa726", label="Volatility Component Color", group="Colors")
var pressureColor = input(name="pressureColor", type="color", defaultValue="#66bb6a", label="Pressure Component Color", group="Colors")

// ---------------------------------------------------------------------------
// Data Sources
// ---------------------------------------------------------------------------
timeseries priceBars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries px = priceBars.close
timeseries high = priceBars.high
timeseries low = priceBars.low
timeseries book = source("orderbook", currentSymbol, currentExchange)

// NaN guard — prevent execution before data is loaded (Biais et al. 2005 data-integrity best practice)
if (isnan(px[0]) || isnan(high[0]) || isnan(low[0])) {
    return
}

// ---------------------------------------------------------------------------
// Component 1: Spread Balance (Biais, Glosten & Spatt 2005)
// ---------------------------------------------------------------------------
// Spread as proxy for adverse selection and market maker compensation.
// Narrow spreads = liquid, competitive market making (Market Making regime).
// Wide spreads = uncertainty, adverse selection risk (Cascade/Distribution).

timeseries bestBid = bookBid(book, 1)
timeseries bestAsk = bookAsk(book, 1)
timeseries midPrice = (bestBid + bestAsk) / 2.0
var spreadBps = midPrice > 0 ? (bestAsk - bestBid) / midPrice * 10000.0 : 0.0

var spreadAvailable = bestBid > 0 && bestAsk > 0 && bestAsk > bestBid

// Spread z-score: how wide is current spread vs. historical
timeseries spreadMean = sma(source=spreadBps, period=spreadLookback)
timeseries spreadStd = stddev(source=spreadBps, period=spreadLookback)
timeseries spreadZ = spreadAvailable && spreadStd > 0 ? (spreadBps - spreadMean) / spreadStd : 0.0

// Normalize: negative spreadZ = narrow (market making), positive = wide (stress)
// Invert so narrow spread = positive contribution to MM regime
timeseries spreadScore = spreadAvailable ? -spreadZ : 0.0
timeseries spreadSmooth = ema(spreadScore, spreadSmoothLen)

// ---------------------------------------------------------------------------
// Component 2: Depth Imbalance (Cont, Kukanov & Stoikov 2014)
// ---------------------------------------------------------------------------
// OBI = (BidVol − AskVol) / (BidVol + AskVol) ∈ [−1, +1]
// Multi-level with depth-decaying weights per Xu, Gould & Howison (2019).

var bids1 = sumBids(book, depth1)
var asks1 = sumAsks(book, depth1)
var bids2 = sumBids(book, depth2)
var asks2 = sumAsks(book, depth2)
var bids3 = sumBids(book, depth3)
var asks3 = sumAsks(book, depth3)
var bids4 = sumBids(book, depth4)
var asks4 = sumAsks(book, depth4)

// Book availability check — prevents NaN/undefined propagation
var bookAvailable = bids1 > 0 && asks1 > 0 && bids2 > 0 && asks2 > 0 && bids3 > 0 && asks3 > 0 && bids4 > 0 && asks4 > 0

var denom1 = bids1 + asks1
var denom2 = bids2 + asks2
var denom3 = bids3 + asks3
var denom4 = bids4 + asks4

var obi1 = bookAvailable && denom1 > 0 ? (bids1 - asks1) / denom1 : 0.0
var obi2 = bookAvailable && denom2 > 0 ? (bids2 - asks2) / denom2 : 0.0
var obi3 = bookAvailable && denom3 > 0 ? (bids3 - asks3) / denom3 : 0.0
var obi4 = bookAvailable && denom4 > 0 ? (bids4 - asks4) / denom4 : 0.0

// Depth-weighted composite (Xu, Gould & Howison 2019)
var w1 = 1.0
var w2 = useDepthWeighting ? weightDecay : 1.0
var w3 = useDepthWeighting ? weightDecay * weightDecay : 1.0
var w4 = useDepthWeighting ? weightDecay * weightDecay * weightDecay : 1.0
var wSum = w1 + w2 + w3 + w4
var compositeOBI = wSum > 0 ? (w1 * obi1 + w2 * obi2 + w3 * obi3 + w4 * obi4) / wSum : 0.0

// ---------------------------------------------------------------------------
// Component 3: Volatility Regime (Harris 1986 intraday seasonality)
// ---------------------------------------------------------------------------
// Z-score of bar range: high = Liquidation Cascade, low = Market Making.

timeseries barRange = high - low
timeseries avgRange = sma(source=barRange, period=volLookback)
timeseries rangeStd = stddev(source=barRange, period=volLookback)
timeseries volZ = rangeStd > 0 ? (barRange - avgRange) / rangeStd : 0.0
timeseries volSmooth = ema(volZ, volSmoothLen)

// ---------------------------------------------------------------------------
// Component 4: Directional Pressure (Gellert & Schlögl 2021)
// ---------------------------------------------------------------------------
// Where did price close within the bar's range? +1 = close at high,
// −1 = close at low. Smoothed over lookback for persistent pressure.

timeseries midBar = (high + low) / 2.0
timeseries barRangeSafe = high - low
timeseries rawPressure = barRangeSafe > 0 ? (px - midBar) / (barRangeSafe / 2.0) : 0.0
// Clamp to [-1, 1]
timeseries clampedPressure = rawPressure > 1.0 ? 1.0 : (rawPressure < -1.0 ? -1.0 : rawPressure)
timeseries pressureSmooth = ema(clampedPressure, pressureSmoothLen)

// ---------------------------------------------------------------------------
// Composite Score (weighted combination, normalized to [-1, +1])
// ---------------------------------------------------------------------------
var totalWeight = spreadWeight + depthWeight + volWeight + pressureWeight
var normFactor = totalWeight > 0 ? 1.0 / totalWeight : 1.0

timeseries compositeScore = normFactor * (
    spreadWeight * spreadSmooth +
    depthWeight * compositeOBI +
    volWeight * (-volSmooth) +  // negative vol = MM regime
    pressureWeight * pressureSmooth
)

// Clamp composite to [-1, 1]
compositeScore = compositeScore > 1.0 ? 1.0 : (compositeScore < -1.0 ? -1.0 : compositeScore)

// ---------------------------------------------------------------------------
// Regime Detection (5-state classification per Biais et al. 2005)
// ---------------------------------------------------------------------------
// Regime mapping:
//   1 = Market Making (balanced, low vol, narrow spread)
//   2 = Accumulation (bid-heavy, building support)
//   3 = Distribution (ask-heavy, increasing pressure)
//   4 = Liquidation Cascade (extreme vol, any direction)
//   0 = Neutral (none of the above dominant)

var regime = 0

if (volSmooth > cascadeVolThresh) {
    regime = 4  // Cascade takes precedence
} else if (compositeScore >= accumThresh) {
    regime = 2  // Accumulation
} else if (compositeScore <= distThresh) {
    regime = 3  // Distribution
} else if (math.abs(compositeScore) <= mmThresh && volSmooth <= 1.0) {
    regime = 1  // Market Making (balanced + low vol)
}

// ---------------------------------------------------------------------------
// Static State Tracking (Session-level persistence)
// ---------------------------------------------------------------------------
// Tracks regime transitions, session extremes, and extreme-event counts.

static lastRegime = 0
static regimeChangeCount = 0
static sessionHighScore = -999999.0
static sessionLowScore = 999999.0
static cascadeCount = 0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

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

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

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

    if (regime == 4) {
        cascadeCount = cascadeCount + 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=accumThresh, color=opacity(accumColor, 30), width=1)
    hline(value=distThresh, color=opacity(distColor, 30), width=1)
    hline(value=mmThresh, color=opacity(mmColor, 20), width=1)
    hline(value=-mmThresh, color=opacity(mmColor, 20), width=1)
}

// Raw composite score as histogram bars (regime-colored)
if (showRawBars) {
    plotBar(
        value=compositeScore,
        colors=[mmColor, accumColor, distColor, cascadeColor, neutralColor],
        colorIndex=regime,
        width=1,
        label=["Composite Score"],
        desc=["Weighted composite microstructure score: MM=1, Accum=2, Dist=3, Cascade=4, Neutral=0"]
    )
}

// Smoothed composite line with regime-coded fill area
if (showComposite) {
    plotLine(
        value=compositeScore,
        width=2,
        colors=[mmColor, accumColor, distColor, cascadeColor, neutralColor],
        colorIndex=regime,
        label=["Regime Score"],
        desc=["Composite microstructure regime score. Regime: MM/Accum/Dist/Cascade/Neutral."],
        fill=true
    )
}

// Individual component lines (optional, for granular analysis)
if (showComponents) {
    plotLine(
        value=spreadSmooth,
        width=1,
        colors=[spreadColor],
        label=["Spread"],
        desc=["Spread balance component (inverted z-score): negative = narrow, positive = wide"]
    )
    plotLine(
        value=compositeOBI,
        width=1,
        colors=[depthColor],
        label=["Depth OBI"],
        desc=["Depth-weighted order book imbalance: +1 = bid-heavy, -1 = ask-heavy"]
    )
    plotLine(
        value=-volSmooth,
        width=1,
        colors=[volColor],
        label=["Vol Regime"],
        desc=["Inverted volatility z-score: positive = calm, negative = volatile"]
    )
    plotLine(
        value=pressureSmooth,
        width=1,
        colors=[pressureColor],
        label=["Pressure"],
        desc=["Directional pressure: +1 = close at high, -1 = close at low"]
    )
}

// Regime transition shapes — directional signal extraction
if (showShapes) {
    var crossAccum = compositeScore >= accumThresh && !isnan(compositeScore[1]) && compositeScore[1] < accumThresh
    var crossDist = compositeScore <= distThresh && !isnan(compositeScore[1]) && compositeScore[1] > distThresh
    var crossMM = math.abs(compositeScore) <= mmThresh && volSmooth <= 1.0 && !isnan(compositeScore[1]) && (math.abs(compositeScore[1]) > mmThresh || volSmooth[1] > 1.0)
    var crossCascade = volSmooth >= cascadeVolThresh && !isnan(volSmooth[1]) && volSmooth[1] < cascadeVolThresh

    if (crossAccum) {
        plotShape(
            value=compositeScore,
            shape="triangleup",
            color=accumColor,
            width=3,
            label=["Accumulation"],
            desc=["Composite score crossed into accumulation regime (bid-heavy building)"]
        )
    }
    if (crossDist) {
        plotShape(
            value=compositeScore,
            shape="triangledown",
            color=distColor,
            width=3,
            label=["Distribution"],
            desc=["Composite score crossed into distribution regime (ask-heavy pressure)"]
        )
    }
    if (crossMM) {
        plotShape(
            value=compositeScore,
            shape="circle",
            color=mmColor,
            width=3,
            label=["Market Making"],
            desc=["Entered market making regime (balanced, low volatility)"]
        )
    }
    if (crossCascade) {
        plotShape(
            value=compositeScore,
            shape="diamond",
            color=cascadeColor,
            width=4,
            label=["Cascade"],
            desc=["Liquidation cascade detected — extreme volatility regime"]
        )
    }
}