OPEN-SOURCE SCRIPT
Regime Engine

Regime Engine
Overview
Regime Engine is a market regime detection system that classifies price action into bullish, bearish, or neutral states using weighted exponential moving average analysis. Once the regime is identified, the indicator generates buy and sell signals based on Donchian channel breakouts, filtered by ADX trend strength and RSI momentum conditions.
The Money Line
The core of regime detection is the Money Line, a weighted combination of two exponential moving averages. By default, the short EMA (8 periods) receives 60% weight while the long EMA (24 periods) receives 40% weight. This weighting allows the Money Line to be more responsive than a simple long-period average while remaining smoother than a short-period average alone.
The Money Line changes color based on the current regime: green for bullish, red for bearish, and yellow for neutral. This provides immediate visual feedback about the market state.
Regime Classification
The indicator determines market regime by comparing the relative positions of the short and long EMAs while also considering RSI levels to avoid classifying overbought or oversold conditions as trend states.
Bullish regime is identified when the short EMA is above the long EMA and RSI is not in overbought territory. This combination suggests upward momentum that is not yet exhausted.
Bearish regime is identified when the short EMA is below the long EMA and RSI is not in oversold territory. This indicates downward momentum with room to continue.
Neutral regime applies when the EMAs are close together or RSI conditions prevent trend classification. The indicator provides two optional methods for enhanced neutral detection.
Neutral Zone Detection
Markets often transition through periods where trend direction is unclear. The indicator offers two complementary methods for detecting these neutral zones.
The slope method examines the rate of change of the Money Line relative to ATR. When the Money Line is moving slowly (slope below a tolerance threshold), the market is classified as neutral regardless of EMA positioning.
The EMA distance method calculates the percentage distance between the short and long EMAs. When they are within a specified percentage of each other, the EMAs are considered too close to reliably indicate direction.
Either or both methods can be enabled, and if either triggers, the regime is classified as neutral.
Donchian Channel Signals
Buy and sell signals are generated when price interacts with the Donchian channel boundaries. The Donchian channel plots the highest high and lowest low over a lookback period (default 20 bars), offset by one bar to prevent repainting.
Buy signals trigger when price touches or breaks below the lower Donchian band, indicating a potential support level. Sell signals trigger when price touches or breaks above the upper Donchian band, indicating potential resistance.
An optional setting requires the close to confirm the break rather than just the wick, providing more conservative signal generation.
ADX Trend Strength Filter
The Average Directional Index filters signals to ensure they occur during trending conditions. When enabled, signals only fire if ADX exceeds the threshold (default 24), confirming that the market has sufficient directional momentum for breakout trades to succeed.
The indicator uses Wilder's original smoothing method for ADX calculation, providing the traditional interpretation of trend strength values.
RSI Momentum Filter
RSI provides additional signal filtering to ensure entries occur at favorable momentum levels. Buy signals require RSI to be at or below the oversold threshold (default 30), indicating potential exhaustion of selling pressure. Sell signals require RSI to be at or above the overbought threshold (default 70), suggesting exhaustion of buying pressure.
These filters can be disabled for traders who prefer unfiltered Donchian breakout signals.
BBWP Volatility Monitoring
Bollinger Band Width Percentile measures current volatility relative to its historical range. The indicator calculates BB width and ranks it against the specified lookback period (default 252 bars, approximately one trading year).
BBWP above 70% indicates elevated volatility, which may signal trend acceleration or potential reversals. BBWP below 30% indicates compressed volatility, often preceding significant moves. The information panel displays the current BBWP reading with color coding to highlight these conditions.
Signal Cooldown
To prevent signal clustering during extended breakout periods, a configurable cooldown prevents new signals of the same type for a specified number of bars after each signal. This ensures each signal represents a distinct trading opportunity.
Visual Components
The Donchian channel can display shaded bands between the upper and lower boundaries. The shading color reflects the current regime: green for bullish, magenta for bearish, and blue for neutral. This provides at-a-glance context for where price is trading within its recent range.
An ADX strength bar at the bottom of the chart uses color coding: white for weak trend (ADX below 15), orange for ranging (ADX 15-24), and blue for trending (ADX above 24). This matches the trend strength display in the information panel.
Price labels appear at signal locations showing the signal type and entry price. Labels are automatically cleaned up after reaching a configurable history limit to maintain chart performance.
Signal candles are highlighted in blue, making it easy to identify exactly which bars generated signals when reviewing historical performance.
Information Panel
A compact table displays key metrics: current regime bias, trend strength classification, BBWP volatility reading, RSI level, and ADX value. Each metric is color-coded to highlight favorable or unfavorable conditions.
The panel can be positioned at any corner or middle edge of the chart. An alternative label-based display anchored to the chart is also available for those who prefer that format.
Trend Persistence Option
By default, the regime is recalculated on every bar. An optional persistence mode changes this behavior so that the regime only changes on EMA crossovers. This reduces regime flipping during choppy conditions but may delay regime recognition during gradual trend changes.
How to Use
Monitor the Money Line color and information panel for current regime. In bullish regimes, focus on buy signals at the lower Donchian band as potential pullback entries. In bearish regimes, focus on sell signals at the upper band as potential short entries or exit points.
Use the ADX strength indicator to gauge signal reliability. Signals during trending conditions (blue ADX bar) have historically higher success rates than signals during ranging conditions (orange bar) or weak trends (white bar).
Watch BBWP for volatility context. Low BBWP readings suggest a significant move may be developing, while high readings indicate the current move may be overextended.
The combination of regime awareness, Donchian breakout signals, and ADX/RSI filtering provides a structured approach to identifying trading opportunities across different market conditions.
Settings Guidance
The default settings work well for cryptocurrency and forex markets on intraday timeframes. For stocks or longer timeframes, consider increasing the EMA periods and Donchian lookback. The ADX threshold can be adjusted based on the typical ADX range for the traded instrument.
The RSI filter levels can be relaxed (higher oversold, lower overbought) for more signals or tightened for higher-quality but less frequent signals. The cooldown period should be adjusted based on timeframe, with shorter timeframes typically requiring longer cooldown periods.
Overview
Regime Engine is a market regime detection system that classifies price action into bullish, bearish, or neutral states using weighted exponential moving average analysis. Once the regime is identified, the indicator generates buy and sell signals based on Donchian channel breakouts, filtered by ADX trend strength and RSI momentum conditions.
The Money Line
The core of regime detection is the Money Line, a weighted combination of two exponential moving averages. By default, the short EMA (8 periods) receives 60% weight while the long EMA (24 periods) receives 40% weight. This weighting allows the Money Line to be more responsive than a simple long-period average while remaining smoother than a short-period average alone.
The Money Line changes color based on the current regime: green for bullish, red for bearish, and yellow for neutral. This provides immediate visual feedback about the market state.
Regime Classification
The indicator determines market regime by comparing the relative positions of the short and long EMAs while also considering RSI levels to avoid classifying overbought or oversold conditions as trend states.
Bullish regime is identified when the short EMA is above the long EMA and RSI is not in overbought territory. This combination suggests upward momentum that is not yet exhausted.
Bearish regime is identified when the short EMA is below the long EMA and RSI is not in oversold territory. This indicates downward momentum with room to continue.
Neutral regime applies when the EMAs are close together or RSI conditions prevent trend classification. The indicator provides two optional methods for enhanced neutral detection.
Neutral Zone Detection
Markets often transition through periods where trend direction is unclear. The indicator offers two complementary methods for detecting these neutral zones.
The slope method examines the rate of change of the Money Line relative to ATR. When the Money Line is moving slowly (slope below a tolerance threshold), the market is classified as neutral regardless of EMA positioning.
The EMA distance method calculates the percentage distance between the short and long EMAs. When they are within a specified percentage of each other, the EMAs are considered too close to reliably indicate direction.
Either or both methods can be enabled, and if either triggers, the regime is classified as neutral.
Donchian Channel Signals
Buy and sell signals are generated when price interacts with the Donchian channel boundaries. The Donchian channel plots the highest high and lowest low over a lookback period (default 20 bars), offset by one bar to prevent repainting.
Buy signals trigger when price touches or breaks below the lower Donchian band, indicating a potential support level. Sell signals trigger when price touches or breaks above the upper Donchian band, indicating potential resistance.
An optional setting requires the close to confirm the break rather than just the wick, providing more conservative signal generation.
ADX Trend Strength Filter
The Average Directional Index filters signals to ensure they occur during trending conditions. When enabled, signals only fire if ADX exceeds the threshold (default 24), confirming that the market has sufficient directional momentum for breakout trades to succeed.
The indicator uses Wilder's original smoothing method for ADX calculation, providing the traditional interpretation of trend strength values.
RSI Momentum Filter
RSI provides additional signal filtering to ensure entries occur at favorable momentum levels. Buy signals require RSI to be at or below the oversold threshold (default 30), indicating potential exhaustion of selling pressure. Sell signals require RSI to be at or above the overbought threshold (default 70), suggesting exhaustion of buying pressure.
These filters can be disabled for traders who prefer unfiltered Donchian breakout signals.
BBWP Volatility Monitoring
Bollinger Band Width Percentile measures current volatility relative to its historical range. The indicator calculates BB width and ranks it against the specified lookback period (default 252 bars, approximately one trading year).
BBWP above 70% indicates elevated volatility, which may signal trend acceleration or potential reversals. BBWP below 30% indicates compressed volatility, often preceding significant moves. The information panel displays the current BBWP reading with color coding to highlight these conditions.
Signal Cooldown
To prevent signal clustering during extended breakout periods, a configurable cooldown prevents new signals of the same type for a specified number of bars after each signal. This ensures each signal represents a distinct trading opportunity.
Visual Components
The Donchian channel can display shaded bands between the upper and lower boundaries. The shading color reflects the current regime: green for bullish, magenta for bearish, and blue for neutral. This provides at-a-glance context for where price is trading within its recent range.
An ADX strength bar at the bottom of the chart uses color coding: white for weak trend (ADX below 15), orange for ranging (ADX 15-24), and blue for trending (ADX above 24). This matches the trend strength display in the information panel.
Price labels appear at signal locations showing the signal type and entry price. Labels are automatically cleaned up after reaching a configurable history limit to maintain chart performance.
Signal candles are highlighted in blue, making it easy to identify exactly which bars generated signals when reviewing historical performance.
Information Panel
A compact table displays key metrics: current regime bias, trend strength classification, BBWP volatility reading, RSI level, and ADX value. Each metric is color-coded to highlight favorable or unfavorable conditions.
The panel can be positioned at any corner or middle edge of the chart. An alternative label-based display anchored to the chart is also available for those who prefer that format.
Trend Persistence Option
By default, the regime is recalculated on every bar. An optional persistence mode changes this behavior so that the regime only changes on EMA crossovers. This reduces regime flipping during choppy conditions but may delay regime recognition during gradual trend changes.
How to Use
Monitor the Money Line color and information panel for current regime. In bullish regimes, focus on buy signals at the lower Donchian band as potential pullback entries. In bearish regimes, focus on sell signals at the upper band as potential short entries or exit points.
Use the ADX strength indicator to gauge signal reliability. Signals during trending conditions (blue ADX bar) have historically higher success rates than signals during ranging conditions (orange bar) or weak trends (white bar).
Watch BBWP for volatility context. Low BBWP readings suggest a significant move may be developing, while high readings indicate the current move may be overextended.
The combination of regime awareness, Donchian breakout signals, and ADX/RSI filtering provides a structured approach to identifying trading opportunities across different market conditions.
Settings Guidance
The default settings work well for cryptocurrency and forex markets on intraday timeframes. For stocks or longer timeframes, consider increasing the EMA periods and Donchian lookback. The ADX threshold can be adjusted based on the typical ADX range for the traded instrument.
The RSI filter levels can be relaxed (higher oversold, lower overbought) for more signals or tightened for higher-quality but less frequent signals. The cooldown period should be adjusted based on timeframe, with shorter timeframes typically requiring longer cooldown periods.
نص برمجي مفتوح المصدر
بروح TradingView الحقيقية، قام مبتكر هذا النص البرمجي بجعله مفتوح المصدر، بحيث يمكن للمتداولين مراجعة وظائفه والتحقق منها. شكرا للمؤلف! بينما يمكنك استخدامه مجانًا، تذكر أن إعادة نشر الكود يخضع لقواعد الموقع الخاصة بنا.
إخلاء المسؤولية
لا يُقصد بالمعلومات والمنشورات أن تكون، أو تشكل، أي نصيحة مالية أو استثمارية أو تجارية أو أنواع أخرى من النصائح أو التوصيات المقدمة أو المعتمدة من TradingView. اقرأ المزيد في شروط الاستخدام.
نص برمجي مفتوح المصدر
بروح TradingView الحقيقية، قام مبتكر هذا النص البرمجي بجعله مفتوح المصدر، بحيث يمكن للمتداولين مراجعة وظائفه والتحقق منها. شكرا للمؤلف! بينما يمكنك استخدامه مجانًا، تذكر أن إعادة نشر الكود يخضع لقواعد الموقع الخاصة بنا.
إخلاء المسؤولية
لا يُقصد بالمعلومات والمنشورات أن تكون، أو تشكل، أي نصيحة مالية أو استثمارية أو تجارية أو أنواع أخرى من النصائح أو التوصيات المقدمة أو المعتمدة من TradingView. اقرأ المزيد في شروط الاستخدام.