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

如何阻止Pine Script遇反向信号时自动平仓先前订单?

问题概述

当前的US30 Pine Script策略存在以下问题:

  • 每当新的入场信号(多/空)生成时,之前持有的订单会被提前平仓,无法持有至预设的止损(SL)或止盈(TP)水平
  • 期望策略允许每个订单独立走完完整流程,仅当价格触及SL/TP时才平仓,不受新信号影响
问题根源

默认情况下,Pine Script的strategy函数会自动平仓反向仓位,且若未设置独立订单标识,新的同方向/反向信号会触发旧订单的强制平仓,导致无法执行预设的离场条件。

修复后的策略代码
//@version=5
strategy("US30 独立订单版", overlay=true, 
         default_qty_type=strategy.percent_of_equity, 
         default_qty_value=100,
         close_entries_rule=strategy.close_entries_rule.none, // 禁止自动平仓旧订单
         allow_entry_in=strategy.longshort) // 允许同时持有多空仓位

// 定义移动平均线
length = 50
ma = ta.sma(close, length)

// 入场条件
longCondition = ta.crossover(close, ma)
shortCondition = ta.crossunder(close, ma)

// 定义US30的100点止损/止盈(1点=1pip)
sl_pips = 100
tp_pips = 100

// 生成唯一订单ID,确保每个新订单独立
long_id = "Long Trade " + str.tostring(bar_index)
short_id = "Short Trade " + str.tostring(bar_index)

if (longCondition)
    // 计算当前订单的SL/TP
    long_sl = close - sl_pips
    long_tp = close + tp_pips
    // 开多单,使用唯一ID
    strategy.entry(long_id, strategy.long)
    // 绑定对应订单的SL/TP
    strategy.exit("Long TP/SL " + str.tostring(bar_index), from_entry=long_id, limit=long_tp, stop=long_sl)

if (shortCondition)
    // 计算当前订单的SL/TP
    short_sl = close + sl_pips
    short_tp = close - tp_pips
    // 开空单,使用唯一ID
    strategy.entry(short_id, strategy.short)
    // 绑定对应订单的SL/TP
    strategy.exit("Short TP/SL " + str.tostring(bar_index), from_entry=short_id, limit=short_tp, stop=short_sl)

// 绘制移动平均线
plot(ma, color=color.blue, title="50 SMA")
关键修改说明
  • close_entries_rule=strategy.close_entries_rule.none:禁止策略自动平仓任何已有的订单,确保旧订单不会被新信号强制平仓
  • allow_entry_in=strategy.longshort:允许同时持有多单和空单,不会因反向信号触发自动平仓
  • 唯一订单ID:通过bar_index为每个入场订单生成唯一名称,确保每个订单的SL/TP绑定到对应的独立仓位,避免信号混淆

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 08:19:57