# T402

> stateful calculation inside a loop

**Severity** Error

A `ta.*` call (or another call that keeps history between bars) appears inside a `for` loop. Every stateful call site owns one piece of history, and inside a loop a single site would be shared by all iterations, mixing their values.

Move the call out of the loop. For a few variants write one call per variant; for many, compute them from a rolling buffer with collection methods.

## Failing example

```flowscope
script "EMA fan"
data chart = subscribe(data.ohlcv)
setup lengths = [20, 50, 200]
plot top = plot.line(title: "Highest EMA")
state best: float = 0.0
on chart.close {
  best = 0.0
  for len in lengths {
    best = math.max(best, ta.ema(chart.close, len) ?? 0.0)
  }
  top.plot(best)
}
```

## Fixed example

```flowscope
script "EMA fan"
data chart = subscribe(data.ohlcv)
plot top = plot.line(title: "Highest EMA")
on chart.close {
  let e20 = ta.ema(chart.close, 20) ?? 0.0
  let e50 = ta.ema(chart.close, 50) ?? 0.0
  let e200 = ta.ema(chart.close, 200) ?? 0.0
  top.plot(math.max(e20, math.max(e50, e200)))
}
```

## Related

- [T428](/docs/scripting/reference/diagnostics/t428)
- [L001](/docs/scripting/reference/diagnostics/l001)
