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

为何TradingView的strategy.close触发买卖警报而非平仓?求助

问题分析与解决方案

原因解析

TradingView 的 strategy.close() 本质上是通过下达反向持仓的订单来实现平仓的:

  • 平多单时,实际执行的是卖出订单(对应 {{strategy.order.action}} 为 sell)
  • 平空单时,实际执行的是买入订单(对应 {{strategy.order.action}} 为 buy)

平台更新后,警报模板中的 {{strategy.order.action}} 会直接返回该反向订单的动作类型,而非专门标识为“平仓”操作,这就是你收到买卖动作警报的核心原因。

解决方案

你可以通过以下两种方式明确区分平仓订单与新入场订单:

方法一:为平仓操作添加自定义注释

修改策略代码,在 strategy.close() 中加入 comment 参数标记平仓动作:

// Short Conditions
if (ShortCondition)
    strategy.entry("Short", strategy.short, comment="新空单")

// Long Conditions 
if (LongCondition)
    strategy.entry("Long", strategy.long, comment="新多单")

// Close the position after 4 bars
if barsSinceLastEntry() >= 4
    strategy.close("Long", comment="平多单")
    strategy.close("Short", comment="平空单") 

然后在警报消息中,同时使用 {{strategy.order.comment}} 和 {{strategy.order.action}} 来区分动作类型,例如:

订单动作:{{strategy.order.action}} | 订单类型:{{strategy.order.comment}}

这样就能直接识别是新入场还是平仓操作。

方法二:改用 strategy.exit() 进行平仓

strategy.exit() 可以更清晰地分离入场和平仓逻辑,且能通过订单ID直接识别平仓动作:

// Short Conditions
if (ShortCondition)
    strategy.entry("Short", strategy.short)

// Long Conditions 
if (LongCondition)
    strategy.entry("Long", strategy.long)

// Close the position after 4 bars
if barsSinceLastEntry() >= 4
    strategy.exit("Exit Long", "Long")  // 第一个参数为平仓订单ID,第二个为对应入场订单ID
    strategy.exit("Exit Short", "Short")

此时在警报中,可通过 {{strategy.order.id}} 判断是否为平仓订单(例如包含 "Exit" 关键字),也可以在 strategy.exit() 中添加 comment 参数进一步标记。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 00:32:24