如何使用Pine Script V5开发价格区间工具 计算两点间百分比差值
Pine Script V5 价格区间百分比计算工具实现方案
实现逻辑说明
- 通过
input.time()参数绑定鼠标交互,支持直接在K线图上点选目标K线,自动获取该K线的时间戳 - 通过
input.price()参数绑定鼠标交互,支持在K线图任意位置点选参考价格位 - 定位到选中时间对应的K线,读取该K线的最高价数值
- 自动计算参考价格与目标K线最高价的百分比差值,正数代表参考价高于K线最高价,负数代表参考价低于K线最高价
- 新增可视化辅助元素:在选中K线和参考价之间绘制区间连线、标注百分比结果和K线最高价,实现类似原生价格区间工具的效果
完整可运行代码
//@version=5 indicator("自定义价格区间百分比工具", overlay=true, shorttitle="价格区间工具") // 交互参数定义,支持鼠标点选 selected_time = input.time(title="选中K线时间", tooltip="点击K线图选择目标K线", confirm=true) selected_price = input.price(title="参考价格", tooltip="点击K线图任意位置选定参考价格", confirm=true) // 定位目标K线,获取其最高价 is_target_bar = time == selected_time target_high = ta.valuewhen(is_target_bar, high, 0) // 计算差值并绘制可视化元素 if not na(target_high) and not na(selected_price) // 计算百分比差值 percent_diff = (selected_price - target_high) / target_high * 100 // 绘制区间虚线 range_line = line.new(x1=selected_time, y1=target_high, x2=selected_time, y2=selected_price, color=percent_diff > 0 ? color.green : color.red, width=2, style=line.style_dashed) // 标注百分比结果 diff_label = label.new(x=selected_time, y=selected_price, text=str.tostring(percent_diff, "#.##") + "%", color=color.new(percent_diff > 0 ? color.green : color.red, 90), textcolor=percent_diff > 0 ? color.green : color.red, style=label.style_label_left, size=size.small) // 标注目标K线最高价 high_label = label.new(x=selected_time, y=target_high, text="目标K线最高价: " + str.tostring(target_high, "#.####"), color=color.new(color.blue, 90), textcolor=color.blue, style=label.style_label_right, size=size.small) // 自动清理旧的绘制元素,避免重复生成 var line_pool = array.new_line() var label_pool = array.new_label() if ta.change(selected_time) or ta.change(selected_price) // 清空旧连线 for i = 0 to array.size(line_pool) - 1 line.delete(array.get(line_pool, i)) array.clear(line_pool) // 清空旧标签 for i = 0 to array.size(label_pool) - 1 label.delete(array.get(label_pool, i)) array.clear(label_pool)
使用方法
- 将上述代码复制到TradingView的Pine脚本编辑器中,点击添加到图表
- 脚本加载后会自动弹出参数确认框,按提示先点击你要统计的目标K线,再点击选定的参考价格位即可自动计算并显示结果
- 需要调整选中的K线或参考价时,双击脚本参数面板中的对应输入项,重新在K线图点选即可更新结果
内容的提问来源于stack exchange,提问作者Lenon Fernandes
相关产品推荐
相关产品推荐

