Blog / Code & convert EAs · MQL5 · Prop firms · Expert Advisors
Coding a News Filter for Prop Firm Rules in MQL5
Learn to build an MQL5 news filter that blocks trades around high-impact economic events and how to test it in MT5.
· 7 min read
Trading around major economic announcements can expose an account to sudden price movements, wider spreads, and unpredictable execution.
For traders using prop firm accounts, this can be particularly risky. Some firms restrict trading around high-impact news events, while others impose specific conditions on opening, closing, or holding positions during designated news windows.
One way to manage this is to build an economic news filter directly into your Expert Advisor.
MetaTrader 5 provides built-in economic calendar functions, including CalendarValueHistory() and CalendarEventById(), which allow an EA to retrieve scheduled events and identify their importance.
In this guide, we'll use these functions to prevent new trades around high-impact economic announcements and explain how to handle the limitations when testing the EA in MT5.
1. Understand how the MT5 economic calendar works
MQL5 provides several functions for accessing economic calendar information.
The most useful ones for a basic news filter include:
| Function | Purpose |
|---|---|
CalendarValueHistory() |
Retrieves economic event records within a specified time range |
CalendarEventById() |
Retrieves the description and properties of an event |
CalendarCountryById() |
Retrieves information about the country associated with an event |
CalendarValueLast() |
Retrieves new or updated calendar records since a previous calendar database state |
For our implementation, we'll primarily use the first two.
CalendarValueHistory() retrieves calendar records, including their scheduled times and event IDs. It returns the number of records it found, or -1 if the request fails. We can then pass each event ID to CalendarEventById() to retrieve its importance level.
MQL5 defines three main importance levels:
- Low importance.
- Moderate importance.
- High importance.
Our objective is to identify high-impact events affecting the currencies traded by the EA.
Important: MT5 economic calendar functions use trade server time, not your computer's local time. This distinction matters when calculating news windows and comparing scheduled event times.
2. Define the news filter settings
Start by adding inputs that allow the trader to configure the currencies and the period during which new trades should be blocked.
input string NewsCurrency1 = "USD";
input string NewsCurrency2 = "EUR";
input int MinutesBeforeNews = 30;
input int MinutesAfterNews = 30;For a EURUSD EA, for example, monitoring USD and EUR announcements makes sense because both currencies influence the instrument.
The time settings create a 60-minute restricted window around each qualifying announcement: 30 minutes before and 30 minutes after.
These are example settings. If you're trading on a prop firm account, configure the window according to the firm's actual news-trading restrictions.
3. Retrieve upcoming economic events
Next, create a function that retrieves calendar records for a selected currency.
bool IsHighImpactNewsWindow(string currency)
{
datetime now = TimeTradeServer();
if(now == 0)
now = TimeCurrent();
// An event that happened up to MinutesAfterNews ago,
// or is due within MinutesBeforeNews, blocks new entries.
datetime fromTime =
now - MinutesAfterNews * 60;
datetime toTime =
now + MinutesBeforeNews * 60;
MqlCalendarValue values[];
ResetLastError();
int count = CalendarValueHistory(
values,
fromTime,
toTime,
NULL,
currency
);
if(count < 0)
{
PrintFormat(
"Calendar request failed for %s. Error: %d",
currency,
GetLastError()
);
// Fail safely: block new entries if calendar data is unavailable.
return true;
}
for(int i = 0; i < count; i++)
{
MqlCalendarEvent event;
if(!CalendarEventById(values[i].event_id, event))
{
PrintFormat(
"Unable to retrieve calendar event: %I64u",
values[i].event_id
);
// Do not silently ignore an event that could be high impact.
return true;
}
if(event.importance == CALENDAR_IMPORTANCE_HIGH)
{
PrintFormat(
"High-impact event detected: %s at %s",
event.name,
TimeToString(values[i].time)
);
return true;
}
}
return false;
}Here's what happens:
- The EA obtains the current trade server time.
- It looks back
MinutesAfterNewsand aheadMinutesBeforeNewsfrom now. An event due in the next 30 minutes, or one released in the last 30 minutes, means the EA is inside that event's restricted window. CalendarValueHistory()retrieves events affecting the selected currency within that period.CalendarEventById()retrieves each event's details.- The EA checks whether an event has high importance.
- If a high-impact event is found, the function returns
true.
Note the direction: the "before" setting decides how far ahead the EA looks, and the "after" setting how far back. Swapping them makes no difference while both are 30 minutes, but it blocks the wrong period as soon as you set them differently.
The function also adopts a fail-safe approach. If the calendar request fails or an event cannot be retrieved, it blocks new entries rather than assuming there is no relevant news.
This is a deliberate safety choice. Depending on the prop firm's requirements, you may want an additional configurable policy for handling temporary calendar outages.
4. Check both currencies before opening a trade
For a currency pair such as EURUSD, checking only USD events would leave the EA exposed to important EUR announcements.
Create a second function to check both configured currencies.
bool IsNewsFilterActive()
{
if(IsHighImpactNewsWindow(NewsCurrency1))
return true;
if(IsHighImpactNewsWindow(NewsCurrency2))
return true;
return false;
}The function returns true whenever either currency has a high-impact event within the restricted window.
You can adapt the currency inputs for other instruments. For example, an EA trading GBPJPY might monitor GBP and JPY announcements.
For instruments such as gold, the relevant currencies and economic events depend on the strategy and the prop firm's requirements.
5. Integrate the filter into your EA
Once the news-filter functions are defined, add the check to the EA's entry logic.
For example:
void OnTick()
{
// Continue managing existing positions.
ManageOpenPositions();
// Block new entries during high-impact news.
if(IsNewsFilterActive())
{
Print("News filter active. New entries blocked.");
return;
}
// Continue with the normal trading strategy.
CheckForNewEntries();
}Notice that existing position management runs before the news filter.
This allows the EA to continue managing open trades while preventing new entries during restricted periods.
In a live EA, you would also avoid printing the message on every tick. Log it once when the window starts, or the Experts log fills up with the same line.
However, blocking new entries does not automatically satisfy every prop firm's news policy. Some firms also restrict closing positions, modifying orders, or holding trades through particular announcements.
If the firm's rules require additional restrictions, those must be implemented separately.
Also consider checking the news filter immediately before sending an order, particularly if your EA uses timers, asynchronous execution, or multiple entry routines.
6. Understand the Strategy Tester limitation
There is an important limitation you must account for when developing an MQL5 news filter.
MT5's built-in economic calendar functions do not work in the Strategy Tester.
Functions such as CalendarValueHistory(), CalendarValueLast(), and CalendarEventById() rely on calendar data provided by the live terminal. They cannot be called normally during historical Strategy Tester execution, and typically fail with error 4014 (ERR_FUNCTION_NOT_ALLOWED).
Because the function above blocks entries whenever the calendar request fails, a backtest of it would simply show an EA that never trades. You cannot run the live news-filter implementation and expect it to retrieve historical economic events during a backtest.
There are two practical ways to handle this.
Option A: Export historical calendar data to CSV
One approach is to collect economic calendar records outside the Strategy Tester and save them to a CSV file.
The process is:
- Run a separate collector script or EA on a live or demo chart.
- Use
CalendarValueHistory()to retrieve the required historical calendar records. - Retrieve each event's details using
CalendarEventById(). - Save the event time, currency, importance, and event name to a CSV file.
- Load that file from your EA when running in the Strategy Tester.
- Compare each simulated test time against the stored event times.
- Apply the same before-and-after restrictions used by the live news filter.
For example, a CSV file could contain:
| Event time | Currency | Importance | Event |
|---|---|---|---|
| 2025.01.15 13:30 | USD | High | CPI |
| 2025.01.29 19:00 | USD | High | Federal Reserve Rate Decision |
| 2025.02.05 10:00 | EUR | High | ECB Monetary Policy Statement |
These are illustrative records.
Your EA can read the file using MQL5 file functions such as FileOpen(), FileReadString(), and FileClose(). The tester runs in its own sandbox, so either place the file in the terminals' common folder and open it with FILE_COMMON, or declare it with #property tester_file so the tester copies it to the testing agent.
Make sure the CSV timestamps use the same time reference as the Strategy Tester data. The calendar uses trade server time, so you may need to account for broker-server timezone differences.
Also note that a calendar downloaded today may contain revised schedules or historical records that differ from what was known at the time. For rigorous historical testing, use archived calendar data that reflects the information available at each historical date.
Option B: Separate live and tester logic
Another approach is to make the EA detect whether it is running in the Strategy Tester and use a different data source.
For example:
bool IsNewsFilterActive()
{
if(MQLInfoInteger(MQL_TESTER))
{
return IsNewsWindowFromCSV();
}
return IsNewsWindowFromCalendar();
}Here, IsNewsWindowFromCSV() represents your historical-data lookup function, while IsNewsWindowFromCalendar() contains the live calendar implementation.
This keeps the trading strategy's entry logic unchanged while allowing the news filter to use the appropriate data source in each environment.
The CSV-loading function must be implemented separately; the example above illustrates the architecture rather than a complete drop-in implementation.
7. Test the news filter before deploying it
Before using the EA on a prop firm account, verify that the filter behaves correctly under different conditions.
A useful checklist includes:
- Confirm that the EA retrieves the correct currency events.
- Verify that only high-impact events trigger the filter.
- Check that the before-and-after windows are calculated correctly, including with different before and after values.
- Confirm that both currencies are monitored for currency pairs.
- Verify that existing positions continue to receive normal management.
- Test what happens when calendar data cannot be retrieved.
- Confirm that the filter uses broker-server time.
- Test the CSV implementation separately in the Strategy Tester.
- Verify that the EA resumes normal entries after the restricted window ends.
Finally, compare the EA's behaviour with the actual prop firm's news policy. An internally correct news filter can still be unsuitable if its event selection, restricted period, or treatment of existing positions does not match the firm's rules.
Conclusion
An economic news filter can help protect an Expert Advisor from trading during high-impact announcements.
MQL5 makes this possible through built-in calendar functions such as CalendarValueHistory() and CalendarEventById(), allowing developers to retrieve scheduled events and filter them by importance and currency.
The main development challenge is handling the Strategy Tester limitation. Since the built-in calendar functions are unavailable during historical testing, you need to export calendar records to a file or use another historical data source.
Build the live and testing logic separately, use the correct server-time reference, and configure the restricted periods according to the prop firm's actual rules. A news filter usually sits next to a daily loss limit; The Most Important Prop Firm Rules covers the rest.
To add a news filter like this to an EA you already have, use PositionAlpha's Fix an EA: paste or upload the EA and describe the change. The AI returns the complete updated .mq4 or .mq5 file and explains each change it made. Compile the result in MetaEditor and test it in the Strategy Tester and on a demo account before you rely on it.
Build a bot from your idea
Describe your trading idea and the AI writes MT4 or MT5 code for you to review and test, with a plain-English explanation and setup steps. Your first bot is free.