本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=5
strategy("Range Filter Strategy with ATR TP/SL", overlay=true, margin_long=100, margin_short=100)
// Inputs
length = input.int(20, title="Range Filter Length")
mult = input.float(1.5, title="Range Filter Multiplier")
atrLength = input.int(14, title="ATR Length")
tpMultiplier = input.float(1.5, title="Take Profit Multiplier")
slMultiplier = input.float(1.5, title="Stop Loss Multiplier")
// Range Filter Calculation
src = close
smooth = ta.sma(src, length)
dev = mult * ta.stdev(src, length)
upper = smooth + dev
lower = smooth - dev
// ATR Calculation
atr = ta.atr(atrLength)
// Trend Direction
var bool uptrend = na
var bool downtrend = na
uptrend := close > upper and (na(uptrend[1]) or uptrend[1])
downtrend := close < lower and (na(downtrend[1]) or downtrend[1])
// Entry Conditions
longCondition = ta.crossover(close, upper) and not uptrend[1]
shortCondition = ta.crossunder(close, lower) and not downtrend[1]
// Exit Conditions (ATR-based)
takeProfitLong = strategy.position_avg_price + (atr * tpMultiplier)
stopLossLong = strategy.position_avg_price - (atr * slMultiplier)
takeProfitShort = strategy.position_avg_price - (atr * tpMultiplier)
stopLossShort = strategy.position_avg_price + (atr * slMultiplier)
// Strategy Execution
if (longCondition)
strategy.entry("Long", strategy.long)
strategy.exit("Exit Long", "Long", limit=takeProfitLong, stop=stopLossLong)
if (shortCondition)
strategy.entry("Short", strategy.short)
strategy.exit("Exit Short", "Short", limit=takeProfitShort, stop=stopLossShort)
// Plotting
plot(upper, color=color.green, title="Upper Range")
plot(lower, color=color.red, title="Lower Range")
plot(smooth, color=color.blue, title="Smooth Line")
// Plot TP/SL levels when in position
plot(strategy.position_size > 0 ? takeProfitLong : na, color=color.green, style=plot.style_circles, linewidth=2, title="TP Long")
plot(strategy.position_size > 0 ? stopLossLong : na, color=color.red, style=plot.style_circles, linewidth=2, title="SL Long")
plot(strategy.position_size < 0 ? takeProfitShort : na, color=color.red, style=plot.style_circles, linewidth=2, title="TP Short")
plot(strategy.position_size < 0 ? stopLossShort : na, color=color.green, style=plot.style_circles, linewidth=2, title="SL Short")