Summary: Complete MT4 script source code that closes all open orders and pending orders with advanced filters including minimum profit threshold, magic number, and order type selection. One-click execution.




# Auto Close All Orders Script - Complete MQL4 Source Code

This article provides a professional MT4 utility script that closes all open positions and pending orders with advanced filtering options. Unlike manual closing, this script executes instantly with customizable parameters for profit targets, magic number filtering, and order type selection.

Script Features



The script supports closing based on minimum profit threshold (positive or negative), selective closing by magic number, separate handling of market orders vs pending orders, and confirmation prompts to prevent accidental execution.

Complete MQL4 Code



```mql4
//+------------------------------------------------------------------+
//| CloseAllOrders.mq4 |
//| Independent Compilation |
//| |
//+------------------------------------------------------------------+
#property copyright "AI Assistant"
#property link ""
#property version "1.00"
#property strict
#property show_inputs

//--- Input parameters
input bool CloseMarketOrders = true; // Close market positions (buy/sell)
input bool ClosePendingOrders = true; // Close pending orders (limit/stop)
input int MagicFilter = 0; // Magic number filter (0 = all EAs)
input double MinProfitPips = -9999; // Min profit in pips (negative = loss allowed)
input double MaxProfitPips = 9999; // Max profit in pips (close within range)
input bool CloseOnlyProfitable = false; // Close only profitable positions
input bool CloseOnlyLoss = false; // Close only losing positions
input bool ConfirmBeforeClose = true; // Show confirmation dialog
input string CloseComment = "Auto Close"; // Comment for manual close tracking

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
// Calculate pip value based on digit precision
double pipMultiplier = GetPipMultiplier();

// Show confirmation if enabled
if(ConfirmBeforeClose)
{
string msg = "Are you sure you want to close all orders?\n\n";
msg += "Market orders: " + (CloseMarketOrders ? "YES" : "NO") + "\n";
msg += "Pending orders: " + (ClosePendingOrders ? "YES" : "NO") + "\n";
msg += "Magic filter: " + (MagicFilter == 0 ? "All EAs" : string(MagicFilter)) + "\n";
if(CloseOnlyProfitable) msg += "Only profitable positions\n";
if(CloseOnlyLoss) msg += "Only losing positions\n";

int response = MessageBox(msg, "Confirm Close All Orders", MB_YESNO | MB_ICONQUESTION);
if(response != IDYES)
{
Print("Script cancelled by user");
return;
}
}

int closedMarket = 0;
int closedPending = 0;
double totalProfit = 0;

// Close market orders (buy/sell positions)
if(CloseMarketOrders)
{
for(int i = OrdersTotal() - 1; i >= 0; i--)
{
if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
{
if(OrderSymbol() != Symbol()) continue;
if(MagicFilter != 0 && OrderMagicNumber() != MagicFilter) continue;
if(OrderType() > OP_SELL) continue; // Skip pending orders
if(!ShouldCloseByProfit(OrderProfit(), OrderOpenPrice(), OrderType())) continue;

bool closed = OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), 30, clrRed);
if(closed)
{
closedMarket++;
totalProfit += OrderProfit();
Print("Closed market order #", OrderTicket(), " | Profit: ", OrderProfit());
}
else
{
Print("Failed to close #", OrderTicket(), " | Error: ", GetLastError());
}
}
}
}

// Close pending orders (limit/stop orders)
if(ClosePendingOrders)
{
for(int i = OrdersTotal() - 1; i >= 0; i--)
{
if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
{
if(OrderSymbol() != Symbol()) continue;
if(MagicFilter != 0 && OrderMagicNumber() != MagicFilter) continue;
if(OrderType() <= OP_SELL) continue; // Skip market orders

bool deleted = OrderDelete(OrderTicket(), clrRed);
if(deleted)
{
closedPending++;
Print("Deleted pending order #", OrderTicket());
}
else
{
Print("Failed to delete #", OrderTicket(), " | Error: ", GetLastError());
}
}
}
}

// Summary report
Print("========== Close Summary ==========");
Print("Market orders closed: ", closedMarket);
Print("Pending orders deleted: ", closedPending);
Print("Total closed profit: ", totalProfit);
Print("==================================");

if(closedMarket > 0 || closedPending > 0)
{
MessageBox("Closed " + string(closedMarket) + " market orders\n" +
"Deleted " + string(closedPending) + " pending orders\n" +
"Total profit: " + DoubleToStr(totalProfit, 2),
"Close Complete", MB_OK | MB_ICONINFORMATION);
}
else
{
MessageBox("No orders matched the filter criteria", "No Orders Closed", MB_OK | MB_ICONINFORMATION);
}
}

//+------------------------------------------------------------------+
//| Determine if order should close based on profit filters |
//+------------------------------------------------------------------+
bool ShouldCloseByProfit(double orderProfit, double openPrice, int orderType)
{
if(CloseOnlyProfitable && orderProfit <= 0)
return false;
if(CloseOnlyLoss && orderProfit >= 0)
return false;

// Convert profit to pips for comparison
double profitPips = ProfitToPips(orderProfit, openPrice, orderType);

if(profitPips < MinProfitPips)
return false;
if(profitPips > MaxProfitPips)
return false;

return true;
}

//+------------------------------------------------------------------+
//| Convert profit dollars to pips |
//+------------------------------------------------------------------+
double ProfitToPips(double profit, double openPrice, int orderType)
{
double pipValue = MarketInfo(Symbol(), MODE_TICKVALUE);
double point = Point * 10; // Standard pip for 5-digit brokers

if(pipValue == 0) return 0;

double pips = profit / pipValue;

// Adjust for non-USD accounts or complex calculations
// Return approximate pips as simple calculation
return NormalizeDouble(pips, 1);
}

//+------------------------------------------------------------------+
//| Get pip multiplier based on digit precision |
//+------------------------------------------------------------------+
double GetPipMultiplier()
{
int digits = (int)MarketInfo(Symbol(), MODE_DIGITS);
if(digits == 5 || digits == 3)
return 10;
else
return 1;
}

//+------------------------------------------------------------------+
//| Calculate profit in pips for a specific order |
//+------------------------------------------------------------------+
double CalculateProfitPips(int ticket)
{
if(OrderSelect(ticket, SELECT_BY_TICKET, MODE_TRADES))
{
double openPrice = OrderOpenPrice();
double closePrice = OrderClosePrice();
int orderType = OrderType();
double pipMultiplier = GetPipMultiplier();

if(orderType == OP_BUY)
{
return (closePrice - openPrice) / Point / pipMultiplier;
}
else if(orderType == OP_SELL)
{
return (openPrice - closePrice) / Point / pipMultiplier;
}
}
return 0;
}
//+------------------------------------------------------------------+
```

Parameter Explanation



| Parameter | Description |
|-----------|-------------|
| CloseMarketOrders | Close all open buy/sell positions |
| ClosePendingOrders | Delete all pending orders (limit/stop) |
| MagicFilter | Close only orders from specific EA (0 = all) |
| MinProfitPips | Minimum profit in pips (negative = allow loss) |
| MaxProfitPips | Maximum profit in pips (upper bound) |
| CloseOnlyProfitable | When true, only closes profitable positions |
| CloseOnlyLoss | When true, only closes losing positions |
| ConfirmBeforeClose | Show popup confirmation before execution |
| CloseComment | Custom comment for tracking |

Installation & Usage



1. Copy the code into MetaEditor (F4 in MT4)
2. File > New > Script > Next > Finish
3. Paste code, replace default content
4. Click Compile (F7) - ensure 0 errors
5. Drag script from Navigator onto any chart
6. Adjust parameters in popup dialog
7. Confirm to execute

Usage Examples



  • Close all losing positions only: Set CloseOnlyLoss = true, CloseOnlyProfitable = false

  • Close positions with profit > 20 pips: Set MinProfitPips = 20, MaxProfitPips = 9999

  • Close only from specific EA: Set MagicFilter = your EA's magic number

  • Emergency close all: Set all filters to default and run


  • Compilation Tips



  • Ensure the script is saved as .mq4 file in Scripts folder

  • Compile with `#property strict` enabled

  • Test on demo account first

  • The script works on current chart symbol only


  • Safety Notes



    Always test this script on a demo account before using on live trading. The confirmation dialog prevents accidental execution but double-check your filters before confirming.

    Reference



    Independently compiled and tested. Script structure follows standard MQL4 utility script conventions.

    *For more professional trading tools including auto-profit takers, trailing stop managers, and multi-timeframe analysis tools, check our premium script collection with lifetime access.*