Perfected FlowScript
EMA cross 539
EMA Cross 5/39 — Perfected Edition is indexed as 317_ema_cross_539.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
14.4 KB
Lines
467
Native Signal Candidates
6 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Bull Cross
line 349:9
Trigger
(showSignals) && (bullishCross)
Value
src
Deps
bullishCross:var, showSignals:input
Bear Cross
line 359:9
Trigger
(showSignals) && (bearishCross)
Value
src
Deps
bearishCross:var, showSignals:input
Golden Cross
line 373:9
Trigger
(showShapes) && (goldenCross)
Value
src
Deps
goldenCross:var, showShapes:input
Death Cross
line 383:9
Trigger
(showShapes) && (deathCross)
Value
src
Deps
deathCross:var, showShapes:input
Long Trend
line 393:9
Trigger
(showShapes) && (longTrendAlert)
Value
fastEma
Deps
longTrendAlert:var, showShapes:input
Short Trend
line 403:9
Trigger
(showShapes) && (shortTrendAlert)
Value
fastEma
Deps
shortTrendAlert:var, showShapes:input
317_ema_cross_539.flowscript
source path: kscripts/perfected/317_ema_cross_539.flowscript · sha256:bc7a2c63ff04c41c63e7061cf7790c694b79ca5dd9630cd40ae3172d5f854ea0
//@version=2
// ============================================================================
// EMA Cross 5/39 — Perfected Edition
// Author: A (@Akana Manekantta saai) | Enhanced by kScript_Perfection_Engineer
// Tags: CORE, #ema, #crossover, #golden_cross, #death_cross, #trend, #regime
//
// Production-quality EMA crossover system using fast (5) and slow (39) EMAs,
// with Golden Cross / Death Cross detection, momentum confirmation via EMA 9
// signal line, regime-based color coding, fill between EMAs, shape markers for
// crossovers, and static state tracking for consecutive-trend analysis.
//
// Research papers underpinning this design:
// 1. Brock, Lakonishok & LeBaron (1992), "Simple Technical Trading Rules and
// the Stochastic Properties of Stock Returns", Journal of Finance.
// The most comprehensive early academic study of MA crossovers using 90 years
// of DJIA data. Found MA crossover buy signals consistently followed by
// positive returns; sell signals by negative returns. Triggered academic
// revival of technical analysis.
//
// 2. Manasa & Reddy (2025), "Trend Analysis by Weighted and EMA":
// Comparative study showing EMA offers more stability than WMA but
// occasionally lags in reversals. EMA crossovers among the most widely
// tested rules in academic literature. [Formula] EMA(t) = α·Price(t) +
// (1−α)·EMA(t−1) where α = 2/(N+1).
//
// 3. Khand et al. (2019), "EMA, MACD, RSI in Pakistan Stock Market":
// EMA variants showed substantial prognostic capability. After transaction
// costs, specific EMA variants (1,50,1) and (1,50,0) remained profitable.
// Trading rules generated more revenue during crisis periods.
//
// 4. Zakamulin (2023), "Optimal Trend-Following with Transaction Costs":
// Proposes pragmatic model where optimal trend-following ≈ simple MA
// crossover rule. Provides mathematical justification for crossover adoption
// with transaction costs. Historical simulations validate effectiveness.
//
// 5. Hurst, Ooi & Pedersen (2014), "A Century of Evidence on Trend-Following":
// Time-series momentum profitable since 1880 across nearly all asset classes.
// Trend following delivers strong positive returns with low correlation to
// traditional assets; performs particularly well in equity bear markets.
//
// 6. Jegadeesh & Titman (1993), "Returns to Buying Winners and Selling Losers":
// Seminal momentum anomaly paper. Past winners keep winning; past losers
// keep losing. Validates the trend-following premise underlying EMA crossovers.
// ============================================================================
define(
title="EMA Cross 5/39 — Perfected Edition",
position="onchart",
axis=false
)
// -----------------------------------------------------------------------------
// 1. USER INPUTS — grouped with constraints
// -----------------------------------------------------------------------------
// --- EMA Core ---
var fastLen = input(
name="fastLen",
type="number",
defaultValue=5,
label="Fast EMA Length",
constraints={min: 2, max: 50, step: 1},
group="EMA Core"
)
var slowLen = input(
name="slowLen",
type="number",
defaultValue=39,
label="Slow EMA Length",
constraints={min: 10, max: 200, step: 1},
group="EMA Core"
)
var sigLen = input(
name="sigLen",
type="number",
defaultValue=9,
label="Signal EMA Length",
constraints={min: 2, max: 50, step: 1},
group="EMA Core"
)
// --- Crossover Settings ---
var goldenMin = input(
name="goldenMin",
type="number",
defaultValue=20,
label="Golden Cross Minimum Slow EMA",
constraints={min: 10, max: 100, step: 1},
group="Crossover Settings"
)
var deathMax = input(
name="deathMax",
type="number",
defaultValue=20,
label="Death Cross Maximum Slow EMA",
constraints={min: 10, max: 100, step: 1},
group="Crossover Settings"
)
// --- Display ---
var showFill = input(
name="showFill",
type="boolean",
defaultValue=true,
label="Fill Between EMAs",
group="Display"
)
var showSignals = input(
name="showSignals",
type="boolean",
defaultValue=true,
label="Show Cross Signals",
group="Display"
)
var showSignalEma = input(
name="showSignalEma",
type="boolean",
defaultValue=true,
label="Show Signal EMA",
group="Display"
)
var showShapes = input(
name="showShapes",
type="boolean",
defaultValue=true,
label="Show Golden/Death Cross Shapes",
group="Display"
)
var showMomentum = input(
name="showMomentum",
type="boolean",
defaultValue=false,
label="Show Momentum Histogram (offchart)",
group="Display"
)
// --- Colors ---
var fastColor = input(
name="fastColor",
type="color",
defaultValue="#2962ff",
label="Fast EMA Color",
group="Colors"
)
var slowColor = input(
name="slowColor",
type="color",
defaultValue="#ff9800",
label="Slow EMA Color",
group="Colors"
)
var sigColor = input(
name="sigColor",
type="color",
defaultValue="#9e9e9e",
label="Signal EMA Color",
group="Colors"
)
var bullColor = input(
name="bullColor",
type="color",
defaultValue="#26a69a",
label="Bullish Color",
group="Colors"
)
var bearColor = input(
name="bearColor",
type="color",
defaultValue="#ef5350",
label="Bearish Color",
group="Colors"
)
// -----------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// -----------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries src = bars.close
if (isnan(src[0])) {
return
}
// -----------------------------------------------------------------------------
// 3. COMPUTATION
// -----------------------------------------------------------------------------
// -- 3.1 EMAs --
timeseries fastEma = ema(src, fastLen)
timeseries slowEma = ema(src, slowLen)
timeseries sigEma = ema(src, sigLen)
// -- 3.2 Crossover detection --
// Golden Cross: fast crosses above slow (bullish trend change)
// Death Cross: fast crosses below slow (bearish trend change)
// Standard 5/39 cross is always a crossover; "Golden/Death" labels reserved
// for longer-term versions (e.g., 50/200). For 5/39, we label them as
// Bullish Cross and Bearish Cross, but use the classic terminology in descriptions.
var crossUp = fastEma > slowEma && fastEma[1] <= slowEma[1]
var crossDown = fastEma < slowEma && fastEma[1] >= slowEma[1]
// Golden Cross variant: fast crosses above slow AND slow EMA is long enough
// (typically used with 50/200, but configurable here)
var isGolden = crossUp && slowLen >= goldenMin
var isDeath = crossDown && slowLen >= deathMax
// -- 3.3 Trend state --
var trendUp = fastEma > slowEma
var trendDown = fastEma < slowEma
// -- 3.4 Signal confirmation --
// Fast EMA vs Signal EMA for momentum confirmation
var fastAboveSig = fastEma > sigEma
var fastBelowSig = fastEma < sigEma
// -- 3.5 Momentum histogram (Fast EMA − Slow EMA) --
timeseries emaDiff = fastEma - slowEma
timeseries sigDiff = emaDiff - ema(sigDiff, sigLen)
// -- 3.6 Regime Detection --
// Strong Bull: fast > slow AND fast > signal AND slope positive
// Weak Bull: fast > slow but fast < signal (momentum fading)
// Strong Bear: fast < slow AND fast < signal AND slope negative
// Weak Bear: fast < slow but fast > signal (momentum fading)
// Neutral: fast ≈ slow
var slopeFast = fastEma - fastEma[1]
var slopeSlow = slowEma - slowEma[1]
var strongBull = trendUp && fastAboveSig && slopeFast > 0
var weakBull = trendUp && !fastAboveSig
var strongBear = trendDown && fastBelowSig && slopeFast < 0
var weakBear = trendDown && !fastBelowSig
var neutralRegime = math.abs(emaDiff) < (slowEma * 0.001) // within 0.1% of slow EMA
var regimeColor = strongBull ? bullColor :
(weakBull ? transparency(bullColor, 50) :
(strongBear ? bearColor :
(weakBear ? transparency(bearColor, 50) : "#9e9e9e")))
// -----------------------------------------------------------------------------
// 4. STATIC STATE TRACKING
// -----------------------------------------------------------------------------
// Track consecutive bars in each trend and cross history
static crossUpCount = 0
static crossDownCount = 0
static lastCrossDir = 0 // 1 = up, -1 = down
static trendUpBars = 0
static trendDownBars = 0
static maxTrendUp = 0
static maxTrendDown = 0
if (crossUp) {
crossUpCount = crossUpCount + 1
lastCrossDir = 1
}
if (crossDown) {
crossDownCount = crossDownCount + 1
lastCrossDir = -1
}
if (trendUp) {
trendUpBars = trendUpBars + 1
trendDownBars = 0
if (trendUpBars > maxTrendUp) {
maxTrendUp = trendUpBars
}
} else if (trendDown) {
trendDownBars = trendDownBars + 1
trendUpBars = 0
if (trendDownBars > maxTrendDown) {
maxTrendDown = trendDownBars
}
} else {
trendUpBars = 0
trendDownBars = 0
}
// -----------------------------------------------------------------------------
// 5. ALERT CONDITIONS
// -----------------------------------------------------------------------------
// Cross events
var goldenCross = isGolden
var deathCross = isDeath
var bullishCross = crossUp && !isGolden
var bearishCross = crossDown && !isDeath
// Trend persistence alerts
var longTrendAlert = trendUpBars >= 20
var shortTrendAlert = trendDownBars >= 20
// EMA / Signal divergence (momentum warning)
var momentumFade = trendUp && !fastAboveSig && fastAboveSig[1]
var momentumBuild = trendDown && !fastBelowSig && fastBelowSig[1]
// -----------------------------------------------------------------------------
// 6. PLOTTING
// -----------------------------------------------------------------------------
// --- Fast EMA (regime-colored) ---
plotLine(
value=fastEma,
width=2,
colors=[regimeColor],
label=["Fast EMA"],
desc=[fastLen + "-period EMA — regime-colored"]
)
// --- Slow EMA ---
plotLine(
value=slowEma,
width=2,
colors=[slowColor],
label=["Slow EMA"],
desc=[slowLen + "-period EMA — trend anchor"]
)
// --- Fill between EMAs ---
if (showFill) {
var fillBull = fastEma > slowEma
plotLine(
value=[fastEma, slowEma],
width=1,
colors=[transparency(bullColor, 20), transparency(bearColor, 20)],
colorIndex=fillBull ? 0 : 1,
fill=true,
label=["Fast EMA", "Slow EMA"],
desc=["Fill between fast and slow EMAs — green=bullish, red=bearish"]
)
}
// --- Signal EMA ---
if (showSignalEma) {
plotLine(
value=sigEma,
width=1,
colors=[sigColor],
label=["Signal EMA"],
desc=[sigLen + "-period EMA — momentum confirmation"]
)
}
// --- Cross Signal Shapes ---
if (showSignals) {
if (bullishCross) {
plotShape(
value=src,
shape="triangleup",
colorIndex=bullColor,
width=3,
label=["Bull Cross"],
desc=["Bullish EMA crossover: " + fastLen + " EMA crossed above " + slowLen + " EMA"]
)
}
if (bearishCross) {
plotShape(
value=src,
shape="triangledown",
colorIndex=bearColor,
width=3,
label=["Bear Cross"],
desc=["Bearish EMA crossover: " + fastLen + " EMA crossed below " + slowLen + " EMA"]
)
}
}
// --- Golden / Death Cross Shapes (when applicable) ---
if (showShapes) {
if (goldenCross) {
plotShape(
value=src,
shape="arrowup",
colorIndex="#ffd700",
width=3,
label=["Golden Cross"],
desc=["Golden Cross: " + fastLen + " EMA crossed above " + slowLen + " EMA with slow ≥ " + goldenMin + " — long-term bullish signal"]
)
}
if (deathCross) {
plotShape(
value=src,
shape="arrowdown",
colorIndex="#8b0000",
width=3,
label=["Death Cross"],
desc=["Death Cross: " + fastLen + " EMA crossed below " + slowLen + " EMA with slow ≥ " + deathMax + " — long-term bearish signal"]
)
}
if (longTrendAlert) {
plotShape(
value=fastEma,
shape="circle",
colorIndex=transparency(bullColor, 40),
width=1,
label=["Long Trend"],
desc=["Bullish trend persisted for " + trendUpBars + " bars — momentum sustained"]
)
}
if (shortTrendAlert) {
plotShape(
value=fastEma,
shape="circle",
colorIndex=transparency(bearColor, 40),
width=1,
label=["Short Trend"],
desc=["Bearish trend persisted for " + trendDownBars + " bars — momentum sustained"]
)
}
}
// --- Momentum Histogram (offchart) ---
if (showMomentum) {
var histBull = emaDiff > 0
plotBar(
value=emaDiff,
colors=[transparency(bullColor, 60), transparency(bearColor, 60)],
colorIndex=histBull ? 0 : 1,
width=1,
label=["EMA Momentum"],
desc=["Fast EMA minus Slow EMA — momentum histogram"],
forceOffchart=true
)
hline(value=0, color="#ffffff30", width=1)
}
// -----------------------------------------------------------------------------
// 7. REGIME TABLE (last bar only)
// -----------------------------------------------------------------------------
if (isLastBar) {
var regimeText = strongBull ? "STRONG BULL" :
(weakBull ? "WEAK BULL" :
(strongBear ? "STRONG BEAR" :
(weakBear ? "WEAK BEAR" : "NEUTRAL")))
var regimeTextColor = strongBull ? bullColor :
(weakBull ? transparency(bullColor, 70) :
(strongBear ? bearColor :
(weakBear ? transparency(bearColor, 70) : "#9e9e9e")))
plotTable(
data=[
["EMA Cross 5/39", regimeText],
["Fast EMA", fastEma[0]],
["Slow EMA", slowEma[0]],
["Signal EMA", sigEma[0]],
["EMA Diff", emaDiff[0]],
["Trend Up Bars", trendUpBars],
["Trend Down Bars", trendDownBars],
["Total Bull Crosses", crossUpCount],
["Total Bear Crosses", crossDownCount]
],
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
)
}