Repetition

Three statements repeat a block: a counted loop, an iteration loop, and a conditional loop. break and continue work inside all of them.

The counted loop

Give a name, a starting value, and a value to count to. The name is available inside the block.

float total = close
for i = 1 to 4 {
    total := total + close[i]
}

Add step to count by something other than one.

float total = close
for i = 2 to 10 step 2 {
    total := total + close[i]
}

step is a reserved word

Because the counted loop uses it, step is reserved. You cannot use it as the name of an argument in a call: a named argument written step = 2 does not parse, wherever it appears.

This one rule is worth remembering. Breaking it is the commonest cause of a compile failure.

The iteration loop

The second form of for walks a source instead of counting. It is written for name in name. The source has to be a plain name: an expression in that position does not parse.

No worked example is given here. Which values can be walked as a source is not documented, and a guessed example would be worse than none.

while

while repeats its block for as long as a condition holds.

int i = 1
while close[i] > close {
    i += 1
    if i > 20 {
        break
    }
}

break and continue

break leaves the loop. continue abandons the rest of the block and starts the next pass.

break outside a loop is rejected. The interpreter reports it rather than ignoring it.

What a loop cannot do

It cannot draw. Chart output functions have to be called at the top level of a script, and a loop body is not the top level. Work out a value in the loop and plot it afterwards.

It cannot read unlimited history. A script can look back at most 500 bars. A loop that indexes further fails while the script is running rather than when it is checked, and the error names the function that asked.

It cannot run without bound. The interpreter enforces its own resource limits and reports a diagnostic when one is exceeded, rather than returning a partial result. Give a while loop an exit that you control.

A complete script

indicator("Five-bar sum", "sum5", false)
float total = close
for i = 1 to 4 {
    total := total + close[i]
}
plot(total / 5)
Ready to put this into practice?
Try GoCharting Premium
Unlock advanced orderflow, market profile, options desk, and real-time data — everything you just read about, live in your charts.
Upgrade