这个只针对国债有效,如果以后还有其他品种收盘时间不一样,那同样需要新建一个策略来单独处理。我还没测试,你可以用模拟先试下。
注意 基准合约必须选择国债。
[Python] 复制代码
from PythonApi import *
import sys
import os
import numpy as np
#指定好文件名称
file_name = "order2.txt"
# 在这个方法中编写任何的初始化逻辑。context对象将会在你的算法策略的任何方法之间做传递。--(必须实现)
def init(context):
context.finish_pending_orders = None
# 你选择的品种的数据更新将会触发此段逻辑,例如日或分钟历史数据切片或者是实时数据切片更新。--(必须实现)
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.finish_pending_orders = 1
# 收盘后触发这个方法,因此不能在收盘后立刻退出交易账户或者停止python程序
def after_trading(context):
write_pending_orders_to_file()
context.finish_pending_orders = None
print('after_trading 已经触发')
# 把未成交单写入到软件根目录下的一个txt里
def write_pending_orders_to_file():
order_list = get_orders("all", 0)
if not order_list is 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 not stk 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():
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
|