返回列表 发布新帖

下单前要检查是否有未成交委托,先撤单,帮看下这样写是否正确

20 0
def cancel_all_orders(c):
    """撤销所有未完成的委托"""
    print("开始撤销所有未完成的委托...")
    try:
        # 获取当前所有委托
        orders = get_trade_detail_data(c.account, c.account_type, 'order')

        if not orders:
            print("没有未完成的委托")
            return True

        # 转换为DataFrame便于筛选
        order_df = pd.DataFrame()
        for o in orders:
            temp_df = pd.DataFrame({
                'order_id': [o.m_strOrderID],
                '股票代码': [o.m_strInstrumentID],
                '市场类型': [o.m_strExchangeID],
                '证券代码': [o.m_strInstrumentID + '.' + o.m_strExchangeID],
                '买卖方向': [o.m_nOffsetFlag],
                '委托状态': [o.m_nOrderStatus],
                '委托数量': [o.m_nVolumeTotalOriginal],
                '成交数量': [o.m_nVolumeTraded]
            })
            order_df = pd.concat([order_df, temp_df], ignore_index=True)

        # 筛选需要撤销的委托:买卖方向为48且委托状态为50
        cancel_list = order_df[(order_df['买卖方向'] == 48) & (order_df['委托状态'].isin([50]))]

        if cancel_list.empty:
            print("没有符合条件的委托需要撤销")
            return True

        print(f"发现{len(cancel_list)}个符合条件的委托,开始撤销...")

        # 遍历并撤销每个符合条件的委托
        for _, order in cancel_list.iterrows():
            try:
                order_id = order['order_id']
                print(f"撤销委托: {order_id}, 证券代码: {order['证券代码']}, 买卖方向: {order['买卖方向']}")

                # 调用撤销委托函数
                result = cancel(order_id, c.account, c.account_type, c)
                print(f"撤销结果: {result}")

            except Exception as e:
                print(f"撤销委托失败: {e}")

        # 等待一段时间,让撤销操作生效
        time.sleep(5)

        # 检查是否还有未完成的委托
        remaining_orders = get_trade_detail_data(c.account, c.account_type, 'order')
        remaining_count = sum(1 for o in remaining_orders if o.m_nVolumeTraded < o.m_nVolumeTotalOriginal)

        if remaining_count > 0:
            print(f"仍有{remaining_count}个委托未撤销成功")
            return False
        else:
            print("所有符合条件的委托已成功撤销")
            return True

    except Exception as e:
        print(f"撤销委托过程中发生错误: {e}")
        return False

回复

您需要登录后才可以回帖 登录 | 立即注册

客服专线

400-080-8112

用思考的速度交易,用真诚的态度合作,我们是认真的!
  • 关注公众号
  • 添加微信客服
Copyright © 2001-2025 迅投QMT社区 版权所有 All Rights Reserved. 蜀ICP备19002686号-2
关灯 快速发帖
扫一扫添加微信客服
QQ客服返回顶部
快速回复 返回顶部 返回列表