# linear regression plot dependent on condition

#### Glefdar

##### Active member
If functions (such as "movingaverage" or "stdev") expect a constant as the length parameter, an error is returned when attempting to instead get the length parameter from a variable.

So if we want to calculate a moving average or standard deviation with a length that varies based on market conditions, it will be necessary to manually write code for movingaverage and stdev instead of using the built-in functions.
EDIT, wanted to share here that Mobius provided code in the TS Lounge that allows for variable length regression line and variable length standard deviation calculations:

Code:
``````# Linear Regression Channel anchored to Highest / Lowest Pivot
# Allows a floating point anchor
# Mobius
# V01.2015

def hh = highestAll(high);
def ll = lowestAll(low);
script S
{
input d = close;
input n = 50;
plot e = fold i = 0 to n
with f
do f + getValue(d, i);
}
def y = close;
def x  = BarNumber();
def nan = double.nan;
def xx = if(isNaN(y[-1]) and !isNaN(y), x, xx[1]);
def hx = if(high == hh, x, hx[1]);
def lx = if(low == ll, x, lx[1]);
def MinX = Max(hx, lx);
def n = highestAll(xx - MinX);
def x1 = HighestAll(if !IsNaN(y) and IsNaN(y[-1])
then x
else nan);
def x0 = HighestAll(if GetValue(x, -n) == x1
then x
else nan);
def x_ = if GetValue(x, -n) >= x1
then x - x0
else x_[1];
def Ex  = S(x_, n);
def Ey  = S(y, n);
def Exy = S(x_ * y, n);
def Exsq = S(sqr(x_), n);
def b = (n * Exy - (Ex * Ey)) / (n * Exsq - (Ex * Ex));
def a = (GetValue(Ey, x - x1) - GetValue(b, x - x1) * GetValue(Ex, x - x1)) / n;
def avg = (fold i = 0 to n
with s
do s + getValue(y, i)) / n;
def SD = Sqrt((fold i2 = 0 to n
with s2 = 0
do s2 + Sqr(avg - GetValue(y, i2))) / n);
plot LRL = if x >= x0
then a + (GetValue(b, x - x1) * x_)
else nan;
LRL.SetStyle(Curve.Firm);
LRL.SetDefaultColor(Color.Cyan);
plot upper = LRL + (highestAll(SD) * .7);
upper.SetStyle(Curve.Firm);
upper.SetDefaultColor(Color.Yellow);
plot lower = LRL - (highestAll(SD) * .7);
lower.SetStyle(Curve.Firm);
lower.SetDefaultColor(Color.Yellow);
# End Code Linear Regression Line``````

This provided me with the template I needed. The only thing that was also important to know was that the fold function can break scripts if your chart is displaying an expansion area, and this has to be prevented by instructing the code with fold (or code accessing the fold output value) with a preliminary condition such as “def {variable} = if isNan(close) then {variable}[1} else ….” or “then double.nan else…” depending on what is needed.

Last edited:
Solution
@SleepyZ Wondering if you could provide your feedback here? I would love to be able to have the LRC stop painting (repainting) once a condition is met. Thanks!!!

[corrected def cond_y = if SecondsFromTime(endtime) <= 0 then x else nan;
1. This will allow you to use Mobius Time Anchored LR Channel and limit its' plot to a condition (cond_y).
2. The plot can be extended from the condition end by input extend = yes;.
3. There are some conditional examples.
4. The image on the left is with extend = no, and the right, extend = yes;. Both show the unmodified code.

Code:
``````#Mobius_Anchored_Linear_Regression_modified_End_at_Cond_y_Extended_Option
#08:35 Mobius: Here's the anchored Regression Channel I use...``````
[Edit to correct lastsell as the code I found for TEI had an error where both lastbuy and last sell were both coded the same.]

The anchor of the channel is based upon a barnumber() of the last condition that you want to use to define that barnumber().

Using the Triple Exhaustion Indicator (TEI), the following was added to the code below to determine which barnumber() to use to anchor the Linear Regression Channel (LRC):

Code:
``````def lastbuy  = highestall(if sellerRegular[1] and !sellerRegular then barnumber() else Double.NaN);
#addlabel(1, lastbuy + " " + lastsell + " " + cond);``````

As TEI is a custom indicator, most of the code needs to be used in place of that used for the referenced ZigZag in the previous example.

Below is the full code for the TEI with LRC, There were no changes to the LRC code. The TEI replaced the ZigZag with the above code snippet to define COND.

Is it possible to modify this script so that the linear regression channel stops calculating based on a specified condition, but then the lines keep extending? The idea is that after the stop condition is met, the LRC lines will keep extending but will no longer repaint. I tried modifying "def y = close" to instead be "def y = if barcountsincecondition>0 then y[1] else close;" but that doesn't work. Am wondering if it's fairly simple and I'm just missing it

Is it possible to modify this script so that the linear regression channel stops calculating based on a specified condition, but then the lines keep extending? The idea is that after the stop condition is met, the LRC lines will keep extending but will no longer repaint. I tried modifying "def y = close" to instead be "def y = if barcountsincecondition>0 then y[1] else close;" but that doesn't work. Am wondering if it's fairly simple and I'm just missing it
@SleepyZ Wondering if you could provide your feedback here? I would love to be able to have the LRC stop painting (repainting) once a condition is met. Thanks!!!

Last edited by a moderator:
@SleepyZ Wondering if you could provide your feedback here? I would love to be able to have the LRC stop painting (repainting) once a condition is met. Thanks!!!

[corrected def cond_y = if SecondsFromTime(endtime) <= 0 then x else nan;
1. This will allow you to use Mobius Time Anchored LR Channel and limit its' plot to a condition (cond_y).
2. The plot can be extended from the condition end by input extend = yes;.
3. There are some conditional examples.
4. The image on the left is with extend = no, and the right, extend = yes;. Both show the unmodified code.

Code:
``````#Mobius_Anchored_Linear_Regression_modified_End_at_Cond_y_Extended_Option
#08:35 Mobius: Here's the anchored Regression Channel I use

# Time Anchored Regression Channel
# Mobius
# V01.01.2016

input StartTime = 0930;
input Channel_1_Width = 0.70;
input Channel_2_Width = 1.00;
input LineWeight = 2;

script E
{
input y = close;
input n = 20;
def s = fold i = 0 to n
with j
do j + GetValue(y, i);
plot D = s;
}
# Variables
def o = open;
def h = high;
def l = low;
def c = close;
def x = BarNumber();
def nan = Double.NaN;
def xx = if IsNaN(c[-1]) and !IsNaN(c) then x else xx[1];
def firstBar = if SecondsFromTime(StartTime) == 0
then x
else firstBar[1];

#Options to End Plot Based Upon Condition and Extended from there
input extend  = no;
input endtime = 0945;
#Examples of Some Potential Conditions
def cond_y    = if SecondsFromTime(endtime) <= 0 then x else nan;
#if high==high(period=aggregationPeriod.DAY) then barnumber() else double.nan;
#if low==low(period=aggregationPeriod.DAY) then barnumber() else double.nan;
AddVerticalLine(x == HighestAll(cond_y), " ", Color.WHITE);
def y         = if x == 1 or IsNaN(close)
then nan
else if Between(x, HighestAll(firstBar), HighestAll(cond_y))
then close
else y[1];
#############

def S_y = if x == HighestAll(firstBar)
then y
else if x > HighestAll(firstBar)
then S_y[1] + y
else S_y[1];
def S_x = if x == HighestAll(firstBar)
then 1
else if x > HighestAll(firstBar)
then S_x[1] + 1
else S_x[1];
def x0_ = HighestAll(xx) - firstBar;
def x1 = HighestAll(if !IsNaN(y) and IsNaN(y[-1])
then x
else nan);
def x0 = HighestAll(if GetValue(x, -x0_) == x1
then x
else nan);
def x_ = if GetValue(x, -x0_) >= x1
then x - x0
else x_[1];
def Ex  = E(x_, x0_);
def Ey  = E(y, x0_);
def Exy = E(x_ * y, x0_);
def Exsq = E(Sqr(x_), x0_);
def b = (x0_ * Exy - (Ex * Ey)) / (x0_ * Exsq - (Ex * Ex));
def a = (GetValue(Ey, x - x1) - GetValue(b, x - x1) * GetValue(Ex, x - x1)) / x0_;
def LR = a + (GetValue(b, x - x1) * x_);
def r = Max(h, c[1]) - Min(l, c[1]);
def Er = E(r, x0_) / x0_;
def mean = S_y / S_x;
def SD = Sqrt((1 / S_x) * (E(Sqr(y - mean), S_x)));
# Plots
plot LRL = if extend == no and  x <= HighestAll(cond_y) #x >= x0  # x is defined as barnumber()
then LR
else if extend == yes and x >= x0
then LR
else nan;
LRL.SetStyle(Curve.FIRM);
LRL.SetLineWeight(LineWeight + 1);
LRL.AssignValueColor(if GetValue(a, x - x1) < LR
then Color.CYAN
else Color.ORANGE);
LRL.HideBubble();
LRL.HideTitle();
plot upper1 = LRL + (HighestAll(SD) * Channel_1_Width);
upper1.SetLineWeight(LineWeight);
upper1.SetDefaultColor(Color.GREEN);
upper1.HideBubble();
upper1.HideTitle();
plot lower1 = LRL - (HighestAll(SD) * Channel_1_Width);
lower1.SetLineWeight(LineWeight);
lower1.SetDefaultColor(Color.RED);
lower1.HideBubble();
lower1.HideTitle();
plot upper2 = LRL + (HighestAll(SD) * Channel_2_Width);
upper2.SetLineWeight(LineWeight);
upper2.SetDefaultColor(Color.GREEN);
upper2.HideBubble();
upper2.HideTitle();
plot lower2 = LRL - (HighestAll(SD) * Channel_2_Width);
lower2.SetLineWeight(LineWeight);
lower2.SetDefaultColor(Color.RED);
lower2.HideBubble();
lower2.HideTitle();
# End Code Time Anchored Regression Channel

#``````

Last edited:

87k+ Posts
405 Online

## The Market Trading Game Changer

Join 2,500+ subscribers inside the useThinkScript VIP Membership Club
• Exclusive indicators
• Proven strategies & setups
• Private Discord community
• Exclusive members-only content
• 1 full year of unlimited support

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?