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?
Mia Alissi
Here's how you can update your close_all function to help diagnose the problem. This will add detailed logging so you can confirm precisely when the method runs, what your portfolio state is, and what happens when self.liquidate() is called—including any exceptions.
Replace your existing close_all with this, and check your logs after your next live run to see exactly what happens 5 minutes before close:
How this helps:
Likely culprit: Many brokerages (including Alpaca) can restrict or reject market orders very close to the end of the session (for example, within 5 minutes before close). If the log confirms the function fires and Liquidate is called, but the returned order tickets indicate no orders placed or you see exceptions, then it's probably due to order cut-off rules at Alpaca's paper trading environment.
Experiment: Try scheduling to 6 or 7 minutes before market close—if those logs show normal liquidation, but 5-minutes does not, it's almost certainly a broker restriction.
Let me know what the logs say and I can advise further steps!
Sources: Scheduled Events Algorithm, Greeks and IV Implementation, Opening Range Breakout for Stocks in Play, Basic Template Crypto Algorithm, Intraday ETF Momentum
The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.
Andrew
I have replaced the close_all function with the code you provided. For today, I have also scheduled close_all to run at 6 minutes before market close, because I suspect you may be correct regarding broker restriction and because I already know close_all fires at 5 minutes before market close. I will report back with my findings.
Below is an example of a portion of the command window debug output from when close_all runs at 5 minutes before market close. What's interesting is at 5 minutes before market close the close_all function runs and the position fails to liquidate, BUT after that (between 5 and 0 minutes before market close) I am able to close the position manually from the Alpaca dashboard by clicking the “X” next to the open position.
20250616 19:55:01.007 TRACE:: BrokerageTransactionHandler.Process(): 06/16/2025 19:55:01 UTC: Cancel Order: (2) - Liquidated Status: Unprocessed20250616 19:55:01.008 TRACE:: Total margin information: TotalMarginUsed: 14475.89, MarginRemaining: 15768.5920250616 19:55:01.010 TRACE:: LiveTradingResultHandler.OrderEvent(): Time: 06/16/2025 19:55:01 OrderID: 2 EventID: 3 Symbol: <symbol> Status: CancelPending Quantity: -382 StopPrice: $75.2 BrokerId: b1ceb150-beb3-4ddd-8bd2-40c1b4a8bdd6, 74c10ffb-8ff3-4f41-8aae-0504718125a120250616 19:55:01.011 TRACE:: BrokerageTransactionHandler.Process(): 06/16/2025 19:55:01 UTC: Submit Order: (4) - OrderId: 4 (BrokerId: ) New Market order for -382 units of <symbol>: Liquidated Liquidated Status: Unprocessed20250616 19:55:01.012 TRACE:: Total margin information: TotalMarginUsed: 14475.89, MarginRemaining: 15768.5920250616 19:55:01.013 TRACE:: Order request margin information: MarginUsed: 14475.89, MarginRemaining: 44720.3720250616 19:55:01.576 TRACE:: Debug: New Order Event: Time: 06/16/2025 19:55:01 OrderID: 2 EventID: 3 Symbol: <symbol> Status: CancelPending Quantity: -382 StopPrice: $75.220250616 19:55:01.692 TRACE:: LiveTradingResultHandler.OrderEvent(): Time: 06/16/2025 19:55:01 OrderID: 4 EventID: 1 Symbol: <symbol> Status: Invalid Quantity: -382 Message: insufficient qty available for order (requested: 382, available: 0) BrokerId:20250616 19:55:02.706 TRACE:: Debug: New Order Event: Time: 06/16/2025 19:55:01 OrderID: 4 EventID: 1 Symbol: <symbol> Status: Invalid Quantity: -382 Message: insufficient qty available for order (requested: 382, available: 0)20250616 19:55:05.446 TRACE:: AlpacaBrokerage.HandleTradeUpdate: {"event":"canceled","execution_id":"58546ba2-1284-48d0-9eae-5982b76591bd","price":null,"position_qty":null,"qty":null,"timestamp":"2025-06-16T19:55:05.4263898Z","order":{"id":"74c10ffb-8ff3-4f41-8aae-0504718125a1","client_order_id":"7ed5a86a-aaf0-4988-a110-6a50f6183b7a","created_at":"2025-06-16T15:20:00.6498527Z","updated_at":"2025-06-16T19:55:05.4278203Z","submitted_at":"2025-06-16T15:20:00.6616902Z","filled_at":null,"expired_at":null,"canceled_at":"2025-06-16T19:55:05.4263898Z","failed_at":null,"replaced_at":null,"asset_id":"dce2ac30-c928-4416-be25-2213d057f30a","symbol":"<symbol>","asset_class":"us_equity","notional":null,"qty":382.0,"filled_qty":0.0,"type":"stop","order_class":"simple","side":"sell","time_in_force":"gtc","limit_price":null,"stop_price":75.2,"trail_price":null,"trail_percent":null,"hwm":null,"filled_avg_price":null,"status":"canceled","replaced_by":null,"replaces":"b1ceb150-beb3-4ddd-8bd2-40c1b4a8bdd6","legs":null}}20250616 19:55:05.449 TRACE:: LiveTradingResultHandler.OrderEvent(): Time: 06/16/2025 19:55:05 OrderID: 2 EventID: 4 Symbol: <symbol> Status: Canceled Quantity: -382 StopPrice: $75.2 Message: AlpacaBrokerage Order Event BrokerId:b1ceb150-beb3-4ddd-8bd2-40c1b4a8bdd6, 74c10ffb-8ff3-4f41-8aae-0504718125a120250616 19:55:05.851 TRACE:: Debug: New Order Event: Time: 06/16/2025 19:55:05 OrderID: 2 EventID: 4 Symbol: <symbol> Status: Canceled Quantity: -382 StopPrice: $75.2 Message: AlpacaBrokerage Order Event
Andrew
close_all ran correctly at 6 minutes before market close today. This was logged to the console:
20250701 19:54:02.628 TRACE:: Log: [CloseAll] Invoked at: 2025-07-01 15:54:01.000425
20250701 19:54:02.630 TRACE:: Log: [CloseAll] Portfolio invested: True
20250701 19:54:02.632 TRACE:: Log: [CloseAll] Attempting Liquidation...
20250701 19:54:03.636 TRACE:: Log: [CloseAll] Liquidation returned tickets:
[<QuantConnect.Orders.OrderTicket object at 0x7edb0d92a880>]
I've posted this issue to the Alpaca Community forum and will report back if receive a resolution or explanation there.
Andrew
The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.
To unlock posting to the community forums please complete at least 30% of Boot Camp.
You can continue your Boot Camp training progress from the terminal. We hope to see you in the community soon!