历史行情
get_historical_data() 是对原始历史 K 线回调的同步封装。它对应原始 TWS API 的:
reqHistoricalData( reqId, contract, endDateTime, durationStr, barSizeSetting, whatToShow, useRTH, formatDate, keepUpToDate, chartOptions) -> historicalData(reqId, bar) -> historicalDataEnd(reqId, start, end)同步封装会收集所有 historicalData() 回调,在收到 historicalDataEnd() 后返回 BarData 列表。
def get_historical_data( self, contract, end_date_time, duration_str, bar_size_setting, what_to_show, use_rth=True, format_date=1, timeout=30,): req_id = self.get_next_valid_id() self.reqHistoricalData( req_id, contract, end_date_time, duration_str, bar_size_setting, what_to_show, use_rth, format_date, False, [], ) return self._wait_for_response(req_id, "historical_data", timeout)| 参数 | 中文含义 | 示例 |
|---|---|---|
contract | 要查询的合约 | AAPL 股票合约 |
end_date_time | 结束时间;空字符串表示可用的最新时间 | "" |
duration_str | 回看多长时间 | "1 D"、"1 W"、"1 M" |
bar_size_setting | K 线周期 | "5 mins"、"1 hour"、"1 day" |
what_to_show | 数据类型 | "TRADES"、"MIDPOINT"、"BID"、"ASK" |
use_rth | 是否只使用常规交易时段 | True |
format_date | 日期格式 | 1 返回可读字符串,2 返回 Unix 时间 |
timeout | 等待历史数据结束回调的秒数 | 30 |
查询 AAPL 最近 1 天 5 分钟线
Section titled “查询 AAPL 最近 1 天 5 分钟线”from ibapi.contract import Contractfrom ibapi.sync_wrapper import TWSSyncWrapper, ResponseTimeout
def stock_contract(symbol: str, currency: str = "USD") -> Contract: contract = Contract() contract.symbol = symbol contract.secType = "STK" contract.exchange = "SMART" contract.currency = currency contract.primaryExchange = "NASDAQ" return contract
app = TWSSyncWrapper(timeout=30)
try: if not app.connect_and_start("127.0.0.1", 7497, 949): raise RuntimeError("连接 TWS API 失败")
bars = app.get_historical_data( contract=stock_contract("AAPL"), end_date_time="", # 空字符串表示请求最近可用时间之前的数据 duration_str="1 D", # 回看 1 天 bar_size_setting="5 mins", # 每根 K 线 5 分钟 what_to_show="TRADES", # 成交数据 use_rth=True, # 只要常规交易时段 format_date=1, # 返回可读时间字符串 timeout=30, )
print(f"BAR_COUNT={len(bars)}")
for bar in bars[:3]: print( bar.date, bar.open, bar.high, bar.low, bar.close, bar.volume, )
except ResponseTimeout: print("历史数据请求超时:没有在超时时间内收到 historicalDataEnd 回调")
finally: app.disconnect_and_stop()BAR_COUNT=78FIRST_DATE=20260612 09:30:00 US/EasternFIRST_OPEN=295.9FIRST_HIGH=297.14FIRST_LOW=294.89FIRST_CLOSE=295.35FIRST_VOLUME=147209078 根 5 分钟 K 线对应美股常规交易时段 6.5 小时。这个结果说明连接、合约、历史数据 farm 和参数组合都正常。
BarData 返回字段
Section titled “BarData 返回字段”get_historical_data() 返回的是 BarData 对象列表。常用字段如下:
| 字段 | 中文含义 |
|---|---|
date | K 线开始时间或日期 |
open | 开盘价 |
high | 最高价 |
low | 最低价 |
close | 收盘价 |
volume | 成交量 |
wap | 加权平均价 |
barCount | 该 K 线内的成交笔数或聚合数量 |
what_to_show 怎么选
Section titled “what_to_show 怎么选”| 值 | 中文含义 | 常见用途 |
|---|---|---|
TRADES | 成交价数据 | 股票、期货等常规 K 线 |
MIDPOINT | 买卖中间价 | 外汇、点差较重要的品种 |
BID | 买价 | 分析买盘报价 |
ASK | 卖价 | 分析卖盘报价 |
BID_ASK | 买卖价组合 | 价差分析 |
HISTORICAL_VOLATILITY | 历史波动率 | 期权相关分析 |
OPTION_IMPLIED_VOLATILITY | 期权隐含波动率 | 期权相关分析 |
不是所有品种都支持所有 what_to_show。如果请求失败,先换成最常用的 TRADES 或 MIDPOINT 验证合约和连接。
| 现象 | 常见原因 | 处理方式 |
|---|---|---|
ResponseTimeout | 请求过大、网络慢、没有收到结束回调 | 缩小 duration_str,增大 timeout |
| 返回空列表 | 非交易日、合约不准确或数据不可用 | 先用 get_contract_details() 确认合约 |
| 权限错误 | 账户没有对应历史数据权限 | 换延迟/可用数据类型,或说明权限限制 |
| 数据时间看起来不对 | 没处理交易所时区 | 保存原始 bar.date 和 timeZoneId |