MT5 Strategy Tester Guide: How to Backtest Expert Advisors (2026)
A step-by-step guide to using the MetaTrader 5 Strategy Tester to backtest Expert Advisors across multiple symbols and timeframes. Learn how to configure tick data quality, choose modelling modes, interpret equity curves, and avoid common pitfalls that produce misleading backtest results.
Strategy logic
Entry conditions
N/A — this is a tutorial/indicator reference page. The companion example EA uses a simple dual-MA crossover to demonstrate Strategy Tester mechanics, entering a buy when the fast MA crosses above the slow MA and a sell when it crosses below.
Exit conditions
N/A — this is a tutorial/indicator reference page. The example EA closes positions by opposite signal or a fixed stop-loss / take-profit to illustrate how those parameters appear in Strategy Tester reports.
MQL5 Expert Advisor Code
//+------------------------------------------------------------------+
//| StrategyTesterDemo.mq5 |
//| Teaching example: dual-MA crossover EA for MT5 Strategy Tester |
//| Demonstrates OnInit / OnTick / OnDeinit patterns and trade ops |
//+------------------------------------------------------------------+
#property copyright "Pineify Demo"
#property version "1.00"
#property strict
//--- Input parameters
input int InpFastPeriod = 10; // Fast MA period
input int InpSlowPeriod = 30; // Slow MA period
input int InpMaMethod = MODE_EMA; // MA method (0=SMA,1=EMA,2=SMMA,3=LWMA)
input double InpLotSize = 0.10; // Trade volume (lots)
input int InpSlippage = 10; // Max slippage in points
input double InpStopLoss = 50.0; // Stop loss in points (0 = disabled)
input double InpTakeProfit = 100.0; // Take profit in points (0 = disabled)
input ulong InpMagicNumber = 20260101;// Magic number to identify EA trades
//--- Indicator handles
int g_fastHandle = INVALID_HANDLE;
int g_slowHandle = INVALID_HANDLE;
//--- State
bool g_initOk = false;
//+------------------------------------------------------------------+
//| Expert initialisation |
//+------------------------------------------------------------------+
int OnInit()
{
//--- Validate periods
if(InpFastPeriod >= InpSlowPeriod)
{
Print("ERROR: Fast period must be less than Slow period.");
return INIT_PARAMETERS_INCORRECT;
}
//--- Create MA handles
g_fastHandle = iMA(_Symbol, PERIOD_CURRENT, InpFastPeriod, 0,
(ENUM_MA_METHOD)InpMaMethod, PRICE_CLOSE);
g_slowHandle = iMA(_Symbol, PERIOD_CURRENT, InpSlowPeriod, 0,
(ENUM_MA_METHOD)InpMaMethod, PRICE_CLOSE);
if(g_fastHandle == INVALID_HANDLE || g_slowHandle == INVALID_HANDLE)
{
Print("ERROR: Failed to create MA indicator handles.");
return INIT_FAILED;
}
g_initOk = true;
PrintFormat("StrategyTesterDemo initialised on %s / %s | Fast=%d Slow=%d",
_Symbol, EnumToString(Period()), InpFastPeriod, InpSlowPeriod);
return INIT_SUCCEEDED;
}
//+------------------------------------------------------------------+
//| Expert deinitialization |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- Release indicator handles to free memory
if(g_fastHandle != INVALID_HANDLE)
{
IndicatorRelease(g_fastHandle);
g_fastHandle = INVALID_HANDLE;
}
if(g_slowHandle != INVALID_HANDLE)
{
IndicatorRelease(g_slowHandle);
g_slowHandle = INVALID_HANDLE;
}
PrintFormat("StrategyTesterDemo deinitialised. Reason code: %d", reason);
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
if(!g_initOk) return;
//--- Only act on a new bar to avoid multiple entries per bar
static datetime s_lastBarTime = 0;
datetime currentBarTime = iTime(_Symbol, PERIOD_CURRENT, 0);
if(currentBarTime == s_lastBarTime) return;
s_lastBarTime = currentBarTime;
//--- Copy two values (index 1 = last closed bar, 2 = bar before that)
double fastBuf[2], slowBuf[2];
if(CopyBuffer(g_fastHandle, 0, 1, 2, fastBuf) < 2) return;
if(CopyBuffer(g_slowHandle, 0, 1, 2, slowBuf) < 2) return;
double fastPrev = fastBuf[0]; // bar-2 (older)
double fastCurr = fastBuf[1]; // bar-1 (most recent closed)
double slowPrev = slowBuf[0];
double slowCurr = slowBuf[1];
//--- Determine crossover signals
bool crossUp = fastPrev < slowPrev && fastCurr > slowCurr;
bool crossDown = fastPrev > slowPrev && fastCurr < slowCurr;
//--- Count open positions for this EA
int buyCount = CountPositions(POSITION_TYPE_BUY);
int sellCount = CountPositions(POSITION_TYPE_SELL);
//--- Buy signal: fast MA crosses above slow MA
if(crossUp && buyCount == 0)
{
CloseAllPositions(POSITION_TYPE_SELL);
OpenTrade(ORDER_TYPE_BUY);
}
//--- Sell signal: fast MA crosses below slow MA
if(crossDown && sellCount == 0)
{
CloseAllPositions(POSITION_TYPE_BUY);
OpenTrade(ORDER_TYPE_SELL);
}
}
//+------------------------------------------------------------------+
//| Count open positions for this EA's magic number and direction |
//+------------------------------------------------------------------+
int CountPositions(ENUM_POSITION_TYPE direction)
{
int count = 0;
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
ulong ticket = PositionGetTicket(i);
if(ticket == 0) continue;
if(PositionGetString(POSITION_SYMBOL) != _Symbol) continue;
if(PositionGetInteger(POSITION_MAGIC) != (long)InpMagicNumber) continue;
if((ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE) != direction) continue;
count++;
}
return count;
}
//+------------------------------------------------------------------+
//| Close all positions of a given type for this EA |
//+------------------------------------------------------------------+
void CloseAllPositions(ENUM_POSITION_TYPE direction)
{
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
ulong ticket = PositionGetTicket(i);
if(ticket == 0) continue;
if(PositionGetString(POSITION_SYMBOL) != _Symbol) continue;
if(PositionGetInteger(POSITION_MAGIC) != (long)InpMagicNumber) continue;
if((ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE) != direction) continue;
MqlTradeRequest req = {};
MqlTradeResult res = {};
req.action = TRADE_ACTION_DEAL;
req.symbol = _Symbol;
req.volume = PositionGetDouble(POSITION_VOLUME);
req.type = (direction == POSITION_TYPE_BUY) ? ORDER_TYPE_SELL : ORDER_TYPE_BUY;
req.price = (req.type == ORDER_TYPE_SELL) ? SymbolInfoDouble(_Symbol, SYMBOL_BID)
: SymbolInfoDouble(_Symbol, SYMBOL_ASK);
req.deviation = InpSlippage;
req.magic = InpMagicNumber;
req.position = ticket;
req.comment = "StrategyTesterDemo close";
if(!OrderSend(req, res))
PrintFormat("CloseAllPositions error: %d", GetLastError());
}
}
//+------------------------------------------------------------------+
//| Open a new trade in the specified direction |
//+------------------------------------------------------------------+
void OpenTrade(ENUM_ORDER_TYPE orderType)
{
double price = (orderType == ORDER_TYPE_BUY)
? SymbolInfoDouble(_Symbol, SYMBOL_ASK)
: SymbolInfoDouble(_Symbol, SYMBOL_BID);
double point = SymbolInfoDouble(_Symbol, SYMBOL_POINT);
int digits = (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS);
double sl = 0.0, tp = 0.0;
if(InpStopLoss > 0)
sl = (orderType == ORDER_TYPE_BUY)
? NormalizeDouble(price - InpStopLoss * point, digits)
: NormalizeDouble(price + InpStopLoss * point, digits);
if(InpTakeProfit > 0)
tp = (orderType == ORDER_TYPE_BUY)
? NormalizeDouble(price + InpTakeProfit * point, digits)
: NormalizeDouble(price - InpTakeProfit * point, digits);
MqlTradeRequest req = {};
MqlTradeResult res = {};
req.action = TRADE_ACTION_DEAL;
req.symbol = _Symbol;
req.volume = InpLotSize;
req.type = orderType;
req.price = price;
req.sl = sl;
req.tp = tp;
req.deviation = InpSlippage;
req.magic = InpMagicNumber;
req.comment = "StrategyTesterDemo";
if(!OrderSend(req, res))
PrintFormat("OpenTrade error: %d retcode: %d", GetLastError(), res.retcode);
else
PrintFormat("Trade opened: %s %s vol=%.2f price=%.5f sl=%.5f tp=%.5f",
EnumToString(orderType), _Symbol, InpLotSize, price, sl, tp);
}
//+------------------------------------------------------------------+Copy this code into MetaEditor, save it in the MQL5/Experts folder, and compile with F7.
Generate a custom Multi-pair educational EA
Describe the ATR inputs, alert rules, visual style, or confirmation filter you want. Pineify generates editable MQL5 source code that you can inspect and compile in MetaEditor.
Pine Script vs MQL5: Same Strategy, Different Platforms
| Aspect | Pine Script (TradingView) | MQL5 (MetaTrader 5) |
|---|---|---|
| Execution | Series evaluated on chart updates | Event handlers with explicit buffers |
| Deployment | Runs in TradingView with alerts | Runs in the MT5 terminal or on a VPS |
| Broker access | Via TradingView broker integration | Direct broker connectivity |
| Backtesting | Strategy Tester for strategy scripts | Strategy Tester for Expert Advisors |
| Code complexity | Simpler, functional syntax | C++-like, more powerful |
The calculation can be implemented on either platform, but the runtime model and buffer APIs differ. Read the Pine Script Supertrend reference before porting logic between them.
Frequently Asked Questions
Related MQL5 pages
Risk and testing note
Past performance is not indicative of future results. Backtest statistics are based on historical data and do not guarantee future profits. Trading involves significant risk of loss. This content is for educational purposes only and does not constitute financial advice.