如何在TradingView策略中实现部分止盈+剩余仓位按规则止损
TradingView 分级止盈+剩余仓位动态止损实现方案
此前实现失败的核心原因
- 开仓时立即调用
strategy.order获取的strategy.position_size是开仓前的旧值,无法正确计算1/3仓位 - 错误指定了
strategy.exit的对应入场ID,且平仓方向逻辑搞反(多头止盈应该对应多头入场订单,不是填Short) - 用收盘价判断后再提交止盈订单会导致触发滞后,甚至回测时漏单
- 部分止盈的
qty_percent参数填错为25,不符合1/3仓位的要求
可直接运行的实现代码
// 新增部分止盈状态标记,避免重复平仓 var bool longTp1Filled = false var bool shortTp1Filled = false // Determine stop loss price based on swinglow/high longStopPrice = periodHighestSwingLow shortStopPrice = periodLowestSwingHigh // Submit entry orders if (enterLong) strategy.entry(id="EL", long=true) longTp1Filled := false // 新开仓重置止盈标记 if (enterShort) strategy.entry(id="ES", long=false) shortTp1Filled := false // 新开仓重置止盈标记 // 多头持仓离场逻辑 if (strategy.position_size > 0) longTp1Price = strategy.position_avg_price * 1.01 // 未触发部分止盈时提交1/3仓位止盈单 if not longTp1Filled strategy.exit(id="XL TP1", from_entry="EL", limit=longTp1Price, qty_percent=33.33, comment="TP 1/3") longTp1Filled := strategy.order_filled("XL TP1") // 始终提交动态止损单,自动适配当前剩余仓位 strategy.exit(id="XL STP", from_entry="EL", stop=longStopPrice, comment="Stop Loss") // 空头持仓离场逻辑 if (strategy.position_size < 0) shortTp1Price = strategy.position_avg_price * 0.99 // 未触发部分止盈时提交1/3仓位止盈单 if not shortTp1Filled strategy.exit(id="XS TP1", from_entry="ES", limit=shortTp1Price, qty_percent=33.33, comment="TP 1/3") shortTp1Filled := strategy.order_filled("XS TP1") // 始终提交动态止损单,自动适配当前剩余仓位 strategy.exit(id="XS STP", from_entry="ES", stop=shortStopPrice, comment="Stop Loss")
逻辑说明
- 用
strategy.order_filled()判断部分止盈单是否成交,成交后不再重复提交该止盈单,避免重复平仓 from_entry参数必须和对应入场订单的ID完全一致,才能正确绑定仓位- 动态止损单每个K线都会更新止损价为最新的swinglow/swinghigh,符合原有止损逻辑;部分止盈成交后,止损单会自动对应剩余的2/3仓位,不需要手动调整数量
- 上述代码适用于单笔入场的场景,如果你策略允许加仓,需要对应调整止盈计算逻辑
内容的提问来源于stack exchange,提问作者gastngouron
相关产品推荐
相关产品推荐

