Last Available Bar Info
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © paragjyoti2012

//@version=5

// @description : This simple library is built with an aim of getting the last available bar information for the chart. This returns a constant value that doesn't change on bar change.
// For backtesting with accurate results on non standard charts, it will be helpful. (Especially if you are using non standard charts like Renko Chart). 


library("Last_Available_Bar_Info")


tf=timeframe.period

// Returns Timestamp of the last available bar (Constant)
export getLastBarTimeStamp()=>
    var t=0
    bid=ta.barssince(bar_index==0)
    if(bid)
        if(t==0)
            t:=time
    t


// Returns Number of Available Bars on the chart (Constant)
export getAvailableBars()=>
 
    last_ts=getLastBarTimeStamp()
    
    mult=timeframe.multiplier*1000
    time_factor=0
    
    tf_str_arr=str.split(tf,"")
    array.reverse(tf_str_arr)
    res=array.get(tf_str_arr,0)
    if(res=="S")
        time_factor:=mult
    else if(res=="D")
        time_factor:=mult*60*24
    else if(res=="W")
        time_factor:=mult*60*24*7
    else if(res=="M")
        time_factor:=mult*60*24*30
    else
        time_factor:=mult*60
        
    delta_time=timenow-last_ts
    bars=math.floor(delta_time/time_factor)
   

// Example   

// import paragjyoti2012/Last_Available_Bar_Info/v2 as LastBarInfo

// last_bar_timestamp=LastBarInfo.getLastBarTimeStamp()
// no_of_bars=LastBarInfo.getAvailableBars()

// If you are using Renko Charts, for backtesting, it's necesary to filter out the historical bars that are not of this timeframe. 
// In Renko charts, once the available bars of the current timeframe (based on your Tradingview active plan) are exhausted, 
// previous bars are filled in with historical bars of higher timeframe. Which is detrimental for backtesting, and it leads to unrealistic results. 
// To get the actual number of bars available of that timeframe, you should use this security function to get the timestamp for the last (real) bar available.
    
    // tf=timeframe.period
    // real_available_bars   = request.security(syminfo.ticker, tf , LastBarInfo.getAvailableBars() ,  lookahead = barmerge.lookahead_off)
    // last_available_bar_timestamp   = request.security(syminfo.ticker, tf , LastBarInfo.getLastBarTimeStamp() ,  lookahead = barmerge.lookahead_off)


