@dsh-ft/dsh-fft-paper-trading 0.7.0 → 0.7.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.
- package/lib/client.js +9 -1
- package/package.json +2 -5
- package/src/client/index.js +8 -0
- package/node_modules/@ftshare-lab/dsh-kline/CHANGELOG.md +0 -564
- package/node_modules/@ftshare-lab/dsh-kline/LICENSE +0 -21
- package/node_modules/@ftshare-lab/dsh-kline/PROVENANCE.md +0 -13
- package/node_modules/@ftshare-lab/dsh-kline/README.en.md +0 -265
- package/node_modules/@ftshare-lab/dsh-kline/README.md +0 -281
- package/node_modules/@ftshare-lab/dsh-kline/chart_service.py +0 -686
- package/node_modules/@ftshare-lab/dsh-kline/config/basic-symbols.json +0 -570
- package/node_modules/@ftshare-lab/dsh-kline/config/dsh-kline.patch.yml +0 -4
- package/node_modules/@ftshare-lab/dsh-kline/config/dsh-tool-catalog.json +0 -3783
- package/node_modules/@ftshare-lab/dsh-kline/cordis.patch.yml +0 -33
- package/node_modules/@ftshare-lab/dsh-kline/core/__init__.py +0 -0
- package/node_modules/@ftshare-lab/dsh-kline/core/adjustment.py +0 -16
- package/node_modules/@ftshare-lab/dsh-kline/core/calc.py +0 -683
- package/node_modules/@ftshare-lab/dsh-kline/core/rows.py +0 -228
- package/node_modules/@ftshare-lab/dsh-kline/core/ta_engine.py +0 -99
- package/node_modules/@ftshare-lab/dsh-kline/lib/candle-sequence.js +0 -15
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-adjustment.js +0 -7
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-annotations.js +0 -33
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-applications.js +0 -171
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-context.js +0 -164
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-observation.js +0 -241
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-service-status.js +0 -82
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-source-status.js +0 -39
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-sources.js +0 -349
- package/node_modules/@ftshare-lab/dsh-kline/lib/client.js +0 -15445
- package/node_modules/@ftshare-lab/dsh-kline/lib/drawing-feedback.js +0 -252
- package/node_modules/@ftshare-lab/dsh-kline/lib/fibonacci.js +0 -18
- package/node_modules/@ftshare-lab/dsh-kline/lib/ftshare-settings-bridge.js +0 -159
- package/node_modules/@ftshare-lab/dsh-kline/lib/index.js +0 -279
- package/node_modules/@ftshare-lab/dsh-kline/lib/labeled-polyline.js +0 -17
- package/node_modules/@ftshare-lab/dsh-kline/lib/price-bands.js +0 -55
- package/node_modules/@ftshare-lab/dsh-kline/lib/price-series.js +0 -47
- package/node_modules/@ftshare-lab/dsh-kline/lib/price-sticks.js +0 -32
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/candle-sequence.d.ts +0 -2
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-adjustment.d.ts +0 -2
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-annotations.d.ts +0 -4
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-applications.d.ts +0 -26
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-context.d.ts +0 -14
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-observation.d.ts +0 -8
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-service-status.d.ts +0 -22
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-source-status.d.ts +0 -47
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-sources.d.ts +0 -25
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/BetterSidebarTab.d.ts +0 -12
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/ClassicShell.d.ts +0 -4
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/KlineContent.d.ts +0 -37
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/PaperKlinePanel.d.ts +0 -15
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/canvas-panel.d.ts +0 -33
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/chart-apply.d.ts +0 -13
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/chart-context.d.ts +0 -23
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/chart-session-resolver.d.ts +0 -2
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/client-context.d.ts +0 -14
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/conversation.d.ts +0 -39
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/default-tab.d.ts +0 -3
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/embed.d.ts +0 -37
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/generated-view.d.ts +0 -2
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/horizontal-lines.d.ts +0 -1
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/host-services.d.ts +0 -55
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/index.d.ts +0 -4
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/mode-preferences.d.ts +0 -13
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar-contract.d.ts +0 -52
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar-register.d.ts +0 -46
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar-services.d.ts +0 -45
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar.d.ts +0 -47
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/sidebar-integration.d.ts +0 -12
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/ui-onboarding.d.ts +0 -13
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/version.d.ts +0 -1
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/drawing-feedback.d.ts +0 -5
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/fibonacci.d.ts +0 -5
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/ftshare-settings-bridge.d.ts +0 -50
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/index.d.ts +0 -26
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/labeled-polyline.d.ts +0 -11
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/price-bands.d.ts +0 -3
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/price-series.d.ts +0 -5
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/price-sticks.d.ts +0 -3
- package/node_modules/@ftshare-lab/dsh-kline/package.json +0 -136
- package/node_modules/@ftshare-lab/dsh-kline/requirements.txt +0 -6
- package/node_modules/@ftshare-lab/dsh-kline/scripts/bootstrap.sh +0 -5
- package/node_modules/@ftshare-lab/dsh-kline/scripts/dsh-bootstrap.mjs +0 -179
- package/node_modules/@ftshare-lab/dsh-kline/scripts/dsh-mcp-plugin.mjs +0 -27
- package/node_modules/@ftshare-lab/dsh-kline/scripts/run-dsh-kline.mjs +0 -655
- package/node_modules/@ftshare-lab/dsh-kline/scripts/run-dsh-kline.sh +0 -5
- package/node_modules/@ftshare-lab/dsh-kline/server.py +0 -1734
- package/node_modules/@ftshare-lab/dsh-kline/tools/__init__.py +0 -0
- package/node_modules/@ftshare-lab/dsh-kline/tools/annotations.py +0 -119
- package/node_modules/@ftshare-lab/dsh-kline/tools/baostock_source.py +0 -176
- package/node_modules/@ftshare-lab/dsh-kline/tools/calc.py +0 -39
- package/node_modules/@ftshare-lab/dsh-kline/tools/channel_candidates.py +0 -260
- package/node_modules/@ftshare-lab/dsh-kline/tools/channel_preview.py +0 -82
- package/node_modules/@ftshare-lab/dsh-kline/tools/channels.py +0 -104
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_applications.py +0 -204
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_context.py +0 -186
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_edits.py +0 -345
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_functions.py +0 -466
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_indicators.py +0 -63
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_measurements.py +0 -84
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_source_status.py +0 -32
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_sources.py +0 -31
- package/node_modules/@ftshare-lab/dsh-kline/tools/draw.py +0 -394
- package/node_modules/@ftshare-lab/dsh-kline/tools/drawing_feedback.py +0 -45
- package/node_modules/@ftshare-lab/dsh-kline/tools/drawing_interaction.py +0 -117
- package/node_modules/@ftshare-lab/dsh-kline/tools/drawing_verification.py +0 -141
- package/node_modules/@ftshare-lab/dsh-kline/tools/fetch.py +0 -4681
- package/node_modules/@ftshare-lab/dsh-kline/tools/fibonacci.py +0 -83
- package/node_modules/@ftshare-lab/dsh-kline/tools/foreign_daily.py +0 -185
- package/node_modules/@ftshare-lab/dsh-kline/tools/free_sources.py +0 -483
- package/node_modules/@ftshare-lab/dsh-kline/tools/lines.py +0 -91
- package/node_modules/@ftshare-lab/dsh-kline/tools/pivots.py +0 -60
- package/node_modules/@ftshare-lab/dsh-kline/tools/polylines.py +0 -125
- package/node_modules/@ftshare-lab/dsh-kline/tools/price_bands.py +0 -165
- package/node_modules/@ftshare-lab/dsh-kline/tools/price_series.py +0 -162
- package/node_modules/@ftshare-lab/dsh-kline/tools/price_sticks.py +0 -114
- package/node_modules/@ftshare-lab/dsh-kline/tools/range_candidates.py +0 -170
- package/node_modules/@ftshare-lab/dsh-kline/tools/rectangles.py +0 -76
- package/node_modules/@ftshare-lab/dsh-kline/tools/regression_channels.py +0 -87
- package/node_modules/@ftshare-lab/dsh-kline/tools/ta_functions.py +0 -228
- package/node_modules/@ftshare-lab/dsh-kline/tools/trend_lines.py +0 -106
- package/node_modules/@ftshare-lab/dsh-kline/tools/watchlist.py +0 -149
- package/node_modules/@ftshare-lab/dsh-kline/view/ft-logo.jpg +0 -0
- package/node_modules/@ftshare-lab/dsh-kline/view/vendor/klinecharts.min.js +0 -7
|
@@ -1,82 +0,0 @@
|
|
|
1
|
-
"""Read-only arithmetic for a host-chosen channel, not fitting or recognition."""
|
|
2
|
-
from __future__ import annotations
|
|
3
|
-
|
|
4
|
-
from datetime import datetime
|
|
5
|
-
import math
|
|
6
|
-
from typing import Any
|
|
7
|
-
|
|
8
|
-
from tools.channels import channel_geometry
|
|
9
|
-
from tools.lines import LineError, validate_line_fields
|
|
10
|
-
from tools.trend_lines import CN_TZ, resolve_anchor_time
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
def preview_channel(rows: list[dict], interval: str, *, start_time: str, start_price: float,
|
|
14
|
-
end_time: str, end_price: float, parallel_time: str, parallel_price: float,
|
|
15
|
-
bar_limit: int = 200) -> dict[str, Any]:
|
|
16
|
-
"""Rows have already passed live-observation validation; never fetch or publish."""
|
|
17
|
-
if isinstance(bar_limit, bool) or not isinstance(bar_limit, int) or not 1 <= bar_limit <= 4000:
|
|
18
|
-
raise LineError("invalid_preview_limit", "bar_limit 为1至4000整数;汇总始终核对完整起止区间。")
|
|
19
|
-
source = {"interval": interval, "chartCommands": [{"type": "SET_CANDLES", "rows": rows}]}
|
|
20
|
-
anchors = []
|
|
21
|
-
for timestamp, price in ((start_time, start_price), (end_time, end_price), (parallel_time, parallel_price)):
|
|
22
|
-
price, _, _ = validate_line_fields(price=price)
|
|
23
|
-
if price is None:
|
|
24
|
-
raise LineError("invalid_price", "三个锚点都需要明确的有限正价格。")
|
|
25
|
-
anchors.append({"time": resolve_anchor_time(source, timestamp), "price": price})
|
|
26
|
-
start, end, parallel = anchors
|
|
27
|
-
geometry = channel_geometry(source, start, end, parallel)
|
|
28
|
-
region = [row for row in rows if start["time"] <= row["time"] <= end["time"]]
|
|
29
|
-
if len(region) > 4000:
|
|
30
|
-
raise LineError("measurement_capacity", "通道核对区间超过4000根;未使用截断样本代替全区间。")
|
|
31
|
-
# Only numerical roundoff, not a subjective touch/fitting tolerance. Keep
|
|
32
|
-
# signed raw distances unrounded and expose the allowance used by counts.
|
|
33
|
-
scale = max(*(a["price"] for edge in ("upper", "lower") for a in geometry[edge].values()),
|
|
34
|
-
*(row[field] for row in region for field in ("low", "high")))
|
|
35
|
-
epsilon = scale * 1e-12
|
|
36
|
-
measured = []
|
|
37
|
-
for index, row in enumerate(region):
|
|
38
|
-
upper = geometry["upper"]["from"]["price"] + geometry["slope_per_bar"] * index
|
|
39
|
-
lower = geometry["lower"]["from"]["price"] + geometry["slope_per_bar"] * index
|
|
40
|
-
values = {"high_minus_upper": row["high"] - upper, "low_minus_lower": row["low"] - lower,
|
|
41
|
-
"body_high_minus_upper": max(row["open"], row["close"]) - upper,
|
|
42
|
-
"body_low_minus_lower": min(row["open"], row["close"]) - lower}
|
|
43
|
-
if not all(math.isfinite(v) for v in (upper, lower, *values.values())):
|
|
44
|
-
raise LineError("nonfinite_channel_measurement", "通道偏差计算超出有限数值范围,未输出部分核对结果。")
|
|
45
|
-
try:
|
|
46
|
-
instant = datetime.fromtimestamp(row["time"], CN_TZ)
|
|
47
|
-
date, iso = instant.date().isoformat(), instant.isoformat(timespec="seconds")
|
|
48
|
-
except (ValueError, OverflowError, OSError):
|
|
49
|
-
date, iso = None, None
|
|
50
|
-
measured.append({"time": row["time"], "date": date, "iso": iso,
|
|
51
|
-
"bar_offset": index, "upper_price": upper, "lower_price": lower,
|
|
52
|
-
"ohlc": {k: row[k] for k in ("open", "high", "low", "close")}, **values})
|
|
53
|
-
summary = {}
|
|
54
|
-
for key, field, sign in (("wick_above", "high_minus_upper", 1), ("wick_below", "low_minus_lower", -1),
|
|
55
|
-
("body_above", "body_high_minus_upper", 1), ("body_below", "body_low_minus_lower", -1)):
|
|
56
|
-
distances = [bar[field] * sign for bar in measured]
|
|
57
|
-
maximum = max(distances)
|
|
58
|
-
witness = measured[distances.index(maximum)]
|
|
59
|
-
summary[key] = {"bar_count": sum(d > epsilon for d in distances),
|
|
60
|
-
"max_price_excess": max(0, maximum),
|
|
61
|
-
"max_excess_witness": {k: witness[k] for k in ("time", "date", "iso", "bar_offset")}
|
|
62
|
-
if maximum > epsilon else None}
|
|
63
|
-
provenance = []
|
|
64
|
-
by_time = {r["time"]: r for r in region}
|
|
65
|
-
for anchor in anchors:
|
|
66
|
-
row = by_time[anchor["time"]]
|
|
67
|
-
provenance.append({**anchor, "exact_matching_ohlc_fields": [k for k in ("open", "high", "low", "close")
|
|
68
|
-
if row[k] == anchor["price"]],
|
|
69
|
-
"price_origin": "caller_supplied_not_selected_by_plugin"})
|
|
70
|
-
return {"schema_version": 1, "evidence_scope": "loaded_browser_candles",
|
|
71
|
-
"range_policy": "inclusive_start_end_only_no_extension", "bar_count": len(region),
|
|
72
|
-
"anchors": dict(zip(("from", "to", "parallel"), provenance)), "geometry": geometry,
|
|
73
|
-
"numeric_policy": {"arithmetic": "float64_unrounded_signed_distances",
|
|
74
|
-
"count_roundoff_allowance": epsilon, "allowance_basis": "max_boundary_and_region_wick_price_times_1e-12",
|
|
75
|
-
"meaning": "numerical_roundoff_only_not_market_touch_tolerance"},
|
|
76
|
-
"distance_convention": "positive high_minus_upper is above; negative low_minus_lower is below; body fields use open/close extrema",
|
|
77
|
-
"summary": summary, "bars": measured[:bar_limit],
|
|
78
|
-
"bar_selection": {"total": len(measured), "returned": min(bar_limit, len(measured)),
|
|
79
|
-
"truncated": len(measured) > bar_limit, "order": "ascending", "sample": "first_limit",
|
|
80
|
-
"summary_scope": "full_inclusive_region"},
|
|
81
|
-
"pattern_classification": "not_provided", "touch_count": "not_provided",
|
|
82
|
-
"quality_score": "not_provided", "drawing_created": False, "render_verified": False}
|
|
@@ -1,104 +0,0 @@
|
|
|
1
|
-
"""Three-anchor, finite parallel price channels on the chart's candle-index axis."""
|
|
2
|
-
from __future__ import annotations
|
|
3
|
-
|
|
4
|
-
from copy import deepcopy
|
|
5
|
-
import hashlib
|
|
6
|
-
import math
|
|
7
|
-
import secrets
|
|
8
|
-
from typing import Any
|
|
9
|
-
|
|
10
|
-
from tools.lines import LineError, validate_line_fields
|
|
11
|
-
from tools.trend_lines import resolve_anchor_time
|
|
12
|
-
|
|
13
|
-
CHANNEL_COMMAND = "DRAW_AGENT_CHANNEL"
|
|
14
|
-
MAX_CHANNELS = 30
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
def channels(payload: dict[str, Any]) -> list[dict[str, Any]]:
|
|
18
|
-
return deepcopy([c for c in payload.get("chartCommands", []) if c.get("type") == CHANNEL_COMMAND])
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
def channel_geometry(payload: dict[str, Any], start: dict, end: dict, parallel: dict) -> dict[str, Any]:
|
|
22
|
-
rows = next((c.get("rows", []) for c in payload.get("chartCommands", []) if c.get("type") == "SET_CANDLES"), [])
|
|
23
|
-
times = [r["time"] for r in rows]
|
|
24
|
-
if any(times.count(a["time"]) != 1 for a in (start, end, parallel)) or any(a >= b for a, b in zip(times, times[1:])):
|
|
25
|
-
raise LineError("invalid_channel_rows", "通道需要唯一、按时间递增的 K 线锚点。")
|
|
26
|
-
if start["time"] >= end["time"]:
|
|
27
|
-
raise LineError("invalid_anchor_order", "通道起点必须早于终点,未自动交换锚点。")
|
|
28
|
-
if not start["time"] <= parallel["time"] <= end["time"]:
|
|
29
|
-
raise LineError("parallel_anchor_outside", "第三点必须位于起止时间范围内;请明确指定,不自动挪动。")
|
|
30
|
-
i, j, k = (times.index(a["time"]) for a in (start, end, parallel))
|
|
31
|
-
# Candles are equally spaced on screen, even across weekends/holidays.
|
|
32
|
-
slope = (end["price"] - start["price"]) / (j - i)
|
|
33
|
-
offset = parallel["price"] - (start["price"] + slope * (k - i))
|
|
34
|
-
tolerance = max(start["price"], end["price"], parallel["price"]) * 1e-12
|
|
35
|
-
if not math.isfinite(offset) or abs(offset) <= tolerance:
|
|
36
|
-
raise LineError("zero_channel_width", "第三点落在基准线上,不能形成有宽度的通道。")
|
|
37
|
-
other = {"from": {"time": start["time"], "price": start["price"] + offset},
|
|
38
|
-
"to": {"time": end["time"], "price": end["price"] + offset}}
|
|
39
|
-
if any(not math.isfinite(a["price"]) or a["price"] <= 0 for a in other.values()):
|
|
40
|
-
raise LineError("invalid_channel_boundary", "推导后的平行边界价格必须大于零且有限,请调整第三点。")
|
|
41
|
-
base = {"from": deepcopy(start), "to": deepcopy(end)}
|
|
42
|
-
upper, lower = (other, base) if offset > 0 else (base, other)
|
|
43
|
-
return {"upper": upper, "lower": lower, "width": abs(offset), "signed_offset": offset,
|
|
44
|
-
"slope_per_bar": slope, "direction": "ascending" if slope > 0 else "descending" if slope < 0 else "horizontal",
|
|
45
|
-
"geometry_basis": "candle_index_linear_price"}
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
def edit_channel(
|
|
49
|
-
payload: dict[str, Any], action: str, *, channel_id: str | None = None,
|
|
50
|
-
start_time: str | None = None, start_price: float | None = None,
|
|
51
|
-
end_time: str | None = None, end_price: float | None = None,
|
|
52
|
-
parallel_time: str | None = None, parallel_price: float | None = None,
|
|
53
|
-
name: str | None = None, color: str | None = None,
|
|
54
|
-
show_midline: bool | None = None, request_id: str | None = None,
|
|
55
|
-
) -> tuple[dict[str, Any], dict[str, Any]]:
|
|
56
|
-
result = deepcopy(payload)
|
|
57
|
-
commands = result.get("chartCommands", [])
|
|
58
|
-
previous = next((c for c in commands if c.get("type") == CHANNEL_COMMAND and c.get("id") == channel_id), None)
|
|
59
|
-
if action in {"update", "delete"} and previous is None:
|
|
60
|
-
raise LineError("channel_not_found", "当前快照不存在该 AI 通道,请先读取通道 ID。")
|
|
61
|
-
if action == "delete":
|
|
62
|
-
commands.remove(previous); result["chartCommands"] = commands
|
|
63
|
-
return result, deepcopy(previous)
|
|
64
|
-
if action not in {"create", "update"}:
|
|
65
|
-
raise LineError("invalid_action", "不支持的通道操作。")
|
|
66
|
-
values = (start_time, start_price, end_time, end_price, parallel_time, parallel_price)
|
|
67
|
-
if action == "create" and any(v is None for v in values):
|
|
68
|
-
raise LineError("missing_anchor", "创建通道需要基准线两点及第三个平行边界锚点,每点明确时间和价格。")
|
|
69
|
-
if action == "update" and all(v is None for v in (*values, name, color, show_midline)):
|
|
70
|
-
raise LineError("empty_update", "请至少修改一个锚点、名称、颜色或中线开关。")
|
|
71
|
-
if show_midline is not None and not isinstance(show_midline, bool):
|
|
72
|
-
raise LineError("invalid_midline", "show_midline 必须是布尔值。")
|
|
73
|
-
_, name, color = validate_line_fields(name=name, color=color, request_id=request_id)
|
|
74
|
-
anchors = []
|
|
75
|
-
for key, time, price in (("from", start_time, start_price), ("to", end_time, end_price), ("parallel", parallel_time, parallel_price)):
|
|
76
|
-
old = previous.get(key, {}) if previous else {}
|
|
77
|
-
value, _, _ = validate_line_fields(price=price if price is not None else old.get("price"))
|
|
78
|
-
anchors.append({"time": resolve_anchor_time(payload, time) if time is not None else old["time"], "price": value})
|
|
79
|
-
start, end, parallel = anchors
|
|
80
|
-
geometry = channel_geometry(payload, start, end, parallel)
|
|
81
|
-
channel = {"type": CHANNEL_COMMAND, "id": previous["id"] if previous else "channel_" + secrets.token_hex(12),
|
|
82
|
-
"interval": payload.get("interval"), "from": start, "to": end, "parallel": parallel,
|
|
83
|
-
"label": name if name is not None else previous["label"] if previous else "",
|
|
84
|
-
"color": color if color is not None else previous["color"] if previous else "info",
|
|
85
|
-
"show_midline": show_midline if show_midline is not None else previous["show_midline"] if previous else True,
|
|
86
|
-
**geometry}
|
|
87
|
-
if previous and previous.get("create_request_id"):
|
|
88
|
-
channel["create_request_id"] = previous["create_request_id"]
|
|
89
|
-
if action == "create":
|
|
90
|
-
if request_id:
|
|
91
|
-
channel["create_request_id"] = request_id
|
|
92
|
-
channel["id"] = "channel_" + hashlib.sha256(request_id.encode()).hexdigest()[:24]
|
|
93
|
-
retry = next((c for c in commands if c.get("type") == CHANNEL_COMMAND and c.get("create_request_id") == request_id), None)
|
|
94
|
-
if retry:
|
|
95
|
-
if any(retry.get(k) != channel[k] for k in ("from", "to", "parallel", "label", "color", "show_midline")):
|
|
96
|
-
raise LineError("request_conflict", "同一 request_id 的通道参数不同,请使用新的 request_id。")
|
|
97
|
-
return result, deepcopy(retry)
|
|
98
|
-
if len(channels(result)) >= MAX_CHANNELS:
|
|
99
|
-
raise LineError("too_many_channels", "当前图表最多保存 30 个 AI 通道。")
|
|
100
|
-
commands.append(channel)
|
|
101
|
-
else:
|
|
102
|
-
commands[commands.index(previous)] = channel
|
|
103
|
-
result["chartCommands"] = commands
|
|
104
|
-
return result, deepcopy(channel)
|
|
@@ -1,204 +0,0 @@
|
|
|
1
|
-
"""Explicit application requests and historical state receipts; never a pixel receipt."""
|
|
2
|
-
from __future__ import annotations
|
|
3
|
-
|
|
4
|
-
import json
|
|
5
|
-
import os
|
|
6
|
-
import re
|
|
7
|
-
import time
|
|
8
|
-
|
|
9
|
-
import chart_service
|
|
10
|
-
from tools.chart_context import read_chart_context
|
|
11
|
-
from tools.lines import LineError
|
|
12
|
-
from tools.drawing_feedback import sanitize_drawing_feedback
|
|
13
|
-
|
|
14
|
-
STATUSES = {"queued", "delivered", "applied", "rejected", "failed", "outcome_unknown"}
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
def application_path(context_ref: str, candidate: str):
|
|
18
|
-
if any(not isinstance(v, str) or not re.fullmatch(r"[A-Za-z0-9_-]{32}", v) for v in (context_ref, candidate)):
|
|
19
|
-
raise LineError("invalid_chart_application_reference", "请使用准备结果的 context_ref 和候选 chart_session,不猜测引用。")
|
|
20
|
-
return chart_service.RUNTIME_DIR / "edits" / str(chart_service.HOST_PROCESS_ID) / context_ref / "applications" / (candidate + ".json")
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
def _read(path):
|
|
24
|
-
try:
|
|
25
|
-
if path.stat().st_size > chart_service.MAX_REQUEST_BYTES: raise ValueError("too large")
|
|
26
|
-
data = json.loads(path.read_text(encoding="utf-8"))
|
|
27
|
-
if not isinstance(data, dict): raise ValueError("not an object")
|
|
28
|
-
return data
|
|
29
|
-
except (OSError, ValueError, TypeError):
|
|
30
|
-
raise LineError("chart_application_unavailable", "应用记录不可用,未猜测网页状态或自动重发。") from None
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
def read_application(context_ref: str, candidate: str) -> dict:
|
|
34
|
-
data = _read(application_path(context_ref, candidate))
|
|
35
|
-
if (data.get("host_process_id") != chart_service.HOST_PROCESS_ID or data.get("context_ref") != context_ref
|
|
36
|
-
or data.get("candidate_chart_session") != candidate or data.get("status") not in STATUSES):
|
|
37
|
-
raise LineError("invalid_chart_application", "应用记录身份或状态不一致。")
|
|
38
|
-
return data
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
def _present(path) -> bool:
|
|
42
|
-
"""Only ENOENT is absence; unreadable/corrupt records must not become 'not requested'."""
|
|
43
|
-
try:
|
|
44
|
-
path.stat()
|
|
45
|
-
return True
|
|
46
|
-
except FileNotFoundError:
|
|
47
|
-
return False
|
|
48
|
-
except OSError:
|
|
49
|
-
raise LineError("chart_application_unavailable", "记录无法核对,未推断尚未请求应用。") from None
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
def read_edit_status(context_ref: str, candidate: str) -> dict:
|
|
53
|
-
"""Read historical preparation or application proof, without acquiring locks or writing.
|
|
54
|
-
|
|
55
|
-
This is not an application reader: confirmed_source must still require a real receipt.
|
|
56
|
-
An absent application alone proves nothing; require the exact successful preparation.
|
|
57
|
-
"""
|
|
58
|
-
path = application_path(context_ref, candidate)
|
|
59
|
-
if _present(path):
|
|
60
|
-
return application_status(read_application(context_ref, candidate))
|
|
61
|
-
directory = path.parent.parent
|
|
62
|
-
|
|
63
|
-
def check_inflight():
|
|
64
|
-
if _present(directory / "prepare.lock"):
|
|
65
|
-
raise LineError("chart_edit_busy", "该视图正在处理或存在中断锁,不能断言尚未请求应用;未重发。")
|
|
66
|
-
if _present(directory / "pending.json"):
|
|
67
|
-
pending = _read(directory / "pending.json").get("candidate_chart_session")
|
|
68
|
-
if pending == candidate:
|
|
69
|
-
raise LineError("chart_application_unavailable", "存在应用请求索引但记录缺失,未推断尚未请求应用。")
|
|
70
|
-
if read_application(context_ref, pending)["status"] not in {"applied", "rejected", "failed"}:
|
|
71
|
-
raise LineError("chart_apply_busy", "该视图有等待或结果未确认的应用,未推断新的应用状态。")
|
|
72
|
-
|
|
73
|
-
check_inflight()
|
|
74
|
-
payload = chart_service.read_chart_snapshot(candidate)
|
|
75
|
-
guard = payload.get("drawing_guard") if payload else None
|
|
76
|
-
if (not isinstance(guard, dict) or guard.get("protocol") != "prepared-only-v1"
|
|
77
|
-
or guard.get("context_ref") != context_ref or guard.get("requires_live_apply") is not True
|
|
78
|
-
or payload.get("drawing_parent_session") != guard.get("chart_session")
|
|
79
|
-
or not isinstance(guard.get("expected_revision"), int) or isinstance(guard["expected_revision"], bool)
|
|
80
|
-
or guard["expected_revision"] <= 0 or not isinstance(guard.get("conversation_id"), str) or not guard["conversation_id"]
|
|
81
|
-
or not isinstance(guard.get("view_id"), str) or not re.fullmatch(r"[A-Za-z0-9_-]{32}", guard["view_id"])
|
|
82
|
-
or not isinstance(guard.get("request_id"), str) or not 1 <= len(guard["request_id"]) <= 128
|
|
83
|
-
or not isinstance(guard.get("chart_session"), str) or not re.fullmatch(r"[A-Za-z0-9_-]{32}", guard["chart_session"])
|
|
84
|
-
or not isinstance(guard.get("parameters"), dict) or guard.get("kind") not in ("horizontal_line", "trend_line", "channel", "rectangle", "fibonacci_retracement", "labeled_polyline", "text_annotation", "number_annotation", "icon_annotation", "series_line", "price_band", "price_sticks", "all_drawings")
|
|
85
|
-
or guard.get("action") not in ("create", "update", "delete")):
|
|
86
|
-
raise LineError("invalid_chart_application", "候选不属于该准备请求,未推断应用状态。")
|
|
87
|
-
entries = _read(directory / "journal.json").get("entries")
|
|
88
|
-
from tools.chart_edits import _hash
|
|
89
|
-
identity = {key: guard.get(key) for key in ("context_ref", "expected_revision", "chart_session", "symbol",
|
|
90
|
-
"kind", "action", "object_id", "parameters")}
|
|
91
|
-
matches = [entry for entry in entries if isinstance(entry, dict) and entry.get("request_id") == guard.get("request_id")] if isinstance(entries, list) and len(entries) <= 64 else []
|
|
92
|
-
entry = matches[0] if len(matches) == 1 else {}
|
|
93
|
-
result = entry.get("result")
|
|
94
|
-
if (not isinstance(result, dict) or entry.get("status") != "prepared"
|
|
95
|
-
or entry.get("revision") != guard.get("expected_revision") or entry.get("fingerprint") != _hash(identity)
|
|
96
|
-
or result.get("ok") is not True or result.get("operation_status") != "prepared"
|
|
97
|
-
or result.get("apply_status") != "not_requested" or result.get("chart_session") != candidate
|
|
98
|
-
or result.get("parent_chart_session") != guard.get("chart_session") or result.get("drawing_guard") != guard
|
|
99
|
-
or any(result.get(key) != guard.get(key) for key in
|
|
100
|
-
("context_ref", "expected_revision", "conversation_id", "view_id", "request_id"))):
|
|
101
|
-
raise LineError("chart_edit_outcome_unknown", "未找到匹配的成功准备记录,未推断尚未请求应用。")
|
|
102
|
-
# A concurrent apply may have completed while we read preparation proof. Prefer
|
|
103
|
-
# its real record; a retained lock/index with no record remains uncertain.
|
|
104
|
-
if _present(path):
|
|
105
|
-
return application_status(read_application(context_ref, candidate))
|
|
106
|
-
check_inflight()
|
|
107
|
-
if _present(path):
|
|
108
|
-
return application_status(read_application(context_ref, candidate))
|
|
109
|
-
return {"ok": True, "operation_status": "prepared", "apply_status": "not_requested",
|
|
110
|
-
**{key: result[key] for key in ("context_ref", "expected_revision", "conversation_id", "view_id", "request_id")},
|
|
111
|
-
"candidate_chart_session": candidate, "parent_chart_session": result["parent_chart_session"],
|
|
112
|
-
"application_record_present": False, "record_is_historical": True,
|
|
113
|
-
"confirmation_scope": "not_confirmed", "render_verified": False,
|
|
114
|
-
"current_view_verified": False, "edit_authorized": False}
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
def application_status(data: dict) -> dict:
|
|
118
|
-
# Queued/delivered can be historical after a host interruption; never invent an acknowledgment.
|
|
119
|
-
result = {k: data.get(k) for k in ("context_ref", "candidate_chart_session", "conversation_id", "view_id",
|
|
120
|
-
"expected_revision", "created_at_ms", "expires_at_ms", "reason", "acknowledged_at_ms", "confirmed_chart_session")}
|
|
121
|
-
expires = data.get("expires_at_ms")
|
|
122
|
-
candidate = chart_service.read_chart_snapshot(data.get("candidate_chart_session"))
|
|
123
|
-
if candidate:
|
|
124
|
-
from tools.chart_edits import snapshot_inventory
|
|
125
|
-
try:
|
|
126
|
-
allowed = list({d["id"]: d for d in [*data.get("base_state", {}).get("drawings", []), *snapshot_inventory(candidate)]
|
|
127
|
-
if d.get("origin") == "ai"}.values())
|
|
128
|
-
feedback = sanitize_drawing_feedback(data.get("drawing_feedback"), allowed)
|
|
129
|
-
except (KeyError, TypeError, AttributeError): feedback = sanitize_drawing_feedback({"report_status": "invalid"}, [])
|
|
130
|
-
else: feedback = sanitize_drawing_feedback(None, [])
|
|
131
|
-
expired = isinstance(expires, (int, float)) and time.time() * 1000 > expires
|
|
132
|
-
result.update(ok=True, apply_status=data["status"], render_verified=False,
|
|
133
|
-
expired=expired, needs_attention=data["status"] == "outcome_unknown" or expired and data["status"] in {"queued", "delivered"}
|
|
134
|
-
or feedback["report_status"] == "invalid" or any(i["status"] in {"failed", "unknown"} for i in feedback["items"]),
|
|
135
|
-
drawing_feedback=feedback,
|
|
136
|
-
confirmation_scope="view_state_only" if data["status"] == "applied" else "not_confirmed",
|
|
137
|
-
record_is_historical=True)
|
|
138
|
-
return result
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
def confirmed_source(payload: dict, context: dict, token: str) -> bool:
|
|
142
|
-
guard = payload.get("drawing_guard") or {}
|
|
143
|
-
try: proof = read_application(guard.get("context_ref"), token)
|
|
144
|
-
except LineError: return False
|
|
145
|
-
return (proof["status"] == "applied" and proof.get("confirmed_chart_session") == token
|
|
146
|
-
and proof.get("conversation_id") == context.get("conversation_id") == guard.get("conversation_id")
|
|
147
|
-
and proof.get("view_id") == guard.get("view_id") and proof.get("request_id") == guard.get("request_id"))
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
def request_chart_apply(context_ref: str, candidate: str) -> dict:
|
|
151
|
-
path = application_path(context_ref, candidate)
|
|
152
|
-
directory = path.parent.parent
|
|
153
|
-
directory.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
154
|
-
lock = directory / "prepare.lock"
|
|
155
|
-
try: descriptor = os.open(lock, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
|
|
156
|
-
except FileExistsError:
|
|
157
|
-
raise LineError("chart_edit_busy", "该视图正在准备或申请应用,未并行修改。") from None
|
|
158
|
-
os.close(descriptor)
|
|
159
|
-
try:
|
|
160
|
-
if path.exists():
|
|
161
|
-
existing = read_application(context_ref, candidate)
|
|
162
|
-
# Same immutable candidate has one delivery, including after a lost reply.
|
|
163
|
-
if existing["status"] != "queued": return application_status(existing)
|
|
164
|
-
else: existing = None
|
|
165
|
-
context = read_chart_context(context_ref, candle_scope="loaded", limit=4000)
|
|
166
|
-
if not context.get("guarded_apply_supported"):
|
|
167
|
-
raise LineError("chart_apply_protocol_unavailable", "该网页尚未声明支持应用协议,请更新/重载插件网页;未发送修改指令。")
|
|
168
|
-
payload = chart_service.read_chart_snapshot(candidate)
|
|
169
|
-
guard = payload.get("drawing_guard") if payload else None
|
|
170
|
-
if (not isinstance(guard, dict) or guard.get("protocol") != "prepared-only-v1"
|
|
171
|
-
or guard.get("context_ref") != context_ref or guard.get("conversation_id") != context["conversation_id"]
|
|
172
|
-
or guard.get("view_id") != context["view_id"]):
|
|
173
|
-
raise LineError("invalid_chart_application", "候选不属于当前视图的准备请求,未申请应用。")
|
|
174
|
-
if context["revision"] != guard.get("expected_revision"):
|
|
175
|
-
raise LineError("chart_context_revision_conflict", "准备后当前图版本已变化,未申请应用。")
|
|
176
|
-
journal = _read(directory / "journal.json")
|
|
177
|
-
entries = journal.get("entries")
|
|
178
|
-
if not isinstance(entries, list) or not any(e.get("status") == "prepared" and e.get("request_id") == guard.get("request_id")
|
|
179
|
-
and isinstance(e.get("result"), dict) and e["result"].get("chart_session") == candidate for e in entries if isinstance(e, dict)):
|
|
180
|
-
raise LineError("chart_edit_outcome_unknown", "未找到成功准备记录,不能申请应用。")
|
|
181
|
-
source = chart_service.read_chart_snapshot(guard.get("chart_session"))
|
|
182
|
-
if source is None: raise LineError("chart_session_not_found", "原始来源快照不可用。")
|
|
183
|
-
from tools.chart_edits import require_alignment
|
|
184
|
-
require_alignment(context, source, guard["chart_session"], guard["symbol"])
|
|
185
|
-
pending = directory / "pending.json"
|
|
186
|
-
if pending.exists():
|
|
187
|
-
old_token = _read(pending).get("candidate_chart_session")
|
|
188
|
-
if old_token != candidate:
|
|
189
|
-
old = read_application(context_ref, old_token)
|
|
190
|
-
if old["status"] not in {"applied", "rejected", "failed"}:
|
|
191
|
-
raise LineError("chart_apply_busy", "该视图有等待或结果未确认的应用,不能覆盖它。")
|
|
192
|
-
if existing is None:
|
|
193
|
-
observation = _read(chart_service.RUNTIME_DIR / "views" / str(chart_service.HOST_PROCESS_ID) / (context_ref + ".json"))
|
|
194
|
-
if observation.get("revision") != guard["expected_revision"] or observation.get("view_id") != guard["view_id"]:
|
|
195
|
-
raise LineError("chart_context_revision_conflict", "读取期间当前图版本已变化,未申请应用。")
|
|
196
|
-
now = int(time.time() * 1000)
|
|
197
|
-
existing = {"host_process_id": chart_service.HOST_PROCESS_ID, "context_ref": context_ref,
|
|
198
|
-
"candidate_chart_session": candidate, "conversation_id": context["conversation_id"], "view_id": context["view_id"],
|
|
199
|
-
"expected_revision": guard["expected_revision"], "request_id": guard["request_id"], "status": "queued",
|
|
200
|
-
"created_at_ms": now, "expires_at_ms": now + 30000, "base_state": observation["state"]}
|
|
201
|
-
chart_service._atomic_runtime_json(path, existing)
|
|
202
|
-
chart_service._atomic_runtime_json(pending, {"candidate_chart_session": candidate})
|
|
203
|
-
return application_status(existing)
|
|
204
|
-
finally: lock.unlink()
|
|
@@ -1,186 +0,0 @@
|
|
|
1
|
-
"""Read live browser observations by capability reference; never infer a current view."""
|
|
2
|
-
from __future__ import annotations
|
|
3
|
-
|
|
4
|
-
from copy import deepcopy
|
|
5
|
-
from datetime import datetime
|
|
6
|
-
import json
|
|
7
|
-
import math
|
|
8
|
-
import re
|
|
9
|
-
import time
|
|
10
|
-
from typing import Any
|
|
11
|
-
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
|
|
12
|
-
|
|
13
|
-
import chart_service
|
|
14
|
-
from core.rows import validate_rows, RowsValidationError
|
|
15
|
-
from tools.lines import LineError
|
|
16
|
-
from tools.drawing_feedback import sanitize_drawing_feedback
|
|
17
|
-
from tools.drawing_interaction import drawing_capabilities
|
|
18
|
-
from tools.trend_lines import CN_TZ
|
|
19
|
-
from tools.chart_measurements import measure_chart_region
|
|
20
|
-
from tools.channel_preview import preview_channel
|
|
21
|
-
from tools.chart_source_status import sanitize_source_status
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
def sanitize_data_provenance(state: dict[str, Any]) -> dict[str, Any]:
|
|
25
|
-
"""Whitelist the additive observation metadata, including old-client unknowns."""
|
|
26
|
-
ready = state.get("state") == "ready"
|
|
27
|
-
intervals = ("minute", "day", "week", "month", "quarter", "year")
|
|
28
|
-
source = state.get("source_interval") if ready and state.get("source_interval") in intervals else None
|
|
29
|
-
display = state.get("interval") if ready and state.get("interval") in intervals else None
|
|
30
|
-
raw = state.get("data_provenance") if ready else None
|
|
31
|
-
raw = raw if isinstance(raw, dict) else {}
|
|
32
|
-
provider = raw.get("provider")
|
|
33
|
-
if provider not in ("ftshare", "eastmoney_free", "tencent_free", "builtin_free", "external"):
|
|
34
|
-
provider = "unknown"
|
|
35
|
-
transformation, aggregation = "unknown", None
|
|
36
|
-
if source and source == display and raw.get("transformation") == "none":
|
|
37
|
-
transformation = "none"
|
|
38
|
-
if source == "day" and display in ("week", "month", "quarter", "year") and raw.get("transformation") == "local_aggregation":
|
|
39
|
-
details = raw.get("aggregation")
|
|
40
|
-
zone = details.get("timezone") if isinstance(details, dict) else None
|
|
41
|
-
if isinstance(zone, str) and len(zone) <= 64 and re.fullmatch(r"[A-Za-z_+-]+(?:/[A-Za-z0-9_+-]+){0,2}", zone):
|
|
42
|
-
try:
|
|
43
|
-
ZoneInfo(zone)
|
|
44
|
-
transformation = "local_aggregation"
|
|
45
|
-
aggregation = {"timezone": zone, "bucket": "calendar_week_monday" if display == "week" else "calendar_" + display,
|
|
46
|
-
"ohlcv": "first_open_max_high_min_low_last_close_sum_volume", "timestamp": "last_source_bar",
|
|
47
|
-
"order": "aggregate_before_range_crop", "completeness": "not_verified"}
|
|
48
|
-
except (ZoneInfoNotFoundError, ValueError):
|
|
49
|
-
pass
|
|
50
|
-
return {"scope": "browser_input_to_display", "provider": provider, "source_interval": source,
|
|
51
|
-
"display_interval": display, "transformation": transformation, "aggregation": aggregation}
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
def _time_label(value: int | None) -> dict[str, Any] | None:
|
|
55
|
-
if value is None:
|
|
56
|
-
return None
|
|
57
|
-
try:
|
|
58
|
-
instant = datetime.fromtimestamp(value, CN_TZ)
|
|
59
|
-
return {"time": value, "date": instant.date().isoformat(), "iso": instant.isoformat(timespec="seconds")}
|
|
60
|
-
except (ValueError, OverflowError, OSError):
|
|
61
|
-
return {"time": value, "date": None, "iso": None}
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
def read_chart_context(context_ref: str, *, candle_scope: str = "visible", limit: int = 200,
|
|
65
|
-
region_start_time: str | None = None, region_end_time: str | None = None,
|
|
66
|
-
channel_candidate: dict[str, Any] | None = None) -> dict[str, Any]:
|
|
67
|
-
if not isinstance(context_ref, str) or not re.fullmatch(r"[A-Za-z0-9_-]{32}", context_ref):
|
|
68
|
-
raise LineError("context_ref_required", "请使用当前对话运行时上下文提供的 context_ref,不要使用 chart_session 或猜测其他对话。")
|
|
69
|
-
if candle_scope not in {"visible", "loaded", "none"} or isinstance(limit, bool) or not isinstance(limit, int) or not 1 <= limit <= 4000:
|
|
70
|
-
raise LineError("invalid_context_arguments", "candle_scope 请选择 visible、loaded 或 none;limit 为1至4000整数。")
|
|
71
|
-
if (region_start_time is None) != (region_end_time is None):
|
|
72
|
-
raise LineError("invalid_measurement_range", "测量需同时指定起止已有K线时间;不自动猜测另一个端点。")
|
|
73
|
-
path = chart_service.RUNTIME_DIR / "views" / str(chart_service.HOST_PROCESS_ID) / f"{context_ref}.json"
|
|
74
|
-
try:
|
|
75
|
-
if path.stat().st_size > chart_service.MAX_REQUEST_BYTES: raise ValueError("too large")
|
|
76
|
-
saved = json.loads(path.read_text(encoding="utf-8"))
|
|
77
|
-
except (OSError, ValueError, TypeError):
|
|
78
|
-
raise LineError("chart_context_unavailable", "当前图表上下文不可用;请打开该对话的图表。未使用旧快照或其他对话代替。") from None
|
|
79
|
-
if not isinstance(saved, dict) or saved.get("ok") is not True or saved.get("context_ref") != context_ref or saved.get("host_process_id") != chart_service.HOST_PROCESS_ID:
|
|
80
|
-
raise LineError("chart_context_unavailable", "上下文不属于当前 DSH 实例。")
|
|
81
|
-
if (not isinstance(saved.get("revision"), int) or isinstance(saved["revision"], bool) or saved["revision"] <= 0
|
|
82
|
-
or not isinstance(saved.get("conversation_id"), str) or not saved["conversation_id"]
|
|
83
|
-
or not isinstance(saved.get("view_id"), str) or not re.fullmatch(r"[A-Za-z0-9_-]{32}", saved["view_id"])):
|
|
84
|
-
raise LineError("invalid_chart_context", "图表视图身份或观察版本无效。")
|
|
85
|
-
observed = saved.get("observed_at_ms")
|
|
86
|
-
if isinstance(observed, bool) or not isinstance(observed, (int, float)) or not math.isfinite(observed):
|
|
87
|
-
raise LineError("invalid_chart_context", "图表观察时间无效。")
|
|
88
|
-
age = time.time() * 1000 - observed
|
|
89
|
-
if age > 90_000 or age < -5000:
|
|
90
|
-
raise LineError("chart_context_stale", "图表上下文已过期或时钟异常,请等待网页重新上报;未回退到旧行情快照。")
|
|
91
|
-
if saved.get("active") is not True: raise LineError("chart_view_inactive", "该图表视图已关闭或未活动。")
|
|
92
|
-
if saved.get("ambiguous") is not False: raise LineError("ambiguous_chart_views", "该对话存在多个活动视图,不能确定当前图;请保留一个活动图表视图。")
|
|
93
|
-
state = saved.get("state")
|
|
94
|
-
if not isinstance(state, dict) or state.get("schema_version") != 1 or state.get("state") not in {"ready", "empty", "not_chart", "loading", "error"}:
|
|
95
|
-
raise LineError("invalid_chart_context", "图表上下文格式无效。")
|
|
96
|
-
try:
|
|
97
|
-
raw = state.get("candles", [])
|
|
98
|
-
if not isinstance(raw, list) or len(raw) > 12000: raise ValueError("rows")
|
|
99
|
-
if state["state"] == "ready":
|
|
100
|
-
if any(any(isinstance(r.get(k), bool) or not isinstance(r.get(k), (int, float)) or not math.isfinite(r[k])
|
|
101
|
-
for k in ("time", "open", "high", "low", "close", "volume"))
|
|
102
|
-
or not isinstance(r["time"], int) or r["time"] <= 0 for r in raw): raise ValueError("row types")
|
|
103
|
-
rows = validate_rows([{k: r[k] for k in ("time", "open", "high", "low", "close", "volume")} for r in raw], min_len=1)
|
|
104
|
-
else: rows = []
|
|
105
|
-
# The browser's clock/order must already be canonical. Do not repair a stale/malformed report.
|
|
106
|
-
if rows and [r["time"] for r in rows] != [r.get("time") for r in raw]: raise ValueError("clock")
|
|
107
|
-
if len(rows) != len(raw) and state["state"] == "ready": raise ValueError("rows")
|
|
108
|
-
viewport = state.get("visible_range", {})
|
|
109
|
-
visible: list[dict] = []
|
|
110
|
-
if state["state"] == "ready" and viewport.get("available") is True:
|
|
111
|
-
start, end = viewport["index_from"], viewport["index_to_exclusive"]
|
|
112
|
-
if any(isinstance(v, bool) or not isinstance(v, int) for v in (start, end)) or not 0 <= start <= end <= len(rows): raise ValueError("viewport")
|
|
113
|
-
visible = rows[start:end]
|
|
114
|
-
view_range = {"available": True, "index_from": start, "index_to_exclusive": end,
|
|
115
|
-
"count": len(visible), "start_time": visible[0]["time"] if visible else None,
|
|
116
|
-
"end_time": visible[-1]["time"] if visible else None}
|
|
117
|
-
else: view_range = {"available": False, "reason": "not_reported"}
|
|
118
|
-
objects = state.get("drawings", []) if state["state"] == "ready" else []
|
|
119
|
-
if not isinstance(objects, list) or len(objects) > 512: raise ValueError("drawings")
|
|
120
|
-
drawing_keys = {"id", "kind", "origin", "name", "color", "interval", "price", "time", "text", "value", "icon", "start_time", "end_time", "lower_price", "upper_price", "show_fill", "show_midline", "series_hash", "band_hash", "sticks_hash", "bar_count"}
|
|
121
|
-
drawings = []
|
|
122
|
-
for obj in objects:
|
|
123
|
-
item = {k: deepcopy(obj[k]) for k in drawing_keys if k in obj}
|
|
124
|
-
if obj.get("kind") == "labeled_polyline":
|
|
125
|
-
from tools.polylines import validate_stored_points
|
|
126
|
-
item["points"] = validate_stored_points(obj["points"])
|
|
127
|
-
elif obj.get("kind") in {"text_annotation", "number_annotation", "icon_annotation"}:
|
|
128
|
-
from tools.annotations import validate_annotation
|
|
129
|
-
annotation = validate_annotation({"type": "DRAW_AGENT_ANNOTATION", "kind": obj["kind"], "id": obj.get("id"),
|
|
130
|
-
"interval": obj.get("interval"), "label": obj.get("name", ""), "color": obj.get("color", "info"),
|
|
131
|
-
"time": obj.get("time"), "price": obj.get("price"), "text": obj.get("text"), "value": obj.get("value"),
|
|
132
|
-
"icon": obj.get("icon")})
|
|
133
|
-
item.update(time=annotation["time"], price=annotation["price"])
|
|
134
|
-
if obj["kind"] == "text_annotation": item["text"] = annotation["text"]
|
|
135
|
-
elif obj["kind"] == "number_annotation": item["value"] = annotation["value"]
|
|
136
|
-
else: item["icon"] = annotation["icon"]
|
|
137
|
-
elif "points" in obj: item["points"] = [{k: p[k] for k in ("time", "price")} for p in obj["points"][:8]]
|
|
138
|
-
if obj.get("kind") == "fibonacci_retracement":
|
|
139
|
-
from tools.fibonacci import validate_ratios
|
|
140
|
-
item["ratios"] = validate_ratios(obj["ratios"])
|
|
141
|
-
item["levels"] = [{"ratio": p["ratio"], "price": p["price"]} for p in obj["levels"][:16]]
|
|
142
|
-
item.update(context_editable=False, edit_capability="source_snapshot_only" if obj.get("origin") == "ai" else "read_only")
|
|
143
|
-
drawings.append(item)
|
|
144
|
-
selection = state.get("selection")
|
|
145
|
-
if selection:
|
|
146
|
-
keys = ("kind", "time") if selection.get("kind") == "candle" else ("kind", "start_time", "end_time")
|
|
147
|
-
selection = {k: selection[k] for k in keys}
|
|
148
|
-
except (ValueError, TypeError, KeyError, AttributeError, RowsValidationError):
|
|
149
|
-
raise LineError("invalid_chart_context", "图表数据或可见范围无效,未把已加载范围冒充为屏幕可见范围。") from None
|
|
150
|
-
selected = visible if candle_scope == "visible" else rows if candle_scope == "loaded" else []
|
|
151
|
-
result = {k: deepcopy(state.get(k)) for k in ("symbol", "name", "interval", "interval_value", "interval_value_status", "source_interval",
|
|
152
|
-
"ui_interval", "display_volume_unit", "range_key", "adjust", "active_page", "indicators", "data_status")}
|
|
153
|
-
source = state.get("source_chart_session")
|
|
154
|
-
result["data_provenance"] = sanitize_data_provenance(state)
|
|
155
|
-
result.update(ok=True, context_ref=context_ref, conversation_id=saved.get("conversation_id"), view_id=saved.get("view_id"),
|
|
156
|
-
guarded_apply_supported=saved.get("guarded_apply_supported") is True,
|
|
157
|
-
drawing_workflow="prepare_then_apply" if saved.get("guarded_apply_supported") is True else "observation_only",
|
|
158
|
-
revision=saved.get("revision"), observed_at_ms=observed, age_ms=max(0, int(age)), state=state["state"],
|
|
159
|
-
observation_source="live_browser_report", time_unit="unix_seconds", render_verified=False, live_view_editable=False,
|
|
160
|
-
source_chart_session=source if isinstance(source, str) and re.fullmatch(r"[A-Za-z0-9_-]{32}", source) else None,
|
|
161
|
-
source_snapshot_alignment="not_verified", loaded_range={"count":len(rows), "start_time": rows[0]["time"] if rows else None,
|
|
162
|
-
"end_time":rows[-1]["time"] if rows else None}, visible_range=view_range,
|
|
163
|
-
drawings=drawings, drawings_scope="stored_objects_for_active_instrument", selection=selection,
|
|
164
|
-
drawing_feedback=sanitize_drawing_feedback(saved.get("drawing_feedback"), [d for d in drawings if d.get("origin") == "ai"]),
|
|
165
|
-
selection_status=state.get("selection_status", "none"), selected_drawing_id=None, selected_drawing_status="not_supported",
|
|
166
|
-
drawing_capabilities=drawing_capabilities(),
|
|
167
|
-
candles=selected[-limit:], candle_selection={"scope":candle_scope,"total":len(selected),"returned":min(limit,len(selected)),
|
|
168
|
-
"truncated":len(selected)>limit,"order":"ascending","sample":"last_limit"})
|
|
169
|
-
result["source_status"] = sanitize_source_status(saved.get("source_status"))
|
|
170
|
-
# Keep raw candles untouched for strict source-alignment checks. Supply a
|
|
171
|
-
# separate deterministic display map so the host need not guess dates.
|
|
172
|
-
result["time_display"] = {"timezone": "UTC+08:00", "basis": "same_as_anchor_date_resolution",
|
|
173
|
-
"loaded_start": _time_label(rows[0]["time"] if rows else None),
|
|
174
|
-
"loaded_end": _time_label(rows[-1]["time"] if rows else None),
|
|
175
|
-
"visible_start": _time_label(visible[0]["time"] if visible else None),
|
|
176
|
-
"visible_end": _time_label(visible[-1]["time"] if visible else None),
|
|
177
|
-
"sample_labels": [_time_label(row["time"]) for row in selected[-limit:]]}
|
|
178
|
-
if region_start_time is not None:
|
|
179
|
-
if state["state"] != "ready":
|
|
180
|
-
raise LineError("chart_measurement_not_ready", "当前图未就绪,不能使用旧K线测量区域。")
|
|
181
|
-
result["region_measurements"] = measure_chart_region(rows, result["interval"], region_start_time, region_end_time)
|
|
182
|
-
if channel_candidate is not None:
|
|
183
|
-
if state["state"] != "ready":
|
|
184
|
-
raise LineError("chart_measurement_not_ready", "当前图未就绪,不能使用旧K线预览通道。")
|
|
185
|
-
result["channel_preview"] = preview_channel(rows, result["interval"], **channel_candidate)
|
|
186
|
-
return result
|