跳转到内容

请求股票合约搜索

reqMatchingSymbols() 根据关键词搜索匹配的合约。它是一次性请求:发送请求后,结果通过 symbolSamples() 返回,不需要再调用取消方法。

app.reqMatchingSymbols(reqId, pattern)
def reqMatchingSymbols(self, reqId: int, pattern: str):
...
参数类型中文含义示例说明
reqIdint请求编号9502自己分配,用来对应回调。
patternstr搜索关键词"AAPL"可以是完整代码,也可以是较短关键词;越模糊结果越多。
from __future__ import annotations
import threading
from collections import Counter
from ibapi.client import EClient
from 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=True
SYMBOL_CALLBACK_RECEIVED=True
SYMBOL_ROW_COUNT=17
SYMBOL_SEC_TYPE_COUNTS=BOND:3,IND:2,STK:12
NON_INFO_ERROR_COUNT=0
写法结果特点建议
"AAPL"返回 AAPL 相关股票、债券、指数等候选适合精确搜索。
"AAP"可能返回更多近似代码适合搜索框联想,但要控制展示数量。
公司全名关键词可能返回更广结果适合人工选择,不适合自动交易。

不一定。它是搜索关键词,但越模糊结果越多。交易系统里建议让用户选择候选结果,或者按证券类型、币种、主要交易所做严格筛选。

不建议。搜索只是找到候选,仍应先筛选 secTypecurrencyprimaryExchange,再用 reqContractDetails() 确认。

不需要。reqMatchingSymbols() 是一次性请求,没有对应取消方法。