I have a project in live deployment with local LEAN CLI trading a $30,000 margin paper trading account at Alpaca, which takes positions intra-day only, both long and short. The live data updates on a 5 minute interval using this code:

self.consolidator = self.consolidate(self.security.symbol, timedelta(minutes=5), self.on_data_consolidated)
 

I have this scheduled event that is supposed to close all open positions exactly 5 minutes before market close every trading day:

self.schedule.on(self.date_rules.every_day(self.security.symbol), self.time_rules.before_market_close(self.security.symbol, 5), self.close_all)
 

And here's the “self.close_all” function:

def close_all(self):
  if self.portfolio.invested:
    self.liquidate()
 

In backtesting everything works as intended, and open positions are closed exactly 5 minutes before market close. However, during live deployment, the self.liquidate() function does not work at the 5 minutes before close mark. 20 minutes, 15 minutes, and 10 minutes before market close all work as intended in live deployment, as do other times throughout the trading day, but 5 minutes before close does not.

What am I missing? Why doesn't the self.liquidate() function work 5 minutes before market close?