Partner Center Find a Broker

Last week, we’ve covered the if-else conditional statement and its usage in forex EA coding. This time, we’ll focus on the “For” statement, its proper syntax, and look at a few examples.

As mentioned in my overview of 3 Kinds of Operators Useful in Creating a Forex EA, the For statement is used to create a cycle that will be repeated while certain conditions are met.

The correct syntax is written:

For (expression; condition; expression)
{
Expressions or functions to be executed;
}

You can read the first line as “Starting from (expression), for as long as (condition) is met, update this (expression). After this, only will the succeeding expressions and functions inside the curly braces be performed.

For example, if you’d like to keep track of how many times a candle has closed above a simple moving average and you’d like to execute a buy order after four candles have fulfilled this criteria, you could have the following:

For (i=0; ClosingPrice > CurrentSMA; i=i+1)
{
Expressions or functions to be executed;
}

Note that this cycle would just keep running for as long as price closes above the current simple moving average. To enter an order after four consecutive candles have met this condition, you would have to include an if-else statement inside the for statement. Yep, that’s possible!

For (i=0; ClosingPrice > CurrentSMA; i=i+1)
{
If (i==4)
{
Set a buy order at the open of the next candle;
break;
}}

To prevent the For statement from going on an infinite loop, you can enter a “break operator” after an order has been taken in order to exit the cycle and stop the count.

As you’ve probably noticed in my recent articles, I haven’t gotten into the details of setting orders just yet so we’ll start with this right away next week. Keep in mind that we’ll probably need a few articles to cover this big topic so make sure you’ve got your basic data typesoperations and operators down pat before moving on to the next forex EA articles!