OPEN-SOURCE SCRIPT

Hurst-Optimized Adaptive Channel [Kodexius]

178
Hurst-Optimized Adaptive Channel (HOAC) is a regime-aware channel indicator that continuously adapts its centerline and volatility bands based on the market’s current behavior. Instead of using a single fixed channel model, HOAC evaluates whether price action is behaving more like a trend-following environment or a mean-reverting environment, then automatically selects the most suitable channel structure.

At the core of the engine is a robust Hurst Exponent estimation using R/S (Rescaled Range) analysis. The Hurst value is smoothed and compared against user-defined thresholds to classify the market regime. In trending regimes, the script emphasizes stability by favoring a slower, smoother channel when it proves more accurate over time. In mean-reversion regimes, it deliberately prioritizes a faster model to react sooner to reversion opportunities, similar in spirit to how traders use Bollinger-style behavior.

The result is a clean, professional adaptive channel with inner and outer bands, dynamic gradient fills, and an optional mean-reversion signal layer. A minimalist dashboard summarizes the detected regime, the current Hurst reading, and which internal model is currently preferred.

imagen

🔹 Features

🔸 Robust Regime Detection via Hurst Exponent (R/S Analysis)

HOAC uses a robust Hurst Exponent estimate derived from log returns and Rescaled Range analysis. The Hurst value acts as a behavioral filter:

- H > Trend Start threshold suggests trend persistence and directional continuation.

- H < Mean Reversion threshold suggests anti-persistence and a higher likelihood of reverting toward a central value.


Values between thresholds are treated as Neutral, allowing the channel to remain adaptive without forcing a hard bias.

This regime framework is designed to make the channel selection context-aware rather than purely reactive to recent volatility.

🔸 Dual Channel Engine (Fast vs Slow Models)

Instead of relying on one fixed channel, HOAC computes two independent channel candidates:

Fast model: shorter WMA basis and standard deviation window, intended to respond quickly and fit more reactive environments.

Slow model: longer WMA basis and standard deviation window, intended to reduce noise and better represent sustained directional flow.

Each model produces:

- A midline (basis)

- Outer bands (wider deviation)

- Inner bands (tighter deviation)


This structure gives you a clear core zone and an outer envelope that better represents volatility expansion.

🔸 Rolling Optimization Memory (Model Selection by Error)

HOAC includes an internal optimization layer that continuously measures how well each model fits current price action. On every bar, each model’s absolute deviation from the basis is recorded into a rolling memory window. The script then compares total accumulated error between fast and slow models and prefers the one with lower recent error.

This approach does not attempt curve fitting on multiple parameters. It focuses on a simple, interpretable metric: “Which model has tracked price more accurately over the last X bars?”

Additionally:

If the regime is Mean Reversion, the script explicitly prioritizes the fast model, ensuring responsiveness when reversals matter most.

🔸 Optional Output Smoothing (User-Selectable)

The final selected channel can be smoothed using your choice of:

- SMA

- EMA

- HMA

- RMA


This affects the plotted midline and all band outputs, allowing you to tune visual stability and responsiveness without changing the underlying decision engine.

🔸 Premium Visualization Layer (Inner Core + Outer Fade)

HOAC uses a layered band design:

- Inner bands define the core equilibrium zone around the midline.

- Outer bands define an extended volatility envelope for extremes.


Gradient fills and line styling help separate the core from the extremes while staying visually clean. The midline includes a subtle glow effect for clarity.

🔸 Adaptive Bar Tinting Strength (Regime Intensity)

Bar coloring dynamically adjusts transparency based on how far the Hurst value is from 0.5. When market behavior is more decisively trending or mean-reverting, the tint becomes more pronounced. When behavior is closer to random, the tint becomes more subtle.

🔸 Mean-Reversion Signal Layer

Mean-reversion signals are enabled when the environment is not classified as Trending:

- Buy when price crosses back above the lower outer band

- Sell when price crosses back below the upper outer band

This is intentionally a “return to channel” logic rather than a breakout logic, aligning signals with mean-reversion behavior and avoiding signals in strongly trending regimes by default.

imagen

🔸 Minimalist Dashboard (HUD)

A compact table displays:

- Current regime classification

- Smoothed Hurst value

- Which model is currently preferred (Fast or Slow)

- Trend flow direction (based on midline slope)

🔹 Calculations

1) Robust Hurst Exponent (R/S Analysis)

The script estimates Hurst using a Rescaled Range approach on log returns. It builds a returns array, computes mean, cumulative deviation range (R), standard deviation (S), then converts RS into a Hurst exponent.

Pine Script®
calc_robust_hurst(int length) => float r = math.log(close / close[1]) float[] returns = array.new_float(length) for i = 0 to length - 1 array.set(returns, i, r) float mean = array.avg(returns) float cumDev = 0.0 float maxCD = -1.0e10 float minCD = 1.0e10 float sumSqDiff = 0.0 for i = 0 to length - 1 float val = array.get(returns, i) sumSqDiff += math.pow(val - mean, 2) cumDev += (val - mean) if cumDev > maxCD maxCD := cumDev if cumDev < minCD minCD := cumDev float R = maxCD - minCD float S = math.sqrt(sumSqDiff / length) float RS = (S == 0) ? 0.0 : (R / S) float hurst = (RS > 0) ? (math.log10(RS) / math.log10(length)) : 0.5 hurst


This design avoids simplistic proxies and attempts to reflect persistence (trend tendency) vs anti-persistence (mean reversion tendency) from the underlying return structure.

2) Hurst Smoothing

Raw Hurst values can be noisy, so the script applies EMA smoothing before regime decisions.

Pine Script®
float rawHurst = calc_robust_hurst(i_hurstLen) float hVal = ta.ema(rawHurst, i_smoothHurst)


This stabilized hVal is the value used across regime classification, dynamic visuals, and the HUD display.

3) Regime Classification

The smoothed Hurst reading is compared to user thresholds to label the environment.

Pine Script®
string regime = "NEUTRAL" if hVal > i_trendZone regime := "TRENDING" else if hVal < i_chopZone regime := "MEAN REV"


Higher Hurst implies more persistence, so the indicator treats it as a trend environment.

Lower Hurst implies more mean-reverting behavior, so the indicator enables MR logic and emphasizes faster adaptation.

4) Dual Channel Models (Fast and Slow)

HOAC computes two candidate channel structures in parallel. Each model is a WMA basis with volatility envelopes derived from standard deviation. Inner and outer bands are created using different multipliers.

Fast model (more reactive):

Pine Script®
float fastBasis = ta.wma(close, 20) float fastDev = ta.stdev(close, 20) ChannelObj fastM = ChannelObj.new(fastBasis, fastBasis + fastDev * 2.0, fastBasis - fastDev * 2.0, fastBasis + fastDev * 1.0, fastBasis - fastDev * 1.0, math.abs(close - fastBasis))


Slow model (more stable):

Pine Script®
float slowBasis = ta.wma(close, 50) float slowDev = ta.stdev(close, 50) ChannelObj slowM = ChannelObj.new(slowBasis, slowBasis + slowDev * 2.5, slowBasis - slowDev * 2.5, slowBasis + slowDev * 1.25, slowBasis - slowDev * 1.25, math.abs(close - slowBasis))


Both models store their structure in a ChannelObj type, including the instantaneous tracking error (abs(close - basis)).

5) Rolling Error Memory and Model Preference

To decide which model fits current conditions better, the script stores recent errors into rolling arrays and compares cumulative error totals.

Pine Script®
var float[] errFast = array.new_float() var float[] errSlow = array.new_float() update_error(float[] errArr, float error, int maxLen) => errArr.unshift(error) if errArr.size() > maxLen errArr.pop()


Each bar updates both error histories and computes which model has lower recent accumulated error.

Pine Script®
update_error(errFast, fastM.error, i_optLookback) update_error(errSlow, slowM.error, i_optLookback) bool preferFast = errFast.sum() < errSlow.sum()


This is an interpretable optimization approach: it does not attempt to brute-force parameters, it simply prefers the model that has tracked price more closely over the last i_optLookback bars.

6) Winner Selection Logic (Regime-Aware Hybrid)

The final model selection uses both regime and rolling error performance.

Pine Script®
ChannelObj winner = regime == "MEAN REV" ? fastM : (preferFast ? fastM : slowM) rawMid := winner.mid rawUp := winner.upper rawDn := winner.lower rawUpInner := winner.upper_inner rawDnInner := winner.lower_inner


In Mean Reversion, the script forces the fast model to ensure responsiveness.

Otherwise, it selects the lowest-error model between fast and slow.

7) Optional Output Smoothing

After the winner is selected, the script optionally smooths the final channel outputs using the chosen moving average type.

Pine Script®
smooth(float src, string type, int len) => switch type "SMA" => ta.sma(src, len) "EMA" => ta.ema(src, len) "HMA" => ta.hma(src, len) "RMA" => ta.rma(src, len) => src float finalMid = i_enableSmooth ? smooth(rawMid, i_smoothType, i_smoothLen) : rawMid float finalUp = i_enableSmooth ? smooth(rawUp, i_smoothType, i_smoothLen) : rawUp float finalDn = i_enableSmooth ? smooth(rawDn, i_smoothType, i_smoothLen) : rawDn float finalUpInner = i_enableSmooth ? smooth(rawUpInner, i_smoothType, i_smoothLen) : rawUpInner float finalDnInner = i_enableSmooth ? smooth(rawDnInner, i_smoothType, i_smoothLen) : rawDnInner


This preserves decision integrity since smoothing happens after model selection, not before.

8) Dynamic Visual Intensity From Hurst

Transparency is derived from the distance of hVal to 0.5, so stronger behavioral regimes appear with clearer tints.

Pine Script®
int dynTrans = int(math.max(20, math.min(80, 100 - (math.abs(hVal - 0.5) * 200))))

Exención de responsabilidad

La información y las publicaciones no constituyen, ni deben considerarse como asesoramiento o recomendaciones financieras, de inversión, de trading o de otro tipo proporcionadas o respaldadas por TradingView. Más información en Condiciones de uso.