The biggest trap in MQL5 is that WebRequest is synchronous. If you fire an HTTP request and your monitoring server takes 5 seconds to respond, your Expert Advisor freezes for 5 seconds. If a critical price level breaks during that freeze, you miss the trade.
To build this safely in MT5, you must decouple the heartbeat from the OnTick event by placing it in OnTimer, and you must enforce a mercilessly short timeout so the EA immediately drops a stalled connection and goes back to watching the market.
Here is the production-ready MQL5 implementation.
Dead-Man Heartbeats: Knowing an Automated System Is Still Alive
Re: Dead-Man Heartbeats: Knowing an Automated System Is Still Alive
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
Re: Dead-Man Heartbeats: Knowing an Automated System Is Still Alive
1. The MQL5 Emitter Code
This code gathers telemetry, constructs a lightweight JSON payload manually (avoiding heavy external JSON libraries), and dispatches it with a strict 500ms timeout.
This code gathers telemetry, constructs a lightweight JSON payload manually (avoiding heavy external JSON libraries), and dispatches it with a strict 500ms timeout.
Code: Select all
input string BotID = "XAGUSD_M5_AntiMartingale_01";
input string MonitorURL = "https://your-gcp-monitor.com/heartbeat";
int OnInit()
{
// Fire the OnTimer event every 60 seconds
EventSetTimer(60);
return(INIT_SUCCEEDED);
}
void OnDeinit(const int reason)
{
// Clean up the timer when the EA is removed
EventKillTimer();
}
void OnTick()
{
// Your core trading logic remains unblocked here
}
void OnTimer()
{
SendHeartbeat();
}
void SendHeartbeat()
{
// 1. Gather Telemetry
double equity = AccountInfoDouble(ACCOUNT_EQUITY);
int openPositions = PositionsTotal();
// 2. Format JSON payload
string jsonPayload = StringFormat(
"{\"bot_id\":\"%s\",\"equity\":%.2f,\"open_positions\":%d}",
BotID, equity, openPositions
);
// 3. Prepare data arrays for WebRequest
char postData[];
char resultData[];
string resultHeaders;
// Convert string to char array (UTF-8)
StringToCharArray(jsonPayload, postData, 0, WHOLE_ARRAY, CP_UTF8);
// CRITICAL MQL5 QUIRK: StringToCharArray includes a null terminator (\0) at the end.
// We must subtract 1 from the array size, otherwise the FastAPI backend
// might reject the JSON payload due to the trailing null character.
int dataSize = ArraySize(postData) - 1;
// 4. Dispatch WebRequest with a strict 500ms timeout
ResetLastError();
int res = WebRequest(
"POST",
MonitorURL,
"Content-Type: application/json\r\n",
500, // 500ms timeout to prevent thread blocking
postData,
dataSize,
resultData,
resultHeaders
);
// 5. Handle silent failures locally
if(res != 200)
{
int err = GetLastError();
// Log locally to the Experts journal, but do not interrupt trading
PrintFormat("Heartbeat dispatch failed. HTTP: %d, MT5 Error: %d", res, err);
}
}Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
Re: Dead-Man Heartbeats: Knowing an Automated System Is Still Alive
2. The Critical MT5 Configuration Step
By default, MetaTrader 5 blocks all outbound HTTP requests as a security measure. If you deploy the code above without configuring the terminal, GetLastError() will return 4014 (ERR_FUNCTION_NOT_ALLOWED) and the heartbeat will silently fail.
To authorize the emitter:
1.) Open MT5 and navigate to Tools > Options > Expert Advisors.
2.) Check the box for "Allow WebRequest for listed URL".
3.) Add your exact GCP monitor endpoint (e.g., [https://your-gcp-monitor.com](https://your-gcp-monitor.com)) to the list.
4.) Click OK.
If you are running this on a headless VPS, you must ensure this setting is saved in your terminal configuration or applied manually when setting up the MT5 instance.
By default, MetaTrader 5 blocks all outbound HTTP requests as a security measure. If you deploy the code above without configuring the terminal, GetLastError() will return 4014 (ERR_FUNCTION_NOT_ALLOWED) and the heartbeat will silently fail.
To authorize the emitter:
1.) Open MT5 and navigate to Tools > Options > Expert Advisors.
2.) Check the box for "Allow WebRequest for listed URL".
3.) Add your exact GCP monitor endpoint (e.g., [https://your-gcp-monitor.com](https://your-gcp-monitor.com)) to the list.
4.) Click OK.
If you are running this on a headless VPS, you must ensure this setting is saved in your terminal configuration or applied manually when setting up the MT5 instance.
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
Re: Dead-Man Heartbeats: Knowing an Automated System Is Still Alive
Securing the endpoint requires a defense-in-depth approach: FastAPI handles the cryptographic verification of the key, while Cloudflare sits at the edge to absorb brute-force attacks and rate-limit spam before it ever reaches your GCP server.
Here is the exact implementation to lock down your monitoring node.
Here is the exact implementation to lock down your monitoring node.
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
Re: Dead-Man Heartbeats: Knowing an Automated System Is Still Alive
1. The FastAPI Inner Defense (Dependency Injection)
FastAPI has a built-in APIKeyHeader utility that seamlessly enforces header validation. By injecting this as a dependency, any request missing the correct key is instantly rejected with a 401 Unauthorized before your core logic even executes.
FastAPI has a built-in APIKeyHeader utility that seamlessly enforces header validation. By injecting this as a dependency, any request missing the correct key is instantly rejected with a 401 Unauthorized before your core logic even executes.
Code: Select all
from fastapi import FastAPI, Depends, HTTPException, Security, status
from fastapi.security import APIKeyHeader
from pydantic import BaseModel
app = FastAPI()
# Define your secure key (in production, load this from an .env file)
SECRET_API_KEY = "x7f9a2...<use_a_long_random_string>...b3c4d5"
# Define the expected header name
api_key_header = APIKeyHeader(name="X-API-Key", auto_error=True)
def verify_api_key(api_key: str = Security(api_key_header)):
if api_key != SECRET_API_KEY:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Forbidden: Invalid API Key"
)
return api_key
class HeartbeatPayload(BaseModel):
bot_id: str
equity: float
open_positions: int
# Inject the security dependency into the endpoint
@app.post("/heartbeat", dependencies=[Depends(verify_api_key)])
async def receive_heartbeat(payload: HeartbeatPayload):
# If the code reaches here, the API key is valid.
# Update your bot's timestamp in the dictionary/Redis cache.
return {"status": "acknowledged"}Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
Re: Dead-Man Heartbeats: Knowing an Automated System Is Still Alive
2. Updating the MQL5 Emitter
To pass Cloudflare and FastAPI, your MetaTrader 5 bot must now inject the API key into its HTTP headers. Update the WebRequest call in your MQL5 code by concatenating the new header onto the Content-Type:
To pass Cloudflare and FastAPI, your MetaTrader 5 bot must now inject the API key into its HTTP headers. Update the WebRequest call in your MQL5 code by concatenating the new header onto the Content-Type:
Code: Select all
// Add your secret key
string apiKey = "x7f9a2...<use_a_long_random_string>...b3c4d5";
// Construct the headers string with carriage returns
string requestHeaders = "Content-Type: application/json\r\n" +
"X-API-Key: " + apiKey + "\r\n";
// Dispatch WebRequest
int res = WebRequest(
"POST",
MonitorURL,
requestHeaders, // Insert the authenticated headers here
500,
postData,
dataSize,
resultData,
resultHeaders
);Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
Re: Dead-Man Heartbeats: Knowing an Automated System Is Still Alive
3. The Cloudflare Outer Defense (WAF & Rate Limiting)
If an attacker discovers your endpoint, they could spam it with random API keys. FastAPI would reject them, but parsing thousands of 401 requests still consumes GCP compute. Cloudflare stops this at the edge network.
Step A: Cloudflare WAF Custom Rule (Block invalid formats)
Force Cloudflare to drop requests that don't even have the header, saving your server from processing them.
Go to Security > WAF > Custom rules.
Create a new rule.
Expression: (http.request.uri.path eq "/heartbeat" and not http.request.headers["x-api-key"] matches ".*")
Action: Block.
Step B: Rate Limiting Rule (Stop Spam)
Since your bot sends a heartbeat every 60 seconds, a rate limit of 5 requests per minute provides enough buffer for network retries while instantly blocking a script kiddie.
Go to Security > WAF > Rate limiting rules.
Create a new rule.
Field: URI Path equals /heartbeat.
When rate exceeds: 5 requests per 1 minute.
Then take action: Block for 1 hour.
With this architecture, malicious traffic hits a brick wall at Cloudflare's edge servers, while your legitimate, encrypted MT5 pings pass straight through to update your FastAPI monitor.
If an attacker discovers your endpoint, they could spam it with random API keys. FastAPI would reject them, but parsing thousands of 401 requests still consumes GCP compute. Cloudflare stops this at the edge network.
Step A: Cloudflare WAF Custom Rule (Block invalid formats)
Force Cloudflare to drop requests that don't even have the header, saving your server from processing them.
Go to Security > WAF > Custom rules.
Create a new rule.
Expression: (http.request.uri.path eq "/heartbeat" and not http.request.headers["x-api-key"] matches ".*")
Action: Block.
Step B: Rate Limiting Rule (Stop Spam)
Since your bot sends a heartbeat every 60 seconds, a rate limit of 5 requests per minute provides enough buffer for network retries while instantly blocking a script kiddie.
Go to Security > WAF > Rate limiting rules.
Create a new rule.
Field: URI Path equals /heartbeat.
When rate exceeds: 5 requests per 1 minute.
Then take action: Block for 1 hour.
With this architecture, malicious traffic hits a brick wall at Cloudflare's edge servers, while your legitimate, encrypted MT5 pings pass straight through to update your FastAPI monitor.
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.