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

//@version=5
library("Pivot", overlay=false)
XLR=2

export init(int XLR)=>
    //init arrays
    var string[] H=array.new_string(0)
    var string[] L=array.new_string(0)
    var string[] A=array.new_string(0)
    //conditions locate pivot points
    h=ta.pivothigh(XLR,XLR)==high[XLR]and barstate.isconfirmed
    l=ta.pivotlow(XLR,XLR)==low[XLR]and barstate.isconfirmed
    //finds pivots and compresses bar_index, direction variable, and high/low value into a single string to protect data
    //pivot highs and lows are placed into separate arrays, organized by bar_index
    for i=0 to 1
        bar=bar_index[i]==bar_index
        if h and bar
            string str = str.tostring(bar_index[XLR])+"_H_"+str.tostring(high[XLR])
            array.unshift(H,str)
        if l and bar
            string str = str.tostring(bar_index[XLR])+"_L_"+str.tostring(low[XLR])
            array.unshift(L,str)
    //checks to see which array is shorter before merging them together
    [long,shrt]=if array.size(H)>array.size(L)
        [H,L]
    else
        [L,H]
    //merges H and L arrays, maintining the bar_index order
    //seperate counters initialized for each array index
    var j=0
    var i=0
    //counters get incremented individually until all elements from H and L arrays are added to A array.
    while i<array.size(long)
        if j<array.size(shrt)
            //bar_index data briefly exposed for comparison between arrays
            x1=array.get(str.split(array.get(shrt,j),"_"),0)
            x2=array.get(str.split(array.get(long,i),"_"),0)
            if str.tonumber(x1) > str.tonumber(x2)
                array.push(A,array.get(shrt,j))
                j:=j+1
            else
                array.push(A,array.get(long,i))
                i:=i+1
        else
            x2=array.get(long,i)
            array.push(A,x2)
            i:=i+1
     //returns all three arrays       
    [H,L,A]


export get(string[] ID,int index) =>
    if barstate.islastconfirmedhistory or barstate.islast
        x = str.tonumber( array.get( str.split( array.get( ID, index ), "_"), 0) )
        d = array.get( str.split( array.get( ID, index ), "_"), 1)
        y = str.tonumber( array.get( str.split( array.get( ID, index ), "_"), 2) )
        [int(x),d,y]

//example of deconstructed pivot arrays
[H,L,A]=init(XLR)

//accessing data in this way is possible but not encouraged
[x, d, y ]=get(H,0)
[x1,d1,y1]=get(H,0)
[x2,d2,y2]=get(H,3)
[x3,d3,y3]=get(H,4)


label.new(
  x=barstate.islast?bar_index:na,
  y=barstate.islast?high:na,
  text=str.tostring(x),
  textcolor=color.rgb(0,0,0),
  size=size.huge,
  style=label.style_label_down
  )
