Exciting Update: Version 1.0.0 is now available, introducing high-performance technical indicators and custom drawing tools. Read more
Version: 1.0.0

Simple Moving Average (SMA)

Calculate and display the Simple Moving Average (SMA) indicator as a line plot overlay.

Overview

The Simple Moving Average (SMA) calculates the average price of an asset over a specified number of periods. It is plotted directly over price candles to smooth short-term volatility and identify long-term trends.

SMA Calculation

The math sums the close prices of the last N bars and divides by N:

// Simple SMA calculation loop
function calculateSMA(bars, period) {
  const sma = [];
  for (let i = 0; i < bars.length; i++) {
    if (i < period - 1) {
      sma.push(null);
      continue;
    }
    let sum = 0;
    for (let j = 0; j < period; j++) {
      sum += bars[i - j].close;
    }
    sma.push(sum / period);
  }
  return sma;
}

Registering SMA Indicator

The SMA indicator registers with the Charting API using the following structure:

window.ChartingAPI.registerIndicator('sma', {
  name: 'SMA',
  type: 'overlay', // Overlay directly on the candlestick pane
  params: { period: 9 },
  defaultColor: '#2196f3',
  calculate: function(bars, params) {
    const period = params.period || 9;
    return calculateSMA(bars, period);
  },
  render: function(ctx, chart, values, bounds, color) {
    // Canvas line rendering pass...
  }
});

Configuration Parameters

  • period: Simple average length (typically 9, 20, 50, or 200).
  • color: Custom hex code for line plot styling.