Download MetaTrader 5

Function for time

To add comments, please log in or register
cdp21 2014.12.10 11:08 


 I have an EA that needs to open positions at a specific time of day, which I want to set externally. This is the (simplified) structure of how I coded it:

extern double OpenTime=1.59

void OnTick()
    double CurHour=Hour();
    double CurMin=Minute();
    double CurTime=CurHour+CurMin/100;


 I haven't had any problem with the EA until I tried to put the external variable OpenTime==1.59.

Apparently it works for most times of the day (also with "59" as minutes), except for (as far as the test I've run shows) some occurrences between 1.36 and 1.59. At first I thought it was because probably the EA didn't receive any tick at that time, but I tried the EA live and although some ticks were received at 1.59, the EA did not open any position. Also, in Strategy tester the same happens, if I put 1.59 no trade is opened (no matter what date I try), but if I put 2.0 everything works smoothly. Then I thought maybe it was due to my broker or its rollover time, but the same happened when I tried 2 different brokers with different server times.

 Maybe I'm just overlooking something stupid, but I cannot find a solution for this and find it very funny. Do you have any ideas? Is there a better way to code a function for time opening trades? 

Carl Schreiber
Carl Schreiber 2014.12.10 11:45  

You should better use 2 variables: one for the hour one for the Minute:

extern int Hour = 1;
extern int Minute = 59;

if (Hour()==1 && Minute()==59) { ..

Less code, no type-cast and no troubles with the doubles!
(double 0.0 isn't exactly zero!) Start the debugger and look at the value of your double it won't be 1.59 exactly but like 1.59000000000000000023!!

cdp21 2014.12.10 14:16  
Thanks gooly, your suggestion solves my problem!

Nevertheless, I still don't understand what's wrong with the code I provided. I mean, where can the "23" in "1.590000000023" come from? I only divide the variable Minute() by 100, there should not be any remainder, shouldn't it? I know I can receive a tick at millisecond precision, but I am only comparing a double value set externally (1.59), with a double value created by the sum of two integers, of which one of them divided by 100. Plus the time between 1.36 and 1.59 is still the only period where I experienced problems!
whroeder1 2014.12.10 17:28  
cdp21 2014.12.10 17:34  
Thank you WHRoeder! Still got lot to learn :)
To add comments, please log in or register