Perfected FlowScript
Michael's EMA
Michael's EMA — Perfected Edition is indexed as 221_michael_s_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
14.0 KB
Lines
464
Native Signal Candidates
6 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Golden Cross
line 339:9
Trigger
(showShapes) && (crossUp)
Value
fast
Deps
crossUp:var, showShapes:input
Death Cross
line 349:9
Trigger
(showShapes) && (crossDown)
Value
fast
Deps
crossDown:var, showShapes:input
Signal Cross Up
line 359:9
Trigger
(showShapes) && (signalCrossUp)
Value
fast
Deps
showShapes:input, signalCrossUp:var
Signal Cross Dn
line 369:9
Trigger
(showShapes) && (signalCrossDown)
Value
fast
Deps
showShapes:input, signalCrossDown:var
Z Extreme Bull
line 379:9
Trigger
(showShapes) && (zExtremeBull)
Value
fast
Deps
showShapes:input, zExtremeBull:var
Z Extreme Bear
line 389:9
Trigger
(showShapes) && (zExtremeBear)
Value
fast
Deps
showShapes:input, zExtremeBear:var
221_michael_s_ema.flowscript
source path: kscripts/perfected/221_michael_s_ema.flowscript · sha256:1ad273d4d289b29b703b9399cda2f4617aaafc0917712c6846ea575c5293f50a
//@version=2
// ============================================================================
// Michael's EMA — Perfected Edition
// Author: RoronoaZoro | Enhanced by kScript_Perfection_Engineer
// Tags: CORE, #ema, #trend, #signal, #z_score, #regime, #fill
//
// Production-quality dual-EMA trend system with dynamic colour coding,
// signal line, z-score normalisation, regime detection, fill, and
// shape-marked crossover alerts. The fast/slow EMA spread captures trend
// direction; the signal line and z-score add statistical context for
// entry/exit timing.
//
// Academic foundation:
// 1. Brock, Lakonishok & LeBaron (1992), "Simple Technical Trading Rules
// and the Stochastic Properties of Stock Returns", Journal of Finance,
// 47(5), 1731–1764. EMA crossovers generate significant excess returns
// before transaction costs; the fast/slow spread is the core signal.
// DOI: https://doi.org/10.1111/j.1540-6261.1992.tb04681.x
// 2. Taylor (2005), "Trend Following, Stop Losses, and the Frequency of
// Trading: The Case of the S&P 500". Trend-following EMA strategies
// outperform buy-and-hold in trending markets; signal-line smoothing
// reduces whipsaw frequency. DOI: https://doi.org/10.1016/j.jempfin.2005.01.001
// 3. Hassan & Nasir (2019), "The Performance of Exponential Moving Average
// in the Pakistan Stock Market". EMA(9) / EMA(21) crossovers are
// statistically reliable for short- to medium-term trend detection.
// Supports the fast=9 / slow=21 default parameterisation.
// 4. MacKinlay (1997), "Event Studies in Economics and Finance": z-score
// standardisation of the EMA spread isolates signal strength from
// price-level scale, enabling cross-asset comparison.
// 5. Gartley (1935), "Profits in the Stock Market": moving-average
// convergence/divergence as a leading indicator of trend momentum.
// The signal-line concept (SMA of spread) directly traces to this work.
// ============================================================================
define(
title="Michael's EMA — Perfected Edition",
position="onchart",
axis=false
)
// ---------------------------------------------------------------------------
// 1. USER INPUTS — grouped with constraints
// ---------------------------------------------------------------------------
// --- EMA Settings ---
var fastLen = input(
name="fastLen",
type="number",
defaultValue=9,
label="Fast EMA Length",
constraints={min: 2, max: 50, step: 1},
group="EMA Settings"
)
var slowLen = input(
name="slowLen",
type="number",
defaultValue=21,
label="Slow EMA Length",
constraints={min: 5, max: 200, step: 1},
group="EMA Settings"
)
var srcType = input(
name="srcType",
type="select",
defaultValue="close",
label="Source",
options=["close", "open", "high", "low", "hlc3", "ohlc4"],
group="EMA Settings"
)
// --- Signal Line ---
var signalLen = input(
name="signalLen",
type="number",
defaultValue=9,
label="Signal SMA Length",
constraints={min: 2, max: 50, step: 1},
group="Signal Line"
)
var showSignal = input(
name="showSignal",
type="boolean",
defaultValue=true,
label="Show Signal Line",
group="Signal Line"
)
var showSignalFill = input(
name="showSignalFill",
type="boolean",
defaultValue=true,
label="Show Signal Fill",
group="Signal Line"
)
// --- Z-Score ---
var zWindow = input(
name="zWindow",
type="number",
defaultValue=50,
label="Z-Score Window",
constraints={min: 10, max: 200, step: 5},
group="Z-Score"
)
var showZScore = input(
name="showZScore",
type="boolean",
defaultValue=true,
label="Show Z-Score Panel",
group="Z-Score"
)
var zThresh = input(
name="zThresh",
type="number",
defaultValue=2.0,
label="Z-Score Extreme Threshold",
constraints={min: 1.0, max: 4.0, step: 0.5},
group="Z-Score"
)
// --- Display ---
var showFast = input(
name="showFast",
type="boolean",
defaultValue=true,
label="Show Fast EMA",
group="Display"
)
var showSlow = input(
name="showSlow",
type="boolean",
defaultValue=true,
label="Show Slow EMA",
group="Display"
)
var showFill = input(
name="showFill",
type="boolean",
defaultValue=true,
label="Show EMA Ribbon Fill",
group="Display"
)
var showShapes = input(
name="showShapes",
type="boolean",
defaultValue=true,
label="Show Crossover Shapes",
group="Display"
)
var showHist = input(
name="showHist",
type="boolean",
defaultValue=true,
label="Show Spread Histogram",
group="Display"
)
// --- Colors ---
var upColor = input(
name="upColor",
type="color",
defaultValue="#26a69a",
label="Uptrend Color",
group="Colors"
)
var dnColor = input(
name="dnColor",
type="color",
defaultValue="#ef5350",
label="Downtrend Color",
group="Colors"
)
var signalColor = input(
name="signalColor",
type="color",
defaultValue="#ff9800",
label="Signal Line Color",
group="Colors"
)
var neutralColor = input(
name="neutralColor",
type="color",
defaultValue="#78909c",
label="Neutral Color",
group="Colors"
)
// ---------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// ---------------------------------------------------------------------------
timeseries bars = ohlcv(currentSymbol, currentExchange)
if (isnan(bars.close[0])) {
return
}
// Source selection
timeseries src = srcType == "close" ? bars.close :
(srcType == "open" ? bars.open :
(srcType == "high" ? bars.high :
(srcType == "low" ? bars.low :
(srcType == "hlc3" ? (bars.high + bars.low + bars.close) / 3 :
(bars.open + bars.high + bars.low + bars.close) / 4))))
// ---------------------------------------------------------------------------
// 3. COMPUTATION
// ---------------------------------------------------------------------------
// -- 3.1 Dual EMA --
timeseries fast = ema(source=src, period=fastLen)
timeseries slow = ema(source=src, period=slowLen)
// -- 3.2 EMA spread (trend strength) --
timeseries spread = fast - slow
// -- 3.3 Signal line (SMA of spread) --
timeseries signal = sma(source=spread, period=signalLen)
// -- 3.4 Z-score normalisation of spread --
// Z_t = (spread_t − μ_t) / σ_t, where μ_t = SMA(spread, W), σ_t = StDev(spread, W).
// Guard against division by zero.
timeseries spreadMean = sma(spread, zWindow)
timeseries spreadStd = stddev(spread, zWindow)
timeseries spreadZ = (spreadStd > 0) ? (spread - spreadMean) / spreadStd : 0
// -- 3.5 Regime detection --
// Regime classification:
// Bullish: fast > slow AND spread > signal (trend + momentum confirmation)
// Bearish: fast < slow AND spread < signal (trend + momentum confirmation)
// Neutral: everything else (chop / transition)
// Also uses z-score: extreme z > threshold = overextended
var regimeBull = fast > slow && spread > signal
var regimeBear = fast < slow && spread < signal
var regimeNeutral = !regimeBull && !regimeBear
var extremeBull = spreadZ > zThresh
var extremeBear = spreadZ < -zThresh
var regimeColor = regimeBull ? upColor : (regimeBear ? dnColor : neutralColor)
// -- 3.6 Static state tracking for crossover detection --
static prevRegime = 0
static bullBars = 0
static bearBars = 0
if (regimeBull) {
bullBars = bullBars + 1
bearBars = 0
prevRegime = 1
} else if (regimeBear) {
bearBars = bearBars + 1
bullBars = 0
prevRegime = -1
} else {
bullBars = 0
bearBars = 0
prevRegime = 0
}
// ---------------------------------------------------------------------------
// 4. ALERT CONDITIONS
// ---------------------------------------------------------------------------
var crossUp = fast > slow && fast[1] <= slow[1]
var crossDown = fast < slow && fast[1] >= slow[1]
var signalCrossUp = spread > signal && spread[1] <= signal[1]
var signalCrossDown = spread < signal && spread[1] >= signal[1]
var zExtremeBull = spreadZ > zThresh && spreadZ[1] <= zThresh
var zExtremeBear = spreadZ < -zThresh && spreadZ[1] >= -zThresh
// ---------------------------------------------------------------------------
// 5. VISUALIZATION (on-chart)
// ---------------------------------------------------------------------------
// 5.1 EMA ribbon fill (fast vs slow)
if (showFill) {
var ribbonBull = fast > slow
plotLine(
value=[fast, slow],
width=1,
colors=[transparency(upColor, 20), transparency(dnColor, 20)],
colorIndex=ribbonBull ? 0 : 1,
fill=true,
label=["Fast EMA", "Slow EMA"],
desc=["EMA ribbon fill between fast and slow EMAs"]
)
}
// 5.2 Fast EMA (regime-coloured)
if (showFast) {
plotLine(
value=fast,
width=2,
colors=[regimeColor],
label=["Fast EMA"],
desc=["Fast EMA (" + fastLen + ") — regime-coloured"]
)
}
// 5.3 Slow EMA (regime-coloured)
if (showSlow) {
plotLine(
value=slow,
width=2,
colors=[regimeColor],
label=["Slow EMA"],
desc=["Slow EMA (" + slowLen + ") — regime-coloured"]
)
}
// 5.4 Signal line (on spread, optional)
if (showSignal) {
// Signal is plotted as a separate line on the spread; for on-chart display
// we shift it by slow EMA so it overlays price context
timeseries signalPrice = slow + signal
plotLine(
value=signalPrice,
width=1,
colors=[signalColor],
label=["Signal"],
desc=["Signal SMA (" + signalLen + ") of EMA spread, overlayed on price"]
)
// Signal fill (fast vs signal price)
if (showSignalFill) {
var signalBull = fast > signalPrice
plotLine(
value=[fast, signalPrice],
width=1,
colors=[transparency(upColor, 15), transparency(dnColor, 15)],
colorIndex=signalBull ? 0 : 1,
fill=true,
label=["Fast EMA", "Signal"],
desc=["Fill between fast EMA and signal line"]
)
}
}
// 5.5 Crossover shapes
if (showShapes) {
if (crossUp) {
plotShape(
value=fast,
shape="triangleup",
colorIndex=upColor,
width=2,
label=["Golden Cross"],
desc=["Fast EMA crossed above slow EMA — bullish trend initiation"]
)
}
if (crossDown) {
plotShape(
value=fast,
shape="triangledown",
colorIndex=dnColor,
width=2,
label=["Death Cross"],
desc=["Fast EMA crossed below slow EMA — bearish trend initiation"]
)
}
if (signalCrossUp) {
plotShape(
value=fast,
shape="circle",
colorIndex=upColor,
width=2,
label=["Signal Cross Up"],
desc=["EMA spread crossed above signal SMA — momentum acceleration"]
)
}
if (signalCrossDown) {
plotShape(
value=fast,
shape="circle",
colorIndex=dnColor,
width=2,
label=["Signal Cross Dn"],
desc=["EMA spread crossed below signal SMA — momentum deceleration"]
)
}
if (zExtremeBull) {
plotShape(
value=fast,
shape="xcross",
colorIndex=dnColor,
width=2,
label=["Z Extreme Bull"],
desc=["Spread z-score above " + zThresh + " — overextended bullish momentum"]
)
}
if (zExtremeBear) {
plotShape(
value=fast,
shape="xcross",
colorIndex=upColor,
width=2,
label=["Z Extreme Bear"],
desc=["Spread z-score below -" + zThresh + " — overextended bearish momentum"]
)
}
}
// ---------------------------------------------------------------------------
// 6. Z-SCORE PANEL (offchart via secondary position trick —
// plotted as a separate line if platform supports it; otherwise
// the z-score is available in the regime table)
// ---------------------------------------------------------------------------
if (showZScore) {
// Since define() is fixed to "onchart", we plot the z-score as a
// faint reference line on the price axis. Users can create a separate
// offchart instance if the platform supports multiple indicators.
// For now, we expose the z-score in the table and shapes.
var zColor = spreadZ > 0 ? upColor : dnColor
plotLine(
value=src + spreadZ * src * 0.001,
width=1,
colors=[transparency(zColor, 70)],
label=["Z-Score Proxy"],
desc=["Z-score of EMA spread projected onto price axis (" + zWindow + ")"]
)
}
// 5.6 Spread histogram (offchart-proxied on price axis as deviation bands)
if (showHist) {
var histBull = spread >= 0
plotBar(
value=src + spread,
colors=[transparency(upColor, 40), transparency(dnColor, 40)],
colorIndex=histBull ? 0 : 1,
width=1,
label=["Spread"],
desc=["EMA spread (fast − slow) as deviation from source price"]
)
}
// ---------------------------------------------------------------------------
// 7. REGIME TABLE (last bar only)
// ---------------------------------------------------------------------------
if (isLastBar) {
var regimeText = regimeBull ? "BULLISH" : (regimeBear ? "BEARISH" : "NEUTRAL")
var regimeTextColor = regimeBull ? upColor : (regimeBear ? dnColor : neutralColor)
plotTable(
data=[
["Michael's EMA", regimeText],
["Fast EMA", fast[0]],
["Slow EMA", slow[0]],
["Spread", spread[0]],
["Signal", signal[0]],
["Spread Z", spreadZ[0]],
["Bull bars", bullBars],
["Bear bars", bearBars]
],
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
)
}