MM Flow
FlowScripts

Perfected FlowScript

Orderbook Momentum

Orderbook Momentum V2 is indexed as 058_orderbook_momentum.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

13.6 KB

Lines

315

Native Signal Candidates

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

4/4 guarded

Zero Cross Up

line 275:9

Trigger

(showShapes) && (crossUp)

Value

momentum

Deps

crossUp:var, showShapes:input

Zero Cross Down

line 285:9

Trigger

(showShapes) && (crossDn)

Value

momentum

Deps

crossDn:var, showShapes:input

Extreme Bull Momentum

line 295:9

Trigger

(showShapes) && (extremeUp)

Value

momentum

Deps

extremeUp:var, showShapes:input

Extreme Bear Momentum

line 305:9

Trigger

(showShapes) && (extremeDn)

Value

momentum

Deps

extremeDn:var, showShapes:input

058_orderbook_momentum.flowscript

source path: kscripts/perfected/058_orderbook_momentum.flowscript · sha256:d4c5640f2ab5cb321bc02538d97460372bd85400beafffa22472389d25ae961e

hash verified
//@version=2

// ============================================================================
// Orderbook Momentum V2 — Rate of Change of Bid/Ask Pressure
// Author: BackQuant (@BackQuant) | Perfected: kScript_Perfection_Engineer
// Tags: ADVANCED, CORE, #orderbook, #momentum, #obi, #microstructure
//
// Momentum of the bid/ask ratio, not the level. Computes the rate of change
// of smoothed orderbook imbalance, revealing acceleration / deceleration in
// orderbook pressure before it shows up in price. Includes momentum oscillator,
// zero-line cross shapes, regime color coding, and static session tracking.
//
// Academic foundation (exact papers & formulas):
//  1. Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events",
//     Journal of Financial Econometrics, 12(1), 47–88.
//     [Formula] OFI_t = Σ(E_bid^i − E_ask^i); price change ≈ (1/depth) × OFI.
//     The slope of the price-impact relationship is inversely proportional to
//     market depth. This is the direct theoretical basis for orderbook imbalance
//     momentum as a leading price signal.
//     DOI: https://doi.org/10.1093/jjfinec/nbt003
//
//  2. Xu, Gould & Howison (2019), "Multi-Level Order-Flow Imbalance in a
//     Limit Order Book", arXiv:1907.06230; Market Microstructure & Liquidity.
//     [Formula] Weighted OFI = Σ w_i × OFI_i / Σ w_i, where w_i = decay^(i−1).
//     Multi-level imbalance significantly improves short-horizon price prediction
//     compared to top-of-book alone. Supports multi-depth aggregation in this
//     script's bid/ask pressure computation.
//     DOI: https://doi.org/10.1142/S238262661950011X
//
//  3. Lipton, Pesavento & Sotiropoulos (2013), "Trade Arrival Dynamics and
//     Quote Imbalance in a Limit Order Book", arXiv:1312.0514.
//     [Formula] Linear relationship between Level 1 order imbalance and future
//     price moves, though future move on average remains within the bid-ask
//     spread. The momentum signal (change in imbalance) anticipates when this
//     relationship is strengthening or weakening.
//     DOI: https://arxiv.org/abs/1312.0514
//
//  4. Cartea, Donnelly & Jaimungal (2018), "Enhancing Trading Strategies with
//     Order Book Signals", Applied Mathematical Finance, 25(1), 1–35.
//     [Formula] Three-regime segmentation: Sell-heavy (−1,−1/3), Neutral
//     (−1/3,1/3), Buy-heavy (1/3,1). Positive price moves are more likely
//     preceded by buy-heavy books; negative by sell-heavy books. Directly
//     motivates the momentum-regime threshold design in this script.
//     DOI: https://www.tandfonline.com/doi/full/10.1080/1350486X.2018.1434009
//
//  5. Gould & Bonart (2016), "Queue Imbalance as a One-Tick-Ahead Price
//     Predictor in a Limit Order Book", Market Microstructure & Liquidity,
//     2(1), 1650006. Logistic regression between queue imbalance and subsequent
//     mid-price direction showed strongly significant relationships for 10
//     liquid Nasdaq stocks. The momentum of queue imbalance should lead the
//     level in predictive power.
//     DOI: https://arxiv.org/abs/1512.03492
//
//  6. Kyle (1985), "Continuous Auctions and Insider Trading", Econometrica,
//     53(6), 1315–1335. [Formula] p_t = p_{t−1} + λ·OFI_t + noise.
//     Kyle's λ establishes the linear price-impact coefficient; the derivative
//     (momentum of OFI) signals when informed flow is accelerating.
//     DOI: https://doi.org/10.2307/1913210
// ============================================================================

define(
    title="Orderbook Momentum V2",
    position="offchart",
    axis=true
)

// ---------------------------------------------------------------------------
// 1. USER INPUTS — All grouped, all numeric inputs carry constraints
// ---------------------------------------------------------------------------

// -- Depth Configuration --
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 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")

// -- Smoothing --
var smoothLen = input(name="smoothLen", type="number", defaultValue=10, label="Imbalance Smoothing", constraints={min: 1, max: 50, step: 1}, group="Smoothing")
var momLen    = input(name="momLen",    type="number", defaultValue=5,  label="Momentum Window", constraints={min: 1, max: 50, step: 1}, group="Smoothing")

// -- Thresholds & Regime --
var thrPos = input(name="thrPos", type="number", defaultValue=0.5, label="Bullish Momentum Threshold", constraints={min: 0.1, max: 5.0, step: 0.1}, group="Thresholds")
var thrNeg = input(name="thrNeg", type="number", defaultValue=-0.5, label="Bearish Momentum Threshold", constraints={min: -5.0, max: -0.1, step: 0.1}, group="Thresholds")

// -- Display --
var showMomentum = input(name="showMomentum", type="boolean", defaultValue=true, label="Show Momentum Oscillator", group="Display")
var showHistogram = input(name="showHistogram", type="boolean", defaultValue=true, label="Show Momentum Histogram", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Zero-Cross Shapes", group="Display")
var showRawOBI = input(name="showRawOBI", type="boolean", defaultValue=false, label="Show Raw OBI Line", group="Display")
var showGuides = input(name="showGuides", type="boolean", defaultValue=true, label="Show Guide Lines", group="Display")

// -- Colors --
var upColor    = input(name="upColor",    type="color", defaultValue="#26a69a", label="Bullish Momentum Color", group="Colors")
var dnColor    = input(name="dnColor",    type="color", defaultValue="#ef5350", label="Bearish Momentum Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#9e9e9e", label="Neutral Color", group="Colors")
var extremeUpColor = input(name="extremeUpColor", type="color", defaultValue="#00e676", label="Extreme Bull Color", group="Colors")
var extremeDnColor = input(name="extremeDnColor", type="color", defaultValue="#ff1744", label="Extreme Bear Color", group="Colors")

// ---------------------------------------------------------------------------
// 2. DATA SOURCES — with isnan() guard on first external access
// ---------------------------------------------------------------------------

timeseries pxTS = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries c    = pxTS.close
timeseries o    = pxTS.open
timeseries h    = pxTS.high
timeseries l    = pxTS.low
timeseries v    = pxTS.volume
timeseries book = source("orderbook", currentSymbol, currentExchange)

// Guard: halt until price and orderbook data are loaded
if (isnan(pxTS.close[0]) || isnan(book[0])) {
    return
}

// ---------------------------------------------------------------------------
// 3. COMPUTATION
// ---------------------------------------------------------------------------

// -- 3.1 Orderbook aggregation at multiple depth bands (Xu et al. 2019) --
// The kScript API accepts depth as a float percentage (e.g., 1.0 = 1%).
// Multi-level OFI improves out-of-sample price prediction vs. top-of-book alone.

var bids1 = sumBids(book, depth1)
var asks1 = sumAsks(book, depth1)
var bids2 = sumBids(book, depth2)
var asks2 = sumAsks(book, depth2)

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

// -- 3.2 OBI computation with zero-division guards --
// OBI = (Bid − Ask) / (Bid + Ask) ∈ [−1, +1]
// Formula from Order Book Filtration and Directional Signal Extraction (2025)
// and Korean Derivatives Association (2015).

var denom1 = bids1 + asks1
var denom2 = bids2 + asks2

var obi1 = bookAvailable && denom1 > 0 ? (bids1 - asks1) / denom1 : 0.0
var obi2 = bookAvailable && denom2 > 0 ? (bids2 - asks2) / denom2 : 0.0

// -- 3.3 Depth-weighted composite OBI (Xu, Gould & Howison 2019) --
// Multi-level OFI with geometrically decaying weights.
// w_i = decay^(i−1) for i = 1,2.
// Composite = Σ w_i × OBI_i / Σ w_i.

var w1 = 1.0
var w2 = useDepthWeighting ? weightDecay : 1.0
var wSum = w1 + w2
var compositeOBI = wSum > 0 ? (w1 * obi1 + w2 * obi2) / wSum : 0.0

// -- 3.4 Smoothed OBI (Cont et al. 2014 noise-reduction) --
timeseries smoothed = ema(compositeOBI, smoothLen)

// -- 3.5 Momentum = rate of change of smoothed OBI --
// The script's core innovation: measuring the *change* in imbalance (momentum)
// rather than the level, which should lead price changes (Lipton et al. 2013).
timeseries momentum = smoothed - smoothed[momLen]

// -- 3.6 Regime detection (Cartea, Donnelly & Jaimungal 2018 three-segment model) --
// Segmented into three regimes:
//   Bull momentum: momentum > thrPos
//   Bear momentum: momentum < thrNeg
//   Neutral: thrNeg < momentum < thrPos

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

if (momentum >= thrPos) {
    regime = 1
} else if (momentum <= thrNeg) {
    regime = -1
}

if (momentum >= thrPos * 2.0) {
    extremeRegime = 1
} else if (momentum <= thrNeg * 2.0) {
    extremeRegime = -1
}

// -- 3.7 Static state tracking (Session-level persistence) --
// Stateful computation for anchoring, session tracking, and counters.
static lastRegime = 0
static regimeChangeCount = 0
static sessionHighMom = -999999.0
static sessionLowMom = 999999.0
static zeroCrossUpCount = 0
static zeroCrossDnCount = 0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

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

    if (momentum > sessionHighMom) {
        sessionHighMom = momentum
    }
    if (momentum < sessionLowMom) {
        sessionLowMom = momentum
    }

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

    // Track zero-line crosses
    if (momentum > 0 && !isnan(momentum[1]) && momentum[1] <= 0) {
        zeroCrossUpCount = zeroCrossUpCount + 1
    }
    if (momentum < 0 && !isnan(momentum[1]) && momentum[1] >= 0) {
        zeroCrossDnCount = zeroCrossDnCount + 1
    }
}

// -- 3.8 Zero-line helper for fill areas --
timeseries zeroLine = 0

// ---------------------------------------------------------------------------
// 4. VISUALIZATION — Multiple types: plotLine, plotBar, plotShape, fill, hline
// ---------------------------------------------------------------------------

// 4.1 Horizontal guide lines
hline(value=0, color="#ffffff30", width=1)
if (showGuides) {
    hline(value=thrPos, color=opacity(upColor, 30), width=1)
    hline(value=thrNeg, color=opacity(dnColor, 30), width=1)
}

// 4.2 Momentum oscillator with regime-coded fill area
if (showMomentum) {
    plotLine(
        value=([momentum, zeroLine]),
        width=2,
        colors=[upColor, dnColor, neutralColor],
        colorIndex=regime == 1 ? 0 : (regime == -1 ? 1 : 2),
        label=["OB Momentum"],
        desc=["Rate of change of smoothed bid/ask imbalance; positive = accelerating bid pressure (Cartea et al. 2018)"],
        fill=true
    )
}

// 4.3 Momentum histogram (bars colored by direction)
if (showHistogram) {
    plotBar(
        value=momentum,
        colors=[upColor, dnColor],
        width=1,
        label=["OB Momentum Histogram"],
        desc=["Rate of change of smoothed OBI; positive = bid pressure accelerating, negative = ask pressure accelerating"]
    )
}

// 4.4 Raw OBI line (optional, for granular context)
if (showRawOBI) {
    plotLine(
        value=smoothed,
        width=1,
        colors=[opacity(neutralColor, 50)],
        label=["Smoothed OBI"],
        desc=["Depth-weighted composite order book imbalance (Cont-Kukanov-Stoikov 2014)"]
    )
}

// 4.5 Zero-line cross shapes (plotShape) — momentum inflection alerts
if (showShapes) {
    var crossUp = momentum > 0 && !isnan(momentum[1]) && momentum[1] <= 0
    var crossDn = momentum < 0 && !isnan(momentum[1]) && momentum[1] >= 0
    var extremeUp = momentum >= thrPos * 2.0 && !isnan(momentum[1]) && momentum[1] < thrPos * 2.0
    var extremeDn = momentum <= thrNeg * 2.0 && !isnan(momentum[1]) && momentum[1] > thrNeg * 2.0

    if (crossUp) {
        plotShape(
            value=momentum,
            shape="triangleup",
            color=upColor,
            width=3,
            label=["Zero Cross Up"],
            desc=["Orderbook momentum crossed above zero — bid pressure accelerating (Lipton et al. 2013)"]
        )
    }
    if (crossDn) {
        plotShape(
            value=momentum,
            shape="triangledown",
            color=dnColor,
            width=3,
            label=["Zero Cross Down"],
            desc=["Orderbook momentum crossed below zero — ask pressure accelerating (Lipton et al. 2013)"]
        )
    }
    if (extremeUp) {
        plotShape(
            value=momentum,
            shape="diamond",
            color=extremeUpColor,
            width=4,
            label=["Extreme Bull Momentum"],
            desc=["Extreme bid pressure acceleration — buy-heavy book regime (Cartea et al. 2018)"]
        )
    }
    if (extremeDn) {
        plotShape(
            value=momentum,
            shape="diamond",
            color=extremeDnColor,
            width=4,
            label=["Extreme Bear Momentum"],
            desc=["Extreme ask pressure acceleration — sell-heavy book regime (Cartea et al. 2018)"]
        )
    }
}