Generate code in 3 minutes
Enter your idea and AI generates runnable code.
In QuantConnect's LEAN engine, the availability of cash from a filled order depends primarily on the Account Type configured for the algorithm (Cash or Margin) and the specific settlement rules of the asset class being traded.
In a Margin account, the buying power from a sale is available immediately.
Portfolio.MarginRemaining and BuyingPower are updated instantly upon the OrderEvent with status Filled.In a Cash account, the cash from a filled sell order is not available until the settlement period passes.
OnData is called.To ensure you are testing the specific cash availability behavior you require, you must set the brokerage model in the initialize method.
class CashSettlementAlgorithm(QCAlgorithm):
def initialize(self):
self.set_start_date(2023, 1, 1)
self.set_cash(100000)
# OPTION 1: Margin Account (Funds available immediately)
# This is the default behavior if not specified.
self.set_brokerage_model(BrokerageName.INTERACTIVE_BROKERS_BROKERAGE, AccountType.MARGIN)
# OPTION 2: Cash Account (Funds locked until settlement)
# Use this to simulate strict settlement rules (e.g., avoiding Good Faith Violations).
# self.set_brokerage_model(BrokerageName.INTERACTIVE_BROKERS_BROKERAGE, AccountType.CASH)
self.add_equity("SPY", Resolution.MINUTE)
def on_order_event(self, order_event):
if order_event.status == OrderStatus.FILLED:
# Check unsettled cash in the portfolio
unsettled = self.portfolio.unsettled_cash
self.debug(f"Order Filled. Unsettled Cash: {unsettled}")
# Check available buying power
buying_power = self.portfolio.margin_remaining
self.debug(f"Available Buying Power: {buying_power}")
| Account Type | Asset Class | Cash Availability |
|---|---|---|
| Margin | Equities, Options, Futures | Immediate (Instant Buying Power update) |
| Cash | US Equities | Delayed (T+2 or T+1 depending on date) |
| Cash | Crypto / Forex | Immediate (Usually T+0) |
Q: How do I check how much cash is currently unsettled in my algorithm?
A: You can access self.portfolio.unsettled_cash to see the total amount of funds currently pending settlement. In a Cash account, this value must drop to zero (or the specific trade amount must settle) before those specific funds are added to self.portfolio.cash.
Q: Does LEAN simulate "Good Faith Violations" (GFV)?
A: LEAN does not explicitly throw a "Good Faith Violation" error that stops the algorithm. However, if you use a Cash account, the engine simply prevents the trade from executing if you do not have settled cash available, effectively simulating the restriction imposed by GFV rules.
Q: When exactly during the day does cash settle?
A: Settlement logic is processed at the beginning of the time step loop. If a trade is scheduled to settle on Day 3, the funds become available for use at market open (or the start of the algorithm's processing loop) on Day 3, prior to the on_data event.