Saturday, February 18, 2012

mq4

I've been writing in mq4 code for the past few years and wanted to share some of it since it's what i primarily code in for enjoyment these days. its a variant of c++ used to automate trading of foreign exchange currencies or display visual aids on foreign exchange currency trading charts.

The following code snippet allows your code to only execute each time a new bar forms. This is important if you want to avoid false signals, as the expert advisor runs every tick, or second, and therefore all of the indicators are constantly fluctuating.

Create a global variable (place it before the start function):
int hour1=99;

This variable will serve to keep track of the current time. The value of 99 is insignificant, its just a random value that isn't equal to any possible tick value which might indicate a new bar. This way, the first time the EA runs, it analyzes whatever bar is on the screen right away, and then begins waiting for the next bar.

Inside the start function, use the following code:
if(hour1 == Time[0]) Exit Sub;
hour1=Time[0];

The first line will check to see if the current bar is new and if not, it exits the start function so your program won't waste any resources. This is especially helpful to speed up back-testing optimization. The second line only executes if there is a new bar forming. It resets the hour1 variable to the new time so your EA won't run the code again until the next new bar.

You could also wrap the code you want to execute inside the if statement and compare it for hour1 =! Time[0]. That can be useful if you have code you'd like to execute every tick, and code you'd like to execute only when a new bar forms. For example, I often choose an entry x number of pips away from the current target and would like to allow my EA to enter the trade rather than setting a Limit or a Stop order, so I monitor price each tick for that entry, but my entries are determined based on hourly bars, so i only want to run that portion of the code at the open of each new bar.

And remember, just because i called the variable hour1 doesn't mean it needs to be an hourly timeframe. Since we used the Time[0] variable instead of Hour[0] we are recording the actual current time value in ticks. This means the code will work on any timeframe window it is applied to.

No comments:

Post a Comment