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

Pine Script循环仅执行一次:指定多日期仅首笔交易触发

问题原因与解决方案

你的代码核心错误是**var关键字的误用**:

循环内声明var string[] date_obj = str.split(array.get(dates, i), "/")时,var会让这个数组变量仅在脚本初始化阶段创建并赋值一次。第一次循环(i=0)时,date_obj被赋值为第一个日期的拆分结果;后续循环(i=1及以后)时,var阻止了date_obj重新赋值,它始终保留第一个日期的拆分数据,自然只会匹配第一个日期的条件。

修改后的代码

var string[] dates = array.from("22/03/2023", "23/03/2023")

for i = 0 to array.size(dates) - 1
    string[] date_obj = str.split(array.get(dates, i), "/")  // 去掉var关键字
    if str.tostring(dayofmonth) == array.get(date_obj, 0) and str.tostring(month) == array.get(date_obj, 1) and str.tostring(year) == array.get(date_obj, 2) and hour == 14 and minute > 50 and strategy.opentrades == 0
        strategy.entry(id = 'Short Entry', direction = strategy.short)

额外优化建议

可以直接将目标日期转换为时间戳比较,避免字符串转换的繁琐和潜在误差:

var int[] targetTimestamps = array.from(timestamp(2023, 3, 22, 14, 51), timestamp(2023, 3, 23, 14, 51))

for i = 0 to array.size(targetTimestamps) - 1
    if time >= array.get(targetTimestamps, i) and strategy.opentrades == 0
        strategy.entry(id = 'Short Entry', direction = strategy.short)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 07:42:46