Trailing Stop [Code Help]

 

Hello, I'm working on some EA's that uses Trailing Stop Loss, I came around with this code:

void Trailing_SL()
{ 
   for (int i = 0; i < OrdersTotal(); i++) //Iterar con todas las ordenes
    {
      bool res = OrderSelect(i,SELECT_BY_POS,MODE_TRADES); //Seleccionar por index i 
       int Local_ticket = OrderTicket(); //Guardar el numero de orden 
              
       if(OrderMagicNumber() == Magic) //Si la orden fue colocada por el bot
         {
           if (OrderType() == OP_BUY) //Y es una compra
            {
             if ( Ask - OrderOpenPrice() >= Trailing_Start * Pips() ) //Revisar si cumple con las condiciones para Trailing SL
               {
                if(Ask - OrderStopLoss() >= Trailing_Start * Pips())
                {
                 double New_TSL_Buy = OrderStopLoss() + Trailing_Step * Pips(); //Calcular el nuevo Stop Loss
                 bool Local_Res; //Indicativo para Fail Safe
                 Local_Res = OrderModify(Local_ticket,OrderOpenPrice(),New_TSL_Buy,OrderTakeProfit(),0); //Y colocarlo
                 
                 if (Local_Res == false)//Si la orden no se modifico correctamente
                  {
                     Alert("Falla en el Trailing Stop Loss para orden #", OrderTicket()); //Notificar que orden es
                     Alert("Codigo del error: ", GetLastError()); //Y la causa
                    }
                   }
                  }
                }
               else if(OrderType() == OP_SELL) //y si es compra
                  {
                    if ( OrderOpenPrice() - Bid >= Trailing_Start * Pips() )//Revisar si cumple con las condiciones para Trailing SL
                      {
                       if(OrderStopLoss() - Bid >= Trailing_Start * Pips()) //Y la diferencia del SL y el Bid es mas grande que la cantidad del trailing
                       {
                        double New_TSL_Sell = OrderStopLoss() - Trailing_Step * Pips(); //Calcular el nuevo Stop Loss
                        bool Local_Res; //Indicativo para Fail Safe
                        Local_Res = OrderModify(Local_ticket,OrderOpenPrice(),New_TSL_Sell,OrderTakeProfit(),0); //Y colocarlo
                          
                          if (Local_Res == false) //Si la orden no se modifico correctamente
                           {
                              Alert("Falla en el Trailing Stop Loss para orden #", OrderTicket()); //Notificar que orden es
                              Alert("Codigo del error: ", GetLastError()); //Y la causa
                             }
                            }
                          }
                        }
                     } 
                  }  
                }

My logic is this:

  • As long the order has the amount of pips on profit or more than the Trailing Start
  • And the difference between the Stop Loss and the current price is more or equal to the Trailing Start
  • Modify the order with the new SL calculated by adding to the current one the ammount of pips specified on the trailing step (This, for scalping systems convenience, in this case, I would take point values istead of entire pips to be suitable for smaller Time Frames)
Is my logic right or I am missing something?

 
           if (OrderType() == OP_BUY) //Y es una compra
            {
             if ( Ask - OrderOpenPrice() >= Trailing_Start * Pips() ) //Revisar si cumple con las condiciones para Trailing SL
               {
                if(Ask - OrderStopLoss() >= Trailing_Start * Pips())
                {
                 double New_TSL_Buy = OrderStopLoss() + Trailing_Step * Pips(); //Calcular el nuevo Stop Loss
                 bool Local_Res; //Indicativo para Fail Safe
                 Local_Res = OrderModify(Local_ticket,OrderOpenPrice(),New_TSL_Buy,OrderTakeProfit(),0); //Y colocarlo
                 
                 if (Local_Res == false)//Si la orden no se modifico correctamente
  1. You buy at the Ask and sell at the Bid.
    • Your buy order's TP/SL are triggered when the Bid reaches it. Not the Ask.
    • Your sell order's TP/SL will be triggered when the Ask reaches it. To trigger at a specific Bid price, add the average spread.
                MODE_SPREAD (Paul) - MQL4 and MetaTrader 4 - MQL4 programming forum - Page 3
    • The charts show Bid prices only. Turn on the Ask line to see how big the spread is (Tools -> Options {control-O} -> charts -> Show ask line.)

  2. A TSL is price - amount, not SL + amount. Your modify might run once. Then on the next tick you move it (by amount) again, and then again...

  3. Correct and simplify your code:
               if (OrderType() == OP_BUY) //Y es una compra
                {
                 double New_TSL_Buy = Bid - Trailing_Start * Pips();
                 if( New_TSL_Buy > MathMax( OrderOpenPrice(), OrderStopLoss() + _Point )
                     if(!OrderModify( ...

  4. You should be able to read your code out loud and have it make sense. You would never write if( (2+2 == 4) == true) would you? if(2+2 == 4) is sufficient. So don't write if(bool == true), just use if(bool) or if(!bool). Code becomes self documenting when you use meaningful variable names, like bool isLongEnabled where as Long_Entry sounds like a trigger price or a ticket number and "if long entry" is an incomplete sentence.

 
whroeder1:
  1. You buy at the Ask and sell at the Bid.
    • Your buy order's TP/SL are triggered when the Bid reaches it. Not the Ask.
    • Your sell order's TP/SL will be triggered when the Ask reaches it. To trigger at a specific Bid price, add the average spread.
                MODE_SPREAD (Paul) - MQL4 and MetaTrader 4 - MQL4 programming forum - Page 3
    • The charts show Bid prices only. Turn on the Ask line to see how big the spread is (Tools -> Options {control-O} -> charts -> Show ask line.)

  2. A TSL is price - amount, not SL + amount. Your modify might run once. Then on the next tick you move it (by amount) again, and then again...

  3. Correct and simplify your code:

  4. You should be able to read your code out loud and have it make sense. You would never write if( (2+2 == 4) == true) would you? if(2+2 == 4) is sufficient. So don't write if(bool == true), just use if(bool) or if(!bool). Code becomes self documenting when you use meaningful variable names, like bool isLongEnabled where as Long_Entry sounds like a trigger price or a ticket number and "if long entry" is an incomplete sentence.

Thanks a lot! if you don't mind, could you help me with some aspects that I didn't got well:

Is there any utility of adding the Trailing Step function to a Trailing SL?

What is this line for?

if( New_TSL_Buy > MathMax( OrderOpenPrice(), OrderStopLoss() + _Point )
 
whroeder1:
  1. You buy at the Ask and sell at the Bid.
    • Your buy order's TP/SL are triggered when the Bid reaches it. Not the Ask.
    • Your sell order's TP/SL will be triggered when the Ask reaches it. To trigger at a specific Bid price, add the average spread.
                MODE_SPREAD (Paul) - MQL4 and MetaTrader 4 - MQL4 programming forum - Page 3
    • The charts show Bid prices only. Turn on the Ask line to see how big the spread is (Tools -> Options {control-O} -> charts -> Show ask line.)

  2. A TSL is price - amount, not SL + amount. Your modify might run once. Then on the next tick you move it (by amount) again, and then again...

  3. Correct and simplify your code:

  4. You should be able to read your code out loud and have it make sense. You would never write if( (2+2 == 4) == true) would you? if(2+2 == 4) is sufficient. So don't write if(bool == true), just use if(bool) or if(!bool). Code becomes self documenting when you use meaningful variable names, like bool isLongEnabled where as Long_Entry sounds like a trigger price or a ticket number and "if long entry" is an incomplete sentencOh,

Oh, and just to make sure, although it might look like a stupid question,on sell orders instead of Bid - TSL would be Ask + TSL right?

 
FernandoBorea: What is this line for?
if( New_TSL_Buy > MathMax( OrderOpenPrice(), OrderStopLoss() + _Point )
  1. You don't trail until it is above open price.
  2. You never trail away from the market.
  3. You never trail with the same value (Error 1.)
 
whroeder1:
  1. You don't trail until it is above open price.
  2. You never trail away from the market.
  3. You never trail with the same value (Error 1.)

Thanks! I made the modifications to the code, I'd like to add some new features and I have some other questions.

void Trailing_SL()
{ 
   for (int i = 0; i < OrdersTotal(); i++) //Iterar con todas las ordenes
    {
      bool res = OrderSelect(i,SELECT_BY_POS,MODE_TRADES); //Seleccionar por index i 
       int Local_ticket = OrderTicket(); //Guardar el numero de orden 
              
       if(OrderMagicNumber() == Magic) //Si la orden fue colocada por el bot
         {
           if (OrderType() == OP_BUY) //Y es una compra
            {
             if (Bid - OrderOpenPrice() >= Trailing_Start * Pips() ) //Revisar si cumple con las condiciones para Trailing SL
               {
                if(Bid - OrderStopLoss() >= Trailing_Start * Pips()) //Y la diferencia del Bid y el SL es superior o igual al Trailing
                {
                 double New_TSL_Buy = (Bid - Trailing_Start * Pips()) + Trailing_Step * Pips(); //Calcular el nuevo Stop Loss
                 bool Local_Res; //Indicativo para Fail Safe
                 Local_Res = OrderModify(Local_ticket,OrderOpenPrice(),New_TSL_Buy,OrderTakeProfit(),0); //Y colocarlo
                 
                 if (Local_Res == false)//Si la orden no se modifico correctamente
                  {
                     Alert("Falla en el Trailing Stop Loss para orden #", OrderTicket()); //Notificar que orden es
                     Alert("Codigo del error: ", GetLastError()); //Y la causa
                    }
                   }
                  }
                }
               else if(OrderType() == OP_SELL) //y si es compra
                  {
                    if ( OrderOpenPrice() - Ask >= Trailing_Start * Pips() )//Revisar si cumple con las condiciones para Trailing SL
                      {
                       if(OrderStopLoss() - Ask >= Trailing_Start * Pips()) //Y la diferencia del SL y el Ask es mas grande que la cantidad del trailing
                       {
                        double New_TSL_Sell = (Ask + Trailing_Start * Pips()) - Trailing_Step * Pips(); //Calcular el nuevo Stop Loss
                        bool Local_Res; //Indicativo para Fail Safe
                        Local_Res = OrderModify(Local_ticket,OrderOpenPrice(),New_TSL_Sell,OrderTakeProfit(),0); //Y colocarlo
                          
                          if (Local_Res == false) //Si la orden no se modifico correctamente
                           {
                              Alert("Falla en el Trailing Stop Loss para orden #", OrderTicket()); //Notificar que orden es
                              Alert("Codigo del error: ", GetLastError()); //Y la causa
                             }
                            }
                          }
                        }
                     } 
                  }  
                }        

I corrected the Bid and Ask errors and the Price - Amount errors, but I have some other questions, as the EA uses Break Even too, I considered that this line:

if(OrderStopLoss() - Ask >= Trailing_Start * Pips())

Would be useful to avoid to move the SL away when BE is activated (Because if the BE moves the SL to entry spot + Safe Pips (a function that I implemented on the EA that makes the trader able to move the SL to X pips in profit when the BE is activated) and the trailing SL is active then it might move back the SL to where it should be according to the trailing stop).

But I have some questions regarding the Price +- amount situation

  • The approach I took making the (Price -+ Amount) -+ Trailing Step part is correct to add the trailing step functionality?
  • The Trailing SL functionality is supposed to move the SL directly to maintain the distance specified (Making kind of a Break Even functionality  (For example, using the code I putted in this comment, when the order has the ammount of pips in profit selected on Trailing_Start it moves the SL directly to the price - that amount on pips, therefore, it moves the SL to profit))?
  • How can I make the trailing stop to trail without necessary moving the SL to profit? (For example, if the price moves 5 pips in profit then the SL is moved 5 pips although it stills below in the case of a buy order or above in the case of a sell order) I think that making something like check for the difference between the actual price and the SL then if its greater than the SL specified on the input then add the ammount of the Trailing Step value in pips to the SL,  (To avoid the EA to over comunicate with the server and flagging the account as hyperactive for moving the SL each tick on a big market movement) so then if the difference is equal or shorter (if it ends up a couple of points shorter due to the trailing step or requotations or if the price moves against) than the SL specified it would just do nothing until the order either hits the SL or moves in profit again so the conditions to move the SL are met. Is that approach correct? (Although if that's not the intended usage of a Trailing SL I think it can be useful to prevent overtaking losses on a situation where the price moves on profit several pips and then turns around, specially on scalping systems where this might happen pretty offen. I know it can sometimes work against the trader because well, if the order gets closed on a pull back  due to the SL movement and then moves back to what would be profits if the order would have kept openend, but for some systems this might improve the overall performance, specially on either short SL or scalping systems working on smaller Time Frames, so it might be good to add an option to activate this behaviour to run some backtesting and optimization to see if it improves the performance over the other Trailing Stop behaviour (Still not sure wich one is the "correct" or intended one).

I hope you are able to help me again on those new questions, I really appreciate your responses as well as those from other moderators! Sorry for keep asking and asking new stuffs.




 
whroeder1:
  1. You buy at the Ask and sell at the Bid.
    • Your buy order's TP/SL are triggered when the Bid reaches it. Not the Ask.
    • Your sell order's TP/SL will be triggered when the Ask reaches it. To trigger at a specific Bid price, add the average spread.
                MODE_SPREAD (Paul) - MQL4 and MetaTrader 4 - MQL4 programming forum - Page 3
    • The charts show Bid prices only. Turn on the Ask line to see how big the spread is (Tools -> Options {control-O} -> charts -> Show ask line.)

  2. A TSL is price - amount, not SL + amount. Your modify might run once. Then on the next tick you move it (by amount) again, and then again...

  3. Correct and simplify your code:

  4. You should be able to read your code out loud and have it make sense. You would never write if( (2+2 == 4) == true) would you? if(2+2 == 4) is sufficient. So don't write if(bool == true), just use if(bool) or if(!bool). Code becomes self documenting when you use meaningful variable names, like bool isLongEnabled where as Long_Entry sounds like a trigger price or a ticket number and "if long entry" is an incomplete sentence.

//+------------------------------------------------------------------+
//          BREAK-EVEN                                               |
//+------------------------------------------------------------------+
void MoveToBreakeven()
{
      //buy order section   
   for(int b=OrdersTotal()-1; b >= 0; b--)
        {
        if(OrderSelect(b,SELECT_BY_POS,MODE_TRADES))
      if(OrderMagicNumber()== MagicNumber)
         if(OrderSymbol()==Symbol())
            if(OrderType()==OP_BUY)
               if(Bid-OrderOpenPrice()>WhenToMoveToBE*pips)
                  if(OrderOpenPrice()>OrderStopLoss())
                     OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice()+(PipsToLockIn*pips),OrderTakeProfit(),0,CLR_NONE);
   }
//sell order section
   for (int s=OrdersTotal()-1; s >= 0; s--)              {          if(OrderSelect(s,SELECT_BY_POS,MODE_TRADES))                 if(OrderMagicNumber()== MagicNumber)                    if(OrderSymbol()==Symbol())                       if(OrderType()==OP_SELL)                   if(OrderOpenPrice()-Ask>WhenToMoveToBE*pips)                      if(OrderOpenPrice()<OrderStopLoss())                             OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice()-(PipsToLockIn*pips),OrderTakeProfit(),0,CLR_NONE);         } } //+------------------------------------------------------------------+ //          TRAILING                                                 | //+------------------------------------------------------------------+ void AdjustTrail() { //buy order section       for(int b=OrdersTotal()-1;b>=0;b--)               {          if(OrderSelect(b,SELECT_BY_POS,MODE_TRADES))            if(OrderMagicNumber()==MagicNumber)               if(OrderSymbol()==Symbol())                   if(OrderType()==OP_BUY)                      if(Bid-OrderOpenPrice()>WhenToTrail*pips)                         if(OrderStopLoss()<Bid-pips*TrailAmount)                            OrderModify(OrderTicket(),OrderOpenPrice(),Bid-(pips*TrailAmount),OrderTakeProfit(),0,CLR_NONE);          } //sell order section       for(int s=OrdersTotal()-1;s>=0;s--)               {          if(OrderSelect(s,SELECT_BY_POS,MODE_TRADES))             if(OrderMagicNumber()== MagicNumber)                if(OrderSymbol()==Symbol())                   if(OrderType()==OP_SELL)                      if(OrderOpenPrice()-Ask>WhenToTrail*pips)                         if((OrderStopLoss()>Ask+TrailAmount*pips) || (OrderStopLoss()==0))                            OrderModify(OrderTicket(),OrderOpenPrice(),Ask+(TrailAmount*pips),OrderTakeProfit(),0,CLR_NONE);          } }

Hi there,

So, I think I'm missing something in these 2 functions, because they both work like a charm for the BUY SECTIONS, but Absolutely nothing in the opposite direction.
I
'm a newbie coder by the way, so kindly pardon me if this may somewhat seem annoying to the more Experienced.

I would be eternally all the help I could get for this.

 

Hello every one

I am new programmer ea and I want put trailing stop in below code. I tried so many times but it's not work. where I put which code? I am very disappointing now! please help me. :(





extern string EA_Setting="                ------ EA Setting ------";

extern int Magic_Number=23519;

extern bool Enabel_ECN_Broker=false;


bool Enable_Reverse_Closing=true;

bool Enable_Multi_Trades=true;


extern string Trading_Setting="              ----- Tradeing Setting -----";

extern double LotSize=0.01;

extern int Distance_Buffer_Pips=10;

extern int TakeProfit_Pips=40;

extern int TrailingStop=100; // just I put here

extern int StopLoss_Pips=8;

extern int Slippage=9;



extern string Timer="              ----- Timer Setting -----";

extern bool Enable_Timer=false;

extern int Start_Trading_Hour=13;

extern int Start_Trading_Minute=30;

extern int End_Trading_Hour=13;

extern int End_Trading_Minute=30;






int Deal_With_Buy1=0;

double Buy_openprice1=0;

string Buy_Sym1="";

double Buy_Lot1=0;

double Buy_TP1=0;

double Buy_SL1=0;

int Deal_With_Sell1=0;

double Sell_openprice1=0;

string Sell_Sym1="";

double Sell_Lot1=0;

double Sell_TP1=0;

double Sell_SL1=0;

int Buy_Ticket1=0;

int Sell_Ticket1=0;

int Buy_To_Close1=0;

int Sell_To_Close1=0;

string Comm1=" ";


bool Enable_Closing_Comfirmation=true;

double ClosingArray[100];

int st=0;

double LastAsk=0;

double LastBid=0;

datetime LastBuy=0;

datetime LastSell=0;


int pip=1;


datetime startin_candle=0;


//+------------------------------------------------------------------+

//| expert initialization function                                   |

//+------------------------------------------------------------------+

int init()

{


}


//+------------------------------------------------------------------+

//| expert deinitialization function                                 |

//+------------------------------------------------------------------+

int deinit()

{


}




int start()

{

  int Go=1;

  

  

  if(startin_candle==0)

   startin_candle=Time[0];

  else

  {

   if(Time[0]>startin_candle)

    Go=1;

   else

    Go=0;

  }  

  

  if(IsTradeContextBusy()==true)

  {

   Go=-1;

   Comment("Trade Context is busy");

  }

  

  if((Deal_With_Buy1!=0 || Deal_With_Sell1!=0) && Go==1)

  {

   string report="Checking Opening Order request ...\n";

   if(Deal_With_Buy1!=0)   

    report=report+

    "Deal_With_Buy1:"+Deal_With_Buy1+"   Buy_Lot1:"+Buy_Lot1+"  Buy_openprice1:"+Buy_openprice1+"  Buy_SL1:"+Buy_SL1

    +"  Buy_TP1:"+Buy_TP1+"  Buy_Ticket1:"+Buy_Ticket1+"\n";


   if(Deal_With_Sell1!=0)   

    report=report+

    "Deal_With_Sell1:"+Deal_With_Sell1+"   Sell_Lot1:"+Sell_Lot1+"  Sell_openprice1:"+Sell_openprice1+"  Sell_SL1:"+Sell_SL1

    +"  Sell_TP1:"+Sell_TP1+"  Sell_Ticket1:"+Sell_Ticket1+"\n";

   Comment(report);

   Go=2;  

  }    

  



  if(Go==1)

  {   


   if(st==0)

   {

    st=1;    

   if(MarketInfo(Symbol(),MODE_DIGITS)==3 || MarketInfo(Symbol(),MODE_DIGITS)==5)

   {

    pip=10;    

    TakeProfit_Pips=TakeProfit_Pips*10;

    StopLoss_Pips=StopLoss_Pips*10;    

    Distance_Buffer_Pips=Distance_Buffer_Pips*10;

    Slippage=Slippage*10;         

   }

   }  

   

   

   int i=OrdersTotal()-1;   

   int found_Buy=0;

   int found_Sell=0;

   

   int AnyLive=0;

   

   for(i=OrdersTotal()-1;i>=0;i--)

   {

    OrderSelect(i,SELECT_BY_POS);

    if(OrderSymbol()==Symbol() && OrderMagicNumber()==Magic_Number && (OrderType()==OP_BUY || OrderType()==OP_SELL))

     AnyLive=1;

    if(OrderSymbol()==Symbol() && OrderMagicNumber()==Magic_Number && OrderOpenTime()>=Time[0])

    {

     if(OrderType()==OP_BUY || OrderType()==OP_BUYSTOP)   

      found_Buy=1;

     if(OrderType()==OP_SELL || OrderType()==OP_SELLSTOP)              

      found_Sell=1;      

    }

    if(OrderSymbol()==Symbol() && OrderMagicNumber()==Magic_Number && (OrderType()==OP_BUYSTOP || OrderType()==OP_SELLSTOP) && Time[0]>OrderOpenTime())

     OrderDelete(OrderTicket());

   }

  

    int Buy_Ok=0;

    int Sell_Ok=0;  

    if(found_Buy==0)

     Buy_Ok=1;

    if(found_Sell==0)

     Sell_Ok=1;

      




   int Time_Ok=0;

   if(Enable_Timer==true)

   {

    if(Start_Trading_Hour<End_Trading_Hour   ||  Start_Trading_Hour==End_Trading_Hour )

    {

     if(TimeHour(TimeLocal())==Start_Trading_Hour && TimeMinute(TimeLocal())>=Start_Trading_Minute)

      Time_Ok=1;

     

     if(TimeHour(TimeLocal())>Start_Trading_Hour && TimeHour(TimeLocal())<=End_Trading_Hour)

      Time_Ok=1;

     

     if(TimeHour(TimeLocal())>End_Trading_Hour  || (TimeHour(TimeLocal())==End_Trading_Hour && TimeMinute(TimeLocal())>End_Trading_Minute)  )

      Time_Ok=0;

    }

    if(Start_Trading_Hour>End_Trading_Hour)

    {

     if(TimeHour(TimeLocal())==Start_Trading_Hour && TimeMinute(TimeLocal())>=Start_Trading_Minute)

      Time_Ok=1;

     

     if(TimeHour(TimeLocal())>Start_Trading_Hour || TimeHour(TimeLocal())<=End_Trading_Hour)

      Time_Ok=1;

     

     if(TimeHour(TimeLocal())==End_Trading_Hour && TimeMinute(TimeLocal())>End_Trading_Minute)

      Time_Ok=0;

      

     if(TimeHour(TimeLocal())>End_Trading_Hour && TimeHour(TimeLocal())<Start_Trading_Hour)

      Time_Ok=0;           

    }

   }

   else

    Time_Ok=1;




  

  

   if(Time_Ok==1 && Buy_Ok==1 && Time[1]>LastBuy && AnyLive==0)

   {            

      Buy_Sym1=Symbol();   

      Buy_openprice1=NormalizeDouble(Bid+Distance_Buffer_Pips*Point,Digits);

      Buy_SL1=Buy_openprice1-(StopLoss_Pips*Point);

      Buy_TP1=Buy_openprice1+(TakeProfit_Pips*Point);              

      Buy_Lot1=LotSize;              

      if(MarketInfo(Symbol(),MODE_MINLOT)==0.01)

       Buy_Lot1=NormalizeDouble(Buy_Lot1,2);

      if(MarketInfo(Symbol(),MODE_MINLOT)==0.1)

       Buy_Lot1=NormalizeDouble(Buy_Lot1,1);              

      Comm1="EA- Buy Trade";

      Deal_With_Buy1=1;

      Buy_Ticket1=0;  

      Go=2;          

   }

   




   if(Time_Ok==1 && Sell_Ok==1 && Time[1]>LastSell && AnyLive==0)

   {           

       Sell_Sym1=Symbol();       

       Sell_openprice1=NormalizeDouble(Bid-Distance_Buffer_Pips*Point,Digits);      

       Sell_SL1=Sell_openprice1+(StopLoss_Pips*Point);

       Sell_TP1=Sell_openprice1-(TakeProfit_Pips*Point);          

       Sell_Lot1=LotSize;

       if(MarketInfo(Symbol(),MODE_MINLOT)==0.01)

        Sell_Lot1=NormalizeDouble(Sell_Lot1,2);

       if(MarketInfo(Symbol(),MODE_MINLOT)==0.1)

        Sell_Lot1=NormalizeDouble(Sell_Lot1,1);          

       Comm1="EA- Sell Trade";

       Deal_With_Sell1=1;

       Sell_Ticket1=0;  

       Go=2;                        

   }




   

  }



 if(Enable_Closing_Comfirmation==true)

 {

  int x=0;

  int AnyToClose=0;  

  for(x=0;x<100;x++)  

  {

   if(ClosingArray[x]!=0)

   {

    OrderSelect(ClosingArray[x],SELECT_BY_TICKET);

    if(OrderCloseTime()==0)

    {

     AnyToClose=1;

     if(OrderType()==OP_BUY)

      OrderClose(OrderTicket(),OrderLots(),NormalizeDouble(Bid,Digits),Slippage,Gold);

}

 if(TrailingStop>0)  

              {                 

               if(Bid-OrderOpenPrice()>MyPoint*TrailingStop)

                 {

                  if(OrderStopLoss()<Bid-MyPoint*TrailingStop)

                    {

                     OrderModify(OrderTicket(),OrderOpenPrice(),Bid-TrailingStop*MyPoint,OrderTakeProfit(),0,Green);

                     return(0);

                    }

                 }

              }

     if(OrderType()==OP_SELL)

      OrderClose(OrderTicket(),OrderLots(),NormalizeDouble(Ask,Digits),Slippage,Gold);

      }

       if(TrailingStop>0)  

              {                 

               if(Bid-OrderOpenPrice()>MyPoint*TrailingStop)

                 {

                  if(OrderStopLoss()<Bid-MyPoint*TrailingStop)

                    {

                     OrderModify(OrderTicket(),OrderOpenPrice(),Bid-TrailingStop*MyPoint,OrderTakeProfit(),0,Green);

                     return(0);

                    }

                 }

              }

     

     if(OrderType()!=OP_BUY && OrderType()!=OP_SELL)

      OrderDelete(OrderTicket());

    }

    else

     ClosingArray[x]=0;

     }

     

   }

   if(AnyToClose==0)

    ObjectDelete("Closing_Flag");

  }


  x=0;

  for(x=0;x<100;x++)  

  {

   if(ClosingArray[x]==0 && ClosingArray[x+1]!=0)

   {

    ClosingArray[x]=ClosingArray[x+1];

    ClosingArray[x+1]=0;

   }

  } 

 }

 

 

 

 

 

 

 if(Go==2)

{

if(Deal_With_Buy1==1)

{

 int k=OrdersTotal()-1;

 int counting=0;

 for(k=OrdersTotal()-1;k>=0;k--)

 {

  OrderSelect(k,SELECT_BY_POS);

  if(OrderTicket()==Buy_Ticket1)

  {

   Deal_With_Buy1=0;

   LastBuy=Time[1];

   counting=1;

   break;

  }

 }

 

 if(counting==0)

 {

      Buy_Sym1=Symbol();   

      Buy_openprice1=NormalizeDouble(Bid+Distance_Buffer_Pips*Point,Digits);

      Buy_SL1=Buy_openprice1-(StopLoss_Pips*Point);

      Buy_TP1=Buy_openprice1+(TakeProfit_Pips*Point);              

 

  if(Enabel_ECN_Broker==false)

  {

    Buy_Ticket1=OrderSend(Symbol(),OP_BUYSTOP,Buy_Lot1,Buy_openprice1,Slippage,Buy_SL1,Buy_TP1,Comm1,Magic_Number,0,Aqua);                 

  }

  if(Enabel_ECN_Broker==true)

  {   

    Buy_Ticket1=OrderSend(Symbol(),OP_BUYSTOP,Buy_Lot1,Buy_openprice1,Slippage,0,0,Comm1,Magic_Number,0,Aqua);    

                 

   if(Buy_Ticket1>0)

   {

    OrderSelect(Buy_Ticket1,SELECT_BY_TICKET);   

    if(OrderStopLoss()!=Buy_SL1 || OrderTakeProfit()!=Buy_TP1) 

     OrderModify(Buy_Ticket1,OrderOpenPrice(),Buy_SL1,Buy_TP1,0,Blue);

   }                

  }     }

            if(TrailingStop>0)  

              {                 

               if(Bid-OrderOpenPrice()>MyPoint*TrailingStop)

                 {

                  if(OrderStopLoss()<Bid-MyPoint*TrailingStop)

                    {

                     OrderModify(OrderTicket(),OrderOpenPrice(),Bid-TrailingStop*MyPoint,OrderTakeProfit(),0,Green);

                     return(0);

                    }

                 }

              }

           }

 }

}

if(Deal_With_Sell1==1)

{

 k=OrdersTotal()-1;

 counting=0;

 for(k=OrdersTotal()-1;k>=0;k--)

 {

  OrderSelect(k,SELECT_BY_POS);

  if(OrderTicket()==Sell_Ticket1)

  {

   Deal_With_Sell1=0;

   LastSell=Time[1];   

   counting=1;

   break;

  }

 }

 

 if(counting==0)

 {

       Sell_Sym1=Symbol();       

       Sell_openprice1=NormalizeDouble(Bid-Distance_Buffer_Pips*Point,Digits);      

       Sell_SL1=Sell_openprice1+(StopLoss_Pips*Point);

       Sell_TP1=Sell_openprice1-(TakeProfit_Pips*Point);          

 

  if(Enabel_ECN_Broker==false)

  {

    Sell_Ticket1=OrderSend(Symbol(),OP_SELLSTOP,Sell_Lot1,Sell_openprice1,Slippage,Sell_SL1,Sell_TP1,Comm1,Magic_Number,0,DeepPink);                  

  }

  if(Enabel_ECN_Broker==true)

  {   

    Sell_Ticket1=OrderSend(Symbol(),OP_SELLSTOP,Sell_Lot1,Sell_openprice1,Slippage,0,0,Comm1,Magic_Number,0,DeepPink);                  


   if(Sell_Ticket1>0)

   {

    OrderSelect(Sell_Ticket1,SELECT_BY_TICKET);   

    if(OrderStopLoss()!=Sell_SL1 || OrderTakeProfit()!=Sell_TP1) 

     OrderModify(Sell_Ticket1,OrderOpenPrice(),Sell_SL1,Sell_TP1,0,DeepPink);

   } 

   

                  

  }    

 }

}

}

   return(0);

  }

//+------------------------------------------------------------------+

 

Please edit your post and use the code button (Alt+S) to paste code

Also remove unnecessary white space to make it easier for others to read.

 

Hey I have this code but need to include 2 options for Break Even once the current position/s are in profits let's say "x" amount of pips and also take partials or do just a trailing stop to BE+ X amounts of pips.


Any help is realy appreciated:

//+------------------------------------------------------------------+
//|                                                      buysell.mq4 |
//|                                                        @VALENPTY |
//|                                                                . |
//+------------------------------------------------------------------+
#property copyright "@VALENPTY"
#property link      "."
#property version   "1.00"
#property strict
input double lots = 1.00;
input double riesgo = 650;
input double benef = 2500;
input double offsetpips = 350;
input int magic = 12321;
 


//  [] 
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
   
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function    []                             |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
   
  }
  bool venta(){
  
  double MH1 = iHigh(NULL,PERIOD_MN1,1);
  double MH2 = iHigh(NULL,PERIOD_MN1,2);
  double MH3 = iHigh(NULL,PERIOD_MN1,3);
  double ML1 = iLow(NULL,PERIOD_MN1,1);
  double ML2 = iLow(NULL,PERIOD_MN1,2);
  double ML3 = iLow(NULL,PERIOD_MN1,3);
 ;
  
 if(Low[0]<ML1 && High[0]>MH3)
         {
         return true;
         }
     else if (Low[0]<ML1 && High[0]<MH1)
         {
         return true;
         }   
         else{
         return false;
         
  }
  }
  
  bool compra(){
  
  double MH1 = iHigh(NULL,PERIOD_MN1,1);
  double MH2 = iHigh(NULL,PERIOD_MN1,2);
  double MH3 = iHigh(NULL,PERIOD_MN1,3);
  double ML1 = iLow(NULL,PERIOD_MN1,1);
  double ML2 = iLow(NULL,PERIOD_MN1,2);
  double ML3 = iLow(NULL,PERIOD_MN1,3);
                                                // para copiar -- [0]  --
  if(Low[0]<ML3 && High[0]>MH1)
         {
         return true;
         }
     else if (Low[0]>ML1 && High[0]>MH1)
         {
         return true;
         }   
         else{
         return false;
         
  }
  }
//+------------------------------------------------------------------+
//| Expert tick function          []                                   |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   bool trade = true;
   for(int i=0;i<OrdersTotal();i++){
      int open_order = OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
      if (OrderSymbol()==Symbol() && OrderMagicNumber()==magic){
         trade = false;
         }
      }
      if(trade==true) 
            {
            if(compra()==true) 
               int open_short = OrderSend(NULL,OP_SELL,lots,Bid,3,Bid+riesgo*_Point,Bid-benef*_Point,"venta",magic,0,clrGreen);
                          
               else if (venta()==true){
               int open_long = OrderSend(NULL,OP_BUY,lots,Ask,3,Ask-riesgo*_Point,Ask+benef*_Point,"compra",magic,0,clrGreen); 
                                                     
                                 
        }
            }
            }
   
  
//+-----------------------------[]-------------------------------------+
Reason: