如何在Pine Script中将绘制的水平线改为水平射线?
在Pine Script中绘制水平射线(替代水平线)
你提供的代码用plot()函数绘制的是贯穿整个图表的水平线,如果要改成从指定位置向右延伸的水平射线,可以使用Pine Script v5的line.new()函数实现,以下是修改后的代码及说明:
//@version=5 indicator("My Horizontal Rays", overlay=true) price1 = input.price(0, "Price 1", confirm=true) price2 = price1 * 1.05 price3 = price1 * 0.95 // 声明持久化的线变量,避免每根K线重复创建线段 var line ray_yellow = na var line ray_green = na var line ray_red = na // 当输入价格变化时,更新射线 if (price1 != price1[1]) // 删除旧射线,避免界面堆积 line.delete(ray_yellow) line.delete(ray_green) line.delete(ray_red) // 创建水平射线:从当前K线开始,向右延伸足够远的距离(模拟无限延伸) ray_yellow := line.new(bar_index, price1, bar_index + 1000, price1, color=color.yellow, width=2) ray_green := line.new(bar_index, price2, bar_index + 1000, price2, color=color.green, width=2) ray_red := line.new(bar_index, price3, bar_index + 1000, price3, color=color.red, width=2)
关键说明:
- 核心差异:
plot()会在全图表范围内绘制价格线,而line.new()可自定义线段的起点与终点。通过将终点X坐标设为bar_index + 1000(远大于当前图表K线数量的数值),就能让线段向右无限延伸,形成射线效果。 - 变量持久化:用
var关键字声明线变量,确保变量不会在每根K线重新初始化,避免重复创建大量冗余线段。 - 动态更新:通过
if (price1 != price1[1])判断输入价格是否变化,变化时删除旧射线并创建新射线,保证射线跟随输入价格实时更新。
如果需要让射线从历史特定K线开始,只需把bar_index替换为目标K线的索引即可(例如用ta.barssince(condition) + bar_index定位满足特定条件的K线)。
内容的提问来源于stack exchange,提问作者sey eeet
相关产品推荐
相关产品推荐

