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

求助:Pine Script中strategy.entry未执行及累计值异常问题

问题原因及修复方案

核心问题1:accumulation变量被重复初始化

你声明float accumulation = 0时未使用var关键字,Pine Script会在每根K线重新计算时将变量重置为0,导致它无法累计数值,仅能在触发条件时临时变为单次买入量,下一根K线又回到0。

修复:用var关键字声明变量,确保脚本运行期间仅初始化一次:

var float accumulation = 0

核心问题2:时间触发条件的精度不匹配

你的时间条件要求hour(time) == 12.0且minute(time) == 0.0,但如果图表时间框架不是分钟级(比如日线、周线),K线的time字段对应K线开盘时间,永远无法满足中午12点的条件,直接导致买入逻辑完全不触发。

另外weekofyear(time) % 2 == 1.0的逻辑存在缺陷:

  • 跨年时周数会重置,可能引发连续两周触发或跳过的问题
  • 不同交易所的周起始定义可能存在差异,导致触发时间混乱

更可靠的时间触发方案

用var变量记录上次买入的周数,实现稳定的隔周买入逻辑:

var int last_buy_week = na
current_week = weekofyear(time)
current_day = dayofweek(time)

// 周二触发(dayofweek=2对应周二),且与上次买入间隔至少一周
if current_day == 2 and (na(last_buy_week) or current_week > last_buy_week + 1)
    strategy.entry(id = "Buy", direction = strategy.long, qty=investment_amount/close)
    accumulation += investment_amount/close
    last_buy_week := current_week

如果必须指定中午12点触发,需切换到1分钟时间框架,同时精准匹配时间点:

if dayofweek(time) == 2 and hour(time) == 12 and minute(time) == 0
    // 买入逻辑

其他细节优化

  • float(investment_amount/close)可简化为investment_amount/close,Pine Script会自动处理类型转换
  • 可添加strategy.risk.allow_entry_in()确保策略允许在指定时间入场,避免默认入场限制

完整修复后的代码

// This strategy buys the asset displayed on the active chart every other week.
strategy("Dollar Cost Averaging")

// Set the amount of USD to buy the asset.
investment_amount = 75

// Variable to track accumulation (var keeps value across bars)
var float accumulation = 0
// Track last buy week to avoid repeated triggers in same week
var int last_buy_week = na

current_week = weekofyear(time)
// 周二触发(dayofweek=2),且为隔周的周二
if dayofweek(time) == 2 and (na(last_buy_week) or current_week != last_buy_week) and current_week % 2 == 1
    // Buy
    strategy.entry(id = "Buy", direction = strategy.long, qty=investment_amount/close)
    // Update accumulation
    accumulation += investment_amount/close
    // Record current week as last buy week
    last_buy_week := current_week

// Plot accumulation to verify
plot(accumulation, title="Total Asset Accumulated", color=color.green)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 06:55:16