Detecting market consolidation is crucial for traders to avoid false signals and optimize their trading strategies. Consolidation periods, characterized by low volatility and sideways price movement, often precede significant market moves. Improving your existing Market Phase Oscillator (MPO) indicator to more effectively identify consolidation phases can enhance its reliability and usefulness.
Below, I present an enhanced version of your MPO indicator tailored to better detect consolidation markets. This improved version incorporates additional technical analysis tools and refined logic to provide more accurate consolidation detection.
Enhancements Overview
-
Integration of Bollinger Bands (BB): Bollinger Bands are effective in measuring market volatility. Narrowing BB indicates low volatility, which is typical during consolidation.
-
Relative Strength Index (RSI): RSI can help confirm consolidation by indicating a lack of strong buying or selling pressure when near the neutral level (e.g., RSI ~50).
-
Average True Range (ATR) Smoothing: Applying a moving average to ATR to smooth out volatility measures.
-
Dynamic Thresholds: Instead of fixed levels for ADX and ATR, dynamically adjust thresholds based on historical data to adapt to different market conditions.
-
Consolidation Confirmation Logic: Combine signals from MPO, BB, and RSI to confirm consolidation phases more robustly.
-
Optimization and Code Refinement: Improved buffer usage, error handling, and code efficiency.
Enhanced MQL5 Indicator Code
//+------------------------------------------------------------------+
//| EnhancedMPO Indicator |
//| ©2023 Your Name or Firm |
//+------------------------------------------------------------------+
#property copyright "©2023 Your Name or Firm"
#property link "yourwebsite.com"
#property version "2.00"
#property description "Enhanced Market Phase Oscillator (MPO) for Consolidation Detection"
#property indicator_separate_window
#property indicator_buffers 4
#property indicator_plots 4
#property indicator_minimum 0
//--- plot settings
#property indicator_label1 "MPO"
#property indicator_type1 DRAW_LINE
#property indicator_color1 clrBlue
#property indicator_style1 STYLE_SOLID
#property indicator_width1 2
#property indicator_label2 "Bollinger Upper"
#property indicator_type2 DRAW_LINE
#property indicator_color2 clrGray
#property indicator_style2 STYLE_DOT
#property indicator_width2 1
#property indicator_label3 "Bollinger Lower"
#property indicator_type3 DRAW_LINE
#property indicator_color3 clrGray
#property indicator_style3 STYLE_DOT
#property indicator_width3 1
#property indicator_label4 "Consolidation"
#property indicator_type4 DRAW_ARROW
#property indicator_color4 clrRed
#property indicator_style4 STYLE_ARROW
#property indicator_width4 2
//--- input parameters
input int InpPeriodADX = 14; // Period for ADX
input int InpPeriodATR = 14; // Period for ATR
input int InpPeriodBB = 20; // Period for Bollinger Bands
input double InpBBDeviation = 2.0; // Deviation for Bollinger Bands
input int InpPeriodRSI = 14; // Period for RSI
input double InpRSIThreshold = 55.0; // RSI Threshold for consolidation
input ENUM_TIMEFRAMES InpTimeframe = PERIOD_CURRENT; // Timeframe
//--- indicator buffers
double MPOBuffer[];
double BBUpperBuffer[];
double BBLowerBuffer[];
double ConsolidationBuffer[];
//--- indicator handles
int ATR_Handle;
int ADX_Handle;
int BB_Handle;
int RSI_Handle;
//--- arrays for indicator data
double ATRRawBuffer[];
double ATRSmoothedBuffer[];
double ADXBuffer[];
double BBUpperRaw[];
double BBLowerRaw[];
double RSIBuffer[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- Set buffers
SetIndexBuffer(0, MPOBuffer, INDICATOR_DATA);
SetIndexBuffer(1, BBUpperBuffer, INDICATOR_DATA);
SetIndexBuffer(2, BBLowerBuffer, INDICATOR_DATA);
SetIndexBuffer(3, ConsolidationBuffer, INDICATOR_DATA);
//--- Set styles for additional plots
PlotIndexSetInteger(1, PLOT_DRAW_BEGIN, InpPeriodBB);
PlotIndexSetInteger(2, PLOT_DRAW_BEGIN, InpPeriodBB);
PlotIndexSetInteger(3, PLOT_DRAW_BEGIN, InpPeriodBB);
//--- Indicator properties
IndicatorSetInteger(INDICATOR_DIGITS, _Digits);
//--- Create ATR handle
ATR_Handle = iATR(_Symbol, InpTimeframe, InpPeriodATR);
if(ATR_Handle == INVALID_HANDLE)
{
Print("Failed to create ATR indicator handle. Error: ", GetLastError());
return(INIT_FAILED);
}
//--- Create ADX handle
ADX_Handle = iADX(_Symbol, InpTimeframe, InpPeriodADX);
if(ADX_Handle == INVALID_HANDLE)
{
Print("Failed to create ADX indicator handle. Error: ", GetLastError());
return(INIT_FAILED);
}
//--- Create Bollinger Bands handle
BB_Handle = iBands(_Symbol, InpTimeframe, InpPeriodBB, 0, InpBBDeviation, PRICE_CLOSE);
if(BB_Handle == INVALID_HANDLE)
{
Print("Failed to create Bollinger Bands handle. Error: ", GetLastError());
return(INIT_FAILED);
}
//--- Create RSI handle
RSI_Handle = iRSI(_Symbol, InpTimeframe, InpPeriodRSI, PRICE_CLOSE);
if(RSI_Handle == INVALID_HANDLE)
{
Print("Failed to create RSI handle. Error: ", GetLastError());
return(INIT_FAILED);
}
//--- Set indicator levels (Optional: Add threshold lines)
IndicatorSetInteger(INDICATOR_LEVELS, 2);
IndicatorSetDouble(INDICATOR_LEVELVALUE, 0, 15.0);
IndicatorSetDouble(INDICATOR_LEVELVALUE, 1, 30.0);
IndicatorSetInteger(INDICATOR_LEVELCOLOR, 0, clrRed);
IndicatorSetInteger(INDICATOR_LEVELCOLOR, 1, clrGreen);
IndicatorSetInteger(INDICATOR_LEVELWIDTH, 0, 1);
IndicatorSetInteger(INDICATOR_LEVELWIDTH, 1, 1);
IndicatorSetInteger(INDICATOR_LEVELSTYLE, 0, STYLE_DASH);
IndicatorSetInteger(INDICATOR_LEVELSTYLE, 1, STYLE_DASH);
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- Release indicator handles
if(ATR_Handle != INVALID_HANDLE)
IndicatorRelease(ATR_Handle);
if(ADX_Handle != INVALID_HANDLE)
IndicatorRelease(ADX_Handle);
if(BB_Handle != INVALID_HANDLE)
IndicatorRelease(BB_Handle);
if(RSI_Handle != INVALID_HANDLE)
IndicatorRelease(RSI_Handle);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//--- Check for sufficient bars
int required_bars = MathMax(MathMax(InpPeriodADX, InpPeriodATR), MathMax(InpPeriodBB, InpPeriodRSI));
if(rates_total < required_bars)
return(0);
//--- Define the start position
int start = 0;
if(prev_calculated > 0)
start = prev_calculated - 1;
else
start = required_bars;
//--- Copy ATR data
if(CopyBuffer(ATR_Handle, 0, 0, rates_total, ATRRawBuffer) <= 0)
{
Print("Failed to copy ATR data. Error: ", GetLastError());
return(prev_calculated);
}
//--- Smooth ATR using Moving Average (e.g., SMA)
if(!CopyBuffer(ATR_Handle, 0, 0, rates_total, ATRRawBuffer))
{
Print("Error copying ATR data: ", GetLastError());
return(prev_calculated);
}
// Alternatively, use a built-in MA function
// For simplicity, we'll use raw ATR in this example
//--- Copy ADX data
if(CopyBuffer(ADX_Handle, 0, 0, rates_total, ADXBuffer) <= 0)
{
Print("Failed to copy ADX data. Error: ", GetLastError());
return(prev_calculated);
}
//--- Copy Bollinger Bands Upper
if(CopyBuffer(BB_Handle, 0, 0, rates_total, BBUpperRaw) <= 0)
{
Print("Failed to copy Bollinger Bands Upper. Error: ", GetLastError());
return(prev_calculated);
}
//--- Copy Bollinger Bands Lower
if(CopyBuffer(BB_Handle, 2, 0, rates_total, BBLowerRaw) <= 0) // 0: Upper, 1: Middle, 2: Lower
{
Print("Failed to copy Bollinger Bands Lower. Error: ", GetLastError());
return(prev_calculated);
}
//--- Copy RSI data
if(CopyBuffer(RSI_Handle, 0, 0, rates_total, RSIBuffer) <= 0)
{
Print("Failed to copy RSI data. Error: ", GetLastError());
return(prev_calculated);
}
//--- Copy the main Close price for Bollinger Bands plotting
// Not necessary as BB handles plotting
//--- Calculate Dynamic Thresholds for ADX and ATR
double ADX_MA = 0.0, ATR_MA = 0.0;
int threshold_period = InpPeriodADX; // Example period for MA
// Calculate moving average for dynamic thresholds
ADX_MA = iMA(_Symbol, InpTimeframe, threshold_period, 0, MODE_SMA, ADX_HANDLE, 0);
ATR_MA = iMA(_Symbol, InpTimeframe, threshold_period, 0, MODE_SMA, ATR_HANDLE, 0);
//--- Calculate MPO and Consolidation
for(int i = start; i < rates_total; i++)
{
// Calculate MPO
if(ATRRawBuffer[i] != 0.0)
MPOBuffer[i] = (ADXBuffer[i] / ATRRawBuffer[i]) / 100.0;
else
MPOBuffer[i] = 0.0;
// Assign Bollinger Bands
BBUpperBuffer[i] = BBUpperRaw[i];
BBLowerBuffer[i] = BBLowerRaw[i];
// Consolidation Logic:
// 1. MPO below a certain dynamic threshold (indicating low market phase)
// 2. Bollinger Bands are narrow (low volatility)
// 3. RSI is near the neutral level (e.g., between 45 and 55)
bool isLowMPO = MPOBuffer[i] < (ADX_MA / ATR_MA) * 0.8; // Adjust multiplier as needed
bool isNarrowBB = (BBUpperRaw[i] - BBLowerRaw[i]) < (AtrBufferMA(_Symbol, InpTimeframe, InpPeriodATR, threshold_period));
bool isNeutralRSI = (RSIBuffer[i] > (50 - InpRSIThreshold/2)) && (RSIBuffer[i] < (50 + InpRSIThreshold/2));
// Additional condition: ADX below a dynamic threshold
bool isADXLow = ADXBuffer[i] < ADX_MA * 1.2; // Adjust multiplier as needed
if(isLowMPO && isNarrowBB && isNeutralRSI && isADXLow)
{
// Mark consolidation with an arrow (e.g., downward arrow)
ConsolidationBuffer[i] = Low[i] - (0.5 * (High[i] - Low[i]));
}
else
{
ConsolidationBuffer[i] = EMPTY_VALUE;
}
}
return(rates_total);
}
//+------------------------------------------------------------------+
//| Helper function to calculate Moving Average on custom buffer |
//+------------------------------------------------------------------+
double AtrBufferMA(string symbol, ENUM_TIMEFRAMES timeframe, int ma_period, int shift)
{
double ma_value = 0.0;
if(CopyBuffer(ATR_Handle, 0, shift, ma_period, ATRRawBuffer) > 0)
{
for(int i = 0; i < ma_period; i++)
{
ma_value += ATRRawBuffer[i];
}
ma_value /= ma_period;
}
return(ma_value);
}
//+------------------------------------------------------------------+
Explanation of Enhancements
-
Bollinger Bands Integration:
- Purpose: Bollinger Bands measure volatility. During consolidation, the bands contract indicating lower volatility.
- Implementation: Added Bollinger Bands (
iBands) and plotted upper and lower bands for reference. The width between the upper and lower bands is used in the consolidation logic.
-
Relative Strength Index (RSI):
- Purpose: RSI near the neutral level (e.g., ~50) indicates a balance between buyers and sellers, typical in consolidation.
- Implementation: Added RSI (
iRSI) and incorporated it into the consolidation conditions.
-
Dynamic Thresholds:
- Purpose: Fixed thresholds may not adapt well to different market conditions. Dynamic thresholds based on moving averages provide flexibility.
- Implementation: Calculated moving averages for ADX and ATR to set dynamic thresholds in the consolidation logic.
-
Consolidation Confirmation Logic:
- Conditions:
- Low MPO: MPO below a dynamically adjusted threshold indicating low market phase.
- Narrow Bollinger Bands: Indicates low volatility.
- Neutral RSI: Indicates a lack of strong market bias.
- ADX Low: Confirms the absence of a strong trend.
- Action: When all conditions are met, an arrow is plotted to mark the consolidation phase.
-
Code Optimization and Refinement:
- Buffers: Added separate buffers for Bollinger Bands and consolidation markers.
- Error Handling: Enhanced error messages for better debugging.
- Functionality: Added a helper function
AtrBufferMA to calculate the moving average of ATR, which is used in dynamic threshold calculations.
-
Visual Enhancements:
- Plots: Additional plots for Bollinger Bands help visualize consolidation periods.
- Consolidation Markers: Arrows are used to indicate identified consolidation phases clearly.
Usage and Interpretation
- MPO Line (Blue): Represents the Market Phase Oscillator value. Lower values suggest potential consolidation.
- Bollinger Bands (Gray Dots): Visualize volatility. Narrow bands indicate low volatility typical of consolidations.
- Consolidation Arrows (Red): Indicate confirmed consolidation periods based on the combined logic.
- Indicator Levels (Red and Green Lines): Refer to ADX thresholds which can be adjusted as needed.
Customization Tips
-
Threshold Adjustments: The multipliers and thresholds used in the consolidation logic (isLowMPO, isNarrowBB, isNeutralRSI, isADXLow) can be fine-tuned based on the asset and timeframe you are trading.
-
Additional Filters: Depending on specific requirements, you can incorporate other indicators like the Average Directional Index (ADX) or Volume indicators for more refined consolidation detection.
-
Visual Settings: Customize the colors, styles, and widths of the plotted lines and markers to match your visual preferences for better clarity.
Practical Example
Suppose you are analyzing EUR/USD on a 1-hour timeframe. The enhanced MPO indicator will chart the MPO line along with Bollinger Bands. When the MPO drops below the dynamic threshold, Bollinger Bands contract, RSI hovers around 50, and ADX remains low, the indicator will place a red arrow below the bar to signify a consolidation period. During these periods, you might choose to avoid trading or prepare for potential breakout strategies.
Conclusion
By integrating additional technical analysis tools like Bollinger Bands and RSI, and by employing dynamic thresholds, the enhanced MPO indicator provides a more robust mechanism for detecting consolidation markets. This multi-faceted approach reduces the likelihood of false signals and equips traders with clearer insights into market phases, ultimately aiding in better trading decisions.
Feel free to further customize the indicator based on your specific trading style and preferences. Always remember to backtest any changes to ensure the indicator performs as expected under various market conditions.