# fold_help_3
#https://usethinkscript.com/threads/how-do-i-code-a-for-loop.22279/
#How do I code a for loop?
#Bassindora 3/28
#Can someone direct me to example code of a for loop?
#I would like to look at the value of a variable that holds a value that I previously assigned for x (input from the user) number of bars.
#I thought it would look something like this:
#for loopvar = 0 to x
#if signal[x] = 1 then do something
#else do something else
#increment loopvar
#I have seen while and fold statements and am having difficulty deciphering them for my use.
# my guess,
# on every bar,
# read from some past bars,
# look for a desired value in signal,
# add up the quantity of bars that had a desired signal
# how many bars back to read data
input bars_back = 5;
# current bar , and past 4 bars
# define signal variable , 0 or 1
# generate random numbers for this test
def signal = round((random() * 1) - 0, 0);
# display the values below each bar
addchartbubble(1, low*0.998,
signal
, color.cyan, 0);
def desired_value = 1;
# count the past bars with the desired value
def cnt = fold a = 0 to bars_back
# create the loop. pick a letter to use , a
# start with offset 0, so it looks at the current bar
# when the loop counter 'a' reaches the end number, bars_back, it stops. it does not process the loop with a value of bars_back for a.
with b
# pick a letter to use as a temporary holder of data for the loop
while !isnan(getvalue(close, a))
# check if trying to read data from non existant bars. (if on the 5th bar, and try to read data from 10 bars back)
# if not an error , then keep looping
do b + (if getvalue(signal, a) == desired_value then 1 else 0);
# read a value from a past bar, and compare it to a value. if equal then increase the value of b
# when the loop is all done , cnt will equal the value of b, the quantity of desired values
# how many of the 4 past bars , and current bar, had a value of 1
addchartbubble(1, high*1.001,
cnt
, color.yellow, 1);
#