Pinescript新手求助:仅当价格未回归日K收盘价时绘制向右水平线
Pine Script 实现未被价格回归的日K收盘价水平线
核心思路
要实现需求,需要跟踪每个日K收盘价,并持续检查后续价格是否触及该价位,仅保留未被触及的价位并绘制水平线:
- 每日收盘时记录当日收盘价和对应的K线索引
- 用数组存储所有待检查的日收盘价及位置
- 每个新K线检查数组中所有价格是否被当前K线的高低区间覆盖,触及的从数组中移除
- 对数组中剩余的未触及价格,绘制向右延伸的水平线
完整代码实现
//@version=5 indicator("未被回归的日收盘价水平线", overlay=true) // 存储未被触及的日收盘价和对应的bar索引 var line[] untestedLines = array.new_line() var float[] untestedCloses = array.new_float() var int[] untestedBarIndices = array.new_int() // 每日收盘时记录数据 isNewDay = ta.change(time("D")) if isNewDay // 记录前一日收盘价和bar索引 prevClose = close[1] prevBarIndex = bar_index[1] // 创建新线条并加入数组 newLine = line.new(prevBarIndex, prevClose, bar_index, prevClose, extend=extend.right, color=color.red) array.push(untestedLines, newLine) array.push(untestedCloses, prevClose) array.push(untestedBarIndices, prevBarIndex) // 检查每个未被触及的价格是否被当前K线触及 if barstate.isconfirmed // 倒序遍历数组,避免删除元素时索引混乱 for i = array.size(untestedCloses) - 1 downto 0 currentClose = array.get(untestedCloses, i) // 检查当前K线的高低区间是否覆盖该收盘价 if low <= currentClose and currentClose <= high // 触及则删除线条并移除数组元素 line.delete(array.get(untestedLines, i)) array.remove(untestedLines, i) array.remove(untestedCloses, i) array.remove(untestedBarIndices, i)
代码说明
- 数组初始化:用三个数组分别存储线条对象、对应的收盘价和K线索引,方便后续跟踪和管理
- 新日检测:通过
ta.change(time("D"))判断新的交易日开始,记录前一日的收盘价和K线位置,并创建对应的水平线加入数组 - 触及检查:每个K线确认后(
barstate.isconfirmed),倒序遍历数组,检查当前K线的高低区间是否覆盖存储的收盘价,若触及则删除对应线条并从数组中移除 - 线条延伸:创建线条时设置
extend=extend.right,未被触及的线条会持续向右延伸
内容的提问来源于stack exchange,提问作者deejay
相关产品推荐
相关产品推荐

