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

Open
#9,929 1 comment 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

Nobody has claimed this yet.

Assessment

Difficulty
5/5
Estimated time
Over a week
Newbie friendliness
35/100
Issue type
Bug
Clarity
Mostly clear
Activity status
Active
Tech stack
csharp
Domain
backend, databases

Research direction

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.

Written by the indexing model from the issue text.

Description

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.

Dominant language
C#
Stars
22.6k
Forks
5.4k
Avg merge
11h 39m
Merged PRs (30d)
104

Getting set up

Open in Codespaces

Starts the project's dev container in your browser, under your own GitHub account.

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from QuantConnect/Lean

All issues in QuantConnect/Lean

Similar issues

More C# issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.