Indicator · Pine Script v5 · On the chart

ATR-SB Algo

by TheMikerik· code credited to MikerikDev

This indicator tracks market trends using an ATR trailing line derived from close prices and a risk multiplier, inspired by the UT Bot algorithm.

View on GitHub

GitHub stars3on the repository
Pine versionv5runs as is
Lines of code148
Settings13inputs
LicenceNone statedfile: MPL-2.0
Last update1 year ago12 Apr 2025

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

148 lines of Pine Script v5 from src/indicator.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

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

//@version=5
  indicator("ATR-SB Algo", overlay = true)
//Last published version: 406
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}

// ~~ TIPS
TIP_risk       = "Possibility to manage the risk you are willing to take. Generally speaking of RISK, the higher is the number you select the less risky the positions will become. For ATR it is exact opposite. The lower is the number you select the less risky the position will become. Default values are set to RISK 10 and ATR 10. Feel free to experiment with it :)"
TIP_trendlines = "You can either display or hide the thick trendline above the filled area. The trendline is bullish if it is below the price action. In another case, if the trendline is above the price action, it is bearish."
TIP_sb_candle  = "Sell buy candle is located in the crossover of this indicator's trendline and price action. This option just highlights that candle. This is also the location where the sell/buy signals appear."
TIP_filling    = "This shows the filled area in between a price action and a highlighted trendline."
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}

// ~~ INPUTS
RISK = input.int(defval = 6, title = "Risk", minval = 1, group = "Risk Management", inline = "risk mngmn")
ATR  = input.int (defval = 10, title = "ATR", minval = 1, group = "Risk Management", inline = "risk mngmn", tooltip = TIP_risk)

TRENDLINES = input.bool(defval = true, title="Trend Signals", inline = "trend", group = "Trendlines")
SHOW_ABOVE = input.color(defval = color.green, title="", inline = "trend", group = "Trendlines")
SHOW_BELOW = input.color(defval = color.red, title="", inline = "trend", group = "Trendlines", tooltip = TIP_trendlines)

SB_CANDLE       = input.bool( defval = true, title = "SB candle", inline = "sb", group = "Sell/Buy Candle")
SB_CANDLE_COLOR = input.color(defval = color.white, title = "", inline = "sb", group = "Sell/Buy Candle", tooltip = TIP_sb_candle)

FILLING    = input.bool(defval = true, title="", inline = "fill", group = "Trend Coloring")
FILL_ABOVE = input.color(defval = color.green, title="Bullish", inline = "fill", group = "Trend Coloring")
FILL_BELOW = input.color(defval = color.red, title="Bearish", inline = "fill", group = "Trend Coloring", tooltip = TIP_filling)

SB_LABEL   = input.bool(defval = true, title = "Show labels"    , group = "Labels")
SL_LABEL   = input.bool(defval = true, title = "Show stop loss" , group = "Labels")
TREND_SWAP = input.bool(defval = true, title = "Show trend swap", group = "Labels")
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}

// ~~ INITIAL VARIABLES
_src = close
_atr = ta.atr(ATR)
_modified_atr = RISK * _atr
_invisible = color.rgb(0, 0, 0, 100)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}

// ~~ FUNCTIONS
main_logic( _input ) =>
    _result = 0.0

    if close > _input and close[1] > _input
        _result := math.max(_input, close - _modified_atr)
    else if close < _input and close[1] < _input
        _result := math.min(_input, close + _modified_atr)
    else if close > _input
        _result := close - _modified_atr
    else
        _result := close + _modified_atr

direction_logic( _input ) =>
    _dir = 0
    if      close[1] < _input and close > _input
        _dir := 1
    else if close[1] > _input and close < _input
        _dir := -1
    else
        _dir := 0

trend_break( _xATR, _price, _sb_signal ) =>
    _stop = false
    if _sb_signal == 1 or _sb_signal == -1
        _stop := false
    else if high > _xATR and _price < _xATR
        _stop := true
    else if low < _xATR and _price > _xATR
        _stop := true
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}

// ~~ INDICATOR LOGIC
_xATR       = 0.0
_xATR       := main_logic(_xATR[1])
_sb_signal    = direction_logic(_xATR[1])
_price      = ta.ema(close,1)
_stop_loss  = trend_break(_xATR[1], _price, _sb_signal)

_trend_below_price = _xATR < _price ? true : false
_trend_above_price = _xATR < _price ? false : true

var _sl_counter = 0
_sl_counter := _stop_loss ? _sl_counter + 1 : _sb_signal ? 0 : _sl_counter
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}

// ~~ STOP LOSS, TREND SWAP
var bool _trend_swap = false
if _sb_signal == 1 or _sb_signal == -1
    _trend_swap := true
else
    _trend_swap := false

var bool _sl_triggered   = false
var bool _trigger_candle = false
var bool _first_candle   = true
var bool _print_cross    = true

if _sl_counter == 1 and _stop_loss and _print_cross
    _print_cross := false
    _sl_triggered := true
    _trigger_candle := true
else if not _print_cross and not _trend_swap
    _trigger_candle := false
    _first_candle := false
else if _trend_swap
    if _print_cross
        _trigger_candle := true
        if _trend_below_price and TREND_SWAP
            label.new(bar_index, high, "TREND SWAP", yloc = yloc.abovebar, style = label.style_xcross, size = size.tiny,  textcolor = SHOW_ABOVE, color = SHOW_ABOVE)
        else if TREND_SWAP
            label.new(bar_index, high, "TREND SWAP", yloc = yloc.belowbar, style = label.style_xcross, size = size.tiny,  textcolor = SHOW_BELOW, color = SHOW_BELOW)
    else
        _sl_triggered := false
        _first_candle := true
        _print_cross := true
else
    _trigger_candle := false

_invisible_filling = not _print_cross and not _trend_swap
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}

// ~~ PLOTS, SHAPES AND FILLS
barcolor( (_sb_signal == 1 or _sb_signal == -1) and SB_CANDLE ? SB_CANDLE_COLOR : na )

_atr_color = not TRENDLINES ? na : _sb_signal == 1 or _sb_signal == -1 ? _invisible : _invisible_filling ? _invisible : _trend_above_price ? SHOW_BELOW : SHOW_ABOVE

_xATR_plot  = plot(_xATR,  color = _atr_color, linewidth = 2)
_price_plot = plot(_price, color = _invisible, linewidth = 1)

fill(_xATR_plot, _price_plot, not FILLING ? na : _invisible_filling ? _invisible : _xATR > _price ? color.new(FILL_BELOW, 75) : color.new(FILL_ABOVE, 75))
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}

// ~~ BUY / SELL SIGNALS

buy = _sb_signal ==  1 and SB_LABEL ? 1 : 0
sell = _sb_signal == -1 and SB_LABEL ? 1 : 0
sl_long = _sl_counter == 1 and _stop_loss and _trend_below_price and SL_LABEL ? 1 : 0
sl_short = _sl_counter == 1 and _stop_loss and _trend_above_price and SL_LABEL ? 1 : 0

// ~~ STRATEGY CONNECITON
plotshape(buy,      location = location.belowbar, style = shape.labelup,   color = color.green, size = size.normal, text = "BUY",  textcolor = color.white)
plotshape(sell,     location = location.abovebar, style = shape.labeldown, color = color.red,   size = size.normal, text = "SELL", textcolor = color.white)
plotshape(sl_long,  location = location.belowbar, style = shape.xcross,    color = SHOW_BELOW ,   size = size.tiny,   text = "Stop Loss (long)", textcolor = SHOW_BELOW)
plotshape(sl_short, location = location.abovebar, style = shape.xcross,    color = SHOW_ABOVE ,   size = size.tiny,   text = "Stop Loss (short)", textcolor = SHOW_ABOVE)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}

Overview

ATR-SB Algo plots the trailing line directly on the price chart, identifies bullish and bearish regime flips, highlights signal candles, and provides visual buy/sell markers along with stop loss reference labels. Users can adjust the ATR length, risk factor, candle coloring, and visual fill between the price action and trendline.

Details

Published by

TheMikerik on GitHub

Code credit

MikerikDev, as written in the script's header

Type

Indicator, Pine Script v5

Draws

On the price chart

Category

Trend, Volatility & bands

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
Riskint6RISK
ATRint10ATR
Trend SignalsbooltrueTRENDLINES
SHOW_ABOVEcolorcolor.greenSHOW_ABOVE
SHOW_BELOWcolorcolor.redSHOW_BELOW
SB candlebooltrueSB_CANDLE
SB_CANDLE_COLORcolorcolor.whiteSB_CANDLE_COLOR
FILLINGbooltrueFILLING
Bullishcolorcolor.greenFILL_ABOVE
Bearishcolorcolor.redFILL_BELOW
Show labelsbooltrueSB_LABEL
Show stop lossbooltrueSL_LABEL
Show all 13 settings
SettingTypeDefaultVariable
Show trend swapbooltrueTREND_SWAP
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

Chandelier Exit

by everget
948 stars

This indicator plots an ATR-based Chandelier Exit trailing stop on the price chart. It tracks a long stop under recent highs and a short stop above recent lows, then switches direction when price crosses the opposite stop. Buy and sell labels mark those flips.

Indicator v6 Volatility & bandsTrend Repaints
Updated 10 days ago · GPL-3.0 GitHub repository of Chandelier Exit

The Momentum Setup is a multi-indicator visual tool designed for trend and momentum analysis directly on the price chart. It combines Relative Strength Index (RSI), Money Flow Index (MFI), Commodity Channel Index (CCI), Supertrend, and a 250-bar percentage cha

Indicator v5 Oscillators & momentumTrend
Updated 1 year ago · MPL-2.0 GitHub repository of Momentum Setup - Ankush Bajaj Momentum Investing Setup
330 stars

Range Filter [Alorse] is a technical indicator overlay for TradingView designed to filter market volatility and identify price trends. It calculates a smoothed range based on historical volatility using a configurable sampling period and multiplier applied to

Indicator v5 TrendVolatility & bands
Updated 2 months ago · None stated GitHub repository of Range Filter [Alorse]
318 stars

This indicator calculates an ATR trailing stop line derived from the highest high minus an average true range multiple over a specified lookback period. It plots the trailing stop line directly on the price chart and colors price bars based on whether the clos

Indicator v5 TrendVolatility & bands
Updated 2 months ago · MIT GitHub repository of ATR Trailing Stoploss

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 yesterday · MIT GitHub repository of NVDA Trend Ribbon

[RS]Donchian Fans

by ricardosantos79
261 stars

This indicator plots Donchian Channel boundary lines along with dynamic fan projections directly on the price chart. It calculates the highest high, lowest low, and median price over a customizable lookback period. Whenever price establishes a new channel high

Indicator v4 Support & resistanceTrend
Updated 4 years ago · None stated GitHub repository of [RS]Donchian Fans

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