Simple code needed for EA (modify two open orders)

 

I've been trying to code something that will modify the take profit of two trades when two trades of a certain symbol are open, essentially,

if OrdersTotal=2

I've tried various OrderSelect functions but cannot seem to make it work, can anyone provide me with the code necessary to run this sort of task?

Thanks,

madmax3

 
Show your code that doesn't work . . . it's the best way for you to learn.
 
 int total=OrdersTotal();
 if(total>1)
                   OrderSelect(total+1, SELECT_BY_POS, MODE_TRADES);
                   
   if(OrderType()==OP_BUY)  
   OrderModify(OrderTicket(),OrderOpenPrice(),OrderStopLoss(),Ask+((TakeProfit+20)*Point),0,Blue);
   
   if(OrderType()==OP_SELL)
   OrderModify(OrderTicket(),OrderOpenPrice(),OrderStopLoss(),Ask+((TakeProfit-20)*Point),0,Blue);

That's the code I've used.

I've also tried using this,

   string Symb=Symbol();                        // Symbol
//------------------------------------------------------------------------------- 2 --
   for(int i=1; i<=OrdersTotal(); i++)          // Cycle searching in orders
     {
      if (OrderSelect(i-1,SELECT_BY_POS)==true) // If the next is available
        {                                       // Analysis of orders:
         int Tip=OrderType();                   // Order type
         if(OrderSymbol()!=Symb||Tip>1)continue;// The order is not "ours"
         double SL=OrderStopLoss();             // SL of the selected order
         double TP    =OrderTakeProfit();
         {TP=Ask+(TakeProfit+20*Point);

This is the whole EA (updated):

//+------------------------------------------------------------------+
//|                                                  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; 
        
    
}

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


   return(0);
  }
  
  
  
  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.
 

In your first bit of code . . . .

OrderSelect(total+1, SELECT_BY_POS, MODE_TRADES);

here you are selecting an Order that doesn't exist. If you ave 4 Orders the total will be 4, and the position numbers will be 0, 1, 2 & 3 . . . you have selected position 5. OrderSelect() returns a bool, if you had checked this return value you would have seen it was false and you would have known then that something was wrong.

 

The second bit of code looks OK, as far as it goes . . . . why do you have a { at the start of this line ?

{  TP=Ask+(TakeProfit+20*Point);
 
RaptorUK:

In your first bit of code . . . .

here you are selecting an Order that doesn't exist. If you ave 4 Orders the total will be 4, and the position numbers will be 0, 1, 2 & 3 . . . you have selected position 5. OrderSelect() returns a bool, if you had checked this return value you would have seen it was false and you would have known then that something was wrong.


How do I check the return value? I can't find it on the journal, btw I am a noob at MQL, I just try and make sense of the code I see.

As for the order select, I've tried various different numbers but it still does not work, I have also tried 'total' just by itself. To select two order how would I go about it?

Thanks,

madmax3

 

Ah, I'm not sure why the { it's there, mistake, removed it now.

How would I go about developing the second bit of code?

 
  1. madmax3:
    How do I check the return value?
    if (!OrderSelect(...))
       Alert("OrderSelect failed: ", GetLastError());

  2. int total=OrdersTotal();
     if(total>1)
    This makes the EA incompatible with every other, including itself on other charts and manual trading.
        for(int iPos = OrdersTotal()-1; iPos >= 0 ; iPos--) if (
            OrderSelect(iPos, SELECT_BY_POS)                    // Only my orders w/
        &&  OrderMagicNumber()  == Magic.Number                 // my magic number
        &&  OrderSymbol()       == chart.symbol                 // and my pair.
        ){
            :

 

Ok I have this so far,

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

I've tried various numbers in the first line, the EA now seems to modify pending orders while I need it to modify open orders, and only modify the open orders if there are two of them. Also, it seems to continuously modify the order.

Also the EA works like this,

  • It firsts places two pending orders (a sell and buy stop) at a specific time
  • The orders expire at a specific time if they aren't fulfilled
  • If both orders are opened then the take profit of both open trades should be modified
Would I need to modify the OrderSelect some how to modify already opened trades?
 
madmax3:

Ok I have this so far,

I've tried various numbers in the first line, the EA now seems to modify pending orders while I need it to modify open orders, and only modify the open orders if there are two of them. Also, it seems to continuously modify the order.

Also the EA works like this,

  • It firsts places two pending orders (a sell and buy stop) at a specific time
  • The orders expire at a specific time if they aren't fulfilled
  • If both orders are opened then the take profit of both open trades should be modified

Then also select OrderType()
 
//+------------------------------------------------------------------+
//|                                                  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; 
        }
        for (int i =1; i < OrdersTotal(); i++) {
    if(OrderSelect(i+1, SELECT_BY_POS, MODE_TRADES)) {
        OrderModify(OrderTicket(),OrderOpenPrice(),OrderStopLoss(),Ask+((TakeProfit+20)*Point),0,Blue);
    }
}

     }
 


   return(0);
  }
  
  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;
      }
   }
 { 
 int total=OrdersTotal();
 if(total>1)
                   OrderSelect(total+1, SELECT_BY_POS, MODE_TRADES);
                   
   if(OrderType()==OP_BUY)  
   OrderModify(OrderTicket(),OrderOpenPrice(),OrderStopLoss(),Ask+((TakeProfit+20)*Point),0,Blue);
   
   if(OrderType()==OP_SELL)
   OrderModify(OrderTicket(),OrderOpenPrice(),OrderStopLoss(),Ask+((TakeProfit-20)*Point),0,Blue);

} 

}



// the end.


	          
Reason: