This template provides a solid foundation for developing Expert Advisors (EAs) on MT5. It includes pre-built modules for trade management, risk settings, and signal generation.
-
Template.mq5
The main EA file that initializes your trading logic and event handlers. -
Header.mqh
Contains input parameters and global settings like risk management, trading hours, and custom indicators. -
Trade_Functions.mqh
Provides functions to open, close, and partially close trades. -
Risk_Functions.mqh
Implements calculations for stop-loss, take-profit, and dynamic lot sizing based on risk. -
Signal_Functions.mqh
Holds indicator initialization and functions to detect entry/exit signals.
- Define specific trading sessions using
TradingHoursStart
andTradingHoursEnd
inputs in Header.mqh - Simply set your desired hours using 24-hour format based on broker server time
- Configure via
RiskMode
input:FIXED_LOT
: Trade with consistent position size (FixedLotSize
)RISK_BASED
: Dynamic sizing based on risk percentage (RiskPercent
)
- Set
AccountBalanceType
to calculate risk from balance, equity, or free margin - Control exposure with
MaxPositions
to limit concurrent trades - Implement
MaximumLotSize
andMinimumLotSize
as safety boundaries - Usage:
LotSize()
function automatically calculates optimal position size
- Set via
StopLossMode
andTakeProfitMode
inputs:FIXED
: Use exact point values fromFixedStopLoss
andFixedTakeProfit
ATR_BASED
: Dynamic values scaled byATRMultiplierSL
andATRMultiplierTP
- Safety limits with
MinStopLoss
/MaxStopLoss
andMinTakeProfit
/MaxTakeProfit
- Access through
StopLoss()
andTakeProfit()
functions which handle all calculations
- Enable with
UsePartialClose
and set trigger level withPartialCloseATRMultiplier
- Configure percentage to close via
PartialClosePercent
(1-99%) - Called automatically during tick processing or manually with
PartialCloseAll()
- Tracks positions with built-in logic to prevent multiple partial closes on same position
- Enable with
UseBreakeven
parameter to automatically move stop-loss to breakeven - Two operation modes available via
BreakevenMode
input:BE_FIXED
: Move to breakeven when profit reachesFixedBreakevenPips
pipsBE_ATR
: Move to breakeven when profit reachesBreakevenATRMultiplier
× ATR value
- Configure additional profit buffer with
BreakevenBuffer
in points - Automatically monitors all positions and applies breakeven when conditions are met
- Called during tick processing via built-in
MoveToBreakeven()
function
- Configurable with
ATRPeriod
andATRTimeframe
inputs - Provides volatility reference for dynamic SL/TP, partial close decisions, and breakeven levels
- Powers volatility-adjusted position sizing when combined with risk-based lot sizing
- Control spread conditions with
MaxSpread
to prevent trading during volatile periods - Set unique
MagicNumber
for position tracking - Customize
OrderComment
for trade identification - Configure slippage tolerance with
Slippage
parameter
This section provides a step-by-step guide to using and customizing the MT5 EA template.
- Copy the entire template folder into your MT5 Experts directory (typically located at
[MT5 Data Folder]\MQL5\Experts\
) - Rename the following files to match your EA's name:
- Template.mq5 →
YourEAName.mq5
- Template.mqproj →
YourEAName.mqproj
- Template.mq5 →
- Update the metadata in three locations:
- Edit copyright, description, version, and icon in
YourEAName.mq5
file header - Update the project properties in
YourEAName.mqproj
file - Update any references to "Template" within the code
- Edit copyright, description, version, and icon in
- Open your renamed EA in MetaEditor
- Configure default trading parameters in Header.mqh:
- Risk management settings (
MaxRiskPerTrade
,RiskDefaultSize
, etc.) - Trading hours (
TradingHourStart
,TradingHourEnd
) - Stop-loss and take-profit parameters
- Position sizing options
- ATR settings for volatility-based decisions
- Risk management settings (
-
Define your entry and exit signals in Signal_Functions.mqh:
- Uncomment and modify the sample code in
CheckEntrySignal()
andCheckExitSignal()
- The template uses a framework where
OpenBuy()
andOpenSell()
handle all position sizing and risk calculations automatically
- Uncomment and modify the sample code in
-
To add custom indicators:
- Declare global variables and handles in your main
.mq5
file - Initialize indicators in
InitializeHandles()
function - Retrieve indicator data in
GetIndicatorsData()
function
- Declare global variables and handles in your main
// Example of adding a custom indicator
// In your .mq5 file:
int CustomIndicatorHandle;
double CustomIndicator_buffer[];
// In InitializeHandles() function:
CustomIndicatorHandle = iCustom(Symbol(), Period(), "indicator_name", param1, param2);
if(CustomIndicatorHandle == INVALID_HANDLE)
{
Print("Failed to create custom indicator handle");
return false;
}
- For advanced customization:
- Modify risk calculations in Risk_Functions.mqh
- Adjust trade execution in Trade_Functions.mqh
-
Compile your EA by pressing F7 in MetaEditor
-
Test in Strategy Tester:
- Select your EA from the Expert Advisor dropdown
- Configure testing parameters (symbol, timeframe, date range)
- Use "Visual mode" for detailed trade visualization
- Review the custom optimization criterion in
OnTester()
function
-
Deploy to a demo account first:
- Attach your EA to a chart
- Enable "Allow Automated Trading" in MT5
- Monitor performance before considering live deployment
-
For optimization:
- Use the built-in optimization functionality in Strategy Tester
- The EA includes a custom optimization criterion in
OnTester()
that balances profit against drawdown
int CountPositions()
- Counts open positions for current symbol with specified magic numberbool OpenBuy()
- Opens a buy position with calculated SL/TP based on risk settingsbool OpenSell()
- Opens a sell position with calculated SL/TP based on risk settingsvoid CloseAllBuy()
- Closes all buy positions for current symbolvoid CloseAllSell()
- Closes all sell positions for current symbolvoid CloseAllPositions()
- Closes all positions opened by this EAbool PartialClose(ulong ticket, double percentage)
- Partially closes a position with specified ticketvoid PartialCloseAll()
- Partially closes all positions based on ATR conditionsvoid MoveToBreakeven()
- Moves stop-loss to breakeven when position reaches profit target using either fixed pips or ATR-based calculations
void SetTradeObject()
- Configures trade object with magic number and slippage
bool InitializeHandles()
- Sets up indicator handles including ATRbool GetIndicatorsData()
- Retrieves indicator data with retry logicvoid CheckEntrySignal()
- Framework for implementing entry signal logicvoid CheckExitSignal()
- Framework for implementing exit signal logic
double StopLoss(ENUM_ORDER_TYPE order_type, double open_price)
- Calculates stop-loss price based on settingsdouble TakeProfit(ENUM_ORDER_TYPE order_type, double open_price)
- Calculates take-profit price based on settingsdouble LotSize(double stop_loss, double open_price)
- Calculates position size based on risk parametersdouble DynamicStopLossPrice(ENUM_ORDER_TYPE type, double open_price)
- Calculates ATR-based dynamic stop-lossdouble DynamicTakeProfitPrice(ENUM_ORDER_TYPE type, double open_price)
- Calculates ATR-based dynamic take-profit
void ProcessTick()
- Main tick processing functionbool Prechecks()
- Validates input parameters during initializationdouble OnTester()
- Custom optimization criterion for backtests
Use this template at your own risk. Always test thoroughly in a demo environment. Past performance is not indicative of future results.