为何脚本中`if barstate.isconfirmed`代码段在实时K线中每根执行两次?
为何
barstate.isconfirmed在实时K线中每根执行两次? 官方手册说明:
当脚本正在计算当前K线的最后一次(收盘)更新时返回true,下一次脚本计算将基于新K线数据。
你的脚本中,if barstate.isconfirmed代码段在实时K线的每根K线会触发两次执行,核心原因如下:
request.security触发重复计算
当使用request.security请求跨周期(这里是240分钟)数据时,Pine Script的实时计算机制会因跨周期数据的同步逻辑,在主周期K线进入barstate.isconfirmed状态后,额外触发一次完整计算。此时新K线尚未生成,barstate.isconfirmed仍为true,导致代码块再次执行。可变持久变量的累加暴露问题
你使用varip _s存储字符串,这个变量会在脚本多次计算中保留值,不会每次计算重置。两次执行barstate.isconfirmed代码块时,都会向_s追加内容,最终在标签中显示重复的Bxx✔,直观暴露了执行两次的问题。
解决办法
添加一个标志变量,确保每根K线仅执行一次barstate.isconfirmed逻辑:
修改updateLabel函数如下:
updateLabel(someStupidObject _obj) => varip _s = "" var bool hasExecuted = false // 新增执行标志 _obj.y := 1 if barstate.isnew // 新K线初始化标志 hasExecuted := false if barstate.isconfirmed and not hasExecuted _s := str.length(_s) > 50 ? str.substring(_s, str.length(_s) - 50) : _s _s += "\nB" + str.tostring(bar_index) +"✔" hasExecuted := true // 标记当前K线已执行 _lbl = label.new(bar_index, high, _s, color = color.yellow, textcolor = color.black)
内容的提问来源于stack exchange,提问作者Moebius
相关产品推荐
相关产品推荐

