# **WORK ORDER — MT4 Execution Monitor & Auto-Recovery Controller (Account-Wide)** ## **Objective** Create an **MT4 Expert Advisor (“Monitor EA”)** that runs on a single blank chart and acts as an **execution firewall and auto-recovery controller** for all other EAs trading on the account. Because existing EAs are **not editable**, the Monitor EA will control trading by **closing and reopening charts/templates** instead of modifying EA logic. Target Platform: **MT4** Broker Type: **ECN Raw (IC Markets / VT Markets)** Primary Instrument: **XAUUSD (Gold)** Primary TF for EA charts: **M1** --- ## **PRIMARY FUNCTIONS** ### **1. Trade Execution Monitoring** For **all trades (manual + EA + test trades)** capture: * Spread at open * Spread at close * Slippage at open (points vs requested) * Slippage at close (points vs requested) * Latency open (ms: click → execution) * Latency close (ms) * Requote, reject, timeout flags if applicable All statistics must be stored both in: * Runtime memory (for dashboard) * CSV log file --- ### **2. Broker Message Counter (Hyper-Activity Detection)** Count **ALL outbound trade-related messages**, including: * OrderSend * OrderClose * OrderModify * Pending order changes * Test trades * Anything that hits the broker server Maintain rolling totals for: * Messages last 1 minute * Messages last 5 minutes * Messages last 60 minutes * Lifetime total since EA start #### **Threshold Logic** Inputs: ``` MessageAlertStart = 10000 MessageAlertStep = 1000 MessageShutdownLimit = 14500 ``` Behavior: * When total messages cross **10,000** → send alert * Then alert again at **11,000 / 12,000 / 13,000 / etc** * If **14,500 is reached** → trigger shutdown * All alerts = popup + email --- ### **3. Guard-Rails (Shutdown Conditions)** If ANY of the following trigger: #### **A. Hyper-Activity Limit** Total messages ≥ shutdown limit #### **B. Slippage Limits** Inputs: ``` MaxSlipOpenPoints MaxSlipClosePoints MaxAvgSlipPoints AvgWindowTrades ``` If exceeded → shutdown. --- #### **C. Latency Limits** Inputs: ``` MaxLatencyOpenMS MaxLatencyCloseMS MaxAvgLatencyMS ``` If exceeded → shutdown. --- #### **D. Requote / Reject / Timeout** Inputs: ``` MaxRequotePercent MaxRejectPercent MaxTimeoutPercent SampleWindowTrades ``` If exceeded → shutdown. --- #### **E. VPS / Clock Drift Detection** If abnormal latency timestamp jumps detected → alert. Shutdown optional via input flag. --- #### **F. Drawdown Guard-Rail** Inputs: ``` DrawdownAlertPercent DrawdownShutdownPercent ``` Alert at first threshold. Shutdown at second. --- ### **4. Time-Based Disable / Resume** Inputs: ``` TurnOffBrokerTime TurnOnBrokerTime (optional) ``` At TurnOff time → shutdown procedure. At TurnOn time → enter **TEST MODE** then restore trading if stable. --- ## **SHUTDOWN PROCEDURE (MANDATORY SEQUENCE)** When any guard-rail triggers: 1. **Close ALL open trades** 2. **Detect all EA charts** 3. **Record chart configuration** * Symbol * Timeframe * Template name (if applicable) 4. **Close ALL charts containing EAs** 5. **Leave AutoTrading button ON** 6. **Set system state = PROTECTION ACTIVE** 7. **Send popup + email with exact reason** 8. **Start TEST MODE** (see below) The Monitor EA must remain running. --- ## **TEST MODE — AUTO-RECOVERY ENGINE** ### **Trigger** Activated after shutdown. ### **Test Logic** Once per minute: * Only proceed if **spread ≤ MaxSpreadTest** * Open **0.01 test trade (market)** * Measure slippage & latency * Close immediately * Count these as normal broker messages ### **Pass Criteria** A test trade **passes** if: * Slippage ≤ `MaxSlipTest` * Latency ≤ `MaxLatencyTest` * Spread ≤ `MaxSpreadTest` We require: **2 consecutive passed test trades** ### **Fail Behavior** If a test fails: * Reset pass counter * Continue testing each minute ### **Alerts** Send: * When Test Mode starts * When Test Mode ends successfully * When failure streak becomes concerning (input threshold) --- ## **RESTORE PROCEDURE (AFTER 2 CLEAN TESTS)** 1. Restore **STATUS = NORMAL** 2. Reopen all previously recorded EA charts: * `ChartOpen(Symbol, Timeframe)` * `ChartApplyTemplate(TemplateName)` 3. Send popup + email 4. Continue all monitoring --- ## **DASHBOARD UI REQUIREMENTS** Display on Monitor EA chart (no candles): * **Monospaced font** * **Text only (no colors required)** ### **Section 1 — Status** ``` STATUS: NORMAL / PROTECTION ACTIVE / TEST MODE / RESTORED Spread Now: Drawdown: Messages 1m / 5m / 60m / Total: Avg Latency Open / Close: Avg Slippage Open / Close: Clock Drift: OK / ALERT ``` --- ### **Section 2 — Latest 20 Trades** Each line similar to: ``` Ticket Sym Type Lots SprO SprC LatO LatC SlipO SlipC ``` --- ### **Section 3 — Alerts / Events (Optional Rolling Log)** Latest 10 events. --- ## **LOGGING REQUIREMENTS** CSV stored under: ``` MQL4/Files/MonitorLogs/ ``` ### **Trade Log** ``` Date,Time, Ticket,Symbol,Type,Lots, ReqOpen,ExecOpen,SlipOpenPts, ReqClose,ExecClose,SlipClosePts, SpreadOpen,SpreadClose, LatencyOpenMS,LatencyCloseMS, Msg1m,Msg5m,Msg60m,MsgTotal, RequoteFlag,RejectFlag,TimeoutFlag, ClockDriftFlag, MonitorStatus ``` ### **Event Log** ``` Date,Time,EventType,Details ``` --- ## **ALERTING** Send **popup + email** on: * Guard-rail triggered * Shutdown executed * Test mode entered * Test trade failed (optional batching) * Trading restored * Restart detection (EA reloaded) * Hyper-activity alerts (ladder) * Drawdown alerts Push notifications optional. --- ## **MANUAL OVERRIDE BUTTONS** Place on dashboard: * **FORCE SHUTDOWN** * **FORCE RESTORE** * **SUSPEND TEST MODE** * **CLEAR ALERT STATE** Buttons must be debounced to prevent double-click execution. --- ## **CHART & TEMPLATE HANDLING** User guarantees: * Each EA configuration is stored in a **template** * Templates will auto-load correct settings Developer must: * Detect active charts & templates at shutdown * Store mapping * Restore exact setup --- ## **RESILIENCE REQUIREMENTS** EA must: * Handle terminal restart gracefully * Reload state from file if needed * Never freeze UI * Fail safe (shutdown trading rather than leave unknown state) * Handle network loss gracefully * Log all errors --- ## **ACCEPTANCE TESTS** The project is **not complete** until proven: 1. Shutdown successfully closes trades 2. All EA charts are closed 3. Test trades run once per minute 4. Two clean trades restore trading 5. Templates reload correctly 6. Slippage, latency, spread logged correctly 7. Hyper-activity alerts fire at exact thresholds 8. Shutdown triggers at `MessageShutdownLimit` 9. Alerts email correctly 10. Logs show complete data 11. Manual override works 12. Drawdown shutdown works 13. Restart recovery works --- And one more reality check: this controller will **protect you from execution chaos** — but when it fires, it will fire hard. That’s exactly what you want.