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

Pinescript获取两个日期间固定交易日K线数量(全K线周期生效)

解决方案

问题根因

你的代码逻辑中,起止时间对应的K线索引(firstTime、secondTime)只有当脚本执行到对应时间的K线时才会被赋值,历史K线上这两个值未完成计算,因此barDelta会随着K线推进逐步变化,无法全局固定。你测试代码里用的ta.cum是逐K累计函数,天然就会逐根递增,当然不符合固定值需求。

修复后的完整代码

//@version=5
indicator('Relative Strength', shorttitle='ARS', max_bars_back=1000, overlay=true)

comparativeTickerId = input.symbol('NSE:NIFTY', title='Comparative Symbol')

startTime = input.time(timestamp("18 May 2021 00:00"), "Start Time")      
endTime   = input.time(timestamp("20 Nov 2021 00:00"), "End Time")  

_barForTime(_t) =>
    var int _bar = na 
    if time_close[1] <= _t and time >= _t
        _bar := bar_index
    _bar
    
firstTime   = _barForTime(startTime)
secondTime  = _barForTime(endTime)

// 核心修改:用var声明固定差值,计算完成后不再变化
var int barDelta = na
if not na(firstTime) and not na(secondTime) and na(barDelta)
    barDelta := secondTime - firstTime

// 兼容时间不在K线范围内的场景,避免报错
lenght = na(barDelta) ? 100 : barDelta // 默认值可自行修改

// 检查barDelta值
plot(lenght, title='Days', color=color.blue,  linewidth = 3, style=plot.style_line)
// 修复标签重复生成问题,仅生成1个标签实时更新
var label countLabel = label.new(bar_index, high, style=label.style_none, text='Bar Count\n' + str.tostring(lenght) + '\n')
label.set_xy(countLabel, bar_index, high)
label.set_text(countLabel, 'Bar Count\n' + str.tostring(lenght) + '\n')

baseSymbol = request.security(syminfo.tickerid, timeframe.period, close)
comparativeSymbol = request.security(comparativeTickerId, timeframe.period, close)
hline(0, color=color.black, linestyle=hline.style_solid)
// 增加空值判断避免索引错误
res = na(lenght) ? na : baseSymbol / baseSymbol[lenght-1] / (comparativeSymbol / comparativeSymbol[lenght-1]) - 1
plot(res, title='ARS', color=res >= 0.0 ? color.lime : color.orange,  linewidth = 2, style=plot.style_area)

关键修改说明

  • 用var关键字声明barDelta,只有当两个时间点的K线索引都计算完成后才赋值一次,之后不再修改,确保全K线范围都是固定常量
  • 增加空值判断逻辑,避免起止时间不在当前加载K线范围内时脚本报错
  • 修复原逻辑中标签每根K线重复生成的问题,降低性能消耗

如果你需要用测试代码的逻辑计算从指定日期到最新K线的固定交易日数,可以使用以下代码:

i_fromYear = input.int(2021, 'From Year', minval=1900)
i_fromMonth = input.int(5, 'From Month', minval=1, maxval=12)
i_fromDay = input.int(18, 'From Day', minval=1, maxval=31)
fromDate = timestamp(i_fromYear, i_fromMonth, i_fromDay, 00, 00)
total = ta.cum(time >= fromDate ? 1 : 0)
// 取最新的累计值作为固定常量
var int fixedTotal = na
if barstate.islast
    fixedTotal := total
// 输出固定值
plot(fixedTotal)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 15:54:09