
等级: 专业版
- 注册:
- 2021-10-19
- 曾用名:
|

楼主 |
发表于 2026-6-18 11:52
|
显示全部楼层
可以帮忙看看为何我这隔夜委托代码延迟5秒执行依然是失灵时不灵呢?我 运行在1分钟周期 设定走完K线再执行,结果依然是在9:30:01秒给我发出去了,具体怎么修改呢?
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 已经触发') |
|