Adaptive Mean Reversion Indicator for ThinkOrSwim

samer800

Conversion Expert
VIP
Lifetime
STSFXxm.png


Author Message:
The Adaptive Mean Reversion Indicator is a tool for identifying mean reversion trading opportunities in the market. The indicator employs a dynamic approach by adapting its parameters based on the detected market regime, ensuring optimal performance in different market conditions.

To determine the market regime, the indicator utilizes a volatility threshold. By comparing the average true range (ATR) over a 14-period to the specified threshold, it determines whether the market is trending or ranging. This information is crucial as it sets the foundation for parameter optimization.

The parameter optimization process is an essential step in the indicator's calculation. It dynamically adjusts the lookback period and threshold level based on the identified market regime. In trending markets, a longer lookback period and higher threshold level are chosen to capture extended trends. In ranging markets, a shorter lookback period and lower threshold level are used to identify mean reversion opportunities within a narrower price range.
https://www.tradingview.com/v/UWITlMWj/

CODE:

CSS:
#// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
# https://www.tradingview.com/v/UWITlMWj/
#// © LeafAlgo
#indicator("Adaptive Mean Reversion Indicator", overlay=false)
# Converted and mod by sam4Cok@Samer800    - 06/2023
declare lower;
#// Market Regime Detection
input ColorBars = yes;
input source = close;
input smoothing    = yes;
input smoothingLength = 3;
input LookbackPeriodTrending = 40;
input LookbackPeriodRanging = 20;
input ThresholdLevelTrending = 2.0;
input ThresholdLevelRanging = 1.5;
input atrLength = 14;
input rsiLength = 14;#, "RSI Length")

def na = Double.NaN;
def pos = Double.POSITIVE_INFINITY;
def neg = Double.NEGATIVE_INFINITY;

#// Volatility function
def x = Exp(StDev(Log(close / close[1]), atrLength) * atrLength);
def h = source * Power(x, 2);
def l = source / Power(x, 2);
def vol = 100 * (close - lowest(l, atrLength)) / (highest(h, atrLength) - lowest(l, atrLength));

#// ATR

def len = Min(2000, AbsValue(Floor(106 * (if IsNaN(vol) then 1 else vol / 100))));
def hh = Highest(high, atrLength);
def ll = Lowest(low, atrLength);
def tr = TrueRange(hh, close, ll);
def modATR = (tr + (len - 1) * modATR[1]) / len;
def nATR = ATR(LENGTH = atrLength);
def isTrending = nATR > modATR;

#// Parameter Optimization
def thresholdLevel = if isTrending then ThresholdLevelTrending else ThresholdLevelRanging;

#// Calculate Mean Reversion
def preMean = if isTrending then Average(source, LookbackPeriodTrending) else Average(source, LookbackPeriodRanging);
def mean = if smoothing then ExpAverage(preMean, smoothingLength) else preMean;
def deviation = if isTrending then StDev(source, LookbackPeriodTrending) else StDev(source, LookbackPeriodRanging);
def upperBand = mean + (deviation * thresholdLevel);
def lowerBand = mean - (deviation * thresholdLevel);

#// Real-Time Parameter Adjustment
def adaptiveMean = if isTrending then mean else Average(source, 3);
def adaptiveUpperBand = if isTrending then upperBand else mean + (deviation * thresholdLevel * 0.75);
def adaptiveLowerBand = if isTrending then lowerBand else mean - (deviation * thresholdLevel * 0.75);

#// Plotting
plot AdptMean = adaptiveMean;                # "Adaptive Mean"
plot AdptUpperBand = adaptiveUpperBand;      # "Adaptive Upper Band"
plot AdptLowerBand = adaptiveLowerBand;      # "Adaptive Lower Band"

AdptMean.SetDefaultColor(Color.WHITE);
AdptUpperBand.SetDefaultColor(Color.GREEN);
AdptLowerBand.SetDefaultColor(Color.RED);
AdptMean.SetLineWeight(2);

#// Signal Generation
def isAboveUpperBand = source > adaptiveUpperBand;
def isBelowLowerBand = source < adaptiveLowerBand;
def signal = if isAboveUpperBand then -1 else if isBelowLowerBand then 1 else 0;

#// RSI Calculation

def nRSI = RSI(PRICE = source, LENGTH = rsiLength);

#// Confluence Condition
def confluenceCondition = nRSI > 70 or nRSI < 30;

#// Background Color

AddCloud(adaptiveUpperBand, adaptiveLowerBand, Color.DARK_GRAY);
AddCloud(if signal == -1 and confluenceCondition then pos else na, neg, Color.DARK_GREEN);
AddCloud(if signal == 1 and confluenceCondition then pos else na, neg, Color.DARK_RED);

AssignPriceColor(if !ColorBars then Color.CURRENT else
                 if signal == -1 and confluenceCondition then Color.GREEN else
                 if signal == -1 then Color.DARK_GREEN else
                 if signal == 1 and confluenceCondition then Color.RED else
                 if signal == 1 then Color.DARK_RED else Color.GRAY);
#-- END of CODE
 
STSFXxm.png


Author Message:
The Adaptive Mean Reversion Indicator is a tool for identifying mean reversion trading opportunities in the market. The indicator employs a dynamic approach by adapting its parameters based on the detected market regime, ensuring optimal performance in different market conditions.

To determine the market regime, the indicator utilizes a volatility threshold. By comparing the average true range (ATR) over a 14-period to the specified threshold, it determines whether the market is trending or ranging. This information is crucial as it sets the foundation for parameter optimization.

The parameter optimization process is an essential step in the indicator's calculation. It dynamically adjusts the lookback period and threshold level based on the identified market regime. In trending markets, a longer lookback period and higher threshold level are chosen to capture extended trends. In ranging markets, a shorter lookback period and lower threshold level are used to identify mean reversion opportunities within a narrower price range.
https://www.tradingview.com/v/UWITlMWj/

CODE:

CSS:
#// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
# https://www.tradingview.com/v/UWITlMWj/
#// © LeafAlgo
#indicator("Adaptive Mean Reversion Indicator", overlay=false)
# Converted and mod by sam4Cok@Samer800    - 06/2023
declare lower;
#// Market Regime Detection
input ColorBars = yes;
input source = close;
input smoothing    = yes;
input smoothingLength = 3;
input LookbackPeriodTrending = 40;
input LookbackPeriodRanging = 20;
input ThresholdLevelTrending = 2.0;
input ThresholdLevelRanging = 1.5;
input atrLength = 14;
input rsiLength = 14;#, "RSI Length")

def na = Double.NaN;
def pos = Double.POSITIVE_INFINITY;
def neg = Double.NEGATIVE_INFINITY;

#// Volatility function
def x = Exp(StDev(Log(close / close[1]), atrLength) * atrLength);
def h = source * Power(x, 2);
def l = source / Power(x, 2);
def vol = 100 * (close - lowest(l, atrLength)) / (highest(h, atrLength) - lowest(l, atrLength));

#// ATR

def len = Min(2000, AbsValue(Floor(106 * (if IsNaN(vol) then 1 else vol / 100))));
def hh = Highest(high, atrLength);
def ll = Lowest(low, atrLength);
def tr = TrueRange(hh, close, ll);
def modATR = (tr + (len - 1) * modATR[1]) / len;
def nATR = ATR(LENGTH = atrLength);
def isTrending = nATR > modATR;

#// Parameter Optimization
def thresholdLevel = if isTrending then ThresholdLevelTrending else ThresholdLevelRanging;

#// Calculate Mean Reversion
def preMean = if isTrending then Average(source, LookbackPeriodTrending) else Average(source, LookbackPeriodRanging);
def mean = if smoothing then ExpAverage(preMean, smoothingLength) else preMean;
def deviation = if isTrending then StDev(source, LookbackPeriodTrending) else StDev(source, LookbackPeriodRanging);
def upperBand = mean + (deviation * thresholdLevel);
def lowerBand = mean - (deviation * thresholdLevel);

#// Real-Time Parameter Adjustment
def adaptiveMean = if isTrending then mean else Average(source, 3);
def adaptiveUpperBand = if isTrending then upperBand else mean + (deviation * thresholdLevel * 0.75);
def adaptiveLowerBand = if isTrending then lowerBand else mean - (deviation * thresholdLevel * 0.75);

#// Plotting
plot AdptMean = adaptiveMean;                # "Adaptive Mean"
plot AdptUpperBand = adaptiveUpperBand;      # "Adaptive Upper Band"
plot AdptLowerBand = adaptiveLowerBand;      # "Adaptive Lower Band"

AdptMean.SetDefaultColor(Color.WHITE);
AdptUpperBand.SetDefaultColor(Color.GREEN);
AdptLowerBand.SetDefaultColor(Color.RED);
AdptMean.SetLineWeight(2);

#// Signal Generation
def isAboveUpperBand = source > adaptiveUpperBand;
def isBelowLowerBand = source < adaptiveLowerBand;
def signal = if isAboveUpperBand then -1 else if isBelowLowerBand then 1 else 0;

#// RSI Calculation

def nRSI = RSI(PRICE = source, LENGTH = rsiLength);

#// Confluence Condition
def confluenceCondition = nRSI > 70 or nRSI < 30;

#// Background Color

AddCloud(adaptiveUpperBand, adaptiveLowerBand, Color.DARK_GRAY);
AddCloud(if signal == -1 and confluenceCondition then pos else na, neg, Color.DARK_GREEN);
AddCloud(if signal == 1 and confluenceCondition then pos else na, neg, Color.DARK_RED);

AssignPriceColor(if !ColorBars then Color.CURRENT else
                 if signal == -1 and confluenceCondition then Color.GREEN else
                 if signal == -1 then Color.DARK_GREEN else
                 if signal == 1 and confluenceCondition then Color.RED else
                 if signal == 1 then Color.DARK_RED else Color.GRAY);
#-- END of CODE
Hi,
would you be able to convert this to multi time frame?
 
Hi,
would you be able to convert this to multi time frame?
find below

CSS:
#// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
# https://www.tradingview.com/v/UWITlMWj/
#// © LeafAlgo
#indicator("Adaptive Mean Reversion Indicator", overlay=false)
# Converted and mod by sam4Cok@Samer800    - 06/2023
# Updated - Added MTF option - 08/2023
declare lower;
#// Market Regime Detection
input ColorBars = yes;
input useChartTimeframe =  {default"Yes", "No"};
input manualTimeframe   = AggregationPeriod.FIFTEEN_MIN;
input source = close;
input VolatilityThreshold = {Default "Auto", "Manual"};
input manualVolatilityThreshold = 0.5;
input smoothing    = yes;
input smoothingLength = 3;
input LookbackPeriodTrending = 40;
input LookbackPeriodRanging = 20;
input ThresholdLevelTrending = 2.0;
input ThresholdLevelRanging = 1.5;
input atrLength = 14;
input rsiLength = 14;#, "RSI Length")
input rsiOverbought = 70;
input rsiOversold = 30;

def na = Double.NaN;
def pos = Double.POSITIVE_INFINITY;
def neg = Double.NEGATIVE_INFINITY;

#-- MTF
def c; def h; def l;
Switch (useChartTimeframe) {
case "Yes" :
    c = source;
    h = high;
    l = low;
case "No"  :
    c = close(Period=manualTimeframe);
    h = high(Period=manualTimeframe);
    l = low(Period=manualTimeframe);
}
def tr1 = TrueRange(h, c, l);
#// Volatility function
def logClose = Log(c / c[1]);
def logstDev = StDev(logClose, atrLength) * atrLength;
def x = Exp(logstDev);
def hx = c * Power(x, 2);
def lx = c / Power(x, 2);
def hhx = highest(hx, atrLength);
def llx = lowest(lx, atrLength);
def vol = (c - llx) / (hhx - llx);
def volAvg = 106 * vol ;
#// ATR
def tr = if isNaN(tr1) then h - l else tr1;
def len = if IsNaN(volAvg) then 1 else
          Min(2000, AbsValue(Floor(volAvg)));
def hh = Highest(h, atrLength);
def ll = Lowest(l, atrLength);
def tr2 = TrueRange(hh, c, ll);
def trHL = if isNaN(tr2) then h - l else tr2;
def modATR = (trHL + (len - 1) * modATR[1]) / len;
def nATR = WildersAverage(tr, atrLength);

def isTrending;
Switch (VolatilityThreshold) {
Case "Auto" : isTrending = nATR > modATR;
Case "Manual" : isTrending = nATR > manualVolatilityThreshold;
}
#// Parameter Optimization
def thresholdLevel = if isTrending then ThresholdLevelTrending else ThresholdLevelRanging;

#// Calculate Mean Reversion
def preMean = if isTrending then Average(c, LookbackPeriodTrending) else Average(c, LookbackPeriodRanging);
def mean = if smoothing then ExpAverage(preMean, smoothingLength) else preMean;
def deviation = if isTrending then StDev(c, LookbackPeriodTrending) else StDev(c, LookbackPeriodRanging);
def upperBand = mean + (deviation * thresholdLevel);
def lowerBand = mean - (deviation * thresholdLevel);

#// Real-Time Parameter Adjustment
def adaptiveMean = if isTrending then mean else Average(c, 3);
def adaptiveUpperBand = if isTrending then upperBand else mean + (deviation * thresholdLevel * 0.75);
def adaptiveLowerBand = if isTrending then lowerBand else mean - (deviation * thresholdLevel * 0.75);

#// Plotting
plot AdptMean = adaptiveMean;                # "Adaptive Mean"
plot AdptUpperBand = adaptiveUpperBand;      # "Adaptive Upper Band"
plot AdptLowerBand = adaptiveLowerBand;      # "Adaptive Lower Band"

AdptMean.SetDefaultColor(Color.WHITE);
AdptUpperBand.SetDefaultColor(Color.GREEN);
AdptLowerBand.SetDefaultColor(Color.RED);
AdptMean.SetLineWeight(2);

#// Signal Generation
def isAboveUpperBand = c > adaptiveUpperBand;
def isBelowLowerBand = c < adaptiveLowerBand;
def signal = if isAboveUpperBand then -1 else if isBelowLowerBand then 1 else 0;

#// RSI Calculation

def nRSI = RSI(PRICE = c, LENGTH = rsiLength);

#// Confluence Condition
def confluenceCondition = nRSI > rsiOverbought or nRSI < rsiOversold;

#// Background Color

AddCloud(adaptiveUpperBand, adaptiveLowerBand, Color.DARK_GRAY);
AddCloud(if signal == -1 and confluenceCondition then pos else na, neg, Color.DARK_GREEN);
AddCloud(if signal == 1 and confluenceCondition then pos else na, neg, Color.DARK_RED);

AssignPriceColor(if !ColorBars then Color.CURRENT else
                 if signal == -1 and confluenceCondition then Color.GREEN else
                 if signal == -1 then Color.DARK_GREEN else
                 if signal == 1 and confluenceCondition then Color.RED else
                 if signal == 1 then Color.DARK_RED else Color.GRAY);
#-- END of CODE
 

Join useThinkScript to post your question to a community of 21,000+ developers and traders.

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
515 Online
Create Post

Similar threads

Similar threads

The Market Trading Game Changer

Join 2,500+ subscribers inside the useThinkScript VIP Membership Club
  • Exclusive indicators
  • Proven strategies & setups
  • Private Discord community
  • ‘Buy The Dip’ signal alerts
  • Exclusive members-only content
  • Add-ons and resources
  • 1 full year of unlimited support

Frequently Asked Questions

What is useThinkScript?

useThinkScript is the #1 community of stock market investors using indicators and other tools to power their trading strategies. Traders of all skill levels use our forums to learn about scripting and indicators, help each other, and discover new ways to gain an edge in the markets.

How do I get started?

We get it. Our forum can be intimidating, if not overwhelming. With thousands of topics, tens of thousands of posts, our community has created an incredibly deep knowledge base for stock traders. No one can ever exhaust every resource provided on our site.

If you are new, or just looking for guidance, here are some helpful links to get you started.

What are the benefits of VIP Membership?
VIP members get exclusive access to these proven and tested premium indicators: Buy the Dip, Advanced Market Moves 2.0, Take Profit, and Volatility Trading Range. In addition, VIP members get access to over 50 VIP-only custom indicators, add-ons, and strategies, private VIP-only forums, private Discord channel to discuss trades and strategies in real-time, customer support, trade alerts, and much more. Learn all about VIP membership here.
How can I access the premium indicators?
To access the premium indicators, which are plug and play ready, sign up for VIP membership here.
Back
Top