Your Expert Advisor (EA) for MetaTrader 5 is quite comprehensive, incorporating multiple indicators and advanced risk management features. Below is a detailed review of your code, highlighting potential issues, areas for improvement, and best practices to enhance its performance and reliability.
1. Indicator Handle Management
Issue:
In MQL5, each call to indicator functions like iMA, iATR, etc., creates a new indicator handle. However, in your current implementation, these handles are not released, leading to potential resource leaks. Over time, this can exhaust the available handles, causing your EA to malfunction.
Recommendation:
Initialize all necessary indicator handles once in the OnInit function and release them in the OnDeinit function. This approach improves efficiency and prevents resource leaks.
Implementation:
// Global indicator handles
int handleADX;
int handleSMA;
int handleWMA;
int handleHMA;
int handleROC;
int handleBollinger;
int handleRSI;
int handleMACD;
int handleATR;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
initialBalance = AccountInfoDouble(ACCOUNT_BALANCE);
Print("EA initialized. Initial Balance: ", initialBalance);
// Initialize ADX
handleADX = iADX("XAUUSD", PERIOD_H1, 14);
if(handleADX == INVALID_HANDLE) {
Print("Failed to initialize ADX indicator.");
return(INIT_FAILED);
}
// Initialize SMA
handleSMA = iMA("XAUUSD", PERIOD_H1, SMAPeriod, 0, MODE_SMA, PRICE_CLOSE);
if(handleSMA == INVALID_HANDLE) {
Print("Failed to initialize SMA indicator.");
return(INIT_FAILED);
}
// Initialize other indicators similarly...
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
// Release indicator handles
IndicatorRelease(handleADX);
IndicatorRelease(handleSMA);
// Release other handles similarly...
Print("EA deinitialized. Reason: ", reason);
}
Benefits:
- Efficiency: Reduces the overhead of creating and destroying handles on every tick.
- Resource Management: Prevents handle exhaustion by properly releasing resources.
2. Calculation of Indicators
Issue:
Manual calculations for indicators like WMA and HMA, while educational, can be inefficient and error-prone. Additionally, functions like CalculateVWAP are manually implemented, which might not account for all nuances of the VWAP calculation.
Recommendation:
Leverage built-in MQL5 indicator functions wherever possible. For custom indicators like HMA, ensure accurate implementation or consider using available libraries.
Implementation:
double GetWMA(string symbol, ENUM_TIMEFRAMES timeframe, int period, int shift)
{
return iMA(symbol, timeframe, period, 0, MODE_WMA, PRICE_CLOSE, shift);
}
double GetHMA(string symbol, ENUM_TIMEFRAMES timeframe, int period, int shift)
{
// HMA calculation requires a custom approach or use of an existing library
// Ensure your implementation accurately reflects HMA's weighted calculation
// Consider verifying with known HMA values
// Alternatively, search for a reliable HMA library or implementation
}
Benefits:
- Accuracy: Built-in functions are optimized and tested for accuracy.
- Performance: Reduces computational overhead compared to manual calculations.
3. Order Placement Logic
Issue:
The PlaceOrder function calculates stopLossPips and takeProfitPips using the ATR value divided by _Point. However, ATR is typically in price units, and dividing by _Point might not yield the correct number of pips, especially for symbols like XAUUSD which have higher price magnitudes.
Recommendation:
Ensure that SL and TP are calculated in terms of points or pips correctly. For metals like XAUUSD, it's often better to define SL and TP in price units directly or adjust the calculation based on the symbol's characteristics.
Implementation:
void PlaceOrder(string symbol, bool buy)
{
MqlTradeRequest request;
MqlTradeResult result;
ZeroMemory(request);
ZeroMemory(result);
double atr = CalculateATR(symbol, PERIOD_H1, ATRPeriod, 0); // Use PERIOD_H1 for consistency
double stopLossPrice = atr * ATRMultiplier;
double takeProfitPrice = stopLossPrice * RiskToRewardRatio;
request.action = TRADE_ACTION_DEAL;
request.symbol = symbol;
request.volume = LotSize;
request.deviation = 5;
request.magic = MagicNumber;
double ask = SymbolInfoDouble(symbol, SYMBOL_ASK);
double bid = SymbolInfoDouble(symbol, SYMBOL_BID);
if (buy)
{
request.type = ORDER_TYPE_BUY;
request.price = ask;
request.sl = request.price - stopLossPrice;
request.tp = request.price + takeProfitPrice;
Print("Placing BUY order on ", symbol, " Price: ", request.price, ", SL: ", request.sl, ", TP: ", request.tp);
}
else
{
request.type = ORDER_TYPE_SELL;
request.price = bid;
request.sl = request.price + stopLossPrice;
request.tp = request.price - takeProfitPrice;
Print("Placing SELL order on ", symbol, " Price: ", request.price, ", SL: ", request.sl, ", TP: ", request.tp);
}
request.type_filling = ORDER_FILLING_FOK; // Choose appropriate filling mode
request.type_time = ORDER_TIME_GTC;
if(!OrderSend(request, result))
{
Print("OrderSend failed with error #", GetLastError(), " on ", symbol);
}
else
{
Print("Order placed successfully on ", symbol, ". Ticket: ", result.order);
}
}
Benefits:
- Accuracy: Ensures SL and TP are set in correct price units.
- Consistency: Uses consistent timeframes for ATR calculations.
- Simplicity: Simplifies the SL and TP calculation logic.
4. Trailing Stop Management
Issue:
The trailing stop logic currently adjusts the SL only once and does not account for continuous trailing as the price moves favorably.
Recommendation:
Implement a dynamic trailing stop that continuously adjusts the SL based on price movements. Ensure that SL is only moved in the direction of profit and never reduces the potential profit.
Implementation:
void ManageTrades()
{
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
ulong ticket = PositionGetTicket(i);
if(PositionSelectByTicket(ticket))
{
double currentProfit = PositionGetDouble(POSITION_PROFIT);
double openPrice = PositionGetDouble(POSITION_PRICE_OPEN);
string symbol = PositionGetString(POSITION_SYMBOL);
ENUM_POSITION_TYPE posType = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
double currentPrice = (posType == POSITION_TYPE_BUY) ? SymbolInfoDouble(symbol, SYMBOL_BID) : SymbolInfoDouble(symbol, SYMBOL_ASK);
double sl = PositionGetDouble(POSITION_SL);
double tp = PositionGetDouble(POSITION_TP);
// Early profit taking
if(currentProfit >= EarlyProfitPips * _Point)
{
Print("Closing position early for profit - Ticket: ", ticket, ", Profit: ", currentProfit);
trade.PositionClose(ticket);
continue;
}
// Trailing stop logic
double trailStopPrice;
if(posType == POSITION_TYPE_BUY)
{
trailStopPrice = currentPrice - TrailingStopPips * _Point;
if(trailStopPrice > sl)
{
if(trade.PositionModify(ticket, trailStopPrice, tp))
Print("Trailing SL adjusted for BUY - New SL: ", trailStopPrice);
else
Print("Failed to modify BUY position - Ticket: ", ticket, ", Error: ", GetLastError());
}
}
else if(posType == POSITION_TYPE_SELL)
{
trailStopPrice = currentPrice + TrailingStopPips * _Point;
if(trailStopPrice < sl)
{
if(trade.PositionModify(ticket, trailStopPrice, tp))
Print("Trailing SL adjusted for SELL - New SL: ", trailStopPrice);
else
Print("Failed to modify SELL position - Ticket: ", ticket, ", Error: ", GetLastError());
}
}
}
}
}
Benefits:
- Dynamic Management: Continuously adjusts SL to lock in profits as the price moves favorably.
- Risk Mitigation: Protects profits and limits losses more effectively.
5. Risk Management Enhancements
Issue:
Current risk management only considers maximum drawdown based on account balance. It doesn't account for individual trade risk or overall exposure (e.g., number of open positions).
Recommendation:
Incorporate per-trade risk based on account equity and overall exposure metrics to ensure diversified and controlled risk.
Implementation:
bool IsRiskAcceptable()
{
double equity = AccountInfoDouble(ACCOUNT_EQUITY);
double maxAllowedDrawdown = initialBalance * (MaxDrawdown / 100.0);
if((initialBalance - equity) > maxAllowedDrawdown)
return false;
// Additional risk checks can be added here (e.g., maximum number of open positions)
return true;
}
void OnTick()
{
// Existing checks...
// Additional risk check
if(!IsRiskAcceptable())
{
Print("Risk parameters exceeded. Pausing trading.");
return;
}
// Proceed with strategy
StrategyOne("XAUUSD", PERIOD_H1);
ManageTrades();
}
Benefits:
- Comprehensive Control: Manages both overall drawdown and individual trade risks.
- Enhanced Safety: Prevents over-exposure and maintains balanced risk across trades.
6. Error Handling and Logging
Issue:
While the current implementation includes basic error messages, it can be enhanced for better debugging and resilience.
Recommendation:
Implement more robust error handling, including retries for certain recoverable errors, and detailed logging for easier troubleshooting.
Implementation:
bool SafeOrderSend(MqlTradeRequest &request, MqlTradeResult &result)
{
if(!OrderSend(request, result))
{
int error = GetLastError();
if(error == ERR_NO_MONEY || error == ERR_TRADE_CONTEXT_BUSY)
{
Sleep(1000); // Wait and retry
ResetLastError();
return OrderSend(request, result);
}
else
{
Print("OrderSend failed with error #", error, " on ", request.symbol);
return false;
}
}
return true;
}
void PlaceOrder(string symbol, bool buy)
{
// Existing code...
if(SafeOrderSend(request, result))
{
Print("Order placed successfully on ", symbol, ". Ticket: ", result.order);
}
else
{
Print("Failed to place order on ", symbol, " after retrying.");
}
}
Benefits:
- Resilience: Automatically retries orders in case of temporary issues.
- Transparency: Provides detailed error information for effective troubleshooting.
7. Economic Events Integration
Issue:
The IsEconomicEventUpcoming function is currently a placeholder. Ignoring economic events can expose the EA to unexpected volatility.
Recommendation:
Integrate an economic calendar to pause trading during high-impact events, reducing the risk of slippage and unexpected market movements.
Implementation:
MQL5 doesn't provide a built-in economic calendar, so you may need to use external APIs or services. Alternatively, manually input key events.
bool IsEconomicEventUpcoming()
{
// Example implementation using predefined events
datetime currentTime = TimeCurrent();
// Define a list of economic event times
datetime events[] = { /* list of upcoming event times */ };
for(int i = 0; i < ArraySize(events); i++)
{
if(MathAbs(events[i] - currentTime) < 60 * 60) // Within the next hour
return true;
}
return false;
}
Benefits:
- Risk Mitigation: Avoids trading during high-impact events that can cause significant price volatility.
- Stability: Reduces the likelihood of unexpected slippage and trade reversals.
8. Code Optimization and Best Practices
Recommendations:
-
Use Constants and Enumerations:
Define constants for frequently used values and enumerations for better readability.
-
Reduce Repetition:
Refactor repetitive code segments into reusable functions or loops.
-
Documentation:
Add more comments and documentation to explain complex logic, especially for custom indicator calculations.
-
Parameter Validation:
Validate input parameters to ensure they fall within acceptable ranges, preventing potential runtime errors.
-
Performance Optimization:
Minimize the number of indicator calculations per tick by caching values where possible.
Example Implementation:
// Define constants
#define SYMBOL "XAUUSD"
#define TIMEFRAME PERIOD_H1
// Refactored strategy call
if(IsWithinTradingHours() && !IsEconomicEventUpcoming() && IsRiskAcceptable())
{
StrategyOne(SYMBOL, TIMEFRAME);
ManageTrades();
}
Benefits:
- Maintainability: Easier to manage and update the codebase.
- Readability: Improves understanding of the code flow for future reviews or modifications.
- Performance: Enhances the EA's responsiveness and reduces computational load.
Conclusion
Your EA is well-structured and incorporates multiple strategic elements. By addressing the issues highlighted above and implementing the recommended improvements, you can enhance its efficiency, reliability, and overall performance. Always ensure thorough backtesting and forward testing in a demo environment before deploying the EA on a live account to validate its effectiveness and stability.
Feel free to reach out if you need further assistance or specific code examples for any of the recommendations.