ys_trade_sdk 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,24 @@
1
+ __pycache__/
2
+ *.pyc
3
+ .venv/
4
+ venv/
5
+ dist/
6
+ build/
7
+ *.egg-info/
8
+ .pytest_cache/
9
+ .mypy_cache/
10
+ .ruff_cache/
11
+ node_modules/
12
+ .DS_Store
13
+ *.log
14
+ /logs/
15
+ app/logs/*
16
+ !app/logs/.gitkeep
17
+ !templates/**/config.yaml
18
+ .env
19
+ ys_base/.pypi_token
20
+
21
+ # 前端锁文件保留,产物与依赖忽略
22
+ ys_web/**/dist/
23
+ smoke_app.log
24
+ /data/
@@ -0,0 +1,76 @@
1
+ Metadata-Version: 2.5
2
+ Name: ys_trade_sdk
3
+ Version: 0.1.0
4
+ Summary: YS 交易网关 SDK:账号线程、行情快照、盈亏与对账
5
+ Author-email: ys <popsars@gmail.com>
6
+ License: MIT
7
+ Requires-Python: >=3.13
8
+ Requires-Dist: aiohttp<4,>=3.10
9
+ Requires-Dist: certifi
10
+ Requires-Dist: exchange-calendars>=4.5
11
+ Requires-Dist: pandas>=2.2
12
+ Requires-Dist: ys-base>=0.1.59
13
+ Description-Content-Type: text/markdown
14
+
15
+ # ys_trade_sdk
16
+
17
+ YS 交易网关 SDK。账号线程、迅投/聚源客户端、行情与静态信息、盈亏缓存、Auth 账号对账都在这个包里。
18
+ 契约、Auth 客户端和服务骨架仍在 `ys_base`。网关改动只升本包,不带动 Auth、MS、模板。
19
+
20
+ ```bash
21
+ uv add ys_trade_sdk
22
+ ```
23
+
24
+ 需要服务骨架的交易系统同时安装底座:
25
+
26
+ ```bash
27
+ uv add "ys_base[server]"
28
+ uv add ys_trade_sdk
29
+ ```
30
+
31
+ 本目录开发:
32
+
33
+ ```bash
34
+ uv python install 3.13
35
+ uv sync --frozen
36
+ uv run pytest
37
+ ```
38
+
39
+ ## 发布到 PyPI
40
+
41
+ 先改 `ys_trade_sdk/__init__.py` 的 `__version__`。PyPI 不允许覆盖同版本。Token 用钥匙串项目 `pypi:__token__`,不要把明文放进仓库。
42
+
43
+ ```bash
44
+ cd ys_trade_sdk
45
+ ./publish-pypi.sh
46
+ ```
47
+
48
+ 清华镜像能看到该版本后再给消费仓升锁。生产锁文件走清华镜像,禁止 `--default-index https://pypi.org/simple`。
49
+
50
+ ```python
51
+ from ys_trade_sdk import Account, TradeManager, TradeRuntimeConfig
52
+
53
+ manager = TradeManager(
54
+ accounts=[
55
+ Account(
56
+ account="A001",
57
+ password="...",
58
+ trade_source="xt",
59
+ trade_uri="ws://trade.example.com",
60
+ profit_enabled=True,
61
+ )
62
+ ],
63
+ runtime_config=TradeRuntimeConfig(
64
+ quote_data_base_url="http://quote.example.com",
65
+ symbol_data_base_url="http://symbol.example.com",
66
+ symbol_data_username="symbol-user",
67
+ symbol_data_password="symbol-password",
68
+ trade_data_base_url="http://trade-data.example.com",
69
+ trade_data_username="trade-user",
70
+ trade_data_password="trade-password",
71
+ ),
72
+ )
73
+ ```
74
+
75
+ 证券连接只认账户快照 `stock_td_server`。有地址和端口时交易源为迅投,地址为 `ws://地址:端口`。
76
+ `profit_enabled=True` 时才要求行情、静态信息和交易数据三类地址齐全。
@@ -0,0 +1,62 @@
1
+ # ys_trade_sdk
2
+
3
+ YS 交易网关 SDK。账号线程、迅投/聚源客户端、行情与静态信息、盈亏缓存、Auth 账号对账都在这个包里。
4
+ 契约、Auth 客户端和服务骨架仍在 `ys_base`。网关改动只升本包,不带动 Auth、MS、模板。
5
+
6
+ ```bash
7
+ uv add ys_trade_sdk
8
+ ```
9
+
10
+ 需要服务骨架的交易系统同时安装底座:
11
+
12
+ ```bash
13
+ uv add "ys_base[server]"
14
+ uv add ys_trade_sdk
15
+ ```
16
+
17
+ 本目录开发:
18
+
19
+ ```bash
20
+ uv python install 3.13
21
+ uv sync --frozen
22
+ uv run pytest
23
+ ```
24
+
25
+ ## 发布到 PyPI
26
+
27
+ 先改 `ys_trade_sdk/__init__.py` 的 `__version__`。PyPI 不允许覆盖同版本。Token 用钥匙串项目 `pypi:__token__`,不要把明文放进仓库。
28
+
29
+ ```bash
30
+ cd ys_trade_sdk
31
+ ./publish-pypi.sh
32
+ ```
33
+
34
+ 清华镜像能看到该版本后再给消费仓升锁。生产锁文件走清华镜像,禁止 `--default-index https://pypi.org/simple`。
35
+
36
+ ```python
37
+ from ys_trade_sdk import Account, TradeManager, TradeRuntimeConfig
38
+
39
+ manager = TradeManager(
40
+ accounts=[
41
+ Account(
42
+ account="A001",
43
+ password="...",
44
+ trade_source="xt",
45
+ trade_uri="ws://trade.example.com",
46
+ profit_enabled=True,
47
+ )
48
+ ],
49
+ runtime_config=TradeRuntimeConfig(
50
+ quote_data_base_url="http://quote.example.com",
51
+ symbol_data_base_url="http://symbol.example.com",
52
+ symbol_data_username="symbol-user",
53
+ symbol_data_password="symbol-password",
54
+ trade_data_base_url="http://trade-data.example.com",
55
+ trade_data_username="trade-user",
56
+ trade_data_password="trade-password",
57
+ ),
58
+ )
59
+ ```
60
+
61
+ 证券连接只认账户快照 `stock_td_server`。有地址和端口时交易源为迅投,地址为 `ws://地址:端口`。
62
+ `profit_enabled=True` 时才要求行情、静态信息和交易数据三类地址齐全。
@@ -0,0 +1,144 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ umask 077
5
+ ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
6
+ PYTHON="$ROOT/.venv/bin/python"
7
+ KEYCHAIN_SERVICE="pypi:__token__"
8
+ PACKAGE="ys_trade_sdk"
9
+ PROJECT="ys-trade-sdk"
10
+
11
+ cd "$ROOT"
12
+
13
+ if [[ ! -x "$PYTHON" ]]; then
14
+ echo "错误:请先执行 uv sync 创建 ${PACKAGE}/.venv" >&2
15
+ exit 1
16
+ fi
17
+ if ! command -v security >/dev/null 2>&1; then
18
+ echo "错误:当前系统不支持 macOS security 钥匙串命令" >&2
19
+ exit 1
20
+ fi
21
+ if ! security find-generic-password -a "$USER" -s "$KEYCHAIN_SERVICE" >/dev/null 2>&1; then
22
+ echo "错误:钥匙串中缺少 $KEYCHAIN_SERVICE 发布凭据" >&2
23
+ exit 1
24
+ fi
25
+
26
+ token="$(security find-generic-password -a "$USER" -s "$KEYCHAIN_SERVICE" -w)"
27
+ if [[ "$token" != pypi-* || "$token" == *[[:space:]]* ]]; then
28
+ unset token
29
+ echo "错误:钥匙串中的 PyPI token 格式无效或包含空白字符" >&2
30
+ exit 1
31
+ fi
32
+ trap 'unset token UV_PUBLISH_TOKEN' EXIT
33
+
34
+ version="$($PYTHON - <<PY
35
+ import re
36
+ from pathlib import Path
37
+
38
+ source = Path("${PACKAGE}/__init__.py").read_text(encoding="utf-8")
39
+ match = re.search(r'__version__\\s*=\\s*["\\u0027]([^"\\u0027]+)', source)
40
+ if match is None:
41
+ raise SystemExit("无法读取 ${PACKAGE} 版本")
42
+ print(match.group(1))
43
+ PY
44
+ )"
45
+
46
+ if curl -fsS "https://pypi.org/pypi/${PROJECT}/$version/json" >/dev/null 2>&1; then
47
+ echo "错误:${PACKAGE} $version 已存在于 PyPI,请先提升版本号" >&2
48
+ exit 1
49
+ fi
50
+
51
+ echo "[1/5] 同步依赖并运行测试"
52
+ uv sync --frozen
53
+ "$PYTHON" -m pytest -q
54
+
55
+ echo "[2/5] 构建 ${PACKAGE} $version"
56
+ rm -rf dist
57
+ uv build
58
+
59
+ echo "[3/5] 审计构建产物"
60
+ VERSION="$version" "$PYTHON" - <<PY
61
+ import os
62
+ import tarfile
63
+ import zipfile
64
+ from pathlib import Path
65
+
66
+ version = os.environ["VERSION"]
67
+ wheel = Path(f"dist/${PACKAGE}-{version}-py3-none-any.whl")
68
+ sdist = Path(f"dist/${PACKAGE}-{version}.tar.gz")
69
+ if not wheel.is_file() or not sdist.is_file():
70
+ raise SystemExit("构建产物不完整")
71
+
72
+ with zipfile.ZipFile(wheel) as archive:
73
+ names = archive.namelist()
74
+ metadata_name = next(name for name in names if name.endswith(".dist-info/METADATA"))
75
+ metadata = archive.read(metadata_name).decode("utf-8")
76
+ if f"Version: {version}" not in metadata:
77
+ raise SystemExit("wheel 元数据版本不匹配")
78
+ if not any(name.startswith("${PACKAGE}/") for name in names):
79
+ raise SystemExit("wheel 中缺少 ${PACKAGE}")
80
+
81
+ with tarfile.open(sdist, "r:gz") as archive:
82
+ if not any("/${PACKAGE}/" in name for name in archive.getnames()):
83
+ raise SystemExit("sdist 中缺少 ${PACKAGE}")
84
+ PY
85
+
86
+ echo "[4/5] 上传到 PyPI"
87
+ UV_PUBLISH_TOKEN="$token" uv publish "dist/${PACKAGE}-$version-py3-none-any.whl" "dist/${PACKAGE}-$version.tar.gz"
88
+ unset token UV_PUBLISH_TOKEN
89
+
90
+ echo "[5/5] 校验 PyPI 文件与哈希"
91
+ VERSION="$version" "$PYTHON" - <<PY
92
+ import hashlib
93
+ import json
94
+ import os
95
+ import time
96
+ import urllib.error
97
+ import urllib.request
98
+ from pathlib import Path
99
+
100
+ version = os.environ["VERSION"]
101
+ url = f"https://pypi.org/pypi/${PROJECT}/{version}/json"
102
+ delays = (2, 3, 5, 8, 13, 21, 34)
103
+ for attempt in range(len(delays) + 1):
104
+ try:
105
+ with urllib.request.urlopen(url, timeout=15) as response:
106
+ payload = json.load(response)
107
+ break
108
+ except (urllib.error.HTTPError, urllib.error.URLError, TimeoutError) as exc:
109
+ retryable = not isinstance(exc, urllib.error.HTTPError) or exc.code == 404
110
+ if not retryable or attempt == len(delays):
111
+ raise
112
+ time.sleep(delays[attempt])
113
+ else:
114
+ raise SystemExit("PyPI 发布结果不可见")
115
+
116
+ remote = {item["filename"]: item["digests"]["sha256"] for item in payload["urls"]}
117
+ for path in sorted(Path("dist").glob(f"${PACKAGE}-{version}*")):
118
+ digest = hashlib.sha256(path.read_bytes()).hexdigest()
119
+ if remote.get(path.name) != digest:
120
+ raise SystemExit(f"PyPI 文件哈希不匹配: {path.name}")
121
+
122
+ simple_url = "https://pypi.org/simple/${PROJECT}/"
123
+ simple_ok = False
124
+ for attempt in range(len(delays) + 1):
125
+ req = urllib.request.Request(simple_url, headers={"User-Agent": "${PROJECT}-publish/1.0"})
126
+ try:
127
+ with urllib.request.urlopen(req, timeout=20) as response:
128
+ simple_body = response.read().decode("utf-8", errors="replace")
129
+ except (urllib.error.HTTPError, urllib.error.URLError, TimeoutError):
130
+ if attempt == len(delays):
131
+ raise
132
+ time.sleep(delays[attempt])
133
+ continue
134
+ if f"${PACKAGE}-{version}" in simple_body:
135
+ simple_ok = True
136
+ break
137
+ if attempt == len(delays):
138
+ break
139
+ time.sleep(delays[attempt])
140
+ if not simple_ok:
141
+ raise SystemExit(f"PyPI simple 索引仍看不到 ${PACKAGE}-{version},JSON 可见不能当作发布成功")
142
+
143
+ print(f"发布完成:https://pypi.org/project/${PROJECT}/{version}/")
144
+ PY
@@ -0,0 +1,51 @@
1
+ [project]
2
+ name = "ys_trade_sdk"
3
+ description = "YS 交易网关 SDK:账号线程、行情快照、盈亏与对账"
4
+ readme = "README.md"
5
+ requires-python = ">=3.13"
6
+ license = { text = "MIT" }
7
+ authors = [{ name = "ys", email = "popsars@gmail.com" }]
8
+ dynamic = ["version"]
9
+ dependencies = [
10
+ "ys-base>=0.1.59",
11
+ "aiohttp>=3.10,<4",
12
+ "certifi",
13
+ "exchange-calendars>=4.5",
14
+ "pandas>=2.2",
15
+ ]
16
+
17
+ [dependency-groups]
18
+ dev = ["pytest>=8", "pytest-asyncio>=0.24", "mypy>=1.11", "ruff>=0.9,<1"]
19
+
20
+ [build-system]
21
+ requires = ["hatchling"]
22
+ build-backend = "hatchling.build"
23
+
24
+ [tool.hatch.version]
25
+ path = "ys_trade_sdk/__init__.py"
26
+
27
+ [tool.hatch.build.targets.wheel]
28
+ packages = ["ys_trade_sdk"]
29
+
30
+ [tool.pytest.ini_options]
31
+ asyncio_mode = "auto"
32
+ testpaths = ["tests"]
33
+
34
+ [tool.ruff]
35
+ target-version = "py313"
36
+ line-length = 120
37
+ extend-exclude = [".venv", ".pytest_cache", ".ruff_cache", "dist", "node_modules"]
38
+
39
+ [tool.ruff.lint]
40
+ select = ["E4", "E7", "E9", "F", "I"]
41
+
42
+ [tool.ruff.format]
43
+ quote-style = "double"
44
+ line-ending = "lf"
45
+
46
+ [tool.uv]
47
+ package = true
48
+
49
+ [[tool.uv.index]]
50
+ url = "https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple"
51
+ default = true
@@ -0,0 +1,141 @@
1
+ from copy import deepcopy
2
+ from typing import Any
3
+
4
+ from ys_base.store.base import LocalStore
5
+
6
+
7
+ class MemoryStore(LocalStore):
8
+ def __init__(self) -> None:
9
+ self.tables: dict[str, dict[str, dict[str, Any]]] = {}
10
+ self.cursors: dict[str, int] = {}
11
+ self.generations: dict[str, str] = {}
12
+ self.authorization_version = 0
13
+
14
+ async def open(self) -> None:
15
+ return None
16
+
17
+ async def close(self) -> None:
18
+ return None
19
+
20
+ async def ping(self) -> None:
21
+ return None
22
+
23
+ async def create_index(
24
+ self,
25
+ table: str,
26
+ keys: str | list[tuple[str, int]],
27
+ *,
28
+ unique: bool = False,
29
+ ) -> None:
30
+ return None
31
+
32
+ async def get_cursor(self, table: str) -> int:
33
+ return self.cursors.get(table, 0)
34
+
35
+ async def get_source_generation(self, table: str) -> str:
36
+ return self.generations.get(table, "")
37
+
38
+ async def list_mirror_tables(self) -> list[str]:
39
+ return [table for table in self.cursors if table.startswith("_auth_")]
40
+
41
+ async def get_authorization_version(self) -> int:
42
+ return self.authorization_version
43
+
44
+ async def set_authorization_version(self, version: int) -> None:
45
+ self.authorization_version = int(version)
46
+
47
+ async def apply_changes(
48
+ self,
49
+ table: str,
50
+ changes: list[dict[str, Any]],
51
+ last_seq: int,
52
+ source_generation: str = "",
53
+ ) -> None:
54
+ docs = deepcopy(self.tables.get(table, {}))
55
+ for change in changes:
56
+ doc = change.get("doc") or {}
57
+ doc_id = str(doc.get("_id", ""))
58
+ if not doc_id:
59
+ continue
60
+ if change.get("op") == "delete":
61
+ docs.pop(doc_id, None)
62
+ else:
63
+ docs[doc_id] = deepcopy(doc)
64
+ self.tables[table] = docs
65
+ self.cursors[table] = int(last_seq)
66
+ self.generations[table] = source_generation
67
+
68
+ async def replace_table(
69
+ self,
70
+ table: str,
71
+ docs: list[dict[str, Any]],
72
+ last_seq: int,
73
+ source_generation: str = "",
74
+ ) -> None:
75
+ self.tables[table] = {str(doc["_id"]): deepcopy(doc) for doc in docs if str(doc.get("_id", ""))}
76
+ self.cursors[table] = int(last_seq)
77
+ self.generations[table] = source_generation
78
+
79
+ async def get(self, table: str, doc_id: str) -> dict[str, Any] | None:
80
+ doc = self.tables.get(table, {}).get(doc_id)
81
+ return deepcopy(doc) if doc is not None else None
82
+
83
+ async def query_all(self, table: str) -> list[dict[str, Any]]:
84
+ return [deepcopy(doc) for doc in self.tables.get(table, {}).values()]
85
+
86
+ async def drop_mirror(self, table: str) -> None:
87
+ self.tables.pop(table, None)
88
+ self.cursors.pop(table, None)
89
+ self.generations.pop(table, None)
90
+
91
+ async def upsert_local(self, table: str, doc: dict[str, Any]) -> None:
92
+ doc_id = str(doc.get("_id", ""))
93
+ if not doc_id:
94
+ raise ValueError("本地业务文档必须包含 _id")
95
+ self.tables.setdefault(table, {})[doc_id] = deepcopy(doc)
96
+
97
+ async def delete_local(self, table: str, doc_id: str) -> None:
98
+ self.tables.setdefault(table, {}).pop(doc_id, None)
99
+
100
+ async def replace_local_table(self, table: str, docs: list[dict[str, Any]]) -> None:
101
+ self.tables[table] = {str(doc["_id"]): deepcopy(doc) for doc in docs if str(doc.get("_id", ""))}
102
+
103
+ async def update_local_if(
104
+ self,
105
+ table: str,
106
+ query: dict[str, Any],
107
+ *,
108
+ increments: dict[str, int] | None = None,
109
+ values: dict[str, Any] | None = None,
110
+ ) -> dict[str, Any] | None:
111
+ for doc_id, stored in self.tables.get(table, {}).items():
112
+ if not _matches_query(stored, query):
113
+ continue
114
+ updated = deepcopy(stored)
115
+ for key, value in (increments or {}).items():
116
+ updated[key] = int(updated.get(key, 0)) + value
117
+ updated.update(values or {})
118
+ self.tables[table][doc_id] = updated
119
+ return deepcopy(updated)
120
+ return None
121
+
122
+
123
+ def _matches_query(doc: dict[str, Any], query: dict[str, Any]) -> bool:
124
+ for key, expected in query.items():
125
+ if key == "$or":
126
+ if not any(_matches_query(doc, branch) for branch in expected):
127
+ return False
128
+ continue
129
+ actual = doc.get(key)
130
+ if isinstance(expected, dict):
131
+ if "$gt" in expected and not (actual is not None and actual > expected["$gt"]):
132
+ return False
133
+ if "$exists" in expected and ((key in doc) is not expected["$exists"]):
134
+ return False
135
+ continue
136
+ if isinstance(actual, list):
137
+ if expected not in actual:
138
+ return False
139
+ elif actual != expected:
140
+ return False
141
+ return True
@@ -0,0 +1,160 @@
1
+ # -*- coding: utf-8 -*-
2
+ """TradeAccountReconciler:账号线程与 auth 下发全同步。"""
3
+
4
+ import pytest
5
+ from ys_base.auth.delta import DeltaSync
6
+
7
+ from tests.memory_store import MemoryStore
8
+ from ys_trade_sdk import TradeAccountReconciler, tradeable_selector
9
+
10
+
11
+ class FakeTradeManager:
12
+ def __init__(self):
13
+ self.events: list[tuple[str, str]] = []
14
+ self.running: set[str] = set()
15
+
16
+ async def start_account(self, doc):
17
+ self.running.add(doc["_id"])
18
+ self.events.append(("start", doc["_id"]))
19
+
20
+ async def stop_account(self, account_id):
21
+ self.running.discard(account_id)
22
+ self.events.append(("stop", account_id))
23
+
24
+
25
+ @pytest.fixture
26
+ async def env():
27
+ store = MemoryStore()
28
+ await store.open()
29
+ delta = DeltaSync(store, tables=["accounts"])
30
+ manager = FakeTradeManager()
31
+ reconciler = TradeAccountReconciler(store, delta, start=manager.start_account, stop=manager.stop_account)
32
+ yield store, delta, manager, reconciler
33
+ await store.close()
34
+
35
+
36
+ def acc(aid: str, enabled: bool = True, **extra) -> dict:
37
+ return {"_id": aid, "cname": f"账户{aid}", "enabled": enabled, **extra}
38
+
39
+
40
+ async def test_snapshot_starts_enabled_accounts(env):
41
+ _, delta, manager, reconciler = env
42
+ await delta.handle_snapshot(
43
+ {"table": "accounts", "batch": 1, "total": 1, "docs": [acc("a1"), acc("a2", enabled=False)], "last_seq": 10}
44
+ )
45
+ assert manager.running == {"a1"} # 未启用账号不拉起
46
+
47
+
48
+ async def test_revoked_distribution_stops_thread(env):
49
+ """auth 取消下发(合成 delete)→ 账号线程及时关闭。"""
50
+ _, delta, manager, _ = env
51
+ await delta.handle_snapshot(
52
+ {"table": "accounts", "batch": 1, "total": 1, "docs": [acc("a1"), acc("a2")], "last_seq": 10}
53
+ )
54
+ assert manager.running == {"a1", "a2"}
55
+ await delta.handle_delta(
56
+ {
57
+ "table": "accounts",
58
+ "changes": [
59
+ {"seq": 11, "op": "delete", "doc": {"_id": "a2"}},
60
+ ],
61
+ "last_seq": 11,
62
+ }
63
+ )
64
+ assert manager.running == {"a1"}
65
+ assert ("stop", "a2") in manager.events
66
+
67
+
68
+ async def test_account_change_restarts_thread(env):
69
+ _, delta, manager, _ = env
70
+ await delta.handle_snapshot(
71
+ {"table": "accounts", "batch": 1, "total": 1, "docs": [acc("a1", login_password="p1")], "last_seq": 5}
72
+ )
73
+ await delta.handle_delta(
74
+ {
75
+ "table": "accounts",
76
+ "changes": [
77
+ {"seq": 6, "op": "upsert", "doc": acc("a1", login_password="p2")},
78
+ ],
79
+ "last_seq": 6,
80
+ }
81
+ )
82
+ assert manager.events == [("start", "a1"), ("stop", "a1"), ("start", "a1")]
83
+
84
+
85
+ async def test_disable_stops_thread(env):
86
+ _, delta, manager, _ = env
87
+ await delta.handle_snapshot({"table": "accounts", "batch": 1, "total": 1, "docs": [acc("a1")], "last_seq": 5})
88
+ await delta.handle_delta(
89
+ {
90
+ "table": "accounts",
91
+ "changes": [
92
+ {"seq": 6, "op": "upsert", "doc": acc("a1", enabled=False)},
93
+ ],
94
+ "last_seq": 6,
95
+ }
96
+ )
97
+ assert manager.running == set()
98
+
99
+
100
+ async def test_bootstrap_from_local_cache_and_shutdown(env):
101
+ """auth 不可用时按本地缓存拉起;退出时全停。"""
102
+ store, _, manager, reconciler = env
103
+ await store.replace_table("_auth_accounts", [acc("a1"), acc("a2")], 20)
104
+ await reconciler.bootstrap()
105
+ assert manager.running == {"a1", "a2"}
106
+ await reconciler.shutdown()
107
+ assert manager.running == set()
108
+ assert reconciler.running_ids == set()
109
+
110
+
111
+ async def test_missing_stock_td_server_stops_existing_thread():
112
+ store = MemoryStore()
113
+ await store.open()
114
+ manager = FakeTradeManager()
115
+ reconciler = TradeAccountReconciler(
116
+ store,
117
+ None,
118
+ start=manager.start_account,
119
+ stop=manager.stop_account,
120
+ selector=tradeable_selector,
121
+ )
122
+ valid = acc(
123
+ "a1",
124
+ login_password="secret",
125
+ stock_td_server={"name": "本地迅投", "host": "127.0.0.1", "port": 9009},
126
+ )
127
+ await store.replace_table("_auth_accounts", [valid], 1)
128
+ await reconciler.bootstrap()
129
+ assert manager.running == {"a1"}
130
+
131
+ await store.replace_table("_auth_accounts", [{**valid, "stock_td_server": None}], 2)
132
+ await reconciler.reconcile()
133
+
134
+ assert manager.running == set()
135
+ assert manager.events == [("start", "a1"), ("stop", "a1")]
136
+ await store.close()
137
+
138
+
139
+ async def test_stop_failure_propagates_and_keeps_running_state():
140
+ store = MemoryStore()
141
+ await store.open()
142
+ manager = FakeTradeManager()
143
+
144
+ async def fail_stop(_account_id: str) -> None:
145
+ raise RuntimeError("gateway did not stop")
146
+
147
+ reconciler = TradeAccountReconciler(
148
+ store,
149
+ None,
150
+ start=manager.start_account,
151
+ stop=fail_stop,
152
+ )
153
+ await store.replace_table("_auth_accounts", [acc("a1")], 1)
154
+ await reconciler.bootstrap()
155
+ await store.replace_table("_auth_accounts", [], 2)
156
+
157
+ with pytest.raises(RuntimeError, match="账号线程停止失败"):
158
+ await reconciler.reconcile()
159
+ assert reconciler.running_ids == {"a1"}
160
+ await store.close()