如何用input.bool开关控制Pine Script中Line.new的显示与隐藏?
实现Line.new的显示/隐藏开关
你之前的问题出在没把线的创建/删除逻辑和开关变量绑定,而且直接用tl[1]删除线的写法不符合Pine Script v5的规则(line.new返回单个线对象,不是数组)。下面是正确的实现方式:
修改后的完整代码
//@version=5 indicator("Asia Range Toggle", overlay=true) // 输入设置 M1 = "Asia Range Settings" ShowAsiaRange = input.bool(true,'Show Asia Range', group= M1) line_color = color.new(color.blue, 0) upperlower_line_style = line.style_dashed sessionLineWidth = 2 user_midline_color = color.new(color.orange, 0) middle_line_style = line.style_solid Width = 1 // 替换成你实际的时段和价格计算逻辑 LineFromDate = timestamp("GMT+8", year, month, dayofmonth, 9, 0, 0) LineToDate = timestamp("GMT+8", year, month, dayofmonth, 16, 0, 0) rth_low = ta.lowest(low, 7) // 示例:取最近7根K线的最低价 rth_high = ta.highest(high, 7) // 示例:取最近7根K线的最高价 rth_mid = (rth_high + rth_low) / 2 // 计算中间价 // 用var声明持久化的线变量,保存当前显示的线对象 var line tl = na var line th = na var line tm = na if ShowAsiaRange // 开启开关时:先删旧线,再创建新线 line.delete(tl) tl = line.new(LineFromDate, rth_low, LineToDate, rth_low, xloc=xloc.bar_time, color=line_color, style=upperlower_line_style, width=sessionLineWidth) line.delete(th) th = line.new(LineFromDate, rth_high, LineToDate, rth_high, xloc=xloc.bar_time, color=line_color, style=upperlower_line_style, width=sessionLineWidth) line.delete(tm) tm = line.new(LineFromDate, rth_mid, LineToDate, rth_mid, xloc=xloc.bar_time, color=user_midline_color, style=middle_line_style, width=Width) else // 关闭开关时:删除所有线并重置变量 line.delete(tl) line.delete(th) line.delete(tm) tl := na th := na tm := na
关键说明
- 用
var定义线变量:让变量在脚本运行全程保持状态,不会每根K线都重新初始化,这样才能跟踪到之前创建的线并删除。 - 开关逻辑绑定:通过
if ShowAsiaRange判断,开启时更新线,关闭时清空所有线。 - 避免冗余线:每次创建新线前先删除旧线,防止图表上堆积大量无效线。
内容的提问来源于stack exchange,提问作者Crypto Gainz
相关产品推荐
相关产品推荐

