Expert Advisors • Indicators • Scripts • Libraries

MQL.RobotFX.org is the biggest collection of MetaTrader expert advisors (MT5 & MT4), indicators, scripts and libraries that can be used to improve trading results, minimize risks or simply automate trading tasks

Metatrader 5 Expert Advisor | Close ALL positions from EA MQL5

CloseAll Module – Automatic Position Closing for MetaTrader 5

The CloseAll Module is a lightweight but powerful utility designed to automatically close all open positions belonging to an Expert Advisor. By filtering positions by symbol and Magic Number, it ensures that only the EA’s own trades are targeted, providing a secure and controlled way to reset trading activity instantly.

This module is especially useful for strategies requiring rapid exit conditions, equity protection systems, emergency stop mechanisms, or shutdown routines after achieving a target profit or risk threshold.
Imagen generada


Purpose

Managing open positions efficiently is crucial in algorithmic trading. In certain scenarios, a strategy must close all active trades immediately—without manual intervention. This module provides exactly that by:

  • Closing all BUY and SELL positions created by the EA

  • Filtering trades by Magic Number for safety

  • int OnInit() {
      return(INIT_SUCCEEDED);
    }
    


    Operating only on the current chart symbol

  • Executing the closing process automatically on every tick (or on demand)

It ensures fast and reliable trade closure in a controlled and accurate manner.


How It Works

1. Trade Library Initialization

The module begins by including the standard MetaTrader 5 trading library:

#include <Trade\Trade.mqh>
CTrade trade;

This provides access to trading functions, including PositionClose() .


2. Global Variables and Magic Number

Two counters are used internally (though not required for the closing logic), and a Magic Number is used to identify which trades belong to the EA:

int Position_buy_count;
int Position_sell_count;

input long MagicNumber = 47836;


3. Execution Flow

The EA initializes normally:

int OnInit() {
  return(INIT_SUCCEEDED);
}
And OnTick calls function when you needed it :
void OnTick() {
  CloseAll();
}

4. The Closing Algorithm

The CloseAll() function:

  • Resets internal counters

  • Iterates through all open positions in reverse order

  • Filters trades by symbol and Magic Number

  • Closes matching positions using trade.PositionClose()

Full function:

void CloseAll() {
  Position_buy_count = 0;
  Position_sell_count = 0;

  for (int i = PositionsTotal() - 1; i >= 0; i--) {
    ulong Ticket = PositionGetTicket(i);
    string PositionSimbol = PositionGetString(POSITION_SYMBOL);
    long PositionMagicNumber = PositionGetInteger(POSITION_MAGIC);

    if (_Symbol == PositionSimbol && MagicNumber == PositionMagicNumber) {
      trade.PositionClose(Ticket);
    }
  }
}

The reverse iteration ensures stable indexing while closing positions, preventing any position from being skipped.


Key Features

  • Automatic closure: Closes all open positions on every tick

  • Safe filtering: Only closes trades with the specified Magic Number

  • Symbol-specific: Operates only on the current chart symbol

  • Fast and efficient: Uses built-in MQL5 trading classes

  • Clean structure: Easy to integrate into any Expert Advisor


Usage Instructions

  1. Import the module into your EA.

  2. Adjust the Magic Number to match your trading system.

  3. Call CloseAll() inside OnTick, OnTimer, or when specific conditions are met.

  4. Ensure your EA has trading permissions enabled in MetaTrader 5.

  5. Monitor closures in the Experts or Journal tab.


Recommended Use Cases

  • Emergency stop module (risk cutoff)

  • Closing all positions after hitting a profit target

  • Resetting a grid or martingale system

  • Ending all trades when market conditions change

  • Preparing the EA for shutdown or strategy reset

  • Creating a “Panic Button” function within an EA


Important Notes

  • The module only closes positions from the current chart symbol.

  • It will not close trades from other symbols unless the function is modified.

  • The Magic Number must match the EA’s opened positions.

  • Pending orders are not closed—only active positions.

  • Requires proper trade permissions in MetaTrader 5.




66035

Best MetaTrader Indicators + Profitable Expert Advisors