OPEN-SOURCE SCRIPT
Market Regime & Trend Filter

🚀 MARKET REGIME & TREND FILTER PRO [MRTF]
The Market Regime & Trend Filter Pro (MRTF), engineered by gunebak4n, is an institutional-grade multi-dimensional trend classification and market structure isolation framework. It is designed to visually map macro price regimes, isolate structural expansions, and filter out low-liquidity market noise without a single pixel of signal repainting.
MRTF operates on the core principle that directional price movement cannot be evaluated in a vacuum. True, sustainable trends are defined by the mathematical convergence of statistical linear regression velocity and validated swing market structures (Higher Highs / Lower Lows). By unifying an asset-agnostic, normalized slope calculation with a lag-free swing matrix, MRTF projects multi-state market environments directly onto the user's chart.
Unlike traditional moving averages or standard trend-following tools that suffer from severe lag or generate devastating false signals during prolonged sideways consolidations, MRTF dynamically shifts across five distinct market regimes—instantly distinguishing a high-conviction breakout from a dangerous, low-velocity trap.
💡 CORE DESIGN PRINCIPLES
🧭 Normalized Statistical Velocity Engine
Standard linear regression slopes fail when comparing different assets or volatile timeframes because their raw values depend entirely on the asset's nominal price. MRTF solves this by processing the raw slope (Beta Coefficient) through a dynamic ATR (Average True Range) normalization matrix. This transforms ordinary regression into a universal, percentage-based momentum tracker that remains stable across Bitcoin, Apple, or Gold.
🧬 Non-Repainting Multi-Layer Validation
The framework continuously evaluates two distinct algorithmic layers:
Statistical Trend Component: A localized rolling covariance engine that measures the geometric slope of the price index over a user-defined lookback window.
Structural Swing Component: A strict, non-repainting pivot tracking system that marks qualified market structures based on strict historical confirmations.
The structural intersection of these layers determines the definitive macro market regime.
💡 KEY FEATURES
📊 Five-State Market Regime Matrix
Instead of a binary "bull or bear" output, MRTF classifies the market into 5 actionable phases to optimize strategy execution:
Strong Bullish: Market structure is breaking higher (HH/HL) and the normalized channel slope is expanding aggressively upward.
Weak Bullish: Structural trend is upward but momentum is flattening, OR macro momentum is extremely bullish despite temporary structural breaks.
Ranging / Choppy: The absolute trend slope is compressed inside the dead-zone threshold. Capital preservation mode.
Weak Bearish: Structural trend is downward but selling momentum is stalling, OR macro momentum is sharply negative despite minor upward structural retracements.
Strong Bearish: Market structure is breaking lower (LH/LL) and the normalized channel slope is accelerating aggressively downward.
🧪 Advanced Chart-Scale Alignment (Log/Linear)
A critical feature engineered into MRTF is its manual Price Scale Mode switch. Because Pine Script cannot natively detect whether a user's visual chart layout is set to Logarithmic or Linear, MRTF provides an input enum to match your chart. This prevents the mathematical distortion of regression slopes on long-term logarithmic charts, ensuring accurate momentum readings.
🛡️ Non-Repainting Historical Swing Mapping
The indicator utilizes advanced pivot logic to identify valid structural peaks and troughs. By utilizing a fixed right-bar confirmation offset, the system completely eliminates the risk of signal repainting. Shapes are placed historically precisely where the structural pivot occurred, offering an uncorrupted look back at structural market transitions.
🔬 MATHEMATICAL ARCHITECTURE
[STEP 1: Chart Scale Selection & Log Transformation]
If Scale Mode is Logarithmic:
Y_val = ln(Close)
If Scale Mode is Linear:
Y_val = Close
[STEP 2: Rolling Window Covariance & Slope Engine]
• Mean_X = SMA(bar_index, Length)
• Mean_Y = SMA(Y_val, Length)
• Mean_XY = SMA(bar_index * Y_val, Length)
• Cov_XY = Mean_XY - (Mean_X * Mean_Y)
• Variance_X = Variance(bar_index, Length)
• Raw_Slope = Cov_XY / Variance_X
[STEP 3: Average True Range Normalization Matrix]
• ATR_Val = ATR(Length)
If Scale Mode is Logarithmic:
Normalized_Slope = Raw_Slope * 100
If Scale Mode is Linear:
Normalized_Slope = (Raw_Slope / ATR_Val) * 100
🛠️ USAGE FRAMEWORK
1. Candlestick Regime Coloring
Monitor the color shifts of the live candlesticks to instantly identify the dominant institutional phase:
Bright Lime Candles: Strong Bullish Expansion. (Ideal for riding strong macro trend extensions).
Muted Green Candles: Weak Bullish Phase / Potential Exhaustion or Minor Retracement.
Gray Candles: Ranging / Choppy Environment. Tighten stop-losses, avoid breakout chasing, and look for mean-reversion setups.
Muted Maroon Candles: Weak Bearish Phase / Defensive Posture.
Bright Red Candles: Strong Bearish Expansion. (Ideal for capital preservation or short-side exposure).
2. Analytical Control Dashboard
The real-time HUD (Heads-Up Display) in the corner of your chart provides a synchronized summary of market health:
Scale Mode: Confirms whether your mathematical engine is aligned with your visual chart scale.
Norm Slope: Displays the exact normalized statistical momentum score. Values crossing outside your threshold indicate volatility expansions.
Market Structure: Shows the structural orientation based on valid pivot series (Bullish, Bearish, or Undetermined).
3. Structural Pivot Turning Points
The small red and lime triangles plotted on the chart mark confirmed structural swing points. Because they are fully non-repainting, they represent concrete psychological levels where institutional order flow shifted, making them excellent levels for placing structural stop-losses or identifying major support/resistance zones.
⚙️ SYSTEM CHARACTERISTICS
Zero Repainting: All background calculations, candlestick color shifts, and swing markers are mathematically locked upon bar close.
Fully Parameterized Controls: Seamlessly adjust regression lengths, swing confirmations, and slope thresholds to adapt the script to Scalping, Day Trading, or Macro Swing Trading.
Asset-Agnostic Engine: Works flawlessly across Equities, Forex, Crypto, Indices, and Commodities by converting absolute price tracking into standardized volatility metrics.
Custom Visual Themes: Every single regime color and dashboard location parameter can be customized within the user settings panel to fit clean dark or light chart aesthetics.
📌 CREDIT
The Market Regime & Trend Filter Pro (MRTF) is officially engineered and published by gunebak4n on TradingView.
This script is built for professional traders who prioritize statistical clarity and structural confirmation over erratic, lagging indicators or noise-heavy lagging moving averages.
⚠️ DISCLAIMER
MRTF is a probabilistic statistical mapping model designed for data visualization. It does not issue absolute trading recommendations, financial advice, or automated profit guarantees. Always backtest your parameters and manage your risk exposure strictly according to your personal trading plan.
The Market Regime & Trend Filter Pro (MRTF), engineered by gunebak4n, is an institutional-grade multi-dimensional trend classification and market structure isolation framework. It is designed to visually map macro price regimes, isolate structural expansions, and filter out low-liquidity market noise without a single pixel of signal repainting.
MRTF operates on the core principle that directional price movement cannot be evaluated in a vacuum. True, sustainable trends are defined by the mathematical convergence of statistical linear regression velocity and validated swing market structures (Higher Highs / Lower Lows). By unifying an asset-agnostic, normalized slope calculation with a lag-free swing matrix, MRTF projects multi-state market environments directly onto the user's chart.
Unlike traditional moving averages or standard trend-following tools that suffer from severe lag or generate devastating false signals during prolonged sideways consolidations, MRTF dynamically shifts across five distinct market regimes—instantly distinguishing a high-conviction breakout from a dangerous, low-velocity trap.
💡 CORE DESIGN PRINCIPLES
🧭 Normalized Statistical Velocity Engine
Standard linear regression slopes fail when comparing different assets or volatile timeframes because their raw values depend entirely on the asset's nominal price. MRTF solves this by processing the raw slope (Beta Coefficient) through a dynamic ATR (Average True Range) normalization matrix. This transforms ordinary regression into a universal, percentage-based momentum tracker that remains stable across Bitcoin, Apple, or Gold.
🧬 Non-Repainting Multi-Layer Validation
The framework continuously evaluates two distinct algorithmic layers:
Statistical Trend Component: A localized rolling covariance engine that measures the geometric slope of the price index over a user-defined lookback window.
Structural Swing Component: A strict, non-repainting pivot tracking system that marks qualified market structures based on strict historical confirmations.
The structural intersection of these layers determines the definitive macro market regime.
💡 KEY FEATURES
📊 Five-State Market Regime Matrix
Instead of a binary "bull or bear" output, MRTF classifies the market into 5 actionable phases to optimize strategy execution:
Strong Bullish: Market structure is breaking higher (HH/HL) and the normalized channel slope is expanding aggressively upward.
Weak Bullish: Structural trend is upward but momentum is flattening, OR macro momentum is extremely bullish despite temporary structural breaks.
Ranging / Choppy: The absolute trend slope is compressed inside the dead-zone threshold. Capital preservation mode.
Weak Bearish: Structural trend is downward but selling momentum is stalling, OR macro momentum is sharply negative despite minor upward structural retracements.
Strong Bearish: Market structure is breaking lower (LH/LL) and the normalized channel slope is accelerating aggressively downward.
🧪 Advanced Chart-Scale Alignment (Log/Linear)
A critical feature engineered into MRTF is its manual Price Scale Mode switch. Because Pine Script cannot natively detect whether a user's visual chart layout is set to Logarithmic or Linear, MRTF provides an input enum to match your chart. This prevents the mathematical distortion of regression slopes on long-term logarithmic charts, ensuring accurate momentum readings.
🛡️ Non-Repainting Historical Swing Mapping
The indicator utilizes advanced pivot logic to identify valid structural peaks and troughs. By utilizing a fixed right-bar confirmation offset, the system completely eliminates the risk of signal repainting. Shapes are placed historically precisely where the structural pivot occurred, offering an uncorrupted look back at structural market transitions.
🔬 MATHEMATICAL ARCHITECTURE
[STEP 1: Chart Scale Selection & Log Transformation]
If Scale Mode is Logarithmic:
Y_val = ln(Close)
If Scale Mode is Linear:
Y_val = Close
[STEP 2: Rolling Window Covariance & Slope Engine]
• Mean_X = SMA(bar_index, Length)
• Mean_Y = SMA(Y_val, Length)
• Mean_XY = SMA(bar_index * Y_val, Length)
• Cov_XY = Mean_XY - (Mean_X * Mean_Y)
• Variance_X = Variance(bar_index, Length)
• Raw_Slope = Cov_XY / Variance_X
[STEP 3: Average True Range Normalization Matrix]
• ATR_Val = ATR(Length)
If Scale Mode is Logarithmic:
Normalized_Slope = Raw_Slope * 100
If Scale Mode is Linear:
Normalized_Slope = (Raw_Slope / ATR_Val) * 100
🛠️ USAGE FRAMEWORK
1. Candlestick Regime Coloring
Monitor the color shifts of the live candlesticks to instantly identify the dominant institutional phase:
Bright Lime Candles: Strong Bullish Expansion. (Ideal for riding strong macro trend extensions).
Muted Green Candles: Weak Bullish Phase / Potential Exhaustion or Minor Retracement.
Gray Candles: Ranging / Choppy Environment. Tighten stop-losses, avoid breakout chasing, and look for mean-reversion setups.
Muted Maroon Candles: Weak Bearish Phase / Defensive Posture.
Bright Red Candles: Strong Bearish Expansion. (Ideal for capital preservation or short-side exposure).
2. Analytical Control Dashboard
The real-time HUD (Heads-Up Display) in the corner of your chart provides a synchronized summary of market health:
Scale Mode: Confirms whether your mathematical engine is aligned with your visual chart scale.
Norm Slope: Displays the exact normalized statistical momentum score. Values crossing outside your threshold indicate volatility expansions.
Market Structure: Shows the structural orientation based on valid pivot series (Bullish, Bearish, or Undetermined).
3. Structural Pivot Turning Points
The small red and lime triangles plotted on the chart mark confirmed structural swing points. Because they are fully non-repainting, they represent concrete psychological levels where institutional order flow shifted, making them excellent levels for placing structural stop-losses or identifying major support/resistance zones.
⚙️ SYSTEM CHARACTERISTICS
Zero Repainting: All background calculations, candlestick color shifts, and swing markers are mathematically locked upon bar close.
Fully Parameterized Controls: Seamlessly adjust regression lengths, swing confirmations, and slope thresholds to adapt the script to Scalping, Day Trading, or Macro Swing Trading.
Asset-Agnostic Engine: Works flawlessly across Equities, Forex, Crypto, Indices, and Commodities by converting absolute price tracking into standardized volatility metrics.
Custom Visual Themes: Every single regime color and dashboard location parameter can be customized within the user settings panel to fit clean dark or light chart aesthetics.
📌 CREDIT
The Market Regime & Trend Filter Pro (MRTF) is officially engineered and published by gunebak4n on TradingView.
This script is built for professional traders who prioritize statistical clarity and structural confirmation over erratic, lagging indicators or noise-heavy lagging moving averages.
⚠️ DISCLAIMER
MRTF is a probabilistic statistical mapping model designed for data visualization. It does not issue absolute trading recommendations, financial advice, or automated profit guarantees. Always backtest your parameters and manage your risk exposure strictly according to your personal trading plan.
Open-source Skript
Ganz im Sinne von TradingView hat dieser Autor sein/ihr Script als Open-Source veröffentlicht. Auf diese Weise können nun auch andere Trader das Script rezensieren und die Funktionalität überprüfen. Vielen Dank an den Autor! Sie können das Script kostenlos verwenden, aber eine Wiederveröffentlichung des Codes unterliegt unseren Hausregeln.
Haftungsausschluss
Die Informationen und Veröffentlichungen sind nicht als Finanz-, Anlage-, Handels- oder andere Arten von Ratschlägen oder Empfehlungen gedacht, die von TradingView bereitgestellt oder gebilligt werden, und stellen diese nicht dar. Lesen Sie mehr in den Nutzungsbedingungen.
Open-source Skript
Ganz im Sinne von TradingView hat dieser Autor sein/ihr Script als Open-Source veröffentlicht. Auf diese Weise können nun auch andere Trader das Script rezensieren und die Funktionalität überprüfen. Vielen Dank an den Autor! Sie können das Script kostenlos verwenden, aber eine Wiederveröffentlichung des Codes unterliegt unseren Hausregeln.
Haftungsausschluss
Die Informationen und Veröffentlichungen sind nicht als Finanz-, Anlage-, Handels- oder andere Arten von Ratschlägen oder Empfehlungen gedacht, die von TradingView bereitgestellt oder gebilligt werden, und stellen diese nicht dar. Lesen Sie mehr in den Nutzungsbedingungen.