def dingding_pos(self, success_orders): if success_orders: msg = {} for od in success_orders: stg = od["strategy"] if od["strategy"] else "None" ac = msg.get(stg, {}) msg[stg] = ac txt = ac.get(od["account"], []) ding = f"> {od['instrument_id']}, {self.mapping[od['type']]}, {od['filled_qty']} @ {od['price_avg']}\n\n" txt.append(ding) msg[stg][od['account']] = txt ding = "" for stg, detail in msg.items(): ding += f"### {stg}\n" for ac, txts in detail.items(): ding += f"#### - {ac}:\n" for txt in txts: ding += txt ding += f"\n {datetime.now().strftime('%y%m%d %H:%M:%S')}" dingding("DASHBOARD", ding)
def auto_launch(self): not_run = self.db_client.query("tasks", { "status": 0, "server": "idle" }) if not_run: stg_list = list(map(lambda x: x["strategy"], not_run)) dingding("INSTANCE", f"> ATTEMPT AUTO-LAUNCH: {stg_list}") servers = self.db_client.query("server", {"type": "trading"}) servers_list = list(map(lambda x: x["server_name"], servers)) running_instance = self.db_client.query("tasks", {"status": 1}) running_serv = list(map(lambda x: x["server"], running_instance)) msg = "### AUTO-LAUNCHER\n\n" for instance in not_run: serv = None for serv_r in list(set(sorted(running_serv))): print("find existing:", instance["strategy"], serv_r, running_serv.count(serv_r)) if running_serv.count(serv_r) < 8: serv = serv_r running_serv.append(serv) break if not serv: f = sorted(list(set(servers_list) ^ set(running_serv))) print("NEW servers:", f) if f: serv = f[0] running_serv.append(serv) else: dingding("INSTANCE", "> Auto-launch failed, NEED NEW SERVER") break msg += yield self.launch_process(serv, instance["strategy"], instance["task_id"]) dingding("AUTO-LAUNCHER", msg)
def post(self,*args,**kwargs): current_user = self.get_current_user() logging.info(f"clearpos post,{self.request.arguments},{args}, body:{self.request.body_arguments}") sym,ac,direction = self.get_argument("symbol").split("_") qty = self.get_argument("qty") stg = filter_name(self.get_argument("strategy")) contract_map, contract_reverse = OKEX.query_futures_instruments() instrument = contract_map[sym.split(":")[0]] account_info = self.db_client.query_one("account",{"name":ac}) gateway = OKEX(account_info) open_orders = gateway.query_futures_orders(instrument,"6") print(open_orders) if open_orders.get("result",False): orders = open_orders["order_info"] need_to_cancel = list(map(lambda x:x["client_oid"] if x["client_oid"].split("FUTU")[0]==stg else None, open_orders["order_info"])) len_cancel_order = len(need_to_cancel) for oid in list(set(need_to_cancel)): r = gateway.cancel_futures_order(instrument, oid) if r.get("result", False): need_to_cancel.remove(oid) if len(need_to_cancel)>0: dingding("INSTANCE CONTROL",f"{stg}, error in cancelling orders") else: order_type = "3" if direction == "LONG" else "4" futures_price = OKEX.query_futures_price(instrument) price = f"{futures_price/1.02:0.3f}" if direction == "LONG" else f"{futures_price*1.02:0.3f}" oid = f"{stg}FUTUDSB{datetime.now().strftime('%y%m%d%H%M')}" r = gateway.send_futures_order(oid, order_type, instrument, price, qty) if r.get("result",False): dingding("INSTANCE CONTROL",f"> CLEAR POSITION: {stg}\n\n {current_user['name']} cancelled {len_cancel_order} open orders and closed postion") else: dingding("INSTANCE CONTROL",f"{stg}, error in close position:{r}")
def post(self, *args, **kwargs): task_id = datetime.now().strftime("%Y%m%d%H%M%S%f")[:-3] stg_list = list(self.request.arguments.keys()) json_obj = self.db_client.query("strategy", {"name": { "$in": stg_list }}) for strategy in json_obj: args = { "task_id": task_id, "Author": self.user["name"], "status": 0, "server": "idle", "strategy": strategy["name"], "account": strategy["trade_symbols_ac"] } self.db_client.insert_one("tasks", args) msg = self.assign_task(stg_list, task_id) dingding( "TASK", f"{args['Author']} Create Task \n\nid: {args['task_id']}\n\n{msg}") self.finish(json.dumps(task_id))
def post(self,*args, **kwargs): stg_name = self.get_argument('name',None) method = self.get_argument('method',None) task_id = self.get_argument('task_id',None) path = f"{working_path}/{task_id}" # 策略文件夹路径 server_name = self.get_argument('server',None) if server_name =="idle": if method == "archive": return self.finish(json.dumps({"result":f"{stg_name}-latest.tar"})) elif method=="delete": self.db_client.update_one("tasks",{"strategy":stg_name,"task_id":task_id},{"status":-1}) return self.finish(json.dumps({"result":True})) server = get_server(server_name) res=False if server: container = server.get(stg_name) if method and stg_name: now = int(datetime.now().timestamp()*1000) if method == "halt": if container: if container.status == "running": status = server.stop(stg_name) if status=="exited": self.db_client.update_one("tasks",{"strategy":stg_name,"task_id":task_id},{"status":0}) self.db_client.update_one("strategy",{"name":stg_name},{"server":"idle"}) self.db_client.insert_one("operation",{"name":stg_name,"op":0,"timestamp":now}) r=self.archive(server, stg_name, path) res=True else: return self.finish(json.dumps({"error":"operation halt failed"})) else: return self.finish(json.dumps({"error":"container not running"})) else: return self.finish(json.dumps({"error":"container not exists"})) elif method == "delete": if container: if container.status=="running": return self.finish(json.dumps({"error":"you should halt container in advance"})) else: r = server.remove(stg_name) if not r: res = True self.db_client.update_one("tasks",{"strategy":stg_name,"task_id":task_id},{"status":-1}) else: return self.finish(json.dumps({"error":"container not exists"})) elif method == "launch": if not container: r = server.create( IMAGE, # 镜像名 stg_name, # 策略名 f"{path}/{stg_name}" ) print("create container:",r) status = server.start(stg_name) if status == "running": res=True self.db_client.update_one("tasks",{"strategy":stg_name,"task_id":task_id},{"server":server_name,"status":1}) self.db_client.update_one("strategy",{"name":stg_name},{"server":server_name}) self.db_client.insert_one("operation",{"name":stg_name,"op":1,"timestamp":now}) elif method == "archive": res = self.archive(server, stg_name, path) else: return self.finish(json.dumps({"error":"params not exists"})) else: if method == "archive": return self.finish(json.dumps({"result":f"{stg_name}-latest.tar"})) return self.finish(json.dumps({"error":"server not exists"})) dingding("OPERATOR", f"* OPERATION {method} for {stg_name}: {res}") self.finish(json.dumps({"result":res}))