You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TradingView Pine Script大量事件竖线显示至未来的问题求助

原因分析
  • 硬编码数据解析溢出:直接在代码中硬编码大量经济事件时间字符串时,Pine Script编译器一次性处理超长列表可能触发内存临时溢出,导致部分时间字符串解析失败,返回默认的错误时间戳(恰好对应5月24日之后的未来时间)。
  • 循环性能瓶颈引发索引错位:若每次bar都遍历大量事件,会触发运行环境的性能限制,部分循环迭代被强制终止,后续事件因索引越界误取未初始化的默认时间值。
  • timestamp()批量调用异常:连续调用timestamp()解析大量时间字符串时,函数可能因负载过高返回na,若代码未过滤该值,最终会用默认未来时间绘制竖线。
修复方案

1. 改用数组存储并延迟初始化

避免硬编码超长列表,用数组分批次存储事件,仅在最后一根bar触发绘制,降低编译和运行负载:

//@version=5
indicator("经济事件竖线", overlay=true)

// 初始化事件数组,仅在最后一根bar加载数据
var eventTimes = array.new<string>()
if barstate.islast
    // 分批次添加事件,避免一次性写入过多数据
    array.push(eventTimes, "2024-03-10T08:30:00")
    array.push(eventTimes, "2024-03-15T09:00:00")
    // 继续添加其他事件...

// 遍历数组绘制竖线
if barstate.islast
    for timeStr in eventTimes
        // 解析时间戳并校验有效性
        eventTs = timestamp(syminfo.timezone, str.split(timeStr, "T")[0], str.split(timeStr, "T")[1])
        if not na(eventTs) and eventTs <= time
            line.new(x1=eventTs, y1=ta.lowest(low, 20)*0.98, x2=eventTs, y2=ta.highest(high, 20)*1.02, color=color.new(color.red, 0), width=1)

2. 增加时间戳有效性校验

对每个解析后的时间戳做非空和非未来校验,过滤无效值:

// 解析后立即校验
eventTs = timestamp(...)
if na(eventTs)
    // 跳过无效时间
    continue
if eventTs > time
    // 跳过未来事件
    continue
// 绘制竖线
line.new(...)

3. 按时间段拆分事件处理

将事件按月份/季度拆分到不同数组,分模块遍历,降低单次循环负载:

var q1Events = array.new<string>()
var q2Events = array.new<string>()

if barstate.islast
    // 第一季度事件
    array.push(q1Events, "2024-01-05T10:00:00")
    // 第二季度事件
    array.push(q2Events, "2024-04-12T08:30:00")

// 分别遍历不同时间段的事件
if barstate.islast
    for timeStr in q1Events
        // 绘制逻辑
    for timeStr in q2Events
        // 绘制逻辑

4. 预计算时间戳

提前将时间字符串转换为时间戳常量,避免运行时重复解析:

// 直接定义时间戳常量列表
var eventTsList = array.new<integer>()
if barstate.islast
    array.push(eventTsList, timestamp(syminfo.timezone, "2024-03-10", "08:30"))
    array.push(eventTsList, timestamp(syminfo.timezone, "2024-03-15", "09:00"))

// 遍历时间戳绘制
if barstate.islast
    for ts in eventTsList
        if ts <= time
            line.new(x1=ts, y1=low*0.99, x2=ts, y2=high*1.01, color=color.red)

内容的提问来源于stack exchange,提问作者Jeremiah Freeman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 08:50:00