Yes, so MACD is depending on many factors to be correct.
So, to make it super accurate you need the right live candle data along with the sufficient historical data of that script.
And may be sometimes the calculation mismatch is also there. Things to remember use the closed candles only, preload enough data (e.g. at least 200 candles) and maintain EMA continuity.
Below is the code you can refer:
def calculate_ema(prices, period):
ema = []
k = 2 / (period + 1)
for i, price in enumerate(prices):
if i == 0:
ema.append(price)
else:
ema.append(price * k + ema[-1] * (1 - k))
return ema
def calculate_macd(prices):
ema12 = calculate_ema(prices, 12)
ema26 = calculate_ema(prices, 26)
macd_line = [e12 - e26 for e12, e26 in zip(ema12, ema26)]
signal_line = calculate_ema(macd_line, 9)
histogram = [m - s for m, s in zip(macd_line, signal_line)]
return macd_line, signal_line, histogram
# Sample
prices = [100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120]
macd, signal, hist = calculate_macd(prices)
print("MACD:", macd[-5:])
print("Signal:", signal[-5:])
print("Histogram:", hist[-5:])