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

如何在Pine Script中可靠检测所有交易开仓(含实时K线)

解决Pine Script实时K线交易开仓检测问题

你的原代码仅通过跟踪最后一笔持仓的ID和时间判断新仓,这种方式在实时K线(未闭合的K线)上会失效——因为实时K线内脚本会重复运行,新仓的entry_time与当前K线时间一致,导致_entryTime != lastEntryTime的条件无法触发;或者已更新的lastEntryId会跳过重复检测。

以下是两种可靠的解决方案:

方案1:用数组跟踪所有已检测的交易ID

通过数组记录所有已处理的交易ID,遍历当前所有持仓,确保每一笔新开仓都被检测到,同时清理已平仓的ID避免数组冗余:

// 存储已处理的交易ID数组
var string[] processedEntryIds = array.new_string()

// 遍历所有当前持仓
for i = 0 to strategy.opentrades - 1
    currentEntryId = strategy.opentrades.entry_id(i)
    // 如果ID未被处理过,标记为新交易
    if not array.includes(processedEntryIds, currentEntryId)
        array.push(processedEntryIds, currentEntryId)
        entryTime = strategy.opentrades.entry_time(i)
        log.info('New trade opened: ' + currentEntryId + ' ' + str.tostring(entryTime))

// 定期清理已平仓的交易ID(可选,优化内存)
for i = 0 to strategy.closedtrades - 1
    closedEntryId = strategy.closedtrades.entry_id(i)
    idIndex = array.indexof(processedEntryIds, closedEntryId)
    if idIndex != -1
        array.remove(processedEntryIds, idIndex)

方案2:跟踪持仓数量变化

通过对比当前和上一次运行时的持仓数量,当持仓数增加时直接遍历新增的仓位,适合大多数场景:

// 记录上一次运行时的持仓数量
var int prevOpenTradesCount = 0

// 更新上一次持仓数为前一个脚本周期的数值
prevOpenTradesCount := strategy.opentrades[1]

// 当当前持仓数大于上一次时,说明有新仓开仓
if strategy.opentrades > prevOpenTradesCount
    // 遍历新增的仓位(从之前的数量到当前最后一个)
    for i = prevOpenTradesCount to strategy.opentrades - 1
        entryId = strategy.opentrades.entry_id(i)
        entryTime = strategy.opentrades.entry_time(i)
        log.info('New trade opened: ' + entryId + ' ' + str.tostring(entryTime))

这两种方法都能覆盖历史K线和实时K线的开仓场景,保证你的策略统计数据和测试器性能汇总一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 04:32:59