请求股票合约搜索
reqMatchingSymbols() 根据关键词搜索匹配的合约。它是一次性请求:发送请求后,结果通过 symbolSamples() 返回,不需要再调用取消方法。
app.reqMatchingSymbols(reqId, pattern)def reqMatchingSymbols(self, reqId: int, pattern: str): ...| 参数 | 类型 | 中文含义 | 示例 | 说明 |
|---|---|---|---|---|
reqId | int | 请求编号 | 9502 | 自己分配,用来对应回调。 |
pattern | str | 搜索关键词 | "AAPL" | 可以是完整代码,也可以是较短关键词;越模糊结果越多。 |
Python 请求示例
Section titled “Python 请求示例”from __future__ import annotations
import threadingfrom collections import Counter
from ibapi.client import EClientfrom ibapi.wrapper import EWrapper
class SymbolSearchApp(EWrapper, EClient): def __init__(self): EClient.__init__(self, self) self.ready = threading.Event() self.samples_ready = threading.Event() self.rows = [] self.errors = []
def nextValidId(self, orderId): # 收到这个回调,说明 API 握手完成,可以发送请求。 self.ready.set()
def error(self, reqId, *args): # 过滤常见连接提示,只保留真正影响请求的错误。 if len(args) >= 2: code = int(args[0]) msg = str(args[1]) else: code = -1 msg = str(args) if code not in {2104, 2105, 2106, 2158}: self.errors.append((reqId, code, msg))
def symbolSamples(self, reqId, contractDescriptions): for item in contractDescriptions: contract = item.contract self.rows.append( { "conId": contract.conId, "symbol": contract.symbol, "secType": contract.secType, "primaryExchange": contract.primaryExchange, "currency": contract.currency, "derivativeSecTypes": sorted(str(x) for x in item.derivativeSecTypes), } ) self.samples_ready.set()
app = SymbolSearchApp()
try: app.connect("127.0.0.1", 7497, clientId=9502) thread = threading.Thread(target=app.run, daemon=True) thread.start()
if not app.ready.wait(10): raise RuntimeError("等待 nextValidId 超时")
app.reqMatchingSymbols(9502, "AAPL") app.samples_ready.wait(10)
sec_type_counts = Counter(row["secType"] for row in app.rows) print(f"SYMBOL_CALLBACK_RECEIVED={app.samples_ready.is_set()}") print(f"SYMBOL_ROW_COUNT={len(app.rows)}") print("SYMBOL_SEC_TYPE_COUNTS=" + ",".join( f"{sec_type}:{count}" for sec_type, count in sorted(sec_type_counts.items()) ))
finally: if app.isConnected(): app.disconnect()示例连接返回:
CONNECTED=TrueSYMBOL_CALLBACK_RECEIVED=TrueSYMBOL_ROW_COUNT=17SYMBOL_SEC_TYPE_COUNTS=BOND:3,IND:2,STK:12NON_INFO_ERROR_COUNT=0参数使用建议
Section titled “参数使用建议”| 写法 | 结果特点 | 建议 |
|---|---|---|
"AAPL" | 返回 AAPL 相关股票、债券、指数等候选 | 适合精确搜索。 |
"AAP" | 可能返回更多近似代码 | 适合搜索框联想,但要控制展示数量。 |
| 公司全名关键词 | 可能返回更广结果 | 适合人工选择,不适合自动交易。 |
pattern 必须是完整股票代码吗
Section titled “pattern 必须是完整股票代码吗”不一定。它是搜索关键词,但越模糊结果越多。交易系统里建议让用户选择候选结果,或者按证券类型、币种、主要交易所做严格筛选。
搜索结果能直接下单吗
Section titled “搜索结果能直接下单吗”不建议。搜索只是找到候选,仍应先筛选 secType、currency、primaryExchange,再用 reqContractDetails() 确认。
需要取消搜索请求吗
Section titled “需要取消搜索请求吗”不需要。reqMatchingSymbols() 是一次性请求,没有对应取消方法。