Strategy · Pine Script v5 · On the chart

ATR Mean Reversion

by hasnocool· code credited to Bcullen175

This strategy identifies mean reversion opportunities using ATR bands on the price chart.

View on GitHub

GitHub stars106on the repository
Pine versionv5runs as is
Lines of code35
Settings5inputs
LicenceGPL-3.0
Last update2 years ago18 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

35 lines of Pine Script v5 from ATR Mean Reversion Strategy V1.pine, published under GPL-3.0. Keep the author's credit and licence lines when you reuse it.

ATR Mean Reversion Strategy V1.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Bcullen175
//@version=5
strategy("ATR Mean Reversion", overlay=true, initial_capital=100000,default_qty_type=strategy.percent_of_equity, default_qty_value=100, commission_type=strategy.commission.percent, commission_value=6E-5) // Brokers rate (ICmarkets = 6E-5)
SLx = input(1.5, "SL Multiplier", tooltip = "Multiplies ATR to widen stop on volatile assests, Higher values reduce risk:reward but increase winrate, Values below 1.2 are not reccomended")
src = input(close, title="Source")
period = input.int(10, "ATR & MA PERIOD")
plot(open+ta.atr(period))
plot(open-ta.atr(period))
plot((ta.ema(src, period)), title = "Mean", color=color.white)
i_startTime     = input.time(title="Start Filter", defval=timestamp("01 Jan 1995 13:30 +0000"), group="Time Filter", tooltip="Start date & time to begin searching for setups")
i_endTime       = input.time(title="End Filter", defval=timestamp("1 Jan 2099 19:30 +0000"), group="Time Filter", tooltip="End date & time to stop searching for setups")
// Check filter(s)
f_dateFilter = time >= i_startTime and time <= i_endTime
atr = ta.atr(period)
// Check buy/sell conditions
var float buyPrice = 0
buyCondition    = low < (open-ta.atr(period)) and strategy.position_size == 0 and f_dateFilter
sellCondition   = (high > (ta.ema(close, period)) and strategy.position_size > 0 and close < low[1]) or high > (open+ta.atr(period))
stopDistance    = strategy.position_size > 0 ? ((buyPrice - atr)/buyPrice) : na
stopPrice       = strategy.position_size > 0 ? (buyPrice - SLx*atr): na
stopCondition   = strategy.position_size > 0 and low < stopPrice
// Enter positions
if buyCondition
    strategy.entry(id="Long", direction=strategy.long)
if buyCondition[1]
    buyPrice := open
// Exit positions
if sellCondition or stopCondition
    strategy.close(id="Long", comment="Exit" + (stopCondition ? "SL=true" : ""))
    buyPrice := na
// Draw pretty colors
plot(buyPrice, color=color.lime, style=plot.style_linebr)
plot(stopPrice, color=color.red, style=plot.style_linebr, offset=-1)
Expand (44 lines)

Overview

ATR Mean Reversion enters long positions when price touches the lower band (open minus ATR) with no open position and within the set time filter. Positions exit on the upper band breach, when price crosses above the EMA, or when price hits the stop loss level calculated as entry price minus SL multiplier times ATR. The main settings adjust the stop loss multiplier, input source, ATR and EMA periods, and define the active trading window. It draws the upper and lower ATR bands along with the EMA mean directly on the price chart. Notable limit is reliance on closing prices for signals and potential for whipsaw in ranging markets.

Details

Published by

hasnocool on GitHub

Code credit

Bcullen175, as written in the script's header

Type

Strategy, Pine Script v5

Draws

On the price chart

Category

Mean reversion, Volatility & bands, Moving averages

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

  • The strategy enters trades without a stop loss

Topics

analysisbtcusdtcryptocurrencydatapandaspythonsimulationtradingtradingview

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
SL Multiplierfloat1.5SLx
Sourcesourceclosesrc
ATR & MA PERIODint10period
Start Filtertimetimestamp("01 Jan 1995 13:30 +0000")i_startTime
End Filtertimetimestamp("1 Jan 2099 19:30 +0000")i_endTime
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

218 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

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 12 days ago · Custom licence GitHub repository of Nexural VWAP Reversion Scaffold
5 stars

Greeffer's Scalping Strategy combines multi-timeframe Exponential Moving Averages, Bollinger Bands, and Donchian Channels to execute dip-buying trades directly on the price chart. It triggers long entries when price dips below both the lower Donchian Channel a

Strategy v5 Moving averagesVolatility & bands
Updated 4 years ago · None stated GitHub repository of Greeffer's Scalping Strategy

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