Posts

Showing posts with the label while loop

How to Use 'for' and 'while' Loops in Pine Script v6: A Complete Technical Guide

Image
Pine Script executes once per bar by default, but many quantitative algorithms require iterating over a range of values or historical data within a single bar's execution context. Understanding how for and while loops work in Pine Script v6 — including their scoping rules, variable update mechanics, and performance implications — is essential for building robust, mathematically sound indicators and strategies. 1. Execution Model: Why Loops Matter in Pine Script Pine Script's runtime processes bars sequentially from left to right on the chart. On each bar, your script runs top-to-bottom exactly once. Loops allow you to perform multiple iterations within a single bar's execution , enabling calculations like manual moving averages, custom lookback aggregations, or iterative optimization routines. graph TD A["Bar N Execution Starts"] --> B["Script runs top-to-bottom"] B --> C{"Loop Encou...