Simple code needed for EA (modify two open orders) - page 3

 

Basically I set two pending orders at a specific time, specifically 23:00 GMT+2 I think. One of the pending orders as a sell stop and the other is a buy stop, both the orders are an equal distance away from the open from the 23:00 candle, in this case 14 pips. Both have a TakeProfit of 28 pips (in this case) and a StopLoss of 55 pips.

Now when both the orders are fulfilled (essentially going both up and down 14 pips from the open price at the 23:00 candle before the orders expire), I want both the orders to have their take profits increased by, for example, 20 pips. So their new take profit is 58 pips in this case. The stop loss however should be kept the same throughout. Essentially what I'm trying to do is some sort of a hedging thing.

If two trades are open then it's likely the price will go in one direction quite a bit, enough to cancel out any losses if the take profits of both trades are increased. To get any profit only one trade would open and reach the take profit or both trades open and hit the take profits without going far in one direction.

I hope this is clear, if it's not I'll provide a picture which should be clearer.

 
WHRoeder:

I was referring to your directly previous post

madmax3 2012.03.09 14:52
Here is the revised code for the whole EA:
Which still shows the problems I stated.
That part of the code is for another part of the EA I believe, the part which opens the pending orders, would that have any effect at all on the part I'm trying to fix? Sorry, I think I have confused parts of the code especially in the original post. I have however, done what you have stated to the part of the code that I specifically need it for.
 
madmax3:

I hope this is clear, if it's not I'll provide a picture which should be clearer.

It's clear, thank you.

So you just want to modify these orders once . . . then the answer is simple. You need to check the 23:00 bar and determine the TPs at which the orders should have been opened . . . if the orders are at the same TP then they need modifying, if they are not at the same TP then they have been modified already and do not need to be modified again . . . simple.

 
RaptorUK:

It's clear, thank you.

So you just want to modify these orders once . . . then the answer is simple. You need to check the 23:00 bar and determine the TPs at which the orders should have been opened . . . if the orders are at the same TP then they need modifying, if they are not at the same TP then they have been modified already and do not need to be modified again . . . simple.

The modifying and checking should only happen when there are two trades open though, how would I go about doing this? Should I add to the code I already have or start again?

So essentially, if there are two trades (same symbol and magic number) the EA should check the take profits of the open trades compared to the previously existing pending orders (which are now executed) and then if they are the same, it should be changed, and once it loops it will check again and find that they are not the same and thus will not further modify the trades?
 
madmax3:
1. The modifying and checking should only happen when there are two trades open though, how would I go about doing this? Should I add to the code I already have or start again?

2. So essentially, if there are two trades (same symbol and magic number) the EA should check the take profits of the open trades compared to the previously existing pending orders (which are now executed) and then if they are the same, it should be changed, and once it loops it will check again and find that they are not the same and thus will not further modify the trades?

1. Loop through the open orders, check the symbol, the magic number, when you have a match that is not a pending order type increment a counter . . . when you get through checking the orders if you have counted 2 then you have 2 open orders for the correct symbol and magic number . . . . so now you can modify them . . . see 2.

2. No, you can't see the TP of the pending orders if they have been activated and are now no longer pending. The EA should check the 23:00 bar and work out what the original TPs would have been . . . then compare these to the TPs of the 2 open orders . . . . from this information the decision can be made to modify or not to modify.

 
RaptorUK:

1. Loop through the open orders, check the symbol, the magic number, when you have a match that is not a pending order type increment a counter . . . when you get through checking the orders if you have counted 2 then you have 2 open orders for the correct symbol and magic number . . . . so now you can modify them . . . see 2.

2. No, you can't see the TP of the pending orders if they have been activated and are now no longer pending. The EA should check the 23:00 bar and work out what the original TPs would have been . . . then compare these to the TPs of the 2 open orders . . . . from this information the decision can be made to modify or not to modify.

Ah I see, I believe this is what I've been trying to do all along. So far one of the orders is modified (specifically the buy one which is order 2 in my testing) but it keeps on getting modified, do I use 'break' to stop it from repeating it? Also how do I count and only modify the open orders when and only there are two of them open? I've been trying to use OrdersTotal() for this but it's not working out, I don't think I'd need to make two separate pieces of code for each order right?
Only the even numbered open orders are being modified and like I said they repeatedly get modified, I've tried various combinations for OrderSelect() but I still can't figure it out, like I said I'm a total noob at MQL and this EA is very nearly done so I would like to just finish it. I've read this https://book.mql4.com/trading/ordermodify would this have anything to do with my situation? It's for a stop loss but I need it for a take profit essentially.

What am I doing wrong here?

     for(int iPos = OrdersTotal()-1; iPos >= 1 ; iPos--) if (
        OrderSelect(iPos, SELECT_BY_POS)                    // Only my orders w/
    &&  OrderMagicNumber()  == MagicNumber                 // my magic number
    &&  OrderSymbol()       == "EURUSD"                // and my pair.
    && (OrderType() == OP_BUY)
    ){OrderModify(OrderTicket(),OrderOpenPrice(),OrderStopLoss(),Ask+((TakeProfit+20)*Point),0,Blue);}
    return(0);
    
  if (
        OrderSelect(iPos-1, SELECT_BY_POS-1)                    
    &&  OrderMagicNumber()  == MagicNumber                
    &&  OrderSymbol()       == "EURUSD"                
    && (OrderType() == OP_SELL)
    ){OrderModify(OrderTicket(),OrderOpenPrice(),OrderStopLoss(),Ask+((TakeProfit-20)*Point),0,Blue);}
return(0);
  }

How would I go about checking if the TP is the same as the 23:00 candle? Would it be necessary as such, since so long as the open orders are modified when 2 of them are there it would achieve the same effect? Or is this just to stop the order continuously getting modified and yes I have checked the documentation.

Thanks,

madmax3

 

Your return(0) is taking you out of start() before the 2nd order is modified.

All you are doing is selecting the Order by position, checking it has the correct Magic number, checking it is the correct symbol and the checking it is OP_BUY . . . . then you modify it, where are you determining if it has or has not been modified already ?

You EA has to be able to recover from being interrupted . .. if your orders get placed and MT4 crashes it has to be able to pick up from where it left off when it is restarted.

This is why you need to determine if the Order has already been modified or needs to be modified . . . how ?

"I set two pending orders at a specific time, specifically 23:00 GMT+2 I think. One of the pending orders as a sell stop and the other is a buy stop, both the orders are an equal distance away from the open from the 23:00 candle, in this case 14 pips. Both have a TakeProfit of 28 pips (in this case) and a StopLoss of 55 pips."

You can calculate where the original TP was by reference to the 23:00 candle, check the order and see if it still set to the original TP, if it is then it can be modified . . . if not then it has already been modified so don't modify it again.

There are other ways of logging that the order has been modified, keep track of the ticket number write the info to a file when it has been modified, when you are about to modify it again open the file and check for the ticket number, etc . . . I think checking vs the original TP is much simpler.

 

So far I have this,

//+------------------------------------------------------------------+
//|                                                  TimeBasedEA.mq4 |
//|                      Copyright © 2008, MetaQuotes Software Corp. |
//|                                       http://www.metaquotes.net/ |
//+------------------------------------------------------------------+
//changed by:       "forex4capital@yahoo.ca"
//changed again by: madmax3

// Time frame: M5 and higher

extern int     MagicNumber = 20080122;
extern double DistancefromAsk;
extern double DistancefromBid;
extern double  TakeProfit  = 28;
extern double  StopLoss    = 55;
extern double  Lots        = 0.1;
extern int     StartHour   = 2300;      // Open Trade time
extern bool    OpenBuy     = true;
extern bool    OpenSell    = true;
extern int     NumBuys     = 1;
extern int     NumSells    = 1;
extern int     Slippage    = 2;

//+------------------------------------------------------------------+
//|                        S T A R T                                 |
//+------------------------------------------------------------------+
int start()
  {
   int cnt, ticket, total;
      if (TimeDayOfWeek(TimeCurrent())==5 && TimeCurrent()>=StrToTime("22:59")) { CloseAll(); return(0); }
   int ct;
//-------------------------------------+
   if(Bars<100)
     {
      Print("bars less than 100");
      return(0);  
     }
//-------------------------------------+

//-------------------------------------+
   if(TakeProfit<10)
     {
      Print("TakeProfit less than 10");
      return(0);  // check TakeProfit
     }
//-------------------------------------+

   ct = Hour() * 100 + Minute();
   total=OrdersTotal();
   if(total<1) 
     {
      // no opened orders identified
      if(AccountFreeMargin()<(1000*Lots))
        {
         Print("We have no money. Free Margin = ", AccountFreeMargin());
         return(0);  
        }
      // check for long position (BUY) possibility
      if(ct == StartHour && Close[1]>Open[1] && OpenBuy)
      //if(ct == StartHour && High[1]<Open[0] && OpenBuy)
        {
         for ( cnt = 0; cnt < NumBuys; cnt++)
         {
           ticket=OrderSend(Symbol(),OP_BUYSTOP,Lots,Ask+(DistancefromAsk*Point),Slippage,Bid-(StopLoss*Point),Ask+(TakeProfit*Point),"",MagicNumber,TimeCurrent()+39600,CLR_NONE);
           ticket=OrderSend(Symbol(),OP_SELLSTOP,Lots,Bid-(DistancefromBid*Point),Slippage,Ask+(StopLoss*Point),Bid-(TakeProfit*Point),"",MagicNumber,TimeCurrent()+39600,CLR_NONE); 
           if(ticket>0)
           {
            if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) Print("BUY order opened : ",OrderOpenPrice());
           }

          
           else Print("Error opening BUY order : ",GetLastError()); 
           

         }
         return; 
        }
      // check for short position (SELL) possibility
      if(ct == StartHour && Close[1]<Open[1] && OpenSell)
      //if(ct == StartHour && Low[1]>Open[0] && OpenSell)
        {
         for ( cnt = 0; cnt < NumSells; cnt++)
         {
           ticket=OrderSend(Symbol(),OP_SELLSTOP,Lots,Bid-(DistancefromAsk*Point),Slippage,Ask+(StopLoss*Point),Bid-(TakeProfit*Point),"",MagicNumber,TimeCurrent()+39600,CLR_NONE);
           ticket=OrderSend(Symbol(),OP_BUYSTOP,Lots,Ask+(DistancefromBid*Point),Slippage,Bid-(StopLoss*Point),Ask+(TakeProfit*Point),"",MagicNumber,TimeCurrent()+39600,CLR_NONE);
           if(ticket>0)
           {
            if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) Print("SELL order opened : ",OrderOpenPrice());
           }
           else Print("Error opening SELL order : ",GetLastError());
         } 
         return; 
        
    
}
//---------------------------------------------------------------

 int Handle,                         // File descriptor
   Qnt_Symb;                           // Number of recorded symbols
   string File_Name="check.csv";        // File name
   
    Handle=FileOpen(File_Name,FILE_CSV|FILE_WRITE|FILE_READ,";");//File opening
   

         FileWrite(Handle,"Ticket","Magic","OTime","Type","Lots","Symbol","OPrice","S/L","T/P"); 
         
          for(int iPos = OrdersTotal()-1; iPos >= 1 ; iPos--)
      {       
       OrderSelect(iPos,SELECT_BY_POS) ;
       FileWrite(
         Handle,
         OrderTicket(),                //int
         OrderMagicNumber(),           //int
         TimeToStr(OrderOpenTime()),   //datetime
         
         OrderLots(),                  //double
         OrderSymbol(),                //string
         OrderOpenPrice(),             //double
         OrderStopLoss(),              //double
         OrderTakeProfit(),            //double
         TimeToStr(OrderCloseTime())  //int
       
        ) ; //end file write
           }   }
           
}
//---------------------------------------------------------------   
 
     
     
  void CloseAll()
{
   for(int cnt=OrdersTotal()-1;cnt>=0;cnt--)
   {
      OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
      if (OrderMagicNumber()!=MagicNumber) continue;
         
      //
      //
      //
      //
      //
         
      if (OrderType()==OP_BUY || OrderType()==OP_SELL)
      {
         for(int c=0; c<3; c++)
         {
            RefreshRates();
            if (OrderType()==OP_BUY)
                  { double cp = Bid;}  
            else  {        cp = Ask;}
               
            OrderClose(OrderTicket(),OrderLots(),cp,0,Yellow);
               int err=GetLastError();
               if(err==4 || err==136 || err==137 || err==138 || err==146)
               {
                  Sleep(5000); continue;
               }  
               break;                     
         }
         break;
      }
      }
      }
   
// the end.

The file writing code as included in above is,

//---------------------------------------------------------------

 int Handle,                         // File descriptor
   Qnt_Symb;                           // Number of recorded symbols
   string File_Name="check.csv";        // File name
   
    Handle=FileOpen(File_Name,FILE_CSV|FILE_WRITE|FILE_READ,";");//File opening
   

         FileWrite(Handle,"Ticket","Magic","OTime","Type","Lots","Symbol","OPrice","S/L","T/P"); 
         
          for(int iPos = OrdersTotal()-1; iPos >= 1 ; iPos--)
      {       
       OrderSelect(iPos,SELECT_BY_POS) ;
       FileWrite(
         Handle,
         OrderTicket(),                //int
         OrderMagicNumber(),           //int
         TimeToStr(OrderOpenTime()),   //datetime
         
         OrderLots(),                  //double
         OrderSymbol(),                //string
         OrderOpenPrice(),             //double
         OrderStopLoss(),              //double
         OrderTakeProfit(),            //double
         TimeToStr(OrderCloseTime())  //int
       
        ) ; //end file write
          	FileClose(Handle); }   }
           
}
//---------------------------------------------------------------   

I'm getting these errors though,

2012.04.04 15:30:06 2012.01.16 06:25 TimeBasedEA Version 2: FileOpen - too many opened files

2012.04.04 15:30:06 2012.01.16 06:25 TimeBasedEA Version 2: invalid handle -1 in FileWrite

What's up with that?

 

Why on earth have you chosen the most difficult of the the two options ?

When you are done writing to the file you need to close it . . . if it is already open you don't need to open it again.

//---------------------------------------------------------------

int Handle,                         // File descriptor
    Qnt_Symb;                           // Number of recorded symbols
string File_Name="check.csv";        // File name
   
Handle=FileOpen(File_Name,FILE_CSV|FILE_WRITE|FILE_READ,";");//File opening    File opened here, outside the loop
   

FileWrite(Handle,"Ticket","Magic","OTime","Type","Lots","Symbol","OPrice","S/L","T/P"); 
         
for(int iPos = OrdersTotal()-1; iPos >= 1 ; iPos--)
   {       
   OrderSelect(iPos,SELECT_BY_POS);
   FileWrite(
         Handle,
         OrderTicket(),                //int
         OrderMagicNumber(),           //int
         TimeToStr(OrderOpenTime()),   //datetime   //  this is a string - Time  to  String
         
         OrderLots(),                  //double
         OrderSymbol(),                //string
         OrderOpenPrice(),             //double
         OrderStopLoss(),              //double
         OrderTakeProfit(),            //double
         TimeToStr(OrderCloseTime() )  //int     //  this is a string - Time  to  String
       
        ) ; //end file write

   FileClose(Handle);      //  why close the file inside the loop when it was opened outside the loop ?
   }   
}    //  what is this code inside of ?
           
}  // end of start
//--------------------------------------------------------------- 

Your for loop is wrong . . . the last order position is 0 not 1

 
RaptorUK:

Why on earth have you chosen the most difficult of the the two options ?

Isn't this the way to do the modification and checking using the file? Or do I need to combine both codes, the modification (my post before the last one) and the file code (which is just to make sure no further modifications take place) ?