Expert Adviser to close all positions when equity reach to defined value

Hello all,

I want to build an EA for this purpose, “when account equity reach to defined value by user, close all positions of all symbols”,

I write below code, but it doesn’t work.

Please help me for modify it.

Thanks.

#property strict

#include <stdlib.mqh>

extern int TargetEquity=5000;

void OnTick()
{
   
   if(AccountEquity()>=TargetEquity)
   {
   int ticket=0;   
   int total=OrdersTotal();
      int i = 0;
      for(i = total; i >=0; i--)
        {
         if(OrderSelect(i,SELECT_BY_POS) &&  OrderSymbol()==Symbol())
           {
            if(OrderType()==OP_BUY || OrderType()==OP_SELL)
              {
               ticket = OrderClose(OrderTicket(),OrderLots(),MarketInfo(Symbol(),MODE_ASK),5);
               ticket = OrderClose(OrderTicket(),OrderLots(),MarketInfo(Symbol(),MODE_BID),5);
              }
           }
        }
   
   }
}

Try this:


#property strict
#include <stdlib.mqh>

input double TargetEquity = 5000.00;
input int Attempts = 10;

void OnTick()
{
   if(AccountEquity() >= TargetEquity)
      for(int i=0; i<Attempts; i++)
         if(close_all())
            goal_achieved();
}

bool close_all()
{
   for(int i=OrdersTotal()-1; i>=0; i--) {
      if(OrderSelect(i,SELECT_BY_POS) 
         && OrderSymbol() == Symbol()
         && OrderType() < 2 //is a live trade, i.e. Buy or Sell
      ){
         RefreshRates();
         int ticket = OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(), 5);
         if(ticket < 0) {
            Print("OrderCloseError: ", ErrorDescription(GetLastError()));
            return false;
         }
      }
   }
   return true;
}

void goal_achieved()
{
   Alert("Equity reached and all positions closed.");
   ExpertRemove();
}

Thanks for your reply, But in my MT4 terminal this code doesn’t work.

Did you test it?

maybe my mt4 has problem.

What that means “doesn’t work” ?

I compile it but in live chart can’t close “open positions”.

You repeat exactly the same with other words.

Give more information ! Not words.

For example the logs (Experts tab) or eventually screenshots.