Implement two conditions to enter a trade_ MA and CCI. (EA)

OTMT Howard
25

Hei MQL5 Community,


I've been working on two entry conditions for my EA. I am still new to coding and would appreciate your assistance in providing your expertise where my code lacks the necessary conditions.


The Strategy:


1. The MA filter check is a Boolean that can be either true or false.

2. As with point 1, the CCI filter check is also a Boolean condition.

When both are set to true, I want to use both at the same time to confirm entry.

Your assistance with this task is greatly appreciated.

extern int     StartHour      = 9;
extern int     MinPipLimit    = 0;
extern int     TakeProfit     = 40;
extern int     StopLoss       = 40;
input int      Slippage       = 0;
extern double  Lots           = 1;
extern bool    CCIFilter      = false;
extern bool    MAFilter       = false;
extern int     MA_Period      = 50;
input ENUM_MA_METHOD MA_Method      = MODE_EMA;

int Magic = 50262802;
// CCI entry
int _Sell = -1;
int _Buy = 1;
int LastOpenTime = 0;


//----------------------------------------------------------------

//+------------------------------------------------------------------+
//|                        isTradenAllowed     CCI Condition                                |
//+------------------------------------------------------------------+
bool isTradeAllowed()
  {
   if(LastOpenTime>=Time[0] - Period()*60)
      return false; // Do not open order twice on the same bar

   return true;
  }
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
// Detect 3/5 digit brokers for Point and Slippage

   if(Point == 0.00001)
     { vPoint = 0.0001; vSlippage = Slippage *10;}
   else
     {
      if(Point == 0.001)
        { vPoint = 0.01; vSlippage = Slippage *10;}
      else
         vPoint = Point;
      vSlippage = Slippage;
        {
         Alert("Parameters incorrect");
         return(INIT_PARAMETERS_INCORRECT);
        }

      myPoint     = GetPipPoint(Symbol());
     }
     {

//---
   return(INIT_SUCCEEDED);
  }
}
//+------------------------------------------------------------------+
//|                   MQL4 Slippage & Point Value                    |
//+------------------------------------------------------------------+
// Global Variables
double vPoint;
int vSlippage;
double   myPoint = Point()*10;

//+------------------------------------------------------------------+
//|                         Tick Functions                           |
//+------------------------------------------------------------------+
void OnTick()
  {
   bool EnterOpenBar = true;
   static bool OpenBar=true;
   static int  ticket = 0;
   string comment;

   double value = MathRand();
   double remain = MathMod(value,2);

   double maVal = iMA(Symbol(),0, MA_Period,MA_Shift,MA_Method,MA_Price,1); 

   if(Hour() == StartHour)
     {
      comment = GetDateAndTime();
      if(OpenBar == true)
        {
         OpenBar=false;
         if(iVolume(NULL,0,0)>1)


            //FindTicket makes sure that the EA will pick up its orders
            //even if it is relaunched
            ticket = FindTicket(Magic);

         bool res;
         res = OrderSelect(ticket, SELECT_BY_POS,MODE_TRADES);
         if(res == true)
           {
            if(OrderCloseTime() == 0)

              {
               bool res2;
               res2 = OrderClose(ticket, Lots, OrderClosePrice(), 10);

               if(res2 == false)
                 {
                  Alert("Error Closing Order #", ticket);
                 }
              }
           }

         if(Open[0] < Open[StartHour] - MinPipLimit*vPoint) //v3.0
           {
            // && All Conditions True
            // || 1 Condition True
            //check ma
            if((remain ==0 && Ask > maVal) || (!MAFilter || CCIFilter == false))
              {
               //here we are assuming that the TakeProfit and StopLoss are entered in Pips
               ticket = OrderSend(Symbol(), OP_BUY, Lots, Ask, vSlippage, Bid-StopLoss*vPoint, Bid+TakeProfit*vPoint, "Set by Advisor", Magic,0,Blue);
               if(ticket < 0)
                 {
                  comment = comment + " " + "Error Sending BUY Order";
                 }
               else
                 {
                  comment = comment + " " + "BUY Order Executed Succesfuly";
                 }
              }
            else
              {
               comment = comment + " " + "Reason Order Not Opened: MA Filter Not Passed";
              }
           }
         else
            if(Open[0] > Open[StartHour] + MinPipLimit*vPoint) //v3.0
              {
               //check ma
               if((remain==1 && Bid<maVal) || (!MAFilter || CCIFilter == false))
                 {
                  //here we are assuming that the TakeProfit and StopLoss are entered in Pips
                  ticket = OrderSend(Symbol(), OP_SELL, Lots, Bid, vSlippage, Ask+StopLoss*vPoint, Ask-TakeProfit*vPoint, "Set by Advisor", Magic,0,Blue);
                  if(ticket < 0)
                    {
                     comment = comment + " " + "Error Sending SELL Order";
                    }
                  else
                    {
                     comment = comment + " " + "SELL Order Executed Successfully";
                    }
                 }
               else
                 {
                  comment = comment + " " + "Reason Order Not Opened: MA Filter Not Passed";
                 }
              }
            else
              {
               comment = comment + " " + "Reason Order Not Opened: MinPipLimit Filter Not Passed";
              }

         Comment(comment);
         Print(comment);
        }
     }
   else
     {
      OpenBar = true;
     }

     {
      //+------------------------------------------------------------------+
      //|                       Signal Condition (CCI)                          |
      //+------------------------------------------------------------------+
      int signal = signal_cci();

      if(!CheckFilters(signal))
         return;

      if(isTradeAllowed())
        {

         if(signal== _Buy)
           {
 
           }
         if(signal== _Sell)
           {
           
           }
        }
     }
  }
//+------------------------------------------------------------------+
//|                         Magic Munber                             |
//+------------------------------------------------------------------+
int FindTicket(int M)
  {
   int ret = 0;
   int total = OrdersTotal();
   for(int i = 0 ; i < total ; i++)
     {
      bool res;
      res = OrderSelect(i, SELECT_BY_POS,MODE_TRADES);
      if(res == true)
        {
         if(OrderMagicNumber() == M)
           {
            ret = OrderTicket();
            break;
           }
        }
     }

   return(ret);
  }

//+------------------------------------------------------------------+
//|                       Time Function                              |
//+------------------------------------------------------------------+
string GetDateAndTime()
  {
   return(string(Year())+"-"+StringFormat("%02d",Month())+"-"+StringFormat("%02d",Day())+" "+StringFormat("%02d",Hour())+":"+StringFormat("%02d",Minute()));
  }
//+------------------------------------------------------------------+
//|       Commodity Channel Index​ (CCI) 100 -BUY & -100 -SELL        |
//+------------------------------------------------------------------+
int signal_cci()
  {
   double x1,x2;

   x1 = iCCI(Symbol(),_Period,50,PRICE_TYPICAL,0);
   x2 = iCCI(Symbol(),_Period,50,PRICE_TYPICAL,1);


   if(x1>-100 && x2<=-100)
      return _Sell;
   if(x1<100 && x2>=100)
      return _Buy;
   return 0;
  }
//+------------------------------------------------------------------+
//|                     Filter Check Confirmation    (CCI)                |
//+------------------------------------------------------------------+
bool CheckFilters(int signal)    //true - you can trade
  {
   if(signal==_Buy)
     {
      return iATR(NULL,_Period,14,0)<0.0002;
     }
   if(signal==_Sell)
     {
      return iATR(NULL,_Period,14,0)<0.0002;
     }

   return true;
  }

//+------------------------------------------------------------------+
//|                       Broker Pip Points                                           |
//+------------------------------------------------------------------+

// Fungsi GetPipPoint
double GetPipPoint(string pair)
  {
   double point= 0.0;
   int digits = (int) MarketInfo(pair, MODE_DIGITS);
   if(digits == 2 || digits== 3)
      point= 0.01;
   else
      if(digits== 4 || digits== 5)
         point= 0.0001;
   return(point);
  }
//+------------------------------------------------------------------+
Alexander Martinez
3150
OTMT Howard:

Hei MQL5 Community,


I've been working on two entry conditions for my EA. I am still new to coding and would appreciate your assistance in providing your expertise where my code lacks the necessary conditions.


The Strategy:


1. The MA filter check is a Boolean that can be either true or false.

2. As with point 1, the CCI filter check is also a Boolean condition.

When both are set to true, I want to use both at the same time to confirm entry.

Your assistance with this task is greatly appreciated.

if((remain==1 && Bid<maVal) || (!MAFilter || CCIFilter == false))
  {
    //here we are assuming that the TakeProfit and StopLoss are entered in Pips
    ticket = OrderSend(Symbol(), OP_SELL, Lots, Bid, vSlippage, Ask+StopLoss*vPoint, Ask-TakeProfit*vPoint, "Set by Advisor", Magic,0,Blue);
    if(ticket < 0)
      {
                     comment = comment + " " + "Error Sending SELL Order";
      }
    else
      {
                     comment = comment + " " + "SELL Order Executed Successfully";
      }
  }

You're not really doing anything with the MAFilter and CCFilter booleans other than checking if the user has them set to true / false, and using that to override the first part of your if-statement condition if the first half evaluates to false.

Also, as of right now, if both MAFilter and CCFilter are set to true, then that section of your if-statement ( (!MAFilter || CCFilter == false) ) is false.

I'm guessing you want it to be like:

1. User has option to validate the signal further by checking MA and CCI.

2. So, if MAFilter == true OR CCIFilter == true, run a check for them before proceeding with opening an order.

If that's the case, then you should remove the check for the booleans and the filters in the following if-statement:

if((remain==1 && Bid<maVal) || (!MAFilter || CCIFilter == false))

This way, the first half of the if-statement must be true before proceeding.

This is how I would re-write the logic according to how I interpreted your intentions.

const bool isValidSignal = remain==1 && Bid < maVal;

if (isValidSignal) {
  if (MAFilter) {
    //--- run check on MAFilter, exit using "return" statement if it doesn't validate the signal
  }

  if (CCIFilter) {
    //--- run check on CCIFilter, exit using "return" statement if it doesn't validate the signal
  }

  //--- Everything checks out, send order
}
You should also consider placing blocks of code inside functions. This will help keep things organized and make it easier to debug. Right now, most of your code is inside the OnTick function.
Alexander Martinez
3150
OTMT Howard:

I would really appreciate you showing me how I must implement the return condition as it is leaving me in the mist, and have been trying to pass this condition with no success.

The return operator allows you to exit a function prematurely.

void greeting(string message) {
  if (message == "") {
    return; //--- no reason to continue further
  }

  Print(greeting);
}

In cases where you created a function that is of a type other than "void", the return operator is required.

int add(int a, int b) {
  return a + b;  //--- returns an int
}

Here's the documentation for the return operator.

In your case, I would create two functions, one for MAFilterCheck and one for CCIFilterCheck.

bool MAFilterCheck() {
  const bool condition = ... //--- enter your MA condition

  if (condition)
    return true;

  return false;
}

bool CCIFilterCheck() {
  const bool condition = ... //--- enter your CCI condition

  if (condition)
    return true;

  return false;
}

//--- this is from the code I posted before:

const bool isValidSignal = remain==1 && Bid < maVal;

if (isValidSignal) {
  if (MAFilter) {
    const bool isMAFilterValid = MAFilterCheck();
    
    //--- if false
    if (!isMAFilterValid) { 
      return;
    } 
  }

  if (CCIFilter) {
    const bool isCCIFilterValid = CCIFilterCheck();
    
    //--- if false
    if (!isCCIFilterValid) { 
      return;
    } 
  }

  //--- Everything checks out, send order
}
EDIT: since you're a beginner, I figure the use of "const" should be explained. The keyword const means that the value stored in the variable cannot be changed any further once the variable has been initialized. It has some advantages and is always good practice to declare variables with the const keyword if you know for certain that there's no reason that the value needs to be changed.