def scrawl_single_tick(i, path, ex, tdates): the_dir1 = os.path.join(path, ex.upper(), str(i[2].year)) if not os.path.exists(the_dir1): os.makedirs(the_dir1) the_dir = os.path.join(path, ex.upper(), str(i[2].year), i[0] + ".csv.gz") the_dir2 = os.path.join(path, ex.upper(), str(i[2].year), i[0] + ".csv") if not os.path.exists(the_dir): print(the_dir) print(i) print(tdates[i[2]]) print(i[2]) api = TqApi(account=TqSim()) # api = TqApi(account=TqSim(),url="ws://192.168.56.1:7777") td = DataDownloader(api, symbol_list=[ex.upper() + "." + i[1]], dur_sec=0, start_dt=tdates[i[2]] + timedelta(hours=17), end_dt=i[2] + timedelta(hours=16), csv_file_name=the_dir2) while not td.is_finished(): api.wait_update() # print("progress: tick:%.2f%%" % td.get_progress()) print("done:" + the_dir) api.close() with open(the_dir2, 'rb') as f: with gzip.GzipFile(filename=the_dir2 + ".gz", mode='w', compresslevel=9) as gf: content = f.read() gf.write(content) os.remove(the_dir2) del td del api gc.collect()
''' 如果当前价格大于10秒K线的MA15则开多仓 如果小于则平仓 ''' api = TqApi("SIM") # 获得 m1901 10秒K线的引用 klines = api.get_kline_serial("DCE.m1901", 10) # 判断开仓条件 while True: api.wait_update() if api.is_changing(klines): ma = sum(klines.close[-15:])/15 print("最新价", klines.close[-1], "MA", ma) if klines.close[-1] > ma: print("最新价大于MA: 市价开仓") api.insert_order(symbol="DCE.m1901", direction="BUY", offset="OPEN", volume=5) break # 判断平仓条件 while True: api.wait_update() if api.is_changing(klines): ma = sum(klines.close[-15:])/15 print("最新价", klines.close[-1], "MA", ma) if klines.close[-1] < ma: print("最新价小于MA: 市价平仓") api.insert_order(symbol="DCE.m1901", direction="SELL", offset="CLOSE", volume=5) break # 关闭api,释放相应资源 api.close()
def run(): #获取命令行参数 parser = argparse.ArgumentParser() parser.add_argument('--source_file') parser.add_argument('--instance_id') parser.add_argument('--instance_file') parser.add_argument('--tq_pid') args = parser.parse_args() TqMonitorThread(int(args.tq_pid)).start() # api api = TqApi(args.instance_id) try: sys.stdout = PrintWriter(api.send_chan, args.instance_id) # log logger = logging.getLogger("TQ") logger.setLevel(logging.INFO) th = TqRunLogger(api.send_chan, args.instance_id) th.setLevel(logging.INFO) logger.addHandler(th) try: #加载策略文件 file_path, file_name = os.path.split(args.source_file) sys.path.insert(0, file_path) module_name = file_name[:-3] param_list = [] # 加载或输入参数 try: # 从文件读取参数表 with open(args.instance_file, "rt") as param_file: instance = json.load(param_file) param_list = instance.get("param_list", []) except Exception: # 获取用户代码中的参数表 def _fake_api_for_param_list(*args, **kwargs): m = sys.modules[module_name] for k, v in m.__dict__.items(): if k.upper() != k: continue if isinstance(v, datetime.date) or isinstance(v, datetime.time) \ or isinstance(v, int) or isinstance(v, float) or isinstance(v, str): param_list.append([k, v]) raise Exception() tqsdk.TqApi = _fake_api_for_param_list try: importlib.import_module(module_name) except Exception: pass param_list = input_param(param_list) if param_list is None: return with open(args.instance_file, "wt") as param_file: json.dump( { "instance_id": args.instance_id, "strategy_file_name": args.source_file, "desc": json.dumps(param_list), "param_list": param_list, }, param_file) api.send_chan.send_nowait({ "aid": "desc", "instance_id": args.instance_id, "status": "RUNNING", "desc": json.dumps(param_list) }) # 拉起实例并直接执行 def _fake_api_for_launch(*args, **kwargs): m = sys.modules[module_name] for k, v in param_list: m.__dict__[k] = v return api tqsdk.TqApi = _fake_api_for_launch __import__(module_name) except ModuleNotFoundError: logger.exception("加载策略文件失败") except IndentationError: logger.exception("策略文件缩进格式错误") except Exception as e: logger.exception("策略运行中遇到异常", exc_info=True) finally: if not api.loop.is_closed(): api.close()