Stop Trading Between Times - page 2

 
lippmaje:

It should work. Maybe the conversion StringToTime went wrong. Just Print the values of _start, _end and servertimeofday to make sure. And this might fix it:

Thanks lippmaje,

I added:

int OnInit()
{
   _currentservertime = TimeCurrent();
   Alert(" _start is ",_start);
   Alert(" _finish is ",_finish);
   Alert(" _currentservertime is ", _currentservertime); 
   return(INIT_SUCCEEDED);
}


and the alerts were as you would expect, though I realize that the _currentserver time will change continually. 

Rather a vexing problem, eh 

 

Try this 

#property strict
input string StartTime="23:30";//Time Window Start (server time)
input string EndTime="05:00";//Time Window End (server time)
enum tw_action
{
twa_trade=0,//Trade Then
twa_dont=1,//Block Trades
twa_ignore=2//Skip
};
input tw_action TimeWindowAction=twa_trade;//Time Window Action : 

struct tw_data
{
bool valid;
int start_hour;
int start_minute;
int start_minutes_code;
int end_hour;
int end_minute;
int end_minutes_code;
datetime last_signal_check;
};
tw_data TWD;//Time Window Data
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- create timer
  ResolveTimeWindow(":");   
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
  //Your Signal fires 
    //Check if time allows trade 
        if(TWD.valid==true&&Time[0]!=TWD.last_signal_check)
        {
        if(CheckTimeWindow()==true)
          {
          //Trades , alerts etc...
          }
        }
  //Your Signal fires  
  }

void ResolveTimeWindow(string separator)
{
bool start_ok=false;
bool end_ok=false;
TWD.valid=false;
//start time 
string result[];
ushort sep=StringGetCharacter(separator,0);
int splits=StringSplit(StartTime,sep,result);
//The above splits the time string to 2 parts the before : and after : , if we dont have 2 splits something is wrong
//if splits ok
  if(splits==2)
  {
  start_ok=true;
  TWD.start_hour=(int)StringToInteger(result[0]);
  TWD.start_minute=(int)StringToInteger(result[1]);
  TWD.start_minutes_code=TWD.start_hour*60+TWD.start_minute;
  }
//if splits ok ends here 
//start time ends here 
//end time 
  ArrayFree(result);
  splits=StringSplit(EndTime,sep,result);
  //if splits ok
  if(splits==2)
  {
  end_ok=true;
  TWD.end_hour=(int)StringToInteger(result[0]);
  TWD.end_minute=(int)StringToInteger(result[1]);
  TWD.end_minutes_code=TWD.end_hour*60+TWD.end_minute;
  }
  //if splits ok ends here 
//end time 
//final check 

if(start_ok==false) Print("Error in start time string , check input");
if(end_ok==false) Print("Error in end time string , check input");
if(start_ok==true&&end_ok==true) TWD.valid=true;
}

bool CheckTimeWindow()
{
bool allow=false;
//if time window setup failed dont allow trades 
//if time window setup succesful and we dont skip time checks 
  if(TWD.valid==true&&TimeWindowAction!=twa_ignore)
  {
  bool in_window=false;
  datetime now=TimeCurrent();
  int hours=TimeHour(now);
  int minutes=TimeMinute(now);
  int current_minutes_code=hours*60+minutes;
  //check if we are in the time window
    //CASE A : The end time is < than the start time 
      //example start 23:00 , end 21:00 
      if(TWD.end_minutes_code<TWD.start_minutes_code)
      {
      int full_day_minutes_code=23*60+59;//for clarification
      int new_day_minutes_code=0;//this one too
      if((current_minutes_code>=TWD.start_minutes_code&&current_minutes_code<=full_day_minutes_code)||(current_minutes_code>=new_day_minutes_code&&current_minutes_code<=TWD.end_minutes_code))      
        {
        in_window=true;
        }
      }
    //CASE B : The end time is > than the start time 
      //example start 21:00 , end 23:00
      if(TWD.end_minutes_code>=TWD.start_minutes_code)
      {
      if(current_minutes_code>=TWD.start_minutes_code&&current_minutes_code<=TWD.end_minutes_code)
        {
        in_window=true;
        }
      }
  //check if we are in the time window ends here 
  //now we know if we are in the time window or not , lets check it against the "Time Window Action"
    //if the instruction is to Only Trade IN THE WINDOW 
      if(TimeWindowAction==twa_trade)
        {
        //and we are outside the window 
          if(in_window==false) allow=false;//for demonstration
        //and we are inside the window 
          if(in_window==true) allow=true;
        }
    //if the instruction is to Only Trade OUTSIDE THE WINDOW 
      if(TimeWindowAction==twa_dont)
        {
        //and we are outside the window 
          if(in_window==false) allow=true;
        //and we are inside the window 
          if(in_window==true) allow=false;//for demonstration
        }
  }
//if time window setup succesful ends here 
//save last check bar time 
TWD.last_signal_check=Time[0];
return(allow);
}
 
Lorentzos Roussos:

Try this 

Wow .... Thanks .... Can't wait. I'll get back to you shortly ...
 
Graham from Brisbane:
Thanks Marco ... his doesn't address the minutes component though ...

Of course you can just expand the example to use more parameters.

struct MqlDateTime 
  { 
   int year;           // Year 
   int mon;            // Month 
   int day;            // Day 
   int hour;           // Hour 
   int min;            // Minutes 
   int sec;            // Seconds 
   int day_of_week;    // Day of week (0-Sunday, 1-Monday, ... ,6-Saturday) 
   int day_of_year;    // Day number of the year (January 1st is assigned the number value of zero) 
  };
int Minute=time1.min;
 
extern string EndTime = "23:30";    // Do not trade after (server time)...
extern string StartTime = "01:30";  // Do not trade before (server time)...

datetime   _start;
datetime   _finish;
datetime _currentservertime;

int OnInit()
{
   _currentservertime = TimeCurrent();
   _start = StringToTime(StartTime) % 86400;
   _finish = StringToTime(EndTime) % 86400;
   return(INIT_SUCCEEDED);
}
void OnTick()
{
   _currentservertime = TimeCurrent();
   datetime servertimeofday = _currentservertime % 86400;
   
   if( servertimeofday >=_finish || servertimeofday <=_start)           // It's after the finish time so  ....
   {
      if(ObjectFind(0,"OutOfHours_Label")<0) OutOfHours();              // Display the out of hours notice if it doesn't exist
      return;                                                           // return to beginning and wait for the next tic
   }


   // servertimeofday >_start && servertimeofday <_finish             // Continue trading and remove the out of hours label if it exists
   ObjectDelete("OutOfHours_Label");                                 // and continue to next line of code
   
   ...
}
Now this should be complete. I removed the second IF because you return control to the caller at the first anyway.
 
Use this function 
StringToTime(TimeToString(Time current(), TIME_DATE)+" "+starting_time) 
The above will first take the date part of current Time() and converts it to string . Then we add starting_time which is input variable of string type =14:00
The above will result in a string that have current data and the required stop time or start time 
When this string is passed to StringToTime() function it will be converted to datetime and you can assign it to any variable .
Sorry for that but I'm using mobile now . If it's unclear in terms of the concept I'll try to use a pc . Just let me know
 
Graham from Brisbane: Sadly, I just don't understand. Maybe it's because of my age (70+).
It's not because of your age. It's because you need to read the manual.
Remainder of division seconds = time % 60;
          MQL4 Reference → Language Basics → Operations and Expressions → Arithmetic Operations

          Find bar of the same time one day ago - Simple Trading Strategies - MQL4 and MetaTrader 4 - MQL4 programming forum
 
Graham from Brisbane:

I just tried this, but it doesn't work for me. I immediately call up the OutOfHours(), even though the server time is about 10:30 at the moment. I shouldn't be blocked from trading for another 13 hours or so ...

I have set end time at 2330 and start time at 0130. Please try it yourself if you have a few moments to spare, and let me know what you think :)

Thanks all for the help.

In MQL your code works fine if you simply say

servertimeofday=TimeCurrent();

 

How about something simple like this:

if(TimeHour(TimeCurrent())==23 && TimeMinute(TimeCurrent())>=30)

{Sleep(7200000);}

This guarantees you avoid the crazy 0 hour spreads and you'll probably only miss out on less than 15 seconds of trading considering how often the ticks occur.

 

Hi,

here is my simple solution for this little problem - may it could help you.

int GetMinute(const int in_Hour, const int in_Minute)
{
        return((in_Hour * 60) + in_Minute);
}

//+------------------------------------------------------------------+

int GetMinute(const datetime in_DateTime)
{
        return((TimeHour(in_DateTime) * 60) + TimeMinute(in_DateTime));
}

//+------------------------------------------------------------------+

...

        if ((GetMinute(TimeCurrent()) >= GetMinute( 1, 30)) &&
            (GetMinute(TimeCurrent()) <= GetMinute(23, 30)))
        {
                ...
        }

Best regards

Reason: