DocsStrategy APIindicators

SMA (Simple Moving Average)

The SMA calculates the arithmetic mean of a price series over a lookback period. It is the simplest and most widely used moving average.

Declaration

function init(ctx) { ctx.indicator('sma50', 'SMA', { period: 50, source: 'close' }); ctx.indicator('sma200', 'SMA', { period: 200, source: 'close' }); }

Options

OptionTypeDefaultDescription
periodnumber20Number of bars to average
sourcestring'close'Price source (open, high, low, close, hl2, hlc3, ohlc4)

Output

Returns a single number[] series.

Accessing Values

function onBar(ctx, i) { const smaValue = ctx.ind.sma50[i]; const prevSma = ctx.ind.sma50[i - 1]; }

Use Cases

Golden Cross / Death Cross

function init(ctx) { ctx.indicator('sma50', 'SMA', { period: 50 }); ctx.indicator('sma200', 'SMA', { period: 200 }); } function onBar(ctx, i) { if (q.crossOver(ctx.ind.sma50, ctx.ind.sma200, i)) { ctx.order.market('ASSET', 1, { signal: 'buy', reason: 'golden_cross' }); } if (q.crossUnder(ctx.ind.sma50, ctx.ind.sma200, i)) { ctx.order.close('ASSET', { signal: 'sell', reason: 'death_cross' }); } }

Calculation

$$SMA = \frac{1}{N} \sum_{i=0}^{N-1} Price_{t-i}$$

Related

  • EMA - Exponentially weighted, faster response
  • WMA - Linearly weighted moving average
  • DEMA - Double EMA for reduced lag
indicatorsmamoving-averagetrendqsl