@ftshare-lab/dsh-kline 0.0.0-stage → 0.6.10
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.
- package/CHANGELOG.md +601 -0
- package/LICENSE +21 -0
- package/PROVENANCE.md +13 -0
- package/README.en.md +116 -0
- package/README.md +115 -2
- package/chart_service.py +687 -0
- package/config/basic-symbols.json +570 -0
- package/config/dsh-kline.patch.yml +4 -0
- package/config/dsh-tool-catalog.json +3875 -0
- package/cordis.patch.yml +33 -0
- package/core/__init__.py +0 -0
- package/core/adjustment.py +16 -0
- package/core/calc.py +691 -0
- package/core/rows.py +228 -0
- package/core/ta_engine.py +99 -0
- package/docs/anonymous-market-support.md +33 -0
- package/docs/automatic-drawing.md +24 -0
- package/docs/chart-functions.md +136 -0
- package/docs/drawing-examples.en.md +13 -0
- package/docs/drawing-examples.md +13 -0
- package/docs/embedding.md +43 -0
- package/docs/fixtures/price-pattern-real-v1.json +1 -0
- package/docs/free-foreign-daily.md +44 -0
- package/docs/guide.en.md +232 -0
- package/docs/guide.md +248 -0
- package/docs/images/abc-drawing-v0.5.0.jpg +0 -0
- package/docs/images/channel-drawing-v0.5.0.jpg +0 -0
- package/docs/images/drawing-workbench-v0.5.0.jpg +0 -0
- package/docs/images/dsh-kline-tab-workspace.png +0 -0
- package/docs/images/dsh-market.png +0 -0
- package/docs/images/kline-news.png +0 -0
- package/docs/images/kline-range-stats.png +0 -0
- package/docs/images/kline-support.png +0 -0
- package/docs/images/main-chart-comparison-v0.6.9.png +0 -0
- package/docs/images/market-overview-v0.6.9.png +0 -0
- package/docs/images/natural-language-abc-wolong-2026-10-27.png +0 -0
- package/docs/images/natural-language-descending-channel-wolong-2026-10-27.png +0 -0
- package/docs/images/platform-breakout-msft-v0.6.9.png +0 -0
- package/docs/npm-release.md +33 -0
- package/docs/price-pattern-rules-v1.md +40 -0
- package/docs/price-pattern-samples-v1.md +42 -0
- package/docs/provider-adaptation.md +73 -0
- package/docs/release-acceptance-v0.4.0.md +46 -0
- package/docs/release-acceptance-v0.4.1.md +43 -0
- package/docs/release-acceptance-v0.5.0.md +40 -0
- package/docs/release-acceptance-v0.6.0.md +33 -0
- package/docs/release-acceptance-v0.6.1.md +19 -0
- package/docs/release-acceptance-v0.6.10.md +21 -0
- package/docs/release-acceptance-v0.6.2.md +31 -0
- package/docs/release-acceptance-v0.6.3.md +25 -0
- package/docs/release-acceptance-v0.6.4.md +24 -0
- package/docs/release-acceptance-v0.6.5.md +21 -0
- package/docs/release-acceptance-v0.6.6.md +21 -0
- package/docs/release-acceptance-v0.6.7.md +18 -0
- package/docs/release-acceptance-v0.6.8.md +18 -0
- package/docs/release-acceptance-v0.6.9.md +98 -0
- package/docs/release-notes-v0.5.0.md +23 -0
- package/docs/release-notes-v0.6.0.md +11 -0
- package/docs/release-notes-v0.6.1.md +20 -0
- package/docs/release-notes-v0.6.10.md +11 -0
- package/docs/release-notes-v0.6.2.md +14 -0
- package/docs/release-notes-v0.6.3.md +26 -0
- package/docs/release-notes-v0.6.4.md +12 -0
- package/docs/release-notes-v0.6.5.md +13 -0
- package/docs/release-notes-v0.6.6.md +13 -0
- package/docs/release-notes-v0.6.7.md +17 -0
- package/docs/release-notes-v0.6.8.md +10 -0
- package/docs/release-notes-v0.6.9.md +16 -0
- package/lib/candle-sequence.js +15 -0
- package/lib/chart-adjustment.js +7 -0
- package/lib/chart-annotations.js +33 -0
- package/lib/chart-applications.js +171 -0
- package/lib/chart-context.js +164 -0
- package/lib/chart-observation.js +251 -0
- package/lib/chart-service-status.js +82 -0
- package/lib/chart-source-status.js +39 -0
- package/lib/chart-sources.js +354 -0
- package/lib/client/BetterSidebarTab.js +70 -0
- package/lib/client/ClassicShell.js +254 -0
- package/lib/client/KlineContent.js +155 -0
- package/lib/client/chart-apply.js +73 -0
- package/lib/client/chart-context.js +233 -0
- package/lib/client/chart-handoff.js +34 -0
- package/lib/client/chart-session-resolver.js +74 -0
- package/lib/client/client-context.js +1 -0
- package/lib/client/conversation.js +88 -0
- package/lib/client/default-tab.js +83 -0
- package/lib/client/embed.js +50 -0
- package/lib/client/generated-view.js +12983 -0
- package/lib/client/horizontal-lines.js +19 -0
- package/lib/client/index.js +62 -0
- package/lib/client/mode-preferences.js +28 -0
- package/lib/client/native-sidebar-contract.js +45 -0
- package/lib/client/native-sidebar-register.js +133 -0
- package/lib/client/native-sidebar-services.js +1 -0
- package/lib/client/native-sidebar.js +96 -0
- package/lib/client/sidebar-integration.js +93 -0
- package/lib/client/ui-onboarding.js +42 -0
- package/lib/client/version.js +14 -0
- package/lib/client.js +17382 -0
- package/lib/client.js.map +1 -0
- package/lib/drawing-feedback.js +284 -0
- package/lib/fibonacci.js +18 -0
- package/lib/ftshare-settings-bridge.js +159 -0
- package/lib/index.js +279 -0
- package/lib/labeled-polyline.js +17 -0
- package/lib/pattern-groups.js +91 -0
- package/lib/price-bands.js +55 -0
- package/lib/price-series.js +47 -0
- package/lib/price-sticks.js +32 -0
- package/lib/types/candle-sequence.d.ts +2 -0
- package/lib/types/chart-adjustment.d.ts +2 -0
- package/lib/types/chart-annotations.d.ts +4 -0
- package/lib/types/chart-applications.d.ts +26 -0
- package/lib/types/chart-context.d.ts +14 -0
- package/lib/types/chart-observation.d.ts +8 -0
- package/lib/types/chart-service-status.d.ts +22 -0
- package/lib/types/chart-source-status.d.ts +47 -0
- package/lib/types/chart-sources.d.ts +25 -0
- package/lib/types/client/BetterSidebarTab.d.ts +12 -0
- package/lib/types/client/ClassicShell.d.ts +4 -0
- package/lib/types/client/KlineContent.d.ts +37 -0
- package/lib/types/client/chart-apply.d.ts +13 -0
- package/lib/types/client/chart-context.d.ts +23 -0
- package/lib/types/client/chart-handoff.d.ts +5 -0
- package/lib/types/client/chart-session-resolver.d.ts +2 -0
- package/lib/types/client/client-context.d.ts +14 -0
- package/lib/types/client/conversation.d.ts +43 -0
- package/lib/types/client/default-tab.d.ts +3 -0
- package/lib/types/client/embed.d.ts +37 -0
- package/lib/types/client/generated-view.d.ts +2 -0
- package/lib/types/client/horizontal-lines.d.ts +1 -0
- package/lib/types/client/index.d.ts +4 -0
- package/lib/types/client/mode-preferences.d.ts +13 -0
- package/lib/types/client/native-sidebar-contract.d.ts +52 -0
- package/lib/types/client/native-sidebar-register.d.ts +46 -0
- package/lib/types/client/native-sidebar-services.d.ts +45 -0
- package/lib/types/client/native-sidebar.d.ts +47 -0
- package/lib/types/client/sidebar-integration.d.ts +12 -0
- package/lib/types/client/ui-onboarding.d.ts +6 -0
- package/lib/types/client/version.d.ts +1 -0
- package/lib/types/drawing-feedback.d.ts +5 -0
- package/lib/types/fibonacci.d.ts +5 -0
- package/lib/types/ftshare-settings-bridge.d.ts +50 -0
- package/lib/types/index.d.ts +26 -0
- package/lib/types/labeled-polyline.d.ts +11 -0
- package/lib/types/pattern-groups.d.ts +2 -0
- package/lib/types/price-bands.d.ts +3 -0
- package/lib/types/price-series.d.ts +5 -0
- package/lib/types/price-sticks.d.ts +3 -0
- package/package.json +153 -4
- package/requirements.txt +6 -0
- package/screenshots.json +11 -0
- package/scripts/bootstrap.sh +5 -0
- package/scripts/dsh-bootstrap.mjs +179 -0
- package/scripts/dsh-mcp-plugin.mjs +27 -0
- package/scripts/run-dsh-kline.mjs +658 -0
- package/scripts/run-dsh-kline.sh +5 -0
- package/server.py +1755 -0
- package/tools/__init__.py +0 -0
- package/tools/annotations.py +119 -0
- package/tools/automatic_analysis.py +158 -0
- package/tools/baostock_source.py +176 -0
- package/tools/calc.py +39 -0
- package/tools/channel_candidates.py +260 -0
- package/tools/channel_preview.py +82 -0
- package/tools/channels.py +104 -0
- package/tools/chart_applications.py +204 -0
- package/tools/chart_context.py +186 -0
- package/tools/chart_edits.py +363 -0
- package/tools/chart_functions.py +451 -0
- package/tools/chart_indicators.py +65 -0
- package/tools/chart_measurements.py +84 -0
- package/tools/chart_source_status.py +32 -0
- package/tools/chart_sources.py +31 -0
- package/tools/closed_daily.py +68 -0
- package/tools/draw.py +410 -0
- package/tools/drawing_feedback.py +45 -0
- package/tools/drawing_interaction.py +117 -0
- package/tools/drawing_verification.py +141 -0
- package/tools/fetch.py +4680 -0
- package/tools/fibonacci.py +83 -0
- package/tools/foreign_daily.py +185 -0
- package/tools/free_sources.py +483 -0
- package/tools/lines.py +91 -0
- package/tools/nine_count.py +66 -0
- package/tools/pattern_groups.py +103 -0
- package/tools/pivots.py +60 -0
- package/tools/polylines.py +131 -0
- package/tools/price_bands.py +165 -0
- package/tools/price_patterns.py +311 -0
- package/tools/price_series.py +162 -0
- package/tools/price_sticks.py +114 -0
- package/tools/range_candidates.py +170 -0
- package/tools/recent_drawing_candidates.py +123 -0
- package/tools/rectangles.py +76 -0
- package/tools/regression_channels.py +87 -0
- package/tools/ta_functions.py +228 -0
- package/tools/trend_lines.py +106 -0
- package/tools/watchlist.py +149 -0
- package/view/ft-logo.jpg +0 -0
- package/view/kline.html +12436 -0
- package/view/vendor/klinecharts.min.js +7 -0
|
@@ -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}
|
|
@@ -0,0 +1,106 @@
|
|
|
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)
|
|
@@ -0,0 +1,149 @@
|
|
|
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}
|
package/view/ft-logo.jpg
ADDED
|
Binary file
|