Pivoting Pivot
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © OztheWoz

// Pivoting pivots. Thank you to @fikira for the help with ideas on how to code this!

//@version=5
indicator("Pivoting Pivot", overlay=true)

p_left = input.int(2, "Pivot Left")
p_right = input.int(2, "Pivot Right")
lg_left = input.int(2, "LG Left")
lg_right = input.int(2, "LG Right")


_xyval(_cond, _ysrc, _xsrc) =>
    x = ta.valuewhen(_cond, _xsrc, 0)
    y = ta.valuewhen(_cond, _ysrc, 0)
    [x, y]

_clearIntArray(_array, oversize) =>
    size = array.size(_array)
    if size > oversize
        (array.pop(_array))


ph = ta.pivothigh(high, p_left, p_right)
pl = ta.pivotlow (low,  p_left, p_right)
p_since = ta.barssince(ph or pl)
[ph_x, ph_y] = _xyval(not na(ph), high[p_right], bar_index[p_right])
[pl_x, pl_y] = _xyval(not na(pl), low[p_right], bar_index[p_right])
// barcolor(ph ? color.yellow : pl ? color.white : na, offset=-2)


_getLG(int _left, int _right) =>
    lg_Hpivot = false
    lg_Lpivot = false
    if barstate.isconfirmed

        var pTime_array = array.new_int()
        switch
            (ph and not pl) =>
                array.unshift(pTime_array, ph_x)
            (pl and not ph) =>
                array.unshift(pTime_array, pl_x)
            (pl and ph)     =>
                array.unshift(pTime_array, pl_x)
        _clearIntArray(pTime_array, 2)
        
        p_curr = array.get(pTime_array, array.size(pTime_array) > 0 ? 0 : na)
        p_last = array.get(pTime_array, array.size(pTime_array) > 1 ? 1 : na)
        lg_Hpivot := (math.abs(p_curr - p_last) >= _left+1) and (p_since >= _right) and (ph[_right])
        lg_Lpivot := (math.abs(p_curr - p_last) >= _left+1) and (p_since >= _right) and (pl[_right])
    [lg_Hpivot, lg_Lpivot]

[lg_H, lg_L] = _getLG(lg_left, lg_right)
barcolor(lg_H ? color.blue : lg_L ? color.navy : na, offset=-(p_right + lg_right))



