Skip to content
ChartDeck ChartScript docs Account Open the terminal

CS2504

warning name inside a loop keeps one value per bar: only its last call on each bar counts.

#What it means

This is a warning. A function with state (such as ta.sma) inside a loop has one state per bar, not one per pass of the loop: every pass on a bar shares it, and only the last call on each bar counts for the next bar.

#Typical cause

  • A ta.* call inside a for or while loop.
  • A ta.* call in the to bound of a for loop, which is read again before every pass.

#How to fix it

Compute the value once before the loop and use the variable inside it. If you need different lengths, compute each one at the top level. See Loops.

#Example

ChartScriptWarning: CS2504
//@chartscript 1
indicator("Loop average")
let total = 0.0
for (let i = 1; i <= 3; i++) {
    total += ta.sma(close, 10)
}
plot(total)

Fixed

ChartScriptOpen in editor
//@chartscript 1
indicator("Loop average")
const sma10 = ta.sma(close, 10)
let total = 0.0
for (let i = 1; i <= 3; i++) {
    total += sma10
}
plot(total)
  • CS2503 — name inside a condition only updates on the bars where this line runs. Move it out of the condition for the usual result.

The ChartScript documentation is in English for now; translations will follow.