如何在longCondition触发时,查找其之前最近inside_bar与该条件间的最高值
在Pine Script中计算longCondition触发前最近inside_bar到触发K线间的最高值
需求说明
当longCondition(由ta.crossover(a, b)定义)触发时,找到此前最近一根满足inside_bar = high <= high[1] and low >= low[1]的K线,计算这两根K线之间的最高价。
实现代码
// 定义基础条件 inside_bar = high <= high[1] and low >= low[1] longCondition = ta.crossover(a, b) // 记录最近一次inside_bar出现的bar索引 lastInsideBarIndex = ta.valuewhen(inside_bar, bar_index, 0) // 触发longCondition时计算区间最高价 var float highestBetween = na if (longCondition) // 区间包含inside_bar和触发K线,若要排除inside_bar,把+1去掉 highestBetween = ta.highest(high, bar_index - lastInsideBarIndex + 1) // 可选:绘制结果以便验证 plot(highestBetween, color=color.red, title="区间最高价")
代码解释
ta.valuewhen(inside_bar, bar_index, 0):获取最近一次inside_bar成立时的bar索引,精准定位触发信号前的最近符合条件的K线。- 当
longCondition触发时,通过bar_index - lastInsideBarIndex + 1确定计算区间的长度,再用ta.highest()提取这段区间内的最高价。 - 使用
var声明highestBetween,可以保留每次触发时计算的结果,不会随新K线刷新而重置。
内容的提问来源于stack exchange,提问作者mjune
相关产品推荐
相关产品推荐

