25.10.2016 Views

Expert Advisor Programming by Andrew R. Young

Expert Advisor Programming by Andrew R. Young

Expert Advisor Programming by Andrew R. Young

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Working with Time and Date<br />

You can also retrieve these values from any datetime variable using a different set of functions.<br />

These functions require a datetime variable as the only parameter, but otherwise work just like the<br />

functions above. If you want to retrieve a time value from TimeLocal(), use the output of the<br />

TimeLocal() function as the argument for the functions below:<br />

• TimeYear() – The four-digit year of the specified datetime value.<br />

• TimeMonth() – The month of the specified datetime value from 1 to 12.<br />

• TimeDay() – The day of the month of the specified datetime value from 1 to 31.<br />

• TimeDayOfWeek() – An integer representing the day of the week of the specified datetime<br />

value. Sunday is 0, Monday is 1, Friday is 5 and so on.<br />

• TimeHour() – The hour of the specified datetime value in 24 hour time, from 0 to 23.<br />

• TimeMinute() – The minute of the specified datetime value from 0 to 59.<br />

Here are a few examples of the usage of these functions. Let's assume that TimeLocal() is equal to<br />

2009.06.15 05:30.<br />

datetime CurrentTime = TimeLocal();<br />

int GetMonth = TimeMonth(CurrentTime); // Returns 6<br />

int GetHour = TimeHour(CurrentTime); // Returns 5<br />

int GetWeekday = TimeDayOfWeek(CurrentTime); // Returns 1 for Monday<br />

Creating A Simple Timer<br />

One very handy thing we can do with time and date in MQL is to add a timer to our expert advisor.<br />

Some traders like to limit their trading to the most active hours of the day, such as the London & New<br />

York sessions. Others may wish to avoid trading during volatile market events, such as news reports<br />

and NFP.<br />

To construct a timer, we need to specify a start time and an end time. We will use external integer<br />

variables to input the time parameters. We will create a datetime constant string, and convert that to<br />

a datetime variable. We will then compare our start and end times to the current time. If the current<br />

time is greater than the start time, but less than the end time, trading will be allowed.<br />

Here are the external variables we're going to use. We'll set a variable to turn the timer on and off, as<br />

well as to select the current time (server or local). We have month, day, hour and minute settings for<br />

both the start and end times:<br />

115

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!