Perfected FlowScript
Depth Change Bubbles
Depth Change Bubbles — Perfected Edition is indexed as 134_depth_change_bubbles.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
16.3 KB
Lines
493
Native Signal Candidates
8 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Bid Build
line 366:5
Trigger
(bidChgZ > threshold)
Value
l
Deps
bidChgZ:timeseries, threshold:input
Ask Build
line 379:5
Trigger
(askChgZ > threshold)
Value
h
Deps
askChgZ:timeseries, threshold:input
Bid Withdraw
line 392:5
Trigger
(bidChgZ < -threshold)
Value
h
Deps
bidChgZ:timeseries, threshold:input
Ask Withdraw
line 405:5
Trigger
(askChgZ < -threshold)
Value
l
Deps
askChgZ:timeseries, threshold:input
Bid Spike
line 418:9
Trigger
(showShapes) && (bidExtreme)
Value
l
Deps
bidExtreme:var, showShapes:input
Ask Spike
line 428:9
Trigger
(showShapes) && (askExtreme)
Value
h
Deps
askExtreme:var, showShapes:input
Bull Regime
line 438:9
Trigger
(showShapes) && (crossBull)
Value
l
Deps
crossBull:var, showShapes:input
Bear Regime
line 448:9
Trigger
(showShapes) && (crossBear)
Value
h
Deps
crossBear:var, showShapes:input
134_depth_change_bubbles.flowscript
source path: kscripts/perfected/134_depth_change_bubbles.flowscript · sha256:ddec552b2f513c808e048ebf849d6076781b3b1261301d9c174e760ebabd6e7b
//@version=2
// ============================================================================
// Depth Change Bubbles — Perfected Edition
// Author: H (@howaitorumu) | Enhanced by kScript Perfection Engineer
// Tags: CORE, ADVANCED, #orderbook, #depth, #liquidity, #microstructure, #bubbles
//
// Production-quality orderbook depth change visualization with multi-level
// z-score standardization, bid/ask directional coloring, and opacity-scaled
// bubbles. Tracks standardized depth changes across configurable depth bands
// to detect significant liquidity additions (support/resistance building).
//
// Research papers underpinning this design:
// 1. Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events":
// OFI model shows orderbook events drive price changes. The script's depth
// change bubbles highlight the most significant liquidity additions that
// signal directional intent. Price impact slope ∝ 1/depth.
// 2. Xu, Gould & Howison (2019), "Multi-Level Order-Flow Imbalance":
// multi-level OFI improves out-of-sample prediction vs. L1-only. The
// script's multi-depth aggregation (1%, 2.5%, 5%, 10%) validates deeper
// book levels as containing meaningful predictive information.
// 3. Order Book Filtration and Directional Signal Extraction (2025):
// OBI values close to ±1 indicate extreme imbalance predictive of price
// movement direction. Depth changes that push OBI toward ±1 are the most
// significant and are flagged with the largest bubbles.
// 4. Cartea, Donnelly & Jaimungal (2018), "Enhancing Trading Strategies with
// Order Book Signals": three-regime segmentation (Sell-heavy, Neutral,
// Buy-heavy) predicts future price moves. The script's depth imbalance
// line maps to this regime classification.
// 5. Gould & Bonart (2016), "Queue Imbalance as a One-Tick-Ahead Price
// Predictor": queue imbalance logistic regression for next-tick direction
// prediction validates bid/ask depth changes as directional signals.
// ============================================================================
define(
title="Depth Change Bubbles — Perfected Edition",
position="onchart",
axis=false
)
// -----------------------------------------------------------------------------
// 1. USER INPUTS — grouped with 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 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"
)
// --- Z-Score Settings ---
var zLen = input(
name="zLen",
type="number",
defaultValue=30,
label="Z-Score Lookback",
constraints={min: 5, max: 200, step: 1},
group="Z-Score"
)
var threshold = input(
name="threshold",
type="number",
defaultValue=2.0,
label="Bubble Threshold (std)",
constraints={min: 0.5, max: 5.0, step: 0.1},
group="Z-Score"
)
var maxSize = input(
name="maxSize",
type="number",
defaultValue=8,
label="Max Bubble Size",
constraints={min: 1, max: 20, step: 1},
group="Z-Score"
)
// --- Display ---
var showLine = input(
name="showLine",
type="boolean",
defaultValue=true,
label="Show Depth Imbalance Line",
group="Display"
)
var showShapes = input(
name="showShapes",
type="boolean",
defaultValue=true,
label="Show Signal Shapes",
group="Display"
)
var showBgBands = input(
name="showBgBands",
type="boolean",
defaultValue=true,
label="Show Z-Score Bands",
group="Display"
)
var showTable = input(
name="showTable",
type="boolean",
defaultValue=true,
label="Show Session Table",
group="Display"
)
// --- Colors ---
var bullColor = input(
name="bullColor",
type="color",
defaultValue="#26a69a",
label="Bid Increase Color",
group="Colors"
)
var bearColor = input(
name="bearColor",
type="color",
defaultValue="#ef5350",
label="Ask Increase Color",
group="Colors"
)
var neutralColor = input(
name="neutralColor",
type="color",
defaultValue="#9e9e9e",
label="Neutral Color",
group="Colors"
)
// -----------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// -----------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries h = bars.high
timeseries l = bars.low
timeseries book = source("orderbook", currentSymbol, currentExchange)
if (isnan(h[0]) || isnan(l[0])) {
return
}
// -----------------------------------------------------------------------------
// 3. MULTI-DEPTH BID/ASK SUMS (Xu et al. 2019)
// -----------------------------------------------------------------------------
// CRITICAL: pass depth as float percentage directly. Do NOT use math.floor()
// or math.max() which incorrectly truncate to integer levels (see pilot
// 001_order_book_pressure for the bug fix documentation).
//
// Multi-depth bands (1%, 2.5%, 5%, 10%) operationalize Cont et al. (2014)
// finding that price impact slope is inversely proportional to depth.
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
// -----------------------------------------------------------------------------
// 4. COMPOSITE DEPTH (Depth-Weighted per Xu et al. 2019)
// -----------------------------------------------------------------------------
// w_i = decay^(i−1) for i = 1,2,3,4.
// Composite depth = Σ w_i × depth_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 compositeBid = wSum > 0 ? (w1 * bids1 + w2 * bids2 + w3 * bids3 + w4 * bids4) / wSum : 0.0
var compositeAsk = wSum > 0 ? (w1 * asks1 + w2 * asks2 + w3 * asks3 + w4 * asks4) / wSum : 0.0
// -----------------------------------------------------------------------------
// 5. DEPTH CHANGE & Z-SCORES
// -----------------------------------------------------------------------------
// Depth change = current composite depth minus previous composite depth.
// Z-score standardizes this change against its rolling history.
timeseries bidChg = compositeBid - nz(compositeBid[1])
timeseries askChg = compositeAsk - nz(compositeAsk[1])
// Bid depth change z-score
timeseries bidChgMean = sma(bidChg, zLen)
timeseries bidChgStd = stddev(bidChg, zLen)
timeseries bidChgZ = (bidChg - bidChgMean) / max(bidChgStd, 1e-9)
// Ask depth change z-score
timeseries askChgMean = sma(askChg, zLen)
timeseries askChgStd = stddev(askChg, zLen)
timeseries askChgZ = (askChg - askChgMean) / max(askChgStd, 1e-9)
// Depth imbalance (bid change z minus ask change z)
timeseries imbalance = bidChgZ - askChgZ
// -----------------------------------------------------------------------------
// 6. BUBBLE SIZE & OPACITY SCALING
// -----------------------------------------------------------------------------
// Bubble size scales with z-score magnitude, clamped to maxSize.
// Opacity scales with z-score extremity: more extreme = more opaque.
// Per Cont et al. (2014), deeper books absorb imbalance with less price
// movement, so we weight deeper levels more heavily in the composite.
timeseries bidBubbleSize = min(abs(bidChgZ) * 2.5, maxSize)
timeseries askBubbleSize = min(abs(askChgZ) * 2.5, maxSize)
var maxZ = maxSize / 2.5
timeseries bidOpacity = min(abs(bidChgZ) / maxZ, 1.0)
timeseries askOpacity = min(abs(askChgZ) / maxZ, 1.0)
// -----------------------------------------------------------------------------
// 7. REGIME DETECTION (Cartea et al. 2018 three-segment model)
// -----------------------------------------------------------------------------
// Buy-heavy: imbalance > +1/3 of maxZ
// Neutral: between -1/3 and +1/3 of maxZ
// Sell-heavy: imbalance < -1/3 of maxZ
var regimeThreshold = maxZ / 3.0
var regime = 0 // 0 = neutral, 1 = bull, -1 = bear
if (imbalance >= regimeThreshold) {
regime = 1
} else if (imbalance <= -regimeThreshold) {
regime = -1
}
// -----------------------------------------------------------------------------
// 8. ALERT CONDITIONS
// -----------------------------------------------------------------------------
var bidExtreme = bidChgZ > threshold && bidChgZ[1] <= threshold
var askExtreme = askChgZ > threshold && askChgZ[1] <= threshold
var bidDrop = bidChgZ < -threshold && bidChgZ[1] >= -threshold
var askDrop = askChgZ < -threshold && askChgZ[1] >= -threshold
// Regime transition signals
var crossBull = imbalance >= regimeThreshold && imbalance[1] < regimeThreshold
var crossBear = imbalance <= -regimeThreshold && imbalance[1] > -regimeThreshold
// -----------------------------------------------------------------------------
// 9. STATIC STATE TRACKING (Session-level persistence)
// -----------------------------------------------------------------------------
static sessionHighBidZ = -999999.0
static sessionLowBidZ = 999999.0
static sessionHighAskZ = -999999.0
static sessionLowAskZ = 999999.0
static sessionHighImbalance = -999999.0
static sessionLowImbalance = 999999.0
static bidBubbleCount = 0
static askBubbleCount = 0
static regimeChangeCount = 0
static lastRegime = 0
static lastBarIndex = 0
var currentBarIndex = bar_index[0]
if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
lastBarIndex = currentBarIndex
if (bidChgZ[0] > sessionHighBidZ) {
sessionHighBidZ = bidChgZ[0]
}
if (bidChgZ[0] < sessionLowBidZ) {
sessionLowBidZ = bidChgZ[0]
}
if (askChgZ[0] > sessionHighAskZ) {
sessionHighAskZ = askChgZ[0]
}
if (askChgZ[0] < sessionLowAskZ) {
sessionLowAskZ = askChgZ[0]
}
if (imbalance[0] > sessionHighImbalance) {
sessionHighImbalance = imbalance[0]
}
if (imbalance[0] < sessionLowImbalance) {
sessionLowImbalance = imbalance[0]
}
if (bidChgZ[0] > threshold) {
bidBubbleCount = bidBubbleCount + 1
}
if (askChgZ[0] > threshold) {
askBubbleCount = askBubbleCount + 1
}
if (lastRegime != regime) {
lastRegime = regime
regimeChangeCount = regimeChangeCount + 1
}
}
// -----------------------------------------------------------------------------
// 10. PLOTTING
// -----------------------------------------------------------------------------
// --- Z-Score Bands (horizontal guides) ---
if (showBgBands) {
hline(value=0, color="#ffffff30", width=1)
hline(value=threshold, color=transparency(bullColor, 40), width=1)
hline(value=-threshold, color=transparency(bearColor, 40), width=1)
}
// --- Depth Imbalance Line (regime-coded) ---
if (showLine) {
var lineColor = imbalance >= 0 ? bullColor : bearColor
plotLine(
value=imbalance,
width=2,
colors=[lineColor],
label=["Depth Imbalance"],
desc=["Depth change imbalance (bidChgZ - askChgZ). Positive = bid-side depth building."]
)
}
// --- Bid Depth Bubbles (green at lows = support building) ---
if (bidChgZ > threshold) {
var bop = 30 + round(70 * bidOpacity)
plotShape(
value=l,
shape="circle",
color=transparency(bullColor, bop),
width=bidBubbleSize,
label=["Bid Build"],
desc=["Bid-side depth increase (z=" + bidChgZ + ") — support building at " + depth1 + "-" + depth4 + "% depth"]
)
}
// --- Ask Depth Bubbles (red at highs = resistance building) ---
if (askChgZ > threshold) {
var aop = 30 + round(70 * askOpacity)
plotShape(
value=h,
shape="circle",
color=transparency(bearColor, aop),
width=askBubbleSize,
label=["Ask Build"],
desc=["Ask-side depth increase (z=" + askChgZ + ") — resistance building at " + depth1 + "-" + depth4 + "% depth"]
)
}
// --- Bid Depth Drop Bubbles (bid liquidity withdrawal) ---
if (bidChgZ < -threshold) {
var bop2 = 30 + round(70 * bidOpacity)
plotShape(
value=h,
shape="circle",
color=transparency(neutralColor, bop2),
width=bidBubbleSize,
label=["Bid Withdraw"],
desc=["Bid-side depth withdrawal (z=" + bidChgZ + ") — support being pulled"]
)
}
// --- Ask Depth Drop Bubbles (ask liquidity withdrawal) ---
if (askChgZ < -threshold) {
var aop2 = 30 + round(70 * askOpacity)
plotShape(
value=l,
shape="circle",
color=transparency(neutralColor, aop2),
width=askBubbleSize,
label=["Ask Withdraw"],
desc=["Ask-side depth withdrawal (z=" + askChgZ + ") — resistance being pulled"]
)
}
// --- Signal Shapes (extreme events and regime transitions) ---
if (showShapes) {
if (bidExtreme) {
plotShape(
value=l,
shape="triangleup",
color=bullColor,
width=3,
label=["Bid Spike"],
desc=["Extreme bid-side depth increase (z=" + bidChgZ + ") — strong support building"]
)
}
if (askExtreme) {
plotShape(
value=h,
shape="triangledown",
color=bearColor,
width=3,
label=["Ask Spike"],
desc=["Extreme ask-side depth increase (z=" + askChgZ + ") — strong resistance building"]
)
}
if (crossBull) {
plotShape(
value=l,
shape="diamond",
color=bullColor,
width=3,
label=["Bull Regime"],
desc=["Depth imbalance crossed into bullish regime — bid-side building dominance"]
)
}
if (crossBear) {
plotShape(
value=h,
shape="diamond",
color=bearColor,
width=3,
label=["Bear Regime"],
desc=["Depth imbalance crossed into bearish regime — ask-side building dominance"]
)
}
}
// -----------------------------------------------------------------------------
// 11. SESSION TABLE (last bar only)
// -----------------------------------------------------------------------------
if (isLastBar && showTable) {
var regimeText = regime == 1 ? "BID-HEAVY" : (regime == -1 ? "ASK-HEAVY" : "NEUTRAL")
var regimeTextColor = regime == 1 ? bullColor : (regime == -1 ? bearColor : neutralColor)
plotTable(
data=[
["Depth Change Bubbles — Perfected", regimeText],
["Bid Depth Z", bidChgZ[0]],
["Ask Depth Z", askChgZ[0]],
["Imbalance", imbalance[0]],
["Session High Bid Z", sessionHighBidZ],
["Session Low Bid Z", sessionLowBidZ],
["Session High Ask Z", sessionHighAskZ],
["Session Low Ask Z", sessionLowAskZ],
["Bid Bubbles", bidBubbleCount],
["Ask Bubbles", askBubbleCount],
["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
)
}