Rather than try to fix your code I will start from scratch. When I say I am going to start from scratch what I actually mean is I am going to steal some code from a previous post that is almost identical to your yours. Link to that previous post:
I only had to add a second moving average and replace the close with one of the moving averages. User inputs are included so you can apply any of the moving averages included with Thinkorswim. The lengths of each can also be adjusted. This is a one size fits all solution.
input priceOne = close;
input lengthOne = 2;
input typeOne = AverageType.SIMPLE;
input priceTwo = close;
input lengthTwo = 8;
input typeTwo = AverageType.SIMPLE;
def maOne = MovingAverage(typeOne, priceOne, lengthOne);
def maTwo = MovingAverage(typeTwo, priceTwo, lengthTwo);
def crossAbove = maOne < maTwo and maOne > maTwo;
def crossBelow = maOne > maTwo and maOne < maTwo; rec countAbove = if crossAbove then 1 else if maOne > maTwo then countAbove + 1 else 0;
rec countBelow = if crossBelow then -1 else if maOne < maTwo then countBelow - 1 else 0; plot data = if countAbove > AbsValue(countBelow) then countAbove else countBelow;
data.AssignValueColor(if data == 0 then Color.CURRENT else Color.BLACK);
AssignBackgroundColor(if data > 0 then Color.GREEN else if data < 0 then Color.RED else Color.CURRENT);
Notice that in this solution we display positive values for cross above and negative values for cross below. This is an improvement over the method your code attempts to implement because with this solution you will be able to sort this column numerically. (sorting does not work properly when you try to display text in the column). Another bonus from using this method is there is no limit to the number of bars this code will count. Actually it's only limited by the amount of historical data available to the custom quote.