MM Flow
FlowScripts

Perfected FlowScript

Normal test mods

Synthetic Orderbook Pressure Z-Score Pro is indexed as 353_normal_test_mods.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.2 KB

Lines

580

Native Signal Candidates

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

6/6 guarded

Extreme Buy

line 482:9

Trigger

(showShapes) && (crossUpOuter)

Value

adjustedZ

Deps

crossUpOuter:var, showShapes:input

Extreme Sell

line 492:9

Trigger

(showShapes) && (crossDnOuter)

Value

adjustedZ

Deps

crossDnOuter:var, showShapes:input

Buy Zone

line 502:9

Trigger

(showShapes) && (crossUpInner)

Value

adjustedZ

Deps

crossUpInner:var, showShapes:input

Sell Zone

line 512:9

Trigger

(showShapes) && (crossDnInner)

Value

adjustedZ

Deps

crossDnInner:var, showShapes:input

Zero Cross Up

line 522:9

Trigger

(showShapes) && (zeroCrossUp)

Value

0

Deps

showShapes:input, zeroCrossUp:var

Zero Cross Down

line 532:9

Trigger

(showShapes) && (zeroCrossDn)

Value

0

Deps

showShapes:input, zeroCrossDn:var

353_normal_test_mods.flowscript

source path: kscripts/perfected/353_normal_test_mods.flowscript · sha256:3cd0ce624cdaecc46ea73d5acb2280e887f3b5cc21da8cac535763f3cdc5a33f

hash verified
//@version=2
// ============================================================================
// Synthetic Orderbook Pressure Z-Score Pro — Perfected Edition
// Author: I (@Iopl147u) | Enhanced by kScript Perfection Engineer
// Tags: FLOW, #orderbook, #zscore, #microstructure, #regime, #pressure
//
// Production-quality synthetic orderbook imbalance indicator derived from
// price-action microstructure. Computes a Z-score of price deviation from
// mid relative to spread, augments with volume confirmation and ATR-based
// dynamic thresholds, and produces a multi-depth composite with five-regime
// segmentation, stateful tracking, and comprehensive signal visualization.
//
// FORMULA FOUNDATION:
// 1. Synthetic Orderbook Imbalance (SOBI): SOBI = (Close − Mid) / Spread
//    where Mid = (High + Low) / 2 and Spread = High − Low. This measures
//    directional pressure from intrabar price positioning.
// 2. Z-Score Normalization: Z = (SOBI − μ) / σ over rolling window.
//    Per Zhao & Palomar (2018), z-score entry thresholds at ±1σ, ±2σ.
// 3. Multi-Depth Composite: Z_composite = Σ w_i × Z_i / Σ w_i where
//    w_i decay with lookback length (Xu, Gould & Howison 2019).
// 4. Regime Segmentation (Cartea et al. 2018): Extreme Buy, Buy, Neutral,
//    Sell, Extreme Sell based on composite z-score thresholds.
// 5. Dynamic Thresholds (Poterba & Summers 1988): bands adjusted by
//    rolling volatility of the z-score itself.
//
// RESEARCH BASIS:
//  • 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.
//    Validates that order flow imbalance drives short-term price changes.
//  • Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint".
//    Z-score normalization framework; entry thresholds at ±1σ, ±2σ.
//  • Xu, Gould & Howison (2019), "Multi-Level Order-Flow Imbalance in a
//    Limit Order Book", arXiv:1907.06230. Multi-level OFI with decaying weights.
//  • Cartea, Donnelly & Jaimungal (2018), "Enhancing Trading Strategies with
//    Order Book Signals", Appl. Math. Finance 25(1), 1–35. Five-regime
//    segmentation improves signal clarity and reduces false positives.
//  • Gould & Bonart (2016), "Queue Imbalance as a One-Tick-Ahead Price
//    Predictor", Market Microstructure & Liquidity 2(1), 1650006. Queue
//    imbalance logistic regression for next-tick direction prediction.
// ============================================================================

define(
    title="Synthetic Orderbook Pressure Z-Score Pro",
    position="offchart",
    axis=true
)

// ----------------------------------------------------------------------------
// 1. USER INPUTS — grouped with constraints
// ----------------------------------------------------------------------------

// --- Depth / Lookback ---
var lookback1 = input(
    name="lookback1",
    type="number",
    defaultValue=20,
    label="Primary Lookback",
    constraints={min: 5, max: 100, step: 1},
    group="Depth / Lookback"
)
var lookback2 = input(
    name="lookback2",
    type="number",
    defaultValue=50,
    label="Secondary Lookback",
    constraints={min: 10, max: 200, step: 1},
    group="Depth / Lookback"
)
var lookback3 = input(
    name="lookback3",
    type="number",
    defaultValue=100,
    label="Tertiary Lookback",
    constraints={min: 20, max: 500, step: 1},
    group="Depth / Lookback"
)
var useMultiDepth = input(
    name="useMultiDepth",
    type="boolean",
    defaultValue=true,
    label="Use Multi-Depth Composite",
    group="Depth / Lookback"
)
var weightDecay = input(
    name="weightDecay",
    type="number",
    defaultValue=0.6,
    label="Depth Weight Decay",
    constraints={min: 0.0, max: 1.0, step: 0.05},
    group="Depth / Lookback"
)

// --- Smoothing ---
var smoothLen = input(
    name="smoothLen",
    type="number",
    defaultValue=3,
    label="EMA Smoothing Length",
    constraints={min: 1, max: 20, step: 1},
    group="Smoothing"
)
var smoothComposite = input(
    name="smoothComposite",
    type="boolean",
    defaultValue=true,
    label="Smooth Composite Z-Score",
    group="Smoothing"
)

// --- Thresholds & Regime ---
var innerGuide = input(
    name="innerGuide",
    type="number",
    defaultValue=1.0,
    label="Inner Guide (σ)",
    constraints={min: 0.5, max: 3.0, step: 0.1},
    group="Thresholds"
)
var outerGuide = input(
    name="outerGuide",
    type="number",
    defaultValue=2.0,
    label="Outer Guide (σ)",
    constraints={min: 1.0, max: 5.0, step: 0.1},
    group="Thresholds"
)
var useDynamic = input(
    name="useDynamic",
    type="boolean",
    defaultValue=true,
    label="Dynamic Thresholds (volatility-adjusted)",
    group="Thresholds"
)
var volLookback = input(
    name="volLookback",
    type="number",
    defaultValue=20,
    label="Volatility Lookback",
    constraints={min: 5, max: 100, step: 1},
    group="Thresholds"
)
var volMultiplier = input(
    name="volMultiplier",
    type="number",
    defaultValue=1.0,
    label="Volatility Multiplier",
    constraints={min: 0.5, max: 3.0, step: 0.1},
    group="Thresholds"
)

// --- Volume Confirmation ---
var useVolConfirm = input(
    name="useVolConfirm",
    type="boolean",
    defaultValue=true,
    label="Use Volume Confirmation",
    group="Volume"
)
var volLen = input(
    name="volLen",
    type="number",
    defaultValue=20,
    label="Volume Average Length",
    constraints={min: 5, max: 100, step: 1},
    group="Volume"
)

// --- Display ---
var showRaw = input(
    name="showRaw",
    type="boolean",
    defaultValue=false,
    label="Show Raw Z-Score Lines",
    group="Display"
)
var showComposite = input(
    name="showComposite",
    type="boolean",
    defaultValue=true,
    label="Show Composite Line",
    group="Display"
)
var showHistogram = input(
    name="showHistogram",
    type="boolean",
    defaultValue=true,
    label="Show Z-Score 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 bidColor = input(
    name="bidColor",
    type="color",
    defaultValue="#26a69a",
    label="Bid-Dominant (Bull) Color",
    group="Colors"
)
var askColor = input(
    name="askColor",
    type="color",
    defaultValue="#ef5350",
    label="Ask-Dominant (Bear) Color",
    group="Colors"
)
var neutralColor = input(
    name="neutralColor",
    type="color",
    defaultValue="#9e9e9e",
    label="Neutral Color",
    group="Colors"
)
var extremeBidColor = input(
    name="extremeBidColor",
    type="color",
    defaultValue="#00e676",
    label="Extreme Bid Color",
    group="Colors"
)
var extremeAskColor = input(
    name="extremeAskColor",
    type="color",
    defaultValue="#ff1744",
    label="Extreme Ask Color",
    group="Colors"
)

// ----------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// ----------------------------------------------------------------------------
timeseries priceBars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries px = priceBars.close

if (isnan(px[0])) {
    return
}

// ----------------------------------------------------------------------------
// 3. SYNTHETIC ORDERBOOK IMBALANCE (SOBI)
// ----------------------------------------------------------------------------
// SOBI = (Close − Mid) / Spread where Mid = (High + Low) / 2
// This measures the intrabar directional pressure from price positioning.
// Per Cont et al. (2014), price changes are driven by order flow imbalance.
// We approximate this from OHLC since true LOB data may not be available.

timeseries mid = (priceBars.high + priceBars.low) / 2.0
timeseries spread = priceBars.high - priceBars.low
spread = spread <= 0 ? 0.0001 : spread

timeseries sobi = (px - mid) / spread

// ----------------------------------------------------------------------------
// 4. Z-SCORE COMPUTATION (Zhao & Palomar 2018)
// ----------------------------------------------------------------------------
// Z = (SOBI − μ) / σ over rolling lookback windows.
// Multi-depth composite using decaying weights per Xu et al. (2019).

timeseries sobiMean1 = sma(source=sobi, period=lookback1)
timeseries sobiStd1 = stddev(source=sobi, period=lookback1)
timeseries sobiZ1 = sobiStd1 > 0 ? (sobi - sobiMean1) / sobiStd1 : 0.0

timeseries sobiMean2 = sma(source=sobi, period=lookback2)
timeseries sobiStd2 = stddev(source=sobi, period=lookback2)
timeseries sobiZ2 = sobiStd2 > 0 ? (sobi - sobiMean2) / sobiStd2 : 0.0

timeseries sobiMean3 = sma(source=sobi, period=lookback3)
timeseries sobiStd3 = stddev(source=sobi, period=lookback3)
timeseries sobiZ3 = sobiStd3 > 0 ? (sobi - sobiMean3) / sobiStd3 : 0.0

// ----------------------------------------------------------------------------
// 5. MULTI-DEPTH COMPOSITE Z-SCORE (Xu, Gould & Howison 2019)
// ----------------------------------------------------------------------------
// Depth-weighted composite with geometric decay: w_i = decay^(i−1).
// Composite = Σ w_i × Z_i / Σ w_i.

var w1 = 1.0
var w2 = useMultiDepth ? weightDecay : 0.0
var w3 = useMultiDepth ? weightDecay * weightDecay : 0.0

var wSum = w1 + w2 + w3
var compositeZ = wSum > 0 ? (w1 * sobiZ1 + w2 * sobiZ2 + w3 * sobiZ3) / wSum : sobiZ1

// Smooth the composite
timeseries smoothedZ = smoothComposite ? ema(source=compositeZ, period=smoothLen) : compositeZ

// Raw individual z-scores (smoothed for display)
timeseries smoothedZ1 = ema(source=sobiZ1, period=smoothLen)
timeseries smoothedZ2 = ema(source=sobiZ2, period=smoothLen)
timeseries smoothedZ3 = ema(source=sobiZ3, period=smoothLen)

// ----------------------------------------------------------------------------
// 6. VOLUME CONFIRMATION (Lee & Ready 1991; Easley et al. 2012)
// ----------------------------------------------------------------------------
timeseries volAvg = sma(source=priceBars.volume, period=volLen)
timeseries volRatio = volAvg > 0 ? priceBars.volume[0] / volAvg[0] : 1.0
timeseries volConfirm = (volRatio - 1.0) * 50.0  // scale to roughly ±50

// Adjust z-score by volume confirmation when enabled
timeseries adjustedZ = useVolConfirm ? smoothedZ + (volConfirm * 0.02) : smoothedZ

// ----------------------------------------------------------------------------
// 7. DYNAMIC THRESHOLDS (Poterba & Summers 1988)
// ----------------------------------------------------------------------------
// Volatility-adjusted bands using rolling stddev of the adjusted z-score.
timeseries zVol = stddev(source=adjustedZ, period=volLookback)

var dynInner = useDynamic ? innerGuide * (1.0 + zVol * volMultiplier) : innerGuide
var dynOuter = useDynamic ? outerGuide * (1.0 + zVol * volMultiplier) : outerGuide

// Guard: ensure inner < outer and cap extremes
if (dynInner >= dynOuter) {
    dynInner = innerGuide
    dynOuter = outerGuide
}
if (dynOuter > 5.0) {
    dynOuter = 5.0
}
if (dynInner < 0.3) {
    dynInner = 0.3
}

// ----------------------------------------------------------------------------
// 8. REGIME DETECTION (Cartea et al. 2018 five-segment model)
// ----------------------------------------------------------------------------
// Five regimes:
//   Extreme Buy:  Z ≥ dynOuter
//   Buy:          dynInner ≤ Z < dynOuter
//   Neutral:      −dynInner < Z < dynInner
//   Sell:         −dynOuter < Z ≤ −dynInner
//   Extreme Sell: Z ≤ −dynOuter

var regime = 0      // 0 = neutral, 1 = buy, 2 = extreme buy, -1 = sell, -2 = extreme sell

if (adjustedZ >= dynOuter) {
    regime = 2
} else if (adjustedZ >= dynInner) {
    regime = 1
} else if (adjustedZ <= -dynOuter) {
    regime = -2
} else if (adjustedZ <= -dynInner) {
    regime = -1
}

var regimeColor = (regime == 2) ? extremeBidColor : (regime == 1 ? bidColor : (regime == -1 ? askColor : (regime == -2 ? extremeAskColor : neutralColor)))

// ----------------------------------------------------------------------------
// 9. STATIC STATE TRACKING (Session-level persistence)
// ----------------------------------------------------------------------------
static lastRegime = 0
static regimeChangeCount = 0
static sessionHighZ = -999999.0
static sessionLowZ = 999999.0
static extremeBidCount = 0
static extremeAskCount = 0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

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

    if (adjustedZ > sessionHighZ) {
        sessionHighZ = adjustedZ
    }
    if (adjustedZ < sessionLowZ) {
        sessionLowZ = adjustedZ
    }

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

    if (regime == 2) {
        extremeBidCount = extremeBidCount + 1
    } else if (regime == -2) {
        extremeAskCount = extremeAskCount + 1
    }
}

// ----------------------------------------------------------------------------
// 10. ALERT CONDITIONS
// ----------------------------------------------------------------------------
var crossUpInner = adjustedZ >= dynInner && !isnan(adjustedZ[1]) && adjustedZ[1] < dynInner
var crossDnInner = adjustedZ <= -dynInner && !isnan(adjustedZ[1]) && adjustedZ[1] > -dynInner
var crossUpOuter = adjustedZ >= dynOuter && !isnan(adjustedZ[1]) && adjustedZ[1] < dynOuter
var crossDnOuter = adjustedZ <= -dynOuter && !isnan(adjustedZ[1]) && adjustedZ[1] > -dynOuter

var zeroCrossUp = adjustedZ >= 0 && !isnan(adjustedZ[1]) && adjustedZ[1] < 0
var zeroCrossDn = adjustedZ < 0 && !isnan(adjustedZ[1]) && adjustedZ[1] >= 0

// ----------------------------------------------------------------------------
// 11. PLOTTING
// ----------------------------------------------------------------------------

// Horizontal guide lines
hline(value=0, color="#ffffff30", width=1)

if (showGuides) {
    hline(value=dynInner, color=transparency(bidColor, 50), width=1)
    hline(value=-dynInner, color=transparency(askColor, 50), width=1)
    hline(value=dynOuter, color=transparency(extremeBidColor, 40), width=1)
    hline(value=-dynOuter, color=transparency(extremeAskColor, 40), width=1)
}

// Raw individual z-score lines (optional, for granular analysis)
if (showRaw) {
    plotLine(
        value=smoothedZ1,
        width=1,
        colors=[transparency(bidColor, 50)],
        label=["Z 1"],
        desc=["Z-score at " + lookback1 + " lookback (shallow, fastest)"]
    )
    plotLine(
        value=smoothedZ2,
        width=1,
        colors=[transparency(bidColor, 40)],
        label=["Z 2"],
        desc=["Z-score at " + lookback2 + " lookback (medium, smoothing)"]
    )
    plotLine(
        value=smoothedZ3,
        width=1,
        colors=[transparency(askColor, 40)],
        label=["Z 3"],
        desc=["Z-score at " + lookback3 + " lookback (deep, structural)"]
    )
}

// Composite z-score histogram with regime coloring
if (showHistogram) {
    plotBar(
        value=adjustedZ,
        colors=[extremeBidColor, bidColor, neutralColor, askColor, extremeAskColor],
        colorIndex=regime == 2 ? 0 : (regime == 1 ? 1 : (regime == -1 ? 3 : (regime == -2 ? 4 : 2))),
        width=1,
        label=["Z-Score Hist"],
        desc=["Composite Z-score histogram with five-regime color coding"]
    )
}

// Smoothed composite line with regime-coded fill area
if (showComposite) {
    plotLine(
        value=adjustedZ,
        width=2,
        colors=[regimeColor],
        label=["Composite Z"],
        desc=["Depth-weighted composite Z-score (EMA-smoothed). Regime: five-segment."]
    )

    // Fill between composite Z and zero line
    plotLine(
        value=[adjustedZ, 0],
        width=1,
        colors=[transparency(bidColor, 15), transparency(askColor, 15)],
        colorIndex=adjustedZ > 0 ? 0 : 1,
        fill=true,
        label=["Composite Z", "Zero"],
        desc=["Fill between composite Z-score and zero line"]
    )
}

// Regime transition shapes (Cartea et al. 2018 signal extraction)
if (showShapes) {
    if (crossUpOuter) {
        plotShape(
            value=adjustedZ,
            shape="triangleup",
            color=extremeBidColor,
            width=3,
            label=["Extreme Buy"],
            desc=["Composite Z crossed into extreme buy regime (Z > +" + dynOuter + "σ)"]
        )
    }
    if (crossDnOuter) {
        plotShape(
            value=adjustedZ,
            shape="triangledown",
            color=extremeAskColor,
            width=3,
            label=["Extreme Sell"],
            desc=["Composite Z crossed into extreme sell regime (Z < −" + dynOuter + "σ)"]
        )
    }
    if (crossUpInner) {
        plotShape(
            value=adjustedZ,
            shape="arrowup",
            color=bidColor,
            width=2,
            label=["Buy Zone"],
            desc=["Composite Z crossed into buy regime (Z > +" + dynInner + "σ)"]
        )
    }
    if (crossDnInner) {
        plotShape(
            value=adjustedZ,
            shape="arrowdown",
            color=askColor,
            width=2,
            label=["Sell Zone"],
            desc=["Composite Z crossed into sell regime (Z < −" + dynInner + "σ)"]
        )
    }
    if (zeroCrossUp) {
        plotShape(
            value=0,
            shape="circle",
            color=bidColor,
            width=2,
            label=["Zero Cross Up"],
            desc=["Composite Z crossed above zero — bullish pressure shift"]
        )
    }
    if (zeroCrossDn) {
        plotShape(
            value=0,
            shape="circle",
            color=askColor,
            width=2,
            label=["Zero Cross Down"],
            desc=["Composite Z crossed below zero — bearish pressure shift"]
        )
    }
}

// ----------------------------------------------------------------------------
// 12. REGIME TABLE (last bar only)
// ----------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = (regime == 2) ? "EXTREME BUY" : (regime == 1 ? "BUY" : (regime == -1 ? "SELL" : (regime == -2 ? "EXTREME SELL" : "NEUTRAL")))
    var regimeTextColor = (regime == 2) ? extremeBidColor : (regime == 1 ? bidColor : (regime == -1 ? askColor : (regime == -2 ? extremeAskColor : neutralColor)))
    var innerText = useDynamic ? "Dyn Inner: " + dynInner : "Static Inner: " + innerGuide
    var outerText = useDynamic ? "Dyn Outer: " + dynOuter : "Static Outer: " + outerGuide

    plotTable(
        data=[
            ["SOBI Z-Score Pro", regimeText],
            ["Composite Z", adjustedZ[0]],
            ["Z 1 (" + lookback1 + ")", sobiZ1[0]],
            ["Z 2 (" + lookback2 + ")", sobiZ2[0]],
            ["Z 3 (" + lookback3 + ")", sobiZ3[0]],
            ["Vol Confirm", volConfirm[0]],
            [innerText, outerText],
            ["Regime Changes", regimeChangeCount],
            ["Extreme Buy Bars", extremeBidCount],
            ["Extreme Sell Bars", extremeAskCount],
            ["Session Z High", sessionHighZ],
            ["Session Z Low", sessionLowZ]
        ],
        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
    )
}