If you want to base a trade decision on whether a stock has met some criteria AND how long since it met that criteria, then one would need to store those two pieces of data. I like storing all my data in a single dataframe but one could also put these in separate dictionaries or some other structures.
Basically just add two more columns to the pipeline output dataframe
# Add two other columns to the dataframe for storing days sma50_above_sma200
# And if a crossover was ever observed
output = output.assign(days_sma50_above_sma200 = 0, crossed_over = False)
Next, update these columns.
# Get a list of all securities that are in todays dataframe but NOT yesterdays
# These are the securities which are 'recent crossed over'
# Set 'crossed_over' to True for those. The days_sma50_above_sma200 will remain 0
recent_cross_over = list(set(output.index.tolist()) - set(context.output.index.tolist()))
output.loc[recent_cross_over, 'crossed_over'] = True
# Get a list of any existing securities in todays dataframe AND yesterdays (ie haven't dropped off)
# Copy the crossed_over value and increment the days_since_crossover value
existing = list(set(output.index.tolist()) & set(context.output.index.tolist()))
output.loc[existing, 'crossed_over'] = context.output.crossed_over
output.loc[existing, 'days_sma50_above_sma200'] = context.output.days_sma50_above_sma200 + 1
Finally, use these pieces of data in your ordering logic. Maybe something like this.
# Create the open rules
# In this case a crossover must have happened (ie True) and the days since must be < 5
open_rules = 'crossed_over and (days_sma50_above_sma200 < 5)'
open_these = context.output.query(open_rules).index.tolist()
See the attached algo. This is just one way but in any case one needs to store the count of days since crossover somehow. Then use that count in the order logic.