Strategy · Pine Script v4 · On the chart

Mean Reversion Strategy

by lth-elm

Mean Reversion Strategy is an overlay strategy that identifies pullbacks using a long-term EMA, RSI, and candlestick patterns.

View on GitHub

GitHub stars285on the repository
Pine versionv4older, still runs
Lines of code144
Settings10inputs
LicenceNone statedfile: MPL-2.0
Last update3 years ago16 Mar 2023

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

144 lines of Pine Script v4 from pinestrategies/Quick-Mean-Reversion-Strat.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

Quick-Mean-Reversion-Strat.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © lth_elm

//@version=4
strategy("Mean reversion strategy", overlay=true, margin_long=100, margin_short=100)


// ----- INPUTS -----


// EMA
ema_len = input(200, minval=1, title="EMA Length")
ema = ema(close, ema_len)
plot(ema, title="EMA", color=color.blue)

// RSI
rsi_len = input(14, minval=1, title="RSI Length")
r = rsi(close, rsi_len)

// ATR
tp_sl_mul = input(false,  "──── TP/SL multiplicator")
risk = input(title="Risk (%)", type=input.float, minval=0, defval=1)
risk := risk/100
atr_bars = input( title="ATR Bars", defval=14, minval=1)
stop_mult = input(title=" ▪ Stoploss Multiplicator", type=input.float, defval=3)
tp_mult = input(title=" ▪ Takeprofit Multiplicator", type=input.float, defval=5)
tp1_mult = input(title=" ▪ TP1 Multiplicator", type=input.float, defval=0.75)
tp2_mult = input(title=" ▪ TP2 Multiplicator", type=input.float, defval=1.5)
tp_close = input(title="► TPx close (%)", type=input.float, defval=15)

atr = atr(atr_bars)

plot(tp_close, title="TP Close", display=display.none)
plot(tp1_mult, title="TP1 Mult", display=display.none)
plot(tp2_mult, title="TP2 Mult", display=display.none)


// ----- CONDITIONS -----


bullishEng = open <= close[1] and close > open[1] and open[1] > close[1]
bearishEng = open >= close[1] and close < open[1] and open[1] < close[1]

goLong = bullishEng and close < ema and r[1] < 30
goShort = bearishEng and close > ema and r[1] > 70


// ------ GET IN/OUT A TRADE ------

inLongPosition = strategy.position_size > 0
inShortPosition = strategy.position_size < 0
notInTrade = strategy.position_size == 0


// ----- MANAGE TP/SL -----


// For long
float long_stop_level = na
float long_profit_level = na
long_stop_level := (goLong and notInTrade) ? close - atr * stop_mult : long_stop_level[1]
long_profit_level := (goLong and notInTrade) ? close + atr * tp_mult : long_profit_level[1]

// For short
float short_stop_level = na
float short_profit_level = na
short_stop_level := (goShort and notInTrade) ? close + atr * stop_mult : short_stop_level[1]
short_profit_level := (goShort and notInTrade) ? close - atr * tp_mult : short_profit_level[1]

// Execute buy or sell order
if goLong and notInTrade
    size = (strategy.equity*risk) / abs(close-long_stop_level)
    strategy.entry("long", strategy.long, qty=size, alert_message="entry")
    // strategy.exit("exit", "long", stop=long_stop_level, limit=long_profit_level, alert_message="exit")
    inLongPosition := true
    notInTrade := false
else if goShort and notInTrade
    size = (strategy.equity*risk) / abs(close-short_stop_level)
    strategy.entry("short", strategy.short, qty=size, when=notInTrade, alert_message="entry")
    // strategy.exit("exit", "short", stop=short_stop_level, limit=short_profit_level, alert_message="exit")
    inShortPosition := true
    notInTrade := false


// ----- MULTIPLE TP -----

// Set multiple takeprofit and the stoploss
ticksConversion(x) =>
    strategy.position_size != 0 ? (x / syminfo.mintick) : float(na)

long_sl = abs(strategy.position_avg_price-long_stop_level)
long_tp = abs(strategy.position_avg_price-long_profit_level)
long_tp1 = tp1_mult * long_sl
long_tp2 = tp2_mult * long_sl
if not notInTrade[1] and goLong[1]
    strategy.exit("tp1", "long", qty_percent = tp_close, profit = ticksConversion(long_tp1), loss = ticksConversion(long_sl), alert_message="tp1_breakeven")
    strategy.exit("tp2", "long", qty_percent = tp_close, profit = ticksConversion(long_tp2), loss = ticksConversion(long_sl), alert_message="tp2")
    strategy.exit("exit", "long", qty_percent = 100, profit = ticksConversion(long_tp), loss = ticksConversion(long_sl), alert_message="exit")

short_sl = abs(strategy.position_avg_price-short_stop_level)
short_tp = abs(strategy.position_avg_price-short_profit_level)
short_tp1 = tp1_mult * short_sl
short_tp2 = tp2_mult * short_sl
if not notInTrade[1] and goShort[1]
    strategy.exit("tp1", "short", qty_percent = tp_close, profit = ticksConversion(short_tp1), loss = ticksConversion(short_sl), alert_message="tp1_breakeven")
    strategy.exit("tp2", "short", qty_percent = tp_close, profit = ticksConversion(short_tp2), loss = ticksConversion(short_sl), alert_message="tp2")
    strategy.exit("exit", "short", qty_percent = 100, profit = ticksConversion(short_tp), loss = ticksConversion(short_sl), alert_message="exit")

// Exit or breakeven
longbreakstop = strategy.position_avg_price + 2 * (strategy.position_avg_price*0.001)
shortbreakstop = strategy.position_avg_price - 2 * (strategy.position_avg_price*0.001)

if inLongPosition
    if close > ema // or we can keep our atr multiplicator first objective
        strategy.close("long", alert_message="exit")
    breakeven_level = strategy.position_avg_price + long_tp1 // change if breakeven tpx
    if high > breakeven_level
        strategy.exit("exit", "long", qty_percent = 100, stop=longbreakstop, limit=long_profit_level, alert_message="exit")
        strategy.exit("tp2", "long", qty_percent = tp_close, stop=longbreakstop, profit = ticksConversion(long_tp2), alert_message="tp2")
if inShortPosition
    if close < ema // or we can keep our atr multiplicator first objective
        strategy.close("short", alert_message="exit")
    breakeven_level = strategy.position_avg_price - short_tp1 // change if breakeven tpx
    if low < breakeven_level
        strategy.exit("exit", "short", qty_percent = 100, stop=shortbreakstop, limit=short_profit_level, alert_message="exit")
        strategy.exit("tp2", "short", qty_percent = tp_close, stop=shortbreakstop, profit = ticksConversion(short_tp2), alert_message="tp2")


// ----- Plot TP/SL -----

plot(longbreakstop, color=color.yellow, title="Long Breakeven", display=display.none)
plot(shortbreakstop, color=color.yellow, title="Short Breakeven", display=display.none)

invisible = color.new(color.white, 100)
p_price = plot(strategy.position_avg_price, color=invisible)
p_long_stop = plot(long_stop_level, color=invisible, style=plot.style_linebr, linewidth=1, title="Long SL")
p_long_profit = plot(long_profit_level, color=invisible, style=plot.style_linebr, linewidth=1, title="Long TP")
p_short_stop = plot(short_stop_level, color=invisible, style=plot.style_linebr, linewidth=1, title="Short SL")
p_short_profit = plot(short_profit_level, color=invisible, style=plot.style_linebr, linewidth=1, title="Short TP")

fill(p_long_stop, p_price, color = inLongPosition ? color.red : na)
fill(p_long_profit, p_price, color = inLongPosition ? color.green : na)
fill(p_short_stop, p_price, color = inShortPosition ? color.red : na)
fill(p_short_profit, p_price, color = inShortPosition ? color.green : na)

Overview

Mean Reversion Strategy generates long signals when a bullish engulfing candle forms below the EMA while RSI is oversold, and short signals when a bearish engulfing candle occurs above the EMA while RSI is overbought. Position sizing is calculated dynamically based on a user-defined risk percentage and ATR-based stop loss distance. Exits are managed with customizable ATR-based stop loss and take profit targets, including partial exits. Adjustable inputs control the indicator periods, risk parameters, and take-profit multipliers.

Details

Published by

lth-elm on GitHub

Type

Strategy, Pine Script v4

Draws

On the price chart

Category

Mean reversion, Candlestick patterns, Oscillators & momentum, Trend

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.

Topics

tradingviewdiscord-botwebhookftxbinancebybitapi

Settings

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

SettingTypeDefaultVariable
EMA Lengthint200ema_len
RSI Lengthint14rsi_len
──── TP/SL multiplicatorboolfalsetp_sl_mul
Risk (%)float1risk
ATR Barsint14atr_bars
 ▪ Stoploss Multiplicatorfloat3stop_mult
 ▪ Takeprofit Multiplicatorfloat5tp_mult
 ▪ TP1 Multiplicatorfloat0.75tp1_mult
 ▪ TP2 Multiplicatorfloat1.5tp2_mult
► TPx close (%)float15tp_close
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

ADX + RSI Strat

by hasnocool
106 stars

This strategy combines a 7-period RSI with an ADX filter to trade market regimes on the price chart. When the ADX indicates ranging conditions below a set threshold, it triggers entries on RSI overbought or oversold extremes. By default, the entry logic is inv

Strategy v4 Oscillators & momentumTrend
Updated 2 years ago · GPL-3.0 GitHub repository of ADX + RSI Strat
7 stars

This strategy combines Ichimoku Kinko Hyo components, a Stochastic oscillator, and specific candlestick patterns to generate trade signals. It identifies Kumo twists and range breakouts while evaluating candle body shapes using Fibonacci threshold filters. Tra

Strategy v4 TrendOscillators & momentum
Updated 2 years ago · MIT GitHub repository of Soulevement / Ressaut Strategy

ADX Trend Filter

by latentwill
4 stars

This strategy enters long when a series labeled ADX is above a threshold and RSI is below 40, and enters short when that series is above the threshold and RSI is above 60. Both series are calculated with the RSI function, so the trend filter is not a true ADX.

Strategy v5 TrendOscillators & momentum
Updated 6 days ago · None stated GitHub repository of ADX Trend Filter

Improvisando [Alorse]

by Hugs-4-Bugs
4 stars

This strategy combines candlestick price action with Exponential Moving Average, RSI, and MACD filters to identify short-term trend trades. A long signal occurs when a bullish candle engulfs the previous open while price remains above the EMA, RSI stays below

Strategy v5 TrendOscillators & momentum
Updated 1 year ago · None stated GitHub repository of Improvisando [Alorse]
330 stars

2 EMA/SMA + RSI Strategy [Alorse] combines three configurable moving averages with a short-period Relative Strength Index filter. It plots fast, slow, and trend moving averages on the price chart. Long entries trigger when the fast moving average is above the

Strategy v4 TrendOscillators & momentum
Updated 2 months ago · None stated GitHub repository of 2 EMA/SMA + RSI Strategy [Alorse]

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