How can I create a MACD indicator in Pine Script?

Asked by Radhesh Joshi · SOLVED
1 reply 214 views Jump to solution Reply
Radhesh Joshi Original Post
Strategy Builder

I’m creating my own technical indicators in Pine Script and want to build a MACD indicator from scratch instead of using a built-in indicator.

I want to understand how the MACD Line, Signal Line, and Histogram are calculated and how to plot all three values properly.

What is the correct way to implement MACD in Pine Script?

Posted Aug 13
Reply

    1 Reply

    Tech Support AlgoDelta
    Tech Support AlgoDelta Automation Expert ·

    Yes sir, you can definitely create a MACD indicator in Pine Script.

    MACD mainly consists of three components:

    -> MACD Line = Fast EMA – Slow EMA
    -> Signal Line = EMA of MACD Line
    -> Histogram = MACD Line – Signal Line

    You can create it using:

    //@version=6
    indicator("Custom MACD", overlay=false)
    fastLength = input.int(12, "Fast Length")
    slowLength = input.int(26, "Slow Length")
    signalLength = input.int(9, "Signal Length")
    
    fastEMA = ta.ema(close, fastLength)
    slowEMA = ta.ema(close, slowLength)
    
    macdLine = fastEMA - slowEMA
    signalLine = ta.ema(macdLine, signalLength)
    histogram = macdLine - signalLine
    
    histColor = histogram >= 0 ?
         (histogram > histogram[1] ? color.teal : color.new(#9ff3ea, 14)) :
         (histogram < histogram[1] ? color.red : color.new(#ffadad, 60))
    
    plot(macdLine, "MACD")
    plot(signalLine, "Signal")
    plot(histogram, "Histogram", style=plot.style_columns, color=histColor)

    -> The Fast EMA and Slow EMA are used to calculate the MACD Line.

    -> The Signal Line is calculated from the MACD Line.

    -> The Histogram shows the difference between the MACD Line and Signal Line.

    You can also change the 12, 26, and 9 values from the indicator settings because they are created as user inputs.

    So that’s how you can create a basic MACD indicator from scratch in Pine Script.

    Verified Solution
      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.