Strategy · Pine Script v5 · On the chart

PineScriptMastery

by Web3Degenerate

This educational strategy demonstrates how to implement trailing stop losses in Pine Script.

View on GitHub

GitHub stars2on the repository
Pine versionv5runs as is
Lines of code64
Settings8inputs
LicenceNone statedfile: MPL-2.0
Last update2 years ago13 Sep 2024

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new strategy, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart. The trades and results appear in the Strategy Tester tab; adjust the settings with the gear icon.

Source Code

64 lines of Pine Script v5 from advanced-pine-script/9.Strategy-Scripts/21.Coding-Strategy-Trailing-Stops.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

21.Coding-Strategy-Trailing-Stops.pine
//This demonstrates various methods we can use to code trailing stop losses in Pine Script to lock in profits in strategy scripts - including ATR and Percentage-based variants with several parameters.

/// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/

// @version=5
strategy("www.PineScriptMastery.com", overlay=true)

// Get user input
tradeType           = input.string(title="Trade Direction", defval="Long", options=["Long", "Short"], confirm=true)
trailSource         = input.string(title="Trail Source", defval="Lows/Highs", options=["Lows/Highs", "Close", "Open"], confirm=true)
trailMethod         = input.string(title="Trail Method", defval="ATR", options=["ATR", "Percent"], confirm=true)
trailPercent        = input.float(title="Trail Percent", defval=10, minval=0.1, confirm=true)
swingLookback       = input.int(title="Lookback", defval=7, confirm=true)
atrPeriod           = input.int(title="ATR Period", defval=14, confirm=true)
atrMultiplier       = input.float(title="ATR Multiplier", defval=1.0, confirm=true)
barTime             = input.time(title="Bar Time", defval=timestamp("01 Jan 2021 13:30 +0000"), confirm=true)

// Enter mock trade (if bar is the one we clicked on and we have no open trades or previous trades)
if time >= barTime and strategy.position_size == 0 and strategy.closedtrades == 0
    strategy.entry("Trade", direction = (tradeType == "Long" ? strategy.long : strategy.short))

// Declare trailing price variable (stores our trail stop value)
var float trailPrice    = na
float next_trailPrice   = na

// Get required trailing stop variables
atrValue                = ta.atr(atrPeriod) * atrMultiplier
float swingLow          = ta.lowest(low, swingLookback)
float swingHigh         = ta.highest(high, swingLookback)

// Get trailing stop price
if trailMethod == "ATR" // Determine ATR trailing stop price based on price source
    next_trailPrice := switch trailSource
        "Close"     => strategy.position_size > 0 ? close - atrValue : close + atrValue
        "Open"      => strategy.position_size > 0 ? open - atrValue : open + atrValue
        => strategy.position_size > 0 ? swingLow - atrValue : swingHigh + atrValue
else if trailMethod == "Percent" // Determine percentage trailing stop price based on price source
    float percentMulti = strategy.position_size > 0 ? (100 - trailPercent) / 100 : (100 + trailPercent) / 100
    next_trailPrice := switch trailSource
        "Close"     => close * percentMulti
        "Open"      => open * percentMulti
        => strategy.position_size > 0 ? swingLow * percentMulti : swingHigh * percentMulti

// Check for trailing stop update
if strategy.position_size != 0 and barstate.isconfirmed
    // Trail long stop ONLY IF temp trailPrice is not set or is a higher price
    if (next_trailPrice > trailPrice or na(trailPrice)) and strategy.position_size > 0
        trailPrice := next_trailPrice
        // Trigger alert
        alert(message="Trailing Stop updated for " + syminfo.tickerid + ": " + str.tostring(trailPrice, "#.#####"), freq=alert.freq_once_per_bar_close)
    // Trail short stop ONLY IF temp trailPrice is not set or is a lower price
    if (next_trailPrice < trailPrice or na(trailPrice)) and strategy.position_size < 0
        trailPrice := next_trailPrice
        // Trigger alert
        alert(message="Trailing Stop updated for " + syminfo.tickerid + ": " + str.tostring(trailPrice, "#.#####"), freq=alert.freq_once_per_bar_close)

// Draw data to chart
plot(strategy.position_size != 0 ? trailPrice : na, color=color.red, title="Trailing Stop")

// Exit trade if stop is hit
strategy.exit(id="Trail Exit", from_entry="Trade", limit=na, stop=trailPrice)

//if (strategy.position_size > 0 and close < trailPrice) or (strategy.position_size < 0 and close > trailPrice)
//    strategy.close("Trade")

Overview

PineScriptMastery executes a single mock trade in the chosen direction starting at a user-defined timestamp. The trailing stop is calculated using either Average True Range or percentage offsets anchored to swing highs and lows, candle opens, or closes. Stop levels only ratchet in a favorable direction as price advances. The script plots levels directly on the price chart. It serves as an implementation template rather than an automated entry signal generator.

Details

Published by

Web3Degenerate on GitHub

Type

Strategy, Pine Script v5

Draws

On the price chart

Category

Volatility & bands, Support & resistance

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Trade DirectionstringLongtradeType
Trail SourcestringLows/HighstrailSource
Trail MethodstringATRtrailMethod
Trail Percentfloat10trailPercent
Lookbackint7swingLookback
ATR Periodint14atrPeriod
ATR Multiplierfloat1.0atrMultiplier
Bar Timetimetimestamp("01 Jan 2021 13:30 +0000")barTime
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

257 stars

This overlay strategy is built for ES futures on the one-minute chart. It plots a volume-weighted moving average of price opens and standard-deviation bands at Fibonacci ratios, plus a second longer volume-weighted average from a higher-timeframe open. Call an

Strategy v5 Volatility & bandsMoving averages
Updated 6 weeks ago · None stated GitHub repository of ES Futures 1M No Repaint

Daily Bias + FVG Strategy

by TradersPost
218 stars

This overlay strategy plots previous-day high and low, the daily open, and fair value gap zones on the price chart. It takes entries on a selectable timeframe when the FVG requirement and an optional session window allow them, then uses an ATR or fixed pip sto

Strategy v6 SMC / ICT / price actionSupport & resistance Repaints
Updated 3 months ago · None stated GitHub repository of Daily Bias + FVG Strategy
106 stars

This overlay strategy plots a two-timeframe Ichimoku setup on the price chart, with Tenkan, Kijun, Chikou, and Kumo from a base higher timeframe and an optional highest-timeframe cloud. It allows two entries in the same direction and uses ATR-based trailing st

Strategy v4 TrendVolatility & bands
Updated 2 years ago · GPL-3.0 GitHub repository of 2Tier Ichimoku Pyramiding [Takazudo]

KC15

by benso87
24 stars

KC15 is a price-chart strategy that configures two moving averages, a Bollinger Band Width Percentile filter, and PMARP entry and exit thresholds for long and short trades. Users can switch each average between SMA and EMA, set lengths and colors, and toggle l

Strategy v5 Moving averagesVolatility & bands
Updated 4 years ago · MPL-2.0 GitHub repository of KC15

This strategy implements a multi-stage trend following system inspired by John W. Seykota. It generates long and short entries when price breaks above or below Donchian channels of specified length. Each entry adds a unit sized to risk a fixed percentage of cu

Strategy v6 TrendVolatility & bands
Updated 11 months ago · None stated GitHub repository of Seykota Alt 29: Multi-Stage Scaling
11 stars

Calculates upper and lower Donchian Channel bands over a customizable lookback length and plots them on the main price chart. At a specified exchange hour, the strategy places a long buy stop order at the upper Donchian Channel level. Unfilled pending orders a

Strategy v6 BreakoutSupport & resistance
Updated 5 months ago · Apache-2.0 GitHub repository of Estrategia Donchian Breakout

More strategys

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers