PROTECTED SOURCE SCRIPT

Adaptive Mean Reversion

57
ADAPTIVE MEAN REVERSION
═══════════════════════════════════════════════════════════════════════════════
INTRODUCTION

The Adaptive Mean Reversion indicator represents a comprehensive approach to identifying potential reversal opportunities in financial markets. Unlike traditional mean reversion systems that rely on fixed parameters, this indicator dynamically adjusts its entry thresholds based on the historical behavior of each specific instrument. This adaptive methodology allows the indicator to calibrate itself to the unique volatility characteristics of any market, whether trading cryptocurrencies, forex pairs, equities, or commodities.

The core innovation lies in how the indicator learns from price action.

Rather than assuming a one-size-fits-all approach where the same ATR multiplier works across all instruments and timeframes, this system continuously measures how far price typically extends beyond established trading ranges. Over time, it builds a statistical profile of penetration depths and uses this information to set intelligent entry levels that reflect actual market behavior rather than arbitrary fixed values.
Beyond the adaptive threshold mechanism, the indicator incorporates multiple advanced features including Fisher-RSI transformation for cleaner momentum signals, regime detection based on directional movement and volume flow, divergence identification for spotting potential reversals, extreme exit conditions for capturing overbought peaks, and comprehensive position management with cascade protection. These features combine to create a complete mean reversion framework rather than a simple signal generator.

═══════════════════════════════════════════════════════════════════════════════

HOW THE INDICATOR WORKS

The foundation of this indicator begins with the Donchian Channel, a well-established technical tool developed by Richard Donchian that identifies the highest high and lowest low over a specified lookback period. This channel defines the recent trading range and serves as the baseline from which extended price movements are measured. The channel is shifted by one bar to prevent any lookahead bias in the calculations.
When price touches or penetrates these Donchian boundaries, the indicator records the depth of penetration normalized by the Average True Range. This normalization is critical because it allows meaningful comparison across different price levels and volatility regimes. A ten-dollar move means something very different on a stock trading at fifty dollars versus one trading at five hundred dollars, but expressing that move as a fraction of ATR creates a universal measurement.

The indicator maintains rolling arrays of these penetration measurements, separately tracking buy-side penetrations below the lower band and sell-side penetrations above the upper band. Once sufficient samples have been collected, the system calculates the average penetration depth and uses this value to establish adaptive entry thresholds. A sensitivity parameter allows traders to fine-tune how aggressively these learned thresholds translate into entry levels.

The resulting entry levels appear on the chart as dynamic bands that float below the Donchian lower boundary for potential buy zones and above the Donchian upper boundary for potential sell zones. These bands expand and contract based on the learned volatility behavior, automatically becoming more permissive in markets that tend to produce deeper penetrations and more restrictive in markets that reverse quickly after touching the channel.

═══════════════════════════════════════════════════════════════════════════════

SIGNAL FILTERING METHODOLOGY

Raw price touches of the adaptive entry levels do not automatically generate signals. The indicator employs multiple confirmation filters derived from established technical analysis research to improve signal quality and reduce false positives.
The momentum filter offers two modes of operation. Classic RSI mode uses the traditional Relative Strength Index developed by J. Welles Wilder, requiring oversold readings for buy signals and overbought readings for sell signals. Alternatively, the Fisher-RSI transformation applies John Ehlers' Fisher Transform to the RSI values, creating a more normally distributed signal that provides cleaner threshold crossings and reduces the lag inherent in standard RSI. The Fisher transformation stretches values near extremes and compresses values near the center, making overbought and oversold conditions more distinct and actionable.

The Average Directional Index provides trend strength confirmation with both minimum and maximum thresholds. The minimum ADX requirement ensures sufficient directional movement for meaningful reversal points. The maximum ADX threshold is equally important for mean reversion strategies, as extremely high ADX readings indicate powerful trends where counter-trend entries consistently fail. By capping ADX at a configurable maximum, the indicator avoids generating signals in markets where mean reversion is unlikely to succeed.
An optional Bollinger Band Width Percentile filter adds a volatility regime component to the signal logic. This filter calculates the current Bollinger Band width as a percentile of its historical range, effectively measuring whether current volatility is high, low, or average relative to recent history. Requiring a minimum BBWP value prevents signals during periods of abnormally compressed volatility, which often precede breakouts rather than reversions.

═══════════════════════════════════════════════════════════════════════════════

REGIME DETECTION AND VISUALIZATION

The indicator incorporates market regime detection to provide contextual awareness beyond simple signal generation. Regime classification uses a combination of directional movement analysis and volume confirmation through On Balance Volume.
A bullish regime is identified when the positive directional indicator exceeds the negative directional indicator, OBV trends above its moving average indicating accumulation, and ADX confirms sufficient trend strength. Bearish regimes require the opposite conditions with negative directional movement dominant and OBV below average indicating distribution. Neutral regimes occur when these conditions are mixed or trend strength is insufficient.

The Donchian channel fill color reflects the current regime, providing immediate visual feedback on market state. Green shading indicates bullish conditions favorable to long entries, pink or red shading indicates bearish conditions where caution on long positions is warranted, and blue shading represents neutral or transitional states. When the band contraction filter detects abnormally narrow channels, orange shading warns that breakout conditions may be developing and mean reversion signals are suspended.

This regime overlay transforms the indicator from a pure signal generator into a contextual analysis tool. Even when no signals are actively triggering, the regime shading provides valuable information about the broader market environment.

═══════════════════════════════════════════════════════════════════════════════

DIVERGENCE DETECTION

The indicator includes built-in divergence detection to identify potential reversal setups where price and momentum disagree. Divergences often precede significant turning points and provide early warning of trend exhaustion.

Bullish divergence occurs when price makes lower lows while RSI makes higher lows. This pattern suggests that despite falling prices, selling pressure is diminishing and buyers may be stepping in at progressively higher momentum levels. The indicator marks bullish divergences with cyan triangle markers below the price bars, drawing attention to potential long entry opportunities.

Bearish divergence occurs when price makes higher highs while RSI makes lower highs. This pattern indicates that despite rising prices, buying momentum is waning and the uptrend may be losing steam. Magenta triangle markers appear above price bars when bearish divergences are detected, warning of potential trend exhaustion even as price continues higher.

The divergence lookback parameter controls how many bars the indicator examines when comparing price and RSI patterns. Shorter lookbacks detect more frequent but potentially less significant divergences, while longer lookbacks identify more substantial divergence patterns that may signal larger reversals.
═══════════════════════════════════════════════════════════════════════════════

EXTREME EXIT FUNCTIONALITY

Mean reversion strategies face a particular challenge when prices enter parabolic moves. Standard sell signals require multiple filter conditions to align, which may not happen quickly enough during explosive rallies. The extreme sell feature addresses this by providing an emergency exit mechanism when RSI reaches extremely overbought levels.

When RSI exceeds the extreme threshold, typically set around 85 or higher, the indicator triggers a sell signal regardless of other filter conditions. This allows positions to capture profits during euphoric price spikes that often reverse sharply. The extreme sell has its own independent cooldown to prevent rapid repeated triggers during volatile conditions.

Importantly, extreme sells are designed as profit-taking exits only and do not reset the cascade counter. This distinction matters because the cascade system tracks position building during normal market conditions. An extreme sell takes profits during an unusual spike but acknowledges that the underlying mean reversion logic may still be valid for the position being built.

A safety check ensures extreme sells only trigger when price is at or above the upper Donchian band, or when ADX confirms sufficient trend strength. This prevents the extreme sell from triggering during conditions where it might exit a position prematurely before the actual price spike occurs.
═══════════════════════════════════════════════════════════════════════════════

POSITION MANAGEMENT FEATURES

The indicator includes built-in logic to manage signal frequency and prevent overtrading. A cooldown parameter establishes the minimum number of bars that must pass between consecutive signals, preventing rapid-fire entries during volatile periods when price may whipsaw through entry levels multiple times.

The cascade management system tracks consecutive buy signals and enforces a maximum limit before requiring a sell signal to reset the counter. This feature supports dollar-cost averaging strategies while preventing unlimited position accumulation. When the cascade limit is reached, the indicator blocks further buy signals until a sell occurs, protecting against runaway position building in trending markets. The current cascade count displays prominently in signal labels and the information table, providing clear visibility into position building status.

The band contraction filter provides additional protection against false signals during consolidation periods. When enabled, this filter measures the current Donchian channel width as a percentile of its historical range. Abnormally narrow channels often indicate impending breakouts rather than mean reversion opportunities. When channel width falls below the contraction threshold percentile, all signals are blocked and the channel fill color changes to orange as a visual warning. This prevents entries just before volatility expansion that could move strongly against mean reversion positions.

For informational purposes, the indicator tracks a theoretical average entry price calculated from accumulated buy signals. This value resets when a sell signal fires, allowing traders to see at a glance what their average cost basis would be if following the signals mechanically. The information table colors the average price display green when current price is above average cost or red when below, providing instant profitability feedback.
═══════════════════════════════════════════════════════════════════════════════

VISUAL COMPONENTS

The chart overlay displays multiple layers of information to support decision-making. The Donchian Channel appears as stepped lines showing the upper boundary and lower boundary of the recent trading range. The adaptive entry levels plot as distinct colored bands below and above the channel, making it immediately clear where price must reach to trigger potential signals.

The channel fill color provides instant regime feedback. Green shading indicates bullish conditions with positive directional movement and accumulation. Pink or red shading indicates bearish conditions with negative directional movement and distribution. Blue shading represents neutral or transitional states. Orange shading warns of band contraction when signals are suspended due to abnormally narrow channel width.
Two indicator bars provide at-a-glance status of the momentum and trend filters. The RSI bar appears at the top of the chart using a color gradient that adapts to whether Fisher-RSI or classic RSI mode is active, progressing from deep green in oversold territory through neutral gray to deep red in overbought conditions. The ADX bar appears at the bottom, progressing through colors that indicate trend strength from very weak to strong.

Divergence markers appear as small triangles when enabled. Cyan upward triangles below bars indicate bullish divergence where price is making lower lows but RSI is making higher lows. Magenta downward triangles above bars indicate bearish divergence where price is making higher highs but RSI is making lower highs.

Signal labels appear directly on the chart when buy, sell, or extreme sell conditions trigger, displaying the signal type and execution price. Label size is configurable to match chart preferences.

The information table consolidates all indicator status into a compact display. The header row shows the current regime with color-coded background. Subsequent rows display the calculation method, trade availability status, cascade counter with warning indicators, average entry price with profit or loss coloring, position status, RSI or Fisher values with threshold comparison, ADX with range display, BBWP percentile, and divergence status. Color coding throughout the table provides immediate feedback on whether conditions are favorable for signals, with warning symbols highlighting any blocking conditions.

═══════════════════════════════════════════════════════════════════════════════

WHAT MAKES THIS INDICATOR UNIQUE

The primary differentiator of this indicator is its self-calibrating nature. Most mean reversion indicators require traders to manually optimize parameters for each instrument and timeframe, a time-consuming process that often leads to curve-fitting. This indicator sidesteps that problem by learning appropriate thresholds directly from market data.

The deterministic adaptive mechanism ensures consistency between what appears on the chart and what triggers alerts. By calculating penetration statistics from a fixed historical window on each bar rather than accumulating samples indefinitely, the indicator produces identical results whether viewed in a browser or processed by the alert server. This technical detail matters enormously for traders who rely on automated alerts matching their chart analysis.

The dual-mode momentum filter with Fisher-RSI transformation provides cleaner signal generation than standard RSI alone. The Fisher Transform normalizes the distribution of RSI values, creating sharper threshold crossings and reducing the common problem of RSI hovering near extreme levels without producing actionable signals.

Regime detection transforms this from a pure signal generator into a contextual analysis tool. The bull, bear, and neutral regime classifications combine directional movement and volume flow analysis to provide broader market context. Even between signals, the regime-shaded channel fill offers valuable information about favorable or unfavorable conditions for mean reversion entries.

The divergence detection module identifies potential reversals before they occur by spotting disagreements between price and momentum. These early warning signals complement the main entry logic and help traders anticipate turning points rather than react to them.

The extreme exit mechanism addresses a specific weakness of mean reversion strategies during parabolic moves. By providing an emergency profit-taking exit when RSI reaches extreme levels, the indicator captures gains during euphoric spikes that often reverse violently.

The comprehensive position management features including cascade protection, band contraction filtering, and cooldown controls transform this from a simple signal generator into a complete trading framework. These features provide the scaffolding needed to build systematic trading approaches around the core signal logic.
═══════════════════════════════════════════════════════════════════════════════

APPROPRIATE USE CASES

This indicator performs best in markets that exhibit mean-reverting behavior, where prices tend to oscillate around a central value rather than trending persistently in one direction. Range-bound markets, consolidation periods, and instruments with natural mean-reversion characteristics provide the most favorable conditions.

Traders should exercise caution during strong trending markets where mean reversion signals may repeatedly trigger against the prevailing trend direction. The ADX filter provides some protection against this scenario, but no filter system is perfect. Combining this indicator with broader market regime analysis can help identify periods when mean reversion strategies are more or less likely to succeed.

The indicator works across all timeframes, though the adaptive learning mechanism requires sufficient historical data to populate the penetration sample arrays. New charts or very high timeframes with limited bar history may initially use default multiplier values until enough samples accumulate. The information table displays current sample counts so traders can verify when adaptive thresholds have fully calibrated.
═══════════════════════════════════════════════════════════════════════════════

RISK DISCLAIMER AND EDUCATIONAL PURPOSE

This indicator is provided for educational and informational purposes only. It is designed to illustrate concepts in adaptive threshold calculation, multi-factor signal filtering, and position management logic. The indicator does not constitute financial advice and should not be used as the sole basis for trading decisions.

Past performance of any trading system or methodology is not necessarily indicative of future results. All trading involves substantial risk of loss and is not suitable for all investors. Before using any indicator or trading system with real capital, traders should thoroughly backtest across multiple market conditions, account for realistic transaction costs and slippage, and ensure proper position sizing relative to account size and risk tolerance.

The technical analysis concepts employed in this indicator draw upon the foundational work of Richard Donchian in channel breakout methodology, J. Welles Wilder in the development of the Relative Strength Index, Average True Range, and Average Directional Index, John Ehlers in the application of Fisher Transform to oscillators, Joseph Granville in the development of On Balance Volume for accumulation and distribution analysis, and John Bollinger in Bollinger Band analysis. These well-established technical tools have been combined and extended with adaptive threshold logic, regime detection, and divergence analysis to create the methodology presented here.
═══════════════════════════════════════════════════════════════════════════════

SETTINGS OVERVIEW

The Channel Settings section controls the Donchian length parameter that determines the lookback period for highest high and lowest low calculations. This establishes the baseline trading range from which extensions are measured.

Adaptive Threshold Settings govern the self-calibrating mechanism. The calculation method can use either average or percentile-based approaches for processing penetration samples. The lookback parameter determines how many band touches are analyzed. Minimum and maximum multiplier values establish bounds for the adaptive calculation, preventing extreme values. The minimum samples setting ensures sufficient data before adaptive thresholds activate. Traders can disable adaptive mode entirely to use a fixed multiplier if preferred.

Momentum Filter Settings control the RSI-based signal confirmation. The Fisher-RSI toggle switches between classic RSI and Fisher-transformed RSI. Separate thresholds exist for each mode, allowing precise calibration of oversold and overbought levels.

Trend and Volatility Filters include ATR length for volatility measurement, ADX settings with both minimum and maximum thresholds, and the optional BBWP filter with its own length and lookback parameters. The signal cooldown setting prevents rapid repeated signals.

Position Management parameters set the cascade protection limit for consecutive buys and the optional band contraction filter with its lookback and threshold settings.

Extreme Exit Settings configure the emergency profit-taking mechanism including the extreme RSI threshold, independent cooldown period, and alert toggle.

Divergence Detection settings enable or disable the divergence scanner, set the lookback period for pattern identification, and toggle the display of divergence markers on the chart.
Alert Settings provide toggles for buy, sell, and extreme sell alert notifications.

Display Settings offer comprehensive control over visual elements including channel visibility, signal labels, information table position, ADX and RSI indicator bars, and adaptive level lines.

The ADX Bar and RSI Bar sections provide granular control over the color-coded indicator bars with customizable threshold levels and colors. Level and Channel Colors allow customization of entry level colors and line widths. Regime Shading settings control the channel fill colors for bull, bear, neutral, and contracted market states.

Pernyataan Penyangkalan

Informasi dan publikasi ini tidak dimaksudkan, dan bukan merupakan, saran atau rekomendasi keuangan, investasi, trading, atau jenis lainnya yang diberikan atau didukung oleh TradingView. Baca selengkapnya di Ketentuan Penggunaan.