In the high-stakes world of automated algorithmic trading, system crashes are frustrating. But there is a failure scenario that is exponentially more dangerous: the Silent Terminal Freeze.
Unlike an outright operating system crash or server reboot (which triggers standard uptime monitors), a silent freeze occurs when the MetaTrader 4 or MetaTrader 5 process appears completely normal inside Windows Task Manager, yet the underlying Expert Advisor thread is completely locked.
Whether caused by a deadlocked C++ DLL import, an unhandled zero-divide exception inside an indicator loop, a gradual memory leak, or a broken TCP socket that failed to trigger a reconnect routine, the result is catastrophic:
- Your trading algorithm stops receiving incoming price ticks.
- Dynamic trailing stops freeze in place.
- Risk management circuit breakers fail to trigger.
- You only discover the disaster hours later when you check your smartphone and find an unhedged position in massive drawdown!
To run high-concurrency automated bots with institutional peace of mind, professional algorithmic traders in Pakistan implement an External Heartbeat Watchdog.
In this quantitative systems guide, we construct an end-to-end monitoring pipeline: programming an MQL5 active heartbeat generator, writing an independent PowerShell/Python watchdog service, and configuring automated process recovery with real-time Telegram mobile alerts.
π The Architecture of an Active Heartbeat Watchdog
Passive monitors (like checking whether terminal64.exe exists in the process table) are useless because a hung process still exists.
An Active Heartbeat Watchdog requires the Expert Advisor to continually prove that its execution loop is healthy:
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β MetaTrader 5 Trading Instance β
β β
β [MQL5 Expert Advisor OnTick() / OnTimer()] β
β β β
β Writes epoch β Overwrites C:\MT5_Data\heartbeat.txt β
β timestamp β every 30 seconds β
βββββββββββββββββΌβββββββββββββββββββββββββββββββββββββββββ
βΌ
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Independent Watchdog Service (Python / PS) β
β β
β β’ Reads heartbeat.txt every 60 seconds β
β β’ If (Current Time - File Time) > 90 seconds: β
β 1. Sends Urgent Telegram Alert to Trader's Phone β
β 2. Force-terminates hung terminal64.exe process β
β 3. Relaunches MetaTrader 5 in portable mode β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
If the EA freezes, crashes, or loses connection to the market feed, it stops updating the timestamp file. The watchdog detects the stale heartbeat within 90 seconds and executes automated recovery!
π οΈ Step 1: Programming the MQL5 Heartbeat Generator
Inside your Expert Advisor, add a lightweight heartbeat function triggered inside OnTimer() or OnTick():
// MQL5 Active Heartbeat Generator
void EmitHeartbeat()
{
static datetime lastHeartbeat = 0;
datetime now = TimeLocal();
// Emit heartbeat at most once every 30 seconds
if (now - lastHeartbeat >= 30)
{
// Check broker connection health
bool isConnected = (bool)TerminalInfoInteger(TERMINAL_CONNECTED);
// Write status and current epoch timestamp to shared file
int fileHandle = FileOpen("heartbeat.txt", FILE_WRITE | FILE_TXT | FILE_COMMON);
if (fileHandle != INVALID_HANDLE)
{
string payload = StringFormat("%d|%s", (int)now, isConnected ? "CONNECTED" : "DISCONNECTED");
FileWriteString(fileHandle, payload);
FileClose(fileHandle);
lastHeartbeat = now;
}
}
}
Notice the use of FILE_COMMONβthis saves the file into MetaTraderβs shared common folder (C:\Users\Administrator\AppData\Roaming\MetaQuotes\Terminal\Common\Files), making it easily accessible to external scripts.
π Step 2: Writing the Python Watchdog Service
This lightweight Python script runs in the background of your Windows Server or Linux VPS, monitoring the heartbeat file, enforcing memory ceiling thresholds, and alerting you via Telegram:
import os
import time
import subprocess
import requests
# CONFIGURATION
COMMON_PATH = os.path.expandvars(r"%APPDATA%\MetaQuotes\Terminal\Common\Files\heartbeat.txt")
TERMINAL_EXE = r"C:\Program Files\MetaTrader 5\terminal64.exe"
MAX_STALE_SECONDS = 90
MAX_RAM_MB = 1800 # Kill process if memory leak exceeds 1.8 GB
TELEGRAM_BOT_TOKEN = "YOUR_BOT_TOKEN_HERE"
TELEGRAM_CHAT_ID = "YOUR_CHAT_ID_HERE"
def send_telegram(message):
try:
url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage"
requests.post(url, json={"chat_id": TELEGRAM_CHAT_ID, "text": message}, timeout=5)
except Exception as e:
print(f"Telegram failed: {e}")
def restart_metatrader():
send_telegram("π¨ CRITICAL ALERT: MetaTrader 5 freeze detected! Terminating and relaunching...")
# Force-kill hung terminal process
subprocess.run(["taskkill", "/F", "/IM", "terminal64.exe"], capture_output=True)
time.sleep(3)
# Relaunch in background
subprocess.Popen([TERMINAL_EXE, "/portable"])
send_telegram("β
MetaTrader 5 successfully recovered and relaunched!")
def monitor_loop():
print("Watchdog daemon active. Monitoring MT5 heartbeat...")
while True:
try:
if os.path.exists(COMMON_PATH):
with open(COMMON_PATH, "r") as f:
content = f.read().strip()
parts = content.split("|")
last_epoch = int(parts[0])
status = parts[1]
elapsed = time.time() - last_epoch
if elapsed > MAX_STALE_SECONDS:
print(f"Heartbeat stale! {elapsed:.0f}s elapsed.")
restart_metatrader()
elif status == "DISCONNECTED":
send_telegram("β οΈ WARNING: EA reports broker connection lost!")
else:
print("Heartbeat file not found.")
except Exception as e:
print(f"Error in watchdog: {e}")
time.sleep(30)
if __name__ == "__main__":
monitor_loop()
β‘ Step 3: Running the Watchdog as an Uninterruptible Windows Service
To ensure your watchdog runs continuously even after server reboots:
- Download NSSM (Non-Sucking Service Manager).
- In PowerShell as Administrator:
nssm install ForexWatchdog "C:\Python312\python.exe" "C:\ForexTools\watchdog.py" nssm set ForexWatchdog AppRotateFiles 1 nssm start ForexWatchdog
Now, your watchdog runs as a native Windows background service, starting automatically on server boot without requiring anyone to log into Remote Desktop!
π Enterprise Cloud Infrastructure for Automated Trading
Building high-reliability automated trading architectures requires carrier-grade server stability:
- Deploy your trading instances on Nextgen Cloud VPS in Pakistan featuring dedicated high-clock CPU cores, 100% NVMe storage, and pre-activated Windows Server environments.
- For quantitative hedge funds, multi-account money managers, and proprietary trading desks requiring dedicated bare-metal hardware and direct cross-connects to London LD4 and New York NY4 liquidity pools, scale on Nextgen enterprise Dedicated Servers in Pakistan and international Dedicated Servers.
π Related Forex, Trading VPS & Server Infrastructure Guides
- Forex Trailing Stop Bot VPS Optimization Guide β Lock in profits with sub-millisecond execution.
- Forex EA Slippage & Spread Filter Optimization on VPS β Protect against rollover spread widening.
- Forex VPS: Windows Server 2025 vs Linux Wine MT5 Comparison β Optimize memory density and execution latency.
Deploy an Ultra-Low-Latency Forex VPS Today
Protect your algorithmic trading capital from silent freezes and network drops. Nextgen provides high-performance Windows and Linux Cloud VPS optimized for MetaTrader 4, MetaTrader 5, and institutional algorithmic trading robots.
