I did not write this code you posted in your question. (I never use variable names such as "X", "Y" or "Z"). This was posted in our Q&A forum? If so, why did you not include a link to that original post? This code you provided does not display moving average crossover. It merely changes the background color based on the relative position of two moving averages. A crossover is when the two lines cross.
As to your request. I spent some time trying to work this out. This one will take way more time than I want to spend for a request in the Q&A forum. In fact at this time I'm not even sure there is a solution. Started down one path and ran into a block wall. But this happens quite often when writing code. Trying to solve problems for which there is no certainty of an answer. You need to be stubborn enough to keep working until the solution is revealed.
Based on feedback from the author of this post I am providing code that counts and displays the number of bars since the most recent cross of two moving averages. The values displayed will be negative for cross below and positive for cross above. With background colored in similar fashion. I have included a low tech way to count the number of days since cross. The input parameter is named barsPerDay and is defaulted to a value of 3. Set this to a value of 1 if you want to count number of bars. Otherwise set it to the number of bars in a day for your selected time frame to count the approximate number of days since the most recent cross.
input maLengthOne = 9;
input maLengthTwo = 21;
input maTypeOne = AverageType.EXPONENTIAL;
input maTypeTwo = AverageType.EXPONENTIAL;
input priceOne = close;
input priceTwo = close;
input barsPerDay = 3;
def maOne = MovingAverage(maTypeOne, priceOne, maLengthOne);
def maTwo = MovingAverage(maTypeTwo, priceTwo, maLengthTwo);
def crossAbove = maOne > maTwo and maOne[1] < maTwo[1];
def crossBelow = maOne < maTwo and maOne[1] > maTwo[1];
rec trackCrossAbove = if crossAbove then 1 else if maOne > maTwo then trackCrossAbove[1] + 1 else 0;
rec trackCrossBelow = if crossBelow then -1 else if maOne < maTwo then trackCrossBelow[1] - 1 else 0;
plot data = if trackCrossAbove > AbsValue(trackCrossBelow) then Round(trackCrossAbove / barsPerDay, 1) else Round(trackCrossBelow, barsPerDay);
data.AssignValueColor(if data > 0 or data < 0 then Color.BLACK else Color.CURRENT);
AssignBackgroundColor(if data > 0 then Color.GREEN else if data < 0 then Color.RED else Color.CURRENT);