Exploration condition based on the number of bars available

I have got an exploration that filters out stocks if they are below the 200 day MA. Unfortunately this only works when there are at least 200 available bars. What I would like to happen is for the exploration to do this.

If there are more than 200 available bars

Trendup = Close>ma(Close,200);

If there are less than 200 available bars

Trendup = Close>MA(Close,50);

I have tried to write this but I'm getting errors and I haven't managed to find out whats wrong. Could someone please help.

firstBar = BarIndex() == 0;

if(BarsSince(firstBar)>200)
{
Trendup=Close>MA(Close,200);

else 

Trendup=Close>MA(Close,50);
}

I am also curious as to why I can plot a 50 period wma on a chart and it will plot from the second bar and yet if I try to plot a 50 period ma I have to wait for 50 bars. Why is this?

I would just do it like this:

ma200 = MA(C,200);
ma50 = MA(C,50);
isTrendUp = IIf(IsNull(ma200), C > ma50, C > ma200);

Regarding your question about MA vs WMA, you will likely find the answer if you look up the official definition of how to calculate a WMA. I don't typically use this indicator, but I believe that moving averages other than simple moving averages (i.e. EMA, WMA, DEMA, AMA, etc.) are typically calculated by applying weights to the previous average and the current value in the data series, unlike a simple moving average which requires n values of the series to calculate MA(n).

3 Likes