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

如何用Pine Script v5计算TradingView选中K线与最后K线收盘价的百分比差值

在TradingView用Pine Script v5计算选中K线与最后K线收盘价的百分比差值

直接上可运行的代码,实现左键选中K线后自动计算并显示该K线收盘价与当前最后一根K线收盘价的百分比差值,右键可重置选中状态:

//@version=5
indicator("选中K线与最后K线百分比差值", overlay=true)

// 持久化存储选中K线的收盘价
var float selected_close = na

// 左键点击选中K线时记录其收盘价
if mouse.isPressed(mouse.left_button)
    selected_close = close[bar_index - mouse.bar_index]

// 获取当前最后一根K线的收盘价
last_close = close

// 计算百分比差值:(最后收盘价 - 选中收盘价)/选中收盘价 * 100
percent_diff = na(selected_close) ? na : ((last_close - selected_close) / selected_close) * 100

// 在图表上显示计算结果,保留两位小数
if not na(selected_close)
    label.new(bar_index, high, str.tostring(percent_diff, "%.2f%"), 
              color=color.new(color.blue, 0), textcolor=color.white, 
              style=label.style_label_down, size=size.small)

// 右键点击重置选中状态
if mouse.isPressed(mouse.right_button)
    selected_close := na

关键逻辑说明

  • mouse.isPressed(mouse.left_button):捕捉左键点击事件,通过mouse.bar_index获取选中K线的索引,再用bar_index - mouse.bar_index定位到对应K线的收盘价。
  • var关键字:确保selected_close变量只初始化一次,不会随K线更新被重置,持久保存选中值。
  • 百分比差值公式:计算的是最后收盘价相对选中收盘价的涨跌幅,结果为正表示最后收盘价比选中时上涨,为负则表示下跌。
  • 右键重置:避免旧的选中数据一直显示,点击右键可清空选中状态。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 15:45:46