Turtle Trading System + ATR Trailing Stop

paulmar-vs · study · 85 行 · 点赞 85 · TradingView 原页

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

Pine Script

//@version=6
indicator("Turtle Trading System + ATR Trailing Stop", overlay=true)
 
// 1. Настройки
length = input.int(20, "Период экстремумов", minval=1)
atrLength = input.int(14, "Период ATR", minval=1)
atrMultiplier = input.float(2.0, "Множитель ATR для трейлинг-стопа", minval=0.1, step=0.1)
resetThreshold = input.float(0.1, "Порог сброса трейлинг-стопа (% от цены)", minval=0.01, step=0.01) / 100
positionType = input.string("Long", "Тип позиции", options=["Long", "Short"])
 
// 2. Рассчитываем уровни
twentyDayHigh = ta.highest(high, length)
twentyDayLow = ta.lowest(low, length)
atr = ta.atr(atrLength)
 
// 3. Трейлинг-стоп на основе ATR
var float trailingStop = na
var float highestPrice = na
var float lowestPrice = na
var float potentialStop = na
 
// Инициализация на первом баре, где atr и close доступны
if na(trailingStop) and not na(atr) and not na(close)
    trailingStop := positionType == "Long" ? close - atr * atrMultiplier : close + atr * atrMultiplier
    highestPrice := positionType == "Long" ? close : na
    lowestPrice := positionType == "Short" ? close : na
 
// Обновляем трейлинг-стоп на каждом баре для более плавного движения
if not na(atr) and not na(close)
    // Обновляем максимальную или минимальную цену
    highestPrice := positionType == "Long" ? math.max(nz(highestPrice[1], close), close) : nz(highestPrice[1], na)
    lowestPrice := positionType == "Short" ? math.min(nz(lowestPrice[1], close), close) : nz(lowestPrice[1], na)
    // Рассчитываем потенциальный стоп
    potentialStop := positionType == "Long" ? highestPrice - atr * atrMultiplier : lowestPrice + atr * atrMultiplier
    // Обновляем трейлинг-стоп
    trailingStop := positionType == "Long" ? math.max(potentialStop, nz(trailingStop[1], potentialStop)) : math.min(potentialStop, nz(trailingStop[1], potentialStop))
    // Сброс трейлинг-стопа при значительном отклонении
    if positionType == "Long" and close < trailingStop * (1 - resetThreshold)
        trailingStop := close - atr * atrMultiplier
        highestPrice := close
    else if positionType == "Short" and close > trailingStop * (1 + resetThreshold)
        trailingStop := close + atr * atrMultiplier
        lowestPrice := close
 
// 4. Визуализация
plot(twentyDayHigh, "20-day High", color=color.red, linewidth=2)
plot(twentyDayLow, "20-day Low", color=color.blue, linewidth=2)
plot(not na(trailingStop) and trailingStop > 0 ? trailingStop : na, "ATR Trailing Stop", color=color.yellow, linewidth=2)
 
// 5. Подписи и алерты
var label hiLabel = na
var label loLabel = na
var label tsLabel = na
 
label.delete(hiLabel[1])
label.delete(loLabel[1])
label.delete(tsLabel[1])
 
if barstate.isconfirmed
    hiLabel := label.new(bar_index, twentyDayHigh, "20H: " + str.tostring(twentyDayHigh, format.mintick), color=color.red, textcolor=color.white, style=label.style_label_down)
    loLabel := label.new(bar_index, twentyDayLow, "20L: " + str.tostring(twentyDayLow, format.mintick), color=color.blue, textcolor=color.white, style=label.style_label_up)
    if not na(trailingStop) and trailingStop > 0
        tsLabel := label.new(bar_index, trailingStop, "Stop: " + str.tostring(trailingStop, format.mintick), color=color.yellow, textcolor=color.white, style=label.style_label_up)
 
// Алерты при достижении трейлинг-стопа
if not na(trailingStop) and positionType == "Long" and close <= trailingStop
    alert("Цена достигла трейлинг-стопа (Long): " + str.tostring(trailingStop), alert.freq_once_per_bar_close)
else if not na(trailingStop) and positionType == "Short" and close >= trailingStop
    alert("Цена достигла трейлинг-стопа (Short): " + str.tostring(trailingStop), alert.freq_once_per_bar_close)
 
// 6. Отладочная таблица
var table debugTable = table.new(position.top_right, 2, 6, border_width=1)
if barstate.isconfirmed
    table.cell(debugTable, 0, 0, "ATR", bgcolor=color.gray, text_color=color.white)
    table.cell(debugTable, 1, 0, str.tostring(atr, format.mintick), bgcolor=color.gray, text_color=color.white)
    table.cell(debugTable, 0, 1, "Close", bgcolor=color.gray, text_color=color.white)
    table.cell(debugTable, 1, 1, str.tostring(close, format.mintick), bgcolor=color.gray, text_color=color.white)
    table.cell(debugTable, 0, 2, "Highest Price", bgcolor=color.gray, text_color=color.white)
    table.cell(debugTable, 1, 2, str.tostring(highestPrice, format.mintick), bgcolor=color.gray, text_color=color.white)
    table.cell(debugTable, 0, 3, "Lowest Price", bgcolor=color.gray, text_color=color.white)
    table.cell(debugTable, 1, 3, str.tostring(lowestPrice, format.mintick), bgcolor=color.gray, text_color=color.white)
    table.cell(debugTable, 0, 4, "Potential Stop", bgcolor=color.gray, text_color=color.white)
    table.cell(debugTable, 1, 4, str.tostring(potentialStop, format.mintick), bgcolor=color.gray, text_color=color.white)
    table.cell(debugTable, 0, 5, "Trailing Stop", bgcolor=color.gray, text_color=color.white)
    table.cell(debugTable, 1, 5, str.tostring(trailingStop, format.mintick), bgcolor=color.gray, text_color=color.white)

← 返回列表