What Does Your Expert Advisor Forget When MetaTrader Restarts?
Many Expert Advisors keep track of things as they run: trades opened today, the stage of a plan, whether a pause has been triggered. Most of that lives in ordinary variables in memory, which works until the EA restarts. Then the question is simple: does it remember where it was, or start again as if nothing had happened?
Restarts are not rare. This article covers when MetaTrader 5 reloads an EA, what it keeps, where state can be stored, and a start-up pattern that rebuilds the picture from the account.
An EA Restarts More Often Than You Think
MetaQuotes’ documentation lists when an Expert Advisor is loaded: when it is attached to a chart, when the terminal starts (if it was attached before shutdown), when a template or profile containing it is loaded, and on connecting to an account, “even if the account number is the same”, if the EA was attached before the terminal logged in (MQL5 Reference, Program Running).
Recompiling the EA and changing its inputs also stop and restart it (MQL5 Reference, Client Terminal Events). So closing the terminal, switching account, loading a template, changing an input or recompiling can each wipe whatever the EA was holding in memory.
One exception works the other way. When the chart’s symbol or timeframe changes, the EA is not unloaded: the terminal calls OnDeinit() and then OnInit() again, but “values of global variables and static variables are not reset” (Program Running). So OnInit() is not always a fresh start: after a reload memory is empty, but after a chart change old values may remain.
The EA Can See Why It Was Stopped
OnDeinit() receives a reason code, which the EA can also read with UninitializeReason(). The codes distinguish, for example, a removal from the chart (REASON_REMOVE), a recompile (REASON_RECOMPILE), a change of symbol or timeframe (REASON_CHARTCHANGE), changed inputs (REASON_PARAMETERS), an account change (REASON_ACCOUNT) and the terminal closing (REASON_CLOSE) (MQL5 Reference, Uninitialization Reason Codes). Logging it is a cheap way to explain odd behaviour later.
What OnDeinit() should not be is the only place state gets saved. Its run “is restricted to 2.5 seconds”, after which it is forcibly terminated (Client Terminal Events), and if the computer crashes or loses power it never runs at all. Anything worth keeping should be saved when it changes, not on the way out.
Where State Can Live, and the Limits of Each
MetaTrader 5 gives an EA two built-in places to keep data outside its own memory.
Terminal global variables are shared by every MQL5 program in the terminal. They are kept “for 4 weeks since the last access”, after which they are deleted automatically (MQL5 Reference, Global Variables of the Terminal). The terminal writes them to disk when it shuts down, but the documentation warns that data can be lost if the computer fails suddenly, and GlobalVariablesFlush() forces an immediate save (GlobalVariablesFlush). They hold only numbers.
Files suit richer state, such as which stage of a multi-step exit has been reached. FileOpen() works inside a sandbox: the terminal’s own MQL5\Files folder, or a folder shared by all terminals when FILE_COMMON is used. During testing the tester uses its own folder, separate from the live terminal’s (MQL5 Reference, FileOpen). Keying each file or variable by account, symbol and the EA’s magic number stops two copies of the same EA overwriting each other.
The Most Reliable Record Is the Account Itself
Saved data can be stale, deleted or wrong; the account at the broker is the actual record. Every trade request can carry a magic number, the documentation’s “Expert Advisor ID” (Trade Request Structure), and every open position exposes it as POSITION_MAGIC, along with POSITION_IDENTIFIER, which links the position to the order that opened it (Position Properties). HistorySelect() loads past orders and deals for a date range, so an EA can also check what has already happened today (HistorySelect).
That leads to a simple rule: on start-up, rebuild the picture from open positions, pending orders and recent deals that carry the EA’s magic number, and treat anything saved locally as a cache to cross-check. If the two disagree, the account wins, and the EA should log the difference so a person can look into it. A Python tool can do the same for open positions: positions_get() filters only by symbol, group or ticket, so the script keeps the positions whose magic field matches the EA’s own (MQL5 Reference, positions_get).
The reason this has to be a fresh check rather than a replay of events is that nothing is replayed. If a stop loss is hit or a position is closed by hand while the EA is not running, the EA receives no event about it when it starts again. Even while running, the arrival order of trade transactions “is not guaranteed” (MQL5 Reference, Event Handling Functions).
A Start-Up Check in MQL5
Here is a minimal example. The EA counts its own open positions on this chart’s symbol from the account, compares that with the number it last saved, and makes no trading decisions until it has done so successfully. It also waits for a server connection, checked with TERMINAL_CONNECTED (Client Terminal Properties), because the terminal allows no more than 5 seconds to synchronise before starting an EA “with available data” (Program Running).
input long InpMagic = 20261201; // this EA's magic number
int g_openPositions = 0; // rebuilt from the account, never trusted from memory
bool g_stateReady = false;
bool RebuildState()
{
if(!TerminalInfoInteger(TERMINAL_CONNECTED))
return false; // no connection yet: try again later
// Just after connecting, the position list may still be syncing, so a real EA
// should wait for the first tick or a short OnTimer delay before trusting a
// count of zero.
int count = 0;
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
ulong ticket = PositionGetTicket(i); // also selects the position
if(ticket == 0) continue;
if(PositionGetInteger(POSITION_MAGIC) == InpMagic &&
PositionGetString(POSITION_SYMBOL) == _Symbol)
count++;
}
g_openPositions = count;
string key = "EA_" + (string)InpMagic + "_" + _Symbol + "_positions";
if(GlobalVariableCheck(key) && (int)GlobalVariableGet(key) != count)
PrintFormat("Saved state said %d positions, account shows %d. Using the account.",
(int)GlobalVariableGet(key), count);
GlobalVariableSet(key, count);
GlobalVariablesFlush(); // save to disk now, not at shutdown
return true;
}
int OnInit()
{
g_stateReady = RebuildState();
return(INIT_SUCCEEDED);
}
void OnTick()
{
if(!g_stateReady)
{
g_stateReady = RebuildState();
if(!g_stateReady) return; // no decisions until state is known
}
// ... trading logic uses g_openPositions ...
}
A real EA would rebuild more than a count and repeat the check from OnTrade(), but the shape is the same: ask the account first, then act.
Moving to a VPS Is a Restart Too
MetaTrader’s built-in virtual hosting migrates charts, Expert Advisors and indicators to a server; scripts are not transferred, and charts with non-standard symbols or timeframes are left behind (MetaTrader 5 Help, Preparing for migration). The help page does not say whether terminal global variables or files in MQL5\Files go with them, so an EA should not assume they do. One that rebuilds its state from the account starts correctly either way.
The TradingView Side: Recalculate, Don’t Remember
Pine Script works differently. A script runs bar by bar across the chart’s history. An indicator recalculates on each update of the live bar, rolling the bar back to its confirmed state before each run. A strategy calculates only on bar close, unless calc_on_every_tick is set. Changing an input restarts the script across the whole dataset (Pine Script v6 User Manual, Execution model). When an alert is created, TradingView saves a copy of the script, its inputs, symbol and timeframe to run on its servers; later changes on the chart do not affect it until the alert is recreated (Pine Script v6 User Manual, Alerts).
So a Pine strategy has no lasting memory of real fills. In a TradingView-to-MetaTrader setup, that knowledge belongs in the bridge or EA, which can check the account.
Limits and Caveats
The start-up check above is a starting point to test on a demo account, not a complete recovery system. The account shows what positions and orders exist, not always why: a plan’s stage or a pause reason may still need saving, and that can go stale. Brokers, account types (netting or hedging) and terminal builds differ, so test recovery against real restarts: a recompile, an input change, a dropped connection and a VPS move. None of this says anything about whether a strategy is any good; it only makes sure the EA knows where it stands when it starts again.
Conclusion
What does an Expert Advisor forget when MetaTrader restarts? Anything it kept only in memory, and it is restarted more often than most people expect. The dependable approach is to save important state as it changes, never rely on OnDeinit() alone, and on every start rebuild the picture from the account, treating saved data as a cross-check rather than the truth.
Designing EAs that recover cleanly from restarts is part of our MetaTrader Services work, with unattended, server-hosted setups covered by our Trading Automation and Cloud Infrastructure services.
Drafted with AI assistance; reviewed, edited and approved by Ionut Claudiu Fratila.