Tradingview Pine-Script:如何仅绘制最后 x 个周期

cod*_*ody 4 time period pine-script

我只想为最后 x 个周期绘制一个指标。我怎么做?

如果我可以进行时间运算(从 plotStartDate 中减去 x * period),也许我可以使用以下代码:

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)
Run Code Online (Sandbox Code Playgroud)

Pin*_*ucF 7

版本 1

不确定这就是你要找的。它使用plot()'sshow_last=参数来限制在isPlotDate满足约束后绘制的最后条形的数量:

//@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)
Run Code Online (Sandbox Code Playgroud)

版本 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)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

版本 3

更简单:

//@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)
Run Code Online (Sandbox Code Playgroud)

  • 事实证明,“timestamp()”能够完成所需的操作,从日期中减去任意月份数。版本 3 利用了这一点,并且与您的第一次尝试出奇地相似。你已经很接近了)[感谢 Pine 团队的提示。] (2认同)