MM Flow
FlowScripts

Perfected FlowScript

EMA Crossover

EMA Crossover — Perfected Edition is indexed as 025_ema_crossover.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.7 KB

Lines

563

Native Signal Candidates

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

7/7 guarded

Bull Cross

line 448:9

Trigger

(showAlerts) && (crossUp)

Value

fastEma

Deps

crossUp:var, showAlerts:input

Bear Cross

line 458:9

Trigger

(showAlerts) && (crossDown)

Value

fastEma

Deps

crossDown:var, showAlerts:input

Strong Bull

line 472:9

Trigger

(showAlerts && strongTrend) && (regimeBull)

Value

fastEma

Deps

regimeBull:var, showAlerts:input, strongTrend:var

Strong Bear

line 482:9

Trigger

(showAlerts && strongTrend) && (regimeBear)

Value

fastEma

Deps

regimeBear:var, showAlerts:input, strongTrend:var

Consolidation

line 496:9

Trigger

(showConsolidation && showAlerts && isConsolidation) && (crossUp || crossDown)

Value

slowEma

Deps

crossDown:var, crossUp:var, isConsolidation:var, showAlerts:input, showConsolidation:input

Low Vol

line 506:5

Trigger

(showConsolidation && showAlerts && isConsolidation)

Value

hi

Deps

isConsolidation:var, showAlerts:input, showConsolidation:input

Unlabeled shape

line 519:5

Trigger

(showRegimeLabel && isLastBar)

Value

hi

Deps

isLastBar:builtin, showRegimeLabel:input

025_ema_crossover.flowscript

source path: kscripts/perfected/025_ema_crossover.flowscript · sha256:dfafe9a9ee232c6f73b47e2392cd0780d01e06017754d02f6c39c280987e9b6f

hash verified
//@version=2
// ============================================================================
// EMA Crossover — Perfected Edition
// Author: BackQuant (@BackQuant) | Enhanced by kScript Perfection Engineer
// Tags: CORE, #ema, #cross, #emacross, #trend, #regime
//
// Production-quality dual EMA trend-following system with crossover/crossunder
// detection, three-regime classification (bull/bear/neutral), EMA ribbon fill,
// gap-width momentum strength indicator, ATR-based consolidation warnings,
// trend strength scoring, and comprehensive shape alerts.
//
// Research papers underpinning this design:
//  1. Manasa & Reddy (2025), "Trend Analysis by Weighted and Exponential
//     Moving Average" (IJRIAS): EMA offers more stability than WMA but
//     occasionally lags in signaling reversals; combined approaches improve
//     robustness. EMA_t = α × Price_t + (1−α) × EMA_{t−1} where α = 2/(N+1).
//  2. Khand et al. (2019), "The Performance of EMA, MACD, RSI and Momentum
//     Trading Rules in the Pakistan Stock Market" (Indian J. Sci. Tech.):
//     EMA variants (1,50,1) and (1,50,0) remained profitable after transaction
//     costs, validating the EMA crossover as a viable trend signal.
//  3. Hurst, Ooi & Pedersen (2014), "A Century of Evidence on Trend-Following
//     Investing" (AQR/NYU): time-series momentum profitable since 1880 across
//     all major asset classes; trend following reduces volatility by a third to
//     a half while delivering strong positive returns.
//  4. Brock, Lakonishok & LeBaron (1992), "Simple Technical Trading Rules and
//     the Stochastic Properties of Stock Returns" (J. Finance): comprehensive
//     study using 90 years of DJIA data; moving average crossovers generated
//     buy signals consistently followed by positive returns and significantly
//     outperformed cash benchmarks.
//  5. Zakamulin (2023), "Optimal Trend-Following with Transaction Costs"
//     (Int. Rev. Fin. Anal.): optimal trend-following strategy resembles the
//     simple MA crossover rule; provides compelling mathematical justification
//     for practical adoption of crossover rules in the presence of frictions.
// ============================================================================

define(
    title="EMA Crossover — Perfected Edition",
    position="onchart",
    axis=false
)

// -----------------------------------------------------------------------------
// 1. USER INPUTS — grouped with constraints
// -----------------------------------------------------------------------------

// --- EMA Settings ---
var fastLen = input(
    name="fastLen",
    type="number",
    defaultValue=12,
    label="Fast EMA Length",
    constraints={min: 2, max: 200, step: 1},
    group="EMA Settings"
)
var slowLen = input(
    name="slowLen",
    type="number",
    defaultValue=26,
    label="Slow EMA Length",
    constraints={min: 2, max: 200, step: 1},
    group="EMA Settings"
)
var emaSource = input(
    name="emaSource",
    type="select",
    defaultValue="Close",
    label="EMA Source",
    options=["Close", "HL2", "HLC3", "OHLC4"],
    group="EMA Settings"
)

// --- Regime Settings ---
var neutralThreshold = input(
    name="neutralThreshold",
    type="number",
    defaultValue=0.5,
    label="Neutral Zone (× ATR)",
    constraints={min: 0.0, max: 5.0, step: 0.1},
    group="Regime Settings"
)
var showNeutral = input(
    name="showNeutral",
    type="boolean",
    defaultValue=true,
    label="Show Neutral Regime",
    group="Regime Settings"
)
var regimeConfirm = input(
    name="regimeConfirm",
    type="number",
    defaultValue=1,
    label="Regime Confirmation Bars",
    constraints={min: 1, max: 10, step: 1},
    group="Regime Settings"
)

// --- ATR Consolidation ---
var atrLen = input(
    name="atrLen",
    type="number",
    defaultValue=14,
    label="ATR Length",
    constraints={min: 5, max: 100, step: 1},
    group="ATR Consolidation"
)
var atrLookback = input(
    name="atrLookback",
    type="number",
    defaultValue=20,
    label="ATR Lookback",
    constraints={min: 5, max: 100, step: 1},
    group="ATR Consolidation"
)
var atrConsolidationMult = input(
    name="atrConsolidationMult",
    type="number",
    defaultValue=0.6,
    label="Consolidation Multiplier",
    constraints={min: 0.1, max: 2.0, step: 0.1},
    group="ATR Consolidation"
)
var showConsolidation = input(
    name="showConsolidation",
    type="boolean",
    defaultValue=true,
    label="Show Consolidation Warning",
    group="ATR Consolidation"
)

// --- Display ---
var showFastSlow = input(
    name="showFastSlow",
    type="boolean",
    defaultValue=true,
    label="Show Fast & Slow EMAs",
    group="Display"
)
var showRibbon = input(
    name="showRibbon",
    type="boolean",
    defaultValue=true,
    label="Show EMA Ribbon Fill",
    group="Display"
)
var showGap = input(
    name="showGap",
    type="boolean",
    defaultValue=true,
    label="Show Gap Histogram",
    group="Display"
)
var showGapPercent = input(
    name="showGapPercent",
    type="boolean",
    defaultValue=false,
    label="Show Gap Percent",
    group="Display"
)
var showGapSignal = input(
    name="showGapSignal",
    type="boolean",
    defaultValue=true,
    label="Show Gap Signal SMA",
    group="Display"
)
var signalLen = input(
    name="signalLen",
    type="number",
    defaultValue=9,
    label="Gap Signal Length",
    constraints={min: 2, max: 50, step: 1},
    group="Display"
)
var showTrendStrength = input(
    name="showTrendStrength",
    type="boolean",
    defaultValue=false,
    label="Show Trend Strength",
    group="Display"
)
var showAlerts = input(
    name="showAlerts",
    type="boolean",
    defaultValue=true,
    label="Show Alert Shapes",
    group="Display"
)
var showRegimeLabel = input(
    name="showRegimeLabel",
    type="boolean",
    defaultValue=true,
    label="Show Regime Label",
    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="#9e9e9e",
    label="Neutral Color",
    group="Colors"
)
var fastColor = input(
    name="fastColor",
    type="color",
    defaultValue="#2962ff",
    label="Fast EMA Color",
    group="Colors"
)
var slowColor = input(
    name="slowColor",
    type="color",
    defaultValue="#ff6d00",
    label="Slow EMA Color",
    group="Colors"
)
var consolidationColor = input(
    name="consolidationColor",
    type="color",
    defaultValue="#ffd700",
    label="Consolidation Warning Color",
    group="Colors"
)

// -----------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// -----------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries hi = bars.high
timeseries lo = bars.low
timeseries cl = bars.close

if (isnan(cl[0]) || isnan(hi[0]) || isnan(lo[0]) || isnan(bars.open[0])) {
    return
}

// EMA source selection
timeseries hl2 = (hi + lo) / 2
timeseries hlc3 = (hi + lo + cl) / 3
timeseries ohlc4 = (bars.open + hi + lo + cl) / 4
timeseries source = emaSource == "HL2" ? hl2 : (emaSource == "HLC3" ? hlc3 : (emaSource == "OHLC4" ? ohlc4 : cl))

// -----------------------------------------------------------------------------
// 3. EMA COMPUTATION
// -----------------------------------------------------------------------------
timeseries fastEma = ema(source, fastLen)
timeseries slowEma = ema(source, slowLen)

// -----------------------------------------------------------------------------
// 4. CROSSOVER / CROSSUNDER DETECTION
// -----------------------------------------------------------------------------
var crossUp = crossover(fastEma, slowEma)
var crossDown = crossunder(fastEma, slowEma)

// -----------------------------------------------------------------------------
// 5. REGIME DETECTION
// -----------------------------------------------------------------------------
// ATR (Wilder) for neutral-band and consolidation detection
timeseries prevClose = isnan(cl[1]) ? cl : cl[1]
timeseries tr1 = hi - lo
timeseries tr2 = math.abs(hi - prevClose)
timeseries tr3 = math.abs(lo - prevClose)
timeseries trueRange = math.max(tr1, math.max(tr2, tr3))
timeseries atr = sma(trueRange, atrLen)

timeseries gap = fastEma - slowEma
timeseries gapPercent = math.abs(gap) / math.max(0.0001, slowEma) * 100
timeseries neutralBand = atr * neutralThreshold

var rawRegimeBull = gap > neutralBand
var rawRegimeBear = gap < -neutralBand
var rawRegimeNeutral = !rawRegimeBull && !rawRegimeBear

// Regime confirmation: require N consecutive bars in regime before switching
static regimeState = 0  // 1 = bull, -1 = bear, 0 = neutral
static regimeBars = 0

if (!isLiveUpdate) {
    var currentRawRegime = rawRegimeBull ? 1 : (rawRegimeBear ? -1 : 0)
    if (currentRawRegime == regimeState) {
        regimeBars = regimeBars + 1
    } else {
        regimeBars = 1
        regimeState = currentRawRegime
    }
}

var regimeBull = regimeState == 1 && regimeBars >= regimeConfirm
var regimeBear = regimeState == -1 && regimeBars >= regimeConfirm
var regimeNeutral = !regimeBull && !regimeBear

var regimeColor = regimeBull ? bullColor : (regimeBear ? bearColor : neutralColor)

// -----------------------------------------------------------------------------
// 6. GAP / MOMENTUM STRENGTH
// -----------------------------------------------------------------------------
var gapBull = gap >= 0
timeseries gapSignal = sma(gap, signalLen)
timeseries trendStrength = math.abs(gap) / math.max(0.0001, atr)

// -----------------------------------------------------------------------------
// 7. ATR-BASED CONSOLIDATION WARNING
// -----------------------------------------------------------------------------
// Per Zakamulin (2023), low-volatility environments reduce crossover signal
// quality. We flag consolidation when current ATR is below its rolling
// average scaled by a multiplier.
timeseries atrSma = sma(atr, atrLookback)
var isConsolidation = atr < atrSma * atrConsolidationMult

// -----------------------------------------------------------------------------
// 8. STATIC STATE — Regime Tracking
// -----------------------------------------------------------------------------
static barCount = 0
static lastRegime = 0
static barsInRegime = 0
static lastCrossBar = 0
static crossCount = 0

if (!isLiveUpdate) {
    barCount = barCount + 1

    // Track regime persistence
    if (regimeState == lastRegime) {
        barsInRegime = barsInRegime + 1
    } else {
        barsInRegime = 0
    }
    lastRegime = regimeState

    // Track crossovers
    if (crossUp || crossDown) {
        crossCount = crossCount + 1
        lastCrossBar = barCount
    }
}

// -----------------------------------------------------------------------------
// 9. ALERT CONDITIONS
// -----------------------------------------------------------------------------
// Consolidation warning: only alert when crossover occurs during consolidation.
var consolidationAlert = (crossUp || crossDown) && isConsolidation

// Strong trend alert: gap > 2× ATR
var strongTrend = math.abs(gap) > atr * 2

// -----------------------------------------------------------------------------
// 10. PLOTTING
// -----------------------------------------------------------------------------

// --- Fast & Slow EMA Lines ---
if (showFastSlow) {
    plotLine(
        value=fastEma,
        width=2,
        colors=[fastColor],
        label=["Fast EMA"],
        desc=["Fast exponential moving average (" + fastLen + ")"]
    )
    plotLine(
        value=slowEma,
        width=2,
        colors=[slowColor],
        label=["Slow EMA"],
        desc=["Slow exponential moving average (" + slowLen + ")"]
    )
}

// --- EMA Ribbon Fill (fast vs slow) ---
if (showRibbon) {
    var ribbonBull = fastEma > slowEma
    plotLine(
        value=[fastEma, slowEma],
        width=1,
        colors=[transparency(bullColor, 30), transparency(bearColor, 30)],
        colorIndex=ribbonBull ? 0 : 1,
        fill=true,
        label=["Fast EMA", "Slow EMA"],
        desc=["Fast EMA ribbon edge", "Slow EMA ribbon edge"]
    )
}

// --- Gap Histogram (momentum strength) ---
if (showGap) {
    plotBar(
        value=gap,
        colors=[transparency(bullColor, 60), transparency(bearColor, 60)],
        colorIndex=gapBull ? 0 : 1,
        width=1,
        label=["EMA Gap"],
        desc=["Gap between fast and slow EMA (momentum strength)"]
    )
}

// --- Gap Signal SMA ---
if (showGapSignal) {
    plotLine(
        value=gapSignal,
        width=1,
        colors=[neutralColor],
        label=["Gap Signal"],
        desc=["SMA of EMA gap (" + signalLen + ") — momentum direction filter"]
    )
}

// --- Gap Percent Line ---
if (showGapPercent) {
    plotLine(
        value=gapPercent,
        width=1,
        colors=[neutralColor],
        label=["Gap %"],
        desc=["Absolute gap between EMAs as percent of slow EMA"]
    )
}

// --- Trend Strength ---
if (showTrendStrength) {
    plotLine(
        value=trendStrength,
        width=1,
        colors=[neutralColor],
        label=["Trend Strength"],
        desc=["Gap magnitude relative to ATR (strength of directional push)"]
    )
}

// --- Zero Line ---
hline(value=0, color=transparency(neutralColor, 40), width=1)

// --- Crossover Shapes ---
if (showAlerts) {
    if (crossUp) {
        plotShape(
            value=fastEma,
            shape="triangleup",
            colorIndex=bullColor,
            width=3,
            label=["Bull Cross"],
            desc=["Fast EMA crossed above Slow EMA — bullish regime change"]
        )
    }
    if (crossDown) {
        plotShape(
            value=fastEma,
            shape="triangledown",
            colorIndex=bearColor,
            width=3,
            label=["Bear Cross"],
            desc=["Fast EMA crossed below Slow EMA — bearish regime change"]
        )
    }
}

// --- Strong Trend Shapes ---
if (showAlerts && strongTrend) {
    if (regimeBull) {
        plotShape(
            value=fastEma,
            shape="arrowup",
            colorIndex=transparency(bullColor, 50),
            width=2,
            label=["Strong Bull"],
            desc=["Gap exceeds 2× ATR — strong bullish momentum"]
        )
    }
    if (regimeBear) {
        plotShape(
            value=fastEma,
            shape="arrowdown",
            colorIndex=transparency(bearColor, 50),
            width=2,
            label=["Strong Bear"],
            desc=["Gap exceeds 2× ATR — strong bearish momentum"]
        )
    }
}

// --- Consolidation Warning Shapes ---
if (showConsolidation && showAlerts && isConsolidation) {
    if (crossUp || crossDown) {
        plotShape(
            value=slowEma,
            shape="diamond",
            colorIndex=consolidationColor,
            width=2,
            label=["Consolidation"],
            desc=["Crossover during low ATR — signal quality reduced"]
        )
    }
    // Background warning dot on every bar during consolidation
    plotShape(
        value=hi,
        shape="circle",
        colorIndex=transparency(consolidationColor, 60),
        width=1,
        label=["Low Vol"],
        desc=["ATR below threshold — potential consolidation zone"]
    )
}

// --- Regime Label (on-chart callout) ---
if (showRegimeLabel && isLastBar) {
    var regimeText = regimeBull ? "BULLISH" : (regimeBear ? "BEARISH" : "NEUTRAL")
    plotPriceLabel(
        price=hi,
        text=regimeText,
        type="callout",
        color="#ffffff",
        backgroundColor=regimeColor,
        size=10,
        fontWeight=700
    )
}

// -----------------------------------------------------------------------------
// 11. REGIME TABLE (last bar only)
// -----------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = regimeBull ? "BULLISH" : (regimeBear ? "BEARISH" : "NEUTRAL")
    var regimeTextColor = regimeColor
    var consolidationText = isConsolidation ? "CONSOLIDATION" : "TRENDING"

    plotTable(
        data=[
            ["EMA Crossover — Perfected", regimeText],
            ["Fast EMA", fastEma[0]],
            ["Slow EMA", slowEma[0]],
            ["Gap", gap[0]],
            ["Gap %", gapPercent[0]],
            ["ATR", atr[0]],
            ["Regime Bars", barsInRegime],
            ["Cross Count", crossCount],
            ["State", consolidationText]
        ],
        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
    )
}