---
title: "Close all positions at once in MT4 and MT5 · CloudSat"
description: "Close every open position at once with MetaTrader 5's Group operations, see what MT4 offers instead, and use a filtered close-all script for MQL4 or MQL5."
url: https://cloudsat.io/learn/close-all-positions-in-mt4-and-mt5
updated: 2026-11-18T12:00:00Z
source: CloudSat (https://cloudsat.io/). Prices in USD.
---

[Trading and crypto](https://cloudsat.io/learn/topic/trading)

# Close all positions at once in MT4 and MT5

Close every open position at once with MetaTrader 5's Group operations, see what MT4 offers instead, and use a filtered close-all script for MQL4 or MQL5.

CloudSat team November 18, 2026 7 min read

There are moments when you want to be flat now: before a release you do not want to hold through, when an Expert Advisor misbehaves, at the end of a session. MetaTrader 5 has a built-in menu for it. MetaTrader 4 does not, and the usual answer there is a script. This guide covers both, along with what "close all" leaves behind, because closing positions is only one of the three things that make an account truly flat.

## What closing everything involves

Three separate things keep an account in the market, and a close-all command handles only one:

| What | Handled by closing positions? | How to deal with it |
| --- | --- | --- |
| Open positions | Yes | The commands and scripts below |
| Pending orders | No | Delete them separately, or they can open new positions later |
| Running Expert Advisors | No | Switch automated trading off first, or they may reopen trades |

A close-all also acts on the whole account, not on one terminal. If the same account is logged in on a VPS and on your PC, positions opened by either are closed, and an EA running in the other terminal can open new ones a second later.

Each position closes with its own market order and pays its own spread, one after another. In a fast market, the last ones may fill at noticeably different prices than the first.

## MetaTrader 5: Group operations

MT5 groups its bulk commands under **Group operations** in the context menu of the **Trade** tab in the Toolbox. The menu only appears when **One Click Trading** is enabled in the platform settings, which asks you to accept its terms the first time.

Always available:

- **Close all positions.** On hedging accounts, the platform first closes opposite positions against each other with **Close By**, then closes what remains normally.
- **Close all profitable positions** and **close all losing positions.**

With a position selected, the menu adds:

- Close all positions for that symbol.
- Close all positions in the same direction (hedging accounts).
- Close opposite positions for the same symbol (hedging accounts).
- Reverse the position (netting accounts).

The same menu deletes pending orders: all of them, those of one type (limit, stop or stop limit), or those for the selected symbol.

Two details are worth knowing. **Close By** closes two opposite positions on the same symbol in one operation, which saves one spread compared with closing each, and is only available in the hedging accounting system. And if an error occurs while opposite positions are being closed, the whole process stops, so look at the Trade tab afterwards and close any survivors. Accounts that follow FIFO rules, which require the oldest position on a symbol to be closed first, do not show the operations that would break that order.

## MetaTrader 4: no built-in close-all

MT4 closes positions one at a time from the **Trade** tab of the Terminal window: double-click a position, or right-click and choose **Close Order**. On accounts that allow opposite positions, the close window's **Close By** type closes one position against another on the same symbol.

For more than a handful of positions, a script is faster and less error-prone. A script runs once when you drop it on a chart and then exits.

## A close-all script for MQL4

This script closes buys, sells or both, optionally deletes pending orders, and can be limited to one symbol or one EA's magic number. `show_confirm` makes the terminal ask before it runs, and `script_show_inputs` shows the options each time:

```mql4
#property strict
#property show_confirm
#property script_show_inputs

input bool   CloseBuys      = true;
input bool   CloseSells     = true;
input bool   DeletePending  = false;
input string OnlySymbol     = "";   // empty = every symbol
input int    OnlyMagic      = -1;   // -1 = any magic number
input int    SlippagePoints = 10;

bool Matches()
{
   if(OnlySymbol != "" && OrderSymbol() != OnlySymbol) return(false);
   if(OnlyMagic >= 0 && OrderMagicNumber() != OnlyMagic) return(false);
   return(true);
}

void OnStart()
{
   for(int i = OrdersTotal() - 1; i >= 0; i--)
   {
      if(!OrderSelect(i, SELECT_BY_POS, MODE_TRADES) || !Matches()) continue;
      int  type = OrderType();
      bool ok   = true;

      if(type == OP_BUY && CloseBuys)
         ok = OrderClose(OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_BID), SlippagePoints, clrNONE);
      else if(type == OP_SELL && CloseSells)
         ok = OrderClose(OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_ASK), SlippagePoints, clrNONE);
      else if(type > OP_SELL && DeletePending)
         ok = OrderDelete(OrderTicket());

      if(!ok) Print("Order #", OrderTicket(), " failed, error ", GetLastError());
   }
}
```

The loop runs from the last order to the first, because closing an order shifts the positions of the ones after it. A buy closes at the bid and a sell at the ask; pending orders have types above `OP_SELL`.

To install it, open **File > Open Data Folder**, save the code as `MQL4\Scripts\CloseAll.mq4`, open it in MetaEditor and compile. A script that trades needs the same permissions as an EA: **AutoTrading** on, and **Allow live trading** ticked on the **Common** tab when its settings appear. Try it on a demo account with a few small positions before you need it for real.

## The same idea in MQL5

In MT5 the built-in menu covers most cases, but a script is still useful inside an EA's emergency logic, or when you want a one-key close with a filter. The standard library's `CTrade` class does the work:

```mql5
#property script_show_inputs
#include <Trade\Trade.mqh>

input long OnlyMagic = -1;   // -1 = any magic number

void OnStart()
{
   CTrade trade;
   trade.SetDeviationInPoints(10);
   for(int i = PositionsTotal() - 1; i >= 0; i--)
   {
      ulong ticket = PositionGetTicket(i);   // also selects the position
      if(ticket == 0) continue;
      if(OnlyMagic >= 0 && PositionGetInteger(POSITION_MAGIC) != OnlyMagic) continue;
      if(!trade.PositionClose(ticket))
         Print("Position #", ticket, " failed: ", trade.ResultRetcodeDescription());
   }
}
```

Save it in `MQL5\Scripts` and compile it. Pending orders in MT5 are separate from positions, so delete them through **Group operations** or extend the script with a loop over `OrdersTotal()`.

## When a position will not close

A close request can fail for reasons that have nothing to do with the script. The Journal tab shows the server's answer for each one, and the MQL4 error codes printed by the script map to these causes:

| Code (MQL4) | Message | What it means | What to do |
| --- | --- | --- | --- |
| 132 | Market is closed | The symbol's session has ended | Wait for the session; the symbol's **Specification** lists its hours |
| 133 | Trade is disabled | The broker has restricted trading on the symbol | Ask the broker; some restrictions allow closing only |
| 136 / 138 | Off quotes / requote | The price moved before the order was accepted | Run the script again; raise the slippage input only if you accept a worse fill |
| 146 | Trade context busy | Another program was sending an order at the same moment | Wait a second and run it again |

A script that reports failures and can be run twice is easier to trust than one that retries silently in a loop, which in a fast market can keep sending orders at worse and worse prices.

## Make it quick to reach

In both platforms, right-click a script in the Navigator and choose **Set hotkey** to run it from the keyboard. The confirmation prompt from `show_confirm` keeps a stray key press from flattening the account.

For a genuine emergency, the order of actions matters more than the tool:

1. Switch **AutoTrading** (MT5: **Algo Trading**) off, so no EA reacts to what you do next.
2. Close the positions with the menu or the script.
3. Delete pending orders.
4. Check the Trade tab, and the Journal for any request the server rejected.
5. If the account is also logged in elsewhere, stop the EAs there too.

## FAQ

### Does closing all positions delete my pending orders?

No. In MT5, use the pending-order commands in **Group operations**; in MT4, run the script with `DeletePending` set to true. Left in place, a pending order can open a new position after you thought you were flat.

### Why did positions reopen right after I closed them?

An Expert Advisor was still running, either in this terminal or in another one logged in to the same account. Switch automated trading off in every terminal before closing.

### Is Close By cheaper than closing positions separately?

On hedging accounts, yes by one spread: two opposite positions close against each other instead of through two market orders. It is not available on netting accounts.

### Can the script close positions on every symbol at once?

Yes. Leave `OnlySymbol` empty and it works through every open order on the account, whatever chart you drop it on.

*Trading involves risk of loss. Nothing in this article is financial advice.*

**Run it on CloudSat.** Cloud VPS on AMD EPYC and NVMe from $1.98/mo in 13 regions, delivered in under 5 minutes and paid in crypto. [See plans](https://cloudsat.io/plans) or [deploy a server](https://dash.cloudsat.io/console/deploy).

## Keep reading

[All guides in Trading and crypto](https://cloudsat.io/learn/topic/trading)

- [Risk controls in MetaTrader 4 and 5: orders, limits, code](https://cloudsat.io/learn/risk-controls-in-metatrader-4-and-5): Trading and crypto Risk controls in MetaTrader 4 and 5: orders, limits, code 7 min read
- [MetaTrader 4 tour: windows, charts, orders and logs](https://cloudsat.io/learn/metatrader-4-terminal-tour): Trading and crypto MetaTrader 4 tour: windows, charts, orders and logs 7 min read
- [Install and run an Expert Advisor in MetaTrader 4](https://cloudsat.io/learn/install-and-run-an-expert-advisor-in-mt4): Trading and crypto Install and run an Expert Advisor in MetaTrader 4 7 min read
- [Install and update MetaTrader 4 on desktop and mobile](https://cloudsat.io/learn/install-and-update-metatrader-4): Trading and crypto Install and update MetaTrader 4 on desktop and mobile 6 min read
