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 afororwhileloop. - A
ta.*call in thetobound of aforloop, 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
//@chartscript 1
indicator("Loop average")
let total = 0.0
for (let i = 1; i <= 3; i++) {
total += ta.sma(close, 10)
}
plot(total)Fixed
//@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)#Related
- CS2503 — name inside a condition only updates on the bars where this line runs. Move it out of the condition for the usual result.