Perfected FlowScript
Bid/Ask Sum
Bid/Ask Sum V2 is indexed as 124_bid_ask_sum.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
16.7 KB
Lines
388
Native Signal Candidates
4 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Bull Regime
line 315:9
Trigger
(showShapes) && (crossUp)
Value
smoothedComposite
Deps
crossUp:var, showShapes:input
Bear Regime
line 325:9
Trigger
(showShapes) && (crossDn)
Value
smoothedComposite
Deps
crossDn:var, showShapes:input
Extreme Bid
line 335:9
Trigger
(showShapes) && (extremeUp)
Value
smoothedComposite
Deps
extremeUp:var, showShapes:input
Extreme Ask
line 345:9
Trigger
(showShapes) && (extremeDn)
Value
smoothedComposite
Deps
extremeDn:var, showShapes:input
124_bid_ask_sum.flowscript
source path: kscripts/perfected/124_bid_ask_sum.flowscript · sha256:51871cb4d71b8a288315983a43b91a005ed43c3ccf5a65fab780f2771e2a03f7
//@version=2
// ============================================================================
// Bid/Ask Sum V2 — Production-Quality Multi-Depth Liquidity Microstructure Indicator
// Author: C (@cryptosonographer) | Perfected by: kScript Perfection Engineer
// Tags: ADVANCED, #orderbook, #liquidity, #microstructure, #OBI, #depth
//
// Multi-depth limit order book bid/ask sum with depth-weighted composite OBI,
// imbalance detection, regime-coded visualization, and academic microstructure
// foundations. Visualizes resting liquidity at four depth bands to identify
// support/resistance from order book structure.
//
// FORMULA FOUNDATION:
// 1. Bid/Ask Sum at depth d: Σ bidVol within d% of mid, Σ askVol within d% of mid
// 2. OBI at depth d: (BidSum − AskSum) / (BidSum + AskSum) ∈ [−1, +1]
// 3. Depth-Weighted Composite OBI: Σ w_i × OBI_i / Σ w_i where w_i = decay^(i−1)
// 4. Regime Segmentation: Sell-heavy (−1,−1/3), Neutral (−1/3,1/3), Buy-heavy (1/3,1)
// per Cartea, Donnelly & Jaimungal (2018).
//
// RESEARCH BASIS:
// • Cont, Kukanov & Stoikov (2014), J. Financial Econometrics 12(1), 47–88.
// OFI-price impact linearity; ΔP ≈ λ·OFI; slope λ ∝ 1/depth.
// • Xu, Gould & Howison (2019), arXiv:1907.06230. Multi-level OFI with
// decaying weights; predictive power improves with each additional depth level.
// • Amihud & Mendelson (1986), "Asset Pricing and the Bid-Ask Spread".
// Bid-ask spread as illiquidity proxy; depth-based measures extend this.
// • Paddrik et al. (2014), "Effects of Limit Order Book Information Level on
// Market Stability Metrics". Deeper book information improves stability measures.
// • 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).
// ============================================================================
define(
title="Bid/Ask Sum V2",
position="offchart",
axis=true
)
// ------------------------------------------------------------------------------
// User Inputs — grouped and constrained per production spec
// ------------------------------------------------------------------------------
// --- Depth Configuration ---
var depth1 = input(name="depth1", type="number", defaultValue=0.5, label="Depth Band 1 (%)", constraints={min: 0.1, max: 50.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: 50.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: 50.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: 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=3, label="EMA Smoothing Length", constraints={min: 1, max: 50, step: 1}, group="Smoothing")
// --- Thresholds & Regime ---
var bullThresh = input(name="bullThresh", type="number", defaultValue=0.33, label="Bullish Regime Threshold (ratio)", constraints={min: 0.05, max: 0.95, step: 0.01}, group="Thresholds")
var bearThresh = input(name="bearThresh", type="number", defaultValue=-0.33, label="Bearish Regime Threshold (ratio)", constraints={min: -0.95, max: -0.05, step: 0.01}, group="Thresholds")
var extremeThresh = input(name="extremeThresh", type="number", defaultValue=0.66, label="Extreme Imbalance Threshold (ratio)", constraints={min: 0.5, max: 0.95, step: 0.01}, group="Thresholds")
// --- Display ---
var showBidAsk = input(name="showBidAsk", type="boolean", defaultValue=false, label="Show Raw Bid/Ask Sums", group="Display")
var showComposite = input(name="showComposite", type="boolean", defaultValue=true, label="Show Composite OBI Line", group="Display")
var showIndividual = input(name="showIndividual", type="boolean", defaultValue=false, label="Show Individual Depth OBI Lines", group="Display")
var showImbalance = input(name="showImbalance", type="boolean", defaultValue=true, label="Show Imbalance Histogram", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Regime Shapes", group="Display")
var showGuides = input(name="showGuides", type="boolean", defaultValue=true, label="Show Guide Lines", group="Display")
var showTable = input(name="showTable", type="boolean", defaultValue=true, label="Show Summary Table", 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")
// ------------------------------------------------------------------------------
// Data Sources
// ------------------------------------------------------------------------------
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 data-integrity best practice)
if (isnan(px[0])) {
return
}
// ------------------------------------------------------------------------------
// Multi-Depth Bid/Ask Sum
// ------------------------------------------------------------------------------
// Per Xu, Gould & Howison (2019), predictive power improves with each additional
// depth level. We use four bands (0.5%, 1%, 2.5%, 5%) to capture both shallow
// near-price pressure and deeper structural liquidity.
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 (Paddrik et al. 2014 robustness)
var bookAvailable = bids1 > 0 && asks1 > 0 && bids2 > 0 && asks2 > 0 && bids3 > 0 && asks3 > 0 && bids4 > 0 && asks4 > 0
// ------------------------------------------------------------------------------
// OBI Computation at Each Depth with Zero-Division Guards
// ------------------------------------------------------------------------------
// OBI = (Bid − Ask) / (Bid + Ask) ∈ [−1, +1]
// Formula from Cont et al. (2014) 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 : 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
// Total liquidity at each depth
var total1 = denom1
var total2 = denom2
var total3 = denom3
var total4 = denom4
// ------------------------------------------------------------------------------
// 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.
// This significantly improves short-horizon prediction vs. top-of-book alone.
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
// ------------------------------------------------------------------------------
// Smoothing (EMA per Cont et al. 2014 noise-reduction)
// ------------------------------------------------------------------------------
var smoothed1 = ema(obi1, smoothLen)
var smoothed2 = ema(obi2, smoothLen)
var smoothed3 = ema(obi3, smoothLen)
var smoothed4 = ema(obi4, smoothLen)
var smoothedComposite = ema(compositeOBI, smoothLen)
// ------------------------------------------------------------------------------
// 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
// These segments predict future price moves: positive changes preceded by
// buy-heavy books; negative changes by sell-heavy books.
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
}
// Regime color for composite line
var compColor = regime == 1 ? bidColor : (regime == -1 ? askColor : neutralColor)
// ------------------------------------------------------------------------------
// Static State Tracking (Session-level persistence)
// ------------------------------------------------------------------------------
// Stateful computation for regime transitions, session extremes, and counters.
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 — Multiple Visualization Types (Line, Bar, Shape, Fill, HLine)
// ------------------------------------------------------------------------------
// Horizontal guide lines — zero line and configurable threshold zones
hline(value=0, color="#ffffff30", width=1)
if (showGuides) {
hline(value=bullThresh, color=transparency(bidColor, 30), width=1)
hline(value=bearThresh, color=transparency(askColor, 30), width=1)
hline(value=extremeThresh, color=transparency(extremeBidColor, 20), width=1)
hline(value=-extremeThresh, color=transparency(extremeAskColor, 20), width=1)
}
// Composite OBI line with regime-coded fill area
if (showComposite) {
plotLine(
value=smoothedComposite,
width=2,
colors=[compColor],
label=["Composite OBI"],
desc=["Depth-weighted composite OBI (EMA-smoothed). Regime: bull/bear/neutral."],
fill=true
)
}
// Imbalance histogram (composite OBI as bars)
if (showImbalance) {
var imbColor = smoothedComposite >= 0 ? bidColor : askColor
plotBar(
value=smoothedComposite,
colors=[imbColor],
width=1,
label=["OBI Imbalance"],
desc=["Composite OBI histogram: positive = bid heavy, negative = ask heavy"]
)
}
// Individual depth OBI lines (optional, for granular analysis)
if (showIndividual) {
plotLine(
value=smoothed1,
width=1,
colors=[transparency(bidColor, 60)],
label=["OBI " + depth1 + "%"],
desc=["Order Book Imbalance at " + depth1 + "% depth (shallow book, top-of-book)"]
)
plotLine(
value=smoothed2,
width=1,
colors=[transparency(bidColor, 40)],
label=["OBI " + depth2 + "%"],
desc=["Order Book Imbalance at " + depth2 + "% depth (near-term liquidity)"]
)
plotLine(
value=smoothed3,
width=1,
colors=[transparency(askColor, 40)],
label=["OBI " + depth3 + "%"],
desc=["Order Book Imbalance at " + depth3 + "% depth (medium-term absorption)"]
)
plotLine(
value=smoothed4,
width=1,
colors=[transparency(askColor, 60)],
label=["OBI " + depth4 + "%"],
desc=["Order Book Imbalance at " + depth4 + "% depth (deep book, structural level)"]
)
}
// Raw bid/ask sum lines (optional diagnostic)
if (showBidAsk) {
plotLine(
value=bids1,
width=1,
colors=[transparency(bidColor, 25)],
label=["Bid Sum " + depth1 + "%"],
desc=["Bid-side liquidity at " + depth1 + "% depth"]
)
plotLine(
value=asks1,
width=1,
colors=[transparency(askColor, 25)],
label=["Ask Sum " + depth1 + "%"],
desc=["Ask-side liquidity at " + depth1 + "% depth"]
)
}
// Regime transition shapes — directional signal extraction (Cartea et al. 2018)
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=smoothedComposite,
shape="triangleup",
color=extremeBidColor,
width=3,
label=["Bull Regime"],
desc=["Composite OBI crossed into bullish regime (buy-heavy)"]
)
}
if (crossDn) {
plotShape(
value=smoothedComposite,
shape="triangledown",
color=extremeAskColor,
width=3,
label=["Bear Regime"],
desc=["Composite OBI crossed into bearish regime (sell-heavy)"]
)
}
if (extremeUp) {
plotShape(
value=smoothedComposite,
shape="diamond",
color=extremeBidColor,
width=4,
label=["Extreme Bid"],
desc=["Extreme bid pressure detected — deep book buy-heavy imbalance"]
)
}
if (extremeDn) {
plotShape(
value=smoothedComposite,
shape="diamond",
color=extremeAskColor,
width=4,
label=["Extreme Ask"],
desc=["Extreme ask pressure detected — deep book sell-heavy imbalance"]
)
}
}
// ------------------------------------------------------------------------------
// Summary Table (last bar only)
// ------------------------------------------------------------------------------
if (showTable && isLastBar) {
var regimeText = regime == 1 ? "BULLISH" : (regime == -1 ? "BEARISH" : "NEUTRAL")
var regimeTextColor = regime == 1 ? bidColor : (regime == -1 ? askColor : neutralColor)
plotTable(
data=[
["Bid/Ask Sum V2", regimeText],
["Composite OBI", smoothedComposite[0]],
["OBI " + depth1 + "%", obi1[0]],
["OBI " + depth2 + "%", obi2[0]],
["OBI " + depth3 + "%", obi3[0]],
["OBI " + depth4 + "%", obi4[0]],
["Regime Changes", regimeChangeCount],
["Extreme Bids", extremeBidCount],
["Extreme Asks", 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
)
}