preview
Using the MQL5 Economic Calendar for News Filter (Part 6): A Filter an EA Can Hold Two Of

Using the MQL5 Economic Calendar for News Filter (Part 6): A Filter an EA Can Hold Two Of

MetaTrader 5 — Examples |
241 0
Solomon Anietie Sunday
Solomon Anietie Sunday

Table of Contents

  1. Introduction
  2. Section 1: The News Code in the Current EA
  3. Section 2: The Filter as a Class
  4. Section 3: The EA That Holds Two Filters
  5. What This Part Does Not Do
  6. Conclusion


Introduction

The news filter built so far reads the broker's calendar when the EA trades live and a CSV file when the Strategy Tester drives it; it gives the releases named in a rule table more room than the calendar's importance tag alone would, blocks entries, closes positions, suspends and restores stops, and keeps a suspension across a terminal restart. Apart from the tier scale and the rule table, which the previous part moved into two headers, all of it sits at file scope in one Expert Advisor. This is manageable as long as you have only one EA. Putting the same protection into a second EA means copying most of the file and maintaining two versions. A fix in one can leave the other unchanged.

The obvious step is to create a header: move the news code into a.mqh file and include it so the logic becomes shareable. This is a necessary step, and for an EA that holds one filter it can be enough. It doesn't solve the case where one EA needs two filters with different settings. Each filter needs its own settings and its own state, and moving code into a header provides neither. By the end of this part, the EA will:

  • Include the filter from NewsFilter.mqh, which declares no inputs and needs no variable or object of a particular name in the EA that includes it.
  • Hold the events, the currency cache, the saved stops, and the suspension flag inside an object instead of at file scope.
  • Run two filters at once on the same symbol, each with its own tier threshold, responses, saved state, and windows for routine and special releases.
  • Read one rule table from both. A window that a rule sets for a release belongs to that table, so it applies in both filters.

Scope of This Article

This part changes how the filter is packaged. It adds no new detection behavior, tier, window rule, or responses, so for the same events and settings a filter gives the same answer to whether a news window is open. That answer is what this article means by the filter's decision. What differs from the previous EA is described where its code is shown. The main differences are how stops are suspended, saved, and restored, what a filter reports when it cannot detect anything, and what the EA in this part does with that report. Two files:

  • NewsFilter.mqh, which goes in MQL5\Include\NewsFilterSuite\ beside the two headers already there.
  • NewsIntegration_Part6.mq5, the EA that uses it.

NewsTypes.mqh and NewsRules.mqh are used as they are. The EA from the previous part keeps working without any change, so moving it to the new header is optional. The steps for that move are in Moving an EA Across.


Section 1: The News Code in the Current EA

Three things in the current EA stand in the way of a header that two EAs can share and that can hold more than one filter: its inputs, its trade object, and its file-scope state. All three can be seen in the EA file from the previous part.

Inputs in a Header

//+------------------------------------------------------------------+
//| INPUTS                                                           |
//+------------------------------------------------------------------+
input group "News Filter Configuration"
input bool   EnableNewsFilter = false;                           // Enable Economic News Filter
input int    NewsMinutesBefore = 5;                              // Minutes before news to restrict
input int    NewsMinutesAfter = 5;                               // Minutes after news to restrict
input bool   RestrictNewTradesDuringNews = true;                 // Block new trades during news window
input bool   SuspendStopsDuringNews = false;                     // Pause SL/TP modifications during the news window
input bool   CloseTradesOnWindowStart = false;                   // Close all trades when a news window opens
input string SymbolCurrencyOverride = "";                        // Manual currency override e.g. "USD,JPY"
input ENUM_NEWS_TIER NewsMinimumTier = NEWS_TIER_HIGH;           // Watch this tier and everything above it
//--- Cache reload interval
input int CacheReloadHours = 6;                                  // How often to reload calendar cache (hours)
input string HistoricalNewsFile = "HistoricalNews.csv";          // CSV file for backtesting news events

input group "Special Tier Configuration"
input int    SpecialMinutesBefore = 30;                          // Minutes before a special event to restrict
input int    SpecialMinutesAfter = 60;                           // Minutes after a special event to restrict
input bool   UseBuiltInSpecialRules = true;                      // Load the shipped rule table
input string SpecialRulesFile = "NewsRules.csv";                 // Optional rule overrides, blank to skip
input bool   NewsFilterVerbose = false;                          // Print each loaded event and its tier

The news section of the EA declares fifteen inputs in two groups. If that block moved into a header, every EA that included the header would get all fifteen inputs, in this order, whether it used them or not. They would appear in the properties dialog and the optimizer's parameter list, so a trader who only wants entry blocking would still see the stop-suspension settings, even though they do nothing for that EA. An input declaration has no optional form. An EA could leave a group out only if the header wrapped that group in conditional compilation, which moves the choice into preprocessor switches that every EA author has to know about.

A second filter with settings of its own would also need a second set of those declarations, and the same names cannot be declared twice. An input declaration defines a variable, so declaring the same name twice produces a redefinition error. An include guard avoids the error by skipping the second copy, which leaves the second filter with no settings of its own. A header with one fixed set of inputs, therefore, gives every filter in the program the same settings. To support different settings, the header would need a second set of inputs with different names. Any EA including the header would then show both sets.

The Borrowed Trade Object

The filter closes positions and removes stops, so it needs a CTrade object. The EA already has one, and the quickest way for a header to reach it is to declare that the object exists elsewhere in the program:

The line below is a counter-example. It is not in any file attached to the article.

extern CTrade trade;

The header only works as intended if the EA declares a CTrade object named exactly "trade." This requirement is implicit, so each EA author must discover it in the header. The EA and the filter would also be sharing the same object. Settings the EA applies to it for its own orders, such as deviation, filling mode, or magic number, would then apply to the filter's requests as well. A change to the trading logic could change how the news filter sends its orders, and neither file would show the connection.

State at File Scope

//+------------------------------------------------------------------+
//| GLOBAL VARIABLES                                                 |
//+------------------------------------------------------------------+
datetime lastCalendarLoad = 0;
CTrade trade;                      // CTrade instance for order management

//--- Structure to store removed stop information
struct SavedStops
  {
   ulong             ticket;        // Trade ticket number
   double            sl;           // Original stop loss
   double            tp;           // Original take profit
  };
SavedStops savedStops[];
bool newsSuspended = false;

//--- Global Variables
SNewsEvent newsEvents[];
bool newsEventsLoaded = false;

SNewsConfig newsConfig;    // The classifier's settings

string cachedCurrencies[];
int cachedCurrencyCount = 0;
bool currencyCacheValid = false;

These declarations remain in a single copy per program, wherever they are written. A variable declared at file scope belongs to the compiled program, and the file that holds the declaration makes no difference. Even with the news code in a header and the input problem solved, the program would still have one event array, one currency cache, one suspension flag, and one list of saved stops. A second filter would have nowhere to keep its own state. For two filters, the state needs an owner smaller than the program. A class provides one, because each object of a class carries its own copy of every non-static member.

What Moves, and Where It Goes

Each piece of the current EA's news code now has a corresponding place in the new header:

In the previous EA In NewsFilter.mqh Why
Inputs declaration SNewsFilterConfig fields, filled by the EA
Inputs declared in a header appear in the EAs that include it
newsEvents[], newsEventsLoaded Private member Each filter loads its own events
cachedCurrencies[], cachedCurrencyCount, currencyCacheValid Private member Each filter resolves relevance for its own symbol
savedStops[], newsSuspended Private member Each filter tracks the positions it suspended
lastCalendarLoad Private member Each filter reloads on its own timer
CTrade trade, shared with the EA Private member the filter owns No borrowed object and no naming rule
The detection, suspension and persistence functions
Methods of the class, most of them private The decisions are the same, and the actions that differ are listed in Section 2 of the article
newsConfig Private member, filled from the configuration  Each filter classifies with its own threshold and its own routine and special windows
lastNewsState, a static local in OnTick()
Private member A static local would be shared by every object 
g_newsRules[] in NewsRules.mqh Unchanged, still at file scope
Deliberate, and covered in Section 2


Section 2: The Filter as a Class

NewsFilter.mqh includes the standard trade library and NewsRules.mqh. It has an include guard and a #property description, and it declares no inputs.

The Configuration

Each setting that was an input becomes a field in a configuration structure, and the EA fills in the fields.

//+------------------------------------------------------------------+
//| What one filter instance is asked to do                          |
//+------------------------------------------------------------------+
struct SNewsFilterConfig
  {
   //--- Detection
   bool              enabled;
   ENUM_NEWS_TIER    minimumTier;
   int               minutesBefore;
   int               minutesAfter;
   int               specialMinutesBefore;
   int               specialMinutesAfter;
   string            currencyOverride;

   //--- Responses
   bool              blockNewTrades;
   bool              closeTradesOnWindowStart;
   bool              suspendStops;

   //--- Positions that closing and suspending reach
   ulong             magicNumber;          // Positions opened with this magic number
   bool              allPositionsOnSymbol; // Every position on the symbol, whoever opened it

   //--- Rule table
   bool              useBuiltInRules;
   string            rulesFile;

   //--- Data sources
   string            historyFile;
   int               cacheReloadHours;

   //--- Identity
   string            statePrefix;

   //--- Diagnostics
   bool              verbose;

   void              SetDefaults(void);
  };

The structure has eighteen fields. The detection fields set which events count and how much room a routine release and a special release get. The three response flags decide what this instance does when a window opens, and they are usually what distinguishes one filter from another in the same EA. The two position fields decide which positions closing and suspending reach, and on their defaults they reach none. statePrefix, together with the symbol, names this instance's saved state; its use is covered under Names for Persistent State.

Sixteen of the eighteen fields belong to the filter that receives them. The two under Rule table, useBuiltInRules and rulesFile, describe the table that every filter in the program shares. Whichever enabled filter starts first builds the table from its own pair, and a later filter builds it again only if it is still empty, so every filter should receive the same two values. A rule in that table can also set its own minutes for a release, and those minutes replace the window fields in every filter. Both points are covered under One Rule Table, Many Filters.

//+------------------------------------------------------------------+
//| Starting values, so an EA overrides only what it cares about     |
//+------------------------------------------------------------------+
void SNewsFilterConfig::SetDefaults(void)
  {
   enabled                  = false;
   minimumTier              = NEWS_TIER_HIGH;
   minutesBefore            = 5;
   minutesAfter             = 5;
   specialMinutesBefore     = 30;
   specialMinutesAfter      = 60;
   currencyOverride         = "";

   blockNewTrades           = true;
   closeTradesOnWindowStart = false;
   suspendStops             = false;

   magicNumber              = 0;
   allPositionsOnSymbol     = false;

   useBuiltInRules          = true;
   rulesFile                = "NewsRules.csv";

   historyFile              = "HistoricalNews.csv";
   cacheReloadHours         = 6;

   statePrefix              = "Harbinger_";

   verbose                  = false;
  }

An EA calls SetDefaults() first and then sets only the fields it wants to change. The defaults are the values the current EA's inputs ship with, so a filter left on its defaults and switched on makes the same decisions as that EA. Passing the settings as a structure also lets the filter grow without breaking an EA that fills it this way. A setup function with eighteen parameters has to be called with every argument in the right order. A nineteenth can be added without breaking existing calls only at the end of the list and only with a default value, and every call still passes the first eighteen by position.

A new field in the structure gets its value in SetDefaults(), so an EA that calls SetDefaults() and assigns fields by name still compiles and runs with the default for a field it never mentions. The protection depends on that habit. An EA that skips SetDefaults() and assigns every field itself leaves a field added later without a value. The rule classifier the filter calls receives its settings the same way.

The Class

//+------------------------------------------------------------------+
//| CNewsFilter                                                      |
//+------------------------------------------------------------------+
class CNewsFilter
  {
private:
   SNewsFilterConfig m_cfg;
   SNewsConfig       m_ruleCfg;      // What the classifier needs, derived from m_cfg
   string            m_symbol;
   CTrade            m_trade;        // Owned, not borrowed from the host EA

   //--- Loaded events
   SNewsEvent        m_events[];
   bool              m_loaded;
   datetime          m_lastLoad;

   //--- Currency relevance
   string            m_currencies[];
   int               m_currencyCount;
   bool              m_currencyValid;

   //--- Stop suspension
   SavedStops        m_savedStops[];
   bool              m_suspended;
   bool              m_lastNewsState;

   //--- Internals
   void              DeriveRuleConfig(void);
   string            RelevantCurrencies(void);
   void              BuildCurrencyCache(void);
   void              MarkSymbolRelevance(void);
   void              LoadCalendar(void);
   bool              LoadHistoryFile(void);

   string            StateName(const string suffix);
   void              SaveState(void);
   void              LoadState(void);
   void              ClearState(void);

   bool              PositionInScope(void);
   void              SetSuspension(const bool suspend);
   bool              RestoreOne(const ulong ticket, double sl, double tp);
   void              CloseAll(void);

   void              Log(const string text);

public:
                     CNewsFilter(void);

   bool              Init(const SNewsFilterConfig &cfg, const string symbol);
   void              Update(void);

   bool              IsNewsTime(void);
   bool              CanOpenNewTrade(void);
   bool              IsSuspended(void)   { return m_suspended; }
   int               EventCount(void)    { return ArraySize(m_events); }
   string            Name(void)          { return m_cfg.statePrefix; }
  };

Each global from the EA's news code is now a member with an m_ prefix. Two CNewsFilter objects, therefore, hold two event arrays, two currency caches, two suspension flags, and two lists of saved stops. What they still share lies outside the objects: the rule table, which stays at file scope deliberately; the terminal's global variables, where each filter's saved state is kept apart by name; and the positions on the symbol, which both can act on.

The CTrade object is a member too. The filter creates and owns it, so the EA does not need a trade object with a particular name, and settings the EA applies to its own CTrade never reach the filter's requests. That is one way to remove the borrowed object, and it asks the least of the EA. Passing a configured CTrade into Init(), or the execution settings through the configuration, would also work and would let the EA decide how the filter's requests are sent. The cost of the choice made here is that the filter's CTrade stays on the standard library's defaults apart from the magic number, which Init() takes from the configuration: a close is sent with a deviation of 10 points, and the filling mode is left to CTrade's own check against the symbol.

The public section contains the constructor, four functions, and three accessors. The fifteen internal functions are private. Twelve of them were global functions in the EA, and StateName(), Log() and PositionInScope() are new. Once other EAs include the file, a change to a function they can call can break them, so the public part is kept to what an EA needs. The accessors report whether stops are suspended, how many events were loaded and the instance's prefix. They are there for a chart comment or a startup line, and the filter's own logic does not use them.

Setting Up One Filter

//+------------------------------------------------------------------+
//| Set up one filter                                                |
//+------------------------------------------------------------------+
bool CNewsFilter::Init(const SNewsFilterConfig &cfg, const string symbol)
  {
   m_cfg    = cfg;
   m_symbol = (StringLen(symbol) > 0) ? symbol : _Symbol;

//--- A position this filter closes is closed under the EA's magic number
   m_trade.SetExpertMagicNumber(m_cfg.magicNumber);

   DeriveRuleConfig();

//--- A reload interval below one hour is read as one hour, and the log says so
   if(m_cfg.cacheReloadHours < 1)
     {
      m_cfg.cacheReloadHours = 1;
      Log("A cache reload interval below one hour was read as one hour.");
     }

//--- Read back a suspension this filter left unfinished. A filter that is
//--- switched off reads it too, so its first tick can put the stops back
   LoadState();

//--- A window that is already open is reported by the first tick
   m_lastNewsState = false;

   if(!m_cfg.enabled)
     {
      Log("Filter disabled.");
      return true;
     }

//--- The rule table is shared by every instance in this program
   if(NewsRules_Count() == 0)
      NewsRules_Build(m_ruleCfg);
   else
      Log(StringFormat("Reusing the rule table already built (%d rules).", NewsRules_Count()));

   BuildCurrencyCache();

//--- In the tester the file is the only source of events
   bool hasEvents = true;
   if(MQLInfoInteger(MQL_TESTER))
      hasEvents = LoadHistoryFile();
   else
      LoadCalendar();

   MarkSymbolRelevance();

//--- An enabled filter that cannot detect anything reports a setup problem
   if(!m_currencyValid)
     {
      Log("Caution: no currency mapping for " + m_symbol + ", this filter will detect nothing.");
      return false;
     }
   if(!hasEvents)
     {
      Log("Caution: no events were kept from the historical file, this filter will detect nothing in this test.");
      return false;
     }

//--- Closing and suspending reach no position until the filter is told whose
   if((m_cfg.closeTradesOnWindowStart || m_cfg.suspendStops) &&
      !m_cfg.allPositionsOnSymbol && m_cfg.magicNumber == 0)
     {
      Log("Caution: no magic number is set, so this filter will close or suspend no position.");
      return false;
     }

   return true;
  }

Init() takes a configuration and a symbol: an empty symbol string selects the chart symbol. A cacheReloadHours below 1 is read as 1, with a line in the log, because a zero would make the live filter query the calendar again as often as once a second. Any suspension this filter left unfinished is then read back from the terminal. That happens before the enabled check, so a filter that has been switched off still learns that its stops are off, and its first tick can put them back. Init() does not record whether a window is open: the first tick reports an open window as a window opening, as the previous EA did, so a filter started inside a window still runs its responses for that window. For an enabled filter, the rule table is built next, because every event is classified against it. The currency cache follows, and then the loader runs, reading the historical file in the tester and the calendar in live trading. Currency relevance is then marked once for all loaded events, so the per-tick scan does not repeat that comparison.

Init() returns false in three cases. In the first two, the filter is switched on but cannot detect anything. In the first, it could not work out which currencies its symbol depends on. That filter loads events, marks none of them as relevant, and reports no news for as long as it runs. In the second, it is running in the Strategy Tester and kept no events from the historical file, because no file is named, the file cannot be opened, or it holds no valid line at or above the filter's tier. In the third, closing or suspending is switched on while magicNumber is 0 and allPositionsOnSymbol is off. That filter still detects windows and blocks entries, but it closes no position and removes no stop.

In the first two cases, the class is not fail-safe on its own. In either of them, IsNewsTime() returns false. As a result, CanOpenNewTrade() allows all trades even though the settings imply the EA is protected. Init() reports the problem once, at initialization, and what to do about it is the EA's decision. The EA later in this article refuses to start. Live trading has a case that Init() does not report at all. A calendar that returns no records is treated as a quiet day, and the filter then detects nothing until its next reload. A query that fails is logged with the error code GetLastError() returns for it, such as 5401 for a request that timed out. It keeps the events already loaded and is tried again a minute later.

The tier threshold is applied when events load. Each loader classifies an event and keeps it only if its tier reaches this instance's minimumTier. Two filters with different thresholds, therefore, hold different event arrays from the same calendar. In the EA below, the entry filter keeps every event from High upwards, and the management filter keeps only the events the rules mark as special. The narrower filter, therefore, has a shorter list to scan on each tick, and its initialization line reports how many events it kept.

The Classifier's Settings

//+------------------------------------------------------------------+
//| The classifier's view of this instance's configuration           |
//+------------------------------------------------------------------+
void CNewsFilter::DeriveRuleConfig(void)
  {
   m_ruleCfg.SetDefaults();

   m_ruleCfg.minimumTier      = m_cfg.minimumTier;
   m_ruleCfg.defaultBefore    = MathMax(0, m_cfg.minutesBefore);
   m_ruleCfg.defaultAfter     = MathMax(0, m_cfg.minutesAfter);
   m_ruleCfg.specialBefore    = MathMax(0, m_cfg.specialMinutesBefore);
   m_ruleCfg.specialAfter     = MathMax(0, m_cfg.specialMinutesAfter);
   m_ruleCfg.loadBuiltInRules = m_cfg.useBuiltInRules;
   m_ruleCfg.rulesFile        = m_cfg.rulesFile;
   m_ruleCfg.verbose          = m_cfg.verbose;

//--- A window below zero is read as zero, and the log says so
   if(m_cfg.minutesBefore < 0 || m_cfg.minutesAfter < 0 ||
      m_cfg.specialMinutesBefore < 0 || m_cfg.specialMinutesAfter < 0)
      Log("A window setting below zero was read as zero.");
  }
The classifier has its own settings structure, and each filter fills one from its configuration. Two instances can therefore share one rule table while using different tier thresholds and different windows for routine and special releases. A release whose rule sets its own minutes is the exception, covered under One Rule Table, Many Filters. A window setting below zero is copied as zero, and the filter says so in the log.

The Scan and the Gate

//+------------------------------------------------------------------+
//| Is this instance inside a news window right now?                 |
//+------------------------------------------------------------------+
bool CNewsFilter::IsNewsTime(void)
  {
   if(!m_cfg.enabled)
      return false;

   datetime now = TimeCurrent();

//--- Live mode refreshes the source on a timer
   if(!MQLInfoInteger(MQL_TESTER))
     {
      if(m_lastLoad == 0 || (now - m_lastLoad) > (datetime)m_cfg.cacheReloadHours * 3600)
        {
         LoadCalendar();
         MarkSymbolRelevance();
        }
     }

   if(!m_loaded || !m_currencyValid)
      return false;

   for(int i = 0; i < ArraySize(m_events); i++)
     {
      if(!m_events[i].affectsSymbol)
         continue;

      datetime windowStart = m_events[i].time - (m_events[i].minutesBefore * 60);
      datetime windowEnd   = m_events[i].time + (m_events[i].minutesAfter * 60);

      if(now >= windowStart && now <= windowEnd)
         return true;
     }

   return false;
  }

In live trading, each instance reloads the calendar on its own timer, controlled by cacheReloadHours. In the tester, the file loaded at initialization is the only source. The scan then goes through the events loaded by this filter, skips those that do not affect its symbol, and compares the current time with each event's window. The minutes before and after are set by the classifier when the event is read, so a special release carries its own window into the scan without any extra check here. The scan has no tier test either, because the loaders stored only the events that passed the threshold. It also no longer prints a line naming the event it found.

In the previous EA, that line was guarded by a static local variable, which every object of the class would share, so the window messages from Update() are what the log shows now. With verbose switched on, the calendar loader prints one line per kept event, giving its time, currency, tier, window in minutes on either side, and name. Reading those lines on the first run shows which events this instance will react to before any window opens. The historical file loader used in the tester prints only its summary line, with the number of lines read, events kept, and special events among them.

The check an EA makes before opening a position is short:

//+------------------------------------------------------------------+
//| The gate an EA calls before opening a position                   |
//+------------------------------------------------------------------+
bool CNewsFilter::CanOpenNewTrade(void)
  {
   if(!m_cfg.enabled)
      return true;
   if(!m_cfg.blockNewTrades)
      return true;

   return !IsNewsTime();
  }

A filter that is switched off, or one configured not to block entries, returns true without scanning. Otherwise, the gate runs the scan, and Update() has already run it once on the same tick, so on a tick where the EA asks the gate, that filter goes through its event list twice. The gate also returns true when the filter has nothing to detect with, because IsNewsTime() returns false in that state.

Per-Tick Work

//+------------------------------------------------------------------+
//| Per-tick work: detect the window opening and closing, and run    |
//| whichever responses this instance was configured for             |
//+------------------------------------------------------------------+
void CNewsFilter::Update(void)
  {
   bool currentState = IsNewsTime();
   bool changed      = (currentState != m_lastNewsState);

   if(changed)
     {
      if(currentState)
        {
         Log("--- NEWS WINDOW STARTED ---");

         if(m_cfg.closeTradesOnWindowStart)
            CloseAll();

         if(m_cfg.suspendStops)
            SetSuspension(true);
        }
      else
         Log("--- NEWS WINDOW ENDED ---");

      m_lastNewsState = currentState;
     }

//--- Stops go back on the first tick on which this filter is not holding
//--- them off for an open window of its own
   bool holding = (m_cfg.suspendStops && currentState);
   if(m_suspended && !holding)
     {
      //--- Anything but the ordinary end of a window gets a line of its own
      if(currentState || !changed)
         Log("Stops are suspended and this filter is not holding them off. Restoring them now.");

      SetSuspension(false);
     }
  }

Update() detects a window opening or closing and runs the responses configured for this instance. It has no enabled check of its own. IsNewsTime() returns false for a filter that is switched off, so such a filter never sees a window open, and only the last test in the function can act for it. The transition logic is the one in the current EA's tick handler. What the filter does differently is listed here, and Names for Persistent State adds one more case:

  1. Where the previous state is kept. The current EA keeps it in a static local variable, and a static local variable inside a class method is shared by every object of the class, so two filters would overwrite each other's record of whether a window was open. The class keeps it in the member m_lastNewsState.
  2. When the stops come back. The current EA restores them only on the tick that reports the window's end. The class restores them on the first tick on which its saved state says they are off and it is not holding them off for an open window of its own. In normal running, that is the same tick. The test also covers a terminal restarted after the window had closed, a filter switched off while its stops were off, and a filter whose suspendStops setting was cleared in the meantime.
  3. Which positions are touched. SetSuspension() and CloseAll() act only on positions that pass PositionInScope(): on the filter's symbol and carrying its magicNumber. The default of 0 selects none, because manual trades and requests sent without a number carry 0. allPositionsOnSymbol, off by default, widens the scope to every position on the symbol, manual trades included. The current EA closed positions on the chart symbol and removed stops from every position in the account, whoever had opened them.
  4. A position with nothing to restore. A position that had neither a stop nor a target when the window opened is left untouched when it closes.
  5. A saved level the price has come close to. The restore compares each saved level with the broker's minimum stop distance. If the price has passed the level, or stands closer to it than that distance, the level is placed at the minimum distance from the current price. The current EA moved a level only after the price had passed it, so a level that was merely too close was sent as saved, which a broker with a stops level refuses.

One Rule Table, Many Filters

The rule table is not a member. It stays at file scope in NewsRules.mqh, and every filter in the program reads the same table. The table records which kinds of release the trader has chosen to treat as special, such as a rate decision. That choice is made once for the program, and two filters in one EA should not work from different versions of it. How much room to give such a release depends on the instrument and the strategy, and two filters can reasonably differ on it. So the table is shared, and the windows and the tier threshold are set per instance in the configuration.

There is one exception. A rule that states its own minutes carries them in the shared table, so every filter uses those minutes for that release, whatever its own settings say. With the sample rules file from the previous part in place, both filters in the EA below would give the FOMC press conference 20 minutes before and 90 after.

Init() checks NewsRules_Count() before building. The first enabled filter to start builds the table from its own useBuiltInRules and rulesFile. A later filter uses that table without reading its own pair, unless the table is still empty. Which filter is first depends on the order of the Init() calls and on which filters are switched on, so the two rule settings are settings of the program and should be the same in every configuration. The EA below passes both filters the same pair through one helper, which makes the table the same whichever filter builds it. If two filters did name different rule files, the second file would not be read once the first had produced any rules. The log line about reusing the table shows that it happened, without naming the file that was skipped, and the code does not prevent the conflict.

File-scope data is not reset when OnInit() runs again after a symbol or timeframe change, so the EA has to empty the table with NewsRules_Reset() at the top of OnInit(). Without that call, the first filter would find the table from the previous pass and reuse it, and a changed rules file would not be read.

Names for Persistent State

The current EA saves suspended stops in terminal global variables whose names start with Harbinger_. Part 3, where that persistence was introduced, noted that running more than one instance would require a longer naming scheme. In the class, every name the filter writes is built by one function, from the prefix and the filter's symbol:

//+------------------------------------------------------------------+
//| Terminal global variable name for this instance                  |
//+------------------------------------------------------------------+
string CNewsFilter::StateName(const string suffix)
  {
   return m_cfg.statePrefix + m_symbol + "_" + suffix;
  }
//+------------------------------------------------------------------+
//| Write the suspension snapshot                                    |
//+------------------------------------------------------------------+
void CNewsFilter::SaveState(void)
  {
   int count = ArraySize(m_savedStops);

   GlobalVariableSet(StateName("Stop_Count"), count);
   GlobalVariableSet(StateName("NewsSuspended"), m_suspended ? 1 : 0);

   for(int i = 0; i < count; i++)
     {
      string base = StateName("Stop_" + IntegerToString(i));

      GlobalVariableSet(base + "_Ticket", (double)m_savedStops[i].ticket);
      GlobalVariableSet(base + "_SL", m_savedStops[i].sl);
      GlobalVariableSet(base + "_TP", m_savedStops[i].tp);
     }

   Log("Persistent stop state saved.");
  }

With the default prefix on EURUSD, the names are:

Harbinger_EURUSD_Stop_Count

Harbinger_EURUSD_Stop_0_Ticket

Harbinger_EURUSD_NewsSuspended

A name is the prefix, the filter's symbol, and a fixed suffix, which is also how each of the filter's log lines starts. Prefixes keep two filters in one EA apart, and the symbol keeps the same EA on charts of different symbols apart, so the two fixed prefixes in this article's EA do not collide between such charts. One case is left. Two filters with the same prefix on the same symbol, in one EA or on two charts, write to the same names, and the one that saves last overwrites the other's levels. Give every filter on a symbol its own prefix, and keep it short, because a terminal variable name can be at most 63 characters.

The names have two limits. They differ from the names the previous EA wrote, which had no symbol in them, so a filter does not find a suspension that EA saved. They also carry no account number. If the terminal is connected to another account while a suspension is saved, the EA is loaded again there with a record that refers to the first account's tickets. In the usual case, none of those tickets exists on the new account, so nothing is restored and the record is cleared.

A ticket is saved as a double, because that is the only type a terminal variable holds. A double carries every whole number exactly only up to 2^53. A position with a ticket above that keeps its stops through the window, with a line in the log, because its number could not be read back exactly after a restart.


Section 3: The EA That Holds Two Filters

The EA that uses the header is NewsIntegration_Part6.mq5.

Installing the File

NewsFilter.mqh goes into MQL5\Include\NewsFilterSuite\, beside NewsTypes.mqh and NewsRules.mqh, and the EA includes it with angle brackets:

#include <Trade/Trade.mqh>
#include <NewsFilterSuite/NewsFilter.mqh>

NewsFilter.mqh includes NewsRules.mqh, which includes NewsTypes.mqh, so the one line brings in all three files. Each file has an include guard, so an EA that also includes one of them directly does not get duplicate declarations.

On the first run, the Experts tab shows the rule count when the table is built, followed by a currency cache line, a loader line, and a relevance line for each filter. If a filter prints a Caution line, its setup returned false, and the EA in this article stops in OnInit() until the cause is corrected: the symbol or SymbolCurrencyOverride for a missing currency mapping, the historical file for a test that kept no events, or MagicNumber for a filter that would close or suspend without one.

Inputs

//+------------------------------------------------------------------+
//| INPUTS                                                           |
//+------------------------------------------------------------------+
input group "Entry Filter"
input bool   EnableEntryFilter = true;                       // Stand down on news before opening a trade
input ENUM_NEWS_TIER EntryMinimumTier = NEWS_TIER_HIGH;      // Watch this tier and above
input int    EntryMinutesBefore = 5;                         // Minutes before a routine event
input int    EntryMinutesAfter = 5;                          // Minutes after a routine event
input int    EntrySpecialBefore = 30;                        // Minutes before a special event
input int    EntrySpecialAfter = 60;                         // Minutes after a special event
input bool   EntryClosesTrades = false;                      // Also close open trades when the window opens

input group "Management Filter"
input bool   EnableManagementFilter = true;                  // Suspend SL/TP around news
input ENUM_NEWS_TIER ManagementMinimumTier = NEWS_TIER_SPECIAL; // Watch this tier and above
input int    ManagementMinutesBefore = 15;                   // Minutes before a routine event
input int    ManagementMinutesAfter = 15;                    // Minutes after a routine event
input int    ManagementSpecialBefore = 20;                   // Minutes before a special event
input int    ManagementSpecialAfter = 45;                    // Minutes after a special event

input group "Shared Settings"
input ulong  MagicNumber = 60600;                            // This EA's trades. The filters close and suspend only these
input string SymbolCurrencyOverride = "";                    // Manual currency override e.g. "USD,JPY"
input bool   UseBuiltInSpecialRules = true;                  // Load the shipped rule table
input string SpecialRulesFile = "NewsRules.csv";             // Optional rule overrides, blank to skip
input string HistoricalNewsFile = "HistoricalNews.csv";      // CSV file for backtesting news events
input int    CacheReloadHours = 6;                           // How often to reload calendar cache (hours)
input bool   NewsFilterVerbose = false;                      // Print each loaded event and its tier

The EA declares twenty inputs in three groups: one group for each filter and one for the settings both filters use. The EA decides how they are named, grouped, and ordered, since the header no longer declares any. The defaults assign different jobs to the two filters:

Setting Entry filter Management
What it does
Blocks new trades Suspends stops
Tier watch High and above Special only
Routine window 5 minutes either side 15 minutes either side
Special window 30 before, 60 after 20 before, 45 after
State prefix Harbinger_ Harbinger_Manage_

A blocked entry usually costs no more than a trade that might have been taken. A suspended stop leaves an open position without protection until the window closes, so a large move during that period has no stop to limit the loss. For that reason, the entry filter stands down for every release it keeps at the High tier or above and gives special releases a wider margin, while the management filter removes stops only around special releases and restores them sooner. The window lengths are defaults for the trader to change: none of them were derived from measurement. The management filter's routine window applies only if its tier is lowered, because at the special tier it keeps no routine events. A rule that states its own minutes replaces these windows in both filters, as One Rule Table, Many Filters explained.

Configuring Both

One helper copies the shared inputs into a configuration, so each shared setting is assigned in one place and both filters receive the same rule settings:

//+------------------------------------------------------------------+
//| Settings shared by both instances                                |
//+------------------------------------------------------------------+
void ApplySharedSettings(SNewsFilterConfig &cfg)
  {
   cfg.magicNumber      = MagicNumber;
   cfg.currencyOverride = SymbolCurrencyOverride;
   cfg.useBuiltInRules  = UseBuiltInSpecialRules;
   cfg.rulesFile        = SpecialRulesFile;
   cfg.historyFile      = HistoricalNewsFile;
   cfg.cacheReloadHours = CacheReloadHours;
   cfg.verbose          = NewsFilterVerbose;
  }

OnInit() builds the two configurations and starts both filters:

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
   Print("News Filter Part 6 initialized");

//--- The EA's own trades carry the number the filters act on
   trade.SetExpertMagicNumber(MagicNumber);

//--- File-scope data is not reset when OnInit() runs again,
//--- so both filters start from an empty rule table
   NewsRules_Reset();

//--- The entry filter. Blocks new trades, and closes open ones
//--- only if EntryClosesTrades is set
   SNewsFilterConfig entryCfg;
   entryCfg.SetDefaults();
   ApplySharedSettings(entryCfg);

   entryCfg.enabled                  = EnableEntryFilter;
   entryCfg.minimumTier              = EntryMinimumTier;
   entryCfg.minutesBefore            = EntryMinutesBefore;
   entryCfg.minutesAfter             = EntryMinutesAfter;
   entryCfg.specialMinutesBefore     = EntrySpecialBefore;
   entryCfg.specialMinutesAfter      = EntrySpecialAfter;
   entryCfg.blockNewTrades           = true;
   entryCfg.closeTradesOnWindowStart = EntryClosesTrades;
   entryCfg.suspendStops             = false;
   entryCfg.statePrefix              = "Harbinger_";

   if(!entryFilter.Init(entryCfg, _Symbol))
     {
      Print("Entry filter reported a setup problem. Check the log above.");
      return INIT_FAILED;
     }

//--- The management filter. Suspends stops
   SNewsFilterConfig manageCfg;
   manageCfg.SetDefaults();
   ApplySharedSettings(manageCfg);

   manageCfg.enabled                  = EnableManagementFilter;
   manageCfg.minimumTier              = ManagementMinimumTier;
   manageCfg.minutesBefore            = ManagementMinutesBefore;
   manageCfg.minutesAfter             = ManagementMinutesAfter;
   manageCfg.specialMinutesBefore     = ManagementSpecialBefore;
   manageCfg.specialMinutesAfter      = ManagementSpecialAfter;
   manageCfg.blockNewTrades           = false;
   manageCfg.closeTradesOnWindowStart = false;
   manageCfg.suspendStops             = true;
   manageCfg.statePrefix              = "Harbinger_Manage_";

   if(!managementFilter.Init(manageCfg, _Symbol))
     {
      Print("Management filter reported a setup problem. Check the log above.");
      return INIT_FAILED;
     }

   return INIT_SUCCEEDED;
  }

OnInit() first gives the EA's own CTrade the MagicNumber input, so its test trades carry the number both filters act on, and then empties the shared rule table, for the reason given under One Rule Table, Many Filters. Each configuration then starts from the defaults, takes the shared settings, and finally its instance-specific settings. The entry filter has suspendStops set to false and the management filter has blockNewTrades set to false, so only the management filter suspends stops and only the entry filter blocks entries.

When a filter's Init() returns false, the EA prints a line pointing back to that filter's warning and returns INIT_FAILED. That is a choice made in this EA, and the class does not enforce it: an EA that ignored the return value would keep running, with that filter letting every trade through. The previous EA made no such check and always started, so the two differ here. Switch the filter off, or correct the cause, and attach the EA again.

Per Tick

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//--- Each filter runs its own responses
   entryFilter.Update();
   managementFilter.Update();

// Temporary trade simulator for testing (remove this after full verification) ---
   static datetime lastTradeTime = 0;
   if(MQLInfoInteger(MQL_TESTER) && !MQLInfoInteger(MQL_OPTIMIZATION))    // Only enabled for single backtest
     {
      if(TimeCurrent() - lastTradeTime >= 3600)    // Every hour
        {
         //--- One gate, one filter. The management filter is never asked
         if(!entryFilter.CanOpenNewTrade())
            return;

         if(PositionsTotal() == 0)    // No open positions
           {
            double price = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
            double sl = price - 200 * _Point;
            double tp = price + 200 * _Point;
            double lot = 0.01;
            if(trade.Buy(lot, _Symbol, 0, sl, tp, "Test Trade"))
               Print("Opened test trade at ", TimeToString(TimeCurrent()));
            lastTradeTime = TimeCurrent();
           }
        }
     }
  }

The tick handler has two parts, and only the first belongs to the integration. That part is three lines: the two Update() calls at the top, and the CanOpenNewTrade() check that an EA makes before it opens a trade. Only the entry filter is asked, because it is the only one configured to block entries. Reloading the calendar, reading the CSV file, matching currencies, checking windows, and tracking transitions all happen inside the filter objects.

Everything else, from the static lastTradeTime line down, is a test harness wrapped around that check. It opens a 0.01-lot buy when no position is open and an hour has passed since the last one, so the filters have a position to act on. Its condition limits it to a single Strategy Tester run, so it does not trade on a live chart. In an EA that trades its own signals, delete the harness and keep the three lines, with the gate placed in front of that EA's own entry code.

Reading the Log

Each line printed by a filter starts with its prefix and symbol in brackets, so the two filters' messages can be distinguished in the same Experts tab.

CS      0       17:06:10.011    NewsIntegration_Part6 (EURUSD,M15)      2026.06.01 00:00:00   News Filter Part 6 initialized
CS      0       17:06:10.011    NewsIntegration_Part6 (EURUSD,M15)      2026.06.01 00:00:00   NewsRules: 34 rules active (34 built-in, 0 from file).
CS      0       17:06:10.011    NewsIntegration_Part6 (EURUSD,M15)      2026.06.01 00:00:00   [Harbinger_EURUSD] Currency cache built: EUR,USD
CS      0       17:06:11.830    NewsIntegration_Part6 (EURUSD,M15)      2026.06.01 00:00:00   [Harbinger_EURUSD] Historical file: 6544 lines read, 5707 events kept, 1121 special.
CS      0       17:06:11.831    NewsIntegration_Part6 (EURUSD,M15)      2026.06.01 00:00:00   [Harbinger_EURUSD] 4377 of 5707 loaded events affect EURUSD.
CS      0       17:06:11.831    NewsIntegration_Part6 (EURUSD,M15)      2026.06.01 00:00:00   [Harbinger_Manage_EURUSD] Reusing the rule table already built (34 rules).
CS      0       17:06:11.831    NewsIntegration_Part6 (EURUSD,M15)      2026.06.01 00:00:00   [Harbinger_Manage_EURUSD] Currency cache built: EUR,USD
CS      0       17:06:11.904    NewsIntegration_Part6 (EURUSD,M15)      2026.06.01 00:00:00   [Harbinger_Manage_EURUSD] Historical file: 6544 lines read, 1121 events kept, 1121 special.
CS      0       17:06:11.904    NewsIntegration_Part6 (EURUSD,M15)      2026.06.01 00:00:00   [Harbinger_Manage_EURUSD] 671 of 1121 loaded events affect EURUSD.

CS      0       17:09:40.062    Trade   2026.06.05 10:33:40   deal performed [#22 buy 0.01 EURUSD at 1.16332]
CS      0       17:09:40.062    Trade   2026.06.05 10:33:40   order performed buy 0.01 at 1.16332 [#22 buy 0.01 EURUSD at 1.16332]
CS      0       17:09:40.064    NewsIntegration_Part6 (EURUSD,M15)      2026.06.05 10:33:40   CTrade::OrderSend: market buy 0.01 EURUSD sl: 1.16132 tp: 1.16532 [done at 1.16332]
CS      0       17:09:40.064    NewsIntegration_Part6 (EURUSD,M15)      2026.06.05 10:33:40   Opened test trade at 2026.06.05 10:33
CS      0       17:09:47.240    NewsIntegration_Part6 (EURUSD,M15)      2026.06.05 15:00:00   [Harbinger_EURUSD] --- NEWS WINDOW STARTED ---
CS      0       17:09:47.496    NewsIntegration_Part6 (EURUSD,M15)      2026.06.05 15:10:00   [Harbinger_Manage_EURUSD] --- NEWS WINDOW STARTED ---
CS      0       17:09:47.496    Trade   2026.06.05 15:10:00   position modified [#22 buy 0.01 EURUSD 1.16332]
CS      0       17:09:47.498    NewsIntegration_Part6 (EURUSD,M15)      2026.06.05 15:10:00   CTrade::OrderSend: modify position #22 EURUSD (sl: 0.00000, tp: 0.00000) [done]
CS      0       17:09:47.498    NewsIntegration_Part6 (EURUSD,M15)      2026.06.05 15:10:00   [Harbinger_Manage_EURUSD] Suspended trade #22: SL/TP removed for news.
CS      0       17:09:47.498    NewsIntegration_Part6 (EURUSD,M15)      2026.06.05 15:10:00   [Harbinger_Manage_EURUSD] Persistent stop state saved.
CS      0       17:10:07.212    NewsIntegration_Part6 (EURUSD,M15)      2026.06.05 16:15:01   [Harbinger_Manage_EURUSD] --- NEWS WINDOW ENDED ---
CS      0       17:10:07.212    Trade   2026.06.05 16:15:01   position modified [#22 buy 0.01 EURUSD 1.16332 sl: 1.15951 tp: 1.16532]
CS      0       17:10:07.214    NewsIntegration_Part6 (EURUSD,M15)      2026.06.05 16:15:01   CTrade::OrderSend: modify position #22 EURUSD (sl: 1.15951, tp: 1.16532) [done]
CS      0       17:10:07.214    NewsIntegration_Part6 (EURUSD,M15)      2026.06.05 16:15:01   [Harbinger_Manage_EURUSD] Restored SL/TP for #22 | SL=1.15951, TP=1.16532
CS      0       17:10:07.214    NewsIntegration_Part6 (EURUSD,M15)      2026.06.05 16:15:01   [Harbinger_Manage_EURUSD] Persistent stop data cleared.

The log comes from one run of this EA in the Strategy Tester, and the lines between the start of the run and the trade of 2026.06.05 are left out. The run used these settings:

Setting Value
Symbol, timeframe EURUSD, M15
Dates 2026.06.01 to 2026.06.29
Data MetaQuotes-Demo, hedging demo account
Modelling Every tick based on real ticks, no delay
Deposit, leverage 100,000 USD, 1:100
Inputs Defaults, except EntryMinutesBefore 30, EntryMinutesAfter 30, SpecialRulesFile blank, NewsFilterVerbose true
The counts in the first lines depend on HistoricalNews.csv. The one used here is an export of the MetaQuotes-Demo calendar in the four-column layout of Part 4, with 6,543 events from 2020.01.01 to 2026.06.29 and a header line. A file exported from another broker or over another range holds other events and gives other counts.

With the default special windows, when both filters react to the same special release, the entry filter's window opens first and closes last, and the management filter's window sits inside it. The log shows the opening order, with the entry filter at 15:00 and the management filter at 15:10, and the stops are off only for the shorter period.

The restore line shows what a suspension can cost. The stop was removed from 1.16132 and came back at 1.15951. While it was off, the price fell through the saved level, so the restore placed the stop at the broker's minimum distance from the current price, as Per-Tick Work describes. The position carried that extra loss with no stop to limit it.

Moving an EA Across

An EA running the previous version can move to the class without changing what its filter decides. A filter left on SetDefaults() and then switched on makes the same decisions as that EA, because the defaults match its input values. NewsRules.csv in the common files folder is read by the same code in NewsRules.mqh, so the rule file needs no change. A suspension in progress does not carry over: the class writes its terminal variables under names that include the symbol, so no filter built on it finds stops the previous EA saved. Make the move while no suspension is in progress.

The migration itself has four steps:

  1. Remove the news code from the EA: its inputs, its globals, the SavedStops structure, and the news functions. NewsFilter.mqh declares SavedStops as well, so that structure left in place stops the EA from compiling with a redefinition error. Keep the EA's CTrade object if its own trading code uses it.
  2. Add #include <NewsFilterSuite/NewsFilter.mqh> and declare one CNewsFilter object at file scope.
  3. In OnInit(), call NewsRules_Reset(), fill an SNewsFilterConfig from whichever inputs the EA keeps, set its magicNumber to the EA's own magic number, pass it to Init(), and decide what a false return means for the EA.
  4. Call Update() at the top of OnTick(), and call CanOpenNewTrade() wherever the EA used to check the news window before opening a trade.


    What This Part Does Not Do

    Only one filter per symbol should be configured to suspend stops, whether the filters sit in one EA or on different charts of the terminal. Two instances removing and restoring stops on the same positions would interfere with each other. The filter whose window opens second finds no stops to save, and the stops come back when the first filter's window closes, even if the second filter's window is still open. The EA above sets suspendStops on one filter only, and nothing in the class enforces that.

    The rule table is shared, and the first enabled filter whose settings produce any rules decides which rule file is used and whether the built-in rules are loaded. A second filter configured differently uses the first filter's table, and its log says the table was reused. A filter that cannot detect anything does not block trading by itself. Init() reports the two such cases it can see at initialization, and an EA that ignores the report trades with that filter letting everything through.

    With two filters on one symbol, each instance loads its own events and scans its own list on every tick. If a filter also gates entries, it scans again on any tick where the EA calls the gate. The workload grows with the number of filters and the length of each list. A filter acts only on positions on its symbol that carry its magic number, so EAs that share a number share its responses, and with allPositionsOnSymbol on it also reaches manual trades and other EAs' positions on its symbol. Each filter handles one symbol. A second instance can be given a different symbol. It then still does its work on the chart symbol's ticks, and that arrangement has not been tested.

    Suspended stops can stay off in three cases. Nothing puts them back while the terminal is down, or while no filter with that prefix is running on that symbol, which is the state after the EA is removed, its chart is closed, or the chart is switched to another symbol. The saved levels wait in the terminal under that name for up to four weeks, the lifetime of an unused terminal variable, and a filter started there again with the same prefix restores them. A restore that the server refuses is not tried again: the log line gives the ticket and the levels so they can be set by hand, and the record is cleared. A change of account while a suspension is saved loses the record, as Names for Persistent State explained.

    Carried forward from earlier parts: the Strategy Tester needs the historical CSV because the calendar cannot be relied on to return past events there; a position has no stop protection while it is suspended; and rules that match on an event code cannot trigger in a backtest, because the historical file has no code column.


    Conclusion

    Before this part, the news filter protected only the EA it was written in, and a second EA needed its own copy of the code. Moving the code into a header removes the copy but leaves three limits. Inputs declared in a header appear in the EAs that include it, and one set of them gives every filter the same settings. A borrowed trade object ties each EA to one object name and to shared trade settings. State at file scope remains one copy per program, whichever file contains the declaration.

    CNewsFilter addresses all three. The inputs stay in the EA, which fills an SNewsFilterConfig and passes it to Init(), and the filter creates and owns its own CTrade. The events, the currency cache, the saved stops, and the suspension flag are members, so each object has its own set, and the prefix and the symbol name the state each one saves in the terminal. With its default inputs, the EA in this part uses that structure to run two policies on one symbol: the entry filter blocks new trades around the releases it keeps at the High tier and above, and the management filter removes stops only around special ones. Both read the same rule table, and a window that a rule sets applies in both.

    Three limits from the previous section matter most in use. A filter acts on the positions on its symbol that carry its magic number, so EAs that share a number share its responses. A refused restore is not tried again. And a filter that cannot detect anything lets trades through unless the EA acts on what Init() returns.

    The source files are provided below.

    Filename Description
    NewsFilter.mqh The filter as a class: configuration struct, per-instance state, detection, the three responses, and persistent state named by prefix and symbol.
    NewsIntegration_Part6.mq5 The EA that holds two filters, one blocking entries and one suspending stops, and configures both from its own inputs.

    Attached files |
    NewsFilter.mqh (29.69 KB)
    Implementing a Zone-Aware Rollover Window Gate in MQL5 Implementing a Zone-Aware Rollover Window Gate in MQL5
    CTradeWindows blocks EA entries during the daily rollover spread spike. Each window is a clock time in a zone such as New York, so it follows that zone through DST. CSpreadProfile learns the windows from tick spreads and saves them to a file that an EA can load. Unit tests and Strategy Tester runs on one server show that a window fixed in server time misses the spike in weeks when the US and EU DST dates differ.
    A Thin gRPC Inference Client: Serving a Live Python Model to MetaTrader 5 Without ONNX A Thin gRPC Inference Client: Serving a Live Python Model to MetaTrader 5 Without ONNX
    Learn how to connect a LightGBM pipeline with a custom feature transformer to an MQL5 Expert Advisor without converting it to ONNX. The article covers the gRPC service, REST gateway, WebRequest() client, signal and risk logic, and probability indicator. An offline replay approximates the EA’s decisions and compares confidence thresholds across in-sample and out-of-sample data, since WebRequest() fails in the Strategy Tester.
    Detrended Cross-Correlation Analysis (DCCA) for Pairs-Trading Pair Selection Under Nonstationarity Detrended Cross-Correlation Analysis (DCCA) for Pairs-Trading Pair Selection Under Nonstationarity
    A complete, native MQL5 toolkit for Detrended Cross-Correlation Analysis: engine, validator, basket scanner, and a reference spread-trading EA. The engine produces a scale-by-scale rho_DCCA(s) curve and a band-mean score to rank pairs, contrasted with a standard Pearson correlation. The article details the box-detrending approach and shows real Strategy Tester results to illustrate how the gate integrates into trade decisions.
    Neural Networks in Trading: Mesh-Based Approximation of Event Streams as a Tool for Analyzing Price Patterns (Conclusion) Neural Networks in Trading: Mesh-Based Approximation of Event Streams as a Tool for Analyzing Price Patterns (Conclusion)
    The article presents an adaptation of the EEMFlow framework for building highly effective trading models using MQL5. MeshFlow estimation algorithms with advanced feature correlation are considered, allowing for accurate analysis of market dynamics and forecasting of price flows. Testing confirmed positive mathematical expectation, moderate drawdowns and high decision-making efficiency.