Home Forums Pine Script How can I create a MACD indicator in Pine Script?

How can I create a MACD indicator in Pine Script?

  • Author
    Posts
    • 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?

    • 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.

Viewing 1 reply thread
×

Start a Discussion

Get help from the AlgoDelta community.

×

Welcome Back!

Enter your email to sign in or create an account. No passwords needed.

⚠️

Delete This?

Are you sure you want to delete this? This action is permanent and cannot be undone.

Scroll to Top