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

//@version=5

// @description: RCI library
library("RCI")

length = input.int(9, "Interval")
source = input.source(close, "Source")

ord (seq, idx, itv) =>
    p = seq[idx]
    o = 1
    s = 0
    for i = 0 to itv - 1
        if p < seq[i]
            o := o + 1
        else
            if p == seq[i]
                s := s + 1
    o + (s - 1) / 2.0

d (src, itv) =>
    sum = 0.0
    for i = 0 to itv - 1
        sum := sum + math.pow((i + 1) - ord(src, i, itv), 2)
    sum

rci_func (src, itv) => (1.0 - 6.0 * d(src, itv) / (itv * (itv * itv - 1.0))) * 100.0

hline(80)
hline(-80)
plot(rci_func(source, length))

// @function: RCI calculating
// @returns:  RCI value
export calc (float src, int len) =>
	rci_func(src, len)
