PineScript技术咨询:绘制时间区间矩形及竖线自适应问题
PineScript 绘制时间区间矩形与竖线自适应解决方案
一、绘制带时间区间的矩形
PineScript 中推荐使用 box.new() 函数绘制指定时间区间的矩形,该函数不依赖价格轴,能精准匹配时间范围。以下是两种常见场景的实现代码:
1. 匹配区间内真实高低价的矩形
//@version=5 indicator("时间区间矩形", overlay=true) // 定义时间区间的起止时间戳(GMT-4时区) startTime = timestamp("GMT-4", 2022, 6, 30, 9, 0) endTime = timestamp("GMT-4", 2022, 6, 30, 12, 0) // 跟踪区间内的最高/最低价 var float rectHigh = na var float rectLow = na var box myBox = na // 进入区间时初始化矩形 if time == startTime rectHigh := high rectLow := low myBox := box.new(left=bar_index, top=rectHigh, right=bar_index, bottom=rectLow, color=color.new(color.blue, 80), border_color=color.blue) // 区间内实时更新矩形边界 else if time > startTime and time <= endTime rectHigh := math.max(rectHigh, high) rectLow := math.min(rectLow, low) box.set_right(myBox, bar_index) box.set_top(myBox, rectHigh) box.set_bottom(myBox, rectLow)
2. 覆盖当前图表可视范围的矩形
如果需要矩形填满当前价格轴可视区域,直接调用图表内置的高低价参数:
//@version=5 indicator("全屏时间矩形", overlay=true) startTime = timestamp("GMT-4", 2022, 6, 30, 9, 0) endTime = timestamp("GMT-4", 2022, 6, 30, 12, 0) // 到达起始时间时一次性绘制矩形 if time == startTime box.new( left=bar_index, top=chart_info.highest_price, right=bar_index + ta.barssince(time == endTime), bottom=chart_info.lowest_price, color=color.new(color.green, 70), border_width=1 )
二、解决竖线压缩价格轴的问题
你当前用 plot.style_histogram 绘制竖线时,硬编码的固定值 5000 会强制拉伸价格轴,导致图表变形。改用 line.new() 函数可彻底解决这个问题——该函数绘制的竖线独立于价格轴,不会影响轴的缩放:
基础自适应竖线
//@version=5 indicator("自适应竖线", overlay=true) targetTime = timestamp("GMT-4", 2022, 6, 30, 11, 6) // 到达目标时间时绘制贯穿当前可视范围的竖线 if time == targetTime line.new( x1=bar_index, y1=chart_info.highest_price, x2=bar_index, y2=chart_info.lowest_price, color=color.red, width=1 )
跟随图表滚动的自适应竖线
如果需要竖线在图表缩放、滚动时自动适配可视范围,可添加实时更新逻辑:
//@version=5 indicator("滚动自适应竖线", overlay=true) targetTime = timestamp("GMT-4", 2022, 6, 30, 11, 6) var line myLine = na // 初始化竖线 if time == targetTime myLine := line.new(x1=bar_index, y1=chart_info.highest_price, x2=bar_index, y2=chart_info.lowest_price, color=color.red, width=1) // 每次图表刷新时更新竖线的上下端点 if barstate.islast and not na(myLine) line.set_y1(myLine, chart_info.highest_price) line.set_y2(myLine, chart_info.lowest_price)
内容的提问来源于stack exchange,提问作者Arcana
相关产品推荐
相关产品推荐

