MACD values not matching broker/chart in my algo — what am I doing wrong?

Asked by Sejpalsinh Jadeja · SOLVED
1 reply 517 views Jump to solution Reply
Sejpalsinh Jadeja Original Post
AlgoDelta Team

I’m calculating MACD in my algo using my 1-minute candles.

I implemented EMA (12, 26) and signal line (9), but when I compare with chart values, they don’t match exactly. Candle data looks correct, still MACD is slightly off.

Is there any specific way to calculate MACD properly so it matches chart values?

Posted Apr 24
Reply

    1 Reply

    Tech Support AlgoDelta
    Tech Support AlgoDelta Automation Expert ·

    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:])
    Verified Solution
    • Got it, thanks for the code it’s really help me a lot to solve this problem. – Sejpalsinh Jadeja Team Jul 3
    Markdown supported · ```json for code blocks · paste or drop screenshots

    Be specific and kind. Never share API keys, passwords or personal account details.

    Welcome to the community

    Log in or create your account in under a minute.

    1. 1Mobile
    2. 2E-mail
    3. 3Password
    +91

    Have a password?

    By continuing you agree to the community guidelines. We’ll send a one-time code by SMS.