ATR Trailing Stop (Long or Short Selectable)

akselkibar · study · 69 行 · 点赞 911 · TradingView 原页

本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。

Pine Script

//@version=5
indicator("ATR Trailing Stop (Long or Short Selectable)", overlay=true)
 
// === Inputs ===
tradeSide = input.string("Long", options=["Long", "Short"], title="Trade Direction")
entryDateYear   = input.int(2023, title="Entry Year", minval=1900, maxval=2100)
entryDateMonth  = input.int(1, title="Entry Month", minval=1, maxval=12)
entryDateDay    = input.int(1, title="Entry Day", minval=1, maxval=31)
entryPrice      = input.float(0, title="Entry Price (0 uses Close)", minval=0, step=0.01)
 
atrLength       = input.int(14, title="ATR Period", minval=1)
atrMultiplier   = input.float(2.0, title="ATR Multiplier", minval=0.1, step=0.1)
customValueForFirstDay = input.float(2.0, title="First-Day Custom Multiplier", minval=0.1, maxval=100, step=0.1)
 
// === ATR Calculation ===
atrValue = ta.atr(atrLength)
 
// === Entry Timestamp ===
entryDate = timestamp(entryDateYear, entryDateMonth, entryDateDay, 00, 00)
 
// === Entry Level ===
var float entryLevel = na
if na(entryLevel) and time >= entryDate
    entryLevel := (entryPrice > 0) ? entryPrice : close
 
// === Start Condition ===
startCalculating = not na(entryLevel) and time >= entryDate
 
// === Trailing Stop Variables ===
var float trailingStop = na
var bool firstDayCalculated = false
var bool stopPlotting = false
 
// === Trailing Stop Logic ===
if startCalculating and not stopPlotting
    if na(trailingStop[1])
        // Initial (first bar after entry) stop
        if tradeSide == "Long"
            if not firstDayCalculated
                trailingStop := entryLevel - atrValue * customValueForFirstDay
                firstDayCalculated := true
            else
                trailingStop := entryLevel - atrMultiplier * atrValue
        else // Short
            if not firstDayCalculated
                trailingStop := entryLevel + atrValue * customValueForFirstDay
                firstDayCalculated := true
            else
                trailingStop := entryLevel + atrMultiplier * atrValue
    else
        // Trailing update
        if tradeSide == "Long"
            float newStop = high - atrMultiplier * atrValue
            trailingStop := math.max(trailingStop[1], newStop)
        else
            float newStop = low + atrMultiplier * atrValue
            trailingStop := math.min(trailingStop[1], newStop)
 
    // Stop plotting if stop is violated
    if tradeSide == "Long" and not na(trailingStop[1]) and low < trailingStop[1]
        stopPlotting := true
    if tradeSide == "Short" and not na(trailingStop[1]) and high > trailingStop[1]
        stopPlotting := true
 
// === Plot ===
plot(startCalculating and not stopPlotting ? trailingStop : na,
     color = (tradeSide == "Long" ? color.green : color.red),
     title="Trailing Stop",
     linewidth=2)

← 返回列表