5

I'm writing an indicator that needs to read the previous 32 candles ohlc data to make a forecast. How can I get the previous 32 candles ohlc data in TradingView > PineScript Editor > Indicator ?

Neo.Mxn0
  • 953
  • 2
  • 8
  • 25
  • There are multiple ways to do this. What do you want to with that information? For example, do you want to get the highest value of the previous 32 candles or your algorithm specifically needs 32 variables for 32 previous values? – vitruvius Nov 10 '19 at 05:57
  • Yes, I need all of thats. I need to calculate avg of prev 32 candles, and check if that range is swing trend. I need all O-H-L-C data – Neo.Mxn0 Nov 10 '19 at 09:07
  • I read the documentation and figured out this syntax: `close[10]` => Access the close price of the candle at -10 position right. – Neo.Mxn0 Nov 10 '19 at 09:21

1 Answers1

6

´[]´ in pinescript is called History Referencing Operator. You can use that operator to access historical values.

You can create 32 variables if your algorithm really needs those 32 individual values, or you can create a function and run a for loop.

Below code shows both examples for n=5.

//@version=4
study("My Script")

src = input(title="Source", type=input.source, defval=close)

src_1 = src[1]
src_2 = src[2]
src_3 = src[3]
src_4 = src[4]
src_5 = src[5]

avg_of_indv = avg(src_1, src_2, src_3, src_4, src_5)

get_average(avg_src, avg_len) =>
    ret_val = 0.0
    for i = 1 to avg_len
        ret_val := ret_val + avg_src[i]
    ret_val/avg_len

avg_of_func = get_average(src, 5)

plot(series=avg_of_indv, title="avg_of_indv", color=color.red, linewidth=2)
plot(series=avg_of_func, title="avg_of_func", color=color.green, linewidth=2)

If you look at the plots, both will be the same.

Also, there are highest() and lowest() functions available in pinescript. Those functions return highest/lowest value for a given number of bars back.

vitruvius
  • 15,740
  • 3
  • 16
  • 26
  • Yes, I resolved that yesterday :) But another issue came to me, I need to highlight the candles range that have shape in 010101010101... (0 mean down, 1 mean up). But history referencing cannot check value of the next candles, just prev candles only. How can I do that? – Neo.Mxn0 Nov 11 '19 at 02:44
  • Please ask another question for this. Here, we ask one question per post. Also, please attach an image that shows what you want to achieve because I’m mot sure what you mean by “next” candles. Do you mean candles that will form in the future? – vitruvius Nov 11 '19 at 06:15
  • I mean the next candle of the current candle, I tried to refer it by close[-1] but history reference is from 0..n – Neo.Mxn0 Nov 11 '19 at 10:22
  • Again, please ask a new question with an image if possible. – vitruvius Nov 11 '19 at 10:48