3 分钟快速生成代码
输入想法,AI 即刻生成可运行代码
在进行跨资产类别的量化交易(如股指期货套利、商品期货与股票对冲等混合资产交易)时,在一个策略中同时监控股票账户和期货账户的资金与连接状态至关重要。QMT 平台提供了强大的多账户订阅与回调机制,允许开发者在单个策略中实现这一功能。
要在 QMT 策略中同时监控股票和期货账户,主要分为两个步骤:
init 初始化函数中多次调用 ContextInfo.set_account():QMT 支持多次调用该方法来绑定不同的资金账号。必须在 init 执行完毕前设置好所有需要监听的账号,否则后续将无法接收到交易主推。account_callback() 回调函数中进行分流处理:当任何一个已订阅的账户状态发生变化时,系统会自动触发 account_callback(ContextInfo, accountInfo)。我们可以通过 accountInfo 对象的属性(如 m_nBrokerType 和 m_strAccountID)来识别是哪一个账户触发了回调,并获取其最新状态。accountInfo.m_nBrokerType:账户类型。1 代表期货账户,2 代表股票账户,3 代表信用账户。accountInfo.m_strAccountID:资金账号 ID。accountInfo.m_strStatus:账户的当前状态。以下是一个完整的 QMT 策略模板,展示了如何同时订阅并监听股票与期货账户:
#encoding:gbk
def init(ContextInfo):
# 1. 定义你的股票账户和期货账户ID
stock_account = '6000000058' # 替换为你的实际股票资金账号
future_account = '110476' # 替换为你的实际期货资金账号
# 2. 多次调用 set_account 订阅多个账户
# 注意:必须在 init 中设置完毕,init 执行后设置将不再订阅交易主推
ContextInfo.set_account(stock_account)
ContextInfo.set_account(future_account)
print(f"[Init] 已成功订阅多账户监控。股票账户: {stock_account}, 期货账户: {future_account}")
def handlebar(ContextInfo):
# 策略核心逻辑写在这里
pass
def account_callback(ContextInfo, accountInfo):
"""
资金账号状态变化实时主推函数(仅在实盘/模拟运行模式下生效)
"""
account_id = accountInfo.m_strAccountID
broker_type = accountInfo.m_nBrokerType
status = accountInfo.m_strStatus
available_cash = accountInfo.m_dAvailable
# 3. 根据 m_nBrokerType 区分账户类型并处理
if broker_type == 2:
print(f"\n>>> [股票账户主推] 账号: {account_id} 状态变化!")
print(f" 当前状态: {status}")
print(f" 可用资金: {available_cash} 元")
print(f" 股票总市值: {accountInfo.m_dStockValue} 元")
elif broker_type == 1:
print(f"\n>>> [期货账户主推] 账号: {account_id} 状态变化!")
print(f" 当前状态: {status}")
print(f" 可用资金: {available_cash} 元")
print(f" 持仓盈亏: {accountInfo.m_dPositionProfit} 元")
print(f" 占用保证金: {accountInfo.m_dMargin} 元")
else:
print(f"\n>>> [其他账户主推] 账号: {account_id}, 类型: {broker_type}, 状态: {status}")
account_callback 等交易回报实时主推函数仅在实盘或模拟运行模式下生效,在历史回测模式下不会触发。passorder 下单函数时务必显式传入对应的 accountid 参数。如果传入的账号为空,QMT 默认会使用最后一次调用 set_account 设置的账号作为下单账号,这在混合资产交易中极易导致下单到错误的账户中。handlebar 中随时使用 get_trade_detail_data(accountID, strAccountType, 'ACCOUNT') 主动查询各个账户的实时资金详情。