策略研究--qmt实现新股自动申购卖出策略

风险提示:本内容为量化技术及平台操作的纯知识分享,不构成任何投资建议,不推荐任何具体证券或交易时机。部分内容可能理解包含错误,请自行核实。市场有风险,投资需谨慎

优化了一下以前的完整新股新购,晚上了一下功能,检查账户持股,新股上市第一天卖出,其他写了一个ptrade教程策略研究--新股新债自动申购上市当天卖出策略,https://mp.weixin.qq.com/s?__biz=MzI5NTE5NTExMw==&mid=2247496946&idx=1&sn=72f8d578da899d1d06acc426cca9c6bf&scene=21#wechat_redirect

今天研究一下怎么样在ptrade上实现这个功能,新股的申购卖出,第一步设置定时函数,启动策略

复制代码
   
python 复制代码
 # 设置定时器1:每天09:42执行申购
    c.run_time("run_subscribe", "1nDay", "2024-07-25 14:30:00")
    print("定时器1已设置,每天14:30自动申购")
        
    c.run_time("check_and_sell_new_stock", "1nDay", "2024-07-25 14:50:00")
    print("定时器2已设置,每天14:50检查新股上市并卖出\n")

读取ipo数据申购,注意北京的交易所要看证券公司支持不

python 复制代码
def run_subscribe(c):
    now = datetime.datetime.now()
    print(f"\n执行申购 - {now.strftime('%Y-%m-%d %H:%M:%S')}")
        
    all_ipo = get_ipo_data()
    print(f"获取到 {len(all_ipo) if all_ipo else 0} 个申购标的")
    
    if not all_ipo:
        print("今日无新股/新债可申购")
        return
        
    for code, info in all_ipo.items():
        issue_price = info.get('issuePrice', 0)
        max_purchase = info.get('maxPurchaseNum', 0)
        
        if issue_price <= 0 or max_purchase <= 0:
            print(f"  {code}: 发行价或申购数量无效,跳过")
            continue
        
        try:
            passorder(
                23,              # opType: 买入/申购
                1101,            # orderType: 普通委托
                c.account,       # 资金账号
                code,            # 证券代码(新股或新债)
                11,              # prType: 指定价
                issue_price,     # 发行价
                max_purchase,    # 最大申购数量
                '打新申购',       # 策略名
                1,               # 立即生效
                '打新',           # 备注
                c                # ContextInfo
            )
            print(f"已提交申购: {code}, 价格:{issue_price}, 数量:{max_purchase}")
        except Exception as e:
            print(f"申购失败 {code}: {e}")
        
    print("申购检查完成\n")

读取新股的上市时间,上市时间等于今天的卖出

简单的代码整理

python 复制代码
def check_and_sell_new_stock(c):
    """
    检查账户持仓,卖出上市当天的新股
    逻辑:查找持仓中上市日期等于今天(上市天数=0)的股票,全部卖出
    """
    now = datetime.datetime.now()
    today_str = now.strftime('%Y-%m-%d')
    today_int = int(now.strftime('%Y%m%d'))  # 转为整数,如 20260729
    print(f"\n执行新股上市检查卖出 - {today_str} {now.strftime('%H:%M:%S')}")
    
    # ---------- 1. 获取账户持仓 ----------
    positions = get_trade_detail_data(c.account, 'stock', 'position')
    
    if not positions:
        print("账户无持仓,无需检查")
        return
    
    print(f"持仓数量: {len(positions)}")
    
    # ---------- 2. 检查每只持仓股票的上市日期 ----------
    new_stocks_to_sell = []
    
    for pos in positions:
        stock_code = pos.m_strInstrumentID
        market = pos.m_strExchangeID
        full_code = f"{stock_code}.{market}"
        hold_volume = pos.m_nVolume
        avail_volume = pos.m_nCanUseVolume
        
        if hold_volume <= 0 or avail_volume <= 0:
            continue
        
        try:
            inst_detail = c.get_instrumentdetail(full_code)
            
            # 修复1:OpenDate 是整数格式 20221222,需要转为字符串再比较
            open_date = inst_detail.get('OpenDate', 0)
            
            if open_date and open_date > 0:
                # 将整数日期转为字符串格式
                open_date_str = str(open_date)
                # 判断是否为今日上市(OpenDate 等于今日日期)
                if open_date == today_int:
                    print(f"  {full_code}({pos.m_strInstrumentName}): 今日上市,准备卖出")
                    new_stocks_to_sell.append({
                        'code': full_code,
                        'volume': avail_volume,
                        'name': pos.m_strInstrumentName
                    })
                else:
                    print(f"  {full_code}: 上市日期{open_date_str},非今日上市,跳过")
            else:
                print(f"  {full_code}: 无法获取上市日期,跳过")
                
        except Exception as e:
            print(f"  {full_code}: 获取上市日期失败 - {e}")
        
    # ---------- 3. 执行卖出 ----------
    if not new_stocks_to_sell:
        print("今日无新股上市,无需卖出")
        return
        
    print(f"\n发现 {len(new_stocks_to_sell)} 只今日上市新股,开始执行卖出...")
    
    for stock in new_stocks_to_sell:
        try:
            passorder(
                24,              # opType: 24 = 卖出
                1101,            # orderType: 普通委托
                c.account,       # 资金账号
                stock['code'],   # 证券代码
                5,               # prType: 5 = 最新价(市价卖出)
                0,               # price: 市价时填0
                stock['volume'], # 可用数量全部卖出
                '新股上市卖出',   # 策略名
                1,               # 立即生效
                '新股卖出',       # 备注
                c                # ContextInfo
            )
            print(f"已提交卖出: {stock['code']}({stock['name']}), 数量:{stock['volume']}")
        except Exception as e:
            print(f"卖出失败 {stock['code']}: {e}")
        print("新股上市检查卖出完成\n")

策略没有问题挂模型交易就可以

下单的结果

不懂的问我就可以

相关推荐
Darling噜啦啦1 小时前
从零实战Milvus向量数据库:用RAG打造你的AI日记助手
数据库
淼澄研学2 小时前
PyTorch深度学习实战:5个核心方法从0到1构建神经网络
前端·数据库·python
脑子进水养啥鱼?2 小时前
where id > ‘5‘ 的查询 sql 查不到 id = ‘10‘ 的数据?
数据库·sql·postgresql
吴声子夜歌2 小时前
MongoDB 4.2——分片简介
数据库·mongodb
腾渊信息科技公司2 小时前
工业时序数据存储选型实战:从PostgreSQL到TDengine,查询从15秒到200ms
数据库·postgresql·tdengine
TDengine (老段)2 小时前
TDengine Node.js 与 C# 连接器 — Web 服务与 .NET 集成
大数据·数据库·node.js·c#·.net·时序数据库·tdengine
l1t2 小时前
PostgreSQL 11–18 中的 SQL 改进:个人精选-1
数据库·sql·postgresql
逃跑的浣熊3 小时前
MySQL 性能分析报告:Page Cache 与 fsync 对读写性能的影响
数据库
eam0511233 小时前
简易AI SQL助手搭建方式
数据库·人工智能·sql