TradingView Pine Script同Bar平仓反手双倍下单问题咨询
Pine Script 同一K线反手Webhook下单量翻倍问题解决办法
问题说明
当同一K线触发反向交易信号(如平多开空)时,使用strategy.entry("ID1", strategy.long)后调用strategy.entry("ID2", strategy.short)的策略,会出现Webhook向经纪商发送的下单量为预期2倍的问题(例如默认下单量1手,实际发送2手)。此问题不影响策略盈亏计算,但存在下单指令的数量错误。
核心原因
strategy.entry在处理反向仓位时,默认会先发送平仓订单,再发送开仓订单。若策略逻辑未明确控制订单流程,可能导致Webhook将两次订单的数量叠加,出现下单量翻倍的异常。
解决方案
方案一:先平仓再开仓,明确控制订单流程
通过判断当前仓位状态,触发反向信号时先平掉原有仓位,再开立新仓位,避免系统自动拆分订单导致的数量异常:
//@version=5 strategy("BarUpDn Strategy", overlay=true, default_qty_type = strategy.fixed, default_qty_value = 1) maxIdLossPcnt = input.float(1, "Max Intraday Loss(%)") strategy.risk.max_intraday_loss(maxIdLossPcnt, strategy.percent_of_equity) // 定义多空触发条件 long_condition = close > open and open > close[1] short_condition = close < open and open < close[1] // 多头信号处理:平空后开多 if (long_condition) if (strategy.position_size < 0) strategy.close("BarDn") // 平掉现有空头仓位 strategy.entry("BarUp", strategy.long) // 空头信号处理:平多后开空 if (short_condition) if (strategy.position_size > 0) strategy.close("BarUp") // 平掉现有多头仓位 strategy.entry("BarDn", strategy.short)
方案二:使用strategy.order直接发送反手单
利用strategy.position_size判断当前仓位,直接发送对应数量的反向订单,让经纪商处理为反手操作(而非拆分平仓+开仓):
//@version=5 strategy("BarUpDn Strategy", overlay=true, default_qty_type = strategy.fixed, default_qty_value = 1) maxIdLossPcnt = input.float(1, "Max Intraday Loss(%)") strategy.risk.max_intraday_loss(maxIdLossPcnt, strategy.percent_of_equity) long_condition = close > open and open > close[1] short_condition = close < open and open < close[1] // 多头信号:空仓开多,持仓为空则反手 if (long_condition) if (strategy.position_size == 0) strategy.entry("BarUp", strategy.long) else if (strategy.position_size < 0) strategy.order("Reverse to Long", strategy.long, qty = abs(strategy.position_size)) // 空头信号:空仓开空,持仓为多则反手 if (short_condition) if (strategy.position_size == 0) strategy.entry("BarDn", strategy.short) else if (strategy.position_size > 0) strategy.order("Reverse to Short", strategy.short, qty = abs(strategy.position_size))
方案三:启用strategy.entry的reverse参数
通过reverse=true参数让系统自动处理反向仓位,本示例中多空条件互斥,天然满足同一K线仅触发一个方向信号的要求:
//@version=5 strategy("BarUpDn Strategy", overlay=true, default_qty_type = strategy.fixed, default_qty_value = 1) maxIdLossPcnt = input.float(1, "Max Intraday Loss(%)") strategy.risk.max_intraday_loss(maxIdLossPcnt, strategy.percent_of_equity) long_condition = close > open and open > close[1] short_condition = close < open and open < close[1] if (long_condition) strategy.entry("BarUp", strategy.long, reverse=true) if (short_condition) strategy.entry("BarDn", strategy.short, reverse=true)
验证说明
修改后可通过TradingView策略测试中的Webhook日志查看下单指令,确认订单数量与预期一致(默认1手)。若经纪商支持反手单,方案二和方案三的效果更优,仅发送一个反手订单而非两个独立订单。
内容的提问来源于stack exchange,提问作者Adek
相关产品推荐
相关产品推荐

