Download MetaTrader 5

Flag last state on EA.

To add comments, please log in or register
alexlearnmql
41
alexlearnmql  

Can someone explain to me why flag last state does not work on EA's but works on Indicators? My code

      
      if ((MA1[1] > MA2[1]) && (flagval1==0))
      {res=OrderSend("USDCAD",OP_BUY,LotsOptimized(),askusdcad,3,0.999*bidusdcad,1.003*bidusdcad,"",MAGICMA,0,Blue);
      flagval1=1;
      flagval2=0;

      }
     
     
     else if ((MA1[1] < MA2[1]) && (flagval2==0)) 
     {res=OrderSend("USDCAD",OP_SELL,LotsOptimized(),bidusdcad,3,1.001*askusdcad,0.997*askusdcad,"",MAGICMA,0,Red);
     flagval1=0;
     flagval2=1;
     
     }

 

It does not memorize the state and just keeps re sending the orders.

What is the workaround for this? I am thinking I will need to use the function to check last order in history on whether the last order type is a buy or sell every time before order send?

Kenneth Raymond Hubbard
151
Kenneth Raymond Hubbard  
Declare the flags as static.
alexlearnmql
41
alexlearnmql  
kennyhubbard:
Declare the flags as static.

Thank you, I think it works now. 

alexlearnmql
41
alexlearnmql  
Do you know how I can make it so that it does not open a trade when I first attach the EA but only once the state changes.
Kenneth Raymond Hubbard
151
Kenneth Raymond Hubbard  

Initialise the static int to 1 ( or to 'off')

static int 
   flagval1=1;
   flagval2=1;
alexlearnmql
41
alexlearnmql  
kennyhubbard:

Initialise the static int to 1 ( or to 'off')

 

Omg I am so stupid lol, that is so simple and I have been trying ages. Thanks again.
alexlearnmql
41
alexlearnmql  
The state is now stuck on 1 and does not seem to be changing, how can I set in to 1 on start but still allow it to change?
Keith Watford
Moderator
10566
Keith Watford  
alexlearnmql:
Do you know how I can make it so that it does not open a trade when I first attach the EA but only once the state changes.

Just check for a cross when a new bar opens

   static datetime last_bar_time=Time[0];

   if(last_bar_time!=Time[0])
     {
      last_bar_time=Time[0];
      //Get values for MA1 and MA2
      if(MA1[1]>MA2[1] && MA1[2]<MA2[2])
        {
         res=OrderSend("USDCAD",OP_BUY,LotsOptimized(),askusdcad,3,0.999*bidusdcad,1.003*bidusdcad,"",MAGICMA,0,Blue);
        }
     }

.

To add comments, please log in or register