MQL4 - automated forex trading   /  

Forum

Login | Register | Language: ru cn en
Buy financial books in MetaTrader Market and trade with confidence

Help please for Time...

Back to topics list To post a new topic, please log in or register
avatar
22
fryfly 2008.04.30 01:53
 

Hi. I am having problems trying to get the first part of my programme! I have read the book and one other tutorial but obvoisly Im not getting it.

All I want to do is to make an expert advisor that will only work at a certain period of time of the day. e.g. if the time is between 6:00am and 18:00pm then the ea will work, if not it will wait untill that time comes before entering any trade.


This is what I have so far:



extern string start_t = "05:00";
extern string end_t = "16:00";


int start()
{
if (TimeCurrent < start_t || TimeCurrent > end_t)
Alert ("Not Trading");
return; // Exit from start()
}



I no that this cant be the right way to put it but the book on this website doesnt actually explain how this should be put unless im missing it. Can anyone point me to the page in the book or tell me where Im going wrong?





 
Pound drops after latest Scottish independence survey

Pound drops after latest Scottish independence survey

GBP fell against the greenback and even against the euro after a YouGov poll showed support for the pro-independence "yes" campaign had risen to 47%. The lead held by the no campaign has fallen to six points from 22 points at the start of August. Analysts say the pound is likely to weaken further ahead of the 18 September referendum.

avatar
396
ukt 2008.04.30 13:32 #
 

Hello ff


first off: visit your editor's help at MQL4 Reference - Date & Time functions

"A group of functions providing the working with data of the datetime type (integer representing the amount of seconds elapsed from midnight, 1 January, 1970)."

and follow the links mentioned


specifically online (or in your editor's help): http://docs.mql4.com/basis/types/datetime


and a forum search for "date time" in subsection Documentation gives eleven hits: http://docs.mql4.com/search/date%20time


basically... you must deal with a 4-byte int value which holds "...seconds elapsed from midnight, 1 January, 1970)."


Then once you have this int value, will be on same wavelength as all system calls etc. There are conversion builtins to go to secs > "datetime string" etc.


Remember that although datetime and int may represent different types, they are both at memory level 4-byte integers so use/interpretation is according to code context, yes?


btw:

you may not want Alert() calls as EA gets recalled on each new incomming trade server data tick.

Maybe a variable protected block(s) that only does once for eg,

"outside trading times of <could plant the start,end times here in o/p string>" and

"inside trading times of <could plant the start,end times here in o/p string>"


just doing the sideways thinking stuff :o)


ps.

not given any code samples. Why? anyone entering "..._t" not need my help with coding :o))


keep up the naming conventions - viz: some variant of Hungarian Notation etc.

life all of sudden becomes soooo much easier when looking back on code!



 
avatar
22
fryfly 2008.05.01 02:01 #
 

Thanks ukt.

I think im on the right track...


extern datetime start_t = D'06:00';
extern datetime end_t = D'14:00';


int start()
{
if (TIME_MINUTES > start_t || TIME_MINUTES < end_t)
Alert ("Trading Time");
return; // Exit from start()
}



I have only placed the alert so that I no if it works. Only problem is it doesnt matter what time I put in the variable start_t or end_t it always seems to give the alert. There is somthing wrong with my maths. Should I be using || symbol?

Also if the 'if' statement is true, will the EA continue with the rest of the code? If so will it stop working if the statements is false?

Im really struggling to get this down, if you could show me how you would do it it wud probably help my understanding.

 
avatar
396
ukt 2008.05.02 18:51 #
 
Please excuse answer delay - life's demands preempt me having fun and learning :o(

Ok then - good for me too as hardly ever use this stuff once put into a function, tested etc. and... forgot about ;)

(please also note that is all IMHO, must be different ways and more than likely simpler ones too ;) hope some readers post their methods - I wanna learn too...


The simple bit is if only using hour boundaries. When use minutes as well, like 06:30...18:45, I learned that cannot just do a large single IF condition. Well, u can but MQL4 does not do short circuit exit when evaluating a conditional statement so time wasted running code unnecessarily.
May seem trivial but if one writes large conditionals all the time especially ones that would benefit from short circuit exit, the excess time on each could cause EA to miss dataTick or other vip event.

Hoping MQL5 more clever...


MQL4 Reference - Basics - Data types - Datetime constants

Datetime constants can be represented as a literal line consisting of 6 parts for values of year, month, date, hours, minutes, and seconds. The constant is enclosed in single quotes and starts with D. Either date (year, month, date) or time (hours, minutes, seconds), or both can be skipped. Datetime constant can vary from Jan 1, 1970 to Dec 31, 2037.

Examples
D'2004.01.01 00:00'     // New Year
D'1980.07.19 12:30:27'
D'19.07.1980 12:30:27'
D'19.07.1980 12' //equal to D'1980.07.19 12:00:00'
D'01.01.2004' //equal to D'01.01.2004 00:00:00'
D'12:30:27' //equal to D'[compilation date] 12:30:27'
D'' //equal to D'[compilation date] 00:00:00'

Its internal representation is a long integer number of 4 bytes. The value represents the amount of seconds elapse from 00:00 Jan 1, 1970.

Notice red above - you want to tell code about a trading window and this is described by a start and end time, yes?

Assuming you want to make the window times variable then you use extern so that the times can be set as required.

Since date + time varies day to day and second by second, yes? As seen above in red, you cannot just put in a datetime constant - keyword being constant, ok?

You gotta think generic or say: the window starts at hh=06 and ends at hh=18 and not need know the day (you do IF is not trading day but diff subj).

By doing this, you can remove code from thinking about the date, just the hour number (can of course be extended to the minutes number too, see attachment)

So... with above in mind we can use int TimeHour() which returns the hh value for any given time.


Complication begins when using the Date & Time functions because we have 'local time' and 'last known server time'

eg, currently, relative to the UK, my MT time/server time is +1hr meaning if my UK time is 12:15 and looking at M15 bar, then MT time for this bar is 13:15

TimeCurrent() returns MT time/server and TimeLocal() returns UK time/where my PC clock is set to.

Is up to YOU to decide on what time you use and how you manipulate it. Personally, I never mess with time eg, my weekend non trading test is simply if(sat||sun) no trading ;)

As an example of diffs btwn current and local times:

Print("Time[Hour:Minute:Seconds](TimeCurrent())=",TimeHour(TimeCurrent()),":",TimeMinute(TimeCurrent()),":",TimeSeconds(TimeCurrent())
,", TimeLocal()=",TimeToStr(TimeLocal(),7)," TimeHour(TimeLocal())=",TimeHour(TimeLocal()) );
results in:

2008.05.01 16:28:56 test GBPUSD,M15: Time[Hour:Minute:Seconds](TimeCurrent())=17:28:56, TimeLocal()=2008.05.01 16:28:56 TimeHour(TimeLocal())=16

can see that TimeLocal() gives PC time... all depends on life, the universe and how you view the trading times - I've never bothered to sweat this issue, at end of day... IF trade to take I take it -lol

Is maybe relevant to you maybe not, but should beware of the diffs, yes? (ha... am gonna save this ramble and print out cause I'm always wondering... well, truth be told, MT makes me wonder ALL the time :o)


So, is easy to get the start,end hh, mm values into EA eg, extern int eiStartHH = 6, eiEndHH = 18; ...

ie, no need mess with D'06:00' constant syntax imho


Have attached file - is way over the top BUT it works and shows "my ideas on this issue"

Remember, my ideas - yes? No doubt better ideas are out there - and I hoping they will be posted - then I learn more, that's the fun bit


hth



Attached files:
  tradewindow.mq4  (5.14 KB)
 
avatar
22
fryfly 2008.05.02 21:25 #
 

WOW. u sure no your stuff. I kinda see how you did this, very clever.

First you Write out what the programe should do with sbInside and sbOutside when either true or false with some error checking stuff that i dont no about..haha. Then you have written the function and calculations for whether it is inside the trading zone and giving an output (bInTrade). Somehow this magically changes to inTradeWindow so that the above coding takes this result of inTradeWindow and somehow you get it to give sbInside and sboutside? I dont quite no how you done this bit, so lets say for example inTradeWindow is true....then somehow the program nos whether sbInside or sbOutside is true or false. It figures out that sbInside is false and sbOutside is true. This is the part I dont quite understand. How does the programme know what sbInside and sbOutside are?


I see why now that you cant use datetime as a variable because its a constant...lol so simple I now feel stupid!

Thanks for you help with this, not really sure if my understanding is better as its gone a little over my head, but im sure this kinda thing takes time if ur not too clever.



p.s. ---->

/*
...
THE Holy Grail income making code goes here :o))
...
*/



LIKE IT! MOST IMPORTANT PART IS THAT HOLY GRAIL CODE... HAHA... if all goes well ill pm u the finished ea..

 
avatar
396
ukt 2008.05.02 23:24 #
 

F... please do not say things like stupid or ur not too clever

No one is such, sincerely I say this friend.

We all start our journey at the same point - only diff is you starting now, me... well, been way too long and guess what? Often I feel like just starting the journey too :o))

MetaTrader sincerely does my head in a lot - methinks the docs could be massively improved (I'm a docs type, and spend loads time having to write testbeds to figure out just what the heck docs mean)

Is ok... but tedious slog.


Tell ya what, I'll think through why I did what I did and annotate code and do my best to figure out how best to answer your questions, ok?

In return, do me favour and do 'desk check' of the function.

1) Get some paper and at the top, on one line each - write down the variables that are used in the function (yer gonna use that line to enter each new value the variable gets - use comma to separate each as you go right, along the line)

Now then... what would the computer do when entering this function? (not expect you to know at the code/cpu level but just look at the function - it's all there!)

2) Any function formal parameters?, if so give em a line and here you can enter there 1st value cuz the calling code will supply values yes?

3) Any variables statics? if so, then write down the current value after the name followed by a comma (remember, static type not loose it's value when function exits... look up in docs if not 'get it', remember that the FIRST time the static is seen by the computer/executed/program loaded into memory, if given - the initialisation value will be loaded/assigned to this variable. BUT, only this once! The next time the processor passes that statement, the variable is not given that first value (if present). Thereafter as each new value gets assigned to variable that's what it has - even when the function and/or start() exits)

excuse me if this known - not mean to go on so, but is vip to know the mechanics a bit so can then just use and... know why you declaring a variable static

4) Any variables initialised when declared? if so, then write down the value...

See, just like a game but is great cuz you being the computer and this really seriously makes you THINK and remember, the computer ALWAYS ALWAYS does what it's told to do... meaning when you 'the computer' execute some crazy logic guess what? you'll see the faults pretty darn fast written down in front of yer eyes!

5) Well then, as a computer ya gotta get down to munching up some code, yes? so take the first real code line in the function and just do what it says! Plug in any values (remember steps 2,3,4 above?) and execute the code!

6) If is assignment then update the variable by appending on it's line the new value - just like the computer does when doing write cycle to the variables memory location...

7) If is boolean statement then again, just plug in the current values of any used variables and play computer...

8) If making any function calls say to the Client Terminal builtin functions, eg, TimeLocal() well then, 'you' know what the function is going to return because you've got the docs and you also know what values you may have given it as actual parameters in the call, yes?

9) so... what ya waiting for? execute the statement - update any variables if needed, if is an IF statement then do the next line of code according to true/false outcome of the evaluated expression...


guess what... seriously - anyone who cannot do this really needs to consider what knowledge they do not have and start cracking the books!


10) anyway, YOU know the expected function outcome because you've fed it with inputs that YOU know will either cause a true OR false result (in our case, the function is type bool, yes?)

Basically at the end of the function or where you hit a return statement, the value inside that bool variable should match up to what YOU know it should be, yes?

If it does not and your are totally confident that you played computer 100% and did exactly what the code told you to do well, guess what? the code is wrong somewhere, yes?


OK, i understand that all readers of above are probably rolling in the aisle laughing themselves to death, but you will learn a lot and is very humbling to realise that you just do not have a clue as to what you are doing in that code...


Some would call this a bottom up design,code,test process or some might call it a stepwise refinement process - makes no difference what is called... is ALL about results - valid results


Millions of times more important because YOUR MONEY is on the line here - not some airy fairy bit of software that some salaried geek writes some where... this is imho the most important hacking ever - this is personal - you screw up and ya gonna feel the PAIN and in the case of some when the sh*t really does hit the fan... their loved ones gonna feel it too, yes?


So, ok, I drivel on and on but feel so strongly about all this gunk... and boy, do I still get it terribly wrong all the time even though I have certain work habits which [in theory] should stop this happening.

Is all part of the grand design... like hammer and chisel - just gotta keep swinging the metal firmly on the chisel head, over and over,....


Anyway - have a go ok? I'll do what I can to annotate code and stuff like that - you just make the 'play computer' game part of your tool set, after awhile not need to be like that all the time (but sometimes is very simple way to quickly sort out some tricky bit of code) because YOU will have gained so much from all this... learning language syntax, learning Client Terminal builtins and learning about yourself too and how/why you think your problems through -- hahaaa, now that's a worthy HOLY GRAIL if ever there was one, yes?



catch up later


 
avatar
22
fryfly 2008.05.04 23:56 #
 

Thanks for sharing this technique. Have been busy with work etc recently so havnt had time to do it untill now. I dont have too much trouble understand it its just actually implementing the code I have problem with? But this will make it soo much easier I think...



Its helped me understand your code a bit more. So I went through the process above and got this far:



static variables are sbInside sbOutside, both are false.

InTradeWindow = custom function so need to go through that code to get result....


bIntrade = false

all the tNows are self explanatory like you said...with the nested ifs and the else statment it will be true if the time is the same as or above starttime HH and MM, and if same as or below EndTime HH and MM.

It returns bIntrade for the result so lets say its true...This is also the result for InTradeWindow so can go back to top code with the result:



Now hopefully my understanding of ! is correct, like you said b4 the docs arnt that great....but it says its a NOT logicall operation meaning it is TRUE if value of operand is FALSE; FALSE and the value of the operand is not FALSE...so if the function InTradeWindow is TRUE, then the ...actually this is where I get lost. I really dont understand... how annoying i am at myself!


I dont get this but Ill give a try at explaining how I see it..........


so lets say InTradeWindow returns TRUE....!InTradeWindow means its true if the operand is FALSE,FALSE and the Operand is not FALSE..this really dont make sense to me. I cant even try to explain it, the person that made this book needs to be shot,seroisly! Cant they write plain old english and actually explain it FFS!!!!! How can an operand be FALSE, FALSE but not be FALSE? WTF! sorry to get so angry ... ok... bear with me....


AHA!!! headache now maybe over and again sorry for unneccesary ramble above, but ill keep it for u 2 have a good laugh at. ! means TRUE if the Operand is FALSE, but it is FALSE if the operand is TRUE. They have explained 2 conditions in the book, but made it look like it is just one statement about it being true. Finally got my head around it! WOOT!

so !bInTradeWindow has a returned value of TRUE, MEANING THE CODE IS FALSE, so the if statement does not commence, it skips to next statment.... which is !sbInside.... originaly value of !sbInside was false, meaning this IF is true so this will commence. AWESOME!!!

So bInTradeWindow is FALSE, !bInTradeWindow has a returned value of FALSE so the IF statment is actually TRUE. Now !sbOutside original value is false, so this IF statment is TRUE meaning this part of code is executed. HAHAHA OMFG.

oNCE AGAIN THANK YOU ukt for this help. It is finally clicking into place.... That is why I wasnt understand it, I didnt really no what the ! operator meant, now I do :D You have answered my questions and taught a valuable lesson.

Take it easy man, will catch up soon and update you on progress of EA......


 
avatar
396
ukt 2008.05.05 18:09 #
 

Hi F, you know... reading your last post has really impressed on me just how hard it is to be messing with boolean logic.


Ok, I use "!" loads BUT... I still often times 'make sure' on paper - working left to right (just like cpu) would do. Using 1 as TRUE and 0 as FALSE, etc.


You got it in a nutshell, ! inverts the sense/logic/meaning. Some languages use NOT, AND, OR instead of !,&&,|| which would have been more readable...


I agree totally with your frustration ;o) and please excuse me for 'somehow' leaping across valleys in a single jump!! without actually giving better 'hints' as to just how I intended to do this jump ;)


I spent some time playing around with code to invert the damn thing - in the end I was getting in a twist too - lol, My brain must be wired to use NOT and well - let you do that if want to!

"if(!isSunnyToday())" can at times just work in certain places imho, but of course IF designed from the start THEN "if(isRainingToday())" for sure would read better - all depends I guess ;)


Your post is great... how you went from zero to hero, really very interesting post indeed.

Following your footsteps was nice and seeing the sun come up was real cool - long may it continue to do so :o)


Please do consider relaying any updates you like, will keep 'subscribed' to topic.


Much appreciated your time taken to 'talk' to me... yep, really liked that.


Enjoy replacing the comment below with yer first coded 'grail


/*
...
THE Holy Grail income making code goes here :o))
...
*/

PS

I was going to mention something about PUBLIC and PRIVATE code and the design and writing thereof.

My particular pet issue which I still fall way short of achieving many times

but once bitten with the knowledge and then thinking a bit about it and how much simple sense it made... I became lost forever ;)


Unfortunately, googling on such words gives hits on OOP. I do not mean Object Oriented Programming or even OOD.

Anyway, to cut to the chase, here are two truisms - imho:


1. IF you write PRIVATE code THEN you should not inflict this code onto the suffering public

2. IF you write PUBLIC code THEN maybe, just maybe the public (which could be you) will not suffer as much ;)


Example: you write a quick 'n dirty test harness for a function and feed that function every combination of inputs you can think of. Aim = break the damn thing, find any gremlins lurking in it, make it smoke!

The test harness is perhaps too simple example but the message is clear - you are coding to get an explicit job done fast and you not care about comments, meaningful identifier names etc, etc.

A throw-away collection of statements, not for reuse... at least by others!

but - IF you are going to keep this test harness and include in the tested function's documentation etc THEN actually - you should have consideration/empathy for the mug that has to use it later [and of course mod it due to making mods on function under test] - worst case is that loadsa time has passed and the mug could be YOU ;)

So... you write PUBLIC code with good well designed and thought out strutured code with sensible comments, great meaningful identifier names, ...


PUBLIC code means you and the other poor saps further down the maintenance path sleep at night... usually!


Once code has it's first clean compile, it's into the maintenance phase... for life!

Maintenance can be not so hellish or it can be way worse than your worst possible dreams.

If the latter - be prepared to spend not only time, but yours or your bosses money in attempts to be maintainer of well... basically a load of cr*p, but probably legacy brown stuff that you or your boss desparately needs... so that you/company stay working and you get a wage!


The confirming metrics on above ideas are well documented...

ie, not just my opinion.


as background reading (always pays to keep reading glasses well used :o)

CODING HORROR - programming and human factors

The author Jeff Atwood is saying what has been said for decades, sadly many not listen - regardless of who says the words...


And... why do I type so much and [generally?] use such crazily long variable names ?

What is the meaning of Coding Horror?



 
avatar
22
fryfly 2008.05.05 23:28 #
 

So actually it would be ok to use if's then...

say :

if(inTradeWindow = true)

{

Print("EA in \'local time\' trade window (",eiStartHH,":",eiStartMM," - ",eiEndHH,":",eiEndMM,")"
," Local time is ",TimeToStr(TimeLocal(),7));

}

else

{

Print("EA not in \'local time\' trade window (",eiStartHH,":",eiStartMM," - ",eiEndHH,":",eiEndMM,")"
," Local time is ",TimeToStr(TimeLocal(),7));

return();

}

and this would work ok? I will keep your code tho as it seems more reliable to me. Just wondering if this is how it could be done.


I am now trying to get data from a custom indicator. The indicator is breakout_eagle_indicator. Im trying to get the high price it gives and also the low price this indicator gives with no success.

I am calling the 2 functions for it:


double boxLow, boxHigh;

boxLow = iCustom(NULL,0,"BreakOut-EAGLE_indicator",0,0);
boxHigh = iCustom(NULL,0,"BreakOut-EAGLE_indicator",0,0);
Print("boxLow ", " boxHigh ");



But all I get is a long number for both so boxLow is the same as boxHigh. I also changed the parameter '0' to 0 for boxLow, and 1 for box high, when I do that it gives the value for boxLow but no value is given for boxHigh leading me to believe that there is only one parameter.

Looking at the code it does have an expression:


DrawObjects(dtTradeDate, "BoxBreakOut_High " + TimeToStr(dtTradeDate,TIME_DATE), periodBegin, periodEnd, BoxEnd, BoxBreakOutColor, BoxBreakOut_Offset,2); DrawObjects(dtTradeDate, "BoxBreakOut_Low " + TimeToStr(dtTradeDate,TIME_DATE), periodBegin, periodEnd, BoxEnd, BoxBreakOutColor, BoxBreakOut_Offset,3);



So the data im trying to get is BoxBreakOut_High and ..._low. There is also another custom function:



dPriceHigh = High[Highest(NULL, 0, MODE_HIGH, iBarBegin-iBarEnd, iBarEnd)];

dPriceLow = Low [Lowest (NULL, 0, MODE_LOW, iBarBegin-iBarEnd, iBarEnd)];


I also think this is the data I need. Any ideas on where I shud start?

There is only one buffer which I have left out from the iCustom function so that it can change its value. Once again the book and docs leave a lot of how to get this kind of data out, only telling the basics, and not very well either. =(

avatar
396
ukt 2008.05.06 02:42 #
 

Hello F,

A suggestion/question... if you are having questions over MQL4 syntax at the outset, is it wise to be programming an EA just now?


The comment about docs may be true but the info is there nevertheless and also please search the forum - it is such a valuable resource!

It really should not be ignored... so much more info from so many perspectives live all over this site and the search box is your personal portal to all this information!


All your iCustom() queries will be answered and the MQL4 syntax knowledge gap really ought to be addressed - why not look at MQL4 book/tutorial?

This section deals with the rules of formatting and execution of operators used in MQL4 and that's just one section of the book.

Also so many other sections including 4 hits for " iCustom" in the book and site wide there are many more eg, Search for iCustom gives 284 hits


I appreciate your eagerness to make EA - but imho [potential] money making aspirations must be tempered with building a solid foundation upon which you can build that killer EA

My eagerness to help is limited... As you may have noticed, my replies are long and this takes [for me anyway a long and painful] time. and... There are far more knowledgeable types on this forum than me... for totally sure.

I have commitments outside this site and however much I input - in the end, it is your journey and with all due respect to you F, the forum is not actually for teaching basic programming skills - that is each persons responsibility. There are masses of programming tutorials on web for the C Programming Language which would easily provide the aforementioned solid foundation.


Regarding the docs, yes - they are somewhat abstract but looking at it in a different perspective, this could also push you towards experimenting with small few line test scripts to test out and discover for yourself what docs are saying - personally, this is my main way of learning and... is so much faster than relying on forum, all the info really is on this site - just use search box. The Print() statement is invaluable in dumping values to Terminal etc.

By experimenting, the by product is a massive increase in your overall MQL4 and MT4 knowledge base.


Remember, a simple script that calls iCustom() and then uses Print() to display result is only 2 lines of code...

Is easy to select various shift values and armed with this and printed value(s), you can look at chart to see if agree. If the ever updating chart is a problem, just print out the string result of TimeToStr( Time[shiftOfTheBarYouLookingAtViaiCustom] ) - the Time[..] is constant once you've printed it out and not then matter if chart gets more bars such that Time[shift] no longer maps same datum/bar.


I really hth



ps.

I have only one aim - to encourage or if necessary, push and shove (politely of course ;) posters to really consider the alternatives to always posting over each new bump encountered on their MT learning path.

These bumps will never go away - as in life, struggle defines people and [can] make them strong.

Learning to be self-reliant is from a practical viewpoint - massive time saver. By their very nature, forums are [generally] working at snail speed.

I mean no disrespect to anyone - life is so brief, yes?

On many posts I mention the MQL4 book and the search box seen at top right of page.... massive, massive resource locater!

There is just so much info on this site - imho, in an ideal world, the forum ought to be akin to the last chance saloon :)

Get on down 'n boogie dude!

A thought for all seekers of MQL4, MT4 [ &life ] enlightment: you are already enlightened, only have to accept that you are...

Use the force, Luke!

and as usual... standard poster's caveat applies: all IMHO

:o))

 
avatar
22
fryfly 2008.05.06 21:31 #
 

Yes sorry, I understand that i am asking a lot considering its your free time. I have discovered that the indicator cannot have data imported, so therefore I will need to copy the code into the EA and implement it that way. Gonna take some work to do this.

I have read through the book, but I suppose I should really try to make simple operations as u suggest to 'get my feet wet'. Then I will learn much more and wont waste other ppls free time. Thanks again for your great help it is much appreciated.

Now on to learning!

Catch up another time matey.

 
Back to topics list  

To add comments, please log in or register