Strategy · Pine Script v5 · On the chart

ATR Reversion System

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

The ATR Reversion System is a long-only mean-reversion strategy that plots ATR bands around a short-term EMA (20) and a long-term EMA (200) filter on the price chart.

View on GitHub

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

66 lines of Pine Script v5 from advanced-pine-script/9.Strategy-Scripts/18.Kelter-Band-Mean-Reversion-System.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

18.Kelter-Band-Mean-Reversion-System.pine
// This breaks down a Keltner Band Mean Reversion system I've been working on for an equity trading portfolio.

// It's a Daily timeframe long-only mean-reversion system designed to be traded on the U.S. stock market. The system is not finished yet in terms of my overall optimization and portfolio construction process, but this is a great example of how to build a simple but effective mean-reversion trading strategy in Pine.

// It's inspired by information from Nick Radge, a reputable and highly talented trend-follower who has also designed some very robust mean-reversion strategies.

// 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
strategy("ATR Reversion System", 
     overlay=true, 
     currency=currency.USD,
     initial_capital=100000, 
     default_qty_type=strategy.percent_of_equity, 
     default_qty_value=100, 
     commission_type=strategy.commission.cash_per_order, 
     commission_value=9.95)

// Get user input
i_EmaLongLength     = input.int(title="Long-term EMA", defval=200)
i_EmaShortLength    = input.int(title="Short-term EMA Length", defval=20)
i_ATRPeriod         = input.int(title="ATR Period", defval=5)
i_ATRBand           = input.float(title="ATR Band Distance", defval=1)
i_ATRStretch        = input.float(title="ATR Buy Stretch", defval=1)
i_SellBand          = input.string(title="Sell At Band:", defval="Middle", options=["Top", "Middle", "Bottom"])
i_SellSrc           = input.source(title="Sell Price Source", defval=high)

// Get indicator values
emaLongTerm     = ta.ema(close, i_EmaLongLength)
emaShortTerm    = ta.ema(close, i_EmaShortLength)
atrValue        = ta.atr(i_ATRPeriod)

// Get ATR bands
atrBandTop = emaShortTerm + (atrValue * i_ATRBand)
atrBandBot = emaShortTerm - (atrValue * i_ATRBand)

// Define price stretch
float buyLimitPrice = na

// Check setup conditions = bar close is below ATR band, above long-term EMA
setupCondition = close < atrBandBot and low > emaLongTerm

// Clear any pending limit orders
strategy.cancel_all()

// Enter trades on next bar after setup condition is met
if setupCondition
    buyLimitPrice := low - (atrValue * i_ATRStretch)
    strategy.entry("Long", strategy.long, limit=buyLimitPrice)

// Get sell price
sellPrice = switch i_SellBand
    "Top"       => atrBandTop
    "Middle"    => emaShortTerm
    "Bottom"    => atrBandBot

// Exit trades
if i_SellSrc >= sellPrice or close < emaLongTerm
    strategy.close("Long", comment="Exit trade")

// Draw data to chart
plot(emaLongTerm, "EMA Filter", color.red, 2)
plot(emaShortTerm, "ATR Band Middle", color.blue)
plot(atrBandBot, "ATR Band Bottom", color=color.green)
plot(atrBandTop, "ATR Band Top", color=color.new(color.gray, 75))
plot(setupCondition ? buyLimitPrice : na, "Buy Limit", color.lime, 1, plot.style_cross)

Overview

ATR Reversion System signals entries by checking if the close is below the bottom ATR band and above the long EMA, then places a limit buy order stretched below the low by the ATR stretch value. Exits occur when the sell price source reaches the selected band (top, middle, or bottom) or when the close drops below the long EMA. Main settings control the ATR period, band distance, buy stretch, sell band type, and price source. It draws all elements on the price chart but has no stop loss.

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

Stocks

Timeframes

H4 and above

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
Long-term EMAint200i_EmaLongLength
Short-term EMA Lengthint20i_EmaShortLength
ATR Periodint5i_ATRPeriod
ATR Band Distancefloat1i_ATRBand
ATR Buy Stretchfloat1i_ATRStretch
Sell At Band:stringMiddlei_SellBand
Sell Price Sourcesourcehighi_SellSrc
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

228 stars

The Mean Reversion Strategy Template calculates a baseline mean using SMA, EMA, or VWAP alongside upper and lower deviation bands based on standard deviation, ATR, or percentage offsets. It generates long and short entries when price touches, bounces from, or

Strategy v6 Mean reversionMoving averages
Updated 3 months ago · None stated GitHub repository of Mean Reversion Strategy Template
106 stars

This strategy backtests a long Bollinger Band deal on the price chart for 3Commas-style bots. It plots short and long simple moving averages, offset bands, and the average entry price of the open deal. A long starts when price crosses the lower band inside a c

Strategy v4 Volatility & bandsMoving averages
Updated 2 years ago · GPL-3.0 GitHub repository of 3Commas Bollinger Strategy

Bollinger Bands Strategy

by cklose2000
105 stars

This strategy generates buy and sell signals based on Bollinger Band crossovers combined with a simple moving average trend filter. It enters a long position when price crosses above the lower band while trading above the SMA filter line, and enters a short po

Strategy v5 Volatility & bandsMoving averages
Updated 1 year ago · None stated GitHub repository of Bollinger Bands Strategy

Bollinger Bands Strategy

by TWODS-CAPITAL
37 stars

This strategy executes trades based on price interactions with standard Bollinger Bands plotted on the price chart. It calculates a simple moving average basis line along with upper and lower standard deviation bands. Long entries are triggered when price cros

Strategy v5 Volatility & bandsMean reversion
Updated 3 years ago · MIT GitHub repository of Bollinger Bands Strategy
9 stars

This strategy scaffold calculates a standard Volume Weighted Average Price (VWAP) alongside upper and lower volatility bands set 1.5 ATRs away. It generates long entry signals when a confirmed bar closes below the lower band and short entry signals when a conf

Strategy v5 Mean reversionMoving averages
Updated 2 weeks ago · Custom licence GitHub repository of Nexural VWAP Reversion Scaffold

More Mean reversion 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