Trade
GetPendingOrders - 查询未完成订单
查询当前所有未完成的订单(挂单),包括部分成交和完全未成交的订单。
语法
python
orders = exchange.GetPendingOrders()参数
无参数。
返回值
返回订单数组(list),每个元素为订单对象(dict),失败返回空列表 []。
订单对象字段说明:
| 字段 | 类型 | 说明 |
|---|---|---|
| Id | str | 订单唯一标识 |
| Price | float | 订单价格 |
| Amount | float | 订单数量 |
| DealAmount | float | 已成交数量 |
| AvgPrice | float | 成交均价 |
| Status | int | 订单状态(0=未完成) |
| Type | int | 订单类型(0=买单, 1=卖单) |
| Offset | int | 期货开平方向(0=开仓, 1=平仓) |
| ContractType | str | 合约类型(期货) |
示例
1. 基础查询未完成订单
python
# 查询所有挂单
orders = exchange.GetPendingOrders()
Log(f"当前挂单数量: {len(orders)}")
for order in orders:
order_type = "买单" if order["Type"] == 0 else "卖单"
filled_pct = (order["DealAmount"] / order["Amount"]) * 100
Log(f"{order_type} - 价格: {order['Price']}")
Log(f" 总量: {order['Amount']}, 已成交: {order['DealAmount']} ({filled_pct:.1f}%)")2. 撤销所有挂单
python
# 方法1:逐个撤销
orders = exchange.GetPendingOrders()
for order in orders:
exchange.CancelOrder(order["Id"])
Log(f"已撤销订单: {order['Id']}")
# 方法2:使用 CancelAllOrders
canceled = exchange.CancelAllOrders()
Log(f"已撤销 {canceled} 个订单")3. 只撤销买单或卖单
python
def cancel_pending_orders(order_type=None):
"""
撤销挂单
order_type: 0=只撤买单, 1=只撤卖单, None=全部撤销
"""
orders = exchange.GetPendingOrders()
canceled = 0
for order in orders:
if order_type is None or order["Type"] == order_type:
exchange.CancelOrder(order["Id"])
canceled += 1
Log(f"已撤销 {canceled} 个订单")
return canceled
# 只撤销买单
cancel_pending_orders(order_type=0)
# 只撤销卖单
cancel_pending_orders(order_type=1)
# 全部撤销
cancel_pending_orders()4. 网格策略订单管理
python
def manage_grid_orders(target_price, grid_size, grid_count):
"""
管理网格订单,保持指定数量的挂单
"""
# 查询当前挂单
orders = exchange.GetPendingOrders()
# 如果挂单数量正确,不做操作
if len(orders) == grid_count * 2:
Log("网格订单完整")
return
# 撤销所有旧订单
for order in orders:
exchange.CancelOrder(order["Id"])
Sleep(1000)
# 重新挂网格订单
for i in range(1, grid_count + 1):
buy_price = target_price * (1 - grid_size * i)
sell_price = target_price * (1 + grid_size * i)
exchange.Buy(buy_price, 0.1)
exchange.Sell(sell_price, 0.1)
Log(f"网格订单已更新: {grid_count} 层")
# 使用:在当前价格附近布置5层网格,每层间隔1%
ticker = exchange.GetTicker()
manage_grid_orders(ticker["Last"], 0.01, 5)5. 监控挂单成交情况
python
# 记录初始挂单
initial_orders = exchange.GetPendingOrders()
initial_count = len(initial_orders)
while True:
current_orders = exchange.GetPendingOrders()
current_count = len(current_orders)
# 检测订单变化
if current_count < initial_count:
filled = initial_count - current_count
Log(f"有 {filled} 个订单成交了")
# 更新记录
initial_orders = current_orders
initial_count = current_count
Sleep(5000)6. 按价格区间撤单
python
def cancel_orders_by_price(min_price, max_price):
"""撤销指定价格区间的挂单"""
orders = exchange.GetPendingOrders()
canceled = 0
for order in orders:
if min_price <= order["Price"] <= max_price:
exchange.CancelOrder(order["Id"])
Log(f"撤销价格 {order['Price']} 的订单")
canceled += 1
Log(f"撤销了 {canceled} 个订单")
return canceled
# 撤销价格在100-110之间的订单
cancel_orders_by_price(100, 110)7. 清理部分成交的订单
python
def cancel_partial_filled_orders():
"""撤销所有部分成交的订单"""
orders = exchange.GetPendingOrders()
canceled = 0
for order in orders:
if order["DealAmount"] > 0: # 有部分成交
fill_ratio = order["DealAmount"] / order["Amount"]
Log(f"撤销部分成交订单: {order['Id']} (成交率 {fill_ratio*100:.1f}%)")
exchange.CancelOrder(order["Id"])
canceled += 1
Log(f"共撤销 {canceled} 个部分成交订单")
cancel_partial_filled_orders()8. 动态调整挂单价格
python
def adjust_pending_orders(price_adjustment):
"""
根据市场变化调整挂单价格
price_adjustment: 价格调整比例(如0.01表示上调1%)
"""
orders = exchange.GetPendingOrders()
# 记录旧订单信息
old_orders = []
for order in orders:
old_orders.append({
"type": order["Type"],
"amount": order["Amount"] - order["DealAmount"], # 未成交部分
"price": order["Price"]
})
exchange.CancelOrder(order["Id"])
Sleep(1000)
# 以新价格重新下单
for old in old_orders:
new_price = old["price"] * (1 + price_adjustment)
if old["type"] == 0: # 买单
exchange.Buy(new_price, old["amount"])
else: # 卖单
exchange.Sell(new_price, old["amount"])
Log(f"已调整 {len(old_orders)} 个订单价格")
# 将所有挂单价格上调1%
adjust_pending_orders(0.01)9. 合约挂单管理
python
exchange.SetContractType("swap")
# 查询合约挂单
orders = exchange.GetPendingOrders()
buy_orders = [] # 开多/平空订单
sell_orders = [] # 开空/平多订单
for order in orders:
if order["Type"] == 0: # 买入
buy_orders.append(order)
else: # 卖出
sell_orders.append(order)
Log(f"买入挂单: {len(buy_orders)} 个")
Log(f"卖出挂单: {len(sell_orders)} 个")
# 按价格排序
buy_orders.sort(key=lambda x: x["Price"], reverse=True) # 价格从高到低
sell_orders.sort(key=lambda x: x["Price"]) # 价格从低到高
# 显示最优挂单
if buy_orders:
Log(f"最高买价: {buy_orders[0]['Price']}")
if sell_orders:
Log(f"最低卖价: {sell_orders[0]['Price']}")10. 挂单风险管理
python
def check_pending_order_risk():
"""检查挂单风险,避免过度挂单"""
orders = exchange.GetPendingOrders()
account = exchange.GetAccount()
# 统计挂单占用资金
buy_value = 0
sell_amount = 0
for order in orders:
if order["Type"] == 0: # 买单
remaining = order["Amount"] - order["DealAmount"]
buy_value += order["Price"] * remaining
else: # 卖单
remaining = order["Amount"] - order["DealAmount"]
sell_amount += remaining
# 计算风险指标
balance = account["Balance"]
stocks = account["Stocks"]
buy_ratio = buy_value / balance if balance > 0 else 0
sell_ratio = sell_amount / stocks if stocks > 0 else 0
Log(f"买单占用: {buy_value} ({buy_ratio*100:.1f}% 余额)")
Log(f"卖单占用: {sell_amount} ({sell_ratio*100:.1f}% 持仓)")
# 风险预警
if buy_ratio > 0.8:
Log("警告: 买单占用资金过多,建议撤销部分订单")
if sell_ratio > 0.8:
Log("警告: 卖单占用币数过多,建议撤销部分订单")
return {
"buy_value": buy_value,
"buy_ratio": buy_ratio,
"sell_amount": sell_amount,
"sell_ratio": sell_ratio
}
check_pending_order_risk()注意事项
- 查询频率:挂单查询比较常用,但仍需注意API限频,建议间隔1-2秒
- 订单状态:只返回状态为0(未完成)的订单,已完成或已取消的不会返回
- 部分成交:返回的订单可能已有部分成交,通过
DealAmount字段判断 - 撤单时机:批量撤单前建议先查询挂单列表,避免重复撤单
- 合约交易:合约挂单包含开平方向,需要注意
Offset字段 - 订单数量限制:某些交易所限制最大挂单数量,超过限制会下单失败