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

MetaTrader 5 provides native calendar functions. This example uses those functions rather than an external HTTP endpoint; availability and returned errors still need handling.

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: Release time in trade-server time; event time mode can indicate that timing is not exact.
  • MqlCalendarValue::actual_value: Integer scaled by 1,000,000; LONG_MIN means unavailable. Check before converting, or use HasActualValue/GetActualValue.
  • MqlCalendarValue::forecast_value: Forecast with the same scaling and missing-value rules; inspect event units separately.
  • MqlCalendarEvent::importance: Severity enum: CALENDAR_IMPORTANCE_NONE, LOW, MODERATE, HIGH.

Designing an Explicit News-Window Policy

A scheduled release can change spreads and execution conditions. A before/after interval is a policy to test, not a shield against all news. This example defaults to 30 minutes before and 15 after high-importance releases for one configured currency.

A matching event blocks the example entry path. Query or metadata failures produce a separate unknown state and also block it. An empty window means only that no matching event was returned; it does not establish normal liquidity.

Implementation details & mechanics

Core implementation pattern

OnTick calls a three-state helper: 1 means a matching high-importance event, 0 means none returned, and -1 means the query could not be verified. The request covers server time minus InpMinutesAfterNews through server time plus InpMinutesBeforeNews. Both an event and an unknown result block the illustrative entry path; no actual order logic is included.

Error handling & safety rules

No position close, breakeven or trailing-stop code is implemented. An entry filter should not suppress unrelated management of existing positions. Calendar APIs are unavailable in Strategy Tester; a tested strategy needs previously captured data and a defined historical server-time/DST mapping. The current example queries on ticks and is not a production cache or latency benchmark.

MQL5 Code Implementation

//+------------------------------------------------------------------+
//|                                     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                      |
//+------------------------------------------------------------------+
int HighImpactNewsStatus(const string currency, int minsBefore, int minsAfter)
  {
   if(!InpEnableNewsFilter)
      return 0;

   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
   ResetLastError();
   int count = CalendarValueHistory(values, fromTime, toTime, NULL, currency);
   if(count<0 || GetLastError()!=0)
     {
      Print("Calendar query unavailable: ",GetLastError());
      return -1;
     }

   for(int i = 0; i < count; i++)
     {
      MqlCalendarEvent event;
      if(!CalendarEventById(values[i].event_id,event))
        {
         Print("Calendar event metadata unavailable: ",GetLastError());
         return -1;
        }
      else
        {
         // 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 1; // Blackout active
           }
        }
     }

   return 0;
  }

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
   if(InpMinutesBeforeNews<0 || InpMinutesAfterNews<0 || InpMinutesBeforeNews>10080 || InpMinutesAfterNews>10080 || InpMinutesBeforeNews+InpMinutesAfterNews==0) return INIT_PARAMETERS_INCORRECT;
   Print("Economic Calendar Filter initialized for currency: ", InpFilterCurrency);
   return(INIT_SUCCEEDED);
  }

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
   // Check news filter before allowing any trading decisions
   int newsStatus = HighImpactNewsStatus(InpFilterCurrency,
                                             InpMinutesBeforeNews,
                                             InpMinutesAfterNews);
   if(newsStatus!=0)
     {
      // Display status on chart comment
      Comment(newsStatus<0 ? "Entry blocked: calendar status unknown" : "Entry blocked: high-importance event in window");
      return;
     }

   Comment(InpEnableNewsFilter ? "No matching high-importance event returned; this is not a market safety signal." : "News filter disabled.");

   // 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 generates editable MQL5 source code. Review its logic, request a syntax check, and compile and test the final file in MetaEditor.

Frequently Asked Questions

Related MQL5 pages

Technical references

Risk and testing note

These educational examples require independent compilation and testing. A compile pass or an illustrative setting does not establish execution correctness or profitability. Any reported performance must be supported by reproducible data and test settings; past results do not predict future returns. Trading involves significant risk of loss. This content is not financial advice.