Since you have included your own code I see that you are trying to learn. So rather than simply give you the solution I will walk through your code and let you know where you went astray from your intended goal.
First, let's take a look at the two lines of code where you intended to capture the CCI crossing it's average:
def crossAbove = cciAvg[1] < CCI[1];
def crossBelow = cciAvg[1] > CCI[1];
Those are not crosses. Those two lines are only capturing when the previous bar has the CCI above or below its average. It does not capture a cross of those two lines. This is how we modify them to capture the crosses:
def crossAbove = CCI[1] < cciAvg[1] and CCI > cciAvg;
def crossBelow = CCI[1] > cciAvg[1] and CCI < cciAvg;
Next, we'll examine the code you created for the variable named "counter":
rec counter = if crossAbove then 1 else if crossBelow then -1 else 0;
The problem here is that this code is not counting anything. The 'rec' indicates you intended this to be a recursive variable assignment. However there is no recursion taking place at all.
But we really don't need to use recursion here. And when you see the final result you may not like what you get. Because in practice, this CCI tends to whipsaw back and forth across the average line. So you get on bar crossing above, followed by the next bar crossing below. Furthermore, you have requested that the color change on AFTER the bar that crosses has closed. So you are always one bar late to the party. Very frequently, you will find the color on your watchlist is exactly the opposite of the condition displayed on the chart for the most current (open) bar.
But here is it, flaws and all. Screenshot below shows the result. You can study the lower subgraph on that chart so see how those colors are being determine. This idea would work much better if you used it on a chart study that had crossovers that were scarce, something like the MACD or Stochastic. CCI is just too choppy.
input length = 14;
input cciAvgLength = 9;
input barsAfterCross = 2;
def price = close + low + high;
def linDev = lindev(price, length);
def CCI = if linDev == 0 then 0 else (price – Average(price, length)) / linDev / 0.015;
def cciAvg = Average(CCI, cciAvgLength);
def crossAbove = CCI[1] < cciAvg[1] and CCI > cciAvg;
def crossBelow = CCI[1] > cciAvg[1] and CCI < cciAvg; def counter = if crossAbove[1] then 1 else if crossBelow[1] then -1 else 0; plot value = if Highest(counter, barsAfterCross + 1) > 0 and CCI[1] > cciAvg[1] then 1 else if Lowest(counter, barsAfterCross + 1) < 0 and CCI[1] < cciAvg[1] then -1 else 0;
value.AssignValueColor(if value == 0 then Color.CURRENT else Color.BLACK);
AssignBackgroundColor(if value == 1 then Color.DARK_GREEN else if value == -1 then Color.DARK_RED else Color.CURRENT);