Coding Help (fold, index and while)

RobertPayne

Member
You will need to use a fold loop in thinkScript. More information on this function is available here: https://tlc.thinkorswim.com/center/reference/thinkScript/Reserved-Words/fold.html

Here's an example.

Ruby:
input length = 60;
def countHighTouches = fold i = 0 to length with internalSum = 0 do if GetValue(high, i) == high then internalSum + 1 else internalSum;
plot arrowUp = counthightouches == 3;
arrowup.setpaintingStrategy(paintingStrategy.BOOLEAN_ARROW_UP);
arrowup.setdefaultColor(color.magenta);
arrowup.setlineWeight(3);

K74Gsn1.png
 

tomsk

Well-known member
VIP
@RobertPayne I looked at your little snippet above, shouldn't we look at GetValue(high, -i) rather than GetValue(high, i)?

Notice the minus sign in front of the variable "i"? I'm pretty sure that would be the case but thought I'd run this by you to confirm.

Here is the revised script if so:

Code:
input length = 60;
def countHighTouches = fold i = 0 to length with internalSum = 0 do if GetValue(high, -i) == high then internalSum + 1 else internalSum;
plot arrowUp = counthightouches == 3;
arrowup.setpaintingStrategy(paintingStrategy.BOOLEAN_ARROW_UP);
arrowup.setdefaultColor(color.magenta);
arrowup.setlineWeight(3);
 

venus360

New member
Can someone help with the thinkscript code to do the following? (I am a thinkscript newbie. I see the reference has fold, index, and while examples but don't know how to do program)

Let us assume following sequence of Up or Down points happened for the past 8 (or n) periods.
+1, +2, +3, -1, -2, -3, +4, +5
Bonus (If I can give more weightage to the most recent periods, it would be great)

I want to store in a variable upPoints adding up +1,+2,+3, +4,+5 = 15
I want to store in a variable downPoints adding up -1, -2, -3 = 6

I then want to plot (the ratio) upPoints / downPoint

Thanks a lot.
 
At first glance, you'll need to write a function that filters neg/pos values from the array & set each new array to it's own variable (upPoints, downPoints). Then recursively iterate over each in order to add the values together (similar to the reduce() method in javascript). If i have some time after market today i'll try to post some example code.
 

venus360

New member
Thank you @markos

I am sorry, if it is not clear. Here is more explanation.

I am looking to find Divergence of price and this ratio (up-down points) using the following method and back test for results.

I will use it with Daily charts but any period more than 15 mins should provide good results. Candle chart for price and plotting this ratio as a line (just like a moving average).

Let us assume following sequence of Up or Down points happened for the past 8 (or n) periods.
+1, +2, +3, -1, -2, -3, +4, +5

Bonus (If I can give more weightage to the most recent periods, it would be great)

What I wrote below is my crude form of pseudo code. Based on @eddielee394's response, he understood what I want. Only thing is I don't know how to code this piece. If I get some snippets of code, I will be able to put the whole thing together.

I want to store in a variable upPoints adding up +1,+2,+3, +4,+5 = 15
I want to store in a variable downPoints adding up -1, -2, -3 = 6

I then want to get (the ratio) upPoints / downPoint and then plot

I want to then plot this in the lower part of the chart (like an oscillator).

Hope this is better.
 

tomsk

Well-known member
VIP
@venus360 Per your request here is a study that plots the ratio of Up/Down points relative to the prior candle that utilizes the fold() construct. I have used 8 candles(periods) as per your description. Additionally I have verified the accuracy of the results by comparing it with manual computations of a stock like AMZN. The results were identical.

Code:
# UpPoints DownPoints Ratio
# tomsk
# 1.17.2020

# Plots the ratio of Up/Down points relative to the prior candle

declare lower;

def upPoints   = fold i = 0 to 8
                 with p
                 do p + GetValue(if close > close[1] then close - close[1] else 0, i);
def downPoints = fold j = 0 to 8
                 with r
                 do r + GetValue(if close < close[1] then close - close[1] else 0, j);
plot ratio = upPoints / AbsValue(downPoints);

AddLabel(1, "Up Points = " + upPoints, Color.Yellow);
AddLabel(1, "Down Points = " + downPoints, Color.Yellow);
# End UpPoints DownPoints Ratio
 

velocity12345

New member
I am trying to do the following: I have a support level on each and every bar. I want to know what (day/bar) support was breached for a certain number of days held going forward and then place the number of days above the starting bar.

For example lets say on January 29th the SPX Support level was 3240 and lets say the "DaysHeld" equals 5. The study would then check to see if the next bar, 1-30-20, low is less than 3240, if not it goes to the next day, 1-31-20, if the low is less than 3240, (lets say it is) then the DaySupportBroken would equal 2. Then the days it took to break support would be placed on the 1-29-20 bar. ie. a number 2 would be placed above 1-29-20. If no low broke support from 1-29-20 going forward 5 days then then a zero would be placed above 1-29-20

This is what I have:

Code:
input DaysHeld   =  5;
def PivotLevel = MovAvgExponential(low, DaysHeld ) - 96.62 ;  #rigged value to break support
plot PivotLevelPlot =  PivotLevel ;
PivotLevelPlot.SetDefaultColor(Color.CYAN);
PivotLevelPlot.SetLineWeight(2);
PivotLevelPlot.SetPaintingStrategy(PaintingStrategy.DASHES);

def DaySupportBroken   = fold idx = 1 to DaysHeld with s = 0 do if Low < Less than the <startbar>support then tell me what day it broke support else 0;

plot CountDayBroken = DaySupportBroken ;
CountDayBroken SetPaintingStrategy(PaintingStrategy.Values_Above);

Any help would be greatly appreciated.

thanks,
 

HawaiianIceberg

New member
I'm using a fold statement and want to have the "to" portion of the loop set to a dynamic number, as opposed to a static one. Like this, where BarsAgoForHigh is calculated previously using a different Fold statement

Def GetLowest = fold j = 0 to BarsAgoForHigh

In other words, BarsAgoForHigh is recalculated every bar, and the fold statement needs to loop that many times

If I set it to a static number, like this, it loops the desired 5 times:

Def GetLowest = fold j = 0 to 5

Here's more specifically what I'm doing. I'm looking for a large upward price swing, followed by price stabilization.

In this example, the stabilization period is 7 days, and the time-frame for the price swing up is 21. So price went up in days 1 through 21, then stabilized in week 4 (days 22-28).

This is the logic:

Starting with 7 days ago, Look back at the prior 21 days to see if there is a jump in price

def HighestHigh = Highest(High[7], 21); # Find the highest high from 7 bars ago back to 28 days ago
def LowestLow = Lowest(Low[7], 21); # Find the highest high from 7 bars ago back to 28 days ago

If there is a price jump, I use a fold loop to calculate how many bars back the highest high was (This variable is called BarsAgoForHigh)

def BarsAgoForHigh = fold i = 0 to 7 with t = 0
do
if high == HighestHigh then
(
t+i
)
else
(
t
);

Then, I use another Fold loop to evaluate what the lowest low is since that high point, which occurred BarsAgoForHigh bars ago. This is where the problem is

def GetLowest = fold j = 0 to BarsAgoForHigh with u = 10000
do
if getvalue(low, j+1) < getvalue(low, j) && getvalue(low, j+1) < u then
(
u*0+ getvalue(low, j+1)

)
else
(
u
);


When BarsAgoForHigh is static (for example, 5), it plots fine
When BarsAgoForHigh is dynamic (as outlined above) it doesn't plot anything (not even other simple plot commands in the study)


The function Lowest(low, BarsAgoForHigh) would be great, however it also does not allow a dynamic length (that's why I turned to Fold loops)

Thank you in advance. I'm just learning this language and find its simplicity can be difficult to work with

side note, is there a way to have an if statement that has multiple then commands lol?

303194d1595374461
 
Last edited by a moderator:

D_Tramp

New member
VIP
Hi!
Please help me.
I'm not a coder and this problem took a few days, but I still can't figure out how to transform this code into Tradingview:
Code:
input n = 10;
plot factorial = fold index = 1 to n + 1 with p = 1 do p * index;

Help me please.
Thank you.
 

HighBredCloud

Well-known member
VIP
Hey All. Would anyone have the time to solve a fold question?
In the below script, would anyone be able to write the avgVolume without using fold?

Code:
# Relative Volume to past days Average Relative Volume 
# Mobius 
# Chat Room Request 01.23.2017 

declare lower;
input length = 10;
def v = volume ;
def bn = BarNumber();
def isOpen = GetTime() >= RegularTradingStart(GetYYYYMMDD()) and GetTime() < RegularTradingEnd(GetYYYYMMDD());
def bars = if bn == 1 then 1 else if isOpen then bars[1] + 1 else 0;
def newDay = GetDay() != GetDay()[1];
def DayVol = if newDay   
                       then v 
                       else DayVol[1] + v;
def avgVolume = (fold day = 0 to length   
                               with s   
                               do s + GetValue(DayVol, day * bars)) / length;

plot R = DayVol / avgVolume * 100;
R.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
R.AssignValueColor(if R > 100 
                                            then Color.GREEN 
                                           else Color.RED);

plot Average = 100;
Average.SetDefaultColor(Color.YELLOW);
Average.HideTitle();
AddLabel(1, "Displays as a Relative % of Avg Volume", Color.WHITE); 

# End Code
 

Similar threads

Top