取消直方图数据
直方图请求应使用 cancelHistogramData() 取消。即使你已经收到结果,也建议把请求编号纳入统一清理逻辑,避免后续批量请求时状态混乱。
官方参考:Histogram Data
直方图还有一种常见情况:请求没有立刻报错,但也长时间没有收到 histogramData()。这时应按超时清理,而不是让请求一直挂在程序里。
AAPL 参考样本中,1 week 请求会收到非空数组,1 day 请求会收到空数组。无论是哪一种,都可以在回调后清理请求状态。
def histogramData(self, reqId, items): """收到直方图后取消对应请求。""" print(f"收到 {len(items)} 个价格档位") self.cancelHistogramData(reqId)配合超时处理时,可以在等待超过预设秒数后调用同一个取消方法:
if not histogram_event.wait(20): print("直方图请求超时,取消请求") app.cancelHistogramData(req_id)和其他取消方法区分
Section titled “和其他取消方法区分”| 请求类型 | 取消方法 |
|---|---|
| 直方图数据 | cancelHistogramData(reqId) |
| 历史 K 线 | cancelHistoricalData(reqId) |
| 最早历史时间 | cancelHeadTimeStamp(reqId) |
| 实时行情 | cancelMktData(tickerId) |
批量请求建议
Section titled “批量请求建议”如果要对很多合约请求直方图,建议维护独立集合:
active_histogram_ids = set()
def request_histogram(app, req_id, contract): """发送直方图请求并记录编号。""" active_histogram_ids.add(req_id) app.reqHistogramData(req_id, contract, True, "1 week")
def cleanup_histograms(app): """退出前清理所有直方图请求。""" for req_id in list(active_histogram_ids): app.cancelHistogramData(req_id) active_histogram_ids.discard(req_id)这样可以避免把直方图请求和历史 K 线请求混在同一个取消队列里。