Perfected FlowScript
Ema RIbbon
EMA Ribbon V2 is indexed as 202_ema_ribbon.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
16.3 KB
Lines
387
Native Signal Candidates
3 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Compression
line 316:9
Trigger
(showComp && showShapes) && (isCompression)
Value
px
Deps
isCompression:var, showComp:input, showShapes:input
Bull Cross
line 333:9
Trigger
(showShapes) && (crossUp)
Value
px
Deps
crossUp:var, showShapes:input
Bear Cross
line 343:9
Trigger
(showShapes) && (crossDn)
Value
px
Deps
crossDn:var, showShapes:input
202_ema_ribbon.flowscript
source path: kscripts/perfected/202_ema_ribbon.flowscript · sha256:3f709fcd0be6a0dfa7af3e1f9252fba58b0c2b197ab90a866846c1167507fb0b
//@version=2
// ============================================================================
// EMA Ribbon V2 — Production-Quality Guppy Multiple Moving Average (GMMA) Ribbon
// Author: T (@Tuto) | Perfected by: kScript Perfection Engineer
// Tags: CORE, #ema, #ribbon, #guppy, #trend, #momentum, #regime
//
// Production-quality academically-grounded multi-EMA ribbon trend indicator.
// Implements the Guppy Multiple Moving Average (GMMA) framework with
// ribbon compression/expansion detection, regime-coded color fills, crossover
// shape markers, and comprehensive stateful tracking.
//
// FORMULA FOUNDATION:
// 1. Guppy Multiple Moving Average (GMMA): Daryl Guppy (1990s–2000s).
// Two clusters of EMAs — short-term (3, 5, 8, 10, 12, 15) representing
// trader sentiment; long-term (30, 35, 40, 45, 50, 60) representing
// investor behavior. Gap width between clusters = trend strength.
// 2. EMA: Price × k + EMA(prev) × (1 − k), where k = 2/(N+1).
// Per Manasa & Reddy (2025), EMA offers stability but lags on reversals.
// Multiple EMAs jointly reduce whipsaw vs. any single average.
// 3. Trend Following: Hurst, Ooi & Pedersen (2014) — time-series momentum
// profitable on average since 1880 across equities, fixed income,
// commodities, and currencies. EMA ribbons visualize multi-horizon momentum.
// 4. Ribbon Compression: Standard deviation of the EMA ensemble. Low stddev
// indicates convergence / range-bound conditions; high stddev indicates
// trending conditions. Related to Bollinger Bandwidth (Bollinger 2001).
//
// RESEARCH BASIS:
// • Guppy, D. (1990s–2000s). Guppy Multiple Moving Average (GMMA) system.
// Technical Analysis of Stocks & Commodities articles.
// • Hurst, B., Ooi, Y.H. & Pedersen, L.H. (2014). "A Century of Evidence on
// Trend-Following Investing." AQR Capital Management. Multi-horizon
// momentum profitability since 1880.
// • Manasa & Reddy (2025). "Trend Analysis by Weighted and Exponential
// Moving Average." IJRIAS. EMA stability vs. WMA responsiveness tradeoff.
// • Bollinger, J. (2001). *Bollinger on Bollinger Bands*. BandWidth as
// volatility / expansion measure; %B as normalized position within bands.
// • Wilder, J.W. (1978). *New Concepts in Technical Trading Systems*.
// Canonical EMA and ATR formulations; smoothing and noise reduction.
// • Zakamulin, V. (2023). "Optimal Trend-Following with Transaction Costs."
// International Review of Financial Analysis. Mathematical justification
// for MA crossover rules under transaction costs.
// ============================================================================
define(
title="EMA Ribbon V2",
position="onchart",
axis=false
)
// ------------------------------------------------------------------------------
// 1. USER INPUTS — grouped with constraints
// ------------------------------------------------------------------------------
// --- Fast Ribbon (Trader Sentiment) ---
var fast1 = input(name="fast1", type="number", defaultValue=5, label="Fast EMA 1", constraints={min: 2, max: 50, step: 1}, group="Fast Ribbon")
var fast2 = input(name="fast2", type="number", defaultValue=8, label="Fast EMA 2", constraints={min: 2, max: 50, step: 1}, group="Fast Ribbon")
var fast3 = input(name="fast3", type="number", defaultValue=10, label="Fast EMA 3", constraints={min: 2, max: 50, step: 1}, group="Fast Ribbon")
var fast4 = input(name="fast4", type="number", defaultValue=12, label="Fast EMA 4", constraints={min: 2, max: 50, step: 1}, group="Fast Ribbon")
// --- Slow Ribbon (Investor Behavior) ---
var slow1 = input(name="slow1", type="number", defaultValue=30, label="Slow EMA 1", constraints={min: 5, max: 200, step: 1}, group="Slow Ribbon")
var slow2 = input(name="slow2", type="number", defaultValue=35, label="Slow EMA 2", constraints={min: 5, max: 200, step: 1}, group="Slow Ribbon")
var slow3 = input(name="slow3", type="number", defaultValue=40, label="Slow EMA 3", constraints={min: 5, max: 200, step: 1}, group="Slow Ribbon")
var slow4 = input(name="slow4", type="number", defaultValue=50, label="Slow EMA 4", constraints={min: 5, max: 200, step: 1}, group="Slow Ribbon")
// --- Source & Smoothing ---
var srcType = input(name="srcType", type="select", defaultValue="close", label="Source Price", options=["close", "hl2", "hlc3", "ohlc4"], group="Calculation")
var ribbonSmooth = input(name="ribbonSmooth", type="number", defaultValue=1, label="Ribbon Smoothing", constraints={min: 1, max: 10, step: 1}, group="Calculation")
// --- Compression / Expansion ---
var compLookback = input(name="compLookback", type="number", defaultValue=20, label="Compression Lookback", constraints={min: 5, max: 100, step: 1}, group="Compression")
var compThreshold = input(name="compThreshold", type="number", defaultValue=0.5, label="Compression Threshold (σ)", constraints={min: 0.1, max: 3.0, step: 0.1}, group="Compression")
var expThreshold = input(name="expThreshold", type="number", defaultValue=2.0, label="Expansion Threshold (σ)", constraints={min: 1.0, max: 5.0, step: 0.1}, group="Compression")
// --- Display ---
var showFast = input(name="showFast", type="boolean", defaultValue=true, label="Show Fast Ribbon", group="Display")
var showSlow = input(name="showSlow", type="boolean", defaultValue=true, label="Show Slow Ribbon", group="Display")
var showRibbonFill = input(name="showRibbonFill", type="boolean", defaultValue=true, label="Show Ribbon Fill", group="Display")
var showAvgLines = input(name="showAvgLines", type="boolean", defaultValue=true, label="Show Avg Lines", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Crossover Shapes", group="Display")
var showComp = input(name="showComp", type="boolean", defaultValue=true, label="Show Compression/Expansion", group="Display")
// --- Colors ---
var fastColor = input(name="fastColor", type="color", defaultValue="#26a69a", label="Fast Ribbon Color", group="Colors")
var slowColor = input(name="slowColor", type="color", defaultValue="#ef5350", label="Slow Ribbon 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="#ff1744", label="Bearish Regime Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#9e9e9e", label="Neutral Regime Color", group="Colors")
var compColor = input(name="compColor", type="color", defaultValue="#ffd600", label="Compression Color", group="Colors")
// ------------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// ------------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries px = bars.close
if (isnan(px[0])) {
return
}
// Source price selection
timeseries src = px
if (srcType == "hl2") {
src = (bars.high + bars.low) / 2
} else if (srcType == "hlc3") {
src = (bars.high + bars.low + bars.close) / 3
} else if (srcType == "ohlc4") {
src = (bars.open + bars.high + bars.low + bars.close) / 4
}
// ------------------------------------------------------------------------------
// 3. EMA COMPUTATION — Full 8-line Ribbon (GMMA Framework)
// ------------------------------------------------------------------------------
timeseries e5 = ema(source=src, period=fast1)
timeseries e8 = ema(source=src, period=fast2)
timeseries e10 = ema(source=src, period=fast3)
timeseries e12 = ema(source=src, period=fast4)
timeseries e30 = ema(source=src, period=slow1)
timeseries e35 = ema(source=src, period=slow2)
timeseries e40 = ema(source=src, period=slow3)
timeseries e50 = ema(source=src, period=slow4)
// Ribbon averages (cluster midpoints)
timeseries fastAvg = (e5 + e8 + e10 + e12) / 4
timeseries slowAvg = (e30 + e35 + e40 + e50) / 4
// Optional smoothing on averages
timeseries fastAvgSmooth = ribbonSmooth > 1 ? ema(fastAvg, ribbonSmooth) : fastAvg
timeseries slowAvgSmooth = ribbonSmooth > 1 ? ema(slowAvg, ribbonSmooth) : slowAvg
// ------------------------------------------------------------------------------
// 4. REGIME DETECTION
// ------------------------------------------------------------------------------
// Bullish: fastAvg > slowAvg AND price > fastAvg (strong uptrend)
// Bearish: fastAvg < slowAvg AND price < fastAvg (strong downtrend)
// Neutral: everything else (chop / transition)
var regimeBull = fastAvgSmooth > slowAvgSmooth && px > fastAvgSmooth
var regimeBear = fastAvgSmooth < slowAvgSmooth && px < fastAvgSmooth
var regimeNeutral = !regimeBull && !regimeBear
var regimeColor = regimeBull ? bullColor : (regimeBear ? bearColor : neutralColor)
// ------------------------------------------------------------------------------
// 5. RIBBON COMPRESSION / EXPANSION DETECTION
// ------------------------------------------------------------------------------
// Per Bollinger (2001) BandWidth concept: ensemble stddev of the 8 EMAs
// measures how tightly clustered vs. spread out the ribbon is.
// Low stddev = compression (pending breakout); high stddev = expansion (trending).
var ribbonMean = (e5 + e8 + e10 + e12 + e30 + e35 + e40 + e50) / 8
var ribbonVar = (
(e5 - ribbonMean) * (e5 - ribbonMean) +
(e8 - ribbonMean) * (e8 - ribbonMean) +
(e10 - ribbonMean) * (e10 - ribbonMean) +
(e12 - ribbonMean) * (e12 - ribbonMean) +
(e30 - ribbonMean) * (e30 - ribbonMean) +
(e35 - ribbonMean) * (e35 - ribbonMean) +
(e40 - ribbonMean) * (e40 - ribbonMean) +
(e50 - ribbonMean) * (e50 - ribbonMean)
) / 8
var ribbonStd = math.sqrt(ribbonVar)
// Normalize ribbon spread by price (percentage) for cross-asset comparability
var ribbonSpreadPct = ribbonMean > 0 ? ribbonStd / ribbonMean * 100.0 : 0.0
// Rolling mean and stddev of the spread for compression/expansion classification
var spreadMean = sma(ribbonSpreadPct, compLookback)
var spreadStd = stddev(ribbonSpreadPct, compLookback)
var spreadZ = spreadStd > 0 ? (ribbonSpreadPct - spreadMean) / spreadStd : 0.0
var isCompression = spreadZ < -compThreshold
var isExpansion = spreadZ > expThreshold
var isTrending = !isCompression && !isExpansion
// ------------------------------------------------------------------------------
// 6. STATIC STATE TRACKING
// ------------------------------------------------------------------------------
static lastRegime = 0
static crossUpCount = 0
static crossDnCount = 0
static compressionCount = 0
static expansionCount = 0
static lastBarIndex = 0
var currentBarIndex = bar_index[0]
if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
lastBarIndex = currentBarIndex
// Track crossover counts
var crossUp = fastAvgSmooth > slowAvgSmooth && !isnan(fastAvgSmooth[1]) && fastAvgSmooth[1] <= slowAvgSmooth[1]
var crossDn = fastAvgSmooth < slowAvgSmooth && !isnan(fastAvgSmooth[1]) && fastAvgSmooth[1] >= slowAvgSmooth[1]
if (crossUp) {
crossUpCount = crossUpCount + 1
}
if (crossDn) {
crossDnCount = crossDnCount + 1
}
// Track compression / expansion counts
if (isCompression) {
compressionCount = compressionCount + 1
}
if (isExpansion) {
expansionCount = expansionCount + 1
}
lastRegime = regimeBull ? 1 : (regimeBear ? -1 : 0)
}
// ------------------------------------------------------------------------------
// 7. PLOTTING
// ------------------------------------------------------------------------------
// --- Fast Ribbon (trader sentiment) ---
if (showFast) {
plotLine(
value=e5,
width=1,
colors=[opacity(fastColor, 80)],
label=["EMA 5"],
desc=["Fast EMA 5 — trader sentiment ribbon edge"]
)
plotLine(
value=e8,
width=1,
colors=[opacity(fastColor, 70)],
label=["EMA 8"],
desc=["Fast EMA 8 — trader sentiment ribbon edge"]
)
plotLine(
value=e10,
width=1,
colors=[opacity(fastColor, 60)],
label=["EMA 10"],
desc=["Fast EMA 10 — trader sentiment ribbon edge"]
)
plotLine(
value=e12,
width=1,
colors=[opacity(fastColor, 50)],
label=["EMA 12"],
desc=["Fast EMA 12 — trader sentiment ribbon edge"]
)
}
// --- Slow Ribbon (investor behavior) ---
if (showSlow) {
plotLine(
value=e30,
width=1,
colors=[opacity(slowColor, 80)],
label=["EMA 30"],
desc=["Slow EMA 30 — investor behavior ribbon edge"]
)
plotLine(
value=e35,
width=1,
colors=[opacity(slowColor, 70)],
label=["EMA 35"],
desc=["Slow EMA 35 — investor behavior ribbon edge"]
)
plotLine(
value=e40,
width=1,
colors=[opacity(slowColor, 60)],
label=["EMA 40"],
desc=["Slow EMA 40 — investor behavior ribbon edge"]
)
plotLine(
value=e50,
width=1,
colors=[opacity(slowColor, 50)],
label=["EMA 50"],
desc=["Slow EMA 50 — investor behavior ribbon edge"]
)
}
// --- Average Lines (ribbon midpoints) with regime fill ---
if (showAvgLines) {
plotLine(
value=fastAvgSmooth,
width=2,
colors=[regimeColor],
label=["Fast Avg"],
desc=["Fast ribbon average (regime-colored)"]
)
plotLine(
value=slowAvgSmooth,
width=2,
colors=[regimeColor],
label=["Slow Avg"],
desc=["Slow ribbon average (regime-colored)"]
)
}
// --- Ribbon Fill (fast avg vs slow avg) ---
if (showRibbonFill) {
var ribbonBull = fastAvgSmooth > slowAvgSmooth
plotLine(
value=[fastAvgSmooth, slowAvgSmooth],
width=1,
colors=[transparency(bullColor, 30), transparency(bearColor, 30)],
colorIndex=ribbonBull ? 0 : 1,
fill=true,
label=["Fast Avg", "Slow Avg"],
desc=["Fill between fast and slow ribbon averages"]
)
}
// --- Compression / Expansion highlight shapes ---
if (showComp && showShapes) {
if (isCompression) {
plotShape(
value=px,
shape="square",
color=compColor,
width=1,
label=["Compression"],
desc=["Ribbon compression detected — EMAs converging, potential breakout pending"]
)
}
}
// --- Crossover shapes ---
if (showShapes) {
var crossUp = fastAvgSmooth > slowAvgSmooth && !isnan(fastAvgSmooth[1]) && fastAvgSmooth[1] <= slowAvgSmooth[1]
var crossDn = fastAvgSmooth < slowAvgSmooth && !isnan(fastAvgSmooth[1]) && fastAvgSmooth[1] >= slowAvgSmooth[1]
if (crossUp) {
plotShape(
value=px,
shape="triangleup",
color=bullColor,
width=3,
label=["Bull Cross"],
desc=["Fast ribbon crossed above slow ribbon — bullish regime shift"]
)
}
if (crossDn) {
plotShape(
value=px,
shape="triangledown",
color=bearColor,
width=3,
label=["Bear Cross"],
desc=["Fast ribbon crossed below slow ribbon — bearish regime shift"]
)
}
}
// ------------------------------------------------------------------------------
// 8. REGIME TABLE (last bar only)
// ------------------------------------------------------------------------------
if (isLastBar) {
var regimeText = regimeBull ? "BULLISH" : (regimeBear ? "BEARISH" : "NEUTRAL")
var regimeTextColor = regimeBull ? bullColor : (regimeBear ? bearColor : neutralColor)
var compText = isCompression ? "COMPRESSION" : (isExpansion ? "EXPANSION" : "TRENDING")
var compTextColor = isCompression ? compColor : (isExpansion ? (regimeBull ? bullColor : bearColor) : neutralColor)
plotTable(
data=[
["EMA Ribbon V2", regimeText],
["Fast Avg", fastAvgSmooth[0]],
["Slow Avg", slowAvgSmooth[0]],
["Ribbon Spread %", ribbonSpreadPct[0]],
["Spread Z-Score", spreadZ[0]],
["State", compText],
["Cross Up", crossUpCount],
["Cross Down", crossDnCount]
],
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
)
}