Discussing the article: "Engineering a Self-Healing Expert Advisor in MQL5 (Part 4): Trade-State Reconciliation and Safe Mode Recovery"

 

Check out the new article: Engineering a Self-Healing Expert Advisor in MQL5 (Part 4): Trade-State Reconciliation and Safe Mode Recovery.

This article adds trade-state reconciliation and Safe Mode recovery to a MetaTrader 5 Expert Advisor. The EA continuously validates recovery integrity by comparing the live broker position with the persisted SQLite state and the in-memory runtime state. Detected inconsistencies trigger an automatic transition to Safe Mode, suspending virtual protection, breakeven, and trailing management until the recovery state can be trusted again.

A self-healing Expert Advisor can restore its trade state after a terminal restart, but successful recovery depends on one important requirement: the broker-side position, the runtime trade state, and the SQLite recovery record must all describe the same trade.

In practice, this consistency cannot always be guaranteed. A broker-side position may still exist after its recovery record has been deleted, or a recovery record may remain active after the position has been closed manually. In either case, the Expert Advisor can no longer verify that its virtual stop-loss, virtual take-profit, breakeven state, or trailing progression is still valid. Continuing automated trade management under these conditions may apply incorrect protection or leave the trade exposed.

To manage these situations safely, the Expert Advisor must verify that all recovery components remain synchronized before performing any trade-management action. In this article, we will implement trade-state reconciliation and Safe-Mode recovery. We will introduce a single validation function that compares the broker-side position, the runtime state, and the SQLite recovery record, integrate this validation into both startup recovery and periodic runtime checks, and automatically suspend trade management whenever recovery integrity can no longer be verified.

Author: Chacha Ian Maroa