Hacktoberfest 2026: những issue maintainer đã đánh dấu cho tháng Mười, đang mở và phù hợp người mới. Xem issue Hacktoberfest

Delisting liquidation proceeds never settle on a Cash account: settlement scan iterates Securities.Values, which excludes delisted securities

Đã đóng
#9,838 0 bình luận 0 reaction 0 người được giao Xem trên GitHub

Maintainer thường phản hồi trong vòng 1 ngày

@abhi-byte62 đang làm issue này rồi.

Từ ngày 6/10/2026.

  • #9840 của @jayzhou2309 — đã đóng, không merge
  • #9873 của @abhi-byte62 — đang mở
  • #9877 của @Martin-Molinero — đang mở

Đánh giá

Độ khó
3/5
Thời gian dự kiến
1-2 ngày
Mức phù hợp với người mới
76/100
Loại issue
Lỗi
Độ rõ ràng
Đặc tả rõ ràng
Mức độ hoạt động
Sôi nổi
Công nghệ
csharp
Lĩnh vực
backend

Hướng nghiên cứu

Start in Engine/AlgorithmManager.cs at AlgorithmManager.Run and compare the settlement scan's use of algorithm.Securities.Values with SecurityManager.Total in Common/Securities/SecurityManager.cs. Read UniverseSelection.HandleDelisting and the delisting liquidation path in BrokerageTransactionHandler, then verify that delayed proceeds for a delisted cash-account security settle after T+1 without changing the margin-interest behavior.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Mô tả

bug

Expected behavior

On a AccountType.Cash account, the proceeds of the automatic "Liquidate from delisting" fill should settle like any other equity sale: DelayedSettlementModel (T+1, 06:00 exchange time by default) moves the amount from UnsettledCashBook to CashBook once the settlement time has passed, so the cash becomes buying power again.

Actual behavior

The liquidation fill lands and the proceeds are added to UnsettledCashBook, but they are never settled for the rest of the backtest. Portfolio.UnsettledCash stays at the full proceeds, Portfolio.Cash and MarginRemaining never recover, while TotalPortfolioValue still counts the money, so the equity curve looks unaffected while the strategy silently cannot redeploy the capital.

Same setup with an ordinary MarketOrder sale of the same security a week earlier settles T+1 correctly, so this is specific to the delisting path.

Cause

AlgorithmManager.Run performs the hourly settlement scan by iterating algorithm.Securities.Values (Engine/AlgorithmManager.cs, foreach (var security in algorithm.Securities.Values) { ... security.SettlementModel.Scan(...) }).

SecurityManager.Values is documented as "Excludes non active or delisted securities" (Common/Securities/SecurityManager.cs). UniverseSelection.HandleDelisting (Engine/DataFeeds/UniverseSelection.cs) sets IsDelisted = true and calls _algorithm.Securities.Remove(data.Symbol) on the Delisted event, in the same time step in which BrokerageTransactionHandler.HandleDelistingNotification fills the synthetic liquidation order and enqueues the proceeds on that security's DelayedSettlementModel.

From that point on the scan loop never visits the delisted security, so DelayedSettlementModel.Scan is never called for it and its _unsettledCashAmounts queue is never drained. Calling Scan by hand from the algorithm drains it immediately (see the log below), which shows the settlement time and the queued amount are both correct and only the scan is unreachable. Securities.ContainsKey still returns true for the symbol (it reads the complete collection), which hides the removal from a casual check.

Margin accounts are unaffected: DefaultBrokerageModel.GetSettlementModel only assigns DelayedSettlementModel to equities when AccountType == Cash.

Reproduce

QC Cloud, LEAN v2.5.0.0.18130 (master). Backtest aff9fc27e21470a270605e2967c91ea1. FMR (First Mercury Financial) was acquired for cash and its map file ends 2011-02-09; any equity held through a delisting reproduces it.

from AlgorithmImports import *


class CashScanProbe(QCAlgorithm):

    def initialize(self):
        self.set_start_date(2011, 1, 20)
        self.set_end_date(2011, 3, 15)
        self.set_cash(100000)
        self.set_brokerage_model(BrokerageName.INTERACTIVE_BROKERS_BROKERAGE, AccountType.CASH)
        eq = self.add_equity("FMR", Resolution.DAILY,
                             data_normalization_mode=DataNormalizationMode.RAW)
        self.fmr = eq.symbol
        self.anchor = self.add_equity("SPY", Resolution.DAILY).symbol  # keeps on_data firing after FMR is gone
        self.bought = False
        self.scanned = False

    def on_data(self, slice):
        bar = slice.bars[self.fmr] if slice.bars.contains_key(self.fmr) else None
        syms = sorted(kvp.key.value for kvp in self.securities)
        sm = self.securities[self.fmr].settlement_model
        self.log(f"STATE {self.time:%Y-%m-%d %H:%M} secKeys={syms} "
                 f"modelUnsettled={sm.get_unsettled_cash().amount} "
                 f"portfolioUnsettled={self.portfolio.unsettled_cash:.2f} cash={self.portfolio.cash:.2f}")
        for s, d in slice.delistings.items():
            self.log(f"DELISTING {s.value} type={d.type} time={d.time:%Y-%m-%d %H:%M}")
        if not self.bought and bar is not None:
            self.market_order(self.fmr, 1000)
            self.bought = True
        # diagnostic only: explicit scan well after the T+1 settlement time has passed
        if not self.scanned and self.time >= datetime(2011, 2, 14):
            self.scanned = True
            p = ScanSettlementModelParameters(self.portfolio, self.securities[self.fmr], self.utc_time)
            self.log(f"MANUALSCAN before unsettled={self.portfolio.unsettled_cash:.2f}")
            sm.scan(p)
            self.log(f"MANUALSCAN after  unsettled={self.portfolio.unsettled_cash:.2f} cash={self.portfolio.cash:.2f}")

    def on_order_event(self, oe):
        self.log(f"ORDEREVENT {oe.utc_time:%Y-%m-%d %H:%M:%S}utc status={oe.status} "
                 f"qty={oe.fill_quantity} px={oe.fill_price} tag={oe.message}")

Log (trimmed):

2011-02-09 00:00 DELISTING FMR type=WARNING time=2011-02-09 00:00
2011-02-09 16:00 STATE secKeys=['FMR', 'SPY'] modelUnsettled=0.0 portfolioUnsettled=0.00 cash=83545.00
2011-02-10 00:00 ORDEREVENT 2011-02-10 05:00:00utc status=FILLED qty=-1000.0 px=16.5 tag=Liquidate from delisting
2011-02-10 00:00 STATE secKeys=['SPY'] modelUnsettled=16500.0 portfolioUnsettled=16500.00 cash=83545.00
2011-02-10 00:00 DELISTING FMR type=DELISTED time=2011-02-10 00:00
2011-02-11 16:00 STATE secKeys=['SPY'] modelUnsettled=16500.0 portfolioUnsettled=16500.00 cash=83545.00
2011-02-14 16:00 STATE secKeys=['SPY'] modelUnsettled=16500.0 portfolioUnsettled=16500.00 cash=83545.00
2011-02-14 16:00 MANUALSCAN before unsettled=16500.00
2011-02-14 16:00 MANUALSCAN after  unsettled=0.00 cash=100045.00

Without the manual scan (same algorithm, the MANUALSCAN block removed) the 16,500 is still unsettled at the end of the run on 2011-03-15.

Control (same setup, ordinary market_order(self.fmr, -1000) on 2011-02-01 instead of holding through the delisting): unsettled 16,450 at the 2011-02-02 fill, cash=99990.00 unsettled=0.00 on 2011-02-03. T+1 settlement works on the normal path.

Proposed change

Run the settlement scan over the securities that can still hold unsettled funds rather than only the active ones. The smallest change is to iterate algorithm.Securities.Total for the SettlementModel.Scan call in AlgorithmManager.Run (keeping Values for the margin-interest call if delisted securities should not accrue interest), so a delisted security keeps being scanned until its queue is empty.

An alternative is to move pending settlements off the per-security model on delisting (e.g. UniverseSelection.HandleDelisting or HandleDelistingNotification forcing a final scan at the settlement time), but the queued item's settlement time is in the future at that point, so a scan-on-removal alone does not settle it.

Open questions

  • Should a delisted security also keep accruing margin interest in that loop, or only settle?
  • Whether the same scan gap affects securities removed by universe selection while they still hold unsettled proceeds (a member removed right after a sale on a cash account). Not tested here.

Reported via Intercom conversation 215476138524644.

Ngôn ngữ chính
C#
Star
22.1k
Fork
5.3k
Merge trung bình
1 ngày 8 giờ
Pull request đã merge (30 ngày)
32

Chuẩn bị môi trường

Mở trong Codespaces

Khởi chạy dev container của dự án ngay trên trình duyệt, bằng tài khoản GitHub của bạn.

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Issue khác của QuantConnect/Lean

Tất cả issue của QuantConnect/Lean

Issue tương tự

Thêm issue về C#

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.