Perfected FlowScript
DEMA Average True Range
DEMA ATR Bands — Perfected Edition is indexed as 109_dema_average_true_range.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
19.4 KB
Lines
678
Native Signal Candidates
12 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Squeeze
line 519:5
Trigger
(showSqueeze && squeezeNow)
Value
dema
Deps
showSqueeze:input, squeezeNow:var
DEMA Cross Up
line 531:5
Trigger
(showDemaCross && demaCrossUp)
Value
low
Deps
demaCrossUp:var, showDemaCross:input
DEMA Cross Down
line 541:5
Trigger
(showDemaCross && demaCrossDown)
Value
high
Deps
demaCrossDown:var, showDemaCross:input
Band 1 High Touch
line 553:5
Trigger
(showBandTouch && touchBand1Hi)
Value
band1Hi
Deps
showBandTouch:input, touchBand1Hi:var
Band 1 Low Touch
line 563:5
Trigger
(showBandTouch && touchBand1Lo)
Value
band1Lo
Deps
showBandTouch:input, touchBand1Lo:var
Band 2 High Touch
line 573:5
Trigger
(showBandTouch && touchBand2Hi)
Value
band2Hi
Deps
showBandTouch:input, touchBand2Hi:var
Band 2 Low Touch
line 583:5
Trigger
(showBandTouch && touchBand2Lo)
Value
band2Lo
Deps
showBandTouch:input, touchBand2Lo:var
Band 3 High Touch
line 593:5
Trigger
(showBandTouch && touchBand3Hi)
Value
band3Hi
Deps
showBandTouch:input, touchBand3Hi:var
Band 3 Low Touch
line 603:5
Trigger
(showBandTouch && touchBand3Lo)
Value
band3Lo
Deps
showBandTouch:input, touchBand3Lo:var
Breakout Up
line 615:5
Trigger
(showBandTouch && breakBand2Hi)
Value
band2Hi
Deps
breakBand2Hi:var, showBandTouch:input
Breakout Down
line 625:5
Trigger
(showBandTouch && breakBand2Lo)
Value
band2Lo
Deps
breakBand2Lo:var, showBandTouch:input
Squeeze Release
line 637:5
Trigger
(showSqueezeShapes && squeezeRelease)
Value
dema
Deps
showSqueezeShapes:input, squeezeRelease:var
109_dema_average_true_range.flowscript
source path: kscripts/perfected/109_dema_average_true_range.flowscript · sha256:aa45f93ea7b568707f8ebb25f393490d00ec99d01d0d20234632e20bfc700b01
//@version=2
// ============================================================================
// DEMA Average True Range — Perfected Edition
// Author: BackQuant (@BackQuant) | Enhanced by kScript_Perfection_Engineer
// Tags: CORE, SPECIALIZED, #dema, #atr, #volatility, #regime, #bands
//
// Production-quality DEMA-centered ATR volatility envelope system. Uses
// Mulloy's DEMA as the centerline for dynamic ATR bands, with regime
// detection, multi-band visualization, squeeze detection, and comprehensive
// shape-marked alert system.
//
// Research papers underpinning this design:
// 1. Mulloy (1994), "Smoothing Data With Faster Moving Averages":
// DEMA = (2 × EMA1) − EMA2; reduces lag vs. traditional EMAs while
// maintaining smoothness. The DEMA centerline stays closer to price
// bars than single or double-smoothed EMAs.
// 2. Wilder (1978), "New Concepts in Technical Trading Systems": canonical
// ATR formula — TR = max(H−L, |H−C(prev)|, |L−C(prev)|), then smoothed
// average over N periods. Foundation for all volatility-based bands.
// 3. Bollinger (2001), "Bollinger on Bollinger Bands": volatility-based
// bands expand and contract based on price volatility. %B measures
// where price sits within bands. BandWidth measures squeeze conditions.
// 4. Leung & Chong (2003), "An Empirical Comparison of Moving Average
// Envelopes and Bollinger Bands": BB superior to MAE at capturing
// abrupt price fluctuations; MAE can outperform in certain trending
// conditions. DEMA-ATR bands combine responsiveness with trend-following.
// 5. Keltner (1960) / Raschke refinement: modern Keltner uses ATR for
// volatility measurement, producing smoother bands than σ-based methods.
// Breakouts above/below channel signal trend continuation.
// ============================================================================
define(
title="DEMA ATR Bands — Perfected Edition",
position="onchart",
axis=false
)
// -----------------------------------------------------------------------------
// 1. USER INPUTS — grouped with constraints
// -----------------------------------------------------------------------------
// --- DEMA Settings ---
var demaLen = input(
name="demaLen",
type="number",
defaultValue=20,
label="DEMA Period",
constraints={min: 2, max: 200, step: 1},
group="DEMA Settings"
)
// --- ATR Settings ---
var atrLen = input(
name="atrLen",
type="number",
defaultValue=14,
label="ATR Period",
constraints={min: 2, max: 100, step: 1},
group="ATR Settings"
)
var atrSmooth = input(
name="atrSmooth",
type="boolean",
defaultValue=true,
label="DEMA-Smooth ATR",
group="ATR Settings"
)
var atrSmoothLen = input(
name="atrSmoothLen",
type="number",
defaultValue=5,
label="ATR Smoothing Length",
constraints={min: 1, max: 50, step: 1},
group="ATR Settings"
)
// --- Band Multipliers ---
var band1Mult = input(
name="band1Mult",
type="number",
defaultValue=1.0,
label="Band 1 Multiplier (×ATR)",
constraints={min: 0.1, max: 5.0, step: 0.1},
group="Bands"
)
var band2Mult = input(
name="band2Mult",
type="number",
defaultValue=2.0,
label="Band 2 Multiplier (×ATR)",
constraints={min: 0.1, max: 5.0, step: 0.1},
group="Bands"
)
var band3Mult = input(
name="band3Mult",
type="number",
defaultValue=3.0,
label="Band 3 Multiplier (×ATR)",
constraints={min: 0.1, max: 5.0, step: 0.1},
group="Bands"
)
var showBand1 = input(
name="showBand1",
type="boolean",
defaultValue=true,
label="Show Band 1",
group="Bands"
)
var showBand2 = input(
name="showBand2",
type="boolean",
defaultValue=true,
label="Show Band 2",
group="Bands"
)
var showBand3 = input(
name="showBand3",
type="boolean",
defaultValue=false,
label="Show Band 3",
group="Bands"
)
var showFill = input(
name="showFill",
type="boolean",
defaultValue=true,
label="Show Band Fills",
group="Bands"
)
// --- Squeeze Detection ---
var showSqueeze = input(
name="showSqueeze",
type="boolean",
defaultValue=true,
label="Show Squeeze Detection",
group="Squeeze"
)
var squeezeLookback = input(
name="squeezeLookback",
type="number",
defaultValue=20,
label="Squeeze Lookback (bars)",
constraints={min: 5, max: 100, step: 1},
group="Squeeze"
)
var squeezeThreshold = input(
name="squeezeThreshold",
type="number",
defaultValue=0.25,
label="Squeeze Threshold (% of range)",
constraints={min: 0.05, max: 0.5, step: 0.05},
group="Squeeze"
)
// --- Confluence MA ---
var showConfluence = input(
name="showConfluence",
type="boolean",
defaultValue=true,
label="Show Confluence MA",
group="Confluence"
)
var confluenceLen = input(
name="confluenceLen",
type="number",
defaultValue=50,
label="Confluence MA Length",
constraints={min: 5, max: 200, step: 1},
group="Confluence"
)
var confluenceType = input(
name="confluenceType",
type="select",
defaultValue="EMA",
label="Confluence MA Type",
options=["SMA", "EMA", "HMA", "DEMA"],
group="Confluence"
)
// --- Display ---
var showDemaCross = input(
name="showDemaCross",
type="boolean",
defaultValue=true,
label="Show DEMA Cross Shapes",
group="Display"
)
var showBandTouch = input(
name="showBandTouch",
type="boolean",
defaultValue=true,
label="Show Band Touch Shapes",
group="Display"
)
var showSqueezeShapes = input(
name="showSqueezeShapes",
type="boolean",
defaultValue=true,
label="Show Squeeze Shapes",
group="Display"
)
var lineWidth = input(
name="lineWidth",
type="number",
defaultValue=2,
label="Line Width",
constraints={min: 1, max: 4, step: 1},
group="Display"
)
var shapeSize = input(
name="shapeSize",
type="number",
defaultValue=2,
label="Shape Size",
constraints={min: 1, max: 4, step: 1},
group="Display"
)
// --- Colors ---
var demaColor = input(
name="demaColor",
type="color",
defaultValue="#ff9800",
label="DEMA Color",
group="Colors"
)
var bullColor = input(
name="bullColor",
type="color",
defaultValue="#26a69a",
label="Bull Color (above DEMA)",
group="Colors"
)
var bearColor = input(
name="bearColor",
type="color",
defaultValue="#ef5350",
label="Bear Color (below DEMA)",
group="Colors"
)
var bandColor = input(
name="bandColor",
type="color",
defaultValue="#9e9e9e",
label="Band Line Color",
group="Colors"
)
var squeezeColor = input(
name="squeezeColor",
type="color",
defaultValue="#ffca28",
label="Squeeze Color",
group="Colors"
)
var confColor = input(
name="confColor",
type="color",
defaultValue="#2962ff",
label="Confluence MA Color",
group="Colors"
)
// -----------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// -----------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries close = bars.close
timeseries high = bars.high
timeseries low = bars.low
timeseries open = bars.open
if (isnan(close[0]) || isnan(high[0]) || isnan(low[0]) || isnan(open[0])) {
return
}
// -----------------------------------------------------------------------------
// 3. DEMA CENTERLINE (Mulloy 1994)
// -----------------------------------------------------------------------------
// DEMA = (2 × EMA1) − EMA2, where EMA2 = EMA(EMA1)
timeseries ema1 = ema(source=close, period=demaLen)
timeseries ema2 = ema(source=ema1, period=demaLen)
timeseries dema = 2 * ema1 - ema2
// -----------------------------------------------------------------------------
// 4. ATR (Wilder 1978) with optional DEMA smoothing
// -----------------------------------------------------------------------------
// True Range = max(H−L, |H−C(prev)|, |L−C(prev)|)
timeseries tr1 = high - low
timeseries tr2 = abs(high - close[1])
timeseries tr3 = abs(low - close[1])
timeseries trueRange = math.max(tr1, math.max(tr2, tr3))
// Raw ATR using RMA (Wilder's smoothing)
timeseries atrRaw = rma(source=trueRange, period=atrLen)
// Optional DEMA smoothing on ATR for cleaner bands
timeseries atrEma1 = ema(source=atrRaw, period=atrSmoothLen)
timeseries atrEma2 = ema(source=atrEma1, period=atrSmoothLen)
timeseries atrDema = 2 * atrEma1 - atrEma2
timeseries atr = atrSmooth ? atrDema : atrRaw
// -----------------------------------------------------------------------------
// 5. DYNAMIC BANDS
// -----------------------------------------------------------------------------
timeseries band1Hi = dema + band1Mult * atr
timeseries band1Lo = dema - band1Mult * atr
timeseries band2Hi = dema + band2Mult * atr
timeseries band2Lo = dema - band2Mult * atr
timeseries band3Hi = dema + band3Mult * atr
timeseries band3Lo = dema - band3Mult * atr
// Bandwidth as percentage of centerline (Bollinger BandWidth concept)
timeseries bandWidth = (band2Hi - band2Lo) / dema * 100
// -----------------------------------------------------------------------------
// 6. REGIME DETECTION
// -----------------------------------------------------------------------------
// Price relative to DEMA centerline
var aboveDema = close > dema
var belowDema = close < dema
// Trend strength: how many bands has price penetrated?
var inBand1 = close > band1Lo && close < band1Hi
var inBand2 = close > band2Lo && close < band2Hi
var aboveBand1 = close > band1Hi
var belowBand1 = close < band1Lo
var aboveBand2 = close > band2Hi
var belowBand2 = close < band2Lo
var regimeBull = close > dema && close > band1Hi
var regimeBear = close < dema && close < band1Lo
var regimeNeutral = !regimeBull && !regimeBear
var regimeColor = regimeBull ? bullColor : (regimeBear ? bearColor : "#9e9e9e")
// -----------------------------------------------------------------------------
// 7. SQUEEZE DETECTION (static tracking)
// -----------------------------------------------------------------------------
// Bandwidth at its lowest in N bars = squeeze condition (preceding volatility
// expansion). Uses static for lowest-bandwidth tracking.
static lowestBandwidth = -1.0
static squeezeActive = false
static squeezeBarCount = 0
var squeezeNow = false
var squeezeRelease = false
if (lowestBandwidth < 0) {
lowestBandwidth = bandWidth[0]
}
// Update lowest bandwidth in lookback window
var lowestBwInPeriod = lowest(source=bandWidth, period=squeezeLookback)
if (bandWidth[0] <= lowestBwInPeriod) {
lowestBandwidth = bandWidth[0]
}
// Squeeze active when current bandwidth is within threshold of its lowest
var squeezePct = lowestBandwidth > 0 ? bandWidth[0] / lowestBandwidth : 1.0
squeezeNow = squeezePct <= (1.0 + squeezeThreshold)
if (squeezeNow && !squeezeActive) {
squeezeActive = true
squeezeBarCount = 1
} else if (squeezeNow && squeezeActive) {
squeezeBarCount = squeezeBarCount + 1
} else if (!squeezeNow && squeezeActive) {
squeezeRelease = true
squeezeActive = false
squeezeBarCount = 0
}
// -----------------------------------------------------------------------------
// 8. CONFLUENCE MA
// -----------------------------------------------------------------------------
timeseries confMA = 0.0
if (confluenceType == "SMA") {
confMA = sma(source=close, period=confluenceLen)
} else if (confluenceType == "EMA") {
confMA = ema(source=close, period=confluenceLen)
} else if (confluenceType == "HMA") {
var halfLen = math.floor(confluenceLen / 2)
var sqrtLen = math.floor(math.sqrt(confluenceLen))
var wmaFast = ema(source=close, period=halfLen)
var wmaSlow = ema(source=close, period=confluenceLen)
confMA = ema(source=2 * wmaFast - wmaSlow, period=sqrtLen)
} else {
var confEma1 = ema(source=close, period=confluenceLen)
var confEma2 = ema(source=confEma1, period=confluenceLen)
confMA = 2 * confEma1 - confEma2
}
// -----------------------------------------------------------------------------
// 9. CROSS & TOUCH DETECTION (shape markers)
// -----------------------------------------------------------------------------
var demaCrossUp = close > dema && close[1] <= dema[1]
var demaCrossDown = close < dema && close[1] >= dema[1]
// Band touches (price intraday touches band)
var touchBand1Hi = high >= band1Hi && low <= band1Hi
var touchBand1Lo = high >= band1Lo && low <= band1Lo
var touchBand2Hi = high >= band2Hi && low <= band2Hi
var touchBand2Lo = high >= band2Lo && low <= band2Lo
var touchBand3Hi = high >= band3Hi && low <= band3Hi
var touchBand3Lo = high >= band3Lo && low <= band3Lo
// Breakouts (close beyond band)
var breakBand2Hi = close > band2Hi && close[1] <= band2Hi[1]
var breakBand2Lo = close < band2Lo && close[1] >= band2Lo[1]
// -----------------------------------------------------------------------------
// 10. PLOTTING
// -----------------------------------------------------------------------------
// --- DEMA Centerline (regime-colored) ---
plotLine(
value=dema,
width=lineWidth,
colors=[bullColor, bearColor],
colorIndex=aboveDema ? 0 : 1,
label=["DEMA"],
desc=["Double EMA centerline (Mulloy " + demaLen + ")"]
)
// --- Confluence MA ---
if (showConfluence) {
plotLine(
value=confMA,
width=lineWidth,
colors=[confColor],
label=[(confluenceType + " " + confluenceLen)],
desc=["Confluence moving average for trend confirmation"]
)
}
// --- Band 1 Fill & Lines ---
if (showBand1) {
if (showFill) {
plotLine(
value=[band1Lo, band1Hi],
width=1,
colors=[transparency(bullColor, 15), transparency(bearColor, 15)],
colorIndex=aboveDema ? 0 : 1,
fill=true,
label=["±1 ATR Fill"],
desc=["±1 ATR band fill (regime-colored)"]
)
}
plotLine(
value=band1Hi,
width=1,
colors=[bandColor],
label=["+1 ATR"],
desc=["Upper band at 1× ATR multiplier"]
)
plotLine(
value=band1Lo,
width=1,
colors=[bandColor],
label=["-1 ATR"],
desc=["Lower band at 1× ATR multiplier"]
)
}
// --- Band 2 Fill & Lines ---
if (showBand2) {
if (showFill) {
plotLine(
value=[band2Lo, band2Hi],
width=1,
colors=[transparency(bullColor, 10), transparency(bearColor, 10)],
colorIndex=aboveDema ? 0 : 1,
fill=true,
label=["±2 ATR Fill"],
desc=["±2 ATR band fill (regime-colored)"]
)
}
plotLine(
value=band2Hi,
width=1,
colors=[bandColor],
label=["+2 ATR"],
desc=["Upper band at 2× ATR multiplier"]
)
plotLine(
value=band2Lo,
width=1,
colors=[bandColor],
label=["-2 ATR"],
desc=["Lower band at 2× ATR multiplier"]
)
}
// --- Band 3 Lines ---
if (showBand3) {
plotLine(
value=band3Hi,
width=1,
colors=[bandColor],
label=["+3 ATR"],
desc=["Upper band at 3× ATR multiplier"]
)
plotLine(
value=band3Lo,
width=1,
colors=[bandColor],
label=["-3 ATR"],
desc=["Lower band at 3× ATR multiplier"]
)
}
// --- Squeeze Highlight ---
if (showSqueeze && squeezeNow) {
plotShape(
value=dema,
shape="diamond",
colorIndex=squeezeColor,
width=shapeSize,
label=["Squeeze"],
desc=["ATR bandwidth squeeze detected (potential breakout)"]
)
}
// --- Shape Markers: DEMA Cross ---
if (showDemaCross && demaCrossUp) {
plotShape(
value=low,
shape="triangleup",
colorIndex=bullColor,
width=shapeSize,
label=["DEMA Cross Up"],
desc=["Price crossed above DEMA centerline"]
)
}
if (showDemaCross && demaCrossDown) {
plotShape(
value=high,
shape="triangledown",
colorIndex=bearColor,
width=shapeSize,
label=["DEMA Cross Down"],
desc=["Price crossed below DEMA centerline"]
)
}
// --- Shape Markers: Band Touch ---
if (showBandTouch && touchBand1Hi) {
plotShape(
value=band1Hi,
shape="triangledown",
colorIndex=bandColor,
width=shapeSize,
label=["Band 1 High Touch"],
desc=["Price touched upper 1× ATR band"]
)
}
if (showBandTouch && touchBand1Lo) {
plotShape(
value=band1Lo,
shape="triangleup",
colorIndex=bandColor,
width=shapeSize,
label=["Band 1 Low Touch"],
desc=["Price touched lower 1× ATR band"]
)
}
if (showBandTouch && touchBand2Hi) {
plotShape(
value=band2Hi,
shape="triangledown",
colorIndex=bandColor,
width=shapeSize,
label=["Band 2 High Touch"],
desc=["Price touched upper 2× ATR band"]
)
}
if (showBandTouch && touchBand2Lo) {
plotShape(
value=band2Lo,
shape="triangleup",
colorIndex=bandColor,
width=shapeSize,
label=["Band 2 Low Touch"],
desc=["Price touched lower 2× ATR band"]
)
}
if (showBandTouch && touchBand3Hi) {
plotShape(
value=band3Hi,
shape="triangledown",
colorIndex=bandColor,
width=shapeSize,
label=["Band 3 High Touch"],
desc=["Price touched upper 3× ATR band"]
)
}
if (showBandTouch && touchBand3Lo) {
plotShape(
value=band3Lo,
shape="triangleup",
colorIndex=bandColor,
width=shapeSize,
label=["Band 3 Low Touch"],
desc=["Price touched lower 3× ATR band"]
)
}
// --- Shape Markers: Band 2 Breakout ---
if (showBandTouch && breakBand2Hi) {
plotShape(
value=band2Hi,
shape="arrowup",
colorIndex=bullColor,
width=shapeSize,
label=["Breakout Up"],
desc=["Price broke above 2× ATR band (strong bullish)"]
)
}
if (showBandTouch && breakBand2Lo) {
plotShape(
value=band2Lo,
shape="arrowdown",
colorIndex=bearColor,
width=shapeSize,
label=["Breakout Down"],
desc=["Price broke below 2× ATR band (strong bearish)"]
)
}
// --- Squeeze Release Shape ---
if (showSqueezeShapes && squeezeRelease) {
plotShape(
value=dema,
shape="circle",
colorIndex=squeezeColor,
width=shapeSize,
label=["Squeeze Release"],
desc=["Squeeze released — volatility expansion likely"]
)
}
// -----------------------------------------------------------------------------
// 11. REGIME TABLE (last bar only)
// -----------------------------------------------------------------------------
if (isLastBar) {
var regimeText = regimeBull ? "BULLISH" : (regimeBear ? "BEARISH" : "NEUTRAL")
var regimeTextColor = regimeBull ? bullColor : (regimeBear ? bearColor : "#9e9e9e")
plotTable(
data=[
["DEMA ATR — Perfected", regimeText],
["DEMA", dema[0]],
["ATR", atr[0]],
["BandWidth %", bandWidth[0]],
["Squeeze", squeezeNow ? "ACTIVE" : "OFF"],
["Band 1", band1Mult + "×"],
["Band 2", band2Mult + "×"],
["Band 3", band3Mult + "×"]
],
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
)
}