// Description :
// Mean Reversion Channel objective, based on Mean Reversion theory (everything has a tendency to revert back to its mean), is to help visualizing:
// Inner Channel -> Dynamic Support and Resistance
// Outer Channel -> Overbought/Oversold Zone which may signal consolidation phase or potential reversal due to unsustainable move
// The concept of this indicator oriiginally derived from Keltner Channel (The Keltner Channel was first introduced by Chester Keltner in the 1960s. The original formula used simple moving averages (SMA) and the high-low price range to calculate the bands. In the 1980s, a new formula was introduced that used ATR.)
// Instead if using SMA/EMA, this indicator used SuperSmoother MA as it's mean with longer lookback period (default to 200) to get more stable channel line. i also added second level so the indicator will have inner and outer channel
// Details of each filtering type used for mean calculation can be read in Ehlers Technical Papers: "Swiss Army Knife Indicator" and/or his book "Cybernetics Analysis for Stock and Futures"
// Disclaimer:
// Past performance is not an indicator of future results.
// My opinions are my own and do not constitute financial advice in any way whatsoever.
// Nothing published by me constitutes an investment/trading recommendation, nor should any data or Content published by me be relied upon for any investment/trading activities.
// I strongly recommends that you perform your own independent research and/or speak with a qualified investment professional before making any financial decisions.
// Any ideas to further improve this indicator are welcome :)
//************************************************************************************************************
// Functions Start {
//************************************************************************************************************
var pi = 2 * asin(1)
var mult = pi * innermult
var mult2 = pi * outermult
var gradsize = 0.5
var gradtransp = zonetransp
get_tf(_lvl)=>
y = f_resInMinutes()
z = timeframe.period
if(mtf_typ=="Auto")
if y < 1
z := _lvl == 1 ? "1" : _lvl == 2 ? "5" : z
else if y <= 3
z := _lvl == 1 ? "5" : _lvl == 2 ? "15" : z
else if y <= 10
z := _lvl == 1 ? "15" : _lvl == 2 ? "60" : z
else if y <= 30
z := _lvl == 1 ? "60" : _lvl == 2 ? "240" : z
else if y <= 120
z := _lvl == 1 ? "240" : _lvl == 2 ? "D" : z
else if y <= 240
z := _lvl == 1 ? "D" : _lvl == 2 ? "W" : z
else if y <= 1440
z := _lvl == 1 ? "W" : _lvl == 2 ? "M" : z
else if y <= 10080
z := _lvl == 1 ? "M" : z
else
z := z
else
z := _lvl == 1 ? mtf_lvl1 : _lvl == 2 ? mtf_lvl2 : z
z
//-----------------------
// Mean Reversion Channel Function
//-----------------------
get_mrc()=>
v_condition = 0
v_meanline = source
v_meanrange = supersmoother(tr, length)
get_stat(_cond) =>
ret = "Price at Mean Line\n"
if (_cond == 1)
ret := "Overbought (Weak)\n"
else if (_cond == 2)
ret := "Overbought\n"
else if (_cond == 3)
ret := "Overbought (Strong)\n"
else if (_cond == 4)
ret := "Price Near Mean\n"
else if (_cond == 5)
ret := "Price Above Mean\n"
else if (_cond == -1)
ret := "Oversold (Weak)\n"
else if (_cond == -2)
ret := "Oversold\n"
else if (_cond == -3)
ret := "Oversold (Strong)\n"
else if (_cond == -4)
ret := "Price Near Mean\n"
else if (_cond == -5)
ret := "Price Below Mean\n"
ret
//-----------------------
// Chart Drawing Function
//-----------------------
format_price(x) =>
y = tostring(x, "0.00000")
if(x>10)
y := tostring(x, "0.000")
if(x>1000)
y := tostring(x, "0.00")
y
//-----------------------
// Plot Extension
//-----------------------
if(displayline and enable_mtf and mtf_disp_typ == "Always Display")
displayline := false
var line mean = na, line.delete(mean), mean := displayline ? f_PriceLine(meanline, #FFCD00) : na
var line res1 = na, line.delete(res1), res1 := displayline ? f_PriceLine(upband1, color.green) : na
var line sup1 = na, line.delete(sup1), sup1 := displayline ? f_PriceLine(loband1, color.green) : na
var line res2 = na, line.delete(res2), res2 := displayline ? f_PriceLine(upband2, color.red) : na
var line sup2 = na, line.delete(sup2), sup2 := displayline ? f_PriceLine(loband2, color.red) : na
tf2 = not timeframe.isweekly and not timeframe.ismonthly ?
"\n\nTimeframe: "+ tf_2 + "\n\nStatus: " + get_stat(mtf2_condition) + dist_2 + brl : ""
mtf_lbl = title+tf0+tf1+tf2
var label label_mtf = na, label.delete(label_mtf), label_mtf := enable_mtf ? f_MTFLabel(mtf_lbl, meanline) : na
//} Drawing End
The Pine Script you've provided implements a Mean Reversion Channel (MRC) indicator based on Mean Reversion theory. This indicator visualizes dynamic support and resistance levels (inner channel) and overbought/oversold zones (outer channel) to help identify potential consolidation phases or reversals due to unsustainable price movements.
Below, I'll provide an overview of how the script works, followed by suggestions for potential improvements.
Overview of the Mean Reversion Channel (MRC) Indicator
Key Features:
Dynamic Support and Resistance:
Inner Channel: Represents dynamic support and resistance levels that adjust based on the mean-reverting behavior of the price.
Overbought/Oversold Zones:
Outer Channel: Signals potential overbought or oversold conditions, which may indicate consolidation or potential reversals.
Filter Types:
Multiple filtering methods are available for calculating the mean, including SuperSmoother, Ehlers EMA, Gaussian, Butterworth, BandStop, SMA, EMA, and RMA.
Multiple Time Frame (MTF) Analysis:
Enables analysis across different time frames to provide a broader market perspective.
Customizable Visualization:
Options to draw channels, display zones with adjustable transparency, and extend lines for better visualization.
How It Works:
Mean Calculation:
The indicator calculates a mean line using the selected filter type over a specified lookback period (default is 200).
Channel Bands:
Inner Bands: Derived by adding and subtracting a multiple (innermult) of the mean range (e.g., ATR) from the mean line.
Outer Bands: Calculated by adding and subtracting a larger multiple (outermult) to capture overbought and oversold zones.
Conditions:
The script evaluates the position of the current price relative to the mean line and channels to determine the market condition (e.g., Overbought, Oversold, Near Mean).
Visualization:
Plots the mean line and channel bands.
Fills the area between outer bands with color gradients to represent different zones.
Displays multiple time frame analysis labels based on user settings.
Detailed Breakdown of the Script
1. Parameters and Inputs:
MRC Parameters:
source: Price source (default is hlc3).
type: Filter type for mean calculation.
length: Lookback period for calculating the mean (default is 200).
innermult & outermult: Multipliers for inner and outer channels.
Chart Settings:
Options to draw channels, display zones, adjust transparency, and extend lines.
MTF Settings:
Enable/disable multiple time frame analysis.
Choose display type (Always Display or On Hover).
Select time frames (auto or custom levels).
2. Functions:
SAK_smoothing: Implements various smoothing algorithms based on Ehlers' techniques.
supersmoother: Applies SuperSmoother filter for mean calculation.
f_resInMinutes & get_tf: Handle multiple time frame (MTF) logic.
get_mrc: Core function to calculate mean line, channel bands, and conditions.
get_stat: Translates condition codes into human-readable strings.
f_PriceLine & f_MTFLabel: Handle drawing lines and labels on the chart.
3. Calculation and Plotting:
Channel Calculation:
Computes mean line using the selected filter.
Determines upper and lower bands for both inner and outer channels.
Condition Evaluation:
Determines if the price is overbought, oversold, near the mean, etc., based on its position relative to the channels.
Visualization:
Plots mean line and channel bands with customizable styles.
Fills zones between bands with color gradients to indicate different market conditions.
Displays MTF analysis labels based on user preferences.
Suggestions for Improvement
Upgrade to Pine Script v5:
Benefits:
Access to newer features and functions.
Improved performance and efficiency.
Enhanced security and error handling.
Implementation:
Change the version directive from //@version=4 to //@version=5.
Update deprecated functions and syntax as needed.
Optimize Performance:
Reduce Repainting:
Ensure that calculations do not rely on future data points to prevent repainting issues.
Minimize Recalculations:
Cache frequently used calculations or results to avoid redundant computations.
Enhance MTF Functionality:
Interactive Time Frames:
Allow users to dynamically select multiple time frames beyond the two provided.
Visualization Options:
Provide more options for MTF labels, such as positioning and styling.
User Customization:
Flexible Parameters:
Let users adjust more aspects of the channel calculations, such as the gradsize or adding more multiplier levels.
Color Schemes:
Offer a variety of color presets or allow users to customize colors for different zones and lines.
Add Alerts:
Implement alert conditions based on the channel interactions, such as when the price crosses the outer bands or reverts to the mean.
Example:
alertcondition(condition == 3, title="Strong Overbought", message="Price is strongly overbought.")
alertcondition(condition == -3, title="Strong Oversold", message="Price is strongly oversold.")
Include Additional Indicators:
Combine the MRC with other indicators like RSI or MACD to provide more comprehensive analysis.
Example:
Display RSI values when the price enters overbought or oversold zones.
Example: Upgrading to Pine Script v5
Here's how you might start upgrading your script to Pine Script v5. This includes changing the version directive and updating some syntax to comply with v5 standards.
//@version=5
indicator("Mean Reversion Channel - MRI Variant", shorttitle="MRC", overlay=true, format=format.price)
// Rest of your code with necessary syntax updates...
Key Changes in v5:
Replace study with indicator.
Use ta. prefix for trading functions (e.g., ta.sma instead of sma).
Update the security function to request.security for better performance and flexibility.
Your Mean Reversion Channel (MRC) indicator is a robust tool for visualizing dynamic support/resistance and overbought/oversold zones. By upgrading to Pine Script v5, optimizing performance, enhancing MTF analysis, and adding more customization and alert features, you can further improve its functionality and user experience. Additionally, implementing the suggested visualization and documentation enhancements will make the indicator more intuitive and valuable for traders.
Feel free to implement these suggestions incrementally, testing each change to ensure the indicator continues to function as expected.