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

如何使用Pine Script在TradingView绘制买卖报价价差图表

TradingView 买卖价差绘制 Pine Script 实现方案

原代码问题说明

  • 错误将内置价格变量bid/ask直接作为symbol类型输入的默认值,symbol类型输入仅接收交易品种ID字符串,不支持传入价格数值
  • 未定义period变量,调用取数函数时会触发未定义变量报错
  • 用K线收盘价close取数,无法获取实时盘口的买一、卖一报价,计算结果不是真实买卖价差
  • 未做除零保护,极端行情下卖价为0时脚本会运行异常

正确实现代码

1. 单品种盘口买卖价差绘制(最常用场景)

直接调用Pine Script内置盘口变量即可,不需要额外配置品种参数,加载到对应图表就能显示该品种的实时买卖价差:

//@version=5
indicator("买卖价差监测", overlay=false, shorttitle="Bid-Ask Spread", precision=5)

// 参数配置
is_relative = input.bool(title="显示相对价差(百分比)", defval=true, tooltip="关闭则显示绝对价差=卖一价-买一价")
line_color = input.color(title="价差线颜色", defval=color.red)
line_width = input.int(title="线宽", defval=2, minval=1)

// 直接取内置盘口价
bid_price = bid
ask_price = ask

// 价差计算,加除零保护
absolute_spread = ask_price - bid_price
relative_spread = ask_price > 0 ? absolute_spread / ask_price * 100 : na

plot_value = is_relative ? relative_spread : absolute_spread
plot(plot_value, color=line_color, linewidth=line_width, title="价差")
hline(0, color=color.gray, linestyle=hline.style_dotted)

2. 跨品种价差绘制

如果需要计算两个不同品种的价格差(比如期货跨月、跨品种套利价差),使用以下代码:

//@version=5
indicator("跨品种价差监测", overlay=false, shorttitle="Cross Spread", precision=5)

// 参数配置
long_sym = input.symbol(title="买侧品种", defval=syminfo.tickerid)
short_sym = input.symbol(title="卖侧品种", defval=syminfo.tickerid)
calc_tf = input.timeframe(title="计算周期", defval=timeframe.period)
is_relative = input.bool(title="显示相对价差(百分比)", defval=true)
line_color = input.color(title="价差线颜色", defval=color.red)

// 取对应品种周期的价格
long_price = request.security(long_sym, calc_tf, close)
short_price = request.security(short_sym, calc_tf, close)

// 价差计算
absolute_spread = short_price - long_price
relative_spread = short_price > 0 ? absolute_spread / short_price * 100 : na

plot(is_relative ? relative_spread : absolute_spread, color=line_color, linewidth=2)

关键说明

  • bid和ask是Pine Script内置全局变量,直接调用即可获取当前图表品种的实时买一、卖一盘口价,不需要额外定义或通过取数函数获取
  • input.symbol类型输入仅接受品种ID字符串(如SSE:600000、BINANCE:BTCUSDT),不能传入价格类数值
  • Pine Script v5版本中旧版security()函数已更新为request.security(),旧语法虽兼容但不推荐长期使用
  • 所有涉及除法的价差计算必须加除零判断,避免极端行情下脚本运行崩溃
  • 回测模式下bid/ask会基于K线数据模拟填充,实盘运行时取交易所实时推送的盘口数据

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.20 16:15:50