Trading View Pine Script中show_last能否设为动态值?
问题:Pine Script中如何动态设置plot的show_last参数?
我在TradingView的Pine Script中使用plot()函数时,将show_last设为常量(如show_last=500)时代码可正常运行:
plot(trendpoint,linewidth= 1,show_last=500 ...
现在我希望show_last实现动态变化——随着每根K线bar_index增加1,show_last也同步增加1。尝试设置show_last=bar_index-500时触发报错,报错信息:
Cannot call 'plot' with argument 'show_last'='call 'operator -' (series int)'. An argument of 'series int' type was used but a 'input int' is expected.
我的示例代码如下:
indicator("Title TBD",overlay=true) bar_index_2 = bar_index-9401 trendpoint = (bar_index_2)* 0.05301886792452835 + 390.34113207547165 plot(trendpoint,linewidth= 1,show_last=500 ,color=color.new(color.rgb(255, 0.0 , 0.0 ), 65 ),style=plot.style_line,title='Stars: 79 , Original Price: 418.07 , Original Date: 2023-10-31T14:00:00-04:00 , Original Position: 523 , Ref Price: 420.88 , Ref Date: 2023-11-01T11:55:00-04:00 , Reference Position: 576 ') trendpoint := (bar_index_2)* 0.05804878048780477 + 387.44390243902444 plot(trendpoint,linewidth= 1,show_last=500 ,color=color.new(color.rgb(255, 9.107142857142858 , 9.107142858 ), 65 ),style=plot.style_line,title='Stars: 77 , Original Price: 418.5 , Original Date: 2023-10-31T15:00:00-04:00 , Original Position: 535 , Ref Price: 420.88 , Ref Date: 2023-11-01T11:55:00-04:00 , Reference Position: 576 ')
作为Pine Script新手,我想请教该如何实现show_last的动态设置?
解决方案
Pine Script的plot()函数中,show_last参数仅接受input类型的常量值,不支持动态变化的series类型变量,所以直接用bar_index计算的值会报错。要实现“只显示最近N根K线的指标线,且N随bar_index递增”的效果,可换用以下思路:
方法:用条件判断将超出显示范围的指标值设为na
通过判断当前K线的bar_index是否在目标范围内,把超出范围的trendpoint设为na(Pine Script中na值不会被绘制),从而实现类似动态show_last的效果。
修改后的示例代码:
indicator("Title TBD",overlay=true) // 定义动态显示的起始bar索引:只显示从该索引开始的K线,随着bar_index增长,显示数量自动增加 show_from_bar = 500 // 可根据需求调整初始值 is_in_show_range = bar_index >= show_from_bar bar_index_2 = bar_index-9401 trendpoint = (bar_index_2)* 0.05301886792452835 + 390.34113207547165 // 仅在目标范围内保留数值,否则设为na trendpoint = is_in_show_range ? trendpoint : na plot(trendpoint,linewidth= 1,color=color.new(color.rgb(255, 0.0 , 0.0 ), 65 ),style=plot.style_line,title='Stars: 79 , Original Price: 418.07 , Original Date: 2023-10-31T14:00:00-04:00 , Original Position: 523 , Ref Price: 420.88 , Ref Date: 2023-11-01T11:55:00-04:00 , Reference Position: 576 ') trendpoint := (bar_index_2)* 0.05804878048780477 + 387.44390243902444 // 同样应用范围判断 trendpoint = is_in_show_range ? trendpoint : na plot(trendpoint,linewidth= 1,color=color.new(color.rgb(255, 9.107142857142858 , 9.107142858 ), 65 ),style=plot.style_line,title='Stars: 77 , Original Price: 418.5 , Original Date: 2023-10-31T15:00:00-04:00 , Original Position: 535 , Ref Price: 420.88 , Ref Date: 2023-11-01T11:55:00-04:00 , Reference Position: 576 ')
逻辑说明
show_from_bar是你希望开始显示指标的起始bar索引,当bar_index大于等于这个值时,指标线才会被绘制;- 随着新K线生成,
bar_index递增,显示的K线数量会自动增加,达到“show_last随bar_index同步增长”的效果; - 这种方法避开了
show_last参数的限制,用Pine Script原生的na值特性实现动态显示控制。
内容的提问来源于stack exchange,提问作者jonathan gabizon
相关产品推荐
相关产品推荐

