Posted By:
30 Jul, 2014 10:34 am PDT

Cycles in MetaTrader

For loops can be used to repeat a certain task for a specified number of times until some condition is true. Syntax of  for loop is: 

 
for(declaration of a counter; the cycle operation conditions;
   counter changes)
  {
    // the source code, that will be repeated is in braces,
  }
Attachment:None


CYCLES

Suppose you decided to calculate a mean value of maximal prices of all bars in the chart. For this purpose you alternatively add each element to a variable, for example so:

doubleAveragePrice = 0.0;

AveragePrice += High[0];

AveragePrice += High[1];

AveragePrice += High[2];

AveragePrice += High[3];

AveragePrice += High[4];// ... and so on

AveragePrice /= Bars;

For such purposes there are cycles. Note, that all operations are absolutely similar, only the index changes from 0 to variable Bars-1 value. It would have been much more convenient somehow to determine a counter and using it refer to the array elements. We can solve this task using cycles:

doubleAveragePrice = 0.0;
for(inta = 0; a < Bars; a++)
{
AveragePrice += High[a];
}

In a general case it can be presented like this:

for(declaration of a counter; the cycle operation conditions;
counter changes)
{
// the source code, that will be repeated is in braces,
}

Cycle operation conditions can be different. For example like this:

a>10// the cycle works while a>10
a!=10// the cycle works while a is not equal to 10
a==20// while a is not equal to 20
a>=2// while a is more or equal to 2
a<=30// while a is less or equal to 30

The counter can be changed in a different way. For example, you do not have to increase it each time by 1. You can do like this:

a--// the counter will each time decrease by 1 
a += 2// the counter will each time increase by 2

Beside, you can place the counter change inside the cycle body. For example so:

for(inta=0; a<Bars;)
{
AveragePrice+=High[a];
 
a++; // the counter changes inside the cycle body
}

 

Was it useful?  




Please login to reply to this problem.