Strategy · Pine Script v5 · On the chart

ATR-SB Algo Strategy

by TheMikerik· code credited to MikerikDev

This strategy plots an ATR trailing trend line on the price chart, built from each close and a risk-scaled average true range.

View on GitHub

GitHub stars3on the repository
Pine versionv5runs as is
Lines of code150
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 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

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

strategy.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
strategy("ATR-SB Algo Strategy", overlay = true)

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}

// ~~ 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
    else
        _sl_triggered := false
        _first_candle := true
        _print_cross := true
else
    _trigger_candle := false

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

// ~~ 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 ENTRY / CLOSE
var bool long_entry = false
var bool short_entry = false

var bool long_close = false
var bool short_close = false

long_entry := _sb_signal ==  1 ? true : false
short_entry := _sb_signal ==  -1 ? true : false

long_close := _sl_counter == 1 and _stop_loss and _trend_below_price ? true : false
short_close := _sl_counter == 1 and _stop_loss and _trend_above_price ? true : false

if (long_close or (_stop_loss and _trend_below_price))
    strategy.close("Long Entry", "Long SL")
if (short_close or (_stop_loss and _trend_above_price))
    strategy.close("Short Entry", "Short SL")
if (long_entry)
    strategy.entry("Long Entry", strategy.long)
if (short_entry)
    strategy.entry("Short Entry", strategy.short)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}

Overview

A close crossing that line marks a buy or sell location. Optional drawing includes a colored trend line, a fill between price and the line, a highlighted crossover candle, and labels for signals, a plotted stop, and trend swaps. Risk and ATR length change the line’s distance from price. No stop-loss order is set by default.

Details

Published by

TheMikerik on GitHub

Code credit

MikerikDev, as written in the script's header

Type

Strategy, Pine Script v5

Draws

On the price chart

Category

Trend, Volatility & bands

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

  • The strategy enters trades without a stop loss

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

330 stars

This strategy calculates Bollinger Bands and Aroon oscillator values to identify mean-reversion opportunities. It enters a long position using full equity when the closing price crosses below the lower Bollinger Band while Aroon Up remains above a user-specifi

Strategy v5 Mean reversionVolatility & bands
Updated 2 months ago · None stated GitHub repository of Bollinger bands + Aroon [Alorse]
257 stars

This overlay strategy targets one-minute ES futures and plots volume-weighted moving-average bands from the open, scaled by a standard-deviation multiple, plus a slower band from ten-minute opens. A higher-timeframe exponential moving average can filter trades

Strategy v6 Moving averagesVolatility & bands
Updated 6 weeks ago · None stated GitHub repository of ES - Futures 1M No Repaint

STRG-BBForce

by harryguiacorn
219 stars

STRG-BBForce is a Bollinger Bands trend-following strategy. It calculates standard Bollinger Bands and tracks directional alignment across the upper, lower, and basis lines. When all three lines slope upward, it opens a long position and closes short positions

Strategy v5 TrendVolatility & bands
Updated 1 year ago · None stated GitHub repository of STRG-BBForce

Nasdaq Prop Firm Strategy

by TradersPost
218 stars

This strategy uses multiple VWAP anchors and a custom Lull indicator to generate buy and sell signals on the Nasdaq price chart. It plots the VWAP trend line and three VWAP anchors with customizable colors and mitigation methods. The Lull indicator produces si

Strategy v6 TrendSupport & resistance Repaints
Updated 3 months ago · None stated GitHub repository of Nasdaq Prop Firm Strategy

This strategy implements a single-layer perceptron machine learning model built from scratch to generate trading signals directly on the price chart. It calculates predictions based on sample size, threshold settings, and optional volatility or volume filters.

Strategy v5 AI / machine learningTrend
Updated 1 year ago · None stated GitHub repository of Machine Learning: Perceptron-Based Strategy [5] (v.3)
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]

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