from tqsdk import TqApi, TqSim, BacktestFinished, TqBacktest, TargetPosTask from datetime import date from tqsdk.ta import MA def buy_Position(klines): ma5 = MA(klines,5) ma10 = MA(klines,10) if klines.iloc[-1].close > ma5.iloc[-1].ma: return 1 return 0 def close_buy(klines): ma5 = MA(klines,5) ma10 = MA(klines,10) if klines.iloc[-1].close < ma5.iloc[-1].ma: return 1 return 0 def sell_Position(klines): ma5 = MA(klines,5) ma10 = MA(klines,10) if klines.iloc[-1].close < ma5.iloc[-1].ma: return 1 return 0 def close_sell(klines): ma5 = MA(klines,5) ma10 = MA(klines,10) if klines.iloc[-1].close > ma5.iloc[-1].ma: return 1 return 0 try: symbol = "DCE.i2009" acc = TqSim(100000) api = TqApi(acc, backtest=TqBacktest(start_dt=date(2020,3,16), end_dt=date(2020,4,16)),web_gui = "http://127.0.0.1:12345") klines = api.get_kline_serial(symbol,1200,200) orders = api.get_order() data = api.get_position(symbol) buy_his_today = data["pos_long_his"]+data["pos_long_today"] sell_his_today = data["pos_short_his"]+data["pos_short_today"] while True: api.wait_update() klines = api.get_kline_serial(symbol,1200,200) if buy_Position(klines): if orders == {} and buy_his_today == 0: order = api.insert_order(symbol, direction="BUY", offset="OPEN",volume=1) print("开多仓") if close_buy(klines): if orders != {} and buy_his_today != 0: order = api.insert_order(symbol, direction="SELL", offset="CLOSE",volume=1) print("平多仓") if sell_Position(klines): if orders == {} and sell_his_today == 0: order = api.insert_order(symbol, direction="SELL", offset="OPEN",volume=1) print("开空仓") if close_sell(klines): if orders != {} and sell_his_today != 0: order = api.insert_order(symbol, direction="BUY", offset="CLOSE",volume=1) print("平空仓") except BacktestFinished as e: # 回测结束时会执行这里的代码 print(acc.trade_log)