Perfected FlowScript
Ob Global
OB Global V2 is indexed as 311_ob_global.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
false
Size
21.1 KB
Lines
665
Native Signal Candidates
4 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Global Bull OB
line 585:9
Trigger
(showShapes) && (bullObNew)
Value
globalBullObLo
Deps
bullObNew:var, showShapes:input
Global Bear OB
line 595:9
Trigger
(showShapes) && (bearObNew)
Value
globalBearObHi
Deps
bearObNew:var, showShapes:input
Extreme Bid
line 610:9
Trigger
(showShapes) && (extremeUp)
Value
compositeOBI
Deps
extremeUp:var, showShapes:input
Extreme Ask
line 620:9
Trigger
(showShapes) && (extremeDn)
Value
compositeOBI
Deps
extremeDn:var, showShapes:input
311_ob_global.flowscript
source path: kscripts/perfected/311_ob_global.flowscript · sha256:fc43a932088e045a590e6238d11c8e5f62794ecd0327ec23e36e8aabba0b3cc8
//@version=2
// ============================================================================
// OB Global V2 — Production-Quality Global Orderbook + Order Block Fusion
// Author: I (@Iopl147u) | Perfected by: kScript Perfection Engineer
// Tags: FLOW, #orderblock, #global, #orderbook, #composite, #microstructure
//
// Global orderbook analysis fused with Order Block detection across multiple
// depth bands and composite OBI. Identifies the largest institutional
// accumulation zones while validating them via multi-depth orderbook imbalance
// to produce high-conviction supply/demand zones.
//
// FORMULA FOUNDATION:
// 1. Order Block (OB) Detection: Bullish OB = last bearish candle before
// displacement ≥ minMove × ATR; Bearish OB = last bullish candle before
// displacement ≥ minMove × ATR. Global lookback captures the largest zones.
// 2. Order Book Imbalance (OBI): OBI = (BidVol − AskVol) / (BidVol + AskVol)
// per Cont, Kukanov & Stoikov (2014). Multi-depth composite across 1%, 2.5%,
// 5%, 10% depth bands per Xu, Gould & Howison (2019).
// 3. Composite OBI: Σ w_i × OBI_i / Σ w_i with geometric decay weights.
// This significantly improves short-horizon prediction vs. top-of-book alone.
// 4. Z-Score Normalization: z = (x − μ) / σ over rolling window, standardizing
// OB displacement and OBI for cross-asset comparison.
// 5. Regime Segmentation: Buy-heavy (+1/3, +1), Neutral (−1/3, +1/3),
// Sell-heavy (−1, −1/3) per Cartea, Donnelly & Jaimungal (2018).
//
// RESEARCH BASIS:
// • Cont, Kukanov & Stoikov (2014), J. Financial Econometrics 12(1), 47–88.
// OFI linearly predicts price changes; slope ∝ 1/depth.
// • Xu, Gould & Howison (2019), arXiv:1907.06230. Multi-level OFI with
// decaying weights significantly improves short-horizon prediction.
// • Cartea, Donnelly & Jaimungal (2018), Appl. Math. Finance 25(1), 1–35.
// Three-regime segmentation predicts future price direction.
// • Gould & Bonart (2016), Market Microstructure & Liquidity 2(1), 1650006.
// Queue imbalance as one-tick-ahead predictor.
// • Campbell, Ramadorai & Vuolteenaho (2005), J. Financial Economics 65(1).
// Institutional order flow and price impact.
// • Madhavan (2000), J. Financial Markets 3(3), 205–258. Market microstructure
// survey; liquidity predicts future price moves.
// ============================================================================
define(
title="OB Global V2",
position="onchart",
axis=false
)
// ------------------------------------------------------------------------------
// User Inputs — grouped and constrained per production spec
// ------------------------------------------------------------------------------
// --- Order Block Detection ---
var lookback = input(
name="lookback",
type="number",
defaultValue=100,
label="Global Lookback",
constraints={min: 10, max: 500, step: 5},
group="Order Block"
)
var minMove = input(
name="minMove",
type="number",
defaultValue=2.0,
label="Min Displacement (ATR mult)",
constraints={min: 0.1, max: 10.0, step: 0.1},
group="Order Block"
)
var atrLen = input(
name="atrLen",
type="number",
defaultValue=14,
label="ATR Length",
constraints={min: 2, max: 50, step: 1},
group="Order Block"
)
var showMid = input(
name="showMid",
type="boolean",
defaultValue=true,
label="Show OB Midline",
group="Order Block"
)
var fillZones = input(
name="fillZones",
type="boolean",
defaultValue=true,
label="Fill OB Zones",
group="Order Block"
)
// --- Orderbook Depth ---
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="Orderbook"
)
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="Orderbook"
)
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="Orderbook"
)
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="Orderbook"
)
var useDepthWeighting = input(
name="useDepthWeighting",
type="boolean",
defaultValue=true,
label="Use Depth-Decaying Weights",
group="Orderbook"
)
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="Orderbook"
)
// --- Z-Score ---
var zScoreLen = input(
name="zScoreLen",
type="number",
defaultValue=50,
label="Z-Score Lookback",
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 showOBI = input(
name="showOBI",
type="boolean",
defaultValue=true,
label="Show Composite OBI",
group="Display"
)
var showIndividual = input(
name="showIndividual",
type="boolean",
defaultValue=false,
label="Show Individual Depth Lines",
group="Display"
)
var showShapes = input(
name="showShapes",
type="boolean",
defaultValue=true,
label="Show OB Activation Shapes",
group="Display"
)
var showZScore = input(
name="showZScore",
type="boolean",
defaultValue=true,
label="Show Z-Score Line",
group="Display"
)
var showGuides = input(
name="showGuides",
type="boolean",
defaultValue=true,
label="Show Threshold Guide Lines",
group="Display"
)
// --- Colors ---
var bullColor = input(
name="bullColor",
type="color",
defaultValue="#26a69a",
label="Bullish OB Color",
group="Colors"
)
var bearColor = input(
name="bearColor",
type="color",
defaultValue="#ef5350",
label="Bearish OB Color",
group="Colors"
)
var bidColor = input(
name="bidColor",
type="color",
defaultValue="#00e676",
label="Bid-Dominant Color",
group="Colors"
)
var askColor = input(
name="askColor",
type="color",
defaultValue="#ff1744",
label="Ask-Dominant Color",
group="Colors"
)
var neutralColor = input(
name="neutralColor",
type="color",
defaultValue="#9e9e9e",
label="Neutral Color",
group="Colors"
)
// ------------------------------------------------------------------------------
// Data Sources & NaN Guard
// ------------------------------------------------------------------------------
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 best practice)
if (isnan(px[0])) {
return
}
// ------------------------------------------------------------------------------
// Global Order Block Detection (wide-lookback displacement)
// ------------------------------------------------------------------------------
timeseries rng = bars.high - bars.low
timeseries atrV = sma(rng, atrLen)
// Rolling extremes in the global lookback window
timeseries hiAll = highest(bars.high, lookback)
timeseries loAll = lowest(bars.low, lookback)
timeseries rangeAll = hiAll - loAll
// Identify largest displacement: highest close vs lowest close in the window
timeseries lowestClose = lowest(bars.close, lookback)
timeseries highestClose = highest(bars.close, lookback)
timeseries globalMove = highestClose - lowestClose
timeseries atrMultiple = atrV > 0 ? globalMove / atrV : 0.0
// Candle polarity
var isBull = bars.close > bars.open ? 1 : -1
// Displacement: current bar displacement vs ATR
timeseries move = math.abs(bars.close - bars.close[1])
var displacement = move >= atrV * minMove ? 1 : 0
// Global OB levels — track the most significant OB in the lookback
static globalBullObHi = 0.0
static globalBullObLo = 0.0
static globalBearObHi = 0.0
static globalBearObLo = 0.0
static globalBullActive = false
static globalBearActive = false
static bullObAge = 0
static bearObAge = 0
static lastBarIndex = 0
var currentBarIndex = bar_index[0]
if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
lastBarIndex = currentBarIndex
if (globalBullActive) {
bullObAge = bullObAge + 1
}
if (globalBearActive) {
bearObAge = bearObAge + 1
}
}
// Detect new global OB — only the largest displacement within lookback
if (displacement && isBull == 1 && bars.close[1] < bars.open[1]) {
globalBullObHi = bars.high[1]
globalBullObLo = bars.low[1]
globalBullActive = true
bullObAge = 0
}
if (displacement && isBull == -1 && bars.close[1] > bars.open[1]) {
globalBearObHi = bars.high[1]
globalBearObLo = bars.low[1]
globalBearActive = true
bearObAge = 0
}
// Mitigate (deactivate) when price closes through the zone
if (globalBullActive && px < globalBullObLo) {
globalBullActive = false
}
if (globalBearActive && px > globalBearObHi) {
globalBearActive = false
}
// Global validation flags
var bullValid = atrMultiple >= minMove && bars.close > lowestClose && globalBullActive
var bearValid = atrMultiple >= minMove && bars.close < highestClose && globalBearActive
// Midpoints for the OB zones
timeseries bullObMid = (globalBullObHi + globalBullObLo) / 2.0
timeseries bearObMid = (globalBearObHi + globalBearObLo) / 2.0
// ------------------------------------------------------------------------------
// Order Book Depth Aggregation (Cont et al. 2014; Xu et al. 2019)
// ------------------------------------------------------------------------------
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
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
// ------------------------------------------------------------------------------
// Z-Score Normalization
// ------------------------------------------------------------------------------
var obiMean = sma(source=compositeOBI, period=zScoreLen)
var obiStd = stddev(source=compositeOBI, period=zScoreLen)
var obiZ = (obiStd > 0 && useZScore) ? (compositeOBI - obiMean) / obiStd : 0.0
// Z-Score of global displacement (standardized displacement strength)
var dispMean = sma(source=globalMove, period=zScoreLen)
var dispStd = stddev(source=globalMove, period=zScoreLen)
var dispZ = (dispStd > 0 && useZScore) ? (globalMove - dispMean) / dispStd : 0.0
// ------------------------------------------------------------------------------
// Regime Detection (Cartea, Donnelly & Jaimungal 2018 three-segment model)
// ------------------------------------------------------------------------------
var regime = 0 // 0 = neutral, 1 = bull, -1 = bear
var extremeRegime = 0 // 0 = normal, 1 = extreme bull, -1 = extreme bear
if (compositeOBI >= bullThresh) {
regime = 1
} else if (compositeOBI <= bearThresh) {
regime = -1
}
if (compositeOBI >= extremeThresh) {
extremeRegime = 1
} else if (compositeOBI <= -extremeThresh) {
extremeRegime = -1
}
// Regime color for OB zones
var obiBullColor = opacity(bullColor, 60)
var obiBearColor = opacity(bearColor, 60)
// ------------------------------------------------------------------------------
// Static State Tracking (Session-level persistence)
// ------------------------------------------------------------------------------
static sessionHighOBI = -999999.0
static sessionLowOBI = 999999.0
static extremeBidCount = 0
static extremeAskCount = 0
static totalOBCount = 0
static sessionBullCount = 0
static sessionBearCount = 0
static regimeChangeCount = 0
static lastRegime = 0
if (!isnan(currentBarIndex) && currentBarIndex == lastBarIndex) {
// On new bar, update session tracking
if (compositeOBI > sessionHighOBI) {
sessionHighOBI = compositeOBI
}
if (compositeOBI < sessionLowOBI) {
sessionLowOBI = compositeOBI
}
if (extremeRegime == 1) {
extremeBidCount = extremeBidCount + 1
} else if (extremeRegime == -1) {
extremeAskCount = extremeAskCount + 1
}
var currentRegime = regime
if (lastRegime != currentRegime) {
lastRegime = currentRegime
regimeChangeCount = regimeChangeCount + 1
}
}
// Track OB formations
if (displacement && isBull == 1 && bars.close[1] < bars.open[1] && (!globalBullActive || bullObAge == 0)) {
totalOBCount = totalOBCount + 1
sessionBullCount = sessionBullCount + 1
}
if (displacement && isBull == -1 && bars.close[1] > bars.open[1] && (!globalBearActive || bearObAge == 0)) {
totalOBCount = totalOBCount + 1
sessionBearCount = sessionBearCount + 1
}
// ------------------------------------------------------------------------------
// Plots — OB Zones, OBI Lines, Z-Score, Shapes, Guides
// ------------------------------------------------------------------------------
// Zero line for OBI
if (showOBI) {
hline(value=0, color="#ffffff30", width=1)
}
// Threshold guide lines
if (showGuides && showOBI) {
hline(value=bullThresh, color=opacity(bullColor, 30), width=1)
hline(value=bearThresh, color=opacity(bearColor, 30), width=1)
hline(value=extremeThresh, color=opacity(bidColor, 20), width=1)
hline(value=-extremeThresh, color=opacity(askColor, 20), width=1)
}
// --- Global Bullish OB Zone (regime-colored by OBI) ---
if (fillZones && bullValid) {
var bullZoneColor = regime == 1 ? obiBullColor : (regime == -1 ? opacity(bearColor, 30) : opacity(bullColor, 40))
plotLine(
value=[globalBullObLo, globalBullObHi],
colors=[bullZoneColor, bullZoneColor],
width=1,
fill=true,
label=["Global Bull OB Low", "Global Bull OB High"],
desc=["Global bullish order block support zone (regime-colored by OBI)", "Global bullish order block resistance top"]
)
}
// --- Global Bearish OB Zone (regime-colored by OBI) ---
if (fillZones && bearValid) {
var bearZoneColor = regime == -1 ? obiBearColor : (regime == 1 ? opacity(bullColor, 30) : opacity(bearColor, 40))
plotLine(
value=[globalBearObLo, globalBearObHi],
colors=[bearZoneColor, bearZoneColor],
width=1,
fill=true,
label=["Global Bear OB Low", "Global Bear OB High"],
desc=["Global bearish order block support floor (regime-colored by OBI)", "Global bearish order block resistance zone"]
)
}
// --- OB Midlines ---
if (showMid && bullValid) {
plotLine(
value=bullObMid,
colors=[bullColor],
width=2,
label=["Global Bull OB Mid"],
desc=["Midpoint of the largest bullish order block in the global window"]
)
}
if (showMid && bearValid) {
plotLine(
value=bearObMid,
colors=[bearColor],
width=2,
label=["Global Bear OB Mid"],
desc=["Midpoint of the largest bearish order block in the global window"]
)
}
// --- Composite OBI Line (regime-colored) ---
if (showOBI) {
plotLine(
value=compositeOBI,
width=2,
colors=[bullColor, bearColor, neutralColor],
colorIndex=regime == 1 ? 0 : (regime == -1 ? 1 : 2),
label=["Composite OBI"],
desc=["Depth-weighted composite OBI (4 bands). Regime: bull/bear/neutral."],
fill=true
)
}
// --- Individual depth lines (optional, for granular analysis) ---
if (showIndividual) {
plotLine(
value=obi1,
width=1,
colors=[opacity(bullColor, 50)],
label=["OBI 1%"],
desc=["Order Book Imbalance at 1% depth (shallow book, top-of-book)"]
)
plotLine(
value=obi2,
width=1,
colors=[opacity(bullColor, 40)],
label=["OBI 2.5%"],
desc=["Order Book Imbalance at 2.5% depth (near-term liquidity)"]
)
plotLine(
value=obi3,
width=1,
colors=[opacity(askColor, 40)],
label=["OBI 5%"],
desc=["Order Book Imbalance at 5% depth (medium-term absorption)"]
)
plotLine(
value=obi4,
width=1,
colors=[opacity(askColor, 50)],
label=["OBI 10%"],
desc=["Order Book Imbalance at 10% depth (deep book, structural level)"]
)
}
// --- Z-Score Line ---
if (showZScore) {
plotLine(
value=obiZ,
width=1,
colors=[bidColor, askColor, neutralColor],
colorIndex=obiZ > 1.0 ? 0 : (obiZ < -1.0 ? 1 : 2),
label=["OBI Z-Score"],
desc=["Z-score of composite OBI (±1 = 1 std dev from mean)"]
)
}
// --- OB Activation Shapes ---
if (showShapes) {
var bullObNew = displacement && isBull == 1 && bars.close[1] < bars.open[1]
var bearObNew = displacement && isBull == -1 && bars.close[1] > bars.open[1]
if (bullObNew) {
plotShape(
value=globalBullObLo,
shape="triangleup",
color=bullColor,
width=3,
label=["Global Bull OB"],
desc=["Global Bullish Order Block formed — largest displacement in window"]
)
}
if (bearObNew) {
plotShape(
value=globalBearObHi,
shape="triangledown",
color=bearColor,
width=3,
label=["Global Bear OB"],
desc=["Global Bearish Order Block formed — largest displacement in window"]
)
}
// Extreme OBI shapes
var extremeUp = compositeOBI >= extremeThresh && !isnan(compositeOBI[1]) && compositeOBI[1] < extremeThresh
var extremeDn = compositeOBI <= -extremeThresh && !isnan(compositeOBI[1]) && compositeOBI[1] > -extremeThresh
if (extremeUp) {
plotShape(
value=compositeOBI,
shape="diamond",
color=bidColor,
width=4,
label=["Extreme Bid"],
desc=["Extreme bid pressure detected — deep book buy-heavy imbalance"]
)
}
if (extremeDn) {
plotShape(
value=compositeOBI,
shape="diamond",
color=askColor,
width=4,
label=["Extreme Ask"],
desc=["Extreme ask pressure detected — deep book sell-heavy imbalance"]
)
}
}
// ------------------------------------------------------------------------------
// Regime Table (last bar only)
// ------------------------------------------------------------------------------
if (isLastBar) {
var regimeText = regime == 1 ? "BULL" : (regime == -1 ? "BEAR" : "NEUTRAL")
var regimeTextColor = regime == 1 ? bullColor : (regime == -1 ? bearColor : neutralColor)
plotTable(
data=[
["OB Global V2", regimeText],
["Composite OBI", compositeOBI[0]],
["OBI Z-Score", obiZ[0]],
["Disp Z-Score", dispZ[0]],
["Global Bull OB", globalBullActive ? "YES" : "NO"],
["Global Bear OB", globalBearActive ? "YES" : "NO"],
["Session High OBI", sessionHighOBI],
["Session Low OBI", sessionLowOBI],
["Extreme Bid Count", extremeBidCount],
["Extreme Ask Count", extremeAskCount],
["Regime Changes", regimeChangeCount]
],
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
)
}