Complete MQL5 guide & code

MQL5 Economic Calendar API: CalendarValueHistory & News Filter Code

Complete guide to MetaTrader 5 economic calendar functions. Use CalendarValueHistory, inspect MqlCalendarValue structs, filter high-impact news events, and build an EA news blackout filter.

What this MQL5 guide covers

MetaTrader 5 provides a built-in Economic Calendar API without requiring third-party REST endpoints or web requests.

CalendarValueHistory retrieves historical and upcoming macroeconomic events within a specified datetime range and currency.

CalendarEventById unpacks event metadata, including importance (CALENDAR_IMPORTANCE_HIGH), sector, and event name.

Automated news filters inspect upcoming releases to suspend trade entries before high-volatility events like CPI, NFP, and rate decisions.

Core MQL5 Economic Calendar Functions

Unlike MetaTrader 4, which required external WebRequests to news APIs, MetaTrader 5 provides native economic calendar functions directly connected to MetaQuotes data servers.

These functions populate arrays of MqlCalendarValue records representing scheduled data releases (such as US Non-Farm Payrolls, GDP, CPI, or central bank interest rate decisions).

FunctionReturn TypePurpose
CalendarValueHistory(values, from, to, country, currency)intFetches event value records between two timestamps for a country or currency
CalendarEventById(event_id, event)boolRetrieves event description, name, type, and importance level
CalendarCountryById(country_id, country)boolRetrieves country name and ISO 3166-1 alpha-2 code
CalendarValueById(value_id, value)boolRetrieves actual, forecast, and revised values for a specific record ID

MqlCalendarValue and MqlCalendarEvent Structures

When CalendarValueHistory executes successfully, it fills an array of MqlCalendarValue structures. To interpret whether an event represents a major risk, you pass the value.event_id to CalendarEventById.

  • MqlCalendarValue::time: The exact scheduled release timestamp (datetime).
  • MqlCalendarValue::actual_value: Reported actual data value (converted using event multiplier).
  • MqlCalendarValue::forecast_value: Consensus estimate forecast value.
  • MqlCalendarEvent::importance: Severity enum: CALENDAR_IMPORTANCE_NONE, LOW, MODERATE, HIGH.

Designing an Automated News Blackout Shield

High-impact economic announcements frequently cause dramatic spread widening, slippage, and whipsaw price action. Production EAs typically define a news window (e.g., 30 minutes before and 30 minutes after major releases).

If CalendarValueHistory reveals a high-importance release within this window, the EA sets a pause flag, preventing new order placement until market liquidity normalizes.

Implementation details & mechanics

Core implementation pattern

Before evaluating trading signals in OnTick(), call the IsHighImpactNewsUpcoming(currency, lookaheadMinutes) helper. The helper queries CalendarValueHistory from TimeCurrent() to TimeCurrent() + (lookaheadMinutes * 60). If any matching event has importance == CALENDAR_IMPORTANCE_HIGH, trading entries are blocked.

Error handling & safety rules

EAs can also use the calendar filter to tighten trailing stops or close open risk before tier-1 events. When an event is within 5 minutes, the EA can loop over open positions and close them via CTrade::PositionClose() or adjust stops to breakeven.

MQL5 Code Implementation Code

//+------------------------------------------------------------------+
//|                                     EconomicCalendarFilterEA.mq5 |
//|                             Copyright 2026, Pineify Guides Series |
//|                                              https://pineify.app |
//+------------------------------------------------------------------+
#property copyright "Pineify Guides Series"
#property link      "https://pineify.app/mql5/economic-calendar-api"
#property version   "1.00"
#property strict

//--- Input parameters
input group "--- News Filter Configuration ---"
input bool   InpEnableNewsFilter    = true;   // Enable Calendar News Filter
input string InpFilterCurrency      = "USD";  // Currency to monitor (e.g. USD, EUR)
input int    InpMinutesBeforeNews   = 30;     // Pause trading N minutes before news
input int    InpMinutesAfterNews    = 15;     // Pause trading N minutes after news

//+------------------------------------------------------------------+
//| Helper: Check if high-impact news is nearby                      |
//+------------------------------------------------------------------+
bool IsHighImpactNewsNearby(const string currency, int minsBefore, int minsAfter)
  {
   if(!InpEnableNewsFilter)
      return false;

   datetime now = TimeCurrent();
   datetime fromTime = now - (minsAfter * 60);
   datetime toTime   = now + (minsBefore * 60);

   MqlCalendarValue values[];
   // Retrieve calendar values for the currency in the specified window
   int count = CalendarValueHistory(values, fromTime, toTime, NULL, currency);
   if(count <= 0)
      return false; // No events found or calendar not available

   for(int i = 0; i < count; i++)
     {
      MqlCalendarEvent event;
      if(CalendarEventById(values[i].event_id, event))
        {
         // Check if event is High Impact
         if(event.importance == CALENDAR_IMPORTANCE_HIGH)
           {
            PrintFormat("NEWS ALERT: High Impact [%s] at %s: '%s'",
                        currency,
                        TimeToString(values[i].time, TIME_DATE|TIME_MINUTES),
                        event.name);
            return true; // Blackout active
           }
        }
     }

   return false;
  }

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
   Print("Economic Calendar Filter initialized for currency: ", InpFilterCurrency);
   return(INIT_SUCCEEDED);
  }

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
   // Check news filter before allowing any trading decisions
   bool isNewsActive = IsHighImpactNewsNearby(InpFilterCurrency,
                                             InpMinutesBeforeNews,
                                             InpMinutesAfterNews);
   if(isNewsActive)
     {
      // Display status on chart comment
      Comment("Trading Suspended: High-impact economic news nearby for ", InpFilterCurrency);
      return;
     }

   Comment("Trading Active: Normal market conditions.");

   // Normal EA strategy signal and order routing continues here...
  }

Copy this code into MetaEditor, save it in your MQL5 folder (Experts, Scripts, or Include), and compile with F7.

Generate custom MQL5 code with Pineify AI

Describe the trade execution, indicator calculations, risk management, or data processing logic you need. Pineify produces clean, typed MQL5 source code ready to compile in MetaEditor.

Frequently Asked Questions

Related MQL5 pages

Technical references

Risk and testing note

Past performance is not indicative of future results. Backtest statistics are based on historical data and do not guarantee future profits. Trading involves significant risk of loss. This content is for educational purposes only and does not constitute financial advice.