fix(trend): reconcile state from actual fills
This commit is contained in:
@@ -136,9 +136,9 @@ class State:
|
||||
|
||||
for code in list(self.codes):
|
||||
item = self.get(code)
|
||||
for order_id_attr, status_attr in (
|
||||
("base_order_id", "base_status"),
|
||||
("added_order_id", "added_status"),
|
||||
for order_id_attr, status_attr, qty_attr, cost_attr in (
|
||||
("base_order_id", "base_status", "base_qty", "base_cost"),
|
||||
("added_order_id", "added_status", "added_qty", "added_cost"),
|
||||
):
|
||||
local_order_id = getattr(item, order_id_attr)
|
||||
current_status = getattr(item, status_attr)
|
||||
@@ -150,6 +150,14 @@ class State:
|
||||
if status != current_status:
|
||||
log.info("[状态] %s 订单=%s,状态=%s->%s", code, local_order_id, current_status, status)
|
||||
setattr(item, status_attr, status)
|
||||
if status == STATUS_OK:
|
||||
quantity, cost = _filled_order(matching_orders)
|
||||
if quantity > 0:
|
||||
setattr(item, qty_attr, quantity)
|
||||
if cost > 0:
|
||||
setattr(item, cost_attr, cost)
|
||||
if status_attr == "added_status":
|
||||
item.added_num += 1
|
||||
self.set(item)
|
||||
|
||||
# Opening orders normally have no position until their first fill. Order
|
||||
@@ -212,3 +220,20 @@ def _order_status(orders: list[OrderItem] | None) -> str:
|
||||
if statuses <= BUSY_STATUSES | COMPLETED_STATUSES:
|
||||
return STATUS_ING
|
||||
return STATUS_NONE
|
||||
|
||||
|
||||
def _filled_order(orders: list[OrderItem] | None) -> tuple[int, float]:
|
||||
"""汇总已成交订单的实际数量和加权成交价。"""
|
||||
quantity = 0
|
||||
amount = 0.0
|
||||
for order in orders or []:
|
||||
filled = order.traded_volume if order.traded_volume > 0 else order.volume
|
||||
if filled <= 0:
|
||||
continue
|
||||
quantity += filled
|
||||
if order.trade_amount > 0:
|
||||
amount += order.trade_amount
|
||||
elif order.trade_price > 0:
|
||||
amount += order.trade_price * filled
|
||||
cost = round(amount / quantity, 4) if quantity > 0 and amount > 0 else 0.0
|
||||
return quantity, cost
|
||||
|
||||
Reference in New Issue
Block a user