如何识别line.new()的特定运行时错误并用于条件判断?
在Pine Script中处理
line.new()的索引越界错误 Pine Script没有运行时错误捕获机制,无法直接判断是否触发了特定原生错误后再执行自定义提示。你需要提前校验参数合法性,从根源避免触发该错误,同时实现自定义错误提示。
你遇到的错误是因为
line.new()的x1参数使用了bar索引,且该索引距离当前bar过远(比如传入了0.0这类无效值)。官方推荐用time替代bar索引作为x坐标,因为time是全局统一的时间戳,不会随图表周期、加载的K线范围变化。提前校验参数的实现示例:
先判断x1的bar索引是否在有效范围内,若不合法则触发自定义错误:
//@version=5 indicator("Line Index Validation", overlay=true) // 示例:假设你的x1是计算得到的bar索引 x1 = 0.0 current_bar = bar_index // 定义合法范围:x1需为非负,且与当前bar索引的差值不超过100(可按需调整) is_valid = x1 >= 0 and math.abs(x1 - current_bar) <= 100 if not is_valid runtime.error("自定义错误:x1参数无效,bar索引距离当前bar过远,请改用time值") else // 参数合法时才创建线条 line.new(x1=x1, y1=close[toint(x1 - current_bar)], x2=current_bar, y2=close, color=color.red)
- 彻底规避错误的方案:直接使用
time作为x参数
//@version=5 indicator("Use Time for Line Coords", overlay=true) // 取100根bar前的时间作为x1 x1_time = time[100] current_time = time line.new(x1=x1_time, y1=close[100], x2=current_time, y2=close, color=color.blue)
内容的提问来源于stack exchange,提问作者AmphibianTrading
相关产品推荐
相关产品推荐

