如何在Pine Script中以bar_index为条件绘制趋势线?
Pine Script 实现指定bar_index间趋势线的解决方案
问题原因
你尝试的代码无法运行,是因为当bar_index == 4时,bar_index[35]等于4 - 35 = -31,Pine Script不允许访问负数索引的历史数据(不存在该K线),触发了索引越界错误。
可行实现方法
根据需求,提供两种常用方案:
方案1:固定连接指定bar_index的趋势线(推荐)
在barstate.islast条件下绘制,此时所有K线已加载,可安全获取任意已存在K线的数据:
//@version=5 indicator(title="连接指定bar_index的趋势线", overlay=true) if barstate.islast and bar_index >= 35 // 确保bar_index=35的K线已存在 // 连接bar_index=35和bar_index=4的两个点 line.new( x1=35, y1=close[bar_index - 35], // 获取bar_index=35的收盘价 x2=4, y2=close[bar_index - 4], // 获取bar_index=4的收盘价 color=color.blue, width=2 )
或者用ta.valuewhen函数更直观地指定条件获取数据,避免索引计算错误:
//@version=5 indicator(title="连接指定bar_index的趋势线", overlay=true) if barstate.islast // 通过条件匹配获取对应bar_index的收盘价 y35 = ta.valuewhen(bar_index == 35, close, 0) y4 = ta.valuewhen(bar_index == 4, close, 0) line.new(x1=35, y1=y35, x2=4, y2=y4, color=color.blue, width=2)
方案2:在特定bar_index触发绘制
如果需要在K线走到某一特定索引(比如bar_index=40)时绘制趋势线,需确保此时能访问到两个目标K线的数据:
//@version=5 indicator(title="在指定bar_index绘制趋势线", overlay=true) // 当K线走到bar_index=40时,绘制连接35和4的趋势线 if bar_index == 40 line.new( x1=35, y1=close[40 - 35], // bar_index=40时,close[5]对应bar_index=35的收盘价 x2=4, y2=close[40 - 4], // close[36]对应bar_index=4的收盘价 color=color.red, width=2 )
关键要点
bar_index从0开始递增,数值越大代表越新的K线;- 访问历史数据时,
var[n]对应当前K线之前第n根K线的数据,其bar_index为当前bar_index - n; - 必须保证访问的历史索引非负(即目标K线已存在),否则会报错。
内容的提问来源于stack exchange,提问作者AmirX
相关产品推荐
相关产品推荐

