# Fold()

#### british43

##### Member
VIP
Is there a different way I can express the "fold i = 0 to x with s do s + GetValue(y, i)"?

Is there a different way I can express the "fold i = 0 to x with s do s + GetValue(y, i)"?

are you wanting to add up a series of bars?

def z = sum( y , x);

@halcyonguy When I tried to scan I'm receiving an error code "Folding: integer 'to' is expected. NaN".

Ruby:
``````# BreakoutRegression_v2020_12_18_JQ
# all the heavy lifting by:
# Breakout Regression v.02
# Nube 3.25.20
# This version does the last two breakouts
# Based on the thoughts shared by Mobius below
#14:37 Mobius: It's not that complicated.. Long Entry: You start with a 5 period LRL that changes slope from delta negative to positive.  Enter a trade at the current LRL price. Then each new bar the length increases by one bar and the slope is recalculated. If still delta positive then you repeat that until you reach x bars. That is the final LRL length and Slope is check until it changes to delta negative and you exit the trade.

#The logic of that method compensates for random price and smooths the volatility. A Regression line is only relevant for the current bar.  So that method makes the highest and best use of a regression line.

# REVISIONS AND VERSIONING
# 12.18.2020  combined enhancements from two previous versions

Script E {
input y = close;
input x = close;
plot E_ = fold i = 0 to x with s do s + GetValue(y, i);
}

# Inputs
input n = 50;#hint n: number of bars for lenght of range
input CenterLine = { default "Hide", "Display" };
input Band = { default "Hide", "Display" };
input priorChannel = { default "Hide", "Display" };

# Variables
def h = high;
def l = low;
def c = close;
def y = HL2;
def nan = Double.NaN;
def bar = BarNumber();
def currentBar = HighestAll(if !IsNaN(c) then bar else nan);
def lower_ = Lowest(c, n)[1];
def upper_ = Highest(c, n)[1];
def long = if c crosses above upper_
then 1
else if c crosses below lower_
then 0
else long[1];
def btoBar = if long crosses above 0 then bar else btoBar[1];
def stoBar = if long crosses below 1 then bar else stoBar[1];
def startBar = Max(HighestAll(btoBar), HighestAll(stoBar)) - n;

def x = CompoundValue(1,
if Between(bar, startBar, currentBar)
then x[1] + 1
else x[1], 0);
def Ex  = E(x, currentBar - startBar);
def Ey  = E(y, currentBar - startBar);
def Exy = E(y * x, currentBar - startBar);
def Exx = E(x * x, currentBar - startBar);
def b = ((currentBar - startBar) * Exy - (Ex * Ey)) /
((currentBar - startBar) * Exx - (Ex * Ex));
def getB = if Between(bar, startBar, currentBar)
then GetValue(b, bar - currentBar)
else nan;
def a = (HighestAll(if bar == currentBar then Ey else nan) - getB *
HighestAll(if bar == currentBar then Ex else nan)) / (currentBar - startBar);
def regression = a + getB * x;
def stDev = Sqrt(Fold stDev_index = 0 to Floor(currentBar - startBar)  with
variance while !IsNaN(regression) do variance +
(Sqr(GetValue(y, stDev_index) - Average(y, n))) /
(currentBar - startBar));
def endLevel = if bar == currentBar then regression else endLevel[1];
def slope = if bar == currentBar then regression - regression[1] else slope[1];
plot t = regression - regression[1];
t.hide();

# Plots
plot
UpperBand = if isNaN(c) then nan else upper_;
UpperBand.SetStyle(Curve.MEDIUM_DASH);
UpperBand.SetDefaultColor(Color.DARK_GREEN);
UpperBand.SetLineWeight(1);
UpperBand.HideTitle();
UpperBand.HideBubble();
UpperBand.SetHiding(!Band);

plot
LowerBand = if isNaN(c) then nan else lower_;
LowerBand.SetDefaultColor(Color.DARK_RED);
LowerBand.SetStyle(Curve.MEDIUM_DASH);
LowerBand.SetLineWeight(1);
LowerBand.HideTitle();
LowerBand.HideBubble();
LowerBand.SetHiding(!Band);

plot
BTO = bar == HighestAll(btoBar);
BTO.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
BTO.SetDefaultColor(Color.LIGHT_GREEN);
#### addchartbubble ( 1, LowestAll(low), "BTO\n" + BTO, Color.WHITE, no);

plot
STO = bar == HighestAll(stoBar);
STO.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
STO.SetDefaultColor(Color.RED);
#### addchartbubble ( 1, LowestAll(low), "STO\n" + STO, Color.WHITE, no);

plot
Mean = regression;
Mean.SetLineWeight(1);
Mean.AssignValueColor(if Mean < Mean[1] then Color.RED else Color.GREEN);
Mean.HideBubble();
Mean.SetHiding(!CenterLine);

plot
Lower = Mean - ((HighestAll(stDev) + LowestAll(stDev)) / 2);
Lower.SetStyle(Curve.Firm);
Lower.AssignValueColor(Mean.TakeValueColor());
Lower.HideBubble();
Lower.HideTitle();

plot
Upper = Mean + ((HighestAll(stDev) + LowestAll(stDev)) / 2);
Upper.SetStyle(Curve.Firm);
Upper.AssignValueColor(Mean.TakeValueColor());
Upper.HideBubble();
Upper.HideTitle();

plot
Extension = if bar >= currentBar then endLevel + slope * (bar - currentBar) else nan;
Extension.SetLineWeight(1);
Extension.AssignValueColor(if Extension < Extension[1] then Color.RED else Color.GREEN);
Extension.HideBubble();
Extension.HideTitle();
Extension.setHiding(!CenterLine);

plot
LowerExtension = Extension - ((HighestAll(stDev) + LowestAll(stDev)) / 2);
LowerExtension.SetStyle(Curve.FIRM);
LowerExtension.AssignValueColor(Extension.TakeValueColor());
LowerExtension.HideBubble();
LowerExtension.HideTitle();

plot
UpperExtension = Extension + ((HighestAll(stDev) + LowestAll(stDev)) / 2);
UpperExtension.SetStyle(Curve.FIRM);
UpperExtension.AssignValueColor(Extension.TakeValueColor());
UpperExtension.HideBubble();
UpperExtension.HideTitle();``````

@halcyonguy When I tried to scan I'm receiving an error code "Folding: integer 'to' is expected. NaN".

Ruby:
``````# BreakoutRegression_v2020_12_18_JQ
# all the heavy lifting by:
# Breakout Regression v.02
# Nube 3.25.20
# This version does the last two breakouts
# Based on the thoughts shared by Mobius below
#14:37 Mobius: It's not that complicated.. Long Entry: You start with a 5 period LRL that changes slope from delta negative to positive.  Enter a trade at the current LRL price. Then each new bar the length increases by one bar and the slope is recalculated. If still delta positive then you repeat that until you reach x bars. That is the final LRL length and Slope is check until it changes to delta negative and you exit the trade.

#The logic of that method compensates for random price and smooths the volatility. A Regression line is only relevant for the current bar.  So that method makes the highest and best use of a regression line.

# REVISIONS AND VERSIONING
# 12.18.2020  combined enhancements from two previous versions

Script E {
input y = close;
input x = close;
plot E_ = fold i = 0 to x with s do s + GetValue(y, i);
}

# Inputs
input n = 50;#hint n: number of bars for lenght of range
input CenterLine = { default "Hide", "Display" };
input Band = { default "Hide", "Display" };
input priorChannel = { default "Hide", "Display" };

# Variables
def h = high;
def l = low;
def c = close;
def y = HL2;
def nan = Double.NaN;
def bar = BarNumber();
def currentBar = HighestAll(if !IsNaN(c) then bar else nan);
def lower_ = Lowest(c, n)[1];
def upper_ = Highest(c, n)[1];
def long = if c crosses above upper_
then 1
else if c crosses below lower_
then 0
else long[1];
def btoBar = if long crosses above 0 then bar else btoBar[1];
def stoBar = if long crosses below 1 then bar else stoBar[1];
def startBar = Max(HighestAll(btoBar), HighestAll(stoBar)) - n;

def x = CompoundValue(1,
if Between(bar, startBar, currentBar)
then x[1] + 1
else x[1], 0);
def Ex  = E(x, currentBar - startBar);
def Ey  = E(y, currentBar - startBar);
def Exy = E(y * x, currentBar - startBar);
def Exx = E(x * x, currentBar - startBar);
def b = ((currentBar - startBar) * Exy - (Ex * Ey)) /
((currentBar - startBar) * Exx - (Ex * Ex));
def getB = if Between(bar, startBar, currentBar)
then GetValue(b, bar - currentBar)
else nan;
def a = (HighestAll(if bar == currentBar then Ey else nan) - getB *
HighestAll(if bar == currentBar then Ex else nan)) / (currentBar - startBar);
def regression = a + getB * x;
def stDev = Sqrt(Fold stDev_index = 0 to Floor(currentBar - startBar)  with
variance while !IsNaN(regression) do variance +
(Sqr(GetValue(y, stDev_index) - Average(y, n))) /
(currentBar - startBar));
def endLevel = if bar == currentBar then regression else endLevel[1];
def slope = if bar == currentBar then regression - regression[1] else slope[1];
plot t = regression - regression[1];
t.hide();

# Plots
plot
UpperBand = if isNaN(c) then nan else upper_;
UpperBand.SetStyle(Curve.MEDIUM_DASH);
UpperBand.SetDefaultColor(Color.DARK_GREEN);
UpperBand.SetLineWeight(1);
UpperBand.HideTitle();
UpperBand.HideBubble();
UpperBand.SetHiding(!Band);

plot
LowerBand = if isNaN(c) then nan else lower_;
LowerBand.SetDefaultColor(Color.DARK_RED);
LowerBand.SetStyle(Curve.MEDIUM_DASH);
LowerBand.SetLineWeight(1);
LowerBand.HideTitle();
LowerBand.HideBubble();
LowerBand.SetHiding(!Band);

plot
BTO = bar == HighestAll(btoBar);
BTO.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
BTO.SetDefaultColor(Color.LIGHT_GREEN);
#### addchartbubble ( 1, LowestAll(low), "BTO\n" + BTO, Color.WHITE, no);

plot
STO = bar == HighestAll(stoBar);
STO.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
STO.SetDefaultColor(Color.RED);
#### addchartbubble ( 1, LowestAll(low), "STO\n" + STO, Color.WHITE, no);

plot
Mean = regression;
Mean.SetLineWeight(1);
Mean.AssignValueColor(if Mean < Mean[1] then Color.RED else Color.GREEN);
Mean.HideBubble();
Mean.SetHiding(!CenterLine);

plot
Lower = Mean - ((HighestAll(stDev) + LowestAll(stDev)) / 2);
Lower.SetStyle(Curve.Firm);
Lower.AssignValueColor(Mean.TakeValueColor());
Lower.HideBubble();
Lower.HideTitle();

plot
Upper = Mean + ((HighestAll(stDev) + LowestAll(stDev)) / 2);
Upper.SetStyle(Curve.Firm);
Upper.AssignValueColor(Mean.TakeValueColor());
Upper.HideBubble();
Upper.HideTitle();

plot
Extension = if bar >= currentBar then endLevel + slope * (bar - currentBar) else nan;
Extension.SetLineWeight(1);
Extension.AssignValueColor(if Extension < Extension[1] then Color.RED else Color.GREEN);
Extension.HideBubble();
Extension.HideTitle();
Extension.setHiding(!CenterLine);

plot
LowerExtension = Extension - ((HighestAll(stDev) + LowestAll(stDev)) / 2);
LowerExtension.SetStyle(Curve.FIRM);
LowerExtension.AssignValueColor(Extension.TakeValueColor());
LowerExtension.HideBubble();
LowerExtension.HideTitle();

plot
UpperExtension = Extension + ((HighestAll(stDev) + LowestAll(stDev)) / 2);
UpperExtension.SetStyle(Curve.FIRM);
UpperExtension.AssignValueColor(Extension.TakeValueColor());
UpperExtension.HideBubble();
UpperExtension.HideTitle();``````

well, that is about as different from the original question as can be.....

i don't scan, so i don't know.

my guesses,

this chart study is too complex to be run as a scan.
maybe the stDev = fold formula is too complex?
try to disable all the formulas that don't contribute to your desired output. disable the plots. that will remove many highestall's.
maybe that will help?

in the script E , x should be an integer, not a price. it is used as a count number in a fold. change it to = 0.
inputs in subs can be set to 0, then when called, real values will be passed into the script.

original
Script E {
input y = close;
input x = close;

new
Script E {
input y = close;
input x = 0;

there are 11 plots. disable them and configure 1 plot for an output, as 1 or 0.

@halcyonguy Tried but I failed. I also tried making the line for this regression long both ways but failed also. I **** at doing extensions. Is there a line of code that works great for extension for at the end or begin of the line?

Ruby:
``````input price = close;
input deviations = .8;  #set your deviation units here.
input length = 100; #set your channel lookback period here.
input opacity = 50;
input showlabels = yes;

def regression = InertiaAll(price, length);
def stdDeviation = StDevAll(price, length);

def bar = BarNumber();
def currentBar = HighestAll(if !IsNaN(close) then bar else Double.NaN);

def endLevel = if bar == currentBar then regression else endLevel[1];
def slope = if bar == currentBar then regression - regression[1] else slope[1];

def Extension = if bar >= currentBar then endLevel + slope * (bar - currentBar) else Double.NaN;

plot UpperLine = regression + deviations * stdDeviation;
plot LowerLine = regression - deviations * stdDeviation;``````

Fold function Learning Questions 8
FOLD Education Questions 3
Workaround for passing a variable to fold? Questions 6
Nested Fold Function Debugging Questions 4
Fold Function Counter Questions 3

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