async def _update_order(self, order_info): """ 更新订单信息 """ order_no = order_info.get('id') is_updated = False if order_no is None: return is_updated, None remain = order_info['unfilled_quantity'] quantity = order_info['quantity'] state = order_info['status'] ctime = order_info['created_at'] utime = order_info['utime'] if state == 'FULLY_FILLED': status = ORDER_STATUS_FAILED elif state == 'PARTIAL_FILLED': status = ORDER_STATUS_PARTIAL_FILLED elif state == 'PENDING': status = ORDER_STATUS_SUBMITTED elif state == 'PARTIAL_CANCELLED': status = ORDER_STATUS_PARTIAL_CANCELED elif state == 'FULLY_CANCELLED': status = ORDER_STATUS_CANCELED else: logger.error('订单状态未处理', order_info) return is_updated, None order = self._orders.get(order_no) if not order: info = { "platform": self._platform, "account": self._account, "strategy": self._strategy, "order_no": order_no, "action": ORDER_ACTION_BUY if order_info["direction"] == 'LONG' else ORDER_ACTION_SELL, "symbol": self._symbol, "price": order_info["price"], "quantity": quantity, "trade_type": TRADE_TYPE_NONE, 'remain': remain, 'status': status } order = Order(**info) is_updated = True else: if order.remain != remain: is_updated = True order.remain = remain elif order.status != status: is_updated = True order.status = status order.ctime = ctime order.utime = utime self._orders[order_no] = order if state in ('FULLY_FILLED', 'PARTIAL_CANCELLED', 'FULLY_CANCELLED'): self._orders.pop(order_no) return is_updated, order
async def _update_order(self, order_info): """ 处理委托单更新 @param order_info 委托单详情 """ if not order_info: return status_updated = False order_no = str(order_info["orderNo"]) state = order_info["state"] order = self._orders.get(order_no) if not order: info = { "platform": self._platform, "account": self._account, "strategy": self._strategy, "order_no": order_no, "action": order_info["action"], "symbol": self._symbol, "price": order_info["priceLimit"], "quantity": order_info["quantity"], "remain": order_info["quantityRemaining"], "avg_price": order_info["priceLimit"] } order = Order(**info) self._orders[order_no] = order # 已提交 if state == "UNDEAL" or state == "PROCESSING": if order.status != ORDER_STATUS_SUBMITTED: order.status = ORDER_STATUS_SUBMITTED status_updated = True # 订单部分成交 elif state == "PARTDEAL": order.status = ORDER_STATUS_PARTIAL_FILLED if order.order_type == ORDER_TYPE_LIMIT: if float(order.remain) != float( order_info["quantityRemaining"]): status_updated = True order.remain = float(order_info["quantityRemaining"]) else: if float(order.remain) != float(order_info["amountRemaining"]): status_updated = True order.remain = float(order_info["amountRemaining"]) # 订单成交完成 elif state == "DEAL": order.status = ORDER_STATUS_FILLED order.remain = 0 status_updated = True # 订单取消 elif state == "CANCEL": order.status = ORDER_STATUS_CANCELED if order.order_type == ORDER_TYPE_LIMIT: if float(order.remain) != float( order_info["quantityRemaining"]): order.remain = float(order_info["quantityRemaining"]) else: if float(order.remain) != float(order_info["amountRemaining"]): order.remain = float(order_info["amountRemaining"]) status_updated = True else: logger.warn("state error! order_info:", order_info, caller=self) return # 有状态更新 执行回调 if status_updated: order.ctime = order_info["utcCreate"] order.utime = order_info["utcUpdate"] if self._order_update_callback: SingleTask.run(self._order_update_callback, copy.copy(order)) # 删除已完成订单 if order.status in [ ORDER_STATUS_FAILED, ORDER_STATUS_CANCELED, ORDER_STATUS_FILLED ]: self._orders.pop(order_no)
async def _update_order(self, order_no, order_info): """ Update order object. Args: order_no: Order ID. order_info: Order information. """ if not order_info: return status_updated = False state = order_info["status"] order = self._orders.get(order_no) if not order: info = { "platform": self._platform, "account": self._account, "strategy": self._strategy, "order_no": order_no, "action": ORDER_ACTION_BUY if order_info["descr"]["type"] == "buy" else ORDER_ACTION_SELL, "symbol": self._symbol, "price": order_info["descr"]["price"], "quantity": order_info["vol"], "remain": order_info["vol"], "avg_price": order_info["price"] } order = Order(**info) self._orders[order_no] = order if state == "pending": if order.status != ORDER_STATUS_SUBMITTED: order.status = ORDER_STATUS_SUBMITTED status_updated = True elif state == "open": vol_exec = float(order_info['vol_exec']) if vol_exec == 0: state = ORDER_STATUS_SUBMITTED if order.status != state: order.status = ORDER_STATUS_SUBMITTED status_updated = True else: remain = float(order.quantity) - vol_exec if order.remain != remain: order.status = ORDER_STATUS_PARTIAL_FILLED order.remain = remain status_updated = True elif state == "closed": order.status = ORDER_STATUS_FILLED order.remain = 0 status_updated = True elif state == "canceled": order.status = ORDER_STATUS_CANCELED status_updated = True elif state == 'expired': order.status = ORDER_STATUS_FAILED status_updated = True else: logger.warn("state error! order_info:", order_info, caller=self) return if status_updated: order.avg_price = order_info["price"] order.ctime = int(order_info["opentm"] * 1000) order.utime = int(order_info["expiretm"] * 1000) if self._order_update_callback: SingleTask.run(self._order_update_callback, copy.copy(order)) # Delete order that already completed. if order.status in [ORDER_STATUS_FAILED, ORDER_STATUS_CANCELED, ORDER_STATUS_FILLED]: self._orders.pop(order_no)
def _update_order(self, order_info): """ 更新订单信息 @param order_info 订单信息 | "New" -> `Open, `New_order_accepted | "PartiallyFilled" -> `Open, `Partially_filled | "Filled" -> `Filled, `Filled | "DoneForDay" -> `Open, `General_order_update | "Canceled" -> `Canceled, `Canceled | "PendingCancel" -> `Pending_cancel, `General_order_update | "Stopped" -> `Open, `General_order_update | "Rejected" -> `Rejected, `New_order_rejected | "PendingNew" -> `Pending_open, `General_order_update | "Expired" -> `Rejected, `New_order_rejected | _ -> invalid_arg' execType ordStatus """ order_no = order_info["orderID"] state = order_info.get("ordStatus") if state == "New": status = ORDER_STATUS_SUBMITTED elif state == "PartiallyFilled": status = ORDER_STATUS_PARTIAL_FILLED elif state == "Filled": status = ORDER_STATUS_FILLED elif state == "Canceled": status = ORDER_STATUS_CANCELED elif state in ["PendingNew", "DoneForDay", "PendingCancel"]: return else: return order = self._orders.get(order_no) if not order: action = ORDER_ACTION_BUY if order_info["side"] == "Buy" else ORDER_ACTION_SELL text = order_info.get("text") trade_type = int(text.split("\n")[-1]) info = { "platform": self._platform, "account": self._account, "strategy": self._strategy, "symbol": self._symbol, "order_no": order_no, "action": action, "price": order_info.get("price"), "quantity": int(order_info["orderQty"]), "remain": int(order_info["orderQty"]), "trade_type": trade_type } order = Order(**info) self._orders[order_no] = order order.status = status if order_info.get("cumQty"): order.remain = order.quantity - int(order_info.get("cumQty")) if order_info.get("avgPx"): order.avg_price = order_info.get("avgPx") if order.status in [ORDER_STATUS_FILLED, ORDER_STATUS_CANCELED, ORDER_STATUS_FAILED]: self._orders.pop(order.order_no) if order_info.get("timestamp"): order.ctime = tools.utctime_str_to_mts(order_info.get("timestamp")) if order_info.get("transactTime"): order.utime = tools.utctime_str_to_mts(order_info.get("transactTime")) return order
def _update_order(self, order_info): """ Order update. Args: order_info: Order information. """ if order_info["contract_type"] != self._contract_type or order_info["symbol"] != self._symbol: return order_no = str(order_info["order_id"]) status = order_info["status"] order = self._orders.get(order_no) if not order: if order_info["direction"] == "buy": if order_info["offset"] == "open": trade_type = TRADE_TYPE_BUY_OPEN else: trade_type = TRADE_TYPE_BUY_CLOSE else: if order_info["offset"] == "close": trade_type = TRADE_TYPE_SELL_CLOSE else: trade_type = TRADE_TYPE_SELL_OPEN info = { "platform": self._platform, "account": self._account, "strategy": self._strategy, "order_no": order_no, "action": ORDER_ACTION_BUY if order_info["direction"] == "buy" else ORDER_ACTION_SELL, "symbol": self._symbol + '/' + self._contract_type, "price": order_info["price"], "quantity": order_info["volume"], "trade_type": trade_type } order = Order(**info) self._orders[order_no] = order if status in [1, 2, 3]: order.status = ORDER_STATUS_SUBMITTED elif status == 4: order.status = ORDER_STATUS_PARTIAL_FILLED order.remain = int(order.quantity) - int(order_info["trade_volume"]) elif status == 6: order.status = ORDER_STATUS_FILLED order.remain = 0 elif status in [5, 7]: order.status = ORDER_STATUS_CANCELED order.remain = int(order.quantity) - int(order_info["trade_volume"]) else: return order.avg_price = order_info["trade_avg_price"] order.ctime = order_info["created_at"] order.utime = order_info["ts"] SingleTask.run(self._order_update_callback, copy.copy(order)) # Delete order that already completed. if order.status in [ORDER_STATUS_FAILED, ORDER_STATUS_CANCELED, ORDER_STATUS_FILLED]: self._orders.pop(order_no) # publish order EventOrder(**order.__dict__).publish() logger.info("symbol:", order.symbol, "order:", order, caller=self)
async def create_order(self, action, price, quantity, order_type=ORDER_TYPE_LIMIT): """ 下单 """ if not self._last_kline or not self._last_kline.usable: return None, "无法创建订单" #获取符号相关信息 syminfo = config.backtest["feature"][self._platform]["syminfo"][self._symbol] price_tick = syminfo["price_tick"] #价格变动最小精度 size_tick = syminfo["size_tick"] #下单数量变动最小精度 size_limit = syminfo["size_limit"] #下单数量最小限制 value_tick = syminfo["value_tick"] #下单金额变动最小精度 value_limit = syminfo["value_limit"] #下单金额最小限制 base_currency = syminfo["base_currency"] #基础币种,交易标的,或者说就是'货' settlement_currency = syminfo["settlement_currency"] #结算币种,或者说就是'钱' #输入参数验证 if order_type == ORDER_TYPE_MARKET: if price: return None, "无法创建订单,市价单价格必须填0" if action == ORDER_ACTION_BUY: #市价买单quantity代表的是下单金额 if quantity < value_limit: return None, "无法创建订单,下单金额太少" if not self.precision_verify(quantity, value_tick): return None, "无法创建订单,下单金额精度错误" else: if quantity < size_limit: return None, "无法创建订单,下单数量太少" if not self.precision_verify(quantity, size_tick): return None, "无法创建订单,下单数量精度错误" else: if price <= 0: return None, "无法创建订单,价格必须大于0" if not self.precision_verify(price, price_tick): return None, "无法创建订单,价格精度错误" if quantity < size_limit: return None, "无法创建订单,下单数量太少" if not self.precision_verify(quantity, size_tick): return None, "无法创建订单,下单数量精度错误" #获取当前时间 ts = ModelAPI.current_milli_timestamp() # if order_type == ORDER_TYPE_MARKET: #市价单 if action == ORDER_ACTION_BUY: #买 bc = self._trader._assets[base_currency] sc = self._trader._assets[settlement_currency] if quantity > sc['free']: return None, "账户余额不够" #收盘均价模拟成交价 tradeprice = tools.nearest(self._last_kline.close_avg_fillna, price_tick) #市价买单quantity指的是'钱',逼真模拟 tradevolmue, left_money = self.market_buy_order_cross(quantity, tradeprice, size_tick) #市价买单quantity指的是'钱' #tradevolmue = quantity/tradeprice #对于现货交易,手续费是从接收币种里面扣除 fee = tradevolmue*self.taker_commission_rate #订单通知 order_no = self.next_order_no() o = { "platform": self._platform, "account": self._account, "strategy": self._strategy, "order_no": order_no, "action": action, "symbol": self._symbol, "price": 0, "quantity": tools.nearest(quantity, value_tick), "remain": tools.nearest(left_money, value_tick), "status": ORDER_STATUS_FILLED, "order_type": order_type, "ctime": ts, "utime": ts #avg_price #trade_type } order = Order(**o) if self.cb.on_order_update_callback: await self.cb.on_order_update_callback(order) #成交通知 fill_no = self.next_fill_no() f = { "platform": self._platform, "account": self._account, "strategy": self._strategy, "fill_no": fill_no, "order_no": order_no, "side": action, #成交方向,买还是卖 "symbol": self._symbol, "price": tools.nearest(tradeprice, price_tick), #成交价格 "quantity": tools.nearest(tradevolmue, size_tick), #成交数量 "liquidity": LIQUIDITY_TYPE_TAKER, #maker成交还是taker成交 "fee": tools.nearest(fee, size_tick), "ctime": ts } fill = Fill(**f) if self.cb.on_fill_update_callback: await self.cb.on_fill_update_callback(fill) #账户资产通知 #'货'增加 bc['free'] += (tradevolmue-fee) bc['free'] = tools.nearest(bc['free'], size_tick) bc['total'] = bc['free'] + bc['locked'] bc['total'] = tools.nearest(bc['total'], size_tick) #'钱'减少 sc['free'] -= quantity #市价买单quantity指的是'钱' sc['free'] = tools.nearest(sc['free'], value_tick) sc['total'] = sc['free'] + sc['locked'] sc['total'] = tools.nearest(sc['total'], value_tick) # ast = Asset(self._platform, self._account, self._trader._assets, ts, True) if self.cb.on_asset_update_callback: await self.cb.on_asset_update_callback(ast) elif action == ORDER_ACTION_SELL: #卖 bc = self._trader._assets[base_currency] sc = self._trader._assets[settlement_currency] if quantity > bc['free']: return None, "账户币不足" #收盘均价模拟成交价 tradeprice = tools.nearest(self._last_kline.close_avg_fillna, price_tick) trademoney = quantity*tradeprice #对于现货交易,手续费是从接收币种里面扣除 fee = trademoney*self.taker_commission_rate trademoney -= fee #订单通知 order_no = self.next_order_no() o = { "platform": self._platform, "account": self._account, "strategy": self._strategy, "order_no": order_no, "action": action, "symbol": self._symbol, "price": 0, "quantity": tools.nearest(quantity, size_tick), "remain": 0, "status": ORDER_STATUS_FILLED, "order_type": order_type, "ctime": ts, "utime": ts #avg_price #trade_type } order = Order(**o) if self.cb.on_order_update_callback: await self.cb.on_order_update_callback(order) #成交通知 fill_no = self.next_fill_no() f = { "platform": self._platform, "account": self._account, "strategy": self._strategy, "fill_no": fill_no, "order_no": order_no, "side": action, #成交方向,买还是卖 "symbol": self._symbol, "price": tools.nearest(tradeprice, price_tick), #成交价格 "quantity": tools.nearest(quantity, size_tick), #成交数量 "liquidity": LIQUIDITY_TYPE_TAKER, #maker成交还是taker成交 "fee": tools.nearest(fee, value_tick), "ctime": ts } fill = Fill(**f) if self.cb.on_fill_update_callback: await self.cb.on_fill_update_callback(fill) #账户资产通知 #'货'减少 bc['free'] -= quantity bc['free'] = tools.nearest(bc['free'], size_tick) bc['total'] = bc['free'] + bc['locked'] bc['total'] = tools.nearest(bc['total'], size_tick) #'钱'增加 sc['free'] += trademoney sc['free'] = tools.nearest(sc['free'], value_tick) sc['total'] = sc['free'] + sc['locked'] sc['total'] = tools.nearest(sc['total'], value_tick) # ast = Asset(self._platform, self._account, self._trader._assets, ts, True) if self.cb.on_asset_update_callback: await self.cb.on_asset_update_callback(ast) elif order_type == ORDER_TYPE_LIMIT: #限价单 if action == ORDER_ACTION_BUY: #买 bc = self._trader._assets[base_currency] sc = self._trader._assets[settlement_currency] if quantity*price > sc['free']: return None, "账户余额不够" #如果下单价格小于当前价格,那意味着无法成交,订单将进入订单薄挂着 if price < self._last_kline.close_avg_fillna: #订单通知 order_no = self.next_order_no() o = { "platform": self._platform, "account": self._account, "strategy": self._strategy, "order_no": order_no, "action": action, "symbol": self._symbol, "price": tools.nearest(price, price_tick), "quantity": tools.nearest(quantity, size_tick), "remain": tools.nearest(quantity, size_tick), "status": ORDER_STATUS_SUBMITTED, "order_type": order_type, "ctime": ts, "utime": ts #avg_price #trade_type } order = Order(**o) self._orders[order_no] = order #进入订单簿 if self.cb.on_order_update_callback: await self.cb.on_order_update_callback(order) #账户资产通知 #'钱'需要被锁定一部分 sc['locked'] += quantity*price #挂单部分所占用的资金需要被锁定 sc['locked'] = tools.nearest(sc['locked'], value_tick) sc['free'] = sc['total'] - sc['locked'] sc['free'] = tools.nearest(sc['free'], value_tick) # ast = Asset(self._platform, self._account, self._trader._assets, ts, True) if self.cb.on_asset_update_callback: await self.cb.on_asset_update_callback(ast) else: #直接成交 #收盘均价模拟成交价 tradeprice = tools.nearest(self._last_kline.close_avg_fillna, price_tick) tradevolmue = quantity #直接模拟全部成交 trademoney = tradeprice*tradevolmue #成交金额 #对于现货交易,手续费是从接收币种里面扣除 fee = tradevolmue*self.taker_commission_rate #订单通知 order_no = self.next_order_no() o = { "platform": self._platform, "account": self._account, "strategy": self._strategy, "order_no": order_no, "action": action, "symbol": self._symbol, "price": tools.nearest(price, price_tick), "quantity": tools.nearest(quantity, size_tick), "remain": 0, "status": ORDER_STATUS_FILLED, "order_type": order_type, "ctime": ts, "utime": ts #avg_price #trade_type } order = Order(**o) if self.cb.on_order_update_callback: await self.cb.on_order_update_callback(order) #成交通知 fill_no = self.next_fill_no() f = { "platform": self._platform, "account": self._account, "strategy": self._strategy, "fill_no": fill_no, "order_no": order_no, "side": action, #成交方向,买还是卖 "symbol": self._symbol, "price": tools.nearest(tradeprice, price_tick), #成交价格 "quantity": tools.nearest(tradevolmue, size_tick), #成交数量 "liquidity": LIQUIDITY_TYPE_TAKER, #maker成交还是taker成交 "fee": tools.nearest(fee, size_tick), "ctime": ts } fill = Fill(**f) if self.cb.on_fill_update_callback: await self.cb.on_fill_update_callback(fill) #账户资产通知 #'货'增加 bc['free'] += (tradevolmue-fee) bc['free'] = tools.nearest(bc['free'], size_tick) bc['total'] = bc['free'] + bc['locked'] bc['total'] = tools.nearest(bc['total'], size_tick) #'钱'减少 sc['free'] -= trademoney sc['free'] = tools.nearest(sc['free'], value_tick) sc['total'] = sc['free'] + sc['locked'] sc['total'] = tools.nearest(sc['total'], value_tick) # ast = Asset(self._platform, self._account, self._trader._assets, ts, True) if self.cb.on_asset_update_callback: await self.cb.on_asset_update_callback(ast) elif action == ORDER_ACTION_SELL: #卖 bc = self._trader._assets[base_currency] sc = self._trader._assets[settlement_currency] if quantity > bc['free']: return None, "账户币不足" #如果下单价格大于当前价格,那意味着无法成交,订单将进入订单薄挂着 if price > self._last_kline.close_avg_fillna: #订单通知 order_no = self.next_order_no() o = { "platform": self._platform, "account": self._account, "strategy": self._strategy, "order_no": order_no, "action": action, "symbol": self._symbol, "price": tools.nearest(price, price_tick), "quantity": tools.nearest(quantity, size_tick), "remain": tools.nearest(quantity, size_tick), "status": ORDER_STATUS_SUBMITTED, "order_type": order_type, "ctime": ts, "utime": ts #avg_price #trade_type } order = Order(**o) self._orders[order_no] = order #进入订单簿 if self.cb.on_order_update_callback: await self.cb.on_order_update_callback(order) #账户资产通知 #'货'需要被锁定一部分 bc['locked'] += quantity #挂单部分所占用的'货'需要被锁定 bc['locked'] = tools.nearest(bc['locked'], size_tick) bc['free'] = bc['total'] - bc['locked'] bc['free'] = tools.nearest(bc['free'], size_tick) # ast = Asset(self._platform, self._account, self._trader._assets, ts, True) if self.cb.on_asset_update_callback: await self.cb.on_asset_update_callback(ast) else: #直接成交 #收盘均价模拟成交价 tradeprice = tools.nearest(self._last_kline.close_avg_fillna, price_tick) trademoney = quantity*tradeprice #对于现货交易,手续费是从接收币种里面扣除 fee = trademoney*self.taker_commission_rate trademoney -= fee #订单通知 order_no = self.next_order_no() o = { "platform": self._platform, "account": self._account, "strategy": self._strategy, "order_no": order_no, "action": action, "symbol": self._symbol, "price": tools.nearest(price, price_tick), "quantity": tools.nearest(quantity, size_tick), "remain": 0, "status": ORDER_STATUS_FILLED, "order_type": order_type, "ctime": ts, "utime": ts #avg_price #trade_type } order = Order(**o) if self.cb.on_order_update_callback: await self.cb.on_order_update_callback(order) #成交通知 fill_no = self.next_fill_no() f = { "platform": self._platform, "account": self._account, "strategy": self._strategy, "fill_no": fill_no, "order_no": order_no, "side": action, #成交方向,买还是卖 "symbol": self._symbol, "price": tools.nearest(tradeprice, price_tick), #成交价格 "quantity": tools.nearest(quantity, size_tick), #成交数量 "liquidity": LIQUIDITY_TYPE_TAKER, #maker成交还是taker成交 "fee": tools.nearest(fee, value_tick), "ctime": ts } fill = Fill(**f) if self.cb.on_fill_update_callback: await self.cb.on_fill_update_callback(fill) #账户资产通知 #'货'减少 bc['free'] -= quantity bc['free'] = tools.nearest(bc['free'], size_tick) bc['total'] = bc['free'] + bc['locked'] bc['total'] = tools.nearest(bc['total'], size_tick) #'钱'增加 sc['free'] += trademoney sc['free'] = tools.nearest(sc['free'], value_tick) sc['total'] = sc['free'] + sc['locked'] sc['total'] = tools.nearest(sc['total'], value_tick) # ast = Asset(self._platform, self._account, self._trader._assets, ts, True) if self.cb.on_asset_update_callback: await self.cb.on_asset_update_callback(ast) elif order_type == ORDER_TYPE_IOC: raise NotImplementedError #返回订单号 return order_no, None
def parse(self): """ Parse self._data to Order object. """ order = Order(**self.data) return order
async def _update_order(self, order_info): """ Update order object. Args: order_info: Order information. """ if not order_info: return status_updated = False order_no = str(order_info["orderNo"]) state = order_info["state"] order = self._orders.get(order_no) if not order: info = { "platform": self._platform, "account": self._account, "strategy": self._strategy, "order_no": order_no, "action": order_info["action"], "symbol": self._symbol, "price": order_info["priceLimit"], "quantity": order_info["quantity"], "remain": order_info["quantityRemaining"], "avg_price": order_info["priceLimit"] } order = Order(**info) self._orders[order_no] = order if state == "UNDEAL" or state == "PROCESSING": if order.status != ORDER_STATUS_SUBMITTED: order.status = ORDER_STATUS_SUBMITTED status_updated = True elif state == "PARTDEAL": order.status = ORDER_STATUS_PARTIAL_FILLED if order.order_type == ORDER_TYPE_LIMIT: if float(order.remain) != float( order_info["quantityRemaining"]): status_updated = True order.remain = float(order_info["quantityRemaining"]) else: if float(order.remain) != float(order_info["amountRemaining"]): status_updated = True order.remain = float(order_info["amountRemaining"]) elif state == "DEAL": order.status = ORDER_STATUS_FILLED order.remain = 0 status_updated = True elif state == "CANCEL": order.status = ORDER_STATUS_CANCELED status_updated = True else: logger.warn("state error! order_info:", order_info, caller=self) return # If order status updated, callback newest order information. if status_updated: order.ctime = order_info["utcCreate"] order.utime = order_info["utcUpdate"] if self._order_update_callback: SingleTask.run(self._order_update_callback, copy.copy(order)) # Delete order that already completed. if order.status in [ ORDER_STATUS_FAILED, ORDER_STATUS_CANCELED, ORDER_STATUS_FILLED ]: self._orders.pop(order_no)
def _update_order(self, order_info): """ Order update. Args: order_info: Order information. Returns: None. """ order_no = str(order_info["order_id"]) state = order_info["state"] remain = int(order_info["size"]) - int(order_info["filled_qty"]) ctime = tools.utctime_str_to_mts(order_info["timestamp"]) if state == "-2": status = ORDER_STATUS_FAILED elif state == "-1": status = ORDER_STATUS_CANCELED elif state == "0": status = ORDER_STATUS_SUBMITTED elif state == "1": status = ORDER_STATUS_PARTIAL_FILLED elif state == "2": status = ORDER_STATUS_FILLED else: return None order = self._orders.get(order_no) if not order: info = { "platform": self._platform, "account": self._account, "strategy": self._strategy, "order_no": order_no, "client_order_id": order_info["client_oid"], "action": ORDER_ACTION_BUY if order_info["type"] in ["1", "4"] else ORDER_ACTION_SELL, "symbol": self._symbol, "price": order_info["price"], "quantity": order_info["size"], "trade_type": int(order_info["type"]) } order = Order(**info) order.remain = remain order.status = status order.avg_price = order_info["price_avg"] order.ctime = ctime order.utime = ctime self._orders[order_no] = order SingleTask.run(self._order_update_callback, copy.copy(order)) if status in [ ORDER_STATUS_FAILED, ORDER_STATUS_CANCELED, ORDER_STATUS_FILLED ]: self._orders.pop(order_no)
async def connected_callback(self): """ 建立连接之后,获取当前所有未完全成交的订单 """ logger.info("Websocket connection authorized successfully.", caller=self) order_infos, error = await self._rest_api.get_open_orders( self._raw_symbol) if error: e = Error("get open orders error: {}".format(error)) if self._init_success_callback: SingleTask.run(self._init_success_callback, False, e) return for order_info in order_infos: order_no = "{}_{}".format(order_info["orderId"], order_info["clientOrderId"]) if order_info["status"] == "NEW": # 部分成交 status = ORDER_STATUS_SUBMITTED elif order_info["status"] == "PARTIALLY_FILLED": # 部分成交 status = ORDER_STATUS_PARTIAL_FILLED elif order_info["status"] == "FILLED": # 完全成交 status = ORDER_STATUS_FILLED elif order_info["status"] == "CANCELED": # 取消 status = ORDER_STATUS_CANCELED elif order_info["status"] == "REJECTED": # 拒绝 status = ORDER_STATUS_FAILED elif order_info["status"] == "EXPIRED": # 过期 status = ORDER_STATUS_FAILED else: logger.warn("unknown status:", order_info, caller=self) continue info = { "platform": self._platform, "account": self._account, "strategy": self._strategy, "order_no": order_no, "action": order_info["side"], "order_type": order_info["type"], "symbol": self._symbol, "price": order_info["price"], "quantity": order_info["origQty"], "remain": float(order_info["origQty"]) - float(order_info["executedQty"]), "status": status, "ctime": order_info["time"], "utime": order_info["updateTime"] } order = Order(**info) self._orders[order_no] = order if self._order_update_callback: SingleTask.run(self._order_update_callback, order) if self._init_success_callback: SingleTask.run(self._init_success_callback, True, None)
def _update_order(self, order_info): """ Order update. Args: order_info: Order information. Returns: None. """ order_no = str(order_info["order_id"]) state = order_info["state"] remain = float(order_info["size"]) - float(order_info["filled_size"]) ctime = tools.utctime_str_to_mts(order_info["ctime"]) utime = tools.utctime_str_to_mts(order_info["utime"]) if state == "-2": status = ORDER_STATUS_FAILED elif state == "-1": status = ORDER_STATUS_CANCELED elif state == "0": status = ORDER_STATUS_SUBMITTED elif state == "1": status = ORDER_STATUS_PARTIAL_FILLED elif state == "2": status = ORDER_STATUS_FILLED else: logger.error("status error! order_info:", order_info, caller=self) return None order = self._orders.get(order_no) if order: order.remain = remain order.status = status order.price = order_info["price"] else: info = { "platform": self._platform, "account": self._account, "strategy": self._strategy, "order_no": order_no, "client_order_id": order_info["client_oid"], "action": ORDER_ACTION_BUY if order_info["side"] == "buy" else ORDER_ACTION_SELL, "symbol": self._symbol, "price": order_info["price"], "quantity": order_info["size"], "remain": remain, "status": status, "avg_price": order_info["price"] } order = Order(**info) self._orders[order_no] = order order.ctime = ctime order.utime = utime SingleTask.run(self._order_update_callback, copy.copy(order)) if status in [ ORDER_STATUS_FAILED, ORDER_STATUS_CANCELED, ORDER_STATUS_FILLED ]: self._orders.pop(order_no)
def _update_order(self, order_info): """ 更新订单信息 @param order_info 订单信息 """ is_updated = False # 当前订单相比之前是否有更新 order_no = order_info['id'] state = order_info["state"] remain = float(order_info["amount"]) - float( order_info["filled_amount"]) ctime = order_info["created_at"] if state == "canceled": status = ORDER_STATUS_CANCELED elif state == "submitted": status = ORDER_STATUS_SUBMITTED elif state == "partial_filled": status = ORDER_STATUS_PARTIAL_FILLED elif state == "filled": status = ORDER_STATUS_FILLED elif state == 'partial_canceled': status = ORDER_STATUS_CANCELED elif state == 'pending_cancel': status = ORDER_STATUS_CANCELED else: logger.error("status error! order_info:", order_info, caller=self) return None order = self._orders.get(order_no) if order: if order.remain != remain: is_updated = True order.remain = remain elif order.status != status: is_updated = True order.status = status elif order.price != order_info["price"]: is_updated = True order.price = order_info["price"] else: info = { "platform": self._platform, "account": self._account, "strategy": self._strategy, "order_no": order_no, "action": ORDER_ACTION_BUY if order_info["side"] == "buy" else ORDER_ACTION_SELL, "symbol": self._symbol, "price": order_info["price"], "quantity": order_info["amount"], "remain": remain, "status": status, "avg_price": order_info["price"] } order = Order(**info) self._orders[order_no] = order is_updated = True order.ctime = ctime if status in [ ORDER_STATUS_FAILED, ORDER_STATUS_CANCELED, ORDER_STATUS_FILLED, ORDER_STATUS_PARTIAL_CANCELED ]: self._orders.pop(order_no) return is_updated, order
async def _update_order(self, order_info): """ 更新订单信息 :param order_info: 订单信息 :return: """ order_no = order_info.get('id') is_updated = False if order_no is None: return is_updated, None remain = order_info['left'] quantity = order_info['size'] finish_as = order_info['finish_as'] state = order_info['status'] ctime = order_info['create_tim'] if state == 'finished': if finish_as == 'filled' or finish_as == 'ioc' or finish_as == 'auto_deleveraged': status = ORDER_STATUS_FILLED elif finish_as == 'cancelled' or finish_as == 'liquidated' or finish_as == 'reduce_only': status = ORDER_STATUS_CANCELED else: logger.error("status error! order_info:", order_info, caller=self) return None elif state == 'open': if quantity != remain: if remain != 0: status = ORDER_STATUS_PARTIAL_FILLED else: status = ORDER_STATUS_FILLED else: status = ORDER_STATUS_SUBMITTED else: logger.error("status error! order_info:", order_info, caller=self) return None order = self._orders.get(order_no) if order: if order.remain != remain: is_updated = True order.remain = remain elif order.status != status: is_updated = True order.status = status elif order.avg_price != order_info['fill_price']: is_updated = True order.price = order_info["price"] else: info = { "platform": self._platform, "account": self._account, "strategy": self._strategy, "order_no": order_no, "action": ORDER_ACTION_BUY if order_info["size"] > 0 else ORDER_ACTION_SELL, "symbol": self._symbol, "price": float(order_info["price"]), "quantity": abs(quantity), "trade_type": int(order_info["text"].split('-')[1]), "remain": abs(remain), "status": status, "avg_price": order_info["fill_price"] } order = Order(**info) self._orders[order_no] = order is_updated = True order.ctime = ctime order.utime = int(time.time()) if status in [ORDER_STATUS_CANCELED, ORDER_STATUS_FILLED]: self._orders.pop(order_no) return is_updated, order
def _update_order(self, order_info=None, s_order_id=None): """ 更新订单信息 """ order = None if order_info: logger.debug('查询订单信息, order: ', order_info) order_no = str(order_info['id']) state = str(order_info["status"]) remain = float(order_info["surplusCount"]) utime = order_info["updateTime"] ctime = order_info["createDate"] action = ORDER_ACTION_BUY if str( order_info['orderType']) == "1" else ORDER_ACTION_SELL if state == "5": status = ORDER_STATUS_CANCELED elif state == "2": status = ORDER_STATUS_PARTIAL_FILLED elif state == "3": status = ORDER_STATUS_FILLED elif state == "4": status = ORDER_STATUS_PENDING_CANCEL else: status = ORDER_STATUS_SUBMITTED info = { "platform": self._platform, "account": self._account, "strategy": self._strategy, "order_no": order_no, "action": action, "symbol": order_info['symbol'], "price": order_info["putPrice"], "quantity": order_info["count"], } order = Order(**info) if order_info.get('dealPrice') is None: avg_price = 0.0 else: avg_price = float(order_info.get('dealPrice')) order.remain = remain order.status = status order.avg_price = avg_price order.ctime = ctime order.utime = utime if s_order_id: info = { "platform": self._platform, "account": self._account, "strategy": self._strategy, "order_no": str(s_order_id), "symbol": self._symbol, } order = Order(**info) order.status = ORDER_STATUS_CANCELED if order and self._order_update_callback: SingleTask.run(self._order_update_callback, copy.copy(order)) return order