Flag last state on EA.

 

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?

 
Declare the flags as static.
 
kennyhubbard:
Declare the flags as static.

Thank you, I think it works now. 

 
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.
 

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

static int 
   flagval1=1;
   flagval2=1;
 
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.
 
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?
 
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);
        }
     }

.

Reason: