0
votes

How to count number of days since moving averages with length of 20, 50, 100 and 200 stacked one above the other since the last time they moved one above the other.

enter image description here

Please refer to the image attached. Orange is 20 DMA Dark Blue is 50 DMA Green is 100 DMA Red is 200 DMA Starting 25th November, 20 DMA, 50 DMA, 100 DMA, 200 DMA stacked one above the other means 20DMA > 50DMA > 100 DMA > 200 DMA. I would like to get the date from when they are stacked and number of days since they are stacked.

Feb 21,2021 Update after Bajaco provided the function barssince:

I am able to get the days count if I am using a single crossover function in barssince. Please see below image with highlighted areas of code and output of the code.

Code: bsince = tostring(barssince(crossover(sma(close, 20), sma(close, 50))), '#.##')

enter image description here

However, when I use crossover function multiple times, barssince is not providing any result. Not sure what I am doing wrong here.

Code: bsince = tostring(barssince(crossover(sma(close, 20), sma(close, 50)) and crossover(sma(close, 50), sma(close, 100)) and crossover(sma(close, 100), sma(close, 200))), '#.##')

enter image description here

Any help is highly appreciated.

1

1 Answers

0
votes

barssince(a > b and b > c and c > d)

As for the date, check the Time and Session info in the docs. I don't know of way besides saving a variable when all of the conditions are true.

Maybe something like:

var int y = na
var int m = na
var int d = na

ma = sma(close,20)
mb = sma(close,50)
mc = sma(close,100)
md = sma(close,200)
cond = ma > mb and mb > mc and mc > md
if cond
    y := year
    m := month
    d := dayofmonth

But there is probably a better solution