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

如何在Pine Script中用模运算符在各时间框架特定K线打印对应数字

问题解决方法

你的代码核心问题是缺少条件判断,导致每根K线都会生成标签,且bar_index[30]的偏移设置也不符合需求。以下是修正后的代码,可实现各时间框架下,仅在当日K线计数为7或30的K线上显示对应数字:

//@version=5
indicator(title='candle count', overlay=true, max_labels_count=500)
text_color = input.color(color.blue, title="Text Color Input")

// 计算当日内的K线计数
var int numBars = 0
t = time('D')
if t != t[1]
    numBars := 1
else
    numBars += 1

// 定义需要显示的目标K线计数
target_nums = [7, 30]

// 仅当K线计数符合目标值时创建标签
if numBars in target_nums
    label.new(bar_index, high, str.tostring(numBars), textcolor=text_color, style=label.style_none, yloc=yloc.abovebar)

关键修正说明:

  • 用var声明numBars,避免脚本重新初始化时重置计数变量
  • 简化当日K线计数逻辑:日期切换时重置为1,否则自动递增
  • 添加if numBars in target_nums条件,仅在计数匹配目标值时生成标签
  • 将标签位置改为当前bar_index,并设置yloc.abovebar让文字显示在K线上方,避免遮挡K线主体

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 12:50:21