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

Pine Script跳空指标优化:如何排除交易日首2根K线?

解决Pine Script跳空指标排除交易日首两根K线的问题

要避免交易日首2根K线调用bar[2]获取昨日数据,你可以通过统计会话内K线序号或直接判断当前是否为前两根K线来实现过滤,以下是两种可行方案:

方案一:统计会话内K线序号过滤

通过计算当前K线与会话首根K线的索引差,直接排除前2根K线:

//@version=5
indicator("gaps test", "Gaps test", overlay = true, max_boxes_count = 500)

// 获取当前会话首根K线的bar_index
firstBarIdx = ta.valuewhen(session.isfirstbar_regular, bar_index, 0)
// 计算当前是会话内的第几根K线(从1开始计数)
sessionBarNum = bar_index - firstBarIdx + 1

blGap = low > high[2]
brGap = high < low[2]

// 仅在会话内第3根及以后的K线执行逻辑
if blGap and sessionBarNum > 2
    gapBox = box.new(left = bar_index[2],
     top = high[2], 
     right = bar_index, 
     bottom = low,
     border_color = color.lime, 
     border_width = 2, 
     border_style = line.style_dotted, 
     bgcolor = na)

if brGap and sessionBarNum > 2
    gapBox = box.new(left = bar_index[2],
     top = low[2], 
     right = bar_index, 
     bottom = high,
     border_color = color.red, 
     border_width = 2, 
     border_style = line.style_dotted, 
     bgcolor = na)

方案二:通过偏移判断过滤第二根K线

利用session.isfirstbar_regular的偏移值,同时排除首根和第二根K线:

//@version=5
indicator("gaps test", "Gaps test", overlay = true, max_boxes_count = 500)

blGap = low > high[2]
brGap = high < low[2]

// 排除会话首根K线,同时排除会话第二根K线(此时session.isfirstbar_regular[1]为true)
isValidBar = not session.isfirstbar_regular and not session.isfirstbar_regular[1]

if blGap and isValidBar
    gapBox = box.new(left = bar_index[2],
     top = high[2], 
     right = bar_index, 
     bottom = low,
     border_color = color.lime, 
     border_width = 2, 
     border_style = line.style_dotted, 
     bgcolor = na)

if brGap and isValidBar
    gapBox = box.new(left = bar_index[2],
     top = low[2], 
     right = bar_index, 
     bottom = high,
     border_color = color.red, 
     border_width = 2, 
     border_style = line.style_dotted, 
     bgcolor = na)

方案说明

  • 方案一逻辑直观,适合需要基于会话内K线序号做更多扩展判断的场景;
  • 方案二更简洁,直接通过偏移判断当前是否为前两根K线,代码量更少。

两种方案都能确保bar[2]获取的是当前会话内的K线数据,不会取到昨日会话的内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 20:27:47