MM Flow
FlowScripts

Perfected FlowScript

GoldenCross Alert

GoldenCross Alert — Perfected is indexed as 285_goldencross_alert.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

9.9 KB

Lines

206

Native Signal Candidates

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

4/4 guarded

Golden Cross

line 117:5

Trigger

(showShapes && alertCross && goldenCross)

Value

low

Deps

alertCross:input, goldenCross:timeseries, showShapes:input

Death Cross

line 120:5

Trigger

(showShapes && alertCross && deathCross)

Value

high

Deps

alertCross:input, deathCross:timeseries, showShapes:input

Extreme Bull Distance

line 125:5

Trigger

(showShapes && alertDistance && extremeDistanceBull)

Value

fast

Deps

alertDistance:input, extremeDistanceBull:var, showShapes:input

Extreme Bear Distance

line 128:5

Trigger

(showShapes && alertDistance && extremeDistanceBear)

Value

fast

Deps

alertDistance:input, extremeDistanceBear:var, showShapes:input

285_goldencross_alert.flowscript

source path: kscripts/perfected/285_goldencross_alert.flowscript · sha256:a612fec624d28bdd21ba33db384e290c4d1e410b55b029f3a9fdd08c2f5d5a27

hash verified
//@version=2
/* ============================================================================
 * GoldenCross Alert — Perfected Edition
 * Author: U (@Urvesh311) | Perfected: kScript_Perfection_Engineer
 * Index: 285
 * Tags: CORE, #GoldenCrossAlert
 *
 * Production-quality Golden Cross / Death Cross indicator with 50/200 EMA
 * cross detection, multi-condition alert system, color-coded regime shading,
 * shape markers, and trend strength measurement.
 *
 * 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. The most comprehensive early study of MA crossovers using
 *     90 years of DJIA data. Buy signals from MA crossovers consistently
 *     followed by positive returns.
 *     DOI: https://doi.org/10.1111/j.1540-6261.1992.tb04681.x
 *
 *  2. Zakamulin (2023), "Optimal Trend-Following with Transaction Costs",
 *     Journal of Portfolio Management, 49(3), 86–101. The optimal trend-following
 *     strategy under transaction costs resembles a simple MA crossover rule.
 *     DOI: https://doi.org/10.3905/jpm.2023.1.478
 *
 *  3. Hurst, Ooi & Pedersen (2014), "A Century of Evidence on Trend-Following
 *     Investing", Journal of Portfolio Management, 40(5), 15–29. Time-series
 *     momentum profitable since 1880 across nearly all asset classes; performs
 *     well in equity bear markets.
 *     DOI: https://doi.org/10.3905/jpm.2014.40.5.015
 *
 *  4. Jegadeesh & Titman (1993), "Returns to Buying Winners and Selling Losers:
 *     Implications for Stock Market Efficiency", Journal of Finance, 48(1),
 *     65–91. Momentum as a premier cross-sectional anomaly; validates the
 *     trend-following premise underlying MA crossovers.
 *     DOI: https://doi.org/10.1111/j.1540-6261.1993.tb04702.x
 * ============================================================================ */

define(title="GoldenCross Alert — Perfected", position="onchart", axis=false)

// ---------------------------------------------------------------------------
// 1. USER INPUTS — grouped, all numeric inputs carry constraints
// ---------------------------------------------------------------------------

// -- Moving Average Settings --
var fastLen = input(name="fastLen", type="number", defaultValue=50, label="Fast EMA Length", constraints={min: 5, max: 100, step: 5}, group="MA Settings")
var slowLen = input(name="slowLen", type="number", defaultValue=200, label="Slow EMA Length", constraints={min: 20, max: 500, step: 10}, group="MA Settings")
var maType = input(name="maType", type="select", defaultValue="EMA", label="MA Type", options=["SMA", "EMA"], group="MA Settings")

// -- Alert Settings --
var alertCross = input(name="alertCross", type="boolean", defaultValue=true, label="Alert on Cross", group="Alerts")
var alertDistance = input(name="alertDistance", type="boolean", defaultValue=true, label="Alert on Distance Extreme", group="Alerts")
var distanceThreshold = input(name="distanceThreshold", type="number", defaultValue=0.15, label="Distance Extreme %", constraints={min: 0.05, max: 0.5, step: 0.05}, group="Alerts")

// -- Display --
var showFast = input(name="showFast", type="boolean", defaultValue=true, label="Show Fast MA", group="Display")
var showSlow = input(name="showSlow", type="boolean", defaultValue=true, label="Show Slow MA", group="Display")
var showFill = input(name="showFill", type="boolean", defaultValue=true, label="Show Regime Fill", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Cross Shapes", group="Display")
var showDistance = input(name="showDistance", type="boolean", defaultValue=false, label="Show Distance Line", group="Display")

// -- Colors --
var fastColor = input(name="fastColor", type="color", defaultValue="#2962ff", label="Fast MA Color", group="Colors")
var slowColor = input(name="slowColor", type="color", defaultValue="#ff6d00", label="Slow MA Color", group="Colors")
var crossBullColor = input(name="crossBullColor", type="color", defaultValue="#00e676", label="Golden Cross Color", group="Colors")
var crossBearColor = input(name="crossBearColor", type="color", defaultValue="#ff5252", label="Death Cross Color", group="Colors")
var fillBullColor = input(name="fillBullColor", type="color", defaultValue="#00c853", label="Bullish Fill", group="Colors")
var fillBearColor = input(name="fillBearColor", type="color", defaultValue="#d50000", label="Bearish Fill", group="Colors")

// ---------------------------------------------------------------------------
// 2. DATA SOURCES & isnan GUARD
// ---------------------------------------------------------------------------

timeseries price = ohlcv(symbol=currentSymbol, exchange=currentExchange)
if (isnan(price.close[0])) {
    return
}

timeseries src = price.close

// ---------------------------------------------------------------------------
// 3. MOVING AVERAGE COMPUTATION
// ---------------------------------------------------------------------------

// -- 3.1 Fast and slow moving averages --
timeseries fast = maType == "EMA" ? ema(src, fastLen) : sma(src, fastLen)
timeseries slow = maType == "EMA" ? ema(src, slowLen) : sma(src, slowLen)

// -- 3.2 Cross detection --
timeseries goldenCross = crossover(fast, slow)
timeseries deathCross = crossunder(fast, slow)

// -- 3.3 Trend regime --
var trendBull = fast > slow
var trendBear = fast < slow
var trendColor = trendBull ? fillBullColor : fillBearColor

// -- 3.4 Distance between fast and slow (as % of price) --
timeseries distance = slow != 0 ? (fast - slow) / slow : 0
timeseries distancePct = distance * 100

// -- 3.5 Extreme distance detection --
var extremeDistanceBull = distance > distanceThreshold
var extremeDistanceBear = distance < -distanceThreshold

// -- 3.6 Trend strength (how long has the current trend been in place?) --
static trendBullBars = 0
static trendBearBars = 0
static lastCrossBar = 0

if (goldenCross) {
    trendBullBars = 1
    trendBearBars = 0
    lastCrossBar = bar_index
} else if (deathCross) {
    trendBearBars = 1
    trendBullBars = 0
    lastCrossBar = bar_index
} else if (trendBull) {
    trendBullBars = trendBullBars + 1
} else if (trendBear) {
    trendBearBars = trendBearBars + 1
}

// -- 3.7 Cross proximity (bars since last cross) --
static barsSinceCross = 0
barsSinceCross = barsSinceCross + 1
if (goldenCross || deathCross) {
    barsSinceCross = 0
}

// ---------------------------------------------------------------------------
// 4. VISUALIZATION
// ---------------------------------------------------------------------------

// -- 4.1 Fast and Slow MAs (plotLine) --
if (showFast) {
    plotLine(value=fast, width=2, colors=[fastColor], label=["Fast MA"], desc=["Fast moving average (" + fastLen + " " + maType + ")"])
}
if (showSlow) {
    plotLine(value=slow, width=2, colors=[slowColor], label=["Slow MA"], desc=["Slow moving average (" + slowLen + " " + maType + ")"])
}

// -- 4.2 Regime fill between fast and slow --
if (showFill) {
    var fillColorIdx = trendBull ? 0 : 1
    plotLine(value=[fast, slow], width=1, colors=[transparency(fillBullColor, 30), transparency(fillBearColor, 30)], colorIndex=fillColorIdx, fill=true, label=["Fast MA", "Slow MA"], desc=["Regime fill: bullish = fast above slow, bearish = fast below slow"])
}

// -- 4.3 Golden Cross / Death Cross shapes --
if (showShapes && alertCross && goldenCross) {
    plotShape(value=low, shape="triangleup", colorIndex=crossBullColor, width=4, label=["Golden Cross"], desc=["Fast MA crossed above slow MA: bullish trend signal"])
}
if (showShapes && alertCross && deathCross) {
    plotShape(value=high, shape="triangledown", colorIndex=crossBearColor, width=4, label=["Death Cross"], desc=["Fast MA crossed below slow MA: bearish trend signal"])
}

// -- 4.4 Extreme distance shapes --
if (showShapes && alertDistance && extremeDistanceBull) {
    plotShape(value=fast, shape="diamond", colorIndex=crossBullColor, width=2, label=["Extreme Bull Distance"], desc=["Fast MA stretched far above slow MA (>" + (distanceThreshold * 100) + "%); potential mean reversion"])
}
if (showShapes && alertDistance && extremeDistanceBear) {
    plotShape(value=fast, shape="diamond", colorIndex=crossBearColor, width=2, label=["Extreme Bear Distance"], desc=["Fast MA stretched far below slow MA (<-" + (distanceThreshold * 100) + "%); potential mean reversion"])
}

// -- 4.5 Distance line (optional, offchart-style) --
if (showDistance) {
    plotLine(value=distancePct, width=1, colors=[trendColor], label=["Distance %"], desc=["Percentage distance between fast and slow MA"])
}

// -- 4.6 Reference line --
hline(value=0, color="#ffffff20", width=1)

// ---------------------------------------------------------------------------
// 5. REGIME TABLE (last bar only)
// ---------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = trendBull ? "BULLISH" : (trendBear ? "BEARISH" : "NEUTRAL")
    var regimeTextColor = trendBull ? crossBullColor : (trendBear ? crossBearColor : "#9e9e9e")
    var crossText = goldenCross ? "GOLDEN CROSS" : (deathCross ? "DEATH CROSS" : "—")
    var distanceText = "Distance: " + (distancePct[0] * 100) + "%"

    plotTable(
        data=[
            ["GoldenCross Alert", regimeText],
            ["Fast MA", fast[0]],
            ["Slow MA", slow[0]],
            ["Distance %", distancePct[0]],
            ["Bull Trend Bars", trendBullBars],
            ["Bear Trend Bars", trendBearBars],
            ["Bars Since Cross", barsSinceCross],
            ["Last Cross", crossText]
        ],
        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
    )
}