MACD Divergence Indicator for ThinkorSwim

What is the top line?
# top line highest(MACD,38) is the highest MACD value in the last 38 bars.
What is the bottom line?
# bottom line lowest(MACD,38) is the lowest MACD value in the last 38 bars.
What does it indicate when the price is above the top line when bottom line is under the top line? And vise versa
When the price CROSSES BELOW the bottom line would be entering buy territory. CROSSES ABOVE the top line, look to sell.

The only way to determine if there is any meaning to you as pertains to your other questions is to put the indicator on your chart. Nothing beats personal experience ;) To determine if this indicator brings value, analyze it over different timeframes, across history and with multiple instruments. The only way you will know what works best for you is to play with the settings and see how the indicator lines up w/ your strategy and with your other indicators.
jOlZ4WS.png
 
Last edited:
# top line highest(MACD,38) is the highest MACD value in the last 38 bars.

# bottom line lowest(MACD,38) is the lowest MACD value in the last 38 bars.

When the price CROSSES BELOW the bottom line would be entering buy territory. CROSSES ABOVE the top line, look to sell.


The only way to determine if there is any meaning to you as pertains to your other questions is to put the indicator on your chart. Nothing beats personal experience ;) To determine if this indicator brings value, analyze it over different timeframes, across history and with multiple instruments. The only way you will know what works best for you is to play with the settings and see how the indicator lines up w/ your strategy and with your other indicators.
jOlZ4WS.png
Thanks for responding.
the top lines and the bottom lines is the higher and lowest value of the MACD histogram. thanks for clearing that up. with that logic i guess the lines moves up or down if its past the 38 look back period. it seems that the lower bar acts as support when over the moving averages and trending up like wise the top bar acts as resistance during a down trend when below the moving averages. still playing around with it to make it more obvious with other indicators for confirmation.
 
Last edited by a moderator:
@tem2005
To scan:

MACD Divergence Scanner​

Bullish MACD Divergence

Code:
MACD_Divergence_2019()."pivotLow" is true within 6 bars

  1. Cut & Paste 1st script in post#1 as a study with the name: MACD_Divergence_2019
  2. Cut & Paste the above code into the scan hacker.
the "within 6 bars" tells your scan to find signals over the last 6 bars. If you want just the current bar then delete "within 6 bars"
and you are set.


Here is a tutorial: https://usethinkscript.com/threads/how-to-use-thinkorswim-stock-hacker-scans.284/
If still having problems. Please attach a marked up image of any problems and errors.
 
Last edited:
Is there anyone that can write the code for an Automatic MACD Divergence like the one in the photo below?

05.18.2022-20.21.png
 
Last edited by a moderator:
Is there anyone that can write the code for an Automatic MACD Divergence like the one in the photo below?
No, we have no open source scripts. Many have tried. But there has been no real successes. Most members are still eyeballing it.
 
Last edited:
...
def upK = FullK crosses above Over_sold;
def upD = FullD crosses above Over_sold;
...
plot data = (upd)or (upk);

Guy A: I have a "Push" car.
Guy B: "Correction, that fine automobile that you have is a Porsche!"
Guy A: "Yes, a "Push" car."
Guy B: "No, it's a Porsche!"
Guy A: "OK, it's alright. You can keep the name, I'll keep the car"

I state that joke because I'm about to disagree with you that you coded a divergence, but it doesn't matter what you call it, as long as it's WORKING FOR YOU.

Your Stochastic code only tells you if FullK or FullD crosses above your OverSold line.

While I agree that crossing above OverSold can be a great signal, I don't see it as divergence.

Investopedia said:

What is Divergence?​

Divergence is when the price of an asset is moving in the opposite direction of a technical indicator, such as an oscillator, or is moving contrary to other data.
Reference: https://www.investopedia.com/terms/d/divergence.asp

For example, if you compared current and prior crossovers of your OverSold line to current and prior high/low values of the Symbol, then I would see that as a decent divergence comparison.

Hope this makes sense.

As far as your request for a MACD Divergence indicator, I did start on one a few days ago, but never completed it. I plan to complete it and share it on these great forums sometime in the near future.

My indicator looks at the MACD Values from prior to crossover compared to high/low values of the symbol just prior to crossover. Signal is generated after the cross-over.

See this video for an explanation of the type of MACD Divergence I am attempting to approximate (I'll try to code in as many of his rules as I can):
 
As far as your request for a MACD Divergence indicator, I did start on one a few days ago, but never completed it. I plan to complete it and share it on these great forums sometime in the near future.

My indicator looks at the MACD Values from prior to crossover compared to high/low values of the symbol just prior to crossover. Signal is generated after the cross-over.

Here it is.

It uses these rules posted by @TradePro on Youtube:

(how I implemented each rule in italics)
Warning: I may have mixed up less than or greater than somewhere in this code, so please double-check and note any errors.

MACD Bearish Divergence:
1. MACD w/ 12/26/9, the classic defaults
Based on ThinkorSwim Factory Default MACD

2. Both MACD and Signal Lines must be ABOVE the ZERO line.
Both MACD_VALUE and MACD_AVG must be GREATER than zero.

3. Higher-High on Price Action
Check for the first and second MACD crosses
Record the price of the candle [within window] immediately prior to each cross. Rationale: if it crossed, the candle should get further from the peak, and watching the video, he was comparing the MACD_VALUE prior to the cross, so it would only make sense to compare the price prior to the cross.
use the recorded values to make future comparisons

4. Lower-High on MACD
Check for the first and second MACD crosses
Record the value of MACD_VALUE [within window] immediately prior to each cross. Rationale: if it crossed, the candle should get further from the peak, and watching the video, he was comparing the MACD_VALUE prior to the cross.
use the recorded values to make future comparisons


5. Between the two points considered for divergence the MACD and Signal Lines DO NOT TOUCH the ZERO line
As explained previously, the crosses are already being tracked.
Also, track between the crosses, and make sure that both MACD lines remain ABOVE the zero line


6. There must be a GAP within the histogram between the peaks [cannot be one contiguous color]
This is satisfied by making sure that there is a first cross followed by a second cross.
Every time there is a cross, the histogram changes color, so if there is a first cross and then a second cross, the color will not be contiguous.


7. The pattern is complete AFTER the cross of the MACD in the direction of your signal
Already looking for that second cross in the code.
After the second cross, the arrow will be plotted.


MACD Bullish Divergence:
1. MACD w/ 12/26/9, the classic defaults
Based on ThinkorSwim Factory Default MACD

2. Both MACD and Signal Lines must be BELOW the ZERO line
Both MACD_VALUE and MACD_AVG must be LESS than zero.

3. Lower-Low on Price Action
Check for the first and second MACD crosses
Record the price of the candle [within window] immediately prior to each cross. Rationale: if it crossed, the candle should get further from the peak, and watching the video, he was comparing the MACD_VALUE prior to the cross, so it would only make sense to compare the price prior to the cross.
use the recorded values to make future comparisons

4. Higher-Low on MACD
Check for the first and second MACD crosses
Record the value of MACD_VALUE [within window] immediately prior to each cross. Rationale: if it crossed, the candle should get further from the peak, and watching the video, he was comparing the MACD_VALUE prior to the cross.
use the recorded values to make future comparisons


5. Between the two points considered for divergence the MACD and Signal Lines DO NOT TOUCH the ZERO line
As explained previously, the crosses are already being tracked.
Also, track between the crosses, and make sure that both MACD lines remain BELOW the zero line


6. There must be a GAP within the histogram between the peaks [cannot be one contiguous color]
This is satisfied by making sure that there is a first cross followed by a second cross.
Every time there is a cross, the histogram changes color, so if there is a first cross and then a second cross, the color will not be contiguous.


7. The pattern is complete after the cross of the MACD in the direction of your signal
Already looking for that second cross in the code.
After the second cross, the arrow will be plotted.



Code:
# MACD Divergence Indicator
# 2022-08-27 by tradecombine
# 
# Requested by Koolkth1 @usethinkscript forums:
# https://usethinkscript.com/threads/macd-divergence-indicator-for-thinkorswim.35/post-80549

# References:
# https://www.youtube.com/watch?v=9o6BG-dCgco
# https://www.youtube.com/watch?v=oQQ-VCJYc6M
# https://usethinkscript.com/threads/tutorial-hold-a-condition-true-until-for-thinkorswim.12093/
# https://stackoverflow.com/questions/56518594/how-to-create-a-variable-that-retains-its-value
# https://stackoverflow.com/questions/66630687/how-can-i-keep-the-atr-of-a-specific-candlestick-inside-a-variable-without-it-ch?rq=1
# https://usethinkscript.com/threads/answers-to-commonly-asked-questions.6006/post-67034
# https://tlc.thinkorswim.com/center/reference/Tech-Indicators/studies-library/M-N/MACD

input plotOffset = .3;
input window = 7;
input MACD_fastLength = 12;
input MACD_slowLength = 26;
input MACD_MACDLength = 9;

def MACD_VALUE = ExpAverage(close, MACD_fastLength) - ExpAverage(close, MACD_slowLength);
def MACD_AVG   = ExpAverage(MACD_VALUE, MACD_MACDLength);

def BEAR_VALUE = MACD_VALUE > 0 && MACD_AVG > 0;
def BULL_VALUE = MACD_VALUE < 0 && MACD_AVG < 0;
def BEAR_CROSS = MACD_VALUE[1] > MACD_AVG[1] && MACD_VALUE < MACD_AVG && BEAR_VALUE;
def BULL_CROSS = MACD_VALUE[1] < MACD_AVG[1] && MACD_VALUE > MACD_AVG && BULL_VALUE;

def VALID_BEAR_BETWEEN_CROSS = if BEAR_CROSS[1] && BEAR_VALUE then 1
                          else if VALID_BEAR_BETWEEN_CROSS[1] && BEAR_VALUE then 1
                          else    0;
                       

def VALID_BULL_BETWEEN_CROSS = if BULL_CROSS[1] && BULL_VALUE then 1
                          else if VALID_BULL_BETWEEN_CROSS[1] == 1 && BULL_VALUE then 1
                          else    0;

def BEAR_CROSS_SECOND = VALID_BEAR_BETWEEN_CROSS[1] == 1 && BEAR_CROSS;
def BEAR_CROSS_FIRST  = VALID_BEAR_BETWEEN_CROSS[1] == 0 && BEAR_CROSS;

def BULL_CROSS_SECOND = VALID_BULL_BETWEEN_CROSS[1] == 1 && BULL_CROSS;
def BULL_CROSS_FIRST  = VALID_BULL_BETWEEN_CROSS[1] == 0 && BULL_CROSS;


def BEAR_HIGH_WINDOW = highest(high, window);
def BULL_LOW_WINDOW  = lowest(low, window);
def BEAR_MACD_WINDOW = highest(MACD_VALUE, window);
def BULL_MACD_WINDOW = lowest(MACD_VALUE, window);

def BEAR_HIGH_FIRST = if BULL_VALUE then Double.NaN
                 else if BEAR_CROSS_FIRST then BEAR_HIGH_WINDOW[1]
                 else    BEAR_HIGH_FIRST[1];

def BEAR_HIGH_SECOND = if BULL_VALUE then Double.NaN
                  else if BEAR_CROSS_SECOND then BEAR_HIGH_WINDOW[1]
                  else    BEAR_HIGH_SECOND[1];

def BULL_LOW_FIRST =  if BEAR_VALUE then Double.NaN
                 else if BULL_CROSS_FIRST then BULL_LOW_WINDOW[1]
                 else    BULL_LOW_FIRST[1];
 
def BULL_LOW_SECOND = if BEAR_VALUE then Double.NaN
                 else if BULL_CROSS_SECOND then BULL_LOW_WINDOW[1]
                 else    BULL_LOW_SECOND[1];


def BEAR_MACD_FIRST = if BULL_VALUE then double.NaN
                 else if BEAR_CROSS_FIRST then BEAR_MACD_WINDOW[1]
                 else    BEAR_MACD_FIRST[1];

def BEAR_MACD_SECOND = if BULL_VALUE then Double.NaN
                 else if BEAR_CROSS_SECOND then BEAR_MACD_WINDOW[1]
                 else    BEAR_MACD_SECOND[1];

def BULL_MACD_FIRST =  if BEAR_VALUE then Double.NaN
                 else if BULL_CROSS_FIRST then BULL_MACD_WINDOW[1]
                 else    BULL_MACD_FIRST[1];
 
def BULL_MACD_SECOND = if BEAR_VALUE then Double.NaN
                 else if BULL_CROSS_SECOND then BULL_MACD_WINDOW[1]
                 else    BULL_MACD_SECOND[1];

def MACD_BULLISH_DIVERGENCE = BULL_LOW_FIRST  > BULL_LOW_SECOND  && BULL_MACD_FIRST < BULL_MACD_SECOND && BULL_CROSS_SECOND;
def MACD_BEARISH_DIVERGENCE = BEAR_HIGH_FIRST < BEAR_HIGH_SECOND && BEAR_MACD_FIRST > BEAR_MACD_SECOND && BEAR_CROSS_SECOND;

def prange = high - low;
def plotHIgh = high + prange * plotOffset;
def plotLow = low - prange * plotOffset;


plot Signal_MACD_Bullish_Divergence = if MACD_BULLISH_DIVERGENCE then plotLow else double.NaN;
plot Signal_MACD_Bearish_Divergence = if MACD_BEARISH_DIVERGENCE then plotHigh else double.NaN;

Signal_MACD_Bullish_Divergence.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
Signal_MACD_Bullish_Divergence.SetDefaultColor(Color.GREEN);
Signal_MACD_Bullish_Divergence.SetLineWeight(2);
Signal_MACD_Bearish_Divergence.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
Signal_MACD_Bearish_Divergence.SetDefaultColor(Color.RED);
Signal_MACD_Bearish_Divergence.SetLineWeight(2);
 
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:



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]

                 más anteriorPHBar[1];

def PLpunto = si !isNaN(CurrMACDPivotL)

              entonces CurrMACDPivotL

              else PLpunto[1];

def anteriorPLBar = if PLpunto != PLpunto[1]

                 entonces CurrPLBar[1]

                 más anteriorPLBar[1];

def HighPivots = bar >=highestAll(priorPHBar);

def LowPivots = bar >=highestAll(priorPLBar);

def pivotHigh = si HighPivots

                entonces CurrMACDPivotH

                más doble.NaN;

plot PlotHline = pivotHigh;

    PlotHline.enableApproximation();

    PlotHline.SetDefaultColor(GetColor(7));

    PlotHline.SetStyle(Curve.Short_DASH);

plot pivotLow = si LowPivots

                entonces CurrMACDPivotL

                más doble.NaN;

    pivotLow.enableApproximation();

    pivotLow.SetDefaultColor(GetColor(7));

    pivotLow.SetStyle(Curve.Short_DASH);

trazar PivotDot = si !isNaN(pivotHigh)

                luego pivote alto

                de lo contrario si !isNaN(pivotLow)

                     luego pivote bajo

                     más doble.NaN;

    pivotDot.SetDefaultColor(GetColor(7));

    pivotDot.SetPaintingStrategy(PaintingStrategy.POINTS);

    pivotDot.SetLineWeight(3);

# Pivotes de código final con proyecciones
How would the code be with the difference of a moving average of 5 periods -35 periods?'
 
Last edited:
The code you quoted includes inputs, that you can change to whatever you like.
Code:
input fastLength = 12;

input slowLength = 26;

input MACDLength = 9;
This is the code I tried, I couldn't find the divergence of maximum and minimum points

# Divergence Pivots
# Mobius
# V03.05.2015 Upper Study

input n = 7;

input fastLength = 5;

input slowLength = 34;

#input MACDLength = 0;

input averageType = AverageType.SIMPLE;

def h = high;

def l = low;

def bar = barNumber();

def Diff = (Average(CLOSE, fastLength) - Average(CLOSE, slowLength));

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
 
This is the code I tried, I couldn't find the divergence of maximum and minimum points
Code:
# Divergence Pivots
# Mobius
# V03.05.2015 Upper Study

input n = 7;

input fastLength = 5;

input slowLength = 34;

#input MACDLength = 0;

input averageType = AverageType.SIMPLE;

def h = high;

def l = low;

def bar = barNumber();

def Diff = (Average(CLOSE, fastLength) - Average(CLOSE, slowLength));

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


I pasted the code in a study, and loaded up the 1Y 1D chart of MSFT, and saw a couple lines.

couple notes:
#1. The code you posted is very dissimilar from the original study (e.g.: simple moving average, not calculating MACD, etc.) . You could try using the original study and experimenting with inputs.
#2. Please use the "code" tags to enclose your code in future posts.
 
For the MACD Divergence code, how can I get an alert when a BULLD or BearD is confirmed/true? I tried it on marketwatch menu on TOS by selecting a study and select the indicator and set it to true for BULLD or BearD, but it it stays as active and never triggers despite showing on the chart (arrow shows up). Appreciate your assistance.
 
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:



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
Hi there I tried to copy this code in TOS under the custom but it is not accepted. The "Ok" & "Apply" boxes are both greyed out so I could not save the script. What should I do? Thanks!
 
Hi there I tried to copy this code in TOS under the custom but it is not accepted. The "Ok" & "Apply" boxes are both greyed out so I could not save the script. What should I do? Thanks!
Sorry, you did not provide enough information to say where you went astray.
One of the more common reasons that the "Ok" & "Apply" boxes are both greyed out, is the name that you gave the study contains illegal or blank characters. Try simplifying the name (you can rename it later).

Here is a tutorial:
https://usethinkscript.com/threads/how-to-import-existing-thinkscript-code-on-thinkorswim.10/
 

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