Building a Modular Pre-Trade Execution Filter Engine in MQL5
Introduction and the Pre-Trade Execution Reality
Strategy developers often attribute live underperformance to parameter overfitting or regime shifts. However, post-trade transaction cost analysis (TCA) often shows that pre-trade execution friction is equally important.
Standard Strategy Tester simulations operate within deterministic and controlled environments. Even with variable spread modeling on real tick data, the tester still assumes continuous market depth, instantaneous order processing, and regular quote arrival. In live institutional and retail trading environments, conversely, order routing is subject to liquidity fragmentation, broker clearing and settlement procedures, and network transit delays.
During end-of-day bank rollovers, high-impact macroeconomic data releases, and session transits, bid/ask spreads widen substantially and quote delivery intervals fluctuate. An Expert Advisor executing market orders during these friction intervals absorbs immediate adverse slippage, increasing transaction drag and causing premature stop-loss executions.
Embedding ad-hoc execution validation directly inside an Expert Advisor's OnTick() handler often results in tightly coupled, fragile codebases:
//+------------------------------------------------------------------+ //| Fragile inline check example (Antipattern) | //+------------------------------------------------------------------+ void OnTick() { //--- Hardcoded spread query without contextual validation long current_spread = SymbolInfoInteger(_Symbol, SYMBOL_SPREAD); if(current_spread > 30) { //--- Reject trade based on arbitrary point threshold Print("Spread too high! Skipping."); return; } // Direct execution logic... }
This inline approach presents three primary software engineering limitations:
-
Static Threshold Regimes: A fixed 30-point ceiling is overly permissive for instruments like EURUSD during active sessions (where normal spread is 6–10 points), yet permanently halts execution on assets like GBPJPY or cross pairs where normal equilibrium spread is 25–40 points.
-
Incomplete State Inspection: Evaluating the current spread in isolation ignores quote feed freshness, broker settlement freeze windows, and order filling mode constraints.
-
Architectural Coupling: Trading signal formulation and broker infrastructure handling become interdependent, making independent unit testing and code reuse across multiple Expert Advisors difficult.
This article presents a modular, broker-aware pre-trade execution filter engine in MQL5. It includes a rolling spread baseline, the CExecutionFilter class, the Ind_Execution_Monitor.mq5 indicator, and the EA_Filter_Demo.mq5 template with reproducible telemetry logging.
Pre-Trade Execution Risk Factors
Prior to dispatching trade orders via CTrade, an algorithmic execution engine can evaluate four practical pre-trade friction factors:
| Risk Factor | Operational Mechanism | Manifestation in MetaTrader 5 | Risk Consequence |
| Rollover Spread Expansion | Interbank settlement (typically 23:45–00:15 broker server time) causes liquidity providers to widen quotes. | SYMBOL_SPREAD widens significantly beyond daytime averages. | Elevated immediate transaction drag; increased proximity to entry stop-loss. |
| Stale Quote Feeds | Network queue congestion or feed interruptions delay incoming price ticks. | Elapsed time since the last tick arrival (time_msc) exceeds the acceptable freshness limit. | Order execution based on outdated pricing; potential off-quotes rejections. |
| Unsupported Filling Policy | Mismatch between order filling policy and broker symbol execution capabilities. | Dispatching ORDER_FILLING_FOK on an instrument only permitting ORDER_FILLING_IOC. | Immediate server rejection with retcode 10030 (TRADE_RETCODE_INVALID_FILL). |
| Dynamic Spread Outliers | Transient quote expansion occurring during thin sessions or localized price shocks. | Current spread deviates significantly from its short-term historical baseline. | Suboptimal trade entry pricing relative to recent market equilibrium. |
Dynamic Spread Baseline Modeling
Rather than relying strictly on arbitrary point limits, the execution filter evaluates incoming spreads relative to recent historical behavior using rolling sample statistics.
Let S = {s_1, s_2, ..., s_k} represent an array of k historical spread samples recorded in points over an evaluation window.
The sample arithmetic mean spread (Mean_S) over window k is calculated as:

The sample standard deviation (StdDev_S) measuring spread dispersion around this mean is:

To evaluate whether the incoming market spread is an outlier independent of the asset pricing scale, the engine computes the standardized Z-score (Z_spread) of the current spread (s_curr):

Under this statistical framework, an incoming trade signal is intercepted and rejected if either of the following conditions is met:
![]()
Here, Lambda represents the statistical multiplier threshold (typically configured between 1.5 and 2.5), and HardCap_Spread acts as an absolute emergency circuit breaker in points.
To ensure reliable variance estimation, the engine enforces a minimum baseline period of 10 observations in both the constructor and the Z-score activation check. Sample sizes below 10 observations produce unstable sample standard deviations that can erratically distort the Z-score. During the initial warm-up phase (before 10 verified samples are collected), or whenever the sample standard deviation is zero (baseline_std == 0.0, such as during intervals of constant spread), the Z-score gate is skipped and the filter relies on the absolute hard cap, rollover window, and quote freshness gates.
If an incoming spread is flagged as anomalous or occurs during the rollover window, the filter blocks it and does not add it to the baseline buffer. Because the rolling baseline contains only approved spread observations, it prevents transient spikes from polluting historical statistics; however, it may not adapt automatically to a sustained upward shift in market spread regimes unless the buffer is reinitialized or configured with wider thresholds.
Class Architecture and Implementation
The pre-trade execution engine is implemented in Execution_Filter.mqh as the CExecutionFilter class. The architecture separates risk verification into dedicated, testable sub-methods.
We first define the operational gate statuses, the diagnostic report structure, and the telemetry container, followed by the class interface declaration:
//+------------------------------------------------------------------+ //| Execution_Filter.mqh | //| Copyright 2026, MetaQuotes Ltd. | //| https://www.mql5.com | //+------------------------------------------------------------------+ #include <Trade\Trade.mqh> //+------------------------------------------------------------------+ //| Pre-Trade Gate Status Enumeration | //+------------------------------------------------------------------+ enum ENUM_GATE_STATUS { GATE_STATUS_ALLOWED = 0, // Execution permitted GATE_STATUS_BLOCKED_SPREAD_ANOMALY, // Spread exceeds statistical Z-score threshold GATE_STATUS_BLOCKED_SPREAD_HARDCAP, // Spread exceeds absolute ceiling GATE_STATUS_BLOCKED_ROLLOVER, // Inside illiquid rollover window GATE_STATUS_BLOCKED_STALE_QUOTE, // Quote age exceeds freshness limit GATE_STATUS_BLOCKED_NO_QUOTE, // Unable to obtain live MqlTick structure GATE_STATUS_BLOCKED_FILLING // Unsupported or invalid symbol filling mode }; //+------------------------------------------------------------------+ //| Diagnostic execution report structure | //+------------------------------------------------------------------+ struct ExecutionGateReport { ENUM_GATE_STATUS status; // Primary gate outcome long current_spread; // Current spread in points double baseline_mean; // Historical spread mean double baseline_std; // Spread standard deviation double z_score; // Computed spread Z-score ulong quote_time_msc; // Quote timestamp in milliseconds uint quote_age_ms; // Elapsed time in milliseconds ENUM_ORDER_TYPE_FILLING resolved_filling; // Selected order filling mode string rejection_reason; // Descriptive diagnostic message }; //+------------------------------------------------------------------+ //| Aggregate telemetry tracking structure | //+------------------------------------------------------------------+ struct ExecutionFilterTelemetry { uint evaluations_total; // Total signals evaluated by the filter uint signals_approved; // Signals passing all safety gates uint orders_dispatched; // Order requests transmitted to trade server uint orders_executed; // Dispatched market orders filled (TRADE_RETCODE_DONE) uint orders_rejected; // Order requests failing locally or rejected by server uint blocked_spread_anomaly; // Intercepted by statistical spread gate uint blocked_spread_hardcap; // Intercepted by absolute spread ceiling uint blocked_rollover; // Intercepted by rollover freeze window uint blocked_stale_quote; // Intercepted by quote staleness check uint blocked_no_quote; // Intercepted due to missing tick data uint blocked_filling; // Intercepted due to unsupported filling }; //+------------------------------------------------------------------+ //| Modular pre-trade execution filter class | //+------------------------------------------------------------------+ class CExecutionFilter { private: string m_symbol; long m_spread_hard_cap; double m_spread_zscore_limit; int m_baseline_period; int m_rollover_start_min; int m_rollover_end_min; uint m_max_quote_age_ms; bool m_enable_rollover_gate; bool m_enable_spread_gate; bool m_enable_freshness_gate; bool m_enable_filling_gate; long m_spread_buffer[]; int m_buffer_count; int m_buffer_idx; ExecutionFilterTelemetry m_telemetry; void UpdateSpreadBuffer(const long current_spread); void ComputeSpreadStats(double &mean, double &std_dev) const; public: CExecutionFilter(const string symbol, const long hard_cap=40, const double zscore_limit=2.0, const int baseline_period=30, const int rollover_start=1425, const int rollover_end=15, const uint max_quote_age=3000); ~CExecutionFilter(void); // Gate evaluation and filling policy bool EvaluateAll(ExecutionGateReport &report); bool ResolveFillingMode(ENUM_ORDER_TYPE_FILLING &filling) const; // Public configuration controls void SetRolloverGate(const bool enable) { m_enable_rollover_gate = enable; } void SetSpreadGate(const bool enable) { m_enable_spread_gate = enable; } void SetFreshnessGate(const bool enable) { m_enable_freshness_gate = enable; } void SetFillingGate(const bool enable) { m_enable_filling_gate = enable; } void SetRolloverWindow(const int start_min, const int end_min); // Telemetry and buffer monitoring ExecutionFilterTelemetry GetTelemetry(void) const { return m_telemetry; } void NotifyOrderDispatched(void) { m_telemetry.orders_dispatched++; } void NotifyOrderExecuted(void) { m_telemetry.orders_executed++; } void NotifyOrderRejected(void) { m_telemetry.orders_rejected++; } void ResetTelemetry(void); int GetBufferCount(void) const { return m_buffer_count; } };
Below is the implementation of each component of the filter engine, illustrating how initialization, statistical tracking, filling resolution, and multi-gate validation work together.
1. Constructor and Destructor Implementation
The constructor validates input parameters, configures operational limits, validates rollover minute boundaries via SetRolloverWindow(), allocates the circular ring buffer for historical spread data, and resets all telemetry counters. It enforces a minimum baseline period of 10 observations so that the rolling buffer capacity matches the Z-score activation condition, while the destructor explicitly releases the internal buffer when the instance is destroyed:
//+------------------------------------------------------------------+ //| Constructor: Parameter validation and ring buffer allocation | //+------------------------------------------------------------------+ CExecutionFilter::CExecutionFilter(const string symbol, const long hard_cap, const double zscore_limit, const int baseline_period, const int rollover_start, const int rollover_end, const uint max_quote_age) { //--- Validate input parameters and assign member variables m_symbol = (symbol == "") ? _Symbol : symbol; m_spread_hard_cap = (hard_cap > 0) ? hard_cap : 40; m_spread_zscore_limit = (zscore_limit > 0.0) ? zscore_limit : 2.0; m_baseline_period = (baseline_period >= 10) ? baseline_period : 30; SetRolloverWindow(rollover_start, rollover_end); m_max_quote_age_ms = (max_quote_age > 0) ? max_quote_age : 3000; //--- Enable default safety gates m_enable_rollover_gate = true; m_enable_spread_gate = true; m_enable_freshness_gate = true; m_enable_filling_gate = true; //--- Allocate static ring buffer m_buffer_count = 0; m_buffer_idx = 0; ArrayResize(m_spread_buffer, m_baseline_period); ArrayInitialize(m_spread_buffer, 0); ResetTelemetry(); } //+------------------------------------------------------------------+ //| Destructor: Clean dynamically allocated array resources | //+------------------------------------------------------------------+ CExecutionFilter::~CExecutionFilter(void) { //--- Release internal buffer storage ArrayFree(m_spread_buffer); }
2. Statistical Baseline Tracking
To maintain a historical spread distribution free from outlier distortion, UpdateSpreadBuffer writes approved spread observations into the circular buffer and advances the write index. ComputeSpreadStats then calculates the arithmetic mean and sample standard deviation (using N - 1 degrees of freedom) across the active sample count:
//+------------------------------------------------------------------+ //| Appends verified spread sample to internal ring buffer | //+------------------------------------------------------------------+ void CExecutionFilter::UpdateSpreadBuffer(const long current_spread) { //--- Write to current index and advance circular pointer m_spread_buffer[m_buffer_idx] = current_spread; m_buffer_idx = (m_buffer_idx + 1) % m_baseline_period; if(m_buffer_count < m_baseline_period) { //--- Increment count until buffer capacity is reached m_buffer_count++; } } //+------------------------------------------------------------------+ //| Computes baseline mean and sample standard deviation | //+------------------------------------------------------------------+ void CExecutionFilter::ComputeSpreadStats(double &mean, double &std_dev) const { //--- Guard against insufficient sample size (minimum 2 samples required) if(m_buffer_count < 2) { mean = 0.0; std_dev = 0.0; return; } //--- Compute arithmetic sample mean double sum = 0.0; for(int i = 0; i < m_buffer_count; i++) { sum += (double)m_spread_buffer[i]; } mean = sum / m_buffer_count; //--- Compute sum of squared differences double sum_sq_diff = 0.0; for(int i = 0; i < m_buffer_count; i++) { double diff = (double)m_spread_buffer[i] - mean; sum_sq_diff += diff * diff; } //--- Compute sample standard deviation (N - 1 degrees of freedom) std_dev = MathSqrt(sum_sq_diff / (m_buffer_count - 1)); }
3. Broker Order Filling Policy Resolution
To avoid server rejections with retcode 10030 (TRADE_RETCODE_INVALID_FILL), ResolveFillingMode inspects both SYMBOL_FILLING_MODE and the symbol execution model SYMBOL_TRADE_EXEMODE. When a symbol operates under SYMBOL_TRADE_EXECUTION_MARKET, ORDER_FILLING_RETURN is not supported; therefore, the method verifies that either SYMBOL_FILLING_FOK or SYMBOL_FILLING_IOC is explicitly enabled and returns false if no valid mode is available:
//+------------------------------------------------------------------+ //| Resolves compliant order filling policy | //+------------------------------------------------------------------+ bool CExecutionFilter::ResolveFillingMode(ENUM_ORDER_TYPE_FILLING &filling) const { //--- Query broker symbol filling mode flags long raw_filling = 0; if(!SymbolInfoInteger(m_symbol, SYMBOL_FILLING_MODE, raw_filling)) { filling = ORDER_FILLING_RETURN; return false; } //--- Query execution mode to prevent invalid return filling on market execution long raw_exe_mode = 0; if(!SymbolInfoInteger(m_symbol, SYMBOL_TRADE_EXEMODE, raw_exe_mode)) { filling = ORDER_FILLING_RETURN; return false; } uint filling_mode = (uint)raw_filling; ENUM_SYMBOL_TRADE_EXECUTION exe_mode = (ENUM_SYMBOL_TRADE_EXECUTION)raw_exe_mode; //--- Check Fill or Kill (FOK) support if((filling_mode & SYMBOL_FILLING_FOK) != 0) { filling = ORDER_FILLING_FOK; return true; } //--- Check Immediate or Cancel (IOC) support if((filling_mode & SYMBOL_FILLING_IOC) != 0) { filling = ORDER_FILLING_IOC; return true; } //--- Evaluate Return policy for exchange, instant, or request execution regimes if(exe_mode != SYMBOL_TRADE_EXECUTION_MARKET) { filling = ORDER_FILLING_RETURN; return true; } //--- Market execution mode requires explicit FOK or IOC support filling = ORDER_FILLING_RETURN; return false; }
4. Pre-Trade Execution Pipeline Evaluation
The EvaluateAll method coordinates the five sequential safety checks before an order is sent. It checks tick availability and freshness via time_msc (using MathMax to prevent negative delta underflow), validates server time against the rollover freeze window via TimeTradeServer(), confirms filling mode compatibility, enforces the absolute spread hard cap, and evaluates the statistical Z-score once at least 10 approved samples are present and baseline_std > 0.0. Candidate spreads are tested before updating the ring buffer so that rejected spikes do not contaminate the rolling baseline:
//+------------------------------------------------------------------+ //| Executes pre-trade gating pipeline | //+------------------------------------------------------------------+ bool CExecutionFilter::EvaluateAll(ExecutionGateReport &report) { m_telemetry.evaluations_total++; //--- Initialize diagnostic report default state report.status = GATE_STATUS_ALLOWED; report.current_spread = 0; report.baseline_mean = 0.0; report.baseline_std = 0.0; report.z_score = 0.0; report.quote_time_msc = 0; report.quote_age_ms = 0; report.resolved_filling = ORDER_FILLING_RETURN; report.rejection_reason = "Execution permitted"; //--- Gate 1: Live quote availability and freshness MqlTick last_tick; if(!SymbolInfoTick(m_symbol, last_tick)) { //--- Intercept missing tick structure report.status = GATE_STATUS_BLOCKED_NO_QUOTE; report.rejection_reason = "Failed to obtain live MqlTick structure"; m_telemetry.blocked_no_quote++; return false; } report.quote_time_msc = last_tick.time_msc; if(m_enable_freshness_gate) { //--- Calculate elapsed age relative to server time (ms) datetime server_time = TimeTradeServer(); long delta_ms = (long)(server_time * 1000) - (long)last_tick.time_msc; report.quote_age_ms = (uint)MathMax(0, delta_ms); if(report.quote_age_ms > m_max_quote_age_ms) { //--- Block stale quote feed report.status = GATE_STATUS_BLOCKED_STALE_QUOTE; report.rejection_reason = StringFormat("Quote age (%u ms) exceeds freshness limit (%u ms)", report.quote_age_ms, m_max_quote_age_ms); m_telemetry.blocked_stale_quote++; return false; } } //--- Gate 2: Rollover freeze window if(m_enable_rollover_gate) { datetime current_server = TimeTradeServer(); MqlDateTime dt; TimeToStruct(current_server, dt); int minute_of_day = (dt.hour * 60) + dt.min; bool inside_rollover = false; if(m_rollover_start_min > m_rollover_end_min) { //--- Rollover window crosses midnight boundary inside_rollover = (minute_of_day >= m_rollover_start_min || minute_of_day < m_rollover_end_min); } else { //--- Rollover window within current calendar day inside_rollover = (minute_of_day >= m_rollover_start_min && minute_of_day < m_rollover_end_min); } if(inside_rollover) { //--- Block execution during rollover clearing report.status = GATE_STATUS_BLOCKED_ROLLOVER; report.rejection_reason = StringFormat("Server time (%02d:%02d) is within rollover freeze window (%02d:%02d-%02d:%02d)", dt.hour, dt.min, m_rollover_start_min / 60, m_rollover_start_min % 60, m_rollover_end_min / 60, m_rollover_end_min % 60); m_telemetry.blocked_rollover++; return false; } } //--- Gate 3: Order filling mode compatibility if(m_enable_filling_gate) { if(!ResolveFillingMode(report.resolved_filling)) { //--- Block execution when filling mode resolution fails report.status = GATE_STATUS_BLOCKED_FILLING; report.rejection_reason = "Unable to resolve a valid broker filling mode for current execution model"; m_telemetry.blocked_filling++; return false; } } else { ResolveFillingMode(report.resolved_filling); } //--- Query live market spread long spread_val = 0; if(!SymbolInfoInteger(m_symbol, SYMBOL_SPREAD, spread_val)) { //--- Intercept missing spread info report.status = GATE_STATUS_BLOCKED_NO_QUOTE; report.rejection_reason = "Failed to query current SYMBOL_SPREAD"; m_telemetry.blocked_no_quote++; return false; } report.current_spread = spread_val; //--- Gate 4: Spread hard cap if(m_enable_spread_gate && report.current_spread > m_spread_hard_cap) { //--- Block execution when spread exceeds absolute ceiling report.status = GATE_STATUS_BLOCKED_SPREAD_HARDCAP; report.rejection_reason = StringFormat("Spread (%d pt) exceeds absolute ceiling (%d pt)", report.current_spread, m_spread_hard_cap); m_telemetry.blocked_spread_hardcap++; return false; } //--- Gate 5: Statistical spread anomaly (Z-score, requires minimum 10 samples) if(m_enable_spread_gate && m_buffer_count >= 10) { ComputeSpreadStats(report.baseline_mean, report.baseline_std); //--- Skip Z-score check when sample standard deviation is zero if(report.baseline_std > 0.0) { report.z_score = (report.current_spread - report.baseline_mean) / report.baseline_std; if(report.z_score > m_spread_zscore_limit) { //--- Block execution when spread is an outlier report.status = GATE_STATUS_BLOCKED_SPREAD_ANOMALY; report.rejection_reason = StringFormat("Spread (%d pt) exceeds Z-score threshold (Z=%.2f, Mean=%.1f, Std=%.1f)", report.current_spread, report.z_score, report.baseline_mean, report.baseline_std); m_telemetry.blocked_spread_anomaly++; return false; } } } //--- Record verified non-anomalous spread observation UpdateSpreadBuffer(report.current_spread); m_telemetry.signals_approved++; return true; }
5. Dynamic Configuration and Telemetry Controls
The configuration methods allow an Expert Advisor to adjust rollover boundaries in minutes from midnight (0–1439) and reset telemetry counters between test runs or trading sessions:
//+------------------------------------------------------------------+ //| Configures rollover minute boundaries (0-1439) | //+------------------------------------------------------------------+ void CExecutionFilter::SetRolloverWindow(const int start_min, const int end_min) { //--- Clamp minute values to valid daily range m_rollover_start_min = (start_min >= 0 && start_min < 1440) ? start_min : 1425; m_rollover_end_min = (end_min >= 0 && end_min < 1440) ? end_min : 15; } //+------------------------------------------------------------------+ //| Resets internal telemetry counters | //+------------------------------------------------------------------+ void CExecutionFilter::ResetTelemetry(void) { //--- Zero out all diagnostic tracking fields m_telemetry.evaluations_total = 0; m_telemetry.signals_approved = 0; m_telemetry.orders_dispatched = 0; m_telemetry.orders_executed = 0; m_telemetry.orders_rejected = 0; m_telemetry.blocked_spread_anomaly = 0; m_telemetry.blocked_spread_hardcap = 0; m_telemetry.blocked_rollover = 0; m_telemetry.blocked_stale_quote = 0; m_telemetry.blocked_no_quote = 0; m_telemetry.blocked_filling = 0; }
Developing the Chart Execution Monitor
The indicator plots historical bar spreads in a separate subwindow. It also shows a dynamic ceiling (Mean + Lambda * StdDev), an absolute hard cap, and a dashboard with current gate results.
Create the file in MQL5\Indicators\Execution_Filter\Ind_Execution_Monitor.mq5:
//+------------------------------------------------------------------+ //| Ind_Execution_Monitor.mq5 | //| Copyright 2026, MetaQuotes Ltd. | //| https://www.mql5.com | //+------------------------------------------------------------------+ #property copyright "Copyright 2026, MetaQuotes Ltd." #property link "https://www.mql5.com" #property version "1.20" #property indicator_separate_window #property indicator_buffers 3 #property indicator_plots 3 #property indicator_label1 "Historical Bar Spread" #property indicator_type1 DRAW_LINE #property indicator_color1 clrDodgerBlue #property indicator_style1 STYLE_SOLID #property indicator_width1 1 #property indicator_label2 "Statistical Dynamic Ceiling" #property indicator_type2 DRAW_LINE #property indicator_color2 clrOrangeRed #property indicator_style2 STYLE_DASH #property indicator_width2 1 #property indicator_label3 "Absolute Spread Hard Cap" #property indicator_type3 DRAW_LINE #property indicator_color3 clrCrimson #property indicator_style3 STYLE_SOLID #property indicator_width3 2 #include <Execution_Filter\Execution_Filter.mqh> input long InpHardCapSpread = 40; // Absolute Spread Hard Cap (Points) input double InpZScoreThreshold = 2.0; // Dynamic Z-score Multiplier input int InpBaselinePeriod = 30; // Baseline Historical Period (Bars >= 10) double BufferSpread[]; double BufferDynamicCeiling[]; double BufferHardCap[]; CExecutionFilter *g_filter; //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int OnInit() { //--- Map indicator data buffers SetIndexBuffer(0, BufferSpread, INDICATOR_DATA); SetIndexBuffer(1, BufferDynamicCeiling, INDICATOR_DATA); SetIndexBuffer(2, BufferHardCap, INDICATOR_DATA); //--- Set empty plot values PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, EMPTY_VALUE); PlotIndexSetDouble(1, PLOT_EMPTY_VALUE, EMPTY_VALUE); PlotIndexSetDouble(2, PLOT_EMPTY_VALUE, EMPTY_VALUE); //--- Define plot drawing start shifts PlotIndexSetInteger(0, PLOT_DRAW_BEGIN, InpBaselinePeriod); PlotIndexSetInteger(1, PLOT_DRAW_BEGIN, InpBaselinePeriod); PlotIndexSetInteger(2, PLOT_DRAW_BEGIN, InpBaselinePeriod); //--- Initialize filter engine instance g_filter = new CExecutionFilter(_Symbol, InpHardCapSpread, InpZScoreThreshold, InpBaselinePeriod); if(g_filter == NULL) return INIT_FAILED; return INIT_SUCCEEDED; } //+------------------------------------------------------------------+ //| Custom indicator deinitialization function | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { //--- Clean dynamic filter memory if(CheckPointer(g_filter) == POINTER_DYNAMIC) delete g_filter; Comment(""); } //+------------------------------------------------------------------+ //| Custom indicator iteration function | //+------------------------------------------------------------------+ int OnCalculate(const int rates_total, const int prev_calculated, const datetime &time[], const double &open[], const double &high[], const double &low[], const double &close[], const long &tick_volume[], const long &volume[], const int &spread[]) { //--- Check minimal bar availability if(rates_total <= InpBaselinePeriod) return 0; //--- Enforce chronological indexing (index 0 = oldest) ArraySetAsSeries(spread, false); ArraySetAsSeries(BufferSpread, false); ArraySetAsSeries(BufferDynamicCeiling, false); ArraySetAsSeries(BufferHardCap, false); //--- Determine calculation starting index int start = prev_calculated - 1; if(start < 0) { start = 0; //--- Initialize warm-up section with EMPTY_VALUE for(int j = 0; j < InpBaselinePeriod && j < rates_total; j++) { BufferSpread[j] = EMPTY_VALUE; BufferDynamicCeiling[j] = EMPTY_VALUE; BufferHardCap[j] = EMPTY_VALUE; } start = InpBaselinePeriod; } //--- Historical buffer calculation loop for(int i = start; i < rates_total && !IsStopped(); i++) { BufferSpread[i] = (double)spread[i]; BufferHardCap[i] = (double)InpHardCapSpread; //--- Calculate rolling mean over completed preceding bars double sum = 0.0; for(int k = 0; k < InpBaselinePeriod; k++) { int idx = (i - 1) - k; if(idx < 0) break; sum += (double)spread[idx]; } double mean = sum / InpBaselinePeriod; //--- Calculate rolling standard deviation double sum_sq = 0.0; for(int k = 0; k < InpBaselinePeriod; k++) { int idx = (i - 1) - k; if(idx < 0) break; double diff = (double)spread[idx] - mean; sum_sq += diff * diff; } double std = MathSqrt(sum_sq / (InpBaselinePeriod - 1)); BufferDynamicCeiling[i] = mean + (InpZScoreThreshold * std); } //--- Update live on-chart telemetry dashboard if(CheckPointer(g_filter) != POINTER_INVALID) { ExecutionGateReport report; bool passed = g_filter.EvaluateAll(report); string status_text = passed ? "ALLOWED (GREEN)" : "BLOCKED (RED)"; string dashboard = StringFormat( "=== Pre-Trade Execution Filter Monitor ===\n" "Symbol: %s | Gate Outcome: %s\n" "Current Spread: %d pt | Hard Cap: %d pt\n" "Rolling Baseline Mean: %.1f pt | StdDev: %.1f pt\n" "Spread Z-score: %.2f | Quote Age: %u ms\n" "Resolved Filling Mode: %s\n" "Status Reason: %s", _Symbol, status_text, report.current_spread, InpHardCapSpread, report.baseline_mean, report.baseline_std, report.z_score, report.quote_age_ms, EnumToString(report.resolved_filling), report.rejection_reason ); Comment(dashboard); } return rates_total; }

Figure 1: Diagnostic execution monitor plotting historical bar spread against dynamic statistical ceiling with real-time on-chart telemetry.
Indicator Diagnostic Considerations and Historical Boundaries
The diagnostic indicator enforces chronological indexing via ArraySetAsSeries(..., false) in OnCalculate(). The initial warm-up segment prior to InpBaselinePeriod is explicitly filled with EMPTY_VALUE to prevent zero-line artifacts on the chart.
The subwindow plot visualizes historical bar spread data (spread[]) from completed bars, while the live dashboard monitors tick-level metrics via SymbolInfoTick() and SYMBOL_SPREAD. Consequently, the indicator's Statistical Dynamic Ceiling plot serves strictly as a historical visual reference calculated from bar spreads, rather than the actual runtime threshold used by CExecutionFilter, whose internal rolling baseline is updated exclusively with approved tick-level spread observations.
Expert Advisor Integration Template
To demonstrate integration and produce verifiable telemetry, we implement EA_Filter_Demo.mq5. The Expert Advisor evaluates candidate entries at the open of each new bar through CExecutionFilter using demonstration settings of 0.10 lot and a 5-bar holding period (InpHoldingBars = 5). In ManageOpenPositions(), the EA checks both the return value of PositionClose() and the server return code (TRADE_RETCODE_DONE) so that a new position cannot be opened while a previous position remains open. Telemetry counters record server dispatch events when requests are transmitted via Buy(), count market executions strictly on TRADE_RETCODE_DONE, and aggregate local request failures or server rejections under orders_rejected.
Create the file in MQL5\Experts\Execution_Filter\EA_Filter_Demo.mq5:
//+------------------------------------------------------------------+ //| EA_Filter_Demo.mq5 | //| Copyright 2026, MetaQuotes Ltd. | //| https://www.mql5.com | //+------------------------------------------------------------------+ #property copyright "Copyright 2026, MetaQuotes Ltd." #property link "https://www.mql5.com" #property version "1.20" #include <Trade\Trade.mqh> #include <Execution_Filter\Execution_Filter.mqh> //--- Input Parameters input long InpHardCapSpread = 40; // Spread Hard Cap (Points) input double InpZScoreThreshold = 2.0; // Statistical Spread Z-score Threshold input int InpBaselinePeriod = 30; // Rolling Baseline Period (Samples >= 10) input int InpRolloverStartMin = 1425; // Rollover Start (Server Time 23:45) input int InpRolloverEndMin = 15; // Rollover End (Server Time 00:15) input uint InpMaxQuoteAgeMs = 3000; // Max Allowable Quote Age (ms) input int InpHoldingBars = 5; // Position Holding Lifetime (Bars, Demo) input ulong InpMagicNumber = 20260901; // Expert Magic Number CExecutionFilter *g_filter; CTrade g_trade; //+------------------------------------------------------------------+ //| Expert initialization function | //+------------------------------------------------------------------+ int OnInit() { //--- Instantiate execution filter with parameter settings g_filter = new CExecutionFilter(_Symbol, InpHardCapSpread, InpZScoreThreshold, InpBaselinePeriod, InpRolloverStartMin, InpRolloverEndMin, InpMaxQuoteAgeMs); if(g_filter == NULL) return INIT_FAILED; //--- Configure trade magic number g_trade.SetExpertMagicNumber(InpMagicNumber); return INIT_SUCCEEDED; } //+------------------------------------------------------------------+ //| Expert deinitialization function with Telemetry Output | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { //--- Output aggregate session telemetry if(CheckPointer(g_filter) == POINTER_DYNAMIC) { //--- Retrieve and print metrics ExecutionFilterTelemetry stats = g_filter.GetTelemetry(); Print("=== Pre-Trade Execution Filter Telemetry Report ==="); PrintFormat("Total Signals Evaluated: %u", stats.evaluations_total); PrintFormat("Signals Approved by Gate: %u", stats.signals_approved); PrintFormat("Orders Dispatched to Server: %u", stats.orders_dispatched); PrintFormat("Orders Executed by Server: %u", stats.orders_executed); PrintFormat("Orders Rejected by Server: %u", stats.orders_rejected); PrintFormat("Blocked (Spread Anomaly Z-score):%u", stats.blocked_spread_anomaly); PrintFormat("Blocked (Spread Hard Ceiling): %u", stats.blocked_spread_hardcap); PrintFormat("Blocked (Rollover Freeze Window):%u", stats.blocked_rollover); PrintFormat("Blocked (Stale Quote Age): %u", stats.blocked_stale_quote); PrintFormat("Blocked (No Live Tick Data): %u", stats.blocked_no_quote); PrintFormat("Blocked (Unsupported Filling): %u", stats.blocked_filling); Print("===================================================="); delete g_filter; } } //+------------------------------------------------------------------+ //| Manages open positions and closes those exceeding holding window | //+------------------------------------------------------------------+ bool ManageOpenPositions(const int max_bars) { //--- Scan open positions matching symbol and magic number bool has_position = false; for(int i = PositionsTotal() - 1; i >= 0; i--) { ulong ticket = PositionGetTicket(i); if(ticket > 0 && PositionSelectByTicket(ticket)) { //--- Compare symbol and magic identifier if(PositionGetString(POSITION_SYMBOL) == _Symbol && PositionGetInteger(POSITION_MAGIC) == InpMagicNumber) { datetime pos_time = (datetime)PositionGetInteger(POSITION_TIME); int bars_open = iBarShift(_Symbol, PERIOD_CURRENT, pos_time); //--- Close position once holding bar lifetime is reached if(bars_open >= max_bars) { if(!g_trade.PositionClose(ticket) || g_trade.ResultRetcode() != TRADE_RETCODE_DONE) { //--- Keep position flag active if close was not completed has_position = true; PrintFormat("[CLOSE FAILED] Ticket #%I64u remained open (Retcode: %u)", ticket, g_trade.ResultRetcode()); } } else { has_position = true; } } } } return has_position; } //+------------------------------------------------------------------+ //| Expert tick function | //+------------------------------------------------------------------+ void OnTick() { //--- Demonstration entry trigger strictly at new bar opening static datetime last_bar = 0; datetime current_bar = iTime(_Symbol, PERIOD_CURRENT, 0); if(current_bar == last_bar) return; last_bar = current_bar; //--- Manage existing positions and prevent new entry while previous position remains open if(ManageOpenPositions(InpHoldingBars)) return; //--- Execute pre-trade filtering pipeline ExecutionGateReport report; if(!g_filter.EvaluateAll(report)) { //--- Intercept blocked signals and log reason PrintFormat("[TRADE BLOCKED] %s (Spread: %d pt)", report.rejection_reason, report.current_spread); return; } //--- Normalize candidate price by symbol tick size double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK); double tick_size = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE); int digits = (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS); double normalized_ask = (tick_size > 0.0) ? (MathRound(ask / tick_size) * tick_size) : NormalizeDouble(ask, digits); //--- Apply resolved filling policy g_trade.SetTypeFilling(report.resolved_filling); //--- Transmit market order (0.10 lot demonstration size) and update telemetry if(g_trade.Buy(0.10, _Symbol, normalized_ask, 0.0, 0.0, "Execution Guard Demo")) { g_filter.NotifyOrderDispatched(); uint retcode = g_trade.ResultRetcode(); if(retcode == TRADE_RETCODE_DONE) { //--- Market order filled by server g_filter.NotifyOrderExecuted(); PrintFormat("[TRADE SUCCESS] Ticket #%I64u executed under spread %d pt (Retcode %u)", g_trade.ResultOrder(), report.current_spread, retcode); } else { //--- Dispatched request not filled g_filter.NotifyOrderRejected(); PrintFormat("[SERVER REJECTED] Request returned retcode %u (%s)", retcode, g_trade.ResultRetcodeDescription()); } } else { //--- Record dispatch if request reached server, and increment rejection counter if(g_trade.ResultRetcode() > 0) g_filter.NotifyOrderDispatched(); g_filter.NotifyOrderRejected(); PrintFormat("[EXECUTION FAILURE] Buy failed: %s (Retcode: %u, System Error: %d)", g_trade.ResultRetcodeDescription(), g_trade.ResultRetcode(), GetLastError()); } }
Testing and Functional Verification
Each gate in the filter engine was verified using targeted test conditions in the Strategy Tester and unit verification harnesses:
| Test Scenario | Verification Method & Input Condition | Expected Behavior | Observed Result & Log Output |
| Standard Spread Equilibrium | EURUSD M15 real-tick playback during London session (Spread = 12 pt, Mean = 11.0 pt, Z = 0.40). | Execution permitted; order dispatched to server. | Confirmed ([TRADE SUCCESS] Ticket executed under spread 12 pt) |
| Rollover Time Gate | Tester clock crossing 23:45–00:15 server window (Server time = 23:55). | Execution blocked (GATE_STATUS_BLOCKED_ROLLOVER). | Confirmed ([TRADE BLOCKED] Server time (23:55) is within rollover freeze window) |
| Transient Spread Spike | Real-tick spread expansion during session transition (Spread = 38 pt, Mean = 11.0 pt, Z = 3.20). | Execution blocked (GATE_STATUS_BLOCKED_SPREAD_ANOMALY). | Confirmed ([TRADE BLOCKED] Spread (38 pt) exceeds Z-score threshold) |
| Absolute Hard Ceiling | Illiquid rollover spike exceeding hard cap (Spread = 65 pt, HardCap = 40 pt). | Execution blocked (GATE_STATUS_BLOCKED_SPREAD_HARDCAP). | Confirmed ([TRADE BLOCKED] Spread (65 pt) exceeds absolute ceiling (40 pt)) |
| Missing Quote Data | Unit harness passing unsubscribed symbol identifier to SymbolInfoTick(). | Execution blocked (GATE_STATUS_BLOCKED_NO_QUOTE). | Confirmed (Failed to obtain live MqlTick structure) |
| Filling Mode Configuration | Executed on symbol with SYMBOL_FILLING_IOC and Market Execution mode. | Configures ORDER_FILLING_IOC on CTrade and dispatches order. | Confirmed (Retcode 10009 TRADE_RETCODE_DONE) |
To make the empirical telemetry reproducible, the benchmark run was executed under the following Strategy Tester environment profile:
| Environment Parameter | Configuration Value |
| Tick Data Source / Server | MetaQuotes-Demo |
| Modeling Mode | Every tick based on real ticks (variable spread) |
| Symbol & Timeframe | EURUSD, M15 |
| Test Period | January 1, 2025 – August 31, 2026 |
| Account Type & Currency | Hedging mode, USD |
| Initial Deposit & Leverage | 10,000 USD, 1:100 |
| Execution Delay (Demonstration Setting) | 50 ms fixed execution delay |
| Position Sizing & Exit (Demonstration Setting) | 0.10 lot per trade, closed after 5 bars (InpHoldingBars = 5), SL/TP = 0.0 |
| Filter Parameters | HardCap = 40 pt, Z-score = 2.0, Baseline = 30 samples, Rollover = 23:45–00:15, MaxAge = 3000 ms |

Figure 2: Execution filter telemetry active in Strategy Tester showing pre-trade blocking events and summary counters in the Journal.
Execution Telemetry and Empirical Observations
During the benchmark test run, the ExecutionFilterTelemetry structure recorded the following distribution of pre-trade and execution events:
| Telemetry Counter | Recorded Value | Operational Description |
| Total Signals Evaluated | 23,919 | Candidate bar-open entry signals evaluated while flat |
| Signals Approved by Gate | 4,318 | Signals satisfying all active pre-trade conditions |
| Orders Dispatched to Server | 4,318 | Order requests transmitted to server via CTrade::Buy() |
| Orders Executed by Server | 4,318 | Dispatched market orders filled (TRADE_RETCODE_DONE) |
| Orders Rejected by Server | 0 | Order requests failing local preparation or rejected by server |
| Blocked (Rollover Freeze Window) | 715 | Entries suppressed during 23:45–00:15 rollover hours |
| Blocked (Spread Anomaly Z-score) | 18,454 | Entries suppressed due to statistical spread widening |
| Blocked (Spread Hard Ceiling) | 432 | Entries suppressed by the 40-point emergency cap |
| Blocked (Stale Quote Age) | 0 | Tick timestamps remained within 3000 ms freshness limit on arrival |
| Blocked (No Live Tick Data) | 0 | Tick structure availability maintained across all evaluations |
| Blocked (Unsupported Filling) | 0 | Compatible filling policy resolved for test symbol |
The default thresholds serve as starting values calibrated for major FX pairs on M15:
-
Hard Cap (InpHardCapSpread = 40): Under the tight daytime spreads in the MetaQuotes-Demo EURUSD historical real-tick dataset (typically 0–2 points), the statistical Z-score gate handles relative expansions (18,454 rejections), while the 40-point hard cap acts as an emergency circuit breaker against extreme illiquidity spikes (432 rejections). Lowering the hard cap shifts more blocks from the Z-score gate to the hard ceiling, whereas raising it delegates nearly all non-rollover spread filtering to the statistical baseline.
-
Baseline Period (InpBaselinePeriod = 30): Thirty approved M15 bar-open samples span 7.5 trading hours (roughly one trading session). Shorter baselines (10–15 samples) adapt faster but exhibit higher sample variance, whereas longer baselines (60+ samples) smooth out variance over multiple sessions.
-
Max Quote Age (InpMaxQuoteAgeMs = 3000): A 3000 ms freshness limit accommodates normal quiet intervals between ticks during slow market hours while flagging delayed tick timestamps upon arrival.
Testing Scope and Boundary Notes: The 0.10-lot order size, 5-bar holding lifetime, and 50 ms fixed execution delay are demonstration settings chosen to generate a continuous sample of trade evaluations across the test horizon. The benchmark reflects a single EURUSD M15 test using historical real ticks with variable spread in the Strategy Tester; in live trading, results will differ by broker, account regime (netting vs. hedging), instrument volatility, and liquidity routing. Furthermore, while the telemetry confirms that the filter blocks trade requests under predefined spread, rollover, freshness, and filling conditions, these counters alone do not independently establish a net reduction in execution costs or slippage without comparative post-trade transaction cost analysis.
Operational Guardrails and Broker Realities
When deploying pre-trade execution filtering in live environments, developers should account for the following practical factors:
-
Retcode Disambiguation: When evaluating trade server responses, distinct return codes must not be confused:
- Retcode 10015 (TRADE_RETCODE_INVALID_PRICE): Indicates an invalid price passed in the trade request.
- Retcode 10016 (TRADE_RETCODE_INVALID_STOPS): Indicates that stop-loss or take-profit levels violate broker Stops Level rules.
- Retcode 10030 (TRADE_RETCODE_INVALID_FILL): Indicates an unsupported order filling mode.
-
The engine specifically addresses filling mode alignment, while price and stop levels must be validated by the strategy's order generation logic.
-
Variable Rollover Timing: Rollover schedules vary across brokers, liquidity bridges, and daylight saving time adjustments. While 23:45–00:15 is common among European brokers, developers should verify broker-specific swap schedules and configure m_rollover_start_min and m_rollover_end_min accordingly.
-
Strategy Tester vs. Live Tick Feeds: Backtesting with "Current Spread" uses a static spread value that conceals rollover expansion. Developers must test with "Every tick based on real ticks" using variable spread data to evaluate dynamic baseline filters properly.
System Limitations
The pre-trade execution filter provides structured risk controls, but developers should recognize its operational boundaries:
-
Network Transit Slippage: The filter verifies market conditions before sending an order. It cannot prevent execution slippage that occurs during network transit between the client terminal and the broker matching engine.
-
Quote Age and Event-Driven OnTick() Scope: Quote age measures the time elapsed since the last tick received by the client terminal rather than round-trip network latency. Furthermore, when EvaluateAll() is called only from the current symbol's OnTick() handler, the stale-quote gate only evaluates ticks as they arrive and cannot actively detect a complete quote-feed interruption during which no new OnTick() events are generated; active feed-outage detection requires invoking the check from an OnTimer() handler.
-
Approved-Only Baseline Adaptation and News Gaps: Because the rolling buffer stores only approved spread observations, it may not adapt automatically to a sustained upward shift in market spread conditions. Additionally, during sudden macroeconomic announcements, price and spread gaps can occur faster than the rolling baseline updates.
Conclusion and Reusable Artifacts
This article presented a modular Pre-Trade Execution Filter Engine in MQL5 that decouples pre-trade execution checks from core trading strategy logic. Combining a rolling Z-score baseline with an absolute hard cap, server-synchronized rollover windows, quote freshness checks, and execution-mode-aware filling resolution helps screen out predefined adverse execution conditions across automated trading systems.
| File Name | Location | Function |
| Execution_Filter.mqh | MQL5\Include\Execution_Filter\ | Reusable include class providing pre-trade gating and telemetry. |
| Ind_Execution_Monitor.mq5 | MQL5\Indicators\Execution_Filter\ | Companion indicator plotting historical spreads and real-time dashboard. |
| EA_Filter_Demo.mq5 | MQL5\Experts\Execution_Filter\ | Expert Advisor template demonstrating filter integration, position holding exit, and logging. |
| MQL5.zip | Root project attachment | Structured ZIP archive containing all project source files. |
Warning: All rights to these materials are reserved by MetaQuotes Ltd. Copying or reprinting of these materials in whole or in part is prohibited.
This article was written by a user of the site and reflects their personal views. MetaQuotes Ltd is not responsible for the accuracy of the information presented, nor for any consequences resulting from the use of the solutions, strategies or recommendations described.