Pinescript中dayofweek()函数日期识别异常,周五统计失效求助
问题解决:Pine Script 统计周五收盘价总和
核心问题分析
你的代码返回0的根本原因是循环方向错误:在Pine Script中,for i = 起始值 to 终止值 仅当起始值 ≤ 终止值时才会执行循环。你的代码里for i = bar_index to 1,而bar_index代表当前最后一根K线的索引(数值远大于1),导致循环完全没有运行,fridayTotal始终保持初始值0。
你提到的跨日K线(周五开盘、周六收盘)其实不是问题——外汇日线K线的time字段记录的是开盘时间,周五的K线开盘时间仍属于周五,dayofweek(time[i])可以正确识别为周五。
修正后的代码
正向遍历版本
indicator("My script", overlay = true) fridayTotal = 0.0 if timeframe.isdaily and barstate.islast // 从最早的K线(索引0)遍历到最新的K线(索引bar_index) for i = 0 to bar_index if dayofweek(time[i]) == dayofweek.friday fridayTotal += close[i] label.new(bar_index, close, str.tostring(fridayTotal))
反向遍历版本
如果习惯从最新K线往回遍历,需要使用down to语法:
indicator("My script", overlay = true) fridayTotal = 0.0 if timeframe.isdaily and barstate.islast // 从最新的K线反向遍历到最早的K线 for i = bar_index down to 0 if dayofweek(time[i]) == dayofweek.friday fridayTotal += close[i] label.new(bar_index, close, str.tostring(fridayTotal))
额外优化建议
- 日线周期下无需额外去重,但若切换到更低周期,可加入交易日判断避免重复统计
- 用
ta.valuewhen()函数简化逻辑,提升代码性能:indicator("My script", overlay = true) if timeframe.isdaily and barstate.islast // 提取所有周五的收盘价集合 fridayCloses = ta.valuewhen(dayofweek == dayofweek.friday, close, 0) fridayTotal = 0.0 // 遍历集合累加求和 for val in fridayCloses fridayTotal += val label.new(bar_index, close, str.tostring(fridayTotal))
内容的提问来源于stack exchange,提问作者John554
相关产品推荐
相关产品推荐

