You need to enable JavaScript to run this app. Pine Script如何为两类strategy.exit退出条件设置OR条件运算符
优惠活动
大模型
产品
解决方案
定价
更多

Pine Script如何为两类strategy.exit退出条件设置OR条件运算符

错误原因
  • 语法不兼容:Pine Script 不支持使用or运算符拼接两个独立的strategy.exit函数调用,你当前的写法是Python逻辑迁移导致的语法错误,你看到的Mismatched input ',' expecting ')'报错就是解析器无法识别该非法语法触发的。
  • 函数用法错误:strategy.exit本身支持同时传入多个离场条件,无需重复调用该函数。
  • 头寸ID错误:空头离场代码中错误填入了多头头寸ID"long",语法修正后也无法正常匹配空头仓位。
解决方案1:复用strategy.exit原生多条件支持(与原有代码兼容性最高)

保留你原有strategy.exit的使用习惯,直接在同一个函数调用中传入两个离场条件即可:

// 多头入场与离场
if (long)
    strategy.entry("long", strategy.long, PosSizeUnits) 

if (strategy.position_size > 0) // 仅持有多头时生效
    strategy.exit("exit_long", "long", stop=stopLossLong, limit=if exitLongquick then close else na)

// 空头入场与离场
if (short)
    strategy.entry("short", strategy.short, PosSizeUnits) 

if (strategy.position_size < 0) // 仅持有空头时生效
    strategy.exit("exit_short", "short", stop=stopLossShort, limit=if exitShortquick then close else na)
解决方案2:条件判断主动平仓(逻辑更直观,适合新手)

如果需要更灵活的离场逻辑扩展,直接用条件判断匹配离场规则后调用strategy.close平仓即可:

// 多头入场
if (long)
    strategy.entry("long", strategy.long, PosSizeUnits) 

// 多头离场:ATR止损或快均线交叉满足任意条件即平仓
if (strategy.position_size > 0)
    if (low <= stopLossLong or exitLongquick)
        strategy.close("long")

// 空头入场
if (short)
    strategy.entry("short", strategy.short, PosSizeUnits) 

// 空头离场:ATR止损或快均线交叉满足任意条件即平仓
if (strategy.position_size < 0)
    if (high >= stopLossShort or exitShortquick)
        strategy.close("short")

两种方案都可以实现你需要的「ATR止损触发前先满足均线交叉则提前离场」的需求,可根据后续代码扩展需要选择。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 14:24:02