Perfected FlowScript
50 x 100 x 200 EMA
50 x 100 x 200 EMA — Perfected Edition is indexed as 243_50_x_100_x_200_ema.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.1 KB
Lines
493
Native Signal Candidates
6 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Golden Cross
line 400:9
Trigger
(showShapes) && (goldenCross)
Value
ema50
Deps
goldenCross:var, showShapes:input
Death Cross
line 410:9
Trigger
(showShapes) && (deathCross)
Value
ema50
Deps
deathCross:var, showShapes:input
50/100 Up
line 420:9
Trigger
(showShapes) && (cross50_100_Up)
Value
ema50
Deps
cross50_100_Up:var, showShapes:input
50/100 Dn
line 430:9
Trigger
(showShapes) && (cross50_100_Dn)
Value
ema50
Deps
cross50_100_Dn:var, showShapes:input
Price > 200
line 440:9
Trigger
(showShapes) && (priceCross200Up)
Value
px
Deps
priceCross200Up:var, showShapes:input
Price < 200
line 450:9
Trigger
(showShapes) && (priceCross200Dn)
Value
px
Deps
priceCross200Dn:var, showShapes:input
243_50_x_100_x_200_ema.flowscript
source path: kscripts/perfected/243_50_x_100_x_200_ema.flowscript · sha256:7bb0a3032591fdfff355878f896abbb986542be2f493eb93ab0622cbeae70284
//@version=2
// ============================================================================
// 50 x 100 x 200 EMA — Perfected Edition
// Author: RoronoaZoro (@RoronoaZoro) | Enhanced by kScript Perfection Engineer
// Tags: CORE, #ema, #trend, #crossover, #ribbon, #regime, #golden_cross, #death_cross
//
// Production-quality triple EMA trend-structure system with regime detection,
// Golden/Death cross identification, multi-band ribbon fill, slope analysis,
// and comprehensive session tracking.
//
// Research papers underpinning this design:
// 1. Manasa & Rajashekhar Reddy (2025), IJRIAS — "Trend Analysis by Weighted
// and Exponential Moving Average": EMA vs WMA stability analysis; EMA
// offers superior trend-tracking stability vs. WMA's faster but noisier
// response.
// 2. Khand et al. (2019), IJST — "EMA, MACD, RSI and Momentum Trading Rules":
// EMA crossover variants (1,50) and (1,50,0) showed substantial prognostic
// capability and remained profitable after transaction costs on KSE-100.
// 3. Hurst, Ooi & Pedersen (2014), "A Century of Evidence on Trend-Following
// Investing": time-series momentum profitable since 1880 across all major
// asset classes; trend-following reduced volatility by a third to a half.
// 4. Brock, Lakonishok & LeBaron (1992), J. Finance: comprehensive study of
// 90 years of DJIA data; moving average crossover rules significantly
// outperformed cash benchmarks, triggering academic revival of TA.
// 5. Zakamulin (2023), "Optimal Trend-Following with Transaction Costs":
// optimal trend-following under transaction costs resembles simple MA
// crossover rules, providing mathematical justification for EMA crossovers.
// ============================================================================
define(
title="50 x 100 x 200 EMA — Perfected Edition",
position="onchart",
axis=false
)
// -----------------------------------------------------------------------------
// 1. USER INPUTS — grouped with constraints
// -----------------------------------------------------------------------------
// --- EMA Periods ---
var show50 = input(
name="show50",
type="boolean",
defaultValue=true,
label="Show 50 EMA",
group="EMA Settings"
)
var show100 = input(
name="show100",
type="boolean",
defaultValue=true,
label="Show 100 EMA",
group="EMA Settings"
)
var show200 = input(
name="show200",
type="boolean",
defaultValue=true,
label="Show 200 EMA",
group="EMA Settings"
)
var ema50Len = input(
name="ema50Len",
type="number",
defaultValue=50,
label="Fast EMA Length",
constraints={min: 5, max: 100, step: 1},
group="EMA Settings"
)
var ema100Len = input(
name="ema100Len",
type="number",
defaultValue=100,
label="Medium EMA Length",
constraints={min: 10, max: 200, step: 1},
group="EMA Settings"
)
var ema200Len = input(
name="ema200Len",
type="number",
defaultValue=200,
label="Slow EMA Length",
constraints={min: 20, max: 500, step: 1},
group="EMA Settings"
)
// --- Smoothing ---
var useSmooth = input(
name="useSmooth",
type="boolean",
defaultValue=false,
label="Apply EMA Smoothing",
group="Smoothing"
)
var smoothLen = input(
name="smoothLen",
type="number",
defaultValue=3,
label="Smoothing Length",
constraints={min: 1, max: 20, step: 1},
group="Smoothing"
)
// --- Ribbon & Fill ---
var showRibbon = input(
name="showRibbon",
type="boolean",
defaultValue=true,
label="Show EMA Ribbon Fill",
group="Display"
)
var showSignalFill = input(
name="showSignalFill",
type="boolean",
defaultValue=true,
label="Show Price-to-200 Fill",
group="Display"
)
var showSlope = input(
name="showSlope",
type="boolean",
defaultValue=true,
label="Show EMA Slope Histogram",
group="Display"
)
var showShapes = input(
name="showShapes",
type="boolean",
defaultValue=true,
label="Show Cross Shapes",
group="Display"
)
var showTable = input(
name="showTable",
type="boolean",
defaultValue=true,
label="Show Status Table",
group="Display"
)
// --- Colors ---
var color50 = input(
name="color50",
type="color",
defaultValue="#ffeb3b",
label="Fast EMA Color",
group="Colors"
)
var color100 = input(
name="color100",
type="color",
defaultValue="#26a69a",
label="Medium EMA Color",
group="Colors"
)
var color200 = input(
name="color200",
type="color",
defaultValue="#ef5350",
label="Slow EMA Color",
group="Colors"
)
var bullColor = input(
name="bullColor",
type="color",
defaultValue="#00e676",
label="Bullish Regime Color",
group="Colors"
)
var bearColor = input(
name="bearColor",
type="color",
defaultValue="#ff5252",
label="Bearish Regime Color",
group="Colors"
)
var neutralColor = input(
name="neutralColor",
type="color",
defaultValue="#9e9e9e",
label="Neutral/Compression Color",
group="Colors"
)
// --- Multi-Timeframe (best-effort) ---
var useMTF = input(
name="useMTF",
type="boolean",
defaultValue=false,
label="Use Higher Timeframe",
group="Multi-Timeframe"
)
var mtfTimeframe = input(
name="mtfTimeframe",
type="select",
defaultValue="1H",
label="Higher Timeframe",
options=["1H", "2H", "4H", "1D"],
group="Multi-Timeframe"
)
// -----------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// -----------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries px = bars.close
if (isnan(px[0])) {
return
}
// Multi-timeframe support (platform-dependent; falls back to current if unavailable)
timeseries mtfPx = px
// -----------------------------------------------------------------------------
// 3. EMA COMPUTATION — canonical exponential smoothing
// -----------------------------------------------------------------------------
// EMA_t = α × Price_t + (1 − α) × EMA_{t−1}, where α = 2 / (N + 1)
// Per Wilder (1978) and Manasa & Reddy (2025), EMA offers superior stability.
timeseries rawEma50 = ema(source=mtfPx, period=ema50Len)
timeseries rawEma100 = ema(source=mtfPx, period=ema100Len)
timeseries rawEma200 = ema(source=mtfPx, period=ema200Len)
// Optional smoothing
var ema50 = useSmooth ? ema(source=rawEma50, period=smoothLen) : rawEma50
var ema100 = useSmooth ? ema(source=rawEma100, period=smoothLen) : rawEma100
var ema200 = useSmooth ? ema(source=rawEma200, period=smoothLen) : rawEma200
// -----------------------------------------------------------------------------
// 4. REGIME DETECTION — stacked order structure
// -----------------------------------------------------------------------------
// Bullish regime: price > 50 > 100 > 200 (strong uptrend, fan spread)
// Bearish regime: price < 50 < 100 < 200 (strong downtrend, fan spread)
// Compression: EMAs converging (potential trend shift)
// Neutral: everything else
var regimeBull = px > ema50 && ema50 > ema100 && ema100 > ema200
var regimeBear = px < ema50 && ema50 < ema100 && ema100 < ema200
var regimeCompression = math.abs(ema50 - ema100) / ema100 < 0.001 || math.abs(ema100 - ema200) / ema200 < 0.001
var regimeNeutral = !regimeBull && !regimeBear && !regimeCompression
var regimeColor = regimeBull ? bullColor : (regimeBear ? bearColor : (regimeCompression ? neutralColor : "#9e9e9e"))
// -----------------------------------------------------------------------------
// 5. CROSS DETECTION — Golden Cross & Death Cross (50/200)
// -----------------------------------------------------------------------------
// Golden Cross: 50 EMA crosses above 200 EMA (bullish trend reversal)
// Death Cross: 50 EMA crosses below 200 EMA (bearish trend reversal)
// Per Brock et al. (1992), MA crossovers have significant predictive power.
var goldenCross = ema50 > ema200 && ema50[1] <= ema200[1]
var deathCross = ema50 < ema200 && ema50[1] >= ema200[1]
// Short-term crosses (50/100) for earlier signals
var cross50_100_Up = ema50 > ema100 && ema50[1] <= ema100[1]
var cross50_100_Dn = ema50 < ema100 && ema50[1] >= ema100[1]
// Price crossing 200 EMA
var priceCross200Up = px > ema200 && px[1] <= ema200[1]
var priceCross200Dn = px < ema200 && px[1] >= ema200[1]
// -----------------------------------------------------------------------------
// 6. EMA SLOPE ANALYSIS — rate of change for momentum
// -----------------------------------------------------------------------------
// Slope measures the first difference of each EMA, indicating momentum
// and curvature of the trend structure.
timeseries slope50 = ema50 - ema50[1]
timeseries slope100 = ema100 - ema100[1]
timeseries slope200 = ema200 - ema200[1]
var avgSlope = (slope50 + slope100 + slope200) / 3.0
// -----------------------------------------------------------------------------
// 7. STATIC STATE TRACKING — session-level persistence
// -----------------------------------------------------------------------------
// Tracks cross counts, regime duration, and EMA extremes for analytics.
static lastRegime = 0 // 0=neutral, 1=bull, -1=bear, 2=compression
static goldenCount = 0
static deathCount = 0
static regimeBullBars = 0
static regimeBearBars = 0
static regimeCompressBars = 0
static sessionHighEma50 = -999999.0
static sessionLowEma50 = 999999.0
static lastBarIndex = 0
var currentBarIndex = bar_index[0]
if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
lastBarIndex = currentBarIndex
// Track EMA extremes
if (ema50[0] > sessionHighEma50) {
sessionHighEma50 = ema50[0]
}
if (ema50[0] < sessionLowEma50) {
sessionLowEma50 = ema50[0]
}
// Regime duration counters
var currentRegime = regimeBull ? 1 : (regimeBear ? -1 : (regimeCompression ? 2 : 0))
if (currentRegime == 1) {
regimeBullBars = regimeBullBars + 1
} else if (currentRegime == -1) {
regimeBearBars = regimeBearBars + 1
} else if (currentRegime == 2) {
regimeCompressBars = regimeCompressBars + 1
}
lastRegime = currentRegime
// Cross counters
if (goldenCross) {
goldenCount = goldenCount + 1
}
if (deathCross) {
deathCount = deathCount + 1
}
}
// -----------------------------------------------------------------------------
// 8. PLOTTING
// -----------------------------------------------------------------------------
// --- EMA Ribbon Fill (50 vs 100) ---
if (showRibbon) {
var ribbonBull = ema50 > ema100
plotLine(
value=[ema50, ema100],
width=1,
colors=[transparency(bullColor, 30), transparency(bearColor, 30)],
colorIndex=ribbonBull ? 0 : 1,
fill=true,
label=["EMA 50", "EMA 100"],
desc=["Fast EMA ribbon edge", "Medium EMA ribbon edge"]
)
}
// --- Price-to-200 Fill ---
if (showSignalFill) {
var priceAbove200 = px > ema200
plotLine(
value=[px, ema200],
width=1,
colors=[transparency(bullColor, 20), transparency(bearColor, 20)],
colorIndex=priceAbove200 ? 0 : 1,
fill=true,
label=["Price", "EMA 200"],
desc=["Fill between price and 200 EMA (trend bias)"]
)
}
// --- Individual EMA Lines ---
if (show50) {
plotLine(
value=ema50,
width=2,
colors=[color50],
label=["EMA 50"],
desc=["50-period EMA: short-term momentum (" + ema50Len + ")"]
)
}
if (show100) {
plotLine(
value=ema100,
width=2,
colors=[color100],
label=["EMA 100"],
desc=["100-period EMA: intermediate trend (" + ema100Len + ")"]
)
}
if (show200) {
plotLine(
value=ema200,
width=2,
colors=[color200],
label=["EMA 200"],
desc=["200-period EMA: long-term bias (" + ema200Len + ")"]
)
}
// --- Slope Histogram (momentum of trend structure) ---
if (showSlope) {
var slopeBull = avgSlope >= 0
plotBar(
value=avgSlope,
colors=[transparency(bullColor, 60), transparency(bearColor, 60)],
colorIndex=slopeBull ? 0 : 1,
width=1,
label=["EMA Slope"],
desc=["Average slope of 50/100/200 EMAs (trend momentum)"]
)
}
// --- Cross Shapes ---
if (showShapes) {
if (goldenCross) {
plotShape(
value=ema50,
shape="triangleup",
colorIndex=bullColor,
width=3,
label=["Golden Cross"],
desc=["Golden Cross: 50 EMA crossed above 200 EMA (bullish reversal)"]
)
}
if (deathCross) {
plotShape(
value=ema50,
shape="triangledown",
colorIndex=bearColor,
width=3,
label=["Death Cross"],
desc=["Death Cross: 50 EMA crossed below 200 EMA (bearish reversal)"]
)
}
if (cross50_100_Up) {
plotShape(
value=ema50,
shape="circle",
colorIndex=bullColor,
width=2,
label=["50/100 Up"],
desc=["50 EMA crossed above 100 EMA (early bullish signal)"]
)
}
if (cross50_100_Dn) {
plotShape(
value=ema50,
shape="circle",
colorIndex=bearColor,
width=2,
label=["50/100 Dn"],
desc=["50 EMA crossed below 100 EMA (early bearish signal)"]
)
}
if (priceCross200Up) {
plotShape(
value=px,
shape="diamond",
colorIndex=bullColor,
width=2,
label=["Price > 200"],
desc=["Price crossed above 200 EMA (long-term trend turn)"]
)
}
if (priceCross200Dn) {
plotShape(
value=px,
shape="diamond",
colorIndex=bearColor,
width=2,
label=["Price < 200"],
desc=["Price crossed below 200 EMA (long-term trend turn)"]
)
}
}
// -----------------------------------------------------------------------------
// 9. REGIME TABLE (last bar only)
// -----------------------------------------------------------------------------
if (showTable && isLastBar) {
var regimeText = regimeBull ? "BULLISH" : (regimeBear ? "BEARISH" : (regimeCompression ? "COMPRESSION" : "NEUTRAL"))
var regimeTextColor = regimeBull ? bullColor : (regimeBear ? bearColor : (regimeCompression ? neutralColor : "#9e9e9e"))
plotTable(
data=[
["50/100/200 EMA Pro", regimeText],
["EMA 50", ema50[0]],
["EMA 100", ema100[0]],
["EMA 200", ema200[0]],
["Avg Slope", avgSlope[0]],
["Golden Crosses", goldenCount],
["Death Crosses", deathCount],
["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
)
}