Problem Description
Solution
To run a function 1 minute before the market closes every day in QuantConnect, you use the self.schedule.on method within the initialize function.
You must combine self.date_rules.every_day(symbol) with self.time_rules.before_market_close(symbol, minutes).
Implementation Details
- Add a Security: You must add a security (e.g., SPY) so the algorithm knows which exchange's operating hours to use.
- Define the Schedule: Use
self.schedule.onto bind the timing rules to a specific method in your class. - Define the Target Method: Create the function that contains the logic you want to execute.
Code Example
#region imports
from AlgorithmImports import *
#endregion
class ScheduledMarketCloseAlgorithm(QCAlgorithm):
def initialize(self):
self.set_start_date(2023, 1, 1)
self.set_end_date(2023, 1, 10)
self.set_cash(100000)
# 1. Add a security to establish the market hours (e.g., US Equity Market)
self.spy = self.add_equity("SPY", Resolution.MINUTE).symbol
# 2. Schedule the event
# self.date_rules.every_day(self.spy): Triggers every trading day for SPY
# self.time_rules.before_market_close(self.spy, 1): Triggers 1 minute before the market closes for SPY
self.schedule.on(
self.date_rules.every_day(self.spy),
self.time_rules.before_market_close(self.spy, 1),
self.execute_before_close
)
def on_data(self, data: Slice):
# Standard data processing
if not self.portfolio.invested:
self.set_holdings(self.spy, 1)
def execute_before_close(self):
"""
This function runs exactly 1 minute before the market closes.
"""
self.log(f"Time: {self.time} - Executing pre-market close logic.")
# Example: Liquidate positions before the day ends to avoid overnight risk
self.liquidate()
Key Considerations
- Symbol Dependency: The
before_market_closerule depends on the specific exchange hours of the symbol provided. If you are trading Crypto (24/7) vs. Equities (9:30-16:00), the "close" time will differ. - Extended Market Hours: If you enable
extended_market_hours=Truewhen adding the equity,before_market_closestill refers to the regular market close (usually 4:00 PM ET for US Equities), not the extended session close. - Time Buffer: Ensure the logic inside your scheduled function can complete within the 1-minute window. If you need more time, increase the minute parameter (e.g.,
before_market_close(self.spy, 5)).
Q&A
Q: Can I schedule the function to run before the market close only on Fridays?
A: Yes. Instead of self.date_rules.every_day(symbol), you can use self.date_rules.every(DayOfWeek.FRIDAY).
Q: Does before_market_close work for Forex or Crypto?
A: Yes, but the definition of "Market Close" varies. For Forex, it is typically Friday at 5 PM ET. For Crypto, which trades 24/7, QuantConnect treats midnight UTC as the daily boundary, but it is generally safer to use specific time rules (e.g., self.time_rules.at(23, 59)) for 24/7 assets to avoid ambiguity.
Q: What happens if the market closes early (e.g., half-day holidays)?
A: The before_market_close rule automatically accounts for early market closures. If the market closes at 1:00 PM instead of 4:00 PM, the event will trigger at 12:59 PM automatically.
Q: Can I pass arguments to the scheduled function?
A: The self.schedule.on method expects a method reference without arguments. If you need to pass data, you should store that data in class-level variables (e.g., self.my_variable) which the scheduled function can access when it runs.