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

Pine Script绘制时序值:当前方案是否推荐?有无更优写法?

关于Pine Script按时间绘制数值的实现优化问题

我希望随时间绘制一些数值,以下是一段示例Pine Script代码:

//@version=5
indicator("test plot values with dates")

items() =>
       time >= timestamp("2024-08-30") ? 0.2 : 
       time >= timestamp("2024-07-26") ? 0.2 : 
       time >= timestamp("2024-06-28") ? 0.1 : 
       time >= timestamp("2024-05-31") ? 0.2 : 
       time >= timestamp("2024-04-26") ? 0.3 : 
       na
plot(items())

运行上述代码可得到对应指标图表。现咨询:该实现方案是否为推荐做法?有无更符合Pine Script风格的实现方式?


原方案的问题

原代码用嵌套三元运算符实现逻辑,虽然能正常运行,但可读性极差,一旦要添加、修改时间点或对应数值,很容易写错逻辑或漏改内容,完全不是Pine Script的推荐写法。

更符合Pine Script风格的实现方式

方式1:数组管理时间-数值对(推荐,适合多时间点场景)

把时间戳和对应数值分别存在数组里,用二分查找快速匹配当前时间的数值,后续维护只需要修改数组内容,逻辑清晰:

//@version=5
indicator("Plot Values with Dates (Array Version)")

// 按从新到旧的顺序定义时间戳数组
timeStamps = array.new_int([
    timestamp("2024-08-30"),
    timestamp("2024-07-26"),
    timestamp("2024-06-28"),
    timestamp("2024-05-31"),
    timestamp("2024-04-26")
])

// 对应数值数组,顺序和时间戳数组严格一致
values = array.new_float([0.2, 0.2, 0.1, 0.2, 0.3])

// 获取当前K线对应的数值
getCurrentValue() =>
    // 二分查找找到第一个大于等于当前时间的索引
    idx = array.bsearch(timeStamps, time, order.descending)
    // 找到则返回对应值,否则返回na
    idx != -1 ? array.get(values, idx) : na

plot(getCurrentValue(), title="Value Over Time")

方式2:switch语句(适合时间点较少的简单场景)

如果时间点不多,用switch替代嵌套三元,可读性会好很多:

//@version=5
indicator("Plot Values with Dates (Switch Version)")

getCurrentValue() =>
    switch
        time >= timestamp("2024-08-30") => 0.2
        time >= timestamp("2024-07-26") => 0.2
        time >= timestamp("2024-06-28") => 0.1
        time >= timestamp("2024-05-31") => 0.2
        time >= timestamp("2024-04-26") => 0.3
        // 默认返回na
        => na

plot(getCurrentValue(), title="Value Over Time")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 22:58:27