OPEN-SOURCE SCRIPT
Hurst Exponent Adaptive Supertrend [QuantAlgo]

🟢 Overview
The Hurst Exponent Adaptive Supertrend identifies trending and mean-reverting market conditions by dynamically adjusting its sensitivity and band width based on the real-time persistence of price movement. It estimates the Hurst exponent through variance scaling to classify the current market regime, applies a Kalman smoother with a Hurst-scaled tracking gain to follow price with regime-appropriate responsiveness, and constructs a supertrend band whose width expands in choppy conditions and contracts in strongly trending ones. This allows traders to stay positioned through genuine trends while filtering out noise-driven whipsaws across any timeframe or instrument.

🟢 How It Works
The indicator's core methodology centres on a three-layer pipeline: regime classification via the Hurst exponent, adaptive price smoothing via a Kalman filter, and dynamic band construction that responds to the estimated market state.
First, the Hurst exponent is estimated by comparing short-run and long-run return variance over the configured lookback window. A lag-q variance is scaled against a lag-1 variance, and the ratio is log-transformed to produce a raw H value that is then clamped between 0 and 1:
Pine Script®
H values above 0.5 indicate persistent, trending behaviour. Values below 0.5 indicate mean-reversion or choppiness. This reading then drives every downstream calculation.
Next, a Kalman smoother tracks price using a gain that is amplified in trending regimes and suppressed in choppy ones, keeping the smoothed price line tight to momentum when it matters and sluggish when it does not:
Pine Script®
Finally, the ATR-based band width is computed using a Hurst-scaled multiplier. When H is low (choppy market), the multiplier is large, widening the band to avoid false flips. When H is high (strong trend), the multiplier approaches the base value, keeping the band tight to price:
Pine Script®
The supertrend logic then ratchets the upper and lower bands in the direction of the prevailing trend, flipping state only when the Kalman-smoothed price crosses the opposing band. This prevents band drift from causing premature reversals during normal consolidation:
Pine Script®

🟢 Signal Interpretation
▶ Bullish Trend (Supertrend Line Below Price with Bullish Color): When the Kalman-smoothed price crosses above the upper band, the indicator flips to a bullish state and the trailing line plots below price as a dynamic support level - the floor that price must decisively break before the uptrend is considered invalidated. The support level ratchets higher with each new bar, never pulling back, locking in the floor as the trend develops. In choppy regimes the band width is deliberately wide, meaning price can pull back significantly without breaching support, keeping traders positioned through noise-driven corrections that lack genuine bearish conviction.
▶ Bearish Trend (Supertrend Line Above Price with Bearish Color): When the Kalman-smoothed price crosses below the lower band, the indicator flips to a bearish state and the trailing line plots above price as a dynamic resistance level - the ceiling price must reclaim before a bullish reversal is confirmed. The resistance level ratchets lower with each new bar, tightening the ceiling as the downtrend develops. As with the bullish state, a wide band in low-H environments requires a substantial recovery move before the indicator reverses, allowing traders to hold directional bias through corrective bounces that stay within the noise threshold.

🟢 Features
▶ Preconfigured Presets: Three optimised parameter sets tailored to different trading styles and timeframes. "Default" delivers balanced trend detection for swing trading on 4-hour and daily charts, with moderate Kalman gain and band scaling suited to typical momentum cycles. "Fast Response" uses a higher tracking gain, shorter ATR window, and tighter base multiplier for intraday trading on 5-minute to 1-hour charts, producing earlier trend flips better suited to active traders. "Smooth Trend" applies a lower Kalman gain, longer ATR period, and wider band scaling for position trading on daily and weekly charts, confirming only major directional shifts with minimal false positives.

▶ Built-in Alerts: Two alert conditions enable automated monitoring of trend transitions without constant chart observation. "Bullish Trend Signal" triggers on the bar the indicator first flips to a bullish state, alerting for potential long entries. "Bearish Trend Signal" fires on the bar the indicator first confirms a bearish state, signalling potential short entries or long exits. Both alerts include the exchange, ticker, and timeframe in the alert message for immediate context.

▶ Visual Customisation: Six color presets (Classic, Aqua, Cosmic, Cyber, Neon, and Custom) accommodate different chart themes and personal preferences, with coordinated bullish and bearish color schemes applied consistently to the trend line. When the Custom preset is selected, independent color pickers for bullish and bearish states allow full manual control over the indicator's appearance.

The Hurst Exponent Adaptive Supertrend identifies trending and mean-reverting market conditions by dynamically adjusting its sensitivity and band width based on the real-time persistence of price movement. It estimates the Hurst exponent through variance scaling to classify the current market regime, applies a Kalman smoother with a Hurst-scaled tracking gain to follow price with regime-appropriate responsiveness, and constructs a supertrend band whose width expands in choppy conditions and contracts in strongly trending ones. This allows traders to stay positioned through genuine trends while filtering out noise-driven whipsaws across any timeframe or instrument.
🟢 How It Works
The indicator's core methodology centres on a three-layer pipeline: regime classification via the Hurst exponent, adaptive price smoothing via a Kalman filter, and dynamic band construction that responds to the estimated market state.
First, the Hurst exponent is estimated by comparing short-run and long-run return variance over the configured lookback window. A lag-q variance is scaled against a lag-1 variance, and the ratio is log-transformed to produce a raw H value that is then clamped between 0 and 1:
var1 = ta.variance(close - close[1], active_h_period)
varq = ta.variance(close - close[active_h_lag], active_h_period)
H_raw = math.log(varq / math.max(var1, 1e-10)) / (2.0 * math.log(active_h_lag))
H = math.max(0.0, math.min(H_raw, 1.0))
H values above 0.5 indicate persistent, trending behaviour. Values below 0.5 indicate mean-reversion or choppiness. This reading then drives every downstream calculation.
Next, a Kalman smoother tracks price using a gain that is amplified in trending regimes and suppressed in choppy ones, keeping the smoothed price line tight to momentum when it matters and sluggish when it does not:
adaptive_gain = math.max(math.min(active_kf_gain * (0.5 + safeH), 0.99), 0.01)
kf := na(kf[1]) ? close : kf[1] + adaptive_gain * (close - kf[1])
Finally, the ATR-based band width is computed using a Hurst-scaled multiplier. When H is low (choppy market), the multiplier is large, widening the band to avoid false flips. When H is high (strong trend), the multiplier approaches the base value, keeping the band tight to price:
h_mult = active_atr_base + active_atr_hscale * (1.0 - safeH)
band = ta.atr(active_atr_len) * h_mult
The supertrend logic then ratchets the upper and lower bands in the direction of the prevailing trend, flipping state only when the Kalman-smoothed price crosses the opposing band. This prevents band drift from causing premature reversals during normal consolidation:
upBand := prevT == 1 ? math.max(kf - band, prevUp) : kf - band
dnBand := prevT == -1 ? math.min(kf + band, prevDn) : kf + band
trend := kf > prevDn ? 1 : kf < prevUp ? -1 : prevT
🟢 Signal Interpretation
▶ Bullish Trend (Supertrend Line Below Price with Bullish Color): When the Kalman-smoothed price crosses above the upper band, the indicator flips to a bullish state and the trailing line plots below price as a dynamic support level - the floor that price must decisively break before the uptrend is considered invalidated. The support level ratchets higher with each new bar, never pulling back, locking in the floor as the trend develops. In choppy regimes the band width is deliberately wide, meaning price can pull back significantly without breaching support, keeping traders positioned through noise-driven corrections that lack genuine bearish conviction.
▶ Bearish Trend (Supertrend Line Above Price with Bearish Color): When the Kalman-smoothed price crosses below the lower band, the indicator flips to a bearish state and the trailing line plots above price as a dynamic resistance level - the ceiling price must reclaim before a bullish reversal is confirmed. The resistance level ratchets lower with each new bar, tightening the ceiling as the downtrend develops. As with the bullish state, a wide band in low-H environments requires a substantial recovery move before the indicator reverses, allowing traders to hold directional bias through corrective bounces that stay within the noise threshold.
🟢 Features
▶ Preconfigured Presets: Three optimised parameter sets tailored to different trading styles and timeframes. "Default" delivers balanced trend detection for swing trading on 4-hour and daily charts, with moderate Kalman gain and band scaling suited to typical momentum cycles. "Fast Response" uses a higher tracking gain, shorter ATR window, and tighter base multiplier for intraday trading on 5-minute to 1-hour charts, producing earlier trend flips better suited to active traders. "Smooth Trend" applies a lower Kalman gain, longer ATR period, and wider band scaling for position trading on daily and weekly charts, confirming only major directional shifts with minimal false positives.
▶ Built-in Alerts: Two alert conditions enable automated monitoring of trend transitions without constant chart observation. "Bullish Trend Signal" triggers on the bar the indicator first flips to a bullish state, alerting for potential long entries. "Bearish Trend Signal" fires on the bar the indicator first confirms a bearish state, signalling potential short entries or long exits. Both alerts include the exchange, ticker, and timeframe in the alert message for immediate context.
▶ Visual Customisation: Six color presets (Classic, Aqua, Cosmic, Cyber, Neon, and Custom) accommodate different chart themes and personal preferences, with coordinated bullish and bearish color schemes applied consistently to the trend line. When the Custom preset is selected, independent color pickers for bullish and bearish states allow full manual control over the indicator's appearance.
Script de código aberto
Em verdadeiro espírito do TradingView, o criador deste script o tornou de código aberto, para que os traders possam revisar e verificar sua funcionalidade. Parabéns ao autor! Embora você possa usá-lo gratuitamente, lembre-se de que a republicação do código está sujeita às nossas Regras da Casa.
🟢 Access our best trading & investing tools here (3-day FREE trial): whop.com/quantalgo/
🟢 Free Special Edition indicators: joinquantalgo.com/special-editions
🟢 Discord: discord.gg/hJaFyGEAyX
🟢 Free Special Edition indicators: joinquantalgo.com/special-editions
🟢 Discord: discord.gg/hJaFyGEAyX
Aviso legal
As informações e publicações não se destinam a ser, e não constituem, conselhos ou recomendações financeiras, de investimento, comerciais ou de outro tipo fornecidos ou endossados pela TradingView. Leia mais nos Termos de Uso.
Script de código aberto
Em verdadeiro espírito do TradingView, o criador deste script o tornou de código aberto, para que os traders possam revisar e verificar sua funcionalidade. Parabéns ao autor! Embora você possa usá-lo gratuitamente, lembre-se de que a republicação do código está sujeita às nossas Regras da Casa.
🟢 Access our best trading & investing tools here (3-day FREE trial): whop.com/quantalgo/
🟢 Free Special Edition indicators: joinquantalgo.com/special-editions
🟢 Discord: discord.gg/hJaFyGEAyX
🟢 Free Special Edition indicators: joinquantalgo.com/special-editions
🟢 Discord: discord.gg/hJaFyGEAyX
Aviso legal
As informações e publicações não se destinam a ser, e não constituem, conselhos ou recomendações financeiras, de investimento, comerciais ou de outro tipo fornecidos ou endossados pela TradingView. Leia mais nos Termos de Uso.