Close All Orders/Positions for MT4/MT5
Table of contents
Orders management is a fundamental task when working with trading tools and expert advisors. In some cases, especially when there is a trigger from some risk management rule, you might want to close all open orders. Here, we will examine two functions — one in MQL4 code and another one in MQL5 code — for doing that, and you will also be able to download a free Close All Orders script for MT4 — a script that can close all open orders automatically. A similar script called Close All Positions is also available for MetaTrader 5.
MQL4 close all orders
When coding an expert advisor, we should all implement safety measures to protect us from big losses. Risk management is a fundamental pillar of an EA. It is necessary to set rules, so that your EA can close all orders if some condition is met.
Some examples that could trigger the closure of all orders can be:
- A group of orders hit the take-profit.
- The cumulative loss of open orders causes the equity or the margin to go under a specific threshold.
- There is a scheduled report coming out that could heavily impact prices.
- An unexpected event is causing sudden changes in exchange rates.
These are only some situations that can push you to close all open orders immediately. You can achieve that with a rather simple piece of MQL4 code.
You have probably already read our guide on the OrderClose function, which can close an individual order in MT4. Below, you can see how to use it to close all orders with a custom function.
The following MQL4 Close All Orders function can close all the open market orders in the same run.
void CloseOrders() { int total = OrdersTotal(); // Log in the terminal the total number of orders. Print(total); // Start a loop to scan all the orders. // The loop starts from the last, otherwise it could skip orders. for (int i = total - 1; i >= 0; i--) { // If the order cannot be selected, throw and log an error. if (OrderSelect(i, SELECT_BY_POS) == false) { Print("ERROR - Unable to select the order - ", GetLastError()); break; } // Result variable - to check if the operation is successful or not. bool result = false; // Update the exchange rates before closing the orders. RefreshRates(); // Bid and Ask price for the order's symbol. double BidPrice = MarketInfo(OrderSymbol(), MODE_BID); double AskPrice = MarketInfo(OrderSymbol(), MODE_ASK); // Closing the order using the correct price depending on the order's type. if (OrderType() == OP_BUY) { result = OrderClose(OrderTicket(), OrderLots(), BidPrice, Slippage); } else if (OrderType() == OP_SELL) { result = OrderClose(OrderTicket(), OrderLots(), AskPrice, Slippage); } // If there was an error, log it. if (!result) Print("ERROR - Unable to close the order - ", OrderTicket(), " - Error ", GetLastError()); } }
MQL4 close all orders function logic
The logic of the function is the following:
- Using a loop, scan all orders.
- Update the prices.
- If the type of order is market buy or sell, close the order using the correct price.
- Check if the operation was successful for each order and, in case it wasn't, return an error.
Possible improvements
The function is not very complex and it can be improved with additional filters. For example, you might want to apply some of the following filters:
- Close only orders in profit.
- Close only orders in loss.
- Close only orders for a specific pair.
- Close only orders with a specific magic number.
- Other filters.
The above function, in a somewhat modified form, is used by many of our expert advisors.
Close All Orders script
If you want to close all orders in MT4, you need to do it manually, unless you use an external tool.
Unfortunately, MT4 does not allow selecting all open orders and closing them all at once.
But there is a solution! You can either code your own script, using the function above as a template, or you can use a ready-made tool.
The script provided below can be copied to your MT4 platform and will let you close all orders with just a couple of clicks.
There is a number of input parameters to set up the script according to your preferences:
In addition to filtering parameters, there is an option to sort orders before closing them in a particular order. This lets you opt for closing the orders of high priority first.
A notable option is to set up a delay (in milliseconds) between closing attempts to avoid overloading the trading server as some Forex brokers don't allow such a behavior and may block autotrading on your account.
You can also control the number of tries the script will go through to close each order. This allows ensure proper closure of trades even during high volatility periods when a close order command to the server may fail due to some error.
Download Close All Orders script for MT4
➥ Download Close All Orders for MT4MT4 Close All Orders script installation
To install the script, please follow the instructions below:
- Download the script archive file.
- Open the MetaTrader 4 data folder (via File→Open Data Folder).
- Open the MQL4 folder.
- Copy all the folders from the archive directly to the MQL4 folder.
- Restart MetaTrader 4 or refresh the list of scripts by right-clicking the Navigator subwindow of the platform and choosing Refresh.
You can also read a more detailed instruction on how to perform the installation.
Make sure you enable Allow live trading in the Common tab when executing this script and also in the platform's menu Tools→Options→Expert Advisors. Otherwise, it won't be able to close any orders.
Pre-entered input parameters
You can pre-enter input parameter values of the Close All Orders script and then save a copy with a different file name to use pre-configured scripts whenever you need them without the need to spend time on the modification of the input parameters.
This way, you will have several scripts at hand ready to be executed (using a keyboard shortcut for example) depending on the situation.
For example, let's make a version for closing only all losing trades.
First, you need to open the CloseAllOrders.mq4 file and locate the OnlyInLoss input parameter:
Now, change the default value from false to true:
It also makes sense to remove the show_inputs
property altogether in such a pre-configured version. This will prevent the confirmation window from appearing when you launch the script:
The line can be either commented out (using two slashes in front of it) or removed altogether:
You can now save the file with some other name to distinguish it from the standard Close All Orders script. For example, you may want to call this one CloseAllOrders_Losing.mq4:
Now it's time to compile the source code:
You can now execute the new script as usual in your MetaTrader 4 or you can right-click on it and set a hotkey:
Now you can run this script instantly to close orders filtered according to your specific requirements as quickly as possible.
A similar process can be repeated to create scripts that close only buy or only sell orders, or a script that closes only orders with a specific magic number (if you need to close only trades opened by some EA), and so on.
MQL5 close all positions
The concept of a function that closes all trades in MetaTrader 5 isn't much different from that of MetaTrader 4. The main difference is that the market orders are called positions in MT5.
This position closing function can be used in the same situations as you would you use the close orders function in MetaTrader 4.
The following MQL5 Close All Positions code is designed to terminate all the existing positions in a single run.
void ClosePositions() { Trade = new CTrade; // A CTrade object to close positions. int total = PositionsTotal(); // Log in the terminal the total number of positions. Print(total); // Start a loop to scan all the positions. // The loop starts from the last, otherwise it could skip positions. for (int i = total - 1; i >= 0; i--) { // If the position cannot be selected, throw and log an error. if (PositionGetSymbol(i) == "") { Print("ERROR - Unable to select the position - ", GetLastError()); break; } // Result variable - to check if the operation is successful or not. bool result = Trade.PositionClose(PositionGetInteger(POSITION_TICKET), Slippage); // If there was an error, log it. if (!result) Print("ERROR - Unable to close the position - ", PositionGetInteger(POSITION_TICKET), " - Error ", GetLastError()); } }
MQL5 close all positions function logic
The function's logic is the following:
- Using a loop, scan all positions.
- Close the position.
- Check if the operation was successful for each position and, in case it wasn't, return an error.
As you can see, it's much simpler in MT5 than in MT4.
Possible improvements
As is the case with the MQL4 closing function, this one could also be improved by adding various filters and sorting options.
Close All Positions script
Unlike MT4, MetaTrader 5 has a built-in facility to mass-close positions — Bulk Operations. However, as you can see, it has its own limitations:
It can close all positions, all profitable positions, all losing positions, all buy positions, all sell positions, all <
current symbol>
positions, or all <
current direction>
in <
current symbol>
positions. Additionally, you can use the Close by method to close the current position using opposite positions in the same symbol (only in hedging mode).
That's not bad compared to what you have in MT4 out of the box, but that still can be vastly improved using, at the very least, additional filters and sorting options.
The script provided below can be installed on your MT5 platform, letting you close all positions based on your preferences:
As is the case with the MT4 script above, the script for MT5 lets you filter positions, sort them, add a delay, and set a number of retries when a closure fails.
Download Close All Positions script for MT5
➥ Download Close All Positions for MT5MT5 Close All Positions script installation
To install the script, please follow the instructions below:
- Download the script archive file.
- Open the MetaTrader 5 data folder (via File→Open Data Folder).
- Navigate to the MQL5 folder.
- Copy all the folders from the archive directly to the MQL5 folder.
- Restart MetaTrader 5 or refresh the list of scripts by right-clicking the Navigator subwindow of the platform and choosing Refresh.
You can also read a more detailed instruction on how to perform the installation.
Make sure you enable Allow Algo Trading in the Common tab when executing this script and also in the platform's menu Tools→Options→Expert Advisors. Otherwise, it won't be able to close any orders.
Pre-entered input parameters
The same as with the MT4 version of the script, it makes sense to pre-enter input parameter values and save a copy with a new file name to use such pre-configured scripts without wasting time on the inputs.
You can prepare several such position-closing scripts and launch them based on the current situation in your trading account.
For example, let's make a version for closing positions with a specific commentary, sorted from the biggest profit to the biggest loss with 1 retry maximum, and a delay of 0.1 second between each closing attempt.
First, you need to open the CloseAllPositions.mq5 file and locate the respective input parameters:
Now, you need to set the new default values:
This way, the script will only close positions with "SuperEA" as a commentary. This can be especially useful when you run different expert advisors on your account and would like to be able to close their positions separately.
As with the MT4 version, it now makes sense to remove the script_show_inputs
property from this pre-configured version:
You can either delete the line or comment it out (by putting two slashes in front of it):
You can now save the copy of the file with a different name. For example, this one can be named CloseAllPositions_Comment.mq5:
You now need to compile the new MQL5 script:
The new script is ready for use — you can either launch it by double-clicking it in your MetaTrader 5 or you can right-click on it and set a hotkey:
The script can now be run quickly whenever you need to close positions filtered and sorted based on your requirements.
You can repeat the process outlined above to create other close-all script versions. For example, one that works only with positions that have a specific magic number (if you need to control the trades of a specific EA).
MT5 Bulk Operations vs. Close All Positions script
Even though MetaTrader 5 offers a bulk position closing facility, it isn't as powerful as a dedicated Close All Positions script. The latter has the following advantages compared to the MT5 Bulk Operations:
- Filter by position commentary.
- Filter by position magic number.
- Sorting before closing.
- Slippage control.
- Retries on failed close operations.
- An option for a delay between closes.
- Speed of access — the script can be run with a keyboard shortcut or a simple double-click.
- Further customization, including detailed logging, for example.
Conclusion
The code provided above explains how an order/position closing script works using a basic example. Our free Close All Orders script for MT4 and Close All Positions script for MT5 provide a ready-made tool for filtered termination of trades as well as more advanced examples of MQL4/MQL5 source code for studying, modification, upgrade, and use in other programs. With it, you can easily create your own script to close orders and positions in MetaTrader using custom conditions and filters.
If you are looking for a broker to use the Close All Orders script on, you can check out our list of MT4 Forex brokers. If you want to use an MT5 version of the script — Close All Positions — feel free to look for a broker that offers MetaTrader 5.
Discussion
Do you have any suggestions or questions regarding this script? You can always discuss Close All Orders and Close All Positions with the other FX traders and MQL4/MQL5 coders on our forum.
Changelog
1.01 — 2023-12-26
- Added the MT5 version of the script — Close All Positions.
- Added the number of retries parameter for the script to continuously attempt closing trades.
- Added sorting options to close trades in a specific order.
- Changed the script's behavior so that pending orders are no longer even processed.