Move to Break Even only selecting modifying 1 order

 

I have this Move to BreakEven function, it work if I only have 1 order open, but when the EA scales in to 3 orders, the other 2 order don't get modified.  I also keep getting modify error 1, I know this means its keeps passing the same value but how do I Stop this. 


void checkforMovetoBe ()
{
      double tp = 0,sl = 0;
        
        
         for (int i = 0; i < OrdersTotal(); i++)
                    {
                       if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
                          if (OrderSymbol()== Symbol() && (OrderMagicNumber()==magic))
                       //   if ((OrderProfit()/pips)>TrailDistance)
                         {
                          {
                           tp=OrigTpbuy;
                           sl=NormalizeDouble(BreakevenOfBuys(),5);
                                               
                          if (OrderType()==0) 
                          if ((OrderProfit()/pips)>TrailDistance)   
                          if(OrderStopLoss()<BreakevenOfBuys())
                         
                           if (OrderModify(OrderTicket(),OrderOpenPrice(),sl,OrderTakeProfit(),0,CLR_NONE))
                               Print("Order ",OrderTicket()," was successfully modified.");
                               else Print("Order ",OrderTicket()," was NOT successfully modified.",GetLastError());    
                                 }
                          {
                          tp=OrigTpsell;
                          sl=NormalizeDouble(BreakevenOfSells(),5);
                         
                          if(OrderType()==1)
                          if ((OrderProfit()/pips)>TrailDistance)
                          if(OrderStopLoss()>BreakevenOfSells())
                                                   
                              if(OrderModify(OrderTicket(),OrderOpenPrice(),sl,OrderTakeProfit(),0,CLR_NONE))
                                  Print("Order ",OrderTicket()," was successfully modified.");
                                  else Print("Order ",OrderTicket()," was NOT successfully modified.",GetLastError());
                           }
                           }
                }                 
                                 
}
 
Please edit your post and use the code button (Alt+S) when pasting code.
EDIT your original post, please do not just post the code correctly in a new post.

Topics concerning MT4 and MQL4 have their own section.
In future please post in the correct section.
I have moved your topic to the MQL4 and Metatrader 4 section.
 
Kristan Carl Malazarte:

I have this Move to BreakEven function, it work if I only have 1 order open, but when the EA scales in to 3 orders, the other 2 order don't get modified.  I also keep getting modify error 1, I know this means its keeps passing the same value but how do I Stop this. 



You can give this a try. Values are not understood when the code is not written completely. Also, what a mistake in the expert tab.


void checkforMovetoBe()
  {
   double tp = 0,sl = 0;


   for(int i = 0; i < OrdersTotal(); i++)
     {
      if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
         if(OrderSymbol()== Symbol() && (OrderMagicNumber()==magic))
            //   if ((OrderProfit()/pips)>TrailDistance)
           {
            if(OrderType()==OP_BUY)
              {
               tp=OrigTpbuy;
               sl=NormalizeDouble(BreakevenOfBuys(),5);


               if((OrderProfit()/pips)>TrailDistance)
                  if(OrderStopLoss()<BreakevenOfBuys() && OrderStopLoss()!=sl)

                     if(OrderModify(OrderTicket(),OrderOpenPrice(),sl,OrderTakeProfit(),0,CLR_NONE))
                        Print("Order BUY  ",OrderTicket()," was successfully modified.");
                     else
                        Print("Order  BUY",OrderTicket()," was NOT successfully modified.",GetLastError()," Order SL ",OrderStopLoss()," New Sl ",sl);
              }


            if(OrderType()==OP_SELL)
              {
               tp=OrigTpsell;
               sl=NormalizeDouble(BreakevenOfSells(),5);


               if((OrderProfit()/pips)>TrailDistance)
                  if(OrderStopLoss()>BreakevenOfSells() && OrderStopLoss()!=sl)

                     if(OrderModify(OrderTicket(),OrderOpenPrice(),sl,OrderTakeProfit(),0,CLR_NONE))
                        Print("Order SELL ",OrderTicket()," was successfully modified.");
                     else
                        Print("Order SELL ",OrderTicket()," was NOT successfully modified.",GetLastError()," Order SL ",OrderStopLoss()," New Sl ",sl);
              }
           }
     }

  } 
 

Hi There, thank you for your response this is the entire code for it. The result is still the same, it only modifies the last position.  The idea is after the initial trade, the EA scales in to 2 other trade when the position goes into the favor of the trade, and then automatically adjusts the stoploss to the breakeven of the trades, after a certain distance in pips set in the traildistance. 


//+------------------------------------------------------------------+
//|                                                 BaseEA2%Rule.mq4 |
//|                        Copyright 2015, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2015, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
 double pips;
  int magic;

       double LotSize=0.01;
   extern int TakeProfit=
30 ;
   extern int StopLoss=10;
   extern int HedgeDist=5;
   extern int TradeSpacing=5;
   extern int MagicSeed=1000;
       double BuyLotSize=0.01;
       double SellLotSize=0.01;   
extern double RiskPercent1=0.01;
extern int ActivationDay=0;
extern int Activationhour=0;
   extern int ActivationMinute=0;
    extern int TrailDistance=30;
extern int BollingerPeriod=20;
extern int BollingerDeviation=2;
 double OrigTpbuy;
   double OrigTpsell;
   
 extern int  Emaperiod=20;
   extern int  EMaShift=0;
   extern int  EMaMethod=1;
   extern int  EMaAppliedTo=0;
     extern int  Fast_Macd_Ema=12;
   extern int  Slow_Macd_Ema=26;
   extern int Signal_Macd=9;
int pendingbuyticket=0,pendingsellticket=0;   

  extern double whentotrail=25;
      extern double trailamount=2;
      
       extern int  FastMA=50;
   extern int  FastMaShift=0;
   extern int  FastMaMethod=0;
   extern int  FastMaAppliedTo=0;
   extern int  SlowMA=160;
   extern int  SlowMaShift=0;
   extern int  SlowMaMethod=0;
   extern int  SlowMaAppliedTo=0;
   extern int  LongMA=200;
   extern int  LongMAShift=0;
   extern int  LongMAMehod=1;
   extern int  LongMAAppliedTo=0;
    extern double psarStep=0.02;
      

int OnInit()
  {
//---
   magic = MagicNumberGenerator();
  
   pips =Point; //.00001 or .0001. .001 .01.
   if(Digits==3||Digits==5)
   pips*=10;
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
   
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   BreakevenOfBuys();
   BreakevenOfSells();
   BuyTradeCounter();
   SellTradeCounter();
 
   checkforsignal();
   checkforMovetoBe (); 
 
 
   
   {  static datetime candletime = 0;
   //  if(Hour()==(Activationhour-5) && Minute()==ActivationMinute) //&& Day()==ActivationDay)
      
      {
    
      InitialTrade();
     candletime = Time[0];  
      }
      
  }
  
 
  
   
   
      
       
 
    Comment(
              
               "\n \n \n Account Equity", AccountEquity(),
               "\n BreakEvenofbuys", NormalizeDouble(BreakevenOfBuys(),5),
               "\n BreakEvenofSells", NormalizeDouble(BreakevenOfSells(),5),
               "\n Hour", Hour()
                
           );
  }
//+------------------------------------------------------------------+
void InitialTrade()
{
 double Emacurrent = iMA(NULL,0,Emaperiod,EMaShift,EMaMethod,EMaAppliedTo,0); 
double eMaprevious = iMA(NULL,0,Emaperiod,EMaShift,EMaMethod,EMaAppliedTo,1); 
double eMaprevious3 = iMA(NULL,0,Emaperiod,EMaShift,EMaMethod,EMaAppliedTo,2);
double eMaprevious4 = iMA(NULL,0,Emaperiod,EMaShift,EMaMethod,EMaAppliedTo,3);  
double Macd_Value=iMACD(NULL,0,Fast_Macd_Ema,Slow_Macd_Ema,Signal_Macd,PRICE_CLOSE,MODE_MAIN,0);
double Macd_valueprevious=iMACD(NULL,0,Fast_Macd_Ema,Slow_Macd_Ema,Signal_Macd,PRICE_CLOSE,MODE_MAIN,1);
double Macd_valueprevious3=iMACD(NULL,0,Fast_Macd_Ema,Slow_Macd_Ema,Signal_Macd,PRICE_CLOSE,MODE_MAIN,2);

   
   if(Macd_Value>0 && Macd_valueprevious<0 && Macd_valueprevious3<0)
   if(Ask>Emacurrent)
   if(Ask-Emacurrent>10*pips)
     
            if(BuyTradeCounter()==0)
                OrderEntry(0);
              //  OrderEntry2(0);
            

   if (Macd_Value<0 && Macd_valueprevious>0 && Macd_valueprevious3>0)
   if (Bid<Emacurrent)
   if(Emacurrent-Bid>10*pips)
                   if(SellTradeCounter()==0)
                OrderEntry(1);
               // OrderEntry2(1);

}

void checkforsignal ()
{

   double MiddleBB=iBands(NULL,0,BollingerPeriod,BollingerDeviation,0,0,MODE_MAIN,1);
   double LowerBB=iBands(NULL,0,BollingerPeriod,BollingerDeviation,0,0,MODE_LOWER,1);
        double UpperBB=iBands(NULL,0,BollingerPeriod,BollingerDeviation,0,0,MODE_UPPER,1);
       
    
      
  
    {
    if (BuyTradeCounter())
               {  
     
                 if(Ask-HighestBuyPosition() >= TradeSpacing*pips)
                 if(BuyTradeCounter()<3)   
                  OrderEntry(0);
           
               }
               
     }  
      
      
    
        
       { if(SellTradeCounter())  
                {
                 if(LowestSellPosition()-Bid >= TradeSpacing*pips)
                 if(SellTradeCounter()<3)
                          OrderEntry(1);
                    }
                    
        }
  
  
  }
void StopOrderEntry(int direction)
{
   double tp = 0,sl = 0;
   
     
   
   if(direction==0)
   
   {
    double BuyPrice=(Ask+HedgeDist*pips);
    tp=(BuyPrice+TakeProfit*pips);
    sl=(BuyPrice-StopLoss*pips);
     OrigTpbuy=tp;
     buyautolots();
      pendingbuyticket = OrderSend(Symbol(),OP_BUYSTOP,BuyLotSize,BuyPrice,3,sl,tp,NULL,magic,0,Green);
     if(pendingbuyticket>0)
         if(OrderModify(pendingbuyticket,OrderOpenPrice(),sl,tp,0,CLR_NONE))
            Print("Order ",pendingbuyticket," was successfully modified.");
            else Print("Order ",pendingbuyticket," was NOT successfully modified.",GetLastError());
      
   }
   
   if(direction==1)
   {
   
    double SellPrice=(Ask-HedgeDist*pips);
    tp=(SellPrice-(TakeProfit*pips));
    sl=(SellPrice+(StopLoss*pips));
    OrigTpsell=tp;
      sellautolots();
      pendingsellticket = OrderSend(Symbol(),OP_SELLSTOP,SellLotSize,SellPrice,3,sl,tp,NULL,magic,0,Red);
     if(pendingsellticket>0)
         if(OrderModify(pendingsellticket,OrderOpenPrice(),sl,tp,0,CLR_NONE))
            Print("Order ",pendingsellticket," was successfully modified.");
            else Print("Order ",pendingsellticket," was NOT successfully modified.",GetLastError());
      }
    
}


void OrderEntry(int direction)
{
   double tp = 0,sl = 0;
   
     
   int buyticket=0,sellticket=0;   
   if(direction==0)
   
   {
    {if(BuyTradeCounter()==0)
    tp=(Ask+TakeProfit*pips);
    else
      tp=(LowestBuyPosition()+TakeProfit*pips);
      }
      sl=(Ask-StopLoss*pips);
     buyautolots();
      buyticket = OrderSend(Symbol(),OP_BUY,BuyLotSize,Ask,3,0,0,NULL,magic,0,Green);
     if(buyticket>0)
         if(OrderModify(buyticket,OrderOpenPrice(),sl,tp,0,CLR_NONE))
            Print("Order ",buyticket," was successfully modified.");
            else Print("Order ",buyticket," was NOT successfully modified.",GetLastError());
      
   }
   
   if(direction==1)
   {
   {
    if(SellTradeCounter()==0)
    tp=(Bid-TakeProfit*pips);
    else
    tp=(HighestSellPosition()-TakeProfit*pips);
    }
      sl=(Bid+StopLoss*pips);//(Psar+2*pips);
      sellautolots();
      sellticket = OrderSend(Symbol(),OP_SELL,SellLotSize,Bid,3,0,0,NULL,magic,0,Red);
     if(sellticket>0)
         if(OrderModify(sellticket,OrderOpenPrice(),sl,tp,0,CLR_NONE))
            Print("Order ",sellticket," was successfully modified.");
            else Print("Order ",sellticket," was NOT successfully modified.",GetLastError());
      }
    
}





int MagicNumberGenerator()
{
        string mySymbol = StringSubstr(_Symbol,0,6);
   int pairNumber=0;
   int GeneratedNumber =0;      
             if (mySymbol == "AUDCAD")  pairNumber=1;
        else if (mySymbol == "AUDCHF")  pairNumber=2;
        else if (mySymbol == "AUDJPY")  pairNumber=3;
        else if (mySymbol == "AUDNZD")  pairNumber=4;
        else if (mySymbol == "AUDUSD")  pairNumber=5;
        else if (mySymbol == "CADCHF")  pairNumber=6;
        else if (mySymbol == "CADJPY")  pairNumber=7;
        else if (mySymbol == "CHFJPY")  pairNumber=8;
        else if (mySymbol == "EURAUD")  pairNumber=9;
        else if (mySymbol == "EURCAD")  pairNumber=10;
        else if (mySymbol == "EURCHF")  pairNumber=11;
        else if (mySymbol == "EURGBP")  pairNumber=12;
        else if (mySymbol == "EURJPY")  pairNumber=13;
        else if (mySymbol == "EURNZD")  pairNumber=14;
        else if (mySymbol == "EURUSD")  pairNumber=15;
        else if (mySymbol == "GBPAUD")  pairNumber=16;
        else if (mySymbol == "GBPCAD")  pairNumber=17;
        else if (mySymbol == "GBPCHF")  pairNumber=18;
        else if (mySymbol == "GBPJPY")  pairNumber=19;
        else if (mySymbol == "GBPNZD")  pairNumber=20;
        else if (mySymbol == "GBPUSD")  pairNumber=21;
        else if (mySymbol == "NZDCAD")  pairNumber=22;
        else if (mySymbol == "NZDJPY")  pairNumber=23;
        else if (mySymbol == "NZDCHF")  pairNumber=24;
        else if (mySymbol == "NZDUSD")  pairNumber=25;
        else if (mySymbol == "USDCAD")  pairNumber=26;
        else if (mySymbol == "USDCHF")  pairNumber=27;
        else if (mySymbol == "USDJPY")  pairNumber=28;
        GeneratedNumber = MagicSeed + (pairNumber*10) + _Period;
        return(GeneratedNumber);
        }
int BuyStopTradeCounter()
{
   int total=0; 
   int totalOrders=OrdersTotal();
   for(int i=totalOrders-1; i >= 0; i--)
          {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
         if(OrderMagicNumber()==magic && (OrderType()==OP_BUYSTOP ))
           total++;
        }   
           return(total);
                              
        
        }
int SellStopTradeCounter()
{
   int total2=0;
   int totalOrders=OrdersTotal();
   for(int i=totalOrders-1; i >= 0; i--)
          {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
         if(OrderMagicNumber()==magic && (OrderType()==OP_SELLSTOP))
            total2++;
         }   
            return (total2);
         
         
         }                         
int BuyTradeCounter()
{
   int total=0; 
   int totalOrders=OrdersTotal();
   for(int i=totalOrders-1; i >= 0; i--)
          {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
         if(OrderMagicNumber()==magic && (OrderType()==OP_BUY ))
           total++;
        }   
           return(total);
                              
        
        }
int SellTradeCounter()
{
   int total2=0;
   int totalOrders=OrdersTotal();
   for(int i=totalOrders-1; i >= 0; i--)
          {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
         if(OrderMagicNumber()==magic && (OrderType()==OP_SELL))
            total2++;
         }   
            return (total2);
         
         
         }                         

double Cummulativeloss()
{
  double CummulativeLossTotal=0;
   for(int i=OrdersHistoryTotal()-1; i >= 0; i--)
          {
      if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY))
         if((OrderSymbol()== Symbol()) && (OrderMagicNumber()==magic ))
         if(OrderProfit()>0)
         break;
         else 
         CummulativeLossTotal+=(OrderProfit()+OrderCommission());
         
         Print("The Cummulative loss is ",CummulativeLossTotal);
                  }
          return (CummulativeLossTotal);
          
}


void buyautolots()
{

double Equity=AccountBalance();
double StopDistance;
StopDistance=(Ask-(Low[0]-StopLoss*pips))/pips;

round (BuyLotSize=(Equity*RiskPercent1)/StopLoss/10);


}
void sellautolots()
{

double Equity=AccountBalance();
double StopDistance;

StopDistance=(((High[0]+StopLoss*pips))-Bid)/pips;


round (SellLotSize=(Equity*RiskPercent1)/StopLoss/10);


}

double LowestSellPosition()
{
        double LowestOpenPrice=0.0;
        for (int cnt=OrdersTotal()-1; cnt >= 0; cnt--)
   {
                if(OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES))
                if(OrderMagicNumber()== magic)
                   if(OrderType()==OP_SELL)
                      if(LowestOpenPrice==0.0)
                       LowestOpenPrice=OrderOpenPrice();
                   else if(OrderOpenPrice()<LowestOpenPrice)
                            LowestOpenPrice=OrderOpenPrice();
        }
   return(LowestOpenPrice);             
}
//+------------------------------------------------------------------+
//| find the price of the lowest buy that's open.                    |
//+------------------------------------------------------------------+

double HighestBuyPosition()
{
        double HighestOpenPrice=0.0;
        for (int cnt=OrdersTotal()-1; cnt >= 0; cnt--)
   {
        if(OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES))
           if(OrderMagicNumber()== magic)
              if(OrderType()==OP_BUY)
                 if(HighestOpenPrice==0.0)
                       HighestOpenPrice=OrderOpenPrice();
                    else if (OrderOpenPrice()>HighestOpenPrice)
                       HighestOpenPrice=OrderOpenPrice();
   }
        return(HighestOpenPrice);               
}                               


double HighestSellPosition()
{
        double HighestOpenPrice=0.0;
        for (int cnt=OrdersTotal()-1; cnt >= 0; cnt--)
   {
                if(OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES))
                if(OrderMagicNumber()== magic)
                   if(OrderType()==OP_SELL)
                      if(OrderOpenPrice()>HighestOpenPrice)
                            HighestOpenPrice=OrderOpenPrice();
        }
   return(HighestOpenPrice);            
}
//+------------------------------------------------------------------+
//| find the price of the lowest buy that's open.                    |
//+------------------------------------------------------------------+

double LowestBuyPosition()
{
        double LowestOpenPrice=0.0;
        for (int cnt=OrdersTotal()-1; cnt >= 0; cnt--)
   {
        if(OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES))
           if(OrderMagicNumber()== magic)
              if(OrderType()==OP_BUY)
                 if(LowestOpenPrice==0.0)
                       LowestOpenPrice=OrderOpenPrice();
                    else if (OrderOpenPrice()<LowestOpenPrice)
                       LowestOpenPrice=OrderOpenPrice();
   }
        return(LowestOpenPrice);                
}         

         
         
    
void checkforMovetoBe()
  {
   double tp = 0,sl = 0;


   for(int i = 0; i < OrdersTotal(); i++)
     {
      if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
         if(OrderSymbol()== Symbol() && (OrderMagicNumber()==magic))
            //   if ((OrderProfit()/pips)>TrailDistance)
           {
            if(OrderType()==OP_BUY)
              {
               tp=OrigTpbuy;
               sl=NormalizeDouble(BreakevenOfBuys(),5);
               if ((OrderProfit()/OrderLots())>TrailDistance*10)   
           
                  if(OrderStopLoss()<BreakevenOfBuys() && OrderStopLoss()!=sl)

                     if(OrderModify(OrderTicket(),OrderOpenPrice(),sl,OrderTakeProfit(),0,CLR_NONE))
                        Print("Order BUY  ",OrderTicket()," was successfully modified.");
                     else
                        Print("Order  BUY",OrderTicket()," was NOT successfully modified.",GetLastError()," Order SL ",OrderStopLoss()," New Sl ",sl);
              }


            if(OrderType()==OP_SELL)
              {
               tp=OrigTpsell;
               sl=NormalizeDouble(BreakevenOfSells(),5);

              if ((OrderProfit()/OrderLots())>TrailDistance*10)   
                  if(OrderStopLoss()>BreakevenOfSells() && OrderStopLoss()!=sl)

                     if(OrderModify(OrderTicket(),OrderOpenPrice(),sl,OrderTakeProfit(),0,CLR_NONE))
                        Print("Order SELL ",OrderTicket()," was successfully modified.");
                     else
                        Print("Order SELL ",OrderTicket()," was NOT successfully modified.",GetLastError()," Order SL ",OrderStopLoss()," New Sl ",sl);
              }
           }
     }

  } 

double BreakevenOfSells()
{
        double TotalLots = 0,
               price = 0,
               lots =0,
               pricetimeslots =0,
               Total =0,
               TotalPriceTimesLots=0;
        for(int cnt=0;cnt<OrdersTotal();cnt++)
        {
      if(OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES))
                   if (OrderMagicNumber()== magic)
                      if(OrderType()==OP_SELL)
                      {
              price = OrderOpenPrice(); 
              lots = OrderLots();
              pricetimeslots = price * lots;
              TotalLots += lots;
              TotalPriceTimesLots += pricetimeslots;
            }
   }
              if(TotalLots)//if total is NOT zero.. 
               Total = TotalPriceTimesLots/TotalLots;
   return(NormalizeDouble(Total,5));
}



double BreakevenOfBuys()
{
        double TotalLots = 0,
               price = 0,
               lots =0,
               pricetimeslots =0,
               Total =0,
               TotalPriceTimesLots=0;
        for(int cnt=0;cnt<OrdersTotal();cnt++)
        {
      if(OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES))
                   if (OrderMagicNumber()== magic)
                      if(OrderType()==OP_BUY)
                      {
              price = OrderOpenPrice(); 
              lots = OrderLots();
              pricetimeslots = price * lots;
              TotalLots += lots;
              TotalPriceTimesLots += pricetimeslots;
            }
   }    
              if(TotalLots)
              Total = TotalPriceTimesLots/TotalLots;
   return(NormalizeDouble(Total,5));
}           

          
 
 
                                                   
 

Hi Buddy, though I did not have enough time to check your code, but if I may understand you, do you want to activate breakeven or trailing stop?

if breakeven then try using this function...

bool BreakEven(int WhenPriceGetToPoint,int SecureProfitPoint,string symbol,int MgicNB)
  {
   for(int i=0; i<OrdersTotal(); i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
        {
         if(OrderSymbol()== symbol && OrderMagicNumber()== MgicNB)
           {
            if(OrderType() == OP_BUY)//Bid>=OrderOpenPrice()+LockInPoint*Point
              {
               if(SymbolInfoDouble(symbol,SYMBOL_BID) >= OrderOpenPrice()+WhenPriceGetToPoint*SymbolInfoDouble(symbol,SYMBOL_POINT))
                 {
                  double sl = OrderOpenPrice()+SecureProfitPoint *SymbolInfoDouble(symbol,SYMBOL_POINT);
                  bool md = OrderModify(OrderTicket(),OrderOpenPrice(),sl,OrderTakeProfit(),0);
                  if(md == true)
                     return true;
                 }
              }
            if(OrderType()== OP_SELL)
              {
               if(SymbolInfoDouble(symbol,SYMBOL_BID) <= OrderOpenPrice()-WhenPriceGetToPoint*SymbolInfoDouble(symbol,SYMBOL_POINT))
                 {
                  double sl = OrderOpenPrice()-SecureProfitPoint *SymbolInfoDouble(symbol,SYMBOL_POINT);
                  bool md = OrderModify(OrderTicket(),OrderOpenPrice(),sl,OrderTakeProfit(),0);
                  if(md == true)
                     return true;
                 }
              }
           }
        }
     }
   return false;
  }
 
Emmanuel Emmanuel Tom:

Hi Buddy, though I did not have enough time to check your code, but if I may understand you, do you want to activate breakeven or trailing stop?

if breakeven then try using this function...

No problems.

Your lot quantity is incorrect. A figure like 100000 is formed. Sl and TP values are incorrect at entry. It will be 100, not 10.

You will use AccountEquity, not AccountBalance. I was simply an investment for correction. He opened 3 orders. updated SL and TP in all of them. Move to stop is working normally.

edrer

e

eee

//+------------------------------------------------------------------+
//|                                                 BaseEA2%Rule.mq4 |
//|                        Copyright 2015, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2015, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
 double pips;
  int magic;

       double LotSize=0.01;
   extern int TakeProfit=300 ;
   extern int StopLoss=100;
   extern int HedgeDist=5;
   extern int TradeSpacing=5;
   extern int MagicSeed=1000;
       double BuyLotSize=0.01;
       double SellLotSize=0.01;   
extern double RiskPercent1=0.01;
extern int ActivationDay=0;
extern int Activationhour=0;
   extern int ActivationMinute=0;
    extern int TrailDistance=30;
extern int BollingerPeriod=20;
extern int BollingerDeviation=2;
 double OrigTpbuy;
   double OrigTpsell;
   
 extern int  Emaperiod=20;
   extern int  EMaShift=0;
   extern int  EMaMethod=1;
   extern int  EMaAppliedTo=0;
     extern int  Fast_Macd_Ema=12;
   extern int  Slow_Macd_Ema=26;
   extern int Signal_Macd=9;
int pendingbuyticket=0,pendingsellticket=0;   

  extern double whentotrail=25;
      extern double trailamount=2;
      
       extern int  FastMA=50;
   extern int  FastMaShift=0;
   extern int  FastMaMethod=0;
   extern int  FastMaAppliedTo=0;
   extern int  SlowMA=160;
   extern int  SlowMaShift=0;
   extern int  SlowMaMethod=0;
   extern int  SlowMaAppliedTo=0;
   extern int  LongMA=200;
   extern int  LongMAShift=0;
   extern int  LongMAMehod=1;
   extern int  LongMAAppliedTo=0;
    extern double psarStep=0.02;
      

int OnInit()
  {
//---
   magic = MagicNumberGenerator();
  
   pips =Point; //.00001 or .0001. .001 .01.
   if(Digits==3||Digits==5)
   pips*=10;
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
   
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   BreakevenOfBuys();
   BreakevenOfSells();
   BuyTradeCounter();
   SellTradeCounter();
 
   checkforsignal();
   checkforMovetoBe (); 
 
 
   
   {  static datetime candletime = 0;
   //  if(Hour()==(Activationhour-5) && Minute()==ActivationMinute) //&& Day()==ActivationDay)
      
      {
    
      InitialTrade();
     candletime = Time[0];  
      }
      
  }
  
 
  
   
   
      
       
 
    Comment(
              
               "\n \n \n Account Equity", AccountEquity(),
               "\n BreakEvenofbuys", NormalizeDouble(BreakevenOfBuys(),5),
               "\n BreakEvenofSells", NormalizeDouble(BreakevenOfSells(),5),
               "\n Hour", Hour()
                
           );
  }
//+------------------------------------------------------------------+
void InitialTrade()
{
 double Emacurrent = iMA(NULL,0,Emaperiod,EMaShift,EMaMethod,EMaAppliedTo,0); 
double eMaprevious = iMA(NULL,0,Emaperiod,EMaShift,EMaMethod,EMaAppliedTo,1); 
double eMaprevious3 = iMA(NULL,0,Emaperiod,EMaShift,EMaMethod,EMaAppliedTo,2);
double eMaprevious4 = iMA(NULL,0,Emaperiod,EMaShift,EMaMethod,EMaAppliedTo,3);  
double Macd_Value=iMACD(NULL,0,Fast_Macd_Ema,Slow_Macd_Ema,Signal_Macd,PRICE_CLOSE,MODE_MAIN,0);
double Macd_valueprevious=iMACD(NULL,0,Fast_Macd_Ema,Slow_Macd_Ema,Signal_Macd,PRICE_CLOSE,MODE_MAIN,1);
double Macd_valueprevious3=iMACD(NULL,0,Fast_Macd_Ema,Slow_Macd_Ema,Signal_Macd,PRICE_CLOSE,MODE_MAIN,2);

   
   if(Macd_Value>0 && Macd_valueprevious<0 && Macd_valueprevious3<0)
   if(Ask>Emacurrent)
   if(Ask-Emacurrent>10*pips)
     
            if(BuyTradeCounter()==0)
                OrderEntry(0);
              //  OrderEntry2(0);
            

   if (Macd_Value<0 && Macd_valueprevious>0 && Macd_valueprevious3>0)
   if (Bid<Emacurrent)
   if(Emacurrent-Bid>10*pips)
                   if(SellTradeCounter()==0)
                OrderEntry(1);
               // OrderEntry2(1);

}

void checkforsignal ()
{

   double MiddleBB=iBands(NULL,0,BollingerPeriod,BollingerDeviation,0,0,MODE_MAIN,1);
   double LowerBB=iBands(NULL,0,BollingerPeriod,BollingerDeviation,0,0,MODE_LOWER,1);
        double UpperBB=iBands(NULL,0,BollingerPeriod,BollingerDeviation,0,0,MODE_UPPER,1);
       
    
      
  
    {
    if (BuyTradeCounter())
               {  
     
                 if(Ask-HighestBuyPosition() >= TradeSpacing*pips)
                 if(BuyTradeCounter()<3)   
                  OrderEntry(0);
           
               }
               
     }  
      
      
    
        
       { if(SellTradeCounter())  
                {
                 if(LowestSellPosition()-Bid >= TradeSpacing*pips)
                 if(SellTradeCounter()<3)
                          OrderEntry(1);
                    }
                    
        }
  
  
  }
void StopOrderEntry(int direction)
{
   double tp = 0,sl = 0;
   
     
   
   if(direction==0)
   
   {
    double BuyPrice=(Ask+HedgeDist*pips);
    tp=(BuyPrice+TakeProfit*pips);
    sl=(BuyPrice-StopLoss*pips);
     OrigTpbuy=tp;
     buyautolots();
      pendingbuyticket = OrderSend(Symbol(),OP_BUYSTOP,BuyLotSize,BuyPrice,3,sl,tp,NULL,magic,0,Green);
      Print("OrderBuyStop ",GetLastError()," BuyLotsize  ",BuyLotSize," Buy Price  ",BuyPrice);
      
     if(pendingbuyticket>0)
         if(OrderModify(pendingbuyticket,OrderOpenPrice(),sl,tp,0,CLR_NONE))
            Print("Order ",pendingbuyticket," was successfully modified.");
            else Print("OrderBuy ",pendingbuyticket," was NOT successfully modified.",GetLastError()," Order SL ",OrderStopLoss()," New Sl ",sl);
      
   }
   
   if(direction==1)
   {
   
    double SellPrice=(Ask-HedgeDist*pips);
    tp=(SellPrice-(TakeProfit*pips));
    sl=(SellPrice+(StopLoss*pips));
    OrigTpsell=tp;
      sellautolots();
      pendingsellticket = OrderSend(Symbol(),OP_SELLSTOP,SellLotSize,SellPrice,3,sl,tp,NULL,magic,0,Red);
       Print("OrderSellStop ",GetLastError()," Sell otsize  ",SellLotSize," Sell Price  ",SellPrice);
     if(pendingsellticket>0)
         if(OrderModify(pendingsellticket,OrderOpenPrice(),sl,tp,0,CLR_NONE))
            Print("Order ",pendingsellticket," was successfully modified.");
            else Print("Order ",pendingsellticket," was NOT successfully modified.",GetLastError(),GetLastError()," Order SL ",OrderStopLoss()," New Sl ",sl);
      }
    
}


void OrderEntry(int direction)
{
   double tp = 0,sl = 0;
   
     
   int buyticket=0,sellticket=0;   
   if(direction==0)
   
   {
    {if(BuyTradeCounter()==0)
    tp=(Ask+TakeProfit*pips);
    else
      tp=(LowestBuyPosition()+TakeProfit*pips);
      }
      sl=(Ask-StopLoss*pips);
     buyautolots();
      buyticket = OrderSend(Symbol(),OP_BUY,BuyLotSize,Ask,3,0,0,NULL,magic,0,Green);
       Print("OrderBuy ",GetLastError()," BuyLotsize  ",BuyLotSize);
     if(buyticket>0)
         if(OrderModify(buyticket,OrderOpenPrice(),sl,tp,0,CLR_NONE))
            Print("Order ",buyticket," was successfully modified.");
            else Print("Order BUY ",buyticket," was NOT successfully modified.",GetLastError(),GetLastError()," Order SL ",OrderStopLoss()," New Sl ",sl);
      
   }
   
   if(direction==1)
   {
   {
    if(SellTradeCounter()==0)
    tp=(Bid-TakeProfit*pips);
    else
    tp=(HighestSellPosition()-TakeProfit*pips);
    }
      sl=(Bid+StopLoss*pips);//(Psar+2*pips);
      sellautolots();
      sellticket = OrderSend(Symbol(),OP_SELL,SellLotSize,Bid,3,0,0,NULL,magic,0,Red);
       Print("OrderSellp ",GetLastError()," SellLotsize  ",SellLotSize);
     if(sellticket>0)
         if(OrderModify(sellticket,OrderOpenPrice(),sl,tp,0,CLR_NONE))
            Print("Order ",sellticket," was successfully modified.");
            else Print("Order SELL ",sellticket," was NOT successfully modified.",GetLastError(),GetLastError()," Order SL ",OrderStopLoss()," New Sl ",sl);
      }
    
}





int MagicNumberGenerator()
{
        string mySymbol = StringSubstr(_Symbol,0,6);
   int pairNumber=0;
   int GeneratedNumber =0;      
             if (mySymbol == "AUDCAD")  pairNumber=1;
        else if (mySymbol == "AUDCHF")  pairNumber=2;
        else if (mySymbol == "AUDJPY")  pairNumber=3;
        else if (mySymbol == "AUDNZD")  pairNumber=4;
        else if (mySymbol == "AUDUSD")  pairNumber=5;
        else if (mySymbol == "CADCHF")  pairNumber=6;
        else if (mySymbol == "CADJPY")  pairNumber=7;
        else if (mySymbol == "CHFJPY")  pairNumber=8;
        else if (mySymbol == "EURAUD")  pairNumber=9;
        else if (mySymbol == "EURCAD")  pairNumber=10;
        else if (mySymbol == "EURCHF")  pairNumber=11;
        else if (mySymbol == "EURGBP")  pairNumber=12;
        else if (mySymbol == "EURJPY")  pairNumber=13;
        else if (mySymbol == "EURNZD")  pairNumber=14;
        else if (mySymbol == "EURUSD")  pairNumber=15;
        else if (mySymbol == "GBPAUD")  pairNumber=16;
        else if (mySymbol == "GBPCAD")  pairNumber=17;
        else if (mySymbol == "GBPCHF")  pairNumber=18;
        else if (mySymbol == "GBPJPY")  pairNumber=19;
        else if (mySymbol == "GBPNZD")  pairNumber=20;
        else if (mySymbol == "GBPUSD")  pairNumber=21;
        else if (mySymbol == "NZDCAD")  pairNumber=22;
        else if (mySymbol == "NZDJPY")  pairNumber=23;
        else if (mySymbol == "NZDCHF")  pairNumber=24;
        else if (mySymbol == "NZDUSD")  pairNumber=25;
        else if (mySymbol == "USDCAD")  pairNumber=26;
        else if (mySymbol == "USDCHF")  pairNumber=27;
        else if (mySymbol == "USDJPY")  pairNumber=28;
        GeneratedNumber = MagicSeed + (pairNumber*10) + _Period;
        return(GeneratedNumber);
        }
int BuyStopTradeCounter()
{
   int total=0; 
   int totalOrders=OrdersTotal();
   for(int i=totalOrders-1; i >= 0; i--)
          {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
         if(OrderMagicNumber()==magic && (OrderType()==OP_BUYSTOP ))
           total++;
        }   
           return(total);
                              
        
        }
int SellStopTradeCounter()
{
   int total2=0;
   int totalOrders=OrdersTotal();
   for(int i=totalOrders-1; i >= 0; i--)
          {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
         if(OrderMagicNumber()==magic && (OrderType()==OP_SELLSTOP))
            total2++;
         }   
            return (total2);
         
         
         }                         
int BuyTradeCounter()
{
   int total=0; 
   int totalOrders=OrdersTotal();
   for(int i=totalOrders-1; i >= 0; i--)
          {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
         if(OrderMagicNumber()==magic && (OrderType()==OP_BUY ))
           total++;
        }   
           return(total);
                              
        
        }
int SellTradeCounter()
{
   int total2=0;
   int totalOrders=OrdersTotal();
   for(int i=totalOrders-1; i >= 0; i--)
          {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
         if(OrderMagicNumber()==magic && (OrderType()==OP_SELL))
            total2++;
         }   
            return (total2);
         
         
         }                         

double Cummulativeloss()
{
  double CummulativeLossTotal=0;
   for(int i=OrdersHistoryTotal()-1; i >= 0; i--)
          {
      if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY))
         if((OrderSymbol()== Symbol()) && (OrderMagicNumber()==magic ))
         if(OrderProfit()>0)
         break;
         else 
         CummulativeLossTotal+=(OrderProfit()+OrderCommission());
         
         Print("The Cummulative loss is ",CummulativeLossTotal);
                  }
          return (CummulativeLossTotal);
          
}


void buyautolots()
{

double Equity=AccountBalance();
double StopDistance;
StopDistance=(Ask-(Low[0]-StopLoss*pips))/pips;

round (BuyLotSize=(Equity*RiskPercent1)/StopLoss/10);


}
void sellautolots()
{

double Equity=AccountEquity();
double StopDistance;

StopDistance=(((High[0]+StopLoss*pips))-Bid)/pips;


round (SellLotSize=(Equity*RiskPercent1)/StopLoss/10);


}

double LowestSellPosition()
{
        double LowestOpenPrice=0.0;
        for (int cnt=OrdersTotal()-1; cnt >= 0; cnt--)
   {
                if(OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES))
                if(OrderMagicNumber()== magic)
                   if(OrderType()==OP_SELL)
                      if(LowestOpenPrice==0.0)
                       LowestOpenPrice=OrderOpenPrice();
                   else if(OrderOpenPrice()<LowestOpenPrice)
                            LowestOpenPrice=OrderOpenPrice();
        }
   return(LowestOpenPrice);             
}
//+------------------------------------------------------------------+
//| find the price of the lowest buy that's open.                    |
//+------------------------------------------------------------------+

double HighestBuyPosition()
{
        double HighestOpenPrice=0.0;
        for (int cnt=OrdersTotal()-1; cnt >= 0; cnt--)
   {
        if(OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES))
           if(OrderMagicNumber()== magic)
              if(OrderType()==OP_BUY)
                 if(HighestOpenPrice==0.0)
                       HighestOpenPrice=OrderOpenPrice();
                    else if (OrderOpenPrice()>HighestOpenPrice)
                       HighestOpenPrice=OrderOpenPrice();
   }
        return(HighestOpenPrice);               
}                               


double HighestSellPosition()
{
        double HighestOpenPrice=0.0;
        for (int cnt=OrdersTotal()-1; cnt >= 0; cnt--)
   {
                if(OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES))
                if(OrderMagicNumber()== magic)
                   if(OrderType()==OP_SELL)
                      if(OrderOpenPrice()>HighestOpenPrice)
                            HighestOpenPrice=OrderOpenPrice();
        }
   return(HighestOpenPrice);            
}
//+------------------------------------------------------------------+
//| find the price of the lowest buy that's open.                    |
//+------------------------------------------------------------------+

double LowestBuyPosition()
{
        double LowestOpenPrice=0.0;
        for (int cnt=OrdersTotal()-1; cnt >= 0; cnt--)
   {
        if(OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES))
           if(OrderMagicNumber()== magic)
              if(OrderType()==OP_BUY)
                 if(LowestOpenPrice==0.0)
                       LowestOpenPrice=OrderOpenPrice();
                    else if (OrderOpenPrice()<LowestOpenPrice)
                       LowestOpenPrice=OrderOpenPrice();
   }
        return(LowestOpenPrice);                
}         

         
         
    
void checkforMovetoBe()
  {
   double tp = 0,sl = 0;


   for(int i = 0; i < OrdersTotal(); i++)
     {
      if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
         if(OrderSymbol()== Symbol() && (OrderMagicNumber()==magic))
            //   if ((OrderProfit()/pips)>TrailDistance)
           {
            if(OrderType()==OP_BUY)
              {
               tp=OrigTpbuy;
               sl=NormalizeDouble(BreakevenOfBuys(),5);
               if ((OrderProfit()/OrderLots())>TrailDistance*10)   
           
                  if(OrderStopLoss()<BreakevenOfBuys() && OrderStopLoss()!=sl)

                     if(OrderModify(OrderTicket(),OrderOpenPrice(),sl,OrderTakeProfit(),0,CLR_NONE))
                        Print("Order BUY  ",OrderTicket()," was successfully modified.");
                     else
                        Print("Order  BUY",OrderTicket()," was NOT successfully modified.",GetLastError()," Order SL ",OrderStopLoss()," New Sl ",sl);
              }


            if(OrderType()==OP_SELL)
              {
               tp=OrigTpsell;
               sl=NormalizeDouble(BreakevenOfSells(),5);

              if ((OrderProfit()/OrderLots())>TrailDistance*10)   
                  if(OrderStopLoss()>BreakevenOfSells() && OrderStopLoss()!=sl)

                     if(OrderModify(OrderTicket(),OrderOpenPrice(),sl,OrderTakeProfit(),0,CLR_NONE))
                        Print("Order SELL ",OrderTicket()," was successfully modified.");
                     else
                        Print("Order SELL ",OrderTicket()," was NOT successfully modified.",GetLastError()," Order SL ",OrderStopLoss()," New Sl ",sl);
              }
           }
     }

  } 

double BreakevenOfSells()
{
        double TotalLots = 0,
               price = 0,
               lots =0,
               pricetimeslots =0,
               Total =0,
               TotalPriceTimesLots=0;
        for(int cnt=0;cnt<OrdersTotal();cnt++)
        {
      if(OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES))
                   if (OrderMagicNumber()== magic)
                      if(OrderType()==OP_SELL)
                      {
              price = OrderOpenPrice(); 
              lots = OrderLots();
              pricetimeslots = price * lots;
              TotalLots += lots;
              TotalPriceTimesLots += pricetimeslots;
            }
   }
              if(TotalLots)//if total is NOT zero.. 
               Total = TotalPriceTimesLots/TotalLots;
   return(NormalizeDouble(Total,5));
}



double BreakevenOfBuys()
{
        double TotalLots = 0,
               price = 0,
               lots =0,
               pricetimeslots =0,
               Total =0,
               TotalPriceTimesLots=0;
        for(int cnt=0;cnt<OrdersTotal();cnt++)
        {
      if(OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES))
                   if (OrderMagicNumber()== magic)
                      if(OrderType()==OP_BUY)
                      {
              price = OrderOpenPrice(); 
              lots = OrderLots();
              pricetimeslots = price * lots;
              TotalLots += lots;
              TotalPriceTimesLots += pricetimeslots;
            }
   }    
              if(TotalLots)
              Total = TotalPriceTimesLots/TotalLots;
   return(NormalizeDouble(Total,5));
}           

          
 
Mehmet Bastem:

No problems.

Your lot quantity is incorrect. A figure like 100000 is formed. Sl and TP values are incorrect at entry. It will be 100, not 10.

You will use AccountEquity, not AccountBalance. I was simply an investment for correction. He opened 3 orders. updated SL and TP in all of them. Move to stop is working normally.




Hi there, thank you for your reply, 

In the strategy tester photo you sent, it only modified order 3, order 1 and 2 was modified to the initial stop loss only. it should have also modified order 1 and 2 to that value of the break even price of the 3 orders. 

Reason: