You can use the `strategy.opentrades.entry_bar_index` built-in variable to get the bar index of the open trade. Then compare it with the current bar index.
n = 50
open_idx = strategy.opentrades.entry_bar_index(strategy.opentrades-1)
diff_idx = bar_index - open_idx
if (diff_idx >= n)
strategy.close("buy")