MM Flow
FlowScripts

Perfected FlowScript

Delta/OB signals

Delta/OB Signals — Perfected Edition is indexed as 251_delta_ob_signals.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

24.0 KB

Lines

602

Native Signal Candidates

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

8/8 guarded

Bull Regime

line 482:9

Trigger

(showShapes) && (crossUp)

Value

composite

Deps

crossUp:var, showShapes:input

Bear Regime

line 492:9

Trigger

(showShapes) && (crossDn)

Value

composite

Deps

crossDn:var, showShapes:input

Zero Cross Up

line 502:9

Trigger

(showShapes) && (zeroUp)

Value

composite

Deps

showShapes:input, zeroUp:var

Zero Cross Down

line 512:9

Trigger

(showShapes) && (zeroDn)

Value

composite

Deps

showShapes:input, zeroDn:var

Extreme Bid

line 522:9

Trigger

(showShapes) && (extremeUp)

Value

composite

Deps

extremeUp:var, showShapes:input

Extreme Ask

line 532:9

Trigger

(showShapes) && (extremeDn)

Value

composite

Deps

extremeDn:var, showShapes:input

Bull Div

line 546:9

Trigger

(showShapes && enableDiv) && (bullDiv)

Value

composite

Deps

bullDiv:var, enableDiv:input, showShapes:input

Bear Div

line 556:9

Trigger

(showShapes && enableDiv) && (bearDiv)

Value

composite

Deps

bearDiv:var, enableDiv:input, showShapes:input

251_delta_ob_signals.flowscript

source path: kscripts/perfected/251_delta_ob_signals.flowscript · sha256:18963f4567d50edfe57bbb9c34015f8fe8d1ba75f128c4c6075a951ccb398b21

hash verified
//@version=2
// ============================================================================
// Delta/OB Signals — Perfected Edition
// Author: I (@Iopl147u)  |  Perfected by: kScript Perfection Engineer
// Tags: FLOW, #delta, #orderbook, #composite, #microstructure, #imbalance
//
// Production-quality combined volume-delta and orderbook-imbalance indicator.
// Integrates multi-depth OBI with buy/sell volume delta into a weighted
// composite signal, with regime detection, divergence alerts, color-coded
// histogram, fill visualization, and comprehensive shape-marker events.
//
// FORMULA FOUNDATION:
// 1. Volume Delta: ΔV = BuyVol − SellVol, normalized by total volume.
//    Per Lee & Ready (1991), quote-midpoint classification for trade direction.
// 2. Multi-Depth OBI: OBI_i = (Bid_i − Ask_i) / (Bid_i + Ask_i) at depth i.
//    Per Xu, Gould & Howison (2019), deeper levels improve prediction.
// 3. Depth-Weighted Composite OBI: Σ w_i × OBI_i / Σ w_i
//    Per Cont, Kukanov & Stoikov (2014), slope ∝ 1/depth.
// 4. Composite Signal: α × DeltaNorm + (1−α) × OBI_Composite
//    Weighted fusion of aggressive flow (delta) and resting liquidity (OBI).
// 5. Regime Detection: Bull (composite > bullThresh), Bear (composite < bearThresh),
//    Neutral (between). Per Cartea et al. (2018) three-segment model.
// 6. Divergence Detection: price makes higher high while composite makes lower high
//    (bearish divergence), or vice versa. Per Murphy (1999).
//
// RESEARCH BASIS:
//  • Lee & Ready (1991), "Inferring Trade Direction from Intraday Data",
//    J. Finance 46(2), 733–746. Quote-midpoint algorithm for buy/sell
//    classification; ~85–93% accuracy. Foundation for all volume delta.
//  • Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events",
//    J. Financial Econometrics 12(1), 47–88. OFI linear price-impact model;
//    multi-level imbalance improves prediction vs. top-of-book alone.
//  • Xu, Gould & Howison (2019), "Multi-Level Order-Flow Imbalance in a Limit
//    Order Book", arXiv:1907.06230. Deeper book levels carry significant
//    predictive power; geometrically decaying weights optimize out-of-sample.
//  • Cartea, Donnelly & Jaimungal (2018), "Enhancing Trading Strategies with
//    Order Book Signals", Appl. Math. Finance 25(1), 1–35. Three-regime
//    segmentation: Sell-heavy, Neutral, Buy-heavy.
//  • Murphy (1999), "Technical Analysis of the Financial Markets". Divergence
//    as a leading reversal signal — price/indicator disagreement at extremes
//    precedes regime shifts.
//  • 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="Delta/OB Signals — Perfected Edition",
    position="offchart",
    axis=true
)

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

// --- Volume Delta ---
var smoothLen = input(name="smoothLen", type="number", defaultValue=14, label="Smoothing Length", constraints={min: 1, max: 50, step: 1}, group="Delta")
var deltaWeight = input(name="deltaWeight", type="number", defaultValue=0.5, label="Delta Weight (0=OBI only, 1=Delta only)", constraints={min: 0.0, max: 1.0, step: 0.05}, group="Delta")
var showDelta = input(name="showDelta", type="boolean", defaultValue=true, label="Show Smoothed Delta", group="Delta")
var showDeltaRaw = input(name="showDeltaRaw", type="boolean", defaultValue=false, label="Show Raw Delta Histogram", group="Delta")

// --- Orderbook ---
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 depth4 = input(name="depth4", type="number", defaultValue=10.0, label="Depth Band 4 (%)", 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")
var showOB = input(name="showOB", type="boolean", defaultValue=true, label="Show OB Imbalance", group="Orderbook")
var showIndividual = input(name="showIndividual", type="boolean", defaultValue=false, label="Show Individual Depth Lines", group="Orderbook")

// --- Thresholds & Regime ---
var bullThresh = input(name="bullThresh", type="number", defaultValue=0.15, label="Bullish Threshold", constraints={min: 0.01, max: 1.0, step: 0.01}, group="Thresholds")
var bearThresh = input(name="bearThresh", type="number", defaultValue=-0.15, label="Bearish Threshold", constraints={min: -1.0, max: -0.01, step: 0.01}, group="Thresholds")
var extremeThresh = input(name="extremeThresh", type="number", defaultValue=0.5, label="Extreme Threshold", constraints={min: 0.1, max: 1.0, step: 0.05}, group="Thresholds")

// --- Divergence ---
var enableDiv = input(name="enableDiv", type="boolean", defaultValue=true, label="Enable Divergence Detection", group="Divergence")
var divLookback = input(name="divLookback", type="number", defaultValue=10, label="Divergence Lookback", constraints={min: 5, max: 50, step: 1}, group="Divergence")

// --- Display ---
var showComposite = input(name="showComposite", type="boolean", defaultValue=true, label="Show Composite Signal", group="Display")
var showHistogram = input(name="showHistogram", type="boolean", defaultValue=true, label="Show Composite Histogram", group="Display")
var showFill = input(name="showFill", type="boolean", defaultValue=true, label="Show Fill Area", group="Display")
var showGuides = input(name="showGuides", type="boolean", defaultValue=true, label="Show Guide Lines", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Alert Shapes", group="Display")

// --- Colors ---
var bidColor = input(name="bidColor", type="color", defaultValue="#26a69a", label="Bid-Dominant / Bullish", group="Colors")
var askColor = input(name="askColor", type="color", defaultValue="#ef5350", label="Ask-Dominant / Bearish", 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")
var divBullColor = input(name="divBullColor", type="color", defaultValue="#00e676", label="Bullish Divergence", group="Colors")
var divBearColor = input(name="divBearColor", type="color", defaultValue="#ff5252", label="Bearish Divergence", group="Colors")

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

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

// ------------------------------------------------------------------------------
// Volume Delta Computation (Lee & Ready 1991)
// ------------------------------------------------------------------------------
// Buy/sell volume classification into normalized delta per bar.

timeseries buyV = buySell.buy_volume
timeseries sellV = buySell.sell_volume
timeseries delta = buyV - sellV
timeseries totalVol = buyV + sellV
timeseries deltaNorm = totalVol > 0 ? delta / totalVol : 0.0
timeseries deltaSmooth = ema(source=deltaNorm, period=smoothLen)

// ------------------------------------------------------------------------------
// Order Book Aggregation (Cont et al. 2014)
// ------------------------------------------------------------------------------
// Multi-depth bands (1%, 2.5%, 5%, 10%) operationalize the inverse
// proportionality between price impact slope and depth.

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

// ------------------------------------------------------------------------------
// OBI Computation with Zero-Division Guards
// ------------------------------------------------------------------------------
// OBI = (Bid − Ask) / (Bid + Ask)  ∈ [−1, +1]

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 OBI (Xu, Gould & Howison 2019)
// ------------------------------------------------------------------------------
// Multi-level OFI with geometrically decaying weights.

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
timeseries obiSmooth = ema(source=compositeOBI, period=smoothLen)

// ------------------------------------------------------------------------------
// Composite Signal: Delta + OB Fusion
// ------------------------------------------------------------------------------
// Weighted combination of aggressive flow (delta) and resting liquidity (OBI).
// α = deltaWeight, (1−α) = OBI weight.

timeseries composite = deltaWeight * deltaSmooth + (1.0 - deltaWeight) * obiSmooth

// ------------------------------------------------------------------------------
// Regime Detection (Cartea et al. 2018 extended)
// ------------------------------------------------------------------------------
// Regime classification:
//   Bullish: composite ≥ bullThresh
//   Bearish: composite ≤ bearThresh
//   Neutral: bearThresh < composite < bullThresh
//   Extreme: |composite| ≥ extremeThresh

var regime = 0       // 0 = neutral, 1 = bull, -1 = bear
var extremeRegime = 0   // 0 = normal, 1 = extreme bull, -1 = extreme bear

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

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

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

// ------------------------------------------------------------------------------
// Divergence Detection (Murphy 1999)
// ------------------------------------------------------------------------------
// Regular divergence: price makes higher high / lower low, composite disagrees.
// Stateful tracking via static variables.

static prevPxHigh = -1.0
static prevCompHigh = -1.0
static prevPxLow = -1.0
static prevCompLow = -1.0

var bearDiv = false
var bullDiv = false

// Initialize on first real bar after NaN guard
if (prevPxHigh < 0) {
    prevPxHigh = priceBars.high[0]
    prevCompHigh = composite[0]
    prevPxLow = priceBars.low[0]
    prevCompLow = composite[0]
}

if (!isLiveUpdate && enableDiv) {
    // Regular Bearish Divergence: price higher high, composite lower high
    var pxHigh = highest(source=priceBars.high, period=divLookback)
    var compHigh = highest(source=composite, period=divLookback)
    if (priceBars.high[0] > prevPxHigh) {
        if (composite[0] < prevCompHigh) {
            bearDiv = true
        }
        prevPxHigh = priceBars.high[0]
        prevCompHigh = composite[0]
    }

    // Regular Bullish Divergence: price lower low, composite higher low
    var pxLow = lowest(source=priceBars.low, period=divLookback)
    var compLow = lowest(source=composite, period=divLookback)
    if (priceBars.low[0] < prevPxLow) {
        if (composite[0] > prevCompLow) {
            bullDiv = true
        }
        prevPxLow = priceBars.low[0]
        prevCompLow = composite[0]
    }
}

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

static lastRegime = 0
static regimeChangeCount = 0
static sessionHighComp = -999999.0
static sessionLowComp = 999999.0
static extremeBidCount = 0
static extremeAskCount = 0
static bullDivCount = 0
static bearDivCount = 0
static zeroCrossCount = 0
static lastBarIndex = 0
static lastComposite = 0.0

var currentBarIndex = bar_index[0]

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

    if (composite > sessionHighComp) {
        sessionHighComp = composite
    }
    if (composite < sessionLowComp) {
        sessionLowComp = composite
    }

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

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

    if (bullDiv) {
        bullDivCount = bullDivCount + 1
    }
    if (bearDiv) {
        bearDivCount = bearDivCount + 1
    }

    // Zero-cross detection
    if ((lastComposite > 0 && composite <= 0) || (lastComposite < 0 && composite >= 0)) {
        zeroCrossCount = zeroCrossCount + 1
    }
    lastComposite = composite
}

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

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

if (showGuides) {
    hline(value=bullThresh, color=opacity(bidColor, 30), width=1)
    hline(value=bearThresh, color=opacity(askColor, 30), width=1)
    hline(value=extremeThresh, color=opacity(extremeBidColor, 20), width=1)
    hline(value=-extremeThresh, color=opacity(extremeAskColor, 20), width=1)
}

// Raw delta histogram (optional)
if (showDeltaRaw) {
    plotBar(
        value=deltaNorm,
        colors=[bidColor, askColor],
        colorIndex=deltaNorm >= 0 ? 0 : 1,
        width=1,
        label=["Raw Delta"],
        desc=["Per-bar normalized buy-sell volume delta (Lee & Ready 1991)"]
    )
}

// Smoothed delta line
if (showDelta) {
    plotLine(
        value=deltaSmooth,
        width=2,
        colors=[bidColor, askColor, neutralColor],
        colorIndex=deltaSmooth >= 0 ? 0 : (deltaSmooth < 0 ? 1 : 2),
        label=["Smoothed Delta"],
        desc=["EMA-smoothed normalized volume delta (weight: " + deltaWeight + ")"]
    )
}

// OB Imbalance line
if (showOB) {
    plotLine(
        value=obiSmooth,
        width=2,
        colors=[opacity(bidColor, 60), opacity(askColor, 60), neutralColor],
        colorIndex=obiSmooth >= 0 ? 0 : (obiSmooth < 0 ? 1 : 2),
        label=["OB Imbalance"],
        desc=["EMA-smoothed depth-weighted composite OBI (weight: " + (1.0 - deltaWeight) + ")"]
    )
}

// Individual depth lines (optional)
if (showIndividual) {
    plotLine(
        value=obi1,
        width=1,
        colors=[opacity(bidColor, 50)],
        label=["OBI 1%"],
        desc=["Order Book Imbalance at 1% depth"]
    )
    plotLine(
        value=obi2,
        width=1,
        colors=[opacity(bidColor, 40)],
        label=["OBI 2.5%"],
        desc=["Order Book Imbalance at 2.5% depth"]
    )
    plotLine(
        value=obi3,
        width=1,
        colors=[opacity(askColor, 40)],
        label=["OBI 5%"],
        desc=["Order Book Imbalance at 5% depth"]
    )
    plotLine(
        value=obi4,
        width=1,
        colors=[opacity(askColor, 50)],
        label=["OBI 10%"],
        desc=["Order Book Imbalance at 10% depth"]
    )
}

// Composite signal histogram (color-coded by regime)
if (showHistogram) {
    var histColorIdx = 0
    if (extremeRegime == 1) {
        histColorIdx = 3
    } else if (extremeRegime == -1) {
        histColorIdx = 4
    } else if (regime == 1) {
        histColorIdx = 0
    } else if (regime == -1) {
        histColorIdx = 1
    } else {
        histColorIdx = 2
    }

    plotBar(
        value=composite,
        colors=[bidColor, askColor, neutralColor, extremeBidColor, extremeAskColor],
        colorIndex=histColorIdx,
        width=1,
        label=["Composite Signal"],
        desc=["Weighted delta + OBI composite histogram (green=bull, red=bear, grey=neutral)"]
    )
}

// Composite signal line with regime-coded fill
if (showComposite) {
    var compLineColorIdx = 0
    if (extremeRegime == 1) {
        compLineColorIdx = 3
    } else if (extremeRegime == -1) {
        compLineColorIdx = 4
    } else if (regime == 1) {
        compLineColorIdx = 0
    } else if (regime == -1) {
        compLineColorIdx = 1
    } else {
        compLineColorIdx = 2
    }

    plotLine(
        value=composite,
        width=2,
        colors=[bidColor, askColor, neutralColor, extremeBidColor, extremeAskColor],
        colorIndex=compLineColorIdx,
        label=["Composite Signal"],
        desc=["Combined delta + OB imbalance signal (" + (deltaWeight * 100) + "% delta / " + ((1.0 - deltaWeight) * 100) + "% OBI)"],
        fill=showFill
    )
}

// Fill area between composite and zero line
if (showFill) {
    var fillColorIdx = composite >= 0 ? 0 : 1
    plotLine(
        value=[composite, 0],
        width=1,
        colors=[opacity(bidColor, 20), opacity(askColor, 20)],
        colorIndex=fillColorIdx,
        fill=true,
        label=["Composite", "Zero"],
        desc=["Fill between composite signal and zero line"]
    )
}

// Delta vs OBI fill (shows agreement/disagreement)
if (showFill && showDelta && showOB) {
    var agreeBull = deltaSmooth > 0 && obiSmooth > 0
    var agreeBear = deltaSmooth < 0 && obiSmooth < 0
    var agreeColor = agreeBull ? opacity(extremeBidColor, 15) : (agreeBear ? opacity(extremeAskColor, 15) : opacity(neutralColor, 10))
    plotLine(
        value=[deltaSmooth, obiSmooth],
        width=1,
        colors=[agreeColor, agreeColor],
        colorIndex=0,
        fill=true,
        label=["Delta", "OBI"],
        desc=["Fill between delta and OBI — bright when both agree"]
    )
}

// Regime transition shapes
if (showShapes) {
    // Cross into bullish regime
    var crossUp = composite >= bullThresh && !isnan(composite[1]) && composite[1] < bullThresh
    // Cross into bearish regime
    var crossDn = composite <= bearThresh && !isnan(composite[1]) && composite[1] > bearThresh
    // Zero cross up
    var zeroUp = composite >= 0 && !isnan(composite[1]) && composite[1] < 0
    // Zero cross down
    var zeroDn = composite <= 0 && !isnan(composite[1]) && composite[1] > 0
    // Extreme bid
    var extremeUp = composite >= extremeThresh && !isnan(composite[1]) && composite[1] < extremeThresh
    // Extreme ask
    var extremeDn = composite <= -extremeThresh && !isnan(composite[1]) && composite[1] > -extremeThresh

    if (crossUp) {
        plotShape(
            value=composite,
            shape="triangleup",
            color=extremeBidColor,
            width=3,
            label=["Bull Regime"],
            desc=["Composite signal crossed into bullish regime — buy pressure dominant"]
        )
    }
    if (crossDn) {
        plotShape(
            value=composite,
            shape="triangledown",
            color=extremeAskColor,
            width=3,
            label=["Bear Regime"],
            desc=["Composite signal crossed into bearish regime — sell pressure dominant"]
        )
    }
    if (zeroUp) {
        plotShape(
            value=composite,
            shape="circle",
            color=bidColor,
            width=2,
            label=["Zero Cross Up"],
            desc=["Composite signal crossed above zero — net pressure flipped bullish"]
        )
    }
    if (zeroDn) {
        plotShape(
            value=composite,
            shape="circle",
            color=askColor,
            width=2,
            label=["Zero Cross Down"],
            desc=["Composite signal crossed below zero — net pressure flipped bearish"]
        )
    }
    if (extremeUp) {
        plotShape(
            value=composite,
            shape="diamond",
            color=extremeBidColor,
            width=4,
            label=["Extreme Bid"],
            desc=["Extreme bid pressure detected — both delta and OBI aligned bullish"]
        )
    }
    if (extremeDn) {
        plotShape(
            value=composite,
            shape="diamond",
            color=extremeAskColor,
            width=4,
            label=["Extreme Ask"],
            desc=["Extreme ask pressure detected — both delta and OBI aligned bearish"]
        )
    }
}

// Divergence shapes
if (showShapes && enableDiv) {
    if (bullDiv) {
        plotShape(
            value=composite,
            shape="arrowup",
            color=divBullColor,
            width=2,
            label=["Bull Div"],
            desc=["Bullish divergence: price lower low, composite higher low (Murphy 1999)"]
        )
    }
    if (bearDiv) {
        plotShape(
            value=composite,
            shape="arrowdown",
            color=divBearColor,
            width=2,
            label=["Bear Div"],
            desc=["Bearish divergence: price higher high, composite lower high (Murphy 1999)"]
        )
    }
}

// ------------------------------------------------------------------------------
// Regime Table (last bar only)
// ------------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = extremeRegime == 1 ? "EXTREME BULL" : (extremeRegime == -1 ? "EXTREME BEAR" : (regime == 1 ? "BULLISH" : (regime == -1 ? "BEARISH" : "NEUTRAL")))
    var regimeTextColor = extremeRegime == 1 ? extremeBidColor : (extremeRegime == -1 ? extremeAskColor : (regime == 1 ? bidColor : (regime == -1 ? askColor : neutralColor)))
    var agreeText = (deltaSmooth >= 0 && obiSmooth >= 0) ? "AGREE BULL" : ((deltaSmooth <= 0 && obiSmooth <= 0) ? "AGREE BEAR" : "DISAGREE")

    plotTable(
        data=[
            ["Delta/OB — Perfected", regimeText],
            ["Composite", composite[0]],
            ["Delta", deltaSmooth[0]],
            ["OBI", obiSmooth[0]],
            ["Agreement", agreeText],
            ["Session High", sessionHighComp],
            ["Session Low", sessionLowComp],
            ["Regime Changes", regimeChangeCount],
            ["Zero Crosses", zeroCrossCount],
            ["Bull Divs", bullDivCount],
            ["Bear Divs", bearDivCount]
        ],
        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
    )
}