Caching
Caching indicator results
There are IContext.GetData (...) methods for caching indicator results, which can work with three types of lists: double, int, bool.
In the last article, we calculated the SMA indicator in this way:
During optimization, the calculation of SMAs with the same period will be repeated many times. To remove unnecessary calculations and reduce optimization time, caching exists. The previous example can be rewritten as follows:
The GetData method works with the data cache, the cache is a table KEY - VALUE. Where KEY is a row, it is always unique in the table, several identical keys cannot exist. VALUE is a list of values (double, int, bool).
The GetData method takes three parameters:
The first parameter is the key prefix. In this example, it is “SMA”.
The second parameter is an array of strings from which the end of the key is built. In this example, the value of the period is transmitted in the form of a string (PeriodFast.ToString ()), for example, it is 100. Then the full name of the key will be "SMA: 100". If several values were transmitted, for example 100, 20, 40, then the key would be "SMA: 100: 20: 40".
The third parameter is a delegate that is called if there is no data in the cache for the given key. That is, this is the calculation of the indicator values. The delegate should return a list of double, int, or bool values.
How it works. Initially, the data cache is empty. When we request the calculation of SMA with a period of 100, the key "SMA: 100" is generated. This key is looked up in the cache table, but it is not there, since the table is empty. Then a delegate is called that calculates the SMA value. The result is written to the cache table with the key "SMA: 100" and the GetData method returns this result. If we again request SMA calculation with a period of 100, then the key "SMA: 100" will be searched in the cache table. Since it is, the GetData method will immediately return the value for this key, and the delegate will not be called.
The value cache is flushed on each recount of the script. In optimization mode, the cache is not flushed.
An example of a script with caching of two moving averages:
Consider an example with complex caching. For example, we need to build the border of the upper channel at maximum prices, and then smooth this border by SMA. It turns out that the channel calculation depends on the channel period, and the SMA calculation depends on the SMA period and on the channel period. Therefore, when calculating the SMA, two parameters must be passed, the SMA period and the channel period. Full example:
Remember that if the caching parameters are set incorrectly, the optimization results will be incorrect.
Last updated