expert advisor system or converting one to an MT4 expert advisor is to limit the ability to trade only once per bar. This is easily accomplished by the use of a module level variable within the Metatrader MQL4 language.A common desire when creating a forex MT4
By default, Metatrader 4 handles all data coming into the workstation tick by tick. A tick is a price change on the forex chart where your expert advisor is running. As each tick is processed, indicators and expert advisors are processed.
Note that it is possible to set up an expert advisor to run in an endless loop, to force it to calculate at a given time, like every 1 second. Endless loops are outside the scope of this tutorial and in my view are generally bad coding convention, but there are some legitamate uses for an endless loop such as for an indicator that tracks a basket of currencies, like Basket_Stats.mq4 or for placing, then modifying an order within a Metatrader script as is done in the Buy w/ SL & TP and Sell w/ SL & TP scripts. Because I tend to avoid endless loops unless special circumstances warrant, Basket_Stats.mq4 doesn't use endless loops. Whichever method you use (event driven or endless loop), module level variables can help in preventing code reentry into a trade block.
The simplest way to prevent an MT4 expert advisor from executing your MQL4 code more than once per bar is to declare a module level variable. Module level variables are declared at the top, just under the external declarations, like so:
In the above example the integer variable
The idea is to encapsulate your trading logic within a block of code that evaluates whether the current bar is a new bar or has already been evaluated for trade or conditional possibilites. This can be accomplished by creating a simple conditional block and placing your trade routine within this block like this:
The simple block above checks if the current bar (
To recap, if you wish to limit processing of a certain block of MQL4 code to only once per bar do the following:
Continue reading how to create a simple forex MT4 expert advisor template that trades only once per bar. If you've ever wanted a template to create simple expert advisors, this might be a good starting point. The code gets more complex as new functions are added to close out buy and sell orders, to keep track of the currently open position, and to place buy or sell orders. At the end of the MQL4 tutorial, a fully functional template is available for download.
Alternatively, if you would like to see a fully functional MT4 expert advisor that only trades once per bar, download the SnowRoller EA for MT4 Expert Advisor and check out the MQL4 code in the MetaEditor.