Divergences for many indicators pinescript

Viewing 9 posts - 1 through 9 (of 9 total)
  • Author
    Posts
  • #237916 quote
    colin2510colin2510
    Participant
    New
    // This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
    // © LuxAlgo
    //@version=5
    indicator(“Order Blocks & Breaker Blocks [LuxAlgo]”, overlay = true
      , max_lines_count  = 500
      , max_labels_count = 500
      , max_boxes_count  = 500)
    //——————————————————————————
    //Settings
    //—————————————————————————–{
    length   = input.int(10, ‘Swing Lookback’     , minval = 3)
    showBull = input.int(3, ‘Show Last Bullish OB’, minval = 0)
    showBear = input.int(3, ‘Show Last Bearish OB’, minval = 0)
    useBody  = input(false, ‘Use Candle Body’)
    //Style
    bullCss      = input(color.new(#2157f3, 80), ‘Bullish OB’   , inline = ‘bullcss’, group = ‘Style’)
    bullBreakCss = input(color.new(#ff1100, 80), ‘Bullish Break’, inline = ‘bullcss’, group = ‘Style’)
    bearCss      = input(color.new(#ff5d00, 80), ‘Bearish OB’   , inline = ‘bearcss’, group = ‘Style’)
    bearBreakCss = input(color.new(#0cb51a, 80), ‘Bearish Break’, inline = ‘bearcss’, group = ‘Style’)
    showLabels = input(false, ‘Show Historical Polarity Changes’)
    //—————————————————————————–}
    //UDT’s
    //—————————————————————————–{
    type ob
        float top = na
        float btm = na
        int   loc = bar_index
        bool  breaker = false
        int   break_loc = na
    type swing
        float y = na
        int   x = na
        bool  crossed = false
    //—————————————————————————–}
    //Functions
    //—————————————————————————–{
    swings(len)=>
        var os = 0
        var swing top = swing.new(na, na)
        var swing btm = swing.new(na, na)
        upper = ta.highest(len)
        lower = ta.lowest(len)
        os:=high[len]>upper?0
          : low[len] < lower ? 1 : os
        if os == 0 and os[1] != 0
            top := swing.new(high[length], bar_index[length])
        if os == 1 and os[1] != 1
            btm := swing.new(low[length], bar_index[length])
        [top, btm]
    method notransp(color css) => color.rgb(color.r(css), color.g(css), color.b(css))
    method display(ob id, css, break_css)=>
        if id.breaker
            box.new(id.loc, id.top, id.break_loc, id.btm, css.notransp()
              , bgcolor = css
              , xloc = xloc.bar_time)
            box.new(id.break_loc, id.top, time+1, id.btm, na
              , bgcolor = break_css
              , extend = extend.right
              , xloc = xloc.bar_time)
            line.new(id.loc, id.top, id.break_loc, id.top, xloc.bar_time, color = css.notransp())
            line.new(id.loc, id.btm, id.break_loc, id.btm, xloc.bar_time, color = css.notransp())
            line.new(id.break_loc, id.top, time+1, id.top, xloc.bar_time, extend.right, break_css.notransp(), line.style_dashed)
            line.new(id.break_loc, id.btm, time+1, id.btm, xloc.bar_time, extend.right, break_css.notransp(), line.style_dashed)
        else
            box.new(id.loc, id.top, time, id.btm, na
              , bgcolor = css
              , extend = extend.right
              , xloc = xloc.bar_time)
            line.new(id.loc, id.top, time, id.top, xloc.bar_time, extend.right, css.notransp())
            line.new(id.loc, id.btm, time, id.btm, xloc.bar_time, extend.right, css.notransp())
    //—————————————————————————–}
    //Detect Swings
    //—————————————————————————–{
    n = bar_index
    [top, btm] = swings(length)
    max = useBody ? math.max(close, open) : high
    min = useBody ? math.min(close, open) : low
    //—————————————————————————–}
    //Bullish OB
    //—————————————————————————–{
    var bullish_ob = array.new<ob>(0)
    bull_break_conf = 0
    if close > top.y and not top.crossed
        top.crossed := true
        minima = max[1]
        maxima = min[1]
        loc = time[1]
        for i = 1 to (n – top.x)-1
            minima := math.min(min[i], minima)
            maxima := minima == min[i] ? max[i] : maxima
            loc := minima == min[i] ? time[i] : loc
        bullish_ob.unshift(ob.new(maxima, minima, loc))
    if bullish_ob.size() > 0
        for i = bullish_ob.size()-1 to 0
            element = bullish_ob.get(i)
            ifnotelement.breaker
                if math.min(close, open) < element.btm
                    element.breaker := true
                    element.break_loc := time
            else
                if close > element.top
                    bullish_ob.remove(i)
                elseifi<showBullandtop.y<element.topandtop.y>element.btm
                    bull_break_conf := 1
    //Set label
    if bull_break_conf > bull_break_conf[1] and showLabels
        label.new(top.x, top.y, ‘▼’, color = na
          , textcolor = bearCss.notransp()
          , style = label.style_label_down
          , size = size.tiny)
    //—————————————————————————–}
    //Bearish OB
    //—————————————————————————–{
    var bearish_ob = array.new<ob>(0)
    bear_break_conf = 0
    if close < btm.y and not btm.crossed
        btm.crossed := true
        minima = min[1]
        maxima = max[1]
        loc = time[1]
        for i = 1 to (n – btm.x)-1
            maxima := math.max(max[i], maxima)
            minima := maxima == max[i] ? min[i] : minima
            loc := maxima == max[i] ? time[i] : loc
        bearish_ob.unshift(ob.new(maxima, minima, loc))
    if bearish_ob.size() > 0
        for i = bearish_ob.size()-1 to 0
            element = bearish_ob.get(i)
            ifnotelement.breaker
                if math.max(close, open) > element.top
                    element.breaker := true
                    element.break_loc := time
            else
                if close < element.btm
                    bearish_ob.remove(i)
                elseifi<showBearandbtm.y>element.btmandbtm.y<element.top
                    bear_break_conf := 1
    //Set label
    if bear_break_conf > bear_break_conf[1] and showLabels
        label.new(btm.x, btm.y, ‘▲’, color = na
          , textcolor = bullCss.notransp()
          , style = label.style_label_up
          , size = size.tiny)
    //—————————————————————————–}
    //Set Order Blocks
    //—————————————————————————–{
    for bx in box.all
        bx.delete()
    for l in line.all
        l.delete()
    if barstate.islast
        //Bullish
        if showBull > 0
            for i = 0 to math.min(showBull-1, bullish_ob.size())
                get_ob = bullish_ob.get(i)
                get_ob.display(bullCss, bullBreakCss)
        //Bearish
        if showBear > 0
            for i = 0 to math.min(showBear-1, bearish_ob.size())
                get_ob = bearish_ob.get(i)
                get_ob.display(bearCss, bearBreakCss)
    //—————————————————————————–}
    #238290 quote
    Iván GonzálezIván González
    Moderator
    Legend

    Here you have the code:

    //---------------------------------------------------------//
    //PRC_Order Blocks and Breaker Blocks
    //version = 0
    //30.09.2024
    //Iván González @ www.prorealcode.com
    //Sharing ProRealTime knowledge
    //---------------------------------------------------------//
    //-----Inputs----------------------------------------------//
    //---------------------------------------------------------//
    length=10 //Swing Lookback
    showBull=5 //Show last bullish OB
    showBear=5 //Show last bearish OB
    useBody=0
    showLabels=1 //Show labels
    lookbackPeriod=300
    //---------------------------------------------------------//
    //-----Detect Swings---------------------------------------//
    //---------------------------------------------------------//
    n=barindex
    once os=0
    upper=highest[length](high)
    lower=lowest[length](low)
    
    if high[length]>upper then
    os=0
    elsif low[length]<lower then
    os=1
    else
    os=os
    endif
    
    if os=0 and os[1]<>0 then
    topy=high[length]
    topx=barindex[length]
    topcrossed=0
    elsif os=1 and os[1]<>1 then
    btmy=low[length]
    btmx=barindex[length]
    btmcrossed=0
    endif
    
    if usebody then
    mimax=max(close,open)
    mimin=min(close,open)
    else
    mimax=max(close,open)
    mimin=min(close,open)
    endif
    
    //---------------------------------------------------------//
    //-----Bullish OB------------------------------------------//
    //---------------------------------------------------------//
    if close > topy and topcrossed=0 then
    
    topcrossed=1
    
    minima=mimax[1]
    maxima=mimin[1]
    loc=barindex[1]
    
    for i=1 to (n-topx)-1 do
    minima=min(mimin[i],minima)
    if minima=mimin[i] then
    maxima=mimax[i]
    loc=barindex[i]
    else
    maxima=maxima
    loc=loc
    endif
    next
    
    $bullTop[m+1]=maxima
    $bullBtm[m+1]=minima
    $bullx[m+1]=loc
    $bullbreak[m+1]=0
    m=m+1
    endif
    
    //---------------------------------------------------------//
    //-----Bearish OB------------------------------------------//
    //---------------------------------------------------------//
    bearBreakConf=0
    if close < btmy and btmcrossed=0 then
    
    btmcrossed=1
    
    minima2=mimin[1]
    maxima2=mimax[1]
    loc2=barindex[1]
    
    for i=1 to (n-btmx)-1 do
    maxima2=max(mimax[i],maxima2)
    if maxima2=mimax[i] then
    minima2=mimin[i]
    loc2=barindex[i]
    else
    minima2=minima2
    loc2=loc2
    endif
    next
    
    $bearTop[z+1]=maxima2
    $bearBtm[z+1]=minima2
    $bearx[z+1]=loc2
    $bearbreak[z+1]=0
    z=z+1
    endif
    
    //---------------------------------------------------------//
    //-----Plot Order Blocks-----------------------------------//
    //---------------------------------------------------------//
    if islastbarupdate then
    
    for i=m downto 1 do
    for j=barindex downto 0 do
    if barindex[j]>$bullx[i] and close[j] < $bullBtm[i] then
    $bullright[i]=barindex[j]
    $bullbreak[i]=1
    break
    else
    $bullright[i]=barindex
    endif
    next
    if i>m-showbull then
    if $bullbreak[i]=0 then
    drawrectangle($bullx[i],$bullBtm[i],$bullright[i]+20,$bullTop[i])coloured("blue")fillcolor("blue",50)
    elsif $bullbreak[i]=1 then
    drawrectangle($bullx[i],$bullBtm[i],$bullright[i],$bullTop[i])coloured("blue")fillcolor("blue",50)
    if close>$bullTop[i]then
    drawrectangle($bullright[i],$bullBtm[i],barindex+20,$bullTop[i])coloured("green",0)fillcolor("green",50)
    elsif close<$bullBtm[i]then
    drawrectangle($bullright[i],$bullBtm[i],barindex+20,$bullTop[i])coloured("red",0)fillcolor("red",50)
    else
    drawrectangle($bullright[i],$bullBtm[i],barindex+20,$bullTop[i])coloured("yellow",0)fillcolor("yellow",50)
    endif
    endif
    endif
    next
    
    for i=z downto 1 do
    for j=barindex downto 0 do
    if barindex[j]>$bearx[i] and close[j] > $bearTop[i] then
    $bearright[i]=barindex[j]
    $bearbreak[i]=1
    break
    else
    $bearright[i]=barindex
    endif
    next
    if i>z-showbear then
    if $bearbreak[i]=0 then
    drawrectangle($bearx[i],$bearBtm[i],$bearright[i]+20,$bearTop[i])coloured("orange")fillcolor("orange",50)
    elsif $bearbreak[i]=1 then
    drawrectangle($bearx[i],$bearBtm[i],$bearright[i],$bearTop[i])coloured("orange")fillcolor("orange",50)
    if close>$bearTop[i]then
    drawrectangle($bearright[i],$bearBtm[i],barindex+20,$bearTop[i])coloured("green",0)fillcolor("green",50)
    elsif close<$bearBtm[i]then
    drawrectangle($bearright[i],$bearBtm[i],barindex+20,$bearTop[i])coloured("red",0)fillcolor("red",50)
    else
    drawrectangle($bearright[i],$bearBtm[i],barindex+20,$bearTop[i])coloured("yellow",0)fillcolor("yellow",50)
    endif
    endif
    endif
    next
    endif
    
    return
    #238291 quote
    colin2510colin2510
    Participant
    New

    Hello thanks for the code!

    However, I keep getting following error message:

    “Line 1:
    Any of the following sign would be more appropriate than “a parameter name”: THEN”

    See attachment.

    Error-Message.png Error-Message.png
    #238300 quote
    robertogozzirobertogozzi
    Moderator
    Legend

    It works like a charm to me.

    Check that both the first and the last lines in your code are the same as those posted above, as it may happen that Copy & Paste adds odd characters and lines, at times.

    #238305 quote
    colin2510colin2510
    Participant
    New

    The problem seems to be that it works in V12 but not in V11.

    I only have acces to ProRealTime V11 (via my broker).

    Is it possible to make the code work in V11?

    Such a good indicator..

    Thank you!

    #238326 quote
    Iván GonzálezIván González
    Moderator
    Legend

    Find the drawing lines of the rectangles and remove the fillcolor("red") part. This should work for you.

    robertogozzi and colin2510 thanked this post
    #238334 quote
    colin2510colin2510
    Participant
    New

    works perfectely thank you!!

    #238337 quote
    colin2510colin2510
    Participant
    New

    I see that the title of my topic was wrong (Divergences instead of Order Blocks). Can you look at the following indicator for Divergences, also from Tradingview?

    #238338 quote
    colin2510colin2510
    Participant
    New
    // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
    // © LonesomeTheBlue
    //@version=4
    study(“Divergence for Many Indicators v4 Colin”, overlay = true, max_bars_back = 1000, max_lines_count = 400, max_labels_count = 400)
    prd = input(defval = 5, title = “Pivot Period”, minval = 1, maxval = 50)
    source = input(defval = “Close”, title = “Source for Pivot Points”, options = [“Close”, “High/Low”])
    searchdiv = input(defval = “Regular”, title = “Divergence Type”, options = [“Regular”, “Hidden”, “Regular/Hidden”])
    showindis = input(defval = “Full”, title = “Show Indicator Names”, options = [“Full”, “First Letter”, “Don’t Show”])
    showlimit = input(1, title=”Minimum Number of Divergence”, minval = 1, maxval = 11)
    maxpp = input(defval = 10, title = “Maximum Pivot Points to Check”, minval = 1, maxval = 20)
    maxbars = input(defval = 100, title = “Maximum Bars to Check”, minval = 30, maxval = 200)
    shownum = input(defval = true, title = “Show Divergence Number”)
    showlast = input(defval = false, title = “Show Only Last Divergence”)
    dontconfirm = input(defval = false, title = “Don’t Wait for Confirmation”)
    showlines = input(defval = true, title = “Show Divergence Lines”)
    showpivot = input(defval = false, title = “Show Pivot Points”)
    calcmacd = input(defval = true, title = “MACD”)
    calcmacda = input(defval = true, title = “MACD Histogram”)
    calcrsi = input(defval = true, title = “RSI”)
    calcstoc = input(defval = true, title = “Stochastic”)
    calccci = input(defval = true, title = “CCI”)
    calcmom = input(defval = true, title = “Momentum”)
    calcobv = input(defval = true, title = “OBV”)
    calcvwmacd = input(true, title = “VWmacd”)
    calccmf = input(true, title = “Chaikin Money Flow”)
    calcmfi = input(true, title = “Money Flow Index”)
    calcext = input(false, title = “Check External Indicator”)
    externalindi = input(defval = close, title = “External Indicator”)
    pos_reg_div_col = input(defval = color.yellow, title = “Positive Regular Divergence”)
    neg_reg_div_col = input(defval = color.navy, title = “Negative Regular Divergence”)
    pos_hid_div_col = input(defval = color.lime, title = “Positive Hidden Divergence”)
    neg_hid_div_col = input(defval = color.red, title = “Negative Hidden Divergence”)
    pos_div_text_col = input(defval = color.black, title = “Positive Divergence Text Color”)
    neg_div_text_col = input(defval = color.white, title = “Negative Divergence Text Color”)
    reg_div_l_style_ = input(defval = “Solid”, title = “Regular Divergence Line Style”, options = [“Solid”, “Dashed”, “Dotted”])
    hid_div_l_style_ = input(defval = “Dashed”, title = “Hdden Divergence Line Style”, options = [“Solid”, “Dashed”, “Dotted”])
    reg_div_l_width = input(defval = 2, title = “Regular Divergence Line Width”, minval = 1, maxval = 5)
    hid_div_l_width = input(defval = 1, title = “Hidden Divergence Line Width”, minval = 1, maxval = 5)
    showmas = input(defval = false, title = “Show MAs 50 & 200”, inline = “ma12”)
    cma1col = input(defval = color.orange, title = “”, inline = “ma12”)
    cma2col = input(defval = color.blue, title = “”, inline = “ma12”)
    cma3col = input(defval = color.black, title = “”, inline = “ma12”)
    plot(showmas ? sma(close, 21) : na, color = showmas ? cma1col : na)
    plot(showmas ? sma(close, 50) : na, color = showmas ? cma2col: na)
    plot(showmas ? sma(close, 200) : na, color = showmas ? cma3col : na)
    // set line styles
    varreg_div_l_style=reg_div_l_style_==”Solid”?line.style_solid:
                           reg_div_l_style_ == “Dashed” ? line.style_dashed :
                           line.style_dotted
    varhid_div_l_style=hid_div_l_style_==”Solid”?line.style_solid:
                           hid_div_l_style_ == “Dashed” ? line.style_dashed :
                           line.style_dotted
    // get indicators
    rsi = rsi(close, 14) // RSI
    [macd, signal, deltamacd] = macd(close, 12, 26, 9) // MACD
    moment = mom(close, 10) // Momentum
    cci = cci(close, 10) // CCI
    Obv = obv // OBV
    stk = sma(stoch(close, high, low, 14), 3) // Stoch
    maFast = vwma(close, 12), maSlow = vwma(close, 26), vwmacd = maFast – maSlow // volume weighted macd
    Cmfm = ((close-low) – (high-close)) / (high – low), Cmfv = Cmfm * volume, cmf = sma(Cmfv, 21) / sma(volume,21) // Chaikin money flow
    Mfi = mfi(close, 14) // Moneyt Flow Index
    // keep indicators names and colors in arrays
    var indicators_name = array.new_string(11)
    var div_colors = array.new_color(4)
    if barstate.isfirst
        // names
        array.set(indicators_name, 0, showindis == “Full” ? “MACD” : “M”)
        array.set(indicators_name, 1, showindis == “Full” ? “Hist” : “H”)
        array.set(indicators_name, 2, showindis == “Full” ? “RSI” : “E”)
        array.set(indicators_name, 3, showindis == “Full” ? “Stoch” : “S”)
        array.set(indicators_name, 4, showindis == “Full” ? “CCI” : “C”)
        array.set(indicators_name, 5, showindis == “Full” ? “MOM” : “M”)
        array.set(indicators_name, 6, showindis == “Full” ? “OBV” : “O”)
        array.set(indicators_name, 7, showindis == “Full” ? “VWMACD” : “V”)
        array.set(indicators_name, 8, showindis == “Full” ? “CMF” : “C”)
        array.set(indicators_name, 9, showindis == “Full” ? “MFI” : “M”)
        array.set(indicators_name,10, showindis == “Full” ? “Extrn” : “X”)
        //colors
        array.set(div_colors, 0, pos_reg_div_col)
        array.set(div_colors, 1, neg_reg_div_col)
        array.set(div_colors, 2, pos_hid_div_col)
        array.set(div_colors, 3, neg_hid_div_col)
    // Check if we get new Pivot High Or Pivot Low
    float ph = pivothigh((source == “Close” ? close : high), prd, prd)
    float pl = pivotlow((source == “Close” ? close : low), prd, prd)
    plotshape(ph and showpivot, text = “H”,  style = shape.labeldown, color = color.new(color.white, 100), textcolor = color.red, location = location.abovebar, offset = -prd)
    plotshape(pl and showpivot, text = “L”,  style = shape.labelup, color = color.new(color.white, 100), textcolor = color.lime, location = location.belowbar, offset = -prd)
    // keep values and positions of Pivot Highs/Lows in the arrays
    var int maxarraysize = 20
    var ph_positions = array.new_int(maxarraysize, 0)
    var pl_positions = array.new_int(maxarraysize, 0)
    var ph_vals = array.new_float(maxarraysize, 0.)
    var pl_vals = array.new_float(maxarraysize, 0.)
    // add PHs to the array
    if ph
        array.unshift(ph_positions, bar_index)
        array.unshift(ph_vals, ph)
        if array.size(ph_positions) > maxarraysize
            array.pop(ph_positions)
            array.pop(ph_vals)
    // add PLs to the array
    if pl
        array.unshift(pl_positions, bar_index)
        array.unshift(pl_vals, pl)
        if array.size(pl_positions) > maxarraysize
            array.pop(pl_positions)
            array.pop(pl_vals)
    // functions to check Regular Divergences and Hidden Divergences
    // function to check positive regular or negative hidden divergence
    // cond == 1 => positive_regular, cond == 2=> negative_hidden
    positive_regular_positive_hidden_divergence(src, cond)=>
        divlen = 0
        prsc = source == “Close” ? close : low
        // if indicators higher than last value and close price is higher than las close
        if dontconfirm or src > src[1] or close > close[1]
            startpoint = dontconfirm ? 0 : 1 // don’t check last candle
            // we search last 15 PPs
            for x = 0 to maxpp – 1
                len = bar_index – array.get(pl_positions, x) + prd
                // if we reach non valued array element or arrived 101. or previous bars then we don’t search more
                if array.get(pl_positions, x) == 0 or len > maxbars
                    break
                iflen>5and
                   ((cond == 1 and src[startpoint] > src[len] and prsc[startpoint] < nz(array.get(pl_vals, x))) or
                   (cond == 2 and src[startpoint] < src[len] and prsc[startpoint] > nz(array.get(pl_vals, x))))
                    slope1 = (src[startpoint] – src[len]) / (len – startpoint)
                    virtual_line1 = src[startpoint] – slope1
                    slope2 = (close[startpoint] – close[len]) / (len – startpoint)
                    virtual_line2 = close[startpoint] – slope2
                    arrived = true
                    for y = 1 + startpoint to len – 1
                        if src[y] < virtual_line1 or nz(close[y]) < virtual_line2
                            arrived := false
                            break
                        virtual_line1 := virtual_line1 – slope1
                        virtual_line2 := virtual_line2 – slope2
                    if arrived
                        divlen := len
                        break
        divlen
    // function to check negative regular or positive hidden divergence
    // cond == 1 => negative_regular, cond == 2=> positive_hidden
    negative_regular_negative_hidden_divergence(src, cond)=>
        divlen = 0
        prsc = source == “Close” ? close : high
        // if indicators higher than last value and close price is higher than las close
        if dontconfirm or src < src[1] or close < close[1]
            startpoint = dontconfirm ? 0 : 1 // don’t check last candle
            // we search last 15 PPs
            for x = 0 to maxpp – 1
                len = bar_index – array.get(ph_positions, x) + prd
                // if we reach non valued array element or arrived 101. or previous bars then we don’t search more
                if array.get(ph_positions, x) == 0 or len > maxbars
                    break
                iflen>5and
                   ((cond==1andsrc[startpoint]<src[len]andprsc[startpoint]>nz(array.get(ph_vals,x)))or
                   (cond == 2 and src[startpoint] > src[len] and prsc[startpoint] < nz(array.get(ph_vals, x))))
                    slope1 = (src[startpoint] – src[len]) / (len – startpoint)
                    virtual_line1 = src[startpoint] – slope1
                    slope2 = (close[startpoint] – nz(close[len])) / (len – startpoint)
                    virtual_line2 = close[startpoint] – slope2
                    arrived = true
                    for y = 1 + startpoint to len – 1
                        if src[y] > virtual_line1 or nz(close[y]) > virtual_line2
                            arrived := false
                            break
                        virtual_line1 := virtual_line1 – slope1
                        virtual_line2 := virtual_line2 – slope2
                    if arrived
                        divlen := len
                        break
        divlen
    // calculate 4 types of divergence if enabled in the options and return divergences in an array
    calculate_divs(cond, indicator)=>
        divs = array.new_int(4, 0)
        array.set(divs, 0, cond and (searchdiv == “Regular” or searchdiv == “Regular/Hidden”) ? positive_regular_positive_hidden_divergence(indicator, 1) : 0)
        array.set(divs, 1, cond and (searchdiv == “Regular” or searchdiv == “Regular/Hidden”) ? negative_regular_negative_hidden_divergence(indicator, 1) : 0)
        array.set(divs, 2, cond and (searchdiv == “Hidden” or searchdiv == “Regular/Hidden”)  ? positive_regular_positive_hidden_divergence(indicator, 2) : 0)
        array.set(divs, 3, cond and (searchdiv == “Hidden” or searchdiv == “Regular/Hidden”)  ? negative_regular_negative_hidden_divergence(indicator, 2) : 0)
        divs
    // array to keep all divergences
    var all_divergences = array.new_int(44) // 11 indicators * 4 divergence = 44 elements
    // set related array elements
    array_set_divs(div_pointer, index)=>
        for x = 0 to 3
            array.set(all_divergences, index * 4 + x, array.get(div_pointer, x))
    // set divergences array
    array_set_divs(calculate_divs(calcmacd, macd), 0)
    array_set_divs(calculate_divs(calcmacda, deltamacd), 1)
    array_set_divs(calculate_divs(calcrsi, rsi), 2)
    array_set_divs(calculate_divs(calcstoc, stk), 3)
    array_set_divs(calculate_divs(calccci, cci), 4)
    array_set_divs(calculate_divs(calcmom, moment), 5)
    array_set_divs(calculate_divs(calcobv, Obv), 6)
    array_set_divs(calculate_divs(calcvwmacd, vwmacd), 7)
    array_set_divs(calculate_divs(calccmf, cmf), 8)
    array_set_divs(calculate_divs(calcmfi, Mfi), 9)
    array_set_divs(calculate_divs(calcext, externalindi), 10)
    // check minimum number of divergence, if less than showlimit then delete all divergence
    total_div = 0
    for x = 0 to array.size(all_divergences) – 1
        total_div := total_div + round(sign(array.get(all_divergences, x)))
    if total_div < showlimit
        array.fill(all_divergences, 0)
    // keep line in an array
    var pos_div_lines = array.new_line(0)
    var neg_div_lines = array.new_line(0)
    var pos_div_labels = array.new_label(0)
    varneg_div_labels=array.new_label(0)
    // remove old lines and labels if showlast option is enabled
    delete_old_pos_div_lines()=>
        if array.size(pos_div_lines) > 0
            forj=0toarray.size(pos_div_lines)-1
                line.delete(array.get(pos_div_lines, j))
            array.clear(pos_div_lines)
    delete_old_neg_div_lines()=>
        if array.size(neg_div_lines) > 0
            forj=0toarray.size(neg_div_lines)-1
                line.delete(array.get(neg_div_lines, j))
            array.clear(neg_div_lines)
    delete_old_pos_div_labels()=>
        ifarray.size(pos_div_labels)>0
            forj=0toarray.size(pos_div_labels)-1
                label.delete(array.get(pos_div_labels, j))
            array.clear(pos_div_labels)
    delete_old_neg_div_labels()=>
        if array.size(neg_div_labels) > 0
            forj=0toarray.size(neg_div_labels)-1
                label.delete(array.get(neg_div_labels, j))
            array.clear(neg_div_labels)
    // delete last creted lines and labels until we met new PH/PV
    delete_last_pos_div_lines_label(n)=>
        if n > 0 and array.size(pos_div_lines) >= n
            asz = array.size(pos_div_lines)
            for j = 1 to n
                line.delete(array.get(pos_div_lines, asz – j))
                array.pop(pos_div_lines)
            if array.size(pos_div_labels) > 0
                label.delete(array.get(pos_div_labels, array.size(pos_div_labels) – 1))
                array.pop(pos_div_labels)
    delete_last_neg_div_lines_label(n)=>
        if n > 0 and array.size(neg_div_lines) >= n
            asz = array.size(neg_div_lines)
            for j = 1 to n
                line.delete(array.get(neg_div_lines, asz – j))
                array.pop(neg_div_lines)
            if array.size(neg_div_labels) > 0
                label.delete(array.get(neg_div_labels, array.size(neg_div_labels) – 1))
                array.pop(neg_div_labels)
    // variables for Alerts
    pos_reg_div_detected = false
    neg_reg_div_detected = false
    pos_hid_div_detected = false
    neg_hid_div_detected = false
    // to remove lines/labels until we met new // PH/PL
    var last_pos_div_lines = 0
    var last_neg_div_lines = 0
    varremove_last_pos_divs=false
    var remove_last_neg_divs = false
    if pl
        remove_last_pos_divs := false
        last_pos_div_lines := 0
    if ph
        remove_last_neg_divs := false
        last_neg_div_lines := 0
    // draw divergences lines and labels
    divergence_text_top = “”
    divergence_text_bottom = “”
    distances = array.new_int(0)
    dnumdiv_top = 0
    dnumdiv_bottom = 0
    top_label_col = color.white
    bottom_label_col = color.white
    old_pos_divs_can_be_removed = true
    old_neg_divs_can_be_removed = true
    startpoint = dontconfirm ? 0 : 1 // used for don’t confirm option
    for x = 0 to 10
        div_type = -1
        for y = 0 to 3
            if array.get(all_divergences, x * 4 + y) > 0 // any divergence?
                div_type := y
                if(y%2)==1
                    dnumdiv_top := dnumdiv_top + 1
                    top_label_col := array.get(div_colors, y)
                if (y % 2) == 0
                    dnumdiv_bottom := dnumdiv_bottom + 1
                    bottom_label_col := array.get(div_colors, y)
                if not array.includes(distances, array.get(all_divergences, x * 4 + y))  // line not exist ?
                    array.push(distances, array.get(all_divergences, x * 4 + y))
                    new_line=showlines?line.new(x1=bar_index-array.get(all_divergences,x*4+y),
                              y1=(source==”Close”?close[array.get(all_divergences,x*4+y)]:
                                               (y%2)==0?low[array.get(all_divergences,x*4+y)]:
                                                              high[array.get(all_divergences, x * 4 + y)]),
                              x2 = bar_index – startpoint,
                              y2=(source==”Close”?close[startpoint]:
                                               (y%2)==0?low[startpoint]:
                                                              high[startpoint]),
                              color = array.get(div_colors, y),
                              style = y < 2 ? reg_div_l_style : hid_div_l_style,
                              width = y < 2 ? reg_div_l_width : hid_div_l_width
                              )
                              : na
                    if (y % 2) == 0
                        if old_pos_divs_can_be_removed
                            old_pos_divs_can_be_removed := false
                            if not showlast and remove_last_pos_divs
                                delete_last_pos_div_lines_label(last_pos_div_lines)
                                last_pos_div_lines := 0
                            if showlast
                                delete_old_pos_div_lines()
                        array.push(pos_div_lines, new_line)
                        last_pos_div_lines := last_pos_div_lines + 1
                        remove_last_pos_divs := true
                    if (y % 2) == 1
                        if old_neg_divs_can_be_removed
                            old_neg_divs_can_be_removed := false
                            if not showlast and remove_last_neg_divs
                                delete_last_neg_div_lines_label(last_neg_div_lines)
                                last_neg_div_lines := 0
                            if showlast
                                delete_old_neg_div_lines()
                        array.push(neg_div_lines, new_line)
                        last_neg_div_lines := last_neg_div_lines + 1
                        remove_last_neg_divs := true
                // set variables for alerts
                if y == 0
                    pos_reg_div_detected := true
                if y == 1
                    neg_reg_div_detected := true
                if y == 2
                    pos_hid_div_detected := true
                if y == 3
                    neg_hid_div_detected := true
        // get text for labels
        if div_type >= 0
            divergence_text_top    := divergence_text_top    + ((div_type % 2) == 1 ? (showindis != “Don’t Show” ? array.get(indicators_name, x) + “\n” : “”) : “”)
            divergence_text_bottom := divergence_text_bottom + ((div_type % 2) == 0 ? (showindis != “Don’t Show” ? array.get(indicators_name, x) + “\n” : “”) : “”)
    // draw labels
    if showindis != “Don’t Show” or shownum
        if shownum and dnumdiv_top > 0
            divergence_text_top := divergence_text_top + tostring(dnumdiv_top)
        if shownum and dnumdiv_bottom > 0
            divergence_text_bottom := divergence_text_bottom + tostring(dnumdiv_bottom)
        if divergence_text_top != “”
            if showlast
                delete_old_neg_div_labels()
            array.push(neg_div_labels,
                          label.new(x=bar_index,
                                     y=max(high,high[1]),
                                     text = divergence_text_top,
                                     color = top_label_col,
                                     textcolor = neg_div_text_col,
                                     style = label.style_label_down
                                     ))
        if divergence_text_bottom != “”
            if showlast
                delete_old_pos_div_labels()
            array.push(pos_div_labels,
                          label.new(x=bar_index,
                                     y=min(low,low[1]),
                                     text = divergence_text_bottom,
                                     color=bottom_label_col,
                                     textcolor = pos_div_text_col,
                                     style = label.style_label_up
                                     ))
    alertcondition(pos_reg_div_detected, title=’Positive Regular Divergence Detected’, message=’Positive Regular Divergence Detected’)
    alertcondition(neg_reg_div_detected, title=’Negative Regular Divergence Detected’, message=’Negative Regular Divergence Detected’)
    alertcondition(pos_hid_div_detected, title=’Positive Hidden Divergence Detected’, message=’Positive Hidden Divergence Detected’)
    alertcondition(neg_hid_div_detected, title=’Negative Hidden Divergence Detected’, message=’Negative Hidden Divergence Detected’)
    alertcondition(pos_reg_div_detected or pos_hid_div_detected, title=’Positive Divergence Detected’, message=’Positive Divergence Detected’)
    alertcondition(neg_reg_div_detected or neg_hid_div_detected, title=’Negative Divergence Detected’, message=’Negative Divergence Detected’)
Viewing 9 posts - 1 through 9 (of 9 total)
  • You must be logged in to reply to this topic.
ProRealAI ProRealAI New

Stuck on this ProBuilder code?

Describe what this topic is trying to build, in plain English, and ProRealAI writes the ProRealTime™ indicator, screener or system for you.

Available in 7 languages
Try ProRealAI

Divergences for many indicators pinescript


ProBuilder: Indicators & Custom Tools

New Reply
Author
author-avatar
colin2510 @colin2510 Participant
Summary

This topic contains 8 replies,
has 3 voices, and was last updated by colin2510colin2510
1 year, 11 months ago.

Topic Details
Forum: ProBuilder: Indicators & Custom Tools
Language: English
Started: 09/22/2024
Status: Active
Attachments: 1 files
ProRealCode ProRealCode
Loading...