Pine脚本:运行代码块在历史数据中只有一次

Pine script: Run code block only once in historical data

在 pine 脚本中,我如何 运行 一个特定的代码块每个栏只有一次。

barstate.isnew // This runs only once in realtime case which is the current bar
But for historical data which is previous bars it is true on each tick, so how can I achieve this for historical data

默认情况下,您的代码只会 运行 每个历史柱形一次。

When a Pine script is loaded on a chart it executes once on each historical bar using the available OHLCV (open, high, low, close, volume) values for each bar. Once the script’s execution reaches the rightmost bar in the dataset, if trading is currently active on the chart’s symbol, then Pine studies will execute once every time an update occurs, i.e., price or volume changes.

详见松树Execution Model
所以,您所要求的已经是 Pine Script 的默认行为。

编辑 1
回应

啊,你的意思是每个实时柱只执行一次。
您需要为此使用 varip 关键字而不是 var.
varip 类似于 var 关键字,但是用 varip 声明的变量在实时柱的更新之间保留它们的值。

这是 March 2021 中发布的相当新的关键字。
this article.

中可以找到关于 varip 用法的详尽解释和示例脚本

下面的示例代码在实时柱的每个“更新报价”上增加一个计数器。

//@version=4
study("")

varip int updateNo = na

if barstate.isnew
    updateNo := 1
else
    updateNo := updateNo + 1

plot(updateNo, style = plot.style_circles)

您可以向其中添加一个变量来实现您想要的效果,如下所示:

//@version=4
study("")

varip int  updateNo   = na
varip bool hasBeenRun = false

if barstate.isnew
    updateNo   := 1
    hasBeenRun := true
else
    if not hasBeenRun
        updateNo := updateNo + 1

plot(updateNo, style = plot.style_circles)