Regression Indicator [BigBeluga] For ThinkOrSwim

OGK

Member
VIP
The author states: The Regression Indicator is designed to help traders identify trends and potential reversals in price movements. By calculating a regression line and a normalized regression indicator, it provides clear visual signals for market direction, aiding in making informed trading decisions. The indicator dynamically updates with the latest market data, ensuring timely and relevant signals.

8DHrWLP.png

Here is the original Tradingview code:
https://www.tradingview.com/script/rFrilcDi-Regression-Indicator-BigBeluga/

For the new ThinkOrSwim code, you must scroll down to the next post
 
Last edited by a moderator:

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

Regression Indicator
From BigBeluga (owner)
Indicator Overview:
The Regression Indicator is designed to help traders identify trends and potential reversals in price movements. By calculating a regression line and a normalized regression indicator, it provides clear visual signals for market direction, aiding in making informed trading decisions. The indicator dynamically updates with the latest market data, ensuring timely and relevant signals.
https://www.tradingview.com/script/rFrilcDi-Regression-Indicator-BigBeluga/
requesting conversion to TOS. If I had to guess Samer is my guy.
thanks in advance :)
View attachment 24204

Code:
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © BigBeluga

//@version=6
indicator('Regression Indicator  [BigBeluga]', overlay = false, max_bars_back = 500)

// =====================================================================================================================}
// INPUTS
// ====================================================================================================================={

int length = input.int(400, 'Regression Length')
int length1 = input.int(100, 'Regression Normalization')
int length2 = input.int(50, 'Signal Line')

color m_color = #049ef7

// =====================================================================================================================}
// CALCULATIONS
// ====================================================================================================================={

// @function regression_indicator is a Normalized Ratio of Regression Lines with close
regression_indicator(src, length) =>
    sum_x = 0.0
    sum_y = 0.0
    sum_xy = 0.0
    sum_x_sq = 0.0
    distance = 0.0
    // Calculate Sum
    for i = 0 to length - 1 by 1
        sum_x := sum_x + i + 1
        sum_y := sum_y + src[i]
        sum_xy := sum_xy + (i + 1) * src[i]
        sum_x_sq := sum_x_sq + math.pow(i + 1, 2)
        sum_x_sq

    // Calculate linear regression coefficients
    slope = (length * sum_xy - sum_x * sum_y) / (length * sum_x_sq - math.pow(sum_x, 2))
    intercept = (sum_y - slope * sum_x) / length

    // Calculate Regression Indicator
    y1 = intercept + slope
    distance := close - y1
    distance_n = ta.sma((distance - ta.sma(distance, length1)) / ta.stdev(distance, length1), 10)

    [distance_n, y1]


[y, y1] = regression_indicator(close, length)

// Signal Lines
mean = ta.sma(y, length2)
mean1 = ta.ema(y, 5)
// Conditions
cond1 = ta.crossunder(mean1, mean) and y > 0
cond2 = ta.crossover(mean1, mean) and y < 0
cond3 = ta.crossover(y, 0)
cond4 = ta.crossunder(y, 0)


// =====================================================================================================================}
// PLOT
// ====================================================================================================================={
// Candles Colors
color = y > 0 ? color.from_gradient(y, 0, 1, na, m_color) : color.from_gradient(y, -1, 0, chart.fg_color, na)

barcolor(color)
plotcandle(open, high, low, close, 'Color Candles', color = color, wickcolor = color, bordercolor = color, force_overlay = true)

// Plot Regression Line
plot(series = y1, title = 'Regression Line', color = color, linewidth = 2, force_overlay = true)
// Plot Regression Indicator
p1 = plot(series = y, title = 'Regression Indicator', color = color, linewidth = 1)

p0 = plot(series = 0, title = 'Zero Line', color = color, linewidth = 1)

// Fill Color Regression Indicator
fill(p1, p0, 2.5, 0, m_color, na, title = 'Upper Fill')
fill(p1, p0, 0, -2.5, na, chart.fg_color, title = 'Lower Fill')

// Signal Line
plot(mean, color = color.rgb(3, 100, 165, 52), linewidth = 2)

// Arrow Trend Direction
var txt = ''
switch
    cond3 =>
        txt := '➚'
        txt
    cond4 =>
        txt := '➘'
        txt

if barstate.islast
    label.delete(label.new(x = bar_index + 3, y = y1, text = txt, style = label.style_label_center, color = color(na), textcolor = color, size = size.huge, force_overlay = true)[1])

// Reversion Signals
if cond1
    label.new(x = bar_index, y = high, text = '◓', style = label.style_label_down, color = color(na), textcolor = chart.fg_color, size = size.large, force_overlay = true)

if cond2
    label.new(x = bar_index, y = low, text = '◒', style = label.style_label_up, color = color(na), textcolor = m_color, size = size.large, force_overlay = true)

// Trend Signals
plotchar(cond3 ? 0 : na, 'TrendUp', '⦿', location = location.absolute, size = size.small, color = #0364a5)
plotchar(cond3 ? close : na, 'TrendUp', '⦿', location = location.absolute, size = size.small, color = #0364a5, force_overlay = true)

plotchar(cond4 ? 0 : na, 'TrendDn', '⦿', location = location.absolute, size = size.small, color = chart.fg_color)
plotchar(cond4 ? close : na, 'TrendDn', '⦿', location = location.absolute, size = size.small, color = chart.fg_color, force_overlay = true)

// =====================================================================================================================}
check below:

Upper Study:

CSS:
#// Indicator for TOS
#// © BigBeluga
#indicator("Regression Indicator [BigBeluga]", overlay = false, max_bars_back = 500)
# Converted by Sam4Cok@Samer800     - 03/2025
input colorBars = yes;
input showLabel = yes;
input length      =   400; #, "Regression Length")
input length1     =   100; #, "Regression Normalization")
input length2     =   50; #,  "Signal Line")

def na = Double.NaN;
def last = IsNaN(close);
#// @function regression_indicator is a Normalized Ratio of Regression Lines with close
script regression_indicator {
    input src = close;
    input length = 400;
    input length1 = 100;
    def sum_y = Sum(src, length);
    def sum_x = fold i = 0 to length with p do
                p + i + 1;
    def sum_xy = fold j = 0 to length with q do   
                 q + (j + 1) * src[j];
    def sum_x_sq = fold k = 0 to length with r do
                   r + Sqr(k + 1);
    def slpNor = (length * sum_xy) - (sum_x * sum_y);
    def slpDor = (length * sum_x_sq - Sqr(sum_x));
    def slope  = slpNor / slpDor;
    def intercept = (sum_y - slope * sum_x) / length;
    def y1        = intercept + slope;
    def distance  = (close - y1);
    def diff = distance - Average(distance, length1);
    def difStDt = diff / StDev(distance, length1);
    def distance_n = Average(difStDt, 10);
    plot reg = if IsNaN(distance_n) then 0 else distance_n;
    plot slp = if IsNaN(y1) then 0 else y1;
}
##// ~~ Gradient Coloring {
script gradient_color {
    input src = close;
    input minVal = 10;
    input maxVal = 400;
    input loR = 173;
    input loG = 216;
    input loB = 230;
    input hiR = 41;
    input hiG = 98;
    input hiB = 255;
    def value = if IsNaN(src) then 0 else src;
    def clamped_value = Max(Min(value, maxVal), minVal);
    def normalized_value = (clamped_value - minVal) / (maxVal - minVal);
    def re = Floor(loR + (hiR - loR) * normalized_value);
    def gr = Floor(loG + (hiG - loG) * normalized_value);
    def bl = Floor(loB + (hiB - loB) * normalized_value);
    plot r = re;
    plot g = gr;
    plot b = bl;
}
def y  = regression_indicator(close, length, length1).reg;
def y1 = regression_indicator(close, length, length1).slp;
#// Signal Lines
def mean  = Average(y, length2);
def mean1 = ExpAverage(y, 5);
#// Colors
def upR = gradient_color(y, 0, 1, 0, 20, 20, 0, 255, 255).R;
def upG = gradient_color(y, 0, 1, 0, 20, 20, 0, 255, 255).G;
def upB = gradient_color(y, 0, 1, 0, 20, 20, 0, 255, 255).B;
def dnR = gradient_color(y, -1, 0, 255, 0, 255, 27, 0, 27).R;
def dnG = gradient_color(y, -1, 0, 255, 0, 255, 27, 0, 27).G;
def dnB = gradient_color(y, -1, 0, 255, 0, 255, 27, 0, 27).B;
def meR = gradient_color(mean, -1, 1, 255, 0, 0, 0, 255, 0).R;
def meG = gradient_color(mean, -1, 1, 255, 0, 0, 0, 255, 0).G;
def meB = gradient_color(mean, -1, 1, 255, 0, 0, 0, 255, 0).B;
def coR = gradient_color(y, -1, 1, 255, 0, 0, 0, 255, 0).R;
def coG = gradient_color(y, -1, 1, 255, 0, 0, 0, 255, 0).G;
def coB = gradient_color(y, -1, 1, 255, 0, 0, 0, 255, 0).B;
#// Conditions
def cond1 = (mean1 < mean) and (mean1[1] >= mean[1]) and y > 0;
def cond2 = (mean1 > mean) and (mean1[1] <= mean[1]) and y < 0;
def cond3 = (y > 0) and (y[1] <= 0);
def cond4 = (y < 0) and (y[1] >= 0);

#-- Signals

plot weakUp = if !last and cond1 then high else na;
plot weakDn = if !last and cond2 then low else na;
plot trendUp1 = if cond3 then low else na;
plot trendDn1 = if cond4 then high else na;
plot trendUp = if cond3 then low else na;
plot trendDn = if cond4 then high else na;
trendUp.SetLineWeight(4);
trendDn.SetLineWeight(4);
trendUp1.SetLineWeight(2);
trendDn1.SetLineWeight(2);
trendUp.SetDefaultColor(Color.CYAN);
trendDn.SetDefaultColor(Color.MAGENTA);
trendUp1.SetDefaultColor(Color.DARK_GRAY);
trendDn1.SetDefaultColor(Color.DARK_GRAY);
trendUp.SetPaintingStrategy(PaintingStrategy.LINE_VS_POINTS);
trendDn.SetPaintingStrategy(PaintingStrategy.LINE_VS_POINTS);
trendUp1.SetPaintingStrategy(PaintingStrategy.POINTS);
trendDn1.SetPaintingStrategy(PaintingStrategy.POINTS);
weakUp.SetDefaultColor(Color.MAGENTA);
weakDn.SetDefaultColor(Color.CYAN);
weakUp.SetPaintingStrategy(PaintingStrategy.BOOLEAN_WEDGE_UP);
weakDn.SetPaintingStrategy(PaintingStrategy.BOOLEAN_WEDGE_DOWN);

#-- Reg Lines

plot regLine = if !last and y1 then y1 else na;
regLine.SetLineWeight(2);
regLine.AssignValueColor(if y > 0 then CreateColor(upR, upG, upB) else CreateColor(dnR, dnG, dnB));

#-- trend
def dir = if !last[-1] then if cond3 then 1 else if cond4 then -1 else dir[1] else dir[1];

plot dirUp = if last[0] and !last[1] then if dir[1] > 0 then y1[1] + (high[1] - low[1]) else na else na;
plot dirDn = if last[0] and !last[1] then if dir[1] < 0 then y1[1] - (high[1] - low[1]) else na else na;
dirUp.AssignValueColor(CreateColor(coR[1], coG[1], coB[1]));
dirDn.AssignValueColor(CreateColor(coR[1], coG[1], coB[1]));
dirUp.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
dirDn.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);

#-- Label
AddLabel(showLabel and dir > 0, "Trend UP (" + AsText(y) + ")", CreateColor(upR, upG, upB));
AddLabel(showLabel and dir < 0, "Trend Dn (" + AsText(y) + ")", CreateColor(dnR, dnG, dnB));

#-- Bar Color

AssignPriceColor(if !colorBars then Color.CURRENT else CreateColor(coR, coG, coB));


#-- END of CODE

Lower Study:

CSS:
#// Indicator for TOS
#// © BigBeluga
#indicator("Regression Indicator [BigBeluga]", overlay = false, max_bars_back = 500)
# Converted by Sam4Cok@Samer800     - 03/2025
Declare lower;

input colorBars = yes;
input showLabel = yes;
input showSignalLine = yes;
input RegressionLength = 400; #, "Regression Length")
input RegressionNormalization = 100; #, "Regression Normalization")
input SignalLineLength = 50; #,  "Signal Line")

def na = Double.NaN;
def last = isNaN(close);

#// @function regression_indicator is a Normalized Ratio of Regression Lines with close
script regression_indicator {
    input src = close;
    input length = 400;
    input length1 = 100;
    def sum_y = Sum(src, length);
    def sum_x = fold i = 0 to length with p do
                p + i + 1;
    def sum_xy = fold j = 0 to length with q do   
                 q + (j + 1) * src[j];
    def sum_x_sq = fold k = 0 to length with r do
                   r + Sqr(k + 1);
    def slpNor = (length * sum_xy) - (sum_x * sum_y);
    def slpDor = (length * sum_x_sq - Sqr(sum_x));
    def slope  = slpNor / slpDor;
    def intercept = (sum_y - slope * sum_x) / length;
    def y1        = intercept + slope;
    def distance  = (close - y1);
    def diff = distance - Average(distance, length1);
    def difStDt = diff / StDev(distance, length1);
    def distance_n = Average(difStDt, 10);
    plot reg = if isNaN(distance_n) then 0 else distance_n;
}
##// ~~ Gradient Coloring {
Script gradient_color {
input src = close;
input minVal = 10;
input maxVal = 400;
input loR = 173;
input loG = 216;
input loB = 230;
input hiR = 41;
input hiG = 98;
input hiB = 255;
    def value = if isNaN(src) then 0 else src;
    def clamped_value = max(min(value, maxVal), minVal);
    def normalized_value = (clamped_value - minVal) / (maxVal - minVal);
    def re = floor(loR + (hiR - loR) * normalized_value);
    def gr = floor(loG + (hiG - loG) * normalized_value);
    def bl = floor(loB + (hiB - loB) * normalized_value);
    plot r = re;
    plot g = gr;
    plot b = bl;
}
def y  = regression_indicator(close, RegressionLength, RegressionNormalization);
#// Signal Lines
def mean  = Average(y, SignalLineLength);
def mean1 = ExpAverage(y, 5);
#// Conditions
def cond3 = (y > 0) and (y[1] <= 0);
def cond4 = (y < 0) and (y[1] >= 0);

#// Colors
def upR = gradient_color(Y, 0, 1, 0, 20, 20, 0, 255, 255).R;
def upG = gradient_color(Y, 0, 1, 0, 20, 20, 0, 255, 255).G;
def upB = gradient_color(Y, 0, 1, 0, 20, 20, 0, 255, 255).B;
def dnR = gradient_color(Y,-1, 0, 255, 0, 255, 27, 0, 27).R;
def dnG = gradient_color(y,-1, 0, 255, 0, 255, 27, 0, 27).G;
def dnB = gradient_color(y,-1, 0, 255, 0, 255, 27, 0, 27).B;
def meR = gradient_color(mean,-1, 1, 255, 0, 0, 0, 255, 0).R;
def meG = gradient_color(mean,-1, 1, 255, 0, 0, 0, 255, 0).G;
def meB = gradient_color(mean,-1, 1, 255, 0, 0, 0, 255, 0).B;
def coR = gradient_color(Y,-1, 1, 255, 0, 0, 0, 255, 0).R;
def coG = gradient_color(Y,-1, 1, 255, 0, 0, 0, 255, 0).G;
def coB = gradient_color(Y,-1, 1, 255, 0, 0, 0, 255, 0).B;

#-- Signals
plot trendUp1 = if cond3 then 0 else na;
plot trendDn1 = if cond4 then 0 else na;
plot trendUp = if cond3 then 0 else na;
plot trendDn = if cond4 then 0 else na;
trendUp.SetLineWeight(4);
trendDn.SetLineWeight(4);
trendUp1.SetLineWeight(2);
trendDn1.SetLineWeight(2);
trendUp.SetDefaultColor(Color.CYAN);
trendDn.SetDefaultColor(Color.MAGENTA);
trendUp1.SetDefaultColor(Color.DARK_GRAY);
trendDn1.SetDefaultColor(Color.DARK_GRAY);
trendUp.SetPaintingStrategy(PaintingStrategy.LINE_VS_POINTS);
trendDn.SetPaintingStrategy(PaintingStrategy.LINE_VS_POINTS);
trendUp1.SetPaintingStrategy(PaintingStrategy.POINTS);
trendDn1.SetPaintingStrategy(PaintingStrategy.POINTS);

#-- Reg Line
plot regLine = if !last then y else na;
regLine.SetLineWeight(2);
regLine.AssignValueColor(if y>0 then CreateColor(upR, upG, upB) else CreateColor(dnR, dnG, dnB));

#// Signal Line
plot sigLine = if showSignalLine and !last then mean else na;
plot zero = if last then na else 0;
zero.AssignValueColor(if y>0 then CreateColor(upR, upG, upB) else CreateColor(dnR, dnG, dnB));
sigLine.AssignValueColor(CreateColor(meR, meG, meB));

#-- Clouds
AddCloud(y, 1, CreateColor(0, 127, 127), color.CURRENT);
AddCloud(-1, y, Color.PLUM, color.CURRENT);
AddCloud(y, 2, CreateColor(0, 127, 127), color.CURRENT);
AddCloud(-2, y, Color.PLUM, color.CURRENT);

#-- trend
def dir = if !last[-1] then if cond3 then 1 else if cond4 then -1 else dir[1] else dir[1];

plot dirUp = if last[0] and !last[1] then if dir[1]>0 then y[1]+0.45 else na else na;
plot dirDn = if last[0] and !last[1] then if dir[1]<0 then y[1]-0.45 else na else na;
dirUp.AssignValueColor(CreateColor(coR[1], coG[1], coB[1]));
dirDn.AssignValueColor(CreateColor(coR[1], coG[1], coB[1]));
dirUp.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
dirDn.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);

#-- Label
AddLabel(showLabel and dir>0, "Trend UP (" + AsText(y) + ")", CreateColor(upR, upG, upB));
AddLabel(showLabel and dir<0, "Trend Dn (" + AsText(y) + ")", CreateColor(dnR, dnG, dnB));

#-- Bar Color

AssignPriceColor(if !colorBars then Color.CURRENT else CreateColor(coR, coG, coB));

#-- END of CODE
 

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
554 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