Hurst Regime Sentinel [JOAT]HURST REGIME SENTINEL
A proper R/S Hurst-exponent regime classifier — the single most respected statistical test for "is this market trending, mean-reverting, or random?". On top of the textbook R/S analysis, the Sentinel adds a five-class regime taxonomy (Strong MR, MR, Random, Trend, Strong Trend), a confirmation-bars filter to suppress flicker, a right-side floating Hurst badge, a regime-tinted background, and — uniquely — a Suggested JOAT Indicator dashboard row that names the best-fit companion script in the JOAT suite for the current regime.
The Hurst exponent, properly
The Hurst exponent H is a number between 0 and 1 that characterises the long-run persistence of a time series:
H < 0.5 — anti-persistent / mean-reverting. The series tends to reverse its recent direction.
H = 0.5 — random walk (Brownian motion). No memory.
H > 0.5 — persistent / trending. The series tends to continue its recent direction.
The classical estimator is R/S analysis (rescaled range): split the window into sub-segments, compute the range of cumulative deviations from each sub-mean, normalise by the sub-stdev, average, and fit a log-log slope. This script implements that estimator over a configurable lookback (default 100, the canonical value), with optional log-return source for theoretical correctness, and an EMA smoother on top of the raw H series to give a stable regime read.
Five-class regime taxonomy
The Sentinel does not just classify into trend/MR/random — it sub-classifies the trend and MR sides:
Strong MR — H below the strong-MR boundary (default 0.30). Severely anti-persistent. Aggressive reversion regime.
MR — H between strong-MR and the MR upper (default 0.40). Mean-reverting.
Random — H between MR upper and trend lower (default 0.55). No statistical edge from persistence assumptions.
Trend — H above trend lower. Trending.
Strong Trend — H above the strong-trend boundary (default 0.65). Strongly persistent. Aggressive momentum regime.
A Minimum-bars-to-confirm filter (default 3 bars) suppresses regime flicker; a change must persist this many bars before it is committed.
Suggested JOAT Indicator row (unique)
The dashboard exposes a Suggested Indicator row that names the best-fit companion script from the JOAT suite for the current regime. The user can pick which suggestions appear (defaults: Volatility Reversion Bands Pro for MR, Quantum Trend Matrix for Trend, Liquidity Magnet Pro for Random — but every other JOAT indicator is selectable). This converts the abstract regime read into a concrete next action: when the regime changes, the script tells you which other tool in the suite to put on the chart.
Visual system
Right-side floating label — anchored N bars to the right of the latest bar with current H value, regime, and sub-class.
Regime-change labels — drawn at the bar where a confirmed regime change occurs.
Background tint by regime — violet for MR, teal for Trend, untinted for Random. Strong sub-classes use a stronger (lower-transparency) alpha than mild sub-classes. Both alphas are configurable.
Optional Hurst line companion — when enabled, plots the H series scaled to a configurable fraction of the visible price range. Use to visually track H movement over time. Off by default for a clean chart.
Optional reference levels at 0.40 / 0.50 / 0.55 when the line is shown.
A locked Mystic palette (teal trend / violet MR / white random on a midnight-blue ground) gives the chart a distinctive structural identity.
Dashboard
Monospaced table positionable to any of nine corners. Surfaces:
Current H value (raw and smoothed).
Regime classification with glyph.
Sub-class (Strong MR / MR / Random / Trend / Strong Trend).
Bars in current regime.
Distance from H to nearest threshold.
Suggested JOAT Indicator row (toggleable).
Source series in use (Close / HL2 / HLC3 / OHLC4 / Log Returns).
Alerts
Multiple alert conditions, each independently controllable:
Regime changed to MR / Random / Trend
Sub-class changed to Strong MR / Strong Trend
H crosses 0.50 (random-walk centre)
How to read it
Three reads, in order of conviction:
Sub-class entry (Strong MR or Strong Trend) — the highest-conviction read. The market has decisively committed to a persistence regime; the suggested companion indicator becomes high-conviction.
Regime change confirmed (after the minimum-bars filter) — meaningful enough to switch toolkits. If you were trading momentum and the script now reads MR, your edge has just rotated.
H crossing 0.50 — the structural fault line. Above, persistence is positive; below, it is negative. Even without a sub-class entry, a clean cross of 0.50 is a regime warning.
Suggested settings
Defaults (lookback 100, EMA smoothing 14, MR upper 0.40, trend lower 0.55, strong boundaries 0.30 / 0.65) are tuned for daily and 4H charts on liquid markets — the timeframes where R/S analysis is statistically most meaningful. For 1H and below the indicator works but the H estimate becomes noisier; raise the EMA smoother to compensate. For very long horizons (1W+) increase lookback to 200.
Originality / what's reused
The R/S Hurst estimator is the textbook 1951 method — public-domain statistics, implemented from the original Hurst paper. The implementation here — the bounded-loop R/S computation with sub-segment averaging, the five-class regime taxonomy with strong sub-classes, the confirmation-bars regime-change filter, the regime-driven background tint with mild/strong alpha tiers, the optional scaled Hurst-line overlay, the right-side floating badge, and the suggested-JOAT-indicator dashboard row — is JOAT-original. No third-party code reused.
Open source
Published open-source under the default Mozilla Public License 2.0. The R/S loop, the regime classifier, the suggested-indicator router, and the dashboard are isolated modules. Forks welcome with credit.
Limitations
Hurst R/S is statistical — it describes the recent past, it does not predict the future. The estimator carries the natural noise of finite-sample R/S; the EMA smoother is there to suppress flicker but cannot eliminate underlying noise on short lookbacks. The "Suggested JOAT Indicator" row is a heuristic mapping from regime to tool, not a prediction that any specific signal from that tool will fire — it tells you which corner of the toolkit to look at; the tool itself tells you when to act.
—
-made with passion by jackofalltrades
Indicator

Parallel Transport & Holonomy [DAFE]Parallel Transport & Holonomy - (⟡ PTH)
This publication presents the quantitative mechanics and theoretical architecture behind the Parallel Transport & Holonomy engine. This system models price and volume dynamics as trajectories on a continuous two-dimensional manifold. By computing the parallel transport of multi-scale momentum vectors, tracking their covariant derivatives, and integrating their path-dependent rotational deficit ( Holonomy ), the indicator identifies macro regime shifts, structural pivots, and trend continuations.
The architecture is entirely self-contained, featuring a Legit Footprint Toggle that automatically falls back to an advanced Synthetic Footprint Engine when tick-level footprint data is unavailable. It is strictly anchored by a Rolling Confidence Matrix (RCM) and modulated by an Ensemble Dynamic Volatility Scaling (DVS) engine.
The core principle of this system is geometric invariance: signal evaluation is not based on static, lagging thresholds but on the coordinate-invariant deviation of momentum from its natural geodesic path.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Riemannian Price-Volume Manifold & Metric Tensor
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
We define the market state as a coordinate point on a two-dimensional Riemannian manifold
M, where the coordinates are:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Parallel Transport & Covariant Derivatives
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Let V be a momentum vector on the tangent space of the manifold, constructed at three distinct temporal scales: Fast (vecFast), Medium (vecMed), and Slow (vecSlow). The coordinate components of the vector scale k are computed as:
Geodesic Deviation
A path is geodesic if its covariant derivative along the direction of travel is zero (representing the path of least resistance on the manifold). We define the geodesic deviation Zgeodesic as the rolling z-score of the absolute transport deviation:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Holonomy & Phase Accumulation
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Holonomy describes the geometric phenomenon where parallel transporting a vector along a closed loop returns a vector with a changed orientation. This angular deficit directly measures the total curvature enclosed by the loop.
Holonomy Group Classifications
Based on the magnitude of the accumulated rotation (HolonomyNorm), the local coordinate space is classified into four geometric groups:
Trivial (Norm<0.10): The manifold is flat; parallel transport is path-independent, indicating quiet consolidated ranges.
Abelian (Norm<0.25): Minor commutative drift; the vector field undergoes predictable linear shifts.
Non-Abelian (Norm<0.50): Significant non-commutative curvature. Parallel transport is highly path-dependent, signaling complex trend development and institutional accumulation.
Singular (Norm≥0.50): Severe rotational deficit. The manifold geometry has collapsed or rotated sharply, marking high-probability reversal peaks and structural transitions.
Holonomy Regime Shifts
A Regime Shift is triggered when HolonomyNorm exceeds the user-defined threshold (i_holoThresh). Depending on the sign of the accumulated loop (sgn(H)) and the divergence between the fast and slow vectors, the engine classifies the transition into one of the following states:
Bull Rotation : Enclosed path yields a positive rotational deficit combined with positive multi-scale momentum.
Bear Rotation : Enclosed path yields a negative rotational deficit combined with negative multi-scale momentum.
Geodesic Break : Extreme localized acceleration causing the momentum field to tear away from its expected trajectory.
Scale Divergence : High-frequency (fast) and low-frequency (slow) vectors rotate in opposite directions, enclosing a singular point.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Rolling Confidence Matrix (RCM)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
The Rolling Confidence Matrix (RCM) acts as a structural anchor. It takes multi-scale geometric indicators from the transport engine and compiles them into a state-space model that dynamically controls signal permissions.
State Space Representation
The matrix maintains a rolling assessment of market structure across three distinct states:
Established (State 0): The trend is structurally intact; manifold bands are compressed, and parallel transport confirms high directional persistence.
Transition (State 1): Price is approaching key structural levels or experiencing a holonomy spike. Manifold bands widen, and standard signals are gated.
Damaged (State 2): Price has broken through primary defensive corridors. Structural confidence is compromised; bands expand by the Damage Band Expansion multiplier
(i_damageWiden), and counter-trend positions are heavily penalized.
External Evidence Injection
On every bar, the system injects external geometric parameters from the manifold:
This evidence is integrated into the RCM, outputting structural permissions (allowLong, allowShort) and score modulations that are applied to the final signal scoring calculations.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Ensemble Dynamic Volatility Scaling (DVS)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
To adapt the mathematical models to varying market volatility, the script runs three independent volatility estimators concurrently on every bar:
Ensemble Combinatorics
The baseline values are calculated as moving averages over the memory period. The script then computes the ratios of the current estimators to their historical baselines:
This ratio dynamically scales the width of the holographic manifold bands and the RCM damage thresholds: during highly volatile regimes, thresholds are expanded to prevent whipsaws; during compression regimes, thresholds are tightened to capture early breakouts.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Footprint & Synthetic Fallback Engine
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
The script includes a Use Legit Footprint toggle (i_useFp). When enabled on charts supporting tick databases, the system requests official exchange-traded order flow data:
fp=request.footprint(i_fpTicks,i_fpVA)
The Advanced Synthetic Footprint Engine
If the user deactivates the footprint toggle, or if the asset/timeframe does not support tick database access (e.g., historical bars or Forex), the Synthetic Footprint Fallback Engine** takes over, simulating volume-at-price and directional delta using high-frequency mathematical approximations:
This estimated delta reconstructs the synthetic buy and sell pressures:
Kyle's Lambda (Price Impact & Liquidity Risk)
Using these directional volumes, we calculate Kyle's price impact coefficient λ, measuring the price change per unit of volume flow:
High values of λ represent illiquid, thin, or toxic conditions. The system calculates the z-score of lambda (Zλ). If Zλ > 2.0, signal scores are dynamically penalized to protect capital from low-liquidity slippage.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Structural Scoring & Signal Gating
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
The system generates a directional Signal Score using a two-tier quantitative scoring process.
Stage 1: Structural Base (Minimum of one required)
Siege Corridor Proximity : Price is within 1.2 ⋅ ATR of a verified support or resistance level.
ScoreBase = 0.28+(Hold Probability⋅0.18)
EMA21 Geodesic Pullback : Price pulls back to the EMA21 in trend alignment.
ScoreBase = 0.25
RSI Extreme Exhaustion : RSI is below 25 (for longs) or above 75 (for shorts).
ScoreBase = 0.28
Stage 2: Confirmations (Additive)
Multi-pattern confluence (2+ patterns matching): +0.15
Pressure bar strength exceeds thresholds: +0.08 to +0.15
Metric curvature aligns with structural turn: +0.10
Volume expansion exceeds historical average: +0.10
Holonomy phase shifts or loop spikes: +0.12
Directional Scaling & Gating
The score is adjusted based on trend alignment. With-Trend (WT) setups (longs above the EMA50, shorts below) are evaluated using standard thresholds. Counter-Trend (CT) setups face a strict scaling penalty:
ScoreCT = ScoreRaw ⋅ clamp(1.0−Trend Strength⋅0.15,0.45,1.0)
Additionally, the score passes through three gates:
Liquidity Penalty : Reduced by up to 30% if order flow thickness is classified as Desert or Frozen.
Kyle Lambda Gate : Penalized if price impact is highly volatile (Zλ > 2.0).
Danger Gate : Score is multiplied by 0.60 if the composite risk danger index exceeds 75.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Input Reference
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
═══ GEOMETRY ENGINE ═══
Hurst Period (30 to 200, default 80): Lookback window for R/S calculations to evaluate trend persistence.
Pivot Length (2 to 15, default 5): Lookback/lookahead buffer for swing pivot detection.
TF Preset (Auto, 1m-5m Scalp, 10m-15m Intra, 30m-1H Swing, 4H-D Position): Set the timeframe scaling preset. Auto dynamically scales lookbacks based on the current chart timeframe.
Use Legit Footprint (Boolean, default true): Toggles whether to query exchange tick database for real footprint data.
Footprint Ticks/Row (1 to 500, default 100): Height of the footprint rows in tick units.
Footprint VA % (50 to 90, default 70): Percentage of volume enclosed within the Value Area.
═══ TRANSPORT & HOLONOMY ═══
Vector Fast Scale (3 to 21, default 8): Periods for tracking short-term momentum vectors.
Vector Medium Scale (10 to 55, default 21): Periods for intermediate momentum geometry.
Vector Slow Scale (21 to 144, default 55): Baseline vector window representing the macro manifold.
Holonomy Window (13 to 89, default 34): Size of the temporal loop used to integrate local deviations.
Holonomy Spike Threshold (0.10 to 0.90, default 0.35): Sensitivity threshold for identifying rotational shifts.
Geodesic Deviation Sensitivity (0.5 to 3.0, default 1.5): Sensitivity for flagging off-path momentum.
Enable Continuation Signals (Boolean, default true): Toggles secondary pullback entries in strong trends.
═══ ROLLING CONFIDENCE MATRIX ═══
Block Transition Signals (Boolean, default true): If active, blocks standard entry signals when the matrix is in transition state.
Conf Band Tightening Factor (0.0 to 1.0, default 0.35): Compression multiplier for manifold bands under high confidence.
Damage Band Expansion (1.0 to 1.5, default 1.15): Expansion multiplier for manifold bands under structural damage.
═══ DYNAMIC VOLATILITY SCALING (DVS) ═══
Enable Ensemble DVS Engine (Boolean, default true): Toggles whether to scale target multiples and thresholds by volatility.
DVS Method (ATR Ratio, Parkinson, Garman-Klass, Ensemble): Method for calculating real-time volatility.
DVS Memory Period (20 to 200, default 100): Baseline lookback window for historical volatility.
DVS Sensitivity (0.3 to 1.5, default 0.7): Exponent scaling parameter for the DVS ratio.
═══ SIGNAL GATING ═══
Signal Threshold (0.10 to 0.85, default 0.40): Minimum score required to fire a signal.
Cooldown Bars (1 to 50, default 6): Minimum bar spacing between consecutive signals.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Visual System & Dashboard Interpretation
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Transport Field Manifold : A multi-layered band surrounding price. It contracts during clean, high-confidence geodesic flow and expands during high-entropy, damaged, or volatile regimes. Its color is determined by the RCM state: Green for bullish stability, Red for bearish, and Purple during transitions.
Siege Corridors : Plotted as horizontal support (Green) and resistance (Red) zones with an ATR-scaled boundary. At the right-hand side of the chart, these corridors display critical metrics: the total historical hit count, the estimated break probability (Pbreak), and the fail/reversal probability (Pfail).
Vector Field Lines : Small arrow-headed lines plotted on every third bar. They show the mathematical direction of the Fast momentum vector. They visually represent the difference between the actual observed path of the market and the expected parallel-transported baseline.
Holonomy Phase Ring : An indicator plotted at the right edge of the chart displaying the current phase angle (e.g., ◐ 144∘).
Glitch Markers: Flagged on the chart as ◈ GLITCH when anomalous pricing data or sudden coordinate jumps are detected on the manifold.
Dashboard: Displays real-time metric readings from all quantitative modules:
Tensor Metrics: Curvature, Entropy, Hurst Exponent, and Price Pressure.
Volatility: Dynamic DVS Ratio, active estimator method, and scaling state.
RCM Brain: State classification, integrity index, and gate permissions.
Performance: Total trades, win rate, total profit (R-multiple), profit factor, and max drawdown.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Limitations and Disclaimers
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
This tool is for analytical purposes only and does not predict future market direction.
Historical Simulation: The built-in simulator represents hypothetical performance on historical data. Past results do not guarantee future performance.
Volume Approximations: The synthetic footprint engine uses OHLCV approximations to estimate volume-at-price and directional delta. It is not an actual connection to L2 exchange data feeds or a central clearing book.
Persistence: Reinforcement learning weights are state-space variables that exist within the local execution thread; they reset to 1.0 on every chart load or browser reload.
— Dskyz. Trade with insight. Trade with anticipation. (It's lonely at the top) Indicator

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:
var1 = ta.variance(close - close , active_h_period)
varq = ta.variance(close - close , 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 ) ? close : kf + adaptive_gain * (close - kf )
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.
Indicator

Hurst Exponent Adaptive Filter (HEAF) [PhenLabs]📊 PhenLabs - Hurst Exponent Adaptive Filter (HEAF)
Version: PineScript™ v6
📌 Description
The Hurst Exponent Adaptive Filter (HEAF) is an advanced Pine Script indicator designed to dynamically adjust moving average calculations based on real time market regimes detected through the Hurst Exponent. The intention behind the creation of this indicator was not a buy/sell indicator but rather a tool to help sharpen traders ability to distinguish regimes in the market mathematically rather than guessing. By analyzing price persistence, it identifies whether the market is trending, mean-reverting, or exhibiting random walk behavior, automatically adapting the MA length to provide more responsive alerts in volatile conditions and smoother outputs in stable ones. This helps traders avoid false signals in choppy markets and capitalize on strong trends, making it ideal for adaptive trading strategies across various timeframes and assets.
Unlike traditional moving averages, HEAF incorporates fractal dimension analysis via the Hurst Exponent to create a self-tuning filter that evolves with market conditions. Traders benefit from visual cues like color coded regimes, adaptive bands for volatility channels, and an information panel that suggests appropriate strategies, enhancing decision making without constant manual adjustments by the user.
🚀 Points of Innovation
Dynamic MA length adjustment using Hurst Exponent for regime-aware filtering, reducing lag in trends and noise in ranges.
Integrated market regime classification (trending, mean-reverting, random) with visual and alert-based notifications.
Customizable color themes and adaptive bands that incorporate ATR for volatility-adjusted channels.
Built-in information panel providing real-time strategy recommendations based on detected regimes.
Power sensitivity parameter to fine-tune adaptation aggressiveness, allowing personalization for different trading styles.
Support for multiple MA types (EMA, SMA, WMA) within an adaptive framework.
🔧 Core Components
Hurst Exponent Calculation: Computes the fractal dimension of price series over a user-defined lookback to detect market persistence or anti-persistence.
Adaptive Length Mechanism: Maps Hurst values to MA lengths between minimum and maximum bounds, using a power function for sensitivity control.
Moving Average Engine: Applies the chosen MA type (EMA, SMA, or WMA) to the adaptive length for the core filter line.
Adaptive Bands: Creates upper and lower channels using ATR multiplied by a band factor, scaled to the current adaptive length.
Regime Detection: Classifies market state with thresholds (e.g., >0.55 for trending) and triggers alerts on regime changes.
Visualization System: Includes gradient fills, regime-colored MA lines, and an info panel for at-a-glance insights.
🔥 Key Features
Regime-Adaptive Filtering: Automatically shortens MA in mean-reverting markets for quick responses and lengthens it in trends for smoother signals, helping traders stay aligned with market dynamics.
Custom Alerts: Notifies on regime shifts and band breakouts, enabling timely strategy adjustments like switching to trend-following in bullish regimes.
Visual Enhancements: Color-coded MA lines, gradient band fills, and an optional info panel that displays market state and trading tips, improving chart readability.
Flexible Settings: Adjustable lookback, min/max lengths, sensitivity power, MA type, and themes to suit various assets and timeframes.
Band Breakout Signals: Highlights potential overbought/oversold conditions via ATR-based channels, useful for entry/exit timing.
🎨 Visualization
Main Adaptive MA Line: Plotted with regime-based colors (e.g., green for trending) to visually indicate market state and filter position relative to price.
Adaptive Bands: Upper and lower lines with gradient fills between them, showing volatility channels that widen in random regimes and tighten in trends.
Price vs. MA Fills: Color-coded areas between price and MA (e.g., bullish green above MA in trending modes) for quick trend strength assessment.
Information Panel: Top-right table displaying current regime (e.g., "Trending Market") and strategy suggestions like "Follow trends" or "Trade ranges."
📖 Usage Guidelines
Core Settings
Hurst Lookback Period
Default: 100
Range: 20-500
Description: Sets the period for Hurst Exponent calculation; longer values provide more stable regime detection but may lag, while shorter ones are more responsive to recent changes.
Minimum MA Length
Default: 10
Range: 5-50
Description: Defines the shortest possible adaptive MA length, ideal for fast responses in mean-reverting conditions.
Maximum MA Length
Default: 200
Range: 50-500
Description: Sets the longest adaptive MA length for smoothing in strong trends; adjust based on asset volatility.
Sensitivity Power
Default: 2.0
Range: 1.0-5.0
Description: Controls how aggressively the length adapts to Hurst changes; higher values make it more sensitive to regime shifts.
MA Type
Default: EMA
Options: EMA, SMA, WMA
Description: Chooses the moving average calculation method; EMA is more responsive, while SMA/WMA offer different weighting.
🖼️ Visual Settings
Show Adaptive Bands
Default: True
Description: Toggles visibility of upper/lower bands for volatility channels.
Band Multiplier
Default: 1.5
Range: 0.5-3.0
Description: Scales band width using ATR; higher values create wider channels for conservative signals.
Show Information Panel
Default: True
Description: Displays regime info and strategy tips in a top-right panel.
MA Line Width
Default: 2
Range: 1-5
Description: Adjusts thickness of the main MA line for better visibility.
Color Theme
Default: Blue
Options: Blue, Classic, Dark Purple, Vibrant
Description: Selects color scheme for MA, bands, and fills to match user preferences.
🚨 Alert Settings
Enable Alerts
Default: True
Description: Activates notifications for regime changes and band breakouts.
✅ Best Use Cases
Trend-Following Strategies: In detected trending regimes, use the adaptive MA as a trailing stop or entry filter for momentum trades.
Range Trading: During mean-reverting periods, monitor band breakouts for buying dips or selling rallies within channels.
Risk Management in Random Markets: Reduce exposure when random walk is detected, using tight stops suggested in the info panel.
Multi-Timeframe Analysis: Apply on higher timeframes for regime confirmation, then drill down to lower ones for entries.
Volatility-Based Entries: Use upper/lower band crossovers as signals in adaptive channels for overbought/oversold trades.
⚠️ Limitations
Lagging in Transitions: Regime detection may delay during rapid market shifts, requiring confirmation from other tools.
Not a Standalone System: Best used in conjunction with other indicators; random regimes can lead to whipsaws if traded aggressively.
Parameter Sensitivity: Optimal settings vary by asset and timeframe, necessitating backtesting.
💡 What Makes This Unique
Hurst-Driven Adaptation: Unlike static MAs, it uses fractal analysis to self-tune, providing regime-specific filtering that's rare in standard indicators.
Integrated Strategy Guidance: The info panel offers actionable tips tied to regimes, bridging analysis and execution.
Multi-Regime Visualization: Combines adaptive bands, colored fills, and alerts in one tool for comprehensive market state awareness.
🔬 How It Works
Hurst Exponent Computation:
Calculates log returns over the lookback period to derive the rescaled range (R/S) ratio.
Normalizes to a 0-1 value, where >0.55 indicates trending, <0.45 mean-reverting, and in-between random.
Length Adaptation:
Maps normalized Hurst to an MA length via a power function, clamping between min and max.
Applies the selected MA type to close prices using this dynamic length.
Visualization and Signals:
Plots the MA with regime colors, adds ATR-based bands, and fills areas for trend strength.
Triggers alerts on regime changes or band crosses, with the info panel suggesting strategies like momentum riding in trends.
💡 Note:
For optimal results, backtest settings on your preferred assets and combine with volume or momentum indicators. Remember, no indicator guarantees profits—use with proper risk management. Access premium features and support at PhenLabs. Indicator

Hurst Exponent Oscillator [PhenLabs]📊 Hurst Exponent Oscillator -
Version: PineScript™ v5
📌 Description
The Hurst Exponent Oscillator (HEO) by PhenLabs is a powerful tool developed for traders who want to distinguish between trending, mean-reverting, and random market behaviors with clarity and precision. By estimating the Hurst Exponent—a statistical measure of long-term memory in financial time series—this indicator helps users make sense of underlying market dynamics that are often not visible through traditional moving averages or oscillators.
Traders can quickly know if the market is likely to continue its current direction (trending), revert to the mean, or behave randomly, allowing for more strategic timing of entries and exits. With customizable smoothing and clear visual cues, the HEO enhances decision-making in a wide range of trading environments.
🚀 Points of Innovation
Integrates advanced Hurst Exponent calculation via Rescaled Range (R/S) analysis, providing unique market character insights.
Offers real-time visual cues for trending, mean-reverting, or random price action zones.
User-controllable EMA smoothing reduces noise for clearer interpretation.
Dynamic coloring and fill for immediate visual categorization of market regime.
Configurable visual thresholds for critical Hurst levels (e.g., 0.4, 0.5, 0.6).
Fully customizable appearance settings to fit different charting preferences.
🔧 Core Components
Log Returns Calculation: Computes log returns of the selected price source to feed into the Hurst calculation, ensuring robust and scale-independent analysis.
Rescaled Range (R/S) Analysis: Assesses the dispersion and cumulative deviation over a rolling window, forming the core statistical basis for the Hurst exponent estimate.
Smoothing Engine: Applies Exponential Moving Average (EMA) smoothing to the raw Hurst value for enhanced clarity.
Dynamic Rolling Windows: Utilizes arrays to maintain efficient, real-time calculations over user-defined lengths.
Adaptive Color Logic: Assigns different highlight and fill colors based on the current Hurst value zone.
🔥 Key Features
Visually differentiates between trending, mean-reverting, and random market modes.
User-adjustable lookback and smoothing periods for tailored sensitivity.
Distinct fill and line styles for each regime to avoid ambiguity.
On-chart reference lines for strong trending and mean-reverting thresholds.
Works with any price series (close, open, HL2, etc.) for versatile application.
🎨 Visualization
Hurst Exponent Curve: Primary plotted line (smoothed if EMA is used) reflects the ongoing estimate of the Hurst exponent.
Colored Zone Filling: The area between the Hurst line and the 0.5 reference line is filled, with color and opacity dynamically indicating the current market regime.
Reference Lines: Dash/dot lines mark standard Hurst thresholds (0.4, 0.5, 0.6) to contextualize the current regime.
All visual elements can be customized for thickness, color intensity, and opacity for user preference.
📖 Usage Guidelines
Data Settings
Hurst Calculation Length
Default: 100
Range: 10-300
Description: Number of bars used in Hurst calculation; higher values mean longer-term analysis, lower values for quicker reaction.
Data Source
Default: close
Description: Select which data series to analyze (e.g., Close, Open, HL2).
Smoothing Length (EMA)
Default: 5
Range: 1-50
Description: Length for smoothing the Hurst value; higher settings yield smoother but less responsive results.
Style Settings
Trending Color (Hurst > 0.5)
Default: Blue tone
Description: Color used when trending regime is detected.
Mean-Reverting Color (Hurst < 0.5)
Default: Orange tone
Description: Color used when mean-reverting regime is detected.
Neutral/Random Color
Default: Soft blue
Description: Color when market behavior is indeterminate or shifting.
Fill Opacity
Default: 70-80
Range: 0-100
Description: Transparency of area fills—higher opacity for stronger visual effect.
Line Width
Default: 2
Range: 1-5
Description: Thickness of the main indicator curve.
✅ Best Use Cases
Identifying if a market is regime-shifting from trending to mean-reverting (or vice versa).
Filtering signals in automated or systematic trading strategies.
Spotting periods of randomness where trading signals should be deprioritized.
Enhancing mean-reversion or trend-following models with regime-awareness.
⚠️ Limitations
Not predictive: Reflects current and recent market state, not future direction.
Sensitive to input parameters—overfitting may occur if settings are changed too frequently.
Smoothing can introduce lag in regime recognition.
May not work optimally in markets with structural breaks or extreme volatility.
💡 What Makes This Unique
Employs advanced statistical market analysis (Hurst exponent) rarely found in standard toolkits.
Offers immediate regime visualization through smart dynamic coloring and zone fills.
🔬 How It Works
Rolling Log Return Calculation:
Each new price creates a log return, forming the basis for robust, non-linear analysis. This ensures all price differences are treated proportionally.
Rescaled Range Analysis:
A rolling window maintains cumulative deviations and computes the statistical “range” (max-min of deviations). This is compared against the standard deviation to estimate “memory”.
Exponent Calculation & Smoothing:
The raw Hurst value is translated from the log of the rescaled range ratio, and then optionally smoothed via EMA to dampen noise and false signals.
Regime Detection Logic:
The smoothed value is checked against 0.5. Values above = trending; below = mean-reverting; near 0.5 = random. These control plot/fill color and zone display.
💡 Note:
Use longer calculation lengths for major market character study, and shorter ones for tactical, short-term adaptation. Smoothing balances noise vs. lag—find a best fit for your trading style. Always combine regime awareness with broader technical/fundamental context for best results. Indicator

Advanced Fractal and Hurst IndicatorAdvanced Fractal and Hurst Indicator (AFHI)
Description:
The Advanced Fractal and Hurst Indicator (AFHI) is a custom technical analysis tool designed to identify market trends and potential reversals by leveraging the concepts of Fractal Dimension and the Hurst Exponent . These advanced mathematical concepts provide insights into the complexity and persistence of price movements, making this indicator a powerful addition to any trader's toolkit.
How It Works:
Fractal Dimension (FD) :
The Fractal Dimension measures the complexity of price movements. A higher Fractal Dimension indicates a more complex, choppy market, while a lower value suggests smoother trends.
The FD is calculated using the log difference of price movements over a specified length.
Hurst Exponent (HE) :
The Hurst Exponent indicates the tendency of a time series to either regress to the mean or cluster in a direction. Values below 0.5 indicate a tendency to revert to the mean (mean-reverting), while values above 0.5 suggest a trending market.
The HE is calculated using the rescaled range method, comparing the range of price movements to the standard deviation.
Composite Indicator :
The Composite Indicator combines the smoothed Fractal Dimension and Hurst Exponent to provide a single value indicating market conditions. This is done by normalizing the FD and HE values and combining them into one metric.
A positive Composite Indicator suggests an uptrend, while a negative value indicates a downtrend.
Smoothing :
Both FD and HE values are smoothed using a simple moving average to reduce noise and provide clearer signals.
Trend Confirmation :
A 50-period moving average (MA) is used to confirm the trend direction. The price being above the MA indicates an uptrend, while below the MA indicates a downtrend.
Background Shading :
The indicator pane is shaded green during uptrend conditions (positive Composite Indicator and price above MA) and red during downtrend conditions (negative Composite Indicator and price below MA).
How Traders Can Use It:
Identifying Trends :
Traders can use the AFHI to identify current market trends. The background shading in the indicator pane provides a visual cue for trend direction, with green indicating an uptrend and red indicating a downtrend.
Trend Confirmation :
The Composite Indicator line, plotted in purple, helps confirm the trend. Positive values suggest a strong uptrend, while negative values indicate a strong downtrend.
Entry and Exit Signals :
Traders can use the transitions of the Composite Indicator and the background shading to time their entry and exit points. For instance, a shift from red to green shading suggests a potential buy opportunity, while a shift from green to red suggests a potential sell opportunity.
Alerts :
The script includes alert conditions that can notify traders when the Composite Indicator signals a new trend direction. Alerts can be set up for both uptrends and downtrends, helping traders stay informed of key market changes.
Strategy Development :
By integrating AFHI into their trading strategies, traders can develop more robust systems that account for market complexity and persistence. The indicator can be used alongside other technical tools to enhance decision-making and improve trade accuracy.
Indicator

Hurst Exponent (Dubuc's variation method)Library "Hurst"
hurst(length, samples, hi, lo)
Estimate the Hurst Exponent using Dubuc's variation method
Parameters:
length : The length of the history window to use. Large values do not cause lag.
samples : The number of scale samples to take within the window. These samples are then used for regression. The minimum value is 2 but 3+ is recommended. Large values give more accurate results but suffer from a performance penalty.
hi : The high value of the series to analyze.
lo : The low value of the series to analyze.
The Hurst Exponent is a measure of fractal dimension, and in the context of time series it may be interpreted as indicating a mean-reverting market if the value is below 0.5 or a trending market if the value is above 0.5. A value of exactly 0.5 corresponds to a random walk.
There are many definitions of fractal dimension and many methods for its estimation. Approaches relying on calculation of an area, such as the Box Counting Method, are inappropriate for time series data, because the units of the x-axis (time) do match the units of the y-axis (price). Other approaches such as Detrended Fluctuation Analysis are useful for nonstationary time series but are not exactly equivalent to the Hurst Exponent.
This library implements Dubuc's variation method for estimating the Hurst Exponent. The technique is insensitive to x-axis units and is therefore useful for time series. It will give slightly different results to DFA, and the two methods should be compared to see which estimator fits your trading objectives best.
Original Paper:
Dubuc B, Quiniou JF, Roques-Carmes C, Tricot C. Evaluating the fractal dimension of profiles. Physical Review A. 1989;39(3):1500-1512. DOI: 10.1103/PhysRevA.39.1500
Review of various Hurst Exponent estimators for time-series data, including Dubuc's method:
www.intechopen.com
Library

HurstExponentLibrary "HurstExponent"
Library to calculate Hurst Exponent refactored from Hurst Exponent - Detrended Fluctuation Analysis
demean(src) Calculates a series subtracted from the series mean.
Parameters:
src : The series used to calculate the difference from the mean (e.g. log returns).
Returns: The series subtracted from the series mean
cumsum(src, length) Calculates a cumulated sum from the series.
Parameters:
src : The series used to calculate the cumulative sum (e.g. demeaned log returns).
length : The length used to calculate the cumulative sum (e.g. 100).
Returns: The cumulative sum of the series as an array
aproximateLogScale(scale, length) Calculates an aproximated log scale. Used to save sample size
Parameters:
scale : The scale to aproximate.
length : The length used to aproximate the expected scale.
Returns: The aproximated log scale of the value
rootMeanSum(cumulativeSum, barId, numberOfSegments) Calculates linear trend to determine error between linear trend and cumulative sum
Parameters:
cumulativeSum : The cumulative sum array to regress.
barId : The barId for the slice
numberOfSegments : The total number of segments used for the regression calculation
Returns: The error between linear trend and cumulative sum
averageRootMeanSum(cumulativeSum, barId, length) Calculates the Root Mean Sum Measured for each block (e.g the aproximated log scale)
Parameters:
cumulativeSum : The cumulative sum array to regress and determine the average of.
barId : The barId for the slice
length : The length used for finding the average
Returns: The average root mean sum error of the cumulativeSum
criticalValues(length) Calculates the critical values for a hurst exponent for a given length
Parameters:
length : The length used for finding the average
Returns: The critical value, upper critical value and lower critical value for a hurst exponent
slope(cumulativeSum, length) Calculates the hurst exponent slope measured from root mean sum, scaled to log log plot using linear regression
Parameters:
cumulativeSum : The cumulative sum array to regress and determine the average of.
length : The length used for the hurst exponent sample size
Returns: The slope of the hurst exponent
smooth(src, length) Smooths input using advanced linear regression
Parameters:
src : The series to smooth (e.g. hurst exponent slope)
length : The length used to smooth
Returns: The src smoothed according to the given length
exponent(src, hurstLength) Wrapper function to calculate the hurst exponent slope
Parameters:
src : The series used for returns calculation (e.g. close)
hurstLength : The length used to calculate the hurst exponent (should be greater than 50)
Returns: The src smoothed according to the given length Library

Indicator

Indicator

Indicator
