Linear Regression Slope [UCSGEARS] For ThinkOrSwim

Tradarr

New member
Author states:
In ideal world the Linear regression slope values will remain same for any time period length. because the equation is y = mx+b, where m is the slope. All I did here is m = y/x

The Main Purpose of this indicator is to see, if the Trend is accelerating or decelerating.

Thank you to the amazing @samer800 for the addition of divergence lines and bubbles
fomDRD0.png


I'm hoping the Tradingview Colored LRS Histogram
https://www.tradingview.com/script/l9bUW1FZ-Linear-Regression-Slope-Version-2/
can be converted to Thinkscript Indicator ? :)

Hoping if someone create this indicator they also add divergence alerts and labels ?
 
Last edited by a moderator:

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

I'm hoping the Tradingview Colored LRS Histogram
https://www.tradingview.com/script/l9bUW1FZ-Linear-Regression-Slope-Version-2/
can be converted to Thinkscript Indicator ? :)

Hoping if someone create this indicator they also add divergence alerts and labels ? View attachment 22058
check the below:
CSS:
#// Created by UCSgears -- Version 2
#// Simple linear regression slope - Good way see if the trend is accelarating or decelarating
#study(title="UCSGEARS - Linear Regression Slope", shorttitle="UCS-LRS", overlay=false)
# Converted by Sam4Cok@Samer800    - 06/2024    - request from UseThinkScript.compoundValue member
declare lower;

input barColor = yes;
input src = close;
input CurveLength = 50; #, minval = 1, title = "Curve Length")
input SlopeLength = 5; #, minval=1, title="Slope Length")
input SignalLength = 13; #, minval=1, title="Signal Length")

def na = Double.NaN;
def last = IsNaN(close);
#//Linear Regression Curve
def lrc = Inertia(src, CurveLength);
#//Linear Regression Slope
def lrs = (lrc - lrc[1]) / 1;
#//Smooth Linear Regression Slope
def slrs = ExpAverage(lrs, SlopeLength);
#//Signal Linear Regression Slope
def alrs = Average(slrs, SignalLength);
#//loalrs = sma(slrs, (glen*5))

def uacce = lrs > alrs and lrs > 0;
def dacce = lrs < alrs and lrs < 0;

def scolor = if uacce then 1 else if dacce then -1 else 0;

plot AvgSlope = alrs; #, color = gray, title = "Average Slope")
plot zero = if last then na else 0; #, title = "Zero Line", color = gray)
AvgSlope.SetDefaultColor(Color.WHITE);
zero.SetDefaultColor(Color.DARK_GRAY);

#----Div-----------
input ShowLastDivLines = yes;
input ShowLastHiddenDivLines = no;
input divSignalOptions = {default "Bubbles", "Vertical Lines"};
input LookBackRight  = 5;           # "Pivot Lookback Right"
input LookBackLeft  = 5;           # "Pivot Lookback Left"
input MaxLookback = 60;   # "Max of Lookback Range"
input MinLookback = 5;    # "Min of Lookback Range"
input DivBull = yes;      # "Plot Bullish"
input DivBear = yes;      # "Plot Bearish"
input DivHiddenBull = no; # "Plot Hidden Bullish"
input DivHiddenBear = no; # "Plot Hidden Bearish"

def bubble = divSignalOptions == divSignalOptions."Bubbles";
def divSrc = slrs;
def lo = low;
def hi = high;

script FindPivots {
    input dat = close; # default data or study being evaluated
    input HL  = 0;    # default high or low pivot designation, -1 low, +1 high
    input lbL  = 5;    # default Pivot Lookback Left
    input lbR  = 1;    # default Pivot Lookback Right
    ##############
    def _nan;    # used for non-number returns
    def _BN;     # the current barnumber
    def _VStop;  # confirms that the lookforward period continues the pivot trend
    def _V;      # the Value at the actual pivot point
    ##############
    _BN  = BarNumber();
    _nan = Double.NaN;
    _VStop = if !IsNaN(dat) and lbR > 0 and lbL > 0 then
                fold a = 1 to lbR + 1 with b=1 while b do
                    if HL > 0 then dat > GetValue(dat, -a) else dat < GetValue(dat, -a) else _nan;
    if (HL > 0) {
        _V = if _BN > lbL and dat == Highest(dat, lbL + 1) and _VStop
            then dat else _nan;
    } else {
        _V = if _BN > lbL and dat == Lowest(dat, lbL + 1) and _VStop
            then dat else _nan;
    }
    plot result = if !IsNaN(_V) and _VStop then _V else _nan;
}

#_inRange(cond) =>
script _inRange {
    input cond = yes;
    input rangeUpper = 60;
    input rangeLower = 5;
    def bars = if cond then 0 else bars[1] + 1;
    def inrange =  (rangeLower <= bars) and (bars <= rangeUpper);
    plot retrun = inrange;
}
def pl = findpivots(divSrc, 1, LookBackLeft, LookBackRight);
def ph = findpivots(divSrc, 1, LookBackLeft, LookBackRight);

def plFound = if !IsNaN(pl) then 1 else 0;
def phFound = if !IsNaN(ph) then 1 else 0;
def vlFound0 = if plFound then divSrc else vlFound0[1];
def vhFound0 = if phFound then divSrc else vhFound0[1];
def plPrice0 = if plFound then lo else plPrice0[1];
def phPrice0 = if phFound then hi else phPrice0[1];

def vlFound = if vlFound0 != vlFound0[1] then vlFound0[1] else vlFound[1];
def vhFound = if vhFound0 != vhFound0[1] then vhFound0[1] else vhFound[1];

def plPrice = if plPrice0 != plPrice0[1] then plPrice0[1] else plPrice[1];
def phPrice = if phPrice0 != phPrice0[1] then phPrice0[1] else phPrice[1];

#// Regular Bullish
def inRangePl = _inRange(plFound[1], MaxLookback, MinLookback);
def oscHL = divSrc > vlFound and inRangePl;
def priceLL = lo < plPrice;
def bullCond = DivBull and plFound and oscHL and priceLL;
#// Hidden Bullish
def oscLL = divSrc < vlFound and inRangePl;
def priceHL = lo > plPrice;
def hiddenBullCond = DivHiddenBull and plFound and oscLL and priceHL;

#// Regular Bearish
def inRangePh = _inRange(phFound[1], MaxLookback, MinLookback);
def oscLH   = divSrc < vhFound and inRangePh;
def priceHH = hi > phPrice;
def bearCond = DivBear and phFound and oscLH and priceHH;
#// Hidden Bearish
def oscHH = divSrc > vhFound and inRangePh;
def priceLH = hi < phPrice;
def hiddenBearCond = DivHiddenBear and phFound and oscHH and priceLH;

#------ Bubbles
AddChartBubble(bubble and bullCond, divSrc, "R", Color.CYAN, no);
AddChartBubble(bubble and bearCond, divSrc, "R", Color.MAGENTA, yes);
AddChartBubble(bubble and hiddenBullCond, divSrc, "H", Color.DARK_GREEN, no);
AddChartBubble(bubble and hiddenBearCond, divSrc, "H", Color.DARK_RED, yes);
#-- Vertica lines
AddVerticalLine(!bubble and bullCond, "Regular", Color.CYAN);
AddVerticalLine(!bubble and bearCond, "Regular", Color.MAGENTA);
AddVerticalLine(!bubble and hiddenBullCond, "Hidden", Color.DARK_GREEN);
AddVerticalLine(!bubble and hiddenBearCond, "Hidden", Color.DARK_RED);

##### Lines
def bar = BarNumber();
#-- Bear Line
def lastPhBar = if phFound then bar else lastPhBar[1];
def prePhBar = if lastPhBar != lastPhBar[1] then lastPhBar[1] else prePhBar[1];
def priorPHBar = if bearCond then prePhBar else priorPHBar[1];
def lastBearBar = if bearCond then bar else lastBearBar[1];
#-- Bull Line
def lastPlBar = if plFound then bar else lastPlBar[1];
def prePlBar = if lastPlBar != lastPlBar[1] then lastPlBar[1] else prePlBar[1];
def priorPLBar = if bullCond then prePlBar else priorPLBar[1];
def lastBullBar = if bullCond then bar else lastBullBar[1];

def HighPivots = if bar == HighestAll(priorPHBar) then 1 else if bar == HighestAll(lastBearBar) then 1 else 0;
def LowPivots  = if bar == HighestAll(priorPLBar) then 1 else if bar == HighestAll(lastBullBar) then 1 else 0;

def pivotHigh = if HighPivots then divSrc else na;
def pivotLow  = if LowPivots  then divSrc else na;

plot PlotHline = if ShowLastDivLines then pivotHigh else na;
PlotHline.EnableApproximation();
PlotHline.SetDefaultColor(Color.MAGENTA);

plot PlotLline = if ShowLastDivLines then pivotLow else na;
PlotLline.EnableApproximation();
PlotLline.SetDefaultColor(Color.CYAN);

#--- Hidden Lines
#-- Bear Line
def priorHPHBar = if hiddenBearCond then prePhBar else priorHPHBar[1];
def lastHBearBar = if hiddenBearCond then bar else lastHBearBar[1];
#-- Bull Line
def priorHPLBar = if hiddenBullCond then prePlBar else priorHPLBar[1];
def lastHBullBar = if hiddenBullCond then bar else lastHBullBar[1];


def HighHPivots = if bar == HighestAll(priorHPHBar) then 1 else if bar == HighestAll(lastHBearBar) then 1 else 0;
def LowHPivots  = if bar == HighestAll(priorHPLBar) then 1 else if bar == HighestAll(lastHBullBar) then 1 else 0;

def pivotHidHigh = if HighHPivots then divSrc else na;
def pivotHidLow  = if LowHPivots  then divSrc else na;

plot PlotHBearline = if ShowLastHiddenDivLines then pivotHidHigh else na;
PlotHBearline.EnableApproximation();
PlotHBearline.SetDefaultColor(Color.DARK_RED);

plot PlotHBullline = if ShowLastHiddenDivLines then pivotHidLow else na;
PlotHBullline.EnableApproximation();
PlotHBullline.SetDefaultColor(Color.DARK_GREEN);

#-- plot lin Reg
plot LinReg = slrs; # "Linear Regression Slope"
LinReg.SetPaintingStrategy(PaintingStrategy.SQUARED_HISTOGRAM);
LinReg.AssignValueColor(if scolor > 0 then if slrs>slrs[1] then Color.GREEN else Color.DARK_GREEN else
                        if scolor < 0 then if slrs<slrs[1] then Color.RED else Color.DARK_RED else Color.GRAY);

#-- bar Color

AssignPriceColor(if !barColor then Color.CURRENT else
                 if scolor > 0 then if slrs>slrs[1] then Color.GREEN else Color.DARK_GREEN else
                 if scolor < 0 then if slrs<slrs[1] then Color.RED else Color.DARK_RED else Color.GRAY);
#-- ENd Code
 
Last edited by a moderator:
check the below:
CSS:
#// Created by UCSgears -- Version 2
#// Simple linear regression slope - Good way see if the trend is accelarating or decelarating
#study(title="UCSGEARS - Linear Regression Slope", shorttitle="UCS-LRS", overlay=false)
# Converted by Sam4Cok@Samer800    - 06/2024    - request from UseThinkScript.compoundValue member
declare lower;

input barColor = yes;
input src = close;
input CurveLength = 50; #, minval = 1, title = "Curve Length")
input SlopeLength = 5; #, minval=1, title="Slope Length")
input SignalLength = 13; #, minval=1, title="Signal Length")

def na = Double.NaN;
def last = IsNaN(close);
#//Linear Regression Curve
def lrc = Inertia(src, CurveLength);
#//Linear Regression Slope
def lrs = (lrc - lrc[1]) / 1;
#//Smooth Linear Regression Slope
def slrs = ExpAverage(lrs, SlopeLength);
#//Signal Linear Regression Slope
def alrs = Average(slrs, SignalLength);
#//loalrs = sma(slrs, (glen*5))

def uacce = lrs > alrs and lrs > 0;
def dacce = lrs < alrs and lrs < 0;

def scolor = if uacce then 1 else if dacce then -1 else 0;

plot AvgSlope = alrs; #, color = gray, title = "Average Slope")
plot zero = if last then na else 0; #, title = "Zero Line", color = gray)
AvgSlope.SetDefaultColor(Color.WHITE);
zero.SetDefaultColor(Color.DARK_GRAY);

#----Div-----------
input ShowLastDivLines = yes;
input ShowLastHiddenDivLines = no;
input divSignalOptions = {default "Bubbles", "Vertical Lines"};
input LookBackRight  = 5;           # "Pivot Lookback Right"
input LookBackLeft  = 5;           # "Pivot Lookback Left"
input MaxLookback = 60;   # "Max of Lookback Range"
input MinLookback = 5;    # "Min of Lookback Range"
input DivBull = yes;      # "Plot Bullish"
input DivBear = yes;      # "Plot Bearish"
input DivHiddenBull = no; # "Plot Hidden Bullish"
input DivHiddenBear = no; # "Plot Hidden Bearish"

def bubble = divSignalOptions == divSignalOptions."Bubbles";
def divSrc = slrs;
def lo = low;
def hi = high;

script FindPivots {
    input dat = close; # default data or study being evaluated
    input HL  = 0;    # default high or low pivot designation, -1 low, +1 high
    input lbL  = 5;    # default Pivot Lookback Left
    input lbR  = 1;    # default Pivot Lookback Right
    ##############
    def _nan;    # used for non-number returns
    def _BN;     # the current barnumber
    def _VStop;  # confirms that the lookforward period continues the pivot trend
    def _V;      # the Value at the actual pivot point
    ##############
    _BN  = BarNumber();
    _nan = Double.NaN;
    _VStop = if !IsNaN(dat) and lbR > 0 and lbL > 0 then
                fold a = 1 to lbR + 1 with b=1 while b do
                    if HL > 0 then dat > GetValue(dat, -a) else dat < GetValue(dat, -a) else _nan;
    if (HL > 0) {
        _V = if _BN > lbL and dat == Highest(dat, lbL + 1) and _VStop
            then dat else _nan;
    } else {
        _V = if _BN > lbL and dat == Lowest(dat, lbL + 1) and _VStop
            then dat else _nan;
    }
    plot result = if !IsNaN(_V) and _VStop then _V else _nan;
}

#_inRange(cond) =>
script _inRange {
    input cond = yes;
    input rangeUpper = 60;
    input rangeLower = 5;
    def bars = if cond then 0 else bars[1] + 1;
    def inrange =  (rangeLower <= bars) and (bars <= rangeUpper);
    plot retrun = inrange;
}
def pl = findpivots(divSrc, -1, LookBackLeft, LookBackRight);
def ph = findpivots(divSrc, 1, LookBackLeft, LookBackRight);

def plFound = if !IsNaN(pl) then 1 else 0;
def phFound = if !IsNaN(ph) then 1 else 0;
def vlFound0 = if plFound then divSrc else vlFound0[1];
def vhFound0 = if phFound then divSrc else vhFound0[1];
def plPrice0 = if plFound then lo else plPrice0[1];
def phPrice0 = if phFound then hi else phPrice0[1];

def vlFound = if vlFound0 != vlFound0[1] then vlFound0[1] else vlFound[1];
def vhFound = if vhFound0 != vhFound0[1] then vhFound0[1] else vhFound[1];

def plPrice = if plPrice0 != plPrice0[1] then plPrice0[1] else plPrice[1];
def phPrice = if phPrice0 != phPrice0[1] then phPrice0[1] else phPrice[1];

#// Regular Bullish
def inRangePl = _inRange(plFound[1], MaxLookback, MinLookback);
def oscHL = divSrc > vlFound and inRangePl;
def priceLL = lo < plPrice;
def bullCond = DivBull and plFound and oscHL and priceLL;
#// Hidden Bullish
def oscLL = divSrc < vlFound and inRangePl;
def priceHL = lo > plPrice;
def hiddenBullCond = DivHiddenBull and plFound and oscLL and priceHL;

#// Regular Bearish
def inRangePh = _inRange(phFound[1], MaxLookback, MinLookback);
def oscLH   = divSrc < vhFound and inRangePh;
def priceHH = hi > phPrice;
def bearCond = DivBear and phFound and oscLH and priceHH;
#// Hidden Bearish
def oscHH = divSrc > vhFound and inRangePh;
def priceLH = hi < phPrice;
def hiddenBearCond = DivHiddenBear and phFound and oscHH and priceLH;

#------ Bubbles
AddChartBubble(bubble and bullCond, divSrc, "R", Color.CYAN, no);
AddChartBubble(bubble and bearCond, divSrc, "R", Color.MAGENTA, yes);
AddChartBubble(bubble and hiddenBullCond, divSrc, "H", Color.DARK_GREEN, no);
AddChartBubble(bubble and hiddenBearCond, divSrc, "H", Color.DARK_RED, yes);
#-- Vertica lines
AddVerticalLine(!bubble and bullCond, "Regular", Color.CYAN);
AddVerticalLine(!bubble and bearCond, "Regular", Color.MAGENTA);
AddVerticalLine(!bubble and hiddenBullCond, "Hidden", Color.DARK_GREEN);
AddVerticalLine(!bubble and hiddenBearCond, "Hidden", Color.DARK_RED);

##### Lines
def bar = BarNumber();
#-- Bear Line
def lastPhBar = if phFound then bar else lastPhBar[1];
def prePhBar = if lastPhBar != lastPhBar[1] then lastPhBar[1] else prePhBar[1];
def priorPHBar = if bearCond then prePhBar else priorPHBar[1];
def lastBearBar = if bearCond then bar else lastBearBar[1];
#-- Bull Line
def lastPlBar = if plFound then bar else lastPlBar[1];
def prePlBar = if lastPlBar != lastPlBar[1] then lastPlBar[1] else prePlBar[1];
def priorPLBar = if bullCond then prePlBar else priorPLBar[1];
def lastBullBar = if bullCond then bar else lastBullBar[1];

def HighPivots = if bar == HighestAll(priorPHBar) then 1 else if bar == HighestAll(lastBearBar) then 1 else 0;
def LowPivots  = if bar == HighestAll(priorPLBar) then 1 else if bar == HighestAll(lastBullBar) then 1 else 0;

def pivotHigh = if HighPivots then divSrc else na;
def pivotLow  = if LowPivots  then divSrc else na;

plot PlotHline = if ShowLastDivLines then pivotHigh else na;
PlotHline.EnableApproximation();
PlotHline.SetDefaultColor(Color.MAGENTA);

plot PlotLline = if ShowLastDivLines then pivotLow else na;
PlotLline.EnableApproximation();
PlotLline.SetDefaultColor(Color.CYAN);

#--- Hidden Lines
#-- Bear Line
def priorHPHBar = if hiddenBearCond then prePhBar else priorHPHBar[1];
def lastHBearBar = if hiddenBearCond then bar else lastHBearBar[1];
#-- Bull Line
def priorHPLBar = if hiddenBullCond then prePlBar else priorHPLBar[1];
def lastHBullBar = if hiddenBullCond then bar else lastHBullBar[1];


def HighHPivots = if bar == HighestAll(priorHPHBar) then 1 else if bar == HighestAll(lastHBearBar) then 1 else 0;
def LowHPivots  = if bar == HighestAll(priorHPLBar) then 1 else if bar == HighestAll(lastHBullBar) then 1 else 0;

def pivotHidHigh = if HighHPivots then divSrc else na;
def pivotHidLow  = if LowHPivots  then divSrc else na;

plot PlotHBearline = if ShowLastHiddenDivLines then pivotHidHigh else na;
PlotHBearline.EnableApproximation();
PlotHBearline.SetDefaultColor(Color.DARK_RED);

plot PlotHBullline = if ShowLastHiddenDivLines then pivotHidLow else na;
PlotHBullline.EnableApproximation();
PlotHBullline.SetDefaultColor(Color.DARK_GREEN);

#-- plot lin Reg
plot LinReg = slrs; # "Linear Regression Slope"
LinReg.SetPaintingStrategy(PaintingStrategy.SQUARED_HISTOGRAM);
LinReg.AssignValueColor(if scolor > 0 then if slrs>slrs[1] then Color.GREEN else Color.DARK_GREEN else
                        if scolor < 0 then if slrs<slrs[1] then Color.RED else Color.DARK_RED else Color.GRAY);

#-- bar Color

AssignPriceColor(if !barColor then Color.CURRENT else
                 if scolor > 0 then if slrs>slrs[1] then Color.GREEN else Color.DARK_GREEN else
                 if scolor < 0 then if slrs<slrs[1] then Color.RED else Color.DARK_RED else Color.GRAY);
#-- ENd Code
Thanks so much!
 
If one wanted to create a conditional order to buy on aqua bubble or sell on magenta bubble how would that best be accomplished? Thank you!
 
If one wanted to create a conditional order to buy on aqua bubble or sell on magenta bubble how would that best be accomplished? Thank you!

Each conditional order needs to be set up manually. Each order executes once. And it's done.
If you want to execute on the next buy trigger, you need to set up the conditional order from scratch again.
There is no automated trading in ThinkOrSwim.

the trigger conditions to buy on aqua bubble or sell on magenta bubble:
bullCond is true #cyan bubble
or
bearCond is true #magenta bubble

Here is a tutorial for conditional orders:
https://usethinkscript.com/threads/answers-to-commonly-asked-questions.6006/#post-80482
 
What would the code for the same exact indicator be except instead of the histogram plotting the slope of the linear regression, it plots the linear regression line itself. I know TOS has this but I'm looking to color the bars based on the line going up (green) or down (red) or flat (grey)....I use range bars, not time bars (the code above works on range bars too so no problem there).

Any help would be greatly appreciated!
 
What would the code for the same exact indicator be except instead of the histogram plotting the slope of the linear regression, it plots the linear regression line itself. I know TOS has this but I'm looking to color the bars based on the line going up (green) or down (red) or flat (grey)....I use range bars, not time bars (the code above works on range bars too so no problem there).

Any help would be greatly appreciated!

Histogram plotting is optimized when the values are oscillating above and below 0.
Given that Linear Regressions do not fit that type of analysis, not sure that your request has any significant analytical value.

But come back, and report if you found this to be of value:
IURi2eu.png


Ruby:
#// Created by UCSgears -- Version 2
#// Simple linear regression slope - Good way see if the trend is accelarating or decelarating
#study(title="UCSGEARS - Linear Regression Slope", shorttitle="UCS-LRS", overlay=false)
# Converted by Sam4Cok@Samer800    - 06/2024    - request from UseThinkScript.compoundValue member
declare lower;

input barColor = yes;
input src = close;
input CurveLength = 50; #, minval = 1, title = "Curve Length")
input SlopeLength = 5; #, minval=1, title="Slope Length")
input SignalLength = 13; #, minval=1, title="Signal Length")

def na = Double.NaN;
def last = IsNaN(close);
#//Linear Regression Curve
def lrc = Inertia(src, CurveLength);
#//Linear Regression Slope
def lrs = (lrc - lrc[1]) / 1;
#//Smooth Linear Regression Slope
def slrs = ExpAverage(lrs, SlopeLength);
#//Signal Linear Regression Slope
def alrs = Average(slrs, SignalLength);
#//loalrs = sma(slrs, (glen*5))

def uacce = lrs > alrs and lrs > 0;
def dacce = lrs < alrs and lrs < 0;

def scolor = if uacce then 1 else if dacce then -1 else 0;

plot AvgSlope = alrs; #, color = gray, title = "Average Slope")
plot zero = if last then na else 0; #, title = "Zero Line", color = gray)
AvgSlope.SetDefaultColor(Color.WHITE);
zero.SetDefaultColor(Color.DARK_GRAY);

#----Div-----------
input ShowLastDivLines = yes;
input ShowLastHiddenDivLines = no;
input divSignalOptions = {default "Bubbles", "Vertical Lines"};
input LookBackRight  = 5;           # "Pivot Lookback Right"
input LookBackLeft  = 5;           # "Pivot Lookback Left"
input MaxLookback = 60;   # "Max of Lookback Range"
input MinLookback = 5;    # "Min of Lookback Range"
input DivBull = yes;      # "Plot Bullish"
input DivBear = yes;      # "Plot Bearish"
input DivHiddenBull = no; # "Plot Hidden Bullish"
input DivHiddenBear = no; # "Plot Hidden Bearish"

def bubble = divSignalOptions == divSignalOptions."Bubbles";
def divSrc = slrs;
def lo = low;
def hi = high;

script FindPivots {
    input dat = close; # default data or study being evaluated
    input HL  = 0;    # default high or low pivot designation, -1 low, +1 high
    input lbL  = 5;    # default Pivot Lookback Left
    input lbR  = 1;    # default Pivot Lookback Right
    ##############
    def _nan;    # used for non-number returns
    def _BN;     # the current barnumber
    def _VStop;  # confirms that the lookforward period continues the pivot trend
    def _V;      # the Value at the actual pivot point
    ##############
    _BN  = BarNumber();
    _nan = Double.NaN;
    _VStop = if !IsNaN(dat) and lbR > 0 and lbL > 0 then
                fold a = 1 to lbR + 1 with b=1 while b do
                    if HL > 0 then dat > GetValue(dat, -a) else dat < GetValue(dat, -a) else _nan;
    if (HL > 0) {
        _V = if _BN > lbL and dat == Highest(dat, lbL + 1) and _VStop
            then dat else _nan;
    } else {
        _V = if _BN > lbL and dat == Lowest(dat, lbL + 1) and _VStop
            then dat else _nan;
    }
    plot result = if !IsNaN(_V) and _VStop then _V else _nan;
}

#_inRange(cond) =>
script _inRange {
    input cond = yes;
    input rangeUpper = 60;
    input rangeLower = 5;
    def bars = if cond then 0 else bars[1] + 1;
    def inrange =  (rangeLower <= bars) and (bars <= rangeUpper);
    plot retrun = inrange;
}
def pl = findpivots(divSrc, -1, LookBackLeft, LookBackRight);
def ph = findpivots(divSrc, 1, LookBackLeft, LookBackRight);

def plFound = if !IsNaN(pl) then 1 else 0;
def phFound = if !IsNaN(ph) then 1 else 0;
def vlFound0 = if plFound then divSrc else vlFound0[1];
def vhFound0 = if phFound then divSrc else vhFound0[1];
def plPrice0 = if plFound then lo else plPrice0[1];
def phPrice0 = if phFound then hi else phPrice0[1];

def vlFound = if vlFound0 != vlFound0[1] then vlFound0[1] else vlFound[1];
def vhFound = if vhFound0 != vhFound0[1] then vhFound0[1] else vhFound[1];

def plPrice = if plPrice0 != plPrice0[1] then plPrice0[1] else plPrice[1];
def phPrice = if phPrice0 != phPrice0[1] then phPrice0[1] else phPrice[1];

#// Regular Bullish
def inRangePl = _inRange(plFound[1], MaxLookback, MinLookback);
def oscHL = divSrc > vlFound and inRangePl;
def priceLL = lo < plPrice;
def bullCond = DivBull and plFound and oscHL and priceLL;
#// Hidden Bullish
def oscLL = divSrc < vlFound and inRangePl;
def priceHL = lo > plPrice;
def hiddenBullCond = DivHiddenBull and plFound and oscLL and priceHL;

#// Regular Bearish
def inRangePh = _inRange(phFound[1], MaxLookback, MinLookback);
def oscLH   = divSrc < vhFound and inRangePh;
def priceHH = hi > phPrice;
def bearCond = DivBear and phFound and oscLH and priceHH;
#// Hidden Bearish
def oscHH = divSrc > vhFound and inRangePh;
def priceLH = hi < phPrice;
def hiddenBearCond = DivHiddenBear and phFound and oscHH and priceLH;

#------ Bubbles
AddChartBubble(bubble and bullCond, divSrc, "R", Color.CYAN, no);
AddChartBubble(bubble and bearCond, divSrc, "R", Color.MAGENTA, yes);
AddChartBubble(bubble and hiddenBullCond, divSrc, "H", Color.DARK_GREEN, no);
AddChartBubble(bubble and hiddenBearCond, divSrc, "H", Color.DARK_RED, yes);
#-- Vertica lines
AddVerticalLine(!bubble and bullCond, "Regular", Color.CYAN);
AddVerticalLine(!bubble and bearCond, "Regular", Color.MAGENTA);
AddVerticalLine(!bubble and hiddenBullCond, "Hidden", Color.DARK_GREEN);
AddVerticalLine(!bubble and hiddenBearCond, "Hidden", Color.DARK_RED);

##### Lines
def bar = BarNumber();
#-- Bear Line
def lastPhBar = if phFound then bar else lastPhBar[1];
def prePhBar = if lastPhBar != lastPhBar[1] then lastPhBar[1] else prePhBar[1];
def priorPHBar = if bearCond then prePhBar else priorPHBar[1];
def lastBearBar = if bearCond then bar else lastBearBar[1];
#-- Bull Line
def lastPlBar = if plFound then bar else lastPlBar[1];
def prePlBar = if lastPlBar != lastPlBar[1] then lastPlBar[1] else prePlBar[1];
def priorPLBar = if bullCond then prePlBar else priorPLBar[1];
def lastBullBar = if bullCond then bar else lastBullBar[1];

def HighPivots = if bar == HighestAll(priorPHBar) then 1 else if bar == HighestAll(lastBearBar) then 1 else 0;
def LowPivots  = if bar == HighestAll(priorPLBar) then 1 else if bar == HighestAll(lastBullBar) then 1 else 0;

def pivotHigh = if HighPivots then divSrc else na;
def pivotLow  = if LowPivots  then divSrc else na;

plot PlotHline = if ShowLastDivLines then pivotHigh else na;
PlotHline.EnableApproximation();
PlotHline.SetDefaultColor(Color.MAGENTA);

plot PlotLline = if ShowLastDivLines then pivotLow else na;
PlotLline.EnableApproximation();
PlotLline.SetDefaultColor(Color.CYAN);

#--- Hidden Lines
#-- Bear Line
def priorHPHBar = if hiddenBearCond then prePhBar else priorHPHBar[1];
def lastHBearBar = if hiddenBearCond then bar else lastHBearBar[1];
#-- Bull Line
def priorHPLBar = if hiddenBullCond then prePlBar else priorHPLBar[1];
def lastHBullBar = if hiddenBullCond then bar else lastHBullBar[1];


def HighHPivots = if bar == HighestAll(priorHPHBar) then 1 else if bar == HighestAll(lastHBearBar) then 1 else 0;
def LowHPivots  = if bar == HighestAll(priorHPLBar) then 1 else if bar == HighestAll(lastHBullBar) then 1 else 0;

def pivotHidHigh = if HighHPivots then divSrc else na;
def pivotHidLow  = if LowHPivots  then divSrc else na;

plot PlotHBearline = if ShowLastHiddenDivLines then pivotHidHigh else na;
PlotHBearline.EnableApproximation();
PlotHBearline.SetDefaultColor(Color.DARK_RED);

plot PlotHBullline = if ShowLastHiddenDivLines then pivotHidLow else na;
PlotHBullline.EnableApproximation();
PlotHBullline.SetDefaultColor(Color.DARK_GREEN);

#-- plot lin Reg
plot LinReg = lrc; # "Linear Regression Slope"
LinReg.SetPaintingStrategy(PaintingStrategy.SQUARED_HISTOGRAM);
LinReg.AssignValueColor(if scolor > 0 then if slrs>slrs[1] then Color.GREEN else Color.DARK_GREEN else
                        if scolor < 0 then if slrs<slrs[1] then Color.RED else Color.DARK_RED else Color.GRAY);

#-- bar Color

AssignPriceColor(if !barColor then Color.CURRENT else
                 if scolor > 0 then if lrc>lrc[1] then Color.GREEN else Color.DARK_GREEN else
                 if scolor < 0 then if lrc<lrc[1] then Color.RED else Color.DARK_RED else Color.GRAY);
#-- ENd Code
 
When I try applying this linear regression slope v2 strategy to a 5 min chart the bubbles are not showing up in real time. The bubbles show up in hindsight after 4 candles have closed after the candle where the bubble eventually shows up. Not sure I'm explaining this right but hope it's making sense. I have it on video via screen recording if that helps but not sure I can post a video here. Would appreciate any insights into this. Am I doing something wrong or is this code not supposed to work in real time? Thank you!
 
When I try applying this linear regression slope v2 strategy to a 5 min chart the bubbles are not showing up in real time. The bubbles show up in hindsight after 4 candles have closed after the candle where the bubble eventually shows up. Not sure I'm explaining this right but hope it's making sense. I have it on video via screen recording if that helps but not sure I can post a video here. Would appreciate any insights into this. Am I doing something wrong or is this code not supposed to work in real time? Thank you!

I apologize. I did not read for comprehension.
I look at this indicator for its linear regression properties.
And didn't even register that you were asking a divergence question.

You are correct, it is not possible to detect the divergences in real time.
It cannot find the divergences until after they have occurred.

If you search divergences on the forum; you will find two types.
1. the Repainters -- majority of the divergence scripts are repainters. They use the high hopes method that the condition will solidify into a real divergence. During strong market directional bias, these can be accurate.
Otherwise, they provide mixed to poor results.

2. the rest of the divergence indicators on the forum will lag and wait until the divergence is defined.
This indicator cannot update in real time.
 
Trying to better understand the inputs and options for this and can't seem to find helpful information online. Might someone please help explain these inputs and options or suggest any resources that would help... Thanks you!
src=close
curve length=50
slope length=5
signal length=13
look back right=5
look back left=5
max lookback=60
min lookback=5
 
Trying to better understand the inputs and options for this and can't seem to find helpful information online. Might someone please help explain these inputs and options or suggest any resources that would help...
Most of the inputs that you are asking for (except the divergence calculations).
Are aspects common to trading.

The specific inputs in your questions are the lengths used in:
Inertia
Linear Regression
and
Moving Averages.

Google these functions and how to apply them to your trading.
Read below how these inputs are being utilized in this thread.


src=close
All scripts need to specify what part of the candle, volume, or data point is being used in calculations.
This script uses a default of the close of the bar


curve length=50
def lrc = Inertia(src, CurveLength);
The above defines the lrc as the inertia function using close and a length of 50
https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Statistical/Inertia

slope length=5
#//Smooth Linear Regression Slope
def slrs = ExpAverage(lrs, SlopeLength);
When using averages, how many bars to average must be inputted.
It is common for short-length-averages to be used for smoothing as in this case.
https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Tech-Analysis/MovingAverage

signal length=13
#//Signal Linear Regression Slope
def alrs = Average(slrs, SignalLength);
When a length of 9-13 bars are using in average calculations; it is often utilized as a Signal Line.
if Linear regression is above its average signal line, it is considered bullish. Below, bearish.
https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Tech-Analysis/MovingAverage

look back right=5
look back left=5
def pl = findpivots(divSrc, 1, LookBackLeft, LookBackRight);
def ph = findpivots(divSrc, 1, LookBackLeft, LookBackRight);
This is specific to divergences. Specifying the definition and character of the divergence
This is where the lag comes in, because it is looking for the definition to form across many bars.
These inputs are used in a customized subscript created and specific to this code.

max lookback=60
min lookback=5
used for the plotting of regular and hidden divergences.
These inputs are used in a customized subscript specific to this code.
 
Last edited by a moderator:
That's super helpful, thank you. Per your suggestions, I googled those specific inputs and reviewed the links you included. I'm still searching for a video that might add another layer of clarity to help me better understand but in the meantime I will keep trying to learn by doing and continue to look for articles/posts that would help.

Would it be theoretically correct if I changed the look back right to equal 1 then the code would wait 1 bar after current bar before showing the 'bubble' instead of waiting 5 bars after current bar?

Reporting back on my attempts to create a conditional order with this study/strategy/code.

I ended up changing the look back right to equal 1. It seemed like the bullish/bearish bubble would show up at the same time the current candle started. I was hoping this was real time enough to trigger an order execution when the current candle opened. So far, I haven't been able to get it to work. I was told by Schwab support that the code might need to be more simplified and streamlined but my attempts have not worked yet.

If anyone knows how to simplify and streamline this code so it would be able real time enough to execute a conditional order I would very much appreciate the help. Thank you!

Here is the conditional order description...
1. Submit the following order: BUY +1 JNJ at current market price. The order is valid until it is either filled or cancelled.
2. Wait until the following condition is satisfied: JNJ STUDY 'Study(). "up" is true;5m' IS TRUE. This order will show a WAIT COND status during waiting.

Here's the code for the Study...
declare upper;
input src = close;
input CurveLength = 50; #, minval = 1, title = "Curve Length")
input SlopeLength = 5; #, minval=1, title="Slope Length")
input SignalLength = 13; #, minval=1, title="Signal Length")

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

#//Linear Regression Curve
def lrc = Inertia(src, CurveLength);

#//Linear Regression Slope
def lrs = (lrc - lrc[1]) / 1;

#//Smooth Linear Regression Slope
def slrs = ExpAverage(lrs, SlopeLength);


#//Signal Linear Regression Slope
def alrs = Average(slrs, SignalLength);

#//loalrs = sma(slrs, (glen*5))

#----Div-----------

input LookBackRight = 1; # "Pivot Lookback Right"
input LookBackLeft = 5; # "Pivot Lookback Left"
input MaxLookback = 60; # "Max of Lookback Range"
input MinLookback = 5; # "Min of Lookback Range"
input DivBull = yes; # "Plot Bullish"
input DivBear = yes; # "Plot Bearish"
input DivHiddenBull = no; # "Plot Hidden Bullish"
input DivHiddenBear = no; # "Plot Hidden Bearish"

def bubble = yes;
def divSrc = slrs;
def lo = low;
def hi = high;

script FindPivots {
input dat = close; # default data or study being evaluated
input HL = 0; # default high or low pivot designation, -1 low, +1 high
input lbL = 5; # default Pivot Lookback Left
input lbR = 1; # default Pivot Lookback Right

##############

def _nan; # used for non-number returns
def _BN; # the current barnumber
def _VStop; # confirms that the lookforward period continues the pivot trend
def _V; # the Value at the actual pivot point


##############

_BN = BarNumber();
_nan = Double.NaN;
_VStop = if !IsNaN(dat) and lbR > 0 and lbL > 0 then
fold a = 1 to lbR + 1 with b=1 while b do
if HL > 0 then dat > GetValue(dat, -a) else dat < GetValue(dat, -a) else _nan;
if (HL > 0) {
_V = if _BN > lbL and dat == Highest(dat, lbL + 1) and _VStop
then dat else _nan;
} else {
_V = if _BN > lbL and dat == Lowest(dat, lbL + 1) and _VStop
then dat else _nan;
}
plot result = if !IsNaN(_V) and _VStop then _V else _nan;
}

#_inRange(cond) =>
script _inRange {
input cond = yes;
input rangeUpper = 60;
input rangeLower = 5;

def bars = if cond then 0 else bars[1] + 1;
def inrange = (rangeLower <= bars) and (bars <= rangeUpper);

plot retrun = inrange;
}

def pl = findpivots(divSrc, -1, LookBackLeft, LookBackRight);
def ph = findpivots(divSrc, 1, LookBackLeft, LookBackRight);
def plFound = if !IsNaN(pl) then 1 else 0;
def phFound = if !IsNaN(ph) then 1 else 0;
def vlFound0 = if plFound then divSrc else vlFound0[1];
def vhFound0 = if phFound then divSrc else vhFound0[1];
def plPrice0 = if plFound then lo else plPrice0[1];
def phPrice0 = if phFound then hi else phPrice0[1];
def vlFound = if vlFound0 != vlFound0[1] then vlFound0[1] else vlFound[1];
def vhFound = if vhFound0 != vhFound0[1] then vhFound0[1] else vhFound[1];
def plPrice = if plPrice0 != plPrice0[1] then plPrice0[1] else plPrice[1];
def phPrice = if phPrice0 != phPrice0[1] then phPrice0[1] else phPrice[1];

#// Regular Bullish
def inRangePl = _inRange(plFound[1], MaxLookback, MinLookback);
def oscHL = divSrc > vlFound and inRangePl;
def priceLL = lo < plPrice;
def bullCond = DivBull and plFound and oscHL and priceLL;

#// Hidden Bullish
def oscLL = divSrc < vlFound and inRangePl;
def priceHL = lo > plPrice;
def hiddenBullCond = DivHiddenBull and plFound and oscLL and priceHL;

#// Regular Bearish
def inRangePh = _inRange(phFound[1], MaxLookback, MinLookback);
def oscLH = divSrc < vhFound and inRangePh;
def priceHH = hi > phPrice;
def bearCond = DivBear and phFound and oscLH and priceHH;

#------ Bubbles
AddChartBubble(bubble and bullCond, divSrc, "R", Color.CYAN, no);
AddChartBubble(bubble and bearCond, divSrc, "R", Color.MAGENTA, yes);

plot up = bubble and bullCond;
plot down = bubble and bearCond;
 
Unfortunately no.
Changing the lookback to 1 would yield inaccurate results.
You need to lookback over a range of bars for the divergence to form.
 
Last edited by a moderator:

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

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