Search code examples
tradingmql5metatrader5

EA in MQL5 does not follow If condition


I am trying to write extremely simple EA in MQL5, which has to follow only one if condition. There is an array that stores the last 5 closing prices. The idea is to open a BUY position when the last 4 closing prices (excluding the current candle) are in uptrend. However the EA starts opening BUY positions one after another without even caring about the condition. I am posting the full code.

I tried to create a new method Uptrend(), which has absolutely the same condition - still does not work.

#include <Trade\Trade.mqh>

CTrade trade;


void OnTick()
  {

  double tpoint = Point();
  double ClosePriceArray[];

  ArraySetAsSeries(ClosePriceArray, true);
  CopyClose(Symbol(), PERIOD_CURRENT, 0, 5, ClosePriceArray);

  double Ask = NormalizeDouble(SymbolInfoDouble(Symbol(),SYMBOL_ASK),_Digits);
  double Bid = NormalizeDouble(SymbolInfoDouble(Symbol(),SYMBOL_BID),_Digits);

  if ((ClosePriceArray[4] < ClosePriceArray[3] < ClosePriceArray[2]< ClosePriceArray[1]) && PositionsTotal() < 1) {
      trade.Buy(0.10, NULL, Ask, (Ask-50*tpoint), (Ask+150*tpoint), NULL);

  }


} 

I want the EA to open a BUY position only when the condition is met. There are no error messages or compilation errors.


Solution

  • Separate the comparison operators using && and add another condition as below

    if ((ClosePriceArray[4] < ClosePriceArray[3] && ClosePriceArray[3] < ClosePriceArray[2] && ClosePriceArray[2]< ClosePriceArray[1]) && PositionsTotal() < 1)
    {
      trade.Buy(0.10, NULL, Ask, (Ask-50*tpoint), (Ask+150*tpoint), NULL);
    }
    

    Also you don't need to Normalize the Bid and Ask prices, they are normalized by default, but you need to Normalize other price values such as tp and sl levels, lot sizes etc.