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

Slow Stochastics多头策略平仓失效问题求助

问题排查与修复

核心问题分析

你的平仓逻辑失效主要有两个原因:

  1. 重复使用同一strategy.exitID:开仓时已创建名为XL的退出指令,exitLong触发时再次调用同名指令会直接覆盖原有设置,而非触发平仓动作。
  2. 平仓逻辑匹配错误:你在exitLong信号触发时用limit=longProfit设置止盈平仓,这和你“%K下穿%D时直接平仓”的需求不符,属于逻辑错位。

修复后的完整代码

//@version=5
strategy(title="Slow Stochastics Crossover", overlay=true,
     pyramiding=0, initial_capital=100000,
     commission_type=strategy.commission.cash_per_order,
     commission_value=4, slippage=2)


smoothK = input.int(3, minval=1), smoothD = input.int(3, minval=1)
k = ta.sma(ta.stoch(close, high, low, 14), smoothK)
d = ta.sma(k, smoothD)

atrLen     = input.int(14, title="ATR Length")
atrValue = ta.atr(atrLen)
stopOffset = input.float(2, title="Stop Offset Multiple", step=.25)
profitOffset = input.float(3, title="Profit Offset Multiple", step=.25) // 修正参数名重复问题

enterLong = ta.crossover(k, d)
exitLong = ta.crossunder(k, d)

longProfit =  close + (profitOffset * atrValue)

longStop = 0.0
longStop := enterLong ? close - (stopOffset * atrValue) :
     longStop[1]


// Position sizing inputs
usePosSize  = input.bool(true, title="Use Position Sizing?")
maxRisk     = input.float(2, title="Max Position Risk %", step=.25)
maxExposure = input.float(10, title="Max Position Exposure %", step=1)
marginPerc  = input.int(10, title="Margin %")

riskEquity = (maxRisk * 0.01) * strategy.equity
riskTrade  = (atrValue * stopOffset) * syminfo.pointvalue

maxPos = ((maxExposure * 0.01) * strategy.equity) /
     ((marginPerc * 0.01) * (close * syminfo.pointvalue))

posSize = usePosSize ? math.min(math.floor(riskEquity / riskTrade), maxPos) : 1

plot(k, color=color.orange, title="%K")
plot(d, color=color.teal, linewidth=2, title="%D")

plot(strategy.position_size > 0 ? longStop : na, color=color.green, 
     linewidth=2, style=plot.style_circles)


if enterLong
    // 开仓时直接创建带止损、止盈的退出指令,使用唯一ID
    strategy.entry("EL", strategy.long, qty=posSize)
    strategy.exit("Exit-EL", from_entry="EL", stop=longStop, limit=longProfit)

if exitLong
    // 触发交叉信号时直接平仓,避免指令覆盖
    strategy.close("EL")

关键修复点说明

  • 修正参数命名冲突:原代码中profitOffset的输入标题和stopOffset重复,改为Profit Offset Multiple避免混淆。
  • 避免指令ID冲突:开仓时使用唯一的退出指令IDExit-EL,防止后续平仓指令覆盖止损止盈设置。
  • 匹配需求的平仓逻辑:当exitLong信号触发时,用strategy.close("EL")直接平掉对应仓位,严格执行“%K下穿%D时平仓”的策略逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 04:16:18