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

Pine Script v5:如何记录实时K线中指标触发的时间与价格?

解决Pine Script实时K线指标触发时间与价格的存储展示问题

可以通过var变量实现需求。var声明的变量仅初始化一次,不会随新K线启动自动重置,能持久保存触发时刻的原始价格与时间,即使K线收盘后也不会被覆盖。

实现思路与代码示例

  1. 定义指标触发条件
  2. 用var变量存储触发时的价格和时间
  3. 触发条件满足时赋值变量,并在图表上标记展示
//@version=5
strategy("Test", process_orders_on_close=true, calc_on_every_tick=true, max_bars_back = 4000, overlay=true, max_lines_count=500, max_labels_count=500)

// 示例:RSI上穿50作为触发条件
rsi_val = ta.rsi(close, 14)
trigger_condition = ta.crossover(rsi_val, 50)

// 初始化var变量,用于存储触发时的价格与时间
var float trigger_price = na
var int trigger_time = na

// 触发条件成立时,存储当前tick的价格与时间(仅首次触发赋值,避免同一K线多次触发覆盖)
if (trigger_condition and na(trigger_price))
    trigger_price := close
    trigger_time := time

// 在图表上绘制触发标签,显示价格与时间
if (not na(trigger_time))
    label.new(bar_index, trigger_price, 
              str.tostring(trigger_price) + "\n" + str.tostring(time, "yyyy-MM-dd HH:mm"),
              color=color.green, textcolor=color.white, style=label.style_label_down)

// 可选:新K线启动时重置变量,确保每个K线仅记录一次触发
if (ta.barstate.isnew)
    trigger_price := na
    trigger_time := na

关键说明

  • calc_on_every_tick=true确保脚本实时计算每一笔tick,能精准捕捉触发时刻
  • var变量的持久化特性:触发时存入的价格与时间不会随K线收盘被覆盖,始终保留触发瞬间的原始值
  • 若无需限制单K线触发次数,可去掉na(trigger_price)的判断,或移除新K线重置的逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 21:25:55