Perfected FlowScript
SCF Trend Indicator
SCF Trend Indicator V2 is indexed as 017_scf_trend_indicator.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
15.6 KB
Lines
463
Native Signal Candidates
2 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Golden Cross
line 411:9
Trigger
(showShapes) && (crossUp)
Value
fastEma
Deps
crossUp:var, showShapes:input
Death Cross
line 421:9
Trigger
(showShapes) && (crossDn)
Value
fastEma
Deps
crossDn:var, showShapes:input
017_scf_trend_indicator.flowscript
source path: kscripts/perfected/017_scf_trend_indicator.flowscript · sha256:ade46603ef925da7a32e8798a7bb3469cf40afdbb081da2f36a65e84fe9c8e5d
//@version=2
// ============================================================================
// SCF Trend Indicator V2 — Production-Quality Adaptive EMA Lane System
// Author: SoulzBTC (@SoulzBTC) | Perfected by: kScript Perfection Engineer
// Tags: CORE, #trend, #ema, #lane, #momentum, #adaptive, #volatility
//
// Dual-period adaptive EMA lane system with momentum-sensitive color encoding,
// transparency gradients based on trend strength, and dynamic band width
// responding to ATR/volatility clustering. Fill areas between fast and slow
// EMAs with regime-based color coding. Shape markers for crossovers.
//
// FORMULA FOUNDATION:
// 1. Fast EMA: EMA_fast = EMA(price, fastLen) — responsive edge
// 2. Slow EMA: EMA_slow = EMA(price, slowLen) — structural trend
// 3. ATR Band Width: Band = ATR(atrLen) × atrMult per Wilder (1978) and
// Kaufman (1995) adaptive smoothing concepts.
// 4. Lane Construction: Upper = max(EMA_fast, EMA_slow) + Band;
// Lower = min(EMA_fast, EMA_slow) − Band
// 5. Trend Strength: strength = |EMA_fast − EMA_slow| / (ATR × atrMult) ∈ [0, ∞
// Normalized to [0, 1] for transparency gradient.
// 6. Momentum Color Encoding: bull = fast > slow; bear = fast < slow;
// intensity modulated by trend strength.
// 7. Kaufman Efficiency Ratio (optional): ER = |ΔP| / Σ|ΔP| ∈ [0,1] per
// Kaufman (1995) — used for adaptive smoothing confirmation.
//
// RESEARCH BASIS:
// • Kaufman (1995), "Smarter Trading: Improving Performance in Changing
// Markets", McGraw-Hill. Introduced Efficiency Ratio (ER) and KAMA;
// supports adaptive band-width response to volatility clustering. [^1]
// • Manasa & Reddy (2025), "Trend Analysis by Weighted and Exponential
// Moving Average", IJRIAS. Combined WMA/EMA approaches yield more robust
// trading decisions; dual-period systems outperform single-period. [^2]
// • Hurst, Ooi & Pedersen (2014), "A Century of Evidence on Trend-Following
// Investing", AQR Capital Management. Trend following delivers strong
// positive returns with low correlation across 130+ years. [^3]
// • Wilder (1978), "New Concepts in Technical Trading Systems", Trend Research.
// Canonical ATR formulation; original smoothing period = 14. [^4]
// • Bollinger (2001), "Bollinger on Bollinger Bands", McGraw-Hill. Volatility
// bands expand/contract based on price dispersion; %B measures position
// within bands. [^5]
// • Khand et al. (2019), "EMA, MACD, RSI and Momentum Trading Rules in the
// Pakistan Stock Market", Indian J. Science and Technology. EMA variants
// showed substantial prognostic capability and remained profitable after
// transaction costs. [^6]
// • Clare et al. (2013), "Trend Following, Stop Losses, and the Frequency of
// Trading", Cass Business School. Simple MA rules outperform complex ones;
// 10-month MA produced highest Sharpe ratio. [^7]
// ============================================================================
define(
title="SCF Trend Indicator V2",
position="onchart",
axis=false
)
// ------------------------------------------------------------------------------
// User Inputs — grouped and constrained per production spec
// ------------------------------------------------------------------------------
// --- EMA Configuration ---
var fastLen = input(
name="fastLen",
type="number",
defaultValue=21,
label="Fast EMA Length",
constraints={min: 2, max: 200, step: 1},
group="EMA"
)
var slowLen = input(
name="slowLen",
type="number",
defaultValue=55,
label="Slow EMA Length",
constraints={min: 2, max: 200, step: 1},
group="EMA"
)
var useAdaptive = input(
name="useAdaptive",
type="boolean",
defaultValue=true,
label="Use Adaptive Smoothing (Kaufman-style)",
group="EMA"
)
// --- ATR / Volatility Band ---
var atrLen = input(
name="atrLen",
type="number",
defaultValue=14,
label="ATR Length",
constraints={min: 2, max: 50, step: 1},
group="Volatility Band"
)
var atrMult = input(
name="atrMult",
type="number",
defaultValue=1.5,
label="Lane Width Multiplier",
constraints={min: 0.1, max: 5.0, step: 0.1},
group="Volatility Band"
)
var useDynamicBand = input(
name="useDynamicBand",
type="boolean",
defaultValue=true,
label="Dynamic Band Width (ATR-based)",
group="Volatility Band"
)
// --- Display ---
var showFastSlow = input(
name="showFastSlow",
type="boolean",
defaultValue=true,
label="Show Fast & Slow EMAs",
group="Display"
)
var showFill = input(
name="showFill",
type="boolean",
defaultValue=true,
label="Show EMA Fill Area",
group="Display"
)
var showLane = input(
name="showLane",
type="boolean",
defaultValue=true,
label="Show Volatility Lane Bands",
group="Display"
)
var showLaneFill = input(
name="showLaneFill",
type="boolean",
defaultValue=true,
label="Show Lane Fill (ATR bands)",
group="Display"
)
var showShapes = input(
name="showShapes",
type="boolean",
defaultValue=true,
label="Show Crossover Shapes",
group="Display"
)
var showStrength = input(
name="showStrength",
type="boolean",
defaultValue=true,
label="Show Trend Strength 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 fastColor = input(
name="fastColor",
type="color",
defaultValue="#2962ff",
label="Fast EMA Color",
group="Colors"
)
var slowColor = input(
name="slowColor",
type="color",
defaultValue="#ff6d00",
label="Slow EMA Color",
group="Colors"
)
var laneColor = input(
name="laneColor",
type="color",
defaultValue="#ffffff",
label="Lane Band Color",
group="Colors"
)
// ------------------------------------------------------------------------------
// Data Sources & NaN Guard
// ------------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries px = bars.close
timeseries hi = bars.high
timeseries lo = bars.low
if (isnan(px[0])) {
return
}
// ------------------------------------------------------------------------------
// EMA Computation — Dual Period Adaptive Lanes
// ------------------------------------------------------------------------------
// Fast EMA = responsive trend edge; Slow EMA = structural trend backbone.
// Per Kaufman (1995), adaptive smoothing responds to market efficiency.
timeseries fastEma = ema(source=px, period=fastLen)
timeseries slowEma = ema(source=px, period=slowLen)
// ------------------------------------------------------------------------------
// ATR / Volatility Band (Wilder 1978)
// ------------------------------------------------------------------------------
// True Range = max(high − low, |high − prevClose|, |low − prevClose|)
// ATR = SMA(TR, atrLen)
// Band width = ATR × atrMult (Keltner-style channel per Keltner 1960 / Raschke 1980s)
timeseries tr1 = hi[0] - lo[0]
timeseries tr2 = abs(hi[0] - px[1])
timeseries tr3 = abs(lo[0] - px[1])
timeseries trueRange = math.max(tr1, math.max(tr2, tr3))
timeseries atr = sma(source=trueRange, period=atrLen)
timeseries laneWidth = useDynamicBand ? atr * atrMult : atrLen * 0.1 * px[0]
// ------------------------------------------------------------------------------
// Lane Construction — Dynamic Upper/Lower Bounds
// ------------------------------------------------------------------------------
// Upper = max(fast, slow) + Band; Lower = min(fast, slow) − Band.
// This creates a volatility-responsive channel that "breathes" with market
// conditions per Bollinger (2001) and Kaufman (1995).
timeseries laneTop = math.max(fastEma[0], slowEma[0]) + laneWidth
timeseries laneBot = math.min(fastEma[0], slowEma[0]) - laneWidth
// ------------------------------------------------------------------------------
// Trend Regime & Strength Detection
// ------------------------------------------------------------------------------
// Regime: bull = fast > slow; bear = fast < slow.
// Trend Strength = normalized distance between EMAs relative to ATR band.
// strength = clamp(|fast − slow| / (ATR × atrMult), 0, 1)
// Used for transparency gradient: stronger trend = more opaque fill.
var isBullish = fastEma[0] > slowEma[0]
var isBearish = fastEma[0] < slowEma[0]
var emaDiff = abs(fastEma[0] - slowEma[0])
var bandBase = atr * atrMult
var rawStrength = bandBase > 0 ? emaDiff / bandBase : 0.0
var trendStrength = math.min(1.0, rawStrength) // normalized to [0, 1]
// Momentum intensity for color modulation
var momentumIntensity = math.min(1.0, trendStrength * 2.0)
// ------------------------------------------------------------------------------
// Kaufman Efficiency Ratio (optional confirmation)
// ------------------------------------------------------------------------------
// ER = |price − price[N]| / Σ|price[i] − price[i−1]| for i = 1..N
// ER → 1 = trending; ER → 0 = ranging. Per Kaufman (1995).
timeseries priceChange = abs(px[0] - px[fastLen])
timeseries sumVolatility = 0.0
for (i = 1; i <= fastLen; i = i + 1) {
sumVolatility = sumVolatility + abs(px[i] - px[i - 1])
}
timeseries efficiencyRatio = sumVolatility > 0 ? priceChange / sumVolatility : 0.0
// ------------------------------------------------------------------------------
// Static State Tracking (Session-level persistence)
// ------------------------------------------------------------------------------
// Tracks crossover counts, regime duration, and lane penetration statistics.
static lastRegime = 0 // 1 = bull, -1 = bear, 0 = neutral/initial
static crossUpCount = 0
static crossDnCount = 0
static maxLaneWidth = 0.0
static avgLaneWidth = 0.0
static laneWidthSum = 0.0
static barCount = 0
static lastBarIndex = 0
var currentBarIndex = bar_index[0]
var crossUp = fastEma[0] > slowEma[0] && !isnan(fastEma[1]) && fastEma[1] <= slowEma[1]
var crossDn = fastEma[0] < slowEma[0] && !isnan(fastEma[1]) && fastEma[1] >= slowEma[1]
if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
lastBarIndex = currentBarIndex
barCount = barCount + 1
// Regime change tracking
var currentRegime = isBullish ? 1 : (isBearish ? -1 : 0)
if (lastRegime != 0 && lastRegime != currentRegime) {
if (currentRegime == 1) {
crossUpCount = crossUpCount + 1
} else if (currentRegime == -1) {
crossDnCount = crossDnCount + 1
}
}
lastRegime = currentRegime
// Lane width statistics
laneWidthSum = laneWidthSum + laneWidth[0]
avgLaneWidth = laneWidthSum / barCount
if (laneWidth[0] > maxLaneWidth) {
maxLaneWidth = laneWidth[0]
}
}
// ------------------------------------------------------------------------------
// Plots — Multi-Layer Visualization (Lines, Fill, Lane Bands, Shapes, Histogram)
// ------------------------------------------------------------------------------
// --- Lane Fill (ATR bands) ---
// Semi-transparent fill between upper and lower lane bounds.
// Color and opacity modulated by trend regime and strength.
if (showLaneFill) {
var laneFillColor = isBullish ? bullColor : bearColor
var laneFillOpacity = math.min(80, 15 + trendStrength * 40)
plotLine(
value=[laneTop, laneBot],
width=1,
colors=[opacity(laneFillColor, laneFillOpacity)],
fill=true,
label=["Lane Top", "Lane Bot"],
desc=["Upper ATR lane bound", "Lower ATR lane bound"]
)
}
// --- Lane Boundary Lines ---
if (showLane) {
plotLine(
value=laneTop,
width=1,
colors=[opacity(laneColor, 30)],
label=["Lane Top"],
desc=["Upper lane bound = max(EMA) + ATR × " + atrMult]
)
plotLine(
value=laneBot,
width=1,
colors=[opacity(laneColor, 30)],
label=["Lane Bot"],
desc=["Lower lane bound = min(EMA) − ATR × " + atrMult]
)
}
// --- EMA Fill Area (between fast and slow) ---
// Momentum-sensitive color with transparency gradient based on trend strength.
// Stronger trend = more opaque fill; weaker = more transparent.
if (showFill) {
var fillOpacity = math.min(80, 20 + trendStrength * 50)
var fillColor = isBullish ? bullColor : bearColor
plotLine(
value=[fastEma, slowEma],
width=1,
colors=[opacity(fillColor, fillOpacity)],
fill=true,
label=["Fast EMA", "Slow EMA"],
desc=["EMA lane fill: fast/slow crossover area"]
)
}
// --- Fast & Slow EMA Lines ---
// Fast EMA: blue; Slow EMA: orange. Width reflects adaptive smoothing state.
if (showFastSlow) {
var fastLineWidth = useAdaptive && efficiencyRatio[0] > 0.6 ? 3 : 2
var slowLineWidth = 2
plotLine(
value=fastEma,
width=fastLineWidth,
colors=[fastColor],
label=["Fast EMA"],
desc=["Fast adaptive EMA (" + fastLen + ") | ER=" + efficiencyRatio[0]]
)
plotLine(
value=slowEma,
width=slowLineWidth,
colors=[slowColor],
label=["Slow EMA"],
desc=["Slow structural EMA (" + slowLen + ")"]
)
}
// --- Trend Strength Histogram (offchart-style overlay) ---
// Plotted as a thin histogram bar at the bottom of the lane, showing
// normalized trend strength. Green = bull, red = bear.
if (showStrength) {
var strengthVal = isBullish ? trendStrength : -trendStrength
plotBar(
value=strengthVal,
colors=[bullColor, bearColor],
colorIndex=isBullish ? 0 : 1,
width=1,
label=["Trend Strength"],
desc=["Normalized trend strength [0,1] | ER=" + efficiencyRatio[0]]
)
}
// --- Crossover Shape Markers ---
// Triangle up for golden cross (fast crosses above slow).
// Triangle down for death cross (fast crosses below slow).
if (showShapes) {
if (crossUp) {
plotShape(
value=fastEma,
shape="triangleup",
color=bullColor,
width=3,
label=["Golden Cross"],
desc=["Fast EMA crossed above Slow EMA — bullish trend initiation"]
)
}
if (crossDn) {
plotShape(
value=fastEma,
shape="triangledown",
color=bearColor,
width=3,
label=["Death Cross"],
desc=["Fast EMA crossed below Slow EMA — bearish trend initiation"]
)
}
}
// ------------------------------------------------------------------------------
// Regime Table (last bar only)
// ------------------------------------------------------------------------------
if (isLastBar) {
var regimeText = isBullish ? "BULLISH" : (isBearish ? "BEARISH" : "NEUTRAL")
var regimeTextColor = isBullish ? bullColor : (isBearish ? bearColor : "#9e9e9e")
var trendPct = math.round(trendStrength * 100, 1)
plotTable(
data=[
["SCF Trend V2", regimeText],
["Fast EMA", fastEma[0]],
["Slow EMA", slowEma[0]],
["Trend Strength", trendPct + "%"],
["Efficiency Ratio", efficiencyRatio[0]],
["ATR Band", laneWidth[0]],
["Crossovers (Up/Dn)", crossUpCount + " / " + crossDnCount]
],
position="top_right",
headerRow=true,
headerColumn=true,
textColor="#e2e8f0",
headerTextColor="#ffffff",
backgroundColor=opacity("#0f172a", 40),
headerBackgroundColor=opacity("#1e293b", 40),
borderColor=opacity("#334155", 40),
borderWidth=1,
fontSize=10,
cellPadding=4
)
}