Repaints MACD Divergences by @DaviddTech For ThinkOrSwim

Repaints

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

@LLP
find belw. pls check

CSS:
#//@version=4
#https://www.tradingview.com/script/soSwR4mX-MACD-Divergences-by-DaviddTech/
#study(title="MACD Divergences by @DaviddTech",  resolution="")
# Converted by Sam4Cok@Samer800 - 09/2022 - Requested by member from UseThinkscript.com
#// Getting inputs
declare lower;
input fast_length = 12;                # "Fast Length"
input slow_length = 26;                # "Slow Length"
input src = close;                     # "Source"
input signal_length = 9;               # "Signal Smoothing"
input sma_source = {Default EMA, SMA}; # "Oscillator MA Type"
input sma_signal = {Default EMA, SMA}; # "Signal Line MA Type"
input dontTouchZero = yes;             # "Don't touch the zero line?"
#// Plot colors
DefineGlobalColor("macd"       , CreateColor(41,98,255));    # >=90
DefineGlobalColor("signal"     , CreateColor(255,109,0));  # >=80
DefineGlobalColor("grow_above" , CreateColor(38,166,154)); # >=70
DefineGlobalColor("fall_above" , CreateColor(178,223,219)); # >=60
DefineGlobalColor("grow_below" , CreateColor(255,205,210));  # >=50
DefineGlobalColor("fall_below" , CreateColor(255,82,82));   # >=40
#// Calculating
def fast_ma = if sma_source == sma_source.SMA then SimpleMovingAvg(src, fast_length) else
                     ExpAverage(src, fast_length);
def slow_ma = if sma_source == sma_source.SMA then SimpleMovingAvg(src, slow_length) else
                     ExpAverage(src, slow_length);
def macd = fast_ma - slow_ma;
def signal = if sma_signal == sma_signal.SMA then SimpleMovingAvg(macd, signal_length) else
                ExpAverage(macd, signal_length);
def hist = macd - signal;
plot Histogram = hist;   # "Histogram"
Histogram.AssignValueColor(if hist>=0 then
                    if hist[1] < hist then GlobalColor("grow_above") else GlobalColor("fall_above")
               else if hist[1] < hist then GlobalColor("grow_below") else GlobalColor("fall_below"));
Histogram.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
plot macdLine = macd;    # "MACD"
macdLine.SetDefaultColor(GlobalColor("macd"));
plot SigLine = signal;   # "Signal"
SigLine.SetDefaultColor(GlobalColor("signal"));

#--- Div-----
input lbl = 5;
input lbr  = 5;
input rangeUpper = 60;
input rangeLower = 5;
input DivBull = yes;      # "Plot Bullish"
input DivHiddenBull = no; # "Plot Hidden Bullish"
input DivBear = yes;      # "Plot Bearish"
input DivHiddenBear = no; # "Plot Hidden Bearish"

def divSrc = macd;

def h = high;
def l = low;
script FindPivots {
    input dat = high; # default data or study being evaluated
    input HL  = 0;    # default high or low pivot designation, -1 low, +1 high
    input PF  = 1;    # default pivot forward period
    input PB  = 5;    # default pivot backward period
    ##############
    def _nan;    # used for non-number returns
    def _BN;     # the current barnumber
    def _VStop;  # confirms that the lookforward period continues the pivot trend
    def _V;      # the Value at the actual pivot point
    def _VBar;   # the bar number at the pivot point
    def _PV;     # the previous pivot Value
    def _PVBar;  # the previous pivot bar number
    def _VDiff;  # the difference in values between last two pivot points
    def _VDist;  # the diffence in barnumbers between last two pivot points
    def _VSlope; # the Slope calculated using value and distance changes
    def _VPivot; # used for the pivot point connector line only
    ##############
    _BN  = BarNumber();
    _nan = Double.NaN;
    _VStop =
        fold a = 1 to PF + 1
        with b = 1 while b
        do if HL > 0 then
            dat > GetValue(dat, -a) else
            dat < GetValue(dat, -a) ;
    if (HL > 0) {
        _V = if _BN > PB and dat == Highest(dat, PB) and _VStop
            then dat else _nan;
    } else {
        _V = if _BN > PB and dat == Lowest(dat, PB) and _VStop
            then dat else _nan;
    }
    _VBar   = if !IsNaN(_V) then _BN else _VBar[1];
    _PV     = if !IsNaN(_V) then GetValue(dat, _BN - _VBar[1]) else _PV[1];
    _PVBar  = if   _VBar != _VBar[1]
            then _PVBar[1] else _VBar;
    _VDiff  = AbsValue(_V) - AbsValue(_PV);
    _VDist  = _BN - _PVBar;
    _VSlope = if _V > _PV  then  1 else
              if _V < _PV  then -1 else 0;
    if (HL > 0) {
        _VPivot = _BN >= HighestAll(_PVBar);
    } else {
        _VPivot = _BN >= LowestAll(_PVBar);
    }
    plot result = if !IsNaN(_V) and _VStop then _V else _nan;
}
script valuewhen {
  input cond = 0;
  input pr = 0;
  input n2 = 0;
  def n = n2 + 1;
  def offset2 = fold j = 0 to 200
    with p
    while p < n + 1
    do p + ( if p == n then j - n else if GetValue(cond, j) then 1 else 0 );
  plot price = GetValue(pr, offset2-1);
}
#_inRange(cond) =>
script _inRange {
    input cond = yes;
    input rangeUpper = 60;
    input rangeLower = 5;
        def bars = if cond then 0 else bars[1] + 1;
        def inrange =  (rangeLower <= bars) and (bars <= rangeUpper);
plot retrun = inRange;
}
def ph =  findpivots(divSrc, 1, lbr, lbl);
def pl =  findpivots(divSrc, -1, lbr, lbl);

def phFound = if isNaN(ph) then 0 else 1;
def plFound = if isNaN(pl) then 0 else 1;

def vhFound = valuewhen(phFound, divSrc, 1);
def vlFound = valuewhen(plFound, divSrc, 1);

def phPrice = valuewhen(phFound, h, 1);
def plPrice = valuewhen(plFound, l, 1);

#// Regular Bullish
def oscHL = divSrc > vlFound and _inRange(plFound[1],rangeUpper,rangeLower) and divSrc < 0;
def priceLL = l < plPrice;
def priceHHZero = highest(divSrc, lbL+lbR+5);
def blowzero = if donttouchzero then priceHHZero < 0 else yes;
def bullCond = DivBull and plFound and oscHL and priceLL and blowzero;
#// Hidden Bullish
def oscLL = divSrc < vlFound and  _inRange(plFound[1],rangeUpper,rangeLower) and divSrc < 0;
def priceHL = l > plPrice;
def hiddenBullCond = DivHiddenBull and plFound and oscLL and priceHL and blowzero;

#// Regular Bearish
def oscLH   = divSrc < vhFound and _inRange(phFound[1],rangeUpper,rangeLower) and divSrc > 0;
def priceHH = h > phPrice;
def priceLLZero =  lowest(divSrc, lbL+lbR+5);
def bearzero = if donttouchzero then priceLLZero > 0 else yes;
def bearCond = DivBear and phFound and oscLH and priceHH and bearzero;
#// Hidden Bearish
def oscHH = divSrc > vhFound and  _inRange(phFound[1],rangeUpper,rangeLower) and divSrc > 0;
def priceLH = h < phPrice;
def hiddenBearCond = DivHiddenBear and phFound and oscHH and priceLH and bearzero;

addchartbubble(bullCond, divSrc, "R", color.green, no);
addchartbubble(bearCond, divSrc, "R", color.red, yes);
addchartbubble(hiddenBullCond, divSrc, "H", color.DARK_green, no);
addchartbubble(hiddenBearCond, divSrc, "H", color.DARK_red, yes);

#---- END
 
Last edited by a moderator:
@LLP
find belw. pls check

CSS:
#//@version=4
#https://www.tradingview.com/script/soSwR4mX-MACD-Divergences-by-DaviddTech/
#study(title="MACD Divergences by @DaviddTech",  resolution="")
# Converted by Sam4Cok@Samer800 - 09/2022 - Requested by member from UseThinkscript.com
#// Getting inputs
declare lower;
input fast_length = 12;                # "Fast Length"
input slow_length = 26;                # "Slow Length"
input src = close;                     # "Source"
input signal_length = 9;               # "Signal Smoothing"
input sma_source = {Default EMA, SMA}; # "Oscillator MA Type"
input sma_signal = {Default EMA, SMA}; # "Signal Line MA Type"
input dontTouchZero = yes;             # "Don't touch the zero line?"
#// Plot colors
DefineGlobalColor("macd"       , CreateColor(41,98,255));    # >=90
DefineGlobalColor("signal"     , CreateColor(255,109,0));  # >=80
DefineGlobalColor("grow_above" , CreateColor(38,166,154)); # >=70
DefineGlobalColor("fall_above" , CreateColor(178,223,219)); # >=60
DefineGlobalColor("grow_below" , CreateColor(255,205,210));  # >=50
DefineGlobalColor("fall_below" , CreateColor(255,82,82));   # >=40
#// Calculating
def fast_ma = if sma_source == sma_source.SMA then SimpleMovingAvg(src, fast_length) else
                     ExpAverage(src, fast_length);
def slow_ma = if sma_source == sma_source.SMA then SimpleMovingAvg(src, slow_length) else
                     ExpAverage(src, slow_length);
def macd = fast_ma - slow_ma;
def signal = if sma_signal == sma_signal.SMA then SimpleMovingAvg(macd, signal_length) else
                ExpAverage(macd, signal_length);
def hist = macd - signal;
plot Histogram = hist;   # "Histogram"
Histogram.AssignValueColor(if hist>=0 then
                    if hist[1] < hist then GlobalColor("grow_above") else GlobalColor("fall_above")
               else if hist[1] < hist then GlobalColor("grow_below") else GlobalColor("fall_below"));
Histogram.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
plot macdLine = macd;    # "MACD"
macdLine.SetDefaultColor(GlobalColor("macd"));
plot SigLine = signal;   # "Signal"
SigLine.SetDefaultColor(GlobalColor("signal"));

#--- Div-----
input lbl = 5;
input lbr  = 5;
input rangeUpper = 60;
input rangeLower = 5;
input DivBull = yes;      # "Plot Bullish"
input DivHiddenBull = no; # "Plot Hidden Bullish"
input DivBear = yes;      # "Plot Bearish"
input DivHiddenBear = no; # "Plot Hidden Bearish"

def divSrc = macd;

def h = high;
def l = low;
script FindPivots {
    input dat = high; # default data or study being evaluated
    input HL  = 0;    # default high or low pivot designation, -1 low, +1 high
    input PF  = 1;    # default pivot forward period
    input PB  = 5;    # default pivot backward period
    ##############
    def _nan;    # used for non-number returns
    def _BN;     # the current barnumber
    def _VStop;  # confirms that the lookforward period continues the pivot trend
    def _V;      # the Value at the actual pivot point
    def _VBar;   # the bar number at the pivot point
    def _PV;     # the previous pivot Value
    def _PVBar;  # the previous pivot bar number
    def _VDiff;  # the difference in values between last two pivot points
    def _VDist;  # the diffence in barnumbers between last two pivot points
    def _VSlope; # the Slope calculated using value and distance changes
    def _VPivot; # used for the pivot point connector line only
    ##############
    _BN  = BarNumber();
    _nan = Double.NaN;
    _VStop =
        fold a = 1 to PF + 1
        with b = 1 while b
        do if HL > 0 then
            dat > GetValue(dat, -a) else
            dat < GetValue(dat, -a) ;
    if (HL > 0) {
        _V = if _BN > PB and dat == Highest(dat, PB) and _VStop
            then dat else _nan;
    } else {
        _V = if _BN > PB and dat == Lowest(dat, PB) and _VStop
            then dat else _nan;
    }
    _VBar   = if !IsNaN(_V) then _BN else _VBar[1];
    _PV     = if !IsNaN(_V) then GetValue(dat, _BN - _VBar[1]) else _PV[1];
    _PVBar  = if   _VBar != _VBar[1]
            then _PVBar[1] else _VBar;
    _VDiff  = AbsValue(_V) - AbsValue(_PV);
    _VDist  = _BN - _PVBar;
    _VSlope = if _V > _PV  then  1 else
              if _V < _PV  then -1 else 0;
    if (HL > 0) {
        _VPivot = _BN >= HighestAll(_PVBar);
    } else {
        _VPivot = _BN >= LowestAll(_PVBar);
    }
    plot result = if !IsNaN(_V) and _VStop then _V else _nan;
}
script valuewhen {
  input cond = 0;
  input pr = 0;
  input n2 = 0;
  def n = n2 + 1;
  def offset2 = fold j = 0 to 200
    with p
    while p < n + 1
    do p + ( if p == n then j - n else if GetValue(cond, j) then 1 else 0 );
  plot price = GetValue(pr, offset2-1);
}
#_inRange(cond) =>
script _inRange {
    input cond = yes;
    input rangeUpper = 60;
    input rangeLower = 5;
        def bars = if cond then 0 else bars[1] + 1;
        def inrange =  (rangeLower <= bars) and (bars <= rangeUpper);
plot retrun = inRange;
}
def ph =  findpivots(divSrc, 1, lbr, lbl);
def pl =  findpivots(divSrc, -1, lbr, lbl);

def phFound = if isNaN(ph) then 0 else 1;
def plFound = if isNaN(pl) then 0 else 1;

def vhFound = valuewhen(phFound, divSrc, 1);
def vlFound = valuewhen(plFound, divSrc, 1);

def phPrice = valuewhen(phFound, h, 1);
def plPrice = valuewhen(plFound, l, 1);

#// Regular Bullish
def oscHL = divSrc > vlFound and _inRange(plFound[1],rangeUpper,rangeLower) and divSrc < 0;
def priceLL = l < plPrice;
def priceHHZero = highest(divSrc, lbL+lbR+5);
def blowzero = if donttouchzero then priceHHZero < 0 else yes;
def bullCond = DivBull and plFound and oscHL and priceLL and blowzero;
#// Hidden Bullish
def oscLL = divSrc < vlFound and  _inRange(plFound[1],rangeUpper,rangeLower) and divSrc < 0;
def priceHL = l > plPrice;
def hiddenBullCond = DivHiddenBull and plFound and oscLL and priceHL and blowzero;

#// Regular Bearish
def oscLH   = divSrc < vhFound and _inRange(phFound[1],rangeUpper,rangeLower) and divSrc > 0;
def priceHH = h > phPrice;
def priceLLZero =  lowest(divSrc, lbL+lbR+5);
def bearzero = if donttouchzero then priceLLZero > 0 else yes;
def bearCond = DivBear and phFound and oscLH and priceHH and bearzero;
#// Hidden Bearish
def oscHH = divSrc > vhFound and  _inRange(phFound[1],rangeUpper,rangeLower) and divSrc > 0;
def priceLH = h < phPrice;
def hiddenBearCond = DivHiddenBear and phFound and oscHH and priceLH and bearzero;

addchartbubble(bullCond, divSrc, "R", color.green, no);
addchartbubble(bearCond, divSrc, "R", color.red, yes);
addchartbubble(hiddenBullCond, divSrc, "H", color.DARK_green, no);
addchartbubble(hiddenBearCond, divSrc, "H", color.DARK_red, yes);

#---- END
Do you know why it shows a word "R" not "BULL" with green color like the original in Tradingview?
 
just change the bottom of the script

addchartbubble(bullCond, divSrc, "Bull", color.green, no);
addchartbubble(bearCond, divSrc, "Bear", color.red, yes);
addchartbubble(hiddenBullCond, divSrc, "Bull", color.DARK_green, no);
addchartbubble(hiddenBearCond, divSrc, "Bear", color.DARK_red, yes);
 
  • 100 %
Reactions: LLP
@samer800, Excellent codes!

How can I modify your codes to identify the previous pivots then draw a line to current pivot when divergence is detected?

Eg. what I'm trying to accomplish👇

Thanks!

MACD Div.jpg
 
Last edited by a moderator:
Can someone, Please ADD this 3 times breakout like original from TD code? See photo.
 

Attachments

  • Screenshot 2024-02-07 065428.MACD.BREAKOUT.png
    Screenshot 2024-02-07 065428.MACD.BREAKOUT.png
    208.7 KB · Views: 174
Can someone, Please ADD this 3 times breakout like original from TD code? See photo.
add the below at the end of the code:

CSS:
input showBreakoutSignals = no;

plot UpSignal = if macd crosses above 0 then 0 else Double.NaN;
plot DownSignal = if macd crosses below 0 then 0 else Double.NaN;

UpSignal.SetHiding(!showBreakoutSignals);
DownSignal.SetHiding(!showBreakoutSignals);
UpSignal.SetDefaultColor(Color.UPTICK);
UpSignal.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
DownSignal.SetDefaultColor(Color.DOWNTICK);
DownSignal.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
 
@samer800, Excellent codes!

How can I modify your codes to identify the previous pivots then draw a line to current pivot when divergence is detected?

Eg. what I'm trying to accomplish👇

Thanks!

View attachment 19126
check the below

CSS:
#//@version=4
#https://www.tradingview.com/script/soSwR4mX-MACD-Divergences-by-DaviddTech/
#study(title="MACD Divergences by @DaviddTech",  resolution="")
# Converted by Sam4Cok@Samer800 - 09/2022 - Requested by member from UseThinkscript.com
# updated for Upper study by Sam4Cok#SAmer800    - 02/2024
#// Getting inputs

input fast_length = 12;                # "Fast Length"
input slow_length = 26;                # "Slow Length"
input src = close;                     # "Source"
input signal_length = 9;               # "Signal Smoothing"
input sma_source = {default EMA, SMA}; # "Oscillator MA Type"
input sma_signal = {default EMA, SMA}; # "Signal Line MA Type"
input dontTouchZero = yes;             # "Don't touch the zero line?"

def na = Double.NaN;
#// Plot colors
DefineGlobalColor("macd"       , CreateColor(41, 98, 255));    # >=90
DefineGlobalColor("signal"     , CreateColor(255, 109, 0));  # >=80
DefineGlobalColor("grow_above" , CreateColor(38, 166, 154)); # >=70
DefineGlobalColor("fall_above" , CreateColor(178, 223, 219)); # >=60
DefineGlobalColor("grow_below" , CreateColor(255, 205, 210));  # >=50
DefineGlobalColor("fall_below" , CreateColor(255, 82, 82));   # >=40
#// Calculating
def fast_ma = if sma_source == sma_source.SMA then SimpleMovingAvg(src, fast_length) else
                     ExpAverage(src, fast_length);
def slow_ma = if sma_source == sma_source.SMA then SimpleMovingAvg(src, slow_length) else
                     ExpAverage(src, slow_length);
def macd = fast_ma - slow_ma;

#--- Div-----

#----Div-----------
input ShowLastDivLines = yes;
input ShowLastHiddenDivLines = no;
input DivBull = yes;      # "Plot Bullish"
input DivBear = yes;      # "Plot Bearish"
input DivHiddenBull = no; # "Plot Hidden Bullish"
input DivHiddenBear = no; # "Plot Hidden Bearish"
input LookBackRight  = 5; # "Pivot Lookback Right"
input LookBackLeft  = 5;  # "Pivot Lookback Left"
input MaxLookback = 60;   # "Max of Lookback Range"
input MinLookback = 5;    # "Min of Lookback Range"

def divSrc = macd;

def h = high;
def l = low;

script FindPivots {
    input dat = close; # default data or study being evaluated
    input HL  = 0;    # default high or low pivot designation, -1 low, +1 high
    input lbL  = 5;    # default Pivot Lookback Left
    input lbR  = 1;    # default Pivot Lookback Right
    ##############
    def _nan;    # used for non-number returns
    def _BN;     # the current barnumber
    def _VStop;  # confirms that the lookforward period continues the pivot trend
    def _V;      # the Value at the actual pivot point
    ##############
    _BN  = BarNumber();
    _nan = Double.NaN;
    _VStop = if !isNaN(dat) and lbr > 0 and lbl > 0 then
                fold a = 1 to lbR + 1 with b=1 while b do
                    if HL > 0 then dat > GetValue(dat,-a) else dat < GetValue(dat,-a) else _nan;
   if (HL > 0) {
        _V = if _BN > lbL + 1 and dat == Highest(dat, lbL + 1) and _VStop
            then dat else _nan;
    } else {
        _V = if _BN > lbL + 1 and dat == Lowest(dat, lbL + 1) and _VStop
            then dat else _nan;
    }
    plot result = if !IsNaN(_V) and _VStop then _V else _nan;
}
#_inRange(cond) =>
script _inRange {
    input cond = yes;
    input rangeUpper = 60;
    input rangeLower = 5;
        def bars = if cond then 0 else bars[1] + 1;
        def inrange =  (rangeLower <= bars) and (bars <= rangeUpper);
plot retrun = inRange;
}
def pl_ = findpivots(divSrc,-1, LookBackLeft, LookBackRight);
def ph_ = findpivots(divSrc, 1, LookBackLeft, LookBackRight);
def pl = !isNaN(pl_);
def ph = !isNaN(ph_);
def pll = lowest(divSrc,LookBackLeft);
def phh = highest(divSrc,LookBackLeft);
def sll = lowest(l, LookBackLeft);
def shh = highest(h, LookBackLeft);
#-- Pvt Low
def plStart  = if pl then yes else plStart[1];
def plFound  = if (plStart and pl) then 1 else 0;
def vlFound1 = if plFound then divSrc else vlFound1[1];
def vlFound_ = if vlFound1!=vlFound1[1] then vlFound1[1] else vlFound_[1];
def vlFound  = if !vlFound_ then pll else vlFound_;
def plPrice1 = if plFound then l else plPrice1[1];
def plPrice_ = if plPrice1!=plPrice1[1] then plPrice1[1] else plPrice_[1];
def plPrice  = if !plPrice_ then sll else plPrice_;
#-- Pvt High
def phStart = if ph then yes else phStart[1];
def phFound = if (phStart and ph) then 1 else 0;
def vhFound1 = if phFound then divSrc else vhFound1[1];
def vhFound_ = if vhFound1!=vhFound1[1] then vhFound1[1] else vhFound_[1];
def vhFound = if !vhFound_ then phh else vhFound_;
def phPrice1 = if phFound then h else phPrice1[1];
def phPrice_ = if phPrice1!=phPrice1[1] then phPrice1[1] else phPrice_[1];
def phPrice = if !phPrice_ then sll else phPrice_;
#// Regular Bullish
def priceHHZero =  highest(divSrc, LookBackLeft + LookBackRight + 5);
def blowzero = if donttouchzero then priceHHZero < 0 else yes;
def inRangePl = _inRange(plFound[1],MaxLookback,MinLookback);
def oscHL = divSrc > vlFound and inRangePl and divSrc < 0;
def priceLL = l < plPrice;
def bullCond = plFound and oscHL and priceLL and blowzero;
#// Hidden Bullish
def oscLL = divSrc < vlFound and inRangePl;
def priceHL = l > plPrice;
def hiddenBullCond = plFound and oscLL and priceHL;
#// Regular Bearish
def priceLLZero =  lowest(divSrc, LookBackLeft + LookBackRight + 5);
def bearzero = if donttouchzero then priceLLZero > 0 else yes;
def inRangePh = _inRange(phFound[1],MaxLookback,MinLookback);
def oscLH   = divSrc < vhFound and inRangePh and divSrc > 0;
def priceHH = h > phPrice;
def bearCond = phFound and oscLH and priceHH and bearzero;
#// Hidden Bearish
def oscHH = divSrc > vhFound and inRangePh;
def priceLH = h < phPrice;
def hiddenBearCond = phFound and oscHH and priceLH;

#------ Bubbles
def bullBub  = DivBull and bullCond;
def HbullBub = DivHiddenBull and hiddenBullCond;
def bearBub  = DivBear and bearCond;
def HbearBub = DivHiddenBear and hiddenBearCond;

addchartbubble(bullBub, low, "R", color.GREEN, no);
addchartbubble(bearBub, high, "R", CreateColor(156,39,176), yes);
addchartbubble(HbullBub, low, "H", color.DARK_green, no);
addchartbubble(HbearBub, high, "H", color.DARK_red, yes);

##### Lines
def bar = BarNumber();
#-- Bear Line
def lastPhBar = if ph then bar else lastPhBar[1];
def prePhBar = if lastPhBar!=lastPhBar[1] then lastPhBar[1] else prePhBar[1];
def priorPHBar = if bearCond then prePhBar else priorPHBar[1];
#-- Bull Line
def lastPlBar = if pl then bar else lastPlBar[1];
def prePlBar = if lastPlBar!=lastPlBar[1] then lastPlBar[1] else prePlBar[1];
def priorPLBar = if bullCond then prePlBar else priorPLBar[1];

def lastBullBar = if bullCond then bar else lastBullBar[1];
def lastBearBar = if bearCond then bar else lastBearBar[1];

def HighPivots = ph and bar >= HighestAll(priorPHBar) and bar <= HighestAll(lastBearBar);
def LowPivots  = pl and bar >= HighestAll(priorPLBar) and bar <= HighestAll(lastBullBar);

def pivotHigh = if HighPivots then high else na;
def pivotLow  = if LowPivots  then low else na;

plot PlotHline = if ShowLastDivLines then pivotHigh else na;
PlotHline.EnableApproximation();
PlotHline.SetDefaultColor(Color.RED);

plot PlotLline = if ShowLastDivLines then pivotLow else na;
PlotLline.EnableApproximation();
PlotLline.SetDefaultColor(Color.GREEN);

#--- Hidden Lines
#-- Bear Line
def priorHPHBar = if hiddenBearCond then prePhBar else priorHPHBar[1];
#-- Bull Line
def priorHPLBar = if hiddenBullCond then prePlBar else priorHPLBar[1];

def lastHBullBar = if hiddenBullCond then bar else lastHBullBar[1];
def lastHBearBar = if hiddenBearCond then bar else lastHBearBar[1];

def HighHPivots = ph and bar >= HighestAll(priorHPHBar) and bar <= HighestAll(lastHBearBar);
def LowHPivots  = pl and bar >= HighestAll(priorHPLBar) and bar <= HighestAll(lastHBullBar);

def pivotHidHigh = if HighHPivots then high else na;
def pivotHidLow  = if LowHPivots  then low else na;

plot PlotHBearline = if ShowLastHiddenDivLines then pivotHidHigh else na;
PlotHBearline.EnableApproximation();
PlotHBearline.SetDefaultColor(Color.DARK_RED);

plot PlotHBullline = if ShowLastHiddenDivLines then pivotHidLow else na;
PlotHBullline.EnableApproximation();
PlotHBullline.SetDefaultColor(Color.DARK_GREEN);

#-- END of CODE

#---- END
 
check the below

CSS:
#//@version=4
#https://www.tradingview.com/script/soSwR4mX-MACD-Divergences-by-DaviddTech/
#study(title="MACD Divergences by @DaviddTech",  resolution="")
# Converted by Sam4Cok@Samer800 - 09/2022 - Requested by member from UseThinkscript.com
# updated for Upper study by Sam4Cok#SAmer800    - 02/2024
#// Getting inputs

input fast_length = 12;                # "Fast Length"
input slow_length = 26;                # "Slow Length"
input src = close;                     # "Source"
input signal_length = 9;               # "Signal Smoothing"
input sma_source = {default EMA, SMA}; # "Oscillator MA Type"
input sma_signal = {default EMA, SMA}; # "Signal Line MA Type"
input dontTouchZero = yes;             # "Don't touch the zero line?"

def na = Double.NaN;
#// Plot colors
DefineGlobalColor("macd"       , CreateColor(41, 98, 255));    # >=90
DefineGlobalColor("signal"     , CreateColor(255, 109, 0));  # >=80
DefineGlobalColor("grow_above" , CreateColor(38, 166, 154)); # >=70
DefineGlobalColor("fall_above" , CreateColor(178, 223, 219)); # >=60
DefineGlobalColor("grow_below" , CreateColor(255, 205, 210));  # >=50
DefineGlobalColor("fall_below" , CreateColor(255, 82, 82));   # >=40
#// Calculating
def fast_ma = if sma_source == sma_source.SMA then SimpleMovingAvg(src, fast_length) else
                     ExpAverage(src, fast_length);
def slow_ma = if sma_source == sma_source.SMA then SimpleMovingAvg(src, slow_length) else
                     ExpAverage(src, slow_length);
def macd = fast_ma - slow_ma;

#--- Div-----

#----Div-----------
input ShowLastDivLines = yes;
input ShowLastHiddenDivLines = no;
input DivBull = yes;      # "Plot Bullish"
input DivBear = yes;      # "Plot Bearish"
input DivHiddenBull = no; # "Plot Hidden Bullish"
input DivHiddenBear = no; # "Plot Hidden Bearish"
input LookBackRight  = 5; # "Pivot Lookback Right"
input LookBackLeft  = 5;  # "Pivot Lookback Left"
input MaxLookback = 60;   # "Max of Lookback Range"
input MinLookback = 5;    # "Min of Lookback Range"

def divSrc = macd;

def h = high;
def l = low;

script FindPivots {
    input dat = close; # default data or study being evaluated
    input HL  = 0;    # default high or low pivot designation, -1 low, +1 high
    input lbL  = 5;    # default Pivot Lookback Left
    input lbR  = 1;    # default Pivot Lookback Right
    ##############
    def _nan;    # used for non-number returns
    def _BN;     # the current barnumber
    def _VStop;  # confirms that the lookforward period continues the pivot trend
    def _V;      # the Value at the actual pivot point
    ##############
    _BN  = BarNumber();
    _nan = Double.NaN;
    _VStop = if !isNaN(dat) and lbr > 0 and lbl > 0 then
                fold a = 1 to lbR + 1 with b=1 while b do
                    if HL > 0 then dat > GetValue(dat,-a) else dat < GetValue(dat,-a) else _nan;
   if (HL > 0) {
        _V = if _BN > lbL + 1 and dat == Highest(dat, lbL + 1) and _VStop
            then dat else _nan;
    } else {
        _V = if _BN > lbL + 1 and dat == Lowest(dat, lbL + 1) and _VStop
            then dat else _nan;
    }
    plot result = if !IsNaN(_V) and _VStop then _V else _nan;
}
#_inRange(cond) =>
script _inRange {
    input cond = yes;
    input rangeUpper = 60;
    input rangeLower = 5;
        def bars = if cond then 0 else bars[1] + 1;
        def inrange =  (rangeLower <= bars) and (bars <= rangeUpper);
plot retrun = inRange;
}
def pl_ = findpivots(divSrc,-1, LookBackLeft, LookBackRight);
def ph_ = findpivots(divSrc, 1, LookBackLeft, LookBackRight);
def pl = !isNaN(pl_);
def ph = !isNaN(ph_);
def pll = lowest(divSrc,LookBackLeft);
def phh = highest(divSrc,LookBackLeft);
def sll = lowest(l, LookBackLeft);
def shh = highest(h, LookBackLeft);
#-- Pvt Low
def plStart  = if pl then yes else plStart[1];
def plFound  = if (plStart and pl) then 1 else 0;
def vlFound1 = if plFound then divSrc else vlFound1[1];
def vlFound_ = if vlFound1!=vlFound1[1] then vlFound1[1] else vlFound_[1];
def vlFound  = if !vlFound_ then pll else vlFound_;
def plPrice1 = if plFound then l else plPrice1[1];
def plPrice_ = if plPrice1!=plPrice1[1] then plPrice1[1] else plPrice_[1];
def plPrice  = if !plPrice_ then sll else plPrice_;
#-- Pvt High
def phStart = if ph then yes else phStart[1];
def phFound = if (phStart and ph) then 1 else 0;
def vhFound1 = if phFound then divSrc else vhFound1[1];
def vhFound_ = if vhFound1!=vhFound1[1] then vhFound1[1] else vhFound_[1];
def vhFound = if !vhFound_ then phh else vhFound_;
def phPrice1 = if phFound then h else phPrice1[1];
def phPrice_ = if phPrice1!=phPrice1[1] then phPrice1[1] else phPrice_[1];
def phPrice = if !phPrice_ then sll else phPrice_;
#// Regular Bullish
def priceHHZero =  highest(divSrc, LookBackLeft + LookBackRight + 5);
def blowzero = if donttouchzero then priceHHZero < 0 else yes;
def inRangePl = _inRange(plFound[1],MaxLookback,MinLookback);
def oscHL = divSrc > vlFound and inRangePl and divSrc < 0;
def priceLL = l < plPrice;
def bullCond = plFound and oscHL and priceLL and blowzero;
#// Hidden Bullish
def oscLL = divSrc < vlFound and inRangePl;
def priceHL = l > plPrice;
def hiddenBullCond = plFound and oscLL and priceHL;
#// Regular Bearish
def priceLLZero =  lowest(divSrc, LookBackLeft + LookBackRight + 5);
def bearzero = if donttouchzero then priceLLZero > 0 else yes;
def inRangePh = _inRange(phFound[1],MaxLookback,MinLookback);
def oscLH   = divSrc < vhFound and inRangePh and divSrc > 0;
def priceHH = h > phPrice;
def bearCond = phFound and oscLH and priceHH and bearzero;
#// Hidden Bearish
def oscHH = divSrc > vhFound and inRangePh;
def priceLH = h < phPrice;
def hiddenBearCond = phFound and oscHH and priceLH;

#------ Bubbles
def bullBub  = DivBull and bullCond;
def HbullBub = DivHiddenBull and hiddenBullCond;
def bearBub  = DivBear and bearCond;
def HbearBub = DivHiddenBear and hiddenBearCond;

addchartbubble(bullBub, low, "R", color.GREEN, no);
addchartbubble(bearBub, high, "R", CreateColor(156,39,176), yes);
addchartbubble(HbullBub, low, "H", color.DARK_green, no);
addchartbubble(HbearBub, high, "H", color.DARK_red, yes);

##### Lines
def bar = BarNumber();
#-- Bear Line
def lastPhBar = if ph then bar else lastPhBar[1];
def prePhBar = if lastPhBar!=lastPhBar[1] then lastPhBar[1] else prePhBar[1];
def priorPHBar = if bearCond then prePhBar else priorPHBar[1];
#-- Bull Line
def lastPlBar = if pl then bar else lastPlBar[1];
def prePlBar = if lastPlBar!=lastPlBar[1] then lastPlBar[1] else prePlBar[1];
def priorPLBar = if bullCond then prePlBar else priorPLBar[1];

def lastBullBar = if bullCond then bar else lastBullBar[1];
def lastBearBar = if bearCond then bar else lastBearBar[1];

def HighPivots = ph and bar >= HighestAll(priorPHBar) and bar <= HighestAll(lastBearBar);
def LowPivots  = pl and bar >= HighestAll(priorPLBar) and bar <= HighestAll(lastBullBar);

def pivotHigh = if HighPivots then high else na;
def pivotLow  = if LowPivots  then low else na;

plot PlotHline = if ShowLastDivLines then pivotHigh else na;
PlotHline.EnableApproximation();
PlotHline.SetDefaultColor(Color.RED);

plot PlotLline = if ShowLastDivLines then pivotLow else na;
PlotLline.EnableApproximation();
PlotLline.SetDefaultColor(Color.GREEN);

#--- Hidden Lines
#-- Bear Line
def priorHPHBar = if hiddenBearCond then prePhBar else priorHPHBar[1];
#-- Bull Line
def priorHPLBar = if hiddenBullCond then prePlBar else priorHPLBar[1];

def lastHBullBar = if hiddenBullCond then bar else lastHBullBar[1];
def lastHBearBar = if hiddenBearCond then bar else lastHBearBar[1];

def HighHPivots = ph and bar >= HighestAll(priorHPHBar) and bar <= HighestAll(lastHBearBar);
def LowHPivots  = pl and bar >= HighestAll(priorHPLBar) and bar <= HighestAll(lastHBullBar);

def pivotHidHigh = if HighHPivots then high else na;
def pivotHidLow  = if LowHPivots  then low else na;

plot PlotHBearline = if ShowLastHiddenDivLines then pivotHidHigh else na;
PlotHBearline.EnableApproximation();
PlotHBearline.SetDefaultColor(Color.DARK_RED);

plot PlotHBullline = if ShowLastHiddenDivLines then pivotHidLow else na;
PlotHBullline.EnableApproximation();
PlotHBullline.SetDefaultColor(Color.DARK_GREEN);

#-- END of CODE

#---- END
@samer800 When does it show the divergence line, right after close and 1 bar later or after few bars? Does it repaint?
 
@samer800 When does it show the divergence line, right after close and 1 bar later or after few bars? Does it repaint?

Yes, it repaints. No, it does not update in real time.
Perhaps you can put it on your chart and come back with your observations as far as what the lag is and how the repainting effects this.
Look forward to your findings.
 
Last edited:

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
256 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