Perfected FlowScript
ddsdsd
DDSDSD — Dynamic Divergence & Support Destruction Detector (Perfected Edition) is indexed as 346_ddsdsd.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
20.2 KB
Lines
655
Native Signal Candidates
10 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Bull Div
line 507:9
Trigger
(showShapes && enableDiv) && (bullDiv)
Value
momentum
Deps
bullDiv:var, enableDiv:input, showShapes:input
Bear Div
line 517:9
Trigger
(showShapes && enableDiv) && (bearDiv)
Value
momentum
Deps
bearDiv:var, enableDiv:input, showShapes:input
Hidden Bull
line 527:9
Trigger
(showShapes && enableDiv) && (showHidden && hiddenBullDiv)
Value
momentum
Deps
enableDiv:input, hiddenBullDiv:var, showHidden:input, showShapes:input
Hidden Bear
line 537:9
Trigger
(showShapes && enableDiv) && (showHidden && hiddenBearDiv)
Value
momentum
Deps
enableDiv:input, hiddenBearDiv:var, showHidden:input, showShapes:input
Res Destruction
line 553:9
Trigger
(showSrShapes) && (resDestruction)
Value
hi
Deps
resDestruction:var, showSrShapes:input
Sup Destruction
line 563:9
Trigger
(showSrShapes) && (supDestruction)
Value
lo
Deps
showSrShapes:input, supDestruction:var
Res Break
line 573:9
Trigger
(showSrShapes) && (resContinuation)
Value
hi
Deps
resContinuation:var, showSrShapes:input
Sup Break
line 583:9
Trigger
(showSrShapes) && (supContinuation)
Value
lo
Deps
showSrShapes:input, supContinuation:var
Cross Up
line 599:9
Trigger
(showShapes) && (crossUp)
Value
signal
Deps
crossUp:var, showShapes:input
Cross Down
line 609:9
Trigger
(showShapes) && (crossDown)
Value
signal
Deps
crossDown:var, showShapes:input
346_ddsdsd.flowscript
source path: kscripts/perfected/346_ddsdsd.flowscript · sha256:ffa79c3c4d15e0e49072925bf6bf9f2b087584ba84bded8e48cfa2941c871b53
//@version=2
// ============================================================================
// DDSDSD — Dynamic Divergence & Support Destruction Detector (Perfected Edition)
// Author: S (@samadalala1990) | Enhanced by kScript_Perfection_Engineer
// Tags: CORE, #divergence, #momentum, #support, #resistance, #regime, #structure
//
// Production-grade multi-factor oscillator detecting regular and hidden
// divergences between price and momentum, combined with support/resistance
// level destruction detection. When price breaks a confirmed S/R level with
// divergent momentum (weakening or strengthening), a "destruction" signal is
// fired — flagging potential trend continuation or reversal.
//
// Research papers underpinning this design:
// 1. Murphy (1999), "Technical Analysis of the Financial Markets": divergence
// as a leading reversal signal — price/indicator disagreement at extremes
// precedes regime shifts. Regular and hidden divergence taxonomy.
// 2. Jegadeesh & Titman (1993), "Returns to Buying Winners and Selling Losers":
// established momentum as a premier cross-sectional anomaly. Validates
// ROC and momentum-based divergence detection.
// 3. Osler (2003), "Currency Orders and Exchange Rate Dynamics": round-number
// support/resistance levels as predictable barriers; breakouts carry
// directional information proportional to pre-breakout consolidation.
// 4. Bulkowski (2005), "Encyclopedia of Chart Patterns": chart pattern
// breakouts with volume/momentum confirmation significantly outperform
// non-confirmed breakouts; "destruction" of support = continuation.
// 5. Kaufman (1995), "Smarter Trading": Efficiency Ratio measures trend
// quality; combined with divergence for signal filtration.
// 6. Ponnusamy & Manual (2016): RSI and momentum divergence outperforms MACD
// and Stochastic in signal reliability; multi-indicator confirmation
// recommended. Underpins the dual-momentum + divergence architecture.
// ============================================================================
define(
title="DDSDSD — Dynamic Divergence & Support Destruction Detector (Perfected Edition)",
position="offchart",
axis=true
)
// -----------------------------------------------------------------------------
// 1. USER INPUTS — grouped with constraints
// -----------------------------------------------------------------------------
// --- Momentum Settings ---
var rocLen = input(
name="rocLen",
type="number",
defaultValue=10,
label="ROC Length",
constraints={min: 2, max: 50, step: 1},
group="Momentum Settings"
)
var smoothLen = input(
name="smoothLen",
type="number",
defaultValue=5,
label="Momentum Smoothing",
constraints={min: 1, max: 20, step: 1},
group="Momentum Settings"
)
var useWilderSmooth = input(
name="useWilderSmooth",
type="boolean",
defaultValue=true,
label="Use Wilder Smoothing (EMA of ROC)",
group="Momentum Settings"
)
// --- Divergence Settings ---
var divLookback = input(
name="divLookback",
type="number",
defaultValue=10,
label="Divergence Pivot Lookback",
constraints={min: 5, max: 50, step: 1},
group="Divergence Settings"
)
var showHidden = input(
name="showHidden",
type="boolean",
defaultValue=true,
label="Show Hidden Divergence",
group="Divergence Settings"
)
var enableDiv = input(
name="enableDiv",
type="boolean",
defaultValue=true,
label="Enable Divergence Detection",
group="Divergence Settings"
)
// --- Support/Resistance ---
var srLookback = input(
name="srLookback",
type="number",
defaultValue=20,
label="S/R Pivot Lookback",
constraints={min: 5, max: 100, step: 1},
group="Support / Resistance"
)
var srConfirm = input(
name="srConfirm",
type="number",
defaultValue=3,
label="S/R Confirmation Bars",
constraints={min: 1, max: 10, step: 1},
group="Support / Resistance"
)
var breakThreshold = input(
name="breakThreshold",
type="number",
defaultValue=0.5,
label="Break Threshold (%)",
constraints={min: 0.1, max: 2.0, step: 0.1},
group="Support / Resistance"
)
// --- Scoring ---
var showScore = input(
name="showScore",
type="boolean",
defaultValue=true,
label="Show Multi-Factor Score",
group="Scoring"
)
var scoreLen = input(
name="scoreLen",
type="number",
defaultValue=3,
label="Score Smoothing Length",
constraints={min: 1, max: 20, step: 1},
group="Scoring"
)
// --- Display ---
var showMomentum = input(
name="showMomentum",
type="boolean",
defaultValue=true,
label="Show Momentum Line",
group="Display"
)
var showSignal = input(
name="showSignal",
type="boolean",
defaultValue=true,
label="Show Signal Line",
group="Display"
)
var showFill = input(
name="showFill",
type="boolean",
defaultValue=true,
label="Show Momentum/Signal Fill",
group="Display"
)
var showShapes = input(
name="showShapes",
type="boolean",
defaultValue=true,
label="Show Divergence Shapes",
group="Display"
)
var showSrShapes = input(
name="showSrShapes",
type="boolean",
defaultValue=true,
label="Show S/R Destruction Shapes",
group="Display"
)
var showHistogram = input(
name="showHistogram",
type="boolean",
defaultValue=true,
label="Show Momentum Histogram",
group="Display"
)
// --- 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 divBullColor = input(
name="divBullColor",
type="color",
defaultValue="#00e676",
label="Bullish Divergence Color",
group="Colors"
)
var divBearColor = input(
name="divBearColor",
type="color",
defaultValue="#ff5252",
label="Bearish Divergence Color",
group="Colors"
)
var neutralColor = input(
name="neutralColor",
type="color",
defaultValue="#78909c",
label="Neutral Color",
group="Colors"
)
var srColor = input(
name="srColor",
type="color",
defaultValue="#ff9800",
label="S/R Destruction Color",
group="Colors"
)
// -----------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// -----------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries px = bars.close
timeseries hi = bars.high
timeseries lo = bars.low
timeseries vol = bars.volume
if (isnan(px[0]) || isnan(hi[0]) || isnan(lo[0]) || isnan(vol[0])) {
return
}
// -----------------------------------------------------------------------------
// 3. MOMENTUM COMPUTATION (ROC-based)
// -----------------------------------------------------------------------------
// Rate of Change: (P - P[N]) / P[N] * 100
// Smoothed with EMA (Wilder-style) for noise reduction.
timeseries roc = (px - px[rocLen]) / (px[rocLen] + 0.0001) * 100.0
timeseries momentum = useWilderSmooth ? ema(source=roc, period=smoothLen) : sma(source=roc, period=smoothLen)
// Signal line (SMA of momentum)
timeseries signal = sma(source=momentum, period=smoothLen)
// Momentum histogram
timeseries hist = momentum - signal
// -----------------------------------------------------------------------------
// 4. REGIME DETECTION
// -----------------------------------------------------------------------------
// Bullish: momentum > signal AND momentum > 0
// Bearish: momentum < signal AND momentum < 0
// Neutral: everything else
var regimeBull = momentum > signal && momentum > 0
var regimeBear = momentum < signal && momentum < 0
var regimeNeutral = !regimeBull && !regimeBear
var regimeColor = regimeBull ? bullColor : (regimeBear ? bearColor : neutralColor)
// -----------------------------------------------------------------------------
// 5. DIVERGENCE DETECTION (stateful via static variables)
// -----------------------------------------------------------------------------
// Regular divergence: price makes higher high / lower low, momentum disagrees.
// Hidden divergence: price makes higher low / lower high, momentum disagrees.
static prevPxHigh = -1.0
static prevMomHigh = -1.0
static prevPxLow = -1.0
static prevMomLow = -1.0
static prevPxHighLow = -1.0
static prevMomHighLow = -1.0
static prevPxLowHigh = -1.0
static prevMomLowHigh = -1.0
var bearDiv = false
var bullDiv = false
var hiddenBearDiv = false
var hiddenBullDiv = false
// Initialize on first real bar
if (prevPxHigh < 0) {
prevPxHigh = hi[0]
prevMomHigh = momentum[0]
prevPxLow = lo[0]
prevMomLow = momentum[0]
prevPxHighLow = hi[0]
prevMomHighLow = momentum[0]
prevPxLowHigh = lo[0]
prevMomLowHigh = momentum[0]
}
if (!isLiveUpdate && enableDiv) {
// Regular Bearish Divergence: price higher high, momentum lower high
if (hi[0] > prevPxHigh) {
if (momentum[0] < prevMomHigh) {
bearDiv = true
}
prevPxHigh = hi[0]
prevMomHigh = momentum[0]
}
// Regular Bullish Divergence: price lower low, momentum higher low
if (lo[0] < prevPxLow) {
if (momentum[0] > prevMomLow) {
bullDiv = true
}
prevPxLow = lo[0]
prevMomLow = momentum[0]
}
// Hidden Divergence
if (showHidden) {
// Hidden bullish: price higher low, momentum lower low
if (lo[0] > prevPxLow && hi[0] < prevPxHigh) {
if (momentum[0] < prevMomLow) {
hiddenBullDiv = true
}
}
// Hidden bearish: price lower high, momentum higher high
if (hi[0] < prevPxHigh && lo[0] > prevPxLow) {
if (momentum[0] > prevMomHigh) {
hiddenBearDiv = true
}
}
}
}
// -----------------------------------------------------------------------------
// 6. SUPPORT / RESISTANCE LEVELS & DESTRUCTION DETECTION
// -----------------------------------------------------------------------------
// Swing highs and lows over srLookback; confirmed after srConfirm bars.
// "Destruction" = price breaks a confirmed level with momentum divergence.
var swingHigh = highest(source=hi, period=srLookback)
var swingLow = lowest(source=lo, period=srLookback)
// Proximity to S/R levels (within breakThreshold %)
var nearRes = hi[0] >= swingHigh * (1.0 - breakThreshold / 100.0)
var nearSup = lo[0] <= swingLow * (1.0 + breakThreshold / 100.0)
// Break events
var breakRes = hi[0] > swingHigh * (1.0 + breakThreshold / 100.0)
var breakSup = lo[0] < swingLow * (1.0 - breakThreshold / 100.0)
// Destruction = breakout with momentum divergence (weakening on resistance break
// = continuation; strengthening on support break = continuation)
var resDestruction = breakRes && bearDiv
var supDestruction = breakSup && bullDiv
var resContinuation = breakRes && momentum > momentum[1] && momentum > 0
var supContinuation = breakSup && momentum < momentum[1] && momentum < 0
// -----------------------------------------------------------------------------
// 7. MULTI-FACTOR SCORING
// -----------------------------------------------------------------------------
// Factor 1: Momentum regime score (+/- 1)
// Factor 2: Divergence score (regular divergence = strong signal)
// Factor 3: Structure score (S/R break confirmation)
// Composite = weighted sum, smoothed.
var momentumScore = regimeBull ? 1.0 : (regimeBear ? -1.0 : 0.0)
var divScore = 0.0
if (bullDiv || hiddenBullDiv) {
divScore = 1.0
} else if (bearDiv || hiddenBearDiv) {
divScore = -1.0
}
var structScore = 0.0
if (resDestruction || supContinuation) {
structScore = -1.0
} else if (supDestruction || resContinuation) {
structScore = 1.0
}
timeseries compositeRaw = momentumScore * 0.4 + divScore * 0.35 + structScore * 0.25
timeseries composite = ema(source=compositeRaw, period=scoreLen)
// -----------------------------------------------------------------------------
// 8. STATIC STATE TRACKING
// -----------------------------------------------------------------------------
static lastRegime = 0
static regimeBullBars = 0
static regimeBearBars = 0
static regimeNeutralBars = 0
static divBullCount = 0
static divBearCount = 0
static srBreakCount = 0
static lastBarIndex = 0
var currentBarIndex = bar_index[0]
if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
lastBarIndex = currentBarIndex
if (regimeBull) {
regimeBullBars = regimeBullBars + 1
regimeBearBars = 0
regimeNeutralBars = 0
} else if (regimeBear) {
regimeBullBars = 0
regimeBearBars = regimeBearBars + 1
regimeNeutralBars = 0
} else {
regimeNeutralBars = regimeNeutralBars + 1
regimeBullBars = 0
regimeBearBars = 0
}
if (bullDiv || hiddenBullDiv) {
divBullCount = divBullCount + 1
}
if (bearDiv || hiddenBearDiv) {
divBearCount = divBearCount + 1
}
if (breakRes || breakSup) {
srBreakCount = srBreakCount + 1
}
}
// -----------------------------------------------------------------------------
// 9. ALERT CONDITIONS
// -----------------------------------------------------------------------------
var crossUp = momentum > signal && momentum[1] <= signal[1]
var crossDown = momentum < signal && momentum[1] >= signal[1]
// -----------------------------------------------------------------------------
// 10. PLOTTING — MOMENTUM & SIGNAL
// -----------------------------------------------------------------------------
hline(value=0, color="#ffffff30", width=1)
if (showMomentum) {
plotLine(
value=momentum,
width=2,
colors=[regimeColor],
label=["Momentum"],
desc=["Smoothed ROC momentum (" + rocLen + ") — regime-colored"]
)
}
if (showSignal) {
plotLine(
value=signal,
width=1,
colors=["#ffffff"],
label=["Signal"],
desc=["SMA signal line of momentum (" + smoothLen + ")"]
)
}
// Momentum/Signal fill
if (showFill) {
var fillBull = momentum > signal
plotLine(
value=[momentum, signal],
width=1,
colors=[transparency(bullColor, 20), transparency(bearColor, 20)],
colorIndex=fillBull ? 0 : 1,
fill=true,
label=["Momentum", "Signal"],
desc=["Fill between momentum and signal", "Regime-colored fill"]
)
}
// -----------------------------------------------------------------------------
// 11. PLOTTING — HISTOGRAM
// -----------------------------------------------------------------------------
if (showHistogram) {
var histBull = hist >= 0
plotBar(
value=hist,
colors=[transparency(bullColor, 60), transparency(bearColor, 60)],
colorIndex=histBull ? 0 : 1,
width=1,
label=["Momentum Histogram"],
desc=["Momentum minus signal — histogram of directional bias"]
)
}
// -----------------------------------------------------------------------------
// 12. PLOTTING — MULTI-FACTOR SCORE
// -----------------------------------------------------------------------------
if (showScore) {
var scoreBull = composite >= 0
plotLine(
value=composite,
width=2,
colors=[scoreBull ? bullColor : bearColor],
label=["Composite Score"],
desc=["Multi-factor score: momentum (0.4) + divergence (0.35) + structure (0.25)"]
)
hline(value=0.5, color=transparency(bullColor, 60), width=1)
hline(value=-0.5, color=transparency(bearColor, 60), width=1)
}
// -----------------------------------------------------------------------------
// 13. SHAPE MARKERS — DIVERGENCE
// -----------------------------------------------------------------------------
if (showShapes && enableDiv) {
if (bullDiv) {
plotShape(
value=momentum,
shape="triangleup",
colorIndex=divBullColor,
width=2,
label=["Bull Div"],
desc=["Bullish regular divergence: price lower low, momentum higher low"]
)
}
if (bearDiv) {
plotShape(
value=momentum,
shape="triangledown",
colorIndex=divBearColor,
width=2,
label=["Bear Div"],
desc=["Bearish regular divergence: price higher high, momentum lower high"]
)
}
if (showHidden && hiddenBullDiv) {
plotShape(
value=momentum,
shape="arrowup",
colorIndex=divBullColor,
width=1,
label=["Hidden Bull"],
desc=["Hidden bullish divergence: price higher low, momentum lower low"]
)
}
if (showHidden && hiddenBearDiv) {
plotShape(
value=momentum,
shape="arrowdown",
colorIndex=divBearColor,
width=1,
label=["Hidden Bear"],
desc=["Hidden bearish divergence: price lower high, momentum higher high"]
)
}
}
// -----------------------------------------------------------------------------
// 14. SHAPE MARKERS — S/R DESTRUCTION
// -----------------------------------------------------------------------------
if (showSrShapes) {
if (resDestruction) {
plotShape(
value=hi,
shape="diamond",
colorIndex=srColor,
width=3,
label=["Res Destruction"],
desc=["Resistance destroyed with bearish divergence — potential reversal"]
)
}
if (supDestruction) {
plotShape(
value=lo,
shape="diamond",
colorIndex=srColor,
width=3,
label=["Sup Destruction"],
desc=["Support destroyed with bullish divergence — potential reversal"]
)
}
if (resContinuation) {
plotShape(
value=hi,
shape="triangleup",
colorIndex=bullColor,
width=2,
label=["Res Break"],
desc=["Resistance break with strengthening momentum — continuation bullish"]
)
}
if (supContinuation) {
plotShape(
value=lo,
shape="triangledown",
colorIndex=bearColor,
width=2,
label=["Sup Break"],
desc=["Support break with weakening momentum — continuation bearish"]
)
}
}
// -----------------------------------------------------------------------------
// 15. CROSSOVER SHAPES
// -----------------------------------------------------------------------------
if (showShapes) {
if (crossUp) {
plotShape(
value=signal,
shape="circle",
colorIndex=bullColor,
width=2,
label=["Cross Up"],
desc=["Momentum crossed above signal — bullish regime shift"]
)
}
if (crossDown) {
plotShape(
value=signal,
shape="circle",
colorIndex=bearColor,
width=2,
label=["Cross Down"],
desc=["Momentum crossed below signal — bearish regime shift"]
)
}
}
// -----------------------------------------------------------------------------
// 16. REGIME TABLE (last bar only)
// -----------------------------------------------------------------------------
if (isLastBar) {
var regimeText = regimeBull ? "BULLISH" : (regimeBear ? "BEARISH" : "NEUTRAL")
var regimeTextColor = regimeBull ? bullColor : (regimeBear ? bearColor : neutralColor)
plotTable(
data=[
["DDSDSD — Divergence & Destruction", regimeText],
["Momentum", momentum[0]],
["Signal", signal[0]],
["Histogram", hist[0]],
["Composite Score", composite[0]],
["Swing High", swingHigh[0]],
["Swing Low", swingLow[0]],
["Bull Div Count", divBullCount],
["Bear Div Count", divBearCount],
["S/R Breaks", srBreakCount],
["Bull Bars", regimeBullBars],
["Bear Bars", regimeBearBars]
],
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
)
}