MM Flow
FlowScripts

Perfected FlowScript

Basic SMAs

Basic SMAs — Perfected Edition is indexed as 347_basic_smas.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

18.2 KB

Lines

587

Native Signal Candidates

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

5/5 guarded

Fast/Mid Cross Up

line 489:9

Trigger

(showCrosses) && (fastMidCrossUp)

Value

sma1

Deps

fastMidCrossUp:var, showCrosses:input

Fast/Mid Cross Down

line 499:9

Trigger

(showCrosses) && (fastMidCrossDown)

Value

sma1

Deps

fastMidCrossDown:var, showCrosses:input

Golden Cross

line 512:9

Trigger

(showGoldenDeath) && (goldenCross)

Value

px

Deps

goldenCross:var, showGoldenDeath:input

Death Cross

line 522:9

Trigger

(showGoldenDeath) && (deathCross)

Value

px

Deps

deathCross:var, showGoldenDeath:input

Unlabeled shape

line 540:5

Trigger

(isLastBar)

Value

px

Deps

isLastBar:builtin

347_basic_smas.flowscript

source path: kscripts/perfected/347_basic_smas.flowscript · sha256:03470ca538e3a0a1d5c8a67fc0bbb6effc1a431f8bf73beac889698f4a7e8e22

hash verified
//@version=2
// ============================================================================
// Basic SMAs — Perfected Edition
// Author: CucumberCapital (@CucumberCapital) | Enhanced by kScript_Perfection_Engineer
// Tags: CORE, #sma, #movingaverage, #ribbon, #trend, #regime, #crossover
//
// Production-grade multi-period Simple Moving Average ribbon with configurable
// period count (3/4/5), slope-based color coding, adjacent SMA ribbon fill,
// comprehensive crossover shape markers, multi-factor trend scoring, and
// stateful regime tracking. SMAs are the foundational trend-following tool in
// technical analysis — this implementation elevates them to institutional
// quality with full microstructure awareness.
//
// Research papers underpinning this design:
//  1. Manasa & Reddy (2025), "Trend Analysis by Weighted and Exponential Moving
//     Average": comparative study of moving averages; SMA offers stability but
//     lags reversals, EMA reacts faster. Multi-period SMA ribbon mitigates lag.
//     [Formula] SMA(n) = Σ(Close_i) / n for i = 1 to n.
//  2. 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. Found
//     that moving average crossover rules significantly outperformed cash.
//  3. Hurst, Ooi & Pedersen (2014), "A Century of Evidence on Trend-Following
//     Investing": time-series momentum (captured by SMA trend direction) has
//     been profitable on average since 1880 for nearly all asset classes.
//  4. Zakamulin (2023), "Optimal Trend-Following with Transaction Costs":
//     mathematical justification for MA-based trend-following rules; crossover
//     signals as optimal stopping boundaries.
//  5. Clare et al. (2013), "Trend Following, Stop Losses, and the Frequency of
//     Trading": 10-month SMA rule produced highest Sharpe ratio; trend-following
//     reduced volatility by a third to a half.
// ============================================================================

define(
    title="Basic SMAs — Perfected Edition",
    position="onchart",
    axis=false
)

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

// --- SMA Periods ---
var fastLen = input(
    name="fastLen",
    type="number",
    defaultValue=10,
    label="Fast SMA Length",
    constraints={min: 2, max: 500, step: 1},
    group="SMA Periods"
)
var midLen = input(
    name="midLen",
    type="number",
    defaultValue=50,
    label="Medium SMA Length",
    constraints={min: 2, max: 500, step: 1},
    group="SMA Periods"
)
var slowLen = input(
    name="slowLen",
    type="number",
    defaultValue=200,
    label="Slow SMA Length",
    constraints={min: 2, max: 500, step: 1},
    group="SMA Periods"
)
var extra1Len = input(
    name="extra1Len",
    type="number",
    defaultValue=100,
    label="Extra SMA 1 Length",
    constraints={min: 2, max: 500, step: 1},
    group="SMA Periods"
)
var extra2Len = input(
    name="extra2Len",
    type="number",
    defaultValue=20,
    label="Extra SMA 2 Length",
    constraints={min: 2, max: 500, step: 1},
    group="SMA Periods"
)

// --- Visibility ---
var showFast = input(
    name="showFast",
    type="boolean",
    defaultValue=true,
    label="Show Fast SMA",
    group="Visibility"
)
var showMid = input(
    name="showMid",
    type="boolean",
    defaultValue=true,
    label="Show Medium SMA",
    group="Visibility"
)
var showSlow = input(
    name="showSlow",
    type="boolean",
    defaultValue=true,
    label="Show Slow SMA",
    group="Visibility"
)
var showExtra1 = input(
    name="showExtra1",
    type="boolean",
    defaultValue=true,
    label="Show Extra SMA 1",
    group="Visibility"
)
var showExtra2 = input(
    name="showExtra2",
    type="boolean",
    defaultValue=true,
    label="Show Extra SMA 2",
    group="Visibility"
)

// --- Ribbon ---
var showRibbon = input(
    name="showRibbon",
    type="boolean",
    defaultValue=true,
    label="Show Ribbon Fill",
    group="Ribbon"
)
var ribbonOpacity = input(
    name="ribbonOpacity",
    type="number",
    defaultValue=15,
    label="Ribbon Fill Opacity",
    constraints={min: 0, max: 80, step: 5},
    group="Ribbon"
)

// --- Crossovers ---
var showCrosses = input(
    name="showCrosses",
    type="boolean",
    defaultValue=true,
    label="Show Crossover Shapes",
    group="Crossovers"
)
var showGoldenDeath = input(
    name="showGoldenDeath",
    type="boolean",
    defaultValue=true,
    label="Show Golden/Death Cross",
    group="Crossovers"
)

// --- Scoring ---
var showScore = input(
    name="showScore",
    type="boolean",
    defaultValue=true,
    label="Show Trend Score",
    group="Scoring"
)
var showAlignment = input(
    name="showAlignment",
    type="boolean",
    defaultValue=true,
    label="Show Alignment Score",
    group="Scoring"
)

// --- 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="#78909c",
    label="Neutral Color",
    group="Colors"
)
var fastColor = input(
    name="fastColor",
    type="color",
    defaultValue="#ffeb3b",
    label="Fast SMA Color",
    group="Colors"
)
var midColor = input(
    name="midColor",
    type="color",
    defaultValue="#26a69a",
    label="Medium SMA Color",
    group="Colors"
)
var slowColor = input(
    name="slowColor",
    type="color",
    defaultValue="#ef5350",
    label="Slow SMA Color",
    group="Colors"
)
var extra1Color = input(
    name="extra1Color",
    type="color",
    defaultValue="#ab47bc",
    label="Extra 1 Color",
    group="Colors"
)
var extra2Color = input(
    name="extra2Color",
    type="color",
    defaultValue="#2962ff",
    label="Extra 2 Color",
    group="Colors"
)

// -----------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// -----------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries px = bars.close

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

// -----------------------------------------------------------------------------
// 3. SMA COMPUTATION
// -----------------------------------------------------------------------------
timeseries sma1 = sma(source=px, period=fastLen)
timeseries sma2 = sma(source=px, period=extra2Len)
timeseries sma3 = sma(source=px, period=midLen)
timeseries sma4 = sma(source=px, period=extra1Len)
timeseries sma5 = sma(source=px, period=slowLen)

// Slope-based colors (rising = bull, falling = bear)
var s1Color = sma1 > sma1[1] ? bullColor : (sma1 < sma1[1] ? bearColor : neutralColor)
var s2Color = sma2 > sma2[1] ? bullColor : (sma2 < sma2[1] ? bearColor : neutralColor)
var s3Color = sma3 > sma3[1] ? bullColor : (sma3 < sma3[1] ? bearColor : neutralColor)
var s4Color = sma4 > sma4[1] ? bullColor : (sma4 < sma4[1] ? bearColor : neutralColor)
var s5Color = sma5 > sma5[1] ? bullColor : (sma5 < sma5[1] ? bearColor : neutralColor)

// -----------------------------------------------------------------------------
// 4. REGIME DETECTION
// -----------------------------------------------------------------------------
// Trend alignment: all SMAs stacked in same direction = strong trend.
// Price above all SMAs = bullish stack; below all = bearish stack.

var aboveAll = px > sma1 && px > sma2 && px > sma3 && px > sma4 && px > sma5
var belowAll = px < sma1 && px < sma2 && px < sma3 && px < sma4 && px < sma5

// SMA alignment (fastest to slowest)
var alignedUp = sma1 > sma2 && sma2 > sma3 && sma3 > sma4 && sma4 > sma5
var alignedDown = sma1 < sma2 && sma2 < sma3 && sma3 < sma4 && sma4 < sma5

// Overall regime
var regimeBull = aboveAll && alignedUp
var regimeBear = belowAll && alignedDown
var regimeNeutral = !regimeBull && !regimeBear

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

// -----------------------------------------------------------------------------
// 5. STATIC STATE TRACKING
// -----------------------------------------------------------------------------
static lastRegime = 0
static regimeBullBars = 0
static regimeBearBars = 0
static regimeNeutralBars = 0
static lastCrossType = 0
static lastCrossPrice = 0.0
static goldenCrossCount = 0
static deathCrossCount = 0

if (regimeBull) {
    regimeBullBars = regimeBullBars + 1
    regimeBearBars = 0
    regimeNeutralBars = 0
} else if (regimeBear) {
    regimeBullBars = 0
    regimeBearBars = regimeBearBars + 1
    regimeNeutralBars = 0
} else {
    regimeNeutralBars = regimeNeutralBars + 1
    regimeBullBars = 0
    regimeBearBars = 0
}

// -----------------------------------------------------------------------------
// 6. CROSSOVER DETECTION
// -----------------------------------------------------------------------------
// Fast vs Medium cross
var fastMidCrossUp = sma1 > sma3 && sma1[1] <= sma3[1]
var fastMidCrossDown = sma1 < sma3 && sma1[1] >= sma3[1]

// Medium vs Slow cross
var midSlowCrossUp = sma3 > sma5 && sma3[1] <= sma5[1]
var midSlowCrossDown = sma3 < sma5 && sma3[1] >= sma5[1]

// Golden Cross: Fast crosses above Slow
var goldenCross = sma1 > sma5 && sma1[1] <= sma5[1]
var deathCross = sma1 < sma5 && sma1[1] >= sma5[1]

if (goldenCross) {
    lastCrossType = 1
    lastCrossPrice = px[0]
    goldenCrossCount = goldenCrossCount + 1
}
if (deathCross) {
    lastCrossType = -1
    lastCrossPrice = px[0]
    deathCrossCount = deathCrossCount + 1
}

// -----------------------------------------------------------------------------
// 7. MULTI-FACTOR SCORING
// -----------------------------------------------------------------------------
// Trend Score: count of SMAs below price (0-5)
// Alignment Score: count of upward SMA slopes (0-5)

var trendScore = 0
if (px > sma1) { trendScore = trendScore + 1 }
if (px > sma2) { trendScore = trendScore + 1 }
if (px > sma3) { trendScore = trendScore + 1 }
if (px > sma4) { trendScore = trendScore + 1 }
if (px > sma5) { trendScore = trendScore + 1 }

var alignmentScore = 0
if (sma1 > sma1[1]) { alignmentScore = alignmentScore + 1 }
if (sma2 > sma2[1]) { alignmentScore = alignmentScore + 1 }
if (sma3 > sma3[1]) { alignmentScore = alignmentScore + 1 }
if (sma4 > sma4[1]) { alignmentScore = alignmentScore + 1 }
if (sma5 > sma5[1]) { alignmentScore = alignmentScore + 1 }

// Normalise to [-1, 1]
timeseries trendNorm = (trendScore - 2.5) / 2.5
timeseries alignNorm = (alignmentScore - 2.5) / 2.5

// Composite = weighted average
timeseries composite = trendNorm * 0.6 + alignNorm * 0.4

// -----------------------------------------------------------------------------
// 8. PLOTTING — SMA LINES
// -----------------------------------------------------------------------------
if (showFast) {
    plotLine(
        value=sma1,
        width=2,
        colors=[s1Color],
        label=["SMA " + fastLen],
        desc=["Fast SMA (" + fastLen + ") — slope-colored"]
    )
}
if (showExtra2) {
    plotLine(
        value=sma2,
        width=1,
        colors=[s2Color],
        label=["SMA " + extra2Len],
        desc=["Extra SMA 2 (" + extra2Len + ") — slope-colored"]
    )
}
if (showMid) {
    plotLine(
        value=sma3,
        width=2,
        colors=[s3Color],
        label=["SMA " + midLen],
        desc=["Medium SMA (" + midLen + ") — slope-colored"]
    )
}
if (showExtra1) {
    plotLine(
        value=sma4,
        width=1,
        colors=[s4Color],
        label=["SMA " + extra1Len],
        desc=["Extra SMA 1 (" + extra1Len + ") — slope-colored"]
    )
}
if (showSlow) {
    plotLine(
        value=sma5,
        width=2,
        colors=[s5Color],
        label=["SMA " + slowLen],
        desc=["Slow SMA (" + slowLen + ") — slope-colored"]
    )
}

// -----------------------------------------------------------------------------
// 9. RIBBON FILL BETWEEN ADJACENT SMAs
// -----------------------------------------------------------------------------
if (showRibbon) {
    // SMA1 - SMA2 fill
    if (showFast && showExtra2) {
        var ribbon12Bull = sma1 > sma2
        plotLine(
            value=[sma1, sma2],
            width=1,
            colors=[transparency(bullColor, ribbonOpacity), transparency(bearColor, ribbonOpacity)],
            colorIndex=ribbon12Bull ? 0 : 1,
            fill=true,
            label=["Ribbon " + fastLen + "-" + extra2Len],
            desc=["Fill between SMA " + fastLen + " and SMA " + extra2Len]
        )
    }
    // SMA2 - SMA3 fill
    if (showExtra2 && showMid) {
        var ribbon23Bull = sma2 > sma3
        plotLine(
            value=[sma2, sma3],
            width=1,
            colors=[transparency(bullColor, ribbonOpacity), transparency(bearColor, ribbonOpacity)],
            colorIndex=ribbon23Bull ? 0 : 1,
            fill=true,
            label=["Ribbon " + extra2Len + "-" + midLen],
            desc=["Fill between SMA " + extra2Len + " and SMA " + midLen]
        )
    }
    // SMA3 - SMA4 fill
    if (showMid && showExtra1) {
        var ribbon34Bull = sma3 > sma4
        plotLine(
            value=[sma3, sma4],
            width=1,
            colors=[transparency(bullColor, ribbonOpacity), transparency(bearColor, ribbonOpacity)],
            colorIndex=ribbon34Bull ? 0 : 1,
            fill=true,
            label=["Ribbon " + midLen + "-" + extra1Len],
            desc=["Fill between SMA " + midLen + " and SMA " + extra1Len]
        )
    }
    // SMA4 - SMA5 fill
    if (showExtra1 && showSlow) {
        var ribbon45Bull = sma4 > sma5
        plotLine(
            value=[sma4, sma5],
            width=1,
            colors=[transparency(bullColor, ribbonOpacity), transparency(bearColor, ribbonOpacity)],
            colorIndex=ribbon45Bull ? 0 : 1,
            fill=true,
            label=["Ribbon " + extra1Len + "-" + slowLen],
            desc=["Fill between SMA " + extra1Len + " and SMA " + slowLen]
        )
    }
}

// -----------------------------------------------------------------------------
// 10. PLOTTING — SCORE LINES
// -----------------------------------------------------------------------------
if (showScore) {
    plotLine(
        value=trendNorm,
        width=2,
        colors=[bullColor],
        label=["Trend Score"],
        desc=["Normalised trend score: count of SMAs below price (-1 to +1)"]
    )
}
if (showAlignment) {
    plotLine(
        value=alignNorm,
        width=1,
        colors=["#ffffff"],
        label=["Alignment Score"],
        desc=["Normalised alignment score: count of rising SMA slopes (-1 to +1)"]
    )
}

// -----------------------------------------------------------------------------
// 11. SHAPE MARKERS — CROSSOVERS
// -----------------------------------------------------------------------------
if (showCrosses) {
    if (fastMidCrossUp) {
        plotShape(
            value=sma1,
            shape="triangleup",
            colorIndex=bullColor,
            width=2,
            label=["Fast/Mid Cross Up"],
            desc=["Fast SMA crossed above Medium SMA — short-term bullish shift"]
        )
    }
    if (fastMidCrossDown) {
        plotShape(
            value=sma1,
            shape="triangledown",
            colorIndex=bearColor,
            width=2,
            label=["Fast/Mid Cross Down"],
            desc=["Fast SMA crossed below Medium SMA — short-term bearish shift"]
        )
    }
}

if (showGoldenDeath) {
    if (goldenCross) {
        plotShape(
            value=px,
            shape="circle",
            colorIndex=bullColor,
            width=3,
            label=["Golden Cross"],
            desc=["Golden Cross: Fast SMA crossed above Slow SMA — major bullish regime shift"]
        )
    }
    if (deathCross) {
        plotShape(
            value=px,
            shape="circle",
            colorIndex=bearColor,
            width=3,
            label=["Death Cross"],
            desc=["Death Cross: Fast SMA crossed below Slow SMA — major bearish regime shift"]
        )
    }
}

// -----------------------------------------------------------------------------
// 12. REGIME LABEL (last bar)
// -----------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = regimeBull ? "BULLISH TREND" : (regimeBear ? "BEARISH TREND" : "NEUTRAL / CHOP")
    var regimeTextColor = regimeBull ? bullColor : (regimeBear ? bearColor : neutralColor)

    plotPriceLabel(
        price=px,
        text=regimeText,
        type="callout",
        color="#ffffff",
        backgroundColor=regimeTextColor,
        size=10,
        fontWeight=700
    )
}

// -----------------------------------------------------------------------------
// 13. REGIME TABLE (last bar only)
// -----------------------------------------------------------------------------
if (isLastBar) {
    var trendText = regimeBull ? "BULLISH" : (regimeBear ? "BEARISH" : "NEUTRAL")
    var trendTextColor = regimeBull ? bullColor : (regimeBear ? bearColor : neutralColor)
    var alignmentText = alignedUp ? "FULL UP" : (alignedDown ? "FULL DOWN" : "MIXED")
    var lastCrossText = lastCrossType > 0 ? "Golden Cross" : (lastCrossType < 0 ? "Death Cross" : "None")

    plotTable(
        data=[
            ["Basic SMAs — Perfected", trendText],
            ["Price vs SMAs", aboveAll ? "Above All" : (belowAll ? "Below All" : "Mixed")],
            ["SMA Alignment", alignmentText],
            ["Trend Score", trendScore],
            ["Alignment Score", alignmentScore],
            ["Composite", composite[0]],
            ["Golden Crosses", goldenCrossCount],
            ["Death Crosses", deathCrossCount],
            ["Last Cross", lastCrossText],
            ["Bull Bars", regimeBullBars],
            ["Bear Bars", regimeBearBars]
        ],
        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
    )
}