Reputation: 1151
I am trying to write an indicator script for TradvingView wherein the 80th percentile value and the 20th percentile value of price close (or any set of values) is plotted on a chart (code given below).
Based on the 'Lookback Period' input (lets say x), it should look at back at x bars from the current bar and calculate and plot the 20th and 80th percentile values for price close (or open or any specified user input). It should do this for every bar.
While it does draw lines across the chart, the percentile values it plots seems to be inaccurate.
Would appreciate feedback on where I am going wrong or if there is a way to calculate percentile values using a function manually since the built in function seems to be calculating them incorrectly.
Thank You! :)
//@version=3
study(title="Percentiles", shorttitle="Percentiles", overlay=true)
// ----- DESCRIPTION
//
// Given a set of values, this indicator plots 2 lines: the upper percentile and the lower percentile
// It was made to be overlaid on the 'Bitmex Funding' indicator but could work with any set of values
//
//
//----- PRINTED/RENDERED VALUES
//
// Upper Percentile Plot Threshold | Lower Percentile Plot Threshold
// Upper Percentile Plot (Green Line)
// Lower Percentile Plot (Red Line)
//
//
// ----- OPTIONS
//
// Lookback Period: The number of values to look at plotting the percentiles thresholds.
// Upper Percentile Plot: The percentile plot i.e. 80th percentile plot of a set of values. By default, the value is 80 is used.
// Lower Percentile Plot: The percentile plot i.e. 20th percentile plot of a set of values. By default, the value is 20 is used.
length = input(100, minval=1, title="Lookback Period")
upperPercentilePlot = input (80, title="Upper Percentile Plot")
lowerPercentilePlot = input(20, title="Lower Percentile Plot")
src = input(close, title="Source")
median_high = percentile_nearest_rank(src, length, upperPercentilePlot)
median_low = percentile_nearest_rank(src, length, lowerPercentilePlot)
plot(median_high, color=blue, title="Upper Percentile Plot", linewidth=2)
plot(median_low, color=blue, title="Lower Percentile Plot", linewidth=2)
Upvotes: 1
Views: 3015
Reputation: 8789
There doesn't appear to be anything wrong with the way you use the function and it seems to work correctly. Replacing your src
line with the modulo 100 of the bar index yields correct results:
src = n%100
Upvotes: 1