Perfected FlowScript
Orderbook Imbalance Levels
Orderbook Imbalance Levels is indexed as 075_orderbook_imbalance_levels.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.5 KB
Lines
381
Native Signal Candidates
4 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Bid Support
line 300:9
Trigger
(showShapes) && (bidSupported)
Value
compositeOBI
Deps
bidSupported:var, showShapes:input
Ask Resistance
line 310:9
Trigger
(showShapes) && (askResisted)
Value
compositeOBI
Deps
askResisted:var, showShapes:input
Extreme Bid
line 327:9
Trigger
(showShapes) && (extremeUp)
Value
compositeOBI
Deps
extremeUp:var, showShapes:input
Extreme Ask
line 337:9
Trigger
(showShapes) && (extremeDn)
Value
compositeOBI
Deps
extremeDn:var, showShapes:input
075_orderbook_imbalance_levels.flowscript
source path: kscripts/perfected/075_orderbook_imbalance_levels.flowscript · sha256:f70b4b0fafb5a62f6a4c45849878bf1573d5d796a7e3cd0956479fcc0d43b24e
//@version=2
// ============================================================================
// Orderbook Imbalance Levels — Perfected Edition
// Author: kiyotaka (@kiyotaka) | Perfected by: kScript Perfection Engineer
// Tags: FLOW, #orderbook, #imbalance, #levels, #support, #resistance, #microstructure
//
// Identifies orderbook imbalance at specific price levels, drawing ATR-scaled
// support/resistance zones when imbalance aligns with pivot extremes. Color coding
// by imbalance direction with shape markers for extreme readings; static state
// persists discovered levels across the session.
//
// FORMULA FOUNDATION:
// 1. Order Flow Imbalance (OFI): OFI = (BidVol − AskVol) / (BidVol + AskVol) ∈ [−1, +1]
// per Cont, Kukanov & Stoikov (2014), J. Financial Econometrics 12(1), 47–88.
// 2. Multi-Level OFI with Decaying Weights: Σ w_i × OFI_i / Σ w_i, w_i = decay^(i−1)
// per Xu, Gould & Howison (2019), arXiv:1907.06230.
// 3. Imbalance Regime Segmentation: Sell-heavy (−1,−1/3), Neutral (−1/3,1/3),
// Buy-heavy (1/3,1) per Cartea, Donnelly & Jaimungal (2018), Appl. Math.
// Finance 25(1), 1–35. These segments predict future price direction.
// 4. Support/Resistance Theory: Pivot extremes (local highs/lows) combined with
// orderbook imbalance identify structurally-significant levels. ATR-scaled zones
// provide volatility-adaptive thickness per Kirkpatrick & Dahlquist (2010) and
// CMT Association (2016) Volatility-Based Support Resistance (VBSR).
//
// RESEARCH BASIS:
// • Cont, Kukanov & Stoikov (2014). OFI = Σ(E_i × ΔP_i); slope ∝ 1/depth.
// • Xu, Gould & Howison (2019). Multi-level OFI with decaying weights.
// • Cartea, Donnelly & Jaimungal (2018). Three-regime segmentation.
// • Gould & Bonart (2016). Queue imbalance as one-tick-ahead predictor.
// • Korean Derivatives Association (2015). Full-book imbalance predicts
// 5-, 10-, and 20-minute returns.
// • Kirkpatrick & Dahlquist (2010). Support/resistance rated 4.41/5 among
// practitioners — most valued technical tool.
// • CMT Association / CFA Institute (2016). VBSR: volatility extremes identify
// expected future S/R levels; statistical tendency of implied vol to mean-revert.
// ============================================================================
define(
title="Orderbook Imbalance Levels",
position="offchart",
axis=true
)
// ------------------------------------------------------------------------------
// User Inputs — grouped and constrained per production spec
// ------------------------------------------------------------------------------
// --- 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 depth3 = input(name="depth3", type="number", defaultValue=5.0, label="Depth Band 3 (%)", constraints={min: 0.1, max: 50.0, step: 0.1}, group="Depth")
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="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")
// --- Thresholds & Regime ---
var bidThreshold = input(name="bidThreshold", type="number", defaultValue=20.0, label="Bid Threshold (%)", constraints={min: 5.0, max: 90.0, step: 1.0}, group="Thresholds")
var askThreshold = input(name="askThreshold", type="number", defaultValue=-20.0, label="Ask Threshold (%)", constraints={min: -90.0, max: -5.0, step: 1.0}, group="Thresholds")
var extremeThreshold = input(name="extremeThreshold", type="number", defaultValue=50.0, label="Extreme Threshold (%)", constraints={min: 30.0, max: 95.0, step: 1.0}, group="Thresholds")
// --- Pivot Detection ---
var pivotWindow = input(name="pivotWindow", type="number", defaultValue=5, label="Pivot Window (bars each side)", constraints={min: 2, max: 20, step: 1}, group="Pivot Detection")
var atrLen = input(name="atrLen", type="number", defaultValue=14, label="ATR Length for Zone Thickness", constraints={min: 5, max: 50, step: 1}, group="Pivot Detection")
var atrMult = input(name="atrMult", type="number", defaultValue=1.0, label="ATR Multiplier for Zone", constraints={min: 0.5, max: 5.0, step: 0.1}, group="Pivot Detection")
// --- Display ---
var showComposite = input(name="showComposite", type="boolean", defaultValue=true, label="Show Composite OBI Line", group="Display")
var showRaw = input(name="showRaw", type="boolean", defaultValue=false, label="Show Raw OBI Line", group="Display")
var showLevels = input(name="showLevels", type="boolean", defaultValue=true, label="Show Support/Resistance Levels", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Extreme Shape Markers", group="Display")
var showGuides = input(name="showGuides", type="boolean", defaultValue=true, label="Show Guide 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 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 neutralColor = input(name="neutralColor", type="color", defaultValue="#9e9e9e", label="Neutral Color", group="Colors")
// ------------------------------------------------------------------------------
// Data Sources & NaN Guard
// ------------------------------------------------------------------------------
timeseries book = source("orderbook", currentSymbol, currentExchange)
timeseries ohlcvData = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries close = ohlcvData.close
timeseries high = ohlcvData.high
timeseries low = ohlcvData.low
timeseries atr = atr(source=ohlcvData, period=atrLen)
if (isnan(close[0])) {
return
}
// ------------------------------------------------------------------------------
// Order Book Aggregation
// ------------------------------------------------------------------------------
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)
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 * 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
// ------------------------------------------------------------------------------
// Depth-Weighted Composite OBI (Xu, Gould & Howison 2019)
// ------------------------------------------------------------------------------
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
var rawOBI = bookAvailable ? (bids1 - asks1) / (bids1 + asks1) * 100.0 : 0.0
// ------------------------------------------------------------------------------
// Regime Detection (Cartea, Donnelly & Jaimungal 2018)
// ------------------------------------------------------------------------------
var regime = 0
var extremeRegime = 0
if (compositeOBI >= bidThreshold) {
regime = 1
} else if (compositeOBI <= askThreshold) {
regime = -1
}
if (compositeOBI >= extremeThreshold) {
extremeRegime = 1
} else if (compositeOBI <= -extremeThreshold) {
extremeRegime = -1
}
// ------------------------------------------------------------------------------
// Pivot Detection (Kirkpatrick & Dahlquist 2010; standard swing pivot logic)
// ------------------------------------------------------------------------------
// Pivot low: low is lowest in a window of (2*pivotWindow + 1) bars centered on current
// Pivot high: high is highest in a window of (2*pivotWindow + 1) bars centered on current
var pivotLow = low < low[1] && low < low[2] && low < low[pivotWindow] && low < low[pivotWindow + 1]
var pivotHigh = high > high[1] && high > high[2] && high > high[pivotWindow] && high > high[pivotWindow + 1]
// --- Level Conditions ---
// Bid support: pivot low + bid-heavy imbalance
// Ask resistance: pivot high + ask-heavy imbalance
var bidSupported = pivotLow && compositeOBI > bidThreshold
var askResisted = pivotHigh && compositeOBI < askThreshold
// Zone thickness adapts to volatility (ATR-scaled per VBSR, CMT Association 2016)
var zoneThickness = atr * atrMult
// Minimum level distance filter (prevent overlapping levels)
// Static tracking of last seen level prices ensures visual clarity
// ------------------------------------------------------------------------------
// Static State Tracking (Level persistence across session)
// ------------------------------------------------------------------------------
// Tracks discovered S/R levels, their type, regime transitions, and counts.
static lastBidLevel = 0.0
static lastAskLevel = 0.0
static lastBidTime = 0
static lastAskTime = 0
static bidLevelCount = 0
static askLevelCount = 0
static extremeBidCount = 0
static extremeAskCount = 0
static lastRegime = 0
static regimeChangeCount = 0
static sessionHighOBI = -999999.0
static sessionLowOBI = 999999.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 (bidSupported) {
lastBidLevel = low
lastBidTime = currentBarIndex
bidLevelCount = bidLevelCount + 1
}
if (askResisted) {
lastAskLevel = high
lastAskTime = currentBarIndex
askLevelCount = askLevelCount + 1
}
if (extremeRegime == 1) {
extremeBidCount = extremeBidCount + 1
} else if (extremeRegime == -1) {
extremeAskCount = extremeAskCount + 1
}
}
// ------------------------------------------------------------------------------
// Plots — Composite Lines, Level Zones, Shapes, and Guides
// ------------------------------------------------------------------------------
// --- Horizontal guide lines ---
hline(value=0, color="#ffffff30", width=1)
if (showGuides) {
hline(value=bidThreshold, color=opacity(bidColor, 30), width=1)
hline(value=askThreshold, color=opacity(askColor, 30), width=1)
hline(value=extremeThreshold, color=opacity(extremeBidColor, 20), width=1)
hline(value=-extremeThreshold, color=opacity(extremeAskColor, 20), width=1)
}
// --- Composite OBI line (regime-colored with fill) ---
if (showComposite) {
var lineColor = regime == 1 ? bidColor : (regime == -1 ? askColor : neutralColor)
plotLine(
value=compositeOBI,
width=2,
colors=[lineColor],
label=["Composite OBI"],
desc=["Depth-weighted composite OBI (" + depth1 + "/" + depth2 + "/" + depth3 + "/" + depth4 + ") — regime-colored"],
fill=true
)
}
// --- Raw OBI line (1% depth only, for reference) ---
if (showRaw) {
plotLine(
value=rawOBI,
width=1,
colors=[opacity(neutralColor, 50)],
label=["Raw OBI 1%"],
desc=["Raw orderbook imbalance at 1% depth (unweighted, unsmoothed)"]
)
}
// --- Support Level Zones (ATR-scaled fill for bid-supported pivots) ---
if (showLevels && bidSupported) {
var supportTop = low + zoneThickness
var supportBottom = low - zoneThickness
plotLine(
value=[supportTop, supportBottom],
width=2,
colors=[opacity(bidColor, 30), opacity(bidColor, 30)],
fill=true,
label=["Bid Support Zone", "Bid Support Zone"],
desc=["Bid-supported pivot low with ATR-scaled volatility zone (" + atrMult + "× ATR)"]
)
}
// --- Resistance Level Zones (ATR-scaled fill for ask-resisted pivots) ---
if (showLevels && askResisted) {
var resistTop = high + zoneThickness
var resistBottom = high - zoneThickness
plotLine(
value=[resistTop, resistBottom],
width=2,
colors=[opacity(askColor, 30), opacity(askColor, 30)],
fill=true,
label=["Ask Resistance Zone", "Ask Resistance Zone"],
desc=["Ask-resisted pivot high with ATR-scaled volatility zone (" + atrMult + "× ATR)"]
)
}
// --- Level shape markers (triangles at extreme levels) ---
if (showShapes) {
if (bidSupported) {
plotShape(
value=compositeOBI,
shape="triangleup",
color=extremeBidColor,
width=3,
label=["Bid Support"],
desc=["Bid-supported pivot low detected — OBI=" + compositeOBI + ", level=" + low]
)
}
if (askResisted) {
plotShape(
value=compositeOBI,
shape="triangledown",
color=extremeAskColor,
width=3,
label=["Ask Resistance"],
desc=["Ask-resisted pivot high detected — OBI=" + compositeOBI + ", level=" + high]
)
}
}
// --- Extreme imbalance shape markers ---
if (showShapes) {
var extremeUp = compositeOBI >= extremeThreshold && !isnan(compositeOBI[1]) && compositeOBI[1] < extremeThreshold
var extremeDn = compositeOBI <= -extremeThreshold && !isnan(compositeOBI[1]) && compositeOBI[1] > -extremeThreshold
if (extremeUp) {
plotShape(
value=compositeOBI,
shape="diamond",
color=extremeBidColor,
width=4,
label=["Extreme Bid"],
desc=["Extreme bid imbalance detected — OBI=" + compositeOBI + ", deep book buy-heavy"]
)
}
if (extremeDn) {
plotShape(
value=compositeOBI,
shape="diamond",
color=extremeAskColor,
width=4,
label=["Extreme Ask"],
desc=["Extreme ask imbalance detected — OBI=" + compositeOBI + ", deep book sell-heavy"]
)
}
}
// ------------------------------------------------------------------------------
// Regime Table (last bar only — summary of session state)
// ------------------------------------------------------------------------------
if (isLastBar && bookAvailable) {
var regimeText = regime == 1 ? "BUY-HEAVY" : (regime == -1 ? "SELL-HEAVY" : "NEUTRAL")
var regimeTextColor = regime == 1 ? bidColor : (regime == -1 ? askColor : neutralColor)
plotTable(
data=[
["Orderbook Imbalance Levels", regimeText],
["Composite OBI", compositeOBI],
["Session High OBI", sessionHighOBI],
["Session Low OBI", sessionLowOBI],
["Bid Levels", bidLevelCount],
["Ask Levels", askLevelCount],
["Extreme Bids", extremeBidCount],
["Extreme Asks", extremeAskCount],
["Last Bid Level", lastBidLevel],
["Last Ask Level", lastAskLevel]
],
position="top_right",
headerRow=true,
headerColumn=true,
textColor="#e2e8f0",
headerTextColor="#ffffff",
backgroundColor=opacity("#0f172a", 40),
headerBackgroundColor=opacity("#1e293b", 40),
borderColor=opacity("#334155", 40),
borderWidth=1,
fontSize=10,
cellPadding=4
)
}