Passing previous calculations

 

Hello,

In the onCalculate method I often want to see for example the value of a moving average 10 bars back. To do that I have a loop that I run for every tick!

for(int n=0; n<10; n++)
        {
         double fMA = iMA(Symbol(), timeframe, ma_period, ma_shift, ma_method, applied_price, i+n); // i is number of current bar
//do sth about it
}

It is quite inefficient, as I calculate the same thing over and over again. Is there any way to pass previous calculations to the next bar?

Cheers

 
dmdamiyo:

Hello,

In the onCalculate method I often want to see for example the value of a moving average 10 bars back. To do that I have a loop that I run for every tick!

It is quite inefficient, as I calculate the same thing over and over again. Is there any way to pass previous calculations to the next bar?

Cheers

Why do you think that you have to loop back?

You don't have to loop back : simply use i+10 in the index (just make sure that i+10 is < Bars)

 

Ok, so I was not clear. For each bar I want to check i+1, i+2, i+3...i+20. So not just the 20th bar back but all bars back up to the 20th.

Imagine that I just want to check if fast MA(5) is below slow MA(10) for every of the 20 bars back. If there was a way to pass previous calculations maybe I wouldn't need to loop 20 bars back for every onCalculate call but implement some smarter algorithm.

Cheers

 

dmdamiyo:

I have a loop that I run for every tick! It is quite inefficient,

I just want to check if fast MA(5) is below slow MA(10) for every of the 20 bars back

  1. Why do you care? The main loop should only be calculating bar zero. See How to do your lookbacks correctly.
  2. Just add a non-visible buffer and increment a count.
    cnt[i] = ima(10,i) > ima(5,i) ? cnt[i+1]+1 : 0;
    If the count is 20 or higher,  you have your check.
 
So I should have a global variable where I will store all the calculations? Unfortunately I don't really see the concept behind the link you posted... I will have to study it a bit more - you said that I should calculate only bar 0 in onCalculate, yet this guy is doing a loop to calculate previous values.
 
So I should have a global variableWhat part of " add a non-visible buffer" was unclear?
I should calculate only bar 0 in onCalculateI didn't say that. After the initial run it should only be doing bar zero. No mind readers here, we can't see your code.