MM Flow
FlowScripts

Perfected FlowScript

Adaptive Moving Averages

Adaptive Moving Averages Pro — Perfected Edition is indexed as 299_adaptive_moving_averages.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

15.5 KB

Lines

486

Native Signal Candidates

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

4/4 guarded

Trend Up

line 410:9

Trigger

(showShapes) && (trendUp)

Value

kama

Deps

showShapes:input, trendUp:var

Trend Down

line 420:9

Trigger

(showShapes) && (trendDown)

Value

kama

Deps

showShapes:input, trendDown:var

Bull Div

line 430:9

Trigger

(showShapes) && (bullDiv)

Value

kama

Deps

bullDiv:var, showShapes:input

Bear Div

line 440:9

Trigger

(showShapes) && (bearDiv)

Value

kama

Deps

bearDiv:var, showShapes:input

299_adaptive_moving_averages.flowscript

source path: kscripts/perfected/299_adaptive_moving_averages.flowscript · sha256:f6a8035851d0dc722960a56778cc00e84e3349444ee283e72f32ca3bbfd52af5

hash verified
//@version=2
// ============================================================================
// Adaptive Moving Averages Pro — Perfected Edition
// Author: D (@ddave334) | Enhanced by kScript_Perfection_Engineer
// Tags: CORE, #adaptive, #kama, #efficiency_ratio, #trend, #regime
//
// Production-quality Kaufman Adaptive Moving Average (KAMA) implementation.
// Computes the Efficiency Ratio (ER) to measure market "fractal efficiency",
// then dynamically adjusts the smoothing constant between fast and slow poles.
// Includes multi-KAMA ribbon, regime detection, price-KAMA divergence, and
// comprehensive fill / shape / histogram visualization.
//
// Research papers underpinning this design:
//  1. Kaufman (1995), "Smarter Trading: Improving Performance in Changing
//     Markets": Introduced KAMA and the Efficiency Ratio (ER). ER = Change /
//     Volatility, ranging from 0 (no direction) to 1 (perfect trend). The
//     smoothing constant SC = [ER × (Fastest SC − Slowest SC) + Slowest SC]².
//  2. Manasa & Reddy (2025), "Trend Analysis by Weighted and EMA": Comparative
//     study showing WMA responds faster but produces more whipsaws, while EMA
//     offers stability. Adaptive MAs solve this dilemma by blending between
//     fast and slow responses based on measured market efficiency.
//  3. StockCharts.com "Kaufman Adaptive Moving Average (KAMA)": Practical
//     implementation reference. KAMA(10,2,30) uses 10 periods for ER, 2 for
//     fastest EMA, 30 for slowest. ER measures "fractal efficiency" of price.
//  4. Mulloy (1994), "Smoothing Data With Faster Moving Averages": Introduced
//     DEMA and TEMA — lag-reduction techniques that complement KAMA's adaptive
//     smoothing philosophy. DEMA = (2 × EMA1) − EMA2, reducing EMA lag.
//  5. Hurst, Ooi & Pedersen (2014), "A Century of Evidence on Trend-Following":
//     Time-series momentum has been profitable since 1880 across nearly all
//     asset classes. Adaptive MAs are designed to capture this momentum while
//     minimizing whipsaws in choppy conditions.
//  6. Zakamulin (2023), "Optimal Trend-Following with Transaction Costs":
//     Optimal trend-following resembles simple MA crossover rules. KAMA's
//     dynamic adjustment provides a theoretically-grounded way to optimize
//     the smoothing parameter in the presence of transaction costs.
// ============================================================================

define(
    title="Adaptive Moving Averages Pro — Perfected Edition",
    position="onchart",
    axis=false
)

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

// --- KAMA Settings ---
var erLen = input(
    name="erLen",
    type="number",
    defaultValue=10,
    label="Efficiency Ratio Length",
    constraints={min: 2, max: 50, step: 1},
    group="KAMA Settings"
)
var fastLen = input(
    name="fastLen",
    type="number",
    defaultValue=2,
    label="Fastest EMA Length",
    constraints={min: 1, max: 10, step: 1},
    group="KAMA Settings"
)
var slowLen = input(
    name="slowLen",
    type="number",
    defaultValue=30,
    label="Slowest EMA Length",
    constraints={min: 5, max: 100, step: 1},
    group="KAMA Settings"
)

// --- Multi-KAMA Ribbon ---
var showRibbon = input(
    name="showRibbon",
    type="boolean",
    defaultValue=true,
    label="Show KAMA Ribbon",
    group="KAMA Ribbon"
)
var ribbonFastLen = input(
    name="ribbonFastLen",
    type="number",
    defaultValue=5,
    label="Ribbon Fast ER Length",
    constraints={min: 2, max: 20, step: 1},
    group="KAMA Ribbon"
)
var ribbonSlowLen = input(
    name="ribbonSlowLen",
    type="number",
    defaultValue=20,
    label="Ribbon Slow ER Length",
    constraints={min: 5, max: 50, step: 1},
    group="KAMA Ribbon"
)

// --- Reference EMA ---
var showEmaRef = input(
    name="showEmaRef",
    type="boolean",
    defaultValue=true,
    label="Show Reference EMA",
    group="Reference EMA"
)
var emaRefLen = input(
    name="emaRefLen",
    type="number",
    defaultValue=21,
    label="Reference EMA Length",
    constraints={min: 5, max: 100, step: 1},
    group="Reference EMA"
)

// --- Regime Detection ---
var enableRegime = input(
    name="enableRegime",
    type="boolean",
    defaultValue=true,
    label="Enable Regime Detection",
    group="Regime Detection"
)
var regimeLen = input(
    name="regimeLen",
    type="number",
    defaultValue=50,
    label="Regime Lookback Length",
    constraints={min: 10, max: 200, step: 1},
    group="Regime Detection"
)

// --- Display ---
var showKama = input(
    name="showKama",
    type="boolean",
    defaultValue=true,
    label="Show Primary KAMA",
    group="Display"
)
var showFill = input(
    name="showFill",
    type="boolean",
    defaultValue=true,
    label="Show KAMA Cloud Fill",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Trend Change Shapes",
    group="Display"
)
var showHist = input(
    name="showHist",
    type="boolean",
    defaultValue=true,
    label="Show ER Histogram",
    group="Display"
)

// --- Colors ---
var kamaColor = input(
    name="kamaColor",
    type="color",
    defaultValue="#2962ff",
    label="KAMA Color",
    group="Colors"
)
var emaColor = input(
    name="emaColor",
    type="color",
    defaultValue="#ff9800",
    label="Reference EMA Color",
    group="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"
)

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

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

// -----------------------------------------------------------------------------
// 3. KAMA COMPUTATION — canonical Kaufman implementation
// -----------------------------------------------------------------------------
// Efficiency Ratio (Kaufman): ER = |price change over N bars| / sum of |bar-to-bar changes|
// ER ranges from 0 (pure noise, no direction) to 1 (perfect trend, all bars in same direction)

timeseries direction = math.abs(src - src[erLen])

// Sum of absolute bar-to-bar changes over erLen periods
timeseries volatility = 0.0
for (var erIndex = 0; erIndex < erLen; erIndex = erIndex + 1) {
    volatility = volatility + math.abs(src[erIndex] - src[erIndex + 1])
}

// Guard: if volatility is 0, ER = 0 (no movement at all)
timeseries er = (volatility > 0) ? (direction / volatility) : 0

// Smoothing constant scaling per Kaufman
// fastestSc = 2 / (fastLen + 1), slowestSc = 2 / (slowLen + 1)
timeseries fastestSc = 2.0 / (fastLen + 1.0)
timeseries slowestSc = 2.0 / (slowLen + 1.0)

// SC = [ER × (fastestSc − slowestSc) + slowestSc]²
// The square smooths the transition between fast and slow more gradually
timeseries sc = (er * (fastestSc - slowestSc) + slowestSc) * (er * (fastestSc - slowestSc) + slowestSc)

// KAMA initialization and recursive update
// KAMA_t = KAMA_{t-1} + SC × (price_t − KAMA_{t-1})
// We use a static variable to track KAMA state across bars
timeseries kama = src
static kamaPrev = na

if (kamaPrev != na) {
    kama = kamaPrev + sc * (src - kamaPrev)
}
kamaPrev = kama

// -----------------------------------------------------------------------------
// 4. MULTI-KAMA RIBBON (fast and slow ER variants)
// -----------------------------------------------------------------------------
// Fast KAMA (shorter ER lookback = more responsive)
timeseries directionFast = math.abs(src - src[ribbonFastLen])
timeseries volatilityFast = 0.0
for (var fastIndex = 0; fastIndex < ribbonFastLen; fastIndex = fastIndex + 1) {
    volatilityFast = volatilityFast + math.abs(src[fastIndex] - src[fastIndex + 1])
}
timeseries erFast = (volatilityFast > 0) ? (directionFast / volatilityFast) : 0
timeseries fastestScFast = 2.0 / (fastLen + 1.0)
timeseries slowestScFast = 2.0 / (slowLen + 1.0)
timeseries scFast = (erFast * (fastestScFast - slowestScFast) + slowestScFast) * (erFast * (fastestScFast - slowestScFast) + slowestScFast)

timeseries kamaFast = src
static kamaFastPrev = na
if (kamaFastPrev != na) {
    kamaFast = kamaFastPrev + scFast * (src - kamaFastPrev)
}
kamaFastPrev = kamaFast

// Slow KAMA (longer ER lookback = smoother)
timeseries directionSlow = math.abs(src - src[ribbonSlowLen])
timeseries volatilitySlow = 0.0
for (var slowIndex = 0; slowIndex < ribbonSlowLen; slowIndex = slowIndex + 1) {
    volatilitySlow = volatilitySlow + math.abs(src[slowIndex] - src[slowIndex + 1])
}
timeseries erSlow = (volatilitySlow > 0) ? (directionSlow / volatilitySlow) : 0
timeseries fastestScSlow = 2.0 / (fastLen + 1.0)
timeseries slowestScSlow = 2.0 / (slowLen + 1.0)
timeseries scSlow = (erSlow * (fastestScSlow - slowestScSlow) + slowestScSlow) * (erSlow * (fastestScSlow - slowestScSlow) + slowestScSlow)

timeseries kamaSlow = src
static kamaSlowPrev = na
if (kamaSlowPrev != na) {
    kamaSlow = kamaSlowPrev + scSlow * (src - kamaSlowPrev)
}
kamaSlowPrev = kamaSlow

// Reference EMA for comparison
timeseries refEma = ema(src, emaRefLen)

// -----------------------------------------------------------------------------
// 5. REGIME DETECTION
// -----------------------------------------------------------------------------
// Regime classification based on price vs KAMA, KAMA slope, and fast vs slow KAMA
var kamaRising = kama > kama[1]
var kamaFalling = kama < kama[1]

var regimeBull = enableRegime ? (src > kama && kamaFast > kamaSlow && kamaRising) : false
var regimeBear = enableRegime ? (src < kama && kamaFast < kamaSlow && kamaFalling) : false
var regimeNeutral = enableRegime ? (!regimeBull && !regimeBear) : false

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

// -----------------------------------------------------------------------------
// 6. STATIC TRACKING — trend persistence and transitions
// -----------------------------------------------------------------------------
static bullBars = 0
static bearBars = 0
static lastRegime = 0

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

// Trend change signals
var trendUp = kamaFast > kamaSlow && kamaFast[1] <= kamaSlow[1]
var trendDown = kamaFast < kamaSlow && kamaFast[1] >= kamaSlow[1]

// Price-KAMA divergence (price new high/low, KAMA disagrees)
var priceHigh = highest(source=src, period=regimeLen)
var priceLow = lowest(source=src, period=regimeLen)
var kamaHigh = highest(source=kama, period=regimeLen)
var kamaLow = lowest(source=kama, period=regimeLen)

var bearDiv = (src[0] >= priceHigh) && (kama[0] < kamaHigh)
var bullDiv = (src[0] <= priceLow) && (kama[0] > kamaLow)

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

// --- Primary KAMA (regime-colored) ---
if (showKama) {
    plotLine(
        value=kama,
        width=2,
        colors=[regimeColor],
        label=["KAMA"],
        desc=["Kaufman Adaptive Moving Average (ER=" + erLen + ", fast=" + fastLen + ", slow=" + slowLen + ")"]
    )
}

// --- KAMA Cloud Fill (fast vs slow KAMA ribbon) ---
if (showFill && showRibbon) {
    var cloudBull = kamaFast > kamaSlow
    plotLine(
        value=[kamaFast, kamaSlow],
        width=1,
        colors=[transparency(bullColor, 30), transparency(bearColor, 30)],
        colorIndex=cloudBull ? 0 : 1,
        fill=true,
        label=["KAMA Fast", "KAMA Slow"],
        desc=["Fast KAMA ribbon edge", "Slow KAMA ribbon edge"]
    )
}

// --- Multi-KAMA Ribbon Lines ---
if (showRibbon) {
    plotLine(
        value=kamaFast,
        width=1,
        colors=[transparency(bullColor, 60)],
        label=["KAMA Fast"],
        desc=["Fast adaptive moving average (short ER lookback)"]
    )
    plotLine(
        value=kamaSlow,
        width=1,
        colors=[transparency(bearColor, 60)],
        label=["KAMA Slow"],
        desc=["Slow adaptive moving average (long ER lookback)"]
    )
}

// --- Reference EMA ---
if (showEmaRef) {
    plotLine(
        value=refEma,
        width=1,
        colors=[emaColor],
        label=["EMA Reference"],
        desc=["Reference EMA (" + emaRefLen + ") for comparison with KAMA"]
    )
}

// --- Efficiency Ratio Histogram (offchart-style bar via plotBar) ---
if (showHist) {
    var erColorIdx = er > 0.5 ? 0 : (er > 0.2 ? 2 : 1)
    plotBar(
        value=er * 100,
        colors=[transparency(bullColor, 60), transparency(bearColor, 60), transparency(neutralColor, 50)],
        colorIndex=erColorIdx,
        width=1,
        label=["ER %"],
        desc=["Efficiency Ratio × 100 (trend strength: >50% strong, 20-50% moderate, <20% weak)"]
    )
}

// --- Trend Change Shapes ---
if (showShapes) {
    if (trendUp) {
        plotShape(
            value=kama,
            shape="triangleup",
            colorIndex=bullColor,
            width=2,
            label=["Trend Up"],
            desc=["Fast KAMA crossed above slow KAMA — bullish trend change"]
        )
    }
    if (trendDown) {
        plotShape(
            value=kama,
            shape="triangledown",
            colorIndex=bearColor,
            width=2,
            label=["Trend Down"],
            desc=["Fast KAMA crossed below slow KAMA — bearish trend change"]
        )
    }
    if (bullDiv) {
        plotShape(
            value=kama,
            shape="arrowup",
            colorIndex=bullColor,
            width=1,
            label=["Bull Div"],
            desc=["Bullish divergence: price lower low, KAMA higher low"]
        )
    }
    if (bearDiv) {
        plotShape(
            value=kama,
            shape="arrowdown",
            colorIndex=bearColor,
            width=1,
            label=["Bear Div"],
            desc=["Bearish divergence: price higher high, KAMA lower high"]
        )
    }
}

// --- Reference hlines ---
hline(value=0, color="#ffffff20", width=1)

// -----------------------------------------------------------------------------
// 8. REGIME TABLE (last bar only)
// -----------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = regimeBull ? "BULLISH" : (regimeBear ? "BEARISH" : "NEUTRAL")
    var regimeTextColor = regimeBull ? bullColor : (regimeBear ? bearColor : neutralColor)
    var erPct = math.round(er[0] * 100, 2)

    plotTable(
        data=[
            ["KAMA Pro", regimeText],
            ["KAMA", kama[0]],
            ["KAMA Fast", kamaFast[0]],
            ["KAMA Slow", kamaSlow[0]],
            ["EMA Ref", refEma[0]],
            ["ER %", erPct],
            ["Bull Bars", bullBars],
            ["Bear Bars", bearBars]
        ],
        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
    )
}