OPEN-SOURCE SCRIPT
Mis à jour

[blackcat] L2 Ehlers MAMA

4 786
Level: 2

Background

John F. Ehlers introuced MESA Adaptive Moving Average-a.k.a "MAMA" in his "Rocket Science for Traders" chapter 17. Forgive the whimsy of the name Dr. Ehlers attached to this unique indicator, but with that name he is sure you will always remember it, like KAMA and VIDYA.


Function

blackcat L2 Ehlers MESA Adaptive Moving Average-a.k.a "MAMA" is used to follow trend. The concept of MAMA is to relate the phase rate of change to the EMA alpha, thus making the EMA adaptive. The cycle phase goes from 0 through 360 degrees in each cycle. The phase is continuous, but is usually drawn with the snap back to 0 degrees as the beginning of each cycle. Thus the phase rate of change is 360 degrees per cycle. The shorter the cycle, the faster the phase rate of change. For example, a 36-bar cycle has a phase rate of change of 10 degrees per bar, while a 10-bar cycle has a rate of change of 36 degrees per bar. The cycle periods tend to be longer when the market is in a Trend Mode.
The cycle phase is computed from the arctangent of the ratio of the Quadrature component to the Inphase component. Dr. Ehlers obtain the phase rate of change values by taking the difference of successive phase measurements. The arctangent function only measures phase over a half cycle, from -90 degrees to +90 degrees. Since the phase measurement snaps back every half cycle, a huge negative rate change of phase every half cycle results from the computation of the rate change of phase. Measured negative rate changes of phase can also occur when the market is in a Trend Mode. Any negative rate change of phase is theoretically impossible because phase must advance as time increases. Dr. Ehlers therefore limit all rate change of phase to be no less than unity.

Key Signal

Smooth --> 4 bar WMA w/ 1 bar lag
Detrender --> The amplitude response of a minimum-length HT can be improved by adjusting the filter coefficients by
trial and error. HT does not allow DC component at zero frequency for transformation. So, Detrender is used to remove DC component/ trend component.
Q1 --> Quadrature phase signal
I1 --> In-phase signal
Period --> Dominant Cycle in bars
SmoothPeriod --> Period with complex averaging
alpha ---> coefficient
MAMA ---> MESA Adaptive Moving Average-a.k.a "MAMA"
FAMA ---> slow line of MAMA

Pros and Cons

100% John F. Ehlers definition translation of original work, even variable names are the same. This help readers who would like to use pine to read his book. If you had read his works, then you will be quite familiar with my code style.

Remarks

The 13th script for Blackcat1402 John F. Ehlers Week publication.

Readme

In real life, I am a prolific inventor. I have successfully applied for more than 60 international and regional patents in the past 12 years. But in the past two years or so, I have tried to transfer my creativity to the development of trading strategies. Tradingview is the ideal platform for me. I am selecting and contributing some of the hundreds of scripts to publish in Tradingview community. Welcome everyone to interact with me to discuss these interesting pine scripts.

The scripts posted are categorized into 5 levels according to my efforts or manhours put into these works.

Level 1 : interesting script snippets or distinctive improvement from classic indicators or strategy. Level 1 scripts can usually appear in more complex indicators as a function module or element.

Level 2 : composite indicator/strategy. By selecting or combining several independent or dependent functions or sub indicators in proper way, the composite script exhibits a resonance phenomenon which can filter out noise or fake trading signal to enhance trading confidence level.

Level 3 : comprehensive indicator/strategy. They are simple trading systems based on my strategies. They are commonly containing several or all of entry signal, close signal, stop loss, take profit, re-entry, risk management, and position sizing techniques. Even some interesting fundamental and mass psychological aspects are incorporated.

Level 4 : script snippets or functions that do not disclose source code. Interesting element that can reveal market laws and work as raw material for indicators and strategies. If you find Level 1~2 scripts are helpful, Level 4 is a private version that took me far more efforts to develop.

Level 5 : indicator/strategy that do not disclose source code. private version of Level 3 script with my accumulated script processing skills or a large number of custom functions. I had a private function library built in past two years. Level 5 scripts use many of them to achieve private trading strategy.
Notes de version
Add buy and sell labels
Notes de version
Correct label bar_index issue
Notes de version
OVERVIEW

This TradingView script calculates and plots the Ehlers MAMA (Mother of All Moving Averages) indicator, providing a dynamic trend-following tool that helps identify potential buy and sell signals based on price movements.

FEATURES

Dynamic Calculation: Automatically adjusts the calculation based on price data.
Customizable Inputs: Allows users to set the Source, FastLimit, and SlowLimit inputs.
Plotting: Displays both MAMA and FAMA lines with customizable colors and line widths.
Cross Labels: Highlights buy and sell signals with labels on the chart.
HOW TO USE

Add the script to your TradingView chart.
Adjust the Source, FastLimit, and SlowLimit inputs in the script editor to customize the indicator.
Observe the MAMA and FAMA lines on the chart.
Look for cross labels indicating potential buy (BUY) or sell (SELL) signals.
LIMITATIONS

The script may not perform optimally on extremely volatile markets.
Results can vary based on the input parameters.
NOTES

The script is based on the Ehlers MAMA indicator formula.
For best results, use it in conjunction with other technical indicators.
Notes de version
█ OVERVIEW

Ehlers MAMA indicator with enhanced signal governance, ATR-based risk management, and a full trading dashboard. It identifies trend reversals using John Ehlers' MAMA/FAMA algorithm and provides actionable buy/sell signals with configurable exit strategies.

█ CONCEPTS

The script is based on John Ehlers' Maximum Adaptive Moving Average (MAMA) and Following Adaptive Moving Average (FAMA) algorithm. It combines spectral analysis with adaptive smoothing to produce low-lag trend signals.

Key principles:
• Trend Detection: MAMA and FAMA crossovers identify trend direction changes
• Signal Governance: A state machine with cooldown and exclusivity rules filters out noisy signals
• Risk Management: ATR-based take profit and stop loss levels adapt to market volatility
• Re-entry System: Optional anchor-based re-entry after exit signals captures trend resumption

█ HOW TO USE

1 — Add the script to your TradingView chart and set it to overlay mode
2 — Configure the Source, FastLimit, and SlowLimit inputs to match your trading style
3 — Adjust the Cooldown Bars and Exclusivity settings to control signal frequency
4 — Enable ATR-based TP/SL levels for structured risk management
5 — Use the dashboard to monitor current position, entry price, SL/TP levels, and ATR

Input Parameters
• Source: Price source for calculation (default: hl2)
• FastLimit: Fast limit factor for alpha calculation (default: 0.5, range: 0.01-2.0)
• SlowLimit: Slow limit factor for alpha calculation (default: 0.05, range: 0.01-1.0)
• Enable Short Signals: Toggle short-side signals on/off (default: true)
• Cooldown Bars: Minimum bars between consecutive signals (default: 3, range: 0-20)
• Same-bar Entry/Exit Exclusivity: Prevents simultaneous entry and exit on the same bar (default: true)
• ATR Length: Period for ATR calculation (default: 14)
• Stop Loss (xATR): ATR multiplier for stop loss distance (default: 2.0)
• Take Profit (xATR): ATR multiplier for take profit distance (default: 3.0)
• Show TP/SL Levels: Toggle TP/SL line visibility (default: true)
• Enable Re-entry (RL/RS): Activate the re-entry system after exit signals (default: false)
• Anchor Window: Number of bars around exit to set re-entry anchors (default: 1, range: 1-5)
• Breakout Source: Price source for re-entry breakout detection (default: Close)
• Show Dashboard: Toggle the position information table (default: true)
• Show Original plotshape: Display the legacy plotshape markers (default: false)

█ FEATURES

• Bidirectional signals: Both long and short entry signals with configurable enable/disable
• State machine signal governance: Prevents signal duplication and enforces cooldown periods
• ATR-based TP/SL visualization: Dynamic stop loss and take profit levels plotted on chart
• Re-entry system (optional): Automatically detects trend resumption after exit signals
• Full dashboard: Real-time position status, entry price, SL/TP levels, and ATR value
• Background color coding: Green for long, red for short positions
• Alert support: Independent alert conditions for entry, exit, and re-entry events
• Configurable plotshape overlay: Legacy signal markers can be toggled on/off

█ SIGNALS

Visual Elements
• BUY label: Green upward label below the bar when MAMA crosses above FAMA
• SELL label: Red downward label above the bar when MAMA crosses below FAMA
• XL/XS labels: Orange X-cross marks indicating exit from long/short positions
• RL/RS labels: Teal/maroon re-entry labels when trend resumes after exit
• Yellow/Fuchsia fill: Area between MAMA and FAMA indicating trend direction
• Background color: Light green for long, light red for short position states
• TP/SL lines: Dashed red (stop loss) and teal (take profit) lines when position is active

█ IMPLEMENTATION NOTES

The core algorithm uses John Ehlers' MAMA/FAMA spectral analysis method with the following built-ins:
• math.asin for phase calculation
• ta.atr for volatility measurement
• nz() for safe historical value access
• request.security is not used — all calculations are on the chart timeframe

Pine Script®


The indicator uses a position state machine (posState: -1/0/+1) to track current market exposure and enforce signal exclusivity.

█ LIMITATIONS

• Best suited for trending markets; may produce false signals in ranging conditions
• The MAMA/FAMA algorithm requires sufficient historical data for convergence
• ATR-based TP/SL levels are reference points, not fixed execution prices
• Re-entry system is disabled by default and should be tested before enabling
• Cooldown settings may cause missed signals in fast-moving markets

█ NOTES

• Original algorithm by blackcat1402, based on John Ehlers' MAMA/FAMA framework
• Published under Mozilla Public License 2.0
• Compatible with all asset classes and timeframes
• The dashboard updates only on the last bar for performance optimization

═════════════════════════════════════════════════════════════════════════
For questions or feedback, use comments section below.
Feel free to use and modify — attribution appreciated.

Clause de non-responsabilité

Les informations et publications ne sont pas destinées à être, et ne constituent pas, des conseils ou recommandations financiers, d'investissement, de trading ou autres fournis ou approuvés par TradingView. Pour en savoir plus, consultez les Conditions d'utilisation.