Pine Script多空单止盈止损异常:空单一进场即平仓求助
Pine Script空单一进场即平仓问题修复方案
问题根源
- 持仓判断逻辑错误:
strategy.position_avg_price是持仓的实际成交价格(始终为正数),空单持仓时该值不会小于0,导致空单的TP/SL代码从未执行。正确的空单持仓判断应使用strategy.position_size < 0(持仓量为负代表空单)。 - 平仓指令目标ID错误:
strategy.close需要指定对应开仓指令的ID,原代码中"LongExit"、"ShortExit"并非开仓时的ID(开仓ID是"buy"、"sell"),导致平仓逻辑混乱。 - 止盈止损指令ID重复:多空单共用同一个exit ID "close",会引发策略内部指令冲突,必须为多空单分别设置独立的exit ID。
修正后的代码
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © Hawkreign //@version=5 strategy(title="SGA Alert", overlay=true, default_qty_type = strategy.cash, default_qty_value = 100) // Input options src = input.source(close, title = "SGA Prime" ) // Long and Short Conditions on the SGA long = ta.rising(src, 1) short = ta.falling(src, 1) // Long and Short Memory longmem = false shortmem = false // Memory Conditions longmem := long ? true : short ? false : longmem[1] shortmem := short ? true : long ? false : shortmem[1] // Entry and Exit Variables buy = long and not (longmem[1]) sell = short and not (shortmem[1]) // Take Profit and Stop Loss SL = 0.10 TP = 0.04 LongStop = strategy.position_avg_price*(1-SL) ShortStop = strategy.position_avg_price*(1+SL) LongProfit = strategy.position_avg_price*(1+TP) ShortProfit = strategy.position_avg_price*(1-TP) // Long and Short Background color bgcolor(buy ? color(color.rgb(11, 238, 18)): na) bgcolor(sell ? color(color.rgb(134, 7, 7)): na) // Long Entry and Exit strategy.entry("buy", strategy.long, when = buy) strategy.close("buy", when = sell) // 指定平仓多单的ID为"buy" if strategy.position_size > 0 // 用持仓量判断多单持仓 strategy.exit(id = "LongExit", stop = LongStop, limit = LongProfit) // Short Entry and Exit strategy.entry("sell", strategy.short, when = sell) strategy.close("sell", when = buy) // 指定平仓空单的ID为"sell" if strategy.position_size < 0 // 用持仓量判断空单持仓 strategy.exit(id = "ShortExit", stop = ShortStop, limit = ShortProfit) plot(src)
关键修改说明
- 将空单持仓判断从
strategy.position_avg_price<0改为strategy.position_size < 0,确保空单的TP/SL逻辑能正常触发。 - 修正
strategy.close的目标ID为对应开仓指令的"buy"和"sell",保证平仓指令精准作用于目标持仓。 - 为多空单的
strategy.exit分别设置独立ID "LongExit"和"ShortExit",避免指令冲突。
内容的提问来源于stack exchange,提问作者HuskyReign
相关产品推荐
相关产品推荐

