3.75K 浏览
0

#!/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日
0

你看到ALIVE的状态是在返回“全部成交”之前呀,你可以在成交之后查看order的状态

arb zhou 发表新评论 2020年4月22日

因为还没成交,所以未成交是1手

图片中第二个红色方框回测内容显示模拟交易委托已经成交了啊

它有先后顺序的,刚下单(没收到成交信息)的时候,自然是ALIVE状态并且未成交手数是1,成交之后就是0了

明白了,那怎样print成交后的状态呢?

您正在查看1个答案中的1个,单击此处查看所有答案。