MM Flow
FlowScripts

Perfected FlowScript

Golden Cross

Golden Cross — Perfected Edition is indexed as 020_golden_cross.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

503

Native Signal Candidates

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

6/6 guarded

Golden Cross

line 388:9

Trigger

(showShapes) && (crossUp && atrFilter && volumeConfirmed)

Value

lo

Deps

atrFilter:var, crossUp:var, showShapes:input, volumeConfirmed:var

Death Cross

line 398:9

Trigger

(showShapes) && (crossDown && atrFilter && volumeConfirmed)

Value

hi

Deps

atrFilter:var, crossDown:var, showShapes:input, volumeConfirmed:var

Weak Golden Cross

line 409:9

Trigger

(showShapes) && (crossUp && (!atrFilter || !volumeConfirmed))

Value

lo

Deps

atrFilter:var, crossUp:var, showShapes:input, volumeConfirmed:var

Weak Death Cross

line 419:9

Trigger

(showShapes) && (crossDown && (!atrFilter || !volumeConfirmed))

Value

hi

Deps

atrFilter:var, crossDown:var, showShapes:input, volumeConfirmed:var

Unlabeled shape

line 446:5

Trigger

(showDuration && isLastBar)

Value

lo

Deps

isLastBar:builtin, showDuration:input

Unlabeled shape

line 459:5

Trigger

(showLabels && isLastBar)

Value

hi

Deps

isLastBar:builtin, showLabels:input

020_golden_cross.flowscript

source path: kscripts/perfected/020_golden_cross.flowscript · sha256:1e843184eb025ab809c9ddd6352f02cc8194f9859a8ecc0f0533367feacbcc2c

hash verified
//@version=2
// ============================================================================
// Golden Cross — Perfected Edition
// Author: kiyotaka (@kiyotaka) | Enhanced by kScript Perfection Engineer
// Tags: CORE, #momentum, #goldencross, #deathcross, #trend, #regime, #atr
//
// Production-quality moving average crossover system with configurable SMA/EMA
// fast/slow periods, full stateful regime tracking, ATR-based volatility filtering,
// regime-colored fill between moving averages, crossover event shape markers,
// trend strength measurement, and consolidation detection.
//
// Research papers underpinning this design:
//  1. Brock, Lakonishok & LeBaron (1992), "Simple Technical Trading Rules
//     and the Stochastic Properties of Stock Returns": most comprehensive
//     early academic study of MA crossover rules using 90 years of DJIA
//     data; crossover rules significantly outperformed cash benchmarks.
//  2. Hurst, Ooi & Pedersen (2014), "A Century of Evidence on Trend-
//     Following Investing": trend-following has been profitable since 1880
//     for nearly all asset classes.
//  3. Zakamulin (2023), "Optimal Trend-Following with Transaction Costs":
//     shows optimal trend-following resembles simple MA crossover under
//     plausible dynamics.
//  4. Manasa & Reddy (2025), "Trend Analysis by Weighted and Exponential
//     Moving Average": comparative study finding combined WMA/EMA approaches
//     yield more robust trading decisions; EMA offers stability.
//  5. Poterba & Summers (1988), "Mean Reversion in Stock Prices: Evidence and
//     Implications": negative autocorrelation at medium horizons; supports
//     dynamic thresholds and volatility-adjusted signal filtering.
//  6. Jegadeesh & Titman (1993), "Returns to Buying Winners and Selling
//     Losers": established momentum as a premier cross-sectional anomaly.
//     Validates trend-following as a persistent market phenomenon.
//  7. Clare et al. (2013), "Trend Following, Stop Losses, and the Frequency
//     of Trading": 10-month MA rule produced highest Sharpe ratio; trend
//     following reduced volatility by a third to a half.
// ============================================================================

define(
    title="Golden Cross — Perfected Edition",
    position="onchart",
    axis=false
)

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

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

// --- ATR Volatility Filter ---
var useAtrFilter = input(
    name="useAtrFilter",
    type="boolean",
    defaultValue=true,
    label="Enable ATR Volatility Filter",
    group="ATR Filter"
)
var atrLen = input(
    name="atrLen",
    type="number",
    defaultValue=14,
    label="ATR Length",
    constraints={min: 5, max: 100, step: 1},
    group="ATR Filter"
)
var atrMult = input(
    name="atrMult",
    type="number",
    defaultValue=1.0,
    label="ATR Filter Multiplier",
    constraints={min: 0.1, max: 5.0, step: 0.1},
    group="ATR Filter"
)

// --- Consolidation Detection ---
var useConsolidation = input(
    name="useConsolidation",
    type="boolean",
    defaultValue=true,
    label="Enable Consolidation Detection",
    group="Consolidation"
)
var consolidationAtrMult = input(
    name="consolidationAtrMult",
    type="number",
    defaultValue=0.5,
    label="Consolidation Threshold (× ATR)",
    constraints={min: 0.05, max: 3.0, step: 0.05},
    group="Consolidation"
)

// --- Volume Confirmation ---
var useVolume = input(
    name="useVolume",
    type="boolean",
    defaultValue=false,
    label="Enable Volume Confirmation",
    group="Volume"
)
var volLookback = input(
    name="volLookback",
    type="number",
    defaultValue=20,
    label="Volume Lookback",
    constraints={min: 5, max: 100, step: 1},
    group="Volume"
)
var volThreshold = input(
    name="volThreshold",
    type="number",
    defaultValue=1.0,
    label="Volume Threshold (× avg)",
    constraints={min: 0.5, max: 5.0, step: 0.1},
    group="Volume"
)

// --- Display ---
var showFastSlow = input(
    name="showFastSlow",
    type="boolean",
    defaultValue=true,
    label="Show Fast & Slow MAs",
    group="Display"
)
var showFill = input(
    name="showFill",
    type="boolean",
    defaultValue=true,
    label="Show MA Regime Fill",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Crossover Shapes",
    group="Display"
)
var showStrength = input(
    name="showStrength",
    type="boolean",
    defaultValue=true,
    label="Show Trend Strength Histogram",
    group="Display"
)
var showLabels = input(
    name="showLabels",
    type="boolean",
    defaultValue=true,
    label="Show Regime Labels",
    group="Display"
)
var showBackground = input(
    name="showBackground",
    type="boolean",
    defaultValue=true,
    label="Show Background Regime Color",
    group="Display"
)
var showDuration = input(
    name="showDuration",
    type="boolean",
    defaultValue=true,
    label="Show Regime Duration Bar Count",
    group="Display"
)

// --- Colors ---
var bullColor = input(
    name="bullColor",
    type="color",
    defaultValue="#26a69a",
    label="Bullish Color",
    group="Colors"
)
var bearColor = input(
    name="bearColor",
    type="color",
    defaultValue="#ef5350",
    label="Bearish Color",
    group="Colors"
)
var neutralColor = input(
    name="neutralColor",
    type="color",
    defaultValue="#9e9e9e",
    label="Neutral/Consolidation Color",
    group="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"
)

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

if (isnan(px[0]) || isnan(hi[0]) || isnan(lo[0]) || isnan(vol[0])) {
    return
}

// -----------------------------------------------------------------------------
// 3. MOVING AVERAGES
// -----------------------------------------------------------------------------
// Fast and slow moving averages with user-selected type (SMA or EMA).
timeseries fastMA = maType == "SMA" ? sma(source=px, period=fastLen) : ema(source=px, period=fastLen)
timeseries slowMA = maType == "SMA" ? sma(source=px, period=slowLen) : ema(source=px, period=slowLen)

// -----------------------------------------------------------------------------
// 4. ATR (WILDER) — TRUE RANGE
// -----------------------------------------------------------------------------
// TR = max(high - low, |high - close[1]|, |low - close[1]|)
// ATR = SMA(TR, atrLen)
// Guard against isnan(close[1]) on the first bar by substituting current close.
timeseries prevClose = isnan(px[1]) ? px : px[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)

// -----------------------------------------------------------------------------
// 5. CROSSOVER DETECTION
// -----------------------------------------------------------------------------
// Manual crossover detection for explicit control and state-machine integration.
var crossUp = fastMA > slowMA && fastMA[1] <= slowMA[1]
var crossDown = fastMA < slowMA && fastMA[1] >= slowMA[1]

// -----------------------------------------------------------------------------
// 6. REGIME STATE MACHINE (static)
// -----------------------------------------------------------------------------
// Regime tracking: 1 = Golden Cross (bullish), -1 = Death Cross (bearish), 0 = Neutral/Consolidation
// Static variables persist across bars for true stateful regime tracking.
static regime = 0
static regimeBarCount = 0
static lastCrossBar = 0
static barCount = 0

if (!isLiveUpdate) {
    barCount = barCount + 1

    // Update regime on confirmed crossovers
    if (crossUp) {
        regime = 1
        lastCrossBar = barCount
        regimeBarCount = 0
    } else if (crossDown) {
        regime = -1
        lastCrossBar = barCount
        regimeBarCount = 0
    }

    // Increment regime duration
    regimeBarCount = regimeBarCount + 1
}

// Current bar regime (derived from MA position, independent of state machine)
var currentRegime = fastMA > slowMA ? 1 : -1

// Consolidation detection: when MA gap is smaller than a fraction of ATR
var isConsolidation = useConsolidation && (math.abs(fastMA - slowMA) < consolidationAtrMult * atr)

// Effective regime color: consolidation overrides trend
var regimeColor = isConsolidation ? neutralColor : (currentRegime == 1 ? bullColor : bearColor)
var regimeLabel = isConsolidation ? "CONSOLIDATION" : (currentRegime == 1 ? "GOLDEN CROSS" : "DEATH CROSS")
var regimeTextColor = isConsolidation ? neutralColor : (currentRegime == 1 ? bullColor : bearColor)

// -----------------------------------------------------------------------------
// 7. TREND STRENGTH
// -----------------------------------------------------------------------------
// Normalized gap between fast and slow MAs divided by ATR.
// Positive = bullish strength, negative = bearish strength, near 0 = consolidation.
timeseries maGap = fastMA - slowMA
timeseries strength = atr > 0 ? maGap / atr : 0

// Strength regime classification
var strengthBull = strength > 1.0
var strengthBear = strength < -1.0
var strengthNeutral = !strengthBull && !strengthBear

// -----------------------------------------------------------------------------
// 8. ATR VOLATILITY FILTER
// -----------------------------------------------------------------------------
// Suppress crossover signals when ATR is low relative to its own rolling average
// (whipsaw zone). This filters out noise during low-volatility chop.
timeseries atrAvg = sma(atr, atrLen)
var atrFilter = useAtrFilter ? (atr > atrMult * atrAvg * 0.5) : true

// -----------------------------------------------------------------------------
// 9. VOLUME CONFIRMATION
// -----------------------------------------------------------------------------
// Optional volume spike confirmation: crossover must occur on above-average volume.
timeseries volAvg = sma(vol, volLookback)
var volumeConfirmed = useVolume ? (vol > volThreshold * volAvg) : true

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

// --- Background Regime Color ---
if (showBackground) {
    var bgColor = isConsolidation ? transparency(neutralColor, 10) : (currentRegime == 1 ? transparency(bullColor, 10) : transparency(bearColor, 10))
    // Background fill via hline-like overlay (plotLine at top/bottom with fill)
    plotLine(
        value=[hi, lo],
        width=0,
        colors=[bgColor, bgColor],
        fill=bgColor,
        label=["BG", "BG"],
        desc=["Background regime color", "Background regime color"]
    )
}

// --- Fast & Slow MA Lines ---
if (showFastSlow) {
    plotLine(
        value=fastMA,
        width=2,
        colors=[fastColor],
        label=["Fast MA"],
        desc=["Fast moving average (" + fastLen + " " + maType + ")"]
    )
    plotLine(
        value=slowMA,
        width=2,
        colors=[slowColor],
        label=["Slow MA"],
        desc=["Slow moving average (" + slowLen + " " + maType + ")"]
    )
}

// --- MA Regime Fill (fast vs slow) ---
if (showFill) {
    var fillBull = fastMA > slowMA
    plotLine(
        value=[fastMA, slowMA],
        width=1,
        colors=[transparency(bullColor, 25), transparency(bearColor, 25)],
        colorIndex=fillBull ? 0 : 1,
        fill=true,
        label=["Fast MA", "Slow MA"],
        desc=["Fill between fast and slow moving averages", "Regime-colored fill"]
    )
}

// --- Crossover Shape Markers ---
if (showShapes) {
    if (crossUp && atrFilter && volumeConfirmed) {
        plotShape(
            value=lo,
            shape="triangleup",
            colorIndex=bullColor,
            width=3,
            label=["Golden Cross"],
            desc=["Golden Cross: fast MA crossed above slow MA"]
        )
    }
    if (crossDown && atrFilter && volumeConfirmed) {
        plotShape(
            value=hi,
            shape="triangledown",
            colorIndex=bearColor,
            width=3,
            label=["Death Cross"],
            desc=["Death Cross: fast MA crossed below slow MA"]
        )
    }
    // Weak cross markers (filtered by ATR or volume)
    if (crossUp && (!atrFilter || !volumeConfirmed)) {
        plotShape(
            value=lo,
            shape="triangleup",
            colorIndex=neutralColor,
            width=2,
            label=["Weak Golden Cross"],
            desc=["Golden Cross filtered by ATR/volume: low confidence"]
        )
    }
    if (crossDown && (!atrFilter || !volumeConfirmed)) {
        plotShape(
            value=hi,
            shape="triangledown",
            colorIndex=neutralColor,
            width=2,
            label=["Weak Death Cross"],
            desc=["Death Cross filtered by ATR/volume: low confidence"]
        )
    }
}

// --- Trend Strength Histogram ---
if (showStrength) {
    var histBull = strength >= 0
    plotBar(
        value=strength,
        colors=[transparency(bullColor, 60), transparency(bearColor, 60)],
        colorIndex=histBull ? 0 : 1,
        width=1,
        label=["Trend Strength"],
        desc=["Normalized MA gap (fast - slow) / ATR. > 1 = strong, < -1 = strong bear, near 0 = consolidation."]
    )
}

// --- Regime Duration Label ---
if (showDuration && isLastBar) {
    var durationText = regime == 1 ? ("Bullish for " + regimeBarCount + " bars") : (regime == -1 ? ("Bearish for " + regimeBarCount + " bars") : "Neutral")
    plotPriceLabel(
        price=lo,
        text=durationText,
        type="callout",
        color="#ffffff",
        backgroundColor=regimeColor,
        size=9,
        fontWeight=600
    )
}

// --- Regime Price Label (last bar) ---
if (showLabels && isLastBar) {
    plotPriceLabel(
        price=hi,
        text=regimeLabel,
        type="callout",
        color="#ffffff",
        backgroundColor=regimeColor,
        size=10,
        fontWeight=700
    )
}

// -----------------------------------------------------------------------------
// 11. REGIME TABLE (last bar only)
// -----------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = isConsolidation ? "CONSOLIDATION" : (currentRegime == 1 ? "BULLISH" : "BEARISH")
    var regimeTextColor = regimeText == "BULLISH" ? bullColor : (regimeText == "BEARISH" ? bearColor : neutralColor)
    var atrFilterText = useAtrFilter ? (atrFilter ? "ATR: PASS" : "ATR: FILTER") : "ATR: OFF"
    var volText = useVolume ? (volumeConfirmed ? "Vol: CONFIRMED" : "Vol: LOW") : "Vol: OFF"

    plotTable(
        data=[
            ["Golden Cross — Perfected", regimeText],
            ["Fast MA (" + fastLen + ")", fastMA[0]],
            ["Slow MA (" + slowLen + ")", slowMA[0]],
            ["MA Gap", maGap[0]],
            ["Trend Strength", strength[0]],
            ["ATR (" + atrLen + ")", atr[0]],
            ["Regime Bars", regimeBarCount],
            [atrFilterText, volText]
        ],
        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
    )
}