FOR

Category: Instructions

The FOR loop in ProBuilder language is a control flow statement that is used to repeat a block of code a specified number of times. This loop is particularly useful when you need to execute a sequence of commands multiple times, either with an ascending order using TO or a descending order using DOWNTO.

Syntax

FOR variable = start TO end DO
    // Commands to be repeated
NEXT

or

FOR variable = start DOWNTO end DO
    // Commands to be repeated
NEXT

Example Usage

Here is a simple example to demonstrate the use of a FOR loop to calculate the sum of opening prices over a range of bars:

a = 0
FOR i = 10 TO 20 DO
    a = open[i] + a
NEXT
RETURN a AS "Sum of Opens"

This example initializes a variable a to zero, then iterates from the 10th bar to the 20th bar, adding each bar’s opening price to a. After completing the loop, it returns the sum of the opening prices.

Advanced Example: Dynamic Moving Average Visualization

The following example demonstrates a more complex use of nested FOR loops to dynamically create a series of moving average lines, often referred to as a “Guppy Moving Average”.

defparam drawonlastbaronly=true
defparam calculateonlastbars=100

// Settings
lookback = 50
firstPeriod = 1
lastPeriod = 30

b = 1
FOR i = max(1, firstPeriod) TO max(1, lastPeriod) DO
    FOR a = 0 TO lookback DO
        drawsegment(barindex[a], average[i][a], barindex[a+1], average[i][a+1]) coloured(0, 191, max(1, 255-b))
    NEXT
    b = b + 5
NEXT
return

This script sets up a visualization where each moving average line is calculated from the firstPeriod to the lastPeriod and drawn over the last 100 bars. The color of each line gradually changes, and the loop increments to adjust the color intensity.

  • The FOR loop is essential for automating repetitive tasks and creating dynamic indicators and visualizations in trading analysis.
  • Understanding how to control the flow with TO and DOWNTO can significantly enhance the flexibility and efficiency of your trading scripts.

Related Instructions:

  • BREAK instructions
  • DO instructions
  • DOWNTO instructions
  • NEXT instructions
  • TO instructions
  • Logo Logo
    Loading...