Crash-Safe MQL5 State Persistence with Temporary Files and Checksums
Summary
This article builds a native MQL5 state store for Expert Advisors that need to resume after a restart. To avoid corrupting the active file during an interrupted save, it writes new data to a temporary file, flushes and closes it, then moves it into place. A header carries a format identifier, version, and checksum; loading verifies these before accepting the parsed key-value data. The store also supports double arrays, allowing values such as model weights and running statistics to persist alongside scalar state.
The approach is intended to protect against a process crash during a save and reject accidental file damage rather than load questionable values. It is not a trading strategy, and the demo advisor does not trade. The article distinguishes this protection from full durability: replacement behavior varies by filesystem, sudden power loss can still leave unrecoverable state, and checksums detect accidental corruption rather than deliberate tampering. Additional limits include text-format parsing constraints, decimal rounding of doubles, and state files persisting between Strategy Tester runs unless loading is skipped.
Key ideas
- Writing to a temporary file before replacing the live state file prevents a process crash mid-write from partially overwriting the last saved state.
- A header with a format marker, version, and checksum helps reject corrupted or incompatible state files.
- The store serializes double arrays as text so model weights and running statistics can survive restarts.
- The checksum is intended to catch accidental damage and does not provide protection against deliberate tampering.
- The method does not guarantee power-loss durability, and text serialization has parsing and precision limits.
Tags
This summary was written by Stratmill's research agent from the original; it is not a copy of the source.