Perfected FlowScript
200 Ema
200 EMA Pro — Perfected Edition is indexed as 194_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
11.9 KB
Lines
385
Native Signal Candidates
6 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Price Cross Up
line 282:9
Trigger
(showShapes) && (priceCrossUp)
Value
emaVal
Deps
priceCrossUp:var, showShapes:input
Price Cross Down
line 292:9
Trigger
(showShapes) && (priceCrossDown)
Value
emaVal
Deps
priceCrossDown:var, showShapes:input
Golden Cross
line 302:9
Trigger
(showShapes) && (goldenCross)
Value
emaVal
Deps
goldenCross:var, showShapes:input
Death Cross
line 312:9
Trigger
(showShapes) && (deathCross)
Value
emaVal
Deps
deathCross:var, showShapes:input
EMA Slope Up
line 326:9
Trigger
(showSlopeShapes) && (emaSlopeUp)
Value
emaVal
Deps
emaSlopeUp:var, showSlopeShapes:input
EMA Slope Down
line 336:9
Trigger
(showSlopeShapes) && (emaSlopeDown)
Value
emaVal
Deps
emaSlopeDown:var, showSlopeShapes:input
194_200_ema.flowscript
source path: kscripts/perfected/194_200_ema.flowscript · sha256:4fb855a73ed290976c4b29df4478e1fade36ac09f4f3cd90303adfb7acf33dd3
//@version=2
// ============================================================================
// 200 EMA Pro — Perfected Edition
// Author: T | Enhanced by kScript_Perfection_Engineer
// Tags: CORE, #trend, #moving_average, #ema, #regime, #crossover
//
// Production-quality 200-period Exponential Moving Average with multi-regime
// detection (price vs EMA, EMA slope), price-EMA fill, color-coded trend
// states, shape markers for crossovers, and static state tracking for
// consecutive regime duration. Includes an optional confluence fast EMA
// to visualise the classic Golden/Death cross relationship.
//
// Research papers underpinning this design:
// 1. Manasa & Reddy (2025), "Trend Analysis by Weighted and Exponential
// Moving Average": comparative study showing EMA offers more stability
// but occasionally lags in reversals. EMA formula: EMA = Price × k +
// EMA(previous) × (1−k), where k = 2/(N+1). The 200-period length is
// the standard long-term trend benchmark used across global markets.
// 2. Brock, Lakonishok & LeBaron (1992), "Simple Technical Trading Rules and
// the Stochastic Properties of Stock Returns": MA crossover rules
// significantly outperformed buy-and-hold on 90 years of DJIA data.
// Validates the price-vs-EMA crossover as a trend-following signal.
// 3. Zakamulin (2023), "Optimal Trend-Following with Transaction Costs":
// optimal trend-following resembles simple MA crossover rules under
// plausible transaction-cost assumptions. Provides mathematical
// justification for the 200 EMA trend-following approach.
// 4. Clare, Seaton, Smith & Thomas (2013), "Trend Following, Stop Losses, and
// the Frequency of Trading: The Case of the S&P 500": simple rules did
// not consistently underperform complex rules. The 200 EMA distills
// trend-following to its essential minimum with robust out-of-sample
// performance.
// 5. Hurst, Ooi & Pedersen (2014), "A Century of Evidence on Trend-Following
// Investing": time-series momentum has been profitable since 1880 across
// equities, fixed income, commodities, and currencies. The 200 EMA as a
// long-term trend filter aligns with multi-asset, multi-horizon evidence.
// ============================================================================
define(
title="200 EMA Pro — Perfected Edition",
position="onchart",
axis=false
)
// ---------------------------------------------------------------------------
// 1. USER INPUTS — All grouped, all numeric inputs carry constraints
// ---------------------------------------------------------------------------
// -- EMA Settings --
var length = input(
name="length",
type="number",
defaultValue=200,
label="EMA Length",
constraints={min: 50, max: 500, step: 10},
group="EMA Settings"
)
var srcType = input(
name="srcType",
type="select",
defaultValue="close",
label="Source",
options=["close", "open", "high", "low", "hl2", "hlc3", "ohlc4"],
group="EMA Settings"
)
// -- Confluence Fast EMA --
var showFastEMA = input(
name="showFastEMA",
type="boolean",
defaultValue=true,
label="Show Fast EMA (50)",
group="Confluence EMA"
)
var fastLen = input(
name="fastLen",
type="number",
defaultValue=50,
label="Fast EMA Length",
constraints={min: 5, max: 100, step: 5},
group="Confluence EMA"
)
// -- Display --
var showPriceFill = input(
name="showPriceFill",
type="boolean",
defaultValue=true,
label="Show Price / EMA Fill",
group="Display"
)
var showShapes = input(
name="showShapes",
type="boolean",
defaultValue=true,
label="Show Crossover Shapes",
group="Display"
)
var showSlopeShapes = input(
name="showSlopeShapes",
type="boolean",
defaultValue=true,
label="Show Slope-Change Shapes",
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 neutralColor = input(
name="neutralColor",
type="color",
defaultValue="#78909c",
label="Neutral Color",
group="Colors"
)
var fastColor = input(
name="fastColor",
type="color",
defaultValue="#42a5f5",
label="Fast EMA Color",
group="Colors"
)
// ---------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// ---------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries src = srcType == "close" ? bars.close
: srcType == "open" ? bars.open
: srcType == "high" ? bars.high
: srcType == "low" ? bars.low
: srcType == "hl2" ? (bars.high + bars.low) / 2
: srcType == "hlc3" ? (bars.high + bars.low + bars.close) / 3
: (bars.open + bars.high + bars.low + bars.close) / 4
if (isnan(src[0])) {
return
}
// ---------------------------------------------------------------------------
// 3. EMA COMPUTATION
// ---------------------------------------------------------------------------
timeseries emaVal = ema(source=src, period=length)
timeseries fastEMA = ema(source=src, period=fastLen)
// Slope detection
timeseries rising = emaVal >= emaVal[1]
timeseries falling = emaVal < emaVal[1]
// ---------------------------------------------------------------------------
// 4. REGIME DETECTION
// ---------------------------------------------------------------------------
// Regime classification based on price vs EMA and EMA slope:
// Strong Bull: price > EMA AND EMA rising
// Strong Bear: price < EMA AND EMA falling
// Weak Bull: price > EMA AND EMA falling (pullback within uptrend)
// Weak Bear: price < EMA AND EMA rising (relief within downtrend)
var regimeStrongBull = src > emaVal && rising
var regimeStrongBear = src < emaVal && falling
var regimeWeakBull = src > emaVal && falling
var regimeWeakBear = src < emaVal && rising
var regimeColor = regimeStrongBull ? bullColor
: regimeStrongBear ? bearColor
: regimeWeakBull ? transparency(bullColor, 50)
: transparency(bearColor, 50)
// ---------------------------------------------------------------------------
// 5. STATIC STATE TRACKING
// ---------------------------------------------------------------------------
static prevPriceAboveEMA = false
static prevEMA = 0.0
static strongBullBars = 0
static strongBearBars = 0
static weakBullBars = 0
static weakBearBars = 0
// Initialise on first real bar
if (prevEMA == 0.0 && !isnan(emaVal[0])) {
prevEMA = emaVal[0]
prevPriceAboveEMA = src[0] > emaVal[0]
}
// Consecutive bar counters
if (regimeStrongBull) {
strongBullBars = strongBullBars + 1
strongBearBars = 0
weakBullBars = 0
weakBearBars = 0
} else if (regimeStrongBear) {
strongBullBars = 0
strongBearBars = strongBearBars + 1
weakBullBars = 0
weakBearBars = 0
} else if (regimeWeakBull) {
strongBullBars = 0
strongBearBars = 0
weakBullBars = weakBullBars + 1
weakBearBars = 0
} else if (regimeWeakBear) {
strongBullBars = 0
strongBearBars = 0
weakBullBars = 0
weakBearBars = weakBearBars + 1
}
// Crossover detection (price vs EMA)
var priceCrossUp = src > emaVal && !prevPriceAboveEMA
var priceCrossDown = src < emaVal && prevPriceAboveEMA
// Slope-change detection
var emaSlopeUp = rising && emaVal[1] < emaVal[2]
var emaSlopeDown = falling && emaVal[1] > emaVal[2]
// Golden / Death cross (fast EMA vs slow EMA)
var goldenCross = showFastEMA ? (fastEMA > emaVal && fastEMA[1] <= emaVal[1]) : false
var deathCross = showFastEMA ? (fastEMA < emaVal && fastEMA[1] >= emaVal[1]) : false
if (!isLiveUpdate) {
prevEMA = emaVal[0]
prevPriceAboveEMA = src[0] > emaVal[0]
}
// ---------------------------------------------------------------------------
// 6. VISUALIZATION
// ---------------------------------------------------------------------------
// -- 200 EMA Line (regime-colored) --
plotLine(
value=emaVal,
width=2,
colors=[regimeColor],
label=["200 EMA"],
desc=["200-period Exponential Moving Average (regime-coloured)"]
)
// -- Fast EMA (confluence) --
if (showFastEMA) {
plotLine(
value=fastEMA,
width=1,
colors=[fastColor],
label=["Fast EMA"],
desc=["Fast EMA (" + fastLen + ") for Golden/Death cross confluence"]
)
}
// -- Price vs EMA Fill --
if (showPriceFill) {
var priceAbove = src > emaVal
plotLine(
value=[src, emaVal],
width=1,
colors=[transparency(bullColor, 15), transparency(bearColor, 15)],
colorIndex=priceAbove ? 0 : 1,
fill=true,
label=["Price", "200 EMA"],
desc=["Fill between price and 200 EMA, coloured by relative position"]
)
}
// -- Crossover Shapes (price vs EMA) --
if (showShapes) {
if (priceCrossUp) {
plotShape(
value=emaVal,
shape="triangleup",
colorIndex=bullColor,
width=2,
label=["Price Cross Up"],
desc=["Price crossed above 200 EMA — bullish trend transition"]
)
}
if (priceCrossDown) {
plotShape(
value=emaVal,
shape="triangledown",
colorIndex=bearColor,
width=2,
label=["Price Cross Down"],
desc=["Price crossed below 200 EMA — bearish trend transition"]
)
}
if (goldenCross) {
plotShape(
value=emaVal,
shape="circle",
colorIndex=bullColor,
width=3,
label=["Golden Cross"],
desc=["Fast EMA crossed above 200 EMA — strong bullish confluence"]
)
}
if (deathCross) {
plotShape(
value=emaVal,
shape="circle",
colorIndex=bearColor,
width=3,
label=["Death Cross"],
desc=["Fast EMA crossed below 200 EMA — strong bearish confluence"]
)
}
}
// -- Slope-Change Shapes --
if (showSlopeShapes) {
if (emaSlopeUp) {
plotShape(
value=emaVal,
shape="arrowup",
colorIndex=transparency(bullColor, 30),
width=1,
label=["EMA Slope Up"],
desc=["200 EMA slope turned positive"]
)
}
if (emaSlopeDown) {
plotShape(
value=emaVal,
shape="arrowdown",
colorIndex=transparency(bearColor, 30),
width=1,
label=["EMA Slope Down"],
desc=["200 EMA slope turned negative"]
)
}
}
// ---------------------------------------------------------------------------
// 7. REGIME TABLE (last bar only)
// ---------------------------------------------------------------------------
if (isLastBar) {
var regimeText = regimeStrongBull ? "STRONG BULL"
: regimeStrongBear ? "STRONG BEAR"
: regimeWeakBull ? "WEAK BULL (Pullback)"
: "WEAK BEAR (Relief)"
var regimeTextColor = regimeStrongBull ? bullColor
: regimeStrongBear ? bearColor
: regimeWeakBull ? transparency(bullColor, 50)
: transparency(bearColor, 50)
plotTable(
data=[
["200 EMA Pro — Perfected", regimeText],
["200 EMA", emaVal[0]],
["Fast EMA", fastEMA[0]],
["Price", src[0]],
["Strong Bull Bars", strongBullBars],
["Strong Bear Bars", strongBearBars],
["Weak Bull Bars", weakBullBars],
["Weak Bear Bars", weakBearBars]
],
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
)
}