/*[[ Name := Moving Average Author := Copyright © 2003, MetaQuotes Software Corp. Link := http://www.metaquotes.ru/ Separate Window := Yes First Color := Red First Draw Type := Line Use Second Data := No ]]*/ Inputs : VolPeriod(5), VolType(0); Variables : shift(0), cnt(0), loopbegin(0), first(True), prevbars(0); Variables : sum(0), smconst(0), prev(0), weight(0), linear(0); Variables : VolValue(0), Volstring(""); SetLoopCount(0); // initial checkings If VolPeriod < 1 Then Exit; // check for additional bars loading or total reloading If Bars < prevbars Or Bars-prevbars>1 Then first = True; prevbars = Bars; If first Then Begin // loopbegin prevent couning of counted bars exclude current loopbegin = Bars-VolPeriod-1; If VolType = 1 then Begin // exponential MA initialization loopbegin = Bars-3; smconst = 2 / (1+VolPeriod); SetIndexValue(Bars-1,V[Bars-1]); End; If loopbegin < 0 Then Exit; // not enough bars for counting first = False; If VolType = 0 Then Volstring = "simple MA" Else If VolType = 1 Then Volstring = "exponential MA" Else If VolType = 2 Then Volstring = "smoothed MA" Else If VolType = 3 Then Volstring = "linear weighted MA"; print(Volstring, " initialized"); End; // moving average loopbegin = loopbegin+1; // current bar is to be recounted too For shift = loopbegin Downto 0 Begin VolValue=0; // 0 - simple If VolType = 0 Then Begin sum = 0; For cnt = 0 To VolPeriod-1 Begin sum = sum + V[shift+cnt]; End; VolValue = sum/VolPeriod; End // 1 - exponential Else If VolType = 1 Then Begin prev = GetIndexValue(shift+1); VolValue = smconst * (V[shift]-prev) + prev; End // 2 - smoothed Else If VolType = 2 Then Begin If shift = Bars-VolPeriod Then Begin sum = 0; For cnt = 0 To VolPeriod-1 Begin sum = sum + V[shift+cnt]; End; End Else Begin prev = GetIndexValue(shift+1); sum = prev*VolPeriod - prev + V[shift]; End; VolValue = sum/VolPeriod; End // 3 - linear weighted Else If VolType = 3 Then Begin sum = 0; weight = 0; linear = VolPeriod; For cnt = 0 To VolPeriod-1 Begin sum = sum + V[shift+cnt]*linear; weight = weight + linear; linear = linear - 1; End; VolValue = sum/weight; End; SetIndexValue(shift,VolValue); loopbegin = loopbegin-1; // prevent to previous bars recounting End;