_CloseOrders

Download script
Author: Copyright � 2007, sx ted
_CloseOrders

This script is designed for MetaTrader 4 to provide users with a variety of automated ways to manage active trades and pending orders. Rather than performing one single action, it offers several specific "modes" of operation that allow you to clean up your trading account based on different criteria.

Core Functionality

The tool scans all currently open positions and pending orders in your account. Depending on which setting you choose, the script will filter these trades and perform an action—either closing a live trade (finishing the position) or deleting a pending order (removing the request to enter a trade).

Available Operation Modes

You can choose from the following logic sets:

  • Complete Cleanup: Closes all currently active trades and deletes all pending orders simultaneously.
  • Close Only: Closes all currently active trades but leaves pending orders untouched.
  • Delete Pending Only: Removes all pending orders from the market without affecting any trades that are already open.
  • Targeted Removal (Magic Number): Only affects trades or pending orders assigned to a specific "Magic Number" (a unique ID used by automated trading systems).
  • Targeted Removal (Comment): Only affects trades or pending orders that contain a specific text comment.
  • Profit-Based Closing:
    • Can be set to close only trades currently in a profit.
    • Can be set to close only trades currently in a loss.
  • Time-Based Cleanup: Closes all active trades and deletes pending orders that were opened before the start of the current day, effectively "resetting" your account for the new day.

Technical Safeguards

To ensure the script works reliably, it includes several background checks:

  • Price Refreshing: It automatically updates the current market price before attempting to close a trade to ensure the execution happens at the correct rate.
  • Slippage Calculation: It calculates the "slippage" (the difference between expected and actual price) to help minimize errors during high-volatility moments.
  • Error Reporting: If a trade fails to close or an order fails to delete, the script is programmed to print a specific error message to the log so you can see exactly what went wrong.
  • Text Normalization: When searching for comments, the script automatically converts your input to uppercase, meaning it won't matter if you type in lowercase or mixed cases.
Orders Execution
Checks for the total of open ordersIt Closes Orders by itself
15 Views
0 Downloads
0 Favorites
_CloseOrders
//+------------------------------------------------------------------+
//|                                                 _CloseOrders.mq4 |
//|                                         Copyright © 2007, sx ted |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2007, sx ted"
#property show_inputs

//+------------------------------------------------------------------+
//| EX4 imports                                                      |
//+------------------------------------------------------------------+
#include <stdlib.mqh>

//+------------------------------------------------------------------+
//| input parameters:                                                |
//+-----------0---+----1----+----2----+----3]------------------------+
extern string _ = "Select one of the following:";
extern bool   CloseOpenOrdersAndCancelPending = false;
extern bool   CloseOpenOrders = false;
extern bool   DeleteAllPendingOrders = false;
extern int    DeletePendingWithMagicNumber = 0;
extern string DeletePendingMatchingComment = "";
extern int    CloseOrdersMatchingMagicNumber = 0;
extern string CloseOrdersMatchingComment = "";
extern bool   CloseOrdersWithPlusProfit = false;
extern bool   CloseOrdersWithMinusProfit = false;
extern bool   CloseOrdersOpenedBeforeToday = false;

//+------------------------------------------------------------------+
//| global variables to program:                                     |
//+------------------------------------------------------------------+
double Price[2];
int    giSlippage;

//+------------------------------------------------------------------+
//| script program start function                                    |
//+------------------------------------------------------------------+
void start() {
  int iOrders=OrdersTotal()-1, i;
  
  if(CloseOpenOrdersAndCancelPending) {
    for(i=iOrders; i>=0; i--) {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) {
        if((OrderType()<=OP_SELL) && GetMarketInfo()) {
          if(!OrderClose(OrderTicket(),OrderLots(),Price[1-OrderType()],giSlippage)) Print(OrderError());
        }
        else if(OrderType()>OP_SELL) {
          if(!OrderDelete(OrderTicket())) Print(OrderError());
        }
      }
    }
  }
  else if(CloseOpenOrders) {
    for(i=iOrders; i>=0; i--) {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES) && (OrderType()<=OP_SELL) && GetMarketInfo() && !OrderClose(OrderTicket(),OrderLots(),Price[1-OrderType()],giSlippage)) Print(OrderError());
    }
  }
  if(DeleteAllPendingOrders) {
    for(i=iOrders; i>=0; i--) {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES) && (OrderType()>OP_SELL) && !OrderDelete(OrderTicket())) Print(OrderError());
    }
  }
  else if(DeletePendingWithMagicNumber > 0) {
    for(i=iOrders; i>=0; i--) {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES) && (OrderMagicNumber() == DeletePendingWithMagicNumber)) {
        if(OrderType()>OP_SELL) {
          if(!OrderDelete(OrderTicket())) Print(OrderError());
        }
      }
    }
  }
  else if(DeletePendingMatchingComment != "") {
    DeletePendingMatchingComment=StringChangeToUpperCase(DeletePendingMatchingComment);
    for(i=iOrders; i>=0; i--) {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES) && (StringChangeToUpperCase(OrderComment()) == DeletePendingMatchingComment)) {
        if(OrderType()>OP_SELL) {
          if(!OrderDelete(OrderTicket())) Print(OrderError());
        }
      }
    }
  }
  else if(CloseOrdersMatchingMagicNumber > 0) {
    for(i=iOrders; i>=0; i--) {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES) && (OrderMagicNumber() == CloseOrdersMatchingMagicNumber)) {
        if((OrderType()<=OP_SELL) && GetMarketInfo()) {
          if(!OrderClose(OrderTicket(),OrderLots(),Price[1-OrderType()],giSlippage)) Print(OrderError());
        }
      }
    }
  }
  else if(CloseOrdersMatchingComment != "") {
    CloseOrdersMatchingComment=StringChangeToUpperCase(CloseOrdersMatchingComment);
    for(i=iOrders; i>=0; i--) {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES) && (StringChangeToUpperCase(OrderComment()) == CloseOrdersMatchingComment)) {
        if((OrderType()<=OP_SELL) && GetMarketInfo()) {
          if(!OrderClose(OrderTicket(),OrderLots(),Price[1-OrderType()],giSlippage)) Print(OrderError());
        }
      }
    }
  }
  else if(CloseOrdersWithPlusProfit) {
    for(i=iOrders; i>=0; i--) {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES) && (OrderProfit() >= 0)) {
        if((OrderType()<=OP_SELL) && GetMarketInfo()) {
          if(!OrderClose(OrderTicket(),OrderLots(),Price[1-OrderType()],giSlippage)) Print(OrderError());
        }
      }
    }
  }
  else if(CloseOrdersWithMinusProfit) {
    for(i=iOrders; i>=0; i--) {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES) && (OrderProfit() <= 0)) {
        if((OrderType()<=OP_SELL) && GetMarketInfo()) {
          if(!OrderClose(OrderTicket(),OrderLots(),Price[1-OrderType()],giSlippage)) Print(OrderError());
        }
      }
    }
  }
  else if(CloseOrdersOpenedBeforeToday) {
    datetime tTodayStart=TimeCurrent()-TimeHour(TimeCurrent())*60*60-TimeMinute(TimeCurrent())*60;
    for(i=iOrders; i>=0; i--) {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES) && (OrderOpenTime() < tTodayStart)) {
        if((OrderType()<=OP_SELL) && GetMarketInfo()) {
          if(!OrderClose(OrderTicket(),OrderLots(),Price[1-OrderType()],giSlippage)) Print(OrderError());
        }
        else if(OrderType()>OP_SELL) {
          if(!OrderDelete(OrderTicket())) Print(OrderError());
        }
      }
    }
  }
}

//+------------------------------------------------------------------+
//| Function..: OrderError                                           |
//+------------------------------------------------------------------+
string OrderError() {
  int iError=GetLastError();
  return(StringConcatenate("Order:",OrderTicket()," GetLastError()=",iError," ",ErrorDescription(iError)));
}

//+------------------------------------------------------------------+
//| Function..: GetMarketInfo                                        |
//| Returns...: bool Success.                                        |
//+------------------------------------------------------------------+
bool GetMarketInfo() {
  RefreshRates();
  Price[0]=MarketInfo(OrderSymbol(),MODE_ASK);
  Price[1]=MarketInfo(OrderSymbol(),MODE_BID);
  double dPoint=MarketInfo(OrderSymbol(),MODE_POINT);
  if(dPoint==0) return(false);
  giSlippage=(Price[0]-Price[1])/dPoint;
  return(Price[0]>0.0 && Price[1]>0.0);
}

//+------------------------------------------------------------------+
//| Function..: StringChangeToUpperCase                              |
//| Example...: StringChangeToUpperCase("oNe mAn"); // ONE MAN       |
//+------------------------------------------------------------------+
string StringChangeToUpperCase(string sText) {
  int iLen=StringLen(sText), i, iChar;

  for(i=0; i < iLen; i++) {
    iChar=StringGetChar(sText, i);
    if(iChar >= 97 && iChar <= 122) sText=StringSetChar(sText, i, iChar-32);
  }
  return(sText);
}
//+------------------------------------------------------------------+

Comments