OPEN-SOURCE SCRIPT
MESA Adaptive Ehlers Flow | AlphaNatt

MESA Adaptive Ehlers Flow | AlphaNatt
An advanced adaptive indicator based on John Ehlers' MESA (Maximum Entropy Spectrum Analysis) algorithm that automatically adjusts to market cycles in real-time, providing superior trend identification with minimal lag across all market conditions.
🎯 What Makes This Indicator Revolutionary?
Unlike traditional moving averages with fixed parameters, this indicator uses Hilbert Transform mathematics to detect the dominant market cycle and adapts its responsiveness accordingly:
📊 Core Components
1. MESA Adaptive Moving Average (MAMA)
The MAMA is the crown jewel of adaptive indicators. It uses the Hilbert Transform to measure the market's dominant cycle and adjusts its smoothing factor in real-time:
Parameters:
2. Following Adaptive Moving Average (FAMA)
The FAMA is a slower version of MAMA that follows the primary signal. The relationship between MAMA and FAMA provides powerful trend confirmation:
3. Hilbert Transform Cycle Detection
The indicator employs sophisticated DSP (Digital Signal Processing) techniques:
⚡ Key Features
Adaptive Alpha Calculation
The indicator's "intelligence" comes from its adaptive alpha:
Dynamic Volatility Bands
Unlike static bands, these adapt to both ATR volatility AND the current cycle state:
Intelligent Color Coding
📈 Trading Strategies
Trend Following Strategy
Entry Signals:
Exit/Management:
Mean Reversion Strategy
Setup Conditions:
Cycle-Based Swing Trading
The indicator's cycle detection makes it ideal for swing trading:
🔬 Technical Background
The Hilbert Transform
The Hilbert Transform is a mathematical operation used in signal processing to extract instantaneous phase and frequency information from a signal. In trading applications:
MESA Algorithm Components
⚙️ Optimization Guide
Fast Limit (0.1 - 0.9)
Slow Limit (0.01 - 0.1)
Band Multiplier (0.5 - 3.0)
🎨 Visual Interpretation
The gradient visualization shows probability zones around the MESA line:
💡 Best Practices
📊 Optimal Timeframes
⚠️ Important Considerations
🔍 What Makes MESA Superior?
Compared to traditional indicators:
🎓 Understanding Adaptation
Adaptation in Action:
🚀 Advanced Applications
Created by AlphaNatt - Based on John Ehlers' MESA research. For educational purposes. Always practice proper risk management. Not financial advice. Always DYOR.
An advanced adaptive indicator based on John Ehlers' MESA (Maximum Entropy Spectrum Analysis) algorithm that automatically adjusts to market cycles in real-time, providing superior trend identification with minimal lag across all market conditions.
🎯 What Makes This Indicator Revolutionary?
Unlike traditional moving averages with fixed parameters, this indicator uses Hilbert Transform mathematics to detect the dominant market cycle and adapts its responsiveness accordingly:
- Automatically detects market cycles using advanced signal processing
- MAMA (MESA Adaptive Moving Average) adapts from fast to slow based on cycle phase
- FAMA (Following Adaptive Moving Average) provides confirmation signals
- Dynamic volatility bands that expand and contract with cycle detection
- Zero manual optimization required - the indicator tunes itself
📊 Core Components
1. MESA Adaptive Moving Average (MAMA)
The MAMA is the crown jewel of adaptive indicators. It uses the Hilbert Transform to measure the market's dominant cycle and adjusts its smoothing factor in real-time:
- During trending phases: Responds quickly to capture moves
- During choppy phases: Smooths heavily to filter noise
- Transition is automatic and seamless based on price action
Parameters:
- Fast Limit: Maximum responsiveness (default: 0.5) - how fast the indicator can adapt
- Slow Limit: Minimum responsiveness (default: 0.05) - maximum smoothing during consolidation
2. Following Adaptive Moving Average (FAMA)
The FAMA is a slower version of MAMA that follows the primary signal. The relationship between MAMA and FAMA provides powerful trend confirmation:
- MAMA > FAMA: Bullish trend in progress
- MAMA < FAMA: Bearish trend in progress
- Crossovers signal potential trend changes
3. Hilbert Transform Cycle Detection
The indicator employs sophisticated DSP (Digital Signal Processing) techniques:
- Detects the dominant cycle period (1.5 to 50 bars)
- Measures phase relationships in the price data
- Calculates adaptive alpha values based on cycle dynamics
- Continuously updates as market character changes
⚡ Key Features
Adaptive Alpha Calculation
The indicator's "intelligence" comes from its adaptive alpha:
Alpha dynamically adjusts between Fast Limit and Slow Limit based on the rate of phase change in the market cycle. Rapid phase changes trigger faster adaptation, while stable cycles maintain smoother response.
Dynamic Volatility Bands
Unlike static bands, these adapt to both ATR volatility AND the current cycle state:
- Bands widen when the indicator detects fast adaptation (trending)
- Bands narrow during slow adaptation (consolidation)
- Band Multiplier controls overall width (default: 1.5)
- Provides context-aware support and resistance
Intelligent Color Coding
- Cyan: Bullish regime (MAMA > FAMA and price > MAMA)
- Magenta: Bearish regime (MAMA < FAMA and price < MAMA)
- Gray: Neutral/transitional state
📈 Trading Strategies
Trend Following Strategy
The MESA indicator excels at identifying and riding strong trends while automatically reducing sensitivity during choppy periods.
Entry Signals:
- Long: MAMA crosses above FAMA with price closing above MAMA
- Short: MAMA crosses below FAMA with price closing below MAMA
Exit/Management:
- Exit longs when MAMA crosses below FAMA
- Exit shorts when MAMA crosses above FAMA
- Use dynamic bands as trailing stop references
Mean Reversion Strategy
When price extends beyond the dynamic bands during established trends, look for bounces back toward the MAMA line.
Setup Conditions:
- Strong trend confirmed by MAMA/FAMA alignment
- Price touches or exceeds outer band
- Enter on first sign of reversal toward MAMA
- Target: Return to MAMA line or opposite band
Cycle-Based Swing Trading
The indicator's cycle detection makes it ideal for swing trading:
- Enter on MAMA/FAMA crossovers
- Hold through the detected cycle period
- Exit on counter-crossover or band extremes
- Works exceptionally well on 4H to Daily timeframes
🔬 Technical Background
The Hilbert Transform
The Hilbert Transform is a mathematical operation used in signal processing to extract instantaneous phase and frequency information from a signal. In trading applications:
- Separates trend from cycle components
- Identifies the dominant market cycle without curve-fitting
- Provides leading indicators of trend changes
MESA Algorithm Components
- Smoothing: 4-bar weighted moving average for noise reduction
- Detrending: Removes linear price trend to isolate cycles
- InPhase & Quadrature: Orthogonal components for phase measurement
- Homodyne Discriminator: Calculates instantaneous period
- Adaptive Alpha: Converts period to smoothing factor
- MAMA/FAMA: Final adaptive moving averages
⚙️ Optimization Guide
Fast Limit (0.1 - 0.9)
- Higher values (0.5-0.9): More responsive, better for volatile markets and lower timeframes
- Lower values (0.1-0.3): Smoother response, better for stable markets and higher timeframes
- Default 0.5: Balanced for most applications
Slow Limit (0.01 - 0.1)
- Higher values (0.05-0.1): Less smoothing during consolidation, more signals
- Lower values (0.01-0.03): Heavy smoothing during chop, fewer but cleaner signals
- Default 0.05: Good noise filtering while maintaining responsiveness
Band Multiplier (0.5 - 3.0)
- Adjust based on instrument volatility
- Backtest to find optimal value for your specific market
- 1.5 works well for most forex and equity indices
- Consider higher values (2.0-2.5) for cryptocurrencies
🎨 Visual Interpretation
The gradient visualization shows probability zones around the MESA line:
- MESA line: The adaptive trend center
- Band expansion: Indicates strong cycle detection and trending
- Band contraction: Indicates consolidation or ranging market
- Color intensity: Shows confidence in trend direction
💡 Best Practices
- Let it adapt: Give the indicator 50+ bars to properly calibrate to the market
- Combine timeframes: Use higher timeframe MESA for trend bias, lower for entries
- Respect the bands: Price rarely stays outside bands for extended periods
- Watch for compression: Narrow bands often precede explosive moves
- Volume confirmation: Combine with volume for higher probability setups
📊 Optimal Timeframes
- 15m - 1H: Day trading with Fast Limit 0.6-0.8
- 4H - Daily: Swing trading with Fast Limit 0.4-0.6 (recommended)
- Weekly: Position trading with Fast Limit 0.2-0.4
⚠️ Important Considerations
- The indicator needs time to "learn" the market - avoid trading the first 50 bars after applying
- Extreme gap events can temporarily disrupt cycle calculations
- Works best in markets with detectable cyclical behavior
- Less effective during news events or extreme volatility spikes
- Consider the detected cycle period for position holding times
🔍 What Makes MESA Superior?
Compared to traditional indicators:
- vs. Fixed MAs: Automatically adjusts to market conditions instead of using one-size-fits-all parameters
- vs. Other Adaptive MAs: Uses true DSP mathematics rather than simple volatility adjustments
- vs. Manual Optimization: Continuously re-optimizes itself in real-time
- vs. Lagging Indicators: Hilbert Transform provides earlier trend change detection
🎓 Understanding Adaptation
The magic of MESA is that it solves the eternal dilemma of technical analysis: be fast and get whipsawed in chop, or be smooth and miss the early move. MESA does both by detecting when to be fast and when to be smooth.
Adaptation in Action:
- Strong trend starts → MESA quickly detects phase change → Fast Limit kicks in → Early entry
- Trend continues → Phase stabilizes → MESA maintains moderate speed → Smooth ride
- Consolidation begins → Phase changes slow → Slow Limit engages → Whipsaw avoidance
🚀 Advanced Applications
- Multi-timeframe confluence: Use MESA on 3 timeframes for high-probability setups
- Divergence detection: Watch for MAMA/price divergences at band extremes
- Cycle period analysis: The internal period calculation can guide position duration
- Band squeeze trading: Narrow bands + MAMA/FAMA cross = high-probability breakout
Created by AlphaNatt - Based on John Ehlers' MESA research. For educational purposes. Always practice proper risk management. Not financial advice. Always DYOR.
Script de código aberto
No verdadeiro espirito do TradingView, o autor desse script o publicou como código aberto, para que os traders possam entendê-lo e verificá-lo. Parabéns ao autor Você pode usá-lo gratuitamente, mas a reutilização desse código em publicações e regida pelas Regras da Casa.
Aviso legal
As informações e publicações não devem ser e não constituem conselhos ou recomendações financeiras, de investimento, de negociação ou de qualquer outro tipo, fornecidas ou endossadas pela TradingView. Leia mais em Termos de uso.
Script de código aberto
No verdadeiro espirito do TradingView, o autor desse script o publicou como código aberto, para que os traders possam entendê-lo e verificá-lo. Parabéns ao autor Você pode usá-lo gratuitamente, mas a reutilização desse código em publicações e regida pelas Regras da Casa.
Aviso legal
As informações e publicações não devem ser e não constituem conselhos ou recomendações financeiras, de investimento, de negociação ou de qualquer outro tipo, fornecidas ou endossadas pela TradingView. Leia mais em Termos de uso.