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

持仓后止损立即触发问题求助及相关Pine Script代码

开仓后止损立即触发的问题解决

问题原因

在开仓的同一根K线中,strategy.position_avg_price还未更新为当前开仓的成交价格。Pine Script中策略的持仓均价会在订单确认成交后才更新,而你在执行strategy.entry的同一根K线就调用strategy.exit,此时strategy.position_avg_price要么为0(无历史持仓),要么是上一次持仓的均价,导致计算出的止损价格完全不符合预期,进而触发立即止损。

解决代码

方法一:用信号触发时的收盘价计算止损

longLossPerc = input(title="Long Stop Loss (%)", type=input.float, minval=0.0, step=0.1, defval=1) * 0.01
shortLossPerc = input(title="Short Stop Loss (%)", type=input.float, minval=0.0, step=0.1, defval=1) * 0.01

// 记录开仓价格
var float longEntryPrice = na
var float shortEntryPrice = na

// 多单开仓时记录收盘价
if (long)
    longEntryPrice := close
// 空单开仓时记录收盘价
if (short)
    shortEntryPrice := close

// 基于开仓价格计算止损
longStopPrice  = longEntryPrice * (1 - longLossPerc)
shortStopPrice = shortEntryPrice * (1 + shortLossPerc)

strategy.entry('Long', strategy.long, when=long, comment='Long',alert_message = message_long_entry)
strategy.exit( "SL","Long", stop=longStopPrice, comment = "SL Long",alert_message = message_long_exit)
strategy.entry('Short', strategy.short, when=short, comment='Short',alert_message = message_short_entry)
strategy.exit( "SL","Short", stop=shortStopPrice, comment = "SL Short",alert_message = message_short_exit)

方法二:用实际成交价格计算止损(更严谨)

longLossPerc = input(title="Long Stop Loss (%)", type=input.float, minval=0.0, step=0.1, defval=1) * 0.01
shortLossPerc = input(title="Short Stop Loss (%)", type=input.float, minval=0.0, step=0.1, defval=1) * 0.01

var float longEntryPrice = na
var float shortEntryPrice = na

// 检测多单成交并记录实际成交价格
if (strategy.position_size > 0 and strategy.position_size[1] <= 0)
    longEntryPrice := strategy.entry_result.price
// 检测空单成交并记录实际成交价格
if (strategy.position_size < 0 and strategy.position_size[1] >= 0)
    shortEntryPrice := strategy.entry_result.price

// 基于实际成交价格计算止损
longStopPrice  = longEntryPrice * (1 - longLossPerc)
shortStopPrice = shortEntryPrice * (1 + shortLossPerc)

strategy.entry('Long', strategy.long, when=long, comment='Long',alert_message = message_long_entry)
strategy.exit( "SL","Long", stop=longStopPrice, comment = "SL Long",alert_message = message_long_exit)
strategy.entry('Short', strategy.short, when=short, comment='Short',alert_message = message_short_entry)
strategy.exit( "SL","Short", stop=shortStopPrice, comment = "SL Short",alert_message = message_short_exit)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 23:50:25