Search code examples
pine-scripttradingpine-script-v5pine-script-v4

How to use barstate.islastconfirmedhistory


Can you please explain how to use barstate.islastconfirmedhistory ?

Can anyone create a sample program where the below built-in variable is used?

barstate.islastconfirmedhistory

Solution

  • It is used to figure out the last historical bar when you add your script to the chart.

    The word "last historical" is very important here.

    What that means is:

    • If the instrument is trading, it will return true for the bar preciding the real-time bar
    • If the instrument is trading and if new bars form, it will still point to the same bar as when you added the indicator to your chart. Because after you add the indicator, the new bars are not being created from historical data, instead, they are being created from real-time data
    • If the instrument is not trading, it will point to the last bar where the market is closed

    Example:

    //@version=5
    indicator(title="My Script", overlay=true)
    
    if barstate.islastconfirmedhistory
        label.new(x=bar_index, y=high, color=color.green, textcolor=color.white, text="Last\nhistorical\nbar")
    

    If I add this to BTC (which is currently trading) and change my timeframe to 5 seconds (so new bars form quickly), you can actually see the point when I added this indicator to my chart. enter image description here

    If I add the same script to APPL, which is currently not trading, it will point to the last bar.

    enter image description here