An Expert Advisor (EA) in the Strategy Tester lives a sheltered life. It starts once, runs without interruption to the end of the test, and nearly every order it sends is filled. A live EA does not get that. The terminal restarts for an update, the VPS reboots, the connection drops for a minute, someone changes the chart's timeframe, and the trade server rejects an order because the price moved or the market is closed.
None of this shows up in a backtest, and all of it can change what the EA does: a daily loss counter that quietly resets to zero, a second position opened because the EA forgot it already had one, or a retry loop that sends the same order several times. This guide shows how to make an MT5 EA rebuild its state after any restart, how to handle trade results without creating duplicates, and how to test both on purpose rather than waiting for them to happen live.
One point up front: the code below is a set of sketches in MQL5, not a drop-in library. Adapt it to your EA, then test it on a demo account. Robust error handling makes the EA behave as designed when things go wrong. It doesn't make the strategy any better.
Why the tester never shows these problems
The tester simulates prices and fills, not the environment. In a normal test:
- There is no restart.
OnInitruns once, so any state held in variables survives the whole test. - Orders rarely fail. Depending on the settings, the tester fills most valid orders, so retry and rejection paths are never exercised.
- There is no disconnection, no terminal update and no second copy of the EA on another chart.
So a backtest can be entirely correct while the code that handles a restart or a rejected order has never run once. Our EA pre-live checklist lists restart behaviour among the code checks. This guide is about how to build and test it.
Step 1: List the state your EA holds
State is anything the EA remembers between ticks that affects what it does next. Write it down. A typical list:
- Positions and pending orders the EA owns.
- Risk counters: today's starting equity or balance, the day's realised loss, the number of trades today.
- Trade management levels: trailing stop levels, break-even flags, partial-close stages.
- Timing: the last bar processed, cooldown timers after a loss, "already traded this session" flags.
- Strategy memory: grid levels, the count of averaging entries, the last signal's direction.
For each item, note what would happen if it were lost or reset at the worst moment. That tells you which items need the most care.
Step 2: Rebuild what the terminal already knows
The safest state is state you don't store at all, because you can derive it again from the terminal. Open positions, pending orders and today's deals are all available, filtered by symbol and magic number.
input long InpMagic = 310001; // unique per EA and chart
datetime ServerDayStart(const datetime t)
{
MqlDateTime s;
TimeToStruct(t, s);
s.hour = 0; s.min = 0; s.sec = 0;
return StructToTime(s);
}
int CountMyPositions()
{
int n = 0;
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
ulong ticket = PositionGetTicket(i); // also selects the position
if(ticket == 0) continue;
if(PositionGetString(POSITION_SYMBOL) == _Symbol &&
PositionGetInteger(POSITION_MAGIC) == InpMagic)
n++;
}
return n;
}
int EntriesToday()
{
datetime from = ServerDayStart(TimeTradeServer());
if(!HistorySelect(from, TimeTradeServer() + 86400))
return -1; // unknown: the caller should not trade
int n = 0;
for(int i = HistoryDealsTotal() - 1; i >= 0; i--)
{
ulong deal = HistoryDealGetTicket(i);
if(deal == 0) continue;
if(HistoryDealGetString(deal, DEAL_SYMBOL) == _Symbol &&
HistoryDealGetInteger(deal, DEAL_MAGIC) == InpMagic &&
HistoryDealGetInteger(deal, DEAL_ENTRY) == DEAL_ENTRY_IN)
n++;
}
return n;
}
Two details matter. First, the "day" here starts at server midnight. If the rule you are following resets at a different time, change ServerDayStart to match it. Second, when the EA can't read its history, it returns a value that means "unknown", and the trading logic should treat unknown as "don't open new trades", not as zero.
Step 3: Persist only what you can't rebuild
Some values can't be derived after the fact. The equity at the start of the day is the usual example: once the day has moved on, the terminal can't tell you what equity was at the reset. Our guide to sizing under a daily loss limit explains why resetting it on a restart is a common and costly bug. Store values like this as soon as they are set.
double g_dayRef = 0.0;
string Key(const string name) { return StringFormat("CT_%s_%I64d_%s", _Symbol, InpMagic, name); }
void LoadOrSetDayReference()
{
datetime today = ServerDayStart(TimeTradeServer());
if(GlobalVariableCheck(Key("day")) && GlobalVariableCheck(Key("ref")) &&
(datetime)GlobalVariableGet(Key("day")) == today)
{
g_dayRef = GlobalVariableGet(Key("ref")); // restored, not reset
return;
}
g_dayRef = AccountInfoDouble(ACCOUNT_EQUITY); // first start of a new day
GlobalVariableSet(Key("day"), (double)today);
GlobalVariableSet(Key("ref"), g_dayRef);
GlobalVariablesFlush(); // write to disk now, not at shutdown
}
Things to know about storing state:
- Terminal global variables survive a restart, but the terminal writes them to disk at shutdown unless you flush them, so a crash can lose recent changes. The terminal also deletes variables that haven't been accessed for several weeks; check the documentation for your build.
- A file in the terminal's data folder gives you more control, such as a version number and a timestamp in each record, at the cost of more code.
- Validate what you load. A stored reference from a different day, account or EA version is worse than none. Check the date and, where it matters, the account number.
- First start mid-day is a special case. If the EA starts for the first time partway through a day, current equity is only an estimate of the day's reference. Decide in advance whether the EA should trade at all for the rest of that day.
Step 4: Treat OnInit as a re-entry point
OnInit doesn't only run when you first attach the EA. It runs again after a terminal restart, after a change of symbol or timeframe on the chart, after a change of inputs, after recompiling, and after switching account. OnDeinit receives a reason code, such as REASON_CHARTCHANGE, REASON_PARAMETERS or REASON_RECOMPILE, that tells you why the EA stopped.
Depending on the reason, the EA's own global variables may or may not keep their values, so don't rely on either. Rebuild state explicitly in every OnInit:
int OnInit()
{
LoadOrSetDayReference();
PrintFormat("init: %d own positions, %d entries today, day reference %.2f",
CountMyPositions(), EntriesToday(), g_dayRef);
return INIT_SUCCEEDED;
}
void OnDeinit(const int reason)
{
PrintFormat("deinit: reason %d", reason);
}
Also handle the day changing while the EA is running: check the server day on each new bar and call the same load-or-set function when it changes, so the overnight path and the restart path share one piece of code.
Step 5: Handle trade results by class
Sending a trade request and getting a successful return from the function is not the same as being filled. Always read the result code (the retcode) the server sends back, and group the codes by what the EA should do:
- Done:
TRADE_RETCODE_DONEmeans the request was executed.TRADE_RETCODE_PLACEDmeans a pending order was placed. - Partly done:
TRADE_RETCODE_DONE_PARTIALmeans only part of the volume was filled. Decide deliberately whether to send the rest or accept the smaller position. - Worth a limited retry: requotes, price changes, no quotes, too many requests, and connection or timeout problems (
TRADE_RETCODE_REQUOTE,TRADE_RETCODE_PRICE_CHANGED,TRADE_RETCODE_PRICE_OFF,TRADE_RETCODE_TOO_MANY_REQUESTS,TRADE_RETCODE_CONNECTION,TRADE_RETCODE_TIMEOUT). - Don't retry: invalid stops, invalid volume, not enough money, market closed, unsupported filling mode and similar codes mean the request itself needs to change, or the EA should stand down. Resending the same request will fail the same way.
Retrying without duplicating
A timeout or a dropped connection doesn't tell you whether the order was executed. If the EA simply resends, it can end up with two positions. So before every retry, check what the EA actually holds, and keep the number of attempts small.
#include <Trade\Trade.mqh>
CTrade trade;
input bool InpInjectFaults = false; // test builds only: simulate refused orders
input double InpFaultRate = 0.2;
bool Retryable(const uint rc)
{
return rc == TRADE_RETCODE_REQUOTE || rc == TRADE_RETCODE_PRICE_CHANGED ||
rc == TRADE_RETCODE_PRICE_OFF || rc == TRADE_RETCODE_TOO_MANY_REQUESTS ||
rc == TRADE_RETCODE_CONNECTION || rc == TRADE_RETCODE_TIMEOUT;
}
uint SendBuy(const double lots, const double sl, const double tp)
{
if(InpInjectFaults && MathRand() / 32767.0 < InpFaultRate)
return TRADE_RETCODE_REQUOTE; // pretend the server refused
trade.Buy(lots, _Symbol, SymbolInfoDouble(_Symbol, SYMBOL_ASK), sl, tp, "entry");
return trade.ResultRetcode();
}
bool OpenBuyOnce(const double lots, const double sl, const double tp)
{
trade.SetExpertMagicNumber(InpMagic);
for(int attempt = 1; attempt <= 3; attempt++)
{
if(CountMyPositions() > 0)
return true; // an earlier attempt may have filled
uint rc = SendBuy(lots, sl, tp);
PrintFormat("buy attempt %d: retcode %u", attempt, rc);
if(rc == TRADE_RETCODE_DONE || rc == TRADE_RETCODE_DONE_PARTIAL)
return true; // partial fill: handle the rest deliberately
if(!Retryable(rc))
return false; // fix the request or stand down
Sleep(500 * attempt);
}
return false;
}
The position check assumes the EA holds at most one position per symbol. If yours holds several, compare against the count it expects instead. After a timeout, the new position may take a moment to appear, so a short wait and a check of the day's deals as well as open positions is safer than one immediate look.
Step 6: Test failure on purpose
Write down the expected behaviour for each scenario first, then make it happen and compare the log with what you wrote.
In the Strategy Tester, run with fault injection switched on. The EA should log each refused order, retry only the codes it treats as retryable, never open more positions than intended and keep trading correctly afterwards. Seed the random generator differently between runs, for example with MathSrand in OnInit, so the faults land at different moments.
On a demo account, with the EA running:
- Close and restart the terminal while a position is open.
- Restart mid-day after the daily counters have moved, and check they were restored, not reset.
- Change the chart's timeframe, then change an input, and check nothing was opened, closed or reset unexpectedly.
- Disconnect the network briefly, then reconnect.
- Attach a second copy of the EA to another chart with a different magic number, and check each manages only its own trades.
- Start the EA while the market is closed and again just after the daily reset.
Keep fault injection out of live builds. Make it an input that defaults to off, or remove it at compile time.
Step 7: Log state changes, not just trades
When something goes wrong live, the log is the only record of what the EA believed. Log every initialisation and its reason, every value loaded or stored, every trade request and its retcode, and every time the EA decides not to trade because a state check failed. Our guide to measuring live execution shows how to log order timing and fills in a form you can analyse later.
Common restart and error-handling mistakes
- Keeping risk counters only in variables, so a restart resets them.
- Assuming
OnInitmeans a fresh start, when it also runs after timeframe and input changes. - Treating a successful function return as a fill, without reading the retcode.
- Retrying every error, including ones that can't succeed until the request changes.
- Resending after a timeout without checking whether the first order was executed.
- Loading stored state without validating its date, account or version.
- Never testing failure paths, because the backtest never triggered them.
Restart and error-handling checklist
- Every piece of EA state listed, with the effect of losing it at the worst moment
- Positions, orders and today's entries rebuilt from the terminal, filtered by symbol and magic number
- Values that can't be rebuilt stored when set, flushed to disk and validated on load
OnInitrebuilds state for every reason it can run, and logs the result- Day changes handled by the same code path as restarts
- Retcodes grouped into done, partly done, retryable and not retryable
- Retries limited, with a position check before each one
- Fault injection tested in the tester, and restart scenarios tested on demo, against written expectations
- Fault injection off by default and absent from live builds
Frequently asked questions
What happens to an MT5 EA when the terminal restarts?
The EA is loaded again and OnInit runs as if it were starting fresh. Values held only in the program's variables are gone, while open positions, pending orders and deal history are still on the account. A well-built EA rebuilds its view of those from the terminal and reloads anything it stored, such as the day's reference equity.
How do I stop my EA resetting its daily loss counter after a restart?
Store the day's reference value, together with the date it applies to, as soon as it is set, using a terminal global variable or a file, and flush it to disk. On start, reload it if the stored date matches today, and only set a new one on the first start of a new day.
Should an EA retry an order after an error?
Only for errors that can succeed on a second attempt, such as a requote or a brief connection problem, and only a small number of times. Before each retry, check whether the earlier attempt was actually executed, so a timeout doesn't turn into two positions. Errors such as invalid stops or insufficient margin need a different request, not a repeat.
Does OnInit only run when I attach the EA to a chart?
No. It also runs after a terminal restart, a change of symbol or timeframe, a change of inputs, a recompile and an account switch. Treat every call to OnInit as a possible restart in the middle of trading and rebuild state accordingly.
How can I test error handling in the MT5 Strategy Tester?
The tester rarely rejects orders, so add a test-only input that makes the EA's order function return a simulated failure some of the time. Run the test with it on and check from the log that the EA retried only what it should, never doubled a position and carried on correctly. Test restarts separately on a demo account.
Want a second pair of eyes?
Start with our free Sample Stress-Test Report. It walks one anonymized, illustrative strategy through a full stress test, start to finish, so you can see what rigorous validation looks like before you test your own.
Read the Sample Stress-Test ReportWant your own backtest checked? The Strategy Audit + 60-minute call is a paid service at a launch price of £100, credited in full against our build and portfolio offers. You send an MT4/MT5 Strategy Tester report or trade-list CSV; what we can check depends on the files you supply, and walk-forward and parameter sweeps are not included because they need the strategy itself. It is analysis of strategy testing, not investment advice, and does not promise any trading or evaluation outcome. See the Strategy Audit
Disclaimers
CollosoTrading provides educational content and analytical services for retail and professional algorithmic traders. We do not provide regulated investment advice, financial advice, or personal recommendations. Trading derivatives, leveraged products, and CFDs carries a high level of risk and may result in losses exceeding deposits. Past performance, including any verified or unverified historical results referenced on this site, is not indicative of future results. Consult an independent regulated financial adviser before making investment decisions.
All figures are backtests or simulations unless marked LIVE. Hypothetical or backtested performance results have inherent limitations and may not reflect actual trading. No representation is made that any account will or is likely to achieve profits or losses similar to those shown. Individual results vary. This article contains no performance figures; the code examples are sketches to adapt and test on a demo account. We do not guarantee the outcome of any prop firm challenge.