Sidechair

for

Browse the reference

Repeats a block with a counter that runs from a start value to an end value in steps, both ends included.

Try it in the editor

for i = start to end runs its block once for each whole number from start up to and including end, adding 1 each time. Add by to change the step: for i = 0 to 20 by 5 runs for 0, 5, 10, 15, 20. If start is larger than end the counter runs downward, so write the step as a positive number either way.

A for loop is an expression: it returns the last value its block evaluated, or na if it never ran. Use break to leave the loop early and continue to skip to the next pass. In v6 the end value is evaluated again before every pass, so a loop whose end changes inside the body can grow or shrink while running.

Syntax

[variables =|:=] for counter = from_num to to_num [by step_num] statements | continue | break return_expression

Remarks

  • The counter is an int and exists only inside the loop. Reading a history value with an offset, such as close[i], is the common use.
  • Loops run on every bar, so a loop of 500 passes over 5000 bars is 2.5 million passes. Prefer the built-in ta.* functions when one does the job.
  • A loop that reads history, such as close[i], can reach before the first bar, where the value is na. Wrap such reads in nz().
  • On Sidechair: all the loops on one bar together are limited to 500,000 passes, and the script stops with a message if it goes past that.

Example

Pine ScriptAverage of the last ten closesOpen in editor
//@version=6
indicator("For loop", overlay = true)
total = 0.0
for i = 0 to 9
    total += nz(close[i])
plot(total / 10, "Loop average", color.orange, 2)
plot(ta.sma(close, 10), "ta.sma", color.blue)

See also

Runs on Sidechair