如何在TradingView PineScript中显示最后一根收K线的指标值?
在Pine Script中显示最后一根已收K线的移动平均线数值
问题分析
你的代码存在几个关键错误,导致数值始终为0:
previousMA被定义为input.int类型,这是用户可配置的参数变量,不能在脚本运行时动态赋值修改,必须用var声明一个持久化变量来存储数值。- 代码中出现未定义的变量
pMA,没有指明要保存的均线数值来源。 - 逻辑判断的顺序和变量赋值方式不符合Pine Script的语法规则,
barstate.isconfirmed本身就代表当前K线已收盘,无需嵌套在barstate.islast判断中。
修正后的代码
下面是修复后的版本,能够正确捕获最后一根已收K线的均线值并通过plotchar显示:
//@version=5 indicator(title="Moving Average", overlay=true, timeframe="", timeframe_gaps=true) len = input.int(9, minval=1, title="Length") src = input(close, title="Source") offset = input.int(title="Offset", defval=0, minval=-500, maxval=500) out = ta.sma(src, len) plot(out, color=color.blue, title="MA", offset=offset) ma(source, length, type) => switch type "SMA" => ta.sma(source, length) "EMA" => ta.ema(source, length) "SMMA (RMA)" => ta.rma(source, length) "WMA" => ta.wma(source, length) "VWMA" => ta.vwma(source, length) typeMA = input.string(title = "Method", defval = "SMA", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group="Smoothing") smoothingLength = input.int(title = "Length", defval = 5, minval = 1, maxval = 100, group="Smoothing") smoothingLine = ma(out, smoothingLength, typeMA) // 用var声明持久化变量存储已收盘的均线值 var float confirmed_ma = na // 当K线收盘时,更新数值 if barstate.isconfirmed confirmed_ma := out // 绘制最后一次确认的均线值 plotchar(confirmed_ma, "Last Confirmed MA", "", location.top, size=size.small) plot(smoothingLine, title="Smoothing Line", color=#f37f20, offset=offset, display=display.none)
其他实现方法
- 直接在数据窗口显示:不需要
plotchar,用var变量存储后,脚本会自动在数据窗口展示该变量的最新值:
var float last_confirmed_ma = na if barstate.isconfirmed last_confirmed_ma := out
- 用Label标注在图表上:如果需要更直观的文本显示,可使用
label函数:
var label ma_label = na if barstate.islast ma_label := label.new(bar_index, high, str.tostring(confirmed_ma, "#.####"), color=color.orange) label.set_xy(ma_label, bar_index, high)
内容的提问来源于stack exchange,提问作者santanderboogieman
相关产品推荐
相关产品推荐

