MM Flow
FlowScripts

Perfected FlowScript

RMA

RMA Pro — Perfected Edition is indexed as 193_rma.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

12.0 KB

Lines

408

Native Signal Candidates

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

4/4 guarded

RMA Cross Up

line 319:9

Trigger

(showShapes) && (crossUp)

Value

rma

Deps

crossUp:var, showShapes:input

RMA Cross Down

line 329:9

Trigger

(showShapes) && (crossDown)

Value

rma

Deps

crossDown:var, showShapes:input

Slope Up

line 339:9

Trigger

(showShapes) && (slopeUp)

Value

rma

Deps

showShapes:input, slopeUp:var

Slope Down

line 349:9

Trigger

(showShapes) && (slopeDown)

Value

rma

Deps

showShapes:input, slopeDown:var

193_rma.flowscript

source path: kscripts/perfected/193_rma.flowscript · sha256:a7516f558f98482a7994b1a06ee5bfbe86f34124902ac33d468e8f1b2f48ead4

hash verified
//@version=2
// ============================================================================
// RMA Pro — Perfected Edition
// Author: BackQuant | Enhanced by kScript_Perfection_Engineer
// Tags: CORE, #movingaverage, #rma, #wilder, #regime, #zscore
//
// Production-quality Wilder's smoothed moving average (RMA / SMMA) with
// signal-line confirmation, z-score normalisation, three-tier regime detection
// (bull / bear / neutral), color-coded fill, shape markers for crossovers and
// slope changes, and static state tracking for consecutive regime duration.
//
// Research papers underpinning this design:
//  1. Wilder (1978), "New Concepts in Technical Trading Systems": canonical
//     reference introducing RMA/SMMA. Recursive formula: rma = (prev_rma ×
//     (len−1) + current_close) / len; alpha = 1/len. Seed with SMA(n).
//  2. Khand et al. (2019), "The Performance of Exponential Moving Average,
//     Moving Average Convergence-Divergence, Relative Strength Index and
//     Momentum Trading Rules in the Pakistan Stock Market": EMA variants
//     showed substantial prognostic capability after transaction costs.
//     Slower-response MAs (RMA) reduce whipsaws, supporting use as a smoother
//     trend filter.
//  3. Brock, Lakonishok & LeBaron (1992), "Simple Technical Trading Rules and
//     the Stochastic Properties of Stock Returns": MA crossover rules
//     significantly outperformed buy-and-hold on 90 years of DJIA data.
//     Validates the RMA + signal-line crossover architecture.
//  4. Zakamulin (2023), "Optimal Trend-Following with Transaction Costs":
//     optimal trend-following resembles simple MA crossover rules under
//     plausible transaction-cost assumptions. Provides mathematical
//     justification for the trend-following approach.
//  5. Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint":
//     z-score normalisation measures distance to equilibrium in units of
//     standard deviations. Underpins the RMA z-score standardisation.
// ============================================================================

define(
    title="RMA Pro — Perfected Edition",
    position="onchart",
    axis=false
)

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

// -- RMA Settings --
var length = input(
    name="length",
    type="number",
    defaultValue=14,
    label="RMA Length",
    constraints={min: 2, max: 200, step: 1},
    group="RMA Settings"
)
var srcType = input(
    name="srcType",
    type="select",
    defaultValue="close",
    label="Source",
    options=["close", "open", "high", "low", "hl2", "hlc3", "ohlc4"],
    group="RMA Settings"
)

// -- Signal Line --
var signalLen = input(
    name="signalLen",
    type="number",
    defaultValue=14,
    label="Signal SMA Length",
    constraints={min: 2, max: 100, step: 1},
    group="Signal Line"
)
var useSignal = input(
    name="useSignal",
    type="boolean",
    defaultValue=true,
    label="Enable Signal Line",
    group="Signal Line"
)

// -- Z-Score --
var zLookback = input(
    name="zLookback",
    type="number",
    defaultValue=50,
    label="Z-Score Lookback",
    constraints={min: 10, max: 200, step: 5},
    group="Z-Score Normalisation"
)
var zThreshold = input(
    name="zThreshold",
    type="number",
    defaultValue=2.0,
    label="Z-Score Extremity Threshold",
    constraints={min: 1.0, max: 4.0, step: 0.5},
    group="Z-Score Normalisation"
)
var showZScore = input(
    name="showZScore",
    type="boolean",
    defaultValue=false,
    label="Show Z-Score (offchart)",
    group="Z-Score Normalisation"
)

// -- Display --
var showRMA = input(
    name="showRMA",
    type="boolean",
    defaultValue=true,
    label="Show RMA Line",
    group="Display"
)
var showSignalLine = input(
    name="showSignalLine",
    type="boolean",
    defaultValue=true,
    label="Show Signal Line",
    group="Display"
)
var showFill = input(
    name="showFill",
    type="boolean",
    defaultValue=true,
    label="Show RMA / Signal Fill",
    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="#78909c",
    label="Neutral Color",
    group="Colors"
)
var signalColor = input(
    name="signalColor",
    type="color",
    defaultValue="#ffffff",
    label="Signal Line Color",
    group="Colors"
)

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

timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)

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.open + bars.high + bars.low + bars.close) / 4

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

// ---------------------------------------------------------------------------
// 3. RMA COMPUTATION — canonical Wilder implementation
// ---------------------------------------------------------------------------
// Wilder RMA: seed = SMA(n), then rma = (prev × (n−1) + current) / n
// Built-in rma() handles seeding internally; we document it for clarity.

timeseries rma = rma(source=src, period=length)

// Slope detection
timeseries rising = rma >= rma[1]
timeseries falling = rma < rma[1]

// ---------------------------------------------------------------------------
// 4. SIGNAL LINE (SMA of RMA)
// ---------------------------------------------------------------------------

timeseries signal = useSignal ? sma(source=rma, period=signalLen) : rma

// ---------------------------------------------------------------------------
// 5. Z-SCORE NORMALISATION
// ---------------------------------------------------------------------------

timeseries rmaMean = sma(source=rma, period=zLookback)
timeseries rmaStd = stddev(source=rma, period=zLookback)
timeseries rmaZ = (rmaStd > 0) ? (rma - rmaMean) / rmaStd : 0

var zOverbought = rmaZ > zThreshold
var zOversold = rmaZ < -zThreshold

// ---------------------------------------------------------------------------
// 6. REGIME DETECTION (bull / bear / neutral)
// ---------------------------------------------------------------------------
// Bullish: RMA > signal AND RMA rising
// Bearish: RMA < signal AND RMA falling
// Neutral: everything else

var regimeBull = rma > signal && rising
var regimeBear = rma < signal && falling
var regimeNeutral = !regimeBull && !regimeBear

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

// ---------------------------------------------------------------------------
// 7. STATIC STATE TRACKING
// ---------------------------------------------------------------------------

static prevRegime = 0
static bullBars = 0
static bearBars = 0
static neutralBars = 0
static prevRMA = 0.0
static prevSignal = 0.0

// Initialise static on first real bar
if (prevRMA == 0.0 && !isnan(rma[0])) {
    prevRMA = rma[0]
    prevSignal = signal[0]
}

if (regimeBull) {
    bullBars = bullBars + 1
    bearBars = 0
    neutralBars = 0
} else if (regimeBear) {
    bullBars = 0
    bearBars = bearBars + 1
    neutralBars = 0
} else {
    bullBars = 0
    bearBars = 0
    neutralBars = neutralBars + 1
}

// Crossover / crossunder detection
var crossUp = rma > signal && prevRMA <= prevSignal
var crossDown = rma < signal && prevRMA >= prevSignal

// Slope-change detection
var slopeUp = rising && rma[1] < rma[2]
var slopeDown = falling && rma[1] > rma[2]

if (!isLiveUpdate) {
    prevRMA = rma[0]
    prevSignal = signal[0]
    if (regimeBull) {
        prevRegime = 1
    } else if (regimeBear) {
        prevRegime = -1
    } else {
        prevRegime = 0
    }
}

// ---------------------------------------------------------------------------
// 8. VISUALIZATION — on-chart
// ---------------------------------------------------------------------------

// -- RMA Line (regime-colored) --
if (showRMA) {
    plotLine(
        value=rma,
        width=2,
        colors=[regimeColor],
        label=["RMA"],
        desc=["Wilder's smoothed moving average (" + length + ")"]
    )
}

// -- Signal Line --
if (useSignal && showSignalLine) {
    plotLine(
        value=signal,
        width=1,
        colors=[signalColor],
        label=["Signal"],
        desc=["SMA of RMA (" + signalLen + ")"]
    )
}

// -- Fill between RMA and Signal --
if (showFill && useSignal) {
    var fillBull = rma > signal
    plotLine(
        value=[rma, signal],
        width=1,
        colors=[transparency(bullColor, 20), transparency(bearColor, 20)],
        colorIndex=fillBull ? 0 : 1,
        fill=true,
        label=["RMA", "Signal"],
        desc=["Fill between RMA and signal line, coloured by relative position"]
    )
}

// -- Crossover Shapes --
if (showShapes) {
    if (crossUp) {
        plotShape(
            value=rma,
            shape="triangleup",
            colorIndex=bullColor,
            width=2,
            label=["RMA Cross Up"],
            desc=["RMA crossed above signal line — bullish regime transition"]
        )
    }
    if (crossDown) {
        plotShape(
            value=rma,
            shape="triangledown",
            colorIndex=bearColor,
            width=2,
            label=["RMA Cross Down"],
            desc=["RMA crossed below signal line — bearish regime transition"]
        )
    }
    if (slopeUp) {
        plotShape(
            value=rma,
            shape="arrowup",
            colorIndex=bullColor,
            width=1,
            label=["Slope Up"],
            desc=["RMA slope turned positive"]
        )
    }
    if (slopeDown) {
        plotShape(
            value=rma,
            shape="arrowdown",
            colorIndex=bearColor,
            width=1,
            label=["Slope Down"],
            desc=["RMA slope turned negative"]
        )
    }
}

// ---------------------------------------------------------------------------
// 9. OPTIONAL Z-SCORE OFF-CHART PANEL
// ---------------------------------------------------------------------------

if (showZScore) {
    plotLine(
        value=rmaZ,
        width=2,
        colors=[regimeColor],
        label=["RMA Z-Score"],
        desc=["Z-score normalised RMA distance from rolling mean"]
    )
    hline(value=0, color="#ffffff30", width=1)
    hline(value=zThreshold, color=transparency(bearColor, 50), width=1)
    hline(value=-zThreshold, color=transparency(bullColor, 50), width=1)
}

// ---------------------------------------------------------------------------
// 10. REGIME TABLE (last bar only)
// ---------------------------------------------------------------------------

if (isLastBar) {
    var regimeText = regimeBull ? "BULLISH" : (regimeBear ? "BEARISH" : "NEUTRAL")
    var regimeTextColor = regimeBull ? bullColor : (regimeBear ? bearColor : neutralColor)

    plotTable(
        data=[
            ["RMA Pro — Perfected", regimeText],
            ["RMA", rma[0]],
            ["Signal", signal[0]],
            ["Z-Score", rmaZ[0]],
            ["Bull Bars", bullBars],
            ["Bear Bars", bearBars],
            ["Neutral Bars", neutralBars]
        ],
        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
    )
}