vnpy / vnpy_ib

VeighNa框架的InteractiveBrokers交易接口
https://www.vnpy.com
MIT License
34 stars 31 forks source link

TimeZone parsing not resilient #27

Closed tbradlo closed 9 months ago

tbradlo commented 11 months ago

I received following execution.time in execDetails: "'20230928 11:17:24 MET'"

in this case condition if "/" in execution.time: is not executed and exception is thrown during datetime.strptime(time_str, "%Y%m%d %H:%M:%S") -> sth like "MET not expected"

Not all TimeZones have "/" in the name: https://www.dataquest.io/blog/python-datetime/

tbradlo commented 11 months ago

sample testcase:

from datetime import datetime
from unittest import TestCase
from unittest.mock import Mock

from ibapi.contract import Contract
from ibapi.execution import Execution

from vnpy_ib.ib_gateway import IbApi

class TestIbGateway(TestCase):

    def test_SHOULD_convert_EST_date_properly(self):
        # given
        contract = a_contract()
        execution = an_execution(time='20230424 17:15:00 EST')

        ib_gateway = Mock()
        ib_api = IbApi(gateway=ib_gateway)

        # when
        ib_api.execDetails(reqId=1, contract=contract, execution=execution)

        # then
        ib_gateway.on_trade.assert_called_once()
        got_date = ib_gateway.on_trade.call_args[0][0].datetime.strftime('%Y%m%d %H:%M:%S %Z')
        self.assertEqual('20230425 00:15:00 CEST', got_date)

def a_contract():
    return Contract()

def a_time_str():
    datetime.now().strftime('%Y%m%d %H:%M:%S %Z')

def an_execution(time=a_time_str(), side='BOT'):
    execution = Execution()
    execution.time = time
    execution.side = side
    return execution
vnpy commented 11 months ago

Thanks. I will check on this.

noranhe commented 11 months ago

已修复https://github.com/vnpy/vnpy_ib/pull/29

noranhe commented 11 months ago

The strftime function cannot identify IANA time zone such as Hongkong and US/Eastern. Therefore, it is better to split spaces of the time string and convert them separately.