CloseAll-PL

Download script
CloseAll-PL

This script is designed to serve as an automated profit-taking and management tool for your trading account. Its primary purpose is to monitor your open positions in real-time and automatically execute a "bulk close" of all active trades once a specific financial milestone is reached.

How the Logic Works

1. Profit Goal Setting At the core of the script is a user-defined profit target. You can specify a numerical value (for example, 30 units of currency). The script constantly calculates your current floating profit or loss across all open trades to see how close you are to this goal.

2. Real-Time Monitoring The script works in a continuous loop, performing three main actions:

  • Calculation: It identifies the total profit/loss currently being generated by your account's active positions.
  • Display: It provides a visual update on your trading screen, showing you the specific profit goal set and your current running profit or loss so you can track progress at a glance.
  • Evaluation: It compares your live profit against your target. If your current profit meets or exceeds the positive target (or falls below a negative target), it triggers the "Close" command.

3. Automated Execution Once the target is hit, the script takes over the manual work of closing positions:

  • Active Trades: It scans all currently open buy and sell positions and closes them immediately at the current market price.
  • Pending Orders: In addition to active trades, the script identifies "pending" orders (orders waiting for the price to hit a certain level) and removes them from the system to ensure no new positions are opened once your goal is reached.

4. Safety and Reset The script includes logic to ensure it doesn't keep trying to execute once the work is done. After it successfully closes all positions, it recognizes that the account is "clear" and resets its internal status. This allows the script to remain active and ready for your next trading session without needing to be restarted manually.

Summary for the User

Think of this tool as an automated "safety net." Instead of having to watch the screen constantly to click "close" the moment you hit your desired profit, this script does the watching for you. It monitors your progress and, the moment your account hits the designated profit level, it instantly flattens all positions and clears out pending orders to lock in your gains.

Orders Execution
Checks for the total of open ordersIt Closes Orders by itself
10 Views
0 Downloads
0 Favorites
CloseAll-PL
//+------------------------------------------------------------------+
//|                                                  CloseAll-PL.mq4 |
//|                                                                  |
//+------------------------------------------------------------------+


extern int	Profit=30;

double myProfit=0;
int EnableClose=0;
//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
  {
//----
  
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
  {
//----
   
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
  {
//----

myProfit=CalcProfit();

ShowInit();


if (EnableClose==1 && CntOrdAll(OP_BUY)==0 && CntOrdAll(OP_SELL)==0 && CntOrdAll(OP_BUYSTOP)==0 
   && CntOrdAll(OP_BUYLIMIT)==0 && CntOrdAll(OP_SELLSTOP)==0 && CntOrdAll(OP_SELLLIMIT)==0) {
   EnableClose=0; // Before Debug: EnableClose=1 
}

if ( (Profit>0 && myProfit>=Profit) || (Profit<0 && myProfit<=Profit)) {
	EnableClose=1;
}    



CloseAll();

   
//----
   return(0);
  }
//+------------------------------------------------------------------+



void CloseAll () {   // #function of CloseAll
if (EnableClose==1) {  // #if Close is yes
int _total=OrdersTotal(); // number of lots or trades  ????
int _ordertype;// order type   
if (_total==0) {return;}  // if total==0
int _ticket; // ticket number
double _priceClose;// price to close orders;
for(int _i=_total-1;_i>=0;_i--)
      {  //# for loop
      if (OrderSelect(_i,SELECT_BY_POS))
         { //# if 
         _ordertype=OrderType();
         _ticket=OrderTicket();
         switch(_ordertype)
            {  //# switch
	    case OP_BUYLIMIT:
	                    OrderDelete(OrderTicket());
	    case OP_BUYSTOP:
                        OrderDelete(OrderTicket());
       case OP_BUY:
               // close buy                
               _priceClose=MarketInfo(OrderSymbol(),MODE_BID);
               Print("Close on ",_i," position order with ticket ¹",_ticket);
               OrderClose(_ticket,OrderLots(),_priceClose,3,Red);
               break;
	    case OP_SELLLIMIT:
	                    OrderDelete(OrderTicket());
	    case OP_SELLSTOP:
                       OrderDelete(OrderTicket());
       case OP_SELL:
               // close sell
               _priceClose=MarketInfo(OrderSymbol(),MODE_ASK);
               Print("Close on ",_i," position order with ticket ¹",_ticket);
               OrderClose(_ticket,OrderLots(),_priceClose,3,Red);
               break;
            default:
               // values from  1 to 5, deleting pending orders
//               Print("Delete on ",_i," position order with ticket ¹",_ticket);
//               OrderDelete(_ticket);  
               break;
            }    //# switch
         }  // # if 
}  // # for loop

} // #if Close yes

return;
} // #function of CloseAll


void ShowInit() {

   string sComment   = "";
   string sp         = "-----------------------------------------------------\n";
   string NL         = "\n";
   sComment = sp;
   sComment = sComment + "CloseByPL will close all trades at: " + Profit + NL;
   sComment = sComment + sp;
   sComment = sComment + "Current P/L="+DoubleToStr(myProfit,0)+ NL;
   Comment(sComment);

return;
}

double CalcProfit() {
double _sum=0;
int _total=OrdersTotal(); // number of lots  
  
if (_total==0) {return (0);}

_sum=AccountProfit();

return(_sum);

}


int CntOrdAll(int Type) {
//return number of orders with specific parameters
int _CntOrd;
_CntOrd=0;
for(int i=0;i<OrdersTotal();i++)
{
   OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
   if (OrderType()==Type) _CntOrd++;
}
return(_CntOrd);
}

Comments