Pine Script绘制指定时段蜡烛矩形报错:end of line without line continuation
解决Pine Script中绘制指定时段矩形的问题
问题描述
需求:在15:00-18:00 GMT+2区间的所有蜡烛周围绘制矩形,矩形顶部为该区间的最高点,底部为该区间的最低点。
尝试的代码:
//@version=5 indicator('My Indicator', overlay = true) // Define the start and end times for the rectangle startTime = timestamp(year, month, day, 10, 0, 0) - time('50D') endTime = timestamp(year, month, day, 11, 0, 0) - time('50D') // Use a for loop to iterate over the days in the data for i = 0 to 49 // Get the high and low values for the rectangle highValue = highest(high[range(startTime, endTime)]) lowValue = lowest(low[range(startTime, endTime)]) // Draw the top and bottom lines of the rectangle hline(highValue, startTime, endTime, color=color.orange) hline(lowValue, startTime, endTime, color=color.orange) // Draw the left and right lines of the rectangle vline(startTime, highValue, lowValue, color=color.orange) vline(endTime, highValue, lowValue, color=color.orange) // Increment the start and end times to the next day startTime := startTime + time('1D')
编译错误:
10:11:36 PM — Compilation error. Line 12: Mismatched input 'highValue' expecting 'end of line without line continuation'
解决方案
原代码核心问题
- 函数参数错误:
hline和vline是绘制贯穿整个图表的水平/垂直线,无法指定时间或价格范围来绘制局部线段,不能用来组合成矩形。 - 范围索引用法错误:
high[range(startTime, endTime)]不是Pine Script的合法语法,highest函数需要通过条件筛选或长度参数来计算区间极值。 - 循环与时间处理逻辑错误:手动循环处理历史日期的方式不符合Pine Script的运行逻辑,应该基于当前蜡烛的时间条件来实时计算和绘制。
正确实现代码
//@version=5 indicator("GMT+2 15-18时段矩形", overlay=true, timezone="Etc/GMT-2") // 定义时段条件:15:00到18:00 GMT+2 inSession = hour >= 15 and hour < 18 // 存储每日时段的关键数据,用var声明只初始化一次 var float dailyHigh = na var float dailyLow = na var int sessionStart = na // 仅在日内图表运行(可选,根据你的时间框架调整) if timeframe.isintraday() // 当进入时段时,初始化当日数据 if inSession and not inSession[1] sessionStart := time dailyHigh := high dailyLow := low // 在时段内持续更新高低点 if inSession dailyHigh := math.max(dailyHigh, high) dailyLow := math.min(dailyLow, low) // 当离开时段时,绘制矩形并重置变量 if not inSession and inSession[1] // 绘制矩形:左上角(开始时间+高点),右下角(当前时间+低点) box.new(left=sessionStart, top=dailyHigh, right=time, bottom=dailyLow, color=color.orange, border_color=color.orange, border_width=1, bgcolor=color.new(color.orange, 90)) // 重置变量,准备下一天的时段 dailyHigh := na dailyLow := na sessionStart := na
代码关键说明
- 时区设置:通过
timezone="Etc/GMT-2"指定GMT+2时区,确保时间判断准确。 - 时段判断:
inSession条件筛选出15:00到18:00之间的蜡烛。 - 变量持久化:用
var声明的变量会保留跨bar的数据,用来存储当日时段的开始时间、高点和低点。 - 矩形绘制:使用
box.new函数直接绘制矩形,参数包含左右时间边界和上下价格边界,同时支持设置边框和背景色透明度。 - 状态切换处理:通过
inSession和inSession[1]的对比,判断进入/离开时段的节点,分别初始化数据和绘制矩形。
内容的提问来源于stack exchange,提问作者isit_reallyme
相关产品推荐
相关产品推荐

