preview
Aggregating Multi-Broker Tick Feeds into a Synthetic Mid-Price in MQL5

Aggregating Multi-Broker Tick Feeds into a Synthetic Mid-Price in MQL5

MetaTrader 5 — Trading systems |
50 0
Ushana Kevin Iorkumbul
Ushana Kevin Iorkumbul

Introduction

Every broker quotes its own bid and ask, and those prices rarely match another broker's exactly because of differences in liquidity sourcing, markup, and latency. The gap matters when comparing execution quality, auditing spread widening during news, or building a reference price that does not depend on one broker. MetaTrader 5 has no built-in way to do this, because each terminal is sandboxed and no API lets one terminal read another's live quotes.

The bridge is deliberately simple: shared files on disk. A small Expert Advisor in each broker terminal writes its quote to a broker-named file on every tick. A separate aggregator Expert Advisor reads those files on a timer, computes a volume-weighted mid-price, and writes it to a custom symbol that can be charted. This symbol is not an ordinary market symbol: each bar is flat, the spread is zero, and the volume fields carry diagnostics. Bar times follow the clock only with a 60-second timer, so at other intervals the series suits live monitoring rather than backtesting (see Limitations).

Two problems matter more than the file input and output: how much weight each feed should carry, and what to do when a file stops updating because a terminal disconnected or closed. A synthetic price that silently averages in a frozen quote is worse than none, so the aggregator detects and excludes stale feeds explicitly. We tested the pipeline on three broker demo accounts, and the findings section lists the conditions so that the observations can be reproduced.

Multi-Broker Aggregator Architecture

Broker terminals to shared files to synthetic mid-price symbol

Multi-Broker Aggregator Architecture

Legend:

  • Gray — external boundary: terminals, shared files, and the synthetic chart.
  • Teal — core logic: reading broker files and computing the mid-price.
  • Coral — setup: creating and writing the custom symbol.
  • Navy — orchestrator: the driver Expert Advisor on a fixed timer.

Figure 1: Each broker terminal runs a FeedPublisherEA instance that writes a shared file on every tick. One AggregatorEA instance reads all files on a timer and writes the mid-price to a custom symbol, and the arrow on the right is labeled with the input that sets the interval.


Why File-Based Bridging Is the Right Tool Here

Global variables are scoped to a single terminal, so they cannot bridge separate broker installations, and named pipes and DDE are either deprecated or awkward to configure across many terminals.

A shared file needs only a common folder. The common data folder, reached through FILE_COMMON, is shared by every MetaTrader installation on the same Windows account. Each publisher writes a small file named after its broker, and the aggregator reads the files named in InpBrokerKeys. Adding a broker means running one more publisher and adding its key to that input.

The tradeoff is atomicity, because a reader could catch a file mid-write. A single short line lowers the odds, and share flags on both sides let a read and a write overlap without a file-access failure. If a read still lands mid-write, the reader retries up to three times, and a file that stays unreadable is skipped for that cycle.


SBrokerQuote and the Shared File Format

SBrokerQuote holds one broker's quote after it is parsed back into memory. On disk, each file holds exactly one line with six pipe-delimited fields: broker_name | symbol_name | bid_price | ask_price | available_volume | write_time. The available_volume field holds the broker's tick volume as a weighting signal. The write_time field is a Unix timestamp from TimeCurrent() that drives the staleness check, and it does not prove the price moved (see Limitations).

//+------------------------------------------------------------------+
//|                                                  BrokerQuote.mqh |
//+------------------------------------------------------------------+
#ifndef BROKERQUOTE_MQH
#define BROKERQUOTE_MQH

//+------------------------------------------------------------------+
//| SBrokerQuote                                                     |
//| One broker's parsed quote, read back from its shared file. Each  |
//| data field maps onto one pipe-delimited field of the file.       |
//+------------------------------------------------------------------+
struct SBrokerQuote
  {
   string            broker_name;       // identifying name parsed from the file name and contents
   string            symbol_name;       // symbol the publisher was attached to when it wrote this quote
   double            bid_price;         // broker's current bid
   double            ask_price;         // broker's current ask
   double            available_volume;  // broker's reported tick volume, used only as a weighting signal
   long              write_time;        // Unix timestamp of when the publisher wrote this file
   bool              parsed_ok;         // true if the file parsed cleanly into valid fields

                     SBrokerQuote(void);
  };

//+------------------------------------------------------------------+
//| SBrokerQuote default constructor                                 |
//| Zero-initializes every field so an unparsed quote is never       |
//| mistaken for a valid one further down the pipeline.              |
//+------------------------------------------------------------------+
SBrokerQuote::SBrokerQuote(void)
  {
   broker_name      = "";
   symbol_name      = "";
   bid_price        = 0.0;
   ask_price        = 0.0;
   available_volume = 0.0;
   write_time       = 0;
   parsed_ok        = false;
  }

#endif // BROKERQUOTE_MQH
//+------------------------------------------------------------------+

The most important field is parsed_ok, which the parser sets to false when anything looks wrong. Causes include a missing or extra field, a mismatched broker name or symbol, a non-numeric field, or an ask below the bid. An ask equal to the bid is accepted because some feeds quote a zero spread, and later stages simply skip any quote with parsed_ok false.

Shared File Format — One Line Per Broker

Shared File Format

Legend:

  • Teal — broker_name, the sanitized key used in the file name.
  • Navy — bid_price and ask_price, the raw quote values.
  • Coral — available_volume, the weight, or the fallback weight when none is reported.
  • Gray — write_time, used for staleness detection.
  • Purple — symbol_name, used to reject feeds that quote a different symbol.

Figure 2: One line of a broker's shared file. The numbers 1 to 6 mark the fields, whose order must match on the writing and reading sides.


A Shared Helper for Broker Keys

Both sides must turn a broker key into the same file name, so both include BrokerKeyUtils.mqh instead of keeping separate copies of the rules. Its single function trims leading and trailing spaces, then replaces spaces, backslashes, slashes, colons, and pipes with underscores.

//+------------------------------------------------------------------+
//|                                               BrokerKeyUtils.mqh |
//+------------------------------------------------------------------+
#ifndef BROKERKEYUTILS_MQH
#define BROKERKEYUTILS_MQH

//+------------------------------------------------------------------+
//| SanitizeBrokerKey                                                |
//| Trims the key and replaces characters that are unsafe in a file  |
//| name. Both the publisher and the aggregator call this function,  |
//| so a key typed the same way always produces the same file name.  |
//+------------------------------------------------------------------+
string SanitizeBrokerKey(const string raw_name)
  {
   string   cleaned = raw_name;

   ::StringTrimLeft(cleaned);
   ::StringTrimRight(cleaned);

   ::StringReplace(cleaned, " ", "_");
   ::StringReplace(cleaned, "\\", "_");
   ::StringReplace(cleaned, "/", "_");
   ::StringReplace(cleaned, ":", "_");
   ::StringReplace(cleaned, "|", "_");

   return(cleaned);
  }

#endif // BROKERKEYUTILS_MQH


CFeedPublisher, the Broker-Side Writer

CFeedPublisher turns the current tick into one line in that broker's file. It is the simplest class here, because code that runs on every tick should do as little as possible.

//+------------------------------------------------------------------+
//|                                                FeedPublisher.mqh |
//+------------------------------------------------------------------+
#ifndef FEEDPUBLISHER_MQH
#define FEEDPUBLISHER_MQH

#include "BrokerKeyUtils.mqh"

//+------------------------------------------------------------------+
//| CFeedPublisher                                                   |
//| Writes this terminal's symbol, bid, ask, and tick volume to a    |
//| broker-keyed shared file on every call to PublishQuote.          |
//+------------------------------------------------------------------+
class CFeedPublisher
  {
private:
   string            m_broker_key;       // sanitized broker identifier used to build the file name
   string            m_file_name;        // full shared file name this publisher writes to

public:
                     CFeedPublisher(void);
                    ~CFeedPublisher(void);

   bool                 Initialize(const string broker_key);
   bool                 PublishQuote(const double bid_price, const double ask_price, const double available_volume);
   string               FileName(void) const;
  };

//+------------------------------------------------------------------+
//| CFeedPublisher constructor                                       |
//| Leaves the broker key and file name empty until Initialize runs. |
//+------------------------------------------------------------------+
CFeedPublisher::CFeedPublisher(void)
  {
   m_broker_key = "";
   m_file_name  = "";
  }

//+------------------------------------------------------------------+
//| CFeedPublisher destructor                                        |
//| No open file handles are held between calls, so there is nothing |
//| to release here.                                                 |
//+------------------------------------------------------------------+
CFeedPublisher::~CFeedPublisher(void)
  {
  }

Initialize() cleans the broker key with SanitizeBrokerKey() before checking it for emptiness, so a key made only of spaces is rejected, and then builds the file name. The aggregator applies the same function to each entry in InpBrokerKeys, so both sides resolve to the same name.

//+------------------------------------------------------------------+
//| Initialize                                                       |
//+------------------------------------------------------------------+
bool CFeedPublisher::Initialize(const string broker_key)
  {
   string   cleaned_key = ::SanitizeBrokerKey(broker_key);

   if(cleaned_key == "")
     {
      ::Print("CFeedPublisher::Initialize failed: broker_key must not be empty");
      return(false);
     }

   m_broker_key = cleaned_key;
   m_file_name  = "MultiBrokerFeed_" + m_broker_key + ".txt";

   return(true);
  }

PublishQuote() opens the file on every call with FILE_WRITE | FILE_TXT | FILE_COMMON | FILE_SHARE_READ. FILE_COMMON places the file in the shared folder, and FILE_SHARE_READ lets the aggregator read while the publisher holds it open. Opening for write empties the file, so each call replaces the previous line. FileName() only exposes the name for logging.

//+------------------------------------------------------------------+
//| PublishQuote                                                     |
//+------------------------------------------------------------------+
bool CFeedPublisher::PublishQuote(const double bid_price, const double ask_price, const double available_volume)
  {
   if(m_file_name == "")
     {
      ::Print("CFeedPublisher::PublishQuote failed: Initialize was not called");
      return(false);
     }

   int      file_handle = ::FileOpen(m_file_name, FILE_WRITE | FILE_TXT | FILE_COMMON | FILE_SHARE_READ);
   if(file_handle == INVALID_HANDLE)
     {
      ::Print("CFeedPublisher::PublishQuote failed: FileOpen returned error ", ::GetLastError());
      return(false);
     }

//--- one pipe-delimited line: broker_name|symbol_name|bid_price|ask_price|available_volume|write_time
   string   quote_line = ::StringFormat("%s|%s|%.8f|%.8f|%.2f|%d",
                                        m_broker_key,
                                        ::Symbol(),
                                        bid_price,
                                        ask_price,
                                        available_volume,
                                        (int)::TimeCurrent());

   ::FileWriteString(file_handle, quote_line);
   ::FileClose(file_handle);

   return(true);
  }

//+------------------------------------------------------------------+
//| FileName                                                         |
//+------------------------------------------------------------------+
string CFeedPublisher::FileName(void) const
  {
   return(m_file_name);
  }

The timestamp is TimeCurrent() cast to an integer, because a Unix integer is unambiguous to parse with  StringSplit(). This is portability of format, not clock agreement: the value still comes from the writing terminal's broker server (see Limitations).


CFeedReader, Parsing a Broker's File Back into a Quote

CFeedReader mirrors CFeedPublisher on the aggregator side. It reads the single line, splits it on the pipe delimiter, validates every field, and returns a filled SBrokerQuote. It also computes staleness, since it sees both the write time and the aggregator's current time.

//+------------------------------------------------------------------+
//|                                                   FeedReader.mqh |
//+------------------------------------------------------------------+
#ifndef FEEDREADER_MQH
#define FEEDREADER_MQH

#include "BrokerQuote.mqh"

//+------------------------------------------------------------------+
//| CFeedReader                                                      |
//| Reads a broker's shared file and parses it into an SBrokerQuote, |
//| including staleness detection against a configurable threshold.  |
//+------------------------------------------------------------------+
class CFeedReader
  {
private:
   int               m_staleness_seconds;   // maximum age, in seconds, before a quote is treated as stale

   bool              IsNumericString(const string value) const;
   bool              ReadFirstLine(const string file_name, string &line) const;

public:
                     CFeedReader(void);
                    ~CFeedReader(void);

   bool                 Initialize(const int staleness_seconds);
   SBrokerQuote         ReadQuote(const string file_name,
                                  const string broker_name,
                                  const string reference_symbol);
   bool                 IsStale(const SBrokerQuote &quote) const;
  };

The constructor sets the staleness threshold to zero, so every quote counts as stale until Initialize() runs with a positive value. The destructor is empty because the class keeps no file handles open between calls.

//+------------------------------------------------------------------+
//| CFeedReader constructor                                          |
//| Defaults the staleness threshold to zero until Initialize is     |
//| called, so an uninitialized reader treats old quotes as stale.   |
//+------------------------------------------------------------------+
CFeedReader::CFeedReader(void)
  {
   m_staleness_seconds = 0;
  }

//+------------------------------------------------------------------+
//| CFeedReader destructor                                           |
//| No open file handles are held between calls, so there is nothing |
//| to release here.                                                 |
//+------------------------------------------------------------------+
CFeedReader::~CFeedReader(void)
  {
  }

Initialize() stores the staleness threshold, in seconds, that IsStale() compares against, and it rejects zero and negative values.

//+------------------------------------------------------------------+
//| Initialize                                                       |
//+------------------------------------------------------------------+
bool CFeedReader::Initialize(const int staleness_seconds)
  {
   if(staleness_seconds <= 0)
     {
      ::Print("CFeedReader::Initialize failed: staleness_seconds must be positive");
      return(false);
     }

   m_staleness_seconds = staleness_seconds;

   return(true);
  }

IsNumericString() accepts only an optional minus sign, digits, and at most one decimal point, because StringToDouble() silently returns 0.0 for text such as "abc".

//+------------------------------------------------------------------+
//| IsNumericString                                                  |
//+------------------------------------------------------------------+
bool CFeedReader::IsNumericString(const string value) const
  {
   int      length      = ::StringLen(value);
   int      digit_count = 0;
   int      dot_count   = 0;

   if(length == 0)
      return(false);

   for(int i = 0; i < length; i++)
     {
      ushort   character = ::StringGetCharacter(value, i);

      if(character == '-' && i == 0)
         continue;

      if(character == '.')
        {
         dot_count++;
         if(dot_count > 1)
            return(false);
         continue;
        }

      if(character < '0' || character > '9')
         return(false);

      digit_count++;
     }

   return(digit_count > 0);
  }

The publisher rewrites its file on every tick, so a read can hit an empty or half-written file. ReadFirstLine() tries up to three times with a 50 ms pause between attempts. It accepts a line only when it holds exactly six fields and the last one is not empty, and it logs the last open error and field count if all three attempts fail.

//+------------------------------------------------------------------+
//| ReadFirstLine                                                    |
//+------------------------------------------------------------------+
bool CFeedReader::ReadFirstLine(const string file_name, string &line) const
  {
   int      last_error  = 0;
   int      last_fields = 0;

   for(int attempt = 0; attempt < 3; attempt++)
     {
      ::ResetLastError();

      int      file_handle = ::FileOpen(file_name,
                                        FILE_READ | FILE_TXT | FILE_COMMON |
                                        FILE_SHARE_READ | FILE_SHARE_WRITE);
      if(file_handle != INVALID_HANDLE)
        {
         line = ::FileReadString(file_handle);
         ::FileClose(file_handle);

         string   parts[];
         int      part_count = ::StringSplit(line, '|', parts);

         last_fields = part_count;

         if(part_count == 6 && ::StringLen(parts[5]) > 0)
            return(true);
        }
      else
         last_error = ::GetLastError();

      if(attempt < 2)
         ::Sleep(50);
     }

   ::Print("CFeedReader::ReadFirstLine: no valid six-field line in ", file_name,
           ", last open error ", last_error, ", last field count ", last_fields);

   return(false);
  }

ReadQuote() rejects a line when no complete line can be read, the field count is not six, the broker name or symbol does not match, or a numeric field is not a number. It also rejects a zero or negative bid or ask, an ask below the bid, or a zero write time. An ask equal to the bid is accepted. Every rejection prints a message, and the final value check prints the raw line. In each case parsed_ok stays false, and the reader never guesses a value.

//+------------------------------------------------------------------+
//| ReadQuote                                                        |
//| Expected line, exactly six fields:                               |
//| broker_name|symbol_name|bid|ask|volume|write_time                |
//| Any rejected line leaves parsed_ok false.                        |
//+------------------------------------------------------------------+
SBrokerQuote CFeedReader::ReadQuote(const string file_name,
                                    const string broker_name,
                                    const string reference_symbol)
  {
   SBrokerQuote result;

   result.broker_name = broker_name;

   string   quote_line = "";
   if(!ReadFirstLine(file_name, quote_line))
      return(result);

   string   fields[];
   int      field_count = ::StringSplit(quote_line, '|', fields);

   if(field_count != 6)
     {
      ::Print("CFeedReader::ReadQuote: expected exactly 6 fields, got ", field_count,
              " in ", file_name);
      return(result);
     }

//--- the file must belong to the broker the aggregator asked for
   if(fields[0] != broker_name)
     {
      ::Print("CFeedReader::ReadQuote: broker name mismatch in ", file_name,
              ", expected ", broker_name, ", found ", fields[0]);
      return(result);
     }

//--- the feed must quote the same symbol as the aggregator chart
   if(fields[1] != reference_symbol)
     {
      ::Print("CFeedReader::ReadQuote: symbol mismatch in ", file_name,
              ", expected ", reference_symbol, ", found ", fields[1]);
      return(result);
     }

//--- every numeric field must look like a number before conversion
   for(int i = 2; i <= 5; i++)
     {
      if(!IsNumericString(fields[i]))
        {
         ::Print("CFeedReader::ReadQuote: non-numeric field ", i,
                 " in ", file_name, ": ", fields[i]);
         return(result);
        }
     }

   double   parsed_bid    = ::StringToDouble(fields[2]);
   double   parsed_ask    = ::StringToDouble(fields[3]);
   double   parsed_volume = ::StringToDouble(fields[4]);
   long     parsed_time   = ::StringToInteger(fields[5]);

//--- a zero spread (ask equal to bid) is valid; only a crossed quote is rejected
   if(parsed_bid <= 0.0 || parsed_ask <= 0.0 || parsed_ask < parsed_bid || parsed_time <= 0)
     {
      ::Print("CFeedReader::ReadQuote: rejected values in ", file_name,
              ": line=", quote_line);
      return(result);
     }

   result.symbol_name      = fields[1];
   result.bid_price        = parsed_bid;
   result.ask_price        = parsed_ask;
   result.available_volume = parsed_volume;
   result.write_time       = parsed_time;
   result.parsed_ok        = true;

   return(result);
  }

IsStale() compares the quote's write time with the aggregator terminal's own TimeCurrent(). It assumes the broker servers' clocks stay reasonably close, because a broker whose clock runs ahead or behind can look stale or deceptively fresh (see Limitations). The test is strictly greater-than, so a quote exactly at the threshold still counts as fresh.

//+------------------------------------------------------------------+
//| IsStale                                                          |
//+------------------------------------------------------------------+
bool CFeedReader::IsStale(const SBrokerQuote &quote) const
  {
   if(!quote.parsed_ok)
      return(true);

   long     current_time = (long)::TimeCurrent();
   long     age_seconds  = current_time - quote.write_time;

   return(age_seconds > m_staleness_seconds);
  }


CFeedAggregator, the Volume-Weighted Mid-Price

This class computes each fresh feed's mid-price as the average of bid and ask, then combines those mid-prices in an average weighted by each broker's tick volume. Tick volume is a proxy for activity, not a direct measure of liquidity (see Limitations).

//+------------------------------------------------------------------+
//|                                               FeedAggregator.mqh |
//+------------------------------------------------------------------+
#ifndef FEEDAGGREGATOR_MQH
#define FEEDAGGREGATOR_MQH

#include "BrokerQuote.mqh"
#include "FeedReader.mqh"

//+------------------------------------------------------------------+
//| SAggregationResult                                               |
//| Outcome of one aggregation cycle: the synthetic mid-price, how   |
//| many feeds contributed, and the total weight behind the result.  |
//+------------------------------------------------------------------+
struct SAggregationResult
  {
   double   synthetic_mid;      // volume-weighted mid-price across contributing feeds
   int      contributing_count; // number of feeds that were fresh and parsed cleanly
   double   total_weight;       // sum of weights behind the synthetic mid-price
   bool     is_valid;           // false when no feed contributed and no price was computed

                        SAggregationResult(void);
  };

//+------------------------------------------------------------------+
//| SAggregationResult default constructor                           |
//| Zero-initializes every field, leaving is_valid false until a real|
//| aggregation cycle fills it.                                      |
//+------------------------------------------------------------------+
SAggregationResult::SAggregationResult(void)
  {
   synthetic_mid      = 0.0;
   contributing_count = 0;
   total_weight       = 0.0;
   is_valid           = false;
  }

//+------------------------------------------------------------------+
//| CFeedAggregator                                                  |
//| Combines a set of broker quotes into a single volume-weighted    |
//| synthetic mid-price, excluding stale or unparseable feeds.       |
//+------------------------------------------------------------------+
class CFeedAggregator
  {
private:
   double               m_fallback_weight;   // static weight used when a feed reports no volume

public:
                        CFeedAggregator(void);
                       ~CFeedAggregator(void);

   bool                 Initialize(const double fallback_weight);
   SAggregationResult   Aggregate(const SBrokerQuote &quotes[], CFeedReader &reader);
  };

//+------------------------------------------------------------------+
//| CFeedAggregator constructor                                      |
//| Defaults the fallback weight to zero until Initialize is called. |
//+------------------------------------------------------------------+
CFeedAggregator::CFeedAggregator(void)
  {
   m_fallback_weight = 0.0;
  }

//+------------------------------------------------------------------+
//| CFeedAggregator destructor                                       |
//| No dynamic resources are owned by the aggregator.                |
//+------------------------------------------------------------------+
CFeedAggregator::~CFeedAggregator(void)
  {
  }

Initialize() stores the fallback weight for a feed that reports zero or missing volume. It must be positive, because a zero weight would make such a feed contribute nothing.

//+------------------------------------------------------------------+
//| Initialize                                                       |
//+------------------------------------------------------------------+
bool CFeedAggregator::Initialize(const double fallback_weight)
  {
   if(fallback_weight <= 0.0)
     {
      ::Print("CFeedAggregator::Initialize failed: fallback_weight must be positive");
      return(false);
     }

   m_fallback_weight = fallback_weight;

   return(true);
  }

Aggregate() excludes stale quotes entirely and applies the fallback weight to zero-volume feeds. Excluding a feed, instead of giving it zero weight, also keeps the contributing count accurate.

//+------------------------------------------------------------------+
//| Aggregate                                                        |
//+------------------------------------------------------------------+
SAggregationResult CFeedAggregator::Aggregate(const SBrokerQuote &quotes[], CFeedReader &reader)
  {
   SAggregationResult result;
   double              weighted_sum = 0.0;
   double              total_weight = 0.0;
   int                 quote_count  = ::ArraySize(quotes);

   for(int i = 0; i < quote_count; i++)
     {
      //--- a feed that failed to parse or has gone stale is excluded from the average entirely
      if(reader.IsStale(quotes[i]))
         continue;

      double   feed_mid    = (quotes[i].bid_price + quotes[i].ask_price) / 2.0;
      double   feed_weight = (quotes[i].available_volume > 0.0) ? quotes[i].available_volume : m_fallback_weight;

      weighted_sum += feed_mid * feed_weight;
      total_weight += feed_weight;
      result.contributing_count++;
     }

//--- no contributing feed means no trustworthy synthetic price can be produced this cycle
   if(result.contributing_count == 0 || total_weight <= 0.0)
     {
      result.is_valid = false;
      return(result);
     }

   result.synthetic_mid = weighted_sum / total_weight;
   result.total_weight  = total_weight;
   result.is_valid      = true;

   return(result);
  }

Aggregate() returns a value type, SAggregationResult, so that a single is_valid flag tells the driver whether the price can be trusted.


CSyntheticSymbolWriter, Publishing the Synthetic Mid-Price

This class writes a validated SAggregationResult as a custom symbol bar, using CustomSymbolCreate() and CustomRatesUpdate().

//+------------------------------------------------------------------+
//|                                        SyntheticSymbolWriter.mqh |
//+------------------------------------------------------------------+
#ifndef SYNTHETICSYMBOLWRITER_MQH
#define SYNTHETICSYMBOLWRITER_MQH

#include "FeedAggregator.mqh"

//+------------------------------------------------------------------+
//| CSyntheticSymbolWriter                                           |
//| Creates the synthetic custom symbol and writes each aggregation  |
//| cycle's result to it as a flat-line MqlRates bar.                |
//+------------------------------------------------------------------+
class CSyntheticSymbolWriter
  {
private:
   string            m_custom_name;      // name of the synthetic custom symbol
   datetime          m_next_bar_time;    // time key to assign to the next written bar
   bool              m_sequencer_ready;  // true once the sequencer has been seeded

   bool              SymbolAlreadyExists(const string custom_name, bool &is_custom);

public:
                     CSyntheticSymbolWriter(void);
                    ~CSyntheticSymbolWriter(void);

   bool                 Create(const string custom_name, const int symbol_digits, const double symbol_point);
   bool                 WriteSyntheticPrice(const SAggregationResult &result);
   string               CustomName(void) const;
  };

//+------------------------------------------------------------------+
//| CSyntheticSymbolWriter constructor                               |
//| Leaves every member at its default until Create is called.       |
//+------------------------------------------------------------------+
CSyntheticSymbolWriter::CSyntheticSymbolWriter(void)
  {
   m_custom_name     = "";
   m_next_bar_time   = 0;
   m_sequencer_ready = false;
  }

//+-------------------------------------------------------------------+
//| CSyntheticSymbolWriter destructor                                 |
//| The custom symbol is not deleted on destruction, so the synthetic |
//| price history survives across EA restarts.                        |
//+-------------------------------------------------------------------+
CSyntheticSymbolWriter::~CSyntheticSymbolWriter(void)
  {
  }

//+------------------------------------------------------------------+
//| SymbolAlreadyExists                                              |
//| Reports whether a symbol with this name exists, and through      |
//| is_custom whether that symbol is a custom symbol.                |
//+------------------------------------------------------------------+
bool CSyntheticSymbolWriter::SymbolAlreadyExists(const string custom_name, bool &is_custom)
  {
   is_custom = false;

   return(::SymbolExist(custom_name, is_custom));
  }

Create() relies on SymbolAlreadyExists(), which calls SymbolExist() to learn whether a symbol exists and whether it is custom. A property query such as SYMBOL_DIGITS cannot tell the two apart. If the name belongs to a regular market symbol, Create() prints a message and returns false, so AggregatorEA stops instead of writing bars into a real symbol. An existing custom symbol counts as success, because an Expert Advisor restarts far more often than it starts fresh.

When it reuses a symbol, Create() warns if the digits or point differ from the requested values. On a first run, it creates the symbol, sets digits and point explicitly, and registers it in Market Watch with SymbolSelect().

//+------------------------------------------------------------------+
//| Create                                                           |
//+------------------------------------------------------------------+
bool CSyntheticSymbolWriter::Create(const string custom_name, const int symbol_digits, const double symbol_point)
  {
   m_custom_name = custom_name;

   bool     is_custom = false;

   if(SymbolAlreadyExists(custom_name, is_custom))
     {
      if(!is_custom)
        {
         ::Print("CSyntheticSymbolWriter::Create failed: ", custom_name,
                 " is a regular market symbol, not a custom symbol. Choose a different synthetic symbol name");
         return(false);
        }

      long     existing_digits = (long)::SymbolInfoInteger(custom_name, SYMBOL_DIGITS);
      double   existing_point  = ::SymbolInfoDouble(custom_name, SYMBOL_POINT);

      if(existing_digits != symbol_digits || ::MathAbs(existing_point - symbol_point) > 0.0000000001)
        {
         ::Print("CSyntheticSymbolWriter::Create warning: ", custom_name,
                 " already exists with digits=", existing_digits, " point=", existing_point,
                 ", which does not match the requested digits=", symbol_digits, " point=", symbol_point);
        }

      ::Print("CSyntheticSymbolWriter::Create: custom symbol ", custom_name, " already exists, reusing it");
      ::SymbolSelect(custom_name, true);
      return(true);
     }

   bool     created = ::CustomSymbolCreate(custom_name, "MultiBroker\\Synthetic");
   if(!created)
     {
      ::Print("CSyntheticSymbolWriter::Create failed: CustomSymbolCreate returned error ", ::GetLastError());
      return(false);
     }

   ::CustomSymbolSetInteger(custom_name, SYMBOL_DIGITS, symbol_digits);
   ::CustomSymbolSetDouble(custom_name, SYMBOL_POINT, symbol_point);

   bool     selected = ::SymbolSelect(custom_name, true);
   if(!selected)
     {
      ::Print("CSyntheticSymbolWriter::Create warning: could not add ", custom_name, " to Market Watch");
     }

   return(true);
  }

WriteSyntheticPrice() sets open, high, low, and close to the same mid-price, because a synthetic price has no natural range. The symbol should be read as a line series, since identical values avoid candle wicks that imply movement that was never measured.

An internal one-minute sequencer guarantees strictly increasing time keys. On the first write, it continues one minute after the symbol's last bar if that bar is ahead of the current time. Otherwise it starts at the current time rounded down to a whole minute.

The sequencer advances one minute on every successful write, whatever InpTimerSeconds is. At 60 seconds the labels track the clock, while a faster timer pushes them ahead: twice as fast at 30 seconds, and about thirty times as fast at 2 seconds. A cycle with no valid price writes no bar and does not advance the sequencer. At any other interval, bar times are sequence labels, not a market history.

//+------------------------------------------------------------------+
//| WriteSyntheticPrice                                              |
//+------------------------------------------------------------------+
bool CSyntheticSymbolWriter::WriteSyntheticPrice(const SAggregationResult &result)
  {
   if(!result.is_valid)
     {
      ::Print("CSyntheticSymbolWriter::WriteSyntheticPrice skipped: aggregation result is not valid");
      return(false);
     }

   MqlRates bar_record[1];

   if(!m_sequencer_ready)
     {
      datetime   last_bar_time = (datetime)::SeriesInfoInteger(m_custom_name, PERIOD_M1, SERIES_LASTBAR_DATE);
      long       start_time    = (last_bar_time > ::TimeCurrent()) ? (long)(last_bar_time + 60) : (long)::TimeCurrent();

      m_next_bar_time   = (datetime)(start_time - (start_time % 60));
      m_sequencer_ready = true;
     }

   bar_record[0].time        = m_next_bar_time;
   bar_record[0].open        = result.synthetic_mid;
   bar_record[0].high        = result.synthetic_mid;
   bar_record[0].low         = result.synthetic_mid;
   bar_record[0].close       = result.synthetic_mid;
   bar_record[0].tick_volume = result.contributing_count;
   bar_record[0].real_volume = (long)::MathRound(result.total_weight);
   bar_record[0].spread      = 0;

   int      written = ::CustomRatesUpdate(m_custom_name, bar_record);
   if(written <= 0)
     {
      ::Print("CSyntheticSymbolWriter::WriteSyntheticPrice failed: CustomRatesUpdate returned error ", ::GetLastError());
      return(false);
     }

   m_next_bar_time += 60;

   return(true);
  }

//+------------------------------------------------------------------+
//| CustomName                                                       |
//+------------------------------------------------------------------+
string CSyntheticSymbolWriter::CustomName(void) const
  {
   return(m_custom_name);
  }

#endif // SYNTHETICSYMBOLWRITER_MQH

On the synthetic bar, tick_volume carries contributing_count, the number of feeds in the average, and real_volume carries the total weight rounded to a whole number. With whole-number volumes or the default fallback of 1.0, the total is already whole. A tick_volume of one or two out of three visibly flags that feeds went stale.


FeedPublisherEA.mq5, the Broker-Side Driver

FeedPublisherEA runs in each broker terminal, where OnInit() reads the broker key, which defaults to the account company name when blank, and OnTick() publishes the current bid, ask, and tick volume. The volume comes from the volume field of MqlTick, which many forex symbols report as zero, as all three test brokers did. It serves only as a weighting signal, and the file contains no aggregation logic.

//+------------------------------------------------------------------+
//|                                              FeedPublisherEA.mq5 |
//+------------------------------------------------------------------+

#include <MultiBrokerAggregator/FeedPublisher.mqh>

input string InpBrokerKey = "";   // broker identifier used in the shared file name; blank uses the account company

CFeedPublisher g_publisher;

//+------------------------------------------------------------------+
//| OnInit                                                           |
//| Initializes the publisher with the broker key supplied by input, |
//| falling back to the account company name when left blank.        |
//+------------------------------------------------------------------+
int OnInit(void)
  {
   string   broker_key = InpBrokerKey;

   if(broker_key == "")
      broker_key = ::AccountInfoString(ACCOUNT_COMPANY);

   if(broker_key == "")
      broker_key = "UnknownBroker";

   if(!g_publisher.Initialize(broker_key))
     {
      ::Print("FeedPublisherEA::OnInit failed: could not initialize publisher for broker_key=", broker_key);
      return(INIT_FAILED);
     }

   ::Print("FeedPublisherEA initialized: broker_key=", broker_key, ", file=", g_publisher.FileName());

   return(INIT_SUCCEEDED);
  }

//+------------------------------------------------------------------+
//| OnTick                                                           |
//| Reads the current quote for this EA's symbol and publishes bid,  |
//| ask, and tick volume to the shared broker file.                  |
//+------------------------------------------------------------------+
void OnTick(void)
  {
   MqlTick  current_tick;

   if(!::SymbolInfoTick(::Symbol(), current_tick))
     {
      ::Print("FeedPublisherEA::OnTick warning: SymbolInfoTick failed with error ", ::GetLastError());
      return;
     }

   double   available_volume = (double)current_tick.volume;

   if(!g_publisher.PublishQuote(current_tick.bid, current_tick.ask, available_volume))
     {
      ::Print("FeedPublisherEA::OnTick warning: PublishQuote failed");
     }
  }
//+------------------------------------------------------------------+


AggregatorEA.mq5, the Master Driver

AggregatorEA runs in the one terminal that computes the synthetic price. OnInit() builds the key list from a comma-separated input, cleans each key with SanitizeBrokerKey(), skips empty and duplicate entries with a warning, and fails if no usable key remains. If InpTimerSeconds is not 60, it prints a note that bar times are sequence labels. A timer drives the loop instead of OnTick(), so the cadence does not depend on the tick rate of the chart's own symbol.

//+------------------------------------------------------------------+
//|                                                 AggregatorEA.mq5 |
//+------------------------------------------------------------------+

#include <MultiBrokerAggregator/BrokerKeyUtils.mqh>
#include <MultiBrokerAggregator/FeedReader.mqh>
#include <MultiBrokerAggregator/FeedAggregator.mqh>
#include <MultiBrokerAggregator/SyntheticSymbolWriter.mqh>

input string InpBrokerKeys        = "BrokerA,BrokerB,BrokerC";  // comma-separated broker keys; each entry is trimmed, empty and duplicate entries are skipped
input string InpSyntheticSymbol   = "SYNTH.MID";                // name of the synthetic custom symbol; must not match a regular market symbol
input int    InpTimerSeconds      = 60;                         // aggregation interval in seconds; 60 keeps bar times on the clock
input int    InpStalenessSeconds  = 10;                         // maximum quote age before a feed is excluded
input double InpFallbackWeight    = 1.0;                        // static weight for feeds with no reported volume
input bool   InpVerboseLogging    = false;                      // true: log every broker's contribution each cycle

CFeedReader              g_reader;
CFeedAggregator          g_aggregator;
CSyntheticSymbolWriter   g_writer;
string                   g_broker_keys[];

//+------------------------------------------------------------------+
//| OnInit                                                           |
//+------------------------------------------------------------------+
int OnInit(void)
  {
   string   raw_keys[];
   int      raw_count = ::StringSplit(InpBrokerKeys, ',', raw_keys);

   ::ArrayResize(g_broker_keys, 0);

//--- clean every entry, then skip empty and duplicate keys
   for(int i = 0; i < raw_count; i++)
     {
      string   cleaned_key = ::SanitizeBrokerKey(raw_keys[i]);

      if(cleaned_key == "")
        {
         ::Print("AggregatorEA::OnInit warning: skipped an empty entry in InpBrokerKeys");
         continue;
        }

      bool     is_duplicate = false;

      for(int j = 0; j < ::ArraySize(g_broker_keys); j++)
        {
         if(g_broker_keys[j] == cleaned_key)
           {
            is_duplicate = true;
            break;
           }
        }

      if(is_duplicate)
        {
         ::Print("AggregatorEA::OnInit warning: skipped duplicate broker key ", cleaned_key);
         continue;
        }

      int      next_index = ::ArraySize(g_broker_keys);
      ::ArrayResize(g_broker_keys, next_index + 1);
      g_broker_keys[next_index] = cleaned_key;
     }

   if(::ArraySize(g_broker_keys) == 0)
     {
      ::Print("AggregatorEA::OnInit failed: InpBrokerKeys produced no usable broker keys");
      return(INIT_FAILED);
     }

   if(!g_reader.Initialize(InpStalenessSeconds))
     {
      ::Print("AggregatorEA::OnInit failed: could not initialize CFeedReader");
      return(INIT_FAILED);
     }

   if(!g_aggregator.Initialize(InpFallbackWeight))
     {
      ::Print("AggregatorEA::OnInit failed: could not initialize CFeedAggregator");
      return(INIT_FAILED);
     }

   int      reference_digits = (int)::SymbolInfoInteger(::Symbol(), SYMBOL_DIGITS);
   double   reference_point  = ::SymbolInfoDouble(::Symbol(), SYMBOL_POINT);

   if(!g_writer.Create(InpSyntheticSymbol, reference_digits, reference_point))
     {
      ::Print("AggregatorEA::OnInit failed: could not create synthetic symbol ", InpSyntheticSymbol);
      return(INIT_FAILED);
     }

   if(!::EventSetTimer(InpTimerSeconds))
     {
      ::Print("AggregatorEA::OnInit failed: EventSetTimer returned error ", ::GetLastError());
      return(INIT_FAILED);
     }

   if(InpTimerSeconds != 60)
      ::Print("AggregatorEA::OnInit note: InpTimerSeconds is not 60, so bar times on ", InpSyntheticSymbol,
              " are sequence labels, not market times");

   ::Print("AggregatorEA initialized: brokers=", InpBrokerKeys,
           ", synthetic_symbol=", InpSyntheticSymbol,
           ", timer_seconds=", InpTimerSeconds,
           ", staleness_seconds=", InpStalenessSeconds);

   return(INIT_SUCCEEDED);
  }

//+------------------------------------------------------------------+
//| OnDeinit                                                         |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
   ::EventKillTimer();
  }

OnTimer() reads every configured file through CFeedReader, passes the quotes to Aggregate(), and writes a valid result through CSyntheticSymbolWriter. The InpVerboseLogging input, off by default, adds one line per broker with bid, ask, spread, weight, and exclusion status. Turn it on during setup, because it is the main way to confirm that every feed is read correctly.

//+------------------------------------------------------------------+
//| OnTimer                                                          |
//+------------------------------------------------------------------+
void OnTimer(void)
  {
   int          broker_count = ::ArraySize(g_broker_keys);
   SBrokerQuote quotes[];

   ::ArrayResize(quotes, broker_count);

   for(int i = 0; i < broker_count; i++)
     {
      string   file_name = "MultiBrokerFeed_" + g_broker_keys[i] + ".txt";
      quotes[i] = g_reader.ReadQuote(file_name, g_broker_keys[i], ::Symbol());
     }

   SAggregationResult result = g_aggregator.Aggregate(quotes, g_reader);

//--- log every broker's contribution regardless of whether it was included, so gaps are visible
   if(InpVerboseLogging)
     {
      for(int i = 0; i < broker_count; i++)
        {
         bool     excluded = g_reader.IsStale(quotes[i]);
         double   spread   = quotes[i].parsed_ok ? (quotes[i].ask_price - quotes[i].bid_price) : 0.0;
         double   weight   = (quotes[i].available_volume > 0.0) ? quotes[i].available_volume : InpFallbackWeight;

         ::Print("Feed contribution: broker=", g_broker_keys[i],
                 ", bid=", ::DoubleToString(quotes[i].bid_price, 5),
                 ", ask=", ::DoubleToString(quotes[i].ask_price, 5),
                 ", spread=", ::DoubleToString(spread, 5),
                 ", weight=", ::DoubleToString(weight, 2),
                 ", excluded=", excluded ? "true" : "false");
        }
     }

   if(!result.is_valid)
     {
      ::Print("AggregatorEA::OnTimer: no synthetic price computed this cycle, every feed was stale or unparseable");
      return;
     }

   ::Print("Synthetic mid-price computed: value=", ::DoubleToString(result.synthetic_mid, 5),
           ", contributing_feeds=", result.contributing_count,
           ", total_weight=", ::DoubleToString(result.total_weight, 2));

   if(!g_writer.WriteSyntheticPrice(result))
     {
      ::Print("AggregatorEA::OnTimer warning: failed to write synthetic price to ", InpSyntheticSymbol);
     }
  }

One Aggregation Cycle — Decision Flow

One Aggregation Cycle — Decision Flow

Legend:

  • Gray — the checks: ReadQuote(), IsStale(), and the contributing-feed test.
  • Red — the excluded path: a failed parse or a stale quote.
  • Teal — the included path: a fresh, valid quote.
  • Coral — where outcomes combine into the weighted average.
  • Navy — the start and end of the cycle.

Figure 3: Decision flow of one OnTimer() firing, repeated for each configured broker. A feed that fails ReadQuote() or IsStale() is excluded, and a valid fresh quote adds its volume-weighted mid-price. The result is written if at least one feed contributed.


Installing and Viewing FeedPublisherEA and AggregatorEA

Running this pipeline correctly involves several terminals working together, and it is worth walking through the setup carefully, since a mismatch in file naming or symbol selection between terminals produces output that looks broken even when every class is functioning exactly as designed.

  • Install one MetaTrader terminal per broker, each in its own folder, because two terminals from the same installation typically cannot run together. All installations on one Windows account share the common data folder.
  • Copy the files, preserving the folder structure. Place the six .mqh files in MQL5\Include\MultiBrokerAggregator in every terminal, FeedPublisherEA.mq5 and AggregatorEA.mq5 in MQL5\Experts\MultiBrokerAggregator, and TestFeedAggregator.mq5 in MQL5\Scripts\MultiBrokerAggregator. Compile in each terminal's own MetaEditor, and recompile after any include file changes, because a compiled Expert Advisor carries its own copy of the include code.
  • Attach FeedPublisherEA to the same symbol in every broker terminal, for example EURUSD. Set InpBrokerKey explicitly to a distinct short identifier such as BrokerA, BrokerB, or BrokerC. The aggregator chart must use the same symbol, because the reader rejects any feed that reports a different one.
  • Confirm each publisher's file name in the Experts log. It should read similar to FeedPublisherEA initialized: broker_key=BrokerA, file=MultiBrokerFeed_BrokerA.txt, with no unexpected underscores where a space was typed.
  • Attach AggregatorEA to one terminal only, on the same instrument. Set InpBrokerKeys to a comma-separated list that matches the publishers' keys, for example BrokerA,BrokerB,BrokerC. A terminal runs only one Expert Advisor per chart, so if the aggregator shares a terminal with a publisher, open a second chart on the same symbol.
  • Open a chart on the synthetic symbol. If it is missing from Market Watch, right-click there and choose Show All. Then drag it onto a new M1 chart and switch to a line chart, because every bar has identical open, high, low, and close values. If SYNTH.MID holds bars from an earlier run with a shorter timer, delete its history first, because those bars carry future-dated labels.


Choosing the Operating Parameters

Four settings decide how often a feed is excluded and how old the synthetic price can be: the timer interval, the staleness threshold, the read retry, and the fallback weight. The defaults suit a liquid instrument such as EURUSD during an active session. Other markets need other values, so this section gives a selection rule for each setting.

Timer interval: Use 60 seconds when the series feeds an M1 chart. A shorter interval gives fresher prices, but bar times then run ahead of the clock by the ratio of 60 to the interval, so use it only for live monitoring.

Staleness threshold: A quote's age depends on the time since the publisher last wrote, not on the timer. A feed that is quiet for longer than the threshold is therefore excluded even if its terminal is healthy. Set the threshold above the longest tick pause you expect on the quietest broker, plus the clock offset between servers, and start at two to three times that pause. Raise it if healthy feeds are excluded, and lower it to drop a dead feed faster.

Read retry: A publisher rewrites its file with one small write, so one 50 ms pause is normally enough. Three attempts add at most 100 ms per unreadable feed. No read-failure message appeared in the runs that included the retry, so the live test did not exercise it.

Fallback weight: This value matters only when some brokers report volume and others do not. A feed reporting a tick volume of 40 outweighs a fallback feed of 1.0 forty to one, so set the fallback near the typical volume of the reporting brokers.

Market condition InpTimerSeconds InpStalenessSeconds Status
Active session, liquid pair such as EURUSD 60, or 30 for monitoring 10 Tested at 30 and 10: one stale exclusion in 66 cycles
Calm session or less liquid instrument 60 30 to 60 Starting point, not tested
Fast market around a news release 60, or 30 for monitoring 5 to 10 Starting point, not tested


Verification, TestFeedAggregator.mq5

This script builds SBrokerQuote values in memory, bypassing the file system, and drives Aggregate() through four scenarios. They are a clean three-feed weighted average, a stale feed with a large weight, every feed stale, and two zero-volume feeds that fall back to the static weight. File reading is covered by the live tests below.

//+------------------------------------------------------------------+
//|                                           TestFeedAggregator.mq5 |
//+------------------------------------------------------------------+
#property script_show_inputs

#include <MultiBrokerAggregator/FeedAggregator.mqh>
#include <MultiBrokerAggregator/FeedReader.mqh>

#define ASSERT(condition, message) \
   if(!(condition)) \
     { \
      ::Print("ASSERT FAILED: ", message); \
      g_failures++; \
     } \
   else \
     { \
      ::Print("ASSERT PASSED: ", message); \
     }

int g_failures = 0;

BuildQuote() is the one helper every test function relies on. It fills an SBrokerQuote directly from explicit values, including parsed_ok = true, rather than going through CFeedReader::ReadQuote() against a real file. This matters because it lets each test construct an exact scenario, a specific bid, ask, tick volume, and write time, without needing a broker terminal actually running or a shared file actually written to disk.

//+------------------------------------------------------------------+
//| BuildQuote                                                       |
//+------------------------------------------------------------------+
SBrokerQuote BuildQuote(const string broker_name, const double bid_price, const double ask_price, const double available_volume, const long write_time)
  {
   SBrokerQuote quote;

   quote.broker_name      = broker_name;
   quote.bid_price        = bid_price;
   quote.ask_price        = ask_price;
   quote.available_volume = available_volume;
   quote.write_time       = write_time;
   quote.parsed_ok        = true;

   return(quote);
  }

TestWeightedAverage() and TestStaleFeedExcluded() cover two sides of one rule: a healthy feed contributes in proportion to its volume, and a stale feed contributes nothing. The second test gives the stale feed a volume of 999, far larger than the two healthy feeds combined, and confirms that this weight never enters the sum.

//+------------------------------------------------------------------+
//| TestWeightedAverage                                              |
//+------------------------------------------------------------------+
void TestWeightedAverage(void)
  {
   CFeedReader     reader;
   CFeedAggregator aggregator;
   long            current_time = (long)::TimeCurrent();

   reader.Initialize(10);
   aggregator.Initialize(1.0);

   SBrokerQuote quotes[3];
   quotes[0] = BuildQuote("BrokerA", 1.10000, 1.10010, 50.0, current_time);
   quotes[1] = BuildQuote("BrokerB", 1.10005, 1.10015, 30.0, current_time);
   quotes[2] = BuildQuote("BrokerC", 1.09995, 1.10005, 20.0, current_time);

   SAggregationResult result = aggregator.Aggregate(quotes, reader);

   double   expected = (1.10005 * 50.0 + 1.10010 * 30.0 + 1.10000 * 20.0) / 100.0;

   ASSERT(result.is_valid, "aggregation is valid with three fresh feeds");
   ASSERT(result.contributing_count == 3, "all three feeds contributed");
   ASSERT(::MathAbs(result.total_weight - 100.0) < 0.0000001, "total weight equals the sum of the three volumes");
   ASSERT(::MathAbs(result.synthetic_mid - expected) < 0.0000001, "synthetic mid-price matches the manual weighted calculation");
  }

//+------------------------------------------------------------------+
//| TestStaleFeedExcluded                                            |
//+------------------------------------------------------------------+
void TestStaleFeedExcluded(void)
  {
   CFeedReader     reader;
   CFeedAggregator aggregator;
   long            current_time = (long)::TimeCurrent();

   reader.Initialize(10);
   aggregator.Initialize(1.0);

   SBrokerQuote quotes[3];
   quotes[0] = BuildQuote("BrokerA", 1.10000, 1.10010, 50.0, current_time);
   quotes[1] = BuildQuote("BrokerB", 1.20000, 1.20010, 999.0, current_time - 999);   // far older than the 10 second threshold
   quotes[2] = BuildQuote("BrokerC", 1.09995, 1.10005, 20.0, current_time);

   SAggregationResult result = aggregator.Aggregate(quotes, reader);

   double   expected = (1.10005 * 50.0 + 1.10000 * 20.0) / 70.0;

   ASSERT(result.is_valid, "aggregation is valid with two fresh feeds after excluding the stale one");
   ASSERT(result.contributing_count == 2, "exactly two feeds contributed, the stale feed was excluded");
   ASSERT(::MathAbs(result.total_weight - 70.0) < 0.0000001, "total weight excludes the stale feed's weight entirely");
   ASSERT(::MathAbs(result.synthetic_mid - expected) < 0.0000001, "synthetic mid-price is unaffected by the stale feed's huge weight");
  }

TestAllFeedsStale() sets both feeds 500 seconds old against a 10-second threshold. It checks that is_valid is false and that contributing_count is exactly zero.

//+------------------------------------------------------------------+
//| TestAllFeedsStale                                                |
//+------------------------------------------------------------------+
void TestAllFeedsStale(void)
  {
   CFeedReader     reader;
   CFeedAggregator aggregator;
   long            current_time = (long)::TimeCurrent();

   reader.Initialize(10);
   aggregator.Initialize(1.0);

   SBrokerQuote quotes[2];
   quotes[0] = BuildQuote("BrokerA", 1.10000, 1.10010, 50.0, current_time - 500);
   quotes[1] = BuildQuote("BrokerB", 1.10005, 1.10015, 30.0, current_time - 500);

   SAggregationResult result = aggregator.Aggregate(quotes, reader);

   ASSERT(!result.is_valid, "aggregation is invalid when every feed is stale");
   ASSERT(result.contributing_count == 0, "no feed contributed to the result");
  }

TestZeroVolumeFallback() gives both feeds a volume of 0.0 and checks that the fallback weight produces a simple average instead of a division by zero.

//+------------------------------------------------------------------+
//| TestZeroVolumeFallback                                           |
//+------------------------------------------------------------------+
void TestZeroVolumeFallback(void)
  {
   CFeedReader     reader;
   CFeedAggregator aggregator;
   long            current_time = (long)::TimeCurrent();

   reader.Initialize(10);
   aggregator.Initialize(1.0);

   SBrokerQuote quotes[2];
   quotes[0] = BuildQuote("BrokerA", 1.10000, 1.10010, 0.0, current_time);
   quotes[1] = BuildQuote("BrokerB", 1.10010, 1.10020, 0.0, current_time);

   SAggregationResult result = aggregator.Aggregate(quotes, reader);

   double   expected = (1.10005 + 1.10015) / 2.0;

   ASSERT(result.is_valid, "aggregation is valid with two zero-volume feeds using the fallback weight");
   ASSERT(::MathAbs(result.total_weight - 2.0) < 0.0000001, "total weight equals two fallback weights of 1.0 each");
   ASSERT(::MathAbs(result.synthetic_mid - expected) < 0.0000001, "synthetic mid-price is a simple average when both feeds use the fallback weight");
  }

OnStart() closes the script out, running all four scenarios in sequence and printing a single summary line at the end. This matters more than it might look, since a person running the script only needs to glance at one line, ALL TESTS PASSED or a specific failure count, to know whether the aggregation logic behaves as designed, without needing to manually scan every individual assertion line above it.

//+------------------------------------------------------------------+
//| OnStart                                                          |
//+------------------------------------------------------------------+
void OnStart(void)
  {
   ::Print("--- TestFeedAggregator: starting verification ---");

   TestWeightedAverage();
   TestStaleFeedExcluded();
   TestAllFeedsStale();
   TestZeroVolumeFallback();

   if(g_failures == 0)
      ::Print("--- TestFeedAggregator: ALL TESTS PASSED ---");
   else
      ::Print("--- TestFeedAggregator: ", g_failures, " ASSERTION(S) FAILED ---");
  }


Findings from Testing Across Three Real Broker Terminals

Test conditions

Item Value
Symbol EURUSD on every publisher chart and on the aggregator chart (H1, or M1 in the first run; the chart timeframe does not affect the timer)
Brokers Three demo accounts, anonymized as BrokerA, BrokerB and BrokerC
Terminals Three MetaTrader 5 terminals (build 6291) on one machine, one per broker. BrokerC’s terminal also hosted AggregatorEA
Machine Dell G15 5530 laptop, Intel Core i7-13650HX (14 cores, 20 logical processors), 64 GB RAM, Windows 11 Pro build 26200
AggregatorEA inputs InpBrokerKeys=BrokerA,BrokerB,BrokerC; InpSyntheticSymbol=SYNTH.MID; InpTimerSeconds=30; InpStalenessSeconds=10; InpFallbackWeight=1.0; InpVerboseLogging=true
Volume All three feeds reported zero tick volume, so every feed used the fallback weight of 1.0
Data source The Experts log of the aggregator terminal, with counters computed from the saved log

Results by run

Run Code state
Log window Cycles All three feeds BrokerC excluded Other exclusions
1 Before the retry 2026-10-08 09:54:24 to 11:00:57 133 61 (45.9%) 71 (53.4%), including 9 cycles of a deliberate symbol-mismatch test BrokerA 1 (quote not parsed)
2 Retry added 2026-11-09 18:21:38 to 18:53:38 65 25 (38.5%) 40 (61.5%) BrokerA 1 (stale)
3 Diagnostic message added 2026-11-10 10:54:32 to 11:08:02 28 9 (32.1%) 19 (67.9%) none
4 Zero spread accepted 2026-11-10 11:15:14 to 11:47:44 66 65 (98.5%) 0 (0%) BrokerA 1 (stale)

Running the pipeline on three demo accounts surfaced several practical issues:

Broker key mismatch: A key typed with a space, such as Broker A, becomes Broker_A in the file name, so an aggregator configured for BrokerA never finds the file. Every feed then reports zero and looks excluded, which resembles a staleness problem. When every feed reports zero at once, compare each publisher's file name with the aggregator's list first. A key with a space on both sides works, because both sides use the same cleaning.

Symbol mismatch across publishers: One publisher was attached to a different symbol than the aggregator chart. The reader rejected it with a message naming the expected and found symbols, which prevented the aggregator from blending two unrelated instruments.

One feed excluded in most cycles: Before the fix, BrokerC was excluded in 50% to 68% of cycles, with a bid and ask of zero and no explanation. Adding the retry did not help, because a run without it excluded BrokerC in 62 of 124 cycles (50.0%), not counting nine cycles of a deliberate symbol-mismatch test, and a run with it in 40 of 65 (61.5%). A diagnostic message in the final value check revealed the cause. All 19 rejected lines in the next run had an ask equal to the bid, because BrokerC quotes a zero spread in many cycles and the reader required a strictly higher ask. Rejecting only a crossed quote removed the exclusions, and in the final run all three feeds contributed in 65 of 66 cycles. Every rejection path in a parser should log why.

Genuine staleness: In the final run, BrokerA was excluded in one of 66 cycles (1.5%). Its quote parsed correctly, so the staleness check caused it, consistent with a pause of more than ten seconds between ticks.

Outdated compiled publisher: A publisher compiled from an outdated FeedPublisher.mqh wrote the wrong number of fields. The reader logged the count it found, and recompiling fixed it.

Zero tick volume: All three brokers reported zero tick volume, so every feed had a weight of 1.00 and the result was a simple average, and only TestFeedAggregator.mq5 exercised the weighting.

Hand-editing the shared files: The publisher rewrites its file on every tick, so manual edits are overwritten within a second. An open text editor can also block the publisher's write. To test validation by hand, remove the publisher from its chart first, edit the file in place, and watch the next aggregator cycle.

Spread differences across brokers: Once all three were aligned on the same instrument, BrokerC quoted a spread of zero or one point (zero in 32 of the 66 cycles of the final run), consistent with an ECN-style account. BrokerA and BrokerB showed spreads between eight and eleven points, consistent with a market-maker model. This is not a defect. It is the kind of cross-broker difference this article set out to reveal. The table below shows three cycles from the final run. In each, the synthetic price sits between the highest and lowest of the feed mid-prices. Because every feed used the fallback weight, these cycles show the equal-weight average and not volume weighting.

Time BrokerA bid/ask BrokerB bid/ask BrokerC bid/ask Feeds Synthetic mid
11:15:14 1.12198/1.12207 1.12202/1.12212 1.12202/1.12203 3 1.12204
11:16:14 1.12181/1.12190 1.12185/1.12194 1.12185/1.12185 3 1.12187
11:29:44 excluded (stale) 1.12206/1.12215 1.12206/1.12206 2 1.12208


Extending the Aggregator

Brokers report tick volume under different conventions, so an explicit per-broker trust weight set by the operator could replace or augment it. An outlier check could also exclude any quote whose mid-price sits too far from the median of the other feeds. Today, a data error or flash quote is weighted like any other fresh feed.

Brokers often name the same instrument differently, for example EURUSD.m, and the exact symbol match rejects such feeds. A per-broker symbol map, set as an input, would solve this.


Limitations

The pipeline needs every terminal to reach the same common data path, which typically means terminals under one Windows account on one machine.

Staleness detection catches a broker that stops publishing, but not one that keeps writing a frozen price, because a recent write timestamp proves only that the file was touched. A feed that stays unreadable through all three read attempts is excluded for that cycle.

After a restart, the sequencer continues after the last bar if that bar is ahead of the current time, but a small gap or jump in the sequence is still possible.

The synthetic series differs from an ordinary market symbol: every bar is flat and the spread is zero. Candlestick patterns, spread analysis, and volume indicators therefore have no meaning, and the series should be used as a line chart of a reference price.

At any interval other than 60 seconds, bar times are sequence labels, not market times. With a 30-second timer the newest bar sits about an hour ahead of the clock after one hour, so the series suits live monitoring but not backtesting. Even at 60 seconds, each bar holds one sampled value per minute, not the open, high, low, and close of real ticks.

A feed whose ask equals its bid is accepted. A zero spread can be legitimate, but it can also come from a demo or aggregated feed.

Staleness detection compares each broker's write timestamp with the aggregator's TimeCurrent(), so clock skew between broker servers can cause incorrect classifications. If the aggregator's own symbol goes quiet, its TimeCurrent() can fall behind and understate every feed's age.

The timer makes the synthetic price a sampled approximation, so a brief spike on one broker between two firings may never appear in the series.

The live evidence comes from one symbol and three demo accounts, in four runs of 28 to 133 cycles, and it is not a performance benchmark.


Conclusion

This article builds a bridge between isolated MetaTrader terminals from nothing more than shared text files, and it turns several brokers' bid and ask streams into one volume-weighted mid-price that can be charted. The publisher side stays minimal to keep overhead low. The aggregator side fails safely, because a stale feed is excluded and a cycle with no trustworthy feed produces no price instead of a misleading one.

Testing on three demo accounts confirmed normal operation, with all three feeds contributing in 65 of 66 cycles of the final run. The tests did not cover mid-session disconnects, frozen upstream prices, or multi-day operation. They did expose setup pitfalls: mismatched broker keys, misaligned symbols, an outdated compiled publisher, and a zero-spread feed that a strict rule rejected without any log message. Because all three brokers reported zero tick volume, only the test script verified the volume weighting. The synthetic price is a sampled, weighted combination of the feeds that were fresh at each timer firing, not a tick-perfect reconstruction.


Programs used in the article:

# Name Type Description
1 BrokerQuote.mqh Include File Defines SBrokerQuote, the struct describing one broker's parsed quote
2 BrokerKeyUtils.mqh Include File Defines SanitizeBrokerKey(), the shared function that cleans a broker key for use in a file name
3 FeedPublisher.mqh Include File Defines CFeedPublisher, which writes this terminal's quote to a broker-keyed shared file
4 FeedReader.mqh Include File Defines CFeedReader, which parses a broker's shared file and detects staleness
5 FeedAggregator.mqh Include File Defines CFeedAggregator, which computes the volume-weighted synthetic mid-price
6 SyntheticSymbolWriter.mqh Include File Defines CSyntheticSymbolWriter, which writes the synthetic mid-price to a custom symbol
7 FeedPublisherEA.mq5 Expert Advisor The broker-side EA that publishes this terminal's quote every tick
8 AggregatorEA.mq5 Expert Advisor The master EA that reads all broker feeds on a timer and computes the synthetic price
9 TestFeedAggregator.mq5 Script Verification script for the weighting, staleness exclusion, and fallback weight logic
10 MultiBrokerAggregator.zip Zip Archive Zip archive containing all the attached files and their paths relative to the terminal's root folder. 
Features of Custom Indicators Creation Features of Custom Indicators Creation
Creation of Custom Indicators in the MetaTrader trading system has a number of features.
Embedding a WebSocket Server in an MQL5 Expert Advisor: Live Push to Browsers and Scripts Without a Middleman Embedding a WebSocket Server in an MQL5 Expert Advisor: Live Push to Browsers and Scripts Without a Middleman
We build a WebSocket server inside an MQL5 Expert Advisor to stream ticks, positions and deal events to a browser or a Python client in real time. The article implements RFC 6455 (handshake, framing, masking and ping/pong) in pure MQL5 with Winsock, drives non-blocking sockets from a timer, wires the server into OnTick/OnTimer/OnTradeTransaction, and measures latency, throughput and trading overhead.
Features of Experts Advisors Features of Experts Advisors
Creation of expert advisors in the MetaTrader trading system has a number of features.
Neural Networks in Trading: Mesh Approximation of Event Streams as a Tool for Analyzing Price Patterns (EEMFlow) Neural Networks in Trading: Mesh Approximation of Event Streams as a Tool for Analyzing Price Patterns (EEMFlow)
The article provides an overview of the architecture of the EEMFlow framework, which is designed to work with event streams. Particular attention is paid to adaptive and multi-level modules, which enable flexible handling of both global and local changes. The framework's architecture preserves key information, minimizes the impact of noise, and efficiently generates features for further analysis, making EEMFlow a promising tool for forecasting financial market dynamics.