How to Program News Filters Into an EA for High-Impact Events
Programming a news filter into an EA for high-impact events comes down to three moving parts: an internal calendar of scheduled release times (NFP, CPI, FOMC, and similar), a tag on each event for currency and impact level, and a comparison of current server time against every event time on each tick or timer cycle. Once the clock lands inside a defined buffer window before and after the release, the EA blocks new orders and, depending on how it's configured, flattens open positions until the volatility settles. The hard part isn't the comparison logic itself. It's keeping the calendar current, accounting for broker time-zone offsets, and testing the whole thing honestly, since most strategy testers can't fully simulate the spread widening and slippage that real news events produce. Built correctly, this becomes a risk-management layer that sits alongside your entry logic rather than a substitute for sound risk management.
In This Guide
- Why News Filters Exist in EA Design
- Step 1: Defining What Counts as "High-Impact"
- Step 2: Building or Importing Your Economic Calendar Feed
- Step 3: Coding the Pre-Event Blackout Window
- Step 4: Coding the Post-Event Cooldown and Re-Entry Logic
- Step 5: Managing Open Positions When News Hits
- Step 6: Backtesting Limitations You Must Account For
Anyone who has watched an XAUUSD chart during a Federal Reserve announcement or a US Non-Farm Payrolls print already knows why traders ask this question. Spreads can widen from a few points to several dollars in seconds. Price can spike hundreds of pips and retrace just as fast, and a resting stop-loss can fill nowhere near where you expected it to. A well-built news filter doesn't predict which direction price will move; it simply keeps your EA out of the chop while the market digests the number. What follows is a practical, code-oriented walkthrough of how experienced MQL4 and MQL5 developers actually build this feature: the tradeoffs involved, the bugs that show up again and again, and where the whole thing fits into a broader gold-trading risk framework.
Why News Filters Exist in EA Design
An Expert Advisor trades on rules built for typical market conditions, and high-impact economic releases are, by definition, atypical. In the seconds around a major US data print, volatility spikes, liquidity briefly thins even though volume is high, and price can temporarily decouple from the technical levels an EA normally reads. A setup that works reliably on an ordinary Tuesday afternoon can throw off a false signal during the two minutes surrounding a Consumer Price Index release, simply because the price action in that window is being driven by order-flow reaction to the headline number rather than the trend structure the strategy was designed to interpret.
The practical risks a news filter controls fall into three buckets. First, spread risk: brokers routinely widen gold spreads around news, which throws off risk-per-trade math built on the assumption of a stable spread. Second, slippage risk: a market order sent milliseconds before a release can fill dozens of pips away from the requested price. Third, stop-hunt risk: a temporary spike can tag a stop that would never have been touched under normal volatility, only for price to reverse moments later. None of this is hypothetical. It's a documented, recurring feature of liquidity around scheduled announcements, and it's part of why the CFTC's guidance on automated trading systems encourages traders to understand how their systems behave under stress, not just under backtested averages.
It's worth being precise about what a news filter does and doesn't do. It does not filter out losing trades; it filters out a specific category of elevated-risk time windows. Some EAs build this logic in directly. Others sidestep the problem a different way, by being highly selective about entries in the first place. Either approach is legitimate engineering, and which one suits you depends on your strategy's holding period and your broker's execution quality.
Step 1: Defining What Counts as "High-Impact"
Before writing a single line of filter code, you need a hard definition of "high-impact," because an EA can't filter what it can't categorize. Most economic calendars use a three-tier system, low, medium, and high impact, sometimes shown as one, two, or three stars. For a gold-focused EA, the events that matter most are USD-denominated, since gold is priced and traded overwhelmingly against the dollar, along with a handful of events tied to broader risk sentiment.
The table below lists the event categories most XAUUSD-focused developers hard-code as "high-impact," along with typical release timing and the kind of volatility spike each has historically produced on gold. These are general characteristics, not predictions about any specific future release.
| Event Type | Typical Release (ET) | Frequency | Typical XAUUSD Volatility Spike* |
|---|---|---|---|
| US Non-Farm Payrolls (NFP) | 8:30 AM, first Friday | Monthly | 300-800+ pips in the first 15 minutes |
| US CPI (Consumer Price Index) | 8:30 AM | Monthly | 200-600 pips in the first 15 minutes |
| FOMC Rate Decision + Statement | 2:00 PM | 8x per year | 150-500 pips, often two-sided |
| Fed Chair Press Conference | 2:30 PM (FOMC days) | 8x per year | Extended volatility for 30-45 minutes |
| US PCE Price Index | 8:30 AM | Monthly | 150-400 pips in the first 15 minutes |
| US GDP (Advance/Final) | 8:30 AM | Quarterly | 100-300 pips |
*Approximate historical ranges for illustration; actual moves vary depending on the release's surprise versus consensus and prevailing market conditions.
In code, this typically becomes an enumerated impact level attached to a custom struct, something like an EventImpact value of LOW, MEDIUM, or HIGH, paired with a currency code string. From there, the filter logic only cares about events where impact equals HIGH and currency equals "USD" (plus "XAU" if your source tags gold-specific events separately). This is also where you settle policy up front: do you filter only USD events, or also major central bank announcements from other regions that move gold indirectly? Most XAUUSD-specific filters stick to USD data, since that's the dominant driver.
Step 2: Building or Importing Your Economic Calendar Feed
An EA needs a data source for event times, and there are three common approaches, each with its own tradeoffs around reliability and platform compatibility.
Approach A: The MT5 Built-In Economic Calendar
MetaTrader 5 provides native calendar functions (documented in the MQL5 reference) that let an EA query upcoming events directly from the terminal, including country, importance level, and scheduled time, with no external file to maintain. It's the most maintenance-free option on offer, but it's MT5-only. MetaTrader 4 has no equivalent built-in calendar, which is why so many MT4 developers end up leaning on Approach B or C instead.
Approach B: A Manually Maintained Array or CSV File
For MT4, or for MT5 developers who want more control over which events get flagged, the common pattern is a hard-coded or externally loaded list: an array of structs (or a CSV read at OnInit()) containing event name, currency, impact level, and scheduled datetime. The weakness is obvious. Someone has to keep this list updated, since FOMC meeting dates are set annually but still have to be re-entered by hand, and ad hoc events like emergency rate decisions never make it into a static list at all.
Approach C: Recurring-Schedule Approximation
A simpler, lower-maintenance approach skips the literal calendar in favor of a rules-based approximation: "block trading on the first Friday of the month between 8:15 AM and 9:00 AM ET" for NFP, calculated programmatically from calendar rules rather than looked up. This trades precision for maintainability. It won't catch every ad hoc event, but it needs no external feed, and it can't silently go stale the way a hard-coded list can.
Whichever approach you choose, store every event time in one consistent reference, almost always broker server time via TimeCurrent(), converting from the source's stated time zone at load time. Mixing time zones is one of the most common bugs in this feature, and it's discussed further below alongside other issues covered in our guide to common EA problems and fixes.
Step 3: Coding the Pre-Event Blackout Window
Once event times are in a comparable format, the core filter logic is simply a time-window check that runs at the top of your trade-decision function, before any entry logic executes. On each new bar, or on a timer (OnTimer() is often cleaner than checking every tick, since minute-level resolution is all you actually need), loop through upcoming events, and for each HIGH-impact event inside your lookback window, calculate the seconds between current time and event time. If that number falls within your pre-event buffer, set a flag such as newsBlackoutActive = true and skip new order placement for that cycle.
Buffer size is a design decision rather than a fixed rule, and it should reflect how your strategy holds trades and how your broker's execution tends to behave. The table below shows a common structure that sizes buffers by event tier instead of applying one blanket window to everything.
| Event Tier | Pre-Event Buffer | Post-Event Buffer | Rationale |
|---|---|---|---|
| Tier 1 (NFP, CPI, FOMC decision) | 15-30 minutes | 15-60 minutes | Highest volatility and widest spread widening; longest cooldown |
| Tier 2 (PCE, GDP, Fed speeches) | 10-15 minutes | 10-30 minutes | Meaningful but generally shorter-lived reaction |
| Tier 3 (regional/secondary data) | 5 minutes or filtered out entirely | 5-10 minutes | Often skipped by XAUUSD-specific filters unless USD-relevant |
Take NFP as a concrete case: it's scheduled for 8:30:00 AM server time, and say you've set a 20-minute pre-event buffer and a 30-minute post-event buffer. Your blackout window runs from 8:10:00 AM to 9:00:00 AM. If your EA's signal logic would have triggered an entry at 8:22 AM, the filter overrides it and no order goes out, no matter how strong the signal looks. Log every override to your Experts tab (via Print()) so you can audit which signals were suppressed and why, useful for understanding your EA's real behavior against its backtested behavior.
Step 4: Coding the Post-Event Cooldown and Re-Entry Logic
The post-event side is where developers make most of their mistakes, because the temptation is to resume trading the instant the timer expires, treating the cooldown as a hard cutoff instead of a fade-out. Elevated volatility and wider-than-normal spreads often persist for several minutes to an hour after a Tier 1 release, well after the initial spike has passed. Two patterns handle this more realistically than a plain timer does.
The first pattern pairs a fixed cooldown with a spread check: once the timer expires, the EA compares the current live spread (via SymbolInfoInteger(_Symbol, SYMBOL_SPREAD) in MQL5, or MarketInfo(Symbol(), MODE_SPREAD) in MQL4) against a stored baseline, and only resumes trading once the live spread has come back to within, say, 150% of that baseline. The second pattern uses a volatility check instead, comparing a short-period ATR value against its recent average and resuming only once ATR falls back within range of its pre-event level. Pairing a minimum timer with one of these confirmation checks holds up better than a timer alone, since a timer by itself is only guessing at how long a given event's effects will last.
It's also worth deciding upfront whether a new high-impact event that starts inside a previous event's post-buffer should extend the blackout or simply run on its own. The cleanest implementation treats the blackout as a rolling union of all active buffers, recomputed on every check, rather than a set of independent timers that could toggle the flag off prematurely between two closely spaced events, say a data release followed shortly after by a Fed speaker.
Step 5: Managing Open Positions When News Hits
Blocking new entries only solves half the problem. You still need a policy for positions that are already open when the blackout window begins. Developers generally implement one of three broad strategies, and the right pick depends on your holding-period style and your tolerance for realized versus unrealized risk.
The first strategy closes everything before the event: flatten open positions a set number of minutes ahead of a Tier 1 release, then re-evaluate fresh once the cooldown ends. This guarantees you can't get caught by an adverse spike, but it also means giving up any favorable trade already in motion and re-entering afterward at a new spread and price. The second strategy holds through the event but widens or removes trailing stops, on the reasoning that a stop-loss distance calibrated for typical volatility is too tight for a news spike and would likely get clipped by noise rather than a genuine reversal. The third strategy leaves open positions untouched entirely and relies solely on the pre-set stop-loss, accepting that slippage on that stop is a known, budgeted risk as long as position size was calculated correctly in the first place, a topic covered in our guide to drawdown and account risk exposure.
None of these three is objectively correct. A short-holding-period scalper is more likely to flatten before news, since positions are rarely held long enough to benefit from surviving the volatility anyway. A trend-following system running wider stops may prefer to ride through scheduled events instead, since flattening and re-entering around every data print erodes returns through repeated spread costs. Whichever you choose, code it explicitly. "Do nothing" should be a deliberate, documented decision, not an oversight nobody caught.
Step 6: Backtesting Limitations You Must Account For
This is the section most developers skip, and it's the one that causes the most surprises once the EA goes live. Standard strategy tester backtests in MT4 or MT5 replay historical price bars, but they generally don't replay the actual spread widening and liquidity gaps that occurred during a historical news event, not unless you're using tick-level data with variable spread modeling configured for it. A backtest of your filter can end up looking artificially clean as a result: it correctly avoids trading during the flagged window, but it can't show what would have happened to your equity if the filter had failed to trigger, or if a position had been caught by real slippage instead of modeled spread.
For a more honest read, run your backtest in "Every tick based on real ticks" mode where it's available, per MetaTrader 5's automated trading documentation. Even then, treat the results skeptically. A backtest really only confirms "did the timer logic skip the flagged bars," not "did this filter meaningfully protect capital." Answering that second question requires comparing live results with and without the filter across enough events to be statistically meaningful. For a broader walkthrough of the process itself, see our guides on backtesting an EA on MT4 and its MT5 equivalent.
Forward testing on a demo account through at least two or three live NFP or FOMC cycles is the more reliable validation step. It exposes the filter to genuine broker spread behavior and execution latency that no backtest fully replicates.
Common Coding Pitfalls and How to Fix Them
The same handful of bugs shows up again and again in news-filter implementations. The table below lists the most frequent ones next to their practical fix.
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Time-zone mismatch between calendar and server time | Calendar source stated in ET or GMT, server time in broker's own offset, which can shift with daylight saving on different dates than US/EU | Normalize every event time to broker server time at load, and re-verify offsets after daylight-saving transitions |
| Stale hard-coded event list | FOMC/NFP dates change yearly; list not updated | Re-verify the list quarterly, or use an automated calendar source where the platform supports it |
| Blackout flag checked only on new bar, not sub-minute | H4 or H1 EAs often only evaluate logic once per bar close | Use OnTimer() for the blackout check specifically, independent of the strategy's own signal timeframe |
| Filter blocks new entries but ignores pending orders | Buy/Sell Limit or Stop orders left resting can still fill during the event | Explicitly cancel or adjust pending orders when the blackout flag activates |
| No logging of suppressed signals | Developer only logs executed trades | Log every instance the filter overrides a signal, with event name and timestamp, for later review |
| Overlapping event windows mishandled | Two buffers computed independently can toggle the flag off between events | Treat the blackout as a rolling union of all active buffers, recalculated each check |
One related issue is worth flagging separately. Some vendors market a "built-in news filter" as a headline feature without disclosing how it's implemented, how the calendar is sourced, or how it's validated. Before trusting that claim on a paid product, ask what data source powers it and what happens to open positions during the blackout. Vague answers are a reasonable basis for skepticism, in the same spirit as the general caution the FTC recommends for automated trading claims you can't independently verify.
Where This Fits Into an EA's Overall Risk Framework
A news filter is one layer of risk control, not a replacement for the others. It belongs alongside position sizing tied to account equity, a maximum-drawdown circuit breaker, and realistic expectations about win rate and payoff ratio. Golden Viper EA, for context, takes a different design path to managing event risk. Rather than running a news-time-window filter, it's deliberately selective by design, typically evaluating for roughly one qualifying setup per day at most on the XAUUSD H4 timeframe, uses risk-based lot sizing across three selectable risk modes (Conservative, Normal, and Aggressive), and applies a profit-lock mechanism on winning trades along with an optional safety stop, with no martingale, grid, or averaging anywhere in its logic. That lower trade frequency, paired with a structural approach to protecting gains, manages exposure to volatile periods in a different way than a dedicated blackout timer would, and reasonable developers can land on either approach.
Whichever approach an EA uses, the track record behind the claims matters more than the marketing copy around it. Golden Viper's live performance is published on a verified Myfxbook account (11943038) and as an MQL5 signal, both relying on independent, broker-authenticated verification rather than self-reported screenshots, which is the same standard Myfxbook documents for connecting a live account. When evaluating any gold EA's claims, insist on this kind of independently verifiable evidence, and see our guide on how to connect MT4 to Myfxbook if you want to verify your own results the same way.
Risk Disclosure
Trading gold, forex, and other leveraged instruments carries substantial risk, and losses remain possible even with a well-coded news filter, careful position sizing, and a verified track record. Past results, whether from a backtest or a live verified account, don't guarantee future performance. A news filter reduces exposure to one specific category of risk; it doesn't eliminate risk generally, and it can't protect against every form of slippage, gap, or broker execution issue. Only trade with capital you can actually afford to lose, and treat any EA, including one with sophisticated news-handling logic, as one component of a broader plan grounded in sound risk management rather than a substitute for it. If gold's price sensitivity to macro data and central bank policy is new territory for you, our overview of how economic news moves gold prices is a useful companion piece to this guide.
Frequently Asked Questions
Can I program a news filter in both MT4 and MT5, or is it MT5-only?
Both platforms support it, though the implementation differs. MT5 ships with a native economic calendar you can query through MQL5 functions, while MT4 has no built-in equivalent, so MT4 developers typically maintain a hard-coded list, load a CSV, or fall back on a recurring-schedule approximation.
What is a reasonable buffer window before and after NFP?
Many developers use a 15-30 minute pre-event buffer and a 15-60 minute post-event buffer for Tier 1 events like NFP, CPI, and FOMC decisions, often extending the post-event side with a spread or ATR confirmation check rather than relying on a fixed timer alone, since volatility rarely subsides on a neat schedule.
Do I need a paid economic calendar API, or can I build this for free?
You can build a fully functional filter for free using MT5's built-in calendar or a manually maintained event list. Paid data feeds mainly add convenience, automatic updates and broader coverage, rather than a fundamentally different mechanism underneath.
Should the filter close open positions before news, or just block new entries?
That depends on your strategy's holding period. Short-term systems often flatten before Tier 1 events to avoid slippage on stops, while longer-term trend systems may prefer to hold through with wider or removed trailing stops, since repeated re-entry adds spread cost over time. Code this decision explicitly rather than leaving it unhandled.
Why does my backtest show the news filter working perfectly, but live results differ?
Standard backtests generally don't replicate the real spread widening and slippage that occur during actual news events, not unless you're using real-tick, variable-spread data modeled specifically for it. Forward testing on a demo account through several live NFP or FOMC cycles gives a far more honest picture of how the filter performs under real conditions.
Does Golden Viper EA use a built-in news filter?
No. Golden Viper doesn't run a scheduled news-blackout filter. It manages event-period risk through a different structural approach instead: selective trade frequency, risk-based lot sizing across three selectable risk modes, and a profit-lock with an optional safety stop, all detailed on the Golden Viper EA product page.
Can a news filter guarantee I avoid losses during high-impact events?
No. Any claim that a filter guarantees avoided losses deserves skepticism, consistent with the red flags the CFTC warns about in automated trading marketing. A well-built filter reduces exposure to a defined risk window; it can't eliminate slippage, gaps, or broker-side execution issues entirely.
How often should I update my hard-coded event calendar?
At minimum quarterly, since FOMC meeting dates are published annually but easy to forget to re-enter, plus immediately after any known schedule change. A stale list is one of the most common reasons a "working" filter quietly stops protecting against events at all.
Should the filter apply to every currency pair, or just gold?
For a gold-focused EA, USD-denominated events matter most, since gold is priced against the dollar, though some developers add a secondary tier for other major central bank decisions that move gold indirectly. Keep the primary list narrow and well-tested rather than trying to cover every global event at once.
Is coding a news filter something a beginner can realistically do?
Yes. With MQL basics (structs, arrays, time functions, and either OnTimer() or new-bar checks) a beginner can put together a functional version in a few sessions. The harder part isn't the syntax. It's testing the thing honestly and understanding its real-world limitations, covered in our guide to understanding EA settings before deploying custom logic live.
Let Golden Viper EA trade gold for you
Automated XAUUSD trading for MT4 & MT5, verified live on Myfxbook. One-time $199, lifetime access.
Get Lifetime Access — $199