erdewit / ib_insync

Python sync/async framework for Interactive Brokers API
BSD 2-Clause "Simplified" License
2.76k stars 726 forks source link

Incorrect Contract "lastTradeDateOrContractMonth" #605

Closed phcchan closed 1 year ago

phcchan commented 1 year ago

Version: TWS 10.19.2a, ib_insync 0.9.85

During TWS login, choose timezone=Asia/Shanghai UTC+8 (US/Eastern is UTC-4 or UTC-5). Below is a minimal code to reproduce the issue:

import ib_insync as ibi

ib = ibi.IB()
ib.connect('127.0.0.1', 7496, 1234)

opt = ibi.Contract(conId=610457880)  # AAPL monthly option expired on 2025-12-19 US/Eastern
ib.qualifyContracts(opt)
print(opt.lastTradeDateOrContractMonth)  # '20251219'

opt = ibi.Contract(conId=629286394)  # AAPL weekly option expired on 2023-06-23 US/Eastern
ib.qualifyContracts(opt)
print(opt.lastTradeDateOrContractMonth)  # '20230624', but expect '20230623'
#                                                  ^                      ^

ib.disconnect()

In case the weekly option is invalid (expired), any soon expired weekly option contract would produce the same issue.

I believe the issue is originated from ib_insync/decoder.py line 327 during handling the lastTimes. For the montly option, lastTimes reads '20251219'; while for the weekly option, it reads '20230624 04:00:00 Asia/Shanghai'.

erdewit commented 1 year ago

During TWS login, choose timezone=Asia/Shanghai

The lastTradeDateOrContractMonth can be sent either with or without timezone string. There is no automatic timezone conversion in the wrapper.

I would suggest to use choose UTC for the TWS login and to use UTC throughout the code base.