基于Parabolic SAR拐点绘制水平线的Pine Script实现求助
Pine Script修正:Parabolic SAR转向水平线坐标错误与参数增强
问题分析
原代码可识别Parabolic SAR的转向拐点,但绘制对应水平线时,线段起止K线坐标逻辑错误,导致线段反向延伸;同时缺少用户可配置参数,无法选择用高低价或收盘价作为水平线的Y轴取值。
修正后的代码
//@version=5 indicator("SAR转向水平线", overlay=true) // 新增用户可选参数:水平线Y轴取值类型 levelSource = input.string("高低点", title="水平线取值来源", options=["高低点", "收盘价"], tooltip="选择水平线的Y轴取值依据") sarStep = input.float(0.02, title="SAR步长") sarMax = input.float(0.2, title="SAR最大步长") // 计算Parabolic SAR sarValue = ta.sar(sarStep, sarMax) // 判断SAR转向信号 isLong = sarValue < low isShort = sarValue > high longSignal = ta.crossover(isLong, isShort) shortSignal = ta.crossunder(isLong, isShort) // 记录转向区间的关键价格与K线索引 var float lastLevelPrice = na var int startBarIndex = na var int endBarIndex = na // 处理多头转向信号(空头→多头) if longSignal endBarIndex = bar_index // 按参数选择水平线价格 if levelSource == "高低点" lastLevelPrice = ta.highest(high, endBarIndex - startBarIndex + 1) else lastLevelPrice = ta.close[endBarIndex - startBarIndex] // 绘制正确区间的水平线 line.new(startBarIndex, lastLevelPrice, endBarIndex, lastLevelPrice, color=color.green, width=2) startBarIndex = bar_index // 处理空头转向信号(多头→空头) if shortSignal endBarIndex = bar_index if levelSource == "高低点" lastLevelPrice = ta.lowest(low, endBarIndex - startBarIndex + 1) else lastLevelPrice = ta.close[endBarIndex - startBarIndex] line.new(startBarIndex, lastLevelPrice, endBarIndex, lastLevelPrice, color=color.red, width=2) startBarIndex = bar_index // 初始化起始K线索引 if bar_index == 0 startBarIndex = bar_index // 绘制SAR指标 plot(sarValue, color=color.blue, title="SAR", style=plot.style_circles)
关键修正点说明
转向区间坐标修正:
- 用
startBarIndex和endBarIndex分别记录每个转向区间的起始、结束K线索引,确保线段从区间起点延伸至终点,彻底解决反向延伸问题 - 通过
ta.crossover/ta.crossunder精准识别多空转向信号,避免误判
- 用
参数功能增强:
- 新增
levelSource输入参数,支持用户切换"高低点"或"收盘价"作为水平线的Y轴取值 - 选择"高低点"时,自动取对应区间内的最高价(空头转多头)或最低价(多头转空头);选择"收盘价"时,取转向结束K线的收盘价
- 新增
线段绘制逻辑优化:
- 每次转向信号触发时,基于记录的区间索引和对应价格绘制水平线,确保线段范围与转向区间完全匹配
内容的提问来源于stack exchange,提问作者Classic Scott
相关产品推荐
相关产品推荐

