can we use fold to traverse 'the future'?

FutureTony

Well-known member
VIP
...mod note: moved from the quoted thread
i updated the link in my post #2.
in that code i ran a loop to 40, to look for a condition, that i thought should happen within 20 bars.

if you are unsure when a condition would become true to trigger the while statement, yes, you can loop to a big number. i would keep it < 500. experiment to find out what is realistic.
--------------------

lookback is a constant, it won't change. it will be 40 until the user types in a different number.

regarding this, and assuming there is no while statement,

input lookback = 40;
fold k = 1 to lookback...

with a to value of 40,
on each bar, k will count up to 39.
when k=39 , it will process the formulas within the loop, then stop. k won't reach 40. it won't process k being equal to 40.

if a while statement is used in a fold, and the while formula becomes false, the loop will stop and the program will procede to the next code line.
Does anyone know if we can use fold to traverse 'the future'? I'm looking at a problem where I am trying to find the next time in the future a condition will be met and grab that bar number. But fold wants to start at zero and forward by default...
So basically look forward (to a pre-determined max # of bars) until our condition equals true and retrieve that bar number. Is that doable?
 
Last edited by a moderator:
Solution
Yes, as you probably know, close[5] will get the close from 5 bars ago. Likewise, a negative offset such as close[-5] will get the close from 5 bars forward. In the fold, while using GetValue() you can simply add a negative sign to the index.

This would be the basic framework lacking further detail...

Def X = Fold Index = 0 to 10
with Data = Double.NaN
while isNaN(Data) do
if GetValue(Condition,-Index) then GetValue(BarNumber(),-Index)
else Double.NaN;
Yes, as you probably know, close[5] will get the close from 5 bars ago. Likewise, a negative offset such as close[-5] will get the close from 5 bars forward. In the fold, while using GetValue() you can simply add a negative sign to the index.

This would be the basic framework lacking further detail...

Def X = Fold Index = 0 to 10
with Data = Double.NaN
while isNaN(Data) do
if GetValue(Condition,-Index) then GetValue(BarNumber(),-Index)
else Double.NaN;
 
Solution
...mod note: moved from the quoted thread

Does anyone know if we can use fold to traverse 'the future'? I'm looking at a problem where I am trying to find the next time in the future a condition will be met and grab that bar number. But fold wants to start at zero and forward by default...
So basically look forward (to a pre-determined max # of bars) until our condition equals true and retrieve that bar number. Is that doable?

here is an example,
this has a loop that looks at future bars and counts how many are smaller than the current bar. (finds inside bars)
https://usethinkscript.com/threads/congestion-zone.10503/#post-93191

partial code example from the study.
it keeps looping , while 'something is true'
Code:
# inside bar , count smaller bars after the current bar
def max_bars = 50;
def inside_bar_count = fold k = 1 to max_bars
  with q = 1
  while (ht_en and highx[0] >= getvalue(highx, -k) and lowx[0] <= getvalue(lowx, -k))
  do q + 1;
 
Last edited:
@halcyonguy

Q1:
Does this mean, ANY INDICATOR that uses fold functions with future bars (i.e. GetValue(X, -k) ), will result in REPAINTING indicator?

Q2:
I am still not quite get the idea of how can you "fetch" a future, not yet existing bar/value??

Is it that, as time goes by (i.e. new bars forming, BN+1, BN+2, ...), than the conditions at bar BN is fulfilled, the indicator gets updated (thus repaints)?

Why can't we just use current + historical bars to accomplish the same thing, but have to use future, non-existing bars?

Thanks!
 
Last edited:
@halcyonguy Does this mean, ANY INDICATOR that uses fold functions with future bars (i.e. GetValue(X, -k) ), will result in REPAINTING indicator?

I am still not quite get the idea of how can you "fetch" a future, not yet existing bar/value??

Is it that, as time goes by (i.e. new bars forming, BN+1, BN+2, ...), than the conditions at bar BN is fulfilled, the indicator gets updated (thus repaints)?

Thanks!

i don't think so. how i understand it,
repainting occurs when data from a longer second aggregation is used, that changes a signal on a closed candle, that is not the current candle.

someone's words on repainting
https://usethinkscript.com/threads/deepwater_the-one-for-thinkorswim.6518/#post-62913


I am still not quite get the idea of how can you "fetch" a future, not yet existing bar/value??

true, you can't read what doesn't exist yet.
but, a bar in the middle of the chart ( any bar that isn't the last bar), can look at a future existing bar.
every time a new bar appears on the right, the study runs on every bar on the chart. during this time a bar in the middle of the chart can look ahead and read a value
 
but, a bar in the middle of the chart ( any bar that isn't the last bar), can look at a future existing bar.
every time a new bar appears on the right, the study runs on every bar on the chart. during this time a bar in the middle of the chart can look ahead and read a value
==> Yes this explains how you can use "existing" future bars in the middle of the chart.
==> But then, why make the logic complex to use a future bar? Why not just design the logic to start from current/latest bar + historical bar to complete any indicator's logic needs?

https://usethinkscript.com/threads/deepwater_the-one-for-thinkorswim.6518/post-62913

"Repainting means that a confirmation signal (in this case a buy spike or sell spike) disappears after the close of the candle if future conditions change."
==> If we are still traverse the "existing" bars in the middle of the charts, then the indicators will not repaint, since it will paint over new plots when it arrives at the "future" bars as it traverse the chart. However when you arrived at the last/current bar on the chart, and your logic refers to a future bar, then wouldn't the signal at the last/current bar be updated as new future bars formed?
 
==> But then, why make the logic complex to use a future bar? Why not just design the logic to start from current/latest bar + historical bar to complete any indicator's logic needs?

it all depends on what is required for the study to do its desired task. depends on what 'complex' is. sometimes loops are needed to do something.
in my example in post 3, on every bar it uses a loop to look for a quantity of consecutive bars that meet the condition. there is no pattern, every bar will have a different number. without a loop it would take a lot of code to replace it, which may end up being more complex.


However when you arrived at the last/current bar on the chart, and your logic refers to a future bar, then wouldn't the signal at the last/current bar be updated as new future bars formed?

then it wouldn't be the last bar anymore, it would be just a bar before the last bar.

on the current bar, it is the last, there are no future bars.
the logic should be smart enough to recognize when it reaches the last bar, so as not to try reading non existent future bars.
like this ( post10 )
https://usethinkscript.com/threads/...y-demand-zones-for-thinkorswim.172/#post-7048
 
it all depends on what is required for the study to do its desired task. depends on what 'complex' is. sometimes loops are needed to do something.
==> Yes, now I understand you need forward bar logic to determine "you are highest or lowest of RSI value in coming bars", in the following RSI_Divergence example (This is the example why I got into this topic in the first place, by trying to understand why it uses future bars in its fold statement):

# RSI_With_Divergence
# Mobius
# V01.01.2013
# 4.15.2019
#hint:<b>RSI with Divergence</b>
https://usethinkscript.com/threads/rsi-divergence-indicator-with-scanner-for-thinkorswim.9626/


the logic should be smart enough to recognize when it reaches the last bar, so as not to try reading non existent future bars.

==> In the above RSI_Divergence example, the fold statement with future bar, it WILL REPAINT the indicator, after I use on-demand to confirm it bar-by-bar. Specifically is this part of the code:

Code:
# Is current bar's RSI_under_OS value the Lowest? (True or False)
def IsCurrL =
        # If current bar RSI < OverSold
        if RSI < OverSold
        then
            # Floor: Rounds a value down to the nearest integer.
            # n: The min distance between two pivot points.
            fold j = 1 to Floor(n / 2)
            with q = 1 # 1 = true, 0 = false
            while q # While 'q' remains true (q = 1)
                do RSI < getValue(RSI, -j) # q = RSI < getValue(RSI, -j)
                # do: Current RSI < RSI[-j] in future bars?
                # do: Current RSI is lowest against future j=7 bars?
        else 0; # 0 = false

For example, a particular should bring "1" or "0" from the above statement, but instead it will go into a NaN value, and after few new bars appear, the previous NaN value will turn into "1". Specifically, it will need 7 futures bar to appear before repaint (which is defined by the n/2 in the fold statement).
 
Although that was Mobius' code, which he is super awesome, but then the indicator becomes somehow useless as it will only show/repaint after 7 bars, where any price actions will be long gone?
 

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

Thread starter Similar threads Forum Replies Date
J Fold Statement help Questions 1
E question about fold statement Questions 2
Human Fold function Learning Questions 8
MrBruceKA FOLD Education Questions 3
P Workaround for passing a variable to fold? Questions 6

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

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