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

TradingView高低柱K线当前价格短划线绘制问题求助

仅在当前K线显示短划线式当前价格线解决方案

我使用高低柱K线(High Low bars),希望在图表中绘制一条短划线展示当前价格,不想用程序默认的贯穿全图价格线。自己编写的Pine Script代码虽接近需求,但会标记过往收盘价,这并非预期。若仅能通过将过往标记设为透明解决,我也可接受,恳请提供解决方案。

原代码:

//@version=5
indicator("Current Price Line", overlay=true)

// Get the current price
currentPrice = close

// Check if the current bar is the last bar in the chart
isLastBar = barstate.islast

// Draw the current price as a short red line only on the current bar
line.new(x1 = isLastBar ? bar_index : na, y1 = isLastBar ? currentPrice : na, x2 = isLastBar ? bar_index + 1 : na, y2 = isLastBar ? currentPrice : na, color = color.red, width = 2)

最优解决方案:仅在最后K线生成线条

原代码的问题在于会在每根K线都尝试创建线条(即使参数为na,仍可能产生无效对象残留),以下代码通过控制仅在最后一根K线创建并维护线条,彻底避免过往标记:

//@version=5
indicator("当前价格短划线", overlay=true)

// 用var定义线条变量,确保只初始化一次
var line priceLine = na

if barstate.islast
    currentPrice = close
    // 删除旧线条,避免残留
    if not na(priceLine)
        line.delete(priceLine)
    // 创建短划线,样式设为短划线,覆盖当前K线右侧一段区域
    priceLine = line.new(bar_index, currentPrice, bar_index + 1, currentPrice, 
                        color=color.red, width=2, style=line.style_dashed)

核心改进点:

  • 用var关键字存储线条对象,避免重复创建
  • 仅在barstate.islast为真时执行操作,完全跳过过往K线
  • 每次更新前删除旧线条,确保界面只保留最新的价格短划线

备选方案:隐藏过往标记

如果需要保留原有代码逻辑,仅隐藏非最后K线的标记,可以通过条件设置透明色实现:

//@version=5
indicator("当前价格短划线", overlay=true)

currentPrice = close
isLastBar = barstate.islast

// 非最后K线时用全透明色,最后K线显示红色短划线
lineColor = isLastBar ? color.red : color.new(color.red, 100)
line.new(x1=bar_index, y1=currentPrice, x2=bar_index+1, y2=currentPrice, 
         color=lineColor, width=2, style=line.style_dashed)

逻辑说明:

  • color.new(color.red, 100)生成完全透明的颜色,非最后K线的线条会被隐藏
  • 仅最后一根K线的线条会以红色短划线形式显示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 00:53:11