Pine Script绘制自定义日期竖线报错:series string不兼容timestamp
解决 Pine Script v5 中 timestamp() 函数的编译错误
问题原因
你遇到的错误是因为 string_date 是一个序列字符串(在每根K线执行时会变化),而 timestamp() 函数在序列执行上下文(即每根K线运行的代码)中要求传入常量字符串。原代码在每根K线中尝试读取数组元素并转换时间戳,导致变量成为序列类型,不符合函数要求。此外,原代码的循环逻辑错误,仅会处理数组的最后一个元素,而非所有日期。
修复方案
需要在脚本初始化阶段一次性处理所有日期,避免在每根K线中生成序列变量。以下是两种可行的修复方式:
方案一:直接初始化时间戳数组(推荐)
将日期字符串转换为时间戳的操作放在数组初始化阶段,数组中直接存储可用于绘制竖线的时间戳常量:
//@version=5 indicator('VertLine_Test', overlay=true) // 直接将日期字符串转换为时间戳存入数组 start_timestamps = array.from( timestamp("2022-12-26 15:15"), timestamp("2023-01-05 01:45"), timestamp("2023-01-10 16:30") ) // 绘制竖线的函数 drawVerticalLine(targetTime) => line.new( x1=targetTime, y1=low, x2=targetTime, y2=high, xloc=xloc.bar_time, extend=extend.both, color=color.new(#ea5e50, 10), style=line.style_solid, width=2 ) // 遍历时间戳数组,一次性绘制所有竖线 for i = 0 to array.size(start_timestamps) - 1 target_time = array.get(start_timestamps, i) drawVerticalLine(target_time)
方案二:全局循环处理字符串数组
如果需要保留字符串数组,可在全局作用域中使用循环(仅在脚本启动时执行一次),此时读取的字符串为常量,可直接传入 timestamp():
//@version=5 indicator('VertLine_Test', overlay=true) // 存储日期字符串的数组 start_dates = array.from( "2022-12-26 15:15", "2023-01-05 01:45", "2023-01-10 16:30" ) // 绘制竖线的函数 drawVerticalLine(targetTime) => line.new( x1=targetTime, y1=low, x2=targetTime, y2=high, xloc=xloc.bar_time, extend=extend.both, color=color.new(#ea5e50, 10), style=line.style_solid, width=2 ) // 全局循环:仅在脚本初始化时执行一次,处理所有日期 for i = 0 to array.size(start_dates) - 1 date_str = array.get(start_dates, i) target_time = timestamp(date_str) drawVerticalLine(target_time)
关键说明
- 全局作用域的
for循环仅在脚本启动时运行一次,不会在每根K线重复执行,因此读取的数组元素为常量类型,符合timestamp()的参数要求。 - 两种方案都会遍历数组中的所有日期,为每个日期绘制一条竖线,解决了原代码仅处理最后一个元素的问题。
内容的提问来源于stack exchange,提问作者Bruce Ecurb
相关产品推荐
相关产品推荐

