MM Flow
FlowScripts

Perfected FlowScript

Multi Moving Average SMA and EMA

Multi Moving Average — SMA & EMA Ribbon is indexed as 137_multi_moving_average_sma_and_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

13.8 KB

Lines

502

Native Signal Candidates

7 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.

7/7 guarded

EMA 9/21 Bull Cross

line 398:9

Trigger

(showCrossovers) && (ema9CrossUp)

Value

ema9

Deps

ema9CrossUp:var, showCrossovers:input

EMA 9/21 Bear Cross

line 408:9

Trigger

(showCrossovers) && (ema9CrossDown)

Value

ema9

Deps

ema9CrossDown:var, showCrossovers:input

SMA 9/21 Bull Cross

line 418:9

Trigger

(showCrossovers) && (sma9CrossUp)

Value

sma9

Deps

showCrossovers:input, sma9CrossUp:var

SMA 9/21 Bear Cross

line 428:9

Trigger

(showCrossovers) && (sma9CrossDown)

Value

sma9

Deps

showCrossovers:input, sma9CrossDown:var

Golden Cross

line 440:5

Trigger

(showGoldenCross && sma50CrossUp)

Value

sma50

Deps

showGoldenCross:input, sma50CrossUp:var

Death Cross

line 450:5

Trigger

(showDeathCross && sma50CrossDown)

Value

sma50

Deps

showDeathCross:input, sma50CrossDown:var

Unlabeled shape

line 463:5

Trigger

(isLastBar)

Value

bars.high

Deps

isLastBar:builtin

137_multi_moving_average_sma_and_ema.flowscript

source path: kscripts/perfected/137_multi_moving_average_sma_and_ema.flowscript · sha256:1de61b854190594488944e47c3ab2f1913ea73b30da109ac6e9965598438c6a5

hash verified
//@version=2
// ============================================================================
// Multi Moving Average — SMA & EMA Ribbon with Regime Detection
// Author: R (@ReinnerM) — Perfected Edition
// Tags: CORE, #movingaverage, #sma, #ema, #ribbon, #trend, #regime
//
// Production-grade multi-period trend overlay plotting SMA 9/21/50/200 and
// EMA 9/21/50/200 with ribbon fill between fast and slow clusters, regime-
// color coding, crossover shape markers, and trend alignment table. Serves
// as a session regime filter and multi-timeframe confluence check.
//
// Academic foundations:
//  - Wilder (1978), "New Concepts in Technical Trading Systems": canonical
//    SMA/EMA smoothing framework. EMA = Price × k + EMA(prev) × (1 − k),
//    where k = 2/(N+1). Introduced ATR as volatility-normalized measure.
//  - Brock, Lakonishok & LeBaron (1992), "Simple Technical Trading Rules and
//    the Stochastic Properties of Stock Returns" (J. Finance). Found MA
//    crossover rules significantly outperformed buy-and-hold on 90 years of
//    DJIA data. Buy signals followed by positive returns; sell by negative.
//  - Manasa & Rajashekhar Reddy (2025), "Trend Analysis by Weighted and
//    Exponential Moving Average". EMA offers stability but lags in reversals;
//    combined SMA+EMA approach yields more robust decisions. Directly supports
//    the dual-ribbon architecture.
//  - Hurst, Ooi & Pedersen (2014), "A Century of Evidence on Trend-Following
//    Investing" (AQR). Time-series momentum profitable since 1880 across
//    equities, fixed income, commodities, and FX. Simple MA rules justified
//    mathematically under transaction costs (Zakamulin 2023).
//  - Zakamulin (2023), "Optimal Trend-Following with Transaction Costs".
//    Optimal trend-following strategy resembles simple MA crossover rule.
//    Historical simulations validate the model's effectiveness.
// ============================================================================

define(
    title="Multi Moving Average — SMA & EMA Ribbon",
    position="onchart",
    axis=false
)

// === USER INPUTS ===
// --- SMA Toggles ---
var showSma9 = input(
    name="showSma9",
    type="boolean",
    defaultValue=true,
    label="Show SMA 9",
    group="SMA Lines"
)
var showSma21 = input(
    name="showSma21",
    type="boolean",
    defaultValue=true,
    label="Show SMA 21",
    group="SMA Lines"
)
var showSma50 = input(
    name="showSma50",
    type="boolean",
    defaultValue=true,
    label="Show SMA 50",
    group="SMA Lines"
)
var showSma200 = input(
    name="showSma200",
    type="boolean",
    defaultValue=true,
    label="Show SMA 200",
    group="SMA Lines"
)

// --- EMA Toggles ---
var showEma9 = input(
    name="showEma9",
    type="boolean",
    defaultValue=true,
    label="Show EMA 9",
    group="EMA Lines"
)
var showEma21 = input(
    name="showEma21",
    type="boolean",
    defaultValue=true,
    label="Show EMA 21",
    group="EMA Lines"
)
var showEma50 = input(
    name="showEma50",
    type="boolean",
    defaultValue=true,
    label="Show EMA 50",
    group="EMA Lines"
)
var showEma200 = input(
    name="showEma200",
    type="boolean",
    defaultValue=true,
    label="Show EMA 200",
    group="EMA Lines"
)

// --- Ribbon Fill ---
var showSmaRibbon = input(
    name="showSmaRibbon",
    type="boolean",
    defaultValue=true,
    label="Show SMA Ribbon Fill (9 vs 200)",
    group="Ribbon Fill"
)
var showEmaRibbon = input(
    name="showEmaRibbon",
    type="boolean",
    defaultValue=true,
    label="Show EMA Ribbon Fill (9 vs 200)",
    group="Ribbon Fill"
)

// --- Crossover Markers ---
var showCrossovers = input(
    name="showCrossovers",
    type="boolean",
    defaultValue=true,
    label="Show Crossover Shapes",
    group="Crossover Markers"
)
var showGoldenCross = input(
    name="showGoldenCross",
    type="boolean",
    defaultValue=true,
    label="Show Golden Cross (50/200 SMA)",
    group="Crossover Markers"
)
var showDeathCross = input(
    name="showDeathCross",
    type="boolean",
    defaultValue=true,
    label="Show Death Cross (50/200 SMA)",
    group="Crossover Markers"
)

// --- Colors ---
var cSma9 = input(
    name="cSma9",
    type="color",
    defaultValue="#26a69a",
    label="SMA 9 Color",
    group="Colors"
)
var cSma21 = input(
    name="cSma21",
    type="color",
    defaultValue="#2962ff",
    label="SMA 21 Color",
    group="Colors"
)
var cSma50 = input(
    name="cSma50",
    type="color",
    defaultValue="#ab47bc",
    label="SMA 50 Color",
    group="Colors"
)
var cSma200 = input(
    name="cSma200",
    type="color",
    defaultValue="#9e9e9e",
    label="SMA 200 Color",
    group="Colors"
)
var cEma9 = input(
    name="cEma9",
    type="color",
    defaultValue="#ff6d00",
    label="EMA 9 Color",
    group="Colors"
)
var cEma21 = input(
    name="cEma21",
    type="color",
    defaultValue="#ffeb3b",
    label="EMA 21 Color",
    group="Colors"
)
var cEma50 = input(
    name="cEma50",
    type="color",
    defaultValue="#26c6da",
    label="EMA 50 Color",
    group="Colors"
)
var cEma200 = input(
    name="cEma200",
    type="color",
    defaultValue="#ef5350",
    label="EMA 200 Color",
    group="Colors"
)
var bullColor = input(
    name="bullColor",
    type="color",
    defaultValue="#26a69a",
    label="Bullish Regime Color",
    group="Colors"
)
var bearColor = input(
    name="bearColor",
    type="color",
    defaultValue="#ef5350",
    label="Bearish Regime Color",
    group="Colors"
)

// === DATA ===
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries c = bars.close

if (isnan(c[0])) {
    return
}

// === MOVING AVERAGES ===
timeseries sma9 = sma(c, 9)
timeseries sma21 = sma(c, 21)
timeseries sma50 = sma(c, 50)
timeseries sma200 = sma(c, 200)
timeseries ema9 = ema(c, 9)
timeseries ema21 = ema(c, 21)
timeseries ema50 = ema(c, 50)
timeseries ema200 = ema(c, 200)

// === REGIME DETECTION ===
// Bullish regime: fast MA above slow MA AND price above fast MA.
// Bearish regime: fast MA below slow MA AND price below fast MA.
// We use both SMA and EMA clusters for confluence.

var smaBull = sma9 > sma50 && sma21 > sma50 && c > sma9
var smaBear = sma9 < sma50 && sma21 < sma50 && c < sma9
var emaBull = ema9 > ema50 && ema21 > ema50 && c > ema9
var emaBear = ema9 < ema50 && ema21 < ema50 && c < ema9

// Combined regime: both SMA and EMA agree = strong; one agrees = moderate; none = neutral.
var strongBull = smaBull && emaBull
var strongBear = smaBear && emaBear
var moderateBull = (smaBull || emaBull) && !strongBull && !strongBear
var moderateBear = (smaBear || emaBear) && !strongBull && !strongBear
var regimeNeutral = !strongBull && !strongBear && !moderateBull && !moderateBear

var regimeColor = strongBull ? bullColor : (strongBear ? bearColor : (moderateBull || moderateBear ? "#ffeb3b" : "#9e9e9e"))

// === CROSSOVER DETECTION ===
// Golden Cross: SMA 50 crosses above SMA 200.
// Death Cross: SMA 50 crosses below SMA 200.
// General crossovers: fast vs slow for any visible pair.

var sma50CrossUp = sma50 > sma200 && sma50[1] <= sma200[1]
var sma50CrossDown = sma50 < sma200 && sma50[1] >= sma200[1]
var ema9CrossUp = ema9 > ema21 && ema9[1] <= ema21[1]
var ema9CrossDown = ema9 < ema21 && ema9[1] >= ema21[1]
var sma9CrossUp = sma9 > sma21 && sma9[1] <= sma21[1]
var sma9CrossDown = sma9 < sma21 && sma9[1] >= sma21[1]

// === STATIC STATE: Crossover & Regime Tracking ===
static lastGoldenCrossBar = 0
static lastDeathCrossBar = 0
static lastRegime = 0  // 1 = bull, -1 = bear, 0 = neutral
static lastCrossoverBar = 0
static lastCrossoverType = 0  // 1 = bull cross, -1 = bear cross

if (!isLiveUpdate) {
    if (sma50CrossUp) {
        lastGoldenCrossBar = barCount
    }
    if (sma50CrossDown) {
        lastDeathCrossBar = barCount
    }
    if (ema9CrossUp || sma9CrossUp) {
        lastCrossoverBar = barCount
        lastCrossoverType = 1
    }
    if (ema9CrossDown || sma9CrossDown) {
        lastCrossoverBar = barCount
        lastCrossoverType = -1
    }
    if (strongBull) {
        lastRegime = 1
    } else if (strongBear) {
        lastRegime = -1
    } else {
        lastRegime = 0
    }
}

// === PLOTS: SMA LINES (plotLine) ===
if (showSma9) {
    plotLine(
        value=sma9,
        width=1,
        colors=[cSma9],
        label=["SMA 9"],
        desc=["Simple Moving Average (9). Short-term trend filter."]
    )
}
if (showSma21) {
    plotLine(
        value=sma21,
        width=1,
        colors=[cSma21],
        label=["SMA 21"],
        desc=["Simple Moving Average (21). Swing trend alignment."]
    )
}
if (showSma50) {
    plotLine(
        value=sma50,
        width=2,
        colors=[cSma50],
        label=["SMA 50"],
        desc=["Simple Moving Average (50). Medium-term trend benchmark."]
    )
}
if (showSma200) {
    plotLine(
        value=sma200,
        width=3,
        colors=[cSma200],
        label=["SMA 200"],
        desc=["Simple Moving Average (200). Long-term secular trend."]
    )
}

// === PLOTS: EMA LINES (plotLine) ===
if (showEma9) {
    plotLine(
        value=ema9,
        width=1,
        colors=[cEma9],
        label=["EMA 9"],
        desc=["Exponential Moving Average (9). Responsive short-term trend."]
    )
}
if (showEma21) {
    plotLine(
        value=ema21,
        width=1,
        colors=[cEma21],
        label=["EMA 21"],
        desc=["Exponential Moving Average (21). Responsive swing alignment."]
    )
}
if (showEma50) {
    plotLine(
        value=ema50,
        width=2,
        colors=[cEma50],
        label=["EMA 50"],
        desc=["Exponential Moving Average (50). Responsive medium-term trend."]
    )
}
if (showEma200) {
    plotLine(
        value=ema200,
        width=3,
        colors=[cEma200],
        label=["EMA 200"],
        desc=["Exponential Moving Average (200). Responsive long-term trend."]
    )
}

// === PLOTS: SMA RIBBON FILL (plotLine with fill) ===
if (showSmaRibbon) {
    var smaRibbonBull = sma9 > sma200
    plotLine(
        value=[sma9, sma200],
        width=1,
        colors=[transparency(bullColor, 30), transparency(bearColor, 30)],
        colorIndex=smaRibbonBull ? 0 : 1,
        fill=true,
        label=["SMA 9 Ribbon", "SMA 200 Ribbon"],
        desc=["SMA ribbon fast edge (9)", "SMA ribbon slow edge (200)"]
    )
}

// === PLOTS: EMA RIBBON FILL (plotLine with fill) ===
if (showEmaRibbon) {
    var emaRibbonBull = ema9 > ema200
    plotLine(
        value=[ema9, ema200],
        width=1,
        colors=[transparency(bullColor, 30), transparency(bearColor, 30)],
        colorIndex=emaRibbonBull ? 0 : 1,
        fill=true,
        label=["EMA 9 Ribbon", "EMA 200 Ribbon"],
        desc=["EMA ribbon fast edge (9)", "EMA ribbon slow edge (200)"]
    )
}

// === PLOTS: CROSSOVER SHAPES (plotShape) ===
if (showCrossovers) {
    if (ema9CrossUp) {
        plotShape(
            value=ema9,
            shape="triangleup",
            colorIndex=bullColor,
            width=3,
            label=["EMA 9/21 Bull Cross"],
            desc=["EMA 9 crossed above EMA 21. Short-term bullish momentum shift."]
        )
    }
    if (ema9CrossDown) {
        plotShape(
            value=ema9,
            shape="triangledown",
            colorIndex=bearColor,
            width=3,
            label=["EMA 9/21 Bear Cross"],
            desc=["EMA 9 crossed below EMA 21. Short-term bearish momentum shift."]
        )
    }
    if (sma9CrossUp) {
        plotShape(
            value=sma9,
            shape="triangleup",
            colorIndex=transparency(bullColor, 60),
            width=2,
            label=["SMA 9/21 Bull Cross"],
            desc=["SMA 9 crossed above SMA 21. Short-term trend confirmation."]
        )
    }
    if (sma9CrossDown) {
        plotShape(
            value=sma9,
            shape="triangledown",
            colorIndex=transparency(bearColor, 60),
            width=2,
            label=["SMA 9/21 Bear Cross"],
            desc=["SMA 9 crossed below SMA 21. Short-term trend weakening."]
        )
    }
}

if (showGoldenCross && sma50CrossUp) {
    plotShape(
        value=sma50,
        shape="circle",
        colorIndex="#ffd700",
        width=4,
        label=["Golden Cross"],
        desc=["Golden Cross: SMA 50 crossed above SMA 200. Classic long-term bullish signal."]
    )
}
if (showDeathCross && sma50CrossDown) {
    plotShape(
        value=sma50,
        shape="xcross",
        colorIndex=bearColor,
        width=4,
        label=["Death Cross"],
        desc=["Death Cross: SMA 50 crossed below SMA 200. Classic long-term bearish signal."]
    )
}

// === REGIME LABEL (plotPriceLabel) ===
if (isLastBar) {
    var regimeText = strongBull ? "STRONG BULLISH" : (strongBear ? "STRONG BEARISH" : (moderateBull ? "MODERATE BULL" : (moderateBear ? "MODERATE BEAR" : "NEUTRAL / CHOP")))
    plotPriceLabel(
        price=bars.high,
        text=regimeText,
        type="callout",
        color="#ffffff",
        backgroundColor=regimeColor,
        size=10,
        fontWeight=700
    )
}

// === TREND ALIGNMENT TABLE (plotTable) ===
if (isLastBar) {
    var smaRegime = smaBull ? "BULL" : (smaBear ? "BEAR" : "NEUTRAL")
    var emaRegime = emaBull ? "BULL" : (emaBear ? "BEAR" : "NEUTRAL")
    var lastGolden = lastGoldenCrossBar > 0 ? (barCount - lastGoldenCrossBar) + " bars ago" : "Never"
    var lastDeath = lastDeathCrossBar > 0 ? (barCount - lastDeathCrossBar) + " bars ago" : "Never"

    plotTable(
        data=[
            ["MA Ribbon", "Regime"],
            ["SMA Cluster", smaRegime],
            ["EMA Cluster", emaRegime],
            ["Golden Cross", lastGolden],
            ["Death Cross", lastDeath]
        ],
        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
    )
}