Perfected FlowScript
ddd
DDD — Directional Divergence Detector (Perfected) is indexed as 357_ddd.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
21.8 KB
Lines
677
Native Signal Candidates
10 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Extreme Bull
line 535:9
Trigger
(showShapes) && (extremeBullEntry)
Value
composite
Deps
extremeBullEntry:var, showShapes:input
Extreme Bear
line 545:9
Trigger
(showShapes) && (extremeBearEntry)
Value
composite
Deps
extremeBearEntry:var, showShapes:input
Bull Regime
line 556:9
Trigger
(showShapes) && (divBullEntry && !extremeBullEntry)
Value
composite
Deps
divBullEntry:var, extremeBullEntry:var, showShapes:input
Bear Regime
line 566:9
Trigger
(showShapes) && (divBearEntry && !extremeBearEntry)
Value
composite
Deps
divBearEntry:var, extremeBearEntry:var, showShapes:input
Zero Cross +
line 577:9
Trigger
(showShapes) && (zeroCrossUp)
Value
0
Deps
showShapes:input, zeroCrossUp:var
Zero Cross -
line 587:9
Trigger
(showShapes) && (zeroCrossDown)
Value
0
Deps
showShapes:input, zeroCrossDown:var
CVD > OI
line 598:9
Trigger
(showShapes) && (cvdCrossOiUp)
Value
cvdZSmooth
Deps
cvdCrossOiUp:var, showShapes:input
CVD < OI
line 608:9
Trigger
(showShapes) && (cvdCrossOiDown)
Value
cvdZSmooth
Deps
cvdCrossOiDown:var, showShapes:input
Div Extreme +
line 619:9
Trigger
(showShapes) && (divExtremeUp)
Value
divergence
Deps
divExtremeUp:var, showShapes:input
Div Extreme -
line 629:9
Trigger
(showShapes) && (divExtremeDown)
Value
divergence
Deps
divExtremeDown:var, showShapes:input
357_ddd.flowscript
source path: kscripts/perfected/357_ddd.flowscript · sha256:a8ca867a316b8f331634dc4e1dc7ba1bdfa70dc2e69d6bd36591a2f4edf6f5c0
//@version=2
// ============================================================================
// DDD — Directional Divergence Detector (Perfected Edition)
// Author: S (@samadalala1990) | Enhanced by kScript Perfection Engineer
// Tags: ADVANCED, #ddd, #multi_factor, #divergence, #regime, #composite
//
// The Directional Divergence Detector (DDD) is a production-quality multi-factor
// composite indicator combining three orthogonal signals:
// (1) CVD Delta — directional volume flow pressure (spot vs perp),
// (2) OI Density — open interest deviation from rolling mean (z-score proxy),
// (3) Divergence — disagreement between volume flow and OI positioning.
//
// When volume flow and OI move together, the composite score confirms regime
// strength. When they diverge, the composite flags potential regime exhaustion
// or reversal — a pattern validated in the microstructure literature.
//
// Research papers underpinning this design:
// 1. Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events":
// OFI_t = Δq_t^b·I_{Δq_t^b>0} − Δq_t^a·I_{Δq_t^a>0}. CVD linearly predicts
// short-term price changes. DOI: https://doi.org/10.1093/jjfinec/nbt003
// 2. Chen, Cuny & Haugen (1995), "Stock Volatility and the Levels of the Basis
// and Open Interest in Futures Contracts": OI levels carry information about
// future volatility and price discovery.
// 3. Chordia, Roll & Subrahmanyam (2002), "Order Imbalance, Liquidity, and
// Market Returns": extreme |Imbalance| predicts return reversals. Directly
// motivates the divergence-threshold design.
// DOI: https://doi.org/10.1016/S0304-405X(02)00136-8
// 4. He & Manela (2022), "Fundamentals of Perpetual Futures": futures-spot gap
// driven by funding-cost momentum; supports joint spot+perp flow analysis.
// 5. Kyle (1985), "Continuous Auctions and Insider Trading": p_t = p_{t−1} +
// λ·OFI_t + noise. Kyle's λ underpins every delta-based trading signal.
// DOI: https://doi.org/10.2307/1913210
// ============================================================================
define(
title="DDD — Directional Divergence Detector (Perfected)",
position="offchart",
axis=true
)
// ---------------------------------------------------------------------------
// 1. USER INPUTS — All grouped, all numeric inputs carry constraints
// ---------------------------------------------------------------------------
// -- 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"
)
// -- CVD Delta --
var cvdWindow = input(
name="cvdWindow",
type="number",
defaultValue=50,
label="CVD Lookback Window",
constraints={min: 10, max: 200, step: 5},
group="CVD Delta"
)
var cvdSmooth = input(
name="cvdSmooth",
type="number",
defaultValue=3,
label="CVD EMA Smooth",
constraints={min: 1, max: 20, step: 1},
group="CVD Delta"
)
// -- OI Density --
var oiLookback = input(
name="oiLookback",
type="number",
defaultValue=30,
label="OI Density Lookback",
constraints={min: 10, max: 100, step: 5},
group="OI Density"
)
var oiSmooth = input(
name="oiSmooth",
type="number",
defaultValue=3,
label="OI EMA Smooth",
constraints={min: 1, max: 20, step: 1},
group="OI Density"
)
// -- Divergence & Composite --
var divThreshold = input(
name="divThreshold",
type="number",
defaultValue=2.0,
label="Divergence Threshold (±σ)",
constraints={min: 0.5, max: 4.0, step: 0.5},
group="Divergence & Composite"
)
var extremeThreshold = input(
name="extremeThreshold",
type="number",
defaultValue=3.0,
label="Extreme Threshold (±σ)",
constraints={min: 2.0, max: 6.0, step: 0.5},
group="Divergence & Composite"
)
var compositeWeight = input(
name="compositeWeight",
type="number",
defaultValue=0.6,
label="CVD Weight (0=OI only, 1=CVD only)",
constraints={min: 0.0, max: 1.0, step: 0.1},
group="Divergence & Composite"
)
var useDynamic = input(
name="useDynamic",
type="boolean",
defaultValue=true,
label="Dynamic Thresholds (volatility-adjusted)",
group="Divergence & Composite"
)
var volLookback = input(
name="volLookback",
type="number",
defaultValue=20,
label="Volatility Lookback",
constraints={min: 5, max: 100, step: 1},
group="Divergence & Composite"
)
var volMultiplier = input(
name="volMultiplier",
type="number",
defaultValue=1.0,
label="Volatility Multiplier",
constraints={min: 0.5, max: 3.0, step: 0.1},
group="Divergence & Composite"
)
// -- Display --
var showCvdZ = input(
name="showCvdZ",
type="boolean",
defaultValue=true,
label="Show CVD Z-Score",
group="Display"
)
var showOiZ = input(
name="showOiZ",
type="boolean",
defaultValue=true,
label="Show OI Density Z-Score",
group="Display"
)
var showComposite = input(
name="showComposite",
type="boolean",
defaultValue=true,
label="Show DDD Composite Score",
group="Display"
)
var showDivergence = input(
name="showDivergence",
type="boolean",
defaultValue=true,
label="Show Divergence Channel",
group="Display"
)
var showHistogram = input(
name="showHistogram",
type="boolean",
defaultValue=true,
label="Show Composite Histogram",
group="Display"
)
var showFill = input(
name="showFill",
type="boolean",
defaultValue=true,
label="Show Composite Fill",
group="Display"
)
var showShapes = input(
name="showShapes",
type="boolean",
defaultValue=true,
label="Show Alert Shapes",
group="Display"
)
// -- Colors --
var cvdColor = input(
name="cvdColor",
type="color",
defaultValue="#2962ff",
label="CVD Z Color",
group="Colors"
)
var oiColor = input(
name="oiColor",
type="color",
defaultValue="#ff6d00",
label="OI Z Color",
group="Colors"
)
var bullColor = input(
name="bullColor",
type="color",
defaultValue="#26a69a",
label="Bull Color",
group="Colors"
)
var bearColor = input(
name="bearColor",
type="color",
defaultValue="#ef5350",
label="Bear Color",
group="Colors"
)
var extremeBullColor = input(
name="extremeBullColor",
type="color",
defaultValue="#00e676",
label="Extreme Bull Color",
group="Colors"
)
var extremeBearColor = input(
name="extremeBearColor",
type="color",
defaultValue="#d50000",
label="Extreme Bear 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 Line Color",
group="Colors"
)
// ---------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// ---------------------------------------------------------------------------
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 perpOI = open_interest(symbol=perpSymbol, exchange=perpExch)
// Guard: halt until all external feeds have loaded
if (isnan(spotBars.close[0]) || isnan(perpBars.close[0]) || isnan(perpOI.close[0]) || !isnum(spotTaker.buy) || !isnum(perpTaker.buy)) {
return
}
// ---------------------------------------------------------------------------
// 3. CVD DELTA — Standardized per-bar volume flow (Lee-Ready fallback)
// ---------------------------------------------------------------------------
// Lee-Ready (1991) tick test: close > open → buyer-initiated; else seller-initiated.
// When taker.buy/sell is available, prefer the direct feed for higher accuracy.
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
// Combined delta (spot + perp) — total directional flow pressure
timeseries totalDelta = spotDelta + perpDelta
// Rolling-window CVD (stationary approximation)
timeseries cvd = sum(totalDelta, cvdWindow)
// Z-score normalization of CVD
timeseries cvdMean = sma(cvd, cvdWindow)
timeseries cvdStd = stddev(cvd, cvdWindow)
timeseries cvdZ = (cvdStd > 0) ? (cvd - cvdMean) / cvdStd : 0
timeseries cvdZSmooth = ema(cvdZ, cvdSmooth)
// ---------------------------------------------------------------------------
// 4. OI DENSITY — Rolling z-score of open interest deviation
// ---------------------------------------------------------------------------
timeseries oiMean = sma(perpOI.close, oiLookback)
timeseries oiStd = stddev(perpOI.close, oiLookback)
timeseries oiZ = (oiStd > 0) ? (perpOI.close - oiMean) / oiStd : 0
timeseries oiZSmooth = ema(oiZ, oiSmooth)
// ---------------------------------------------------------------------------
// 5. DIVERGENCE — Disagreement between CVD flow and OI positioning
// ---------------------------------------------------------------------------
// When CVD and OI disagree, the market is often at a turning point:
// • Rising OI + negative CVD = new shorts opening (bearish build-up)
// • Falling OI + positive CVD = short covering (bullish squeeze)
// • Rising OI + positive CVD = genuine bullish momentum
// • Falling OI + negative CVD = genuine bearish momentum
timeseries divergence = cvdZSmooth - oiZSmooth
// ---------------------------------------------------------------------------
// 6. COMPOSITE SCORE — Weighted multi-factor aggregation
// ---------------------------------------------------------------------------
// The composite blends CVD flow and OI density into a single regime score.
// Weight is user-tunable: 0.6 default gives slight preference to flow.
timeseries composite = ema((compositeWeight * cvdZSmooth) + ((1.0 - compositeWeight) * oiZSmooth), 3)
// ---------------------------------------------------------------------------
// 7. DYNAMIC THRESHOLDS
// ---------------------------------------------------------------------------
timeseries compVol = stddev(composite, volLookback)
var dynDiv = useDynamic ? math.max(0.5, divThreshold + compVol * volMultiplier) : divThreshold
var dynExtreme = useDynamic ? math.max(1.5, extremeThreshold + compVol * volMultiplier * 1.5) : extremeThreshold
// Guard: ensure bands never invert
if (dynExtreme <= dynDiv) {
dynExtreme = divThreshold + 1.0
dynDiv = divThreshold
}
// ---------------------------------------------------------------------------
// 8. REGIME DETECTION (Composite-based)
// ---------------------------------------------------------------------------
var extremeBull = composite > dynExtreme
var bullRegime = composite > dynDiv && !extremeBull
var extremeBear = composite < -dynExtreme
var bearRegime = composite < -dynDiv && !extremeBear
var neutralRegime = !extremeBull && !bullRegime && !extremeBear && !bearRegime
var compRegColor = extremeBull ? extremeBullColor : (bullRegime ? bullColor : (extremeBear ? extremeBearColor : (bearRegime ? bearColor : neutralColor)))
// Divergence regime (flow vs positioning disagreement)
var divBull = divergence > dynDiv
var divBear = divergence < -dynDiv
var divNeutral = !divBull && !divBear
var divRegColor = divBull ? extremeBullColor : (divBear ? extremeBearColor : neutralColor)
// ---------------------------------------------------------------------------
// 9. STATIC TRACKING — Consecutive regime bars
// ---------------------------------------------------------------------------
static lastRegime = 0
static compBullBars = 0
static compBearBars = 0
static compExtremeBullBars = 0
static compExtremeBearBars = 0
static divBullBars = 0
static divBearBars = 0
if (extremeBull) {
compExtremeBullBars = compExtremeBullBars + 1
compExtremeBearBars = 0
lastRegime = 2
} else if (bullRegime) {
compBullBars = compBullBars + 1
compBearBars = 0
compExtremeBearBars = 0
lastRegime = 1
} else if (extremeBear) {
compExtremeBearBars = compExtremeBearBars + 1
compExtremeBullBars = 0
lastRegime = -2
} else if (bearRegime) {
compBearBars = compBearBars + 1
compBullBars = 0
compExtremeBullBars = 0
lastRegime = -1
} else {
compBullBars = 0
compBearBars = 0
compExtremeBullBars = 0
compExtremeBearBars = 0
lastRegime = 0
}
if (divBull) {
divBullBars = divBullBars + 1
divBearBars = 0
} else if (divBear) {
divBearBars = divBearBars + 1
divBullBars = 0
} else {
divBullBars = 0
divBearBars = 0
}
// ---------------------------------------------------------------------------
// 10. ALERT CONDITIONS
// ---------------------------------------------------------------------------
// Composite extreme entries
var extremeBullEntry = extremeBull && !extremeBull[1]
var extremeBearEntry = extremeBear && !extremeBear[1]
var divBullEntry = bullRegime && !bullRegime[1]
var divBearEntry = bearRegime && !bearRegime[1]
// Zero-line crossings
var zeroCrossUp = composite > 0 && composite[1] <= 0
var zeroCrossDown = composite < 0 && composite[1] >= 0
// Divergence between CVD and OI
var divCrossUp = divergence > dynDiv && divergence[1] <= dynDiv
var divCrossDown = divergence < -dynDiv && divergence[1] >= -dynDiv
var divExtremeUp = divergence > dynExtreme && divergence[1] <= dynExtreme
var divExtremeDown = divergence < -dynExtreme && divergence[1] >= -dynExtreme
// CVD vs OI cross (when one crosses the other)
var cvdCrossOiUp = cvdZSmooth > oiZSmooth && cvdZSmooth[1] <= oiZSmooth[1]
var cvdCrossOiDown = cvdZSmooth < oiZSmooth && cvdZSmooth[1] >= oiZSmooth[1]
// ---------------------------------------------------------------------------
// 11. PLOTTING
// ---------------------------------------------------------------------------
// -- Midline & Thresholds --
hline(value=0, color="#ffffff20", width=1)
if (showComposite || showCvdZ || showOiZ) {
hline(value=dynDiv, color=transparency(bullColor, 60), width=1)
hline(value=-dynDiv, color=transparency(bearColor, 60), width=1)
hline(value=dynExtreme, color=transparency(extremeBullColor, 50), width=1)
hline(value=-dynExtreme, color=transparency(extremeBearColor, 50), width=1)
}
// -- CVD Z-Score (component 1) --
if (showCvdZ) {
plotLine(
value=cvdZSmooth,
width=2,
colors=[cvdColor],
label=["CVD Z"],
desc=["Standardized cumulative volume delta z-score (flow pressure)"]
)
}
// -- OI Density Z-Score (component 2) --
if (showOiZ) {
plotLine(
value=oiZSmooth,
width=2,
colors=[oiColor],
label=["OI Z"],
desc=["Standardized open interest density z-score (positioning pressure)"]
)
}
// -- Composite Score (regime-colored) --
if (showComposite) {
plotLine(
value=composite,
width=2,
colors=[compRegColor],
label=["DDD Composite"],
desc=["Multi-factor composite score: weighted blend of CVD flow and OI density (regime-colored)"]
)
}
// -- Fill between Composite and zero --
if (showFill) {
var compAboveZero = composite > 0
plotLine(
value=[composite, 0],
width=1,
colors=[transparency(bullColor, 20), transparency(bearColor, 20)],
colorIndex=compAboveZero ? 0 : 1,
fill=true,
label=["Composite", "Zero"],
desc=["Fill between DDD composite score and zero line"]
)
}
// -- Divergence Channel (flow vs positioning disagreement) --
if (showDivergence) {
plotLine(
value=divergence,
width=2,
colors=[divRegColor],
label=["Divergence"],
desc=["CVD Z minus OI Z: disagreement between volume flow and open interest positioning (regime-colored)"]
)
}
// -- Composite Histogram --
if (showHistogram) {
var histBull = composite >= 0
plotBar(
value=composite,
colors=[transparency(bullColor, 60), transparency(bearColor, 60)],
colorIndex=histBull ? 0 : 1,
width=1,
label=["DDD Histogram"],
desc=["Histogram of DDD composite score (regime color-coded)"]
)
}
// -- Shape Markers --
if (showShapes) {
// Composite extreme entries
if (extremeBullEntry) {
plotShape(
value=composite,
shape="triangleup",
colorIndex=extremeBullColor,
width=3,
label=["Extreme Bull"],
desc=["DDD composite entered extreme bullish regime (>" + dynExtreme + ") — strong confluent bullish pressure"]
)
}
if (extremeBearEntry) {
plotShape(
value=composite,
shape="triangledown",
colorIndex=extremeBearColor,
width=3,
label=["Extreme Bear"],
desc=["DDD composite entered extreme bearish regime (<" + -dynExtreme + ") — strong confluent bearish pressure"]
)
}
// Composite divergence threshold entries
if (divBullEntry && !extremeBullEntry) {
plotShape(
value=composite,
shape="arrowup",
colorIndex=bullColor,
width=2,
label=["Bull Regime"],
desc=["DDD composite crossed above divergence threshold (" + dynDiv + ")"]
)
}
if (divBearEntry && !extremeBearEntry) {
plotShape(
value=composite,
shape="arrowdown",
colorIndex=bearColor,
width=2,
label=["Bear Regime"],
desc=["DDD composite crossed below divergence threshold (" + -dynDiv + ")"]
)
}
// Zero-line crossings
if (zeroCrossUp) {
plotShape(
value=0,
shape="diamond",
colorIndex=bullColor,
width=2,
label=["Zero Cross +"],
desc=["DDD composite crossed above zero — aggregate pressure turning positive"]
)
}
if (zeroCrossDown) {
plotShape(
value=0,
shape="diamond",
colorIndex=bearColor,
width=2,
label=["Zero Cross -"],
desc=["DDD composite crossed below zero — aggregate pressure turning negative"]
)
}
// CVD vs OI crossovers (flow vs positioning disagreement)
if (cvdCrossOiUp) {
plotShape(
value=cvdZSmooth,
shape="circle",
colorIndex=cvdColor,
width=2,
label=["CVD > OI"],
desc=["CVD flow crossed above OI density — volume leading positioning"]
)
}
if (cvdCrossOiDown) {
plotShape(
value=cvdZSmooth,
shape="circle",
colorIndex=oiColor,
width=2,
label=["CVD < OI"],
desc=["CVD flow crossed below OI density — positioning leading volume"]
)
}
// Divergence extreme crossings
if (divExtremeUp) {
plotShape(
value=divergence,
shape="triangleup",
colorIndex=extremeBullColor,
width=2,
label=["Div Extreme +"],
desc=["Divergence entered extreme positive — flow massively outpacing positioning (potential squeeze)"]
)
}
if (divExtremeDown) {
plotShape(
value=divergence,
shape="triangledown",
colorIndex=extremeBearColor,
width=2,
label=["Div Extreme -"],
desc=["Divergence entered extreme negative — positioning massively outpacing flow (potential trap)"]
)
}
}
// ---------------------------------------------------------------------------
// 12. REGIME TABLE (last bar only)
// ---------------------------------------------------------------------------
if (isLastBar) {
var regimeText = extremeBull ? "EXTREME BULL" : (bullRegime ? "BULL" : (extremeBear ? "EXTREME BEAR" : (bearRegime ? "BEAR" : "NEUTRAL")))
var regimeTextColor = extremeBull ? extremeBullColor : (bullRegime ? bullColor : (extremeBear ? extremeBearColor : (bearRegime ? bearColor : neutralColor)))
var divLabel = useDynamic ? "Dyn Div: ±" + dynDiv : "Static Div: ±" + divThreshold
var extLabel = useDynamic ? "Dyn Extreme: ±" + dynExtreme : "Static Extreme: ±" + extremeThreshold
plotTable(
data=[
["DDD — Perfected", regimeText],
["Composite Score", composite[0]],
["CVD Z", cvdZSmooth[0]],
["OI Z", oiZSmooth[0]],
["Divergence", divergence[0]],
["Raw OI", perpOI.close[0]],
["CVD Weight", compositeWeight],
[divLabel, extLabel],
["Comp Bull Bars", compBullBars],
["Comp Bear Bars", compBearBars],
["Div Bull Bars", divBullBars],
["Div Bear Bars", divBearBars]
],
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
)
}