Strategy · Pine Script v5 · On the chart

Mean Reversal Portfolio

by imzeeshan

This strategy combines five selectable mean-reversion and swing trading sub-strategies into a unified system.

View on GitHub

GitHub stars3on the repository
Pine versionv5runs as is
Lines of code100
Settings9inputs
LicenceMIT
Last update2 years ago8 Jul 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

100 lines of Pine Script v5 from strategies/mean-reversal/MeanReversalPortfolio/scripts/MeanReversalPortfolioStrategy.pinescript, published under MIT. Keep the author's credit and licence lines when you reuse it.

MeanReversalPortfolioStrategy.pinescript
//@version=5
//@Author: @GeorgeFreelanceDeveloper, @LucyFreelanceDeveloper
strategy("MeanReversalPortfolio", overlay=true, margin_long=100, margin_short=100, default_qty_type=strategy.percent_of_equity, default_qty_value=100)

// ********************************
// User defined inputs
// ********************************

var G_BASIC_SETTINGS = "Basic settings"
var G_FILTER_SETTINGS = "Filter settings"
var G_TIME = "Time settings"


enableStrategy1 = input.bool(defval = true, title = "Enable strategy 1", tooltip = "The first swing trading strategy involves entering when the price has dropped from a recent high and selling on strength.",  group = G_BASIC_SETTINGS)
enableStrategy2 = input.bool(defval = true, title = "Enable strategy 2", tooltip = "The second strategy is known as Turnaround Tuesday and involves buying at the close on Monday if the close is lower for the second day in a row.",  group = G_BASIC_SETTINGS)
enableStrategy3 = input.bool(defval = true, title = "Enable strategy 3", tooltip = "The third swing trading strategy is a simple mean reversion strategy that involves buying when the close is lower than the low of the previous 5 trading days.",  group = G_BASIC_SETTINGS)
enableStrategy4 = input.bool(defval = true, title = "Enable strategy 4", tooltip = "The fourth trading strategy is based on volatility and involves buying when today's range is lower than the daily range of the previous 6 trading days and the close is above the 200-day moving average.",  group = G_BASIC_SETTINGS)
enableStrategy5 = input.bool(defval = true, title = "Enable strategy 5", tooltip = "The fifth and final swing trading strategy involves buying on a weak day when the price has set a new ten-day high earlier in the trading session.",  group = G_BASIC_SETTINGS)


enableFilter = input.bool(defval = true, title = "Enable filter", tooltip = "Filter is close price is above 200 day simple moving average of benchmark",  group = G_FILTER_SETTINGS)
benchmarkSymbol = input.symbol(defval = "SPX", title = "Benchmark symbol", group = G_FILTER_SETTINGS)

fromDateTime = input.time(defval = timestamp("2012-01-01T01:01+0000"), title = "From Date and time", group = G_TIME) 
toDateTime = input.time(defval = timestamp("9999-01-01T01:01+0000"), title = "To Date and time", group = G_TIME)


// ********************************
// Functions
// ********************************
tradeDateIsAllowed() => time >= fromDateTime and time <= toDateTime

strategy1() =>
    // Calculate the Average of High minus Low over the Last 25 Days
    len = 25
    avgHighLow = ta.sma(high-low, len)

    // Calculate the IBS (Internal Bar Strength) Indicator:
    ibs = (close - low) / (high - low)

    // Calculate a band 2.5 times lower than tthe high over the last 10 days by using average from point number 1
    lowerBand = ta.highest(10) - avgHighLow * 2.5
    enableStrategy1 ? close < lowerBand and ibs < 0.3 : false

strategy2() =>
    monday = dayofweek == dayofweek.monday
    today_close_lower_than_friday_close = close < close[1]
    friday_close_lower_than_thursday_close = close[1] < close[2]
    enableStrategy2 ? monday and today_close_lower_than_friday_close and friday_close_lower_than_thursday_close : false   

strategy3() =>
    lowerChannel = ta.lowest(low[1], 5)
    enableStrategy3 ?  close <= lowerChannel : false

strategy4() =>
    // Calculate the lowest range of the previous 6 trading days
    lowestRange = ta.lowest(high - low, 6)

    // Calculate the 200-day moving average
    ma200 = ta.sma(close, 200)

    // Entry condition: Today's range is the lowest of the last 6 days AND close is above the 200-day MA
    enableStrategy4 ? (lowestRange == high - low) and (close > ma200) : false

strategy5() =>
    // Calculate the highest high of the last ten days
    highestHigh = ta.highest(high[1], 10)


    // Calculate the IBS indicator
    ibs = (close - low) / (high - low)

    // Entry condition: Today's high is higher than the previous high of the last ten days AND IBS is below 0.15
    enableStrategy5 ? high >= highestHigh and ibs < 0.15 : false


// **********************************
// Perform calculations and analysis
// **********************************

// Filter
benchmarkSymbolClose = request.security(benchmarkSymbol,"1D", close)
filter = enableFilter ? benchmarkSymbolClose[1] >= ta.sma(source = benchmarkSymbolClose, length = 200) : true

buyCondition = (strategy1() or strategy2() or strategy3() or strategy4() or strategy5()) and filter and tradeDateIsAllowed()
sellCondition = close > high[1]

// ********************************
// Draw outputs
// ********************************
//plot(strategy.equity, title="equity", color=color.red, linewidth=2, style=plot.style_areabr)

// ********************************
// Manage trade
// ********************************
if (buyCondition)
    strategy.entry("My Long Entry Id", strategy.long)

if (sellCondition)
    strategy.close("My Long Entry Id")

Overview

Mean Reversal Portfolio generates entry signals based on conditions like Internal Bar Strength drops, consecutive lower closes into Tuesday, multi-day channel breakdowns, volatility range contractions, or weak closes after new highs. A global trend filter can restrict entries to periods when a benchmark index trades above its 200-day moving average. Inputs allow enabling or disabling individual sub-strategies and defining a date window. The script overlays signals on the main price chart, though it operates without standard stop-loss exits.

Details

Published by

imzeeshan on GitHub

Type

Strategy, Pine Script v5

Draws

On the price chart

Category

Mean reversion, Trend

Markets

Stocks, Indices

Timeframes

H4 and above, M15-H1

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
Enable strategy 1booltrueenableStrategy1
Enable strategy 2booltrueenableStrategy2
Enable strategy 3booltrueenableStrategy3
Enable strategy 4booltrueenableStrategy4
Enable strategy 5booltrueenableStrategy5
Enable filterbooltrueenableFilter
Benchmark symbolsymbolSPXbenchmarkSymbol
From Date and timetimetimestamp("2012-01-01T01:01+0000")fromDateTime
To Date and timetimetimestamp("9999-01-01T01:01+0000")toDateTime
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]
285 stars

Mean Reversion Strategy is an overlay strategy that identifies pullbacks using a long-term EMA, RSI, and candlestick patterns. It generates long signals when a bullish engulfing candle forms below the EMA while RSI is oversold, and short signals when a bearish

Strategy v4 Mean reversionCandlestick patterns
Updated 3 years ago · None stated GitHub repository of Mean Reversion Strategy

8 Day Run

by hasnocool
106 stars

Inspired by Linda Raschke's strategy for T-note futures, this script identifies extended trends where price remains on one side of a 5-period SMA for more than eight consecutive bars. It enters long on the first pullback below the SMA following an eight-bar bu

Strategy v4 TrendMoving averages
Updated 2 years ago · GPL-3.0 GitHub repository of 8 Day Run

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
53 stars

This strategy identifies long entry opportunities based on short-term price pullbacks below a major trend filter. It enters long when three consecutive lower closes occur below the 200-period simple moving average, followed by the current bar closing back abov

Strategy v6 TrendMoving averages
Updated 2 months ago · MPL-2.0 GitHub repository of Ivan Scherman Pattern - TP/SL

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