Finding the crossover - MT4

 

Hello Experts!


I'm coding an EA and have an issue, say I'm find EMA crossover, like EMA 5 crossing EMA 20 to buy and vice versa, but when I load the EA into a chart, it immediately opens an order based on the EMA5 being greater or lesser than EMA20.

Ex:

if (EMA5() > EMA20())
        {
          BuyOrder(lots, magic);
        }
if (EMA5() < EMA20())
        {
          SellOrder(lots, magic);
        }
EMA5() { //Calculate EMA-05 } EMA20() { //Calculate EMA-20 } BuyOrder(int i, string mn) { ... } SellOrder(int i, string mn) { ... }

Right now, as soon as I load the EA in a chart, it opens a BUY or SELL based on the above condition, resulting in Loss mostly on the first trade.

Seeking your suggestion / Guidance in coding this efficiently, so the EA waits after loading it, until a crossover happens and not immediately open a trade.

Ex: If EMA5 is greater than EMA20 when loaded to a chart, it waits until it goes smaller or vice versa before opening a trade


Thank you in advance

 

To detect a cross, you'll need to compare two bars' worth of each EMA - i.e. 4 points, not just 2.

So assuming EMA5 and EMA20 are arrays, I'll do my comparison this way:

if (EMA5[1]>EMA20[1] && EMA5[2]<EMA20[2])
{
   // Buy condition met
}
else
if (EMA5[1]<EMA20[1] && EMA5[2]>EMA20[2])
{
   // Sell condition met
}
 
Seng Joo Thio:

To detect a cross, you'll need to compare two bars' worth of each EMA - i.e. 4 points, not just 2.

So assuming EMA5 and EMA20 are arrays, I'll do my comparison this way:

That makes a lot of sense, Thank you u r amazing!

 
Arunkumar Kalyanasundaram: it waits until it goes smaller or vice versa before opening a trade

Don't look at a condition (fast>slow) look for a change of condition (a cross.)

bool wasUp = EMA5[2] > EMA20[2];
bool  isUp = EMA5[1] > EMA20[1];  // Condition.
bool isCross = isUp != wasUp;     // Change of condition.
if(isCross){
   if(isUp) BuyOrder(lots, magic);
   else     SellOrder(lots, magic);
}

Obviously you need to check for already open orders and/or a new bar.

 

hello,

i am looking for a market screener to get opportunity on the market.

Reason: