3 分钟快速生成代码
输入想法,AI 即刻生成可运行代码
在期货套利交易中,滑点与两腿合约下单的时间差(腿部风险)是影响策略收益的核心因素。qmt (Quantitative Market Trader) 平台提供了强大的 passorder 组合交易下单指令,支持多腿合约的套利逻辑,帮助投资者实现跨品种或跨期套利的自动化交易。
passorder 函数通过设置特定的 opType(操作类型)与 orderType(下单方式),支持对期货组合进行同步下单。
volume 单位为篮子/组合的份数)。以下示例展示如何在 handlebar 函数中计算两个关联期货品种(例如螺纹钢与铁矿石,或不同月份的股指期货)的价差,当价差突破布林带上轨时执行开空组合(卖出腿A,买入腿B),突破下轨时执行开多组合。
#encoding:gbk
import numpy as np
def init(ContextInfo):
# 1. 设定期货交易账号
ContextInfo.account = '110476'
ContextInfo.set_account(ContextInfo.account)
# 2. 设定套利合约腿
ContextInfo.leg1 = 'IF2309.IF'
ContextInfo.leg2 = 'IF2312.IF'
ContextInfo.set_universe([ContextInfo.leg1, ContextInfo.leg2])
# 3. 设定策略参数
ContextInfo.period = 20 # 均线周期
ContextInfo.std_dev = 2 # 标准差倍数
ContextInfo.trade_units = 1 # 每次套利交易份数
def handlebar(ContextInfo):
# 获取当前bar索引
index = ContextInfo.barpos
# 获取历史收盘价计算价差
data = ContextInfo.get_history_data(ContextInfo.period + 1, '1d', 'close')
if ContextInfo.leg1 not in data or ContextInfo.leg2 not in data:
return
close1 = np.array(data[ContextInfo.leg1])
close2 = np.array(data[ContextInfo.leg2])
if len(close1) < ContextInfo.period or len(close2) < ContextInfo.period:
return
# 计算价差序列 (腿1 - 腿2)
spread = close1 - close2
mean_spread = np.mean(spread[:-1])
std_spread = np.std(spread[:-1])
upper_bound = mean_spread + ContextInfo.std_dev * std_spread
lower_bound = mean_spread - ContextInfo.std_dev * std_spread
current_spread = spread[-1]
# 获取最新委托与持仓状态进行风控(此处简化为价格触发)
# 价差高于上轨:套利组合做空(卖出 Leg1,买入 Leg2)
if current_spread > upper_bound:
# opType=43(期货组合开空), orderType=1101/2101, prType=5(最新价), quickTrade=1(立即下单)
passorder(43, 1101, ContextInfo.account, ContextInfo.leg1, 5, -1, ContextInfo.trade_units, 'Arbitrage_Strategy', 1, ContextInfo)
print(f"[触及上轨] 发送组合开空指令,当前价差: {current_spread:.2f}")
# 价差低于下轨:套利组合做多(买入 Leg1,卖出 Leg2)
elif current_spread < lower_bound:
# opType=40(期货组合开多), orderType=1101/2101, prType=5(最新价), quickTrade=1(立即下单)
passorder(40, 1101, ContextInfo.account, ContextInfo.leg1, 5, -1, ContextInfo.trade_units, 'Arbitrage_Strategy', 1, ContextInfo)
print(f"[触及下轨] 发送组合开多指令,当前价差: {current_spread:.2f}")
prType=14)或最新价(prType=5)以提高撮合成功率。quickTrade 参数设置为 1,可在信号触发时立即发送委托,无需等待当前 Bar 彻底收盘。get_trade_detail_data 定期检查套利腿的成交状态。若出现单腿成交(Leg-out)风险,需通过 cancel 函数撤单并执行补单逻辑。