Code Snipset to Filter Order Placement Base on Time

By: yogi triana @ November 14, 2007 11:36 pm

mql4wizard.gif

In many cases, we need to put order/transaction placement filter base on time. For example, we only want to entry the market during the busy hour, or only entry the market in a specific time, etc..

Following code is a simple and general purpose code for your expert advisor. The time filter can be configured through the EA parameters “prm_trade_timeframe”.

extern bool   time_filter          = true;
extern string prm_trade_timeframe  = "00:00-06:00;17:00-23:58;";

string atimestart[10];
string atimestop[10];
int timerangecount = 0;

int init(){
   /* -------- insert this code int the EA initialization -----*/
   string strt = prm_trade_timeframe;
   int start = 0;
   int len = StringLen(strt);
   while (start < len) {
      int tokensemicolon = StringFind(strt, ";", start);
      if (tokensemicolon == -1) {
        if (len - start < 5) {
           break;
        }
      }
      int tokendash = StringFind(strt, "-", start);
      if ((tokendash == -1) || (tokendash > tokensemicolon)) {
         break;
      }
      string timestart =
            StringSubstr(strt, start, tokendash - start);
      string timestop  =
            StringSubstr(strt, tokendash + 1,
            tokensemicolon - tokendash - 1);
      if ((StringLen(timestart) != 5 ) ||
            (StringLen(timestop) != 5 )) {
        MessageBox(
            "Parameter prm_trade_timeframe contains error!");
        break;
      }
      atimestart[timerangecount] = timestart;
      atimestop[timerangecount] = timestop;
      timerangecount++;
      start = tokensemicolon + 1; // process next time
   }
   if (timerangecount == 0) {
     MessageBox(
          "No time range specified, no trade seem to be allowed.");
   } else {
     int i;
     for (i = 0; i < timerangecount; i++) {
       Print(StringConcatenate("Trade Allowed Time: ",
                  atimestart[i], " to ", atimestop[i]));
     }
   }
   /* -------------*/
   return(0);
}

bool is_trading_time(int time){
  bool allowed = false;
  int i;
  for (i = 0; i < timerangecount; i++) {
    allowed = (time >= StrToTime(atimestart[i])) &&
            ((time <= StrToTime(atimestop[i])));
    if (allowed) {
      break;
    }
  }
  return (allowed);
}


  
Filed under: Script Snipset

Comments are closed.