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

Aperta
#9,929 1 commento 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
5/5
Tempo stimato
Più di una settimana
Idoneità per principianti
35/100
Tipo di issue
Bug
Chiarezza
Abbastanza chiara
Stato di attività
Attiva
Stack tecnologico
csharp
Ambito
backend, databases

Direzione di ricerca

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.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

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.

Lingua principale
C#
Stelle
22.6k
Fork
5.4k
Merge medio
11h 39m
PR unite (30g)
104

Preparare l'ambiente

Apri in Codespaces

Avvia il container di sviluppo del progetto nel browser, con il tuo account GitHub.

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di QuantConnect/Lean

Tutte le issue di QuantConnect/Lean

Issue simili

Altre issue su C#

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.