Below is the complete MetaTrader 4 (MT4) Expert Advisor (EA) code based on the specified requirements for the Enhanced Mean Reversion Strategy with SMA Bands. The EA is written in MQL4 and incorporates the core strategy rules, risk management, trading time restrictions, and other features. Since the custom indicator source code was not provided in the query, I have used iCustom() to call an external indicator named "SMA_Bands" with the default settings you specified. You mentioned that the indicator source code will be attached separately, so you can replace the iCustom() calls with the actual indicator calculations if needed (e.g., by integrating the indicator code directly into the EA).
Key Notes on the Code:
- Indicator Integration: The EA assumes the custom indicator "SMA_Bands.ex4" is compiled and available in the MT4 indicators folder. It uses buffer indices: 0 for the upper band, 1 for the middle band (SMA), and 2 for the lower band. If the buffer indices differ, you can adjust them in the code. When you provide the indicator source code, you can modify the EA to include the indicator logic directly (e.g., by copying the indicator's calculation into a function within the EA).
- Pips vs. Points: The code uses a custom
Pip calculation to handle pips correctly for both 4-digit and 5-digit brokers, as per your requirement.
- Trading Time: The EA restricts trading to a specific time window (e.g., between
Start_Hour and End_Hour) using the broker's server time. It automatically handles the server time via TimeCurrent().
- Risk Management: Position sizing is based on a percentage of account balance, with lot sizes calculated using stop loss distance, tick value, and normalization to broker lot step rules. Maximum spread and slippage are enforced.
- Order Management: The EA handles breakeven and trailing stops for the second position after the first position's take profit is hit. Additional positions in the same direction are allowed only when an existing trade has reached breakeven.
- Hedging: Allowed, as the EA can open both buy and sell orders simultaneously if conditions are met.
- Magic Number and Comments: A magic number is used to group trades, and comments are set for each order (e.g., "5-1" for trade ID 5, position 1) to facilitate management.
- Strategy Tester Friendly: The EA uses bar-based entry detection on the indicator's timeframe (default M5) to avoid multiple entries and ensure compatibility with MT4 strategy tester. It also includes error handling and printing for debugging.
- Default Settings: All parameters are exposed as inputs for easy optimization in the strategy tester.
- Trailing Stop Logic: Simplified to a fixed distance after breakeven is hit. You can adjust or add step-based trailing if needed.
- Code Structure: The EA is organized with clear sections for inputs, initialization, tick handling (order management and entry checks), and helper functions.
To use this EA:
- Compile it in MT4 (File > Open Data Folder > MQL4 > Experts, save the file, and compile).
- Attach it to a chart (e.g., M5 timeframe).
- Ensure the custom indicator "SMA_Bands.ex4" is available or integrate its code.
- Backtest in the strategy tester with the desired settings.
Here is the complete MQL4 code:
#property copyright "Assistant"
#property link "https://example.com"
#property version "1.00"
#property strict
//+------------------------------------------------------------------+
//| Include files |
//+------------------------------------------------------------------+
#include <stderror.mqh>
//+------------------------------------------------------------------+
//| Input Parameters |
//+------------------------------------------------------------------+
input double Risk_Percent = 0.1; // Risk percentage of account balance (default 0.1%)
input int SL_Multiplier = 1; // Multiplier for stop loss distance (default 1)
input int Ind_Period = PERIOD_M5; // Indicator timeframe (default M5)
input int SMA_Period = 144; // SMA period for indicator (default 144)
input int Volatility_Method = 2; // Volatility method for indicator (default 2)
input int Volatility_Period = 288; // Volatility period for indicator (default 288)
input double Volatility_Multiplier = 1.0; // Volatility multiplier for indicator (default 1)
input double Channel_Ratio = 0.5; // Channel ratio for indicator (default 0.5)
input int Max_Bars_Ind = 0; // Max bars to calculate for indicator (default 0, all bars)
input int Magic_Number = 12345; // Magic number for orders
input int Start_Hour = 1; // Start hour for trading (e.g., 1 for 1 AM)
input int End_Hour = 2; // End hour for trading (e.g., 2 for 2 AM)
input double Max_Spread_Pips = 3.0; // Maximum allowed spread in pips
input int Max_Slippage = 3; // Maximum slippage in points
input double Trail_Start_Pips = 20.0; // Trailing stop start distance in pips (after breakeven)
input double Trail_Distance_Pips = 10.0; // Trailing stop distance in pips
// Static variables for bar detection and trade ID tracking
static datetime last_bar_time = 0;
static int trade_id = 0;
// Global variables
double Pip;
int Digits;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
// Set digits and pip value based on broker (handles 4/5 digit pricing)
Digits = (int)MarketInfo(Symbol(), MODE_DIGITS);
double point = MarketInfo(Symbol(), MODE_POINT);
Pip = point * (Digits % 2 == 1 ? 10.0 : 1.0); // Pip value (e.g., 0.0001 for most pairs)
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
// Cleanup if needed (e.g., print deinit reason)
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// Manage existing orders (breakeven and trailing)
ManageOrders();
// Detect new bar on indicator timeframe
datetime current_time = iTime(Symbol(), Ind_Period, 0);
if(current_time > last_bar_time)
{
last_bar_time = current_time; // Update last bar time
// Check trading time, spread, and entry conditions
if(IsTradingAllowed())
{
CheckEntry();
}
}
}
//+------------------------------------------------------------------+
//| Manage existing orders (breakeven and trailing) |
//+------------------------------------------------------------------+
void ManageOrders()
{
int total = OrdersTotal();
for(int i = 0; i < total; i++)
{
if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
{
if(OrderMagicNumber() == Magic_Number)
{
// Parse comment to extract trade ID and position number (format: "ID-Pos")
string comment = OrderComment();
int dash_pos = StringFind(comment, "-");
if(dash_pos > 0)
{
string id_str = StringSubstr(comment, 0, dash_pos);
string pos_str = StringSubstr(comment, dash_pos + 1);
int trade_id_order = (int)StrToInteger(id_str);
int pos_num = (int)StrToInteger(pos_str);
if(pos_num == 2) // Only manage second position
{
// Check if Position 1 for the same trade ID is still open
bool pos1_open = IsPositionOpen(trade_id_order, 1);
if(!pos1_open) // Position 1 is closed, handle breakeven and trailing
{
double entry_price = OrderOpenPrice();
double current_sl = OrderStopLoss();
// Set breakeven if not already set
if(OrderType() == OP_SELL && (current_sl == 0.0 || current_sl > entry_price))
{
double new_sl = NormalizeDouble(entry_price, Digits); // Breakeven for sell
if(OrderModify(OrderTicket(), OrderOpenPrice(), new_sl, OrderTakeProfit(), 0, clrNONE))
Print("Set breakeven for sell ticket ", OrderTicket());
else
Print("Error setting breakeven: ", GetLastError());
}
else if(OrderType() == OP_BUY && (current_sl == 0.0 || current_sl < entry_price))
{
double new_sl = NormalizeDouble(entry_price, Digits); // Breakeven for buy
if(OrderModify(OrderTicket(), OrderOpenPrice(), new_sl, OrderTakeProfit(), 0, clrNONE))
Print("Set breakeven for buy ticket ", OrderTicket());
else
Print("Error setting breakeven: ", GetLastError());
}
// Apply trailing stop if conditions met (after breakeven)
ApplyTrailingStop();
}
}
}
}
}
}
}
//+------------------------------------------------------------------+
//| Apply trailing stop to the current order |
//+------------------------------------------------------------------+
void ApplyTrailingStop()
{
double entry_price = OrderOpenPrice();
double current_sl = OrderStopLoss();
double trail_start_price = 0.0;
double trail_distance_price = Trail_Distance_Pips * Pip;
if(OrderType() == OP_SELL)
{
trail_start_price = entry_price - Trail_Start_Pips * Pip; // Price level to start trailing
if(Bid < trail_start_price && (current_sl == 0.0 || current_sl > Bid + trail_distance_price)) // Trail only if can tighten SL
{
double new_sl = NormalizeDouble(Bid + trail_distance_price, Digits);
if(OrderModify(OrderTicket(), OrderOpenPrice(), new_sl, OrderTakeProfit(), 0, clrNONE))
Print("Trailed SL for sell ticket ", OrderTicket());
else
Print("Error trailing SL: ", GetLastError());
}
}
else if(OrderType() == OP_BUY)
{
trail_start_price = entry_price + Trail_Start_Pips * Pip; // Price level to start trailing
if(Ask > trail_start_price && (current_sl == 0.0 || current_sl < Ask - trail_distance_price)) // Trail only if can tighten SL
{
double new_sl = NormalizeDouble(Ask - trail_distance_price, Digits);
if(OrderModify(OrderTicket(), OrderOpenPrice(), new_sl, OrderTakeProfit(), 0, clrNONE))
Print("Trailed SL for buy ticket ", OrderTicket());
else
Print("Error trailing SL: ", GetLastError());
}
}
}
//+------------------------------------------------------------------+
//| Check if Position with given trade ID and position number is open|
//+------------------------------------------------------------------+
bool IsPositionOpen(int trade_id_check, int pos_num_check)
{
int total = OrdersTotal();
for(int i = 0; i < total; i++)
{
if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
{
if(OrderMagicNumber() == Magic_Number)
{
string comment = OrderComment();
int dash_pos = StringFind(comment, "-");
if(dash_pos > 0)
{
string id_str = StringSubstr(comment, 0, dash_pos);
string pos_str = StringSubstr(comment, dash_pos + 1);
int trade_id_order = (int)StrToInteger(id_str);
int pos_num = (int)StrToInteger(pos_str);
if(trade_id_order == trade_id_check && pos_num == pos_num_check)
return true; // Position found and open
}
}
}
}
return false; // No open position found
}
//+------------------------------------------------------------------+
//| Check if trading is allowed (time and spread) |
//+------------------------------------------------------------------+
bool IsTradingAllowed()
{
// Check trading time using broker server time
datetime time_current = TimeCurrent();
int hour_now = (int)((time_current % 86400) / 3600); // Extract hour from datetime
if(hour_now < Start_Hour || hour_now > End_Hour)
return false; // Outside trading hours
// Check spread
double spread_points = MarketInfo(Symbol(), MODE_SPREAD);
double spread_pips = spread_points / (Digits % 2 == 1 ? 10.0 : 1.0); // Convert spread to pips
if(spread_pips > Max_Spread_Pips)
return false; // Spread too high
return true; // Trading allowed
}
//+------------------------------------------------------------------+
//| Check entry conditions and open trades |
//+------------------------------------------------------------------+
void CheckEntry()
{
// Get band values and close prices for bar 1 (closed bar) and bar 2
double upper1 = iCustom(Symbol(), Ind_Period, "SMA_Bands", SMA_Period, Volatility_Method, Volatility_Period, Volatility_Multiplier, Channel_Ratio, Max_Bars_Ind, 0, 1); // Upper band, bar 1
double middle1 = iCustom(Symbol(), Ind_Period, "SMA_Bands", SMA_Period, Volatility_Method, Volatility_Period, Volatility_Multiplier, Channel_Ratio, Max_Bars_Ind, 1, 1); // Middle band, bar 1
double lower1 = iCustom(Symbol(), Ind_Period, "SMA_Bands", SMA_Period, Volatility_Method, Volatility_Period, Volatility_Multiplier, Channel_Ratio, Max_Bars_Ind, 2, 1); // Lower band, bar 1
double upper2 = iCustom(Symbol(), Ind_Period, "SMA_Bands", SMA_Period, Volatility_Method, Volatility_Period, Volatility_Multiplier, Channel_Ratio, Max_Bars_Ind, 0, 2); // Upper band, bar 2
double lower2 = iCustom(Symbol(), Ind_Period, "SMA_Bands", SMA_Period, Volatility_Method, Volatility_Period, Volatility_Multiplier, Channel_Ratio, Max_Bars_Ind, 2, 2); // Lower band, bar 2
double close1 = iClose(Symbol(), Ind_Period, 1);
double close2 = iClose(Symbol(), Ind_Period, 2);
// Short entry: price crosses above or equal to upper band
if(close2 <= upper2 && close1 > upper1) // Cross up detected
{
if(CanEnterTrade(OP_SELL))
{
OpenTrade(OP_SELL, upper1, middle1, lower1);
}
}
// Long entry: price crosses below or equal to lower band
if(close2 >= lower2 && close1 < lower1) // Cross down detected
{
if(CanEnterTrade(OP_BUY))
{
OpenTrade(OP_BUY, lower1, middle1, upper1);
}
}
}
//+------------------------------------------------------------------+
//| Check if entry is allowed (no trade or breakeven on existing) |
//+------------------------------------------------------------------+
bool CanEnterTrade(int cmd)
{
bool has_trade = false;
bool has_breakeven = false;
int total = OrdersTotal();
for(int i = 0; i < total; i++)
{
if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
{
if(OrderMagicNumber() == Magic_Number && OrderType() == cmd) // Same direction
{
has_trade = true;
double sl = OrderStopLoss();
double entry = OrderOpenPrice();
if((cmd == OP_SELL && sl <= entry) || (cmd == OP_BUY && sl >= entry)) // Breakeven or better
{
has_breakeven = true;
break; // No need to check further
}
}
}
}
if(has_trade && !has_breakeven)
return false; // Has trades but no breakeven, cannot enter additional
return true; // No trades or breakeven exists, can enter
}
//+------------------------------------------------------------------+
//| Open trade with two positions |
//+------------------------------------------------------------------+
void OpenTrade(int cmd, double band1, double middle, double band2)
{
double entry_price, sl_price, tp1_price, tp2_price, dist_pips, sl_distance_price, sl_distance_points, tick_value, risk_total, risk_per_position, lot_size;
double min_lot = MarketInfo(Symbol(), MODE_MINLOT);
double max_lot = MarketInfo(Symbol(), MODE_MAXLOT);
double lot_step = MarketInfo(Symbol(), MODE_LOTSTEP);
if(cmd == OP_SELL)
{
entry_price = MarketInfo(Symbol(), MODE_BID); // Entry for short
dist_pips = (band1 - middle) / Pip; // Distance in pips (upper - middle)
sl_price = band1 + dist_pips * SL_Multiplier * Pip; // SL price
tp1_price = middle; // TP1 at middle band
tp2_price = band2; // TP2 at lower band for 1:2 RR
sl_distance_price = sl_price - entry_price; // Positive for short
}
else // OP_BUY
{
entry_price = MarketInfo(Symbol(), MODE_ASK); // Entry for long
dist_pips = (middle - band1) / Pip; // Distance in pips (middle - lower)
sl_price = band1 - dist_pips * SL_Multiplier * Pip; // SL price
tp1_price = middle; // TP1 at middle band
tp2_price = band2; // TP2 at upper band for 1:2 RR
sl_distance_price = entry_price - sl_price; // Positive for long
}
sl_distance_points = sl_distance_price / MarketInfo(Symbol(), MODE_POINT);
tick_value = MarketInfo(Symbol(), MODE_TICKVALUE);
risk_total = (Risk_Percent / 100.0) * AccountBalance();
risk_per_position = risk_total / 2.0; // 50% risk per position
lot_size = risk_per_position / (sl_distance_points * tick_value); // Calculate lot size
// Normalize lot size to broker rules
lot_size = MathMax(min_lot, MathMin(max_lot, lot_size));
lot_size = MathRound(lot_size / lot_step) * lot_step; // Round to lot step
if(lot_size < min_lot) return; // Lot size too small, abort
// Increment trade ID and set comments
trade_id++;
string comment1 = IntegerToString(trade_id) + "-1"; // Comment for position 1
string comment2 = IntegerToString(trade_id) + "-2"; // Comment for position 2
// Open first position
int ticket1 = OrderSend(Symbol(), cmd, lot_size, entry_price, Max_Slippage, 0, 0, comment1, Magic_Number, 0, (cmd == OP_SELL ? clrRed : clrBlue));
if(ticket1 > 0 && OrderSelect(ticket1, SELECT_BY_TICKET, MODE_TRADES))
{
if(!OrderModify(ticket1, OrderOpenPrice(), NormalizeDouble(sl_price, Digits), NormalizeDouble(tp1_price, Digits), 0, clrNONE))
Print("Error modifying TP/SL for ticket1: ", GetLastError());
}
// Open second position
int ticket2 = OrderSend(Symbol(), cmd, lot_size, entry_price, Max_Slippage, 0, 0, comment2, Magic_Number, 0, (cmd == OP_SELL ? clrRed : clrBlue));
if(ticket2 > 0 && OrderSelect(ticket2, SELECT_BY_TICKET, MODE_TRADES))
{
if(!OrderModify(ticket2, OrderOpenPrice(), NormalizeDouble(sl_price, Digits), NormalizeDouble(tp2_price, Digits), 0, clrNONE))
Print("Error modifying TP/SL for ticket2: ", GetLastError());
}
}
Explanation of Code Components:
- Inputs: All parameters are configurable via the MT4 input dialog, allowing easy optimization in the strategy tester.
- OnTick(): Handles order management (breakeven and trailing) and entry checks only on new bars of the indicator timeframe to prevent multiple entries.
- ManageOrders(): Loops through open orders, applies breakeven and trailing to the second position after the first is closed.
- CheckEntry(): Detects cross signals using closed bars and calls trade opening if conditions are met.
- CanEnterTrade(): Ensures additional positions are only opened when breakeven is hit on an existing trade in the same direction.
- OpenTrade(): Calculates and opens two positions with appropriate SL, TP, and lot sizes.
- Error Handling: Uses
GetLastError() and Print() statements for debugging, ensuring robustness.
- Tester Compatibility: Bar-based entry and input parameters make it suitable for backtesting and optimization.
If you provide the custom indicator source code, I can refine the EA by integrating it directly (e.g., by adding a function to calculate the bands). Let me know if you need any modifications!