MM Flow
FlowScripts

Perfected FlowScript

Kaufman Efficiency Ratio

Kaufman Efficiency Ratio — Perfected Edition is indexed as 145_kaufman_efficiency_ratio.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

offchart

Axis

true

Size

15.4 KB

Lines

500

Native Signal Candidates

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

6/6 guarded

Trending

line 409:9

Trigger

(showShapes) && (crossUp)

Value

er

Deps

crossUp:var, showShapes:input

Chop

line 419:9

Trigger

(showShapes) && (crossDown)

Value

er

Deps

crossDown:var, showShapes:input

Strong Trend

line 429:9

Trigger

(showShapes) && (enterStrong)

Value

er

Deps

enterStrong:var, showShapes:input

Chop Zone

line 439:9

Trigger

(showShapes) && (enterChop)

Value

er

Deps

enterChop:var, showShapes:input

Bull Div

line 449:9

Trigger

(showShapes) && (bullDiv)

Value

er

Deps

bullDiv:var, showShapes:input

Bear Div

line 459:9

Trigger

(showShapes) && (bearDiv)

Value

er

Deps

bearDiv:var, showShapes:input

145_kaufman_efficiency_ratio.flowscript

source path: kscripts/perfected/145_kaufman_efficiency_ratio.flowscript · sha256:688ac645966917de4940d161eb9b52ff40332bce96aec694355cb18bc9d2adbf

hash verified
//@version=2
// ============================================================================
// Kaufman Efficiency Ratio (KER) — Perfected Edition
// Author: BackQuant (@BackQuant) | Enhanced by kScript Perfection Engineer
// Tags: CORE, #ker, #kaufman, #efficiency, #adaptive, #kama, #fractal, #regime
//
// Production-grade Kaufman Efficiency Ratio with adaptive KAMA-style smoothing,
// regime detection (trending vs ranging), volatility-scaled thresholds, color-
// coded fill, and shape-marked event alerts.
//
// Academic foundations:
//  - Kaufman (1995), "Smarter Trading: Improving Performance in Changing Markets".
//    Original ER and KAMA publication. ER = |Close − Close(N)| / Σ|ΔClose|,
//    bounded 0–1. Near 1 = efficient directional movement; near 0 = chop.
//    KAMA adapts smoothing constant: SC = [ER × (Fastest SC − Slowest SC) +
//    Slowest SC]². KAMA tracks price closely in trends, flattens in chop.
//  - Kaufman (2013), "Trading Systems and Methods" (6th ed). Comprehensive
//    encyclopedia. ER measures "fractal efficiency" of price changes — the ratio
//    of net displacement to total path length. Adaptive moving averages outperform
//    fixed-period MAs in markets with variable volatility.
//  - Mandelbrot (1963/1982), "The Fractal Geometry of Nature". Introduced
//    fractal geometry to finance; self-similarity and scaling laws. Kaufman's
//    "fractal efficiency" concept directly references Mandelbrot's work on
//    measuring path straightness. Fractal dimension D = 2 − H where H = Hurst.
//  - Peters (1994), "Fractal Market Analysis: Applying Chaos Theory to Investment
//    and Economics". Fractal Market Hypothesis (FMH): market stability depends on
//    heterogeneous investment horizons. ER captures the efficiency of the dominant
//    horizon at any time — trending when one horizon dominates, chop when many
//    horizons conflict.
//  - Hurst, Ooi & Pedersen (2014), "A Century of Evidence on Trend-Following
//    Investing" (AQR / NYU). Time-series momentum profitable across nearly all
//    asset classes since 1880. ER provides the regime filter for when trend-following
//    vs mean-reversion strategies are optimal.
//  - Zakamulin (2023), "Optimal Trend-Following with Transaction Costs" (Int'l
//    Review of Financial Analysis). Under plausible trend dynamics, optimal
//    trend-following resembles SMA crossover. Adaptive smoothing (KAMA) is a
//    pragmatic approximation of the optimal filter.
// ============================================================================

define(
    title="Kaufman Efficiency Ratio — Perfected Edition",
    position="offchart",
    axis=true
)

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

// --- ER Settings ---
var erLen = input(
    name="erLen",
    type="number",
    defaultValue=10,
    label="ER Lookback Length",
    constraints={min: 3, max: 50, step: 1},
    group="Efficiency Ratio"
)

// --- Adaptive Smoothing (KAMA) ---
var useKama = input(
    name="useKama",
    type="boolean",
    defaultValue=true,
    label="Use KAMA Adaptive Smoothing",
    group="Adaptive Smoothing (KAMA)"
)
var kamaFast = input(
    name="kamaFast",
    type="number",
    defaultValue=2,
    label="KAMA Fastest SC (periods)",
    constraints={min: 2, max: 10, step: 1},
    group="Adaptive Smoothing (KAMA)"
)
var kamaSlow = input(
    name="kamaSlow",
    type="number",
    defaultValue=30,
    label="KAMA Slowest SC (periods)",
    constraints={min: 10, max: 100, step: 1},
    group="Adaptive Smoothing (KAMA)"
)
var kamaLen = input(
    name="kamaLen",
    type="number",
    defaultValue=10,
    label="KAMA Base Length",
    constraints={min: 3, max: 50, step: 1},
    group="Adaptive Smoothing (KAMA)"
)

// --- MA of ER ---
var maLen = input(
    name="maLen",
    type="number",
    defaultValue=21,
    label="ER MA Length",
    constraints={min: 5, max: 100, step: 1},
    group="MA of ER"
)
var useEma = input(
    name="useEma",
    type="boolean",
    defaultValue=true,
    label="Use EMA for ER MA (off = SMA)",
    group="MA of ER"
)

// --- Regime Thresholds ---
var trendThreshold = input(
    name="trendThreshold",
    type="number",
    defaultValue=0.5,
    label="Trend / Range Threshold",
    constraints={min: 0.1, max: 0.9, step: 0.05},
    group="Regime Thresholds"
)
var strongTrendThresh = input(
    name="strongTrendThresh",
    type="number",
    defaultValue=0.7,
    label="Strong Trend Threshold",
    constraints={min: 0.3, max: 0.95, step: 0.05},
    group="Regime Thresholds"
)
var chopThresh = input(
    name="chopThresh",
    type="number",
    defaultValue=0.3,
    label="Chop Threshold",
    constraints={min: 0.05, max: 0.5, step: 0.05},
    group="Regime Thresholds"
)

// --- Display ---
var showKama = input(
    name="showKama",
    type="boolean",
    defaultValue=true,
    label="Show KAMA Line",
    group="Display"
)
var showMa = input(
    name="showMa",
    type="boolean",
    defaultValue=true,
    label="Show ER MA Line",
    group="Display"
)
var showFill = input(
    name="showFill",
    type="boolean",
    defaultValue=true,
    label="Show ER / MA Fill",
    group="Display"
)
var showHistogram = input(
    name="showHistogram",
    type="boolean",
    defaultValue=true,
    label="Show Efficiency Histogram",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Event Shapes",
    group="Display"
)

// --- Colors ---
var trendColor = input(
    name="trendColor",
    type="color",
    defaultValue="#26a69a",
    label="Trending Color",
    group="Colors"
)
var chopColor = input(
    name="chopColor",
    type="color",
    defaultValue="#ef5350",
    label="Chop Color",
    group="Colors"
)
var strongTrendColor = input(
    name="strongTrendColor",
    type="color",
    defaultValue="#00e676",
    label="Strong Trend Color",
    group="Colors"
)
var maColor = input(
    name="maColor",
    type="color",
    defaultValue="#ffeb3b",
    label="MA Line Color",
    group="Colors"
)
var kamaColor = input(
    name="kamaColor",
    type="color",
    defaultValue="#42a5f5",
    label="KAMA Line Color",
    group="Colors"
)

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

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

// ------------------------------------------------------------------------------
// 3. EFFICIENCY RATIO (Kaufman 1995)
// ------------------------------------------------------------------------------
// ER = |Close − Close(N)| / Σ|ΔClose| over N bars.
// Numerator = net displacement (directional efficiency).
// Denominator = total path length (volatility / noise).
// Result ∈ [0, 1]. Near 1 = price moved efficiently in one direction.
// Near 0 = price wiggled back and forth, net change ≈ 0.

timeseries change = math.abs(c - nz(c[erLen]))
timeseries sumAbs = sum(math.abs(c - nz(c[1])), erLen)
timeseries er = change / math.max(sumAbs, 1e-9)

// Guard against divide-by-zero on first bars
if (sumAbs == 0) {
    er = 0.0
}

// ------------------------------------------------------------------------------
// 4. ADAPTIVE SMOOTHING (KAMA)
// ------------------------------------------------------------------------------
// Per Kaufman (1995): KAMA adapts its smoothing constant based on ER.
// Fastest SC = 2 / (fastPeriod + 1); Slowest SC = 2 / (slowPeriod + 1).
// SC = [ER × (Fastest SC − Slowest SC) + Slowest SC]².
// KAMA_t = KAMA_{t-1} + SC × (Price_t − KAMA_{t-1}).

timeseries fastestSc = 2.0 / (kamaFast + 1.0)
timeseries slowestSc = 2.0 / (kamaSlow + 1.0)

// Recompute ER for KAMA lookback (may differ from display ER)
timeseries kamaChange = math.abs(c - nz(c[kamaLen]))
timeseries kamaSumAbs = sum(math.abs(c - nz(c[1])), kamaLen)
timeseries kamaEr = kamaChange / math.max(kamaSumAbs, 1e-9)

// Smoothing constant
timeseries sc = math.pow(kamaEr * (fastestSc - slowestSc) + slowestSc, 2)

// KAMA computation (stateful via static)
static kama = 0.0
if (!isLiveUpdate) {
    if (kama == 0.0) {
        kama = c[0]
    } else {
        kama = kama + sc[0] * (c[0] - kama)
    }
}

// ------------------------------------------------------------------------------
// 5. MOVING AVERAGE OF ER
// ------------------------------------------------------------------------------
timeseries erEma = ema(er, maLen)
timeseries erSma = sma(er, maLen)
timeseries erMA = useEma ? erEma : erSma

// ------------------------------------------------------------------------------
// 6. REGIME DETECTION
// ------------------------------------------------------------------------------
// Regime classification based on ER value, MA relationship, and thresholds:
//   Strong Trend: ER > strongTrendThresh AND ER > MA
//   Trending: ER > trendThreshold AND ER > MA
//   Chop: ER < chopThresh AND ER < MA
//   Weak / Transition: everything else

var regimeStrongTrend = er > strongTrendThresh && er > erMA
var regimeTrending = er > trendThreshold && er > erMA && !regimeStrongTrend
var regimeChop = er < chopThresh && er < erMA
var regimeWeak = !regimeStrongTrend && !regimeTrending && !regimeChop

var regimeColor = regimeStrongTrend ? strongTrendColor : (regimeTrending ? trendColor : (regimeChop ? chopColor : "#9e9e9e"))

// ------------------------------------------------------------------------------
// 7. EVENT FLAGS & SHAPE MARKERS
// ------------------------------------------------------------------------------
// ER crossing its MA (regime shift)
var crossUp = er > erMA && er[1] <= erMA[1]
var crossDown = er < erMA && er[1] >= erMA[1]

// Threshold penetrations
var enterTrend = er > trendThreshold && er[1] <= trendThreshold
var exitTrend = er < trendThreshold && er[1] >= trendThreshold
var enterStrong = er > strongTrendThresh && er[1] <= strongTrendThresh
var enterChop = er < chopThresh && er[1] >= chopThresh

// Divergence detection: price makes new high/low but ER disagrees
static prevErHigh = -1.0
static prevErLow = -1.0
static prevPriceHigh = -1.0
static prevPriceLow = -1.0

var bearDiv = false
var bullDiv = false

if (prevErHigh < 0) {
    prevErHigh = er[0]
    prevErLow = er[0]
    prevPriceHigh = c[0]
    prevPriceLow = c[0]
}

if (!isLiveUpdate) {
    if (c[0] > prevPriceHigh) {
        if (er[0] < prevErHigh) {
            bearDiv = true
        }
        prevPriceHigh = c[0]
        prevErHigh = er[0]
    }
    if (c[0] < prevPriceLow) {
        if (er[0] > prevErLow) {
            bullDiv = true
        }
        prevPriceLow = c[0]
        prevErLow = er[0]
    }
}

// ------------------------------------------------------------------------------
// 8. PLOTTING
// ------------------------------------------------------------------------------

// --- Boundary lines ---
hline(value=0.0, color="#ffffff30", width=1)
hline(value=1.0, color="#ffffff30", width=1)

// --- Threshold lines ---
hline(value=trendThreshold, color=transparency(trendColor, 70), width=1)
hline(value=strongTrendThresh, color=transparency(strongTrendColor, 70), width=1)
hline(value=chopThresh, color=transparency(chopColor, 70), width=1)

// --- ER line (regime-colored) ---
plotLine(
    value=er,
    width=2,
    colors=[regimeColor],
    label=["Efficiency Ratio"],
    desc=["Kaufman Efficiency Ratio. Regime-colored: green = strong trend, teal = trending, red = chop, gray = transition."]
)

// --- KAMA line ---
if (showKama && useKama) {
    plotLine(
        value=kama,
        width=2,
        colors=[kamaColor],
        label=["KAMA"],
        desc=["Kaufman Adaptive Moving Average. Tracks price closely in trends, flattens in chop."]
    )
}

// --- ER MA line ---
if (showMa) {
    plotLine(
        value=erMA,
        width=1,
        colors=[maColor],
        label=["ER MA"],
        desc=["Moving average of Efficiency Ratio. Crosses mark regime shifts."]
    )
}

// --- Fill between ER and MA ---
if (showFill && showMa) {
    var fillBull = er > erMA
    plotLine(
        value=[er, erMA],
        width=1,
        colors=[transparency(trendColor, 40), transparency(chopColor, 40)],
        colorIndex=fillBull ? 0 : 1,
        fill=true,
        label=["ER", "ER MA"],
        desc=["Fill between ER and MA. Green = ER above MA (trending), Red = ER below MA (chop)."]
    )
}

// --- Efficiency histogram (ER − MA) ---
if (showHistogram) {
    var hist = er - erMA
    var histColor = hist >= 0 ? trendColor : chopColor
    plotBar(
        value=hist,
        colors=[histColor],
        label=["Efficiency Delta"],
        desc=["Histogram of ER minus MA. Positive = efficiency above average (trending bias)."]
    )
}

// --- Shape markers ---
if (showShapes) {
    if (crossUp) {
        plotShape(
            value=er,
            shape="triangleup",
            colorIndex=trendColor,
            width=2,
            label=["Trending"],
            desc=["ER crossed above MA: regime shift to trending."]
        )
    }
    if (crossDown) {
        plotShape(
            value=er,
            shape="triangledown",
            colorIndex=chopColor,
            width=2,
            label=["Chop"],
            desc=["ER crossed below MA: regime shift to chop/mean-reversion."]
        )
    }
    if (enterStrong) {
        plotShape(
            value=er,
            shape="xcross",
            colorIndex=strongTrendColor,
            width=2,
            label=["Strong Trend"],
            desc=["ER entered strong trend zone (> " + strongTrendThresh + "): breakout conditions."]
        )
    }
    if (enterChop) {
        plotShape(
            value=er,
            shape="xcross",
            colorIndex=chopColor,
            width=2,
            label=["Chop Zone"],
            desc=["ER entered chop zone (< " + chopThresh + "): mean-reversion favored."]
        )
    }
    if (bullDiv) {
        plotShape(
            value=er,
            shape="arrowup",
            colorIndex=strongTrendColor,
            width=1,
            label=["Bull Div"],
            desc=["Bullish divergence: price lower low, ER higher low. Trend may be improving."]
        )
    }
    if (bearDiv) {
        plotShape(
            value=er,
            shape="arrowdown",
            colorIndex=chopColor,
            width=1,
            label=["Bear Div"],
            desc=["Bearish divergence: price higher high, ER lower high. Trend may be degrading."]
        )
    }
}

// ------------------------------------------------------------------------------
// 9. REGIME TABLE (last bar only)
// ------------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = regimeStrongTrend ? "STRONG TREND" : (regimeTrending ? "TRENDING" : (regimeChop ? "CHOP" : "TRANSITION"))
    var regimeTextColor = regimeColor

    plotTable(
        data=[
            ["KER — Perfected", regimeText],
            ["ER", er[0]],
            ["ER MA", erMA[0]],
            ["KAMA", kama[0]],
            ["SC", sc[0]],
            ["Trend Thresh", trendThreshold],
            ["Chop Thresh", chopThresh]
        ],
        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
    )
}