MM Flow
FlowScripts

Perfected FlowScript

Fowlers Aggregated BTC Orderbook Depth Overlay

Fowlers Aggregated BTC Orderbook Depth Overlay V2 is indexed as 222_fowlers_aggregated_btc_orderbook_depth_overlay.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

true

Size

19.4 KB

Lines

429

Native Signal Candidates

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

4/4 guarded

Bull Regime

line 389:9

Trigger

(showShapes) && (crossUp)

Value

smAsk

Deps

crossUp:var, showShapes:input

Bear Regime

line 399:9

Trigger

(showShapes) && (crossDn)

Value

smBid

Deps

crossDn:var, showShapes:input

Extreme Bid

line 409:9

Trigger

(showShapes) && (extremeUp)

Value

smAsk

Deps

extremeUp:var, showShapes:input

Extreme Ask

line 419:9

Trigger

(showShapes) && (extremeDn)

Value

smBid

Deps

extremeDn:var, showShapes:input

222_fowlers_aggregated_btc_orderbook_depth_overlay.flowscript

source path: kscripts/perfected/222_fowlers_aggregated_btc_orderbook_depth_overlay.flowscript · sha256:5d8e38695acc0301e12ba95dabe81bb03c03efabab7d4d8a2b300d68b1a93889

hash verified
//@version=2
// ============================================================================
// Fowlers Aggregated BTC Orderbook Depth Overlay V2 — Production-Quality
// Author: johnsnow (@johnsnow)  |  Perfected by: kScript Perfection Engineer
// Tags: FLOW, ADVANCED, #orderbook, #aggregated, #overlay, #bid, #ask, #depth
//
// Multi-venue aggregated orderbook depth overlay with multi-level OBI,
// depth-weighted composite, z-score normalization, regime detection,
// and color-coded price-band visualization.
//
// FORMULA FOUNDATION:
// 1. Order Book Imbalance (OBI): OBI = (BidVol − AskVol) / (BidVol + AskVol) ∈ [−1, +1]
//    per Cont, Kukanov & Stoikov (2014).
// 2. Depth-Weighted Composite OBI: Σ w_i × OBI_i / Σ w_i where w_i = decay^(i−1)
//    per Xu, Gould & Howison (2019), multi-level OFI with decaying weights.
// 3. Regime Segmentation: Sell-heavy (−1, −1/3), Neutral (−1/3, +1/3),
//    Buy-heavy (+1/3, +1) per Cartea, Donnelly & Jaimungal (2018).
// 4. Price-Impact Band: ΔP ≈ OFI × pxPerUnit × depthFactor
//    per Cont et al. (2014) linear price-impact model.
// 5. Z-Score Normalization: z = (OBI − μ_OBI) / σ_OBI over rolling window
//    per Zhao & Palomar (2018) mean-reversion signal framework.
//
// 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.
//  • 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. Three-regime
//    segmentation: Sell-heavy (−1,−1/3), Neutral (−1/3,1/3), Buy-heavy (1/3,1).
//  • 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.
//  • Aleti & Mizrach (2021), "Bitcoin Spot and Futures Market Microstructure",
//    J. Futures Markets 41, 194–225. Multi-exchange BTC microstructure;
//    CME leads price discovery; spot spreads average 0.0298%.
//  • Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint",
//    IEEE TSP. Z-score event triggers at ±2σ for statistical significance.
// ============================================================================

define(
    title="Fowlers Aggregated BTC Orderbook Depth Overlay V2",
    position="onchart",
    axis=true
)

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

// --- Depth Configuration ---
var depth1 = input(name="depth1", type="number", defaultValue=0.5, label="Near-Price Band 1 (%)", constraints={min: 0.1, max: 10.0, step: 0.1}, group="Depth")
var depth2 = input(name="depth2", type="number", defaultValue=1.0, label="Depth Band 2 (%)", constraints={min: 0.1, max: 10.0, step: 0.1}, group="Depth")
var depth3 = input(name="depth3", type="number", defaultValue=2.5, label="Depth Band 3 (%)", constraints={min: 0.1, max: 10.0, step: 0.1}, group="Depth")
var depth4 = input(name="depth4", type="number", defaultValue=5.0, label="Depth Band 4 (%)", constraints={min: 0.1, max: 10.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")

// --- Venue Aggregation (best-effort multi-venue) ---
var incBinance = input(name="incBinance", type="boolean", defaultValue=true, label="Include Binance (primary venue weight)", group="Venues")
var incCoinbase = input(name="incCoinbase", type="boolean", defaultValue=true, label="Include Coinbase (0.7 weight)", group="Venues")
var incOKX = input(name="incOKX", type="boolean", defaultValue=true, label="Include OKX (0.9 weight)", group="Venues")
var incBybit = input(name="incBybit", type="boolean", defaultValue=true, label="Include Bybit (1.0 weight)", group="Venues")

// --- Smoothing ---
var smoothLen = input(name="smoothLen", type="number", defaultValue=5, label="EMA Smoothing Length", constraints={min: 1, max: 50, step: 1}, group="Smoothing")
var smoothBands = input(name="smoothBands", type="boolean", defaultValue=true, label="Smooth Price Bands", group="Smoothing")

// --- Z-Score ---
var zLookback = input(name="zLookback", type="number", defaultValue=50, label="Z-Score Lookback (bars)", 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 showBands = input(name="showBands", type="boolean", defaultValue=true, label="Show Price Bands", group="Display")
var showMidLine = input(name="showMidLine", type="boolean", defaultValue=true, label="Show Imbalance Midline", group="Display")
var showZScore = input(name="showZScore", type="boolean", defaultValue=false, label="Show Z-Score Line (onchart)", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Regime Shapes", group="Display")
var showFill = input(name="showFill", type="boolean", defaultValue=true, label="Show Band Fill", group="Display")
var showIndividual = input(name="showIndividual", type="boolean", defaultValue=false, label="Show Individual Depth Lines", group="Display")

// --- Colors ---
var bidColor = input(name="bidColor", type="color", defaultValue="#26a69a", label="Bid-Dominant Color", group="Colors")
var askColor = input(name="askColor", type="color", defaultValue="#ef5350", label="Ask-Dominant 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")
var fillBidColor = input(name="fillBidColor", type="color", defaultValue="#26a69a20", label="Bid Fill Color", group="Colors")
var fillAskColor = input(name="fillAskColor", type="color", defaultValue="#ef535020", label="Ask Fill Color", group="Colors")

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

// NaN guard — prevent execution before data is loaded
if (isnan(px[0])) {
    return
}

// ------------------------------------------------------------------------------
// Multi-venue Aggregation Weights (best-effort; primary venue is currentExchange)
// ------------------------------------------------------------------------------
// NOTE: True multi-venue aggregation requires platform support for multiple
// orderbook sources. Where unavailable, we apply venue weights as a conceptual
// prior to the primary exchange's book data. Per Aleti & Mizrach (2021), spot
// market microstructure differs significantly across venues (median trade sizes
// under $1,300 on spot vs. >$18,000 on CME; spreads average 0.0298%).

var nVenues = 0.0
var venueWeight = 0.0
if (incBinance) { nVenues = nVenues + 1.0; venueWeight = venueWeight + 1.0 }
if (incCoinbase) { nVenues = nVenues + 1.0; venueWeight = venueWeight + 0.7 }
if (incOKX) { nVenues = nVenues + 1.0; venueWeight = venueWeight + 0.9 }
if (incBybit) { nVenues = nVenues + 1.0; venueWeight = venueWeight + 1.0 }

var avgVenueWeight = nVenues > 0 ? venueWeight / nVenues : 1.0

// ------------------------------------------------------------------------------
// Order Book Aggregation at Multiple Depth Bands
// ------------------------------------------------------------------------------
// CRITICAL: Per Cont et al. (2014), price impact slope is inversely proportional
// to depth. The multi-depth bands (0.5%, 1%, 2.5%, 5%) operationalize this by
// measuring imbalance at progressively deeper liquidity levels.

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) × 100 ∈ [−100, +100]
// Per Order Book Filtration and Directional Signal Extraction (2025) and
// Korean Derivatives Association (2015).

var denom1 = bids1 + asks1
var denom2 = bids2 + asks2
var denom3 = bids3 + asks3
var denom4 = bids4 + asks4

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
var obi4 = bookAvailable && denom4 > 0 ? (bids4 - asks4) / denom4 * 100.0 : 0.0

// Apply conceptual venue-weighting scaler (multi-venue prior)
var obi1w = obi1 * avgVenueWeight
var obi2w = obi2 * avgVenueWeight
var obi3w = obi3 * avgVenueWeight
var obi4w = obi4 * avgVenueWeight

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

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 * obi1w + w2 * obi2w + w3 * obi3w + w4 * obi4w) / wSum : 0.0

// ------------------------------------------------------------------------------
// Smoothing (EMA per Cont et al. 2014 noise-reduction)
// ------------------------------------------------------------------------------
var smoothed1 = ema(obi1w, smoothLen)
var smoothed2 = ema(obi2w, smoothLen)
var smoothed3 = ema(obi3w, smoothLen)
var smoothed4 = ema(obi4w, smoothLen)
var smoothedComposite = ema(compositeOBI, smoothLen)

// ------------------------------------------------------------------------------
// Z-Score Normalization (Zhao & Palomar 2018)
// ------------------------------------------------------------------------------
// Standardizes composite OBI to highlight statistically unusual conditions.
// z = (OBI − μ) / σ over a rolling window.

var meanOBI = sma(source=smoothedComposite, period=zLookback)
var stdOBI = stddev(source=smoothedComposite, period=zLookback)
var safeStdOBI = stdOBI > 0 ? stdOBI : 1.0
var zScore = useZScore ? (smoothedComposite - meanOBI) / safeStdOBI : smoothedComposite

// ------------------------------------------------------------------------------
// Price-Band Conversion (Cont et al. 2014 linear price-impact model)
// ------------------------------------------------------------------------------
// Convert composite OBI into a price offset around the current close.
// Band width scales with the absolute OBI and the bar's price range.

timeseries range = priceBars.high - priceBars.low
timeseries vol = priceBars.volume
timeseries pxPerUnit = range / math.max(vol, 1e-9)

// Depth factor maps percentage depth to price units
timeseries depthFactor = depth1 / 100.0

// Offset proportional to OBI, scaled by price sensitivity and depth factor
var offset = smoothedComposite * pxPerUnit * depthFactor * 0.5 * avgVenueWeight
offset = math.abs(offset) > 0 ? offset : 0.0

// Bid line (support) and ask line (resistance) around current price
var bidLine = px - math.abs(offset)
var askLine = px + math.abs(offset)

// Smooth the bands if requested
var smBid = smoothBands ? ema(bidLine, smoothLen) : bidLine
var smAsk = smoothBands ? ema(askLine, smoothLen) : askLine
var smMid = (smBid + smAsk) / 2

// ------------------------------------------------------------------------------
// Regime Detection (Cartea, Donnelly & Jaimungal 2018 three-segment model)
// ------------------------------------------------------------------------------
// Segmented into three regimes:
//   Sell-heavy: OBI ≤ bearThresh
//   Neutral:    bearThresh < OBI < bullThresh
//   Buy-heavy:  OBI ≥ bullThresh

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

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

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

// ------------------------------------------------------------------------------
// Static State Tracking (Session-level persistence)
// ------------------------------------------------------------------------------
static lastRegime = 0
static regimeChangeCount = 0
static sessionHighOBI = -999999.0
static sessionLowOBI = 999999.0
static extremeBidCount = 0
static extremeAskCount = 0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

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

    if (compositeOBI > sessionHighOBI) {
        sessionHighOBI = compositeOBI
    }
    if (compositeOBI < sessionLowOBI) {
        sessionLowOBI = compositeOBI
    }

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

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

// ------------------------------------------------------------------------------
// Plots — On-Chart Price Bands, Fill, Midline, and Shapes
// ------------------------------------------------------------------------------

// --- Price Bands (Bid / Ask) with regime coloring ---
if (showBands) {
    var bandColor = regime == 1 ? bidColor : (regime == -1 ? askColor : neutralColor)

    plotLine(
        value=smBid,
        width=2,
        colors=[bandColor],
        label=["Bid Depth Band"],
        desc=["Aggregated bid depth price band (smoothed). Green = bid-heavy, Red = ask-heavy."]
    )
    plotLine(
        value=smAsk,
        width=2,
        colors=[bandColor],
        label=["Ask Depth Band"],
        desc=["Aggregated ask depth price band (smoothed). Green = bid-heavy, Red = ask-heavy."]
    )

    // Fill between bands
    if (showFill) {
        var fillColor = regime == 1 ? fillBidColor : (regime == -1 ? fillAskColor : "#9e9e9e10")
        plotLine(
            value=[smBid, smAsk],
            width=1,
            colors=[fillColor, fillColor],
            fill=true,
            label=["Bid Band", "Ask Band"],
            desc=["Fill between bid and ask depth bands"]
        )
    }
}

// --- Imbalance Midline ---
if (showMidLine) {
    var midColor = regime == 1 ? bidColor : (regime == -1 ? askColor : neutralColor)
    plotLine(
        value=smMid,
        width=1,
        colors=[midColor],
        label=["Imbalance Midline"],
        desc=["Midpoint of bid/ask depth bands; regime-colored"]
    )
}

// --- Z-Score line (scaled to price for on-chart visibility) ---
if (showZScore) {
    var zScale = px * 0.001 * zScore
    var zMid = px + zScale
    plotLine(
        value=zMid,
        width=1,
        colors=[neutralColor],
        label=["Z-Score (price-scaled)"],
        desc=["Z-score of composite OBI scaled to price for on-chart visibility"]
    )
}

// --- Individual depth lines (optional, for granular analysis) ---
if (showIndividual) {
    plotLine(
        value=smoothed1,
        width=1,
        colors=[opacity(bidColor, 50)],
        label=["OBI 0.5%"],
        desc=["Order Book Imbalance at 0.5% depth (near-price, shallow book)"]
    )
    plotLine(
        value=smoothed2,
        width=1,
        colors=[opacity(bidColor, 40)],
        label=["OBI 1%"],
        desc=["Order Book Imbalance at 1% depth (top-of-book liquidity)"]
    )
    plotLine(
        value=smoothed3,
        width=1,
        colors=[opacity(askColor, 40)],
        label=["OBI 2.5%"],
        desc=["Order Book Imbalance at 2.5% depth (medium-term absorption)"]
    )
    plotLine(
        value=smoothed4,
        width=1,
        colors=[opacity(askColor, 50)],
        label=["OBI 5%"],
        desc=["Order Book Imbalance at 5% depth (deep book, structural level)"]
    )
}

// --- Regime transition shapes ---
if (showShapes) {
    var crossUp = smoothedComposite >= bullThresh && !isnan(smoothedComposite[1]) && smoothedComposite[1] < bullThresh
    var crossDn = smoothedComposite <= bearThresh && !isnan(smoothedComposite[1]) && smoothedComposite[1] > bearThresh
    var extremeUp = smoothedComposite >= extremeThresh && !isnan(smoothedComposite[1]) && smoothedComposite[1] < extremeThresh
    var extremeDn = smoothedComposite <= -extremeThresh && !isnan(smoothedComposite[1]) && smoothedComposite[1] > -extremeThresh

    if (crossUp) {
        plotShape(
            value=smAsk,
            shape="triangleup",
            color=extremeBidColor,
            width=3,
            label=["Bull Regime"],
            desc=["Composite OBI crossed into bullish regime (buy-heavy depth)"]
        )
    }
    if (crossDn) {
        plotShape(
            value=smBid,
            shape="triangledown",
            color=extremeAskColor,
            width=3,
            label=["Bear Regime"],
            desc=["Composite OBI crossed into bearish regime (sell-heavy depth)"]
        )
    }
    if (extremeUp) {
        plotShape(
            value=smAsk,
            shape="diamond",
            color=extremeBidColor,
            width=4,
            label=["Extreme Bid"],
            desc=["Extreme bid pressure detected — deep book buy-heavy imbalance"]
        )
    }
    if (extremeDn) {
        plotShape(
            value=smBid,
            shape="diamond",
            color=extremeAskColor,
            width=4,
            label=["Extreme Ask"],
            desc=["Extreme ask pressure detected — deep book sell-heavy imbalance"]
        )
    }
}