MACD Divergence Indicator for ThinkorSwim

I've been using this Momentum Divergence study daytrading SPY options and have been struggling to make it tangible for many months. I have the rules for it but implementing with thinkscript can be a headache at times. There's an upper and lower study.
Currently the upper only plots one bullish div, and it doesn't have the 5 days on either side condition(step 4).

Bullish Mom Div:
1. Look at the last 60 price bars.
2. Find the lowest intraday price.
3. Look at the 28 MOM.
4. Was the lowest intraday low accompanied by a new low in MOM +/− five days on either side of the date of the price low?
5. If YES then there is no buy setup.
6. If no, then there is a buy setup (BSU).
7. If there is a BSU then mark your chart as follows:
A = the new intraday price low
B = the MOM for the same date as A
C = the lowest MOM previous to B
D = the intraday price low for the same date as point C
8. Examine your chart. Is the low at A lower than the low at D while the MOM at B is higher than the MOM at C?
9. If this is true, then find the highest MOM between points B and C inclusive (for example, including these two points) and mark it with the letter E.
10. If MOM penetrates E at the end of any bar then you have a buy trigger.
11. After the trigger has been hit and you have entered a trade, find the highest intraday high and the lowest intraday low between points A and D.
12. Calculate the difference between these two prices.
13. Calculate 50 percent of the difference. You now have the first profit target (PT1).
14. If you have a long position, add the price of the market on the trigger date to PT1 to get your exact profit target
15. The full profit target (PT2) is the full range of the difference you calculated.

Bearish Mom Div:
1. Look at the last 60 price bars.
2. Find the highest intraday price high.
3. Look at the 28 MOM.
4. Was the highest intraday high accompanied by a new high in MOM +/− five days on either side of the date of the price high?
5. If YES then there is no sell setup.
6. If NO then there is a sell setup (SSU).
7. If there is a SSU, then mark your chart as follows:
A = the new intraday price high
B = the MOM for the same date as A
C = the highest MOM previous to B
D = the intraday price high for the same date as point C
8. Examine your chart. Is the high at A higher than the high at D, while the MOM at B is lower than the MOM at C?
9. If this is true, then find the lowest MOM between points B and C inclusive (i.e., including these two points) and mark it with the letter E.
10. If MOM penetrates E at the end of any bar, then you have a sell trigger.
11. After the trigger has been hit and you have entered a trade, find the highest intraday high and the lowest intraday low between points A and D.
12. Calculate the difference between these two prices.
13. Calculate 50 percent of the difference. You now have the first profit target (PT1).
14. If you have a short position, subtract the price of the market on the trigger date from PT1 to get your exact profit target.
15. The full profit target (PT2) is the full range of the difference you calculated.

The idea:
  • it runs through the chart and plots all the momentum div setups (A, B, C, D points and/or line)
  • a price level that starts at point E and extends right until Momentum crosses E's value
  • if this is possible, these boxes(from BenTen's study with Demand Zones) be added that start at the price when Momentum crosses E and ends at PT1 and PT2 price levels, or any way to show PT1 and PT2 per div
* end of study. this will be made into a strategy as well and I will post in the comments when it is made. just want to offer both the study and the strategy*

If anyone can help or would like to complete this, it would save me time and stress. For some this could be very easy, to me it is not. Well not with thinkscript. I was able to script this in python and have it place trades with TDA's APIs. Being able to see it would be incredible and greatly appreciated.
 
image-37.png


Below is code for divergence columns , you can get code and tutorial for squeeze columns at tosindicators.com for free .
https://tosindicators.com/indicators/ttm-squeeze-dashboard

Code:
#Dvg Columns
def PosDvgMACD = LinearRegressionSlope()."LRS" is less than or equal to 0 and
LinearRegressionSlope("price" = MACD())."LRS" is greater than 0 and
MACD()is less than 0;

def NegDvgMACD = LinearRegressionSlope()."LRS" is greater than or equal to 0 and
LinearRegressionSlope("price" = MACD())."LRS" is less than 0 and
MACD()is greater than 0;

AddLabel(PosDvg, "PosDvgMACD", color.black);
AddLabel(NegDvg, "NegDvgMACD", color.black);
AddLabel(!PosDvg and !NegDvg, " ", color.black);

AssignBackgroundColor(if bullish then color.green else if NegDvg then color.red else color.black);
 
@westsail5000

westsail5000 said:
The current diff is 20% or more over the average diff"

Like @XeoNoX, not quite sure what you're looking for. I'm contributing what hopefully fits your scenario, since I was practicing custom watchlist columns while reviewing my Swing watchlist today.

Below uses the default MACD
diffAvg is the average of the DIFF
averageTypeDiff is the averageType, it is of the SIMPLE type by default. (toggle comments if you want EXPONENTIAL vs. SIMPLE type.)
^upon review,
diffLength is the number of bars used to compute the average, 26 by default.
diffIncrease is the percentage of change. .2 = 20%, by default.

I couldn't determine if "more" meant "more positive" or simply "more of what it already is". That is, what if the diffAvg is a NEGATIVE value?
That is, consider this:
10+2 = 12. 10 increased by 20%
-10 -2 = =12. -10 went more negative by 20%.
-10 +2 = -8. -10 went more positive by 20%.

I wasn't sure which version you were looking for, so added a scenario to consider both. Just uncomment the Scan.assignValueColor that you need.

Hope this helps (i only coded it 'cause I was hoping it already existed when I came to this thread.)
# Note: this is based on the original ThinkOrSwim MACD. This allows you flexibility to alter your MACD values and what-not.

Code:
# MACD Diff Average Plotter
# tradecombine
# V04.04.2021 Study/Scanner
# 
# Based on request from @westsail5000 @usethinkscript
# https://usethinkscript.com/threads/hidden-macd-divergence-indicator-for-thinkorswim.35/page-4
# Based on the ThinkOrSwim original MACD
# https://tlc.thinkorswim.com/center/reference/Tech-Indicators/studies-library/M-N/MACD

input fastLength = 12;
input slowLength = 26;
input MACDLength = 9;
input diffLength = 26;
input diffIncrease = .2;
input averageType = AverageType.EXPONENTIAL;
input averageTypeDiff = AverageType.SIMPLE;
#input averageDiff = AverageType.EXPONENTIAL;
input showBreakoutSignals = no;

def Value = MovingAverage(averageType, close, fastLength) - MovingAverage(averageType, close, slowLength);
def Avg = MovingAverage(averageType, Value, MACDLength);
def Diff = Value - Avg;
def diffAvg = MovingAverage(averageTypeDiff, Diff, diffLength);

Plot Scan = diffAvg;
# If Positive Increase is what matters
#Scan.assignValueColor(if (Diff[0] >= (diffIncrease * AbsValue(diffAvg)) + diffAvg) then Color.Green else Color.White);
# If increasing Range is what matters
#Scan.assignValueColor(if Diff[0] > 0 && diffAvg > 0 && Diff[0] >= (diffIncrease * diffAvg + diffAvg) then Color.Green else if Diff[0] < 0 && diffAvg < 0 && Diff[0] <= (diffIncrease * diffAvg + diffAvg) then Color.Red Else Color.White);
 
@Batman See post#1 Read through the thread to understand the peculiarities of the MACD Divergence Indicator
 
https://funwiththinkscript.com/indicators/macd-divergence/

True Divergence between upper and lower. When you click on link above it shows you "live" in action and it seems pretty good. Ive recently taken a liking to divergences and thought wow this thing pretty much paints them for you, so pretty easy to spot. I like that you can monkey around with MTF too.
Here's a screen shot. Would love to know if someone came close to duplicating it. Ive searched and found couple divergence chats but not like this. Hope its here somewhere.

⚠ edited by moderator. Shared media blocked.
**Images, Videos, Media content from commercial websites can NOT be shared on this forum. The Internet is not in and of itself public domain. Most commercial material is protected by copyright.
 
Last edited by a moderator:
@dmaffo The only MACD divergence scripts on this forum are in this thread.
 
Last edited:
Thats too bad, this one looks pretty good. It makes it so easy to spot divergences. If using steady time frame I would suspect it not to repaint.
 
Would you or someone please upload the code to this MACD Hostogram Divergence indicator? It is no longer available in the video.
I think I understand, are you after the bottom script on this youtube video you shared?
If so the script never exited that I know of here. I tried looking for it but could not find. Regardless I hope this is the picture of the script you were after so at least we all know what you were after.
pidRO7E.jpg
 
Many years ago I developed a Stochastic Divergence Indicator, (code below and photos below), works best on 5 min time frame and up. I made this from a lot of cutting and pasting/trial and error. Basically when a Divergence is detected a the indicator produces a spike in the lower study section. The photos show where these divergences are, please note, I drews these lines, not the indicator.

What I'm trying to do now, is develop a similar study but for the MACD Oscillator, reason why, the MACD filters how more False Signals than the Stochastic, I'll post some marked up photos.

Here's my Original Stochastic Divergence Code:

input over_bought = 80;
input over_sold = 20;
input KPeriod = 14;
input DPeriod = 3;
input priceH = high;
input priceL = low;
input priceC = close;
input averageType = AverageType.SIMPLE;
input showBreakoutSignals = {default "No", "On FullK", "On FullD", "On FullK & FullD"};

def lowest_k = Lowest(priceL, KPeriod);
def c1 = pricel - lowest_k;
def c2 = Highest(priceH, KPeriod) - lowest_k;
def FastK = if c2 != 0 then c1 / c2 * 100 else 0;

def FullK = MovingAverage(averageType, FastK);
def FullD = MovingAverage(averageType, FullK, DPeriod);

def upK = FullK crosses above Over_sold;
def upD = FullD crosses above Over_sold;
def downK = FullK crosses below Over_bought;
def downD = FullD crosses below Over_bought;

plot data = (upd)or (upk);

Here's the photo of how it works:


Heres' the photos of what I'm trying to accomplish.

MACD Oscillator Divergence Signal. As you can see, sometimes the Stochastic Divergence lines up with the MACD Oscillator, however, there are many more false signals, does anyone know how to clean this up?

 
Many years ago I developed a Stochastic Divergence Indicator, (code below and photos below), works best on 5 min time frame and up. I made this from a lot of cutting and pasting/trial and error. Basically when a Divergence is detected a the indicator produces a spike in the lower study section. The photos show where these divergences are, please note, I drews these lines, not the indicator.

What I'm trying to do now, is develop a similar study but for the MACD Oscillator, reason why, the MACD filters how more False Signals than the Stochastic, I'll post some marked up photos.
The false signals make the MACD Divergence too unreliable.
Read more here:
https://www.investopedia.com/articl...115/why-macd-divergence-unreliable-signal.asp
 
The false signals make the MACD Divergence too unreliable.
Read more here:
https://www.investopedia.com/articl...115/why-macd-divergence-unreliable-signal.asp
I see what you're saying, it seems to depend on how you read the divergence. If you look at a lot of those example in the article, they're focusing on a long range of price movement to MACD correlation. But if you look at the examples and the oscillation high and low directly after the previous ones, the were some pull backs along the way. So I wouldn't necessarily rely on divergence for a reversal especially if going against the overall market trend but I would look at a divergence for a fade or small pull back.

However, market momentum does play a big factor with stochastic or MACD, when the market is extremely bullish, it will blow through several divergences and vice versa. But historically I find a bullish divergence has a higher probability than a bearish divergence.

From the example of my indicator alone, you can see a high probability. But trend isn't necessarily reversing however, it is reacting in line with the divergence.
 
anyone know how to scan for the first yellow bar after a red bar under the mobius Divergence code? Thanks
 
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.
# _____________________________________________________________

any suggestions on the time frame to use on this? also how do you read the chart. it plots a top bar and a bottom bar, when the price is near the bottom bar, does that mean go long or is that a stoploss like wise if the bar is on top and price gets near it does that mean short or go long? same question if the bottom line support breaks vs top like resistance breaks? any thoughts on how you use this indicator @john3
 
any suggestions on the time frame to use on this? also how do you read the chart. it plots a top bar and a bottom bar, when the price is near the bottom bar, does that mean go long or is that a stoploss like wise if the bar is on top and price gets near it does that mean short or go long? same question if the bottom line support breaks vs top like resistance breaks? any thoughts on how you use this indicator @john3
There is nothing in the code that prevents it from being used on all timeframes.
if your question is how to use divergences in a strategy:
https://www.google.com/search?q=how...9i57j0i390.6921j0j15&sourceid=chrome&ie=UTF-8
 
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.
# _____________________________________________________________
This code seems really good and I am using it with some rules and seems to be doing okay but I still don't understand exactly what is it actually plotting.
What is the top line?
What is the bottom line?
What does it indicate when the price is between the two?
What does it indicate when the price is above the top line when bottom line is under the top line? And vise versa
Likewise what does it mean when the price is over the bottom line but bottom line is on top of the top line? And vise versa
When the bottom line shifts up or down what does that mean? Same question for the top line.

I wish I knew how to read the source code but I can't decipher it.
If anyone who can may be just look at this code and tell me in simple English what is the code actually saying I would greatly appreciate it.
Thanks
 

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
359 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