
等级: 专业版
- 注册:
- 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 已经触发') |
|