Perfected FlowScript
DTS MTF Liquidity & Order Flow Fusion [15m]
DTS MTF Liquidity & Order Flow Fusion V2 is indexed as 208_dts_mtf_liquidity_order_flow_fusion_15m.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
18.6 KB
Lines
369
Native Signal Candidates
4 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Long Absorption
line 320:9
Trigger
(showAbsorption) && (absorbLong)
Value
compositeZSmooth
Deps
absorbLong:timeseries, showAbsorption:input
Short Absorption
line 330:9
Trigger
(showAbsorption) && (absorbShort)
Value
compositeZSmooth
Deps
absorbShort:timeseries, showAbsorption:input
Extreme Bull Fusion
line 343:5
Trigger
(showShapes && extremeBull)
Value
compositeZSmooth
Deps
extremeBull:var, showShapes:input
Extreme Bear Fusion
line 353:5
Trigger
(showShapes && extremeBear)
Value
compositeZSmooth
Deps
extremeBear:var, showShapes:input
208_dts_mtf_liquidity_order_flow_fusion_15m.flowscript
source path: kscripts/perfected/208_dts_mtf_liquidity_order_flow_fusion_15m.flowscript · sha256:31123e644b387fb867e8fd6157b0fb7e0f62a5818d08fc622e60aaf7471a4e3a
//@version=2
// ============================================================================
// DTS MTF Liquidity & Order Flow Fusion V2 — Multi-Timeframe Microstructure
// Author: D (@Dariusz Sulikowski) | Perfected by: kScript_Perfection_Engineer
// Tags: ADVANCED, CORE, FLOW, #orderflow, #cvd, #liquidations, #openinterest, #mtf
//
// A multi-timeframe market microstructure fusion tool combining three pillars:
// Sentiment (Open Interest delta), Liquidity (liquidation magnet zones), and
// Execution (CVD + order flow). With z-score normalization, regime detection,
// and absorption signal shapes.
//
// FORMULA FOUNDATION:
// 1. OI Delta Sentiment: dOI_t = OI_t − OI_{t−W} per Brunnermeier & Pedersen (2009).
// Four regimes: Long Build-up, Short Covering, Short Build-up, Long Liquidation.
// 2. Liquidation Spike Proxy: liqProxy = Volume / |Close − Open| per
// "Market Liquidity and Funding Liquidity" (2009). Extreme proxy = z-score > 2σ.
// 3. CVD: CVD_t = Σ_{i=0}^{W−1} Δ_{t−i} per Cont, Kukanov & Stoikov (2014).
// Z-score normalization: z_t = (CVD_t − μ_t) / σ_t per Zhao & Palomar (2018).
// 4. Absorption Detection: price tests liquidation zone + CVD anomaly + candle
// closes in opposite half per Easley, López de Prado & O'Hara (2012) VPIN.
// 5. Regime Segmentation: Composite z-score into Bullish (>+1σ), Neutral,
// Bearish (<−1σ) with extreme thresholds at ±2σ.
//
// RESEARCH BASIS:
// • Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events",
// J. Financial Econometrics 12(1), 47–88. OFI-price change linearity;
// absorption = flow without price movement.
// • Brunnermeier & Pedersen (2009), "Market Liquidity and Funding Liquidity",
// Review of Financial Studies 22(6), 2201–2238. Liquidity spirals; liquidation
// zones = structural imbalances; small shocks amplify into systemic crises.
// • Easley, López de Prado & O'Hara (2012), "Flow Toxicity and Liquidity in a
// High-Frequency World", Rev. Financial Studies 25(5), 1547–1574. VPIN =
// volume-synchronized buy-sell imbalance; anticipates flash crashes.
// • He & Manela (2022), "Fundamentals of Perpetual Futures". No-arbitrage
// perpetual pricing; past-return momentum explains futures-spot gap (R²>50%).
// • Chordia, Roll & Subrahmanyam (2002), "Order Imbalance, Liquidity, and
// Market Returns", J. Financial Economics 65(1), 111–130. Extreme imbalances
// predict return reversals; directly motivates divergence-threshold design.
// • Lee & Ready (1991), "Inferring Trade Direction from Intraday Data", J.
// Finance 46(2), 733–746. Tick-classification algorithm (85–93% accuracy).
// • Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint",
// IEEE Trans. Signal Processing. z-score event triggers at Δ = d × σ_z.
// ============================================================================
define(title="DTS MTF Liquidity & Order Flow Fusion V2", position="offchart", axis=true)
// ---------------------------------------------------------------------------
// 1. USER INPUTS — All grouped, all numeric inputs carry constraints
// ---------------------------------------------------------------------------
// -- Data Sources --
var oiSymbol = input(name="oiSymbol", type="string", defaultValue="BTCUSDT", label="OI Symbol", group="Data Sources")
var oiExchange = input(name="oiExchange", type="string", defaultValue="BINANCE_FUTURES", label="OI Exchange", group="Data Sources")
var spotSymbol = input(name="spotSymbol", type="string", defaultValue="BTCUSDT", label="Spot Symbol", group="Data Sources")
var spotExch = input(name="spotExch", type="string", defaultValue="BINANCE", label="Spot Exchange", group="Data Sources")
var perpSymbol = input(name="perpSymbol", type="string", defaultValue="BTCUSDT", label="Perp Symbol", group="Data Sources")
var perpExch = input(name="perpExch", type="string", defaultValue="BINANCE_FUTURES", label="Perp Exchange", group="Data Sources")
// -- OI Sentiment --
var oiPeriod = input(name="oiPeriod", type="number", defaultValue=4, label="OI Delta Period (bars)", constraints={min: 1, max: 24, step: 1}, group="OI Sentiment")
var oiZWindow = input(name="oiZWindow", type="number", defaultValue=50, label="OI Z-Score Window", constraints={min: 20, max: 200, step: 5}, group="OI Sentiment")
var oiSmooth = input(name="oiSmooth", type="number", defaultValue=3, label="OI EMA Smooth", constraints={min: 1, max: 20, step: 1}, group="OI Sentiment")
// -- Liquidation Detection --
var liqThreshold = input(name="liqThreshold", type="number", defaultValue=2.0, label="Liquidation Spike Threshold (sigma)", constraints={min: 1.0, max: 4.0, step: 0.5}, group="Liquidation")
var liqLookback = input(name="liqLookback", type="number", defaultValue=50, label="Liquidation Lookback", constraints={min: 20, max: 200, step: 5}, group="Liquidation")
var liqZWindow = input(name="liqZWindow", type="number", defaultValue=50, label="Liq Z-Score Window", constraints={min: 20, max: 200, step: 5}, group="Liquidation")
// -- CVD & Order Flow --
var cvdLen = input(name="cvdLen", type="number", defaultValue=20, label="CVD Lookback", constraints={min: 5, max: 100, step: 5}, group="Order Flow")
var cvdZWindow = input(name="cvdZWindow", type="number", defaultValue=50, label="CVD Z-Score Window", constraints={min: 20, max: 200, step: 5}, group="Order Flow")
var flowSmooth = input(name="flowSmooth", type="number", defaultValue=3, label="Flow EMA Smooth", constraints={min: 1, max: 20, step: 1}, group="Order Flow")
// -- Absorption --
var absorbTopPct = input(name="absorbTopPct", type="number", defaultValue=0.5, label="Absorption Close Position (0-1)", constraints={min: 0.1, max: 0.9, step: 0.05}, group="Absorption")
var absorbZThresh = input(name="absorbZThresh", type="number", defaultValue=2.0, label="Absorption CVD Z Threshold", constraints={min: 1.0, max: 4.0, step: 0.5}, group="Absorption")
// -- Composite & Regime --
var compZWindow = input(name="compZWindow", type="number", defaultValue=50, label="Composite Z Window", constraints={min: 20, max: 200, step: 5}, group="Composite")
var bullThresh = input(name="bullThresh", type="number", defaultValue=1.0, label="Bullish Threshold (sigma)", constraints={min: 0.5, max: 3.0, step: 0.5}, group="Composite")
var bearThresh = input(name="bearThresh", type="number", defaultValue=-1.0, label="Bearish Threshold (sigma)", constraints={min: -3.0, max: -0.5, step: 0.5}, group="Composite")
var extremeThresh = input(name="extremeThresh", type="number", defaultValue=2.0, label="Extreme Threshold (sigma)", constraints={min: 1.5, max: 4.0, step: 0.5}, group="Composite")
// -- Display --
var showOI = input(name="showOI", type="boolean", defaultValue=true, label="Show OI Sentiment Z", group="Display")
var showLiq = input(name="showLiq", type="boolean", defaultValue=true, label="Show Liquidation Z", group="Display")
var showCVD = input(name="showCVD", type="boolean", defaultValue=true, label="Show CVD Z", group="Display")
var showComposite = input(name="showComposite", type="boolean", defaultValue=true, label="Show Composite Flow", group="Display")
var showMagnet = input(name="showMagnet", type="boolean", defaultValue=true, label="Show Magnet Zones", group="Display")
var showAbsorption = input(name="showAbsorption", type="boolean", defaultValue=true, label="Show Absorption Signals", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Extreme Shapes", group="Display")
// -- Colors --
var upColor = input(name="upColor", type="color", defaultValue="#26a69a", label="Bullish Color", group="Colors")
var dnColor = input(name="dnColor", type="color", defaultValue="#ef5350", label="Bearish Color", group="Colors")
var liqColor = input(name="liqColor", type="color", defaultValue="#9c27b0", label="Liquidation Color", group="Colors")
var cvdColor = input(name="cvdColor", type="color", defaultValue="#2962ff", label="CVD Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#78909c", label="Neutral Color", group="Colors")
var compositeColor = input(name="compositeColor", type="color", defaultValue="#ffffff", label="Composite Color", group="Colors")
var absorbUpColor = input(name="absorbUpColor", type="color", defaultValue="#00e676", label="Long Absorption Color", group="Colors")
var absorbDnColor = input(name="absorbDnColor", type="color", defaultValue="#ff1744", label="Short Absorption Color", group="Colors")
// ---------------------------------------------------------------------------
// 2. DATA SOURCES — with isnan() guard on first external access
// ---------------------------------------------------------------------------
timeseries oiTS = open_interest(symbol=oiSymbol, exchange=oiExchange)
timeseries spotBars = ohlcv(symbol=spotSymbol, exchange=spotExch)
timeseries perpBars = ohlcv(symbol=perpSymbol, exchange=perpExch)
timeseries spotTaker = source("taker_volume", spotSymbol, spotExch)
timeseries perpTaker = source("taker_volume", perpSymbol, perpExch)
timeseries bars = ohlcv(currentSymbol, currentExchange)
// Guard: halt until all external feeds have loaded to avoid NaN propagation
if (isnan(oiTS.close[0]) || isnan(spotBars.close[0]) || isnan(perpBars.close[0]) || !isnum(spotTaker.buy) || !isnum(perpTaker.buy) || isnan(bars.close[0])) {
return
}
// ---------------------------------------------------------------------------
// 3. COMPUTATION
// ---------------------------------------------------------------------------
// -- 3.1 OI Delta Sentiment (Brunnermeier & Pedersen 2009) --
// OI delta = current OI − OI[period]; z-score normalized for cross-time comparison.
timeseries dOI = oiTS.close - oiTS.close[oiPeriod]
timeseries oiMean = sma(dOI, oiZWindow)
timeseries oiStd = stdev(dOI, oiZWindow)
timeseries oiZ = (oiStd > 0) ? (dOI - oiMean) / oiStd : 0
timeseries oiZSmooth = ema(oiZ, oiSmooth)
// OI sentiment regime: +OI + up close = Long Build-up; +OI + down = Short Covering
// -OI + down = Short Build-up; -OI + up = Long Liquidation
timeseries oiPos = dOI > 0 and bars.close > bars.open ? 1 : dOI > 0 and bars.close < bars.open ? 0.5 : dOI < 0 and bars.close < bars.open ? -1 : dOI < 0 and bars.close > bars.open ? -0.5 : 0
// -- 3.2 Liquidation Spike Detection (Brunnermeier & Pedersen 2009) --
// Proxy: extreme volume / range ratio. When liquidity is forcefully removed,
// volume surges while range may not expand proportionally (absorption).
timeseries vol = bars.volume
timeseries range = math.abs(bars.close - bars.open)
timeseries liqProxy = vol / math.max(range, 1e-9)
timeseries liqMean = sma(liqProxy, liqLookback)
timeseries liqStd = stdev(liqProxy, liqLookback)
timeseries liqZ = (liqStd > 0) ? (liqProxy - liqMean) / liqStd : 0
timeseries liqSpike = liqZ > liqThreshold
// Magnet zones: recent high-volume spike price levels (areas of maximum pain)
timeseries magnetHi = liqSpike and bars.close > bars.open ? bars.high : nz(magnetHi[1])
timeseries magnetLo = liqSpike and bars.close < bars.open ? bars.low : nz(magnetLo[1])
// -- 3.3 CVD & Order Flow (Cont, Kukanov & Stoikov 2014; Lee & Ready 1991) --
// Lee-Ready fallback when taker feed is unavailable.
timeseries spotBuy = isnum(spotTaker.buy) ? spotTaker.buy : (spotBars.close > spotBars.open ? spotBars.volume : 0)
timeseries spotSell = isnum(spotTaker.sell) ? spotTaker.sell : (spotBars.close <= spotBars.open ? spotBars.volume : 0)
timeseries spotDelta = spotBuy - spotSell
timeseries perpBuy = isnum(perpTaker.buy) ? perpTaker.buy : (perpBars.close > perpBars.open ? perpBars.volume : 0)
timeseries perpSell = isnum(perpTaker.sell) ? perpTaker.sell : (perpBars.close <= perpBars.open ? perpBars.volume : 0)
timeseries perpDelta = perpBuy - perpSell
// Rolling-window CVD (stationary approximation)
timeseries spotCVD = sum(spotDelta, cvdLen)
timeseries perpCVD = sum(perpDelta, cvdLen)
// CVD z-score normalization
timeseries spotCVDMean = sma(spotCVD, cvdZWindow)
timeseries spotCVDStd = stdev(spotCVD, cvdZWindow)
timeseries spotCVDZ = (spotCVDStd > 0) ? (spotCVD - spotCVDMean) / spotCVDStd : 0
timeseries perpCVDMean = sma(perpCVD, cvdZWindow)
timeseries perpCVDStd = stdev(perpCVD, cvdZWindow)
timeseries perpCVDZ = (perpCVDStd > 0) ? (perpCVD - perpCVDMean) / perpCVDStd : 0
// Combined CVD z-score (average of spot and perp)
timeseries cvdZCombined = ema((spotCVDZ + perpCVDZ) / 2, flowSmooth)
// -- 3.4 Composite Liquidity + Order Flow Score --
// Equal-weighted z-score fusion of OI sentiment, liquidation pressure, and CVD.
// Normalized again to produce a unified regime indicator.
timeseries rawComposite = (oiZSmooth + liqZ + cvdZCombined) / 3.0
timeseries compMean = sma(rawComposite, compZWindow)
timeseries compStd = stdev(rawComposite, compZWindow)
timeseries compositeZ = (compStd > 0) ? (rawComposite - compMean) / compStd : 0
timeseries compositeZSmooth = ema(compositeZ, flowSmooth)
// -- 3.5 Regime Detection (configurable thresholds, no magic numbers) --
var bullishRegime = compositeZSmooth > bullThresh
var bearishRegime = compositeZSmooth < bearThresh
var extremeBull = compositeZSmooth > extremeThresh
var extremeBear = compositeZSmooth < -extremeThresh
var neutralRegime = !bullishRegime && !bearishRegime
// Regime state tracking via static variables
static lastRegime = 0
static bullBars = 0
static bearBars = 0
static regimeChanges = 0
if (bullishRegime) {
bullBars = bullBars + 1
bearBars = 0
if (lastRegime != 1) {
regimeChanges = regimeChanges + 1
}
lastRegime = 1
} else if (bearishRegime) {
bearBars = bearBars + 1
bullBars = 0
if (lastRegime != -1) {
regimeChanges = regimeChanges + 1
}
lastRegime = -1
} else {
bullBars = 0
bearBars = 0
lastRegime = 0
}
// -- 3.6 Absorption Detection (Easley, López de Prado & O'Hara 2012 VPIN) --
// Price tests liquidation zone + CVD shows extreme anomaly + candle closes
// in opposite half = hidden demand/supply stepping in.
timeseries closePos = (bars.close - bars.low) / math.max(bars.high - bars.low, 1e-9)
timeseries priceNearMagnetHi = bars.high >= magnetHi * 0.998 and bars.high <= magnetHi * 1.002
timeseries priceNearMagnetLo = bars.low >= magnetLo * 0.998 and bars.low <= magnetLo * 1.002
timeseries cvdAnomalyNeg = cvdZCombined < -absorbZThresh
timeseries cvdAnomalyPos = cvdZCombined > absorbZThresh
// Long absorption: price tests resistance (magnetHi) + CVD anomaly negative + close upper half
// Short absorption: price tests support (magnetLo) + CVD anomaly positive + close lower half
timeseries absorbLong = priceNearMagnetHi and cvdAnomalyNeg and closePos > absorbTopPct
timeseries absorbShort = priceNearMagnetLo and cvdAnomalyPos and closePos < (1 - absorbTopPct)
// -- 3.7 Zero-line helper for fill areas --
timeseries zeroLine = 0
// ---------------------------------------------------------------------------
// 4. VISUALIZATION — Multiple types: plotLine, plotShape, plotBar, fill
// ---------------------------------------------------------------------------
// 4.1 OI Sentiment Z-score (plotLine)
if (showOI) {
plotLine(
value=oiZSmooth,
width=2,
colors=[upColor, dnColor, neutralColor],
colorIndex=oiZSmooth > 1.0 ? 0 : (oiZSmooth < -1.0 ? 1 : 2),
label=["OI Sentiment Z"],
desc=["Open Interest delta z-score: positive=long build-up, negative=short build-up/liquidation"]
)
}
// 4.2 Liquidation Z-score (plotLine)
if (showLiq) {
plotLine(
value=liqZ,
width=2,
colors=[liqColor, neutralColor],
colorIndex=liqZ > liqThreshold ? 0 : 1,
label=["Liquidation Z"],
desc=["Liquidation proxy z-score: extreme values flag forced liquidation events"]
)
}
// 4.3 CVD Z-score (plotLine)
if (showCVD) {
plotLine(
value=cvdZCombined,
width=2,
colors=[cvdColor, neutralColor],
colorIndex=math.abs(cvdZCombined) > 1.0 ? 0 : 1,
label=["CVD Z"],
desc=["Combined spot+perp CVD z-score: measures aggressive order flow pressure"]
)
}
// 4.4 Composite flow with fill area (plotLine + fill)
if (showComposite) {
timeseries compColorIdx = bullishRegime ? 0 : (bearishRegime ? 1 : 2)
plotLine(
value=([compositeZSmooth, zeroLine]),
width=2,
colors=[upColor, dnColor, neutralColor],
colorIndex=compColorIdx,
label=["Composite Flow"],
desc=["Liquidity + Order Flow composite z-score; filled histogram by regime"],
fill=true
)
}
// 4.5 Composite flow bars (plotBar) — sign-based colouring
if (showComposite) {
plotBar(value=compositeZSmooth, colors=[upColor, dnColor], label=["Composite Bars"], desc=["Composite z-score as bars"])
}
// 4.6 Magnet zones (plotLine — dashed reference levels)
if (showMagnet) {
plotLine(
value=magnetHi,
width=1,
colors=[opacity(liqColor, 50)],
label=["Magnet Resistance"],
desc=["Liquidation magnet zone: high-volume spike resistance level"]
)
plotLine(
value=magnetLo,
width=1,
colors=[opacity(liqColor, 50)],
label=["Magnet Support"],
desc=["Liquidation magnet zone: high-volume spike support level"]
)
}
// 4.7 Absorption signals (plotShape)
if (showAbsorption) {
if (absorbLong) {
plotShape(
value=compositeZSmooth,
shape="triangleup",
color=absorbUpColor,
width=4,
label=["Long Absorption"],
desc=["Long absorption: price tests resistance, CVD shows selling, but candle closes upper half — hidden demand"]
)
}
if (absorbShort) {
plotShape(
value=compositeZSmooth,
shape="triangledown",
color=absorbDnColor,
width=4,
label=["Short Absorption"],
desc=["Short absorption: price tests support, CVD shows buying, but candle closes lower half — hidden supply"]
)
}
}
// 4.8 Extreme divergence shapes (plotShape)
if (showShapes && extremeBull) {
plotShape(
value=compositeZSmooth,
shape="triangleup",
color=upColor,
width=3,
label=["Extreme Bull Fusion"],
desc=["All three pillars aligned bullish: OI build-up + low liquidation + positive CVD"]
)
}
if (showShapes && extremeBear) {
plotShape(
value=compositeZSmooth,
shape="triangledown",
color=dnColor,
width=3,
label=["Extreme Bear Fusion"],
desc=["All three pillars aligned bearish: OI liquidation + high liquidation + negative CVD"]
)
}
// 4.9 Reference thresholds (hline)
hline(value=0, color="#ffffff30", width=1)
hline(value=bullThresh, color="#ffffff20", width=1)
hline(value=bearThresh, color="#ffffff20", width=1)
hline(value=extremeThresh, color="#ffffff15", width=1)
hline(value=-extremeThresh, color="#ffffff15", width=1)