// Open initial trades if ADX allows
if(CheckADX())
{
OpenBuyOrder(MiddleOfGrid + GridSpreadPoints);
OpenSellOrder(MiddleOfGrid - GridSpreadPoints);
}
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
// Close all positions if needed
if(MessageBox("Do you want to close all trades?", "Close Trades", MB_YESNO) == IDYES)
{
CloseAllPositions();
}
// Release the ADX indicator handle
IndicatorRelease(ADXHandle);
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
if(!CheckADX())
{
if(TradingAllowed)
{
CloseAllPositions();
TradingAllowed = false;
Print("ADX above threshold. Closing all trades and pausing trading.");
}
return;
}
//+------------------------------------------------------------------+
//| Open a buy order |
//+------------------------------------------------------------------+
void OpenBuyOrder(double takeProfit)
{
MqlTradeRequest request = {};
MqlTradeResult result = {};
//+------------------------------------------------------------------+
//| Open a sell order |
//+------------------------------------------------------------------+
void OpenSellOrder(double takeProfit)
{
MqlTradeRequest request = {};
MqlTradeResult result = {};
and this is an indicator that speacalizes in detecting consolidating:
//+------------------------------------------------------------------+
//| consilidation X3.mq5 |
//| |
//| Copyright 2024, Your Name |
//+------------------------------------------------------------------+
#property copyright "Copyright 2024"
#property link ""
#property version "1.00"
#property indicator_separate_window
#property indicator_buffers 6
#property indicator_plots 6
//--- Enums for MA types
enum ENUM_MA_TYPE {
MA_SMA, // Simple
MA_EMA, // Exponential
MA_SMMA, // Smoothed
MA_LWMA // Linear Weighted
};
//--- Set drawing begin
PlotIndexSetInteger(0, PLOT_DRAW_BEGIN, Period1);
PlotIndexSetInteger(2, PLOT_DRAW_BEGIN, Period2);
PlotIndexSetInteger(4, PLOT_DRAW_BEGIN, Period3);
//--- set accuracy
IndicatorSetInteger(INDICATOR_DIGITS, 4);
//--- set empty values
PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, 0.0);
PlotIndexSetDouble(1, PLOT_EMPTY_VALUE, 0.0);
PlotIndexSetDouble(2, PLOT_EMPTY_VALUE, 0.0);
PlotIndexSetDouble(3, PLOT_EMPTY_VALUE, 0.0);
PlotIndexSetDouble(4, PLOT_EMPTY_VALUE, 0.0);
PlotIndexSetDouble(5, PLOT_EMPTY_VALUE, 0.0);
//--- set indicator name
string short_name = "Triple Consolidation Ratio (Smoothed)";
IndicatorSetString(INDICATOR_SHORTNAME, short_name);
// Delete any existing rectangles
DeleteAllRectangles();
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason) {
DeleteAllRectangles();
}
//+------------------------------------------------------------------+
//| Calculate MA based on type |
//+------------------------------------------------------------------+
double CalculateMA(const double &values[], int position, int period, ENUM_MA_TYPE maType) {
if(position < period - 1) return 0;
code
double ma = 0;
double sum = 0;
double weight = 0;
double weightSum = 0;
switch(maType) {
case MA_SMA: {
for(int i = 0; i < period; i++)
sum += values[position - i];
ma = sum / period;
break;
}
case MA_EMA: {
double alpha = 2.0 / (period + 1.0);
ma = values[position];
for(int i = 1; i < period; i++)
ma = (values[position - i] * alpha) + (ma * (1.0 - alpha));
break;
}
case MA_SMMA: {
double alpha = 1.0 / period;
ma = values[position];
for(int i = 1; i < period; i++)
ma = (values[position - i] * alpha) + (ma * (1.0 - alpha));
break;
}
case MA_LWMA: {
for(int i = 0; i < period; i++) {
weight = period - i;
sum += values[position - i] * weight;
weightSum += weight;
}
ma = sum / weightSum;
break;
}
}
return ma;
}
//+------------------------------------------------------------------+
//| Calculate consolidation ratio for given period and MA type |
//+------------------------------------------------------------------+
double CalculateRatio(const double &open[], const double &close[], int position,
int period, ENUM_MA_TYPE maType) {
if(position < period) return 0;
code
double ranges[];
ArrayResize(ranges, period);
ArrayInitialize(ranges, 0);
// Calculate ranges
for(int i = 0; i < period; i++) {
ranges[i] = MathAbs(open[position-i] - close[position-i]);
}
// Calculate average range using specified MA type
double avgRange = CalculateMA(ranges, period-1, period, maType);
if(avgRange == 0) return 0;
// Calculate expected total range
double expectedRange = avgRange * period;
// Calculate actual price change
double actualChange = MathAbs(close[position] - close[position - period]);
// Return ratio
return actualChange / expectedRange;
}
//+------------------------------------------------------------------+
//| Delete all rectangles drawn by the indicator |
//+------------------------------------------------------------------+
void DeleteAllRectangles() {
ObjectsDeleteAll(0, rectPrefix);
}
//+------------------------------------------------------------------+
//| Check if all ratios indicate consolidation |
//+------------------------------------------------------------------+
bool IsConsolidating(int position) {
if(position < 0) return false;
Yes, you can integrate the indicator into the Expert Advisor (EA) to use its consolidation detection logic instead of the ADX indicator. Below is the updated EA code with the consolidation detection logic integrated. The ADX-related code has been replaced with the functions and parameters from your indicator.
mq5
#property copyright "Copyright 2023, Your Name"
#property link "https://www.mql5.com"
#property version "1.05"
#property strict
#include <Trade\Trade.mqh> // Include trade functions
//--- Input parameters
input string Symbol = "EURUSD"; // Trading symbol
input double GridSpreadPips = 60; // Grid spread in pips
input int MaxTradesOpen = 20; // Maximum number of open trades
input int MagicNumber = 11223344585; // Magic number for identifying bot trades
input double RiskPercentage = 100.0; // Total account risk percentage
// Consolidation detection parameters (from the indicator)
input int Period1 = 21; // Period 1
input ENUM_MA_METHOD MAType1 = MODE_SMA; // MA Type 1
input double Threshold1 = 0.25; // Threshold 1
input int Period2 = 52; // Period 2
input ENUM_MA_METHOD MAType2 = MODE_EMA; // MA Type 2
input double Threshold2 = 0.15; // Threshold 2
input int Period3 = 120; // Period 3
input ENUM_MA_METHOD MAType3 = MODE_SMMA; // MA Type 3
input double Threshold3 = 0.1; // Threshold 3
input int SmoothingPeriod = 3; // Smoothing Period
input ENUM_MA_METHOD SmoothingMAType = MODE_EMA; // Smoothing MA Type
// Global variables
double GridSpreadPoints;
double MiddleOfGrid;
double GridLevels[];
double LotSize;
bool TradingAllowed = true;
CTrade trade; // Trade object for executing orders
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
// Convert pips to points
GridSpreadPoints = GridSpreadPips * 10 * SymbolInfoDouble(Symbol, SYMBOL_POINT);
// Calculate lot size
LotSize = CalculateLotSize();
// Initialize grid
MiddleOfGrid = SymbolInfoDouble(Symbol, SYMBOL_BID);
UpdateGridLevels();
// Open initial trades if market is consolidating
if(CheckConsolidation())
{
OpenBuyOrder(MiddleOfGrid + GridSpreadPoints);
OpenSellOrder(MiddleOfGrid - GridSpreadPoints);
}
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
// Close all positions if needed
if(MessageBox("Do you want to close all trades?", "Close Trades", MB_YESNO) == IDYES)
{
CloseAllPositions();
}
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
if(!CheckConsolidation())
{
if(TradingAllowed)
{
CloseAllPositions();
TradingAllowed = false;
Print("Market is not consolidating. Closing all trades and pausing trading.");
}
return;
}
if(!TradingAllowed)
{
TradingAllowed = true;
Print("Market is consolidating. Resuming trading.");
}
double currentPrice = (SymbolInfoDouble(Symbol, SYMBOL_BID) + SymbolInfoDouble(Symbol, SYMBOL_ASK)) / 2;
if(currentPrice <= GridLevels[0] || currentPrice >= GridLevels[2])
{
if(GetOpenPositionsCount() + 2 <= MaxTradesOpen)
{
Print("Opening new positions... ", Symbol);
OpenBuyOrder(currentPrice + GridSpreadPoints);
OpenSellOrder(currentPrice - GridSpreadPoints);
}
else
{
CloseAllPositions();
}
MiddleOfGrid = currentPrice;
UpdateGridLevels();
}
}
//+------------------------------------------------------------------+
//| Check if the market is consolidating |
//+------------------------------------------------------------------+
bool CheckConsolidation()
{
int maxPeriod = MathMax(MathMax(Period1, Period2), Period3) + SmoothingPeriod + 10;
// Get price data
MqlRates priceData[];
if(CopyRates(Symbol(), Period(), 0, maxPeriod, priceData) != maxPeriod)
{
Print("Not enough price data to calculate consolidation ratios.");
return false;
}
int dataSize = ArraySize(priceData);
double openPrices[], closePrices[];
ArrayResize(openPrices, dataSize);
ArrayResize(closePrices, dataSize);
for(int i = 0; i < dataSize; i++)
{
openPrices[i] = priceData[i].open;
closePrices[i] = priceData[i].close;
}
int position = dataSize - 1; // Latest data point
// Calculate ratios
double ratio1 = CalculateRatio(openPrices, closePrices, position, Period1, MAType1);
double ratio2 = CalculateRatio(openPrices, closePrices, position, Period2, MAType2);
double ratio3 = CalculateRatio(openPrices, closePrices, position, Period3, MAType3);
// Apply smoothing if SmoothingPeriod > 1
if(SmoothingPeriod > 1)
{
double ratios1[], ratios2[], ratios3[];
ArrayResize(ratios1, dataSize);
ArrayResize(ratios2, dataSize);
ArrayResize(ratios3, dataSize);
// Store ratios in arrays
for(int i = 0; i < dataSize; i++)
{
ratios1[i] = CalculateRatio(openPrices, closePrices, i, Period1, MAType1);
ratios2[i] = CalculateRatio(openPrices, closePrices, i, Period2, MAType2);
ratios3[i] = CalculateRatio(openPrices, closePrices, i, Period3, MAType3);
}
// Apply smoothing
ratio1 = CalculateMA(ratios1, position, SmoothingPeriod, SmoothingMAType);
ratio2 = CalculateMA(ratios2, position, SmoothingPeriod, SmoothingMAType);
ratio3 = CalculateMA(ratios3, position, SmoothingPeriod, SmoothingMAType);
}
// Compare ratios with thresholds
bool isConsolidating = (ratio1 < Threshold1) && (ratio2 < Threshold2) && (ratio3 < Threshold3);
return isConsolidating;
}
//+------------------------------------------------------------------+
//| Calculate moving average based on type |
//+------------------------------------------------------------------+
double CalculateMA(const double &values[], int position, int period, ENUM_MA_METHOD maType)
{
if(position < period - 1) return 0;
double ma = 0;
switch(maType)
{
case MODE_SMA:
{
double sum = 0;
for(int i = 0; i < period; i++)
sum += values[position - i];
ma = sum / period;
break;
}
case MODE_EMA:
{
double alpha = 2.0 / (period + 1.0);
ma = values[position];
for(int i = 1; i < period; i++)
ma = (values[position - i] * alpha) + (ma * (1.0 - alpha));
break;
}
case MODE_SMMA:
{
double alpha = 1.0 / period;
ma = values[position];
for(int i = 1; i < period; i++)
ma = (values[position - i] * alpha) + (ma * (1.0 - alpha));
break;
}
case MODE_LWMA:
{
double sum = 0;
double weightSum = 0;
for(int i = 0; i < period; i++)
{
double weight = period - i;
sum += values[position - i] * weight;
weightSum += weight;
}
ma = sum / weightSum;
break;
}
default:
ma = 0;
break;
}
return ma;
}
//+------------------------------------------------------------------+
//| Calculate consolidation ratio for a given period and MA type |
//+------------------------------------------------------------------+
double CalculateRatio(const double &openPrices[], const double &closePrices[], int position, int period, ENUM_MA_METHOD maType)
{
if(position < period) return 0;
double ranges[];
ArrayResize(ranges, period);
// Calculate ranges
for(int i = 0; i < period; i++)
{
ranges[i] = MathAbs(openPrices[position - i] - closePrices[position - i]);
}
// Calculate average range using specified MA type
double avgRange = CalculateMA(ranges, period - 1, period, maType);
if(avgRange == 0) return 0;
// Calculate expected total range
double expectedRange = avgRange * period;
// Calculate actual price change
double actualChange = MathAbs(closePrices[position] - closePrices[position - period]);
// Return ratio
return actualChange / expectedRange;
}
//+------------------------------------------------------------------+
//| Calculate lot size based on risk and max trades |
//+------------------------------------------------------------------+
double CalculateLotSize()
{
double accountBalance = AccountInfoDouble(ACCOUNT_BALANCE);
double leverage = AccountInfoInteger(ACCOUNT_LEVERAGE);
double includingLeverage = accountBalance * leverage;
string baseCurrency = StringSubstr(Symbol, 0, 3);
string accountCurrency = AccountInfoString(ACCOUNT_CURRENCY);
double conversionRate = 1;
if(baseCurrency != accountCurrency)
{
string conversionPair = baseCurrency + accountCurrency;
conversionRate = SymbolInfoDouble(conversionPair, SYMBOL_BID);
if(conversionRate == 0) // If direct conversion is not available, try inverse
{
conversionPair = accountCurrency + baseCurrency;
conversionRate = 1 / SymbolInfoDouble(conversionPair, SYMBOL_BID);
}
}
double lotValueInAccountCurrency = 100000 * conversionRate;
double lotsInAccount = (includingLeverage * RiskPercentage / 100) / lotValueInAccountCurrency;
double lotSizePerTrade = NormalizeDouble(lotsInAccount / MaxTradesOpen, 2);
// Ensure lot size is within allowed limits
double minLot = SymbolInfoDouble(Symbol, SYMBOL_VOLUME_MIN);
double maxLot = SymbolInfoDouble(Symbol, SYMBOL_VOLUME_MAX);
lotSizePerTrade = MathMax(minLot, MathMin(maxLot, lotSizePerTrade));
Print("Calculated Lot Size per trade: ", lotSizePerTrade);
return lotSizePerTrade;
}
//+------------------------------------------------------------------+
//| Update grid levels |
//+------------------------------------------------------------------+
void UpdateGridLevels()
{
ArrayResize(GridLevels, 3);
GridLevels[0] = MiddleOfGrid - GridSpreadPoints;
GridLevels[1] = MiddleOfGrid;
GridLevels[2] = MiddleOfGrid + GridSpreadPoints;
}
//+------------------------------------------------------------------+
//| Open a buy order |
//+------------------------------------------------------------------+
void OpenBuyOrder(double takeProfit)
{
trade.SetExpertMagicNumber(MagicNumber);
trade.Buy(LotSize, Symbol, 0, takeProfit, 0, "Grid Buy Order");
}
//+------------------------------------------------------------------+
//| Open a sell order |
//+------------------------------------------------------------------+
void OpenSellOrder(double takeProfit)
{
trade.SetExpertMagicNumber(MagicNumber);
trade.Sell(LotSize, Symbol, 0, takeProfit, 0, "Grid Sell Order");
}
//+------------------------------------------------------------------+
//| Close all positions |
//+------------------------------------------------------------------+
void CloseAllPositions()
{
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
ulong ticket = PositionGetTicket(i);
if(PositionSelectByTicket(ticket))
{
if(PositionGetString(POSITION_SYMBOL) == Symbol && PositionGetInteger(POSITION_MAGIC) == MagicNumber)
{
trade.PositionClose(ticket);
}
}
}
LotSize = CalculateLotSize();
}
//+------------------------------------------------------------------+
//| Get the count of open positions for our EA |
//+------------------------------------------------------------------+
int GetOpenPositionsCount()
{
int count = 0;
for(int i = 0; i < PositionsTotal(); i++)
{
ulong ticket = PositionGetTicket(i);
if(PositionSelectByTicket(ticket))
{
if(PositionGetString(POSITION_SYMBOL) == Symbol && PositionGetInteger(POSITION_MAGIC) == MagicNumber)
{
count++;
}
}
}
return count;
}
Explanation of the Changes:
Removed ADX-related Code: The ADX indicator and its associated functions and variables have been removed since we're replacing it with the consolidation detection logic.
Integrated Indicator Logic:
Added the input parameters from the indicator to the EA's input parameters.
Implemented the CalculateMA(), CalculateRatio(), and CheckConsolidation() functions in the EA to replicate the consolidation detection logic from the indicator.
The CheckConsolidation() function retrieves the necessary historical price data and calculates the ratios to determine if the market is consolidating.
Updated the Trading Logic:
Replaced calls to CheckADX() with CheckConsolidation() in the OnInit() and OnTick() functions.
The EA now checks if the market is consolidating before opening or closing positions.
Optimized Position Handling:
Added a GetOpenPositionsCount() function to accurately count the number of open positions associated with the EA (using the MagicNumber and Symbol).
Modified CloseAllPositions() to only close positions that were opened by the EA (matching MagicNumber and Symbol).
Note:
This integration assumes that you want to use the consolidation detection logic in place of the ADX indicator to control when the EA opens or closes trades.
The EA now uses the CTrade class (included via Trade\Trade.mqh) for executing trade operations, which simplifies order placement and management.
Make sure to test the EA thoroughly in a demo environment before running it in a live account to ensure that it behaves as expected.