Tradingview Pine-Script: How to plot only the last x periods

Viewed 7439

I'd like to plot an indicator only for the last x periods. How do I do that?

If I could do time operations (substract x * period from plotStartDate), maybe I could use this code:

period = timeframe.ismonthly or timeframe.isweekly ? "12M" : "M"
plotStartDate = timestamp(year(timenow), month(timenow), dayofmonth(timenow), 00, 00)
isPlotDate = time >= plotStartDate
plot(isPlotDate ? mydata : na, color=mydata != mydata[1]:na, style=plot.style_line, linewidth=2)
2 Answers

Version 1

Not sure this is what you're looking for. It uses plot()'s show_last= parameter to restrict the number of last bars plotted after your isPlotDate constraint has been satisfied:

//@version=4
study("", "", true)
xPeriods = input(10)
plotStartDate = timestamp(year(timenow), month(timenow), dayofmonth(timenow), 00, 00)
isPlotDate = time >= plotStartDate
plot(isPlotDate ? close : na, show_last = xPeriods)

Version 2

//@version=4
study("Plot starting n months back", "", true)
monthsBack      = input(3, minval = 0)
monthsExtra     = monthsBack % 12
monthsExcedent  = month(timenow) - monthsExtra
yearsBack       = floor(monthsBack / 12) + (monthsExcedent <= 0 ? 1 : 0)
targetMonth     = monthsExcedent <= 0 ? 12 + monthsExcedent : monthsExcedent
targetYearMonth = year == year(timenow) - yearsBack and month == targetMonth
beginMonth      = not targetYearMonth[1] and targetYearMonth

var float valueToPlot = na
if beginMonth
    valueToPlot := high
plot(valueToPlot)
bgcolor(beginMonth ? color.green : na)

enter image description here

Version 3

Simpler:

//@version=4
study("Plot starting n months back", "", true)
monthsBack = input(3, minval = 0)

targetDate = time >= timestamp(year(timenow), month(timenow) - monthsBack, 1, 0, 0, 0)
beginMonth = not targetDate[1] and targetDate

var float valueToPlot = na
if beginMonth
    valueToPlot := high
plot(valueToPlot)
bgcolor(beginMonth ? color.green : na)

Version 4

At v4 you can set the variable show_last in the plot() function.

In "PineScript language reference manual" says:

show_last (input integer) If set, defines the number of bars (from the last bar back to the past) to plot on chart.

https://www.tradingview.com/pine-script-reference/#fun_plot

Related