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

TradingView PineScript:实现多标的首根K线基准百分比对比图表

PineScript 修改方案:多标的基准百分比走势同窗绘制

核心逻辑

将每个标的的收盘价,以图表首根K线的收盘价为基准,计算相对百分比变化(公式:(当前收盘价 / 首根收盘价 - 1) * 100),同时设置Y轴为百分比格式展示。

完整代码

//@version=5
indicator("多标的基准百分比走势", overlay=false, shorttitle="Benchmark % Change", precision=2)

// 定义需要对比的标的列表
symbols = ["NIFTY", "BANKNIFTY", "CNXFINANCE", "CNXPHARMA"]

// 初始化首根K线收盘价作为基准(仅执行一次)
var float nifty_base = request.security(symbols[0], timeframe.period, close, barmerge.gaps_on, barmerge.lookahead_on)[0]
var float banknifty_base = request.security(symbols[1], timeframe.period, close, barmerge.gaps_on, barmerge.lookahead_on)[0]
var float cnxfinance_base = request.security(symbols[2], timeframe.period, close, barmerge.gaps_on, barmerge.lookahead_on)[0]
var float cnxpharma_base = request.security(symbols[3], timeframe.period, close, barmerge.gaps_on, barmerge.lookahead_on)[0]

// 获取当前各标的实时收盘价
nifty_close = request.security(symbols[0], timeframe.period, close)
banknifty_close = request.security(symbols[1], timeframe.period, close)
cnxfinance_close = request.security(symbols[2], timeframe.period, close)
cnxpharma_close = request.security(symbols[3], timeframe.period, close)

// 计算相对基准的百分比变化
nifty_pct = (nifty_close / nifty_base - 1) * 100
banknifty_pct = (banknifty_close / banknifty_base - 1) * 100
cnxfinance_pct = (cnxfinance_close / cnxfinance_base - 1) * 100
cnxpharma_pct = (cnxpharma_close / cnxpharma_base - 1) * 100

// 绘制各标的百分比走势,区分颜色
plot(nifty_pct, title="NIFTY", color=color.blue, linewidth=2)
plot(banknifty_pct, title="BANKNIFTY", color=color.red, linewidth=2)
plot(cnxfinance_pct, title="CNXFINANCE", color=color.green, linewidth=2)
plot(cnxpharma_pct, title="CNXPHARMA", color=color.orange, linewidth=2)

// 设置Y轴为百分比格式
yaxis(title="百分比变化", tickformat="%.2f%%")

关键细节说明

  • var关键字:确保基准值仅在第一根K线时获取,后续不会随K线更新,保证所有标的都以同一时间点为对比基准
  • request.security:跨标的获取数据,参数barmerge.gaps_on和barmerge.lookahead_on确保不同标的数据对齐,避免时间差导致的偏差
  • tickformat="%.2f%%":强制Y轴刻度显示为带两位小数的百分比格式,符合需求的可视化效果
  • precision=2:控制指标数值的显示精度,让百分比数据更清晰

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 22:31:11