Skip to main content

ta.sma#

Simple moving average over the trailing length bars ending at index i.

SYNTAX#

function ta.sma(values: (number | null)[], length: number, i: number): number | null

ARGUMENTS#

  • values ((number | null)[]) — Series of input values, oldest-first. Same length as candles.
  • length (number) — Window length. Must be positive.
  • i (number) — Current bar index (typically the i argument of onBar).

RETURNS#

number | null — average over values[i-length+1 .. i], or null during warmup or on missing data.

REMARKS#

Re-walks the window on every call (O(length) per bar). For O(1) updates, maintain your own running sum in ctx.state. NaN, null, undefined, and ±Infinity all propagate to a null output.

EXAMPLE#

const closes = [];
function onBar(i, ctx) {
  closes[i] = candles[i].close;
  const v = ta.sma(closes, ctx.settings.length, i);
  if (v !== null) plot('sma', v, { color: '#42a5f5' });
}

SEE ALSO#

ta.ema, ta.stdev, ta.highest