How to code a EA to trade in time range ?

 

Hello,

I am new to coding mql5. And I have been coding a scalping EA. Now I need to code it to trade between a time range and two time periods should be as inputs to optimise it afterwards. I need a help with this issue. My code is down below.

Thank you.

//+------------------------------------------------------------------+
//|                                                 ShiftedMA_v1.mq5 |
//+------------------------------------------------------------------+
#property copyright "Copyright 2021, Malinda Rasingolla"
#property version   "1.00"
//+------------------------------------------------------------------+                              

//Indicator inputs
input int                  InpFastPeriods       =  12;           // Fast MA periods
input int                  InpSlowPeriods       =  20;           // Slow MA periods
input int                  ADX_Level            =  25;           // ADX level

//SL and TP in pips input
input int takeProfit_pips                       =  400;
input int stopLoss_pips                         =  400;

//lotsize input
input double               InpLots              =  0.01;          // Trade lot size

//Magic number input
input int                  InpMagicNumber       =  212122;        // Magic Number

 #include <Trade/Trade.mqh>
            CTrade         Trade;
            CPositionInfo  PositionInfo;

void OnTick()
  {
       // Just exit if trading is not allowed
      if (!(bool)AccountInfoInteger(ACCOUNT_TRADE_ALLOWED)) return;
       
      // Once per bar
      if (!NewBar()) return;
       
      // Also exit if there is already a trade open
      if (TradeCount() > 6)     return;
      

      
      //Initializing Indicators
      double   fastMaArray[]; 
      double   slowMaArray[]; 
      double   ADXArray[];
      
      int HandleFast     =  iMA(Symbol(), Period(), InpFastPeriods,0, MODE_EMA, PRICE_CLOSE);
      int HandleSlow     =  iMA(Symbol(), Period(), InpSlowPeriods,0, MODE_EMA, PRICE_CLOSE);
      int HandleADX      =  iADX(Symbol(), Period(),14);
      
      ArraySetAsSeries(fastMaArray, true);
      ArraySetAsSeries(slowMaArray, true);
      ArraySetAsSeries(ADXArray   , true);
      
      CopyBuffer(HandleFast, 0, 0, 3, fastMaArray);
      CopyBuffer(HandleSlow, 0, 0, 3, slowMaArray);
      CopyBuffer(HandleADX,  0, 0, 1, ADXArray);
      
      double fastMa      = fastMaArray[0];
      double fastMaShift = fastMaArray[2];
      double slowMa      = slowMaArray[0];
      double slowMaShift = slowMaArray[2];
      double ADX         = ADXArray[0];
     

      //Signals
      double Ask = SymbolInfoDouble(Symbol(), SYMBOL_ASK);
      double Bid = SymbolInfoDouble(Symbol(), SYMBOL_BID);      
      
      string signal      = "";
      if((fastMa-fastMaShift)>0 && (slowMa-slowMaShift)>0 && ADX>ADX_Level)
      {
         signal      = "buy";
         Comment("Signal : Buy\nTrade count : ",(TradeCount()+2));
      }
      if((fastMa-fastMaShift)<0 && (slowMa-slowMaShift)<0 && ADX>ADX_Level)
      {
         signal      = "sell";
         Comment("Signal : Sell\nTrade count : ",(TradeCount()+2));
      }
      
      
      //Executing Orders
      double   tpPrice;
      double   slPrice;
      double   openPrice;
      
      if(signal == "buy")
      {
         openPrice   =  SymbolInfoDouble(Symbol(), SYMBOL_ASK);
         tpPrice     =  openPrice + takeProfit_pips*_Point;  
         slPrice     =  openPrice - stopLoss_pips*_Point;
         Trade.Buy(InpLots,Symbol(),openPrice,slPrice,tpPrice,NULL);
      }
      
      if(signal == "sell")
      {
         openPrice   =  SymbolInfoDouble(Symbol(), SYMBOL_BID);
         tpPrice     =  openPrice - takeProfit_pips*_Point; 
         slPrice     =  openPrice + stopLoss_pips*_Point; 
         Trade.Sell(InpLots,Symbol(),openPrice,slPrice,tpPrice,NULL);
      }
     
     
   
  }
//+------------------------------------------------------------------+




bool  NewBar() 
   {
      datetime          now      =  iTime(Symbol(), Period(), 0);
      static datetime   prevTime =  now;
      if (prevTime==now)   return(false);
      prevTime =  now;
      return(true);
   }

 int   TradeCount() 
   {
       
      int tradeCount = 0;
      
      for(int i=PositionsTotal()-1; i>0; i--)  
      {
        string symbol   = PositionGetSymbol(i);
        if(Symbol()==symbol) 
        {
            tradeCount  += 1;
        }
      }  
         return(tradeCount);
          
   }
   
   
   
   
   
   
 

Mistake # 1: You create several indicator handles at each tick! The MQL5 style implies: the indicator handle must be created ONCE and must be done in OnInit!

Example:

Creating an iMA indicator handle, getting indicator values

How to start with MQL5
How to start with MQL5
  • 2020.03.05
  • www.mql5.com
This thread discusses MQL5 code examples. There will be examples of how to get data from indicators, how to program advisors...
 
Vladimir Karputov #:

Mistake # 1: You create several indicator handles at each tick! The MQL5 style implies: the indicator handle must be created ONCE and must be done in OnInit!

Example:

Creating an iMA indicator handle, getting indicator values

Thank you soo much sir. I will make it right. Please feel free to point me errors if there is more.
 
malinda_rasingolla # :
Thank you soo much sir. I will make it right. Please feel free to point me errors if there is more.

It is better to fix errors gradually: the error is found -> you need to fix the error -> you need to show the corrected code

 
Vladimir Karputov #:

It is better to fix errors gradually: the error is found -> you need to fix the error -> you need to show the corrected code

I fixed the code. 
//+------------------------------------------------------------------+
//|                                                 ShiftedMA_v1.mq5 |
//+------------------------------------------------------------------+
#property copyright "Copyright 2021, Malinda Rasingolla"
#property version   "1.00"
//+------------------------------------------------------------------+                              

//Indicator inputs
input int                  InpFastPeriods       =  12;           // Fast MA periods
input int                  InpSlowPeriods       =  20;           // Slow MA periods
input int                  ADX_Level            =  25;           // ADX level

//SL and TP in pips input
input int takeProfit_pips                       =  400;
input int stopLoss_pips                         =  400;

//lotsize input
input double               InpLots              =  0.01;          // Trade lot size

//Magic number input
input int                  InpMagicNumber       =  212122;        // Magic Number

//indicator handles
int HandleFast     ;
int HandleSlow     ;
int HandleADX      ;

 #include <Trade/Trade.mqh>
            CTrade         Trade;
            CPositionInfo  PositionInfo;

int OnInit()
   {
      HandleFast     =  iMA(Symbol(), Period(), InpFastPeriods,0, MODE_EMA, PRICE_CLOSE);
      if (HandleFast ==INVALID_HANDLE)  return(INIT_FAILED);
      HandleSlow     =  iMA(Symbol(), Period(), InpSlowPeriods,0, MODE_EMA, PRICE_CLOSE);
      if (HandleSlow ==INVALID_HANDLE)  return(INIT_FAILED);
      HandleADX      =  iADX(Symbol(), Period(),14);
      if (HandleADX  ==INVALID_HANDLE)  return(INIT_FAILED);
      
      return(INIT_SUCCEEDED);
   }
void OnTick()
  {
       // Just exit if trading is not allowed
      if (!(bool)AccountInfoInteger(ACCOUNT_TRADE_ALLOWED)) return;
       
      // Once per bar
      if (!NewBar()) return;
       
      // Also exit if there is already a trade open
      if (TradeCount() > 6)     return;
      

      
      //Initializing Indicators
      double   fastMaArray[]; 
      double   slowMaArray[]; 
      double   ADXArray[];
      

      
      ArraySetAsSeries(fastMaArray, true);
      ArraySetAsSeries(slowMaArray, true);
      ArraySetAsSeries(ADXArray   , true);
      
      CopyBuffer(HandleFast, 0, 0, 3, fastMaArray);
      CopyBuffer(HandleSlow, 0, 0, 3, slowMaArray);
      CopyBuffer(HandleADX,  0, 0, 1, ADXArray);
      
      double fastMa      = fastMaArray[0];
      double fastMaShift = fastMaArray[2];
      double slowMa      = slowMaArray[0];
      double slowMaShift = slowMaArray[2];
      double ADX         = ADXArray[0];
     

      //Signals
      double Ask = SymbolInfoDouble(Symbol(), SYMBOL_ASK);
      double Bid = SymbolInfoDouble(Symbol(), SYMBOL_BID);      
      
      string signal      = "";
      if((fastMa-fastMaShift)>0 && (slowMa-slowMaShift)>0 && ADX>ADX_Level)
      {
         signal      = "buy";
         Comment("Signal : Buy\nTrade count : ",(TradeCount()+2));
      }
      if((fastMa-fastMaShift)<0 && (slowMa-slowMaShift)<0 && ADX>ADX_Level)
      {
         signal      = "sell";
         Comment("Signal : Sell\nTrade count : ",(TradeCount()+2));
      }
      
      
      //Executing Orders
      double   tpPrice;
      double   slPrice;
      double   openPrice;
      
      if(signal == "buy")
      {
         openPrice   =  SymbolInfoDouble(Symbol(), SYMBOL_ASK);
         tpPrice     =  openPrice + takeProfit_pips*_Point;  
         slPrice     =  openPrice - stopLoss_pips*_Point;
         Trade.Buy(InpLots,Symbol(),openPrice,slPrice,tpPrice,NULL);
      }
      
      if(signal == "sell")
      {
         openPrice   =  SymbolInfoDouble(Symbol(), SYMBOL_BID);
         tpPrice     =  openPrice - takeProfit_pips*_Point; 
         slPrice     =  openPrice + stopLoss_pips*_Point; 
         Trade.Sell(InpLots,Symbol(),openPrice,slPrice,tpPrice,NULL);
      }
     
     
   
  }
//+------------------------------------------------------------------+




bool  NewBar() 
   {
      datetime          now      =  iTime(Symbol(), Period(), 0);
      static datetime   prevTime =  now;
      if (prevTime==now)   return(false);
      prevTime =  now;
      return(true);
   }

 int   TradeCount() 
   {
       
      int tradeCount = 0;
      
      for(int i=PositionsTotal()-1; i>0; i--)  
      {
        string symbol   = PositionGetSymbol(i);
        if(Symbol()==symbol) 
        {
            tradeCount  += 1;
        }
      }  
         return(tradeCount);
          
   }
   
   
   
   
   
   
 
Now run your code in the Strategy Tester. Check if errors appear or not.
 
Vladimir Karputov #:
Now run your code in the Strategy Tester. Check if errors appear or not.
Yes now it has no errors. Thank you. Can you help me to code this EA to trade in a time range ? 
 
malinda_rasingolla # :
Yes now it has no errors. Thank you. Can you help me to code this EA to trade in a time range ? 

You must decide: how to limit the trading interval? Only for hours or hours and minutes.

 
Vladimir Karputov #:

You must decide: how to limit the trading interval? Only for hours or hours and minutes.

Hours and minutes is what I want to use.

 
malinda_rasingolla # :

Hours and minutes is what I want to use.

In this case, input parameters are needed:

input group             "Time control"
input bool                 InpTimeControl          = true;           // Use time control
input uchar                InpStartHour            = 10;             // Start Hour
input uchar                InpStartMinute          = 01;             // Start Minute
input uchar                InpEndHour              = 15;             // End Hour
input uchar                InpEndMinute            = 02;             // End Minute

need a check function:

//+------------------------------------------------------------------+
//| TimeControl                                                      |
//+------------------------------------------------------------------+
bool TimeControlHourMinute(void)
  {
   if(!InpTimeControl)
      return(true);
   MqlDateTime STimeCurrent;
   datetime time_current=TimeCurrent();
   if(time_current==D'1970.01.01 00:00')
      return(false);
   TimeToStruct(time_current,STimeCurrent);
   if((InpStartHour*60*60+InpStartMinute*60)<(InpEndHour*60*60+InpEndMinute*60)) // intraday time interval
     {
      /*
      Example:
      input uchar    InpStartHour      = 5;        // Start hour
      input uchar    InpEndHour        = 10;       // End hour
      0  1  2  3  4  5  6  7  8  9  10 11 12 13 14 15 16 17 18 19 20 21 22 23 0  1  2  3  4  5  6  7  8  9  10 11 12 13 14 15
      _  _  _  _  _  +  +  +  +  +  _  _  _  _  _  _  _  _  _  _  _  _  _  _  _  _  _  _  _  +  +  +  +  +  _  _  _  _  _  _
      */
      if((STimeCurrent.hour*60*60+STimeCurrent.min*60>=InpStartHour*60*60+InpStartMinute*60) &&
         (STimeCurrent.hour*60*60+STimeCurrent.min*60<InpEndHour*60*60+InpEndMinute*60))
         return(true);
     }
   else
      if((InpStartHour*60*60+InpStartMinute*60)>(InpEndHour*60*60+InpEndMinute*60)) // time interval with the transition in a day
        {
         /*
         Example:
         input uchar    InpStartHour      = 10;       // Start hour
         input uchar    InpEndHour        = 5;        // End hour
         0  1  2  3  4  5  6  7  8  9  10 11 12 13 14 15 16 17 18 19 20 21 22 23 0  1  2  3  4  5  6  7  8  9  10 11 12 13 14 15
         _  _  _  _  _  _  _  _  _  _  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  _  _  _  _  _  +  +  +  +  +  +
         */
         if(STimeCurrent.hour*60*60+STimeCurrent.min*60>=InpStartHour*60*60+InpStartMinute*60 ||
            STimeCurrent.hour*60*60+STimeCurrent.min*60<InpEndHour*60*60+InpEndMinute*60)
            return(true);
        }
      else
         return(false);
//---
   return(false);
  }

Usage example:

***
   if(!TimeControlHourMinute())
      return(true);
***
 
malinda_rasingolla:

Hello,

I am new to coding mql5. And I have been coding a scalping EA. Now I need to code it to trade between a time range and two time periods should be as inputs to optimise it afterwards. I need a help with this issue. My code is down below.

Thank you.

There's no need of your code to post an example:

//+--- Parameters ---!
input int StartHour = 9;
input int StopHour  = 18;

//+--- HourFilter ---!
MqlDateTime time;TimeCurrent(time);
bool Filter=(StartHour<StopHour&&(time.hour>=StartHour&&time.hour<StopHour))||(StartHour>StopHour&&(time.hour>=StartHour||time.hour<StopHour));

From my point this is the simpler way to filter by hour, notice that StartHour could be after than StopHour. Filter condition must be true.