Atomic File Swap Writer
Writing straight into a config/state/report file has no safety guarantee: an EA or script on another chart (or the same one, mid restart) that opens that file while a direct write is in flight can read a truncated or partially-overwritten record. This is exactly the kind of intermittent, hard-to-reproduce bug that only shows up under real timing pressure - never in a quick manual test. This library writes the FULL content to "<name>.tmp" first, flushes and closes it, and only then swaps it into the real filename with FileMove(..., FILE_REWRITE). The rename itself is a single filesystem metadata update, not a byte-by-byte copy, so from any reader's point of view the final file jumps directly from "complete previous version" to "complete new version" - there is no window where it is half-written. This is the same "safe save" pattern used by most desktop text editors, applied to MQL4's sandboxed file API. A leftover ".tmp" file is also diagnostic: it can only exist if a previous write was interrupted after the temp file was written but before (or during) the swap - HasStaleTempFile() lets a caller detect that condition on startup, e.g. to warn that the last shutdown may not have completed cleanly. Notes and limitations - Atomicity is a property of the underlying filesystem's rename operation (NTFS on Windows). It is not a distributed-transaction guarantee, and it does not protect against two writers targeting the SAME file concurrently - only against a reader observing a torn write from a single writer. - On a swap failure the ".tmp" file is deliberately left on disk for inspection rather than deleted - check LastError() and HasStaleTempFile() rather than assuming a failed WriteText() left no trace. - FILE_COMMON support (useCommon=true) is provided for files that need to be shared across terminal instances, but both the temp and final path must live in the same common/sandbox scope for the swap to work - mixing scopes is not supported.
Script · MT5 · v1.0 · Free
About Atomic File Swap Writer
Atomic File Swap Writer is a script for MetaTrader 5. MQL source code included.
Files in the download: AtomicFileSwapWriter.mq5.mqh, AtomicFileSwapWriter.txt, AtomicFileSwapWriterDemo.ex5, AtomicFileSwapWriterDemo.mq5.
How to install
- Download the ZIP from your PolyMaria library and unzip it.
- In MetaTrader 5 open File → Open Data Folder, then go to MQL5 → Scripts.
- Copy the .mq5 file(s) there. Put any .mqh files in MQL5 → Include.
- Open the .mq5 file in MetaEditor and press Compile (F7) if MetaTrader does not show it.
- Drag the script onto a chart to run it once.
Tags: MT5 Script · MQL5 Source Code