Pinescript V5:获取条件触发后最高值遇编译错误的解决方案求助
Pine Script 5 条件触发后获取区间最高值报错问题
我在Pine Script 5版本中,想要获取Cond_1(EMA金叉)触发后的区间最高值,写了如下简化代码:
Cond_1 = ta.crossover(ema_1, ema_2) Cond_2 = ta.crossunder(ema_1, ema_2) // 想要获取Cond_1触发后的最高值,所以用了ta.barssince()和ta.highest() Bars_count = ta.barssince(Cond_1) Highest = ta.highest(Bars_count) plot(Highest)
编译时出现如下报错:
Study error.
Invalid value of the 'length' argument (NaN) in the
"Highest" function. It must be > 0
我尝试给Bars_count加1,或者在ta.highest()前使用fixnan(),但都无效,代码如下:
Cond_1 = ta.crossover(ema_1, ema_2) Cond_2 = ta.crossunder(ema_1, ema_2) Bars_count = ta.barssince(Cond_1) + 1 // 试图确保结果始终大于0 Highest = fixnan(ta.highest(Bars_count)) plot(Highest)
请问有什么解决办法?
解决方案
问题根源在于**ta.barssince(Cond_1)在Cond_1从未触发时会返回NaN**,即使加1后还是NaN,而ta.highest()不接受NaN作为长度参数。另外,ta.highest(length)的逻辑是取最近length根K线的最高值,但你需要的是从Cond_1触发后到当前的区间最高值,用ta.barssince()作为长度的写法本身逻辑就有问题(当新的K线出现,Bars_count会递增,ta.highest(Bars_count)会不断扩大计算范围,直到下一个Cond_1触发)。
推荐两种更可靠的实现方式:
方法1:使用ta.highest()的条件重置版本
利用ta.highest()可以结合区间长度的特性,直接指定从Cond_1触发后开始计算最高值,同时处理未触发的情况:
// 补充示例中缺失的EMA定义 ema_1 = ta.ema(close, 50) ema_2 = ta.ema(close, 200) Cond_1 = ta.crossover(ema_1, ema_2) Cond_2 = ta.crossunder(ema_1, ema_2) // 计算Cond_1触发后的区间长度,加1是因为barssince返回的是间隔K线数 bar_length = ta.barssince(Cond_1) + 1 // 从Cond_1触发后取最高值,未触发时用当前close兜底 Highest = na(bar_length) ? close : ta.highest(close, bar_length) plot(Highest, color=color.new(color.green, 0), title="金叉后最高值")
方法2:使用var变量手动追踪最高值
通过变量持续更新最高值,在Cond_1触发时重置,灵活性更高:
// 补充示例中缺失的EMA定义 ema_1 = ta.ema(close, 50) ema_2 = ta.ema(close, 200) Cond_1 = ta.crossover(ema_1, ema_2) Cond_2 = ta.crossunder(ema_1, ema_2) // 初始化var变量,用于存储区间最高值 var float current_highest = na // Cond_1触发时,将当前close设为初始最高值 if (Cond_1) current_highest := close // 非Cond_1触发时,更新最高值为当前close和current_highest的较大者 else if not na(current_highest) current_highest := math.max(current_highest, close) // 可选:Cond_2触发时重置最高值 if (Cond_2) current_highest := na plot(current_highest, color=color.new(color.red, 0), title="金叉后最高值")
关键说明
- 方法1更简洁,适合不需要额外逻辑的场景;
- 方法2灵活性更高,方便在
Cond_2(死叉)触发时添加自定义逻辑; - 两种方法都处理了
Cond_1未触发时的NaN问题,避免报错。
内容的提问来源于stack exchange,提问作者Tùng Nguyễn Viết
相关产品推荐
相关产品推荐

