Discussing the article: "State Persistence in MQL5 (Part 1): A Crash-Safe State Store That Survives a Restart"
You are missing trading opportunities:
- Free trading apps
- Over 8,000 signals for copying
- Economic news for exploring financial markets
Registration
Log in
You agree to website policy and terms of use
If you do not have an account, please register
Check out the new article: State Persistence in MQL5 (Part 1): A Crash-Safe State Store That Survives a Restart.
The series develops state persistence for MQL5 Expert Advisors. Part 1 delivers a crash-safe key-value store: a CStateStore class that saves through a temporary file and a rename, carries a versioned header with a checksum, and stores integers, doubles, strings, booleans, and double arrays, plus a demo advisor that resumes a counter and a rolling window after a restart. Readers get a compact include file and a pattern that protects the live state file if the process dies mid-save.
MQL5 already gives us three well-known ways to keep state on disk. The first writes a fixed-size structure to a binary file, as in the article Keeping Memory Across Restarts: EA State Persistence Using Binary Files in MQL5. The second is a key-value store over a flat file, covered recently in the article Persistent Key-Value Store in MQL5: Using Flat Files as a Lightweight Database for EA State. The third is a database, with the SQLite engine the platform ships natively, which the series Engineering a Self-Healing Expert Advisor in MQL5 uses to persist trade state. SQLite, used with its transactions, already solves the write-safety problem this article is about, and it is the right tool once the state grows. The binary structure is compact and restores doubles bit for bit, but it holds only fixed-size members, so strings and dynamic arrays stay out. The binary and flat-file articles both write over the live file in place. The binary one checks only a version field on load, and neither verifies the content with a checksum.
The flat-file article is open about its own weak point. Its reliability analysis names a crash between truncating the file and finishing the write as the primary failure mode. It suggests a temporary file and a rename as the mitigation, a technique it expected to require a DLL. This article implements that mitigation with the native FileMove function, with no DLL, in a small, dependency-free class.
For a developer, the article builds that class step by step. Each save writes a temporary file and only then renames it over the live one. A header with a magic word, a version and a checksum lets the load reject a file whose pairs were truncated or changed. The store also keeps double arrays, so model weights and running statistics survive a restart along with counters.
Author: Martin Alejandro Bamonte