DEV Community

Omais Ali
Omais Ali

Posted on

Keeping MQL5 EA state alive across terminal restarts

An Expert Advisor that keeps important state only in global variables of the program loses it every time the terminal restarts, the VPS reboots, or someone changes the chart timeframe. Counters reset, a daily loss lock disappears, and a grid EA forgets which level it was on.

Here is a small pattern that has worked well for me.

1. Decide what must survive

Typical candidates: trades opened today, realised loss today, a lock flag set after the daily limit was hit, and the date those values belong to. Anything you can rebuild from the open positions list should be rebuilt instead of stored.

2. Store it in terminal global variables

Terminal global variables persist on disk and survive a restart. Prefix the name with the symbol and magic number so two instances never collide.

string Key(string name)
{
   return StringFormat("EA_%s_%I64d_%s", _Symbol, InpMagic, name);
}

void SaveState()
{
   GlobalVariableSet(Key("day"), (double)iTime(_Symbol, PERIOD_D1, 0));
   GlobalVariableSet(Key("loss"), g_lossToday);
   GlobalVariableSet(Key("locked"), g_locked ? 1.0 : 0.0);
   GlobalVariablesFlush();
}

void LoadState()
{
   datetime today = iTime(_Symbol, PERIOD_D1, 0);
   if(GlobalVariableCheck(Key("day")) && (datetime)GlobalVariableGet(Key("day")) == today)
   {
      g_lossToday = GlobalVariableGet(Key("loss"));
      g_locked    = GlobalVariableGet(Key("locked")) > 0.5;
   }
   else
   {
      g_lossToday = 0;
      g_locked    = false;
   }
}
Enter fullscreen mode Exit fullscreen mode

3. Call it at the right moments

Call LoadState in OnInit and SaveState whenever a value changes, for example in OnTradeTransaction after a deal closes. GlobalVariablesFlush forces a write so a crash right after does not lose the update.

4. Rebuild, then compare

After loading, scan open positions with your magic number and compare with what the state says. If they disagree, log a warning and trust the positions. The broker is the source of truth; your file is a cache.

Things to watch

Terminal global variables are deleted after four weeks without access, so do not use them for long term history. For that, write a CSV to the Files folder. And never store anything secret in them, since any EA on the terminal can read them.

Top comments (0)