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

Pine Script布林带交易策略止损单设置技术求助

Pine Script 布林带策略止损设置修正方案

原代码核心问题

  • 止损价依赖strategy.position_avg_price计算,该值无持仓时为0,且每根K线会重新更新,无法固定为入场时刻的价格
  • strategy.exit参数绑定错误:多单(EL)的止损应为Stop_long,空单(ES)的止损应为Stop_short,原代码两者颠倒
  • 出场条件exitLong逻辑不合理,与止损规则存在冲突

修正核心要点

  1. 固定入场基准价:用valuewhen函数捕获入场信号触发时的价格,确保止损价始终基于入场价计算,而非实时变动的持仓均价
  2. 修正止损参数关联:将多单止损绑定Stop_long,空单止损绑定Stop_short,匹配对应仓位的止损逻辑
  3. 整合出场逻辑:保留止损出场的同时,优化趋势出场条件,避免重复平仓指令冲突

修正后完整代码

//@version=3

// BACKTESTING RANGE
 
// From Date Inputs
fromDay = input(defval = 29, title = "From Day", minval = 1, maxval = 31)
fromMonth = input(defval = 9, title = "From Month", minval = 1, maxval = 12)
fromYear = input(defval = 2021, title = "From Year", minval = 1970)
 
// To Date Inputs
toDay = input(defval = 28, title = "To Day", minval = 1, maxval = 31)
toMonth = input(defval = 1, title = "To Month", minval = 1, maxval = 12)
toYear = input(defval = 2023, title = "To Year", minval = 1970)
 
// Calculate start/end date and time condition
startDate = timestamp(fromYear, fromMonth, fromDay, 00, 00)
finishDate = timestamp(toYear, toMonth, toDay, 00, 00)
time_cond = time >= startDate and time <= finishDate

// Set stop loss level with input options (optional)
Lossperc_Long = input(title="Long Stop Loss (%)",
     type=float, minval=0.0, step=0.1, defval=1) * 0.01

Lossperc_Short = input(title="Short Stop Loss (%)",
     type=float, minval=0.0, step=0.1, defval=1) * 0.01
 

////////////////////////////////////////////////////////////////////////////////


// 1. Define strategy settings
strategy(title="Bollinger Breakout OBI", overlay=true,
     pyramiding=0, initial_capital=100000,
     commission_type=strategy.commission.cash_per_order,
     commission_value=4, slippage=2)

smaLength = input(title="SMA Length", type=integer, defval=20)
stdLength = input(title="StdDev Length", type=integer, defval=20)

ubOffset = input(title="Upper Band Offset", type=float, defval=2.0, step=0.5)
lbOffset = input(title="Lower Band Offset", type=float, defval=2.0, step=0.5)

usePosSize = input(title="Use Position Sizing?", type=bool, defval=true)
riskPerc   = input(title="Risk %", type=float, defval=0.5, step=0.25)

// 2. Calculate strategy values
smaValue = sma(close, smaLength)
stdDev   = stdev(close, stdLength)

upperBand = smaValue + (stdDev * ubOffset)
lowerBand = smaValue - (stdDev * lbOffset)


///////////// RSI
RSIlength = input(16,title="RSI Period Length")
RSIoverSold = input(40,title="RSI Oversold")
RSIoverBought = input(60,title="RSI Overbought")  
price = close
vrsi = rsi(price, RSIlength)


///////////// POSITION SIZING
riskEquity  = (riskPerc / 100) * strategy.equity
atrCurrency = (atr(20) * syminfo.pointvalue)
posSize     = usePosSize ? floor(riskEquity / atrCurrency) : 1



// 3. Output strategy data

// BB PLOT
plot(series=smaValue, title="SMA", color=teal)

plot(series=upperBand, title="UB", color=green,
     linewidth=2)
plot(series=lowerBand, title="LB", color=red,
     linewidth=2)

// 4. Determine long trading conditions
enterLong = crossover(close, lowerBand) and (vrsi < RSIoverSold)
exitLong  = crossover(close, upperBand) // 修正多单出场条件:上穿上轨离场
// 捕获多单入场时的价格,计算固定止损价
longEntryPrice = valuewhen(enterLong, close, 0)
Stop_long = longEntryPrice * (1 - Lossperc_Long)

// 5. Code short trading conditions
enterShort = crossunder(close, upperBand) and (vrsi > RSIoverBought)
exitShort  = crossunder(close, lowerBand) // 空单出场条件:下穿下轨离场
// 捕获空单入场时的价格,计算固定止损价
shortEntryPrice = valuewhen(enterShort, close, 0)
Stop_short = shortEntryPrice * (1 + Lossperc_Short)


// 6. Submit entry orders
if (enterLong) and time_cond
    strategy.entry(id="EL", long=true, qty=posSize)

if (enterShort) and time_cond
    strategy.entry(id="ES", long=false, qty=posSize)

// 7. Submit exit orders:整合止损与趋势出场逻辑
strategy.exit(id="Exit EL", from_entry="EL", stop=Stop_long, when=exitLong)
strategy.exit(id="Exit ES", from_entry="ES", stop=Stop_short, when=exitShort)


// 可选:绘制止损价参考线
plot(strategy.position_size > 0 ? Stop_long : na, color=red, style=hline, title="Long Stop Loss")
plot(strategy.position_size < 0 ? Stop_short : na, color=green, style=hline, title="Short Stop Loss")

plot(close + 2*atr(20), color=yellow )
plot(close - 2*atr(20), color=yellow)

关键修正说明

  • 固定入场价:valuewhen(enterLong, close, 0)会精准捕获多单触发时的收盘价,作为止损计算的基准,该值在入场后保持不变,直到下一次入场信号触发
  • 止损逻辑匹配:strategy.exit通过from_entry指定对应入场单,stop参数绑定正确的止损价,when参数关联趋势出场条件,实现“止损或趋势反转任一触发即平仓”
  • 出场条件优化:将多单出场条件改为上穿上轨,更符合布林带突破策略的趋势跟踪逻辑,避免原条件与止损规则冲突

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 16:35:22