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

金字塔下单后如何让strategy.exit仅触发一次实现统一TP/SL?

解决金字塔下单后单次触发止盈止损平全部仓位的问题

问题根源

你当前用strategy.exit绑定from_entry时,会对每一笔金字塔开仓的单独仓位生成独立的止盈止损订单,所以触发时会分20次平仓。要实现单次触发平全部,需要直接针对总仓位提交统一的止盈止损订单,而非绑定到单条entry记录。

具体实现代码

1. 保留原开仓逻辑,记录总仓位大小

// 原开仓代码不变
strategy.entry(id = 'Short Entry', direction = strategy.short, qty=qty, alert_message = '{"position_to_open":{"side":"Short"}}', comment=comment_open_short)

// 记录总开仓手数(仅在仓位变化且非空仓时更新)
var float total_position_qty = 0.0
if strategy.position_size != strategy.position_size[1] and strategy.position_size != 0
    total_position_qty = abs(strategy.position_size)

2. 提交针对总仓位的止盈止损订单

代替原strategy.exit,直接提交限价止盈单和止损止损单,数量设为总仓位大小:

// 做空场景:止盈限价单(价格跌到TP时平全部空仓)
if strategy.position_size < 0 and not na(tp)
    strategy.order(
        id="Global Short TP",
        direction=strategy.long,
        qty=total_position_qty,
        limit=tp,
        comment="Global Short Take Profit"
    )

// 做空场景:止损止损单(价格涨到SL时平全部空仓)
if strategy.position_size < 0 and not na(sl)
    strategy.order(
        id="Global Short SL",
        direction=strategy.long,
        qty=total_position_qty,
        stop=sl,
        comment="Global Short Stop Loss"
    )

关键说明

  • 这种方式会在价格精准触及TP/SL时,一次性平掉全部20手仓位,不会分多次触发。
  • 订单类型和strategy.exit一致(限价/止损),保证价格触发的精准性,解决你用close_all时无法精准执行的问题。
  • 如果后续有金字塔加仓,total_position_qty会自动更新为最新总仓位;若需要同步调整止盈止损订单,可添加strategy.cancel()先取消旧订单,再提交新的对应总仓位的订单。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 11:45:21