Dead-Man's Switch for MetaTrader 5: An EA Heartbeat That Reports Health, and a Guardian That Acts When It Goes Silent
Introduction
Every EA I've shipped eventually asks the same question at 3 a.m.: is it actually still running, or did it quietly stop three hours ago while still looking green in the terminal? A crashed EA is loud - you get a popup, a red cross on the chart. A silently stuck EA is not. AutoTrading can get toggled off by someone else on a shared VPS, a broker can freeze quotes without disconnecting the terminal, a timer handler can hang on a blocking call you didn't think was blocking, and the chart will sit there looking perfectly normal while nothing is happening behind it.
This article builds a dead man's switch for that exact failure mode. One EA (the host) emits a small, information-dense "health beat" every few seconds to a relay process that lives outside the terminal. A second EA (the guardian) polls that relay and runs its own state machine, independent of whatever is wrong with the host. If the beats stop for long enough, the guardian confirms it, alerts, and - if you want it to - acts: moves stops to breakeven or flattens the positions tied to a magic number.
I ran the whole thing on a real MetaQuotes-Demo account, injected two different kinds of fault on purpose, and recorded what actually happened, including one thing that didn't go the way I expected on the first pass. That part stays in.
Scope. This is a watchdog for the EA's own liveness, not a trading-signal filter and not a replacement for broker-side risk controls. Whether the host is alive is inferred solely from what the host reports in its beat. The guardian has no independent confirmation beyond the JSON payload. Its view of the account when it acts is different: ActFlatten() and ActBreakeven() read live positions straight off the terminal via PositionsTotal(), POSITION_MAGIC rather than out of that payload.
The host EA and the guardian EA still run in the same terminal and on the same trading account, using the same network path to the relay. This provides independence from the host's process memory and code path, but not from the terminal, the VPS, or the account as a whole. I tested two fault types on one demo account over a few hours: beats silently stopped while the EA kept running, and the EA's timer thread blocked outright. I did not test a hard EA crash, a killed terminal process, the relay going down while the host kept beating, or a flatten against a real open position - those are noted as open items at the end, not folded into the results as if they were covered.
Why a heartbeat, not a liveness ping
A simpler version of this idea is a ping: the EA posts "I'm alive" every N seconds, and a watcher complains if the pings stop. I didn't build that, because a ping tells you the EA process exists and nothing else. An EA can be technically alive and still be useless - AutoTrading disabled, the account barred from trading, quotes frozen, the symbol's session closed. A ping would keep going the whole time.
So the beat carries vitals, not just a timestamp. Every beat reports a bitmask of health flags, the tick age on the EA's own symbol, open position count and floating result for its magic number, and the account's margin level - that margin figure is telemetry only, logged for the reader to act on, and it doesn't feed the bad-mask or the DEGRADED classification itself. The guardian doesn't currently act on a mix of flags beyond flagging DEGRADED alone, but the data is there in the relay's JSON if you want to build alerting on top of it later - "the EA is beating but AutoTrading is off" is a diagnosis this design can surface that a plain ping can't. It is worth being explicit about the limitation, though: if AutoTrading is off at the terminal level, the guardian's own ActFlatten() or ActBreakeven() will likely fail to place orders for the same reason the host couldn't - the switch can tell you trading is disabled, it can't trade around that fact.
It's worth being explicit about what this replaces, because the obvious shortcuts all fail the same way. A GlobalVariable the EA updates on every tick looks like a heartbeat, but it only proves the EA is alive to something else running in the same terminal - a watcher EA on another chart can read it, a process outside MetaTrader can't, and if the terminal itself hangs or the machine loses power, there's nothing left to read it anyway. A file the EA touches periodically has the same blind spot, plus whatever filesystem-caching surprises come with running it over a network share.
A Telegram bot the EA pings directly solves the "outside the terminal process" problem but puts the alerting path through the same process that might be the thing that's stuck - if the EA's thread is blocked, as in the hang test below, it can't send that message either, and now the one signal you were relying on is silent for exactly the reason you needed it to fire. Using a separate relay process with its own clock makes the “last beat received” timestamp trustworthy even when the host is not. The relay still runs on the same machine and will fail if the VPS goes down, but it cannot be blocked by failures inside the terminal process. What it can't do anything about is the payload's content: the host still decides what bad, positions, and floating say, so the relay can vouch for when a beat arrived, not for whether what it contains is accurate.
The three pieces and how they talk
There are three separate programs, deliberately not sharing process memory with each other:
- CHeartbeatEmitter, a class the host EA owns. It POSTs a JSON beat to the relay on every timer tick.
- relay.py, a small Python HTTP server with zero third-party dependencies. It stamps every beat with its own clock - nothing the EA claims about time is trusted - and persists state to disk so a relay restart doesn't lose history.
- CGuardian, a class a second EA owns. It polls the relay's /status endpoint on its own timer and runs a state machine that's completely decoupled from the host's code path.
That separation is the actual point of the design, scoped honestly: it buys memory and code-path independence, not full failure-domain independence. If the host EA's own process locks up - the fault I tested in the second run below - nothing it can do affects the guardian's own logic, because the guardian isn't reading anything out of the host's memory; it's reading a relay that stamped its own last-seen time, in a different process, on a clock the host doesn't control. What the two EAs still share: the same terminal, the same trading account, the same AutoTrading switch, and the same VPS. A terminal-wide freeze, AutoTrading toggled off, or the VPS itself going down can affect both EAs at once - this design catches "the host went quiet while everything else kept working," not "the whole box is down," and the next section is explicit about which of those relay.py actually covers.

Fig. 1. The three processes and who talks to whom - solid arrows are always-on, the dashed arrow fires only once DEAD is confirmed.
- Host EA (EURUSD H1) - CHeartbeatEmitter class, OnTimer() calls Beat()
- relay.py - standard library only, its own clock, persists to relay_state.json
- Guardian EA (AUDUSD H1) - CGuardian::Step() itself, the state machine from the next section
- DMS_StatusView - reads the GlobalVariables CGuardian::Publish() writes, no network call of its own
- Act() - alert-only, breakeven, or flatten, dispatched only once DMS_STATE_DEAD is confirmed
Protocol struct: what a beat and a status reply actually contain
//--- vitals collected by the host EA for one beat struct SDmsVitals { ulong seq; // beat counter, bumped on every attempt ulong boot; // instance stamp, changes on every restart long login; // account login int periodSec; // configured beat period int bad; // DMS_BAD_* mask int tickAgeSec; // seconds since the last tick, -1 if none int positions; // open positions for the magic number double floating; // floating result for the magic number double marginLevel; // percent, 0 when no margin is used bool sessionOpen; // symbol is inside a trade session }; //--- relay answer as the guardian sees it struct SDmsStatus { bool reachable; // relay answered HTTP 200 bool known; // relay has seen this node id bool armed; // not inside a disarm window int http; // HTTP status, -1 on transport error int bad; // DMS_BAD_* mask of the last beat int gaps; // beats lost, counted from sequence holes int restarts; // EA restarts seen by the relay long login; // account login of the last beat ulong seq; // last sequence number double age; // seconds since the last beat, relay clock };
Notice that age is computed on the relay's own clock, never trusted from the EA. If the host's local clock is wrong, or if NTP drifts on the VPS, it doesn't matter - the relay only cares about when it last received bytes, not what timestamp those bytes claimed.
Collecting a beat
The emitter's Collect() builds the vitals struct fresh on every call, reading straight from the terminal rather than caching anything:
CHeartbeatEmitter::Collect
//+------------------------------------------------------------------+ //| CHeartbeatEmitter::Collect | //+------------------------------------------------------------------+ void CHeartbeatEmitter::Collect(SDmsVitals &v) { ZeroMemory(v); m_seq++; v.seq=m_seq; v.boot=m_boot; v.login=AccountInfoInteger(ACCOUNT_LOGIN); v.periodSec=m_period; v.positions=CountPositions(v.floating); v.marginLevel=AccountInfoDouble(ACCOUNT_MARGIN_LEVEL); v.sessionOpen=DmsSessionOpen(m_symbol); long tq=SymbolInfoInteger(m_symbol,SYMBOL_TIME); v.tickAgeSec=(tq>0) ? (int)MathMax((long)0,(long)TimeTradeServer()-tq) : -1; int bad=0; if(TerminalInfoInteger(TERMINAL_CONNECTED)==0) bad|=DMS_BAD_DISCONNECTED; if(TerminalInfoInteger(TERMINAL_TRADE_ALLOWED)==0) bad|=DMS_BAD_TERMINAL_TRADE; if(MQLInfoInteger(MQL_TRADE_ALLOWED)==0) bad|=DMS_BAD_EA_TRADE; if(AccountInfoInteger(ACCOUNT_TRADE_ALLOWED)==0 || AccountInfoInteger(ACCOUNT_TRADE_EXPERT)==0) bad|=DMS_BAD_ACCOUNT_TRADE; if(v.sessionOpen && v.tickAgeSec>m_staleSec) bad|=DMS_BAD_STALE_QUOTES; v.bad=bad; }
The tickAgeSec line is the one I'd flag if you're adapting this: it casts through long on both sides of the subtraction before narrowing back to int again, specifically so a brief negative delta - possible if the symbol's server-time tick lands a touch ahead of TimeTradeServer() on a slow refresh - can't wrap into a huge unsigned-looking number and trip the stale-quote flag by accident.
Beat() is what actually sends it, and it's also where the fault-injection hook for the first test lives:
CHeartbeatEmitter::Beat
//+------------------------------------------------------------------+ //| CHeartbeatEmitter::Beat | //+------------------------------------------------------------------+ bool CHeartbeatEmitter::Beat(void) { if(m_mute) return(false); SDmsVitals v; Collect(v); m_stats.attempts++; m_stats.seq=v.seq; m_stats.bad=v.bad; m_stats.tickAge=v.tickAgeSec; //--- a withheld beat still burns its sequence number, the relay sees the hole if(m_dropEvery>0 && (v.seq%(ulong)m_dropEvery)==0) { m_stats.dropped++; return(false); } if(m_skip>0) { m_skip--; m_stats.skipped++; return(false); } //--- the tester has no WebRequest, only the schedule is counted if(MQLInfoInteger(MQL_TESTER)!=0) { m_stats.http=-2; return(true); } string payload=DmsBuildPayload(m_id,v); char body[]; char reply[]; string replyHdr; string hdr="Content-Type: application/json\r\nX-DMS-Token: "+m_token+"\r\n"; StringToCharArray(payload,body,0,StringLen(payload),CP_UTF8); ulong t0=GetMicrosecondCount(); ResetLastError(); int code=WebRequest("POST",m_url+"/beat",hdr,m_timeout,body,reply,replyHdr); int err=GetLastError(); m_stats.rttMs=(double)(GetMicrosecondCount()-t0)/1000.0; m_stats.http=code; if(code==200) { m_stats.fails=0; LogBeat(v); return(true); } m_stats.fails++; if(m_stats.fails==1 || (m_stats.fails%30)==0) { PrintFormat("DMS: beat %I64u failed, http=%d err=%d",v.seq,code,err); if(code==-1) DmsWebHint(err); } //--- three misses in a row and the emitter backs off a few ticks if(m_stats.fails>=3) m_skip=MathMin(m_stats.fails-2,4); LogBeat(v); return(false); }
That backoff matters on a flaky connection: a WebRequest timeout of 3000 ms would otherwise block the timer tick for up to three seconds, on every tick, while the EA is also meant to be trading.
The relay: a clock the host EA doesn't control
Everything above only matters if the thing receiving the beats can't be fooled by the host's own idea of time. relay.py is deliberately boring - standard library only, a ThreadingHTTPServer instance, and a shared-secret token checked with hmac.compare_digest rather than a plain string match, so a timing side-channel on the token comparison isn't a free vulnerability I'd be shipping by accident. That constant-time check is a narrow guarantee, though - it protects the token comparison itself, not the channel.
There's no TLS, no per-request signature, and no replay protection on top of it, and the node id in the payload isn't bound to an account: anyone holding the token can post under any id they like and overwrite that node's state in the relay. On 127.0.0.1 itself, with the token kept off a shared machine, that's an acceptable trade-off; move the relay off localhost and it stops being one.
record_beat
def record_beat(doc): nid = str(doc.get("id", "")) if not ID_RE.match(nid): raise ValueError("bad id") seq = int(doc["seq"]) boot = int(doc.get("boot", 0)) with LOCK: n = NODES.setdefault(nid, new_node()) if n["beats"] > 0: if boot != n["boot"]: n["restarts"] += 1 elif seq > n["seq"] + 1: n["gaps"] += seq - n["seq"] - 1 n["seq"] = seq if boot != n["boot"] else max(seq, n["seq"]) n["boot"] = boot n["beats"] += 1 n["mono"] = time.monotonic() n["wall"] = time.time() # the vitals the guardian and the watcher depend on n["bad"] = int(doc.get("bad", 0)) n["tick_age"] = int(doc.get("tick_age", -1)) n["positions"] = int(doc.get("positions", 0)) n["floating"] = float(doc.get("floating", 0.0)) n["margin_level"] = float(doc.get("margin_level", 0.0)) n["session_open"] = int(doc.get("session_open", 0)) n["login"] = int(doc.get("login", 0)) n["period"] = max(1, int(doc.get("period", 10))) save_state()
Two things stand out in that function. First, mono is what every age calculation is based on - time.monotonic() itself, which can't jump backwards if the relay's wall-clock gets NTP-corrected mid-session, but which also isn't meaningful across a process restart on its own. load_state() accounts for that: on startup it rebuilds each node's mono stamp from the persisted wall time via time.monotonic() - (time.time() - wall) math, so a relay restart doesn't silently report every node as freshly beating when it hasn't heard from any of them yet. Second, the gap counter compares the incoming seq against what the relay already has: if the host's sequence number jumps by more than one, that's a dropped beat recorded permanently in gaps itself, separate from whatever the guardian's live state machine decides about silence. You get that number even for a gap too short to ever trip the guardian's own detection threshold - useful for noticing a flaky link before it becomes an incident.
The timestamps are only half of what record_beat keeps. Every field of the beat that matters is stored on the node, right after them in the same function: the bad mask, the login, the beat period, the tick age, the position count and floating result, the margin level and the session flag. The period is what the watcher's limit uses, and the bad mask and login are what /status hands to the guardian. The reply is built by status_of():
status_of
def status_of(nid): with LOCK: n = NODES.get(nid) if n is None: return {"known": 0, "armed": 1, "age": -1, "bad": 0, "gaps": 0, "restarts": 0, "seq": 0, "login": 0} return { "known": 1 if n["beats"] > 0 else 0, "armed": 1 if time.time() >= n["disarm_until"] else 0, "age": round(age_of(n), 2), "bad": n["bad"], "gaps": n["gaps"], "restarts": n["restarts"], "seq": n["seq"], "login": n["login"], "positions": n["positions"], "tick_age": n["tick_age"], "floating": n["floating"], "period": n["period"], "beats": n["beats"], }
That closes the loop from payload to guardian: the bad, login and seq in SDmsStatus come straight from the last beat, and age is computed on the relay's clock at the moment of the poll. One honest detail: margin_level and session_open are stored on the node but /status does not return them, so the guardian never sees them - they are there for anyone reading the relay's state file, which fits the telemetry-only role of the margin figure described earlier.
The boot value is what separates a dropped sequence number from a genuine restart. The host EA sets boot once in CHeartbeatEmitter::Init() itself, using the local clock and the tick counter. It remains constant for the EA's lifetime; any restart produces a new boot value. When a beat shows up carrying a boot value that doesn't match what the relay already has on file for that node, record_beat treats it as a restart rather than a gap: the sequence counter resets to whatever the new instance reports instead of being compared against the old one, so a legitimate restart doesn't get misread as hundreds of lost beats.
Watching that restarts counter climb was, in fact, exactly how the stale fault-flag behavior described further down first became visible as a pattern rather than a one-off - the host kept restarting cleanly on every parameter change, and kept staying silent anyway, which only makes sense once you separate "the process came back" from "the process came back in the state you expected."
The relay also runs its own one-second watcher loop, independent of any guardian polling it:
watcher
def watcher(): while True: time.sleep(1.0) out = [] with LOCK: for nid, n in NODES.items(): if n["beats"] == 0: continue age = age_of(n) armed = time.time() >= n["disarm_until"] limit = n["period"] * ARGS.miss + ARGS.grace if armed and age > limit and not n["alerted"]: n["alerted"] = True out.append("[%s] silent for %.0fs" % (nid, age)) elif n["alerted"] and age <= n["period"] * 1.5: n["alerted"] = False out.append("[%s] beating again" % nid) for m in out: push(m)
That loop was what gave me the clearest evidence later of exactly how long the host went silent, independent of anything the EA terminal was telling me - the relay's own console is a plain, append-only transcript of exactly when a node went quiet and when it came back, in a process the host EA can't influence once a beat stops arriving.
The guardian's state machine
This is the part that actually decides whether something is wrong. CGuardian::Step() is a pure function of the relay's last answer and its own internal counters - it never looks at the host EA at all:
CGuardian::Step
//+------------------------------------------------------------------+ //| CGuardian::Step | //+------------------------------------------------------------------+ ENUM_DMS_STATE CGuardian::Step(const SDmsStatus &st) { ENUM_DMS_STATE prev=m_state; ENUM_DMS_STATE next=m_state; m_st=st; //--- an unreachable relay says nothing about the node if(!st.reachable) { m_relayFails++; m_deadPolls=0; if(m_relayFails==DMS_RELAY_ALERT_AFTER) Notify("relay unreachable, no action taken"); if(m_latched && !m_actionDone) Act(); Publish(); return(m_state); } if(m_relayFails>=DMS_RELAY_ALERT_AFTER) Notify("relay reachable again"); m_relayFails=0; //--- classify this poll double freshAt=1.5*(double)m_cfg.beatPeriod; double deadAt=(double)(m_cfg.missBeats*m_cfg.beatPeriod+m_cfg.graceSec); bool advanced=(st.seq!=m_lastSeq); if(!st.armed) { next=DMS_STATE_DISARMED; m_deadPolls=0; m_cleanPolls=0; Release(); } else if(!st.known) { next=DMS_STATE_UNKNOWN; m_deadPolls=0; } else if(st.age>deadAt) { m_deadPolls++; m_cleanPolls=0; next=(m_deadPolls>=m_cfg.confirmPolls) ? DMS_STATE_DEAD : DMS_STATE_LATE; } else if(st.age>freshAt) { m_deadPolls=0; m_cleanPolls=0; next=DMS_STATE_LATE; } else { m_deadPolls=0; if(advanced) m_cleanPolls++; next=(st.bad!=0) ? DMS_STATE_DEGRADED : DMS_STATE_OK; } m_lastSeq=st.seq; //--- once fired, only a run of clean beats releases the latch if(m_latched && next!=DMS_STATE_DISARMED) { if(m_cleanPolls>=m_cfg.rearmBeats) Release(); else next=DMS_STATE_DEAD; } if(next==DMS_STATE_DEAD && !m_latched) { m_latched=true; m_actionDone=false; m_closeTries=0; m_deadEntries++; } m_state=next; if(next!=prev) { m_transitions++; OnTransition(prev,next,st); } if(m_latched && !m_actionDone) Act(); Publish(); return(m_state); }
Three things are doing real work here. First, an unreachable relay is handled as its own branch, never folded into the dead count - if I can't reach the relay, I genuinely don't know whether the host is fine, and treating "I can't check" the same as "confirmed dead" is how you get an EA flattening live positions because of a Wi-Fi blip on the VPS, not because anything is actually wrong. The Notify("relay unreachable, no action taken") line is about not making a new DEAD call on missing data, not a blanket promise: if the switch had already latched DEAD on a previous, reachable poll and Act() hadn't finished yet - still working through closeTries itself, say - an unreachable relay won't stop that retry.
The branch only refuses to escalate on silence it can't verify; it doesn't pause an action already in flight. Second, once DMS_STATE_DEAD fires, it latches: the state machine keeps reporting DEAD on every subsequent poll, action or not, until rearmBeats consecutive beats have advanced the sequence number - a single lucky poll right after a restart can't quietly clear an incident that genuinely happened. The shipped code's own comment calls this "a run of clean beats," which is a bit generous: m_cleanPolls only checks that seq moved, not that st.bad==0 too, so a run of beats that are fresh but still flagged DEGRADED can release the latch just as well as genuinely healthy ones. Worth knowing if you're relying on the rearm as proof the host is fully healthy rather than just beating again. Third, confirmPolls exists specifically so a single slow poll against a relay that's momentarily busy doesn't fire the action off one noisy sample.
Worst-case detection latency, from the last good beat to the guardian confirming DEAD:
T_detect ≤ k·P + G + C·Q
where k is InpMissBeats itself, P is the beat period, G is the grace seconds, C is InpConfirm itself, and Q is the guardian's own poll period. With this build's defaults - k=3, P=10, G=10, C=2 and a 5s poll - that works out to around 50 seconds worst case - and the real runs below landed inside that bound.
There's one more state in the enum I haven't explained yet: DMS_STATE_DISARMED state. A dead man's switch that can't be told "I know, leave it alone" isn't one you'd actually run in production - a planned platform restart, a broker maintenance window, or a deliberate strategy pause would otherwise walk straight into a false DEAD and, depending on the configured action, an unwanted flatten. The relay exposes this as two endpoints rather than putting the decision anywhere in the EA itself, on the theory that an operator reaching for a phone or a browser during an outage shouldn't need the MetaTrader terminal to be reachable at all:
set_disarm
def set_disarm(nid, minutes): with LOCK: n = NODES.setdefault(nid, new_node()) n["disarm_until"] = time.time() + minutes * 60 if minutes > 0 else 0.0 n["alerted"] = False save_state(force=True)
The 1 to 240 limit does not live in set_disarm() itself. It is applied where the request arrives, in the HTTP handler, before set_disarm() is called:
do_POST, the /disarm branch
if url.path == "/disarm": try: minutes = min(240, max(1, int(q.get("minutes", ["30"])[0]))) except ValueError: return self._send(400, {"error": "minutes"}) set_disarm(nid, minutes) return self._send(200, {"disarmed_minutes": minutes}) if url.path == "/arm": set_disarm(nid, 0) return self._send(200, {"armed": 1})
A missing value defaults to 30 minutes, anything below 1 becomes 1, anything above 240 becomes 240, and a non-numeric value is rejected with a 400. /arm passes 0, which is the one value set_disarm() treats as "clear the window".
A POST /disarm?id=host-1&minutes=30 sets a window, clamped server-side to between 1 and 240 minutes so a typo can't accidentally disarm the switch for a week; POST /arm?id=host-1 clears it early if the maintenance finishes sooner than planned. Back in Step() itself, st.armed coming back false takes priority over every other check - the state goes straight to DMS_STATE_DISARMED state, the dead-poll and clean-poll counters both reset, and the latch releases immediately via the same Release() call a normal recovery uses.
That ordering matters: if the window were checked after the age comparison instead of before it, a node that had already been silently approaching DEAD right as the disarm was requested could still fire once before the window took effect. Checking armed first closes that gap - but it also means a disarm request clears an already-confirmed DEAD, not just a pending one, since !st.armed is checked before the latch logic on every poll. That's intentional for maintenance, but it's also the mechanism's main operational risk surface: anyone who can reach /disarm with the token can silence a genuinely fired switch.
Acting on confirmed silence
What the guardian actually does once it's confirmed dead is a straight switch on one input, with alert-only as the honest default:
CGuardian::Act
//+------------------------------------------------------------------+ //| CGuardian::Act | //+------------------------------------------------------------------+ void CGuardian::Act(void) { if(m_dryRun) { m_actionDone=true; return; } //--- never touch an account other than the one the beat came from if(m_st.login!=0 && m_st.login!=AccountInfoInteger(ACCOUNT_LOGIN)) { Notify("login mismatch, alert only"); m_actionDone=true; return; } switch(m_cfg.action) { case DMS_ACTION_BREAKEVEN: ActBreakeven(); break; case DMS_ACTION_FLATTEN: ActFlatten(); break; default: m_actionDone=true; break; } }
The login check is there because the relay can in principle be shared by more than one node - if a beat ever shows up tagged with a login that doesn't match the terminal the guardian is running in, the safe move is to alert and do nothing, not flatten an account the guardian has no business touching. It only guards when a login is present, though: m_st.login!=0 has to be true for the mismatch check to run at all, so a status reply that comes back with login==0 - the relay's own default for a node it has no beat on file for - skips the check entirely rather than failing safe.
In practice that path only matters if known is also true with no login recorded, which the beat payload always sets, but it's a gap in the guard worth knowing about if you adapt this. ActFlatten() only ever closes positions carrying the configured magic number, and gives up cleanly after closeTries passes rather than looping forever against a broker that's rejecting the close:
CGuardian::ActFlatten
//+------------------------------------------------------------------+ //| CGuardian::ActFlatten | //+------------------------------------------------------------------+ void CGuardian::ActFlatten(void) { m_closeTries++; for(int i=PositionsTotal()-1; i>=0; i--) { ulong tk=PositionGetTicket(i); if(tk==0 || PositionGetInteger(POSITION_MAGIC)!=m_cfg.magic) continue; m_trade.SetTypeFillingBySymbol(PositionGetString(POSITION_SYMBOL)); if(!m_trade.PositionClose(tk)) PrintFormat("DMS: close #%I64u failed, retcode=%u",tk,m_trade.ResultRetcode()); } int left=CountPositions(); if(left==0) { m_actionDone=true; Notify("flatten complete"); } else if(m_closeTries>=m_cfg.closeTries) { m_actionDone=true; Notify(StringFormat("flatten gave up, %d positions left",left)); } }
Fault injection in the host EA
To get real timing data instead of guessing at the formula above, the host EA ships with a small, explicit fault-injection block - not a hidden debug flag, an actual input group you set before running the EA:
ApplyFault
//+------------------------------------------------------------------+ //| ApplyFault | //+------------------------------------------------------------------+ void ApplyFault(void) { if(InpFault==DMS_FAULT_NONE || g_faultFired) return; if(TimeLocal()-g_start<InpFaultAfterSec) return; g_faultFired=true; if(InpFault==DMS_FAULT_MUTE) { Print("Fault: beats muted, trading continues"); g_beat.Mute(true); } else if(InpFault==DMS_FAULT_HANG) { Print("Fault: blocking the timer thread"); for(int i=0; i<InpHangSec && !IsStopped(); i++) Sleep(1000); } }
Two different failure shapes, deliberately: muting only stops the beat call, so the EA's trading logic in OnTick() keeps running completely normally the whole time - this simulates a monitoring blind spot, not a frozen EA. Hanging blocks inside OnTimer() itself with a plain Sleep() loop, which simulates an EA that's genuinely stuck - nothing else on that timer handler runs either until the sleep loop finishes or the EA is removed.
Running it for real: two controlled faults, one demo account
I ran this on a MetaQuotes-Demo hedge account, host EA on EURUSD H1 and guardian on AUDUSD H1 (different charts so each gets its own timer, no fighting over one chart), relay running locally on the same machine via python relay.py --token <token> --port 8080 command. Guardian settings: beat period 10s, 3 missed beats before DEAD is even possible, 10s grace. The confirm-poll input (InpConfirm) was 1 for the mute run and 2 for the hang run.
| Fault | Fault onset logged | DEAD confirmed | Detection latency (onset to DEAD) | Recovery |
|---|---|---|---|---|
| Mute (beats silently withheld, trading continues) | 14:02:41.330 | 14:03:16.386, age 45.0s | 35.1s | confirmed clean on a later run |
| Timer-thread hang (90s blocking sleep) | 20:55:23.907 | 20:56:01.890, age 48.0s | 38.0s | 20:57:16.878, age 2.7s |
Both land comfortably inside the roughly 50-second worst case from the formula above. Here, detection latency is the wall-clock time from the fault-onset entry in the Experts log to the DEAD transition. This differs from Step() 's age value: age is the time since the last beat on the relay's clock, whereas detection latency also includes the already-elapsed portion of the current beat cycle. The mute case landed faster (35.1s) than the hang case (38.0s) simply because of where each fault happened to land inside that cycle, not because the two mechanisms behave differently at the state-machine level: from the guardian's side, both look identical, the relay's age crosses deadAt and stays there for confirmPolls in a row. That's exactly the point of decoupling detection from cause - the guardian doesn't need to know why the host went quiet, only that it did.
I also confirmed the dispatch logic itself rather than trusting the switch statement by inspection: with InpAction set to alert-only, a later DEAD transition on the same setup produced the Notify() line and no "flatten complete" line - the default: branch in Act() ran, not ActFlatten() itself. On the first mute run, with the action still at its shipped default of flatten, the same transition did produce "flatten complete" again, correctly, against zero open positions since the EMA-cross strategy hadn't opened one yet at that point in the run.
The 35.1s and 38.0s figures are each single runs, not averages over repeated trials, and I'd treat them as "landed where the formula says they should," not as a tight statistical characterization of this setup's typical latency - a handful of runs on one demo account, on one machine, is not a sample size sufficient to characterize the latency statistically. What they do establish is that the mechanism behaves the way Step() says it should: silence crosses the dead threshold, the confirm count gates a single noisy poll from firing early, and the latch holds until a run of advanced beats clears it, whatever their bad flags say. The guardian's own trace file for each run - DeadManSwitch\trace_host-1.csv - has every poll in between those two timestamps, which is what let me confirm the state only ever moved OK → LATE → DEAD in order, never skipping LATE, rather than taking the two endpoints on faith.
A real bug, caught by the switch itself
This is the part I'd normally be tempted to leave out, and the reason I'm not: partway through testing, I set InpAction on the guardian to alert-only, then later tried to turn the mute fault back off on the host by reopening its Properties dialog, setting InpFault back to None itself, and clicking OK. The guardian correctly stopped flattening. The host, however, stayed completely silent - no beats reached the relay for several hours afterward, confirmed by the relay's own console never once printing beating again in that window, even though the Experts log showed the host had genuinely restarted and InpFault genuinely read None in its Inputs tab.
The cause is sitting in plain sight once you put OnInit() next to the two globals it never touches:
CHeartbeatEmitter g_beat; // health emitter bool g_faultFired=false; // fault already applied
OnInit
//+------------------------------------------------------------------+ //| OnInit | //+------------------------------------------------------------------+ int OnInit() { if(InpFastMa>=InpSlowMa || InpRiskPct<=0.0 || InpBeatSec<1) { Print("Inputs: fast EMA must be below slow EMA, risk above 0, beat period 1 or more"); return(INIT_PARAMETERS_INCORRECT); } if(!g_beat.Init(InpRelayUrl,InpNodeId,InpToken,_Symbol,InpMagic,InpBeatSec, InpTimeoutMs,InpStaleSec,InpDropEvery)) return(INIT_PARAMETERS_INCORRECT); g_hFast=iMA(_Symbol,_Period,InpFastMa,0,MODE_EMA,PRICE_CLOSE); g_hSlow=iMA(_Symbol,_Period,InpSlowMa,0,MODE_EMA,PRICE_CLOSE); g_hAtr=iATR(_Symbol,_Period,InpAtrPeriod); if(g_hFast==INVALID_HANDLE || g_hSlow==INVALID_HANDLE || g_hAtr==INVALID_HANDLE) { Print("Indicator handle failed, err=",GetLastError()); return(INIT_FAILED); } g_trade.SetExpertMagicNumber(InpMagic); g_trade.SetDeviationInPoints(30); g_start=TimeLocal(); if(!EventSetTimer(InpBeatSec)) return(INIT_FAILED); //--- first beat goes out now, not one period from now g_beat.Beat(); return(INIT_SUCCEEDED); }
g_beat.Init() re-reads every input and resets the emitter's connection settings, but it stops short of touching m_mute - that flag isn't part of what Init() was written to manage, because under normal operation nothing ever sets it outside of a deliberate fault test. Nowhere in this function does g_faultFired get reset to false anywhere, and nowhere does it call g_beat.Mute(false) either. Changing an input through Properties and clicking OK triggers OnDeinit(REASON_PARAMETERS) followed immediately by a fresh OnInit() - but it does not unload the program. g_faultFired and the g_beat object both keep whatever state they already held across that cycle, because neither one is reconstructed; only a full remove-and-reattach actually tears the instance down.
ApplyFault() had already set g_faultFired=true and called g_beat.Mute(true) once, earlier in the session. A parameters-only restart leaves both of those exactly as they were - OnInit() never resets g_faultFired and never calls g_beat.Mute(false) - so the emitter kept returning early out of Beat() on the very first line, regardless of what InpFault said. Flipping the dropdown back to None changed nothing that mattered, because the code path that would have unmuted it was never there in the first place.
The fix in the field was a full remove-and-reattach rather than a Properties edit, which does tear the instance down and re-run every global initializer - the relay logged beating again within the next beat cycle, and the guardian confirmed recovery a few seconds later. The correct code fix is to make OnInit() idempotent with respect to fault state - explicitly reset g_faultFired=false and call g_beat.Mute(false) at the top of OnInit() - so a genuine parameter change always starts from a clean slate instead of inheriting whatever the previous input values left behind. I'm leaving the shipped code as tested above rather than quietly patching it after the fact, because the failure mode itself - and the fact that the dead man's switch caught it instead of the operator noticing on their own - is a more honest demonstration of what this kind of tool is actually for than a clean run would have been.
If you're adapting this for your own EA: any global object or flag that fault-injection logic touches needs an explicit reset at the top of OnInit() itself. MQL5's parameters-only restart is not a fresh process - don't assume it is.
Giving it eyes: the on-chart status indicator
Journal lines and relay console output are fine while you're actively watching a terminal, but they're not something you'd glance at from across the room. DMS_StatusView is a small sub-window indicator that reads the same GlobalVariables the guardian publishes on every poll and draws them as a line chart plus a text label, so the state of the switch is visible at a glance on the same chart the guardian is running on, without the indicator talking to the relay itself at all.
The guardian writes these after every Step() call, prefixed per node id so more than one switch can run in the same terminal without colliding:
CGuardian::Publish
//+------------------------------------------------------------------+ //| CGuardian::Publish | //+------------------------------------------------------------------+ void CGuardian::Publish(void) { if(m_dryRun) return; Put("state",(double)m_state); Put("age",m_st.age); Put("bad",(double)m_st.bad); Put("seq",(double)m_st.seq); Put("dead_polls",(double)m_deadPolls); Put("relay_fails",(double)m_relayFails); Put("latched",m_latched ? 1.0 : 0.0); Put("stamp",(double)TimeLocal()); }
GlobalVariables are the right tool here specifically because they're process-local to the terminal and survive a chart reload - an indicator dropped onto the guardian's own chart, or any other chart in the same terminal, picks them straight up with GlobalVariableGet() alone, no HTTP request and no extra load on the relay. The trade-off is the one you'd expect: this only works within a single terminal. A second terminal, or a VPS running the guardian headless, needs its own view - which is exactly what the relay's /status endpoint and the Python console are for.
The indicator's own timer just repaints on a one-second cadence and color-codes the label by state - green for OK, orange for LATE or DEGRADED, red for DEAD, gray for UNKNOWN or DISARMED or when no guardian is running in that terminal at all:
Paint
//+------------------------------------------------------------------+ //| Paint | //+------------------------------------------------------------------+ void Paint(void) { if(g_total<1) return; int idx=g_total-1; g_bufLate[idx]=1.5*(double)InpBeatSec; g_bufDead[idx]=(double)(InpMissBeats*InpBeatSec+InpGraceSec); if(!GlobalVariableCheck(g_prefix+"state")) { g_bufAge[idx]=EMPTY_VALUE; Say(InpNodeId+": no guardian running in this terminal",clrGray); return; } double age=GlobalVariableGet(g_prefix+"age"); ENUM_DMS_STATE st=(ENUM_DMS_STATE)(int)GlobalVariableGet(g_prefix+"state"); int bad=(int)GlobalVariableGet(g_prefix+"bad"); g_bufAge[idx]=(age>=0.0) ? age : EMPTY_VALUE; color clr=clrLimeGreen; if(st==DMS_STATE_LATE || st==DMS_STATE_DEGRADED) clr=clrOrange; else if(st==DMS_STATE_DEAD) clr=clrRed; else if(st==DMS_STATE_UNKNOWN || st==DMS_STATE_DISARMED) clr=clrGray; Say(StringFormat("%s: %s | age %.1fs | flags %s | seq %.0f",InpNodeId,DmsStateName(st), age,DmsBadText(bad),GlobalVariableGet(g_prefix+"seq")),clr); }
The two extra buffers, g_bufLate and g_bufDead together, plot the LATE and DEAD thresholds as flat reference lines next to the live age curve - set those inputs to match the guardian and the chart becomes a direct visual of how close the age line sits to tripping the switch.
Replaying a trace without touching a live account
Every poll the guardian makes gets appended to a trace file, not just the ones that cause a transition - CGuardian::Trace() writes one row per Poll() call to DeadManSwitch\trace_<id>.csv file, independent of whatever the Journal shows. That trace is what made it possible to re-run the state machine against a recorded sequence of relay answers without needing a live demo account at all, which matters once you're trying to check a change to the guardian's own thresholds without waiting through another real silence.
CGuardian::Trace
//+------------------------------------------------------------------+ //| CGuardian::Trace | //+------------------------------------------------------------------+ void CGuardian::Trace(const SDmsStatus &st) { if(m_dryRun) return; int h=DmsOpenAppend(m_traceFile,"time,reachable,known,armed,age,bad,seq,login"); if(h==INVALID_HANDLE) return; FileWrite(h,TimeToString(TimeLocal(),TIME_DATE|TIME_SECONDS),st.reachable ? 1 : 0, st.known ? 1 : 0,st.armed ? 1 : 0,DoubleToString(st.age,1),st.bad,st.seq,st.login); FileClose(h); }
It writes the raw SDmsStatus the guardian just fetched, before Step() does anything with it - which is also exactly the shape DMS_Replay expects to read back, column for column.
DMS_Replay is a script that reads that CSV back row by row and drives a second CGuardian instance through it in dry-run mode, where Act() and Notify() never touch orders or the Alert popup:
OnStart
//+------------------------------------------------------------------+ //| OnStart | //+------------------------------------------------------------------+ void OnStart() { int h=FileOpen(InpFile,FILE_READ|FILE_CSV|FILE_ANSI|FILE_SHARE_READ,','); if(h==INVALID_HANDLE) { PrintFormat("Replay: cannot open %s, err=%d",InpFile,GetLastError()); return; } SDmsGuardianCfg cfg; cfg.url="http://replay"; cfg.id=InpNodeId; cfg.token=""; cfg.magic=0; cfg.action=DMS_ACTION_ALERT_ONLY; cfg.beatPeriod=InpBeatSec; cfg.missBeats=InpMissBeats; cfg.graceSec=InpGraceSec; cfg.confirmPolls=InpConfirm; cfg.rearmBeats=InpRearmBeats; cfg.closeTries=1; cfg.timeoutMs=1000; cfg.padPoints=0; cfg.push=false; CGuardian guard; guard.SetDryRun(true); if(!guard.Init(cfg)) { FileClose(h); return; } //--- skip the header row for(int i=0; i<8; i++) FileReadString(h); int rows=0; while(!FileIsEnding(h)) { string ts=FileReadString(h); if(ts=="" && FileIsEnding(h)) break; SDmsStatus st; ZeroMemory(st); st.reachable=(FileReadString(h)=="1"); st.known=(FileReadString(h)=="1"); st.armed=(FileReadString(h)=="1"); st.age=StringToDouble(FileReadString(h)); st.bad=(int)StringToInteger(FileReadString(h)); st.seq=(ulong)StringToInteger(FileReadString(h)); st.login=(long)StringToInteger(FileReadString(h)); rows++; ulong before=guard.Transitions(); guard.Step(st); if(guard.Transitions()!=before) PrintFormat("Replay: row %d at %s",rows,ts); } FileClose(h); PrintFormat("Replay: %d polls, %I64u transitions, DEAD entered %I64u times, final state %s", rows,guard.Transitions(),guard.DeadEntries(),DmsStateName(guard.State())); }
Notice the configuration it builds has nothing in it that reaches the network - cfg.url is a placeholder string the dry-run instance never calls WebRequest at all, because Fetch() is never invoked in this path; the trace rows are fed straight into Step() directly. That's deliberate separation: the thing being tested is the state machine's logic against a fixed, reproducible sequence of inputs, not the network path, which already has its own coverage from the live runs above. I used this to replay the whole captured trace, 8,743 polls, through the same state machine. With InpConfirm set to 2 the replay reports 17 transitions, DEAD entered 5 times and a final state of OK; with it set to 1, 15 transitions, still 5 DEAD entries and a final state of OK. The mute run is visible in the raw rows (columns: time, reachable, known, armed, age, bad, seq, login):
2026.10.04 14:03:06,1,1,1,35.0,0,104,112373670 2026.10.04 14:03:11,1,1,1,40.0,0,104,112373670 2026.10.04 14:03:16,1,1,1,45.0,0,104,112373670 2026.10.04 14:03:21,1,1,1,50.0,0,104,112373670 2026.10.04 14:03:26,1,1,1,55.0,0,104,112373670
Replayed with InpConfirm at 1, the guardian goes OK to LATE at 14:02:51 (age 20.1s) and LATE to DEAD at 14:03:16 (age 45.0s), which matches the mute run's table row. With 2 it reaches DEAD one poll later, at 14:03:21 (age 50.0s). The hang run replays the same way: with 2, OK to LATE at 20:55:31 (age 18.0s), LATE to DEAD at 20:56:01 (age 48.0s), then back to OK at 20:57:16 (age 2.7s); with 1, DEAD arrives at 20:55:56 (age 43.0s).
Setting it up: the allowlist, the relay, and two charts
None of the above does anything until WebRequest is actually allowed to leave the terminal, and this is the step that trips people up first. MetaTrader blocks every outbound WebRequest call by default - Tools > Options > Expert Advisors > "Allow WebRequest for listed URL," and the entry has to be the bare origin the relay is listening on, http://127.0.0.1:8080 exactly, not a path underneath it. Get this wrong and every beat and every poll fails with ERR_WEBREQUEST_INVALID_ADDRESS before a single byte leaves the terminal - that error is a configuration problem, not a network one, and no amount of restarting the relay fixes it.
With the allowlist set, the relay itself needs nothing beyond a standard Python install:
python relay.py --token <shared-secret> --port 8080
and the host and guardian EAs each need their own chart. MetaTrader only allows one EA per chart, so the host and guardian can't share one - and a freshly opened chart on a symbol and timeframe that's already open elsewhere in the terminal doesn't create a second window, it just refocuses the existing one, which looks like nothing happened. File > New Chart on a symbol and timeframe combination that isn't already open anywhere else in the terminal is the reliable way to get a genuinely separate chart for each EA, which is why the test runs above have the host on EURUSD H1 and the guardian on AUDUSD H1 rather than two instances of the same symbol.
Reproducing these runs
Everything above came from one setup, run on one machine. The table below is what another reader would need to match it, rather than re-derive it from scattered mentions of inputs across the article:
| Item | Value used in this article |
|---|---|
| Terminal | MetaTrader 5, MetaQuotes-Demo hedge account |
| Test type | Live forward run on the demo account, not the Strategy Tester, so no tick generation mode or modelled spread applies. The tester cannot run WebRequest, which is why the beat call returns early there. |
| Account | Demo, retail hedging, leverage 1:100, deposit currency USD, balance 100,000.00 USD with no open positions |
| Spread | Floating on EURUSD. No spread value was recorded during the runs, and none could have been live: see the market state row |
| Commission | None listed in the EURUSD symbol specification on this server |
| Market state | The trace timestamps fall on Sunday 4 October. The server's EURUSD specification has no quote or trade session on Sunday, so there were no live quotes during either run. The beat does not depend on ticks, so the timings stand, but the stale-quote flag was not exercised |
| Host EA chart | EURUSD, H1 |
| Guardian EA chart | AUDUSD, H1 (separate chart, same terminal) |
| Relay | relay.py, standard library only, run locally via python relay.py --token <token> --port 8080 |
| InpBeatSec (host beat period) | 10s |
| InpMissBeats | 3 |
| InpGraceSec | 10s |
| InpConfirm (confirm polls) | 1 for the mute run, 2 for the hang run |
| InpRearmBeats | 3 |
| Guardian poll period | 5s |
| Fault 1 | mute (beats silently withheld, host EA otherwise running normally) |
| Fault 2 | timer-thread hang, 90s blocking sleep |
Conclusion
What's proven here, on real data from a demo account: the state machine correctly separates "relay unreachable" from "host confirmed dead," the latch genuinely holds until a run of advanced beats releases it, regardless of bad flags, the alert-only and flatten action paths both dispatch correctly off the same switch statement, and detection latency for two different fault mechanisms - a silent mute and a full timer-thread hang - landed at 35.1s and 38.0s respectively, both inside the roughly 50-second worst case the formula predicts for two confirm polls.
What isn't covered yet: I didn't test the relay going down while the host kept beating normally, a hard kill of the host's terminal process, a flatten firing against a real open position rather than a flat book, AutoTrading disabled at the terminal level (which likely breaks the action path the same way it breaks the host), or a network split where the host can reach the relay but the guardian can't, or vice versa. Those are the next runs on my list, and I'd treat any claim about this switch's behavior under those specific conditions as unverified until I've actually produced the logs for them.
If you're going to run this on an account that actually trades, the restart bug above is the one lesson worth carrying over regardless of whether you use this exact code: anything fault-injection logic sets on a global object or a plain global flag needs an explicit reset at the top of OnInit() again, because MetaTrader's parameters-only restart is not the fresh process it looks like. Test that reset path the same way the state machine itself got tested here - by forcing the fault, forcing the "fix," and checking the relay's own console for proof the beat actually went through, rather than trusting that a dropdown reading None means the EA agrees with it.
Files in the archive
MQL5.zip unpacks straight into the terminal's data folder, and every file lands in the path it needs - unzip it over the MQL5 folder and nothing has to be moved by hand.
| Path | What it is |
|---|---|
| MQL5\Experts\DeadManSwitch\DMS_Host_EA.mq5 | Host EA - runs CHeartbeatEmitter, sends a beat to the relay every InpBeatSec seconds |
| MQL5\Experts\DeadManSwitch\DMS_Guardian_EA.mq5 | Guardian EA - runs CGuardian, polls the relay and drives the state machine |
| MQL5\Include\DeadManSwitch\DmsHeartbeat.mqh | CHeartbeatEmitter class - collects vitals and posts the JSON beat |
| MQL5\Include\DeadManSwitch\DmsGuardian.mqh | CGuardian class - the state machine, actions, and trace logging |
| MQL5\Include\DeadManSwitch\DmsProtocol.mqh | Shared structs, JSON encode/decode, and the WebRequest wrapper both EAs use |
| MQL5\Indicators\DeadManSwitch\DMS_StatusView.mq5 | On-chart indicator - reads the guardian's GlobalVariables, no network calls of its own |
| MQL5\Scripts\DeadManSwitch\DMS_Replay.mq5 | Replay script - re-runs a recorded trace CSV through a dry-run guardian instance |
| MQL5\Files\DeadManSwitch\Python\relay.py | The relay itself - standard library only, run as python relay.py --token <token> --port 8080 |
Warning: All rights to these materials are reserved by MetaQuotes Ltd. Copying or reprinting of these materials in whole or in part is prohibited.
This article was written by a user of the site and reflects their personal views. MetaQuotes Ltd is not responsible for the accuracy of the information presented, nor for any consequences resulting from the use of the solutions, strategies or recommendations described.