🚀 AI 一键生成 qmt 策略代码

QMT 平台如何通过 passorder 函数进行程序化下单交易?

qmt | 发布时间: 2025/11/24
以下内容由 EasyQuant 生成。

问题描述

请告诉我如何使用代码下一个限价单来买入100股股票。

解决方案

在 QMT 中,可以使用 passorder 函数(综合交易下单)或 order_shares 函数(指定股数交易)来下限价单。

以下是两种方法的具体代码示例和说明。

方法一:使用 passorder 函数(推荐)

这是 QMT 最核心的下单函数,功能最全面。要下限价单,关键在于将报价类型 prType 设置为 11(指定价/模型价),并在 price 参数中填入具体的买入价格。

# -*- coding: gbk -*-

def init(ContextInfo):
    # 1. 设置资金账号 (请替换为您真实的资金账号)
    ContextInfo.accID = '6000000000'
    ContextInfo.set_account(ContextInfo.accID)

def handlebar(ContextInfo):
    # 获取当前K线索引
    index = ContextInfo.barpos
    # 获取当前K线的时间
    realtime = ContextInfo.get_bar_timetag(index)
    
    # 示例:仅在最后一根K线(实时行情)触发下单,避免历史回测重复下单
    if ContextInfo.is_last_bar():
        
        # 下单参数设置
        opType = 23        # 23 代表股票买入
        orderType = 1101   # 1101 代表单股、单账号、普通、股/手方式下单
        accountID = ContextInfo.accID
        orderCode = '600000.SH' # 浦发银行
        prType = 11        # 11 代表指定价(限价单)
        price = 10.50      # 设置限价为 10.50 元
        volume = 100       # 买入 100 股
        
        # 执行下单
        passorder(opType, orderType, accountID, orderCode, prType, price, volume, ContextInfo)
        
        print(f"已发送限价买入指令:{orderCode}, 价格:{price}, 数量:{volume}")

参数详解:

  • opType=23:表示股票买入。
  • prType=11:表示指定价(限价)。如果不设置为 11,填写的 price 将无效。
  • price=10.50:具体的限价价格。
  • volume=100:买入的数量(股)。

方法二:使用 order_shares 函数(简便方法)

这是一个封装好的便捷函数,语法更简单。通过设置 style 参数为 'fix' 来指定限价。

# -*- coding: gbk -*-

def init(ContextInfo):
    # 设置资金账号
    ContextInfo.accID = '6000000000'
    ContextInfo.set_account(ContextInfo.accID)

def handlebar(ContextInfo):
    if ContextInfo.is_last_bar():
        # 股票代码
        stock_code = '600000.SH'
        # 目标限价
        limit_price = 10.50
        # 买入数量 (正数代表买入,负数代表卖出)
        amount = 100
        
        # 下单:style='fix' 表示限价单
        order_shares(stock_code, amount, 'fix', limit_price, ContextInfo, ContextInfo.accID)
        
        print(f"已通过order_shares发送限价单:{stock_code}, 价格:{limit_price}, 数量:{amount}")

参数详解:

  • style='fix':表示指定价(限价)。
  • price:紧跟在 style 之后的参数,即具体的限价价格。

注意事项

  1. 编码格式:代码第一行必须包含 # -*- coding: gbk -*-,否则中文注释或字符串可能会导致乱码或报错。
  2. 账号绑定:必须在 init 中使用 ContextInfo.set_account() 绑定您的实际资金账号,否则无法下单。
  3. 运行模式:上述代码在“实盘”或“模拟”模式下会产生真实的委托信号;在“回测”模式下,passorder 的限价单逻辑通常依赖于撮合机制(回测参数中的撮合方式)。
  4. 重复下单保护:在 handlebar 中直接写下单函数,每个 tick(分笔数据)更新或每根 K 线更新都会触发。实际策略中,请务必增加逻辑判断(如判断信号是否已触发、是否已有持仓等),防止重复买入。