MACD is the difference between a fast and a slow EMA, plotted with a signal-line EMA and a histogram of the gap between them. Signal-line crossovers, zero-line crosses and histogram divergence are the classic triggers. Copy the version for your platform.
#property indicator_separate_window
#property indicator_buffers 3
extern int Fast_Period = 12;
extern int Slow_Period = 26;
extern int Signal_Period = 9;
double MacdBuf[], SignalBuf[], HistBuf[];
int OnInit() {
SetIndexBuffer(0, MacdBuf);
SetIndexBuffer(1, SignalBuf);
SetIndexBuffer(2, HistBuf);
return 0;
}
int OnCalculate(const int rates_total, const int prev_calculated, const double &close[]) {
for (int i = prev_calculated; i < rates_total; i++) {
MacdBuf[i] = iMA(NULL, 0, Fast_Period, 0, MODE_EMA, PRICE_CLOSE, i)
- iMA(NULL, 0, Slow_Period, 0, MODE_EMA, PRICE_CLOSE, i);
SignalBuf[i] = iMAOnArray(MacdBuf, 0, Signal_Period, 0, MODE_EMA, i);
HistBuf[i] = MacdBuf[i] - SignalBuf[i];
}
return rates_total;
}#property indicator_separate_window
#property indicator_buffers 3
input int Fast_Period = 12;
input int Slow_Period = 26;
input int Signal_Period = 9;
double MacdBuf[], SignalBuf[], HistBuf[];
int OnInit() {
SetIndexBuffer(0, MacdBuf);
SetIndexBuffer(1, SignalBuf);
SetIndexBuffer(2, HistBuf);
return INIT_SUCCEEDED;
}
int OnCalculate(const int rates_total, const int prev_calculated,
const datetime &time[], const double &open[], const double &high[],
const double &low[], const double &close[], const long &tick_volume[],
const long &volume[], const int &spread[]) {
for (int i = prev_calculated; i < rates_total; i++) {
MacdBuf[i] = iMA(NULL, 0, Fast_Period, 0, MODE_EMA, PRICE_CLOSE, i)
- iMA(NULL, 0, Slow_Period, 0, MODE_EMA, PRICE_CLOSE, i);
SignalBuf[i] = iMAOnArray(MacdBuf, 0, Signal_Period, 0, MODE_EMA, i);
HistBuf[i] = MacdBuf[i] - SignalBuf[i];
}
return rates_total;
}inputs: FastLen(12), SlowLen(26), SignalLen(9);
variables: MacdVal(0), SignalVal(0), HistVal(0);
MacdVal = MACD(Close, FastLen, SlowLen);
SignalVal = XAverage(MacdVal, SignalLen);
HistVal = MacdVal - SignalVal;
Plot1(MacdVal, "MACD");
Plot2(SignalVal, "Signal");
Plot3(HistVal, "Histogram");//@version=5
indicator("MACD", overlay=false)
fast = input.int(12, "Fast Length")
slow = input.int(26, "Slow Length")
signal_len = input.int(9, "Signal")
fastMA = ta.ema(close, fast)
slowMA = ta.ema(close, slow)
macd = fastMA - slowMA
signal = ta.ema(macd, signal_len)
hist = macd - signal
plot(macd, title="MACD", color=color.blue, linewidth=2)
plot(signal, title="Signal", color=color.orange)
plot(hist, title="Histogram", style=plot.style_histogram)
hline(0)To use it inside dtcharts, paste any version into the Script Converter and it becomes a native indicator on your chart.