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

如何在Pine Script中设置摆动低点止损及1:1、1:2风险收益比两档止盈

Pine Script 摆动低点止损+两档止盈逻辑实现

你原有代码的核心错误如下:

  • strategy.exit()的profit、loss参数要求输入相对入场价的基点差值,你直接传入绝对价格会导致止盈止损完全不生效
  • 摆动低点没有在开仓时锁定,后续行情更新时会持续变动,导致风险收益比计算错误
  • 止盈指令没有绑定对应入场ID,可能出现误平仓
  • 额外编写的止损平仓逻辑和strategy.exit()自带的止损功能重复,容易触发冲突

修正后完整代码

//@version=5
strategy("My Strategy", overlay=true, margin_long=100, margin_short=100)

var float recentSwinglow = na
var float SL = na
var float TP1 = na
var float TP2 = na
var float difference = na

// 计算20周期摆动低点
swingLow = ta.lowest(low, 20)

// 做多条件
longCondition = ta.crossover(ta.sma(close, 14), ta.sma(close, 28))
if (longCondition)
    strategy.entry("My Long Entry Id", strategy.long)    
    // 开仓时锁定摆动低点、止损、止盈价格
    recentSwinglow := swingLow
    SL := recentSwinglow
    difference := strategy.position_avg_price - SL
    TP1 := strategy.position_avg_price + difference
    TP2 := strategy.position_avg_price + difference * 2

// 做空条件(可按需开启)
shortCondition = ta.crossunder(ta.sma(close, 14), ta.sma(close, 28))
if (shortCondition)
    strategy.entry("My Short Entry Id", strategy.short)

// 绘图
plot(recentSwinglow, color = color.red, linewidth = 2, title="Recent Swing Low")
plot(strategy.position_avg_price, color = color.white, title="Entry Price")
plot(SL, color = color.red, linewidth = 2, title="Stop Loss")
plot(TP1, color = color.green, linewidth = 2, title="TP1 (1:1 RR)")
plot(TP2, color = color.purple, linewidth = 2, title="TP2 (1:2 RR)")

// 退出策略:第一档止盈平25%仓位,绑定止损
strategy.exit('TP1_Exit', "My Long Entry Id", qty_percent=25, limit=TP1, stop=SL)
// 第二档止盈平剩余仓位,止损移动到第一档止盈价(保本止损)
strategy.exit('TP2_Exit', "My Long Entry Id", limit=TP2, stop=TP1)

关键修改说明

  • 改用strategy.exit()的limit、stop参数直接传入绝对价格,无需手动换算基点,避免计算错误
  • 所有退出指令都绑定了对应入场ID"My Long Entry Id",只会平对应做多订单的仓位
  • 开仓时一次性锁定摆动低点、风险差值、两档止盈价格,后续不会随行情变动,保证风险收益比准确
  • 取消了重复的止损平仓判断,strategy.exit()会自动触发止损平仓
  • 若需要第一档止盈平半仓,直接将qty_percent=25改为qty_percent=50即可

内容的提问来源于stack exchange,提问作者Martin Moltke Wozniak

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 17:15:04