Return-to-Mean Clock: Measuring Price Reversion to Moving Averages

Return-to-Mean Clock: Measuring Price Reversion to Moving Averages
Download ALL MT5 indicators (6120)
YouTube Video Thumbnail



Similar MetaTrader Tools

Return-to-Mean Clock: Measuring Price Reversion to Moving Averages

Info

The Return-to-Mean Clock: Measuring Price Reversion to Moving Averages is a Indicator for MetaTrader 5 that the return-to-mean clock indicator quantifies how long it takes for price to revert to a moving average after experiencing a significant deviation. This addresses a common trading concept: "Price is stretched, it will come back to the average.

Usage

This tool is typically used for enhancing chart analysis and decision making.

Platform

This Indicator works exclusively on MetaTrader 5 (both build 600+ and newer versions).

Setup

Place the downloaded file in MQL5/Indicators folder via File ? Open Data Folder in MetaTrader 5.


How to Install and Use Return-to-Mean Clock: Measuring Price Reversion to Moving Averages

1. Installation: Place your file in the MQL/Indicators folder via "Open Data Folder" and restart your terminal.

2. Loading: Find the indicator in the Navigator, drag it onto your chart, and configure the input parameters in the popup window.

3. Customization: Press Ctrl+I to open the indicator list, select your tool, and click "Properties" to change colors, levels, or visual styles.

4. Updating: Replace the old file in the Indicators folder with the new version and restart the platform to apply changes.

Frequently Asked Questions

Q: Why is my indicator not showing? A: Verify the file is in the MQL/Indicators folder, or try right-clicking the "Indicators" tree in the Navigator and clicking "Refresh."

Q: Do custom indicators slow down the platform? A: Too many complex indicators can impact performance; remove unused ones via the "Indicator List" (Ctrl+I).

Q: Can I use MT4 indicators on MT5? A: No, MQL4 and MQL5 are distinct languages; ensure the indicator is compiled specifically for your platform version.

What this tool does

The Return-to-Mean Clock indicator quantifies how long it takes for price to revert to a moving average after experiencing a significant deviation.

Typical Use Case

This Indicator excels in automated trading and technical analysis on MetaTrader 5.

Compatible Platform & Setup

This Indicator works on MetaTrader 5. Place the file in the MQL5/Indicators folder and restart the terminal.

Description & Settings

Related: Range Expansion Clock: Identifying Peak Range Formation Hours - another powerful indicator for MetaTrader 5 traders.

The Return-to-Mean Clock indicator quantifies how long it takes for price to revert to a moving average after experiencing a significant deviation. This addresses a common trading concept: "Price is stretched, it will come back to the average." This indicator provides measurable data on how stretched is too stretched, how often reversion actually occurs, and the timeframe involved (e.g., five bars or fifty). Without this data, relying on such ideas becomes mere intuition, potentially leading to losses for traders who wait for a reversion that never materializes.

Also recommended: Spread and Liquidity Clock: Time-of-Day Cost-to-Range Profile - similar indicator with strong performance on MetaTrader 5.


This indicator analyzes your chosen symbol, timeframe, and broker data to provide these insights.

Definitions:

Mean: An Exponential Moving Average (EMA) of the closing price over a specified period (InpMaPeriod).

Distance: Calculated as the difference between the closing price and the EMA, divided by the Average True Range (ATR) over a specified period (InpAtrPeriod). This value is positive when price is above the average and negative when below. Measuring distance in ATR units allows for comparison across different symbols and timeframes.

Stretch Event: A stretch event is initiated on a closed bar when the absolute distance from the average reaches a predefined level (InpLevel1, InpLevel2, InpLevel3) for the first time since the previous bar was below that level. If a bar's price crosses multiple levels, an event is triggered for each.

Outcome: Following an event, the indicator tracks the price action bar by bar until one of three conditions is met:
- Return: The closing price returns to or crosses the EMA.
- Further: The closing price moves at least a specified multiple of ATR (InpExtendAtr) beyond the event's level, measured from the average.
- None: Neither a return nor a further move occurs within a maximum number of bars (InpMaxBars).

A return and a further move cannot be recorded for the same bar, as both are determined by the closing price of that bar.

Clock: This represents the number of bars elapsed from the event's initiation to its conclusion (return). The panel displays the median (the number of bars taken for half of all observed returns) and the 80th percentile (the number of bars for 80% of returns).

Understanding the data is crucial. The indicator shows the proportion of stretches followed by a return versus those that move further away. This information is vital for traders assessing the risk and reward of fading price extremes.

The indicator operates without look-ahead bias. Events are only added to the statistics once their outcome is definitively known. The most recent, still-forming bar is shown in the histogram but does not influence the calculated statistics. Calculations are incremental, utilizing running EMA and ATR values, and a short-term list for tracking open events, ensuring efficiency without historical rescanning.

How to Interpret the Indicator:

Histogram (Indicator Window):
This displays one bar for each chart bar, representing the distance of the close from the EMA in ATR units. Gray bars indicate distances within the first level, while white bars show distances beyond it. Dotted lines mark the zero level and the three stretch levels on both sides.

Data Window:
- Distance from EMA (ATR): The current bar's distance from the EMA in ATR.
- Bars in stretch: The number of consecutive closed bars where the close has remained beyond the first level on the same side. This value is 0 when within the first level and empty for the bar currently forming.

Panel (Top Left of Chart):
- Line 1: Displays the symbol, timeframe, number of closed bars analyzed, settings for the mean period, the definition of a return, the distance considered 'further', and the maximum wait period.
- Line 2: Column headers.
- Lines 3-5: Data presented per stretch level. 'n' is the count of events with a concluded outcome. 'return', 'further', and 'none' represent the percentage share of each outcome, summing to 100%. 'median' and 'p80' show the bar count for returns, calculated only for events that resulted in a return.
- Line 6: Details of the current ongoing stretch. It shows the distance, side (above/below average), duration in bars, the highest level reached, and the return/further shares and median for that level.
- Line 7: A summary line with symbol, timeframe, bar count, EMA period, wait time, and for each level, the return share and median, formatted for easy copying into comments.

Dashes (--):
A row displays '--' instead of percentages if it has fewer than the minimum required events (InpMinCases). The median and p80 also show '--' if fewer than half of InpMinCases events (but at least 5) have resulted in a return.

Figure 1 (Example Description):
Illustrates the last 100 bars of a simulated H1 series demonstrating price reversion towards a slowly moving mean. The example chart includes a dashed line for the EMA(50) (note: the indicator itself primarily shows the distance histogram; a standard Moving Average indicator can be added to the chart for visualization). The histogram visualizes distance in ATR with dotted lines at 0, 1, 2, and 3 ATR. The panel indicates analysis of 5,052 closed bars, with the 'now' line showing a stretch of 2.85 ATR below the EMA for 11 bars. The numbers are from simulated data and do not represent real market conditions.

External Variables (Inputs):

Input Name
Default Value
Purpose

InpMaPeriod
50
Period for the Exponential Moving Average (EMA) of the mean (range: 5-500).

InpAtrPeriod
14
Period for the Average True Range (ATR) calculation, used as the unit for distance measurement (range: 5-200). The initial bars, up to twice the longer of InpMaPeriod and InpAtrPeriod, are used for EMA and ATR initialization and are excluded from analysis.

InpLevel1
1.0
The first stretch level in ATR units (range: 0.25-10).

InpLevel2
2.0
The second stretch level in ATR units. This level is automatically adjusted to be at least 0.25 ATR above InpLevel1.

InpLevel3
3.0
The third stretch level in ATR units. This level is automatically adjusted to be at least 0.25 ATR above InpLevel2.

InpMaxBars
30
The maximum number of bars to wait for an outcome after a stretch event is triggered (range: 5-100).

InpExtendAtr
1.0
Defines how far price must move beyond a stretch level (in ATR units) to be considered a 'further' move (range: 0.25-5).

InpHistoryBars
50000
The number of most recent bars to analyze upon indicator loading or full recalculation. Setting to 0 analyzes all available bars. New bars are continuously added as they form.

InpMinCases
30
The minimum number of completed events required before percentages are displayed for a given row (range: 5-1000).

InpShowPanel
true
Toggles the display of the statistics panel on the chart.

InpColorNormal
clrGray
The color used for histogram bars representing distances within the first stretch level.

InpColorStretch
clrWhite
The color used for histogram bars representing distances beyond the first stretch level.

InpTextColor
clrSilver
The color of the text elements within the statistics panel.

InpFontSize
8
The font size for the panel text. The line height is scaled proportionally to this size. (Example font: Consolas).

InpPanelX, InpPanelY
8, 14
The X and Y offsets in pixels from the upper-left corner of the chart where the statistics panel will be displayed.

Recommended Usage:

Symbols and Timeframes:
This indicator is suitable for any symbol and timeframe. The generated statistics are specific to the symbol, timeframe, and input settings used. Therefore, comparisons should be made between analyses using identical settings. Apply the indicator to the symbols you actively trade.

Analyze Columns Holistically:
Interpret the 'return' and 'further' percentages together. A high 'return' percentage might be misleading if a significant portion of those instances were preceded by a 'further' move. Consider the 'wait' time (median) to understand the typical duration of a return. The p80 value indicates the longer-term reversion scenario.

Impact of Trends:
Strong trending markets tend to exhibit fewer price reversions. The indicator's statistics represent an average across the entire analyzed history, including both ranging and trending phases. A stretch occurring during a strong trend may have different implications than one during a range-bound period, a distinction the indicator does not explicitly differentiate.

Mean Reversion Dynamics:
The moving average itself progresses with price. A 'return' event can occur either because price moves back to the average or because the average moves to the price. Both scenarios terminate the stretch. Using a slower EMA results in a more stable average and potentially fewer 'return' events.

Overlapping Events:
It's possible for price to dip below a level and then cross back above it within the InpMaxBars timeframe, initiating a new event while a previous one is still active. Since these events are not strictly independent, the actual uncertainty might be greater than the raw statistics suggest. Pay close attention to the 'n' column (number of cases). For rare events at higher levels, consider increasing InpHistoryBars to analyze a larger dataset.

Historical Data Analysis:
Experiment with the InpHistoryBars input to examine both older and more recent portions of the data. If the return rates differ significantly between historical segments, it may indicate that the symbol's reversion behavior is not constant over time.

Timeframe and Wait Period Alignment:
The default InpMaxBars (30) is suitable for longer timeframes but may be short for very short timeframes. Adjusting the wait period affects the classification of outcomes; a longer wait can convert 'none' outcomes into 'return' or 'further' events and increases the median wait time. Ensure consistency in input settings when comparing different symbols.

Edge vs. Profit:
This indicator highlights potential statistical edges based on historical data. It does not account for trading costs such as spread, swap, or slippage, nor does it explicitly account for the risk of a continued stretch. Entry and exit signals are not provided.

Past Performance Data:
The statistics reflect past market behavior within the loaded historical data. They are not predictive of future price movements or reversion probabilities.

Broker Data Dependency:
The accuracy of the analysis depends on the broker's data feed, including closing prices, highs, and lows, which can vary based on the data provider and timezone. Gaps in historical data or significant price jumps (e.g., over a weekend) can affect ATR calculations and potentially trigger multiple event levels simultaneously.

Performance and Resource Usage:
The indicator processes each bar once. It manages a list of up to 256 waiting events and stores a few hundred data points for the panel. Real-time updates primarily affect the currently forming bar and the panel display.

Chart Objects:
The indicator creates a panel on the main chart window, with lines typically prefixed with 'RM_P'. These objects are automatically removed when the indicator is de-initialized.

Account Type Compatibility:
The indicator functions independently of account types (netting or hedging) as it does not perform trading operations.

Community Data Sharing:
Share your findings by attaching the indicator to a chart, copying the last line of the panel, and posting it in the comments along with your broker's name and the symbol/timeframe. For example: EURUSD H1 | 50000 bars | EMA 50 | back at the EMA within 30 bars: 1.0 ATR 62% (median 4) | 2.0 ATR 66% (median 7) | 3.0 ATR 71% (median 11). This helps build a collective understanding of which symbols revert to the mean quickly and which do not, and how reversion likelihood changes at different levels.

You may also like: XAUUSD Hourly Volatility Clock: Typical Hourly Range vs. Current Hour - excellent alternative for indicator users on MetaTrader 5.

Source Code

#property copyright "RobotFX"
#property link "https://robotfx.org"
#property version     "1.00"
#property description "This code is educational. Feel free to use, modify and upgrade as you wish. Visit ROBOTFX.ORG for professional trading tools"
#property indicator_separate_window
#property indicator_buffers 3
#property indicator_plots   2
#property indicator_label1  "Distance from EMA (ATR)"
#property indicator_type1   DRAW_COLOR_HISTOGRAM
#property indicator_color1  clrGray, clrWhite

.......

Leave your opinion, ask a question, share some knowledge

⚠ Limitations & Risk Warning

  • This tool is provided for educational and testing purposes only.
  • Past performance does not guarantee future results.
  • Trading involves substantial risk of loss. Use on a demo account first.
  • Results may vary depending on market conditions, broker, and settings.
  • We recommend thorough backtesting and forward testing before using with real funds.
© ROBOTFX Free educational tools by RobotFX. Use entirely at your own risk; we are not liable for any financial losses incurred.