# Previous sum of bars where shortMA>longMA

Hello,

I would like to get SUM of bars when MA(C,20)>MA(C,50) last time the situation was completed (ended with situation when MA50 crossed bellow MA20).

Home the picture makes the question understandable: Use SumSince for example ( "!" is equal to "NOT").

``````ma1 = MA(C,20);
ma2 = MA(C,50);
cond = ma1 > ma2;
csum = SumSince(! cond, 1);

Plot( C, "Price", colorDefault, styleCandle );
Plot( ma1, "MA1", colorRed );
Plot( ma2, "MA2", colorYellow );
Plot( csum, "SumBars", colorOrange, styleHistogram | styleOwnScale );
`````` 1 Like

Or perhaps you want to have it like so(?)

``````ma1 = MA(C,20);
ma2 = MA(C,50);
cond = MA(C,20)>MA(C,50);
csum = ValueWhen( cond, SumSince(!cond, 1), 1 );

Plot( C, "Price", colorDefault, styleCandle );
Plot( ma1, "MA1", colorRed );
Plot( ma2, "MA2", colorYellow );
Plot( csum, "SumBars", colorOrange, styleHistogram| styleOwnScale );
Plot( Ref(csum, -1), "PrevSumBars", colorRed, styleHistogram| styleOwnScale );
`````` 2 Likes

And last version (trying to understand what you actually want).
Now you can choose which one.

``````/// @link https://forum.amibroker.com/t/previous-sum-of-bars-where-shortma-longma/6603/4
ma1 = MA(C,20);
ma2 = MA(C,50);
cond = MA(C,20)>MA(C,50);

csum = SumSince(! cond, 1);
vwcsum = ValueWhen( cond, csum );
prevlast = IIf( cond, ValueWhen(csum == 1, Ref(vwcsum, -1)), Null);

Plot( C, "Price", colorDefault, styleCandle );
Plot( ma1, "MA1", colorRed );
Plot( ma2, "MA2", colorYellow );
Plot( csum, "SumBars", colorOrange, styleHistogram | styleLeftAxisScale );
Plot( prevlast, "PrevLastSumBars", colorRed, styleHistogram | styleLeftAxisScale );
`````` 6 Likes

fxshrat thank you so much. The third version was excatly the one I was looking for.