Move to break even once takeprofit() is hit?

 

I am switching from partially closing on position to actually placing 4 positions with fixed take profit targets.

 I had the hassle of working out how to partially close a position just the once. Now I am stuck with moving all the trades to break even one the first trade hits its fixed profit target.

 If I do something like "if( bid - FirstProfitTarget > Point / 2. )"  it obviously wouldn't work because the trade will always be closed first and then the for loop has nothing to work on meaning it wouldn't move others to break even.

 There has to be a damn easy way I just don't know. Maybe I can do it by looking through previously closed trades?

 Can anyone advise me on the easiest way to do this...

 

Thanks! 

 
//+------------------------------------------------------------------+
//|Moving trade to break even                                        |
//+------------------------------------------------------------------+
void Move_To_BreakEven()
{

int PositionIndex; 
int TotalNumberOfOrders;
TotalNumberOfOrders  = OrdersTotal();

for(PositionIndex = TotalNumberOfOrders - 1; PositionIndex >= 0 ; PositionIndex --) 
  {  
   if( ! OrderSelect(PositionIndex, SELECT_BY_POS, MODE_HISTORY)  ) continue;
     if( OrderMagicNumber() == MagicNumber || OrderMagicNumber() == MagicNumber2 ||  OrderMagicNumber() == MagicNumber3 )   
      if ( OrderSymbol() == Symbol() )       
         {
         RefreshRates();
 
          if( OrderType()== OP_BUY )
            {
                    if((OrderOpenPrice() + (PipsToLockIn*pips)) - OrderOpenPrice() > Point / 2. ) 
                    if(OrderStopLoss() - (OrderOpenPrice() + (PipsToLockIn*pips)) > Point / 2. )break;
                    {
                    Buy_StopLoss_Break_Even = OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice()+(PipsToLockIn*pips),OrderTakeProfit(),0,CLR_NONE);   
                    if(Buy_StopLoss_Break_Even!=True)Print("BUY B/E Stop Loss Failed: ", GetLastError(), " On: ", OrderSymbol());
                    } 
                                 
            }
           
           if( OrderType()== OP_SELL )
           
            {
                   if(OrderStopLoss() - (OrderOpenPrice() - (PipsToLockIn*pips)) > Point / 2. )
                    if(OrderOpenPrice()-(PipsToLockIn*pips) - OrderStopLoss() > Point / 2. )break;
                    { 
                    Sell_StopLoss_Break_Even = OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice()-(PipsToLockIn*pips),OrderTakeProfit(),0,CLR_NONE);
                    if(Sell_StopLoss_Break_Even!=True)Print("SELL B/E Stop Loss Failed: ", GetLastError(), " On: ", OrderSymbol());
                    
                    }
            }
        }
  }
}
I'm currently using this. I want to be able to move "MagicNumber 2" and "MagicNumber3" to break even once "MagicNumber" hits and closes out at that takeprofit target. Anyone push me in the right direction?
 
Could it be done by comparing OrderOpenTime() of current selected orders with the one in the history, and if they match, then move to break even if applicable on the remaining two open positions???? Would that work?
 

Isn't

  if((OrderOpenPrice() + (PipsToLockIn*pips)) - OrderOpenPrice() > Point / 2. ) 

 just the same as

  if(PipsToLockIn*pips > Point / 2. ) 

 ?

You are selecting orders from OrdersHistory ie closed trades.

if( ! OrderSelect(PositionIndex, SELECT_BY_POS, MODE_HISTORY)  ) continue;

 

You cannot modify closed trades. 

 
DomGilberto:

. Now I am stuck with moving all the trades to break even one the first trade hits its fixed profit target.

 

You know the level of the first trade's TP

Use that level to move the other trades to break-even 

 
//+------------------------------------------------------------------+
//|Moving trade to break even                                        |
//+------------------------------------------------------------------+
void Move_To_BreakEven()
{

int PositionIndex; 
int TotalNumberOfOrders;
TotalNumberOfOrders  = OrdersTotal();

static int Selected_Trade_1;
static int Selected_Trade_2;

for(PositionIndex = TotalNumberOfOrders - 1; PositionIndex >= 0 ; PositionIndex --) 
  {  
   if( ! OrderSelect(PositionIndex, SELECT_BY_POS, MODE_TRADES)  ) continue;
     if( OrderMagicNumber() == MagicNumber1 || OrderMagicNumber() == MagicNumber2 || OrderMagicNumber() == MagicNumber3)   
      if ( OrderSymbol() == Symbol() )       
         {
         RefreshRates();
         
         if( OrderMagicNumber() == MagicNumber2 )
            {
            Selected_Trade_1 = OrderTicket();
            Print("MagicNumber2 is OrderTicket(): ", Selected_Trade_1);
            }

         if( OrderMagicNumber() == MagicNumber3 )
            {
            Selected_Trade_2 = OrderTicket();
            Print("MagicNumber3 is OrderTicket(): ", Selected_Trade_2);
            }        

    
         if( OrderType() == OP_BUY && OrderMagicNumber() == MagicNumber1 )
         {        
           btp1 = OrderTakeProfit();
           Print("btp1 = ", btp1);
         }
         
          if( OrderType()== OP_BUY && Bid - btp1 > Point / 2. )
            {
                    
                    
                    
                    if(OrderStopLoss() - (OrderOpenPrice() + (PipsToLockIn*pips)) > Point / 2. )break;
                    if((OrderOpenPrice() + (PipsToLockIn*pips)) - OrderOpenPrice() > Point / 2. ) 
                    {
                    Buy_StopLoss_Break_Even1 = OrderModify(Selected_Trade_1,OrderOpenPrice(),OrderOpenPrice()+(PipsToLockIn*pips),OrderTakeProfit(),0,CLR_NONE);
                    Buy_StopLoss_Break_Even2= OrderModify(Selected_Trade_2,OrderOpenPrice(),OrderOpenPrice()+(PipsToLockIn*pips),OrderTakeProfit(),0,CLR_NONE);
                    
                    if(Buy_StopLoss_Break_Even1 == True)Print("BUY B/E was successful");  
                    if(Buy_StopLoss_Break_Even1 != True)Print("BUY B/E Stop Loss Failed. Error Code: ", GetLastError(), " On: ", OrderSymbol());
                    } 
                                 
            }
...
Is this the most effective way of doing it? I am still getting OrderModify error 1 for some reason? Anyone help? I am calling it like this (below) on the OnTick function below

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
  
   if(IsNewCandle())
      {
      CheckForMaTrade();//signals, deletions and candle trails only need checked on a new candle.
      }
    
   if( OpenOrdersThisPair(Symbol()) > 0 )
     { 
      
      MA_Trail();
     
      int PositionIndex; 
      int TotalNumberOfOrders;
      TotalNumberOfOrders  = OrdersTotal();

      for(PositionIndex = TotalNumberOfOrders - 1; PositionIndex >= 0 ; PositionIndex --) 
         {  
         if( ! OrderSelect(PositionIndex, SELECT_BY_POS, MODE_TRADES)  ) continue;
            if( OrderMagicNumber() == MagicNumber1 || OrderMagicNumber() == MagicNumber2 || OrderMagicNumber() == MagicNumber3)   
               if ( OrderSymbol() == Symbol() ) 
     
                     {
                     
                     if( OrderType() == OP_BUY && (OrderOpenPrice() + (PipsToLockIn*pips)) - OrderStopLoss() > Point / 2. )
                        {   
                        Move_To_BreakEven();
                        }
                     
                     if( OrderType() == OP_SELL && OrderStopLoss() - (OrderOpenPrice() - (PipsToLockIn*pips)) > Point / 2. )
                        {   
                        Move_To_BreakEven();
                        }
                     
                     }
                     
          } 
       
      }
 }
 

Do you mean

if( OrderType() == OP_BUY && (OrderOpenPrice() + (PipsToLockIn*pips)) - OrderStopLoss() > Point / 2. )

 or this?

if( OrderType() == OP_BUY && (OrderOpenPrice() + (PipsToLockIn*pips) - OrderStopLoss() > Point / 2. ))

 or maybe even

if( OrderType() == OP_BUY && MathAbs(OrderOpenPrice() + PipsToLockIn*pips - OrderStopLoss()) > Point / 2. )

 

 

Did you see my earlier post? If so, what is this supposed to do?

if((OrderOpenPrice() + (PipsToLockIn*pips)) - OrderOpenPrice() > Point / 2. ) 

 

 I assume that btp1 is global scope

Why not declare it globally with the value 0, then

if( btp1 ==0 )
      {
      //Code to check for order with Magic number 1 and assign OrderTakeProfit() value to btp1 
      }

 

 

When the 3 trades are first opened

the loop in your main code will call the Move_To_BreakEven()  function 3 times per tick  -  Why?

 

  
 if((OrderOpenPrice() + (PipsToLockIn*pips)) - OrderOpenPrice() > Point / 2. ) 
   {
   Buy_StopLoss_Break_Even1 = OrderModify(Selected_Trade_1,OrderOpenPrice(),OrderOpenPrice()
                              +(PipsToLockIn*pips),OrderTakeProfit(),0,CLR_NONE);
   Buy_StopLoss_Break_Even2= OrderModify(Selected_Trade_2,OrderOpenPrice(),OrderOpenPrice()
                             +(PipsToLockIn*pips),OrderTakeProfit(),0,CLR_NONE);
                    
   if(Buy_StopLoss_Break_Even1 == True)Print("BUY B/E was successful");  
   if(Buy_StopLoss_Break_Even1 != True)Print("BUY B/E Stop Loss Failed. Error Code: ", GetLastError(),
                                             " On: ", OrderSymbol());
   } 

 

  in the above code you are trying to modify 2 orders, but only 1 order is selected in the loop. The next cycle, another order will be selected and the code will try to modify the same 2 trades

 
I'm pulling my hair out here. Can anyone shed some light on this OrderModify Error 1? All trades move to break-even but I don't know why I am still seeing this damn error?

//+----------------------------------------------------------------------------------------------------------------------------------------+
// Move to break even function  
//+----------------------------------------------------------------------------------------------------------------------------------------+ 

void Move_To_BreakEven()
  {
   
   for(int b=OrdersTotal()-1; b>=0; b--)
     {
      if( !OrderSelect(b,SELECT_BY_POS,MODE_TRADES))continue;
         if( OrderMagicNumber()== MagicNumber1 || OrderMagicNumber()== MagicNumber2 || OrderMagicNumber()== MagicNumber3 || OrderMagicNumber()== MagicNumber4 )
            if(OrderSymbol() == Symbol())
             {            
               

               if( OrderType() == OP_BUY && (OrderOpenPrice() + (PipsToLockIn*pips)) > OrderStopLoss() - Point ) 
               {     
                   if(OrderMagicNumber() == MagicNumber1 )TakeProfit_1 = NormalizeDouble(OrderTakeProfit(), Digits);
                   
                   if( OrderStopLoss() > (OrderOpenPrice() + (PipsToLockIn*pips)) - Point )break;  
                   if( Bid - TakeProfit_1 > Point / 2. )
                   {
                  
                     Buy_StopLoss_Break_Even1 = OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice()+(PipsToLockIn*pips),OrderTakeProfit(),0,CLR_NONE);  
                     
                     if(Buy_StopLoss_Break_Even1 == True)Print("BUY B/E was successful. Order ticket was: ", OrderTicket()); 
                     if(Buy_StopLoss_Break_Even1 != True)Print("BUY B/E Stop Loss Failed: ", GetLastError(), " On: ", OrderSymbol());
                   } 
               }    
               
 
               if( OrderType() == OP_SELL && OrderStopLoss() > (OrderOpenPrice()-(PipsToLockIn*pips))  - Point  )     
               { 
                  if( OrderMagicNumber() == MagicNumber1 )TakeProfit_1 = NormalizeDouble(OrderTakeProfit(), Digits);
                  
                  if((OrderOpenPrice()-(PipsToLockIn*pips)) > OrderStopLoss() - Point )break;
                  if( TakeProfit_1 - Ask > Point / 2. ) 
                  { 

                   Sell_StopLoss_Break_Even1 = OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice()-(PipsToLockIn*pips),OrderTakeProfit(),0,CLR_NONE);
                   
                   if(Sell_StopLoss_Break_Even1 == True)Print("SELL B/E was successful. Order ticket was:", OrderTicket());
                   if(Sell_StopLoss_Break_Even1 != True)Print("SELL B/E Stop Loss Failed: ", GetLastError(), " On: ", OrderSymbol());             
                  }    
               }
      
            }
    
    }
   
}

...

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
 {
  
   if(IsNewCandle())
      {
      CheckForMaTrade();
      Trade_Calibration();
      }
      
   if( OpenOrdersThisPair(Symbol()) > 0 )
      {
      MA_Trail();
      Move_To_BreakEven(); // <<<<<<<<<<<<
      }         
 }
 
DomGilberto: I'm pulling my hair out here. Can anyone shed some light on this OrderModify Error 1? All trades move to break-even but I don't know why I am still seeing this damn error?
  1. You
    Server
    Change the SL to X
    It is at X!
    Change the SL to XIt is at X!
    Change the SL to XYou are insane
  2. if( OrderStopLoss() > (OrderOpenPrice() + (PipsToLockIn*pips)) - Point )break;
    :
    Buy_StopLoss_Break_Even1 = OrderModify(OrderTicket(), OrderOpenPrice(), OrderOpenPrice()+(PipsToLockIn*pips), OrderTakeProfit(), 0, CLR_NONE);
    First you test if the SL is above your new value (X,) and when it's not you set it to that value. How can the SL ever be above?
  3. Don't repeat code. Test if you need to move it. Not if you already have.
    double newSL = OrderOpenPrice() + PipsToLockIn * pips;
    if( OrderStopLoss() < newSL - Point ){
      Buy_StopLoss_Break_Even1 = OrderModify(OrderTicket(), OrderOpenPrice(), newSL, OrderTakeProfit(), 0, CLR_NONE); 
  4. Use meaningful names. "Buy StopLoss Break Even" is meaningless. Could be a price, could be a signal. DidModify or isModifyOK would be more understandable. Why use a variable at all, just if( !OrderModify(...){ ... } Then had you printing out your variables (including OOP(), OSL() and newSL you would have found your answer.
  5. Are your books one column but two feet wide? No because that is unreadable. They are 6 inches, sometimes two columns, so you can read it easily. So should be your code. I'm not going to go scrolling back and forth trying to read it. Format your code so you can read it.
 
WHRoeder:
  1. You
    Server
    Change the SL to X
    It is at X!
    Change the SL to XIt is at X!
    Change the SL to XYou are insane
  2. if( OrderStopLoss() > (OrderOpenPrice() + (PipsToLockIn*pips)) - Point )break;
    :
    Buy_StopLoss_Break_Even1 = OrderModify(OrderTicket(), OrderOpenPrice(), OrderOpenPrice()+(PipsToLockIn*pips), OrderTakeProfit(), 0, CLR_NONE);
    First you test if the SL is above your new value (X,) and when it's not you set it to that value. How can the SL ever be above?
  3. Don't repeat code. Test if you need to move it. Not if you already have.
  4. Use meaningful names. "Buy StopLoss Break Even" is meaningless. Could be a price, could be a signal. DidModify or isModifyOK would be more understandable. Why use a variable at all, just if( !OrderModify(...){ ... } Then had you printing out your variables (including OOP(), OSL() and newSL you would have found your answer.
  5. Are your books one column but two feet wide? No because that is unreadable. They are 6 inches, sometimes two columns, so you can read it easily. So should be your code. I'm not going to go scrolling back and forth trying to read it. Format your code so you can read it.

Thank you kindly for your input. The SL can be above the OrderOpenPrice() because:

  1. it's either been put their by the constant trailing stop and the first target has not been hit yet (as the first "TakeProfit1" holds the first OrderTakeProfit() price and when Bid or Ask is > = than TakeProfit1 - it triggers the OrderModify())
  2. The "Buy_StopLoss_Break_Even1" OrderModify has put the stop there..

My logic was to break the loop and not bother using OrderModify if this was the case and avoid any errors. Apparently not though!

I will definitely try to compact down my code so that it is easier to read. All the small nuances of coding practices are still to be learned (and the actual coding itself! :P)

I have taken aboard what you are explaining above but I am still receiving OrderModify error 1. The OrderModify is only supposed to modify 3 of the 4 remaining trades that are open due to the OrderTakeProfit() of the first target being reached by either Bid or Ask. This void function below gets called on every tick if there are > 0 OrdersOpenThisPair.

Here's the revised code. Correct me if I still am not understanding about the book column reference you made...

UPDATE: Ok, so this is infact not returning OrderModify error 1, instead it is returning OrderModify Error 130 (Invalid Stops).... My Trailing Void is returning OrderModify error 1 (but I will look into that later).

//+----------------------------------------------------------------------------------
// Move to break even function  
//+----------------------------------------------------------------------------------

void Move_To_BreakEven()
{
  
for(int b=OrdersTotal()-1; b>=0; b--)
  {
  if( !OrderSelect(b,SELECT_BY_POS,MODE_TRADES))continue;
   if( OrderMagicNumber()== MagicNumber1 || OrderMagicNumber()== MagicNumber2 
      || OrderMagicNumber()== MagicNumber3 || OrderMagicNumber()== MagicNumber4 )
     if(OrderSymbol() == Symbol())
      { 
                   
      double new_sell_SL = OrderOpenPrice()-(PipsToLockIn*pips);
      double new_buy_SL  = OrderOpenPrice()+(PipsToLockIn*pips);

      if(OrderType() == OP_BUY && 
        (OrderOpenPrice() + (PipsToLockIn*pips)) > OrderStopLoss() - Point ) 
        {     
        if(OrderMagicNumber() == MagicNumber1 ){
          TakeProfit_1 = NormalizeDouble(OrderTakeProfit(), Digits);}
                    
        if( Bid - TakeProfit_1 > Point / 2. && OrderStopLoss() < new_buy_SL )
          {
          Buy_StopLoss_Break_Even1 = OrderModify(OrderTicket(),OrderOpenPrice(),new_buy_SL,OrderTakeProfit(),0,CLR_NONE);  
          if(Buy_StopLoss_Break_Even1 == True)Print("BUY B/E was successful. Order ticket was: ", OrderTicket()); 
          if(Buy_StopLoss_Break_Even1 != True)Print("BUY B/E Stop Loss Failed: ", GetLastError(), " On: ", OrderSymbol());
          } 
        }    
               
   if(OrderType() == OP_SELL && 
       OrderStopLoss() > (OrderOpenPrice()-(PipsToLockIn*pips))  - Point  )     
      { 
      if(OrderMagicNumber() == MagicNumber1 ){
      TakeProfit_1 = NormalizeDouble(OrderTakeProfit(), Digits);}
                  
    if( TakeProfit_1 - Ask > Point / 2. && OrderStopLoss() > new_sell_SL ) 
       { 
       Sell_StopLoss_Break_Even1 = OrderModify(OrderTicket(),OrderOpenPrice(),new_sell_SL,OrderTakeProfit(),0,CLR_NONE);
       if(Sell_StopLoss_Break_Even1 == True)Print("SELL B/E was successful. Order ticket was:", OrderTicket());
       if(Sell_StopLoss_Break_Even1 != True)Print("SELL B/E Stop Loss Failed: ", GetLastError(), " On: ", OrderSymbol());             
       }    
      }
    }
  }   
}