Skip to main content
A loop repeats a block within one bar’s run. Use talib functions for rolling statistics and loops for work that has no built-in, such as scanning an array.

for i = a to b

  • The counter takes the values a, a + 1, …, b, so 0 to 4 runs five times.
  • When a is larger than b the loop counts down by 1: for i = 10 to 0.
  • When a equals b the body does not run at all. So 0 to n - 1 visits n positions only for n of 2 or more: for n = 1 it runs zero times, and for n = 0 it counts down through 0 and -1. For an array use for x in a.
  • step sets the increment (for i = 10 to 0 step -2); its sign must point from a toward b, or the script stops when it runs with Step value should be less than 0 or Step value should be greater than 0.
  • a, b and step are numbers, evaluated once before the first pass; they may be series values. The counter has the type of a, so a loop with whole-number bounds cannot have a fractional step. The counter exists only inside the loop.
The compiler says: The step value type (literal float) for the for loop is not compatible with counter i type (literal int). Start the loop at 0.0 to count in floats.

for x in array

for x in a visits the elements of the array variable a in order and does nothing for an empty array. After in comes the name of an array variable, not an expression (anything else gives The for ... in loop can only iterate over an array.). x is a copy: assigning to it does not change the array.

while, break, continue

while condition { repeats while the condition (a bool or a number) holds. break leaves the innermost loop and continue skips to its next pass; outside a loop both are refused: Break statement can only be used inside a loop.
No loop has an iteration limit; the 45-second run limit is the only stop (see Limits).

The word step

step is reserved, so int step = 2 is refused (no viable alternative at input ‘intstep’), but it is allowed as a named argument: input.float(2.0, "Factor", step=0.5).