MM Flow
FlowScripts

Perfected FlowScript

OB publicc

OB Publicc V2 is indexed as 309_ob_publicc.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

onchart

Axis

false

Size

17.8 KB

Lines

574

Native Signal Candidates

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

4/4 guarded

Bull OB

line 495:9

Trigger

(showShapes) && (bullObNew)

Value

bullObLo

Deps

bullObNew:var, showShapes:input

Bear OB

line 505:9

Trigger

(showShapes) && (bearObNew)

Value

bearObHi

Deps

bearObNew:var, showShapes:input

Extreme Bid

line 520:9

Trigger

(showShapes) && (extremeUp)

Value

compositeOBI

Deps

extremeUp:var, showShapes:input

Extreme Ask

line 530:9

Trigger

(showShapes) && (extremeDn)

Value

compositeOBI

Deps

extremeDn:var, showShapes:input

309_ob_publicc.flowscript

source path: kscripts/perfected/309_ob_publicc.flowscript · sha256:f24c403ccdd1f0576c6139ad0386b323820181aacf4760d26fd2fee0174e408e

hash verified
//@version=2
// ============================================================================
// OB Publicc V2 — Production-Quality Order Block + Public Orderbook Fusion
// Author: I (@Iopl147u)  |  Perfected by: kScript Perfection Engineer
// Tags: FLOW, #orderblock, #orderbook, #microstructure, #OBI, #liquidity
//
// Order Block identification fused with public orderbook depth analysis,
// z-score normalization, and regime-aware visualization. Identifies
// institutional accumulation zones while validating them against live
// orderbook imbalance to filter weak vs. high-conviction OB zones.
//
// FORMULA FOUNDATION:
// 1. Order Block (OB) Detection: Bullish OB = last bearish candle before
//    displacement ≥ minMove × ATR; Bearish OB = last bullish candle before
//    displacement ≥ minMove × ATR.
// 2. Order Book Imbalance (OBI): OBI = (BidVol − AskVol) / (BidVol + AskVol)
//    per Cont, Kukanov & Stoikov (2014). Validates OB quality via live book.
// 3. Depth-Weighted Composite OBI: Σ w_i × OBI_i / Σ w_i per Xu, Gould &
//    Howison (2019). Multi-level depth bands with decaying weights.
// 4. Z-Score Normalization: z = (x − μ) / σ over rolling window, standardizing
//    OB displacement and OBI for cross-asset comparison.
// 5. Regime Segmentation: Buy-heavy (+1/3, +1), Neutral (−1/3, +1/3),
//    Sell-heavy (−1, −1/3) per Cartea, Donnelly & Jaimungal (2018).
//
// RESEARCH BASIS:
//  • Cont, Kukanov & Stoikov (2014), J. Financial Econometrics 12(1), 47–88.
//    OFI linearly predicts price changes; slope ∝ 1/depth.
//  • Xu, Gould & Howison (2019), arXiv:1907.06230. Multi-level OFI with
//    decaying weights significantly improves short-horizon prediction.
//  • Cartea, Donnelly & Jaimungal (2018), Appl. Math. Finance 25(1), 1–35.
//    Three-regime segmentation predicts future price direction.
//  • Gould & Bonart (2016), Market Microstructure & Liquidity 2(1), 1650006.
//    Queue imbalance as one-tick-ahead predictor.
//  • Campbell, Ramadorai & Vuolteenaho (2005), J. Financial Economics 65(1).
//    Institutional order flow and price impact.
// ============================================================================

define(
    title="OB Publicc V2",
    position="onchart",
    axis=false
)

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

// --- Order Block Detection ---
var lookback = input(
    name="lookback",
    type="number",
    defaultValue=20,
    label="OB Lookback",
    constraints={min: 5, max: 200, step: 1},
    group="Order Block"
)
var minMove = input(
    name="minMove",
    type="number",
    defaultValue=1.5,
    label="Min Displacement (ATR mult)",
    constraints={min: 0.1, max: 10.0, step: 0.1},
    group="Order Block"
)
var atrLen = input(
    name="atrLen",
    type="number",
    defaultValue=14,
    label="ATR Length",
    constraints={min: 2, max: 50, step: 1},
    group="Order Block"
)
var maxBlocks = input(
    name="maxBlocks",
    type="number",
    defaultValue=3,
    label="Max Active Blocks",
    constraints={min: 1, max: 10, step: 1},
    group="Order Block"
)

// --- Orderbook Depth ---
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="Orderbook"
)
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="Orderbook"
)
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="Orderbook"
)
var useDepthWeighting = input(
    name="useDepthWeighting",
    type="boolean",
    defaultValue=true,
    label="Use Depth-Decaying Weights",
    group="Orderbook"
)
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="Orderbook"
)

// --- Z-Score ---
var zScoreLen = input(
    name="zScoreLen",
    type="number",
    defaultValue=50,
    label="Z-Score Lookback",
    constraints={min: 10, max: 500, step: 5},
    group="Z-Score"
)
var useZScore = input(
    name="useZScore",
    type="boolean",
    defaultValue=true,
    label="Enable Z-Score Normalization",
    group="Z-Score"
)

// --- Thresholds & Regime ---
var bullThresh = input(
    name="bullThresh",
    type="number",
    defaultValue=33.0,
    label="Bullish Regime Threshold (%)",
    constraints={min: 10.0, max: 90.0, step: 1.0},
    group="Thresholds"
)
var bearThresh = input(
    name="bearThresh",
    type="number",
    defaultValue=-33.0,
    label="Bearish Regime Threshold (%)",
    constraints={min: -90.0, max: -10.0, step: 1.0},
    group="Thresholds"
)
var extremeThresh = input(
    name="extremeThresh",
    type="number",
    defaultValue=66.0,
    label="Extreme Imbalance Threshold (%)",
    constraints={min: 50.0, max: 95.0, step: 1.0},
    group="Thresholds"
)

// --- Display ---
var showZones = input(
    name="showZones",
    type="boolean",
    defaultValue=true,
    label="Show OB Zones",
    group="Display"
)
var zoneWidth = input(
    name="zoneWidth",
    type="number",
    defaultValue=1,
    label="Zone Border Width",
    constraints={min: 1, max: 5, step: 1},
    group="Display"
)
var showOBI = input(
    name="showOBI",
    type="boolean",
    defaultValue=true,
    label="Show Composite OBI Line",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show OB Activation Shapes",
    group="Display"
)
var showZScore = input(
    name="showZScore",
    type="boolean",
    defaultValue=true,
    label="Show Z-Score Line",
    group="Display"
)
var showGuides = input(
    name="showGuides",
    type="boolean",
    defaultValue=true,
    label="Show Threshold Guide Lines",
    group="Display"
)

// --- Colors ---
var bullColor = input(
    name="bullColor",
    type="color",
    defaultValue="#26a69a",
    label="Bullish OB Color",
    group="Colors"
)
var bearColor = input(
    name="bearColor",
    type="color",
    defaultValue="#ef5350",
    label="Bearish OB Color",
    group="Colors"
)
var bidColor = input(
    name="bidColor",
    type="color",
    defaultValue="#00e676",
    label="Bid-Dominant Color",
    group="Colors"
)
var askColor = input(
    name="askColor",
    type="color",
    defaultValue="#ff1744",
    label="Ask-Dominant Color",
    group="Colors"
)
var neutralColor = input(
    name="neutralColor",
    type="color",
    defaultValue="#9e9e9e",
    label="Neutral Color",
    group="Colors"
)

// ------------------------------------------------------------------------------
// Data Sources & NaN Guard
// ------------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries px = bars.close
timeseries book = source("orderbook", currentSymbol, currentExchange)

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

// ------------------------------------------------------------------------------
// Order Block Detection
// ------------------------------------------------------------------------------
timeseries rng = bars.high - bars.low
timeseries atrV = sma(rng, atrLen)

// Candle polarity: bullish (+1) or bearish (-1)
var isBull = bars.close > bars.open ? 1 : -1

// Displacement: a candle whose move exceeds minMove × ATR
timeseries move = math.abs(bars.close - bars.close[1])
var displacement = move >= atrV * minMove ? 1 : 0

// Static OB state tracking (session-level persistence)
static bullObHi = 0.0
static bullObLo = 0.0
static bearObHi = 0.0
static bearObLo = 0.0
static bullObActive = false
static bearObActive = false
static bullObAge = 0
static bearObAge = 0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
    lastBarIndex = currentBarIndex
    if (bullObActive) {
        bullObAge = bullObAge + 1
    }
    if (bearObActive) {
        bearObAge = bearObAge + 1
    }
}

// Detect new OB on displacement
timeseries obHigh = bars.high[1]
timeseries obLow = bars.low[1]

if (displacement && isBull == 1 && bars.close[1] < bars.open[1]) {
    bullObHi = bars.high[1]
    bullObLo = bars.low[1]
    bullObActive = true
    bullObAge = 0
}
if (displacement && isBull == -1 && bars.close[1] > bars.open[1]) {
    bearObHi = bars.high[1]
    bearObLo = bars.low[1]
    bearObActive = true
    bearObAge = 0
}

// Mitigate (deactivate) OB when price closes through it
if (bullObActive && px < bullObLo) {
    bullObActive = false
}
if (bearObActive && px > bearObHi) {
    bearObActive = false
}

// ------------------------------------------------------------------------------
// Order Book Depth Aggregation (Cont et al. 2014; Xu et al. 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)

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

// OBI computation with zero-division guards
var denom1 = bids1 + asks1
var denom2 = bids2 + asks2
var denom3 = bids3 + asks3

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

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

// ------------------------------------------------------------------------------
// Z-Score Normalization of Composite OBI
// ------------------------------------------------------------------------------
var obiMean = sma(source=compositeOBI, period=zScoreLen)
var obiStd = stddev(source=compositeOBI, period=zScoreLen)
var obiZ = (obiStd > 0 && useZScore) ? (compositeOBI - obiMean) / obiStd : 0.0

// Z-Score of OB displacement (standardized displacement strength)
var dispMean = sma(source=move, period=zScoreLen)
var dispStd = stddev(source=move, period=zScoreLen)
var dispZ = (dispStd > 0 && useZScore) ? (move - dispMean) / dispStd : 0.0

// ------------------------------------------------------------------------------
// Regime Detection (Cartea, Donnelly & Jaimungal 2018 three-segment model)
// ------------------------------------------------------------------------------
var regime = 0      // 0 = neutral, 1 = bull, -1 = bear
var extremeRegime = 0  // 0 = normal, 1 = extreme bull, -1 = extreme bear

if (compositeOBI >= bullThresh) {
    regime = 1
} else if (compositeOBI <= bearThresh) {
    regime = -1
}

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

// Regime color for OB zones
var obiBullColor = opacity(bullColor, 60)
var obiBearColor = opacity(bearColor, 60)

// ------------------------------------------------------------------------------
// Static State Tracking (Session-level persistence)
// ------------------------------------------------------------------------------
static sessionHighOBI = -999999.0
static sessionLowOBI = 999999.0
static extremeBidCount = 0
static extremeAskCount = 0
static totalOBCount = 0
static sessionBullCount = 0
static sessionBearCount = 0

if (!isnan(currentBarIndex) && currentBarIndex == lastBarIndex) {
    // On new bar, update session tracking
    if (compositeOBI > sessionHighOBI) {
        sessionHighOBI = compositeOBI
    }
    if (compositeOBI < sessionLowOBI) {
        sessionLowOBI = compositeOBI
    }

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

// Track OB formations (counts on activation)
if (displacement && isBull == 1 && bars.close[1] < bars.open[1] && (!bullObActive || bullObAge == 0)) {
    totalOBCount = totalOBCount + 1
    sessionBullCount = sessionBullCount + 1
}
if (displacement && isBull == -1 && bars.close[1] > bars.open[1] && (!bearObActive || bearObAge == 0)) {
    totalOBCount = totalOBCount + 1
    sessionBearCount = sessionBearCount + 1
}

// ------------------------------------------------------------------------------
// Plots — OB Zones, OBI Line, Z-Score, Shapes, Guides
// ------------------------------------------------------------------------------

// Zero line for OBI
if (showOBI) {
    hline(value=0, color="#ffffff30", width=1)
}

// Threshold guide lines
if (showGuides && showOBI) {
    hline(value=bullThresh, color=opacity(bullColor, 30), width=1)
    hline(value=bearThresh, color=opacity(bearColor, 30), width=1)
    hline(value=extremeThresh, color=opacity(bidColor, 20), width=1)
    hline(value=-extremeThresh, color=opacity(askColor, 20), width=1)
}

// --- Bullish OB Zone (regime-colored by OBI) ---
if (showZones && bullObActive) {
    var bullZoneColor = regime == 1 ? obiBullColor : (regime == -1 ? opacity(bearColor, 30) : opacity(bullColor, 40))
    plotLine(
        value=[bullObLo, bullObHi],
        colors=[bullZoneColor, bullZoneColor],
        width=zoneWidth,
        fill=true,
        label=["Bull OB Low", "Bull OB High"],
        desc=["Bullish order block support zone (regime-colored by OBI)", "Bullish order block resistance top"]
    )
}

// --- Bearish OB Zone (regime-colored by OBI) ---
if (showZones && bearObActive) {
    var bearZoneColor = regime == -1 ? obiBearColor : (regime == 1 ? opacity(bullColor, 30) : opacity(bearColor, 40))
    plotLine(
        value=[bearObLo, bearObHi],
        colors=[bearZoneColor, bearZoneColor],
        width=zoneWidth,
        fill=true,
        label=["Bear OB Low", "Bear OB High"],
        desc=["Bearish order block support floor (regime-colored by OBI)", "Bearish order block resistance zone"]
    )
}

// --- Composite OBI Line (regime-colored) ---
if (showOBI) {
    plotLine(
        value=compositeOBI,
        width=2,
        colors=[bullColor, bearColor, neutralColor],
        colorIndex=regime == 1 ? 0 : (regime == -1 ? 1 : 2),
        label=["Composite OBI"],
        desc=["Depth-weighted composite OBI. Regime: bull/bear/neutral."],
        fill=true
    )
}

// --- Z-Score Line ---
if (showZScore) {
    plotLine(
        value=obiZ,
        width=1,
        colors=[bidColor, askColor, neutralColor],
        colorIndex=obiZ > 1.0 ? 0 : (obiZ < -1.0 ? 1 : 2),
        label=["OBI Z-Score"],
        desc=["Z-score of composite OBI (±1 = 1 std dev from mean)"]
    )
}

// --- OB Activation Shapes ---
if (showShapes) {
    var bullObNew = displacement && isBull == 1 && bars.close[1] < bars.open[1]
    var bearObNew = displacement && isBull == -1 && bars.close[1] > bars.open[1]

    if (bullObNew) {
        plotShape(
            value=bullObLo,
            shape="triangleup",
            color=bullColor,
            width=3,
            label=["Bull OB"],
            desc=["Bullish Order Block formed: prior bearish candle before displacement"]
        )
    }
    if (bearObNew) {
        plotShape(
            value=bearObHi,
            shape="triangledown",
            color=bearColor,
            width=3,
            label=["Bear OB"],
            desc=["Bearish Order Block formed: prior bullish candle before displacement"]
        )
    }

    // Extreme OBI shapes
    var extremeUp = compositeOBI >= extremeThresh && !isnan(compositeOBI[1]) && compositeOBI[1] < extremeThresh
    var extremeDn = compositeOBI <= -extremeThresh && !isnan(compositeOBI[1]) && compositeOBI[1] > -extremeThresh

    if (extremeUp) {
        plotShape(
            value=compositeOBI,
            shape="diamond",
            color=bidColor,
            width=4,
            label=["Extreme Bid"],
            desc=["Extreme bid pressure detected — deep book buy-heavy imbalance"]
        )
    }
    if (extremeDn) {
        plotShape(
            value=compositeOBI,
            shape="diamond",
            color=askColor,
            width=4,
            label=["Extreme Ask"],
            desc=["Extreme ask pressure detected — deep book sell-heavy imbalance"]
        )
    }
}

// ------------------------------------------------------------------------------
// Regime Table (last bar only)
// ------------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = regime == 1 ? "BULL" : (regime == -1 ? "BEAR" : "NEUTRAL")
    var regimeTextColor = regime == 1 ? bullColor : (regime == -1 ? bearColor : neutralColor)

    plotTable(
        data=[
            ["OB Publicc V2", regimeText],
            ["Composite OBI", compositeOBI[0]],
            ["OBI Z-Score", obiZ[0]],
            ["Disp Z-Score", dispZ[0]],
            ["Bull OB Active", bullObActive ? "YES" : "NO"],
            ["Bear OB Active", bearObActive ? "YES" : "NO"],
            ["Session High OBI", sessionHighOBI],
            ["Session Low OBI", sessionLowOBI],
            ["Extreme Bid Count", extremeBidCount],
            ["Extreme Ask Count", extremeAskCount]
        ],
        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
    )
}