CloseOrders_v1-0
Download scriptThis script is a specialized tool designed for MetaTrader 4 users to manage and exit trading positions quickly. Its primary purpose is to provide an automated way to close one or multiple open trades based on specific rules that you define before running the script.
Instead of manually closing every trade one by one, this tool scans your active portfolio and executes closures based on the following logic:
Customizable Filtering Options
The script allows you to set "filters" so it only acts on specific types of trades. You can choose to limit its actions using any of these criteria:
- Specific Instrument: You can tell the script to only close trades for the specific currency pair or asset currently shown on your chart.
- Profitability Status: You have the option to target only your winning trades (in profit) or only your losing trades.
- Magic Number Tracking: If you use Expert Advisors (EAs) that assign unique identification numbers to their trades, you can tell the script to only close orders belonging to a specific ID.
- Specific Comments: If you manually label your trades with specific notes, the script can be instructed to only close those that match your exact text description.
Operational Mechanics
When you run the script, it performs the following automated steps:
- Portfolio Scan: It starts at the end of your open trade list and works backward. This is a standard safety practice in trading software to ensure no orders are skipped during the deletion process.
- Criteria Verification: For every open trade found, the script checks it against your chosen filters (e.g., "Is this in profit?" or "Does it have the right magic number?"). If a trade doesn't meet your requirements, the script simply moves to the next one.
- Smart Execution: Once a matching trade is identified, the script automatically determines the correct current market price (the Bid for sells or the Ask for buys) and attempts to close the position immediately.
- Speed & Stability Controls:
- Slippage Protection: It includes a setting to manage "slippage," ensuring the trades are closed at acceptable prices even during fast-moving markets.
- Execution Delay: You can set a millisecond delay between each closing action. This is useful for preventing your account from being flagged for over-activity by a broker during high-volume periods.
- Reporting: After the process is complete, the script provides a summary in the terminal window, telling you exactly how many trades were successfully closed and flagging any specific errors that occurred during the process.
//+------------------------------------------------------------------+
//| CloseOrders_v1-0.mq4 |
//| Luca Spinello |
//| https://mql4tradingautomation.com |
//+------------------------------------------------------------------+
#property copyright "Luca Spinello - mql4tradingautomation.com"
#property link "https://mql4tradingautomation.com"
#property version "1.00"
#property strict
#property description "This script allows you to close all or only the selected positions"
#property description ""
#property description ""
#property description "DISCLAIMER: This script comes with no guarantee at all, you can use it at your own risk"
#property description "We recommend to test it first on a Demo Account"
#property show_inputs
//Configure the external variables
extern bool OnlyCurrentSymbol=false; //Close only instrument in the chart
extern bool OnlyInProfit=false; //Close only orders in profit
extern bool OnlyInLoss=false; //Close only orders in loss
extern bool OnlyMagicNumber=false; //Close only orders matching the magic number
extern int MagicNumber=0; //Matching magic number
extern bool OnlyWithComment=false; //Close only orders with the following comment
extern string MatchingComment=""; //Matching comment
extern double Slippage=2; //Slippage
extern int Delay=0; //Delay to wait between closing orders (in milliseconds)
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//---
//Counter for orders closed
int TotalClosed=0;
//Normalization of the digits
if(Digits==3 || Digits==5){
Slippage=Slippage*10;
}
//Scan the open orders backwards
for(int i=OrdersTotal()-1; i>=0; i--){
//Select the order, if not selected print the error and continue with the next index
if( OrderSelect( i, SELECT_BY_POS, MODE_TRADES ) == false ) {
Print("ERROR - Unable to select the order - ",GetLastError());
continue;
}
//Check if the order can be closed matching the criteria, if criteria not matched skip to the next
if(OnlyCurrentSymbol && OrderSymbol()!=Symbol()) continue;
if(OnlyInProfit && OrderProfit()<=0) continue;
if(OnlyInLoss && OrderProfit()>=0) continue;
if(OnlyMagicNumber && OrderMagicNumber()!=MagicNumber) continue;
if(OnlyWithComment && StringCompare(OrderComment(),MatchingComment)!=0) continue;
//Prepare the close price
double ClosePrice=0;
RefreshRates();
if(OrderType()==OP_BUY) ClosePrice=NormalizeDouble(MarketInfo(OrderSymbol(),MODE_BID),Digits);
if(OrderType()==OP_SELL) ClosePrice=NormalizeDouble(MarketInfo(OrderSymbol(),MODE_ASK),Digits);
//Try to close the order
if(OrderClose(OrderTicket(),OrderLots(),ClosePrice,Slippage,CLR_NONE)){
TotalClosed++;
}
else{
Print("Order failed to close with error - ",GetLastError());
}
//Wait a delay
Sleep(Delay);
}
//Print the total of orders closed
Print("Total orders closed = ",TotalClosed);
}
//+------------------------------------------------------------------+
Comments