Why MT5 CalendarValueHistory() Fails Prop-Firm News Rules (and How to Build a Fail-Closed Gate)
Automated strategies on funded prop-firm accounts (FTMO, FundingPips, The5ers) frequently fail news-restriction rules because of a quiet MetaTrader 5 trap: trusting CalendarValueHistory() and MqlCalendarValue structs dir
Automated strategies on funded prop-firm accounts (FTMO, FundingPips, The5ers) frequently fail news-restriction rules because of a quiet MetaTrader 5 trap: trusting CalendarValueHistory() and MqlCalendarValue structs directly on a live trading server.
On paper, polling the native MQL5 calendar before calling OrderSend() looks straightforward. On real prop-firm white-label servers, it breaks in three specific ways.
1. Three Ways CalendarValueHistory() Fails on Live Prop Servers
A. The Silent Zero-Event Fail-Open Bug
Many prop-firm and offshore MT5 servers disable or strip the MetaQuotes economic calendar feed on trade nodes. When your EA queries upcoming events, CalendarValueHistory() often returns 0 records while GetLastError() still reports 0:
MqlCalendarValue values[];
datetime from = TimeTradeServer() - 300;
datetime to = TimeTradeServer() + 300;
int count = CalendarValueHistory(values, from, to, NULL, "USD");
// Trap: on stripped broker servers, count == 0 and GetLastError() == 0.
// Naive EAs treat 0 events as "no news scheduled" and trade straight into CPI.
Unless you explicitly distinguish "calm calendar day" from "calendar feed disabled on this broker server," a standard news filter fails open at the worst possible moment.
B. TimeTradeServer() vs. Prop-Firm DST Mismatches
During the two-week US/EU daylight-saving transition in March and October, broker server clocks (GMT+2 / GMT+3) and prop-firm compliance clocks (CE(S)T or America/New_York) temporarily shift relative to hardcoded session offsets. A 60-second clock mismatch turns a T-5m pre-news cutoff into an instant rule breach.
C. Static Timestamps Ignore Post-Release Microstructure
Even when CalendarValueHistory() returns a valid timestamp, a calendar schedule only tells you when CPI or NFP drops. It has zero visibility into:
- First-print
Actual vs. Forecastsurprise magnitude (standardized sigma shock). - Two-way post-release spread whipsaws that outlast a fixed 2-minute or 5-minute timer.
- Conflicting simultaneous releases across base and quote legs (for example, US data colliding with CAD jobs on
USDCAD). - Closed-source third-party
.ex5EAs where you cannot editOnTick(), or external LLM agents running outside MetaTrader 5.
2. Decoupling the Gate: Single-Chart Hub + GlobalVariableTemp RAM Bus
If you run 6 to 10 charts on a VPS, letting every chart fire independent WebRequest() calls wastes rate limits, blocks chart threads on network timeouts, and duplicates broker-suffix parsing (EURUSD.pro, XAUUSDm, mEURUSD, GOLD).
A cleaner pattern separates external polling from chart execution:
-
One Master Hub EA on a single chart runs
EventSetTimer(15), polls a compact (~250-byte per pair) external macro/risk state endpoint overWebRequest(), normalizes broker symbols to canonical 6-letter pairs, and writes temporary RAM flags viaGlobalVariableTemp(). -
Trading EAs on every other chart read those RAM flags in ~0.001 ms inside
OnTick()with zero network calls and zero DLL imports.
Why GlobalVariableTemp() instead of plain GlobalVariableSet()? Standard MT5 global variables flush to gvariables.dat and persist on disk for 4 weeks. If your VPS reboots mid-session while a flag says 1.0 (safe), a persistent variable wakes up lying. GlobalVariableTemp() lives strictly in volatile RAM and vanishes on restart, while a dedicated UTC timestamp (FNR_HEARTBEAT_TS) catches stalled timers inside a running terminal.
Fail-Closed MQL5 Reader Guard (Backtest + Stale-Heartbeat Safe)
Here is the minimal fail-closed check any custom .mq5 EA can run before opening a position (taken from our open reference implementation, ForexNewsRadar_PropShield.mq5):
static const string CANONICAL_PAIRS[18] = {
"EURUSD","XAUUSD","GBPUSD","USDJPY","XAGUSD","EURJPY",
"GBPJPY","AUDUSD","USDCAD","USDCHF","NZDUSD","EURAUD",
"GBPAUD","CADJPY","AUDJPY","NZDJPY","CHFJPY","EURCHF"
};
string NormalizePair6(const string rawSym) {
string up = rawSym;
StringToUpper(up);
if(StringFind(up, "GOLD") >= 0) return "XAUUSD";
if(StringFind(up, "SILVER") >= 0) return "XAGUSD";
for(int k = 0; k < 18; k++) {
if(StringFind(up, CANONICAL_PAIRS[k]) >= 0) return CANONICAL_PAIRS[k];
}
return "";
}
bool IsPropNewsSafe(const string rawSym) {
// 1. Always bypass live RAM/HTTP checks inside Strategy Tester
if(MQLInfoInteger(MQL_TESTER)) return true;
string canon = NormalizePair6(rawSym);
if(canon == "") return false;
// 2. Fail-closed if Master Hub heartbeat is missing or older than 45s
if(!GlobalVariableCheck("FNR_HEARTBEAT_TS")) return false;
datetime lastSync = (datetime)GlobalVariableGet("FNR_HEARTBEAT_TS");
if(TimeGMT() < lastSync || (TimeGMT() - lastSync) > 45) return false;
// 3. Read volatile RAM gate for the canonical pair (e.g. "XAUUSD", "EURUSD")
string key = "FNR_PROP_SAFE_" + canon;
if(!GlobalVariableCheck(key)) return false;
return (GlobalVariableGet(key) > 0.5);
}
void OnTick() {
if(!IsPropNewsSafe(_Symbol)) {
return; // T-5m PRE_NEWS, 5m post-release window, VETO, or stale feed active
}
// Normal entry logic...
}
Checking StringFind(up, CANONICAL_PAIRS[k]) against the explicit pair table handles broker prefixes and suffixes (mEURUSD, iXAUUSD.pro, XAUUSDm, GOLD) cleanly without truncating a leading prefix character.
3. Guarding Compiled .ex5 Bots Without Triggering Hyperactivity Bans
Many prop traders run compiled .ex5 EAs where OnTick() cannot be modified. Those bots often place Buy Stop or Sell Stop orders hours ahead of NY open, which later fill inside a restricted T-5m CPI window and breach the account.
Deleting resting pending orders from a companion Hub EA works, provided you handle two real-world traps:
-
Event-driven interception (
OnTradeTransaction): Polling every 15 seconds is fine for scheduled countdowns, yet an aggressive.ex5bot may place a fresh pending order 2 seconds before CPI. Listening forTRADE_TRANSACTION_ORDER_ADDinsideOnTradeTransaction()catches new pending orders immediately during an active blackout without touching already-open market positions. -
The
OrderDelete/OrderSendLoop Circuit Breaker: If a poorly coded.ex5bot sees its pending order disappear and re-submits it on every tick, an uncapped guard will delete and re-delete 50 times per second. Prop firms enforce strict Server Hyperactivity caps (often 1,500 to 2,000 order messages per day) and will terminate the evaluation. Cap automated deletions strictly (for example,InpMaxDeletesPerMin = 8per symbol/minute, opt-in viaInpDeletePendingOnVeto = trueand scoped byORDER_MAGIC) and push a mobileSendNotification()alert when the circuit breaker trips.
4. Sharing the Same Gate With AI Agents Over Stateless Streamable HTTP MCP
Deterministic MQL5 owns sub-millisecond execution and pending-order sweeps, while coding agents and research copilots (Claude Code, Cursor, Codex, Grok, and MetaTrader 5's built-in Tools -> Options -> MCP client) benefit from reading the exact same macro surprise and prop-blackout state without scraping HTML calendars.
We exposed the backend feed behind PropShield as a stateless Streamable HTTP MCP server (2026-07-28 spec with single-RPC server/discover SEP-2575, RFC 8615 /.well-known/mcp.json, RFC 9728 protected-resource metadata, and backward-compatible initialize), listed in the Official MCP Registry (com.forexnewsradar/mcp).
Design Lessons From Running a Financial MCP Server in Production
-
Keep every tool strictly read-only: LLMs should inspect
prop_safe_to_trade,wait_seconds, and historicalsurprise_zsigma prints, never callOrderSend(). -
Fail closed on hallucinated arguments: Models occasionally invent extra filter parameters (such as
timeframe). Enforcing anObject.hasOwnparameter allowlist and returningallowed_to_open_trade: false(isError: true) prevents an agent from mistaking an unfiltered response for a safe green light. -
Normalize spoken tickers server-side: ChatGPT and Grok routinely pass
"GOLD","EUR/USD", or"EURUSD.pro"even when JSON schema examples specify"XAUUSD".
Register in Claude Code
export FNR_API_KEY="fnr_live_..."
claude mcp add --transport http forexnewsradar https://forexnewsradar.com/mcp \
--header "Authorization: Bearer $FNR_API_KEY"
Standard MCP Config (Cursor / .mcp.json)
{
"mcpServers": {
"forexnewsradar": {
"type": "http",
"url": "https://forexnewsradar.com/mcp",
"headers": {
"Authorization": "Bearer ${FNR_API_KEY}"
}
}
}
}
Native MetaTrader 5 MCP Client
In recent MT5 builds: open Tools -> Options -> MCP, click + Add new MCP server, set the endpoint to https://forexnewsradar.com/mcp, and supply your FNR_API_KEY.
| Read-Only Tool | Output Summary |
|---|---|
check_prop_trade_gate |
Boolean prop_safe_to_trade, T-5m pre/post blackout state, VETO reason, directional bias, and wait_seconds
|
get_pair_telemetry |
Live state, next Tier-1 countdown, standardized surprise_z releases, and closed ECN execution history |
list_radar_pairs |
18-pair session snapshot across Tokyo, London, and New York (Metals, USD, EUR, JPY, GBP) |
get_macro_feed |
Upcoming high-impact catalysts, active VETO / PRE_NEWS locks, and recent prints |
get_entitlement_status |
Unlocked pair scopes, expiry timestamp, and 240 req/min rate-limit quota |
5. Inspecting the Live Wire Without a Key
If you want to inspect the JSON schema, RFC 8615 MCP Server Card, or build your own WebRequest() / Python parser against a live feed, EURUSD telemetry and discovery metadata are open with no login or API key (POST /mcp and the remaining 17 FX/Metals pairs use a fixed-term Bearer key):
# RFC 8615 MCP Server Card (2026-07-28 capabilities & tool schemas)
curl -sS https://forexnewsradar.com/.well-known/mcp.json
# Full EUR/USD telemetry (radar_health, agent_guidance, recent sigma releases)
curl -sS https://forexnewsradar.com/api/v1/pairs/EURUSD
# ~250-byte flat payload tailored for MQL5 WebRequest() char[] buffers
curl -sS "https://forexnewsradar.com/api/v1/pairs/EURUSD?compact=1"
Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.