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

如何在Pine Script中回溯历史K线检测形态并获取其Bar Index?

Pine Script 实时检测当日历史K线形态并获取Bar Index

以下是针对需求的两种实现方案,适合刚接触Pine Script的用户,代码逻辑清晰且适配实盘场景:


方案1:实时回溯当日所有K线检测

适合需要每根实时K线更新时,重新扫描当日全部K线的场景:

//@version=5
indicator("当日特定K线检测", overlay=true)

// 1. 定义点数计算逻辑(根据品种调整)
// 示例:外汇品种1点=0.0001,股票/期货按最小变动单位修改
pointValue = 0.0001
barPoint = (high - low) / pointValue

// 2. 判断当前K线是否属于当日
isToday(timeVal) =>
    timeVal >= timestamp(year, month, dayofmonth, 0, 0) and timeVal < timestamp(year, month, dayofmonth + 1, 0, 0)

// 3. 存储符合条件的Bar Index数组(var关键字保留跨K线数据)
var int[] targetBarIndexes = array.new_int()

// 4. 实时K线更新时执行检测
if barstate.islast
    array.clear(targetBarIndexes)
    // 回溯当日所有K线
    for i = 0 to bar_index
        if not isToday(time[i])
            continue
        // 检测K线点数是否等于10(可改为>=或<=)
        if barPoint[i] == 10
            array.push(targetBarIndexes, i)

// 5. 可视化标记与结果输出
if array.size(targetBarIndexes) > 0
    // 在符合条件的K线上标记Bar Index
    for idx in targetBarIndexes
        label.new(idx, high[idx], str.tostring(idx), color=color.red, textcolor=color.white, size=size.small)
    // 在最新K线旁显示所有符合条件的Bar Index
    label.new(bar_index, high, "目标Bar Index: " + str.tostring(array.join(targetBarIndexes, ", ")), color=color.green, textcolor=color.white, style=label.style_label_down)

方案2:逐K线增量检测(效率更高)

适合实盘场景,无需重复回溯,每根K线闭合时自动检测并记录:

//@version=5
indicator("当日特定K线检测(优化版)", overlay=true)

// 1. 定义点数计算逻辑
pointValue = 0.0001
barPoint = (high - low) / pointValue

// 2. 当日时段判断
isToday = time >= timestamp(year, month, dayofmonth, 0, 0) and time < timestamp(year, month, dayofmonth + 1, 0, 0)

// 3. 初始化存储数组(当日开盘时清空)
var int[] targetBarIndexes = array.new_int()
if time == timestamp(year, month, dayofmonth, 0, 0)
    array.clear(targetBarIndexes)

// 4. 每根K线闭合时检测
if barstate.isconfirmed and isToday
    if barPoint == 10
        array.push(targetBarIndexes, bar_index)

// 5. 可视化输出
if array.size(targetBarIndexes) > 0
    for idx in targetBarIndexes
        label.new(idx, high[idx], str.tostring(idx), color=color.blue, textcolor=color.white, size=size.small)
    label.new(bar_index, low, "已找到" + str.tostring(array.size(targetBarIndexes)) + "根目标K线,Index: " + str.tostring(array.join(targetBarIndexes, ", ")), color=color.orange, textcolor=color.white, style=label.style_label_up)

关键说明

  • 点数计算:pointValue需根据交易品种修改,比如期货品种可能设为syminfo.mintick * 10(10个最小变动单位为1点)。
  • Bar Index:bar_index是Pine Script内置的K线索引值,每根K线唯一对应。
  • 实时触发:barstate.islast确保仅在最新实时K线更新时执行检测,barstate.isconfirmed仅在K线完全闭合时触发。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 13:27:15