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

PineScript中基于input.time选中K线的左右K线标注问题求助

解决Pine Script中选中K线及相邻K线添加标签的问题

问题说明

需要实现两个功能:

  • 通过input.time(confirm=true)选择图表上的一根K线
  • 为选中K线及其左、右相邻K线添加标签

原代码仅选中K线的标签显示正常,左右相邻K线的标签位置完全错误,核心问题是错误使用bar_index[start_time]来转换时间到bar索引——Pine Script中bar_index[N]表示回溯N根K线的bar索引,而非根据时间查找对应索引。

修正方案

方法一:用变量存储选中K线的bar索引

通过var变量记录选中时间对应的bar索引,再基于该索引计算左右相邻K线的回溯步数,获取对应时间和价格数据:

//@version=5
indicator("选中K线及相邻标签", overlay = true)
start_time = input.time(timestamp("20 Jan 2021"), "选择K线", confirm=true)

// 存储选中K线的bar索引,var确保仅初始化一次
var int selected_bar_idx = na
// 当K线时间与选中时间匹配时,记录当前bar索引
if time == start_time
    selected_bar_idx := bar_index

// 仅在选中索引有效时创建标签
if not na(selected_bar_idx)
    // 计算当前K线到选中K线的回溯步数
    back_steps = bar_index - selected_bar_idx
    
    // 选中K线的标签
    label.new(x=start_time, y=high[back_steps], text='选中K线', color=color.white, xloc=xloc.bar_time, yloc=yloc.abovebar)
    
    // 左侧相邻K线:索引为selected_bar_idx-1,计算对应回溯步数
    left_back_steps = bar_index - (selected_bar_idx - 1)
    label.new(x=time[left_back_steps], y=high[left_back_steps], text='左侧K线', color=color.white, xloc=xloc.bar_time, yloc=yloc.abovebar)
    
    // 右侧相邻K线:索引为selected_bar_idx+1,计算对应回溯步数
    right_back_steps = bar_index - (selected_bar_idx + 1)
    label.new(x=time[right_back_steps], y=high[right_back_steps], text='右侧K线', color=color.white, xloc=xloc.bar_time, yloc=yloc.abovebar)

方法二:用ta.valuewhen直接获取对应数据

利用ta.valuewhen函数直接提取满足条件的K线数据,代码更简洁直观:

//@version=5
indicator("选中K线及相邻标签", overlay = true)
start_time = input.time(timestamp("20 Jan 2021"), "选择K线", confirm=true)

// 获取选中时间对应的bar索引
selected_bar_idx = ta.valuewhen(time == start_time, bar_index, 0)

// 仅在选中索引有效时创建标签
if not na(selected_bar_idx)
    // 选中K线的标签
    label.new(x=start_time, y=ta.valuewhen(time == start_time, high, 0), text='选中K线', color=color.white, xloc=xloc.bar_time, yloc=yloc.abovebar)
    
    // 左侧相邻K线:提取bar索引为selected_bar_idx-1的时间和最高价
    left_bar_time = ta.valuewhen(bar_index == selected_bar_idx - 1, time, 0)
    left_bar_high = ta.valuewhen(bar_index == selected_bar_idx - 1, high, 0)
    label.new(x=left_bar_time, y=left_bar_high, text='左侧K线', color=color.white, xloc=xloc.bar_time, yloc=yloc.abovebar)
    
    // 右侧相邻K线:提取bar索引为selected_bar_idx+1的时间和最高价
    right_bar_time = ta.valuewhen(bar_index == selected_bar_idx + 1, time, 0)
    right_bar_high = ta.valuewhen(bar_index == selected_bar_idx + 1, high, 0)
    label.new(x=right_bar_time, y=right_bar_high, text='右侧K线', color=color.white, xloc=xloc.bar_time, yloc=yloc.abovebar)

代码说明

  • 两种方法均先正确获取选中时间对应的bar索引,避免原代码中错误的下标用法
  • 基于正确的bar索引,通过回溯步数或ta.valuewhen函数获取相邻K线的时间和价格数据,确保标签位置准确

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 14:05:16