Gaussian Filter [BigBeluga] for ThinkOrSwim

samer800

Moderator - Expert
VIP
Lifetime
BRH6b4Q.png


Author Message:
The Gaussian Filter - BigBeluga indicator is a trend-following tool that uses a Gaussian filter to smooth price data and identify directional shifts in the market. It provides dynamic signals for entering and exiting trades based on trend changes, helping traders stay aligned with the market's momentum. What sets this indicator apart is its ability to display precise entry and exit points with real-time tracking of percentage price changes, making it ideal for trend-based strategies.

CODE:
CSS:
#// Indicator for TOS
#// © BigBeluga
#indicator("Gaussian Filter [BigBeluga]", overlay = true, max_labels_count = 500)
# Converted by Sam4Cok@Samer800    - 09/2024

input timeframe = AggregationPeriod.MIN;
input CandlesColor = no; #(false, "Candles Color", group = group2)
input showLabels = no;
input length = 50;     # "Length"
input sigma  = 10;     #Hint sigma: Sigma defines the amount of smoothing.
input showLevels = yes; #(true, "Show Levels", inline = "1", group = group2)


def na = Double.NaN;
def last = isNaN(close);
def current = GetAggregationPeriod();
def tf = Max(Current, timeframe);
#// ATR (Average True Range) for level calculation
def tr = TrueRange(high(Period = tf), close(Period = tf), low(Period = tf));
def atr = WildersAverage(tr, 200);
#-- Colors
DefineGlobalColor("up", CreateColor(24,231,162));
DefineGlobalColor("dn", CreateColor(252,124,19));
DefineGlobalColor("dup", CreateColor(9,89,62));
DefineGlobalColor("ddn", CreateColor(113,52,1));
DefineGlobalColor("no", Color.GRAY);

script rising{
    input src = close;
    input len = 20;
        def rising = fold i = 0 to len with p=1 while p do
                     GetValue(src, i) > GetValue(src, i + 1);
        plot out = rising;
}
script falling{
    input src = close;
    input len = 20;
        def falling = fold i = 0 to len with p=1 while p do
                      GetValue(src, i) < GetValue(src, i + 1);
        plot out = falling;
}

#//@returns (float) The smoothed value from the Gaussian filter.
Script gaussian_filter {
input src = close;
input length = 50;
input sigma = 10;
    def pi = Double.Pi;
    def total = fold j = 0 to length with p do
                 p + (exp(-0.5 * power((j - length / 2) / sigma, 2.0))
                                         / sqrt(sigma * 2.0 * pi));
    def sum = fold i = 0 to length with q do
              q + src[i] * ((exp(-0.5 * power((i - length / 2) / sigma, 2.0))
                                         / sqrt(sigma * 2.0 * pi))/total);
    plot out = if sum then sum else Double.NaN;
}
#// Calculate the smoothed Gaussian value
def smoothed  = gaussian_filter(close(Period = tf), length, sigma);
#/ Detect trend changes based on crossover conditions
def condition_up = rising(smoothed, 4);
def condition_dn = falling(smoothed, 4);
def state = {Default "ini", "up", "dn"};
def trend;
Switch (state[1]) {
Case "up":
    state = if condition_dn then state."dn" else state[1];
    trend = 1;
Case "dn":
    state = if condition_up then state."up" else state[1];
    trend = -1;
Default :
    trend = 0;
    state = if condition_up then state."up" else
            if condition_dn then state."dn" else state[1];
}
def change = (trend - trend[1]);
#// Determine the candle color based on trend change if enabled
def col = if hl2(Period = tf) > smoothed and trend<=0 then 0 else
          if hl2(Period = tf) < smoothed and trend>=0 then 0 else trend;
def p2 = smoothed + (Average(hl2(Period = tf), 5) - smoothed)/2;
#/ Plot the Gaussian Filter line
#// Plot markers on the chart for trend change signals
plot FilterUp1 = if condition_up and change then smoothed else na; # "Filter Up", "⦿"
plot FilterDn1 = if condition_dn and change then smoothed else na; # "Filter Dn", "⦿"
plot FilterUp = FilterUp1; # "Filter Up", "⦿"
plot FilterDn = FilterDn1; # "Filter Dn", "⦿"
FilterUp.SetLineWeight(5);
FilterDn.SetLineWeight(5);
FilterUp.SetDefaultColor(GlobalColor("up"));
FilterDn.SetDefaultColor(GlobalColor("dn"));
FilterUp1.SetPaintingStrategy(PaintingStrategy.SQUARES);
FilterDn1.SetPaintingStrategy(PaintingStrategy.SQUARES);
FilterUp1.SetDefaultColor(Color.BLACK);
FilterDn1.SetDefaultColor(Color.BLACK);
FilterUp.SetPaintingStrategy(PaintingStrategy.SQUARES);
FilterDn.SetPaintingStrategy(PaintingStrategy.SQUARES);
#// Gaussian Filter line
plot GaussianFilter = smoothed; # "Gaussian Filter"
GaussianFilter.SetLineWeight(2);
GaussianFilter.AssignValueColor(if col>0 then GlobalColor("up") else
                                if col<0 then GlobalColor("dn") else GlobalColor("no"));

AddCloud(if col[-1] then p2 else na, GaussianFilter, GlobalColor("dup"), GlobalColor("ddn"));

#// Enter/Exit labels

def point; def price; def color_level;
if showLevels {
    if condition_up and change {
        point       = smoothed - atr;
        price       = Round(close(Period = tf), 2);
        color_level = 1;
#        if not na(point)
#            "Exit".draw_label(color.new(colDn, 40), index_dn, point[1],
#            str.tostring(price) + "\n" + str.tostring(percent_change, format.percent), size.small)
   } else if condition_dn and change {
        point       = smoothed + atr;
        price       = Round(close(Period = tf), 2);
        color_level = -1;
#        if not na(point)
#            "Enter".draw_label(color.new(colUp, 40), index_up, point[1],
#            str.tostring(price) + "\n" + str.tostring(percent_change, format.percent), size.small)
    } else {
        point       = point[1];
        price       = price[1];
        color_level = color_level[1];}
    } else {
        point       = na;
        price       = na;
        color_level = na;
}
def percent_change = (close(Period = tf)/price-1);
#/ Signals
#// Enter and Exit Levels
plot lines = if !last and point==point[1] and point then point else na;
lines.SetStyle(Curve.MEDIUM_DASH);
lines.AssignValueColor(if color_level>0 then GlobalColor("up") else
                       if color_level<0 then GlobalColor("dn") else GlobalColor("no"));

#-- Labels
AddChartBubble(showLabels and isNaN(lines) and !isNaN(lines[1]), lines[1],
 (if color_level[1]>0 then "Enter\n" else "Exit\n") + AsDollars(point[1]) + "\n" + AsPercent(percent_change[1]),
                if color_level[1]>0 then GlobalColor("up") else GlobalColor("dn"),
                if color_level[1]>0 then no else yes);

#-- Bar Color
AssignPriceColor(if !CandlesColor then Color.CURRENT else
                 if color_level>0 then Color.CYAN else
                 if color_level<0 then Color.MAGENTA else GlobalColor("no"));

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