MM Flow
FlowScripts

Perfected FlowScript

Fractal Dimensions

Fractal Dimensions — Perfected Edition is indexed as 300_fractal_dimensions.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.2 KB

Lines

474

Native Signal Candidates

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

6/6 guarded

Eff Cross Up

line 381:9

Trigger

(showShapes) && (crossUp)

Value

efficiency

Deps

crossUp:var, showShapes:input

Eff Cross Down

line 391:9

Trigger

(showShapes) && (crossDown)

Value

efficiency

Deps

crossDown:var, showShapes:input

Trend Regime

line 401:9

Trigger

(showShapes) && (trendEnter)

Value

efficiency

Deps

showShapes:input, trendEnter:var

Chop Regime

line 411:9

Trigger

(showShapes) && (chopEnter)

Value

efficiency

Deps

chopEnter:var, showShapes:input

Z-Score High

line 421:9

Trigger

(showShapes) && (zExtremeHigh)

Value

efficiency

Deps

showShapes:input, zExtremeHigh:var

Z-Score Low

line 431:9

Trigger

(showShapes) && (zExtremeLow)

Value

efficiency

Deps

showShapes:input, zExtremeLow:var

300_fractal_dimensions.flowscript

source path: kscripts/perfected/300_fractal_dimensions.flowscript · sha256:8b893f2d23805257664f622803c03330c225d1bc8d8e5faecda24c36417a0804

hash verified
//@version=2
// ============================================================================
// Fractal Dimensions — Perfected Edition
// Author: D (@ddave334) | Enhanced by kScript Perfection Engineer
// Tags: CORE, #fractal, #hurst, #efficiency, #regime, #trend, #meanreversion
//
// Production-quality fractal dimension analysis combining the Kaufman Efficiency
// Ratio (fractal efficiency), Hurst exponent approximation via R/S analysis, and
// z-score-normalized regime detection. Distinguishes trending markets (low
// fractal dimension, high efficiency) from mean-reverting / choppy markets
// (high fractal dimension, low efficiency) with full color-coding, fill, and
// shape-marker visualization.
//
// Research papers underpinning this design:
//  1. Mandelbrot (1963), "The Variation of Certain Speculative Prices":
//     introduced fractal geometry to finance; established self-similarity and
//     heavy-tailed distributions. Fractal dimension D = 2 − H where H is the
//     Hurst exponent.
//  2. Peters (1994), "Fractal Market Analysis: Applying Chaos Theory to
//     Investment and Economics": proposed the Fractal Market Hypothesis (FMH).
//     Market stability depends on heterogeneous investment horizons; crises occur
//     when short-term trading dominates. R/S analysis is the canonical estimator
//     for H.
//  3. Wu & Xiong (2025), "A Fractal Market Perspective on Improving Futures
//     Pricing": fractal futures pricing model using Hurst exponent reduces
//     pricing errors vs. cost-of-carry models on CSI 300 data.
//  4. Kaufman (1995), "Smarter Trading: Improving Performance in Changing
//     Markets": introduced the Efficiency Ratio (ER) = Change / Volatility.
//     ER ranges from 0 (no direction, choppy) to 1 (perfect trend). ER is
//     conceptually a "fractal efficiency" measure of price path straightness.
//  5. Lo & MacKinlay (1988), "Stock Market Prices Do Not Follow Random Walks":
//     variance ratio test for autocorrelation. VR > 1 signals momentum
//     (positive ACF, trending); VR < 1 signals mean reversion (negative ACF).
//     Underpins the autocorrelation-based regime classification used here.
// ============================================================================

define(
    title="Fractal Dimensions — Perfected Edition",
    position="offchart",
    axis=true
)

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

// --- Efficiency Settings ---
var effLen = input(
    name="effLen",
    type="number",
    defaultValue=30,
    label="Efficiency Ratio Window",
    constraints={min: 5, max: 100, step: 1},
    group="Efficiency Settings"
)
var smoothLen = input(
    name="smoothLen",
    type="number",
    defaultValue=3,
    label="Smoothing Length",
    constraints={min: 1, max: 20, step: 1},
    group="Efficiency Settings"
)

// --- Hurst Exponent ---
var hurstLen = input(
    name="hurstLen",
    type="number",
    defaultValue=50,
    label="Hurst R/S Lookback",
    constraints={min: 10, max: 200, step: 1},
    group="Hurst Exponent"
)
var hurstShort = input(
    name="hurstShort",
    type="number",
    defaultValue=10,
    label="Hurst Short Sub-period",
    constraints={min: 5, max: 50, step: 1},
    group="Hurst Exponent"
)

// --- Thresholds ---
var trendUp = input(
    name="trendUp",
    type="number",
    defaultValue=65,
    label="Strong Trend Threshold",
    constraints={min: 50, max: 95, step: 1},
    group="Thresholds"
)
var trendDn = input(
    name="trendDn",
    type="number",
    defaultValue=35,
    label="Choppy / Mean-Revert Threshold",
    constraints={min: 5, max: 50, step: 1},
    group="Thresholds"
)

// --- Z-Score ---
var zScoreLen = input(
    name="zScoreLen",
    type="number",
    defaultValue=20,
    label="Z-Score Lookback",
    constraints={min: 5, max: 100, step: 1},
    group="Z-Score"
)
var zScoreThresh = input(
    name="zScoreThresh",
    type="number",
    defaultValue=2.0,
    label="Z-Score Extreme Threshold",
    constraints={min: 0.5, max: 4.0, step: 0.1},
    group="Z-Score"
)

// --- Display ---
var showEfficiency = input(
    name="showEfficiency",
    type="boolean",
    defaultValue=true,
    label="Show Efficiency Ratio",
    group="Display"
)
var showHurst = input(
    name="showHurst",
    type="boolean",
    defaultValue=true,
    label="Show Hurst Exponent (0-1)",
    group="Display"
)
var showZScore = input(
    name="showZScore",
    type="boolean",
    defaultValue=true,
    label="Show Z-Score",
    group="Display"
)
var showRegimeFill = input(
    name="showRegimeFill",
    type="boolean",
    defaultValue=true,
    label="Show Regime Fill",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Regime Shapes",
    group="Display"
)

// --- Colors ---
var bullColor = input(
    name="bullColor",
    type="color",
    defaultValue="#26a69a",
    label="Trending / Bull Color",
    group="Colors"
)
var bearColor = input(
    name="bearColor",
    type="color",
    defaultValue="#ef5350",
    label="Choppy / 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 px = bars.close

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

// -----------------------------------------------------------------------------
// 3. KAUFMAN EFFICIENCY RATIO (Fractal Efficiency)
// -----------------------------------------------------------------------------
// ER = |Price Change over N bars| / Sum of absolute bar-to-bar changes
// Trending -> ER close to 1 (straight line); Choppy -> ER close to 0 (wandering)
// Per Kaufman (1995), this is the "fractal efficiency" of price changes.

timeseries netChange = math.abs(px - px[effLen])
timeseries totalVol = 0.0
for (var i = 0; i < effLen; i = i + 1) {
    totalVol = totalVol + math.abs(px[i] - px[i + 1])
}

timeseries rawEff = totalVol > 0 ? netChange / totalVol : 0.0
timeseries efficiency = sma(rawEff * 100.0, smoothLen)
efficiency = math.max(0.0, math.min(100.0, efficiency))

// -----------------------------------------------------------------------------
// 4. HURST EXPONENT APPROXIMATION (R/S Analysis)
// -----------------------------------------------------------------------------
// Mandelbrot (1963): H > 0.5 indicates persistent (trending) behavior;
// H < 0.5 indicates anti-persistent (mean-reverting) behavior.
// We approximate H using a simplified range-to-standard-deviation ratio over
// the lookback window, scaled to the [0, 1] interval.

timeseries hurstRange = highest(px, hurstLen) - lowest(px, hurstLen)
timeseries hurstStd = stddev(px, hurstLen)
timeseries rawHurst = hurstStd > 0 ? math.log(hurstRange / hurstStd) / math.log(hurstLen) : 0.5
// Clamp to [0, 1] per canonical Hurst bounds
timeseries hurst = math.max(0.0, math.min(1.0, rawHurst))

// Fractal dimension: D = 2 - H
// Low D (close to 1) = smooth/trending; High D (close to 2) = rough/choppy
timeseries fractalDim = 2.0 - hurst

// -----------------------------------------------------------------------------
// 5. Z-SCORE NORMALIZATION
// -----------------------------------------------------------------------------
// Per Zhao & Palomar (2018), z-score normalization converts raw efficiency into
// standard-deviation units relative to a rolling mean, enabling adaptive
// threshold detection.

timeseries effMean = sma(efficiency, zScoreLen)
timeseries effStd = stddev(efficiency, zScoreLen)
timeseries effZScore = effStd > 0 ? (efficiency - effMean) / effStd : 0.0

// -----------------------------------------------------------------------------
// 6. REGIME DETECTION
// -----------------------------------------------------------------------------
// Three-regime classification:
//   TRENDING: efficiency >= trendUp  AND hurst >= 0.5
//   CHOPPY:   efficiency <= trendDn  AND hurst < 0.5
//   NEUTRAL:  everything else

var regimeTrend = efficiency >= trendUp && hurst >= 0.5
var regimeChop = efficiency <= trendDn && hurst < 0.5
var regimeNeutral = !regimeTrend && !regimeChop

var regimeColor = regimeTrend ? bullColor : (regimeChop ? bearColor : neutralColor)

// Signal line: EMA of efficiency for crossover detection
timeseries signalLine = ema(efficiency, smoothLen)

// -----------------------------------------------------------------------------
// 7. STATIC STATE TRACKING
// -----------------------------------------------------------------------------
// Session-level persistence for tracking regime transitions, session extremes,
// and efficiency statistics across bars.

static lastRegime = 0
static regimeChangeCount = 0
static sessionHighEff = -999999.0
static sessionLowEff = 999999.0
static sessionHighHurst = -999999.0
static sessionLowHurst = 999999.0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

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

    if (efficiency > sessionHighEff) {
        sessionHighEff = efficiency
    }
    if (efficiency < sessionLowEff) {
        sessionLowEff = efficiency
    }
    if (hurst > sessionHighHurst) {
        sessionHighHurst = hurst
    }
    if (hurst < sessionLowHurst) {
        sessionLowHurst = hurst
    }

    var currRegime = regimeTrend ? 1 : (regimeChop ? -1 : 0)
    if (lastRegime != currRegime) {
        lastRegime = currRegime
        regimeChangeCount = regimeChangeCount + 1
    }
}

// -----------------------------------------------------------------------------
// 8. ALERT CONDITIONS
// -----------------------------------------------------------------------------
// Crossovers of efficiency vs. signal line; extreme z-score penetrations;
// regime transitions.

var crossUp = efficiency > signalLine && efficiency[1] <= signalLine[1]
var crossDown = efficiency < signalLine && efficiency[1] >= signalLine[1]

var zExtremeHigh = effZScore >= zScoreThresh && effZScore[1] < zScoreThresh
var zExtremeLow = effZScore <= -zScoreThresh && effZScore[1] > -zScoreThresh[1]

var trendEnter = regimeTrend && !regimeTrend[1]
var chopEnter = regimeChop && !regimeChop[1]

// -----------------------------------------------------------------------------
// 9. PLOTTING
// -----------------------------------------------------------------------------

// --- Midline ---
hline(value=50.0, color="#ffffff20", width=1)

// --- Threshold lines ---
hline(value=trendUp, color=transparency(bullColor, 60), width=1)
hline(value=trendDn, color=transparency(bearColor, 60), width=1)

// --- Efficiency Ratio (regime-colored) ---
if (showEfficiency) {
    plotLine(
        value=efficiency,
        width=2,
        colors=[regimeColor],
        label=["Efficiency Ratio"],
        desc=["Kaufman Efficiency Ratio (0-100). Trending = high, choppy = low."]
    )
}

// --- Signal Line ---
if (showEfficiency) {
    plotLine(
        value=signalLine,
        width=1,
        colors=[neutralColor],
        label=["Signal EMA"],
        desc=["EMA smoothing of efficiency ratio for crossover detection"]
    )
}

// --- Regime Fill (efficiency vs. signal) ---
if (showRegimeFill && showEfficiency) {
    var effBull = efficiency > signalLine
    plotLine(
        value=[efficiency, signalLine],
        width=1,
        colors=[transparency(bullColor, 20), transparency(bearColor, 20)],
        colorIndex=effBull ? 0 : 1,
        fill=true,
        label=["Efficiency", "Signal"],
        desc=["Fill between efficiency ratio and signal EMA"]
    )
}

// --- Hurst Exponent (scaled to 0-100 for overlay) ---
if (showHurst) {
    plotLine(
        value=hurst * 100.0,
        width=1,
        colors=["#ffd700"],
        label=["Hurst × 100"],
        desc=["Hurst exponent (scaled 0-100). H > 0.5 = trending persistence."]
    )
    hline(value=50.0, color="#ffd70020", width=1)
}

// --- Z-Score ---
if (showZScore) {
    plotLine(
        value=effZScore,
        width=1,
        colors=["#7c4dff"],
        label=["Efficiency Z-Score"],
        desc=["Z-score of efficiency ratio over " + zScoreLen + " bars"]
    )
    hline(value=zScoreThresh, color="#7c4dff30", width=1)
    hline(value=-zScoreThresh, color="#7c4dff30", width=1)
}

// --- Shape Markers ---
if (showShapes) {
    if (crossUp) {
        plotShape(
            value=efficiency,
            shape="triangleup",
            color=bullColor,
            width=2,
            label=["Eff Cross Up"],
            desc=["Efficiency ratio crossed above signal EMA"]
        )
    }
    if (crossDown) {
        plotShape(
            value=efficiency,
            shape="triangledown",
            color=bearColor,
            width=2,
            label=["Eff Cross Down"],
            desc=["Efficiency ratio crossed below signal EMA"]
        )
    }
    if (trendEnter) {
        plotShape(
            value=efficiency,
            shape="diamond",
            color=bullColor,
            width=3,
            label=["Trend Regime"],
            desc=["Entered trending regime: efficiency >= " + trendUp + " and Hurst >= 0.5"]
        )
    }
    if (chopEnter) {
        plotShape(
            value=efficiency,
            shape="diamond",
            color=bearColor,
            width=3,
            label=["Chop Regime"],
            desc=["Entered choppy/mean-reverting regime: efficiency <= " + trendDn + " and Hurst < 0.5"]
        )
    }
    if (zExtremeHigh) {
        plotShape(
            value=efficiency,
            shape="xcross",
            color=bullColor,
            width=2,
            label=["Z-Score High"],
            desc=["Efficiency z-score crossed above +" + zScoreThresh]
        )
    }
    if (zExtremeLow) {
        plotShape(
            value=efficiency,
            shape="xcross",
            color=bearColor,
            width=2,
            label=["Z-Score Low"],
            desc=["Efficiency z-score crossed below -" + zScoreThresh]
        )
    }
}

// -----------------------------------------------------------------------------
// 10. REGIME TABLE (last bar only)
// -----------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = regimeTrend ? "TRENDING" : (regimeChop ? "CHOPPY" : "NEUTRAL")
    var regimeTextColor = regimeTrend ? bullColor : (regimeChop ? bearColor : neutralColor)

    plotTable(
        data=[
            ["Fractal Dimensions — Perfected", regimeText],
            ["Efficiency", efficiency[0]],
            ["Hurst (H)", hurst[0]],
            ["Fractal Dim (D)", fractalDim[0]],
            ["Z-Score", effZScore[0]],
            ["Signal EMA", signalLine[0]],
            ["Session High Eff", sessionHighEff],
            ["Session Low Eff", sessionLowEff],
            ["Regime Changes", regimeChangeCount]
        ],
        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
    )
}