求助:如何检测最新K线对支撑/阻力线的测试穿越
支撑/阻力线最新K线穿越检测修改方案
现有代码仅能检测前一根K线对支撑线和阻力线的穿越情况,需修改为检测最新K线的穿越行为。
现有代码
for i = 0 to support.size() - 1 if (high[1] > support.get(i).get_y1() and math.max(open[1],close[1])< support.get(i).get_y1()) or (low[1] < support.get(i).get_y1() and math.min(open[1],close[1])> support.get(i).get_y1()) lastCrossedBar := bar_index deleteLine := true if deleteLine line.delete(support.get(i)) for i = 0 to resistance.size() - 1 if (high[1] > resistance.get(i).get_y1() and math.max(open[1],close[1])< resistance.get(i).get_y1()) or (low[1] < resistance.get(i).get_y1() and math.min(open[1],close[1])> resistance.get(i).get_y1()) lastCrossedBar := bar_index deleteLine := true if deleteLine line.delete(resistance.get(i))
修改方案
在Pine Script中,[1]代表前一根K线的行情数据,[0]才是最新K线(当前Bar)的行情数据。只需将代码中所有的high[1]、open[1]、close[1]、low[1]替换为high[0]、open[0]、close[0]、low[0],即可实现检测最新K线的穿越逻辑。
修改后的完整代码
// 检测最新K线对支撑线的穿越 for i = 0 to support.size() - 1 supportLevel = support.get(i).get_y1() // 判断最新K线是否穿越支撑线 if (high[0] > supportLevel and math.max(open[0], close[0]) < supportLevel) or (low[0] < supportLevel and math.min(open[0], close[0]) > supportLevel) lastCrossedBar := bar_index deleteLine := true if deleteLine line.delete(support.get(i)) // 检测最新K线对阻力线的穿越 for i = 0 to resistance.size() - 1 resistanceLevel = resistance.get(i).get_y1() // 判断最新K线是否穿越阻力线 if (high[0] > resistanceLevel and math.max(open[0], close[0]) < resistanceLevel) or (low[0] < resistanceLevel and math.min(open[0], close[0]) > resistanceLevel) lastCrossedBar := bar_index deleteLine := true if deleteLine line.delete(resistance.get(i))
补充说明
- 新增
supportLevel和resistanceLevel变量,提升代码可读性 - 保留原逻辑中的穿越判断条件:K线实体位于线的一侧,影线穿透至另一侧
- 图片说明:展示了K线穿越支撑/阻力线的典型场景,辅助理解穿越检测的触发逻辑
内容的提问来源于stack exchange,提问作者Javier Franco Lineros
相关产品推荐
相关产品推荐

