Perfected FlowScript
Supertrend
Supertrend Perfected is indexed as 069_supertrend.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
10.5 KB
Lines
276
Native Signal Candidates
3 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Bull Flip
line 244:5
Trigger
(showTrendFlip && trendFlipUp)
Value
st
Deps
showTrendFlip:input, trendFlipUp:var
Bear Flip
line 254:5
Trigger
(showTrendFlip && trendFlipDown)
Value
st
Deps
showTrendFlip:input, trendFlipDown:var
Unlabeled shape
line 266:5
Trigger
(showTrendLabel && isLastBar)
Value
h
Deps
isLastBar:builtin, showTrendLabel:input
069_supertrend.flowscript
source path: kscripts/perfected/069_supertrend.flowscript · sha256:973ca3fb0bbfa5077f4a93aaeac63ad04ecde2cc8a85a521761c7d0d2511f3ec
//@version=2
// ============================================================================
// Supertrend — ATR-Based Trend Overlay [Perfected]
// Author: BackQuant (@BackQuant) | Perfected: kScript_Perfection_Engineer
// Tags: CORE, #trend, #atr, #supertrend
//
// Production-grade Supertrend with ATR-based dynamic bands, trend direction
// state machine, color-coded fill between bands, shape markers for trend
// changes, and static state persistence for robust trend tracking.
//
// Academic foundations:
// - Wilder (1978), "New Concepts in Technical Trading Systems", Trend Research.
// [Formula] ATR = average of True Range over N periods; TR = max(H−L,
// |H−C[1]|, |L−C[1]|). Supertrend is entirely built on ATR-based bands.
//
// - Abdul Rahman (2024), "Optimising Supertrend Parameters using Bayesian
// Optimisation for Maximising Profit". Upper Band = (H+L)/2 + (ATR×M);
// Lower Band = (H+L)/2 − (ATR×M); trend flips when price crosses the
// active trailing band.
//
// - Dr. Sven-Olaf Schmidt (2011), "Evaluation of Super-Trend Indicator's
// Parameters for Major FOREX Pairs over 12 Years". Systematic analysis of
// 9,200 parameter pairs; best overall: multiplier 7.9, window 9. Parameter
// robustness varies by currency (EUR/USD wide, GBP/JPY narrow).
//
// - Hurst, Ooi & Pedersen (2014), "A Century of Evidence on Trend-Following
// Investing". Time-series momentum profitable since 1880 across nearly
// all asset classes. Supertrend aligns with this long-term evidence.
//
// - Valeriy Zakamulin (2023), "Optimal Trend-Following with Transaction Costs".
// Mathematical justification for MA-based trend-following rules; supports
// ATR-band trailing-stop logic.
// ============================================================================
define(
title="Supertrend Perfected",
position="onchart",
axis=false
)
// ---------------------------------------------------------------------------
// User Inputs — all grouped, all numeric inputs carry constraints
// ---------------------------------------------------------------------------
// --- Bands ---
var atrLen = input(name="atrLen", type="number", defaultValue=10, label="ATR Period", constraints={min: 2, max: 100, step: 1}, group="Bands")
var factor = input(name="factor", type="number", defaultValue=3.0, label="ATR Multiplier", constraints={min: 0.5, max: 10.0, step: 0.5}, group="Bands")
var showBands = input(name="showBands", type="boolean", defaultValue=true, label="Show Basic Bands", group="Bands")
// --- Display ---
var showFill = input(name="showFill", type="boolean", defaultValue=true, label="Show Band Fill", group="Display")
var showTrendFlip = input(name="showTrendFlip", type="boolean", defaultValue=true, label="Show Trend-Flip Shapes", group="Display")
var showTrendLabel = input(name="showTrendLabel", type="boolean", defaultValue=true, label="Show Trend Label", 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 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 bandUpColor = input(name="bandUpColor", type="color", defaultValue="#26a69a", label="Upper Band Color", group="Colors")
var bandDnColor = input(name="bandDnColor", type="color", defaultValue="#ef5350", label="Lower Band Color", group="Colors")
var flipUpColor = input(name="flipUpColor", type="color", defaultValue="#00c853", label="Bullish Flip Color", group="Colors")
var flipDnColor = input(name="flipDnColor", type="color", defaultValue="#d50000", label="Bearish Flip Color", group="Colors")
// ---------------------------------------------------------------------------
// Data Sources
// ---------------------------------------------------------------------------
timeseries pxTS = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries o = pxTS.open
timeseries h = pxTS.high
timeseries l = pxTS.low
timeseries c = pxTS.close
// isnan guard: prevent computation on incomplete data
if (isnan(c[0]) || isnan(h[0]) || isnan(l[0]) || isnan(o[0])) {
return
}
// ---------------------------------------------------------------------------
// True Range & ATR (Wilder)
// ---------------------------------------------------------------------------
// TR = max(high − low, |high − close[1]|, |low − close[1]|)
// ATR = RMA(TR, atrLen) — using proper RMA smoothing as per Wilder (1978).
// ---------------------------------------------------------------------------
timeseries prevClose = isnan(c[1]) ? c : c[1]
timeseries tr1 = h - l
timeseries tr2 = math.abs(h - prevClose)
timeseries tr3 = math.abs(l - prevClose)
timeseries trueRange = math.max(tr1, math.max(tr2, tr3))
timeseries atr = rma(trueRange, atrLen)
// ---------------------------------------------------------------------------
// Basic Bands
// ---------------------------------------------------------------------------
// Upper Band = (High + Low) / 2 + (ATR × Multiplier)
// Lower Band = (High + Low) / 2 − (ATR × Multiplier)
// ---------------------------------------------------------------------------
timeseries hl2 = (h + l) / 2.0
timeseries upperBand = hl2 + factor * atr
timeseries lowerBand = hl2 - factor * atr
// ---------------------------------------------------------------------------
// Supertrend State Machine (static variables for trend persistence)
// ---------------------------------------------------------------------------
// finalUpper / finalLower: trailing bands that only tighten in the direction
// of the current trend and do not expand unnecessarily.
//
// Trend flips:
// Bullish flip: close > previous finalUpper (price breaks above resistance)
// Bearish flip: close < previous finalLower (price breaks below support)
//
// Supertrend value (st):
// Bullish trend: max(previous st, finalLower) — only rises
// Bearish trend: min(previous st, finalUpper) — only falls
// ---------------------------------------------------------------------------
static finalUpper = 0.0
static finalLower = 0.0
static dir = 1.0 // 1.0 = bullish, -1.0 = bearish
static st = 0.0 // Supertrend value (active trailing stop)
static prevDir = 1.0 // Previous direction for flip detection
// Initialize on first bar
if (finalUpper == 0.0 || isnan(finalUpper)) {
finalUpper = upperBand
finalLower = lowerBand
// Determine initial direction based on close vs bands
if (c > upperBand) {
dir = 1.0
st = finalLower
} else if (c < lowerBand) {
dir = -1.0
st = finalUpper
} else {
// Price between bands; default bullish
dir = 1.0
st = finalLower
}
prevDir = dir
}
// Update final bands (tightening logic)
// Upper band tightens downward; lower band tightens upward.
// Reset to basic band on a trend flip.
finalUpper = (upperBand < finalUpper[1]) || (c[1] > finalUpper[1]) ? upperBand : finalUpper[1]
finalLower = (lowerBand > finalLower[1]) || (c[1] < finalLower[1]) ? lowerBand : finalLower[1]
// Trend flip detection
var bullishFlip = c > finalUpper
var bearishFlip = c < finalLower
// State transition
if (bullishFlip) {
dir = 1.0
st = finalLower
} else if (bearishFlip) {
dir = -1.0
st = finalUpper
} else {
// No flip: tighten the trailing stop in the direction of the trend
st = dir > 0 ? math.max(st[1], finalLower) : math.min(st[1], finalUpper)
}
// Trend flip event flag (for shape plotting)
var trendFlipUp = dir > 0 && prevDir <= 0
var trendFlipDown = dir < 0 && prevDir >= 0
// Update static prevDir on bar close
if (!isLiveUpdate) {
prevDir = dir
}
// ---------------------------------------------------------------------------
// Regime Detection & Trend Strength
// ---------------------------------------------------------------------------
// Trend strength: consecutive bars in the same direction.
// ---------------------------------------------------------------------------
static bullStreak = 0
static bearStreak = 0
if (!isLiveUpdate) {
if (dir > 0) {
bullStreak = bullStreak + 1
bearStreak = 0
} else {
bearStreak = bearStreak + 1
bullStreak = 0
}
}
var trendLabel = dir > 0 ? "BULLISH TREND" : "BEARISH TREND"
var trendColor = dir > 0 ? upColor : dnColor
// ---------------------------------------------------------------------------
// Visualization
// ---------------------------------------------------------------------------
// --- Supertrend Line (regime-colored) ---
plotLine(
value=st,
width=lineWidth,
colors=[upColor, dnColor],
colorIndex=dir > 0 ? 0 : 1,
label=["Supertrend"],
desc=["ATR-based trailing stop; bullish when price holds above, bearish when below"]
)
// --- Basic Band Lines ---
if (showBands) {
plotLine(
value=upperBand,
width=1,
colors=[bandUpColor],
label=["Upper Band"],
desc=["Basic upper band: (H+L)/2 + ATR × multiplier"]
)
plotLine(
value=lowerBand,
width=1,
colors=[bandDnColor],
label=["Lower Band"],
desc=["Basic lower band: (H+L)/2 − ATR × multiplier"]
)
}
// --- Band Fill (regime-colored, reduced opacity) ---
if (showFill) {
plotLine(
value=([upperBand, lowerBand]),
width=1,
colors=[opacity(upColor, 10), opacity(dnColor, 10)],
colorIndex=dir > 0 ? 0 : 1,
fill=true,
label=["Band Fill"],
desc=["ATR band fill colored by current trend direction"]
)
}
// --- Trend Flip Shape Markers ---
if (showTrendFlip && trendFlipUp) {
plotShape(
value=st,
shape="triangleup",
colorIndex=flipUpColor,
width=shapeSize + 2,
label=["Bull Flip"],
desc=["Trend flipped bullish: price closed above the upper trailing band"]
)
}
if (showTrendFlip && trendFlipDown) {
plotShape(
value=st,
shape="triangledown",
colorIndex=flipDnColor,
width=shapeSize + 2,
label=["Bear Flip"],
desc=["Trend flipped bearish: price closed below the lower trailing band"]
)
}
// --- Trend Label (on last bar) ---
if (showTrendLabel && isLastBar) {
plotPriceLabel(
price=h,
text=trendLabel,
type="callout",
color="#ffffff",
backgroundColor=trendColor,
size=10,
fontWeight=700
)
}