In this article, we delve into the functionality and application of barstate.isconfirmed
in Pine Script, particularly in the context of plotting a Relative Strength Index (RSI) indicator. We’ll explore how this feature helps in managing the peculiarities of real-time versus historical data in trading scripts.
What is barstate.isconfirmed
?
barstate.isconfirmed
is a built-in boolean variable in Pine Script. Its primary purpose is to differentiate between historical and real-time bars in a chart.
- Historical Bars: For all historical bars,
barstate.isconfirmed
is alwaystrue
. This means that the data for these bars is finalized. - Real-Time Bars: For the real-time bar,
barstate.isconfirmed
becomestrue
only when the bar closes. This is critical to avoid what is known as ‘repainting’ – a situation where an indicator changes its values as new price data comes in.
Application in Plotting RSI
Now, let’s apply this to plot a Relative Strength Index (RSI), ensuring that it only plots on confirmed bars to avoid repainting:
Pine Script Example:
//@version=5 indicator("My Unique RSI Indicator",overlay = true) customRSI = ta.rsi(close, 20) plot(barstate.isconfirmed ? customRSI : na)
Breakdown of the Script:
indicator("My Unique RSI Indicator")
: This line initializes our custom indicator and names it “My Unique RSI Indicator”.customRSI = ta.rsi(close, 20)
: We declare a variablecustomRSI
and assign it the value of the RSI computed over the last 20 bars.ta.rsi()
is a built-in function that calculates the RSI.plot(barstate.isconfirmed ? customRSI : na)
: This is wherebarstate.isconfirmed
comes into play. We use a ternary operator to decide what to plot:- If
barstate.isconfirmed
istrue
(i.e., for historical bars and the last update of a real-time bar), we plotcustomRSI
. - If
barstate.isconfirmed
isfalse
(i.e., during the formation of a real-time bar), we plotna
(not available), essentially plotting nothing.
- If
Key Features and Takeaways:
- Function Usability:
barstate.isconfirmed
is highly useful for strategies and indicators that need to avoid repainting, ensuring decisions are based on confirmed data. - Syntax: The syntax is straightforward, often used in conditional statements to determine whether to execute certain code segments.
- Application: Particularly useful in time-sensitive indicators like RSI, where real-time data might cause misleading signals if not handled properly.
- Limitation: It’s important to note that
barstate.isconfirmed
does not work withinrequest.security()
calls, which are used to fetch data from different timeframes or symbols.
In conclusion, barstate.isconfirmed
is a valuable tool in Pine Script programming, particularly for ensuring accuracy and reliability in indicators and strategies that rely on real-time data. By understanding and applying this function correctly, traders and programmers can significantly enhance the effectiveness of their trading scripts.