The challenge was that computing the SMA using the full calculation (sum all of the inputs over the window, and divide by window size) took FAR too long...
The result is the attached script which periodically uses the full computation to compare to the incremental one. If the error exceeds a threshold, it increases the frequency with which it checks. If the error is less than the threshold, it decreases the frequency of checks (with limits in both directions). The result is an SMA with the precision required, and close to the speed of the incremental version.
The maximum error is set statically (rMaxErr in the Variables region).
If high precision is ALWAYS required, the window can be set to a negative value. So, -14 will do a 14-period SMA performing the full calculation each time. Using a 14 for the window will typically perform the incremental calculation, and checking this periodically against a full calculation.
The window is limited to a maximum of 254 so that the cache is never exceeded.
If you would like to see when the error threshold is exceeded, un-comment the "Print()" statement.
Please post if you find this helpful.
SharkCub
Comment