Returns the simple moving average: the plain mean of the last length values of source, na until length bars exist.
ta.sma adds the last length values of source, including the current bar's, and divides by length. Every value in the window counts the same, so a spike leaves the average only when it drops out of the window.
The first value appears on bar number length. Before that, and whenever any value inside the window is na, the result is na. The window counts executions of the call, so call ta.sma on every bar rather than inside an if block.
Syntax
ta.sma(source: series int/float, length: series int) -> series floatArguments
| Name | Type | Default | Description |
|---|---|---|---|
| source | series int/ | required | Series of values to average, such as close, hl2 or another indicator's output. |
| length | series int | required | Number of bars in the window. A whole number of 1 or more; a smaller value stops the script with an error. |
Returns
series float: the mean of the last length values of source, or na while the window is not full.
Remarks
- Simple averages lag price by about (length - 1) / 2 bars. Use
ta.emaorta.wmato put more weight on recent bars. ta.sma(x, 1)returns x. A length longer than the number of bars on the chart returns na on every bar.
Example
//@version=6
indicator("SMA pair", overlay = true)
fastLen = input.int(20, "Fast length", minval = 1)
slowLen = input.int(50, "Slow length", minval = 1)
plot(ta.sma(close, fastLen), "Fast SMA", color = color.orange)
plot(ta.sma(close, slowLen), "Slow SMA", color = color.blue, linewidth = 2)See also
Runs on Sidechair