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

如何用Pine Script绘制当前月高点水平射线并添加CMH文本?

Pine Script v5 实现带"CMH"标记的当前月度高点水平射线

你的代码存在两个核心问题:一是绘制射线的触发条件过于严格,只会在新月份的最后一根K线才生成射线;二是缺少在射线右侧添加文本标记的逻辑。以下是修正后的完整代码,同时实现了实时更新月度高点射线和右侧"CMH"文本的功能:

//@version=5
indicator(title="Current Month High with CMH Label", overlay=true)

// 初始化月度高点相关变量和绘图对象
var float currentMonthHigh = na
var int currentMonthBarIndex = na
var line monthHighLine = na
var label cmhLabel = na

// 更新当前月度高点和对应K线索引
currentMonth = month(time)
prevMonth = month(time[1])

if currentMonth != prevMonth
    currentMonthHigh := high
    currentMonthBarIndex := bar_index
else
    if high > currentMonthHigh
        currentMonthHigh := high
        currentMonthBarIndex := bar_index

// 更新月度高点射线:仅在当前月份更新,避免重复创建
if barstate.islast
    // 移除旧射线(如果存在)
    if not na(monthHighLine)
        line.delete(monthHighLine)
    // 创建新的水平射线,从高点出现的K线延伸至右侧
    monthHighLine := line.new(currentMonthBarIndex, currentMonthHigh, last_bar_index, currentMonthHigh, 
         color=color.aqua, width=1, extend=extend.right)
    
    // 更新"CMH"标签:放在屏幕最右侧的高点位置
    if not na(cmhLabel)
        label.delete(cmhLabel)
    cmhLabel := label.new(last_bar_index, currentMonthHigh, "CMH", 
         color=color.aqua, textcolor=color.white, style=label.style_label_left, size=size.small)

关键逻辑说明:

  • 使用var声明line和label对象,避免每个K线都重复创建绘图元素,提升性能
  • 在barstate.islast(最后一根K线)时更新射线和标签,确保只在图表右侧显示最新状态
  • 射线从月度高点出现的K线开始绘制,延伸至右侧;标签固定在屏幕最右侧的高点价格位置,样式设为左对齐避免遮挡
  • 每次更新月度高点时,同步更新射线的起点和标签的位置

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 02:07:07