Adaptive Gaussian Moving Average for ThinkOrSwim

samer800

Moderator - Expert
VIP
Lifetime
D4li2WK.png


Author Message:
The Adaptive Gaussian Moving Average (AGMA) is a versatile technical indicator that combines the concept of a Gaussian Moving Average (GMA) with adaptive parameters based on market volatility. The indicator aims to provide a smoothed trend line that dynamically adjusts to different market conditions, offering a more responsive analysis of price movements.
Calculation:
The AGMA is calculated by applying a weighted moving average based on a Gaussian distribution. The length parameter determines the number of bars considered for the calculation. The adaptive parameter enables or disables the adaptive feature. When adaptive is true, the sigma value, which represents the standard deviation, is dynamically calculated using the standard deviation of the closing prices over the volatilityPeriod. When adaptive is false, a user-defined fixed value for sigma can be input.
Interpretation:
The AGMA generates a smoothed line that follows the trend of the price action. When the AGMA line is rising, it suggests an uptrend, while a declining line indicates a downtrend. The adaptive feature allows the indicator to adjust its sensitivity based on market volatility, making it more responsive during periods of high volatility and less sensitive during low volatility conditions.
Potential Uses in Strategies:
-- Trend Identification: Traders can use the AGMA to identify the direction of the prevailing trend. Buying opportunities may arise when the price is above the AGMA line during an uptrend, while selling opportunities may be considered when the price is below the AGMA line during a downtrend.

-- Trend Confirmation: The AGMA can be used in conjunction with other technical indicators or trend-following strategies to confirm the strength and sustainability of a trend. A strong and steady AGMA line can provide additional confidence in the prevailing trend.

-- Volatility-Based Strategies: Traders can utilize the adaptive feature of the AGMA to build volatility-based strategies. By adjusting the sigma value based on market volatility, the indicator can dynamically adapt to changing market conditions, potentially improving the accuracy of entry and exit signals.

CODE:
CSS:
#// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
#// © LeafAlgo
#indicator("Adaptive Gaussian Moving Average", overlay=true)
# conerted by Sam4Cok@Samer800    - 05/2023

input BarColor = yes;
input length = 38;                # "Length"
input useHighLowPrice = no;
input adaptive = yes;             # "Adaptive Parameters"
input volatilityPeriod = 20;      # "Volatility Period"
input StandardDeviation = 1.0;    # "Standard Deviation"

#// Calculate Gaussian Moving Average
def hiSrc = if useHighLowPrice then high else close;
def loSrc = if useHighLowPrice then low else close;
def src = if useHighLowPrice then hlc3 else close;

def sigma = if adaptive then stdev(src, volatilityPeriod) else StandardDeviation;

def gma_ = fold i = 0 to length with p do
          p + (((fold r = 0 to i + 1 with s=hiSrc do if s > GetValue(hiSrc,r) then s else GetValue(hiSrc,r)) +
                (fold m = 0 to i + 1 with t=loSrc do if t < GetValue(loSrc,m) then t else GetValue(loSrc,m))) *
                (exp(- power(((i - (length -1)) / (2 * sigma)), 2) / 2)));

def sumOfWeights = fold j = 0 to length with q do
                   q + (exp(-power(((j - (length -1)) / (2 * sigma)), 2) / 2));

def gma1 = (gma_ / sumOfWeights) / 2;
def gma = gma1;

def gmaColor = src >= gma;

plot GaussianMa = gma;    # "Gaussian Moving Average"

GaussianMa.AssignValueColor(if gmaColor then Color.CYAN else Color.MAGENTA);

AssignPriceColor(if !BarColor then Color.CURRENT else
                 if gmaColor then Color.GREEN else Color.RED);

#END of CODE
 
D4li2WK.png


Author Message:
The Adaptive Gaussian Moving Average (AGMA) is a versatile technical indicator that combines the concept of a Gaussian Moving Average (GMA) with adaptive parameters based on market volatility. The indicator aims to provide a smoothed trend line that dynamically adjusts to different market conditions, offering a more responsive analysis of price movements.
Calculation:
The AGMA is calculated by applying a weighted moving average based on a Gaussian distribution. The length parameter determines the number of bars considered for the calculation. The adaptive parameter enables or disables the adaptive feature. When adaptive is true, the sigma value, which represents the standard deviation, is dynamically calculated using the standard deviation of the closing prices over the volatilityPeriod. When adaptive is false, a user-defined fixed value for sigma can be input.
Interpretation:
The AGMA generates a smoothed line that follows the trend of the price action. When the AGMA line is rising, it suggests an uptrend, while a declining line indicates a downtrend. The adaptive feature allows the indicator to adjust its sensitivity based on market volatility, making it more responsive during periods of high volatility and less sensitive during low volatility conditions.
Potential Uses in Strategies:
-- Trend Identification: Traders can use the AGMA to identify the direction of the prevailing trend. Buying opportunities may arise when the price is above the AGMA line during an uptrend, while selling opportunities may be considered when the price is below the AGMA line during a downtrend.

-- Trend Confirmation: The AGMA can be used in conjunction with other technical indicators or trend-following strategies to confirm the strength and sustainability of a trend. A strong and steady AGMA line can provide additional confidence in the prevailing trend.

-- Volatility-Based Strategies: Traders can utilize the adaptive feature of the AGMA to build volatility-based strategies. By adjusting the sigma value based on market volatility, the indicator can dynamically adapt to changing market conditions, potentially improving the accuracy of entry and exit signals.

CODE:
CSS:
#// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
#// © LeafAlgo
#indicator("Adaptive Gaussian Moving Average", overlay=true)
# conerted by Sam4Cok@Samer800    - 05/2023

input BarColor = yes;
input length = 38;                # "Length"
input useHighLowPrice = no;
input adaptive = yes;             # "Adaptive Parameters"
input volatilityPeriod = 20;      # "Volatility Period"
input StandardDeviation = 1.0;    # "Standard Deviation"

#// Calculate Gaussian Moving Average
def hiSrc = if useHighLowPrice then high else close;
def loSrc = if useHighLowPrice then low else close;
def src = if useHighLowPrice then hlc3 else close;

def sigma = if adaptive then stdev(src, volatilityPeriod) else StandardDeviation;

def gma_ = fold i = 0 to length with p do
          p + (((fold r = 0 to i + 1 with s=hiSrc do if s > GetValue(hiSrc,r) then s else GetValue(hiSrc,r)) +
                (fold m = 0 to i + 1 with t=loSrc do if t < GetValue(loSrc,m) then t else GetValue(loSrc,m))) *
                (exp(- power(((i - (length -1)) / (2 * sigma)), 2) / 2)));

def sumOfWeights = fold j = 0 to length with q do
                   q + (exp(-power(((j - (length -1)) / (2 * sigma)), 2) / 2));

def gma1 = (gma_ / sumOfWeights) / 2;
def gma = gma1;

def gmaColor = src >= gma;

plot GaussianMa = gma;    # "Gaussian Moving Average"

GaussianMa.AssignValueColor(if gmaColor then Color.CYAN else Color.MAGENTA);

AssignPriceColor(if !BarColor then Color.CURRENT else
                 if gmaColor then Color.GREEN else Color.RED);

#END of CODE

@samer800 could you make these multi time frame and still color the bars while on the smaller time ? so a 60 min gaussin on a five min chart and color the bars. thank you
 
Last edited by a moderator:
@samer800 could you make these multi time frame and still color the bars while on the smaller time ? so a 60 min gaussin on a five min chart and color the bars. thank you
check the below

CSS:
#// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
#// © LeafAlgo
#indicator("Adaptive Gaussian Moving Average", overlay=true)
# conerted by Sam4Cok@Samer800    - 05/2023
# Update MTF option added by Sam4Cok@Samer800 - 09/2023
input BarColor = yes;
input ShowSignals = yes;
input useChartTimeframe = {Default "Yes", "No"};
input manualTimeframe = AggregationPeriod.FIFTEEN_MIN;
input source   = FundamentalType.CLOSE;
input length = 14;                # "Length"
input adaptive = yes;             # "Adaptive Parameters"
input volatilityPeriod = 20;      # "Volatility Period"
input StandardDeviation = 1.0;    # "Standard Deviation"
input almaSmoothing = no;#, title='Smoothing', minval=1, group = "ALMA Smoothing")
input offset = 0.85;
input sigma1 = 6;

def na = Double.NaN;
def srcChart = Fundamental(source);
def srcTF = Fundamental(source, Period = manualTimeframe);
def hiTF = Fundamental(FundamentalType.HIGH, Period = manualTimeframe);
def loTF = Fundamental(FundamentalType.LOW, Period = manualTimeframe);
def src_;def hi_; def lo_;
Switch (useChartTimeframe) {
Case "Yes" :
    src_ = srcChart;
    hi_ = high;
    lo_ = low;
Case "No" :
    src_ = srcTF;
    hi_  = hiTF;
    lo_  = loTF;
}
def src = src_;
def hi = hi_;
def lo = lo_;
def tr = TrueRange(hi, src, lo);
#pine_alma(series, windowsize, offset, sigma) =>
script ALMA {
  input series = close;
  input windowsize = 9;
  input Offset = 0.85;
  input Sigma = 6;
    def m = Offset * (windowsize - 1);
    def s = windowsize / Sigma;
    def norm  = fold z = 0 to windowsize with CW do
         CW + Exp(-(Sqr(z - m)) / (2 * Sqr(s)));
    def sum  = fold y = 0 to windowsize with WS do
         WS + Exp(-(Sqr(y - m)) / (2 * Sqr(s))) * GetValue(series, windowsize - 1 - y);
    plot ALMA = sum  / norm ;
}

#// Calculate Gaussian Moving Average
def sigma = if adaptive then stdev(src, volatilityPeriod) else StandardDeviation;

def gma_ = fold i = 0 to length  with p do
          p + (((fold r = 0 to i + 1 with s=src do max(s, GetValue(src,r))) +
                (fold m = 0 to i + 1 with t=src do min(t, GetValue(src,m)))) *
                (exp(- power(((i - (length -1)) / (2 * sigma)), 2) / 2)));


def sumOfWeights = fold j = 0 to length with q do
                   q + (exp(-power(((j - (length -1)) / (2 * sigma)), 2) / 2));

def gma1 = (gma_ / sumOfWeights) / 2;
def gma = if almaSmoothing then ALMA(gma1, length,Offset, sigma1) else gma1;
def almaGma = ALMA(gma1[almaSmoothing], length,Offset, sigma1);

def gmaColor = gma >= almaGma;

plot GaussianMa = gma;    # "Gaussian Moving Average"
GaussianMa.SetLineWeight(2);
GaussianMa.AssignValueColor(if gmaColor then Color.CYAN else Color.MAGENTA);

AssignPriceColor(if !BarColor then Color.CURRENT else
                 if gmaColor then Color.GREEN else Color.RED);
#--- Signal
script nATR {
input src = close;
input length = 14;
    def nATR = WildersAverage(src, length);
    plot out = nATR;
}
Script CMO {
input src = close;
input length = 20;
    def curClose = src;
    def prevClose = src[1];
    def inc = if curClose > prevClose then curClose - prevClose else 0;
    def dec = if prevClose > curClose then prevClose - curClose else 0;
    def sumInc = sum(inc, length);
    def sumDec = sum(dec, length);
    def CMO = if sumInc + sumDec == 0 then 0 else (sumInc - sumDec) / (sumInc + sumDec) * 100;
    plot out = CMO;
}
Script nRSI {
input price = close;
input length = 14;
    def NetChgAvg = WildersAverage(price - price[1], length);
    def TotChgAvg = WildersAverage(AbsValue(price - price[1]), length);
    def ChgRatio = if TotChgAvg != 0 then NetChgAvg / TotChgAvg else 0;
    def nRSI = 50 * (ChgRatio + 1);
    plot out = nRSI;
}
def nATR = nATR(tr, 2) > WMA(nATR(tr), length);
def nrsi = nRSI(src, 2) > WMA(nRSI(src), length);
def ChandMom = CMO(src , 2) > WMA(CMO(src), length);
def SigUp = ShowSignals and (gma crosses above almaGma) and nrsi and ChandMom and nATR;
def SigDn = ShowSignals and (gma crosses below almaGma) and !nrsi and !ChandMom and nATR;

AddChartBubble(SigUp, low, "B", Color.CYAN, no);
AddChartBubble(SigDn, high, "S", Color.MAGENTA, yes);


#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
681 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