金字塔决策交易系统

 找回密码
 

微信登录

微信扫一扫,快速登录

搜索
12
返回列表 发新帖
楼主: 105190

请问下 执行国债隔夜委托时失败,提示以下这段话如何解决?

[复制链接]

62

主题

285

帖子

285

积分

Rank: 4

等级: 专业版

注册:
2021-10-19
曾用名:
 楼主| 发表于 2026-4-27 13:56 | 显示全部楼层
代码如下:
from PythonApi import *
import sys
import os
import numpy as np
import time
from datetime import datetime, timedelta

# 指定好文件名称
file_name = "order2.txt"

# 在这个方法中编写任何的初始化逻辑。context对象将会在你的算法策略的任何方法之间做传递。--(必须实现)
def init(context):
    context.finish_pending_orders = None

# 把未成交单写入到软件根目录下的一个txt里
def write_pending_orders_to_file():
    order_list = get_orders("all", 0)
    if order_list is not None:
        for order in order_list:
            book_id = order.order_book_id  # 品种代码
            # 过滤品种代码中的数值            
            stk = ''.join(c for c in book_id if not c.isdigit())
            # 市场代码
            MARKETLABEL = stk[:2]
            stk = stk[2:]
            # 只处理国债品种
            if stk not in ('T', 'TF', 'TL', 'TS'):
                continue
            point = round(get_dynainf(book_id, 208), 7)  # Point是最小变动价位的小数位
            if int(point) > 0:
                point = 0
            else:
                point = len(str(point).split(".")[1])               
            
            side = order.side  # 订单方向 "buy"买:"sell"卖
            position_effect = order.position_effect  # 开平标志 "open"开仓 "close"平仓
            price = str(np.around(order.price, decimals=point+1))  # 委托价格,仅对限价有效
            unfilled_quantity = str(order.unfilled_quantity)  # 未成交的数量
            lines = [book_id, side, position_effect, price, unfilled_quantity]               
            with open(file_name, "a") as file:
                file.writelines(' '.join(lines) + '\n')   

# 执行下单,并清空历史的未成交单记录        
def place_order(context):
    # 获取当前时间
    current_time = datetime.now()
   
    # 检查是否已经开盘
    if not hasattr(context, 'market_opened_time'):
        # 获取开盘时间(假设是9:30开盘)
        market_open_time = current_time.replace(hour=9, minute=30, second=0, microsecond=0)
        context.market_opened_time = market_open_time
   
    # 计算开盘后5秒的时间点
    order_execution_time = context.market_opened_time + timedelta(seconds=5)
   
    # 如果当前时间还没到开盘后5秒,则跳过执行
    if current_time < order_execution_time:
        return
   
    with open(file_name, "r") as file:
        for line in file:
            if not line.strip():
                continue
            book_id, side, position_effect, price, unfilled_quantity = line.split()
            point = round(get_dynainf(book_id, 208), 7)  # Point是最小变动价位的小数位
            if int(point) > 0:
                point = 0
            else:
                point = len(str(point).split(".")[1])
            
            function_name = side + "_" + position_effect
            # 从全局环境中直接获取到具体的函数
            function_object = getattr(sys.modules[__name__], function_name)
            try:
                function_object(book_id, "Limit",
                                price=np.around(float(price), decimals=point+1),
                                volume=int(unfilled_quantity))
            except Exception as ex:
                raise
   
    # 下完单直接清空内容
    with open(file_name, "w") as file:
        pass

# 你选择的品种的数据更新将会触发此段逻辑,例如日或分钟历史数据切片或者是实时数据切片更新。--(必须实现)
def handle_bar(context):   
    if context.finish_pending_orders is None:
        file_exists = os.path.exists(file_name)
        file_not_empty = file_exists and os.path.getsize(file_name) > 0
        if file_not_empty:
            place_order(context)  # 这里需要传入context参数
            context.finish_pending_orders = 1

# 收盘后触发这个方法,因此不能在收盘后立刻退出交易账户或者停止python程序
def after_trading(context):
    write_pending_orders_to_file()
    context.finish_pending_orders = None
    print('after_trading 已经触发')
回复

使用道具 举报

2

主题

6446

帖子

6446

积分

Rank: 8Rank: 8

等级: 超级版主

注册:
2021-5-24
曾用名:
发表于 2026-4-27 14:28 | 显示全部楼层
截图202604271425274429.png

你这里  如果 place_order 里实际没有执行(时间未到的逻辑下),这里就不能改变状态的。


否则你实际没执行,这个状态已经被标记为 已执行.

然后你这里下单时间问题,这个我只看你提供的信息还是无法判断。你找下交易日志,看下触发02秒下单的代码行,要进一步核实下。
回复

使用道具 举报

62

主题

285

帖子

285

积分

Rank: 4

等级: 专业版

注册:
2021-10-19
曾用名:
 楼主| 发表于 2026-4-27 14:40 | 显示全部楼层
资深技术05 发表于 2026-4-27 14:28
你这里  如果 place_order 里实际没有执行(时间未到的逻辑下),这里就不能改变状态的。

这是我是试图修改调整本地时间的执行日志 4.2日当天的被系统清理了 找不到了


补充内容 (2026-4-27 14:45):
我 今天收盘后重新运行执行下 明天就有交易日志了 您说的  place_order 里实际没有执行(时间未到的逻辑下),这里就不能改变状态的  这边要如何改?
f373aac8-6afe-4aaa-a3d5-47b61c96d13f.png
回复

使用道具 举报

2

主题

6446

帖子

6446

积分

Rank: 8Rank: 8

等级: 超级版主

注册:
2021-5-24
曾用名:
发表于 2026-4-27 14:46 | 显示全部楼层
这也看不出什么了。你先改下我前面说的那个问题吧。那个问题在 你基本上就是不执行的状态。
回复

使用道具 举报

62

主题

285

帖子

285

积分

Rank: 4

等级: 专业版

注册:
2021-10-19
曾用名:
 楼主| 发表于 2026-4-27 14:48 | 显示全部楼层
资深技术05 发表于 2026-4-27 14:46
这也看不出什么了。你先改下我前面说的那个问题吧。那个问题在 你基本上就是不执行的状态。

要如何改呢?可以直接帮我改下吗
回复

使用道具 举报

2

主题

6446

帖子

6446

积分

Rank: 8Rank: 8

等级: 超级版主

注册:
2021-5-24
曾用名:
发表于 2026-4-27 14:50 | 显示全部楼层
place_order  你让他有个返回值,如果没有执行到下单地方 都返回false,如果是false 那个变量值就不要重置为1.  
回复

使用道具 举报

62

主题

285

帖子

285

积分

Rank: 4

等级: 专业版

注册:
2021-10-19
曾用名:
 楼主| 发表于 2026-4-27 16:23 | 显示全部楼层
资深技术05 发表于 2026-4-27 14:50
place_order  你让他有个返回值,如果没有执行到下单地方 都返回false,如果是false 那个变量值就不要重置 ...

from PythonApi import *
import sys
import os
import numpy as np
import time
from datetime import datetime, timedelta

# 指定好文件名称
file_name = "order2.txt"

# 在这个方法中编写任何的初始化逻辑。context对象将会在你的算法策略的任何方法之间做传递。--(必须实现)
def init(context):
    context.finish_pending_orders = None
   
# 把未成交单写入到软件根目录下的一个txt里
def write_pending_orders_to_file():
    order_list = get_orders("all", 0)
    if order_list is not None:
        for order in order_list:
            book_id = order.order_book_id  # 品种代码
            # 过滤品种代码中的数值
            stk = ''.join(c for c in book_id if not c.isdigit())
            # 市场代码
            MARKETLABEL = stk[:2]
            stk = stk[2:]
            # 只处理国债品种
            if stk not in ('T', 'TF', 'TL', 'TS'):
                continue
            point = round(get_dynainf(book_id, 208), 7) # Point是最小变动价位的小数位
            if int(point) > 0:
                point = 0
            else:
                point = len(str(point).split(".")[1])               
            
            side = order.side   # 订单方向 "buy"买:"sell"卖
            position_effect = order.position_effect  # 开平标志 "open"开仓 "close"平仓
            price = str(np.around(order.price, decimals=point+1)) # 委托价格,仅对限价有效
            unfilled_quantity = str(order.unfilled_quantity)  # 未成交的数量
            lines = [book_id, side, position_effect, price, unfilled_quantity]               
            with open(file_name, "a") as file:
                file.writelines(' '.join(lines) + '\n')   

# 执行下单,并清空历史的未成交单记录
def place_order(context):
    # 获取当前时间
    current_time = datetime.now()
   
    # 检查是否已经开盘
    if not hasattr(context, 'market_opened_time'):
        market_open_time = current_time.replace(hour=9, minute=30, second=0, microsecond=0)
        context.market_opened_time = market_open_time
   
    # 计算开盘后5秒的时间点
    order_execution_time = context.market_opened_time + timedelta(seconds=5)
   
    # 如果当前时间还没到开盘后5秒,则跳过执行
    if current_time < order_execution_time:
        return False  # [修改1] 未到执行时间,返回False
   
    # [修改2] 新增:检查文件是否有内容
    if not os.path.exists(file_name) or os.path.getsize(file_name) == 0:
        return False  # 文件为空,返回False
   
    executed = False  # [修改3] 新增:标记是否执行了下单
   
    with open(file_name, "r") as file:
        for line in file:
            if not line.strip():
                continue
            book_id, side, position_effect, price, unfilled_quantity = line.split()
            point = round(get_dynainf(book_id, 208), 7)  # Point是最小变动价位的小数位
            if int(point) > 0:
                point = 0
            else:
                point = len(str(point).split(".")[1])
            
            function_name = side + "_" + position_effect
            # 从全局环境中直接获取到具体的函数
            function_object = getattr(sys.modules[__name__], function_name)
            try:
                function_object(book_id, "Limit",
                                price=np.around(float(price), decimals=point+1),
                                volume=int(unfilled_quantity))
                executed = True  # [修改4] 标记已执行下单
            except Exception as ex:
                print(f"下单失败: {ex}")  # [修改5] 新增:打印错误信息
                continue
   
    # 下完单直接清空内容
    if executed:  # [修改6] 只有执行了下单才清空文件
        with open(file_name, "w") as file:
            pass
   
    return executed  # [修改7] 返回是否执行了下单
   
   
# 你选择的品种的数据更新将会触发此段逻辑,例如日或分钟历史数据切片或者是实时数据切片更新。--(必须实现)
def handle_bar(context):   
    if context.finish_pending_orders is None:
        file_exists = os.path.exists(file_name)
        file_not_empty = file_exists and os.path.getsize(file_name) > 0
        if file_not_empty:
            # [修改8] 只有place_order返回True时才设置finish_pending_orders
            if place_order(context):  # [修改9] 检查返回值
                context.finish_pending_orders = 1
# 收盘后触发这个方法,因此不能在收盘后立刻退出交易账户或者停止python程序
def after_trading(context):
    write_pending_orders_to_file()
    context.finish_pending_orders = None
    print('after_trading 已经触发')

补充内容 (2026-4-27 16:23):
这样子修改可以吗?
回复

使用道具 举报

2

主题

6446

帖子

6446

积分

Rank: 8Rank: 8

等级: 超级版主

注册:
2021-5-24
曾用名:
发表于 2026-4-27 17:17 | 显示全部楼层
可以。
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 微信登录

本版积分规则

手机版|小黑屋|上海金之塔信息技术有限公司 ( 沪ICP备13035422号 )

GMT+8, 2026-4-27 21:41 , Processed in 0.117013 second(s), 22 queries .

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表