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

策略现有出场条件中添加Stop Loss和Take Profit失效求助

问题分析

你的代码存在核心逻辑错误:strategy.entry()的stop和limit参数是用来定义入场挂单的触发条件,而非持仓后的止盈止损机制。比如做多时,你设置stop=slPrice会把入场单变成“跌破止损价才入场”的反向挂单,完全背离了持仓止损的需求,这就是止盈止损失效的原因。

解决方案

正确实现持仓止盈止损的方式有两种,以下是修正后的代码:

方法1:使用strategy.exit(推荐,逻辑更清晰)

// 仅在持仓时计算止盈止损价
var float tpPrice = na
var float slPrice = na

if (strategy.position_size > 0)
    tpPrice := strategy.position_avg_price * (1 + (tpPercent / 100))
    slPrice := strategy.position_avg_price * (1 - (slPercent / 100))
elif (strategy.position_size < 0)
    tpPrice := strategy.position_avg_price * (1 - (tpPercent / 100))
    slPrice := strategy.position_avg_price * (1 + (slPercent / 100))

// Long entry
if (longCondition)
    strategy.entry("Long", strategy.long)
    // 绑定多头持仓的止盈止损
    strategy.exit("Exit Long", "Long", stop=slPrice, limit=tpPrice)

// 原有出场条件
if (strategy.position_size > 0)
    strategy.close("Long", when=(D > overboughtLevel and signalLine > 0))

// Short entry
if (shortCondition)
    strategy.entry("Short", strategy.short)
    // 绑定空头持仓的止盈止损
    strategy.exit("Exit Short", "Short", stop=slPrice, limit=tpPrice)

// 原有出场条件
if (strategy.position_size < 0)
    strategy.close("Short", when=(D < oversoldLevel and signalLine < 0))

方法2:在strategy.entry中直接指定stop_loss和take_profit参数

// 仅在持仓时计算止盈止损价
var float tpPrice = na
var float slPrice = na

if (strategy.position_size > 0)
    tpPrice := strategy.position_avg_price * (1 + (tpPercent / 100))
    slPrice := strategy.position_avg_price * (1 - (slPercent / 100))
elif (strategy.position_size < 0)
    tpPrice := strategy.position_avg_price * (1 - (tpPercent / 100))
    slPrice := strategy.position_avg_price * (1 + (slPercent / 100))

// Long entry
strategy.entry("Long", strategy.long, when=longCondition, stop_loss=slPrice, take_profit=tpPrice)
if (strategy.position_size > 0)
    strategy.close("Long", when=(D > overboughtLevel and signalLine > 0))

// Short entry
strategy.entry("Short", strategy.short, when=shortCondition, stop_loss=slPrice, take_profit=tpPrice)
if (strategy.position_size < 0)
    strategy.close("Short", when=(D < oversoldLevel and signalLine < 0))
额外提示
  • 新增了持仓状态判断后再计算止盈止损价的逻辑,避免未持仓时strategy.position_avg_price返回0导致的无效价格问题
  • 原有strategy.close()触发时,会自动取消对应的止盈止损挂单,不影响原有出场逻辑的优先级

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 03:22:20