Thinking in Pine - Study References Too Many Bars In the History

BINANCE:BTCUSDT   Bitcoin / TetherUS
Welcome to "Thinking in Pine" short video series on the topics of Pine Script.

Today's topic is handling the error - "The study references too many candles in the history" and other bar_index related issues.

If you are not familiar with Pine Script time series concepts, please go through our previous videos.

🎲 Points Discussed
  • When do we get the error "Study references too many candles in the history" and how to overcome this issue.
  • bar_index limitations with drawing objects on the chart.

🎯 Example Program - Historical Reference Alternative Implementation

// When we are trying to refer to history more than or equal to 10000 bars older
// float value = close[10000]
// plot(value)

// Alternative implementation
var values =<float>()
// Throws error on first bar since the number of items is less than 10000
// float valueFromArray = values.get(10000)
// plot(valueFromArray)

//Option 1 - Get the last available value when the number of bars available is less than 10000
float valueFromArray1 = values.get(math.min(bar_index, 10000))

// Option 2 - If number of available bars less than 10000, then set value to na else get the value of 10000 bars back
float valueFromArray2 = values.size() <= 10000? na : values.get(10000)

🎯 Example Program - Drawing Object Limitations with Bar Index

// Trying to create a line too far in history or in future
// if(barstate.islast)
//     Throws error as can only draw upto 9999 bars before
//     ln1 =, high, bar_index-10000, high)

//     Throws error as we can only draw upto 500 bars in the future.
//     ln2 =, high, bar_index+501, high)

startingPoint = ta.valuewhen(bar_index == last_bar_index-10000, time, 0)
float price = 0.0
    // However, we can draw more than 10000 bars back or more than 500 bars in the future using time instead of bar _index
    ln =, high, startingPoint, high, xloc=xloc.bar_time)
    // Cannot use line.get_price when the line is drawn using xloc = xloc.bar_time
    // price := ln.get_price(last_bar_index-5000)


The information and publications are not meant to be, and do not constitute, financial, investment, trading, or other types of advice or recommendations supplied or endorsed by TradingView. Read more in the Terms of Use.