2026-08-28 18:52:27 +08:00
|
|
|
|
"""趋势策略委托簿,对应 Go 客户端的 ``logic/order.go``。"""
|
|
|
|
|
|
|
|
|
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
|
|
|
|
|
import secrets
|
2026-09-01 14:28:49 +08:00
|
|
|
|
import logging as log
|
2026-08-28 18:52:27 +08:00
|
|
|
|
from dataclasses import dataclass
|
|
|
|
|
|
from datetime import datetime, timedelta
|
|
|
|
|
|
from threading import Lock
|
|
|
|
|
|
from typing import Any
|
2026-09-05 00:23:55 +08:00
|
|
|
|
from cachelib import SimpleCache
|
2026-08-28 18:52:27 +08:00
|
|
|
|
|
2026-09-01 14:28:49 +08:00
|
|
|
|
from sdk import APIError, ORDER_SIDE_BY_OFFSET, Client, OrderItem
|
2026-08-28 18:52:27 +08:00
|
|
|
|
|
|
|
|
|
|
# 表示委托仍在处理、可能继续成交的 QMT 状态。
|
|
|
|
|
|
BUSY_STATUSES = {"48", "49", "50", "51", "52", "55"}
|
2026-08-30 14:46:34 +08:00
|
|
|
|
COMPLETED_STATUSES = {"56"}
|
|
|
|
|
|
TRACKED_STATUSES = BUSY_STATUSES | COMPLETED_STATUSES
|
|
|
|
|
|
CANCELABLE_STATUSES = {"49", "50", "51", "52"}
|
2026-08-28 18:52:27 +08:00
|
|
|
|
|
|
|
|
|
|
|
2026-08-28 22:46:04 +08:00
|
|
|
|
@dataclass(frozen=True, slots=True)
|
2026-08-28 18:52:27 +08:00
|
|
|
|
class PlaceOrderRequest:
|
|
|
|
|
|
"""``OrderBook.place`` 提交委托所需的全部参数。"""
|
|
|
|
|
|
|
|
|
|
|
|
client: Any
|
|
|
|
|
|
op: int
|
|
|
|
|
|
code: str
|
|
|
|
|
|
volume: int
|
|
|
|
|
|
order_id: str
|
2026-08-28 22:46:04 +08:00
|
|
|
|
strategy_name: str
|
2026-08-28 18:52:27 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class OrderBook:
|
|
|
|
|
|
"""线程安全的活动委托缓存。"""
|
|
|
|
|
|
|
2026-09-05 00:23:55 +08:00
|
|
|
|
def __init__(self, lock_timeout_sec: int = 180, cancel_timeout_sec: float = 10) -> None:
|
|
|
|
|
|
self.lock_timeout_sec = max(1, lock_timeout_sec)
|
2026-08-30 00:34:27 +08:00
|
|
|
|
self.cancel_timeout_sec = timedelta(seconds=cancel_timeout_sec)
|
2026-08-30 14:46:34 +08:00
|
|
|
|
self.data: list[OrderItem] = []
|
2026-09-05 11:32:10 +08:00
|
|
|
|
self.busy_keys: set[str] = set()
|
2026-09-05 00:23:55 +08:00
|
|
|
|
self.busy_cache = SimpleCache(threshold=10_000, default_timeout=self.lock_timeout_sec)
|
2026-08-30 00:34:27 +08:00
|
|
|
|
self.mutex = Lock()
|
2026-08-28 18:52:27 +08:00
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
2026-09-05 00:23:55 +08:00
|
|
|
|
def new_order_id() -> str:
|
2026-09-03 15:27:11 +08:00
|
|
|
|
"""生成 ``trend-xxxxxxxx`` 格式的本地订单号。"""
|
2026-09-05 00:23:55 +08:00
|
|
|
|
return f"trend-{secrets.token_hex(12)}"
|
2026-08-28 18:52:27 +08:00
|
|
|
|
|
|
|
|
|
|
def busy(self, code: str, side: str) -> bool:
|
|
|
|
|
|
"""判断证券是否存在仍在处理中的同方向委托。"""
|
2026-08-30 00:34:27 +08:00
|
|
|
|
with self.mutex:
|
2026-09-05 11:32:10 +08:00
|
|
|
|
key = self._busy_key(side, code)
|
|
|
|
|
|
return key in self.busy_keys or self.busy_cache.has(key)
|
2026-09-05 00:23:55 +08:00
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
|
def _busy_key(side: str, code: str) -> str:
|
|
|
|
|
|
return f"{side}-{code}"
|
2026-08-28 18:52:27 +08:00
|
|
|
|
|
2026-09-03 11:33:43 +08:00
|
|
|
|
def refresh(self, client: Client, orders: list[OrderItem]) -> None:
|
|
|
|
|
|
"""用账户快照刷新委托,并撤销超时的活动委托。"""
|
2026-08-30 14:46:34 +08:00
|
|
|
|
current = datetime.now()
|
|
|
|
|
|
data: list[OrderItem] = []
|
2026-09-05 00:23:55 +08:00
|
|
|
|
busy_keys: set[str] = set()
|
2026-09-01 14:28:49 +08:00
|
|
|
|
canceled = 0
|
2026-08-30 14:46:34 +08:00
|
|
|
|
|
|
|
|
|
|
for item in orders:
|
|
|
|
|
|
# 不处理状态不对的
|
|
|
|
|
|
if item.status not in TRACKED_STATUSES:
|
|
|
|
|
|
continue
|
2026-09-05 11:32:10 +08:00
|
|
|
|
if item.status in BUSY_STATUSES:
|
|
|
|
|
|
busy_keys.add(self._busy_key(item.side, item.code))
|
2026-08-30 14:46:34 +08:00
|
|
|
|
# 清理过期的
|
|
|
|
|
|
if (
|
|
|
|
|
|
item.created_at is not None
|
|
|
|
|
|
and item.status in CANCELABLE_STATUSES
|
|
|
|
|
|
and current - item.created_at > self.cancel_timeout_sec
|
|
|
|
|
|
):
|
|
|
|
|
|
client.cancel_by_id(item.id)
|
2026-09-01 14:28:49 +08:00
|
|
|
|
canceled += 1
|
2026-09-01 15:49:09 +08:00
|
|
|
|
log.info("[Order] 超时撤单,代码=%s,方向=%s,柜台订单=%s", item.code, item.side, item.id)
|
2026-08-30 14:46:34 +08:00
|
|
|
|
continue
|
|
|
|
|
|
|
|
|
|
|
|
# 缓存本次有效订单
|
|
|
|
|
|
data.append(item)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
with self.mutex:
|
|
|
|
|
|
self.data = data
|
2026-09-05 11:32:10 +08:00
|
|
|
|
self.busy_keys = busy_keys
|
2026-09-05 00:23:55 +08:00
|
|
|
|
log.info("[Order] 刷新完成,跟踪=%d,处理中=%d,撤销=%d", len(data), len(busy_keys), canceled)
|
2026-08-28 18:52:27 +08:00
|
|
|
|
|
|
|
|
|
|
def place(self, request: PlaceOrderRequest) -> bool:
|
|
|
|
|
|
"""按最新价提交委托,并立即写入本地方向锁。"""
|
2026-09-05 00:23:55 +08:00
|
|
|
|
side = ORDER_SIDE_BY_OFFSET.get(str(request.op), "")
|
|
|
|
|
|
if not side:
|
|
|
|
|
|
log.warning("[Order] 下单失败,代码=%s,原因=未知买卖方向(%s)", request.code, request.op)
|
|
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
|
|
key = self._busy_key(side, request.code)
|
|
|
|
|
|
with self.mutex:
|
2026-09-05 11:32:10 +08:00
|
|
|
|
if key in self.busy_keys or self.busy_cache.has(key):
|
2026-09-05 00:23:55 +08:00
|
|
|
|
log.info("[Order] 跳过重复下单,代码=%s,方向=%s", request.code, side)
|
|
|
|
|
|
return False
|
|
|
|
|
|
self.busy_cache.set(key, True, timeout=self.lock_timeout_sec)
|
|
|
|
|
|
|
2026-09-01 14:28:49 +08:00
|
|
|
|
try:
|
2026-09-05 11:32:10 +08:00
|
|
|
|
result = request.client.passorder(
|
|
|
|
|
|
op_type=request.op,
|
|
|
|
|
|
stock_code=request.code,
|
|
|
|
|
|
volume=request.volume,
|
|
|
|
|
|
strategy_name=request.strategy_name,
|
|
|
|
|
|
order_id=request.order_id,
|
2026-09-01 14:28:49 +08:00
|
|
|
|
)
|
|
|
|
|
|
except APIError as exc:
|
2026-09-01 15:49:09 +08:00
|
|
|
|
log.exception("[Order] 下单失败,代码=%s,本地订单=%s,HTTP状态=%d,错误=%s", request.code, request.order_id, exc.status_code, exc.message or str(exc))
|
2026-09-01 14:28:49 +08:00
|
|
|
|
return False
|
2026-08-28 22:46:04 +08:00
|
|
|
|
if not isinstance(result, dict):
|
2026-09-01 15:49:09 +08:00
|
|
|
|
log.warning("[Order] 下单失败,代码=%s,本地订单=%s,原因=响应格式无效", request.code, request.order_id)
|
2026-08-28 22:46:04 +08:00
|
|
|
|
return False
|
|
|
|
|
|
order_ref = str(result.get("order_ref") or "").strip().lower()
|
|
|
|
|
|
if result.get("status") != "success" or order_ref in {"", "unknown", "none"}:
|
2026-09-01 15:49:09 +08:00
|
|
|
|
log.warning("[Order] 下单被拒绝,代码=%s,本地订单=%s,状态=%s,柜台订单=%s", request.code, request.order_id, result.get("status"), order_ref)
|
2026-08-28 22:46:04 +08:00
|
|
|
|
return False
|
2026-08-28 18:52:27 +08:00
|
|
|
|
|
2026-08-28 22:46:04 +08:00
|
|
|
|
pending = OrderItem(
|
|
|
|
|
|
id=order_ref,
|
|
|
|
|
|
code=request.code,
|
|
|
|
|
|
side=side,
|
|
|
|
|
|
remark=request.order_id,
|
|
|
|
|
|
status="48",
|
|
|
|
|
|
created_at=datetime.now(),
|
|
|
|
|
|
volume=request.volume,
|
|
|
|
|
|
local_order_id=request.order_id,
|
|
|
|
|
|
)
|
2026-08-30 00:34:27 +08:00
|
|
|
|
with self.mutex:
|
2026-08-30 15:29:21 +08:00
|
|
|
|
self.data.append(pending)
|
2026-09-01 15:49:09 +08:00
|
|
|
|
log.info("[Order] 下单已受理,代码=%s,方向=%s,数量=%d,本地订单=%s,柜台订单=%s", request.code, side, request.volume, request.order_id, order_ref)
|
2026-08-28 18:52:27 +08:00
|
|
|
|
return True
|