MM Flow
FlowScripts

Perfected FlowScript

Weighted Moving Average

WMA Ribbon Pro is indexed as 170_weighted_moving_average.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

14.3 KB

Lines

463

Native Signal Candidates

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

6/6 guarded

Price Cross Up

line 366:9

Trigger

(showShapes) && (priceCrossUp)

Value

wma1

Deps

priceCrossUp:var, showShapes:input

Price Cross Down

line 376:9

Trigger

(showShapes) && (priceCrossDown)

Value

wma1

Deps

priceCrossDown:var, showShapes:input

Ribbon Bull

line 386:9

Trigger

(showShapes) && (ribbonCrossUp)

Value

wma5

Deps

ribbonCrossUp:var, showShapes:input

Ribbon Bear

line 396:9

Trigger

(showShapes) && (ribbonCrossDown)

Value

wma5

Deps

ribbonCrossDown:var, showShapes:input

WMA1>2

line 406:9

Trigger

(showShapes) && (cross12Up)

Value

wma2

Deps

cross12Up:var, showShapes:input

WMA1<2

line 416:9

Trigger

(showShapes) && (cross12Down)

Value

wma2

Deps

cross12Down:var, showShapes:input

170_weighted_moving_average.flowscript

source path: kscripts/perfected/170_weighted_moving_average.flowscript · sha256:ff33ac2c28497837c4290ddd126b6e1d1254a4a6796152fa726dae7172722d26

hash verified
//@version=2
// ============================================================================
// Weighted Moving Average Ribbon Pro — Perfected Edition
// Author: BackQuant (@BackQuant) | Enhanced by kScript Perfection Engineer
// Tags: CORE, #wma, #movingaverage, #ribbon, #trend, #regime
//
// Production-quality academically-grounded Weighted Moving Average ribbon
// with multiple WMA lines, ribbon fill, price-regime color coding, crossover
// shape markers, and session-level static tracking.
//
// FORMULA FOUNDATION:
// 1. WMA = Σ(w_i × Price_i) / Σw_i where w_i increases linearly for recent
//    periods (Manasa & Reddy 2025).
// 2. Hull Moving Average: HMA = WMA(√n) of [2×WMA(n/2) − WMA(n)] (Hull 2005).
//    WMA is the foundational building block enabling lag-reduction techniques.
// 3. Ribbon Regime Detection: price above all WMAs = strong uptrend;
//    price below all WMAs = strong downtrend; mixed = transition/chop.
// 4. Guppy Multiple Moving Average (GMMA) concept: short-term cluster
//    (traders) vs long-term cluster (investors) for trend participation
//    assessment (Guppy 1990s–2000s).
//
// RESEARCH BASIS:
//  • Manasa & Reddy (2025), "Trend Analysis by Weighted and Exponential Moving
//    Average": WMA responds faster to recent price changes than SMA/EMA of same
//    length due to linear weighting; most recent price has highest weight.
//  • Hull (2005), "The Hull Moving Average": HMA nearly eliminates lag while
//    preserving smoothness. WMA is the core component enabling this.
//  • Guppy (1990s–2000s), "Guppy Multiple Moving Average (GMMA)": uses two
//    clusters of EMAs (short-term 3–15, long-term 30–60) representing trader
//    and investor sentiment. Ribbon separation = trend strength; compression =
//    transition. This script adapts the GMMA concept to WMA.
//  • Brock, Lakonishok & LeBaron (1992), "Simple Technical Trading Rules":
//    MA crossovers significantly outperformed benchmarks on 90 years of DJIA.
//  • Hurst, Ooi & Pedersen (2014), "A Century of Evidence on Trend-Following":
//    time-series momentum profitable since 1880 across nearly all asset classes.
// ============================================================================

define(
    title="WMA Ribbon Pro",
    position="onchart",
    axis=false
)

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

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

// --- Ribbon Lengths ---
var len1 = input(
    name="len1",
    type="number",
    defaultValue=10,
    label="WMA Length 1 (Fast)",
    constraints={min: 2, max: 200, step: 1},
    group="Ribbon Lengths"
)
var len2 = input(
    name="len2",
    type="number",
    defaultValue=20,
    label="WMA Length 2",
    constraints={min: 2, max: 200, step: 1},
    group="Ribbon Lengths"
)
var len3 = input(
    name="len3",
    type="number",
    defaultValue=30,
    label="WMA Length 3",
    constraints={min: 2, max: 200, step: 1},
    group="Ribbon Lengths"
)
var len4 = input(
    name="len4",
    type="number",
    defaultValue=50,
    label="WMA Length 4",
    constraints={min: 2, max: 200, step: 1},
    group="Ribbon Lengths"
)
var len5 = input(
    name="len5",
    type="number",
    defaultValue=100,
    label="WMA Length 5 (Slow)",
    constraints={min: 2, max: 300, step: 1},
    group="Ribbon Lengths"
)

// --- Display ---
var showRibbon = input(
    name="showRibbon",
    type="boolean",
    defaultValue=true,
    label="Show WMA Ribbon",
    group="Display"
)
var showRibbonFill = input(
    name="showRibbonFill",
    type="boolean",
    defaultValue=true,
    label="Show Ribbon Fill",
    group="Display"
)
var showPriceFill = input(
    name="showPriceFill",
    type="boolean",
    defaultValue=true,
    label="Show Price vs WMA Fill",
    group="Display"
)
var showSource = input(
    name="showSource",
    type="boolean",
    defaultValue=false,
    label="Show Source Line",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Crossover Shapes",
    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 srcColor = input(
    name="srcColor",
    type="color",
    defaultValue="#e2e8f0",
    label="Source Color",
    group="Colors"
)

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

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

// Source selection
timeseries source = (src == "close") ? px
    : (src == "open") ? bars.open
    : (src == "high") ? bars.high
    : (src == "low") ? bars.low
    : (src == "hl2") ? (bars.high + bars.low) / 2.0
    : (bars.high + bars.low + bars.close) / 3.0

// -----------------------------------------------------------------------------
// 3. WMA RIBBON COMPUTATION
// -----------------------------------------------------------------------------
// Linearly weighted moving averages with progressive lengths.
// WMA = Σ(w_i × Price_i) / Σw_i where w_i increases linearly.
// Recent prices receive progressively higher weights.

timeseries wma1 = wma(source, len1)
timeseries wma2 = wma(source, len2)
timeseries wma3 = wma(source, len3)
timeseries wma4 = wma(source, len4)
timeseries wma5 = wma(source, len5)

// Ribbon average (center of mass)
timeseries ribbonAvg = (wma1 + wma2 + wma3 + wma4 + wma5) / 5.0

// -----------------------------------------------------------------------------
// 4. REGIME DETECTION
// -----------------------------------------------------------------------------
// Strong Bull: price > all WMAs (all WMAs aligned below price)
// Strong Bear: price < all WMAs (all WMAs aligned above price)
// Mixed/Neutral: price between WMAs (transition or chop)
//
// Also tracks ribbon slope: rising = bullish momentum; falling = bearish.

var allAbove = source > wma1 && source > wma2 && source > wma3 && source > wma4 && source > wma5
var allBelow = source < wma1 && source < wma2 && source < wma3 && source < wma4 && source < wma5
var ribbonBull = allAbove
var ribbonBear = allBelow
var ribbonNeutral = !ribbonBull && !ribbonBear

var regimeColor = ribbonBull ? bullColor : (ribbonBear ? bearColor : neutralColor)

// Ribbon spread (dispersion between fast and slow WMAs)
var ribbonSpread = wma1 - wma5
var spreadExpanding = ribbonSpread > ribbonSpread[1]

// -----------------------------------------------------------------------------
// 5. STATIC STATE TRACKING
// -----------------------------------------------------------------------------
// Tracks crossovers, regime transitions, and session extremes.

static lastRegime = 0
static regimeChangeCount = 0
static priceWmaCrossCount = 0
static ribbonCompressCount = 0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

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

    var currentRegime = ribbonBull ? 1 : (ribbonBear ? -1 : 0)
    if (lastRegime != currentRegime) {
        lastRegime = currentRegime
        regimeChangeCount = regimeChangeCount + 1
    }

    // Count ribbon compression events (spread narrowing)
    if (!isnan(ribbonSpread[1]) && ribbonSpread < ribbonSpread[1] * 0.7) {
        ribbonCompressCount = ribbonCompressCount + 1
    }

    // Count price/WMA crossovers
    var priceAboveWma1 = source > wma1
    var priceAboveWma1Prev = source[1] > wma1[1]
    if (priceAboveWma1 != priceAboveWma1Prev) {
        priceWmaCrossCount = priceWmaCrossCount + 1
    }
}

// -----------------------------------------------------------------------------
// 6. ALERT CONDITIONS
// -----------------------------------------------------------------------------
// Price crosses the fastest WMA (primary trend signal)
var priceCrossUp = source > wma1 && source[1] <= wma1[1]
var priceCrossDown = source < wma1 && source[1] >= wma1[1]

// WMA crossovers (fastest crosses slowest — ribbon regime shift)
var ribbonCrossUp = wma1 > wma5 && wma1[1] <= wma5[1]
var ribbonCrossDown = wma1 < wma5 && wma1[1] >= wma5[1]

// Golden/Death cross analogs between adjacent WMAs
var cross12Up = wma1 > wma2 && wma1[1] <= wma2[1]
var cross12Down = wma1 < wma2 && wma1[1] >= wma2[1]

// -----------------------------------------------------------------------------
// 7. PLOTTING
// -----------------------------------------------------------------------------

// --- Source line (optional) ---
if (showSource) {
    plotLine(
        value=source,
        width=1,
        colors=[srcColor],
        label=["Source"],
        desc=["Source price series (" + src + ")"]
    )
}

// --- WMA Ribbon Lines ---
if (showRibbon) {
    plotLine(
        value=wma1,
        width=2,
        colors=[bullColor],
        label=["WMA " + len1],
        desc=["Fast WMA (" + len1 + ") — highest responsiveness"]
    )
    plotLine(
        value=wma2,
        width=1,
        colors=[opacity(bullColor, 70)],
        label=["WMA " + len2],
        desc=["WMA ribbon edge (" + len2 + ")"]
    )
    plotLine(
        value=wma3,
        width=1,
        colors=[neutralColor],
        label=["WMA " + len3],
        desc=["WMA ribbon mid (" + len3 + ")"]
    )
    plotLine(
        value=wma4,
        width=1,
        colors=[opacity(bearColor, 70)],
        label=["WMA " + len4],
        desc=["WMA ribbon edge (" + len4 + ")"]
    )
    plotLine(
        value=wma5,
        width=2,
        colors=[bearColor],
        label=["WMA " + len5],
        desc=["Slow WMA (" + len5 + ") — trend anchor"]
    )
}

// --- Ribbon Fill (fastest vs slowest) ---
if (showRibbon && showRibbonFill) {
    var ribbonFillBull = wma1 > wma5
    plotLine(
        value=[wma1, wma5],
        width=1,
        colors=[transparency(bullColor, 15), transparency(bearColor, 15)],
        colorIndex=ribbonFillBull ? 0 : 1,
        fill=true,
        label=["WMA Fast", "WMA Slow"],
        desc=["Ribbon fill between fastest and slowest WMA"]
    )
}

// --- Price vs Ribbon Average Fill ---
if (showPriceFill) {
    var priceFillBull = source > ribbonAvg
    plotLine(
        value=[source, ribbonAvg],
        width=1,
        colors=[transparency(bullColor, 20), transparency(bearColor, 20)],
        colorIndex=priceFillBull ? 0 : 1,
        fill=true,
        label=["Price", "Ribbon Avg"],
        desc=["Fill between price and ribbon average — regime-coded"]
    )
}

// --- Ribbon Average (regime-colored reference) ---
plotLine(
    value=ribbonAvg,
    width=2,
    colors=[regimeColor],
    label=["Ribbon Average"],
    desc=["Average of all WMAs (" + len1 + "/" + len2 + "/" + len3 + "/" + len4 + "/" + len5 + ") — regime-colored"]
)

// --- Crossover Shapes ---
if (showShapes) {
    if (priceCrossUp) {
        plotShape(
            value=wma1,
            shape="triangleup",
            color=bullColor,
            width=2,
            label=["Price Cross Up"],
            desc=["Price crossed above fastest WMA (" + len1 + ") — bullish bias"]
        )
    }
    if (priceCrossDown) {
        plotShape(
            value=wma1,
            shape="triangledown",
            color=bearColor,
            width=2,
            label=["Price Cross Down"],
            desc=["Price crossed below fastest WMA (" + len1 + ") — bearish bias"]
        )
    }
    if (ribbonCrossUp) {
        plotShape(
            value=wma5,
            shape="diamond",
            color=bullColor,
            width=3,
            label=["Ribbon Bull"],
            desc=["Fast WMA crossed above slow WMA — full ribbon bullish alignment"]
        )
    }
    if (ribbonCrossDown) {
        plotShape(
            value=wma5,
            shape="diamond",
            color=bearColor,
            width=3,
            label=["Ribbon Bear"],
            desc=["Fast WMA crossed below slow WMA — full ribbon bearish alignment"]
        )
    }
    if (cross12Up) {
        plotShape(
            value=wma2,
            shape="arrowup",
            color=opacity(bullColor, 80),
            width=1,
            label=["WMA1>2"],
            desc=["WMA " + len1 + " crossed above WMA " + len2]
        )
    }
    if (cross12Down) {
        plotShape(
            value=wma2,
            shape="arrowdown",
            color=opacity(bearColor, 80),
            width=1,
            label=["WMA1<2"],
            desc=["WMA " + len1 + " crossed below WMA " + len2]
        )
    }
}

// -----------------------------------------------------------------------------
// 8. REGIME TABLE (last bar only)
// -----------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = ribbonBull ? "BULLISH" : (ribbonBear ? "BEARISH" : "NEUTRAL / MIXED")
    var regimeTextColor = ribbonBull ? bullColor : (ribbonBear ? bearColor : neutralColor)
    var spreadText = spreadExpanding ? "EXPANDING" : "COMPRESSING"

    plotTable(
        data=[
            ["WMA Ribbon Pro", regimeText],
            ["Ribbon Spread", ribbonSpread[0]],
            ["Spread Trend", spreadText],
            ["WMA " + len1, wma1[0]],
            ["WMA " + len2, wma2[0]],
            ["WMA " + len3, wma3[0]],
            ["WMA " + len4, wma4[0]],
            ["WMA " + len5, wma5[0]],
            ["Ribbon Avg", ribbonAvg[0]],
            ["Regime Changes", regimeChangeCount],
            ["Price/WMA Crosses", priceWmaCrossCount],
            ["Compression Events", ribbonCompressCount]
        ],
        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
    )
}