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

//@version=5
indicator("ROC Percentile")
roclen = input.int(10, "ROC Length")
roc = ta.roc(close, roclen)
length = input(500, "Lookback Period")
col = roc >= 0 ? color.green : color.red

// Create arrays for positive and negative values
pos = array.new_float(0)
neg = array.new_float(0)

// Count of pos and neg, to calculate percentage values
poscount = 0
negcount = 0

// Loop through length, adding pos/neg roc values to arrays
for i=0 to length - 1
    if roc[i] > 0
        array.push(pos, roc[i])
        poscount += 1
    else if roc[i] < 0
        array.push(neg, roc[i])
        negcount += 1
        
// Sort arrays by ROC value
array.sort(pos, order.ascending)
array.sort(neg, order.descending)
// Find current ROC value ranking position within the neg/pos arrays.
posindex = array.indexof(pos, roc)
negindex = array.indexof(neg, roc)
// Turn the ranking position into percentile value
pospercent = ((posindex + 1) / poscount) * 100
negpercent = ((negindex + 1) / negcount) * 100

plot(pospercent, style=plot.style_columns, color=col)
plot(-negpercent, style=plot.style_columns, color=col)
plot(50, style=plot.style_circles, color=color.green)
plot(-50, style=plot.style_circles, color=color.red)