Search code examples
pine-scripttradingview-api

Can show_last be dynamic in Pine Script for Trading View


I'm using the plot function with show_last as a constant and the code works well plot(trendpoint,linewidth= 1,show_last=500 ...

I'm now trying to have the show_last function be dynamic, meaning as the bar_index increases by 1 with every candle, the show_last would also increase by 1. plot(trendpoint,linewidth= 1,show_last=bar_index-500 ...

But this generates an error

More Details... I'm new to pine script and found that the code below works when show_last is a constant:

indicator("Title TBD",overlay=true)

bar_index_2 = bar_index-9401

trendpoint = (bar_index_2)* 0.05301886792452835 + 390.34113207547165

plot(trendpoint,linewidth= 1,**show_last=500** ,color=color.new(color.rgb(255, 0.0 , 0.0 ), 65 ),style=plot.style_line,title='Stars: 79 , Original Price: 418.07 , Original Date: 2023-10-31T14:00:00-04:00 , Original Position: 523 , Ref Price: 420.88 , Ref Date: 2023-11-01T11:55:00-04:00 , Reference Position: 576 ')

trendpoint := (bar_index_2)* 0.05804878048780477 + 387.44390243902444

plot(trendpoint,linewidth= 1,**show_last=500** ,color=color.new(color.rgb(255, 9.107142857142858 , 9.107142857142858 ), 65 ),style=plot.style_line,title='Stars: 77 , Original Price: 418.5 , Original Date: 2023-10-31T15:00:00-04:00 , Original Position: 535 , Ref Price: 420.88 , Ref Date: 2023-11-01T11:55:00-04:00 , Reference Position: 576 ')

For example is there a way to make the show_last = bar_index - 500? This generates an error: Cannot call 'plot' with argument 'show_last'='call 'operator -' (series int)'. An argument of 'series int' type was used but a 'input int' is expected.

Anyone have any suggestions for a noob?


Solution

  • While you cannot use a dynamic value for show_last in plot(), if what you want to achieve is to draw a line over a certain number of bars in the past, you can use a line object instead of plot():

    //@version=5
    indicator("drawLine", overlay = true)
    
    int fromBarIndex = bar_index - 700
    int toBarIndex = fromBarIndex + 500
    float price = 30000
    
    if barstate.islast
        var line priceLine = line.new(fromBarIndex, price, toBarIndex, price)
    

    View screenshot