MM Flow
FlowScripts

Perfected FlowScript

OBRR

OBRR Pro — Order Book Refresh Rate is indexed as 295_obrr.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.8 KB

Lines

458

Native Signal Candidates

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

3/3 guarded

Bid Pressure Spike

line 395:9

Trigger

(showShapes) && (crossUpPressure)

Value

pressureScoreSmooth

Deps

crossUpPressure:var, showShapes:input

Ask Pressure Spike

line 405:9

Trigger

(showShapes) && (crossDownPressure)

Value

pressureScoreSmooth

Deps

crossDownPressure:var, showShapes:input

Pressure Neutralized

line 415:9

Trigger

(showShapes) && (returnToNeutral)

Value

pressureScoreSmooth

Deps

returnToNeutral:var, showShapes:input

295_obrr.flowscript

source path: kscripts/perfected/295_obrr.flowscript · sha256:58a0b4a6b5c215774c10b45763f5fe00f233c8b146200b4dcf5d60e2d69c50a4

hash verified
//@version=2
// ============================================================================
// OBRR Pro — Order Book Refresh Rate & Microstructure Pressure Gauge
// Author: kiyotaka (@kiyotaka) | Enhanced by kScript Perfection Engineer
// Index: 295
// Tags: CORE, #orderbook, #refreshrate, #microstructure, #pressure, #zscore
//
// Production-grade order book refresh rate indicator measuring the velocity
// of bid/ask changes, order flow imbalance, and liquidity pressure. Implements
// z-score normalization, regime detection, and multi-depth aggregation with
// color-coded histogram and shape-based alerts.
//
// Academic foundations:
//  1. Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events"
//     (J. Financial Econometrics, 12(1), 47–88). Introduced OFI metric;
//     linear relationship between order flow imbalance and short-term price
//     changes. Slope ∝ 1/depth. OFI explains ~65% of variance in mid-price
//     changes at best bid/ask. [^1]
//  2. Gould & Bonart (2016), "Queue Imbalance as a One-Tick-Ahead Price
//     Predictor" (Market Microstructure and Liquidity, 2(1), 1650006). Queue
//     imbalance shows strongly significant logistic relationships with next
//     mid-price direction for liquid Nasdaq stocks. [^2]
//  3. Amihud & Mendelson (1986), "Asset Pricing and the Bid-Ask Spread"
//     (JFE, 17(2), 223–249). Expected returns are an increasing function of
//     the bid-ask spread; spread acts as a proxy for illiquidity. [^3]
//  4. Kyle (1985), "Continuous Auctions and Insider Trading" (Econometrica,
//     53(6), 1315–1335). Kyle's λ = price impact per unit of order flow.
//     Three liquidity dimensions: tightness, depth, resiliency. [^4]
//  5. Cartea, Donnelly & Jaimungal (2018), "Enhancing Trading Strategies with
//     Order Book Signals" (Applied Mathematical Finance, 25(1), 1–35). Segmented
//     volume imbalance into three regimes (sell-heavy, neutral, buy-heavy);
//     these segments predict future price moves. [^5]
//  6. Kızılersü et al. (2016), "Universal Behaviour in the Stock Market: Time
//     Dynamics of the Electronic Orderbook" (Physics Letters A, 380, 2207–2212).
//     Orderbook changes follow left-truncated Weibull distribution with universal
//     shape parameter corresponding to maximum entropy. [^6]
// ============================================================================

define(
    title="OBRR Pro — Order Book Refresh Rate",
    position="offchart",
    axis=true
)

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

// --- Orderbook Settings ---
var depth = input(
    name="depth",
    type="number",
    defaultValue=5,
    label="Orderbook Depth Levels",
    constraints={min: 1, max: 20, step: 1},
    group="Orderbook Settings"
)
var useMultiDepth = input(
    name="useMultiDepth",
    type="boolean",
    defaultValue=true,
    label="Use Multi-Depth Weighted Aggregation",
    group="Orderbook Settings"
)

// --- Refresh Rate Settings ---
var refreshLookback = input(
    name="refreshLookback",
    type="number",
    defaultValue=20,
    label="Refresh Rate Lookback",
    constraints={min: 5, max: 100, step: 1},
    group="Refresh Rate"
)
var refreshSmooth = input(
    name="refreshSmooth",
    type="number",
    defaultValue=3,
    label="Refresh Rate Smoothing",
    constraints={min: 1, max: 20, step: 1},
    group="Refresh Rate"
)

// --- Z-Score Settings ---
var zLookback = input(
    name="zLookback",
    type="number",
    defaultValue=20,
    label="Z-Score Lookback",
    constraints={min: 5, max: 100, step: 1},
    group="Z-Score"
)

// --- Thresholds ---
var pressureHigh = input(
    name="pressureHigh",
    type="number",
    defaultValue=2.0,
    label="High Pressure Threshold (σ)",
    constraints={min: 1.0, max: 4.0, step: 0.1},
    group="Thresholds"
)
var pressureLow = input(
    name="pressureLow",
    type="number",
    defaultValue=-2.0,
    label="Low Pressure Threshold (σ)",
    constraints={min: -4.0, max: -1.0, step: 0.1},
    group="Thresholds"
)

// --- Display ---
var showRefresh = input(
    name="showRefresh",
    type="boolean",
    defaultValue=true,
    label="Show Refresh Rate Lines",
    group="Display"
)
var showPressure = input(
    name="showPressure",
    type="boolean",
    defaultValue=true,
    label="Show Pressure Z-Score",
    group="Display"
)
var showHistogram = input(
    name="showHistogram",
    type="boolean",
    defaultValue=true,
    label="Show Pressure Histogram",
    group="Display"
)
var showRibbon = input(
    name="showRibbon",
    type="boolean",
    defaultValue=true,
    label="Show Pressure Ribbon",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Alert Shapes",
    group="Display"
)

// --- Colors ---
var bullColor = input(
    name="bullColor",
    type="color",
    defaultValue="#26a69a",
    label="Bid Pressure Color",
    group="Colors"
)
var bearColor = input(
    name="bearColor",
    type="color",
    defaultValue="#ef5350",
    label="Ask Pressure Color",
    group="Colors"
)
var neutralColor = input(
    name="neutralColor",
    type="color",
    defaultValue="#9e9e9e",
    label="Neutral Color",
    group="Colors"
)
var refreshColor = input(
    name="refreshColor",
    type="color",
    defaultValue="#ff9800",
    label="Refresh Rate Color",
    group="Colors"
)

// -----------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// -----------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries px = bars.close
timeseries hi = bars.high
timeseries lo = bars.low

if (isnan(px[0]) || isnan(hi[0]) || isnan(lo[0])) {
    return
}

// Orderbook data (best-effort; gracefully degrade if unavailable)
timeseries book = source("orderbook", currentSymbol, currentExchange)

// -----------------------------------------------------------------------------
// 3. ORDERBOOK DATA EXTRACTION
// -----------------------------------------------------------------------------
// Multi-depth aggregation with decaying weights (per Xu, Gould & Howison 2019)
// L1 gets full weight, deeper levels get progressively less weight.
timeseries bidsL1 = sumBids(book, 1)
timeseries asksL1 = sumAsks(book, 1)
timeseries bidsL3 = sumBids(book, 3)
timeseries asksL3 = sumAsks(book, 3)
timeseries bidsL5 = sumBids(book, 5)
timeseries asksL5 = sumAsks(book, 5)

// Weighted multi-depth totals (decay factor: L1=1.0, L3=0.7, L5=0.5)
timeseries bidsWeighted = useMultiDepth ? (bidsL1 + 0.7 * (bidsL3 - bidsL1) + 0.5 * (bidsL5 - bidsL3)) : bidsL1
timeseries asksWeighted = useMultiDepth ? (asksL1 + 0.7 * (asksL3 - asksL1) + 0.5 * (asksL5 - asksL3)) : asksL1

// Total depth
timeseries totalDepth = bidsWeighted + asksWeighted + 0.001

// -----------------------------------------------------------------------------
// 4. REFRESH RATE COMPUTATION
// -----------------------------------------------------------------------------
// Refresh rate = bar-to-bar change in bid/ask quantities.
// Positive bid refresh = new liquidity entering on bid side.
// Positive ask refresh = new liquidity entering on ask side.

timeseries bidRefresh = bidsWeighted - bidsWeighted[1]
timeseries askRefresh = asksWeighted - asksWeighted[1]

// Net refresh rate: bid refresh minus ask refresh
// Positive = more bid-side activity (buy pressure)
// Negative = more ask-side activity (sell pressure)
timeseries netRefresh = bidRefresh - askRefresh

// Absolute refresh rate (total churn)
timeseries absRefresh = math.abs(bidRefresh) + math.abs(askRefresh)

// Smooth the refresh rates
timeseries netRefreshSmooth = ema(netRefresh, refreshSmooth)
timeseries absRefreshSmooth = ema(absRefresh, refreshSmooth)

// -----------------------------------------------------------------------------
// 5. ORDERBOOK IMBALANCE & PRESSURE
// -----------------------------------------------------------------------------
// Per Cont et al. (2014): OFI = (ΔBid·1_{bid up} + ΔAsk·1_{ask down}) scaled by depth.
// We use a simplified but effective imbalance metric.

timeseries obi = (bidsWeighted - asksWeighted) / totalDepth

// Bid/ask spread estimate (from orderbook top-of-book)
timeseries spreadEst = asksL1 > bidsL1 ? asksL1 - bidsL1 : 0.01

// Spread-normalized pressure (per Lipton et al. 2013)
timeseries pressureRaw = obi * 100

// Refresh rate normalized by total depth (velocity metric)
timeseries velocityRaw = totalDepth > 0 ? absRefresh / totalDepth * 100 : 0

// -----------------------------------------------------------------------------
// 6. Z-SCORE NORMALIZATION
// -----------------------------------------------------------------------------
// Per Zhao & Palomar (2018): z_t = (x_t − μ_t) / σ_t.
// We z-score both the pressure and the net refresh rate.

// Pressure Z
timeseries pMean = sma(pressureRaw, zLookback)
timeseries pStd = stddev(pressureRaw, zLookback)
timeseries pZ = pStd > 0 ? (pressureRaw - pMean) / pStd : 0

// Refresh Rate Z
timeseries rMean = sma(netRefreshSmooth, zLookback)
timeseries rStd = stddev(netRefreshSmooth, zLookback)
timeseries rZ = rStd > 0 ? (netRefreshSmooth - rMean) / rStd : 0

// Velocity Z
timeseries vMean = sma(velocityRaw, zLookback)
timeseries vStd = stddev(velocityRaw, zLookback)
timeseries vZ = vStd > 0 ? (velocityRaw - vMean) / vStd : 0

// Combined pressure score (weighted composite)
timeseries pressureScore = pZ * 0.5 + rZ * 0.3 + vZ * 0.2

// Smooth the pressure score
timeseries pressureScoreSmooth = ema(pressureScore, refreshSmooth)

// -----------------------------------------------------------------------------
// 7. REGIME DETECTION
// -----------------------------------------------------------------------------
// Regime classification per Cartea et al. (2018) three-segment approach:
//   Bid-Heavy:   pressureScore > pressureHigh
//   Ask-Heavy:   pressureScore < pressureLow
//   Neutral:     everything else

var regimeBidHeavy = pressureScoreSmooth > pressureHigh
var regimeAskHeavy = pressureScoreSmooth < pressureLow
var regimeNeutral = !regimeBidHeavy && !regimeAskHeavy

var regimeColor = regimeBidHeavy ? bullColor : (regimeAskHeavy ? bearColor : neutralColor)

// -----------------------------------------------------------------------------
// 8. ALERT CONDITIONS
// -----------------------------------------------------------------------------
var crossUpPressure = pressureScoreSmooth > pressureHigh && pressureScoreSmooth[1] <= pressureHigh
var crossDownPressure = pressureScoreSmooth < pressureLow && pressureScoreSmooth[1] >= pressureLow
var returnToNeutral = (pressureScoreSmooth >= pressureLow && pressureScoreSmooth <= pressureHigh) && (pressureScoreSmooth[1] > pressureHigh || pressureScoreSmooth[1] < pressureLow)

// -----------------------------------------------------------------------------
// 9. STATIC STATE: Historical tracking
// -----------------------------------------------------------------------------
static maxPressure = -9999.0
static minPressure = 9999.0
static maxRefresh = -9999.0
static minRefresh = 9999.0
static barCount = 0

if (!isLiveUpdate) {
    barCount = barCount + 1
    if (pressureScoreSmooth > maxPressure) {
        maxPressure = pressureScoreSmooth
    }
    if (pressureScoreSmooth < minPressure) {
        minPressure = pressureScoreSmooth
    }
    if (netRefreshSmooth > maxRefresh) {
        maxRefresh = netRefreshSmooth
    }
    if (netRefreshSmooth < minRefresh) {
        minRefresh = netRefreshSmooth
    }
}

// -----------------------------------------------------------------------------
// 10. PLOTTING
// -----------------------------------------------------------------------------

// --- Zero line ---
hline(value=0, color="#ffffff20", width=1)

// --- Pressure thresholds ---
hline(value=pressureHigh, color=transparency(bullColor, 50), width=1)
hline(value=pressureLow, color=transparency(bearColor, 50), width=1)

// --- Refresh Rate Lines (bid/ask components) ---
if (showRefresh) {
    plotLine(
        value=netRefreshSmooth,
        width=2,
        colors=[refreshColor],
        label=["Net Refresh Rate"],
        desc=["Smoothed net refresh rate (bid refresh − ask refresh). Positive = bid pressure."]
    )
    plotLine(
        value=absRefreshSmooth,
        width=1,
        colors=["#42a5f5"],
        label=["Abs Refresh Rate"],
        desc=["Smoothed absolute refresh rate (total orderbook churn)"]
    )
}

// --- Pressure Score (regime-colored) ---
if (showPressure) {
    plotLine(
        value=pressureScoreSmooth,
        width=2,
        colors=[regimeColor],
        label=["Pressure Z-Score"],
        desc=["Composite pressure score (50% OBI + 30% refresh + 20% velocity), z-score normalized and smoothed"]
    )
}

// --- Pressure Ribbon (pressure vs zero, fill) ---
if (showRibbon) {
    var ribbonBull = pressureScoreSmooth >= 0
    plotLine(
        value=[pressureScoreSmooth, 0],
        width=1,
        colors=[transparency(regimeColor, 30), transparency(neutralColor, 10)],
        colorIndex=ribbonBull ? 0 : 0,
        fill=true,
        label=["Pressure Z", "Zero"],
        desc=["Pressure z-score ribbon fill", "Zero reference line"]
    )
}

// --- Pressure Histogram ---
if (showHistogram) {
    var histBull = pressureScoreSmooth >= 0
    plotBar(
        value=pressureScoreSmooth,
        colors=[transparency(bullColor, 60), transparency(bearColor, 60)],
        colorIndex=histBull ? 0 : 1,
        width=1,
        label=["Pressure Histogram"],
        desc=["Histogram of pressure z-score (positive = bid pressure, negative = ask pressure)"]
    )
}

// --- Alert Shapes ---
if (showShapes) {
    if (crossUpPressure) {
        plotShape(
            value=pressureScoreSmooth,
            shape="triangleup",
            colorIndex=bullColor,
            width=2,
            label=["Bid Pressure Spike"],
            desc=["Pressure z-score crossed above high threshold (" + pressureHigh + "σ). Strong bid-side liquidity injection."]
        )
    }
    if (crossDownPressure) {
        plotShape(
            value=pressureScoreSmooth,
            shape="triangledown",
            colorIndex=bearColor,
            width=2,
            label=["Ask Pressure Spike"],
            desc=["Pressure z-score crossed below low threshold (" + pressureLow + "σ). Strong ask-side liquidity injection."]
        )
    }
    if (returnToNeutral) {
        plotShape(
            value=pressureScoreSmooth,
            shape="circle",
            colorIndex=neutralColor,
            width=1,
            label=["Pressure Neutralized"],
            desc=["Pressure returned to neutral zone. Orderbook imbalance dissipated."]
        )
    }
}

// -----------------------------------------------------------------------------
// 11. REGIME TABLE (last bar only)
// -----------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = regimeBidHeavy ? "BID-HEAVY" : (regimeAskHeavy ? "ASK-HEAVY" : "NEUTRAL")
    var regimeTextColor = regimeColor

    plotTable(
        data=[
            ["OBRR Pro — Pressure", regimeText],
            ["Pressure Z", pressureScoreSmooth[0]],
            ["Net Refresh", netRefreshSmooth[0]],
            ["Abs Refresh", absRefreshSmooth[0]],
            ["OBI %", obi[0] * 100],
            ["Bid Depth", bidsWeighted[0]],
            ["Ask Depth", asksWeighted[0]],
            ["Max Pressure Z", maxPressure],
            ["Min Pressure Z", minPressure]
        ],
        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
    )
}