Aggregating Economic Calendar Events into a Structured MQL5 Data Feed
Introduction
An Expert Advisor that wants to avoid trading around scheduled news has to read the terminal calendar first. The built-in CalendarValueHistory() function returns raw records for every country and every importance level in the requested range. Before an EA can use them for news filtering, the records need an impact filter, a currency filter, a mapping to the symbols that the EA trades, a sort order, and a clear answer to one question: how far away is the next event right now?
This article presents a small package that does this work. The central class is CCalendarFeed. It wraps CalendarValueHistory(), keeps only the events that matter for the universe, stores them in a time-sorted array of CCalendarEvent structures, and answers two queries: GetNextEvent() and IsInNewsWindow().
The calendar functions are not available in the Strategy Tester. Check the documentation for your terminal build before relying on this statement for your own setup. For this reason the feed never calls the calendar functions directly. It reads raw records through an abstract source class, and it reads the current time through an abstract clock class. The package contains a terminal source and a terminal clock for live use, and a fake source and a scripted clock for tests and demonstrations. Everything produced from the fake source is labeled synthetic in this article.
The reader will learn how to turn raw records into a feed. The article also explains how to define the news window and minute rounding, handle failed calls, duplicates, revisions, and inexact-time events, and call the feed from an EA. The package contains eight files: five include files, one indicator, and two scripts. The Program Inventory at the end lists them all. The feed is a filter aid. It is not trading advice.

Figure 1: Architecture of the package. The calendar source, either the terminal source or the fake source, supplies raw records to CCalendarFeed. The symbol mapper supplies the relevant currencies and the clock supplies the reference time. The feed keeps the sorted events, and the queries read them for NewsOverlay, the demo and test scripts, and your own EA.
The Raw Calendar Problem
A raw record is one MqlCalendarValue. It carries the record identifier id, the event identifier event_id, the event time, the reporting period, the revision number, four value fields, and impact_type. It does not carry the event name, the importance, the time mode, or the currency. Those live in two other structures that are reached by identifier: MqlCalendarEvent through CalendarEventById(), and MqlCalendarCountry through CalendarCountryById().
The documentation states that all calendar functions use the trade server time, so the time field of a raw record and the time arguments of CalendarValueHistory() are in the trade server time zone and not in local time. Check the documentation for your terminal build if you rely on this detail.
Two names are easy to confuse. The impact_type field of a raw record describes the potential effect on the currency rate, with the values unset, positive, and negative. The importance of an event, with the values none, low, moderate, and high, is a field of MqlCalendarEvent. This article uses the term impact level for the importance value, and the feed filters on it.
CalendarValueHistory() returns the number of values on success and -1 on failure. The documented errors include ERR_INTERNAL_ERROR, ERR_NOT_ENOUGH_MEMORY, ERR_CALENDAR_TIMEOUT, and ERR_CALENDAR_MORE_DATA. A raw record also has no notion of a window around it, and a list of raw records is not sorted for the question that an EA asks. Figure 2 shows the news window that the feed builds around one event.
Synthetic Example of a News Window

Figure 2: News window for one event that occurs at 13:30:00 (trade server time) with a buffer of 15 minutes. The window opens at 13:15:00 and ends at 13:45:00 (trade server time), both ends included. The five query times are the ones from the worked-example table. The data is synthetic and derived from the formulas, not from a run.
Feed Rules and Theory
The feed applies six rules. All of them are conventions of this package, and the choices marked as heuristics are not facts about the market.
- Impact filter: An event is kept when its impact level is greater than or equal to a minimum. The default minimum is high, which is a heuristic. A lower threshold keeps more events and produces more news windows.
- Currency filter: An event is kept when the currency of its country is one of the relevant currencies, which are the union of the currencies of all symbols in the universe. The comparison is exact after upper casing, so an event whose country has an empty currency is dropped.
- Symbol mapping: The mapper reads the base and profit currencies with SymbolInfoString() and the properties SYMBOL_CURRENCY_BASE and SYMBOL_CURRENCY_PROFIT. For indices, metals, and crypto symbols, a fallback table overrides the terminal. The table is a convention that you must review for your broker, and the package does not claim that every symbol is mapped correctly. A symbol that maps to no currency is skipped and reported in the log.
- Sort order: Events are sorted by ascending time. Events with equal time are ordered by record identifier, so the order is deterministic.
- Minutes to the event: minutes_to_event is floor((event time − reference time)/60). The seconds are the event time minus the reference time, so they are negative after the event. The floor applies to negative values as well: -1 second gives -1 minute, -60 seconds gives -1 minute, and -61 seconds give -2 minutes. The reference time is the time that the feed uses as now, and the field is correct only for the reference time at which it was computed. A query result is therefore always computed for one explicit reference time. The explicit query methods compute the fields from the event times and never read the stored minutes_to_event. The short query methods read the clock, call Recompute() with that time, and then call the explicit form. The stored fields are meant for display and logging.
- News window: The window runs from buffer_minutes before an event to buffer_minutes after it, with both ends included. A reference time is inside the window when the seconds to the event lie between minus and plus the buffer in seconds, inclusive. The test uses seconds and not rounded minutes. The default buffer of 15 minutes is a heuristic.
The next event for a symbol is the first event in the loaded range, in time order, whose time is greater than or equal to the reference time and whose currency belongs to the symbol. An event at exactly the reference time is therefore the next event. When no stored event qualifies, the feed reports found as false. This means only that no such event lies before the end of the loaded range. It does not prove that no event follows, because events after the loaded range were never read.
Worked example: One event occurs at 13:30:00 (trade server time), and the buffer is 15 minutes, or 900 seconds. The window opens at 13:15:00 and ends at 13:45:00 (trade server time). The feed has no other event for the symbol, and all times are on the same day. The data is synthetic.
| Reference time | Next event | Seconds to the event | minutes_to_event | In news window |
|---|---|---|---|---|
| 13:14:59 | the 13:30:00 event | 901 | 15 | false |
| 13:15:00 | the 13:30:00 event | 900 | 15 | true |
| 13:30:00 | the 13:30:00 event | 0 | 0 | true |
| 13:45:00 | none | -900 | -15 | true |
| 13:45:01 | none | -901 | -16 | false |
Row by row: at 901 seconds the floor is 15, but 901 is greater than 900, so the reference time is one second before the window. At 900 seconds the boundary is included. At -900 seconds the end of the window is included. At -901 seconds the quotient is -15.02, the floor is -16, and the reference time is one second after the window.
The first two rows show why the window test must use seconds, because minutes_to_event is 15 in both and only the window flag differs. In the fourth row the next event is none because no stored event lies at or after the reference time, yet the window flag is true, so IsInNewsWindow() looks at past events as well.
The Data Model: CalTypes.mqh
CalTypes.mqh holds the constants, the enumerations, the structures, and two small functions that the rest of the package shares. The constants define the defaults. The lookback and horizon values are heuristics.
//+------------------------------------------------------------------+ //| CalTypes.mqh | //| Data model for the calendar feed (constants and types) | //+------------------------------------------------------------------+ #ifndef CAL_TYPES_MQH #define CAL_TYPES_MQH //--- data model of the calendar feed: constants, enumerations, //--- structures and two small helpers that the other files share //--- time conversion #define CAL_SECONDS_PER_MINUTE 60 // seconds in one minute //--- default settings, all three values are heuristics #define CAL_DEFAULT_BUFFER_MINUTES 15 // buffer of the news window, minutes #define CAL_DEFAULT_LOOKBACK_MINUTES 720 // loaded range starts 12 hours before the reference time #define CAL_DEFAULT_HORIZON_MINUTES 4320 // loaded range ends 72 hours after the reference time //--- array growth #define CAL_ARRAY_RESERVE 64 // reserve for ArrayResize(), limits reallocations //--- impact level of an event: the importance value of the terminal //--- calendar, converted to a type of this package. The impact filter //--- compares these values, so the numeric order must not change enum ENUM_CAL_IMPACT { CAL_IMPACT_NONE = 0, // impact level not set CAL_IMPACT_LOW = 1, // low impact level CAL_IMPACT_MODERATE = 2, // moderate impact level CAL_IMPACT_HIGH = 3 // high impact level };
The status enumeration starts with a value that cannot pass for success. A feed that was never refreshed reports CAL_STATUS_NOT_REFRESHED, and only CAL_STATUS_OK means that the last Refresh() call succeeded and returned raw records. A call that succeeds but returns zero raw records is reported as CAL_STATUS_NO_DATA and is not treated as usable. This is a heuristic: a calendar normally has records for a range of several days, so an empty answer is suspicious.
//--- status of the feed and of a query. CAL_STATUS_NOT_REFRESHED is the //--- initial state, so a feed that was never refreshed cannot pass for //--- success. Only CAL_STATUS_OK means that the answers can be trusted enum ENUM_CAL_STATUS { CAL_STATUS_NOT_REFRESHED = 0, // initial state, never counts as success CAL_STATUS_OK = 1, // last Refresh() succeeded and returned raw records CAL_STATUS_NO_DATA = 2, // the call succeeded but returned no raw records CAL_STATUS_CALL_FAILED = 3, // the source reported a failure, see LastError() CAL_STATUS_NO_UNIVERSE = 4, // no relevant currencies are known CAL_STATUS_RANGE_NOT_COVERED = 5, // the query needs times outside the loaded range CAL_STATUS_SYMBOL_UNKNOWN = 6, // the symbol is not in the universe CAL_STATUS_BAD_ARGUMENT = 7 // invalid argument, or the source or the clock is missing };
The treatment of events without an exact time is a choice. The documentation lists four time modes: an exact time, all day, no time, and tentative. The default of the feed is to drop everything that is not an exact time, because a news window needs a point in time. The alternative keeps those events and marks them with exact_time set to false. Both choices are heuristics.
//--- treatment of events without an exact time (all-day, no time or //--- tentative time mode). A heuristic, the reader may choose the other enum ENUM_CAL_INEXACT_POLICY { CAL_INEXACT_SKIP = 0, // default: drop the event CAL_INEXACT_INCLUDE = 1 // keep the event with exact_time set to false };
The structure CCalendarEvent is the event of the feed. The fields seconds_to_event and minutes_to_event are valid only for the reference time at which they were computed, as described above.
//--- one event of the feed, built from one raw record. The fields //--- seconds_to_event and minutes_to_event are valid only for the //--- reference time at which they were computed struct CCalendarEvent { ulong record_id; // id of the raw record (MqlCalendarValue.id) ulong event_id; // id of the event description (MqlCalendarValue.event_id) datetime time; // event time, trade server time datetime period; // reporting period of the raw record, 0 when none int revision; // revision number of the raw record string name; // event name from the event description string currency; // currency of the country, upper case string country_code; // country code, for example "US" ENUM_CAL_IMPACT impact; // impact level bool exact_time; // false for all-day, no time and tentative time modes long seconds_to_event; // event time minus reference time, negative after the event int minutes_to_event; // floor of seconds_to_event divided by 60 CCalendarEvent() { Reset(); } // constructor //--- clears every field void Reset() { record_id = 0; event_id = 0; time = 0; period = 0; revision = 0; name = ""; currency = ""; country_code = ""; impact = CAL_IMPACT_NONE; exact_time = false; seconds_to_event = 0; minutes_to_event = 0; } };
The structure SCalendarQuery carries the result of a query, including the status. A query that could not be answered has a status other than CAL_STATUS_OK, so a caller can tell "outside every window" from "unknown".
//--- result of a query. The status tells "outside every news window" apart //--- from "unknown": found and in_window mean something only when the //--- status is CAL_STATUS_OK struct SCalendarQuery { ENUM_CAL_STATUS status; // CAL_STATUS_OK only when the query could be answered bool found; // an event was selected bool in_window; // result of IsInNewsWindow() datetime reference_time; // reference time of this answer int buffer_minutes; // buffer of the news window, minutes CCalendarEvent event; // selected event, fields computed for reference_time SCalendarQuery() { Reset(); } // constructor //--- clears every field, the status returns to the initial state void Reset() { status = CAL_STATUS_NOT_REFRESHED; found = false; in_window = false; reference_time = 0; buffer_minutes = 0; event.Reset(); } };
A third structure, SCalFeedStats, holds counters for the last Refresh(): raw records, lookups that failed, and the records dropped by each rule.
//--- counters of the last Refresh(): what was read and why raw records //--- were dropped. Every raw record is counted at most once struct SCalFeedStats { int raw_records; // raw records returned by the source int lookup_failed; // dropped: the event or country lookup failed int below_impact; // dropped: impact level below the minimum int inexact_time; // dropped: no time, or no exact time and the policy is skip int other_currency; // dropped: currency is not a relevant currency int duplicates; // dropped: record id already stored int revisions_dropped; // dropped: stored event has an equal or higher revision int revisions_replaced; // stored events replaced by a higher revision //--- sets every counter to zero void Reset() { raw_records = 0; lookup_failed = 0; below_impact = 0; inexact_time = 0; other_currency = 0; duplicates = 0; revisions_dropped = 0; revisions_replaced = 0; } };
The next block shows the conversion helpers.
//+------------------------------------------------------------------+ //| CalImpactFromImportance | //| Converts the importance value of an event | //| (ENUM_CALENDAR_EVENT_IMPORTANCE) to an impact level. A value | //| that is not listed gives CAL_IMPACT_NONE. | //+------------------------------------------------------------------+ ENUM_CAL_IMPACT CalImpactFromImportance(const int importance) { switch(importance) { case CALENDAR_IMPORTANCE_LOW: return(CAL_IMPACT_LOW); case CALENDAR_IMPORTANCE_MODERATE: return(CAL_IMPACT_MODERATE); case CALENDAR_IMPORTANCE_HIGH: return(CAL_IMPACT_HIGH); } return(CAL_IMPACT_NONE); } //+------------------------------------------------------------------+ //| CalImpactToString | //| Converts an impact level to text for log messages. | //+------------------------------------------------------------------+ string CalImpactToString(const ENUM_CAL_IMPACT impact) { switch(impact) { case CAL_IMPACT_LOW: return("low"); case CAL_IMPACT_MODERATE: return("moderate"); case CAL_IMPACT_HIGH: return("high"); } return("none"); } //+------------------------------------------------------------------+ //| CalStatusToString | //| Converts a status to text for log messages. | //+------------------------------------------------------------------+ string CalStatusToString(const ENUM_CAL_STATUS status) { switch(status) { case CAL_STATUS_NOT_REFRESHED: return("NOT_REFRESHED"); case CAL_STATUS_OK: return("OK"); case CAL_STATUS_NO_DATA: return("NO_DATA"); case CAL_STATUS_CALL_FAILED: return("CALL_FAILED"); case CAL_STATUS_NO_UNIVERSE: return("NO_UNIVERSE"); case CAL_STATUS_RANGE_NOT_COVERED: return("RANGE_NOT_COVERED"); case CAL_STATUS_SYMBOL_UNKNOWN: return("SYMBOL_UNKNOWN"); case CAL_STATUS_BAD_ARGUMENT: return("BAD_ARGUMENT"); } return("UNKNOWN"); }
CalFloorMinutes() implements the rounding rule. The operator / truncates toward zero, and the remainder has the sign of the dividend, so the function corrects negative values that have a remainder.
//+------------------------------------------------------------------+ //| CalFloorMinutes | //+------------------------------------------------------------------+ int CalFloorMinutes(const long seconds) { long minutes = seconds / CAL_SECONDS_PER_MINUTE; //--- the remainder has the sign of the dividend, so it is negative //--- exactly when the truncated quotient is one minute too high if(seconds % CAL_SECONDS_PER_MINUTE < 0) minutes--; return((int)minutes); }
CalWindowContains() is the exact window test. Both ends are included.
//+------------------------------------------------------------------+ //| CalWindowContains | //| News window test on seconds, not on rounded minutes. True when | //| seconds_to_event lies between -buffer_seconds and +buffer_seconds| //| and both ends are included. | //+------------------------------------------------------------------+ bool CalWindowContains(const long seconds_to_event, const long buffer_seconds) { return(seconds_to_event <= buffer_seconds && seconds_to_event >= -buffer_seconds); }
The Calendar Source: Clock.mqh and CalendarSource.mqh
The feed depends on an abstract clock and an abstract source. The clock comes first. The abstract class has a pure virtual method and a virtual destructor.
//+------------------------------------------------------------------+ //| Clock.mqh | //| Abstract clock, terminal clock and scripted clock | //+------------------------------------------------------------------+ #ifndef CAL_CLOCK_MQH #define CAL_CLOCK_MQH //+------------------------------------------------------------------+ //| CClock | //| Abstract clock. The feed reads the clock time only through | //| this interface, so a test can inject a scripted time. | //+------------------------------------------------------------------+ class CClock { public: //--- virtual destructor: a derived object can be deleted through a base pointer virtual ~CClock() {} virtual datetime Now() const = 0; // clock time, trade server time };
The terminal clock returns TimeTradeServer(), which is the time zone that the documentation gives for calendar times.
//+------------------------------------------------------------------+ //| CTerminalClock | //| Clock for live use. Returns TimeTradeServer(), the time zone | //| that the documentation gives for the calendar times. | //+------------------------------------------------------------------+ class CTerminalClock : public CClock { public: virtual datetime Now() const { return(TimeTradeServer()); } };
The scripted clock returns a time that the test or the demo sets. This is the injected clock.
//+------------------------------------------------------------------+ //| CScriptedClock | //| Injected clock for tests and demonstrations. It returns the time | //| that the program sets and never moves by itself. | //+------------------------------------------------------------------+ class CScriptedClock : public CClock { private: datetime m_now; // time returned by Now() public: CScriptedClock() : m_now(0) {} void Set(const datetime value) { m_now = value; } // jumps to a time void Advance(const int seconds) { m_now += seconds; } // moves forward, or back if negative virtual datetime Now() const { return(m_now); } };
The abstract source mirrors the three calendar functions that the feed needs. Each method returns true on success and reports an error code through the last parameter.
//+------------------------------------------------------------------+ //| CalendarSource.mqh | //| Abstract source, terminal source and fake source | //+------------------------------------------------------------------+ #ifndef CAL_SOURCE_MQH #define CAL_SOURCE_MQH //+------------------------------------------------------------------+ //| CCalendarSource | //| Abstract source of raw records and of the lookups that the feed | //| needs. The feed reads the calendar only through this interface, | //| because the calendar functions do not work in the Strategy | //| Tester. Each method returns true on success. On failure it | //| returns false and stores the error code in error_code. | //+------------------------------------------------------------------+ class CCalendarSource { public: //--- virtual destructor: a derived object can be deleted through a base pointer virtual ~CCalendarSource() {} //--- raw records with a time in the range from..to, trade server time virtual bool FetchValues(const datetime from, const datetime to, MqlCalendarValue &values[], int &error_code) = 0; //--- event description (name, importance, time mode, country) by event id virtual bool FetchEvent(const ulong event_id, MqlCalendarEvent &info, int &error_code) = 0; //--- country description (code, currency) by country id virtual bool FetchCountry(const long country_id, MqlCalendarCountry &country, int &error_code) = 0; };
The terminal source wraps the documented functions. CalendarValueHistory() returns the number of values or -1, so the wrapper treats a negative result as a failure and reads the error code with GetLastError(). The class continues in the next block.
//+------------------------------------------------------------------+ //| CTerminalCalendarSource | //| Source for live use. Wraps CalendarValueHistory(), | //| CalendarEventById() and CalendarCountryById(). | //+------------------------------------------------------------------+ class CTerminalCalendarSource : public CCalendarSource { public: //--- FetchValues: wraps CalendarValueHistory() for all countries. The //--- function returns the number of raw records, or -1 on failure. virtual bool FetchValues(const datetime from, const datetime to, MqlCalendarValue &values[], int &error_code) { ResetLastError(); const int count = CalendarValueHistory(values, from, to); //--- -1 is a failure: keep the error code and return no raw records if(count < 0) { error_code = GetLastError(); ArrayResize(values, 0); return(false); } //--- a count of 0 is a success, the feed decides what an empty answer means error_code = 0; return(true); }
CalendarEventById() and CalendarCountryById() return a boolean. The wrappers copy the error code in the same way. The closing brace ends the class.
//--- FetchEvent: wraps CalendarEventById(), which returns true or false. virtual bool FetchEvent(const ulong event_id, MqlCalendarEvent &info, int &error_code) { ResetLastError(); if(CalendarEventById(event_id, info)) { error_code = 0; return(true); } error_code = GetLastError(); return(false); } //--- FetchCountry: wraps CalendarCountryById(), which returns true or //--- false. virtual bool FetchCountry(const long country_id, MqlCalendarCountry &country, int &error_code) { ResetLastError(); if(CalendarCountryById(country_id, country)) { error_code = 0; return(true); } error_code = GetLastError(); return(false); } };
The fake source keeps scripted countries, events, and values, and it can be told to fail. It also counts the calls, so a test can check the cost statements made later in this article. The class continues in the next two blocks.
//+------------------------------------------------------------------+ //| CFakeCalendarSource | //| Fake source for tests and demonstrations. It returns scripted | //| data, can be told to fail, and counts its calls so that a test | //| can check the cost of Refresh(). Data from this class is | //| synthetic. | //+------------------------------------------------------------------+ class CFakeCalendarSource : public CCalendarSource { private: //--- scripted data MqlCalendarValue m_values[]; // scripted raw records MqlCalendarEvent m_events[]; // scripted event descriptions MqlCalendarCountry m_countries[]; // scripted country descriptions //--- scripted failure of FetchValues() bool m_fail_values; // true: FetchValues() fails int m_fail_code; // error code reported by the failure //--- call counters int m_values_calls; // number of FetchValues() calls int m_event_calls; // number of FetchEvent() calls int m_country_calls; // number of FetchCountry() calls public: CFakeCalendarSource() : m_fail_values(false), m_fail_code(0), m_values_calls(0), m_event_calls(0), m_country_calls(0) {} //--- read access to the call counters int ValuesCalls() const { return(m_values_calls); } int EventCalls() const { return(m_event_calls); } int CountryCalls() const { return(m_country_calls); } //--- scripted failure: from now on FetchValues() fails with this code void FailValues(const int code) { m_fail_values = true; m_fail_code = code; } void ClearFailure() { m_fail_values = false; m_fail_code = 0; }
The three Add methods fill the scripted tables. The fake does not model every field of the terminal structures. It fills only the fields that the feed reads.
//--- AddCountry: adds a country description. The name is set to the code. void AddCountry(const long id, const string code, const string currency) { const int n = ArraySize(m_countries); ArrayResize(m_countries, n + 1); m_countries[n].id = (ulong)id; m_countries[n].code = code; m_countries[n].currency = currency; m_countries[n].name = code; } //--- AddEvent: adds an event description. Only the fields that the feed //--- reads are set. void AddEvent(const ulong id, const string name, const ENUM_CALENDAR_EVENT_IMPORTANCE importance, const ENUM_CALENDAR_EVENT_TIMEMODE time_mode, const long country_id) { const int n = ArraySize(m_events); ArrayResize(m_events, n + 1); m_events[n].id = id; m_events[n].name = name; m_events[n].importance = importance; m_events[n].time_mode = time_mode; m_events[n].country_id = (ulong)country_id; m_events[n].type = CALENDAR_TYPE_EVENT; } //--- AddValue: adds a raw record. Only the fields that the feed reads are //--- set, the value fields stay empty. void AddValue(const ulong id, const ulong event_id, const datetime time, const datetime period, const int revision) { const int n = ArraySize(m_values); ArrayResize(m_values, n + 1); m_values[n].id = id; m_values[n].event_id = event_id; m_values[n].time = time; m_values[n].period = period; m_values[n].revision = revision; }
The fake FetchValues() honors the time range, like the real call, and returns an empty array with success when nothing matches. The lookups return a failure with ERR_CALENDAR_NO_DATA for an unknown identifier. The documented description of that code is that a country was not found, so for an unknown event identifier the fake uses it only as a stand-in failure code.
//--- FetchValues: returns the scripted raw records with from <= time <= //--- to, in the order they were added. An empty result is a success. virtual bool FetchValues(const datetime from, const datetime to, MqlCalendarValue &values[], int &error_code) { m_values_calls++; ArrayResize(values, 0); //--- scripted failure if(m_fail_values) { error_code = m_fail_code; return(false); } //--- keep the raw records inside the requested range const int total = ArraySize(m_values); for(int i = 0; i < total; i++) { if(m_values[i].time < from || m_values[i].time > to) continue; const int n = ArraySize(values); ArrayResize(values, n + 1); values[n] = m_values[i]; } error_code = 0; return(true); } //--- FetchEvent: returns the scripted event description. An unknown id //--- fails with ERR_CALENDAR_NO_DATA, used here only as a stand-in code. virtual bool FetchEvent(const ulong event_id, MqlCalendarEvent &info, int &error_code) { m_event_calls++; const int total = ArraySize(m_events); for(int i = 0; i < total; i++) if(m_events[i].id == event_id) { info = m_events[i]; error_code = 0; return(true); } error_code = ERR_CALENDAR_NO_DATA; return(false); } //--- FetchCountry: returns the scripted country description. An unknown //--- id fails with ERR_CALENDAR_NO_DATA, the code whose documented //--- description is "country not found". virtual bool FetchCountry(const long country_id, MqlCalendarCountry &country, int &error_code) { m_country_calls++; const int total = ArraySize(m_countries); for(int i = 0; i < total; i++) if((long)m_countries[i].id == country_id) { country = m_countries[i]; error_code = 0; return(true); } error_code = ERR_CALENDAR_NO_DATA; return(false); } };
The Symbol Mapper
CSymbolMapper has no data members, so it is stateless. MapFromTable() reads the fallback table, MapFromTerminal() reads the base and profit currencies, and Map() prefers the table. The table format is SYMBOL:CUR1,CUR2;SYMBOL2:CUR.
//+------------------------------------------------------------------+ //| SymbolMapper.mqh | //| Stateless mapping from a symbol to its currencies | //+------------------------------------------------------------------+ #ifndef CAL_SYMBOL_MAPPER_MQH #define CAL_SYMBOL_MAPPER_MQH //+------------------------------------------------------------------+ //| CSymbolMapper | //| Stateless mapping from a symbol to its currencies. The fallback | //| table has priority, the terminal properties are used when the | //| table has no entry. The table is a convention that the reader | //| must review for the broker in use. | //+------------------------------------------------------------------+ class CSymbolMapper { private: //--- helpers string Normalize(const string text) const; // trims and upper cases bool AddUnique(string &list[], const string currency) const; // skips empty and repeated values public: //--- mapping, each method returns the number of currencies found int MapFromTable(const string symbol, const string table, string ¤cies[]) const; int MapFromTerminal(const string symbol, string ¤cies[]) const; int Map(const string symbol, const string table, string ¤cies[]) const; };
The helper Normalize() trims and upper cases text. The helper AddUnique() skips empty strings and duplicates.
//+------------------------------------------------------------------+ //| Normalize | //| Trims both ends and converts to upper case, so that comparisons | //| do not depend on spaces or letter case. | //+------------------------------------------------------------------+ string CSymbolMapper::Normalize(const string text) const { string value = text; StringTrimLeft(value); StringTrimRight(value); StringToUpper(value); return(value); } //+------------------------------------------------------------------+ //| AddUnique | //| Appends a currency to the list. Returns false and changes | //| nothing for an empty string or a currency already in the list. | //+------------------------------------------------------------------+ bool CSymbolMapper::AddUnique(string &list[], const string currency) const { if(currency == "") return(false); //--- linear search, the list has at most a few entries const int total = ArraySize(list); for(int i = 0; i < total; i++) if(list[i] == currency) return(false); ArrayResize(list, total + 1); list[total] = currency; return(true); }
MapFromTable() splits the table with StringSplit() and matches the symbol name exactly after normalization. A broker suffix such as.m needs its own entry, which is a limitation of this convention.
//+------------------------------------------------------------------+ //| MapFromTable | //| Reads the currencies of a symbol from the fallback table. | //| Format: "SYMBOL:CUR1,CUR2;SYMBOL2:CUR". The symbol must match | //| exactly after trimming and upper casing, so a broker suffix | //| needs its own entry. Returns 0 when the symbol is not listed. | //+------------------------------------------------------------------+ int CSymbolMapper::MapFromTable(const string symbol, const string table, string ¤cies[]) const { ArrayResize(currencies, 0); const string wanted = Normalize(symbol); //--- split the table into entries, one per symbol string entries[]; const int count = StringSplit(table, ';', entries); for(int i = 0; i < count; i++) { //--- an entry without a colon or without a symbol name is ignored const int colon = StringFind(entries[i], ":"); if(colon <= 0) continue; if(Normalize(StringSubstr(entries[i], 0, colon)) != wanted) continue; //--- the entry matches: split the currency list and stop searching string parts[]; const int n = StringSplit(StringSubstr(entries[i], colon + 1), ',', parts); for(int j = 0; j < n; j++) AddUnique(currencies, Normalize(parts[j])); break; } return(ArraySize(currencies)); }
MapFromTerminal() and Map() complete the class. For a currency pair the two documented properties give the two currencies. For an index, a metal, or a crypto symbol the values depend on the broker, so the table exists.
//+------------------------------------------------------------------+ //| MapFromTerminal | //| Reads the base currency and the profit currency of the symbol | //| from the terminal. For a currency pair these are the two | //| currencies. For an index, a metal or a crypto symbol the values | //| depend on the broker, so check them or use the fallback table. | //+------------------------------------------------------------------+ int CSymbolMapper::MapFromTerminal(const string symbol, string ¤cies[]) const { ArrayResize(currencies, 0); AddUnique(currencies, Normalize(SymbolInfoString(symbol, SYMBOL_CURRENCY_BASE))); AddUnique(currencies, Normalize(SymbolInfoString(symbol, SYMBOL_CURRENCY_PROFIT))); return(ArraySize(currencies)); } //+------------------------------------------------------------------+ //| Map | //| Maps a symbol to its currencies. The fallback table is tried | //| first, then the terminal. Returns 0 when both give nothing. | //+------------------------------------------------------------------+ int CSymbolMapper::Map(const string symbol, const string table, string ¤cies[]) const { if(MapFromTable(symbol, table, currencies) > 0) return(ArraySize(currencies)); return(MapFromTerminal(symbol, currencies)); }
The overlay indicator exposes the table as an input. The default content below is a convention for common names, and the reader must review it for the broker in use. It is not a claim that these symbols exist or that the mapping is right for every broker.
//+------------------------------------------------------------------+ //| Settings of the loaded range, the refresh period, the fallback | //| table and the color of the lines. | //+------------------------------------------------------------------+ input int InpLookbackHours = 24; // hours before the reference time input int InpHorizonHours = 72; // hours after the reference time input int InpRefreshMinutes = 15; // refresh period, minutes input string InpFallbackTable = "US30:USD;US500:USD;USTEC:USD;DE40:EUR;UK100:GBP;JP225:JPY;XAUUSD:USD;XAGUSD:USD;BTCUSD:USD"; input color InpLineColor = clrCrimson; // color of the lines and the labels //--- prefix of every object that this indicator creates and may delete #define OVERLAY_PREFIX "NEWSOV_" //--- objects of the indicator, created in OnInit(), deleted in OnDeinit() CTerminalCalendarSource *g_source = NULL; // source for live use CTerminalClock *g_clock = NULL; // clock for live use CCalendarFeed *g_feed = NULL; // feed of the chart symbol
The Feed: CCalendarFeed
The class declaration lists the private helpers and the public methods. The comments separate the methods that change state from the methods that do not. The methods that change state are Init(), SetUniverse(), SetFilter(), SetRange(), Refresh(), Recompute(), and the two short query forms that call Recompute(). The explicit query forms, AffectsSymbol(), GetEventAt(), GetStats(), LogSummary(), and the simple getters do not change state.
The feed does not own the source or the clock. The program that creates them deletes them.
First, two small structures cache the lookups for event metadata and country metadata during one refresh.
//+------------------------------------------------------------------+ //| CalendarFeed.mqh | //| Structured, time-sorted feed built from raw records | //+------------------------------------------------------------------+ #ifndef CAL_FEED_MQH #define CAL_FEED_MQH #include "CalTypes.mqh" #include "Clock.mqh" #include "CalendarSource.mqh" #include "SymbolMapper.mqh" //--- cached lookup of one event description. found is false when the //--- lookup failed, so the same failure is not requested again struct SCalEventMeta { ulong event_id; // id of the event description bool found; // true when the lookup succeeded string name; // event name int importance; // importance value, ENUM_CALENDAR_EVENT_IMPORTANCE int time_mode; // time mode, ENUM_CALENDAR_EVENT_TIMEMODE long country_id; // id of the country of the event }; //--- cached lookup of one country description, same rule as above struct SCalCountryMeta { long country_id; // id of the country bool found; // true when the lookup succeeded string currency; // currency, upper case string code; // country code }; //+------------------------------------------------------------------+ //| CCalendarFeed | //| Structured feed of calendar events. Refresh() reads the raw | //| records from the source, drops the ones that the rules reject | //| and stores the rest as events sorted by time. The queries answer | //| from the stored events for one reference time. | //| Rule: minutes_to_event is correct only for the reference time at | //| which it was computed. A query method that takes a reference | //| time computes the fields again for the event it returns. A short | //| query form reads the clock and calls Recompute() first. | //| The source and the clock belong to the caller, not to the feed. | //+------------------------------------------------------------------+ class CCalendarFeed { private: //--- dependencies, owned by the caller CCalendarSource *m_source; // source of raw records and lookups CClock *m_clock; // source of the clock time CSymbolMapper m_mapper; // symbol to currencies //--- universe string m_symbols[]; // symbols of the universe string m_symbol_cur[]; // currencies of each symbol as ",EUR,USD,", same index as m_symbols string m_currencies[]; // relevant currencies, no repeated currencies //--- filter and loaded range settings ENUM_CAL_IMPACT m_min_impact; // events below this impact level are dropped ENUM_CAL_INEXACT_POLICY m_inexact_policy; // treatment of events without an exact time int m_lookback_minutes; // loaded range starts this long before the clock time int m_horizon_minutes; // loaded range ends this long after the clock time //--- state of the last Refresh() datetime m_range_from; // start of the loaded range, trade server time datetime m_range_to; // end of the loaded range datetime m_reference_time; // reference time of the last Recompute() datetime m_last_refresh; // clock time of the last Refresh() that reached the source ENUM_CAL_STATUS m_status; // status of the feed int m_last_error; // error code of the last failed source call, 0 if none CCalendarEvent m_events[]; // events sorted by time, then by record id int m_count; // number of stored events SCalEventMeta m_event_cache[]; // event lookups of this refresh, failures included SCalCountryMeta m_country_cache[]; // country lookups of this refresh, failures included SCalFeedStats m_stats; // counters of the last Refresh() //--- storage helpers void ClearEvents(); // removes events, resets counters void AddCurrency(const string currency); // adds a relevant currency once bool IsRelevantCurrency(const string currency) const; int FindSymbol(const string symbol) const; // index in the universe, -1 if absent bool AffectsSymbolIndex(const CCalendarEvent &ev, const int symbol_index) const; //--- lookups of the refresh, both return an index into a cache int LoadEventMeta(const ulong event_id); int LoadCountryMeta(const long country_id); //--- rules applied to one raw record, then the sorted insert void AcceptRecord(const MqlCalendarValue &raw); void InsertEvent(const CCalendarEvent &ev); void RemoveAt(const int index); //--- common checks of the explicit query forms bool PrepareQuery(const string symbol, const datetime reference_time, const int buffer_minutes, SCalendarQuery &result, int &symbol_index) const; public: CCalendarFeed(); //--- setup, these methods also change the state of the feed bool Init(CCalendarSource *source, CClock *clock); bool SetUniverse(const string &symbols[], const string fallback_table); void SetFilter(const ENUM_CAL_IMPACT min_impact, const ENUM_CAL_INEXACT_POLICY policy); void SetRange(const int lookback_minutes, const int horizon_minutes); //--- methods that change state bool Refresh(); // reads the source, rebuilds the events void Recompute(const datetime reference_time); // updates the time fields of all events bool GetNextEvent(const string symbol, SCalendarQuery &result); // short form, reads the clock bool IsInNewsWindow(const string symbol, const int buffer_minutes); // short form, reads the clock //--- methods that do not change state bool GetNextEvent(const string symbol, const datetime reference_time, SCalendarQuery &result) const; bool IsInNewsWindow(const string symbol, const int buffer_minutes, const datetime reference_time, SCalendarQuery &result) const; bool AffectsSymbol(const CCalendarEvent &ev, const string symbol) const; bool GetEventAt(const int index, CCalendarEvent &ev) const; int Count() const { return(m_count); } ENUM_CAL_STATUS Status() const { return(m_status); } int LastError() const { return(m_last_error); } bool IsUsable() const { return(m_status == CAL_STATUS_OK); } datetime RangeFrom() const { return(m_range_from); } datetime RangeTo() const { return(m_range_to); } datetime ReferenceTime() const { return(m_reference_time); } void GetStats(SCalFeedStats &stats) const { stats = m_stats; } void LogSummary() const; };
The constructor sets the heuristic defaults. Init() stores the source and the clock, and SetFilter() and SetRange() change the filter and the range.
//+------------------------------------------------------------------+ //| CCalendarFeed constructor | //| Sets the heuristic defaults. The status starts as | //| CAL_STATUS_NOT_REFRESHED, so the feed cannot pass for success | //| before Refresh(). | //+------------------------------------------------------------------+ CCalendarFeed::CCalendarFeed() { m_source = NULL; m_clock = NULL; m_min_impact = CAL_IMPACT_HIGH; // heuristic default m_inexact_policy = CAL_INEXACT_SKIP; // heuristic default m_lookback_minutes = CAL_DEFAULT_LOOKBACK_MINUTES; m_horizon_minutes = CAL_DEFAULT_HORIZON_MINUTES; m_range_from = 0; m_range_to = 0; m_reference_time = 0; m_last_refresh = 0; m_status = CAL_STATUS_NOT_REFRESHED; m_last_error = 0; m_count = 0; m_stats.Reset(); } //+------------------------------------------------------------------+ //| Init | //| Stores the source and the clock. The feed does not delete them. | //| Returns false with CAL_STATUS_BAD_ARGUMENT when one is NULL. | //+------------------------------------------------------------------+ bool CCalendarFeed::Init(CCalendarSource *source, CClock *clock) { if(source == NULL || clock == NULL) { m_status = CAL_STATUS_BAD_ARGUMENT; return(false); } m_source = source; m_clock = clock; return(true); } //+------------------------------------------------------------------+ //| SetFilter | //| Sets the minimum impact level and the treatment of events | //| without an exact time. Takes effect at the next Refresh(). | //+------------------------------------------------------------------+ void CCalendarFeed::SetFilter(const ENUM_CAL_IMPACT min_impact, const ENUM_CAL_INEXACT_POLICY policy) { m_min_impact = min_impact; m_inexact_policy = policy; } //+------------------------------------------------------------------+ //| SetRange | //| Sets how far before and after the clock time Refresh() loads | //| raw records, in minutes. Negative values become 0. Takes effect | //| at the next Refresh(). | //+------------------------------------------------------------------+ void CCalendarFeed::SetRange(const int lookback_minutes, const int horizon_minutes) { m_lookback_minutes = MathMax(lookback_minutes, 0); m_horizon_minutes = MathMax(horizon_minutes, 0); }
SetUniverse() maps every symbol and builds the relevant currencies. It stores one string per symbol in the form,EUR,USD,, so the test for a currency is a substring search. It clears the events and resets the status to not refreshed, because the stored events no longer match a new universe. A symbol without currencies is skipped with a log line. If no currency remains, the status becomes CAL_STATUS_NO_UNIVERSE.
//+------------------------------------------------------------------+ //| AddCurrency | //| Adds a currency to the relevant currencies once. | //+------------------------------------------------------------------+ void CCalendarFeed::AddCurrency(const string currency) { const int total = ArraySize(m_currencies); for(int i = 0; i < total; i++) if(m_currencies[i] == currency) return; ArrayResize(m_currencies, total + 1); m_currencies[total] = currency; } //+------------------------------------------------------------------+ //| SetUniverse | //| Maps every symbol to its currencies and builds the relevant | //| currencies. A symbol without currencies is skipped and logged. | //| The stored events no longer match a new universe, so they are | //| cleared and the status returns to CAL_STATUS_NOT_REFRESHED. | //| Returns false with CAL_STATUS_NO_UNIVERSE when no currency | //| remains. | //+------------------------------------------------------------------+ bool CCalendarFeed::SetUniverse(const string &symbols[], const string fallback_table) { ArrayResize(m_symbols, 0); ArrayResize(m_symbol_cur, 0); ArrayResize(m_currencies, 0); ClearEvents(); m_status = CAL_STATUS_NOT_REFRESHED; const int total = ArraySize(symbols); for(int i = 0; i < total; i++) { string list[]; const int n = m_mapper.Map(symbols[i], fallback_table, list); if(n <= 0) { PrintFormat("CCalendarFeed: no currencies mapped for %s, symbol skipped", symbols[i]); continue; } //--- store the currencies of the symbol as ",EUR,USD,". The commas //--- on both sides let AffectsSymbolIndex() search for ",EUR," //--- without matching a part of another code string joined = ","; for(int j = 0; j < n; j++) { joined += list[j] + ","; AddCurrency(list[j]); } const int k = ArraySize(m_symbols); ArrayResize(m_symbols, k + 1); ArrayResize(m_symbol_cur, k + 1); m_symbols[k] = symbols[i]; m_symbol_cur[k] = joined; } if(ArraySize(m_currencies) == 0) { m_status = CAL_STATUS_NO_UNIVERSE; return(false); } return(true); }
The lookup helpers are short. AffectsSymbol() is public so that the overlay can ask whether an event belongs to the chart symbol.
//+------------------------------------------------------------------+ //| IsRelevantCurrency | //| True when the currency is one of the relevant currencies. | //+------------------------------------------------------------------+ bool CCalendarFeed::IsRelevantCurrency(const string currency) const { const int total = ArraySize(m_currencies); for(int i = 0; i < total; i++) if(m_currencies[i] == currency) return(true); return(false); } //+------------------------------------------------------------------+ //| FindSymbol | //| Index of a symbol in the universe, or -1 when it is not there. | //+------------------------------------------------------------------+ int CCalendarFeed::FindSymbol(const string symbol) const { const int total = ArraySize(m_symbols); for(int i = 0; i < total; i++) if(m_symbols[i] == symbol) return(i); return(-1); } //+------------------------------------------------------------------+ //| AffectsSymbolIndex | //| True when the currency of the event is one of the currencies of | //| the symbol at symbol_index. | //+------------------------------------------------------------------+ bool CCalendarFeed::AffectsSymbolIndex(const CCalendarEvent &ev, const int symbol_index) const { if(symbol_index < 0 || symbol_index >= ArraySize(m_symbol_cur)) return(false); return(StringFind(m_symbol_cur[symbol_index], "," + ev.currency + ",") >= 0); } //+------------------------------------------------------------------+ //| AffectsSymbol | //| Public form of AffectsSymbolIndex(). Returns false for a symbol | //| that is not in the universe. | //+------------------------------------------------------------------+ bool CCalendarFeed::AffectsSymbol(const CCalendarEvent &ev, const string symbol) const { return(AffectsSymbolIndex(ev, FindSymbol(symbol))); }
LoadEventMeta() and LoadCountryMeta() read the event description and the country description through the source. A failed lookup is cached as well, so the same identifier is never requested twice during one refresh.
//+------------------------------------------------------------------+ //| LoadEventMeta | //| Returns the index of the cached event description. The first | //| request calls the source, a failed lookup is cached as well. | //+------------------------------------------------------------------+ int CCalendarFeed::LoadEventMeta(const ulong event_id) { //--- cache hit: no call to the source const int size = ArraySize(m_event_cache); for(int i = 0; i < size; i++) if(m_event_cache[i].event_id == event_id) return(i); //--- cache miss: start with a "not found" entry SCalEventMeta meta; meta.event_id = event_id; meta.found = false; meta.name = ""; meta.importance = 0; meta.time_mode = 0; meta.country_id = 0; //--- one call to the source, the error code is not needed here MqlCalendarEvent info; int error = 0; if(m_source.FetchEvent(event_id, info, error)) { meta.found = true; meta.name = info.name; meta.importance = (int)info.importance; meta.time_mode = (int)info.time_mode; meta.country_id = (long)info.country_id; } ArrayResize(m_event_cache, size + 1, CAL_ARRAY_RESERVE); m_event_cache[size] = meta; return(size); } //+------------------------------------------------------------------+ //| LoadCountryMeta | //| Returns the index of the cached country description. Same rule | //| as LoadEventMeta(). The currency is stored in upper case, to | //| match the relevant currencies. | //+------------------------------------------------------------------+ int CCalendarFeed::LoadCountryMeta(const long country_id) { //--- cache hit: no call to the source const int size = ArraySize(m_country_cache); for(int i = 0; i < size; i++) if(m_country_cache[i].country_id == country_id) return(i); //--- cache miss: start with a "not found" entry SCalCountryMeta meta; meta.country_id = country_id; meta.found = false; meta.currency = ""; meta.code = ""; //--- one call to the source, the error code is not needed here MqlCalendarCountry country; int error = 0; if(m_source.FetchCountry(country_id, country, error)) { meta.found = true; meta.currency = country.currency; meta.code = country.code; StringToUpper(meta.currency); } ArrayResize(m_country_cache, size + 1, CAL_ARRAY_RESERVE); m_country_cache[size] = meta; return(size); }
AcceptRecord() applies the rules in a fixed order: the time check, the event lookup, the impact filter, the time mode, the country lookup, and the currency filter. Only the time check needs no lookup, so it comes first. The country lookup comes last, after the filters that need only the event description. Every drop increments one counter.
//+------------------------------------------------------------------+ //| AcceptRecord | //+------------------------------------------------------------------+ void CCalendarFeed::AcceptRecord(const MqlCalendarValue &raw) { //--- a raw record without a time cannot be placed on the time axis if(raw.time <= 0) { m_stats.inexact_time++; return; } //--- event description: name, importance, time mode, country const int mi = LoadEventMeta(raw.event_id); if(!m_event_cache[mi].found) { m_stats.lookup_failed++; return; } //--- impact filter const ENUM_CAL_IMPACT impact = CalImpactFromImportance(m_event_cache[mi].importance); if(impact < m_min_impact) { m_stats.below_impact++; return; } //--- only CALENDAR_TIMEMODE_DATETIME has an exact time. The other modes //--- (all-day, no time, tentative) follow the inexact policy const bool exact = (m_event_cache[mi].time_mode == CALENDAR_TIMEMODE_DATETIME); if(!exact && m_inexact_policy == CAL_INEXACT_SKIP) { m_stats.inexact_time++; return; } //--- country description: currency and code const int ci = LoadCountryMeta(m_event_cache[mi].country_id); if(!m_country_cache[ci].found) { m_stats.lookup_failed++; return; } //--- currency filter if(!IsRelevantCurrency(m_country_cache[ci].currency)) { m_stats.other_currency++; return; } //--- the raw record passed every rule: build the event and store it CCalendarEvent ev; ev.record_id = raw.id; ev.event_id = raw.event_id; ev.time = raw.time; ev.period = raw.period; ev.revision = raw.revision; ev.name = m_event_cache[mi].name; ev.currency = m_country_cache[ci].currency; ev.country_code = m_country_cache[ci].code; ev.impact = impact; ev.exact_time = exact; InsertEvent(ev); }
InsertEvent() handles duplicates and revisions before inserting into the sorted array. A known record identifier is treated as a duplicate and is dropped. If period is set, (event_id, period) identifies a release: a higher revision replaces the stored event, and an equal or lower revision is dropped. If period is not set, events are not merged.
//+------------------------------------------------------------------+ //| InsertEvent | //| Stores an event in the sorted array. Duplicate rule: the same | //| record id is dropped. Revision rule (a heuristic): when the | //| period is set, event id and period identify one release. A | //| higher revision replaces the stored event, an equal or lower | //| one is dropped. Without a period, events are never merged. | //+------------------------------------------------------------------+ void CCalendarFeed::InsertEvent(const CCalendarEvent &ev) { //--- look for a duplicate or an earlier revision of the same release for(int i = 0; i < m_count; i++) { if(m_events[i].record_id == ev.record_id) { m_stats.duplicates++; return; } if(ev.period > 0 && m_events[i].event_id == ev.event_id && m_events[i].period == ev.period) { if(ev.revision > m_events[i].revision) { //--- newer revision: remove the stored event and insert this one RemoveAt(i); m_stats.revisions_replaced++; break; } m_stats.revisions_dropped++; return; } } //--- sorted insert: order by time, then by record id, so the order is //--- deterministic. Grow the array, then move later events up by one //--- position until the gap is at the right place ArrayResize(m_events, m_count + 1, CAL_ARRAY_RESERVE); int pos = m_count; while(pos > 0 && (ev.time < m_events[pos - 1].time || (ev.time == m_events[pos - 1].time && ev.record_id < m_events[pos - 1].record_id))) { m_events[pos] = m_events[pos - 1]; pos--; } m_events[pos] = ev; m_count++; } //+------------------------------------------------------------------+ //| RemoveAt | //| Removes the event at index and keeps the order of the others. | //+------------------------------------------------------------------+ void CCalendarFeed::RemoveAt(const int index) { for(int i = index; i < m_count - 1; i++) m_events[i] = m_events[i + 1]; m_count--; ArrayResize(m_events, m_count, CAL_ARRAY_RESERVE); } //+------------------------------------------------------------------+ //| ClearEvents | //| Removes all events and resets the counters. | //+------------------------------------------------------------------+ void CCalendarFeed::ClearEvents() { ArrayResize(m_events, 0); m_count = 0; m_stats.Reset(); }
Refresh() is the only method that calls the source for values. It clears the events and the caches, reads the clock, computes the range, and makes one call. A failed call sets CAL_STATUS_CALL_FAILED and keeps the error code. A call that returns zero raw records sets CAL_STATUS_NO_DATA. Only a call that returns records and finishes the loop sets CAL_STATUS_OK. A failed or empty refresh leaves the event array empty, so the feed never serves events from an earlier refresh as if they were current. The last step is Recompute() with the time that the refresh used.
//+------------------------------------------------------------------+ //| Refresh | //| Rebuilds the events from the source with one FetchValues() call. | //| The loaded range is the clock time minus the lookback up to the | //| clock time plus the horizon. The old events are removed first, | //| so a failed or empty refresh never leaves stale events that | //| look current. Returns true only when the status is | //| CAL_STATUS_OK. At the end Recompute() uses the same clock time. | //+------------------------------------------------------------------+ bool CCalendarFeed::Refresh() { m_last_error = 0; //--- the feed cannot work without a source and a clock if(m_source == NULL || m_clock == NULL) { m_status = CAL_STATUS_BAD_ARGUMENT; return(false); } //--- nothing to filter by when the universe is empty if(ArraySize(m_currencies) == 0) { m_status = CAL_STATUS_NO_UNIVERSE; return(false); } //--- start clean: events, counters and the caches of the last refresh ClearEvents(); ArrayResize(m_event_cache, 0); ArrayResize(m_country_cache, 0); //--- loaded range around the current clock time const datetime now = m_clock.Now(); m_range_from = now - m_lookback_minutes * CAL_SECONDS_PER_MINUTE; m_range_to = now + m_horizon_minutes * CAL_SECONDS_PER_MINUTE; //--- the single call that reads raw records MqlCalendarValue raw[]; int error = 0; if(!m_source.FetchValues(m_range_from, m_range_to, raw, error)) { m_status = CAL_STATUS_CALL_FAILED; m_last_error = error; return(false); } //--- an empty answer is not treated as success: a calendar normally has //--- raw records for a loaded range of several days (a heuristic) m_stats.raw_records = ArraySize(raw); if(m_stats.raw_records == 0) { m_status = CAL_STATUS_NO_DATA; m_last_refresh = now; return(false); } //--- apply the rules to every raw record for(int i = 0; i < m_stats.raw_records; i++) AcceptRecord(raw[i]); //--- success, then fill the time fields for the same clock time m_last_refresh = now; m_status = CAL_STATUS_OK; Recompute(now); return(true); }
Recompute() updates the two time fields of every stored event for one reference time. The subtraction is done on values cast to long, so negative results stay negative.
//+------------------------------------------------------------------+ //| Recompute | //| Updates seconds_to_event and minutes_to_event of every stored | //| event for one reference time. The fields are correct only for | //| that reference time. Seconds are computed on long values, so | //| they stay negative after the event. | //+------------------------------------------------------------------+ void CCalendarFeed::Recompute(const datetime reference_time) { m_reference_time = reference_time; for(int i = 0; i < m_count; i++) { m_events[i].seconds_to_event = (long)m_events[i].time - (long)reference_time; m_events[i].minutes_to_event = CalFloorMinutes(m_events[i].seconds_to_event); } }
PrepareQuery() validates query requests and does not change state. A query is answerable only if the feed status is OK, the symbol is in the universe, the arguments are valid, and the interval [reference time − buffer, reference time + buffer] lies within the loaded range. Otherwise the result carries the reason, and the caller knows that the answer is unknown. A window that extends beyond the loaded range is reported as not covered, because events outside the range were never loaded.
This check covers the reference time and the buffer only. GetNextEvent() uses a buffer of 0, so the gate confirms that the reference time lies inside the loaded range. It does not require any coverage after the reference time.
//+------------------------------------------------------------------+ //| PrepareQuery | //| Common gate of the explicit query forms. A query can be answered | //| only when the status is OK, the symbol is in the universe, the | //| arguments are valid and the interval from the reference time | //| minus the buffer to the reference time plus the buffer lies in | //| the loaded range. Otherwise result.status says why, and the | //| caller must not read the answer as "no event". | //+------------------------------------------------------------------+ bool CCalendarFeed::PrepareQuery(const string symbol, const datetime reference_time, const int buffer_minutes, SCalendarQuery &result, int &symbol_index) const { result.Reset(); result.reference_time = reference_time; result.buffer_minutes = buffer_minutes; //--- the feed must hold current events if(m_status != CAL_STATUS_OK) { result.status = m_status; return(false); } //--- the symbol must belong to the universe symbol_index = FindSymbol(symbol); if(symbol_index < 0) { result.status = CAL_STATUS_SYMBOL_UNKNOWN; return(false); } //--- a negative buffer and a missing reference time make no sense if(buffer_minutes < 0 || reference_time <= 0) { result.status = CAL_STATUS_BAD_ARGUMENT; return(false); } //--- events outside the loaded range were never read, so the answer //--- would be unknown, not "no event" const long buffer_seconds = (long)buffer_minutes * CAL_SECONDS_PER_MINUTE; if((long)reference_time - buffer_seconds < (long)m_range_from || (long)reference_time + buffer_seconds > (long)m_range_to) { result.status = CAL_STATUS_RANGE_NOT_COVERED; return(false); } result.status = CAL_STATUS_OK; return(true); }
GetNextEvent() with a reference time selects the first stored event at or after the reference time that affects the symbol. The copy that it returns carries seconds and minutes computed for that reference time. When no stored event qualifies, the method returns true with found set to false. This means that the loaded range holds no such event up to RangeTo(), not that no event follows. A caller that needs this answer for a given look-ahead must check that RangeTo() minus the reference time is at least that look-ahead. The loaded range ends at a fixed time, so this margin shrinks between refreshes.
//+------------------------------------------------------------------+ //| GetNextEvent | //| Explicit form, does not change state. Selects the first event | //| for the symbol with time >= reference_time, so an event that | //| occurs exactly at the reference time is the next event. The | //| returned copy has seconds and minutes computed for | //| reference_time. Returns false when the query cannot be answered, | //| see result.status. Returns true with result.found = false when | //| no stored event qualifies. This means "no next event in the | //| loaded range", not "no next event at all": events after | //| RangeTo() were never read. | //+------------------------------------------------------------------+ bool CCalendarFeed::GetNextEvent(const string symbol, const datetime reference_time, SCalendarQuery &result) const { int idx = -1; if(!PrepareQuery(symbol, reference_time, 0, result, idx)) return(false); //--- the events are sorted by time, so the first match is the next event for(int i = 0; i < m_count; i++) { if((long)m_events[i].time < (long)reference_time) continue; if(!AffectsSymbolIndex(m_events[i], idx)) continue; result.found = true; result.event = m_events[i]; //--- do not trust the stored fields, compute them for this reference time result.event.seconds_to_event = (long)m_events[i].time - (long)reference_time; result.event.minutes_to_event = CalFloorMinutes(result.event.seconds_to_event); break; } return(true); }
IsInNewsWindow() with a reference time walks the sorted events and stops at the first event whose time is later than the reference time plus the buffer, because every later event is also beyond the news window of that reference time. It uses the exact test on seconds. A window that crosses a weekend needs no special case, because the arithmetic uses plain seconds of one time axis. The weekend minutes count like all other minutes, and the feed does not model market hours.
//+------------------------------------------------------------------+ //| IsInNewsWindow | //| Explicit form, does not change state. The news window of an | //| event is [event - buffer, event + buffer], both ends included. | //| Past events count too. The test uses seconds, not rounded | //| minutes. A news window that crosses a weekend needs no special | //| case, because all times lie on one time axis. Returns false when | //| the query cannot be answered, see result.status. Otherwise | //| result holds in_window and, when true, the event that caused it. | //+------------------------------------------------------------------+ bool CCalendarFeed::IsInNewsWindow(const string symbol, const int buffer_minutes, const datetime reference_time, SCalendarQuery &result) const { int idx = -1; if(!PrepareQuery(symbol, reference_time, buffer_minutes, result, idx)) return(false); const long buffer_seconds = (long)buffer_minutes * CAL_SECONDS_PER_MINUTE; for(int i = 0; i < m_count; i++) { const long secs = (long)m_events[i].time - (long)reference_time; //--- the events are sorted by time, so every later event is also //--- beyond the end of the news window if(secs > buffer_seconds) break; //--- the cheap time test comes before the string search if(!CalWindowContains(secs, buffer_seconds)) continue; if(!AffectsSymbolIndex(m_events[i], idx)) continue; result.found = true; result.in_window = true; result.event = m_events[i]; result.event.seconds_to_event = secs; result.event.minutes_to_event = CalFloorMinutes(secs); break; } return(true); }
The short forms use the clock. Both call Recompute() first, which is the other half of the rule stated above. The short IsInNewsWindow() returns only the flag. A false value means that no window was detected. It does not mean that the situation is safe, so a program that needs the difference must check IsUsable() or call the explicit form.
//+------------------------------------------------------------------+ //| GetNextEvent | //| Short form, changes state. Reads the clock, calls Recompute() | //| with that time, then runs the explicit form. | //+------------------------------------------------------------------+ bool CCalendarFeed::GetNextEvent(const string symbol, SCalendarQuery &result) { if(m_clock == NULL) { result.Reset(); result.status = CAL_STATUS_BAD_ARGUMENT; return(false); } Recompute(m_clock.Now()); return(GetNextEvent(symbol, m_reference_time, result)); } //+------------------------------------------------------------------+ //| IsInNewsWindow | //| Short form, changes state. Reads the clock, calls Recompute() | //| with that time, then runs the explicit form. Returns only the | //| news window flag. False means "no news window detected", not | //| "safe": it is also returned when the query cannot be answered. A | //| program that needs the difference must check IsUsable() or use | //| the explicit form and read result.status. | //+------------------------------------------------------------------+ bool CCalendarFeed::IsInNewsWindow(const string symbol, const int buffer_minutes) { SCalendarQuery result; if(m_clock == NULL) return(false); Recompute(m_clock.Now()); IsInNewsWindow(symbol, buffer_minutes, m_reference_time, result); return(result.in_window); }
The last block holds GetEventAt() and LogSummary(). The summary prints the status, the last error code, the number of stored events, the range, and the counters of the last refresh.
//+------------------------------------------------------------------+ //| GetEventAt | //| Copies the stored event at index. Returns false when the index | //| is out of range. The time fields belong to the reference time | //| of the last Recompute(). | //+------------------------------------------------------------------+ bool CCalendarFeed::GetEventAt(const int index, CCalendarEvent &ev) const { if(index < 0 || index >= m_count) return(false); ev = m_events[index]; return(true); } //+------------------------------------------------------------------+ //| LogSummary | //| Prints the status, the last error code, the number of events, | //| the loaded range and the counters of the last Refresh(). | //+------------------------------------------------------------------+ void CCalendarFeed::LogSummary() const { PrintFormat("CCalendarFeed: status=%s, last error=%d, events=%d", CalStatusToString(m_status), m_last_error, m_count); PrintFormat(" range from %s to %s (clock time zone)", TimeToString(m_range_from, TIME_DATE | TIME_SECONDS), TimeToString(m_range_to, TIME_DATE | TIME_SECONDS)); PrintFormat(" raw=%d, lookup failed=%d, below impact=%d, inexact time=%d, other currency=%d", m_stats.raw_records, m_stats.lookup_failed, m_stats.below_impact, m_stats.inexact_time, m_stats.other_currency); PrintFormat(" duplicates=%d, revisions dropped=%d, revisions replaced=%d", m_stats.duplicates, m_stats.revisions_dropped, m_stats.revisions_replaced); }
The cost of the methods follows from the code above.
Refresh() makes one FetchValues() call. It makes one FetchEvent() call for each distinct event identifier among the raw records with a positive time, including the identifiers whose lookup fails, because failures are cached. It makes one FetchCountry() call for each distinct country identifier among the records that pass the event lookup, the impact filter, and the time-mode rule. It loops once over the raw records.
For each raw record it scans the event cache, and for each record that reaches the country step it scans the country cache. For each accepted record, InsertEvent() scans the stored events once for duplicates, calls ArrayResize() once, and runs a shift loop that moves at most the number of stored events. A replaced revision adds one RemoveAt() call with one more ArrayResize() call. Each new entry in the event cache or the country cache costs one ArrayResize() call. The worst case is quadratic in the number of events. If the terminal returns records in time order the shift loop does not move anything. Performance was not measured for this article. Refresh() also calls ArrayResize() three times to clear arrays and ends with one loop in Recompute().
Recompute() makes one loop over the stored events and allocates nothing. GetNextEvent() and IsInNewsWindow() with a reference time make one pass over the universe in FindSymbol() and one pass over the stored events with an early exit. The string concatenation in AffectsSymbolIndex() creates a temporary string. In GetNextEvent() it runs for events at or after the reference time until the first match. In IsInNewsWindow() it runs only for events that lie inside the window. The short forms add one Recompute() loop.
The Chart Overlay
NewsOverlay.mq5 is an indicator without plots. It builds a feed with a terminal source and a terminal clock for the chart symbol, keeps only high impact levels, and draws one vertical line per event for the currencies of that symbol. Every object name starts with the fixed prefix NEWSOV_. On exit the indicator removes the objects whose names start with that prefix and nothing else. If you create your own objects with the same prefix, they are removed too.
//+------------------------------------------------------------------+ //| NewsOverlay.mq5 | //| Draws one vertical line per high impact event for the chart | //| symbol, using the terminal calendar through CCalendarFeed. | //+------------------------------------------------------------------+ #property description "Filter aid for chart review. Not trading advice." #property indicator_chart_window #property indicator_buffers 0 #property indicator_plots 0 #include <CalendarFeed\CalendarFeed.mqh> //+------------------------------------------------------------------+ //| Settings of the loaded range, the refresh period, the fallback | //| table and the color of the lines. | //+------------------------------------------------------------------+ input int InpLookbackHours = 24; // hours before the reference time input int InpHorizonHours = 72; // hours after the reference time input int InpRefreshMinutes = 15; // refresh period, minutes input string InpFallbackTable = "US30:USD;US500:USD;USTEC:USD;DE40:EUR;UK100:GBP;JP225:JPY;XAUUSD:USD;XAGUSD:USD;BTCUSD:USD"; input color InpLineColor = clrCrimson; // color of the lines and the labels //--- prefix of every object that this indicator creates and may delete #define OVERLAY_PREFIX "NEWSOV_" //--- objects of the indicator, created in OnInit(), deleted in OnDeinit() CTerminalCalendarSource *g_source = NULL; // source for live use CTerminalClock *g_clock = NULL; // clock for live use CCalendarFeed *g_feed = NULL; // feed of the chart symbol
The label contains the currency, the event name, and the time in server time. DrawEvent() creates a vertical line with the label as tooltip, and a text object at the top of the visible price range. The text object is positioned when the overlay is drawn and does not follow later scrolling of the price axis. Chart time uses the server time, so a line is placed where the feed has the event. Check the documentation of your terminal build for the details of the chart time axis.
//+------------------------------------------------------------------+ //| BuildLabel | //| Label text: currency, event name and event time. The time is | //| the trade server time, as stored in the event. | //+------------------------------------------------------------------+ string BuildLabel(const CCalendarEvent &ev) { return(ev.currency + " " + ev.name + " " + TimeToString(ev.time, TIME_DATE | TIME_MINUTES) + " (server time)"); } //+------------------------------------------------------------------+ //| DrawEvent | //| Draws one vertical line and one text object for an event. Both | //| names use the prefix and the record id, so every event has its | //| own pair. The text sits at the price level top, which is the | //| visible maximum at the moment of drawing. It does not follow | //| later scrolling of the price axis. | //+------------------------------------------------------------------+ void DrawEvent(const CCalendarEvent &ev, const double top) { const string id = (string)ev.record_id; const string line = OVERLAY_PREFIX + "L_" + id; const string label = OVERLAY_PREFIX + "T_" + id; const string text = BuildLabel(ev); //--- vertical line at the event time, the tooltip shows the full label if(ObjectCreate(0, line, OBJ_VLINE, 0, ev.time, 0)) { ObjectSetInteger(0, line, OBJPROP_COLOR, InpLineColor); ObjectSetInteger(0, line, OBJPROP_STYLE, STYLE_DOT); ObjectSetInteger(0, line, OBJPROP_BACK, true); ObjectSetInteger(0, line, OBJPROP_SELECTABLE, false); ObjectSetString(0, line, OBJPROP_TOOLTIP, text); } //--- text object, anchored at its left upper corner at the event time if(ObjectCreate(0, label, OBJ_TEXT, 0, ev.time, top)) { ObjectSetString(0, label, OBJPROP_TEXT, text); ObjectSetInteger(0, label, OBJPROP_COLOR, InpLineColor); ObjectSetInteger(0, label, OBJPROP_FONTSIZE, 8); ObjectSetInteger(0, label, OBJPROP_ANCHOR, ANCHOR_LEFT_UPPER); ObjectSetInteger(0, label, OBJPROP_SELECTABLE, false); } }
UpdateOverlay() deletes the old objects, refreshes the feed, and draws. When the refresh fails, no lines are drawn and the status and the error code are printed, so an empty chart is never mistaken for a quiet calendar.
//+------------------------------------------------------------------+ //| UpdateOverlay | //| Deletes the old objects, refreshes the feed and draws one line | //| for each event with a high impact level that affects the chart | //| symbol. When the refresh fails nothing is drawn, and the status | //| and the error code are printed, so an empty chart is not | //| mistaken for a quiet calendar. | //+------------------------------------------------------------------+ void UpdateOverlay() { //--- delete only the objects with the fixed prefix ObjectsDeleteAll(0, OVERLAY_PREFIX); if(!g_feed.Refresh()) { PrintFormat("NewsOverlay: no lines drawn, feed status %s, error %d", CalStatusToString(g_feed.Status()), g_feed.LastError()); ChartRedraw(); return; } //--- walk the sorted events, keep the events of this symbol with a high impact level const double top = ChartGetDouble(0, CHART_PRICE_MAX); const int total = g_feed.Count(); for(int i = 0; i < total; i++) { CCalendarEvent ev; if(!g_feed.GetEventAt(i, ev)) continue; if(ev.impact != CAL_IMPACT_HIGH || !g_feed.AffectsSymbol(ev, _Symbol)) continue; DrawEvent(ev, top); } ChartRedraw(); }
The event handlers create the objects, start a timer, and release everything in OnDeinit(). The indicator calls the calendar in OnInit() and in OnTimer(), so it depends on the terminal calendar and is not meant for the Strategy Tester.
//+------------------------------------------------------------------+ //| OnInit | //| Creates the source, the clock and the feed, sets the universe to | //| the chart symbol, starts the refresh timer and draws once. | //+------------------------------------------------------------------+ int OnInit() { g_source = new CTerminalCalendarSource(); g_clock = new CTerminalClock(); g_feed = new CCalendarFeed(); //--- the universe is the chart symbol only string universe[1]; universe[0] = _Symbol; if(!g_feed.Init(g_source, g_clock) || !g_feed.SetUniverse(universe, InpFallbackTable)) { Print("NewsOverlay: initialization failed, status ", CalStatusToString(g_feed.Status())); return(INIT_FAILED); } //--- high impact level only, events without an exact time are dropped g_feed.SetFilter(CAL_IMPACT_HIGH, CAL_INEXACT_SKIP); g_feed.SetRange(InpLookbackHours * 60, InpHorizonHours * 60); EventSetTimer(MathMax(InpRefreshMinutes, 1) * 60); UpdateOverlay(); return(INIT_SUCCEEDED); } //+------------------------------------------------------------------+ //| OnTimer | //| Redraws the overlay at every refresh period. | //+------------------------------------------------------------------+ void OnTimer() { UpdateOverlay(); } //+------------------------------------------------------------------+ //| OnDeinit | //| Stops the timer, removes only the objects of this indicator and | //| deletes the objects that OnInit() created. | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { EventKillTimer(); ObjectsDeleteAll(0, OVERLAY_PREFIX); ChartRedraw(); if(g_feed != NULL) { delete g_feed; g_feed = NULL; } if(g_clock != NULL) { delete g_clock; g_clock = NULL; } if(g_source != NULL) { delete g_source; g_source = NULL; } } //+------------------------------------------------------------------+ //| OnCalculate | //| Required by an indicator. This indicator has no buffers and | //| does nothing here, all work is done in OnInit() and OnTimer(). | //+------------------------------------------------------------------+ int OnCalculate(const int rates_total, const int prev_calculated, const datetime &time[], const double &open[], const double &high[], const double &low[], const double &close[], const long &tick_volume[], const long &volume[], const int &spread[]) { return(rates_total); }
The Demo Program
CalendarFeedDemo.mq5 wires the pieces together. In its default mode it uses the fake source and a scripted clock, so every line it prints is synthetic. With InpUseTerminal set to true it uses the terminal source and the terminal clock, and then the log shows real data from the terminal.
//+------------------------------------------------------------------+ //| CalendarFeedDemo.mq5 | //| Wires the feed together. Default mode uses a fake source and | //| a scripted clock, so every output is synthetic. | //+------------------------------------------------------------------+ #property script_show_inputs #include <CalendarFeed\CalendarFeed.mqh> //+------------------------------------------------------------------+ //| Settings of the data mode, the universe, the filter and the | //| news window. | //+------------------------------------------------------------------+ //--- data mode input bool InpUseTerminal = false; // true: terminal calendar and terminal clock //--- universe input string InpSymbols = "DEMOUSD,DEMOEUR"; // symbols, comma separated input string InpFallbackTable = "DEMOUSD:USD;DEMOEUR:EUR"; // fallback table of the mapper //--- filter and news window input ENUM_CAL_IMPACT InpMinImpact = CAL_IMPACT_HIGH; // minimum impact level input int InpBufferMinutes = CAL_DEFAULT_BUFFER_MINUTES; // news window buffer, minutes //--- loaded range input int InpLookbackHours = 12; // hours before the reference time input int InpHorizonHours = 72; // hours after the reference time
The synthetic data contains one event of each kind that the feed has to handle: a duplicate record, a revision of an event, an event with a moderate impact level, and an event with a tentative time mode. The symbol names DEMOUSD and DEMOEUR do not exist in a terminal, so the fallback table maps them and the terminal is not asked.
//+------------------------------------------------------------------+ //| BuildSyntheticData | //| Fills the fake source with synthetic data. All times are trade | //| server time. The data has one case for each rule of the feed: | //| a duplicate raw record, a revision, an event below the minimum | //| impact level and an event without an exact time. | //+------------------------------------------------------------------+ void BuildSyntheticData(CFakeCalendarSource &fake) { //--- countries and their currencies fake.AddCountry(1, "US", "USD"); fake.AddCountry(2, "EU", "EUR"); fake.AddCountry(3, "GB", "GBP"); //--- event descriptions: id, name, importance, time mode, country fake.AddEvent(5001, "Synthetic USD Release", CALENDAR_IMPORTANCE_HIGH, CALENDAR_TIMEMODE_DATETIME, 1); fake.AddEvent(5002, "Synthetic EUR Release", CALENDAR_IMPORTANCE_HIGH, CALENDAR_TIMEMODE_DATETIME, 2); fake.AddEvent(5003, "Synthetic GBP Release", CALENDAR_IMPORTANCE_MODERATE, CALENDAR_TIMEMODE_DATETIME, 3); fake.AddEvent(5004, "Synthetic USD Speech", CALENDAR_IMPORTANCE_HIGH, CALENDAR_TIMEMODE_TENTATIVE, 1); //--- raw records: record id, event id, time, period, revision const datetime period = D'2026.09.30 00:00:00'; fake.AddValue(9001, 5001, D'2026.10.13 13:30:00', period, 1); fake.AddValue(9001, 5001, D'2026.10.13 13:30:00', period, 1); // duplicate record id fake.AddValue(9002, 5002, D'2026.10.14 12:15:00', period, 1); fake.AddValue(9005, 5002, D'2026.10.14 12:15:00', period, 2); // revision of raw record 9002 fake.AddValue(9003, 5003, D'2026.10.13 08:30:00', period, 1); // moderate impact level, dropped fake.AddValue(9004, 5004, D'2026.10.13 15:00:00', 0, 0); // tentative time mode, dropped }
The helper LogEvents() prints the stored events together with their minutes_to_event and the reference time of the last Recompute(). QueryAt() calls both explicit query forms for one reference time and prints either the answer or the status that explains why there is none.
//+------------------------------------------------------------------+ //| LogEvents | //| Prints every stored event with its minutes_to_event and the | //| reference time of the last Recompute(). | //+------------------------------------------------------------------+ void LogEvents(const CCalendarFeed &feed) { const int total = feed.Count(); for(int i = 0; i < total; i++) { CCalendarEvent ev; if(!feed.GetEventAt(i, ev)) continue; PrintFormat(" #%d %s %s occurs at %s | impact %s | exact %s | minutes_to_event %d (reference %s)", i, ev.currency, ev.name, TimeToString(ev.time, TIME_DATE | TIME_SECONDS), CalImpactToString(ev.impact), ev.exact_time ? "yes" : "no", ev.minutes_to_event, TimeToString(feed.ReferenceTime(), TIME_DATE | TIME_SECONDS)); } } //+------------------------------------------------------------------+ //| QueryAt | //| Runs both explicit query forms for one reference time and prints | //| the answer. A query that cannot be answered prints its status | //| instead of an answer. | //+------------------------------------------------------------------+ void QueryAt(const CCalendarFeed &feed, const string symbol, const datetime reference_time) { SCalendarQuery next, window; const bool ok_next = feed.GetNextEvent(symbol, reference_time, next); const bool ok_window = feed.IsInNewsWindow(symbol, InpBufferMinutes, reference_time, window); if(!ok_next || !ok_window) { PrintFormat("%s reference %s: not answerable, status %s", symbol, TimeToString(reference_time, TIME_DATE | TIME_SECONDS), CalStatusToString(ok_next ? window.status : next.status)); return; } PrintFormat("%s reference %s: next=%s, minutes_to_event=%s, in_window=%s", symbol, TimeToString(reference_time, TIME_DATE | TIME_SECONDS), next.found ? next.event.name : "none", next.found ? IntegerToString(next.event.minutes_to_event) : "n/a", window.in_window ? "true" : "false"); }
OnStart() creates the objects, initializes the feed, refreshes it, logs the summary, and queries it at the five reference times of the worked-example table. It finishes with one call of the short form after the scripted clock is moved.
//+------------------------------------------------------------------+ //| OnStart | //| Chooses the data mode, builds the feed, refreshes it, logs the | //| summary and the events, and queries the feed. In demo mode the | //| queries use the five reference times of the worked example, | //| then one call of the short form after the scripted clock moves. | //+------------------------------------------------------------------+ void OnStart() { CCalendarSource *source = NULL; CClock *clock = NULL; CScriptedClock *scripted = NULL; // set only in demo mode //--- live mode: terminal source and terminal clock. Demo mode: fake //--- source with synthetic data and a scripted clock if(InpUseTerminal) { source = new CTerminalCalendarSource(); clock = new CTerminalClock(); } else { CFakeCalendarSource *fake = new CFakeCalendarSource(); BuildSyntheticData(fake); scripted = new CScriptedClock(); scripted.Set(D'2026.10.13 12:00:00'); source = fake; clock = scripted; Print("Demo mode: synthetic data from the fake source and the scripted clock."); } //--- the universe comes from the input string universe[]; StringSplit(InpSymbols, ',', universe); CCalendarFeed feed; if(!feed.Init(source, clock) || !feed.SetUniverse(universe, InpFallbackTable)) Print("Setup failed, status ", CalStatusToString(feed.Status())); else { feed.SetFilter(InpMinImpact, CAL_INEXACT_SKIP); feed.SetRange(InpLookbackHours * 60, InpHorizonHours * 60); //--- Refresh() returns true only for CAL_STATUS_OK. The summary is //--- printed in every case, so a failure is visible in the log const bool refreshed = feed.Refresh(); feed.LogSummary(); if(refreshed) { LogEvents(feed); if(scripted != NULL) { //--- the five reference times of the worked example const datetime times[] = {D'2026.10.13 13:14:59', D'2026.10.13 13:15:00', D'2026.10.13 13:30:00', D'2026.10.13 13:45:00', D'2026.10.13 13:45:01'}; for(int i = 0; i < ArraySize(times); i++) QueryAt(feed, "DEMOUSD", times[i]); //--- short form: the clock is moved, the feed refreshes its fields first scripted.Set(D'2026.10.13 13:20:00'); PrintFormat("Short form at clock %s: IsInNewsWindow(DEMOUSD)=%s", TimeToString(scripted.Now(), TIME_DATE | TIME_SECONDS), feed.IsInNewsWindow("DEMOUSD", InpBufferMinutes) ? "true" : "false"); } else //--- live mode: one query at the current clock time QueryAt(feed, universe[0], clock.Now()); } } //--- the feed does not own the source and the clock, so the program deletes them delete clock; delete source; }
Verification and Testing
TestCalendarFeed.mq5 runs the logic with scripted data only. It uses the fake source and the scripted clock. It does not cover the terminal calendar, the calendar data of the broker, or network behavior. It checks the mapper with the table path, the rounding of minutes, the sort order, the filters, the boundaries of the news window, duplicates and revisions, the failure statuses, and the call counts of the fake source. It does not check the terminal path of the mapper beyond one unknown symbol, and it does not check the chart overlay.
The boundary tests use the five reference times of the worked example: one second before the window, exactly at the start, exactly at the event, exactly at the end, and one second after. They also check a window that crosses a weekend with a buffer of 3000 minutes, and the minutes before and after an event. The failure tests check the initial status, a failed call with its error code, an empty answer, an empty universe, an unknown symbol, a negative buffer, and a reference time outside the loaded range. The call-count test compares the calls of the fake source with the cost statements in this article.
The script prints one line for each failed check and a final line with the number of passed and failed checks.
//+------------------------------------------------------------------+ //| OnStart | //| Runs every test group and prints the totals. | //+------------------------------------------------------------------+ void OnStart() { TestMapper(); TestRounding(); TestSorting(); TestFilters(); TestBoundaries(); TestWeekend(); TestDuplicates(); TestFailures(); TestCallCounts(); PrintFormat("TestCalendarFeed: %d checks passed, %d failed (scripted data only)", g_pass, g_fail); }
The script was run on the symbol EURUSD, and the Experts tab ended with the two lines below. The first line is expected, because one test maps an unknown symbol on purpose. The checks use scripted data, so this result says nothing about the live calendar of any broker.
CCalendarFeed: no currencies mapped for NO_SUCH_SYMBOL_XYZ, symbol skipped TestCalendarFeed: 96 checks passed, 0 failed (scripted data only)
The script prints only the total. The table splits it by test function. The counts were taken from the source code and add up to 96.
| # | Test function | What it checks | Checks |
|---|---|---|---|
| 1 | TestMapper() | Table path, trimming, duplicates, unknown symbol. | 7 |
| 2 | TestRounding() | CalFloorMinutes() for 10 values. | 10 |
| 3 | TestSorting() | Order by time, tie broken by record id. | 5 |
| 4 | TestFilters() | Impact filter, currency filter, inexact time. | 9 |
| 5 | TestBoundaries() | Five reference times, minutes after the event, Recompute(), short forms. | 30 |
| 6 | TestWeekend() | News window across a weekend. | 6 |
| 7 | TestDuplicates() | Duplicates and revisions. | 9 |
| 8 | TestFailures() | The status values. | 16 |
| 9 | TestCallCounts() | Calls of the fake source. | 4 |
| Total | 96 |
Environment of the runs: MetaTrader 5 build 6252 (64-bit) with a demo account. The test script ran on an EURUSD M15 chart at 2026.10.21 11:49, and the demo-script run shown in the next section ran on a GBPUSD H4 chart at 2026.10.21 15:30. Both times are as printed in the Experts tab, which shows the local time of the computer and not trade server time. Both scripts use scripted data by default, so the chart symbol and period do not change their output.
Interpreting the Output
The demo log starts with the summary of the feed: the status, the last error code, the number of stored events, the loaded range, and the counters. The status must be OK before the events mean anything. After the summary, each line shows one event with its currency, name, time, impact level, the exact-time flag, minutes_to_event, and the reference time for which that field was computed. A positive minutes_to_event means that the event is still ahead, zero means that it is 0 to 59 seconds ahead, and a negative value means that it already occurred. The query lines show the next event, minutes_to_event, and the window flag for each reference time. A line that says not answerable shows the status instead, for example not refreshed or range not covered.
2026.10.21 15:30:10.749 CalendarFeedDemo (GBPUSD,H4) Demo mode: synthetic data from the fake source and the scripted clock. 2026.10.21 15:30:10.750 CalendarFeedDemo (GBPUSD,H4) CCalendarFeed: status=OK, last error=0, events=2 range from 2026.10.13 00:00:00 to 2026.10.16 12:00:00 (clock time zone) raw=6, lookup failed=0, below impact=1, inexact time=1, other currency=0 duplicates=1, revisions dropped=0, revisions replaced=1 #0 USD Synthetic USD Release occurs at 2026.10.13 13:30:00 | impact high | exact yes | minutes_to_event 90 (reference 2026.10.13 12:00:00) #1 EUR Synthetic EUR Release occurs at 2026.10.14 12:15:00 | impact high | exact yes | minutes_to_event 1455 (reference 2026.10.13 12:00:00) DEMOUSD reference 2026.10.13 13:14:59: next=Synthetic USD Release, minutes_to_event=15, in_window=false DEMOUSD reference 2026.10.13 13:15:00: next=Synthetic USD Release, minutes_to_event=15, in_window=true DEMOUSD reference 2026.10.13 13:30:00: next=Synthetic USD Release, minutes_to_event=0, in_window=true DEMOUSD reference 2026.10.13 13:45:00: next=none, minutes_to_event=n/a, in_window=true DEMOUSD reference 2026.10.13 13:45:01: next=none, minutes_to_event=n/a, in_window=false Short form at clock 2026.10.13 13:20:00: IsInNewsWindow(DEMOUSD)=true
On the chart, each dotted vertical line marks the time of one high-impact event for a currency of the chart symbol, and the text next to it gives the currency, the name, and the time in server time. No line means one of two things: the feed holds no high-impact event for the chart symbol in the loaded range, or the refresh failed. The Experts tab tells the two cases apart, because a failed refresh prints the status and the error code.

Figure 3: NewsOverlay on the EURUSD H1 chart of a demo account, MetaTrader 5 build 6252, on 2026.10.21. The dotted vertical lines mark high-impact events, and the labels carry the currency and the event name. The colored boxes on the time axis are drawn by the terminal and not by NewsOverlay.
Two limits are visible in the figure. A label near the right edge of the chart is clipped, because the text object is anchored at its left edge and the chart ends. The full label stays available as the tooltip of the vertical line. The text object is also placed at the visible price maximum at the time of drawing, so it does not follow the chart when the price scale changes until the next call of UpdateOverlay().
An EA can use the feed before it opens a trade. The following sketch keeps one feed for the symbol of the EA and refreshes it from a timer. It uses the explicit query form, and it treats an unanswerable query as a reason not to trade. This is a policy choice for the sketch and not a rule of the package. Because the calendar is not available in the Strategy Tester, an EA built this way would never trade in the tester unless you add a switch that disables the filter there.
CTerminalCalendarSource *g_source = NULL; CTerminalClock *g_clock = NULL; CCalendarFeed *g_feed = NULL; bool NewsBlocksTrading(const string symbol,const int buffer_minutes) { SCalendarQuery q; //--- Not answerable (not refreshed, failed call, range not covered): do not trade. if(!g_feed.IsInNewsWindow(symbol,buffer_minutes,g_clock.Now(),q)) return(true); return(q.in_window); } void OnTick() { if(NewsBlocksTrading(_Symbol,CAL_DEFAULT_BUFFER_MINUTES)) return; // ... the rules of the EA that may open a trade ... } void OnTimer() { g_feed.Refresh(); }
The sketch assumes that OnInit() creates the three objects, calls Init(), SetUniverse(), SetFilter(), and SetRange(), starts a timer, and calls Refresh() once. The loaded range must be longer than the refresh period plus the buffer, or the query becomes not answerable between refreshes. The sketch uses IsInNewsWindow(), which reports CAL_STATUS_RANGE_NOT_COVERED when the window leaves the loaded range, so a false answer with the status OK covers the whole window. An EA that calls GetNextEvent() must read found equal to false as “no event in the loaded range”, and it should compare RangeTo() minus the current time with the look-ahead that it needs. A smaller margin is treated like an unanswerable query.
Extending the Feed
A per-event buffer needs a new field in CCalendarEvent, for example buffer_minutes, filled in AcceptRecord() from a rule such as a different buffer for each event name. IsInNewsWindow() would then use the buffer of each event instead of one argument, and PrepareQuery() would use the largest buffer to check the loaded range.
A minimum impact level for each currency replaces the single m_min_impact with an array parallel to the relevant currencies. The change is in SetFilter(), which needs a currency argument, and in the impact check of AcceptRecord(), which looks up the minimum for the country currency.
A look-ahead argument is a second way to remove the ambiguity. GetNextEvent() would take the required look-ahead in minutes. PrepareQuery() would then check that the reference time plus the look-ahead lies inside the loaded range, and return CAL_STATUS_RANGE_NOT_COVERED when it does not. Then found equal to false with status OK would prove that no event exists within the look-ahead. This changes the signature, so the tests must change as well.
A cache file between runs needs two new pieces. After Refresh(), a method writes the events and the loaded range to a text file with FileWrite(). A second method reads the file and calls InsertEvent() for each row, then sets the status. Structures with strings cannot be written in binary form, so a text format is the simple choice. The loaded range and the time of the refresh must be stored too, because the range check in PrepareQuery() depends on them. A feed that was loaded from a cache must not report CAL_STATUS_OK unless the cache is current.
A different source needs a new class that derives from CCalendarSource and implements three methods. Because the interface returns the documented structures, a new source must produce MqlCalendarValue, MqlCalendarEvent, and MqlCalendarCountry records. Nothing else in the feed changes.
Limitations and Design Tradeoffs
The calendar functions are not available in the Strategy Tester, so a backtest cannot reproduce the news filter from the terminal calendar. The fake source allows tests and demonstrations with scripted data, but those are synthetic and say nothing about the behavior of the real calendar. A strategy that uses the filter in live trading but not in the tester is tested under different rules, and the difference should be stated when results are reported. Data availability in the live terminal also matters. A failed call, a timeout, or an empty answer leaves the feed unusable, and the package reports this through the status and does not guess.
All feed times use the clock's time zone. With the terminal clock, that is trade server time, which is also the calendar's documented time zone. The feed subtracts times as plain seconds. If the trade server changes its offset between the reference time and an event, for example during a daylight saving change, the elapsed seconds do not match the real elapsed time, and the package does not correct for it. Check the documentation and the behavior of your broker for this case. Revisions are a second risk. A published value can be revised after the feed was loaded, and the feed sees the new revision only at the next Refresh(). The revision rule that merges records by event identifier and period is a heuristic and can merge records that should stay separate.
The filter depends on broker calendar data. If importance, time, event presence, or currency is wrong or missing, the filter will be wrong, and the feed cannot detect it. The symbol mapping has the same dependency on the symbol properties of the broker and on the fallback table. The impact levels, the default buffer, and the treatment of tentative events are heuristics that the reader must adjust. The feed is a filter aid and not trading advice.
Conclusion
The package turns the raw output of CalendarValueHistory() into a small, queryable feed. It keeps the time logic in one place, defines the news window and the rounding of minutes exactly, and reports failures through a status that cannot pass for success. The abstract source and the injected clock make the logic testable without the terminal calendar.
The feed is a base for a news filter and not a finished one. Its defaults are heuristics, its mapping needs a review for each broker, and its answers depend on the calendar data that the broker supplies. Review those choices before the feed gates any real trade.
Programs used in the article:
| # | Name | Type | Description |
|---|---|---|---|
| 1 | CalTypes.mqh | Include file | Constants, enumerations, the CCalendarEvent structure, the query and statistics structures, and the minute and window helpers. |
| 2 | Clock.mqh | Include file | The abstract clock, the terminal clock, and the scripted clock. |
| 3 | CalendarSource.mqh | Include file | The abstract source, the terminal source that wraps the calendar functions, and the fake source for tests. |
| 4 | SymbolMapper.mqh | Include file | The stateless mapper from a symbol to its currencies, with the fallback table. |
| 5 | CalendarFeed.mqh | Include file | The CCalendarFeed class with Refresh(), Recompute(), GetNextEvent(), and IsInNewsWindow(). |
| 6 | NewsOverlay.mq5 | Custom Indicator | Draws one vertical line and one label for each high-impact event of the chart symbol. |
| 7 | CalendarFeedDemo.mq5 | Script | Wires the feed together and logs a summary and queries, with synthetic data by default. |
| 8 | TestCalendarFeed.mq5 | Script | Runs the logic tests with scripted data only. |
| 9 | CalendarFeedSources.zip | Zip Archive | Zip archive containing all the attached files and their paths relative to the terminal's root folder. |
Warning: All rights to these materials are reserved by MetaQuotes Ltd. Copying or reprinting of these materials in whole or in part is prohibited.
This article was written by a user of the site and reflects their personal views. MetaQuotes Ltd is not responsible for the accuracy of the information presented, nor for any consequences resulting from the use of the solutions, strategies or recommendations described.