Files
big-qmt/py-client/strategy/trend/state.py

215 lines
7.3 KiB
Python
Raw Normal View History

2026-08-28 18:52:27 +08:00
"""趋势策略持仓状态的内存管理与 JSON 持久化。"""
from __future__ import annotations
import json
2026-09-01 14:28:49 +08:00
import logging as log
2026-08-28 18:52:27 +08:00
from dataclasses import asdict, dataclass
from pathlib import Path
from threading import Lock
from typing import Iterable
2026-08-30 00:34:27 +08:00
from sdk import OrderItem, PositionItem
2026-09-05 00:23:55 +08:00
from .order import BUSY_STATUSES, COMPLETED_STATUSES
2026-08-28 18:52:27 +08:00
# 委托状态:无操作、处理中、已完成。
STATUS_NONE = ""
STATUS_ING = "ING"
STATUS_OK = "OK"
@dataclass(slots=True)
class StateItem:
"""单只证券的底仓和补仓状态。"""
# 证券代码。
code: str
# 底仓订单、数量、成本和处理状态。
base_order_id: str = ""
base_qty: int = 0
base_cost: float = 0.0
base_status: str = STATUS_NONE
# 补仓订单、补仓次数、数量、成本和处理状态。
added_order_id: str = ""
added_num: int = 0
added_qty: int = 0
added_cost: float = 0.0
added_status: str = STATUS_NONE
class State:
"""线程安全的策略状态存储。
状态以内存字典提供快速访问并通过临时文件替换的方式写入 JSON
防止程序在写入过程中退出而破坏原状态文件
"""
def __init__(self, path: str | Path) -> None:
self.path = Path(path)
self.lock = Lock()
self.items = self._load()
@classmethod
def for_strategy(
cls,
data_dir: str | Path,
strategy: str,
account_id: str,
) -> "State":
"""根据数据目录、策略名称和账户生成独立状态文件。"""
state_path = Path(data_dir) / f"{strategy}_{account_id}_state.json"
return cls(state_path)
@property
def codes(self) -> list[str]:
"""返回当前已经接管的全部证券代码快照。"""
with self.lock:
return list(self.items)
def get(self, code: str) -> StateItem:
"""获取指定证券的状态;不存在时抛出 KeyError。"""
with self.lock:
return self.items[code]
def set(self, item: StateItem) -> None:
"""新增或覆盖一只证券的状态。"""
with self.lock:
self.items[item.code] = item
2026-08-30 00:34:27 +08:00
def delete(self, code: str) -> bool:
"""删除已终结的证券状态,并返回是否实际删除。"""
with self.lock:
return self.items.pop(code, None) is not None
2026-08-28 18:52:27 +08:00
2026-08-30 00:34:27 +08:00
def sync_positions(self, positions: Iterable[PositionItem]) -> None:
2026-08-28 18:52:27 +08:00
"""把尚未接管的真实持仓初始化为已完成底仓。
无证券代码无持仓数量或成本无效的记录会被忽略同步结束后
立即保存确保首次接管的持仓在程序重启后仍可恢复
"""
known_codes = set(self.codes)
2026-09-01 14:28:49 +08:00
imported = 0
2026-08-28 18:52:27 +08:00
for position in positions:
if (
not position.stock_code
or position.volume <= 0
or position.open_price <= 0
or position.stock_code in known_codes
):
continue
self.set(
StateItem(
2026-09-05 00:23:55 +08:00
base_order_id=position.trade_id,
2026-08-28 18:52:27 +08:00
code=position.stock_code,
base_qty=position.volume,
2026-09-03 15:27:11 +08:00
base_cost=round(position.open_price, 2),
2026-08-28 18:52:27 +08:00
base_status=STATUS_OK,
)
)
known_codes.add(position.stock_code)
2026-09-01 14:28:49 +08:00
imported += 1
2026-08-28 18:52:27 +08:00
self.save()
2026-09-01 14:28:49 +08:00
if imported:
log.info("[状态] 导入持仓=%d,状态总数=%d", imported, len(known_codes))
2026-08-28 18:52:27 +08:00
2026-08-28 22:46:04 +08:00
def reconcile(
self,
2026-08-30 00:34:27 +08:00
positions: Iterable[PositionItem],
orders: list[OrderItem],
2026-08-28 22:46:04 +08:00
) -> None:
2026-08-30 15:29:21 +08:00
"""用真实持仓和委托恢复本地状态;拆分订单全部完成才算完成。"""
2026-08-28 22:46:04 +08:00
position_list = list(positions)
self.sync_positions(position_list)
2026-08-30 00:34:27 +08:00
position_codes = {
2026-08-28 22:46:04 +08:00
item.stock_code for item in position_list if item.volume > 0
}
2026-08-30 15:29:21 +08:00
orders_by_local_id: dict[str, list[OrderItem]] = {}
for order in orders:
if order.local_order_id:
orders_by_local_id.setdefault(order.local_order_id, []).append(order)
2026-08-28 22:46:04 +08:00
for code in list(self.codes):
item = self.get(code)
2026-08-30 15:29:21 +08:00
for order_id_attr, status_attr in (
("base_order_id", "base_status"),
("added_order_id", "added_status"),
):
local_order_id = getattr(item, order_id_attr)
current_status = getattr(item, status_attr)
2026-09-05 00:23:55 +08:00
if current_status != STATUS_ING or not local_order_id:
2026-08-30 15:29:21 +08:00
continue
matching_orders = orders_by_local_id.get(local_order_id)
2026-09-05 00:23:55 +08:00
status = _order_status(matching_orders)
if status != current_status:
log.info("[状态] %s 订单=%s,状态=%s->%s", code, local_order_id, current_status, status)
setattr(item, status_attr, status)
2026-08-28 22:46:04 +08:00
self.set(item)
2026-08-30 00:34:27 +08:00
# Opening orders normally have no position until their first fill. Order
# reconciliation must therefore happen before stale state is removed.
for code in list(self.codes):
if code not in position_codes:
2026-09-03 15:27:11 +08:00
item = self.get(code)
if any(
order_id and order_id in orders_by_local_id
for order_id in (item.base_order_id, item.added_order_id)
):
continue
2026-09-01 14:28:49 +08:00
if self.delete(code):
log.info("[状态] 已移除持仓状态,代码=%s", code)
2026-08-28 22:46:04 +08:00
self.save()
2026-08-28 18:52:27 +08:00
def save(self) -> None:
"""将内存状态格式化写入 JSON并原子替换正式文件。"""
with self.lock:
self.path.parent.mkdir(parents=True, exist_ok=True)
temporary_path = self.path.with_suffix(self.path.suffix + ".tmp")
payload = {
code: asdict(item)
for code, item in self.items.items()
}
temporary_path.write_text(
json.dumps(payload, ensure_ascii=False, indent=2) + "\n",
encoding="utf-8",
)
temporary_path.replace(self.path)
def _load(self) -> dict[str, StateItem]:
"""读取已有状态文件;文件不存在时从空状态开始。"""
try:
raw = json.loads(self.path.read_text(encoding="utf-8"))
except FileNotFoundError:
return {}
except (OSError, json.JSONDecodeError) as exc:
raise ValueError(f"[状态] 读取或解析失败: {exc}") from exc
if not isinstance(raw, dict):
raise ValueError("[状态] 状态文件根节点必须是 JSON 对象")
try:
return {
code: StateItem(**item)
for code, item in raw.items()
}
except (TypeError, ValueError) as exc:
raise ValueError(f"[状态] 状态字段无效: {exc}") from exc
2026-09-05 00:23:55 +08:00
def _order_status(orders: list[OrderItem] | None) -> str:
"""将柜台订单简化为无状态、处理中或已成交。"""
if not orders:
return STATUS_NONE
statuses = {order.status for order in orders}
if statuses <= COMPLETED_STATUSES:
return STATUS_OK
if statuses <= BUSY_STATUSES | COMPLETED_STATUSES:
return STATUS_ING
return STATUS_NONE