Here's the AmiBroker code to calculate the number of bars since the close crossed the OR high or low when in neutral state:
// Assuming you already have OR_state, OR_high, and OR_low defined
// Define the state constants
OR_state_bullish = 0;
OR_state_bearish = 1;
OR_state_neutral = 2;
OR_state_range = 3;
// Initialize the counters
bars_since_below_high = 0;
bars_since_above_low = 0;
// Track if we've ever crossed the levels
ever_crossed_high = 0;
ever_crossed_low = 0;
// Loop through the bars
for (i = 1; i < BarCount; i++)
{
// Check if we're past the OR formation period
if (OR_state[i-1] == OR_state_range AND OR_state[i] != OR_state_range)
{
// Reset counters at the start of a new OR period
bars_since_below_high[i] = 0;
bars_since_above_low[i] = 0;
ever_crossed_high[i] = 0;
ever_crossed_low[i] = 0;
}
else if (OR_state[i] != OR_state_range)
{
// Track if close has crossed OR high
if (Close[i] > OR_high[i])
{
ever_crossed_high[i] = 1;
bars_since_below_high[i] = 0;
}
else if (ever_crossed_high[i-1])
{
bars_since_below_high[i] = bars_since_below_high[i-1] + 1;
ever_crossed_high[i] = 1;
}
else
{
bars_since_below_high[i] = 0;
ever_crossed_high[i] = 0;
}
// Track if close has crossed OR low
if (Close[i] < OR_low[i])
{
ever_crossed_low[i] = 1;
bars_since_above_low[i] = 0;
}
else if (ever_crossed_low[i-1])
{
bars_since_above_low[i] = bars_since_above_low[i-1] + 1;
ever_crossed_low[i] = 1;
}
else
{
bars_since_above_low[i] = 0;
ever_crossed_low[i] = 0;
}
}
}
// Create the final output for neutral state
neutral_bars_since_high = IIf(OR_state == OR_state_neutral AND ever_crossed_high, bars_since_below_high, 0);
neutral_bars_since_low = IIf(OR_state == OR_state_neutral AND ever_crossed_low, bars_since_above_low, 0);
neutral_never_crossed = IIf(OR_state == OR_state_neutral AND NOT ever_crossed_high AND NOT ever_crossed_low, 0, Null);
// Display the values when in neutral state
Filter = OR_state == OR_state_neutral;
AddColumn(neutral_bars_since_high, "Bars Since < OR High", 1.0);
AddColumn(neutral_bars_since_low, "Bars Since > OR Low", 1.0);
AddColumn(neutral_never_crossed, "Never Crossed (0)", 1.0);
This code tracks:
neutral_bars_since_high: Number of bars since close was last above OR high (when currently in neutral)
neutral_bars_since_low: Number of bars since close was last below OR low (when currently in neutral)
neutral_never_crossed: Shows 0 if the close has never crossed either OR boundary since formation
The logic maintains counters that increment each bar the close stays within the range after having crossed a boundary, and resets when a new OR period begins or when the close crosses the boundary again.