如何判断图表中箱体顶部是否被触碰及价格重回箱体时删除箱体
Pine Script 箱体需求实现方案
核心逻辑实现
针对你提出的两个需求,以下是修正后的代码及逻辑说明:
问题分析
你的原始代码存在两处明显问题:一是重复调用box.delete(box.delete(OBS))会导致语法错误;二是未记录箱体状态,无法实现顶部触碰判断和重回箱体删除的逻辑。
完整实现代码
//@version=5 indicator("影线占比箱体监测", overlay=true) // 替换为你实际的「蜡烛影线占比70%」判断逻辑 n = ta.barssince(/* 这里填写影线占比70%的条件,例如: (high - low) * 0.7 <= math.max(high - close, close - low) */) // 存储箱体对象与状态 var box[] box_list = array.new_box() var bool[] is_top_touched = array.new_bool() // 创建箱体:满足影线条件时执行 if n != -1 and not na(low[n]) and not na(high[n]) new_box = box.new(left=bar_index-1, top=low[n], right=bar_index+100, bottom=high[n], border_color=color.black, border_width=1, bgcolor=color.rgb(104, 204, 174, 51), extend=extend.right) array.push(box_list, new_box) array.push(is_top_touched, false) // 遍历处理所有箱体 for i = 0 to array.size(box_list)-1 current_box = array.get(box_list, i) if current_box != na box_top = box.get_top(current_box) box_bottom = box.get_bottom(current_box) // 需求1:判断箱体顶部是否被价格触碰 if not array.get(is_top_touched, i) if high >= box_top array.set(is_top_touched, i, true) // 可选:顶部触碰时添加标记 label.new(bar_index, high, "顶部触碰", color=color.red, textcolor=color.white) // 需求2:价格重回箱体范围时删除箱体 if close >= box_bottom and close <= box_top box.delete(current_box) array.remove(box_list, i) array.remove(is_top_touched, i)
代码说明
- 使用
var定义数组存储箱体对象和顶部触碰状态,确保状态在Bar循环中持续保留 - 顶部触碰判断:通过对比当前K线最高价与箱体顶部,标记触碰状态,可按需添加提示标记
- 重回箱体删除:当收盘价落在箱体顶底区间内时,删除箱体并从数组中移除对应记录
内容的提问来源于stack exchange,提问作者Rocky Menezes
相关产品推荐
相关产品推荐

