跳转到内容

服务器时间

get_current_time() 是同步封装里最适合做连接验证的方法。它对应原始 TWS API 的:

reqCurrentTime() -> currentTime(time_value)

这个请求不依赖行情权限,不读取账户,不涉及订单,因此很适合作为“连接已经可用”的最小测试。

官方 Python API 包中的定义如下:

def get_current_time(self, timeout=1):
self.reqCurrentTime()
return self._wait_for_response(0, "current_time", timeout)

参数说明:

参数含义
timeout等待 currentTime() 回调的秒数

返回值是整数 Unix 时间戳,表示 IBKR 服务器侧时间。

from datetime import datetime, timezone
from ibapi.sync_wrapper import TWSSyncWrapper, ResponseTimeout
app = TWSSyncWrapper(timeout=5)
try:
connected = app.connect_and_start("127.0.0.1", 7497, 943)
print(f"CONNECTED={connected}")
if not connected:
raise RuntimeError("连接 TWS API 失败")
server_time = app.get_current_time(timeout=5)
readable_time = datetime.fromtimestamp(server_time, tz=timezone.utc)
print(f"CURRENT_TIME={server_time}")
print(f"UTC_TIME={readable_time.isoformat()}")
except ResponseTimeout:
print("请求已经发出,但没有在超时时间内收到 currentTime 回调")
finally:
app.disconnect_and_stop()

这段代码只做一件事:确认同步封装能发请求并收到回调。

使用 TWS 模拟账户、127.0.0.1:7497、独立 clientId 检查连接时,常见输出类似:

CONNECTED=True
CURRENT_TIME=1781421671
UTC_TIME=2026-06-14T07:21:11+00:00
IS_CONNECTED_AFTER_STOP=False

看到 CURRENT_TIME 返回,说明:

  • connect_and_start() 已完成连接和消息线程启动。
  • TWS 已返回 nextValidId()
  • reqCurrentTime() 请求成功发出。
  • currentTime() 回调被同步封装接收并返回。

异步写法需要自己实现回调:

def currentTime(self, time_value: int):
print(time_value)

同步写法直接调用:

server_time = app.get_current_time(timeout=5)

两者底层返回的是同一类数据。同步封装只是帮你等待回调,不会改变 TWS API 的请求限制和连接状态。

现象常见原因处理方式
ResponseTimeout没有收到 currentTime() 回调先确认 connect_and_start() 返回 True
504 Not connectedAPI 客户端未连接重新连接并等待 nextValidId()
502连不上 TWS 端口检查 TWS 是否运行、API 是否启用、端口是否正确
返回时间戳但看不懂Unix 时间戳不是格式化日期datetime.fromtimestamp() 转换

如果 get_current_time() 都失败,不要继续调合约、行情、账户或订单接口。先把连接层修好。

IBKR Campus: TWS API Documentation