Generate code in 3 minutes
Enter your idea and AI generates runnable code.
Based on the QuantConnect LEAN engine architecture, the processing order for a specific time slice is strictly defined.
The specific order for the events you requested is: Order Fills (for non-market orders) $\rightarrow$ Margin Checks $\rightarrow$ Data Events (OnData).
When LEAN synchronizes data to create a timeslice, it executes the following steps in this specific order:
Security and Cash objects with the latest data prices.on_margin_call_warning or on_margin_call events are triggered immediately.Slice object is passed to the on_data method in your algorithm.on_data method sees the updated portfolio state (cash and holdings) immediately.For a complete context, here is the relevant subset of the execution flow from the documentation:
Security objects with the latest data.Cash objects in the CashBook.on_securities_changed.Dividends, Splits, and Delistings to their respective event handlers.Slice to the on_data method.In Backtesting, market orders are filled synchronously. If you place a market order inside on_data, it is processed immediately, and you will receive the on_order_event before the next line of code in on_data executes (assuming the market is open). In Live Trading, market orders are asynchronous; the fill event will arrive in a future execution loop.
on_margin_call?No, you generally cannot place new entry trades inside on_margin_call. This method is specifically designed for you to return a list of SubmitOrderRequest objects to liquidate positions to satisfy the margin requirement.
on_data run if there is no new data?Yes, if "Fill Forward" is enabled (which is the default setting). The on_data event handler will be triggered regularly with the previous data carried forward, ensuring your logic runs on a consistent heartbeat.