MACD Divergence Indicator for ThinkorSwim

BenTen

Administrative
Staff member
Staff
VIP
Lifetime
Here we have a MACD Divergence indicator for ThinkorSwim platform. This one should be able to give you potential signals for regular and hidden MACD divergences.

Xsl4jwQ.png


Full notes from the author:

The MACD Histogram divergence as per Alexander Elder's definition was tricky to code (also your reference links were not working so I had to search and read his book for the definition) and it took me many days but I finally solved it! To my knowledge, no one has coded the MACD Histogram divergence per Elder's definition in thinkScript before. The following script will plot large red arrows at potential regular bearish divergence, large green arrows at potential regular bullish divergence, small pink arrows at potential hidden bearish divergence and small lime arrows at potential hidden bullish divergence. The code will also alert you if arrow is plotted.

The reason I am using the word "potential" is because the code compares the high or low with the previous swing high or swing low to determine divergence (instead of comparing two swing highs or two swing lows), in order to get a fast signal before divergence is complete. Once you get the arrow(s) then wait for the MACD Histogram bar to become smaller for entry signal. If after the arrows are plotted, the histogram bars keep getting bigger to the point there is no divergence, then it is a no go.

I could have coded for divergence between two swing highs or two swing lows once the swing points have been determined, but it takes few smaller bars after the highest or lowest bar to determine swing high or swing low point, so plotting of the arrow will be delayed by few bars and by then price might already have moved a lot and signal might not be as useful. My code does not lag and arrow is plotted immediately if there is a potential divergence. You can change the number of bars used to determine the previous swing high or swing low in "edit properties" (default is 2).

This code is an upper study only and will not plot the MACD Histogram. Use the standard MACD Histogram in ToS as the lower study. In the Auto versus Manual pane in top right corner, make sure to uncheck all boxes except "fit study markers". Switching extended hours on or off will make a difference in divergences.

W2MBWbI.png


thinkScript Code

Rich (BB code):
input bar = 2;

input fastLength = 12;

input slowLength = 26;

input MACDLength = 9;

input averageType = AverageType.EXPONENTIAL;

plot Diff = MACD(fastLength, slowLength, MACDLength, averageType).Diff;

def SwingHigh = Diff > 0 and Diff >= highest(Diff[1], bar) and Diff >= highest(Diff[-bar], bar);

def SHprice = if SwingHigh then Diff else SHprice[1];

def SHBar = if SwingHigh then BarNumber() else SHBar[1];

def CrossBarL = if Diff crosses below 0 then BarNumber() else CrossBarL[1];

def SwingLow = Diff < 0 and Diff <= lowest(Diff[1], bar) and Diff <= lowest(Diff[-bar], bar);

def SLprice = if SwingLow then Diff else SLprice[1];

def SLBar = if SwingLow then BarNumber() else SLBar[1];

def CrossBarH = if Diff crosses above 0 then BarNumber() else CrossBarH[1];

def SHSP = if SwingHigh then high else SHSP[1];

def SLSP = if SwingLow then low else SLSP[1];

def BearDiv = Diff > 0 and CrossBarL[1] > SHBar[1] and Diff < SHprice[1] and high > SHSP[1] and SHprice[1] - Diff > 0.005;

def BullDiv = Diff < 0 and CrossBarH[1] > SLBar[1] and Diff > SLprice[1] and low < SLSP[1] and Diff - SLprice[1] > 0.005;

def HiddenBearDiv = Diff > 0 and Diff > SHprice[1] and high < SHSP[1] and Diff - SHprice[1] > 0.005;

def HiddenBullDiv = Diff < 0 and Diff < SLprice[1] and low > SLSP[1] and SLprice[1] - Diff > 0.005;

plot BearD = if BearDiv then high else Double.NaN;

        BearD.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);

        BearD.AssignValueColor(Color.RED);

        BearD.SetLineWeight(3);

plot BullD = if BullDiv then low else Double.NaN;

        BullD.SetPaintingStrategy(PaintingStrategy.ARROW_UP);

        BullD.AssignValueColor(Color.UPTICK);

        BullD.SetLineWeight(3);

plot HiddenBearD = if HiddenBearDiv then high else Double.NaN;

        HiddenBearD.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);

        HiddenBearD.AssignValueColor(Color.PINK);

        HiddenBearD.SetLineWeight(1);

plot HiddenBullD = if HiddenBullDiv then low else Double.NaN;

        HiddenBullD.SetPaintingStrategy(PaintingStrategy.ARROW_UP);

        HiddenBullD.AssignValueColor(Color.LIME);

        HiddenBullD.SetLineWeight(1);

Alert(BearDiv[1], "Short MACD divergence", Alert.BAR, Sound.Ring);

Alert(BullDiv[1], "Long MACD divergence", Alert.BAR, Sound.Ring);

Alert(HiddenBearDiv[1], "Short hidden MACD divergence", Alert.BAR, Sound.Ring);

Alert(HiddenBullDiv[1], "Long hidden MACD divergence", Alert.BAR, Sound.Ring);

Shareable Link

https://tos.mx/Cbe8LU

Here is another indicator that displays MACD divergence on the upper chart.

Code:
# MACD Divergence Pivots
# Mobius
# V03.05.2015 Upper Study

input n = 2;

input fastLength = 12;

input slowLength = 26;

input MACDLength = 9;

input averageType = AverageType.EXPONENTIAL;

def h = high;

def l = low;

def bar = barNumber();

def Diff = MACD(fastLength, slowLength, MACDLength, averageType).Diff;

def CurrMACDh = if Diff > 0

                then fold i = 1 to n + 1

                with p = 1

                while p

                do Diff > getValue(Diff, -i)

                else 0;

def CurrMACDPivotH = if (bar > n and

                         Diff == highest(Diff, n) and

                         CurrMACDh)

                     then h

                     else double.NaN;

def CurrMACDl = if Diff < 0

                then fold j = 1 to n + 1

                with q = 1

                while q

                do Diff < getValue(Diff, -j)

                else 0;

def CurrMACDPivotL = if (bar > n and

                         Diff == lowest(Diff, n) and

                         CurrMACDl)

                     then l

                     else double.NaN;

def CurrPHBar = if !isNaN(CurrMACDPivotH)

                then bar

                else CurrPHBar[1];

def CurrPLBar = if !isNaN(CurrMACDPivotL)

                then bar

                else CurrPLBar[1];

def PHpoint = if !isNaN(CurrMACDPivotH)

              then CurrMACDPivotH

              else PHpoint[1];

def priorPHBar = if PHpoint != PHpoint[1]

                 then CurrPHBar[1]

                 else priorPHBar[1];

def PLpoint = if !isNaN(CurrMACDPivotL)

              then CurrMACDPivotL

              else PLpoint[1];

def priorPLBar = if PLpoint != PLpoint[1]

                 then CurrPLBar[1]

                 else priorPLBar[1];

def HighPivots = bar >= highestAll(priorPHBar);

def LowPivots = bar >= highestAll(priorPLBar);

def pivotHigh = if HighPivots

                then CurrMACDPivotH

                else double.NaN;

plot PlotHline = pivotHigh;

    PlotHline.enableApproximation();

    PlotHline.SetDefaultColor(GetColor(7));

    PlotHline.SetStyle(Curve.Short_DASH);

plot pivotLow = if LowPivots

                then CurrMACDPivotL

                else double.NaN;

    pivotLow.enableApproximation();

    pivotLow.SetDefaultColor(GetColor(7));

    pivotLow.SetStyle(Curve.Short_DASH);

plot PivotDot = if !isNaN(pivotHigh)

                then pivotHigh

                else if !isNaN(pivotLow)

                     then pivotLow

                     else double.NaN;

    pivotDot.SetDefaultColor(GetColor(7));

    pivotDot.SetPaintingStrategy(PaintingStrategy.POINTS);

    pivotDot.SetLineWeight(3);

# End Code Pivots with Projections
 
Last edited by a moderator:
@Ace_Trader posted this scanner for the MACD Divergence indicator in our chatroom. I thought it was really cool and worth saving. Here is the code to put into your scanner.

It will be in the form of a Watchlist. That way you can easily have it on the left column and have an eye out for new divergences being formed.

lN3Lu0H.png


MACD Divergence Scanner

Bullish MACD Divergence

Rich (BB code):
MACD_Divergence_2019()."pivotLow" is true within 6 bars

Bearish MACD Divergence

Rich (BB code):
MACD_Divergence_2019()."PlotHline" is true within 6 bars

YouTube Tutorial
 
Last edited:
Hi Guys. I am new here but am just flabber gasted buy the great work you have done. I know its been mentioned before but what do I do if I load the indicator ( like this one for MACD Divergence) and it squeezes the chart?

I read further and know about unchecking in the auto/manual tab all but fit study markers. THANKS! I will try to calm my excitement down.
 
Last edited:
Here's another version of MACD divergence, shared by @john3

Code:
# MACDDIVERGENCE_R1V1
# R1V1   2011.05.14:22:15 - TONY LIPTON
#        monitors macd divergenge for entry

#        MAJOR CODE CONTRIBUTION by KumoBob aka Bob Campbell
#        http://fibonacci-financial.blogspot.com/

INPUT VFL = 12;
INPUT VSL = 26;

DEF VLB = VFL + VSL;

DEF vh34 = highest(MACDHistogram(VFL,VSL),VLB);
DEF vl34 = lowest(MACDHistogram(VFL,VSL),VLB);

input ChartBubblesON = NO;
input LinesON = Yes;

rec top;
rec bot;

top = if
MACDHistogram(VFL,VSL) == VH34
then High  else top[1];
bot = if
MACDHistogram(VFL,VSL) == VL34
then Low  else bot[1];

plot topline = if !LinesOn then Double.NaN else top;
topline.SetLineWeight(1);
topline.assignValueColor(if ((top < HIGH)) then color.DOWNTICK  else color.gray);
topline.SetPaintingStrategy(PaintingStrategy.points);
plot bottomline =  if !LinesOn then Double.NaN else bot;
bottomline.SetLineWeight(1);
bottomline.assignValueColor(if ((LOW < bot)) then color.UPTICK else color.gray);
bottomline.SetPaintingStrategy(PaintingStrategy.dashes);
# _____________________________________________________________
# Thinkscript is the property of ThinkorSwim and TDAmeritrade
# Sections of this script may have been copied or modified from
# one or more Thinkscript studies in part or in their entirety.
# _____________________________________________________________
 
Wow thank you so much! I was having trouble finding the true MACD divergence on my own, but your code blew my mind 🤯

Code:
# ToS Name: MACD_DivergenceCandles_MobiusEtAl
# Archive Name: MACD Divergence Candles_MobiusEtAl
# Certain comments by Johnny Quotron

# 04.21.2018  Johnny Quotron..upon inspection it appears this script is incomplete.
#    The script identifies divergences only when the MACD histogram is falling and the high is rising
#    I will do my best to correct this
#    added wedges to enhance visibility

# Posted in the thinkscript lounge on March 14, 2018
# 12:30 Wally: # MACD Divergence
# http://tos.mx/YtIZcq#
# MACDdivergence_Mobius
# MACD Divergence
# Values in MACD are default values
# If Price and MACD are Divergent Bar will be colored White
# Price for the purpose if identifying the Divergence is based on High rather than Close by JQ
# Mobius
# Chat Room Request 03.10.2014

input displayReminderLabel = yes;
input fastLength = 12;          #  length was 13 in wally share
input slowLength = 26;         #  length was 21 in wally share
input MACDLength =  9;       #  length was 8 in wally share
input AverageType = {SMA, default EMA};

def MACDcurrent = MACD(fastLength = fastLength,
                         slowLength = slowLength,
                         MACDLength = MACDLength,
                         AverageType = AverageType);


def MACDprevious =  MACD(fastLength = fastLength,
                         slowLength = slowLength,
                         MACDLength = MACDLength,
                         AverageType = AverageType)[1];

# DivergenceUp logic if MACD is falling and High is rising you have Divergence
def DivergenceUP = if MACDcurrent is less than MACDprevious
                and
                    high is greater than high[1]
                then 1
                    else Double.NaN;    # if the MACD Histogram is Falling and the High is rising then "DivergenceUP" by JQ

AssignPriceColor(if !isNaN(DivergenceUP)
                then Color.White
                else Color.Current);          # if DivergenceUP is a number then paint the candle white by JQ

# wedge plot by JQ
plot DivergenceWedgeUP = DivergenceUP;
divergenceWedgeUP.setpaintingstrategy(paintingstrategy.boolean_wedge_up);
divergenceWedgeUP.setdefaultcolor(color.white);

addlabel (yes, "MACDprevious = " + MACDprevious + " MACDcurrent = " + MACDcurrent + " ", color.lime);
addlabel (MACDcurrent < MACDprevious, " DivergenceUP condition met: MACD Falling", color.lime);
addlabel (MACDcurrent >= MACDprevious, " DivergenceUP condition failed: MACD rising", color.pink);
addlabel (yes, "high[1] = " + high[1] + " high = " + high + " ", color.lime);
addlabel (high > high[1], " DivergenceUp condition met: High is Rising ", color.Lime);
addlabel (high < high[1], " DivergenceUp condition failed: High is Falling ", color.pink);

# Divergence Down Logic

def DivergenceDN = if MACDcurrent is greater than MACDprevious
                 and
                    low is less than low[1]
                 then 1
                     else Double.NaN;    # if the MACD Histogram is Falling and the High is rising then "DivergenceDN" by JQ

AssignPriceColor(if !isNaN(DivergenceDN)
                then Color.yellow
                else Color.Current);          # if DivergenceDN is a number then paint the candle white by JQ

# wedge plot by JQ
plot DivergenceWedgeDN = DivergenceDN;
divergenceWedgeDN.setpaintingstrategy(paintingstrategy.boolean_wedge_down);
divergenceWedgeDN.setdefaultcolor(color.white);


addlabel (yes, "MACDprevious = " + MACDprevious + " MACDcurrent = " + MACDcurrent + " ", color.yellow);
addlabel (MACDcurrent > MACDprevious, " DivergenceDN condition met: MACD Rising", color.yellow);
addlabel (MACDcurrent <= MACDprevious, " DivergenceUP condition failed: MACD Falling", color.pink);
addlabel (yes, "low[1] = " + low[1] + " low = " + low + " ", color.yellow);
addlabel (low < low[1], " DivergenceDN condition Met: Low is Falling ", color.Yellow);
addlabel (low > low[1], " DivergenceUp condition Failed: Low is Rising ", color.pink);

addlabel (displayReminderLabel, " White candles indicate divergence.  Wedges indicates direction ", color.white);

# End code
 
Hello, I am writing through a translator, sorry if there are errors.
I want to ask if you have
MACD Divergence
, only as a filter for the watchlist? If so, I will be very grateful to you.
 
@Portland I'm not aware of any MACD divergence watchlist column that is available out there. Unless someone can create one.
 
Here's another version of MACD divergence, shared by @john3

Code:
# MACDDIVERGENCE_R1V1
# R1V1   2011.05.14:22:15 - TONY LIPTON
#        monitors macd divergenge for entry

#        MAJOR CODE CONTRIBUTION by KumoBob aka Bob Campbell
#        http://fibonacci-financial.blogspot.com/

INPUT VFL = 12;
INPUT VSL = 26;

DEF VLB = VFL + VSL;

DEF vh34 = highest(MACDHistogram(VFL,VSL),VLB);
DEF vl34 = lowest(MACDHistogram(VFL,VSL),VLB);

input ChartBubblesON = NO;
input LinesON = Yes;

rec top;
rec bot;

top = if
MACDHistogram(VFL,VSL) == VH34
then High  else top[1];
bot = if
MACDHistogram(VFL,VSL) == VL34
then Low  else bot[1];

plot topline = if !LinesOn then Double.NaN else top;
topline.SetLineWeight(1);
topline.assignValueColor(if ((top < HIGH)) then color.DOWNTICK  else color.gray);
topline.SetPaintingStrategy(PaintingStrategy.points);
plot bottomline =  if !LinesOn then Double.NaN else bot;
bottomline.SetLineWeight(1);
bottomline.assignValueColor(if ((LOW < bot)) then color.UPTICK else color.gray);
bottomline.SetPaintingStrategy(PaintingStrategy.dashes);
# _____________________________________________________________
# Thinkscript is the property of ThinkorSwim and TDAmeritrade
# Sections of this script may have been copied or modified from
# one or more Thinkscript studies in part or in their entirety.
# _____________________________________________________________
Ben could you elaborate a little on how this code works and what these lines mean, reference the above code from Tony Lipton, thanks
 
@Trading51 I don't have much experience with that indicator, not sure if I would be able to explain it to you.
 
@Juxtapose MACD should be the default indicator in ToS. Now sure which which buy and sell are you referring to?
 
Someone please slap for being ***** again today... 1051 PL to 83 At close. Divergence is 100% accurate after the first 2-3 red arrow down and green arrow up. Definitely banging big tomorrow.
 
i too tried the divergence with IWM. It works quite well and i was able to simulate the buy/sell point on paper trade. I've actually entered a buy order at the last 5 minutes as it shows a double bottom. looking for another nice gap up tomorrow.
 

Join useThinkScript to post your question to a community of 21,000+ developers and traders.

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
289 Online
Create Post

Similar threads

Similar threads

The Market Trading Game Changer

Join 2,500+ subscribers inside the useThinkScript VIP Membership Club
  • Exclusive indicators
  • Proven strategies & setups
  • Private Discord community
  • ‘Buy The Dip’ signal alerts
  • Exclusive members-only content
  • Add-ons and resources
  • 1 full year of unlimited support

Frequently Asked Questions

What is useThinkScript?

useThinkScript is the #1 community of stock market investors using indicators and other tools to power their trading strategies. Traders of all skill levels use our forums to learn about scripting and indicators, help each other, and discover new ways to gain an edge in the markets.

How do I get started?

We get it. Our forum can be intimidating, if not overwhelming. With thousands of topics, tens of thousands of posts, our community has created an incredibly deep knowledge base for stock traders. No one can ever exhaust every resource provided on our site.

If you are new, or just looking for guidance, here are some helpful links to get you started.

What are the benefits of VIP Membership?
VIP members get exclusive access to these proven and tested premium indicators: Buy the Dip, Advanced Market Moves 2.0, Take Profit, and Volatility Trading Range. In addition, VIP members get access to over 50 VIP-only custom indicators, add-ons, and strategies, private VIP-only forums, private Discord channel to discuss trades and strategies in real-time, customer support, trade alerts, and much more. Learn all about VIP membership here.
How can I access the premium indicators?
To access the premium indicators, which are plug and play ready, sign up for VIP membership here.
Back
Top