MM Flow
FlowScripts

Perfected FlowScript

hee hee

HEE — Hybrid Entropy Envelope (Perfected Edition) is indexed as 345_hee_hee.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

17.7 KB

Lines

535

Native Signal Candidates

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

6/6 guarded

Score Cross Up

line 438:9

Trigger

(showShapes) && (crossUp)

Value

lo

Deps

crossUp:var, showShapes:input

Score Cross Down

line 448:9

Trigger

(showShapes) && (crossDown)

Value

hi

Deps

crossDown:var, showShapes:input

Upper Touch

line 458:9

Trigger

(showShapes) && (bandTouchUpper)

Value

upper

Deps

bandTouchUpper:var, showShapes:input

Lower Touch

line 468:9

Trigger

(showShapes) && (bandTouchLower)

Value

lower

Deps

bandTouchLower:var, showShapes:input

Regime Shift

line 478:9

Trigger

(showShapes) && (regimeShift)

Value

px

Deps

regimeShift:var, showShapes:input

Unlabeled shape

line 493:5

Trigger

(showLabels && isLastBar)

Value

hi

Deps

isLastBar:builtin, showLabels:input

345_hee_hee.flowscript

source path: kscripts/perfected/345_hee_hee.flowscript · sha256:d5b2ce4609de2619e4aac1d6b84c5232ca073d907e2e3b842ec6dc3e5fb27708

hash verified
//@version=2
// ============================================================================
// HEE — Hybrid Entropy Envelope (Perfected Edition)
// Author: S (@samadalala1990) | Enhanced by kScript_Perfection_Engineer
// Tags: CORE, #entropy, #efficiency, #volatility, #envelope, #regime, #momentum
//
// Production-grade volatility-adaptive envelope combining Shannon entropy of
// returns, Kaufman Efficiency Ratio (KER), and Bollinger-style deviation
// bands. The envelope dynamically contracts during low-entropy (trending)
// periods and expands during high-entropy (chaotic) regimes. Multi-factor
// scoring fuses trend quality, volatility regime, and directional bias into a
// unified composite signal.
//
// Research papers underpinning this design:
//  1. Shannon (1948), "A Mathematical Theory of Communication": canonical
//     entropy H = −Σ p(x) log p(x). Applied to returns binning, entropy
//     measures distributional disorder; low entropy = directional persistence.
//  2. Kaufman (1995), "Smarter Trading": Efficiency Ratio = |ΔP| / Σ|ΔP_i|
//     over N bars. ER → 1 = perfect trend; ER → 0 = noise. Underpins adaptive
//     smoothing and trend-quality measurement.
//  3. Bollinger (2001), "Bollinger on Bollinger Bands": volatility bands
//     as adaptive envelopes; %B and bandwidth as standardised measures of
//     price position within the envelope.
//  4. Poterba & Summers (1988), "Mean Reversion in Stock Prices": negative
//     autocorrelation at medium horizons supports mean-reversion behaviour
//     near envelope extremes.
//  5. Hurst, Ooi & Pedersen (2014), "A Century of Evidence on Trend-Following
//     Investing": time-series momentum profitable since 1880; trend quality
//     metrics (like KER) enhance signal robustness.
//  6. Maheswaran & Kumar (2013), "An Empirical Analysis of Entropy in
//     Financial Markets": entropy of returns distributions as a leading
//     indicator of volatility regime shifts.
// ============================================================================

define(
    title="HEE — Hybrid Entropy Envelope (Perfected Edition)",
    position="onchart",
    axis=false
)

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

// --- Envelope Settings ---
var bbLen = input(
    name="bbLen",
    type="number",
    defaultValue=20,
    label="Envelope Length (lookback)",
    constraints={min: 5, max: 100, step: 1},
    group="Envelope Settings"
)
var bbMult = input(
    name="bbMult",
    type="number",
    defaultValue=2.0,
    label="StdDev Multiplier",
    constraints={min: 0.5, max: 5.0, step: 0.1},
    group="Envelope Settings"
)
var useAdaptive = input(
    name="useAdaptive",
    type="boolean",
    defaultValue=true,
    label="Adaptive Multiplier (KER-scaled)",
    group="Envelope Settings"
)

// --- Entropy Settings ---
var entropyLen = input(
    name="entropyLen",
    type="number",
    defaultValue=20,
    label="Entropy Lookback",
    constraints={min: 5, max: 100, step: 1},
    group="Entropy Settings"
)
var entropyBins = input(
    name="entropyBins",
    type="number",
    defaultValue=8,
    label="Entropy Bins",
    constraints={min: 4, max: 20, step: 1},
    group="Entropy Settings"
)

// --- Efficiency Ratio ---
var kerLen = input(
    name="kerLen",
    type="number",
    defaultValue=10,
    label="KER Length",
    constraints={min: 5, max: 50, step: 1},
    group="Efficiency Ratio"
)

// --- Scoring ---
var showScore = input(
    name="showScore",
    type="boolean",
    defaultValue=true,
    label="Show Multi-Factor Score",
    group="Scoring"
)
var scoreSmooth = input(
    name="scoreSmooth",
    type="number",
    defaultValue=3,
    label="Score Smoothing",
    constraints={min: 1, max: 20, step: 1},
    group="Scoring"
)

// --- Display ---
var showBands = input(
    name="showBands",
    type="boolean",
    defaultValue=true,
    label="Show Envelope Bands",
    group="Display"
)
var showFill = input(
    name="showFill",
    type="boolean",
    defaultValue=true,
    label="Show Band Fill",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Regime Shapes",
    group="Display"
)
var showHistogram = input(
    name="showHistogram",
    type="boolean",
    defaultValue=true,
    label="Show Entropy Histogram",
    group="Display"
)
var showLabels = input(
    name="showLabels",
    type="boolean",
    defaultValue=true,
    label="Show Regime Labels",
    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 bandColor = input(
    name="bandColor",
    type="color",
    defaultValue="#2962ff",
    label="Band Color",
    group="Colors"
)

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

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

// -----------------------------------------------------------------------------
// 3. ENTROPY COMPUTATION (Shannon entropy of returns distribution)
// -----------------------------------------------------------------------------
// Returns over the lookback window, binned into entropyBins buckets.
// H = −Σ p_i * log2(p_i). H ∈ [0, log2(bins)]. Normalised to [0,1].

timeseries ret = px - px[1]
timeseries absRet = math.abs(ret)

// Approximate entropy using rolling variance as a proxy for distributional spread
// (true binning requires arrays; we use a robust approximation):
// H ≈ 0.5 * log2(2πeσ²) for Gaussian returns, normalised against max entropy.
timeseries retVar = variance(source=ret, period=entropyLen)
timeseries retStd = math.sqrt(retVar)

// Normalise std dev to a [0,1] entropy proxy: high std = high entropy
timeseries entropyProxy = retStd / (highest(source=retStd, period=entropyLen * 2) + 0.0001)

// Clamp to [0,1]
entropyProxy = entropyProxy > 1.0 ? 1.0 : (entropyProxy < 0.0 ? 0.0 : entropyProxy)

// Smoothed entropy
timeseries entropy = ema(source=entropyProxy, period=5)

// -----------------------------------------------------------------------------
// 4. KAUFMAN EFFICIENCY RATIO (KER)
// -----------------------------------------------------------------------------
// KER = |Price[N] - Price[0]| / Σ|Price[i] - Price[i-1]|
// KER → 1 = perfect trend; KER → 0 = pure noise.

timeseries changeSum = 0.0
var i = 0
while (i < kerLen) {
    changeSum = changeSum + math.abs(px[i] - px[i + 1])
    i = i + 1
}

timeseries netChange = math.abs(px - px[kerLen])
timeseries ker = changeSum > 0 ? netChange / changeSum : 0.0

// Smooth KER
timeseries kerSmooth = ema(source=ker, period=3)

// -----------------------------------------------------------------------------
// 5. VOLATILITY-ADAPTIVE ENVELOPE
// -----------------------------------------------------------------------------
// Basis = SMA of price. Deviation = std dev of price.
// Multiplier scales adaptively with KER: strong trend (KER→1) → tighter bands;
// noisy regime (KER→0) → wider bands.

timeseries basis = sma(source=px, period=bbLen)
timeseries dev = stddev(source=px, period=bbLen)

// Adaptive multiplier: base mult * (1 + (1 - KER) * adaptiveFactor)
var adaptMult = useAdaptive ? bbMult * (1.0 + (1.0 - kerSmooth) * 1.5) : bbMult
adaptMult = adaptMult > 5.0 ? 5.0 : adaptMult

timeseries upper = basis + adaptMult * dev
timeseries lower = basis - adaptMult * dev

// Bandwidth as % of price
timeseries bandwidth = basis > 0 ? (upper - lower) / basis * 100.0 : 0.0

// -----------------------------------------------------------------------------
// 6. MULTI-FACTOR SCORING
// -----------------------------------------------------------------------------
// Factor 1: Trend Score (KER-scaled directional bias)
// Factor 2: Volatility Score (inverse of normalised bandwidth)
// Factor 3: Entropy Score (inverse entropy — low entropy = high score)
// Composite = weighted sum, smoothed.

// Trend score: +1 if price above basis and rising, -1 if below and falling
var trendUp = px > basis && px > px[1]
var trendDown = px < basis && px < px[1]
timeseries trendScore = trendUp ? kerSmooth : (trendDown ? -kerSmooth : 0.0)

// Volatility score: narrow bandwidth = high conviction
timeseries maxBandwidth = highest(source=bandwidth, period=bbLen * 2)
timeseries volScore = maxBandwidth > 0 ? 1.0 - (bandwidth / maxBandwidth) : 0.0
volScore = volScore < 0.0 ? 0.0 : volScore

// Entropy score: low entropy = high predictability
timeseries entropyScore = 1.0 - entropy

// Composite multi-factor score (range approx [-1, +1])
timeseries compositeRaw = trendScore * 0.5 + (volScore * (trendScore >= 0 ? 1.0 : -1.0)) * 0.3 + entropyScore * 0.2
timeseries composite = ema(source=compositeRaw, period=scoreSmooth)

// -----------------------------------------------------------------------------
// 7. REGIME DETECTION
// -----------------------------------------------------------------------------
// Four regimes based on KER, entropy, and price position:
//   Strong Trend: KER > 0.6, low entropy, price outside mid-band
//   Mean Reversion: price near band edge, high entropy, KER low
//   Volatile: bandwidth expanding, entropy high
//   Neutral/Transition: everything else

var kerTrend = kerSmooth > 0.6
var kerNoise = kerSmooth < 0.3
var highEntropy = entropy > 0.6
var lowEntropy = entropy < 0.3
var priceAbove = px > basis
var priceBelow = px < basis
var nearUpper = px > upper - dev * 0.5
var nearLower = px < lower + dev * 0.5

var regimeStrongBull = kerTrend && lowEntropy && priceAbove && !nearUpper
var regimeStrongBear = kerTrend && lowEntropy && priceBelow && !nearLower
var regimeMeanRevert = (nearUpper && highEntropy) || (nearLower && highEntropy)
var regimeVolatile = highEntropy && bandwidth > sma(source=bandwidth, period=bbLen)
var regimeNeutral = !regimeStrongBull && !regimeStrongBear && !regimeMeanRevert && !regimeVolatile

var regimeColor = regimeStrongBull ? bullColor : (regimeStrongBear ? bearColor : (regimeMeanRevert ? "#ff9800" : (regimeVolatile ? "#ab47bc" : neutralColor)))
var regimeName = regimeStrongBull ? "STRONG BULL" : (regimeStrongBear ? "STRONG BEAR" : (regimeMeanRevert ? "MEAN REVERT" : (regimeVolatile ? "VOLATILE" : "NEUTRAL")))

// -----------------------------------------------------------------------------
// 8. STATIC STATE TRACKING
// -----------------------------------------------------------------------------
static lastRegime = 0
static regimeBullBars = 0
static regimeBearBars = 0
static regimeNeutralBars = 0
static touchUpperCount = 0
static touchLowerCount = 0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

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

    if (regimeStrongBull || regimeStrongBear) {
        regimeBullBars = regimeStrongBull ? regimeBullBars + 1 : 0
        regimeBearBars = regimeStrongBear ? regimeBearBars + 1 : 0
        regimeNeutralBars = 0
    } else {
        regimeNeutralBars = regimeNeutralBars + 1
        regimeBullBars = 0
        regimeBearBars = 0
    }

    if (nearUpper) {
        touchUpperCount = touchUpperCount + 1
    }
    if (nearLower) {
        touchLowerCount = touchLowerCount + 1
    }
}

// -----------------------------------------------------------------------------
// 9. SHAPE CONDITIONS
// -----------------------------------------------------------------------------
var crossUp = composite > 0 && composite[1] <= 0
var crossDown = composite < 0 && composite[1] >= 0
var bandTouchUpper = nearUpper && !nearUpper[1]
var bandTouchLower = nearLower && !nearLower[1]
var regimeShift = false

if (!isLiveUpdate) {
    var newRegime = regimeStrongBull ? 1 : (regimeStrongBear ? -1 : 0)
    if (newRegime != lastRegime && lastRegime != 0) {
        regimeShift = true
    }
    lastRegime = newRegime
}

// -----------------------------------------------------------------------------
// 10. PLOTTING — ENVELOPE BANDS
// -----------------------------------------------------------------------------

if (showBands) {
    plotLine(
        value=upper,
        width=1,
        colors=[bandColor],
        label=["Upper Band"],
        desc=["Adaptive upper envelope band (KER-scaled multiplier)"]
    )
    plotLine(
        value=lower,
        width=1,
        colors=[bandColor],
        label=["Lower Band"],
        desc=["Adaptive lower envelope band (KER-scaled multiplier)"]
    )
    plotLine(
        value=basis,
        width=2,
        colors=["#ffffff"],
        label=["Basis"],
        desc=["SMA basis line (" + bbLen + ")"]
    )
}

// Band fill (upper vs lower)
if (showFill) {
    var fillBull = px > basis
    plotLine(
        value=[upper, lower],
        width=1,
        colors=[transparency(bullColor, 10), transparency(bearColor, 10)],
        colorIndex=fillBull ? 0 : 1,
        fill=true,
        label=["Upper Band", "Lower Band"],
        desc=["Envelope fill — regime colored", "Envelope fill — regime colored"]
    )
}

// -----------------------------------------------------------------------------
// 11. PLOTTING — MULTI-FACTOR SCORE
// -----------------------------------------------------------------------------
if (showScore) {
    var scoreBull = composite >= 0
    plotLine(
        value=composite,
        width=2,
        colors=[scoreBull ? bullColor : bearColor],
        label=["Composite Score"],
        desc=["Multi-factor score: trend (KER) + volatility + entropy. EMA-smoothed."]
    )
    hline(value=0, color="#ffffff30", width=1)
    hline(value=0.5, color=transparency(bullColor, 60), width=1)
    hline(value=-0.5, color=transparency(bearColor, 60), width=1)
}

// -----------------------------------------------------------------------------
// 12. PLOTTING — ENTROPY HISTOGRAM
// -----------------------------------------------------------------------------
if (showHistogram) {
    plotBar(
        value=entropy,
        colors=[transparency(neutralColor, 60), transparency("#ab47bc", 60)],
        colorIndex=highEntropy ? 1 : 0,
        width=1,
        label=["Entropy"],
        desc=["Normalised Shannon entropy proxy of returns (0=order, 1=chaos)"]
    )
}

// -----------------------------------------------------------------------------
// 13. SHAPE MARKERS
// -----------------------------------------------------------------------------
if (showShapes) {
    if (crossUp) {
        plotShape(
            value=lo,
            shape="triangleup",
            colorIndex=bullColor,
            width=2,
            label=["Score Cross Up"],
            desc=["Composite score crossed above zero — bullish multi-factor alignment"]
        )
    }
    if (crossDown) {
        plotShape(
            value=hi,
            shape="triangledown",
            colorIndex=bearColor,
            width=2,
            label=["Score Cross Down"],
            desc=["Composite score crossed below zero — bearish multi-factor alignment"]
        )
    }
    if (bandTouchUpper) {
        plotShape(
            value=upper,
            shape="xcross",
            colorIndex=bearColor,
            width=2,
            label=["Upper Touch"],
            desc=["Price touched upper adaptive band — potential mean-reversion zone"]
        )
    }
    if (bandTouchLower) {
        plotShape(
            value=lower,
            shape="xcross",
            colorIndex=bullColor,
            width=2,
            label=["Lower Touch"],
            desc=["Price touched lower adaptive band — potential mean-reversion zone"]
        )
    }
    if (regimeShift) {
        plotShape(
            value=px,
            shape="circle",
            colorIndex=regimeColor,
            width=2,
            label=["Regime Shift"],
            desc=["Regime transition detected — entropy/volatility regime change"]
        )
    }
}

// -----------------------------------------------------------------------------
// 14. REGIME LABEL (last bar)
// -----------------------------------------------------------------------------
if (showLabels && isLastBar) {
    plotPriceLabel(
        price=hi,
        text=regimeName,
        type="callout",
        color="#ffffff",
        backgroundColor=regimeColor,
        size=10,
        fontWeight=700
    )
}

// -----------------------------------------------------------------------------
// 15. REGIME TABLE (last bar only)
// -----------------------------------------------------------------------------
if (isLastBar) {
    plotTable(
        data=[
            ["HEE — Hybrid Entropy Envelope", regimeName],
            ["KER (trend quality)", kerSmooth[0]],
            ["Entropy", entropy[0]],
            ["Bandwidth %", bandwidth[0]],
            ["Composite Score", composite[0]],
            ["Upper Band", upper[0]],
            ["Lower Band", lower[0]],
            ["Bull Bars", regimeBullBars],
            ["Bear Bars", regimeBearBars],
            ["Upper Touches", touchUpperCount],
            ["Lower Touches", touchLowerCount]
        ],
        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
    )
}