Problem with TP and SL Management in EA MQL4 code

 

Hi guys,

I've been working on an EA that is supposed to move all positions stop losses to entry, if the last order hit take profit. The EA is restricted to 3 positions. The code below that I've written moves the first position stop loss to entry, but doesn't affect any of the other positions, and I wanted to know why is this the case during my backtest analyses.

For reference I also get Error 130, 1, and 4180 randomly in my error log. Just wondering if I could get a little guidance as to how to correct my code so that all positions have their stop loss moved to entry/order open price.

Thanks!

if(OrdersTotal() >= 0) {
   if(OrderSelect(OrdersHistoryTotal()-1,SELECT_BY_POS,MODE_HISTORY)==true && 
      OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber && OrderType()<=1) {
         if (OrderProfit() > 0 && OrdersTotal() < 3) {
            for(int PositionIndex = (OrdersTotal()-1); PositionIndex >= 0; PositionIndex--) 
               if(OrderSelect(PositionIndex, SELECT_BY_POS, MODE_TRADES) == true) continue;{
                 if (OrderModify( OrderTicket(), OrderOpenPrice(), (OrderOpenPrice()), OrderTakeProfit(),OrderExpiration(),clrNONE) == false)               // <-- try to close the order
         Print("Order Modify failed, order number: ", OrderTicket(), " Error: ", GetLastError() ); else Print("Order modified successfully.");
                
         } 
      }
    }
   }
Basic Principles - Trading Operations - MetaTrader 5 Help
Basic Principles - Trading Operations - MetaTrader 5 Help
  • www.metatrader5.com
is an instruction given to a broker to buy or sell a financial instrument. There are two main types of orders: Market and Pending. In addition, there are special Take Profit and Stop Loss levels. is the commercial exchange (buying or selling) of a financial security. Buying is executed at the demand price (Ask), and Sell is performed at the...