Making my EA survive a restart without forgetting its state
I restarted my platform once while the EA had open trades and it behaved strangely. It had lost track of things like which trades had already had a partial close, and how many trades it had taken that day. It took some clean up to fix.
The lesson was that anything the EA needs to remember across a restart can't live only in variables. Variables disappear when the program is removed or the platform restarts. Now I store the important bits where they persist: in global variables of the terminal, or in a small file.
What I save: the count of trades today, the daily starting balance, flags for partial closes keyed by the position ticket, and the time of the last trade for cooldowns. On startup, the EA reads those values and also scans the open positions to rebuild its picture. If something doesn't match, it logs a warning.
I test by deliberately stopping the platform mid trade on a demo, and restarting. It's easy to forget, but a restart will happen eventually, due to an update, a power cut or a mistake.
Making my EA survive a restart without forgetting its state
Re: Making my EA survive a restart without forgetting its state
One thing I would add is to save the magic number logic carefully. If you run the same EA on several charts, each instance needs its own magic number so that on restart each one only picks up its own trades. I had a bug where two instances both thought they owned the same position after a restart, and one tried to manage it with the wrong rules. Scanning open positions by symbol and magic number on startup fixed it, and now each instance rebuilds only what belongs to it.
It’s Fairman 
Re: Making my EA survive a restart without forgetting its state
For anyone using terminal global variables, be aware they can be cleared if you delete them by hand or if the terminal data is reset, and they only store numbers. I use them for counts and timestamps, but anything more complex goes into a small file in the files folder, written each time the value changes. I also write a version number at the top of the file so that if I change the format later, the EA can tell an old file from a new one and not misread it.
It’s Fairman 
Re: Making my EA survive a restart without forgetting its state
Testing restarts deliberately on demo is the best advice in this thread. I go further and test the ugly cases: restart during the news filter, restart just after a partial close, and restart across midnight server time when the daily counters should reset. The midnight one caught a bug where the daily trade count carried over from the previous day because the saved date was not compared on startup. Without forcing those cases I would never have found it until it cost me a trade.
It’s Fairman 
-
Shadow Trader
- Posts: 5594
- Joined: Wed Sep 09, 2026 5:19 pm
Re: Making my EA survive a restart without forgetting its state
One failure mode worth testing is the power cut that lands halfway through writing the state file. The file can end up truncated, and on restart the EA reads half a record as if it were valid.
The usual fix is to write to a temporary file first and only then replace the real one, so the saved state is always either the old version or the new one. The version number mentioned above helps here too, since a file with a missing or odd header can be rejected instead of trusted.
On MT4 there is a second trap with flags keyed by ticket. A partial close there gives the remaining position a new ticket number, so a flag saved against the old ticket no longer matches anything after the close.
For the daily trade count, rebuilding it from the account history on startup is often safer than saving it at all. The server's record of today's deals cannot drift out of date, and it also catches a trade closed by the stop while the platform was down.
That leaves the file for things the server cannot know, like cooldown timers and which management stage a trade has reached. Has anyone found a clean way to test the half written file case on demo, short of pulling the plug?
The usual fix is to write to a temporary file first and only then replace the real one, so the saved state is always either the old version or the new one. The version number mentioned above helps here too, since a file with a missing or odd header can be rejected instead of trusted.
On MT4 there is a second trap with flags keyed by ticket. A partial close there gives the remaining position a new ticket number, so a flag saved against the old ticket no longer matches anything after the close.
For the daily trade count, rebuilding it from the account history on startup is often safer than saving it at all. The server's record of today's deals cannot drift out of date, and it also catches a trade closed by the stop while the platform was down.
That leaves the file for things the server cannot know, like cooldown timers and which management stage a trade has reached. Has anyone found a clean way to test the half written file case on demo, short of pulling the plug?
-
FXS Prop Desk
- Posts: 1689
- Joined: Wed Oct 07, 2026 9:52 am
Re: Making my EA survive a restart without forgetting its state
One detail with terminal global variables: the terminal writes them to disk when it shuts down normally, so after a crash or a power cut the latest values can be missing. Calling GlobalVariablesFlush() right after each change closes that gap.
For the file, writing to a temporary file first and then replacing the old one means a cut in the middle of a write can't leave you with half a file and an EA that reads garbage on startup.
How do you handle a position that changed size while the EA was off, for example a manual partial close from the phone? Comparing the saved lot size with the current one on startup would catch that before the EA tries to close a piece that is already gone.
For the file, writing to a temporary file first and then replacing the old one means a cut in the middle of a write can't leave you with half a file and an EA that reads garbage on startup.
How do you handle a position that changed size while the EA was off, for example a manual partial close from the phone? Comparing the saved lot size with the current one on startup would catch that before the EA tries to close a piece that is already gone.
FXS Official Team | The Idea Lab & Strategy
-
Shadow Trader
- Posts: 5594
- Joined: Wed Sep 09, 2026 5:19 pm
Re: Making my EA survive a restart without forgetting its state
On the question of a position that changed while the EA was off, a startup routine that reconciles before managing anything handles most of it. The saved state says what the EA expects, and the server says what is actually there.
Say the file records 0.30 lots at stage zero, with the first partial still to come, and startup finds 0.20 lots open. The EA should not close another third of the original size, since that would take the position down to 0.10.
The safer rule is to treat any shrink as an outside change, mark the first stage done, and log it for a human to check. If the position is gone entirely, the account history shows whether it closed at the stop, the target or by hand.
Pending orders are the other blind spot, because the server can fill them while the terminal is closed. An EA that placed a limit before going offline may wake up with a live trade it has no stage or timer for.
Scanning for positions with the EA's magic number but no matching record, and giving them a default state, closes that gap. Does anyone let the EA carry on managing those, or flag them and stand aside?
Say the file records 0.30 lots at stage zero, with the first partial still to come, and startup finds 0.20 lots open. The EA should not close another third of the original size, since that would take the position down to 0.10.
The safer rule is to treat any shrink as an outside change, mark the first stage done, and log it for a human to check. If the position is gone entirely, the account history shows whether it closed at the stop, the target or by hand.
Pending orders are the other blind spot, because the server can fill them while the terminal is closed. An EA that placed a limit before going offline may wake up with a live trade it has no stage or timer for.
Scanning for positions with the EA's magic number but no matching record, and giving them a default state, closes that gap. Does anyone let the EA carry on managing those, or flag them and stand aside?
-
Shadow Trader
- Posts: 5594
- Joined: Wed Sep 09, 2026 5:19 pm
Re: Making my EA survive a restart without forgetting its state
When an automated system restarts, it must rebuild its understanding of the world. Open positions, pending orders, and partially completed actions may exist from before the shutdown, and the program's internal state is gone.
A robust design queries the broker for all current positions and orders at startup and compares them with a persisted record of intended state. Differences are resolved according to defined rules. Orphaned positions without matching strategy records might be closed or adopted, depending on policy.
Tagging orders with identifiers, such as magic numbers or comments, makes it possible to attribute positions to specific strategies or signals. Persisting state to disk at key moments, such as after each order confirmation, allows recovery. Without reconciliation, restarts can produce duplicate trades, forgotten positions, or double hedges. Testing the restart behavior in a controlled environment, with positions open and orders pending, verifies that the logic handles realistic situations. A strategy that cannot restart safely carries hidden operational risk.
A robust design queries the broker for all current positions and orders at startup and compares them with a persisted record of intended state. Differences are resolved according to defined rules. Orphaned positions without matching strategy records might be closed or adopted, depending on policy.
Tagging orders with identifiers, such as magic numbers or comments, makes it possible to attribute positions to specific strategies or signals. Persisting state to disk at key moments, such as after each order confirmation, allows recovery. Without reconciliation, restarts can produce duplicate trades, forgotten positions, or double hedges. Testing the restart behavior in a controlled environment, with positions open and orders pending, verifies that the logic handles realistic situations. A strategy that cannot restart safely carries hidden operational risk.