Strategy · Pine Script v5 · On the chart

Stops & Targets

by Web3Degenerate· code credited to ZenAndTheArtOfTrading / www.PineScriptMastery.com

This script demonstrates how to calculate and display ATR-based stop loss and take profit levels directly on the price chart.

View on GitHub

GitHub stars2on the repository
Pine versionv5runs as is
Lines of code121
Settings4inputs
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

121 lines of Pine Script v5 from advanced-pine-script/5.Indicators/17.Displaying-Stops-Targets.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

17.Displaying-Stops-Targets.pine
// How to plot your stops and targets

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

// @version=5
// SINGLE TRADE VERSION
strategy("Stops & Targets", overlay=true)

// Import library
import ZenAndTheArtOfTrading/ZenLibrary/3 as zen

// Get user input
atrMulti   = input.float(title="ATR SL Multiplier", defval=1.0)
riskReward = input.float(title="Risk:Reward", defval=1.0)

// Detect pattern(s)
hammer = zen.isHammer()
star   = zen.isStar()

// Check filters
ema = ta.ema(close, 50)
atr = ta.atr(14)
readyToTrade = not na(ema) and not na(atr)
var int inTrade = 0

// Combine patterns & filters
validLong  = readyToTrade and hammer and close > ema and inTrade == 0
validShort = readyToTrade and star and close < ema and inTrade == 0

// Calculate long stops & targets
longStop = low - (atr * atrMulti) // Stop loss price
longStopDistance = close - longStop // Stop distance in pips
longTarget = close + (longStopDistance * riskReward) // Target price

// Calculate short stops & targets
shortStop = high + (atr * atrMulti) // Stop loss price
shortStopDistance = shortStop - close // Stop distance in pips
shortTarget = close - (shortStopDistance * riskReward) // Target price

// Save stops & targets
var float t_stop = na
var float t_target = na
if (validLong or validShort) and inTrade == 0
    t_stop := validLong ? longStop : shortStop
    t_target := validLong ? longTarget : shortTarget
    inTrade := validLong ? 1 : -1

// Check if long stop or target is hit
if inTrade == 1
    if high >= t_target or low <= t_stop
        inTrade := 0

// Check if short stop or target is hit
if inTrade == -1
    if high >= t_stop or low <= t_target
        inTrade := 0

// Draw signals & data
plot(ema, title="EMA")
plotshape(validLong, style=shape.triangleup, color=color.green, location=location.belowbar, text="Long", title="Long")
plotshape(validShort, style=shape.triangledown, color=color.red, location=location.abovebar, text="Short", title="Short")

// Draw stops & targets
plot(inTrade != 0 ? t_stop : na, style=plot.style_linebr, color=color.red, title="Trade Stop")
plot(inTrade != 0 ? t_target : na, style=plot.style_linebr, color=color.green, title="Trade Target")


Code To Display All Trade Signals:

Copy Code
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ZenAndTheArtOfTrading / www.PineScriptMastery.com
// @version=5
// ALL SIGNALS
indicator("Stops & Targets", overlay=true)

// Import library
import ZenAndTheArtOfTrading/ZenLibrary/3 as zen

// Get user input
atrMulti   = input.float(title="ATR SL Multiplier", defval=1.0)
riskReward = input.float(title="Risk:Reward", defval=1.0)

// Detect pattern(s)
hammer = zen.isHammer()
star   = zen.isStar()

// Check filters
ema = ta.ema(close, 50)
atr = ta.atr(14)
readyToTrade = not na(ema) and not na(atr)

// Combine patterns & filters
validLong  = readyToTrade and hammer and close > ema
validShort = readyToTrade and star and close < ema

// Calculate long stops & targets
longStop = low - (atr * atrMulti) // Stop loss price
longStopDistance = close - longStop // Stop distance in pips
longTarget = close + (longStopDistance * riskReward) // Target price

// Calculate short stops & targets
shortStop = high + (atr * atrMulti) // Stop loss price
shortStopDistance = shortStop - close // Stop distance in pips
shortTarget = close - (shortStopDistance * riskReward) // Target price

// Save stops & targets
var float t_stop = na
var float t_target = na
if validLong or validShort
    t_stop := validLong ? longStop : shortStop
    t_target := validLong ? longTarget : shortTarget

// Draw signals & data
plot(ema, title="EMA")
plotshape(validLong, style=shape.triangleup, color=color.green, location=location.belowbar, text="Long", title="Long")
plotshape(validShort, style=shape.triangledown, color=color.red, location=location.abovebar, text="Short", title="Short")

// Draw stops & targets
plot(validLong or validShort ? t_stop : na, style=plot.style_linebr, color=color.red, title="Trade Stop")
plot(validLong or validShort ? t_target : na, style=plot.style_linebr, color=color.green, title="Trade Target")

Overview

Stops & Targets detects hammer and shooting star candlestick patterns filtered by a 50-period EMA trend. When a setup occurs and no active trade is tracked, it calculates a stop loss using an ATR multiplier and projects a profit target according to the chosen risk-to-reward ratio. The script plots the entry signals, the EMA line, and active stop and target levels.

Details

Published by

Web3Degenerate on GitHub

Code credit

ZenAndTheArtOfTrading / www.PineScriptMastery.com, as written in the script's header

Draws

On the price chart

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
ATR SL Multiplierfloat1.0atrMulti
Risk:Rewardfloat1.0riskReward
ATR SL Multiplierfloat1.0atrMulti
Risk:Rewardfloat1.0riskReward
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

Pin Bar Magic v1

by Alorse
330 stars

This strategy trades price action pin bar patterns aligned with moving average trend alignment on the main price chart. It defines uptrends or downtrends using a fan arrangement of three moving averages (6 EMA, 18 EMA, and 50 SMA). Entry conditions require a b

Strategy v4 Candlestick patternsTrend
Updated 2 months ago · None stated GitHub repository of Pin Bar Magic v1
257 stars

This overlay strategy marks short-term turning points on the price chart and enters SPY option-style trades from them. It plots simple moving averages of highs and lows, draws up and down reversal arrows, and colors bars when a short-term extreme coincides wit

Strategy v5 TrendMoving averages Repaints
Updated 7 weeks ago · None stated GitHub repository of SPY Options Trading - Alert

This strategy calculates and plots smoothed Heikin-Ashi candles directly onto the main price chart using exponential moving averages of open, high, low, and close prices. It enters a long position after three consecutive bullish smoothed candles with sequentia

Strategy v4 TrendMoving averages
Updated 2 years ago · GPL-3.0 GitHub repository of Abdoli's Heikin Ashi Smoothed Buy & Sell Strategy Rev.4

DI Engulfing A002

by ruckard
13 stars

This strategy executes trades based on candlestick engulfing patterns aligned with a 200-period exponential moving average trend filter. It enters long positions when a bullish engulfing candle follows three consecutive bearish candles while price trades above

Strategy v5 Candlestick patternsTrend
Updated 1 year ago · None stated GitHub repository of DI Engulfing A002
7 stars

This strategy combines Ichimoku Kinko Hyo components, a Stochastic oscillator, and specific candlestick patterns to generate trade signals. It identifies Kumo twists and range breakouts while evaluating candle body shapes using Fibonacci threshold filters. Tra

Strategy v4 TrendOscillators & momentum
Updated 2 years ago · MIT GitHub repository of Soulevement / Ressaut Strategy

More Candlestick patterns scripts

Related on ForexR

Trade Your Charts With a Regulated Broker

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

Compare brokers