#!/usr/bin/env python # -*- coding: utf-8 -*- # 均线金叉开仓死叉平仓策略 __author__ = "ZYP" from tqsdk import TqApi,TqSim,TqBacktest,BacktestFinished from tqsdk.ta import MA import time from datetime import date SYMBOL = "SHFE.rb2005" # 开仓条件函数 def open_position(klines): ma20 = MA(klines, 20) ma40 = MA(klines, 40) if (ma20.iloc[-1].ma > ma40.iloc[-1].ma) and (ma20.iloc[-2].ma < ma40.iloc[-1].ma): return 1 return 0 # 平仓条件函数 def close_position(klines): ma20 = MA(klines,20) ma40 = MA(klines,40) if (ma20.iloc[-1].ma < ma40.iloc[-1].ma) and (ma20.iloc[-2].ma > ma40.iloc[-1].ma): return 1 return 0 try: api=TqApi(web_gui = "http://127.0.0.1:52974", backtest=TqBacktest(start_dt=date(2020, 4, 7), end_dt=date(2020, 4, 10))) klines = api.get_kline_serial(SYMBOL, 5 * 60, 100) while True: api.wait_update() # 开仓 if open_position(klines): long_position = api.get_position(SYMBOL) order = api.get_order() if long_position['pos_long_his']==0 and order=={}: order = api.insert_order(symbol=SYMBOL, direction="BUY", offset="OPEN", volume=1) print("我开仓了","委托状态:%s, 已成交:%d手, 未成交:%d手" %(order.status, order.volume_orign-order.volume_left, order.volume_left)) quote = api.get_quote(SYMBOL) print(quote["datetime"]) # 当开仓了,更新transaction.txt文件,然后运行发送邮件脚本就可以将交易记录发送邮件 f = open("transaction.txt","w",encoding = "utf8") f.write(quote["datetime"]+":我开仓了") f.close() time.sleep(5) # 平仓 if close_position(klines): long_position = api.get_position(SYMBOL) if long_position['pos_long_his'] != 0: order = api.insert_order(symbol=SYMBOL, direction="SELL", offset="CLOSE", volume=1) print("我平仓了") quote = api.get_quote(SYMBOL) print(quote["datetime"]) # 当平仓了,更新transaction.txt文件,然后运行发送邮件脚本就可以将交易记录发送邮件 f = open("transaction.txt","w",encoding="utf8") f.write(quote["datetime"]+":我平仓了") f.close() time.sleep(5) except BacktestFinished as e: # 回测结束时会执行这里的代码 #print(acc.trade_log) pass api.close()
请教下,在使用api.insert_order下单后,回测显示已经全部成交,但是order返回的状态还是ALIVE,成交是0手,未成交1手,按理应该成交是1,未成交未0
west 已回答的问题 2020年4月22日
因为还没成交,所以未成交是1手