# One-Click Close All Orders Script - Complete MQL4 Source Code
This article provides a practical utility script for MT4 that closes all open orders instantly. Unlike basic close scripts, this tool displays total profit/loss before execution and offers filtering options by magic number or currency pair.
Script Features
Complete MQL4 Code
```mql4
//+------------------------------------------------------------------+
//| CloseAllOrders.mq4 |
//| Generated by AI Assistant |
//| |
//+------------------------------------------------------------------+
#property copyright "AI Assistant"
#property link ""
#property version "1.00"
#property strict
#property show_inputs
//+------------------------------------------------------------------+
//| Input parameters |
//+------------------------------------------------------------------+
input bool CloseAll = true; // Close all orders (ignores filters below)
input int FilterMagic = 0; // Filter by magic number (0=all)
input string FilterSymbol = ""; // Filter by symbol (empty=current chart)
input bool ShowConfirmation = true; // Show confirmation dialog
//+------------------------------------------------------------------+
//| Script start function |
//+------------------------------------------------------------------+
void OnStart()
{
string targetSymbol = (FilterSymbol == "") ? Symbol() : FilterSymbol;
int totalOrders = OrdersTotal();
if(totalOrders == 0)
{
Alert("No orders found to close.");
return;
}
// Calculate total profit/loss first
double totalProfit = 0;
int orderCount = 0;
for(int i = 0; i < totalOrders; i++)
{
if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
{
bool matchSymbol = (CloseAll || OrderSymbol() == targetSymbol);
bool matchMagic = (CloseAll || FilterMagic == 0 || OrderMagicNumber() == FilterMagic);
if(matchSymbol && matchMagic)
{
totalProfit += OrderProfit() + OrderSwap() + OrderCommission();
orderCount++;
}
}
}
if(orderCount == 0)
{
Alert("No orders match the filter criteria.");
return;
}
// Build confirmation message
string msg = "Found " + string(orderCount) + " order(s) to close.\n";
msg += "Total P/L: " + DoubleToStr(totalProfit, 2) + " " + AccountCurrency() + "\n";
msg += "Symbol: " + targetSymbol + "\n";
if(FilterMagic != 0 && !CloseAll)
msg += "Magic: " + string(FilterMagic) + "\n";
msg += "\nDo you want to close them?";
if(ShowConfirmation && MessageBox(msg, "Close Orders", MB_YESNO | MB_ICONQUESTION) != IDYES)
{
Print("Order closing cancelled by user.");
return;
}
// Close orders
int closed = 0;
int errors = 0;
for(int i = OrdersTotal() - 1; i >= 0; i--)
{
if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
{
bool matchSymbol = (CloseAll || OrderSymbol() == targetSymbol);
bool matchMagic = (CloseAll || FilterMagic == 0 || OrderMagicNumber() == FilterMagic);
if(matchSymbol && matchMagic)
{
bool result = OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), 3, clrRed);
if(result)
{
closed++;
Print("Closed order #", OrderTicket(), " | Profit: ", OrderProfit() + OrderSwap() + OrderCommission());
}
else
{
errors++;
Print("Failed to close order #", OrderTicket(), " | Error: ", GetLastError());
}
}
}
}
// Final report
Print("===== Close Summary =====");
Print("Closed: ", closed, " | Errors: ", errors);
Print("Total P/L: ", DoubleToStr(totalProfit, 2), " ", AccountCurrency());
if(closed > 0)
Alert("Successfully closed ", closed, " order(s). Total P/L: ", DoubleToStr(totalProfit, 2), " ", AccountCurrency());
else if(errors > 0)
Alert("Failed to close orders. Check experts log for details.");
}
//+------------------------------------------------------------------+
//| Helper: Get order close price |
//+------------------------------------------------------------------+
double OrderClosePrice()
{
if(OrderType() == OP_BUY)
return Bid;
else if(OrderType() == OP_SELL)
return Ask;
else
return 0;
}
//+------------------------------------------------------------------+
```
Parameter Explanation
| Parameter | Description |
|-----------|-------------|
| CloseAll | True = close all orders regardless of symbol/magic |
| FilterMagic | Specific EA magic number to close (0 = all) |
| FilterSymbol | Currency pair to filter (empty = current chart symbol) |
| ShowConfirmation | Show confirmation dialog before execution |
Installation & Usage
1. Copy code to MetaEditor (F4 in MT4)
2. Click Compile (F7) - ensure no errors
3. Drag script from Navigator to any chart
4. Adjust parameters in popup window
5. Confirm dialog to execute
Practical Use Cases
Scenario 1 - Emergency Close: Market moves against you - drag script to chart, click Yes - all positions closed instantly.
Scenario 2 - Close Specific EA: Set FilterMagic to your EA's magic number, close only that EA's trades while leaving manual trades open.
Scenario 3 - Close One Pair: Set FilterSymbol to "EURUSD" to close only EURUSD positions.
Compilation Notes
Important Tips
Test on demo account first. This script closes market orders only (pending orders not included). For pending orders, use `OrderDelete()` function. The script calculates profit including swap and commission.
Reference
Independent compilation. Standard order closing logic based on MQL4 OrderSend and OrderClose functions.
*For advanced trading tools including automated risk management, trailing stop EAs, and portfolio closers, explore our premium script collection with lifetime updates.*