DocsStrategy APIindicators

MACD (Moving Average Convergence Divergence)

MACD is one of the most popular technical indicators. It shows the relationship between two EMAs and provides momentum, trend direction, and signal line crossover information.

Declaration

function init(ctx) { ctx.indicator('macd', 'MACD', { fastPeriod: 12, slowPeriod: 26, signalPeriod: 9 }); }

Options

OptionTypeDefaultDescription
fastPeriodnumber12Fast EMA period
slowPeriodnumber26Slow EMA period
signalPeriodnumber9Signal line EMA period

Output

Returns an object with three series, accessed via underscore naming:

PropertyDescription
lineMACD line (fast EMA - slow EMA)
signalSignal line (EMA of MACD line)
histogramHistogram (MACD line - signal line)

Accessing Values

function onBar(ctx, i) { const macdLine = ctx.ind.macd_line[i]; const signal = ctx.ind.macd_signal[i]; const histogram = ctx.ind.macd_histogram[i]; }

Use Cases

Signal Line Crossover

function onBar(ctx, i) { if (q.crossOver(ctx.ind.macd_line, ctx.ind.macd_signal, i)) { ctx.order.market('ASSET', 1, { signal: 'buy', reason: 'macd_cross_up' }); } if (q.crossUnder(ctx.ind.macd_line, ctx.ind.macd_signal, i)) { ctx.order.close('ASSET', { signal: 'sell', reason: 'macd_cross_down' }); } }

Histogram Momentum

function onBar(ctx, i) { const hist = ctx.ind.macd_histogram[i]; const prevHist = ctx.ind.macd_histogram[i - 1]; // Rising histogram = increasing bullish momentum if (hist > 0 && hist > prevHist) { // Strong bullish momentum } }

Calculation

  • MACD Line = EMA(fast) - EMA(slow)
  • Signal Line = EMA(MACD Line, signalPeriod)
  • Histogram = MACD Line - Signal Line

Related

  • EMA - Underlying EMA calculations
  • PPO - Percentage-based momentum oscillator
  • RSI - Another popular momentum indicator
indicatormacdmomentumtrendoscillatorqsl