MM Flow
FlowScripts

Perfected FlowScript

MA with Color

MA with Color V2 is indexed as 199_ma_with_color.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.6 KB

Lines

339

Native Signal Candidates

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

4/4 guarded

Golden Cross

line 266:9

Trigger

(showShapes) && (goldenCross)

Value

fastMA

Deps

goldenCross:var, showShapes:input

Death Cross

line 276:9

Trigger

(showShapes) && (deathCross)

Value

fastMA

Deps

deathCross:var, showShapes:input

Fast>Med

line 286:9

Trigger

(showShapes) && (fastMedCrossUp)

Value

fastMA

Deps

fastMedCrossUp:var, showShapes:input

Fast<Med

line 296:9

Trigger

(showShapes) && (fastMedCrossDn)

Value

fastMA

Deps

fastMedCrossDn:var, showShapes:input

199_ma_with_color.flowscript

source path: kscripts/perfected/199_ma_with_color.flowscript · sha256:1eff8d2e3973baa5f29c2ae3d2b72bef5fd1f04ecf02a5dc89c02c1ff5db94b9

hash verified
//@version=2
// ============================================================================
// MA with Color V2 — Production-Quality Multi-MA Regime Indicator
// Author: BackQuant  |  Perfected by: kScript Perfection Engineer
// Tags: CORE, #ma, #trend, #regime, #crossover, #ribbon
//
// Multi-moving-average regime-colored indicator with fill, crossover shapes,
// and static session tracking. Supports SMA, EMA, HMA, DEMA types.
//
// FORMULA FOUNDATION:
// 1. Moving Average Regime: Price above MA = bullish (rising), below = bearish
//    (falling). Color coding communicates trend direction at a glance.
// 2. Multiple MAs: Fast / medium / slow triad for crossover confirmation per
//    Wilder (1978) and Brock, Lakonishok & LeBaron (1992) MA profitability.
// 3. Hull Moving Average (HMA): HMA = WMA(√n) of [2×WMA(n/2) − WMA(n)] per
//    Hull (2005). Nearly eliminates lag while improving smoothness.
// 4. DEMA: DEMA = 2×EMA − EMA(EMA) per Mulloy (1994). Lag reduction via
//    double-exponential smoothing.
// 5. MA Fill: Ribbon between fast and slow MAs visualizes trend strength;
//    widening = strengthening, narrowing = weakening / convergence.
// 6. Crossover Signals: Golden cross (fast above slow) and death cross
//    (fast below slow) are canonical trend-following entry signals.
//
// RESEARCH BASIS:
//  • Wilder, J.W. (1978), *New Concepts in Technical Trading Systems*. SMA/EMA
//    foundations; ATR-based volatility measurement. Original RSI/ADX source.
//  • Brock, Lakonishok & LeBaron (1992), "Simple Technical Trading Rules and
//    the Stochastic Properties of Stock Returns", J. Finance. MA crossovers
//    significantly outperform buy-and-hold over 90 years of DJIA data.
//  • Hull, A. (2005), "The Hull Moving Average". Lag-reduction technique.
//  • Mulloy, P. (1994), "Smoothing Data With Faster Moving Averages", TASC
//    Jan 1994. DEMA/TEMA lag-reduction methodology.
//  • Jegadeesh & Titman (1993), "Returns to Buying Winners and Selling Losers",
//    J. Finance 48(1). Momentum anomaly validates trend-following.
//  • Zakamulin, V. (2023), "Optimal Trend-Following with Transaction Costs",
//    IRFA. Mathematical justification for MA crossover rules.
//  • Hurst, Ooi & Pedersen (2014), "A Century of Evidence on Trend-Following
//    Investing", AQR. Trend-following profitable since 1880 across asset classes.
// ============================================================================

define(
    title="MA with Color V2",
    position="onchart",
    axis=false
)

// ------------------------------------------------------------------------------
// User Inputs — grouped and constrained per production spec
// ------------------------------------------------------------------------------

// --- Fast MA ---
var fastType = input(name="fastType", type="select", defaultValue="EMA", label="Fast MA Type", options=["SMA", "EMA", "HMA", "DEMA"], group="Fast MA")
var fastLen = input(name="fastLen", type="number", defaultValue=9, label="Fast MA Length", constraints={min: 2, max: 100, step: 1}, group="Fast MA")

// --- Medium MA ---
var medType = input(name="medType", type="select", defaultValue="EMA", label="Medium MA Type", options=["SMA", "EMA", "HMA", "DEMA"], group="Medium MA")
var medLen = input(name="medLen", type="number", defaultValue=21, label="Medium MA Length", constraints={min: 2, max: 200, step: 1}, group="Medium MA")

// --- Slow MA ---
var slowType = input(name="slowType", type="select", defaultValue="SMA", label="Slow MA Type", options=["SMA", "EMA", "HMA", "DEMA"], group="Slow MA")
var slowLen = input(name="slowLen", type="number", defaultValue=50, label="Slow MA Length", constraints={min: 2, max: 300, step: 1}, group="Slow MA")

// --- Source ---
var srcType = input(name="srcType", type="select", defaultValue="close", label="Source", options=["close", "open", "high", "low", "hl2", "hlc3", "ohlc4"], group="Source")

// --- Display ---
var showFast = input(name="showFast", type="boolean", defaultValue=true, label="Show Fast MA", group="Display")
var showMed = input(name="showMed", type="boolean", defaultValue=true, label="Show Medium MA", group="Display")
var showSlow = input(name="showSlow", type="boolean", defaultValue=true, label="Show Slow MA", group="Display")
var showRibbon = input(name="showRibbon", type="boolean", defaultValue=true, label="Show Fast/Slow Ribbon Fill", group="Display")
var showMedFill = input(name="showMedFill", type="boolean", defaultValue=true, label="Show Fast/Medium Fill", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Crossover Shapes", group="Display")
var showTable = input(name="showTable", type="boolean", defaultValue=true, label="Show Summary Table", 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 Color", group="Colors")
var slowColor = input(name="slowColor", type="color", defaultValue="#ffca28", label="Slow MA Color", group="Colors")

// ------------------------------------------------------------------------------
// Data Sources & NaN Guard
// ------------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries px = bars.close

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

// Source selection
timeseries src = srcType == "close" ? bars.close : srcType == "open" ? bars.open : srcType == "high" ? bars.high : srcType == "low" ? bars.low : srcType == "hl2" ? (bars.high + bars.low) / 2 : srcType == "hlc3" ? (bars.high + bars.low + bars.close) / 3 : (bars.high + bars.low + bars.close + bars.open) / 4

// ------------------------------------------------------------------------------
// MA Helper Functions
// ------------------------------------------------------------------------------

// Hull Moving Average (Hull 2005)
// HMA = WMA(√n) of [2×WMA(n/2) − WMA(n)]
function hma(series, period) {
    var half = math.max(1, math.floor(period / 2))
    var sqrtP = math.max(1, math.floor(math.sqrt(period)))
    var wma1 = wma(source=series, period=half)
    var wma2 = wma(source=series, period=period)
    var raw = 2 * wma1 - wma2
    return wma(source=raw, period=sqrtP)
}

// DEMA (Mulloy 1994)
// DEMA = 2×EMA − EMA(EMA)
function dema(series, period) {
    var e1 = ema(source=series, period=period)
    var e2 = ema(source=e1, period=period)
    return 2 * e1 - e2
}

// Generic MA selector
function ma(series, type, period) {
    if (type == "SMA") {
        return sma(source=series, period=period)
    } else if (type == "EMA") {
        return ema(source=series, period=period)
    } else if (type == "HMA") {
        return hma(series, period)
    } else if (type == "DEMA") {
        return dema(series, period)
    }
    return sma(source=series, period=period)
}

// ------------------------------------------------------------------------------
// Multi-MA Computation
// ------------------------------------------------------------------------------
timeseries fastMA = ma(src, fastType, fastLen)
timeseries medMA = ma(src, medType, medLen)
timeseries slowMA = ma(src, slowType, slowLen)

// Regime detection: bull = fast > med > slow, bear = fast < med < slow, else neutral
var regimeBull = fastMA >= medMA && medMA >= slowMA
var regimeBear = fastMA <= medMA && medMA <= slowMA
var regimeNeutral = !regimeBull && !regimeBear

// Color by regime
var fastColor = regimeBull ? bullColor : (regimeBear ? bearColor : neutralColor)
var medColor = regimeBull ? opacity(bullColor, 70) : (regimeBear ? opacity(bearColor, 70) : neutralColor)

// Rising / falling for individual MA color variants
var fastRising = fastMA >= fastMA[1]
var medRising = medMA >= medMA[1]
var slowRising = slowMA >= slowMA[1]

// ------------------------------------------------------------------------------
// Crossover Detection
// ------------------------------------------------------------------------------
var goldenCross = fastMA > slowMA && !isnan(fastMA[1]) && fastMA[1] <= slowMA[1]
var deathCross = fastMA < slowMA && !isnan(fastMA[1]) && fastMA[1] >= slowMA[1]
var fastMedCrossUp = fastMA > medMA && !isnan(fastMA[1]) && fastMA[1] <= medMA[1]
var fastMedCrossDn = fastMA < medMA && !isnan(fastMA[1]) && fastMA[1] >= medMA[1]

// ------------------------------------------------------------------------------
// Static State Tracking (Session-level persistence)
// ------------------------------------------------------------------------------
static lastBarIndex = 0
static goldenCrossCount = 0
static deathCrossCount = 0
static sessionHighPrice = 0.0
static sessionLowPrice = 999999999.0
static bullBarCount = 0
static bearBarCount = 0
static neutralBarCount = 0

var currentBarIndex = bar_index[0]

if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
    lastBarIndex = currentBarIndex

    if (px[0] > sessionHighPrice) {
        sessionHighPrice = px[0]
    }
    if (px[0] < sessionLowPrice) {
        sessionLowPrice = px[0]
    }
    if (goldenCross) {
        goldenCrossCount = goldenCrossCount + 1
    }
    if (deathCross) {
        deathCrossCount = deathCrossCount + 1
    }
    if (regimeBull) {
        bullBarCount = bullBarCount + 1
    } else if (regimeBear) {
        bearBarCount = bearBarCount + 1
    } else {
        neutralBarCount = neutralBarCount + 1
    }
}

// ------------------------------------------------------------------------------
// Plots — Multi-MA with Fill, Regime Color, and Crossover Shapes
// ------------------------------------------------------------------------------

// --- Fast/Slow Ribbon Fill ---
if (showRibbon) {
    var ribbonBull = fastMA >= slowMA
    plotLine(
        value=[fastMA, slowMA],
        width=1,
        colors=[opacity(bullColor, 30), opacity(bearColor, 30)],
        colorIndex=ribbonBull ? 0 : 1,
        fill=true,
        label=["Fast MA", "Slow MA"],
        desc=["Fast MA ribbon edge", "Slow MA ribbon edge — fill color indicates trend alignment"]
    )
}

// --- Fast/Medium Fill ---
if (showMedFill) {
    var medFillBull = fastMA >= medMA
    plotLine(
        value=[fastMA, medMA],
        width=1,
        colors=[opacity(bullColor, 20), opacity(bearColor, 20)],
        colorIndex=medFillBull ? 0 : 1,
        fill=true,
        label=["Fast MA", "Medium MA"],
        desc=["Fast/Medium MA fill — convergence/divergence signal"]
    )
}

// --- Fast MA (regime-colored) ---
if (showFast) {
    plotLine(
        value=fastMA,
        width=2,
        colors=[fastColor],
        label=["Fast MA"],
        desc=["Fast MA (" + fastType + " " + fastLen + ") — regime-colored: green=bull, red=bear, grey=neutral"]
    )
}

// --- Medium MA (regime-colored, slightly dimmed) ---
if (showMed) {
    plotLine(
        value=medMA,
        width=2,
        colors=[medColor],
        label=["Medium MA"],
        desc=["Medium MA (" + medType + " " + medLen + ") — trend confirmation layer"]
    )
}

// --- Slow MA (fixed color, structural anchor) ---
if (showSlow) {
    plotLine(
        value=slowMA,
        width=2,
        colors=[slowColor],
        label=["Slow MA"],
        desc=["Slow MA (" + slowType + " " + slowLen + ") — structural trend anchor"]
    )
}

// --- Crossover Shapes ---
if (showShapes) {
    if (goldenCross) {
        plotShape(
            value=fastMA,
            shape="triangleup",
            color=bullColor,
            width=3,
            label=["Golden Cross"],
            desc=["Fast MA crossed above Slow MA — bullish trend signal (Brock et al. 1992)"]
        )
    }
    if (deathCross) {
        plotShape(
            value=fastMA,
            shape="triangledown",
            color=bearColor,
            width=3,
            label=["Death Cross"],
            desc=["Fast MA crossed below Slow MA — bearish trend signal"]
        )
    }
    if (fastMedCrossUp) {
        plotShape(
            value=fastMA,
            shape="circle",
            color=opacity(bullColor, 70),
            width=2,
            label=["Fast>Med"],
            desc=["Fast MA crossed above Medium MA — early momentum confirmation"]
        )
    }
    if (fastMedCrossDn) {
        plotShape(
            value=fastMA,
            shape="circle",
            color=opacity(bearColor, 70),
            width=2,
            label=["Fast<Med"],
            desc=["Fast MA crossed below Medium MA — early momentum loss"]
        )
    }
}

// ------------------------------------------------------------------------------
// Summary Table (last bar only)
// ------------------------------------------------------------------------------
if (showTable && isLastBar) {
    var regimeText = regimeBull ? "BULLISH" : (regimeBear ? "BEARISH" : "NEUTRAL")
    var regimeTextColor = regimeBull ? bullColor : (regimeBear ? bearColor : neutralColor)

    plotTable(
        data=[
            ["MA with Color V2", regimeText],
            ["Fast MA", fastMA[0]],
            ["Medium MA", medMA[0]],
            ["Slow MA", slowMA[0]],
            ["Golden Crosses", goldenCrossCount],
            ["Death Crosses", deathCrossCount],
            ["Bull Bars", bullBarCount],
            ["Bear Bars", bearBarCount],
            ["Neutral Bars", neutralBarCount]
        ],
        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
    )
}