Perfected FlowScript
iceberg bubble
Iceberg Bubble V2 is indexed as 261_iceberg_bubble.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
14.4 KB
Lines
328
Native Signal Candidates
3 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Iceberg Bid
line 296:9
Trigger
(showShapes) && (iceBid && iceExtreme)
Value
px - (px * 0.002)
Deps
iceBid:var, iceExtreme:var, showShapes:input
Iceberg Ask
line 307:9
Trigger
(showShapes) && (iceAsk && iceExtreme)
Value
px + (px * 0.002)
Deps
iceAsk:var, iceExtreme:var, showShapes:input
Absorption
line 318:9
Trigger
(showShapes) && (iceExtreme && !iceBid && !iceAsk)
Value
px
Deps
iceAsk:var, iceBid:var, iceExtreme:var, showShapes:input
261_iceberg_bubble.flowscript
source path: kscripts/perfected/261_iceberg_bubble.flowscript · sha256:4990a761ecef90a6d168c3909ce3a225ecef4714cc777ceb2a8fed6aae5884fa
//@version=2
// ============================================================================
// Iceberg Bubble V2 — Production-Quality Hidden Liquidity Detector
// Author: S (@Sufian Bout) | Perfected by: kScript Perfection Engineer
// Index: 261
// Tags: FLOW, #iceberg, #hidden-liquidity, #orderbook, #microstructure, #absorption
//
// Detects iceberg orders (hidden large orders) by monitoring passive absorption
// patterns, volume anomalies, and microstructure signatures. Combines orderbook
// depth imbalance, volume spike detection, and price-impact analysis to flag
// institutional iceberg activity.
//
// FORMULA FOUNDATION:
// 1. Depth Imbalance: DI = (BidVol − AskVol) / (BidVol + AskVol) [−1, +1]
// 2. Volume Anomaly Score: Z = (Vol − AvgVol) / StdDev(Vol) (σ-based spike)
// 3. Iceberg Signature: Large volume + minimal price movement + deep book
// imbalance. Per Biais, Hillion & Spatt (1995), iceberg orders show
// as repeated executions at same price with no book movement.
// 4. Absorption Score: A = VolAnomaly × (1 − |PriceImpact|/Range) × |DI|
// High absorption = large volume absorbed without price movement.
//
// RESEARCH BASIS:
// • Biais, Hillion & Spatt (1995), "An Empirical Analysis of the Limit Order
// Book", Review of Financial Studies 8(3), 363–408. Iceberg orders
// identified by repeated trade sizes and zero quote revision.
// • Harris (2003), "Trading and Exchanges", Oxford. Iceberg detection via
// trade clustering at same price level without depth depletion.
// • Cartea & Jaimungal (2013), "Modelling Asset Prices for Algorithmic Trading
// and Market-Making", J. Risk Finance. Passive absorption as a signature
// of large latent liquidity.
// • Hasbrouck (2007), "Empirical Market Microstructure", Oxford. Trade
// price impact inversely related to orderbook depth; minimal impact under
// heavy depth signals hidden liquidity.
// • Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events",
// J. Financial Econometrics 12(1), 47–88. Price-impact slope ∝ 1/depth.
// ============================================================================
define(
title="Iceberg Bubble V2",
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")
// --- Volume Anomaly ---
var volLookback = input(name="volLookback", type="number", defaultValue=20, label="Volume Lookback", constraints={min: 5, max: 100, step: 1}, group="Volume")
var volMul = input(name="volMul", type="number", defaultValue=2.0, label="Volume Spike Multiplier (σ)", constraints={min: 1.0, max: 5.0, step: 0.1}, group="Volume")
var minVolZ = input(name="minVolZ", type="number", defaultValue=1.5, label="Min Volume Z-Score", constraints={min: 0.5, max: 5.0, step: 0.1}, group="Volume")
// --- Iceberg Detection ---
var iceThresh = input(name="iceThresh", type="number", defaultValue=2.0, label="Iceberg Absorption Threshold", constraints={min: 0.5, max: 10.0, step: 0.1}, group="Iceberg")
var priceImpactMax = input(name="priceImpactMax", type="number", defaultValue=0.5, label="Max Price Impact (%)", constraints={min: 0.05, max: 2.0, step: 0.05}, group="Iceberg")
var lookback = input(name="lookback", type="number", defaultValue=20, label="Absorption Lookback", constraints={min: 5, max: 50, step: 1}, group="Iceberg")
// --- Smoothing ---
var smoothLen = input(name="smoothLen", type="number", defaultValue=5, label="EMA Smoothing Length", constraints={min: 1, max: 50, step: 1}, group="Smoothing")
// --- Display ---
var showDepthLine = input(name="showDepthLine", type="boolean", defaultValue=true, label="Show Depth Imbalance Line", group="Display")
var showBars = input(name="showBars", type="boolean", defaultValue=true, label="Show Absorption Histogram", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Iceberg Shapes", group="Display")
var showComposite = input(name="showComposite", type="boolean", defaultValue=true, label="Show Composite Score", group="Display")
var showVolAnomaly = input(name="showVolAnomaly", type="boolean", defaultValue=false, label="Show Volume Anomaly Line", 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 iceBidColor = input(name="iceBidColor", type="color", defaultValue="#00e676", label="Iceberg Bid Color", group="Colors")
var iceAskColor = input(name="iceAskColor", type="color", defaultValue="#ff1744", label="Iceberg Ask Color", group="Colors")
var anomalyColor = input(name="anomalyColor", type="color", defaultValue="#ffeb3b", label="Volume Anomaly Color", group="Colors")
// ------------------------------------------------------------------------------
// Data Sources & NaN Guard
// ------------------------------------------------------------------------------
timeseries priceBars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries px = priceBars.close
timeseries vol = priceBars.volume
timeseries book = source("orderbook", currentSymbol, currentExchange)
if (isnan(px[0])) {
return
}
// ------------------------------------------------------------------------------
// Order Book Aggregation (multi-depth per Cont et al. 2014)
// ------------------------------------------------------------------------------
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
// ------------------------------------------------------------------------------
// Depth Imbalance Computation (OBI formula, normalized to [−100, +100])
// ------------------------------------------------------------------------------
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 Imbalance
// ------------------------------------------------------------------------------
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 compositeDI = wSum > 0 ? (w1 * obi1 + w2 * obi2 + w3 * obi3 + w4 * obi4) / wSum : 0.0
// ------------------------------------------------------------------------------
// Volume Anomaly Scoring (Z-score of volume)
// ------------------------------------------------------------------------------
var avgVol = sma(vol, volLookback)
var stdVol = stddev(vol, volLookback)
var volZ = stdVol > 0 ? (vol - avgVol) / stdVol : 0.0
var volAnomaly = volZ > minVolZ ? volZ : 0.0
var volSpike = volZ >= volMul
// ------------------------------------------------------------------------------
// Price Impact Analysis (minimal impact = absorption signature)
// ------------------------------------------------------------------------------
var barRange = priceBars.high - priceBars.low
var avgRange = sma(barRange, lookback)
var avgRangeSafe = avgRange > 0 ? avgRange : 0.0001
// Price impact as percentage of typical range
var priceImpactPct = avgRangeSafe > 0 ? (barRange / avgRangeSafe) : 0.0
// Absorption score: high volume + low price impact + deep imbalance
// A = VolZ × (1 − impact/maxImpact) × |DI| / 100
var absorptionRaw = volZ * (1.0 - math.min(priceImpactPct, 1.0)) * (math.abs(compositeDI) / 100.0)
var absorptionScore = absorptionRaw > 0 ? absorptionRaw : 0.0
// ------------------------------------------------------------------------------
// Iceberg Detection (Biais et al. 1995 signature)
// ------------------------------------------------------------------------------
// Iceberg bid: volume anomaly + bid-heavy book + low price impact
// Iceberg ask: volume anomaly + ask-heavy book + low price impact
var iceBid = volSpike && compositeDI > 30.0 && priceImpactPct < priceImpactMax
var iceAsk = volSpike && compositeDI < -30.0 && priceImpactPct < priceImpactMax
var iceExtreme = absorptionScore >= iceThresh
// ------------------------------------------------------------------------------
// Smoothing
// ------------------------------------------------------------------------------
var smoothedDI = ema(compositeDI, smoothLen)
var smoothedAbsorption = ema(absorptionScore, smoothLen)
// ------------------------------------------------------------------------------
// Regime Detection
// ------------------------------------------------------------------------------
var regime = 0 // 0 = neutral, 1 = bid-heavy, -1 = ask-heavy
var extremeRegime = 0 // 0 = normal, 1 = extreme bid, -1 = extreme ask
if (smoothedDI >= 30.0) {
regime = 1
} else if (smoothedDI <= -30.0) {
regime = -1
}
if (smoothedDI >= 60.0) {
extremeRegime = 1
} else if (smoothedDI <= -60.0) {
extremeRegime = -1
}
// ------------------------------------------------------------------------------
// Static State Tracking (session-level persistence)
// ------------------------------------------------------------------------------
static lastRegime = 0
static regimeChangeCount = 0
static sessionHighDI = -999999.0
static sessionLowDI = 999999.0
static iceBidCount = 0
static iceAskCount = 0
static maxAbsorption = 0.0
static lastBarIndex = 0
var currentBarIndex = bar_index[0]
if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
lastBarIndex = currentBarIndex
if (compositeDI > sessionHighDI) {
sessionHighDI = compositeDI
}
if (compositeDI < sessionLowDI) {
sessionLowDI = compositeDI
}
if (lastRegime != regime) {
lastRegime = regime
regimeChangeCount = regimeChangeCount + 1
}
if (iceBid) {
iceBidCount = iceBidCount + 1
}
if (iceAsk) {
iceAskCount = iceAskCount + 1
}
if (absorptionScore > maxAbsorption) {
maxAbsorption = absorptionScore
}
}
// ------------------------------------------------------------------------------
// Plots — Multiple Visualization Types
// ------------------------------------------------------------------------------
// Zero line
hline(value=0, color="#ffffff30", width=1)
// Threshold guides
hline(value=30, color=opacity(bidColor, 30), width=1)
hline(value=-30, color=opacity(askColor, 30), width=1)
// Depth imbalance line (regime-colored with fill)
if (showDepthLine) {
plotLine(
value=smoothedDI,
width=2,
colors=[bidColor, askColor, neutralColor],
colorIndex=regime == 1 ? 0 : (regime == -1 ? 1 : 2),
label=["Depth Imbalance"],
desc=["Depth-weighted composite imbalance (bid+ / ask−)"],
fill=true
)
}
// Composite score line (absorption metric)
if (showComposite) {
plotLine(
value=smoothedAbsorption * 50.0,
width=1,
colors=[anomalyColor],
label=["Absorption Score"],
desc=["Normalized absorption score × 50 (iceberg signature strength)"]
)
}
// Volume anomaly line
if (showVolAnomaly) {
plotLine(
value=volAnomaly * 10.0,
width=1,
colors=[anomalyColor],
label=["Vol Anomaly"],
desc=["Volume Z-score × 10 (spike detector)"]
)
}
// Absorption histogram (bid/ask colored)
if (showBars) {
var barColor = absorptionScore >= iceThresh ? (regime == 1 ? iceBidColor : (regime == -1 ? iceAskColor : anomalyColor)) : neutralColor
plotBar(
value=absorptionScore * 50.0,
colors=[barColor, neutralColor],
colorIndex=absorptionScore >= iceThresh ? 0 : 1,
width=1,
label=["Absorption"],
desc=["Absorption score histogram — high bars = possible iceberg"]
)
}
// Iceberg shape markers
if (showShapes) {
// Bid iceberg
if (iceBid && iceExtreme) {
plotShape(
value=px - (px * 0.002),
shape="circle",
color=iceBidColor,
width=4,
label=["Iceberg Bid"],
desc=["Hidden bid iceberg detected: volume spike + bid absorption + low impact"]
)
}
// Ask iceberg
if (iceAsk && iceExtreme) {
plotShape(
value=px + (px * 0.002),
shape="circle",
color=iceAskColor,
width=4,
label=["Iceberg Ask"],
desc=["Hidden ask iceberg detected: volume spike + ask absorption + low impact"]
)
}
// Extreme absorption diamond
if (iceExtreme && !iceBid && !iceAsk) {
plotShape(
value=px,
shape="diamond",
color=anomalyColor,
width=3,
label=["Absorption"],
desc=["Extreme absorption event — investigate for hidden liquidity"]
)
}
}