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
| Option | Type | Default | Description |
|---|---|---|---|
fastPeriod | number | 12 | Fast EMA period |
slowPeriod | number | 26 | Slow EMA period |
signalPeriod | number | 9 | Signal line EMA period |
Output
Returns an object with three series, accessed via underscore naming:
| Property | Description |
|---|---|
line | MACD line (fast EMA - slow EMA) |
signal | Signal line (EMA of MACD line) |
histogram | Histogram (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
indicatormacdmomentumtrendoscillatorqsl