//--- 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 int InpThresholdRSI = 10; // RSI Threshold range around 50 for consolidation
input ENUM_TIMEFRAMES InpTimeframe = PERIOD_CURRENT; // Timeframe
//--- Set indicator levels (Optional: Add threshold lines)
IndicatorSetInteger(INDICATOR_LEVELS, 2);
// Set other indicator levels if needed
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);
//--- Delete all rectangle objects created by this indicator
long total_objects = ObjectsTotal(0, -1, -1);
for (int i = total_objects - 1; i >= 0; i--)
{
string obj_name = ObjectName(0, i);
if (StringFind(obj_name, "Consolidation_", 0) != -1)
{
ObjectDelete(0, obj_name);
}
}
}
//+------------------------------------------------------------------+
//| 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)) + 10; // Extra buffer
if (rates_total < required_bars)
return(0);
//--- Determine the start position for calculation
int start = 0;
if (prev_calculated > 0)
start = prev_calculated - 1;
else
start = 0; // Start from the beginning
//--- Declare dynamic threshold variables
double ADX_MA, ATR_MA;
int threshold_period = InpPeriodADX; // Example period for MA
//--- Calculate Moving Averages for dynamic thresholds
//--- ADX Moving Average
ADX_MA = 0.0;
if (CopyBuffer(ADX_Handle, 0, 0, threshold_period, ADXBuffer) > 0)
{
for (int i = 0; i < threshold_period; i++)
{
ADX_MA += ADXBuffer[i];
}
ADX_MA /= threshold_period;
}
else
{
Print("Failed to copy ADX buffer for MA calculation. Error: ", GetLastError());
return(prev_calculated);
}
//--- ATR Moving Average
ATR_MA = 0.0;
if (CopyBuffer(ATR_Handle, 0, 0, threshold_period, ATRBuffer) > 0)
{
for (int i = 0; i < threshold_period; i++)
{
ATR_MA += ATRBuffer[i];
}
ATR_MA /= threshold_period;
}
else
{
Print("Failed to copy ATR buffer for MA calculation. Error: ", GetLastError());
return(prev_calculated);
}
//--- Loop through each bar
for (int i = start; i < rates_total; i++)
{
//--- Calculate MPO
if (ATRBuffer[i] != 0.0)
MPOBuffer[i] = (ADXBuffer[i] / ATRBuffer[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 50 - InpThresholdRSI/2 and 50 + InpThresholdRSI/2)
// 4. ADX below a dynamic threshold
bool isLowMPO = MPOBuffer[i] < (ADX_MA / ATR_MA) * 0.8; // Adjust multiplier as needed
bool isNarrowBB = (BBUpperRaw[i] - BBLowerRaw[i]) < ATR_MA * 0.5; // Example: BB width less than half ATR MA
bool isNeutralRSI = (RSIBuffer[i] > (50 - InpThresholdRSI / 2)) && (RSIBuffer[i] < (50 + InpThresholdRSI / 2));
bool isADXLow = ADXBuffer[i] < ADX_MA * 1.2; // Adjust multiplier as needed
bool isConsolidation = isLowMPO && isNarrowBB && isNeutralRSI && isADXLow;
if (isConsolidation)
{
if (!inConsolidation)
{
// Consolidation starts
inConsolidation = true;
consolidationStartTime = time[i];
consolidationHigh = high[i];
consolidationLow = low[i];
}
else
{
// Update high and low for the consolidation period
if (high[i] > consolidationHigh) consolidationHigh = high[i];
if (low[i] < consolidationLow) consolidationLow = low[i];
}
}
else
{
if (inConsolidation)
{
// Consolidation ends
datetime consolidationEndTime = time[i];
inConsolidation = false;
// Create rectangle object
string objName = "Consolidation_" + IntegerToString(consolidationStartTime);
ObjectDelete(0, objName); // Delete if already exists
bool created = ObjectCreate(0, objName, OBJ_RECTANGLE, 0,
consolidationStartTime, consolidationHigh,
consolidationEndTime, consolidationLow);
if (created)
{
// Set properties
ObjectSetInteger(0, objName, OBJPROP_COLOR, clrYellow);
ObjectSetInteger(0, objName, OBJPROP_STYLE, STYLE_SOLID);
ObjectSetInteger(0, objName, OBJPROP_WIDTH, 1);
ObjectSetInteger(0, objName, OBJPROP_FILL, true);
ObjectSetInteger(0, objName, OBJPROP_BACK, true); // Draw in background
color fillColor = clrYellow;
fillColor = ColorToARGB(fillColor, 128); // 128 is half transparency (0-255)
ObjectSetInteger(0, objName, OBJPROP_BGCOLOR, fillColor);
}
else
{
Print("Failed to create rectangle object. Error: ", GetLastError());
}
}
}
The reason your indicator is not drawing rectangles is because the dynamic thresholds ADX_MA and ATR_MA are calculated only once at the beginning of your OnCalculate function, using static data from the oldest bars. This means that they're not updated per bar as you iterate through your data, causing your consolidation conditions to rarely (or never) be met, especially in the newer bars. Since the conditions for marking consolidation are not being satisfied, the indicator never attempts to create rectangle objects to represent these periods.
Detailed Explanation:
Dynamic Thresholds Not Updated Per Bar:
In your code, you calculate ADX_MA and ATR_MA before the main loop, using the earliest threshold_period number of bars:
//--- ADX Moving Average
ADX_MA = 0.0;
if (CopyBuffer(ADX_Handle, 0, 0, threshold_period, ADXBuffer) > 0)
{
for (int i = 0; i < threshold_period; i++)
{
ADX_MA += ADXBuffer[i];
}
ADX_MA /= threshold_period;
}
The same approach is taken for ATR_MA.
This means that ADX_MA and ATR_MA are static values representing the average of the earliest threshold_period bars in your data and don't reflect the current state of the market as you progress through your data in the loop.
Conditions for Consolidation Never Met:
Since ADX_MA and ATR_MA are static and do not reflect the values at each bar, your consolidation conditions likely remain false throughout the data:
Because of this, isConsolidation remains false, and the code inside the block that creates rectangles is never executed.
Fix: Calculate Moving Averages Per Bar:
To correct this, you need to calculate ADX_MA and ATR_MA at each bar within your loop, so that they reflect the dynamic nature of the market data.
Here's how you can modify your code:
// Initialize sum variables
double sumADX = 0.0;
double sumATR = 0.0;
// Loop through each bar
for (int i = start; i < rates_total; i++)
{
// Update sums
if (i >= threshold_period)
{
sumADX += ADXBuffer[i];
sumATR += ATRBuffer[i];
// Subtract values that are no longer in the moving average window
sumADX -= ADXBuffer[i - threshold_period];
sumATR -= ATRBuffer[i - threshold_period];
}
else
{
sumADX += ADXBuffer[i];
sumATR += ATRBuffer[i];
}
// Calculate moving averages when enough data is available
if (i >= threshold_period - 1)
{
ADX_MA = sumADX / threshold_period;
ATR_MA = sumATR / threshold_period;
}
else
{
// Not enough data to compute MA, skip to next iteration
continue;
}
// Now your conditions will be accurate per bar
bool isLowMPO = MPOBuffer[i] < (ADX_MA / ATR_MA) * 0.8;
bool isNarrowBB = (BBUpperRaw[i] - BBLowerRaw[i]) < ATR_MA * 0.5;
bool isNeutralRSI = (RSIBuffer[i] > (50 - InpThresholdRSI / 2)) && (RSIBuffer[i] < (50 + InpThresholdRSI / 2));
bool isADXLow = ADXBuffer[i] < ADX_MA * 1.2;
bool isConsolidation = isLowMPO && isNarrowBB && isNeutralRSI && isADXLow;
// (Rest of your code remains the same)
}
By recalculating ADX_MA and ATR_MA inside the loop, you ensure that these thresholds are accurate for each bar, so your conditions will correctly identify consolidation periods.
Additional Debugging Tips:
Print Statements: Add Print() statements inside your loop to check the values of your variables at each step. This will help you understand if the conditions are ever met and why.
Error Messages: Check the Experts or Journal tab in your MetaTrader platform for any error messages. Your code already includes printing errors when copying buffers fails.
Object Creation: Ensure that your ObjectCreate() function is being called with valid parameters. Even with correct conditions, if the parameters are invalid (e.g., times and prices not on the chart), the rectangle won't appear.
Ensure Correct Indexing:
Remember that in MQL5, arrays in OnCalculate are indexed such that time[0] corresponds to the oldest bar, and time[rates_total - 1] is the most recent bar.
Your loop from start to rates_total aligns with this indexing, but ensure that all your array accesses are correct.
Confirm Object Coordinates:
Double-check that consolidationStartTime, consolidationEndTime, consolidationHigh, and consolidationLow have valid values that exist within the visible portion of your chart.
You may want to print these values whenever you attempt to create a rectangle to ensure they're correct:
Print("Creating rectangle from ", TimeToString(consolidationStartTime), " to ", TimeToString(consolidationEndTime), " high: ", consolidationHigh, " low: ", consolidationLow);
Conclusion:
By recalculating ADX_MA and ATR_MA inside your main loop so they reflect the dynamic state of the market at each bar, you allow your consolidation conditions to be accurately evaluated. This correction should result in the rectangles being drawn during periods of consolidation as intended.