Indicator · Pine Script v6 · On the chart

Swing Trade ATR

by rubbermetal· code credited to claygrace74

Swing Trade ATR is an indicator that marks Swing L and Swing S labels when a 9-period EMA crosses a 21-period EMA, with a fill between them.

View on GitHub

GitHub stars1on the repository
Pine versionv6current
Lines of code101
Settings8inputs
LicenceMPL-2.0
Last update4 months ago10 Jun 2026

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 indicator, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart, then adjust the settings with the gear icon next to its name.

Source Code

101 lines of Pine Script v6 from Swing Trade Strategy.pine, published under MPL-2.0. Keep the author's credit and licence lines when you reuse it.

Swing Trade Strategy.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © claygrace74

//@version=6
indicator("Swing Trade ATR", shorttitle="Swing", overlay=true)

// ==================== EMA Settings ====================
var ema_group = "EMA Settings"
fast_length = input.int(9, "Fast EMA Length", minval=1, group=ema_group)
slow_length = input.int(21, "Slow EMA Length", minval=1, group=ema_group)

// ==================== ATR Risk Management ====================
var atr_group = "ATR Risk Management"
atr_length       = input.int(14, "ATR Length", minval=1, group=atr_group)
atr_sl_multiplier = input.float(2.0, "ATR Stop Loss Multiplier", minval=0.5, step=0.5, group=atr_group)
atr_tp_multiplier = input.float(3.0, "ATR Take Profit Multiplier", minval=0.5, step=0.5, group=atr_group)

// ==================== Display Settings ====================
var disp_group = "Display Settings"
i_showSignals  = input.bool(true, "Show Entry Signals", group=disp_group)
i_showSLTP     = input.bool(true, "Show SL/TP Levels", group=disp_group)
i_showRR       = input.bool(true, "Show R:R Info Table", group=disp_group)

// ==================================================================================
// Core Calculations
// ==================================================================================
ema_fast = ta.ema(close, fast_length)
ema_slow = ta.ema(close, slow_length)
atr = ta.atr(atr_length)

long_signal  = ta.crossover(ema_fast, ema_slow)
short_signal = ta.crossunder(ema_fast, ema_slow)

bullish = ema_fast > ema_slow

// Track SL/TP from last signal
var float sl_level = na
var float tp_level = na
var float entry_level = na
var bool  lastIsLong = true

if long_signal
    entry_level := close
    sl_level := close - atr * atr_sl_multiplier
    tp_level := close + atr * atr_tp_multiplier
    lastIsLong := true
if short_signal
    entry_level := close
    sl_level := close + atr * atr_sl_multiplier
    tp_level := close - atr * atr_tp_multiplier
    lastIsLong := false

// Check if SL/TP hit
slHit = (lastIsLong and not na(sl_level) and low <= sl_level) or (not lastIsLong and not na(sl_level) and high >= sl_level)
tpHit = (lastIsLong and not na(tp_level) and high >= tp_level) or (not lastIsLong and not na(tp_level) and low <= tp_level)

if slHit or tpHit
    sl_level := na
    tp_level := na
    entry_level := na

// Risk/reward ratio
rr_ratio = atr_tp_multiplier / atr_sl_multiplier

// ==================================================================================
// Plots
// ==================================================================================
pFast = plot(ema_fast, "Fast EMA", color=color.new(color.blue, 0), linewidth=2)
pSlow = plot(ema_slow, "Slow EMA", color=color.new(color.red, 0), linewidth=2)
fill(pFast, pSlow, color=bullish ? color.new(color.green, 85) : color.new(color.red, 85), title="EMA Fill")

// Entry signals
plotshape(i_showSignals and long_signal,  style=shape.triangleup,   location=location.belowbar, color=color.green, text="Swing L", textcolor=color.green, size=size.small, title="Swing Long")
plotshape(i_showSignals and short_signal, style=shape.triangledown, location=location.abovebar, color=color.red,   text="Swing S", textcolor=color.red,   size=size.small, title="Swing Short")

// SL/TP levels
plot(i_showSLTP and not na(sl_level) ? sl_level : na, "Stop Loss", color=color.new(color.orange, 30), style=plot.style_linebr, linewidth=1)
plot(i_showSLTP and not na(tp_level) ? tp_level : na, "Take Profit", color=color.new(color.lime, 30), style=plot.style_linebr, linewidth=1)
plot(i_showSLTP and not na(entry_level) ? entry_level : na, "Entry", color=color.new(color.gray, 50), style=plot.style_linebr, linewidth=1)

// SL/TP hit markers
plotshape(slHit, style=shape.xcross, location=location.absolute, color=color.orange, size=size.tiny, title="SL Hit")
plotshape(tpHit, style=shape.circle, location=location.absolute, color=color.lime, size=size.tiny, title="TP Hit")

// R:R info table
var tbl = table.new(position.top_right, 2, 3, bgcolor=color.new(color.black, 50), border_width=1, border_color=color.new(color.gray, 50))
if i_showRR and barstate.islast
    table.cell(tbl, 0, 0, "ATR", text_color=color.gray, text_size=size.tiny)
    table.cell(tbl, 1, 0, str.tostring(atr, format.mintick), text_color=color.white, text_size=size.tiny)
    table.cell(tbl, 0, 1, "R:R", text_color=color.gray, text_size=size.tiny)
    table.cell(tbl, 1, 1, "1:" + str.tostring(rr_ratio, "#.0"), text_color=color.new(color.lime, 0), text_size=size.tiny)
    table.cell(tbl, 0, 2, "Trend", text_color=color.gray, text_size=size.tiny)
    table.cell(tbl, 1, 2, bullish ? "BULL" : "BEAR", text_color=bullish ? color.green : color.red, text_size=size.tiny)

// ==================================================================================
// Alert Conditions
// ==================================================================================
alertcondition(long_signal,  "Swing Long Signal",  "Fast EMA crossed above slow EMA — swing long entry")
alertcondition(short_signal, "Swing Short Signal", "Fast EMA crossed below slow EMA — swing short entry")
alertcondition(slHit,        "Stop Loss Hit",      "Price hit ATR-based stop loss level")
alertcondition(tpHit,        "Take Profit Hit",    "Price hit ATR-based take profit level")

Overview

After each signal it draws stop loss and take profit lines at ATR multiples from the signal close and clears them when price touches either. An optional table shows the risk to reward ratio. It places no orders. It draws on the price chart.

Details

Published by

rubbermetal on GitHub

Code credit

claygrace74, as written in the script's header

Type

Indicator, Pine Script v6

Draws

On the price chart

Category

Trend, Moving averages, Volatility & bands

Markets

Any symbol

Timeframes

H4 and above

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
Fast EMA Lengthint9fast_length
Slow EMA Lengthint21slow_length
ATR Lengthint14atr_length
ATR Stop Loss Multiplierfloat2.0atr_sl_multiplier
ATR Take Profit Multiplierfloat3.0atr_tp_multiplier
Show Entry Signalsbooltruei_showSignals
Show SL/TP Levelsbooltruei_showSLTP
Show R:R Info Tablebooltruei_showRR
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

318 stars

This indicator plots four customizable moving averages directly on the main price chart using default lengths of 3, 8, 21, and 50 periods. It fills the space between adjacent averages in green or maroon depending on trend alignment. Additionally, it computes B

Indicator v5 Moving averagesTrend
Updated 2 months ago · MIT GitHub repository of Multiple Moving Averages

NVDA Trend Ribbon

by longsurf-ai
277 stars

This indicator plots three exponential moving averages and ATR volatility envelopes on the price chart. It compares the fast and slow EMAs to shade a trend ribbon and marks confirmed upward and downward crossovers with triangle labels. Settings change the thre

Indicator v6 TrendMoving averages
Updated 2 days ago · MIT GitHub repository of NVDA Trend Ribbon

Bollinger Bands Force

by harryguiacorn
219 stars

This indicator modifies standard Bollinger Bands to measure directional trend force based on line alignment. It calculates a simple moving average basis along with upper and lower volatility bands. When all three lines move upward or downward simultaneously, i

Indicator v5 Volatility & bandsTrend
Updated 1 year ago · None stated GitHub repository of Bollinger Bands Force

Adaptive MA Slope

by capissimo
114 stars

This indicator calculates Kaufman's Adaptive Moving Average (KAMA) on a chosen price source and determines trend direction based on the slope across a configurable lookback window. Signals can be filtered by short-term volatility expansion using ATR comparison

Indicator v4 Moving averagesTrend
Updated 1 year ago · None stated GitHub repository of Adaptive MA Slope

More indicators

Trade Your Charts With a Regulated Broker

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

Compare brokers