Strategy · Pine Script v5 · On the chart

Trailing Stop Strategy

by CjHare

This strategy enters long positions when the fast SMA of 10 periods crosses above the slow SMA of 30 periods.

View on GitHub

GitHub stars2on the repository
Pine versionv5runs as is
Lines of code37
Settings3inputs
LicenceApache-2.0
Last update2 years ago4 Aug 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

37 lines of Pine Script v5 from src/strategy/stop-loss.pine, published under Apache-2.0. Keep the author's credit and licence lines when you reuse it.

stop-loss.pine
// SMA Crossover Trailing Stop Loss Strategy
//
// Long Buy trigger:
// - Short SMA, Long SMA crossover
//
// Input configuration
// - trailingStopPercentInput: Trailing stop percentage, minimum 0.1%, increments of 0.1%
// - fastLengthInput: 10; number of periods for the source fast moving average 
// - slowLengthInput: 30; number of periods for the source slow moving average 

//@version=5
strategy("Trailing Stop Strategy", overlay=true)

// Constants
string LONG_POSITION = "Long"

// Input parameters
float   trailingStopPercentInput    = input.float(1.5, title="Trailing Stop Percentage", minval=0.1, step=0.1)
int     fastLengthInput             = input.int(10, minval=1, title="Fast Length")
int     slowLengthInput             = input.int(30, minval=1, title="Slow Length")

// Calculate the stop price by applying the inverse percentage to the price 
float trailingStop = strategy.position_avg_price * (1 - trailingStopPercentInput / 100)

// Long entry: shortMA crosses from under to over the longMA
longEntrySignal() =>
    float fastMA = ta.sma(close, fastLengthInput)
    float slowMA = ta.sma(close, slowLengthInput)
    ta.crossover(fastMA, slowMA)

// On signal, enter a long position
if (longEntrySignal())
    strategy.entry(LONG_POSITION, strategy.long)

// When long position, create an exit using the trailing stop
if (strategy.position_size > 0)
    strategy.exit("Trailing Stop", from_entry=LONG_POSITION, trail_price=trailingStop, trail_offset=na)

Overview

Trailing Stop Strategy calculates the trailing stop price as the position average price multiplied by one minus the trailing stop percentage divided by 100. The strategy exits long positions using a trailing stop mechanism that dynamically adjusts the stop price based on the trailing stop setting. The main inputs allow users to change the trailing stop percentage, fast length, and slow length values. The strategy draws its signals and plots directly on the price chart.

Details

Published by

CjHare on GitHub

Type

Strategy, Pine Script v5

Draws

On the price chart

Category

Trend, Moving averages

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.

Topics

pinescript-indicatorspinescript-strategies

Settings

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

SettingTypeDefaultVariable
Trailing Stop Percentagefloat1.5trailingStopPercentInput
Fast Lengthint10fastLengthInput
Slow Lengthint30slowLengthInput
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

Doge SMA

by hackingthemarkets
474 stars

Doge SMA is a long-only moving-average crossover strategy drawn on the price chart. It calculates a fast and a slow simple moving average of close and enters a long position when the fast average crosses above the slow average, but only inside a user-defined s

Strategy v4 TrendMoving averages
Updated 4 years ago · None stated GitHub repository of Doge SMA

This strategy calculates and plots a fast Exponential Moving Average (EMA) and a slow EMA directly on the main price chart. It enters long trades when the fast EMA crosses above the slow EMA and exits when the fast EMA crosses below the slow EMA. Inputs allow

Strategy v6 TrendMoving averages
Updated today · AGPL-3.0 GitHub repository of Forven S01508 — Simple EMA20/50 Cross
330 stars

2 EMA/SMA + RSI Strategy [Alorse] combines three configurable moving averages with a short-period Relative Strength Index filter. It plots fast, slow, and trend moving averages on the price chart. Long entries trigger when the fast moving average is above the

Strategy v4 TrendOscillators & momentum
Updated 2 months ago · None stated GitHub repository of 2 EMA/SMA + RSI Strategy [Alorse]

Acrypto - Weighted Strategy

by AlbertoCuadra
318 stars

This strategy plots on the price chart and opens long or short positions when a weighted score from MACD, Stochastic RSI, RSI, Supertrend and a moving-average crossover exceeds a user-set trigger. Each component has its own weight and candle delay. Entries can

Strategy v5 TrendOscillators & momentum
Updated 3 years ago · Custom licence GitHub repository of Acrypto - Weighted Strategy
257 stars

This strategy calculates dynamic support and resistance levels using pivot highs and lows alongside a custom smoothed trend filter and a 3-period EMA. It identifies entry opportunities when price breaks out relative to the trend filter and short-term EMA cross

Strategy v5 TrendSupport & resistance Repaints
Updated 6 weeks ago · None stated GitHub repository of 30s - ES 1m Strategy Candle Bar

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