I would like to pay your attention at the following part of your indicator:
- Code: Select all
local sumy=0;
local sumxy=0;
local sumx=0;
local sumx2=0;
...
function Update()
...
sumy=sumy+zakljucna;
sumxy=sumxy+(zakljucna*test);
sumx=sumx+test;
sumx2=sumx2+(test*test);
end
This will work well only when you have applied your indicator on the static historical data, which never receives updates and never be scrolled back, to upload more data.
Please look at the logic.
1) Your indicator is applied to the chart. sumy is zero.
2) Marketscope starts to calculate the indicator from the oldest (0) bar to newest, calling the Update function once per candle. sumy accumulates the sequental value as it is expected.
3a) Now the user scrolled your chart back, so older data appears in the front of the collection. The marketscope starting to call your indicator for older bars. Oups, but sumy contains the value which already accumulated a sum for newest value!
3b) Now the new tick comes and updates the last candle. The marketscope calls your indicator again to re-caculate the value for the latest candle. In fact, we must substract the previously calculated value for a candle before adding a new one.
You have to do the following to avoid this:
1) Create internal streams for sumy, sumy2, sumx, sumx2
Add the following code into the Prepare function
- Code: Select all
sumy = instance:addInternalStream(0, 0);
sumy1 = instance:addInternalStream(0, 0);
sumx = instance:addInternalStream(0, 0);
sumx2 = instance:addInternalStream(0, 0);
2) For the first candle just put the first value, for further candles - use the stored previous value from the internal streams
- Code: Select all
if period == 0 then
sumy[period] = zakljucna;
else
sumy[period] = sumy[period - 1] + zakljucna;
end
In this way your indicator will be absolutely safe to be recalculated starting at any candle or in case the candle is recalculated multiple times.