@dsh-ft/dsh-fft-paper-trading 0.7.1 → 0.7.3

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 (132) hide show
  1. package/README.md +1 -1
  2. package/README.zh.md +1 -1
  3. package/lib/client.js +1 -1
  4. package/package.json +1 -4
  5. package/node_modules/@ftshare-lab/dsh-kline/CHANGELOG.md +0 -611
  6. package/node_modules/@ftshare-lab/dsh-kline/LICENSE +0 -21
  7. package/node_modules/@ftshare-lab/dsh-kline/PROVENANCE.md +0 -13
  8. package/node_modules/@ftshare-lab/dsh-kline/README.en.md +0 -171
  9. package/node_modules/@ftshare-lab/dsh-kline/README.md +0 -171
  10. package/node_modules/@ftshare-lab/dsh-kline/chart_service.py +0 -687
  11. package/node_modules/@ftshare-lab/dsh-kline/config/basic-symbols.json +0 -570
  12. package/node_modules/@ftshare-lab/dsh-kline/config/dsh-kline.patch.yml +0 -4
  13. package/node_modules/@ftshare-lab/dsh-kline/config/dsh-tool-catalog.json +0 -3875
  14. package/node_modules/@ftshare-lab/dsh-kline/cordis.patch.yml +0 -33
  15. package/node_modules/@ftshare-lab/dsh-kline/core/__init__.py +0 -0
  16. package/node_modules/@ftshare-lab/dsh-kline/core/adjustment.py +0 -16
  17. package/node_modules/@ftshare-lab/dsh-kline/core/calc.py +0 -691
  18. package/node_modules/@ftshare-lab/dsh-kline/core/rows.py +0 -228
  19. package/node_modules/@ftshare-lab/dsh-kline/core/ta_engine.py +0 -99
  20. package/node_modules/@ftshare-lab/dsh-kline/lib/candle-sequence.js +0 -15
  21. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-adjustment.js +0 -7
  22. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-annotations.js +0 -33
  23. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-applications.js +0 -171
  24. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-context.js +0 -164
  25. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-observation.js +0 -251
  26. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-service-status.js +0 -82
  27. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-source-status.js +0 -39
  28. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-sources.js +0 -354
  29. package/node_modules/@ftshare-lab/dsh-kline/lib/client.js +0 -17581
  30. package/node_modules/@ftshare-lab/dsh-kline/lib/drawing-feedback.js +0 -284
  31. package/node_modules/@ftshare-lab/dsh-kline/lib/fibonacci.js +0 -18
  32. package/node_modules/@ftshare-lab/dsh-kline/lib/ftshare-settings-bridge.js +0 -159
  33. package/node_modules/@ftshare-lab/dsh-kline/lib/index.js +0 -279
  34. package/node_modules/@ftshare-lab/dsh-kline/lib/labeled-polyline.js +0 -17
  35. package/node_modules/@ftshare-lab/dsh-kline/lib/pattern-groups.js +0 -91
  36. package/node_modules/@ftshare-lab/dsh-kline/lib/price-bands.js +0 -55
  37. package/node_modules/@ftshare-lab/dsh-kline/lib/price-series.js +0 -47
  38. package/node_modules/@ftshare-lab/dsh-kline/lib/price-sticks.js +0 -32
  39. package/node_modules/@ftshare-lab/dsh-kline/lib/types/candle-sequence.d.ts +0 -2
  40. package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-adjustment.d.ts +0 -2
  41. package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-annotations.d.ts +0 -4
  42. package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-applications.d.ts +0 -26
  43. package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-context.d.ts +0 -14
  44. package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-observation.d.ts +0 -8
  45. package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-service-status.d.ts +0 -22
  46. package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-source-status.d.ts +0 -47
  47. package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-sources.d.ts +0 -25
  48. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/BetterSidebarTab.d.ts +0 -12
  49. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/ClassicShell.d.ts +0 -4
  50. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/KlineContent.d.ts +0 -37
  51. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/PanelHost.d.ts +0 -25
  52. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/chart-apply.d.ts +0 -13
  53. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/chart-context.d.ts +0 -23
  54. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/chart-handoff.d.ts +0 -5
  55. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/chart-session-resolver.d.ts +0 -2
  56. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/client-context.d.ts +0 -16
  57. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/conversation.d.ts +0 -43
  58. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/default-tab.d.ts +0 -3
  59. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/embed.d.ts +0 -37
  60. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/generated-view.d.ts +0 -2
  61. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/horizontal-lines.d.ts +0 -1
  62. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/host-options.d.ts +0 -38
  63. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/host-panels.d.ts +0 -55
  64. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/index.d.ts +0 -4
  65. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/mode-preferences.d.ts +0 -25
  66. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar-contract.d.ts +0 -52
  67. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar-register.d.ts +0 -46
  68. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar-services.d.ts +0 -45
  69. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar.d.ts +0 -47
  70. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/sidebar-integration.d.ts +0 -12
  71. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/ui-onboarding.d.ts +0 -7
  72. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/version.d.ts +0 -1
  73. package/node_modules/@ftshare-lab/dsh-kline/lib/types/drawing-feedback.d.ts +0 -5
  74. package/node_modules/@ftshare-lab/dsh-kline/lib/types/fibonacci.d.ts +0 -5
  75. package/node_modules/@ftshare-lab/dsh-kline/lib/types/ftshare-settings-bridge.d.ts +0 -50
  76. package/node_modules/@ftshare-lab/dsh-kline/lib/types/index.d.ts +0 -26
  77. package/node_modules/@ftshare-lab/dsh-kline/lib/types/labeled-polyline.d.ts +0 -11
  78. package/node_modules/@ftshare-lab/dsh-kline/lib/types/pattern-groups.d.ts +0 -2
  79. package/node_modules/@ftshare-lab/dsh-kline/lib/types/price-bands.d.ts +0 -3
  80. package/node_modules/@ftshare-lab/dsh-kline/lib/types/price-series.d.ts +0 -5
  81. package/node_modules/@ftshare-lab/dsh-kline/lib/types/price-sticks.d.ts +0 -3
  82. package/node_modules/@ftshare-lab/dsh-kline/package.json +0 -157
  83. package/node_modules/@ftshare-lab/dsh-kline/requirements.txt +0 -6
  84. package/node_modules/@ftshare-lab/dsh-kline/scripts/bootstrap.sh +0 -5
  85. package/node_modules/@ftshare-lab/dsh-kline/scripts/dsh-bootstrap.mjs +0 -179
  86. package/node_modules/@ftshare-lab/dsh-kline/scripts/dsh-mcp-plugin.mjs +0 -27
  87. package/node_modules/@ftshare-lab/dsh-kline/scripts/run-dsh-kline.mjs +0 -658
  88. package/node_modules/@ftshare-lab/dsh-kline/scripts/run-dsh-kline.sh +0 -5
  89. package/node_modules/@ftshare-lab/dsh-kline/server.py +0 -1755
  90. package/node_modules/@ftshare-lab/dsh-kline/tools/__init__.py +0 -0
  91. package/node_modules/@ftshare-lab/dsh-kline/tools/annotations.py +0 -119
  92. package/node_modules/@ftshare-lab/dsh-kline/tools/automatic_analysis.py +0 -158
  93. package/node_modules/@ftshare-lab/dsh-kline/tools/baostock_source.py +0 -176
  94. package/node_modules/@ftshare-lab/dsh-kline/tools/calc.py +0 -39
  95. package/node_modules/@ftshare-lab/dsh-kline/tools/channel_candidates.py +0 -260
  96. package/node_modules/@ftshare-lab/dsh-kline/tools/channel_preview.py +0 -82
  97. package/node_modules/@ftshare-lab/dsh-kline/tools/channels.py +0 -104
  98. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_applications.py +0 -204
  99. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_context.py +0 -186
  100. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_edits.py +0 -363
  101. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_functions.py +0 -451
  102. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_indicators.py +0 -65
  103. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_measurements.py +0 -84
  104. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_source_status.py +0 -32
  105. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_sources.py +0 -31
  106. package/node_modules/@ftshare-lab/dsh-kline/tools/closed_daily.py +0 -68
  107. package/node_modules/@ftshare-lab/dsh-kline/tools/draw.py +0 -410
  108. package/node_modules/@ftshare-lab/dsh-kline/tools/drawing_feedback.py +0 -45
  109. package/node_modules/@ftshare-lab/dsh-kline/tools/drawing_interaction.py +0 -117
  110. package/node_modules/@ftshare-lab/dsh-kline/tools/drawing_verification.py +0 -141
  111. package/node_modules/@ftshare-lab/dsh-kline/tools/fetch.py +0 -4680
  112. package/node_modules/@ftshare-lab/dsh-kline/tools/fibonacci.py +0 -83
  113. package/node_modules/@ftshare-lab/dsh-kline/tools/foreign_daily.py +0 -185
  114. package/node_modules/@ftshare-lab/dsh-kline/tools/free_sources.py +0 -483
  115. package/node_modules/@ftshare-lab/dsh-kline/tools/lines.py +0 -91
  116. package/node_modules/@ftshare-lab/dsh-kline/tools/nine_count.py +0 -66
  117. package/node_modules/@ftshare-lab/dsh-kline/tools/pattern_groups.py +0 -103
  118. package/node_modules/@ftshare-lab/dsh-kline/tools/pivots.py +0 -60
  119. package/node_modules/@ftshare-lab/dsh-kline/tools/polylines.py +0 -131
  120. package/node_modules/@ftshare-lab/dsh-kline/tools/price_bands.py +0 -165
  121. package/node_modules/@ftshare-lab/dsh-kline/tools/price_patterns.py +0 -311
  122. package/node_modules/@ftshare-lab/dsh-kline/tools/price_series.py +0 -162
  123. package/node_modules/@ftshare-lab/dsh-kline/tools/price_sticks.py +0 -114
  124. package/node_modules/@ftshare-lab/dsh-kline/tools/range_candidates.py +0 -170
  125. package/node_modules/@ftshare-lab/dsh-kline/tools/recent_drawing_candidates.py +0 -123
  126. package/node_modules/@ftshare-lab/dsh-kline/tools/rectangles.py +0 -76
  127. package/node_modules/@ftshare-lab/dsh-kline/tools/regression_channels.py +0 -87
  128. package/node_modules/@ftshare-lab/dsh-kline/tools/ta_functions.py +0 -228
  129. package/node_modules/@ftshare-lab/dsh-kline/tools/trend_lines.py +0 -106
  130. package/node_modules/@ftshare-lab/dsh-kline/tools/watchlist.py +0 -149
  131. package/node_modules/@ftshare-lab/dsh-kline/view/ft-logo.jpg +0 -0
  132. package/node_modules/@ftshare-lab/dsh-kline/view/vendor/klinecharts.min.js +0 -7
@@ -1,228 +0,0 @@
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}
@@ -1,106 +0,0 @@
1
- """Explicit two-anchor AI segments, separate from automatic trend annotations."""
2
- from __future__ import annotations
3
-
4
- from copy import deepcopy
5
- from datetime import datetime, timedelta, timezone
6
- import hashlib
7
- import re
8
- import secrets
9
- from typing import Any
10
-
11
- from tools.lines import LineError, MAX_LINES, validate_line_fields
12
-
13
- TREND_COMMAND = "DRAW_AGENT_TREND_LINE"
14
- CN_TZ = timezone(timedelta(hours=8))
15
-
16
-
17
- def trend_lines(payload: dict[str, Any]) -> list[dict[str, Any]]:
18
- return deepcopy([c for c in payload.get("chartCommands", []) if c.get("type") == TREND_COMMAND])
19
-
20
-
21
- def resolve_anchor_time(payload: dict[str, Any], value: str) -> int:
22
- """Resolve exactly one existing bar; never silently snap to a nearby candle."""
23
- rows = next((c.get("rows", []) for c in payload.get("chartCommands", []) if c.get("type") == "SET_CANDLES"), [])
24
- if not isinstance(value, str) or not value.strip():
25
- raise LineError("invalid_anchor_time", "锚点时间需要 YYYY-MM-DD、带时区的 ISO 时间或 Unix 秒字符串。")
26
- value = value.strip()
27
- try:
28
- if re.fullmatch(r"\d{4}-\d{2}-\d{2}", value):
29
- date = datetime.strptime(value, "%Y-%m-%d").date()
30
- if payload.get("interval") not in {"day", "week", "month", "quarter", "year"}:
31
- raise LineError("ambiguous_anchor_time", "分钟周期请指定带时区的 K 线收盘时间或 Unix 秒,不能只写日期。")
32
- matches = [int(r["time"]) for r in rows
33
- if datetime.fromtimestamp(r["time"], CN_TZ).date() == date]
34
- else:
35
- if re.fullmatch(r"\d{1,10}", value):
36
- timestamp = int(value)
37
- else:
38
- instant = datetime.fromisoformat(value.replace("Z", "+00:00"))
39
- if instant.tzinfo is None or instant.microsecond:
40
- raise ValueError("explicit timezone and whole seconds required")
41
- timestamp = int(instant.timestamp())
42
- matches = [int(r["time"]) for r in rows if r["time"] == timestamp]
43
- except (ValueError, OverflowError, OSError) as exc:
44
- if isinstance(exc, LineError):
45
- raise
46
- raise LineError("invalid_anchor_time", "时间格式无效;请使用有效日期、带时区的 ISO 时间或 Unix 秒(不是毫秒)。") from exc
47
- if not matches:
48
- raise LineError("anchor_not_found", "该锚点时间不在当前快照的 K 线中,未改线;请核对交易日和图表范围,不要擅自换日期。")
49
- if len(matches) != 1:
50
- raise LineError("ambiguous_anchor_time", "该日期对应多根 K 线,请指定精确的带时区时间或 Unix 秒。")
51
- return matches[0]
52
-
53
-
54
- def edit_trend_line(
55
- payload: dict[str, Any], action: str, *, line_id: str | None = None,
56
- start_time: str | None = None, start_price: float | None = None,
57
- end_time: str | None = None, end_price: float | None = None,
58
- name: str | None = None, color: str | None = None, request_id: str | None = None,
59
- ) -> tuple[dict[str, Any], dict[str, Any]]:
60
- result = deepcopy(payload)
61
- commands = result.get("chartCommands", [])
62
- previous = next((c for c in commands if c.get("type") == TREND_COMMAND and c.get("id") == line_id), None)
63
- if action in {"update", "delete"} and previous is None:
64
- raise LineError("line_not_found", "当前快照不存在该 AI 趋势线,请先读回趋势线 ID。")
65
- if action == "delete":
66
- commands.remove(previous)
67
- result["chartCommands"] = commands
68
- return result, deepcopy(previous)
69
- if action not in {"create", "update"}:
70
- raise LineError("invalid_action", "不支持的趋势线操作。")
71
- if action == "update" and all(v is None for v in (start_time, start_price, end_time, end_price, name, color)):
72
- raise LineError("empty_update", "请至少修改一个锚点、名称或颜色。")
73
- if action == "create" and any(v is None for v in (start_time, start_price, end_time, end_price)):
74
- raise LineError("missing_anchor", "创建趋势线需要两个明确的时间和价格锚点。")
75
- start_price, name, color = validate_line_fields(
76
- price=start_price if start_price is not None else previous["from"]["price"],
77
- name=name, color=color, request_id=request_id)
78
- end_price, _, _ = validate_line_fields(price=end_price if end_price is not None else previous["to"]["price"])
79
- start = {"time": resolve_anchor_time(payload, start_time) if start_time is not None else previous["from"]["time"],
80
- "price": start_price}
81
- end = {"time": resolve_anchor_time(payload, end_time) if end_time is not None else previous["to"]["time"],
82
- "price": end_price}
83
- if start["time"] >= end["time"]:
84
- raise LineError("invalid_anchor_order", "起点时间必须早于终点时间;未自动交换锚点。")
85
- line = {"type": TREND_COMMAND, "id": previous["id"] if previous else "trend_" + secrets.token_hex(12),
86
- "from": start, "to": end,
87
- "label": name if name is not None else previous["label"] if previous else "",
88
- "color": color if color is not None else previous["color"] if previous else "info"}
89
- if previous and previous.get("create_request_id"):
90
- line["create_request_id"] = previous["create_request_id"]
91
- if action == "create":
92
- if request_id:
93
- line["create_request_id"] = request_id
94
- line["id"] = "trend_" + hashlib.sha256(request_id.encode()).hexdigest()[:24]
95
- retry = next((c for c in commands if c.get("type") == TREND_COMMAND and c.get("create_request_id") == request_id), None)
96
- if retry:
97
- if any(retry.get(k) != line[k] for k in ("from", "to", "label", "color")):
98
- raise LineError("request_conflict", "同一 request_id 的绘图参数不同,请使用新的 request_id。")
99
- return result, deepcopy(retry)
100
- if len(trend_lines(result)) >= MAX_LINES:
101
- raise LineError("too_many_lines", "当前图表最多保存 60 条 AI 趋势线。")
102
- commands.append(line)
103
- else:
104
- commands[commands.index(previous)] = line
105
- result["chartCommands"] = commands
106
- return result, deepcopy(line)
@@ -1,149 +0,0 @@
1
- """Persistent, user-local watchlist state shared by dsh_kline clients.
2
-
3
- Charts, conversations and sidebar tabs deliberately have different local
4
- state. A watchlist is different: it is a user collection and must survive
5
- switching conversations or restarting an individual MCP process.
6
- """
7
-
8
- from __future__ import annotations
9
-
10
- import json
11
- import os
12
- import tempfile
13
- import threading
14
- import time
15
- from pathlib import Path
16
- from typing import Any
17
-
18
-
19
- MAX_ITEMS = 200
20
- MAX_GROUPS = 12
21
- _LOCK = threading.RLock()
22
- _MILLISECONDS_THRESHOLD = 100_000_000_000
23
-
24
-
25
- def _state_path() -> Path:
26
- configured = str(os.environ.get("DSH_KLINE_STATE_DIR") or "").strip()
27
- root = Path(configured).expanduser() if configured else Path.home() / ".cache" / "dsh_kline"
28
- return root / "watchlist-v1.json"
29
-
30
-
31
- def _default_state() -> dict[str, Any]:
32
- return {
33
- "version": 1,
34
- "revision": 0,
35
- "updated_at": 0,
36
- "groups": [{"id": "default", "name": "默认分组"}],
37
- "items": [],
38
- "activeGroupId": "default",
39
- "sort": "manual",
40
- }
41
-
42
-
43
- def _normalize_state(value: Any) -> dict[str, Any]:
44
- base = _default_state()
45
- if not isinstance(value, dict):
46
- return base
47
- groups: list[dict[str, str]] = []
48
- seen_groups: set[str] = set()
49
- for raw in value.get("groups") if isinstance(value.get("groups"), list) else []:
50
- if not isinstance(raw, dict):
51
- continue
52
- group_id = str(raw.get("id") or "").strip()[:48]
53
- name = str(raw.get("name") or "").strip()[:24]
54
- if not group_id or not name or group_id in seen_groups:
55
- continue
56
- seen_groups.add(group_id)
57
- groups.append({"id": group_id, "name": name})
58
- if len(groups) >= MAX_GROUPS:
59
- break
60
- if "default" not in seen_groups:
61
- groups.insert(0, {"id": "default", "name": "默认分组"})
62
- groups = groups[:MAX_GROUPS]
63
- allowed = {group["id"] for group in groups}
64
- items: list[dict[str, str]] = []
65
- seen_items: set[tuple[str, str]] = set()
66
- for raw in value.get("items") if isinstance(value.get("items"), list) else []:
67
- if not isinstance(raw, dict):
68
- continue
69
- symbol = str(raw.get("symbol") or "").strip().upper()[:64]
70
- name = str(raw.get("name") or symbol).strip()[:80]
71
- group_id = str(raw.get("groupId") or raw.get("group_id") or "default").strip()[:48]
72
- key = (symbol, group_id)
73
- if not symbol or group_id not in allowed or key in seen_items:
74
- continue
75
- seen_items.add(key)
76
- items.append({"symbol": symbol, "name": name or symbol, "groupId": group_id})
77
- if len(items) >= MAX_ITEMS:
78
- break
79
- active = str(value.get("activeGroupId") or value.get("active_group_id") or "default")
80
- if active not in allowed:
81
- active = "default"
82
- updated_at = max(0, int(value.get("updated_at") or 0))
83
- # Early development builds wrote seconds. Persist milliseconds from now
84
- # on so client edits made in the same second remain orderable.
85
- if 0 < updated_at < _MILLISECONDS_THRESHOLD:
86
- updated_at *= 1000
87
- return {
88
- "version": 1,
89
- "revision": max(0, int(value.get("revision") or 0)),
90
- "updated_at": updated_at,
91
- "groups": groups,
92
- "items": items,
93
- "activeGroupId": active,
94
- "sort": value.get("sort") if value.get("sort") in {"manual", "change_desc", "change_asc"} else "manual",
95
- }
96
-
97
-
98
- def get_watchlist_state() -> dict[str, Any]:
99
- """Read the user-local watchlist; missing/corrupt files safely become empty."""
100
- with _LOCK:
101
- try:
102
- raw = json.loads(_state_path().read_text(encoding="utf-8"))
103
- except (OSError, TypeError, ValueError):
104
- raw = None
105
- return _normalize_state(raw)
106
-
107
-
108
- def save_watchlist_state(state: Any) -> dict[str, Any]:
109
- """Atomically persist a complete validated user watchlist and return it.
110
-
111
- A browser sends the revision it last read. Rejecting a stale write gives
112
- it a chance to reconcile instead of silently overwriting edits made in a
113
- different conversation or DSH instance.
114
- """
115
- with _LOCK:
116
- previous = get_watchlist_state()
117
- expected_revision: int | None = None
118
- if isinstance(state, dict) and "revision" in state:
119
- try:
120
- expected_revision = max(0, int(state.get("revision")))
121
- except (TypeError, ValueError):
122
- return {"ok": False, "error": "watchlist_invalid_revision", "message": "自选版本号无效"}
123
- if expected_revision is not None and expected_revision != previous["revision"]:
124
- return {
125
- "ok": False,
126
- "error": "watchlist_conflict",
127
- "message": "自选已在另一处更新,请同步后重试",
128
- "watchlist": previous,
129
- }
130
- normalized = _normalize_state(state)
131
- normalized["revision"] = previous["revision"] + 1
132
- normalized["updated_at"] = time.time_ns() // 1_000_000
133
- path = _state_path()
134
- try:
135
- path.parent.mkdir(parents=True, exist_ok=True)
136
- descriptor, temporary_name = tempfile.mkstemp(prefix="watchlist-", suffix=".tmp", dir=path.parent)
137
- with os.fdopen(descriptor, "w", encoding="utf-8") as handle:
138
- json.dump(normalized, handle, ensure_ascii=False, separators=(",", ":"))
139
- handle.flush()
140
- os.fsync(handle.fileno())
141
- os.chmod(temporary_name, 0o600)
142
- os.replace(temporary_name, path)
143
- except OSError as exc:
144
- try:
145
- os.unlink(temporary_name)
146
- except (OSError, UnboundLocalError):
147
- pass
148
- return {"ok": False, "error": "watchlist_persist_failed", "message": f"无法保存自选:{exc}"}
149
- return {"ok": True, "watchlist": normalized}