What is How to Add News Filter and Equity Protection to MetaTrader EA Code in Forex Trading?
Published: Sep 08, 2026 Last Updated: Sep 08, 2026 By FXSnipers Team ✓ Reviewed by FXSnipers Research Team

What is How to Add News Filter and Equity Protection to MetaTrader EA Code in Forex Trading?

Automated trading systems, or Expert Advisors (EAs), are highly efficient at executing rule-based strategies 24/5. However, even the most robust technical indicators can fail when confronted with extreme fundamental volatility or unexpected market events. Without safeguards, high-impact news releases or cascading drawdowns can decimate a trading account in minutes.

To transform a basic trading algorithm into an institutional-grade system, developers and algorithmic traders must integrate two critical risk-mitigation features: a News Filter and Equity Protection. This guide walks you through the concepts, logical flows, and MQL4/MQL5 code blocks required to embed these guardrails directly into your MetaTrader Expert Advisors.

Key Takeaway: A profitable strategy is only as good as its defense. Adding active news filters and absolute equity hard-stops ensures that your EA survives unexpected black swan events and high-spread macroeconomic announcements.

How to Implement a News Filter in MetaTrader (MQL4/MQL5)

A news filter prevents your EA from opening new positions (and optionally closes existing ones) during high-impact macroeconomic events, such as Non-Farm Payrolls (NFP), FOMC interest rate decisions, or CPI releases. During these periods, liquidity dries up, spreads widen, and slippage increases significantly.

To build a news filter, your EA needs to know when these events occur. This is typically achieved by using a WebRequest() function inside MQL to fetch XML or JSON calendar data from an external provider, parsing the timestamps, and comparing them with the terminal's current time.

The Logic of a News Filter

The algorithm evaluates the time distance between the current market time and the nearest upcoming or recently passed news event. The configuration is usually managed with three primary variables:

  • Minutes Before News: The window before the event during which new trades are blocked (e.g., 30 minutes).
  • Minutes After News: The cooling-off period after the event before trading resumes (e.g., 60 minutes).
  • Impact Level: A filter to only trigger blocks for high-impact events (often labeled as "High" or "Red" news).

Sample MQL Code Structure for News Checking

Below is a conceptual code block demonstrating how an EA checks if it is currently safe to trade based on a simplified time array of upcoming news events. If you are not comfortable writing your own data parsers, you can explore pre-configured, professional-grade systems in our free and premium Expert Advisors directory.

// Global inputs
input bool   UseNewsFilter      = true;     // Enable News Filter
input int    MinsBeforeNews     = 30;       // Stop trading X minutes before news
input int    MinsAfterNews      = 60;       // Resume trading Y minutes after news

// Array holding parsed news times (datetime)
datetime NewsTimes[];

// Function to check if trading is allowed
bool IsTradingAllowedByNews() {
    if (!UseNewsFilter) return true;

    datetime currentServerTime = TimeCurrent();
    int totalEvents = ArraySize(NewsTimes);

    for (int i = 0; i < totalEvents; i++) {
        datetime newsTime = NewsTimes[i];
        
        // Calculate the difference in seconds
        long diffBefore = (long)newsTime - (long)currentServerTime;
        long diffAfter  = (long)currentServerTime - (long)newsTime;

        // Check if we are inside the restricted "before" window
        if (diffBefore > 0 && diffBefore <= (MinsBeforeNews * 60)) {
            return false; // Trading is blocked
        }
        
        // Check if we are inside the restricted "after" window
        if (diffAfter > 0 && diffAfter <= (MinsAfterNews * 60)) {
            return false; // Trading is blocked
        }
    }
    return true; // Safe to trade
}

Adding Equity Protection to Your EA

While a news filter protects against external economic shockwaves, equity protection guards your account from internal strategy failure—such as grid setups going rogue or trade management failure during unexpected black-swan trend shifts.

Equity protection refers to real-time risk-monitoring routines that track the account's overall floating loss and profit. If the floating drawdown exceeds a specific pre-defined threshold (either in cash value or percentage terms), the EA acts as an emergency circuit breaker. It will instantly close all open market positions, delete pending orders, and halt trading operations completely.

Core Components of Equity Protection

  • Max Drawdown Threshold: The absolute maximum percentage of account balance (e.g., 5% or 10%) you are willing to risk across all open positions.
  • Daily Loss Limit: A limit reset every 24 hours that locks trading once a cumulative daily loss target is breached.
  • Hard Stop-Out Execution: The backend process that loops through all open orders, closes them via market execution, and disables the EA.

MQL5 Equity Protection Implementation Example

The following implementation displays how to calculate current equity drawdown in real-time and trigger a hard exit if your threshold is crossed. If you need help integrating advanced functions like this into your custom indicators or strategies, check out our custom MQL coding services.

// Global inputs
input double MaxDrawdownPercent = 5.0; // Max Allowed Drawdown %
input bool   CloseAllOnBreach   = true; // Close all trades on breach

// Check Equity Protection inside OnTick()
void CheckEquityProtection() {
    double balance = AccountInfoDouble(ACCOUNT_BALANCE);
    double equity  = AccountInfoDouble(ACCOUNT_EQUITY);
    
    // Calculate current drawdown percentage
    double currentDrawdown = 0.0;
    if (balance > 0) {
        currentDrawdown = ((balance - equity) / balance) * 100.0;
    }
    
    if (currentDrawdown >= MaxDrawdownPercent) {
        Print("CRITICAL: Equity Protection triggered. Drawdown is: ", DoubleToString(currentDrawdown, 2), "%");
        
        if (CloseAllOnBreach) {
            CloseAllOpenTrades();
            DeleteAllPendingOrders();
        }
        
        // Deactivate the EA to prevent further trading
        ExpertRemove();
    }
}

// Function to close all open market positions
void CloseAllOpenTrades() {
    // Loop backwards through open positions and close them (MQL5 logic)
    for (int i = PositionsTotal() - 1; i >= 0; i--) {
        ulong ticket = PositionGetTicket(i);
        if (ticket > 0) {
            // Include trade execution class to close by ticket
            // e.g., trade.PositionClose(ticket);
        }
    }
}

Combining the Features for Institutional Risk Control

Adding these algorithms directly into your EA’s main logic block ensures that your automated systems act defensively. By integrating the news filter within the order entry conditions and placing the equity protection routine inside the OnTick() function, you build a double-layered defense system.

Before deploying code to a live account, it is critical to backtest the logic using real variable spread data, high latency simulation, and historical calendar integration. This ensures that your filters function as expected under extreme conditions without generating runtime errors or infinite order-execution loops.

Developer Tip: Keep an eye on MetaTrader's "WebRequests" settings. To fetch news successfully, you must explicitly add the target calendar domain to the list of allowed URLs in Tools -> Options -> Expert Advisors -> Allow WebRequest for listed URL.

Conclusion

Developing a highly accurate entry strategy is only one half of professional algorithmic trading. Protecting trading capital from unexpected macroeconomic disruptions and strategy tail-risk is what ultimately separates successful systems from failing ones.

By integrating a robust news calendar filter and setting up real-time equity hard-stops, you can significantly lower the risk profile of your portfolio. Whether you build these systems yourself using MQL code or employ premium pre-built scripts, proper risk structures will ensure your portfolio survives to trade another day.

RN

FXSnipers Team

Lead MQL Developer

Algorithmic systems architect and quantitative developer at FXSnipers. Specializes in MQL5 strategy automation, MT5 tick data modeling, and mathematical risk management systems.

Recommended Trading Tools & EAs

Automate your strategies with these fully backtested expert advisors matching this article's topics.

THRONE OF THORNS EA (CON)
Expert Advisor

THRONE OF THORNS EA (CON)

An adaptive auction-driven EA that reads live tick order flow to classify the market as TRENDING or RANGING, then deploys three coordinated roles — SWORD, SPIKE, and GHOST — to attack, recover, and extend positions with full daily profit-lock and drawdown protection.

FXSnipers Team

Written by FXSnipers Team

The FXSnipers Team is a dedicated group of professional traders and quantitative developers. With years of experience building high-performance Expert Advisors, automated systems, and robust risk management strategies for MT4 and MT5, they share deep market insights to help retail traders automate their success.

Other Articles You Might Like

Exclusive Trader Kit 2026

Forex EA & Risk Management Cheat Sheet

Download the complete quantitative guide: Position Sizing Formulas, Prop Firm Drawdown Rules, and MQL5 Parameter Cheat Sheets.

Instant PDF Access No Spam Guarantee