GoodTilDate time in force ignores the time of day: 10:05 expiry on an equity order is cancelled at the market close, docs say the specified time

オープン
#9,929 コメント 1 件 リアクション 0 件 担当者 0 名 GitHub で見る

メンテナーはふだん 1 日以内に返信

まだ誰も着手していません。

評価

難易度
5/5
見積もり時間
1週間以上
初心者へのやさしさ
35/100
issue の種類
バグ
明瞭さ
おおむね明確
活発さ
活発
技術スタック
csharp
領域
backend, databases

調査の方向性

Start with Common/Orders/TimeInForces/GoodTilDateTimeInForce.cs and trace the expiry checks, then compare the GTD mapping in Brokerages/Backtesting/BacktestingBrokerage.cs and InteractiveBrokersBrokerage.cs. Review the time-in-force documentation example to understand the stated behavior. Done means the intended expiry semantics are decided and implemented consistently across the engine, applicable brokerage mappings, and documentation.

索引モデルが issue の本文から書いたものです。

説明

Expected Behavior

TimeInForce.GoodTilDate(DateTime expiry) honours the time of day in expiry, as the docs state. The Time In Force page (Order Properties > Time In Force) describes GoodTilDate as "Order is valid until filled or the specified expiration time" and its example is a limit order "good until noon": TimeInForce.GoodTilDate(new DateTime(2019, 6, 19, 12, 0, 0)).

Actual Behavior

The time of day is ignored for equities (and options and futures). A US equity limit order submitted at 10:00 ET with GoodTilDate(2024-06-18 10:05:00) stays Submitted at 10:06, at 12:00 and at 15:59, and is cancelled at 16:00 with "The order has expired."

The same date-only semantics are applied when the order goes to a brokerage: the Interactive Brokers integration (QuantConnect.InteractiveBrokersBrokerage/InteractiveBrokersBrokerage.cs, ConvertOrder, non-Forex branch) sets ibOrder.GoodTillDate to exchangeHours.GetNextMarketClose(gtdTimeInForce.Expiry.Date, false) in UTC, so IB receives the exchange close of the expiry date even though IB's goodTillDate field carries a full timestamp.

Either the engine (and the brokerage mappings) should honour the time component, or the docs page should say that GoodTilDate expires at the market close of the expiry date (17:00 New York for Forex and CFD, midnight for crypto) and drop the "good until noon" example.

Reproduce

Cloud backtest in our org: project 38179358, backtest 8dfc7ef01b305647b625814ab0717385, LEAN 2.5.0.0.18198, SPY minute, 2024-06-18.

from AlgorithmImports import *


class GtdIntradayExpiryRepro(QCAlgorithm):
    def initialize(self):
        self.set_start_date(2024, 6, 18)
        self.set_end_date(2024, 6, 18)
        self.set_cash(100000)
        self.set_brokerage_model(BrokerageName.INTERACTIVE_BROKERS_BROKERAGE, AccountType.MARGIN)
        self._spy = self.add_equity("SPY", Resolution.MINUTE).symbol
        self._ticket = None
        self.schedule.on(self.date_rules.every_day(self._spy), self.time_rules.at(10, 0), self._place)
        self.schedule.on(self.date_rules.every_day(self._spy), self.time_rules.at(10, 6), self._check)
        self.schedule.on(self.date_rules.every_day(self._spy), self.time_rules.at(12, 0), self._check)
        self.schedule.on(self.date_rules.every_day(self._spy), self.time_rules.at(15, 59), self._check)

    def _place(self):
        props = InteractiveBrokersOrderProperties()
        props.time_in_force = TimeInForce.good_til_date(datetime(2024, 6, 18, 10, 5, 0))
        price = self.securities[self._spy].price
        limit = round(price * 0.8, 2)
        self._ticket = self.limit_order(self._spy, 10, limit, order_properties=props)
        self.log(f"{self.time}: placed order {self._ticket.order_id}, limit {limit}, GTD 2024-06-18 10:05:00")

    def _check(self):
        if self._ticket is not None:
            self.log(f"{self.time}: order {self._ticket.order_id} status {self._ticket.status}")

    def on_order_event(self, order_event):
        self.log(f"{self.time}: order event {order_event}")

    def on_end_of_algorithm(self):
        if self._ticket is not None:
            self.log(f"end of algorithm: order {self._ticket.order_id} status {self._ticket.status}")

Log:

2024-06-18 10:00:00 order event Time: 06/18/2024 14:00:00 OrderID: 1 EventID: 1 Symbol: SPY Status: Submitted Quantity: 10 LimitPrice: $425.46
2024-06-18 10:00:00 placed order 1, limit 425.46, GTD 2024-06-18 10:05:00
2024-06-18 10:06:00 order 1 status SUBMITTED
2024-06-18 12:00:00 order 1 status SUBMITTED
2024-06-18 15:59:00 order 1 status SUBMITTED
2024-06-18 16:00:00 order event Time: 06/18/2024 20:00:00 OrderID: 1 EventID: 2 Symbol: SPY Status: Canceled Quantity: 10 LimitPrice: $425.46 Message: The order has expired.
2024-06-18 16:00:00 end of algorithm: order 1 status CANCELED

Evidence

  • Common/Orders/TimeInForces/GoodTilDateTimeInForce.cs, IsOrderExpired: for Equity, Option, Future, FutureOption, IndexOption and the default branch, expired = time >= exchangeHours.GetLastDailyMarketClose(Expiry.Date, false) ("expires at market close of expiry date"); Forex and CFD use GetForexOrderExpiryDateTime (17:00 New York, date only); Crypto uses time.Date > Expiry.Date.
  • Brokerages/Backtesting/BacktestingBrokerage.cs ~line 748: order.TimeInForce.IsOrderExpired(security, order) then RemoveOrders(..., OrderStatus.Canceled, "The order has expired.").
  • Lean.Brokerages.InteractiveBrokers, InteractiveBrokersBrokerage.cs (commit fb86123, 2026-10-01), ConvertOrder GTD block: var expiry = exchangeHours.GetNextMarketClose(gtdTimeInForce.Expiry.Date, false); ibOrder.GoodTillDate = expiryUtc.ToString("yyyyMMdd HH:mm:ss UTC", ...); ParseExpiryDateTime returns .Date when reading open orders back.
  • Documentation repo: 03 Writing Algorithms/22 Trading and Orders/09 Order Properties/03 Time In Force.html lines 24-25 and 39-50 (the "good until noon" example).

Proposed change

Decide the intended semantics:

  1. Honour the time: in IsOrderExpired, when Expiry.TimeOfDay != TimeSpan.Zero, expire at Expiry (in the exchange time zone) capped at the day's market close; and in the brokerage mappings that accept a timestamp (IB's GoodTillDate already does), send the time instead of the market close. Backtest and live then agree with the docs.
  2. Or keep the date-only semantics and fix the docs: state that GoodTilDate expires at the market close of the expiry date (17:00 New York for Forex and CFD, midnight for crypto), replace the "good until noon" example, and note that the time component is ignored.

Open questions

  • Other brokerage integrations' GTD mappings would need the same review if option 1 is chosen.

Intercom conversation 215476480160999.

主要言語
C#
スター
22.6k
フォーク
5.4k
平均マージ
11時間 39分
マージ済み PR(30日)
104

環境構築

Codespaces で開く

このプロジェクトの開発コンテナを、あなたの GitHub アカウントでブラウザ上に起動します。

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

QuantConnect/Lean のほかの issue

QuantConnect/Lean の issue をすべて見る

似ている issue

C# の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。