@dsh-ft/dsh-fft-paper-trading 0.6.0 → 0.6.2

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.
Files changed (110) hide show
  1. package/README.md +4 -4
  2. package/README.zh.md +4 -4
  3. package/lib/agent/format.d.ts.map +1 -1
  4. package/lib/agent/format.js +4 -0
  5. package/lib/agent/format.js.map +1 -1
  6. package/lib/agent/tools.d.ts.map +1 -1
  7. package/lib/agent/tools.js +5 -3
  8. package/lib/agent/tools.js.map +1 -1
  9. package/lib/client.js +76 -13
  10. package/lib/contract.d.ts.map +1 -1
  11. package/lib/contract.js +3 -1
  12. package/lib/contract.js.map +1 -1
  13. package/lib/core/risk.d.ts.map +1 -1
  14. package/lib/core/risk.js +10 -2
  15. package/lib/core/risk.js.map +1 -1
  16. package/lib/core/views.js +2 -2
  17. package/lib/core/views.js.map +1 -1
  18. package/lib/data/ftshare-trading-calendar.d.ts +47 -12
  19. package/lib/data/ftshare-trading-calendar.d.ts.map +1 -1
  20. package/lib/data/ftshare-trading-calendar.js +156 -44
  21. package/lib/data/ftshare-trading-calendar.js.map +1 -1
  22. package/lib/service/paper-service.d.ts +1 -1
  23. package/lib/service/paper-service.d.ts.map +1 -1
  24. package/lib/service/paper-service.js +24 -12
  25. package/lib/service/paper-service.js.map +1 -1
  26. package/lib/service/rpc.d.ts.map +1 -1
  27. package/lib/service/rpc.js +12 -1
  28. package/lib/service/rpc.js.map +1 -1
  29. package/node_modules/@ftshare-lab/dsh-kline/CHANGELOG.md +98 -0
  30. package/node_modules/@ftshare-lab/dsh-kline/README.en.md +116 -26
  31. package/node_modules/@ftshare-lab/dsh-kline/README.md +125 -25
  32. package/node_modules/@ftshare-lab/dsh-kline/chart_service.py +38 -0
  33. package/node_modules/@ftshare-lab/dsh-kline/cordis.patch.yml +3 -9
  34. package/node_modules/@ftshare-lab/dsh-kline/core/calc.py +63 -269
  35. package/node_modules/@ftshare-lab/dsh-kline/core/rows.py +15 -3
  36. package/node_modules/@ftshare-lab/dsh-kline/core/ta_engine.py +99 -0
  37. package/node_modules/@ftshare-lab/dsh-kline/lib/candle-sequence.js +15 -0
  38. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-annotations.js +33 -0
  39. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-applications.js +1 -1
  40. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-context.js +12 -3
  41. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-observation.js +91 -2
  42. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-sources.js +64 -13
  43. package/node_modules/@ftshare-lab/dsh-kline/lib/client.js +3356 -787
  44. package/node_modules/@ftshare-lab/dsh-kline/lib/drawing-feedback.js +96 -19
  45. package/node_modules/@ftshare-lab/dsh-kline/lib/fibonacci.js +18 -0
  46. package/node_modules/@ftshare-lab/dsh-kline/lib/index.js +19 -2
  47. package/node_modules/@ftshare-lab/dsh-kline/lib/labeled-polyline.js +17 -0
  48. package/node_modules/@ftshare-lab/dsh-kline/lib/price-bands.js +55 -0
  49. package/node_modules/@ftshare-lab/dsh-kline/lib/price-series.js +47 -0
  50. package/node_modules/@ftshare-lab/dsh-kline/lib/price-sticks.js +32 -0
  51. package/node_modules/@ftshare-lab/dsh-kline/lib/types/candle-sequence.d.ts +2 -0
  52. package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-annotations.d.ts +4 -0
  53. package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-context.d.ts +1 -1
  54. package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-observation.d.ts +2 -0
  55. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/BetterSidebarTab.d.ts +3 -2
  56. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/ClassicShell.d.ts +1 -1
  57. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/chart-context.d.ts +1 -0
  58. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/client-context.d.ts +14 -0
  59. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/conversation.d.ts +11 -3
  60. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/embed.d.ts +2 -2
  61. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/generated-view.d.ts +1 -1
  62. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/host-services.d.ts +0 -36
  63. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/index.d.ts +2 -1
  64. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar-contract.d.ts +35 -4
  65. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar-register.d.ts +46 -0
  66. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar-services.d.ts +45 -0
  67. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar.d.ts +21 -36
  68. package/node_modules/@ftshare-lab/dsh-kline/lib/types/fibonacci.d.ts +5 -0
  69. package/node_modules/@ftshare-lab/dsh-kline/lib/types/labeled-polyline.d.ts +11 -0
  70. package/node_modules/@ftshare-lab/dsh-kline/lib/types/price-bands.d.ts +3 -0
  71. package/node_modules/@ftshare-lab/dsh-kline/lib/types/price-series.d.ts +5 -0
  72. package/node_modules/@ftshare-lab/dsh-kline/lib/types/price-sticks.d.ts +3 -0
  73. package/node_modules/@ftshare-lab/dsh-kline/package.json +27 -5
  74. package/node_modules/@ftshare-lab/dsh-kline/requirements.txt +2 -0
  75. package/node_modules/@ftshare-lab/dsh-kline/scripts/dsh-mcp-plugin.mjs +27 -0
  76. package/node_modules/@ftshare-lab/dsh-kline/scripts/run-dsh-kline.mjs +180 -49
  77. package/node_modules/@ftshare-lab/dsh-kline/server.py +300 -34
  78. package/node_modules/@ftshare-lab/dsh-kline/tools/annotations.py +119 -0
  79. package/node_modules/@ftshare-lab/dsh-kline/tools/baostock_source.py +176 -0
  80. package/node_modules/@ftshare-lab/dsh-kline/tools/channel_candidates.py +260 -0
  81. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_applications.py +1 -1
  82. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_context.py +22 -3
  83. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_edits.py +141 -16
  84. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_functions.py +466 -0
  85. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_indicators.py +63 -0
  86. package/node_modules/@ftshare-lab/dsh-kline/tools/draw.py +3 -0
  87. package/node_modules/@ftshare-lab/dsh-kline/tools/drawing_feedback.py +13 -7
  88. package/node_modules/@ftshare-lab/dsh-kline/tools/drawing_interaction.py +117 -0
  89. package/node_modules/@ftshare-lab/dsh-kline/tools/drawing_verification.py +58 -3
  90. package/node_modules/@ftshare-lab/dsh-kline/tools/fetch.py +164 -40
  91. package/node_modules/@ftshare-lab/dsh-kline/tools/fibonacci.py +83 -0
  92. package/node_modules/@ftshare-lab/dsh-kline/tools/free_sources.py +78 -21
  93. package/node_modules/@ftshare-lab/dsh-kline/tools/pivots.py +60 -0
  94. package/node_modules/@ftshare-lab/dsh-kline/tools/polylines.py +125 -0
  95. package/node_modules/@ftshare-lab/dsh-kline/tools/price_bands.py +165 -0
  96. package/node_modules/@ftshare-lab/dsh-kline/tools/price_series.py +162 -0
  97. package/node_modules/@ftshare-lab/dsh-kline/tools/price_sticks.py +114 -0
  98. package/node_modules/@ftshare-lab/dsh-kline/tools/range_candidates.py +170 -0
  99. package/node_modules/@ftshare-lab/dsh-kline/tools/regression_channels.py +87 -0
  100. package/node_modules/@ftshare-lab/dsh-kline/tools/ta_functions.py +228 -0
  101. package/package.json +3 -3
  102. package/src/agent/format.ts +3 -0
  103. package/src/agent/tools.ts +5 -3
  104. package/src/client/index.js +75 -12
  105. package/src/contract.ts +3 -1
  106. package/src/core/risk.ts +10 -2
  107. package/src/core/views.ts +2 -2
  108. package/src/data/ftshare-trading-calendar.ts +184 -45
  109. package/src/service/paper-service.ts +22 -19
  110. package/src/service/rpc.ts +12 -1
@@ -0,0 +1,228 @@
1
+ """Read-only, current-chart-bound access to the complete pinned TA-Lib catalog."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import math
7
+ from time import perf_counter
8
+
9
+ import chart_service
10
+ from core.ta_engine import ENGINE_VERSION, NATIVE_VERSION, calculate, catalog
11
+ from tools.chart_context import read_chart_context
12
+ from tools.chart_edits import require_alignment
13
+ from tools.chart_functions import _binding, _hash
14
+ from tools.lines import LineError
15
+
16
+
17
+ CATALOG = catalog()
18
+ CATALOG_BY_NAME = {item["name"]: item for item in CATALOG}
19
+ MAX_RESULT_BYTES = 1024 * 1024
20
+ MAX_RESULTS_PER_VIEW = 16
21
+
22
+
23
+ def list_ta_catalog(*, group: str | None = None, query: str | None = None,
24
+ offset: int = 0, limit: int = 25) -> dict:
25
+ if type(offset) is not int or offset < 0 or type(limit) is not int or not 1 <= limit <= 50:
26
+ raise LineError("invalid_ta_pagination", "TA-Lib 目录分页参数无效。")
27
+ if group is not None and (not isinstance(group, str) or len(group) > 64):
28
+ raise LineError("invalid_ta_group", "TA-Lib 函数组别无效。")
29
+ if query is not None and (not isinstance(query, str) or len(query) > 64):
30
+ raise LineError("invalid_ta_query", "TA-Lib 搜索词无效。")
31
+ matches = [entry for entry in CATALOG
32
+ if (not group or entry["group"].casefold() == group.casefold())
33
+ and (not query or query.casefold() in (entry["name"] + " " + entry["display_name"]).casefold())]
34
+ return {"ok": True, "engine": "TA-Lib", "engine_version": ENGINE_VERSION, "native_version": NATIVE_VERSION,
35
+ "total_catalog": len(CATALOG), "total_matches": len(matches), "offset": offset, "limit": limit,
36
+ "groups": sorted({entry["group"] for entry in CATALOG}),
37
+ "functions": [{key: entry[key] for key in ("name", "group", "display_name", "input_names", "parameters",
38
+ "output_names", "function_flags")}
39
+ for entry in matches[offset:offset + limit]],
40
+ "result_usage": "analysis_only", "chart_modified": False}
41
+
42
+
43
+ def _context(context_ref, expected_revision, chart_session, symbol):
44
+ context = read_chart_context(context_ref, candle_scope="loaded", limit=4000)
45
+ if type(expected_revision) is not int or context["revision"] != expected_revision:
46
+ raise LineError("chart_context_revision_conflict", "当前图观察版本已改变,请重新读取。")
47
+ payload = chart_service.read_chart_snapshot(chart_session)
48
+ if payload is None:
49
+ raise LineError("chart_session_not_found", "当前图来源不存在。")
50
+ require_alignment(context, payload, chart_session, symbol)
51
+ if context["candle_selection"]["truncated"] or not context["candles"]:
52
+ raise LineError("ta_candles_unavailable", "仅支持当前图1至4000根完整已加载K线,不截断计算。")
53
+ return context
54
+
55
+
56
+ def _directory(context):
57
+ return chart_service.RUNTIME_DIR / "ta_functions" / str(chart_service.HOST_PROCESS_ID) / context["context_ref"]
58
+
59
+
60
+ def _aligned_outputs(record, context, names):
61
+ times = record.get("times")
62
+ outputs = record.get("outputs")
63
+ return (isinstance(times, list) and times == [row["time"] for row in context["candles"]]
64
+ and isinstance(outputs, dict)
65
+ and all(isinstance(outputs.get(name), list) and len(outputs[name]) == len(times) for name in names))
66
+
67
+
68
+ def _positive(value):
69
+ return type(value) in (int, float) and math.isfinite(value) and value > 0
70
+
71
+
72
+ def _renderable_line(record, context):
73
+ """Only a finite, positive SMA/EMA(close) series fits the current price-line contract."""
74
+ parameters = record.get("parameters")
75
+ period = parameters.get("timeperiod") if isinstance(parameters, dict) else None
76
+ if not (record.get("function") in {"SMA", "EMA"} and type(period) is int and 2 <= period <= 200
77
+ and record.get("price_sources") in ({}, {"price": "close"})
78
+ and _aligned_outputs(record, context, ("real",))):
79
+ return False
80
+ values = record["outputs"]["real"]
81
+ return any(value is not None for value in values) and all(value is None or _positive(value) for value in values)
82
+
83
+
84
+ def _renderable_bbands(record, context):
85
+ params = record.get("parameters")
86
+ if not (record.get("function") == "BBANDS" and isinstance(params, dict)
87
+ and type(params.get("timeperiod")) is int and 2 <= params["timeperiod"] <= 200
88
+ and type(params.get("matype")) is int and params["matype"] == 0
89
+ and all(type(params.get(key)) in (int, float) and math.isfinite(params[key])
90
+ and 0 < params[key] <= 5 for key in ("nbdevup", "nbdevdn"))
91
+ and record.get("price_sources") in ({}, {"price": "close"})
92
+ and _aligned_outputs(record, context, ("upperband", "middleband", "lowerband"))):
93
+ return False
94
+ outputs = record["outputs"]
95
+ triples = zip(outputs["upperband"], outputs["middleband"], outputs["lowerband"])
96
+ valid = 0
97
+ for upper, middle, lower in triples:
98
+ if upper is middle is lower is None:
99
+ continue
100
+ if not (_positive(upper) and _positive(middle) and _positive(lower)
101
+ and upper > middle > lower):
102
+ return False
103
+ valid += 1
104
+ return valid > 0
105
+
106
+
107
+ def _load_record(context, result_ref, expected_revision):
108
+ if not isinstance(result_ref, str) or len(result_ref) != 64 or any(c not in "0123456789abcdef" for c in result_ref):
109
+ raise LineError("invalid_ta_result_ref", "TA-Lib 结果引用无效。")
110
+ path = _directory(context) / f"{result_ref}.json"
111
+ try:
112
+ if path.stat().st_size > MAX_RESULT_BYTES:
113
+ raise ValueError("size")
114
+ record = json.loads(path.read_text(encoding="utf-8"))
115
+ if _hash(record) != result_ref or record.get("schema_version") != 1:
116
+ raise ValueError("hash")
117
+ except (OSError, ValueError, TypeError):
118
+ raise LineError("ta_result_unavailable", "结果引用不存在或已失效。") from None
119
+ if (record.get("engine") != "TA-Lib" or record.get("engine_version") != ENGINE_VERSION
120
+ or record.get("native_version") != NATIVE_VERSION or record.get("result_usage") != "analysis_only"
121
+ or record.get("binding") != _binding(context)
122
+ or record.get("observation_revision") != expected_revision):
123
+ raise LineError("ta_result_mismatch", "结果与当前标的、周期、行情或视图不匹配,请重新计算。")
124
+ return record
125
+
126
+
127
+ def resolve_ta_drawing(result_ref, context, kind):
128
+ """Explicitly promote an allowlisted bound TA result into guarded price geometry."""
129
+ record = _load_record(context, result_ref, context["revision"])
130
+ if kind == "series_line" and _renderable_line(record, context):
131
+ return {"source": {"kind": record["function"].lower(), "period": record["parameters"]["timeperiod"]},
132
+ "condition": None, "values": list(record["outputs"]["real"])}
133
+ if kind == "price_band" and _renderable_bbands(record, context):
134
+ params = record["parameters"]
135
+ source = {"kind": "bbands", "period": params["timeperiod"],
136
+ "deviation_up": params["nbdevup"], "deviation_down": params["nbdevdn"], "matype": 0}
137
+ return {"upper_source": {**source, "output": "upperband"},
138
+ "lower_source": {**source, "output": "lowerband"}, "condition": None,
139
+ "upper_values": list(record["outputs"]["upperband"]),
140
+ "middle_values": list(record["outputs"]["middleband"]),
141
+ "lower_values": list(record["outputs"]["lowerband"])}
142
+ raise LineError("ta_result_not_drawable", "仅支持当前图的有限 SMA/EMA(close) 单线或 BBANDS(close, SMA中轨) 三线价带;请核对函数、输入、参数与目标图形。")
143
+
144
+
145
+ def run_ta(context_ref, expected_revision, chart_session, symbol, name, parameters=None,
146
+ price_sources=None, periods_constant=14):
147
+ started = perf_counter()
148
+ if not isinstance(name, str) or name not in CATALOG_BY_NAME:
149
+ raise LineError("unknown_ta_function", "未知 TA-Lib 函数,请先查询 list_ta_functions。")
150
+ context = _context(context_ref, expected_revision, chart_session, symbol)
151
+ try:
152
+ info, values = calculate(name, context["candles"], parameters=parameters,
153
+ price_sources=price_sources, periods_constant=periods_constant)
154
+ except Exception as exc:
155
+ if isinstance(exc, RuntimeError):
156
+ raise
157
+ raise LineError("invalid_ta_parameters", f"TA-Lib 参数或输入无效:{exc}") from None
158
+ rows = context["candles"]
159
+ summaries = {}
160
+ any_finite = False
161
+ for output_name, series in values.items():
162
+ valid = [(index, value) for index, value in enumerate(series) if value is not None]
163
+ any_finite |= bool(valid)
164
+ summaries[output_name] = {
165
+ "first_valid": {"index": valid[0][0], "time": rows[valid[0][0]]["time"]} if valid else None,
166
+ "latest": {"index": valid[-1][0], "time": rows[valid[-1][0]]["time"],
167
+ "value": valid[-1][1]} if valid else None,
168
+ "valid_count": len(valid), "nonzero_count": sum(value != 0 for _, value in valid),
169
+ }
170
+ record = {"schema_version": 1, "engine": "TA-Lib", "engine_version": ENGINE_VERSION,
171
+ "native_version": NATIVE_VERSION, "binding": _binding(context),
172
+ "observation_revision": expected_revision, "function": name,
173
+ "parameters": {**info["parameters"], **(parameters or {})},
174
+ "price_sources": price_sources or {}, "periods_constant": periods_constant if name == "MAVP" else None,
175
+ "times": [row["time"] for row in rows], "outputs": values, "summary": summaries,
176
+ "result_usage": "analysis_only"}
177
+ encoded = json.dumps(record, ensure_ascii=False, separators=(",", ":"), allow_nan=False).encode()
178
+ if len(encoded) > MAX_RESULT_BYTES:
179
+ raise LineError("ta_result_too_large", "TA-Lib 结果超过本地容量限制,未保存。")
180
+ result_ref = _hash(record)
181
+ refreshed = read_chart_context(context_ref, candle_scope="loaded", limit=4000)
182
+ if refreshed["revision"] != expected_revision or _binding(refreshed) != record["binding"]:
183
+ raise LineError("chart_context_revision_conflict", "计算期间当前图已改变,未保存结果。")
184
+ directory = _directory(context)
185
+ path = directory / f"{result_ref}.json"
186
+ if not path.exists():
187
+ existing = sorted(directory.glob("*.json"), key=lambda item: (item.stat().st_mtime_ns, item.name)) if directory.exists() else []
188
+ if len(existing) >= MAX_RESULTS_PER_VIEW:
189
+ try:
190
+ for expired in existing[:len(existing) - MAX_RESULTS_PER_VIEW + 1]:
191
+ expired.unlink()
192
+ except OSError:
193
+ raise LineError("ta_result_capacity", "当前图的临时结果容量已满,无法淘汰旧结果。") from None
194
+ chart_service._atomic_runtime_json(path, record)
195
+ else:
196
+ try:
197
+ if json.loads(path.read_text(encoding="utf-8")) != record:
198
+ raise ValueError("collision")
199
+ except (OSError, ValueError):
200
+ raise LineError("ta_result_invalid", "已保存 TA 结果无效,未覆盖。") from None
201
+ return {"ok": True, "engine": "TA-Lib", "engine_version": ENGINE_VERSION,
202
+ "native_version": NATIVE_VERSION, "result_ref": result_ref, "function": name,
203
+ "parameters": record["parameters"], "price_sources": record["price_sources"],
204
+ "status": "ok" if any_finite else "no_finite_output", "summary": summaries,
205
+ "loaded_bars": len(rows), "data_fingerprint": record["binding"]["data_fingerprint"],
206
+ "data_scope": {key: context.get(key) for key in ("symbol", "interval", "interval_value", "adjust", "loaded_range")},
207
+ "result_usage": "analysis_only", "chart_modified": False, "render_verified": False,
208
+ "selectable_render_targets": ([{"kind": "series_line", "output_name": "real"}]
209
+ if _renderable_line(record, context) else
210
+ [{"kind": "price_band", "output_names": ["upperband", "middleband", "lowerband"]}]
211
+ if _renderable_bbands(record, context) else []),
212
+ "calculation_ms": round((perf_counter() - started) * 1000, 3)}
213
+
214
+
215
+ def read_ta(context_ref, expected_revision, chart_session, symbol, result_ref, output_name,
216
+ offset=0, limit=200):
217
+ if type(offset) is not int or offset < 0 or type(limit) is not int or not 1 <= limit <= 250:
218
+ raise LineError("invalid_ta_pagination", "TA-Lib 结果分页参数无效。")
219
+ context = _context(context_ref, expected_revision, chart_session, symbol)
220
+ record = _load_record(context, result_ref, expected_revision)
221
+ series = record.get("outputs", {}).get(output_name) if isinstance(output_name, str) else None
222
+ times = record.get("times")
223
+ if not isinstance(series, list) or not isinstance(times, list) or len(series) != len(times):
224
+ raise LineError("ta_output_unknown", "结果不存在此输出名称。")
225
+ return {"ok": True, "result_ref": result_ref, "function": record["function"],
226
+ "output_name": output_name, "total": len(series), "offset": offset, "limit": limit,
227
+ "items": [{"time": times[i], "value": series[i]} for i in range(offset, min(offset + limit, len(series)))],
228
+ "result_usage": "analysis_only", "chart_modified": False}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dsh-ft/dsh-fft-paper-trading",
3
- "version": "0.6.0",
3
+ "version": "0.6.2",
4
4
  "description": "A-share and commodity futures paper trading for DeepSeek Harness: local ledger, batch orders, review, and FTShare quotes.",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -50,8 +50,8 @@
50
50
  ],
51
51
  "dependencies": {
52
52
  "@dsh-ft/dsh-fft-settings": "^0.5.0",
53
- "@dsh-ft/dsh-fft-ftshare": "^0.3.0",
54
- "@ftshare-lab/dsh-kline": "0.4.0"
53
+ "@dsh-ft/dsh-fft-ftshare": "^0.4.0",
54
+ "@ftshare-lab/dsh-kline": "0.6.4"
55
55
  },
56
56
  "bundledDependencies": [
57
57
  "@ftshare-lab/dsh-kline"
@@ -47,6 +47,9 @@ export function renderOrder(order: OrderView): string {
47
47
  }
48
48
  const parts = [`${status[order.status]}:${order.side === 'buy' ? '买入' : '卖出'} ${formatSymbol(order.symbol, order.name)} ${order.qty} 股`]
49
49
  if (order.type === 'limit' && order.limitPrice !== undefined) parts.push(`限价 ${order.limitPrice.toFixed(2)}`)
50
+ // A queued order is not "waiting for a price to cross": it has no matching
51
+ // window yet, so say when it will be tried.
52
+ if (order.status === 'queued') parts.push('下一交易时段开盘后撮合')
50
53
  if (order.fillPrice !== undefined) parts.push(`成交价 ${order.fillPrice.toFixed(2)}`)
51
54
  if (order.reason !== undefined) parts.push(`原因 ${order.reason}`)
52
55
  if (order.note !== undefined) parts.push(`备注 ${order.note}`)
@@ -47,6 +47,7 @@ const param = {
47
47
  period: { type: 'string', description: '复盘区间:7d、30d、all' },
48
48
  reset: { type: 'boolean', description: '是否重置账户' },
49
49
  confirm: { type: 'boolean', description: '重置时必须为 true' },
50
+ initialCash: { type: 'number', description: '重置时的初始资金(元),不填沿用当前设置' },
50
51
  action: { type: 'string', description: '动作:status 查交易时段 / search 搜标的' },
51
52
  query: { type: 'string', description: '搜索关键词(代码或名称)' },
52
53
  limit: { type: 'number', description: '返回条数上限,默认 10' },
@@ -57,7 +58,7 @@ function required<T extends ValueSchemaSpec>(property: T): T & { required: true
57
58
  return { ...property, required: true }
58
59
  }
59
60
 
60
- const accountParameters = { reset: param.reset, confirm: param.confirm } satisfies ParameterSchemaSpec
61
+ const accountParameters = { reset: param.reset, confirm: param.confirm, initialCash: param.initialCash } satisfies ParameterSchemaSpec
61
62
  const marketParameters = { action: param.action, query: param.query, limit: param.limit } satisfies ParameterSchemaSpec
62
63
  const quoteParameters = { symbol: param.symbol, symbols: param.symbols } satisfies ParameterSchemaSpec
63
64
  const previewParameters = {
@@ -113,12 +114,13 @@ export function registerPaperTools(tools: ToolsLike, service: PaperService): voi
113
114
  ...base,
114
115
  name: 'paper_stock_account',
115
116
  parameters: accountParameters,
116
- description: '查看模拟盘账户、持仓、挂单与最近成交;reset=true 且 confirm=true 时重置账户。',
117
+ description: '查看模拟盘账户、持仓、挂单与最近成交;reset=true 且 confirm=true 时重置账户(可用 initialCash 指定初始资金,元)。',
117
118
  async execute(args: unknown): Promise<ToolResult> {
118
119
  const input = (args ?? {}) as Record<string, unknown>
119
120
  try {
121
+ const startingCash = typeof input.initialCash === 'number' ? Math.round(input.initialCash * 100) : undefined
120
122
  const account = input.reset === true
121
- ? await service.reset(input.confirm === true)
123
+ ? await service.reset(input.confirm === true, startingCash)
122
124
  : await service.account()
123
125
  const [orders, trades] = await Promise.all([service.orders(), service.trades()])
124
126
  const pending = orders.filter(order => order.status === 'pending' || order.status === 'queued' || order.status === 'partially_filled')
@@ -295,7 +295,7 @@ window.__ModuleLoader__.load({
295
295
  }
296
296
 
297
297
  const STATUS_TEXT = {
298
- queued: '排队',
298
+ queued: '待开盘',
299
299
  pending: '挂单',
300
300
  partially_filled: '部分成交',
301
301
  filled: '成交',
@@ -307,7 +307,9 @@ window.__ModuleLoader__.load({
307
307
  const sessionNote = session => {
308
308
  if (!session || session.canMatch) return ''
309
309
  if (session.phase === 'auction_close') return '(收盘竞价暂不支持下单)'
310
- return '(仅可预埋限价单)'
310
+ if (session.phase === 'pre_open') return '(集合竞价,09:30 开盘撮合)'
311
+ if (session.phase === 'lunch') return '(午休,13:00 开盘撮合)'
312
+ return '(盘后委托顺延至下一交易时段开盘)'
311
313
  }
312
314
  const PHASE_TEXT = {
313
315
  pre_open: '集合竞价',
@@ -761,6 +763,7 @@ window.__ModuleLoader__.load({
761
763
  }
762
764
 
763
765
  const CASH_QUICK_AMOUNTS = [10000, 50000, 100000]
766
+ const RESET_QUICK_AMOUNTS = [500000, 1000000, 2000000]
764
767
 
765
768
  /**
766
769
  * Inline cash in/out panel shared by the stock and futures headers.
@@ -797,6 +800,38 @@ window.__ModuleLoader__.load({
797
800
  )
798
801
  }
799
802
 
803
+ /**
804
+ * Inline reset confirmation with the starting cash.
805
+ *
806
+ * A reset keeps the previous settings, so an account opened at 10 万 would
807
+ * otherwise stay there forever; the input lets the user pick the starting
808
+ * cash in the same step, and reuses the cash panel's atoms.
809
+ */
810
+ function ResetPanel({ initialCash, amount, onAmount, busy, onCancel, onSubmit }) {
811
+ const cents = cashAmountCents(amount)
812
+ const reason = cents === null ? '初始资金需为正数' : ''
813
+ return h('div', { className: 'pt-cash' },
814
+ h('div', { className: 'pt-row' },
815
+ h('div', { className: 'pt-note' }, '初始资金(元)'),
816
+ h('input', {
817
+ className: 'pt-input', style: { width: 130 }, inputMode: 'decimal', placeholder: `当前 ${money(initialCash)}`,
818
+ value: amount, onChange: event => onAmount(event.target.value),
819
+ }),
820
+ RESET_QUICK_AMOUNTS.map(value => h('button', {
821
+ key: value, className: 'pt-btn', onClick: () => onAmount(String(value)),
822
+ }, `${value / 10000}万`)),
823
+ ),
824
+ h('div', { className: 'pt-row' },
825
+ h('div', { className: 'pt-note' }, '重置会清空持仓与挂单,账本先备份'),
826
+ h('button', { className: 'pt-btn', onClick: onCancel, disabled: busy }, '取消'),
827
+ h('button', {
828
+ className: 'pt-btn pt-btn-danger', onClick: onSubmit, disabled: busy || reason !== '', title: reason || undefined,
829
+ }, busy ? '处理中…' : '确认重置'),
830
+ ),
831
+ reason !== '' ? h('div', { className: 'pt-note pt-risk-high' }, reason) : null,
832
+ )
833
+ }
834
+
800
835
  function DebouncedNumber({ value, onChange, placeholder, min, step }) {
801
836
  return h('input', {
802
837
  className: 'pt-input',
@@ -1151,7 +1186,7 @@ window.__ModuleLoader__.load({
1151
1186
  )
1152
1187
  }
1153
1188
  const pendingText = order.status === 'queued'
1154
- ? '当前时段不撮合,进入连续竞价后按最新价判定'
1189
+ ? '当前时段不撮合,已受理为下一交易时段开盘委托'
1155
1190
  : '现价未穿越,成交前一直挂单'
1156
1191
  return h('div', { className: 'pt-receipt', 'data-state': 'resting', title: order.id },
1157
1192
  `挂单:${side} ${symbol} ${count(order.qty)} 股${order.limitPrice === undefined ? '' : ` @ ${money(order.limitPrice)}`} · ${pendingText} · 单 ${order.id}`,
@@ -1283,7 +1318,7 @@ window.__ModuleLoader__.load({
1283
1318
  ))),
1284
1319
  ),
1285
1320
  pending.some(order => order.status === 'queued')
1286
- ? h('div', { className: 'pt-note' }, '「排队」:当前时段不撮合,下一交易时段会尝试成交,可随时撤单。')
1321
+ ? h('div', { className: 'pt-note' }, '「待开盘」:当前时段不撮合,下一交易时段开盘后按当时价格尝试成交,可随时撤单。')
1287
1322
  : null,
1288
1323
  ),
1289
1324
  h('div', null,
@@ -1492,7 +1527,7 @@ window.__ModuleLoader__.load({
1492
1527
  if (account !== null && account.blocked === true) return '账户已锁定'
1493
1528
  if (preview === null) return '先批量预览'
1494
1529
  if (rows.length === 0) return '没有可下单的行'
1495
- if (preview.session && preview.session.canMatch === false) return '当前时段不能市价成交'
1530
+ if (preview.session && preview.session.phase === 'auction_close') return '收盘竞价暂不支持模拟撮合'
1496
1531
  return ''
1497
1532
  }, [account, preview, rows])
1498
1533
 
@@ -2509,6 +2544,10 @@ window.__ModuleLoader__.load({
2509
2544
  const [cashOpen, setCashOpen] = useState(false)
2510
2545
  const [cashSide, setCashSide] = useState('deposit')
2511
2546
  const [cashAmount, setCashAmount] = useState('')
2547
+ // Inline reset strip: picking the starting cash is part of the reset, so
2548
+ // it replaces the browser confirm dialog instead of living in settings.
2549
+ const [resetOpen, setResetOpen] = useState(false)
2550
+ const [resetCash, setResetCash] = useState('')
2512
2551
  const submitting = useRef(false)
2513
2552
  const placeKey = useRef({ key: '', id: '' })
2514
2553
  const [preview, setPreview] = useState(null)
@@ -2943,23 +2982,26 @@ window.__ModuleLoader__.load({
2943
2982
  }, [])
2944
2983
 
2945
2984
  const reset = useCallback(async () => {
2946
- if (!window.confirm('重置模拟交易账户?持仓与挂单会清空;当前账本会先备份,可在备份里找回。')) return
2985
+ const cents = cashAmountCents(resetCash)
2986
+ if (cents === null) return
2947
2987
  setBusy(true)
2948
2988
  try {
2949
- setAccount(await rpc('account/reset', { confirm: true }))
2989
+ setAccount(await rpc('account/reset', { confirm: true, initialCash: cents / 100 }))
2950
2990
  setPreview(null)
2951
2991
  setReceipt(null)
2952
2992
  await loadAll(true)
2953
2993
  await loadReviewDetail()
2954
2994
  setPreviewNonce(value => value + 1)
2955
2995
  setResetNonce(value => value + 1)
2956
- setNotice('账户已重置')
2996
+ setResetOpen(false)
2997
+ setResetCash('')
2998
+ setNotice(`账户已重置,初始资金 ${money(cents / 100)}`)
2957
2999
  } catch (cause) {
2958
3000
  setError(errorOf(cause))
2959
3001
  } finally {
2960
3002
  setBusy(false)
2961
3003
  }
2962
- }, [loadAll, loadReviewDetail])
3004
+ }, [resetCash, loadAll, loadReviewDetail])
2963
3005
 
2964
3006
  /** 注资/提款:写一条账本事件,现金与总资产随之更新,盈亏剔除净入金。 */
2965
3007
  const moveCash = useCallback(async () => {
@@ -3018,14 +3060,15 @@ window.__ModuleLoader__.load({
3018
3060
  if (form.side === 'buy' && qty % 100 !== 0) return '买入需 100 股整数倍'
3019
3061
  if (form.type === 'limit' && !(Number(form.limitPrice) > 0)) return '填写限价'
3020
3062
  if (session !== null && session.phase === 'auction_close') return '收盘竞价暂不支持模拟撮合'
3021
- if (form.type === 'market' && session !== null && !session.canMatch) return '当前时段不能市价成交'
3022
3063
  if (form.type === 'market' && quote === null && !(Number(form.price) > 0)) return '无行情,请填参考价'
3023
3064
  if (preview !== null && preview.quote?.status === 'suspended') return '停牌'
3024
3065
  if (preview !== null && form.type === 'limit' && preview.priceLimit !== undefined) {
3025
3066
  const price = Number(form.limitPrice)
3026
3067
  if (price < preview.priceLimit.lower || price > preview.priceLimit.upper) return '价格超出涨跌停'
3027
3068
  }
3028
- if (form.side === 'buy' && preview !== null && preview.cashAfterCents < 0) return '资金不足'
3069
+ if (form.side === 'buy' && preview !== null && preview.cashAfterCents < 0) {
3070
+ return `资金不足(还差 ${cents(-preview.cashAfterCents)})`
3071
+ }
3029
3072
  if (form.side === 'sell' && preview !== null && qty > preview.availableQty) return '可卖不足'
3030
3073
  return ''
3031
3074
  }, [blocked, form, session, quote, preview])
@@ -3073,9 +3116,18 @@ window.__ModuleLoader__.load({
3073
3116
  onClick: () => {
3074
3117
  setError(null)
3075
3118
  setCashOpen(value => !value)
3119
+ setResetOpen(false)
3076
3120
  },
3077
3121
  }, '资金'),
3078
- h('button', { className: 'pt-btn pt-btn-danger', onClick: reset, disabled: busy }, '重置'),
3122
+ h('button', {
3123
+ className: 'pt-btn pt-btn-danger', 'data-active': resetOpen, disabled: busy,
3124
+ onClick: () => {
3125
+ setError(null)
3126
+ setResetOpen(value => !value)
3127
+ setResetCash(String(account.initialCash))
3128
+ setCashOpen(false)
3129
+ },
3130
+ }, '重置'),
3079
3131
  h(FeedbackLink),
3080
3132
  ),
3081
3133
  ),
@@ -3093,6 +3145,17 @@ window.__ModuleLoader__.load({
3093
3145
  },
3094
3146
  onSubmit: moveCash,
3095
3147
  }) : null,
3148
+ resetOpen ? h(ResetPanel, {
3149
+ initialCash: account.initialCash,
3150
+ amount: resetCash,
3151
+ onAmount: setResetCash,
3152
+ busy,
3153
+ onCancel: () => {
3154
+ setResetOpen(false)
3155
+ setResetCash('')
3156
+ },
3157
+ onSubmit: reset,
3158
+ }) : null,
3096
3159
  account.blocked ? h('div', { className: 'pt-blocked' },
3097
3160
  h('div', { className: 'pt-blocked-text' },
3098
3161
  h('div', null, '账本校验失败,账户已锁定。'),
package/src/contract.ts CHANGED
@@ -43,7 +43,9 @@ export interface PaperSettings {
43
43
  }
44
44
 
45
45
  export const DEFAULT_SETTINGS: PaperSettings = {
46
- initialCashCents: 10_000_000,
46
+ // 100 万,A 股模拟盘的常规默认值:1 手贵州茅台(约 14.5 万)也能买,
47
+ // 10 万会让新账户连一手高价股都下不了单。
48
+ initialCashCents: 100_000_000,
47
49
  commissionRate: 0.00025,
48
50
  minCommissionCents: 500,
49
51
  stampDutyRate: 0.0005,
package/src/core/risk.ts CHANGED
@@ -72,8 +72,16 @@ export function checkOrder(
72
72
  const amount = amountCents(price, draft.qty)
73
73
  if (draft.side === 'buy') {
74
74
  const fees = computeFees(amount, 'buy', settings)
75
- if (state.cashCents < amount + fees.totalCents) {
76
- return { ok: false, code: 'INSUFFICIENT_CASH', message: '可用资金不足(含费用)' }
75
+ const needCents = amount + fees.totalCents
76
+ if (state.cashCents < needCents) {
77
+ // Name both numbers: "可用资金不足" alone leaves the user guessing
78
+ // whether a cheaper lot or a deposit is the way out.
79
+ const yuan = (cents: number) => (cents / 100).toFixed(2)
80
+ return {
81
+ ok: false,
82
+ code: 'INSUFFICIENT_CASH',
83
+ message: `可用资金不足(需 ${yuan(needCents)} 元,可用 ${yuan(state.cashCents)} 元)`,
84
+ }
77
85
  }
78
86
  if (settings.maxOrderNotionalCents > 0 && amount > settings.maxOrderNotionalCents) {
79
87
  return { ok: false, code: 'MAX_NOTIONAL', message: '超过单笔金额上限' }
package/src/core/views.ts CHANGED
@@ -164,8 +164,8 @@ export function previewOrder(
164
164
  }
165
165
  if (session !== undefined && !session.canMatch) {
166
166
  warnings.push(draft.type === 'limit'
167
- ? '当前时段不能连续成交,委托将排队'
168
- : '当前时段不能市价成交,请改用限价或等开盘')
167
+ ? '当前时段不能连续成交,委托将排队到下一交易时段'
168
+ : '当前时段不能立即成交,市价单将作为下一交易时段开盘委托排队')
169
169
  }
170
170
  if (quote !== null && quote.status === 'suspended') warnings.push('标的停牌,暂不能成交')
171
171
  // A limit that the last price has not reached cannot fill now: say so, and