@dsh-ft/dsh-fft-paper-trading 0.6.0 → 0.6.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -4
- package/README.zh.md +4 -4
- package/lib/agent/format.d.ts.map +1 -1
- package/lib/agent/format.js +4 -0
- package/lib/agent/format.js.map +1 -1
- package/lib/agent/tools.d.ts.map +1 -1
- package/lib/agent/tools.js +5 -3
- package/lib/agent/tools.js.map +1 -1
- package/lib/client.js +76 -13
- package/lib/contract.d.ts.map +1 -1
- package/lib/contract.js +3 -1
- package/lib/contract.js.map +1 -1
- package/lib/core/risk.d.ts.map +1 -1
- package/lib/core/risk.js +10 -2
- package/lib/core/risk.js.map +1 -1
- package/lib/core/views.js +2 -2
- package/lib/core/views.js.map +1 -1
- package/lib/data/ftshare-trading-calendar.d.ts +47 -12
- package/lib/data/ftshare-trading-calendar.d.ts.map +1 -1
- package/lib/data/ftshare-trading-calendar.js +156 -44
- package/lib/data/ftshare-trading-calendar.js.map +1 -1
- package/lib/service/paper-service.d.ts +1 -1
- package/lib/service/paper-service.d.ts.map +1 -1
- package/lib/service/paper-service.js +24 -12
- package/lib/service/paper-service.js.map +1 -1
- package/lib/service/rpc.d.ts.map +1 -1
- package/lib/service/rpc.js +12 -1
- package/lib/service/rpc.js.map +1 -1
- package/node_modules/@ftshare-lab/dsh-kline/CHANGELOG.md +98 -0
- package/node_modules/@ftshare-lab/dsh-kline/README.en.md +116 -26
- package/node_modules/@ftshare-lab/dsh-kline/README.md +125 -25
- package/node_modules/@ftshare-lab/dsh-kline/chart_service.py +38 -0
- package/node_modules/@ftshare-lab/dsh-kline/cordis.patch.yml +3 -9
- package/node_modules/@ftshare-lab/dsh-kline/core/calc.py +63 -269
- package/node_modules/@ftshare-lab/dsh-kline/core/rows.py +15 -3
- package/node_modules/@ftshare-lab/dsh-kline/core/ta_engine.py +99 -0
- package/node_modules/@ftshare-lab/dsh-kline/lib/candle-sequence.js +15 -0
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-annotations.js +33 -0
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-applications.js +1 -1
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-context.js +12 -3
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-observation.js +91 -2
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-sources.js +64 -13
- package/node_modules/@ftshare-lab/dsh-kline/lib/client.js +3356 -787
- package/node_modules/@ftshare-lab/dsh-kline/lib/drawing-feedback.js +96 -19
- package/node_modules/@ftshare-lab/dsh-kline/lib/fibonacci.js +18 -0
- package/node_modules/@ftshare-lab/dsh-kline/lib/index.js +19 -2
- package/node_modules/@ftshare-lab/dsh-kline/lib/labeled-polyline.js +17 -0
- package/node_modules/@ftshare-lab/dsh-kline/lib/price-bands.js +55 -0
- package/node_modules/@ftshare-lab/dsh-kline/lib/price-series.js +47 -0
- package/node_modules/@ftshare-lab/dsh-kline/lib/price-sticks.js +32 -0
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/candle-sequence.d.ts +2 -0
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-annotations.d.ts +4 -0
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-context.d.ts +1 -1
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-observation.d.ts +2 -0
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/BetterSidebarTab.d.ts +3 -2
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/ClassicShell.d.ts +1 -1
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/chart-context.d.ts +1 -0
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/client-context.d.ts +14 -0
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/conversation.d.ts +11 -3
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/embed.d.ts +2 -2
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/generated-view.d.ts +1 -1
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/host-services.d.ts +0 -36
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/index.d.ts +2 -1
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar-contract.d.ts +35 -4
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar-register.d.ts +46 -0
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar-services.d.ts +45 -0
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar.d.ts +21 -36
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/fibonacci.d.ts +5 -0
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/labeled-polyline.d.ts +11 -0
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/price-bands.d.ts +3 -0
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/price-series.d.ts +5 -0
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/price-sticks.d.ts +3 -0
- package/node_modules/@ftshare-lab/dsh-kline/package.json +27 -5
- package/node_modules/@ftshare-lab/dsh-kline/requirements.txt +2 -0
- package/node_modules/@ftshare-lab/dsh-kline/scripts/dsh-mcp-plugin.mjs +27 -0
- package/node_modules/@ftshare-lab/dsh-kline/scripts/run-dsh-kline.mjs +180 -49
- package/node_modules/@ftshare-lab/dsh-kline/server.py +300 -34
- package/node_modules/@ftshare-lab/dsh-kline/tools/annotations.py +119 -0
- package/node_modules/@ftshare-lab/dsh-kline/tools/baostock_source.py +176 -0
- package/node_modules/@ftshare-lab/dsh-kline/tools/channel_candidates.py +260 -0
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_applications.py +1 -1
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_context.py +22 -3
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_edits.py +141 -16
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_functions.py +466 -0
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_indicators.py +63 -0
- package/node_modules/@ftshare-lab/dsh-kline/tools/draw.py +3 -0
- package/node_modules/@ftshare-lab/dsh-kline/tools/drawing_feedback.py +13 -7
- package/node_modules/@ftshare-lab/dsh-kline/tools/drawing_interaction.py +117 -0
- package/node_modules/@ftshare-lab/dsh-kline/tools/drawing_verification.py +58 -3
- package/node_modules/@ftshare-lab/dsh-kline/tools/fetch.py +164 -40
- package/node_modules/@ftshare-lab/dsh-kline/tools/fibonacci.py +83 -0
- package/node_modules/@ftshare-lab/dsh-kline/tools/free_sources.py +78 -21
- package/node_modules/@ftshare-lab/dsh-kline/tools/pivots.py +60 -0
- package/node_modules/@ftshare-lab/dsh-kline/tools/polylines.py +125 -0
- package/node_modules/@ftshare-lab/dsh-kline/tools/price_bands.py +165 -0
- package/node_modules/@ftshare-lab/dsh-kline/tools/price_series.py +162 -0
- package/node_modules/@ftshare-lab/dsh-kline/tools/price_sticks.py +114 -0
- package/node_modules/@ftshare-lab/dsh-kline/tools/range_candidates.py +170 -0
- package/node_modules/@ftshare-lab/dsh-kline/tools/regression_channels.py +87 -0
- package/node_modules/@ftshare-lab/dsh-kline/tools/ta_functions.py +228 -0
- package/package.json +3 -3
- package/src/agent/format.ts +3 -0
- package/src/agent/tools.ts +5 -3
- package/src/client/index.js +75 -12
- package/src/contract.ts +3 -1
- package/src/core/risk.ts +10 -2
- package/src/core/views.ts +2 -2
- package/src/data/ftshare-trading-calendar.ts +184 -45
- package/src/service/paper-service.ts +22 -19
- package/src/service/rpc.ts +12 -1
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
"""Finite price-domain retracements. No pivot discovery or pixel interpolation."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from copy import deepcopy
|
|
5
|
+
import hashlib
|
|
6
|
+
import math
|
|
7
|
+
import secrets
|
|
8
|
+
|
|
9
|
+
from tools.lines import LineError, validate_line_fields
|
|
10
|
+
from tools.trend_lines import resolve_anchor_time
|
|
11
|
+
|
|
12
|
+
FIBONACCI_COMMAND = "DRAW_AGENT_FIBONACCI"
|
|
13
|
+
DEFAULT_RATIOS = [0, .236, .382, .5, .618, .786, 1]
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def validate_ratios(ratios):
|
|
17
|
+
if (not isinstance(ratios, list) or not 1 <= len(ratios) <= 16
|
|
18
|
+
or any(type(r) not in (int, float) or not math.isfinite(r) or not 0 <= r <= 1 for r in ratios)
|
|
19
|
+
or any(a >= b for a, b in zip(ratios, ratios[1:]))):
|
|
20
|
+
raise LineError("invalid_fibonacci_ratios", "回撤比例需为1至16个递增、不重复的0至1有限数值;未自动排序。")
|
|
21
|
+
return [float(r) for r in ratios]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def fibonacci_levels(start_price, end_price, ratios):
|
|
25
|
+
start, _, _ = validate_line_fields(price=start_price)
|
|
26
|
+
end, _, _ = validate_line_fields(price=end_price)
|
|
27
|
+
if start == end:
|
|
28
|
+
raise LineError("zero_fibonacci_range", "两个锚点价格不能相同。")
|
|
29
|
+
levels = [{"ratio": r, "price": end - r * (end - start)} for r in validate_ratios(ratios)]
|
|
30
|
+
if any(not math.isfinite(p["price"]) or p["price"] <= 0 for p in levels):
|
|
31
|
+
raise LineError("invalid_fibonacci_price", "回撤价位必须为大于零的有限数值。")
|
|
32
|
+
return levels
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def edit_fibonacci(payload, action, *, fibonacci_id=None, start_time=None, start_price=None,
|
|
36
|
+
end_time=None, end_price=None, ratios=None, name=None, color=None, request_id=None):
|
|
37
|
+
result = deepcopy(payload)
|
|
38
|
+
commands = result.get("chartCommands", [])
|
|
39
|
+
previous = next((c for c in commands if c.get("type") == FIBONACCI_COMMAND and c.get("id") == fibonacci_id), None)
|
|
40
|
+
if action in {"update", "delete"} and previous is None:
|
|
41
|
+
raise LineError("fibonacci_not_found", "当前快照不存在该 AI 斐波那契对象,请先读取对象 ID。")
|
|
42
|
+
if action == "delete":
|
|
43
|
+
commands.remove(previous)
|
|
44
|
+
return result, deepcopy(previous)
|
|
45
|
+
if action not in {"create", "update"}:
|
|
46
|
+
raise LineError("invalid_action", "不支持的斐波那契操作。")
|
|
47
|
+
values = (start_time, start_price, end_time, end_price)
|
|
48
|
+
if action == "create" and any(v is None for v in values):
|
|
49
|
+
raise LineError("missing_anchor", "需要明确的两个时间和价格锚点,不自动选择最近高低点。")
|
|
50
|
+
if action == "update" and all(v is None for v in (*values, ratios, name, color)):
|
|
51
|
+
raise LineError("empty_update", "请至少修改锚点、比例、名称或颜色。")
|
|
52
|
+
_, name, color = validate_line_fields(name=name, color=color, request_id=request_id)
|
|
53
|
+
anchors = []
|
|
54
|
+
for key, time, price in (("from", start_time, start_price), ("to", end_time, end_price)):
|
|
55
|
+
old = previous[key] if previous else {}
|
|
56
|
+
value, _, _ = validate_line_fields(price=price if price is not None else old.get("price"))
|
|
57
|
+
anchors.append({"time": resolve_anchor_time(payload, time) if time is not None else old["time"], "price": value})
|
|
58
|
+
start, end = anchors
|
|
59
|
+
if start["time"] >= end["time"]:
|
|
60
|
+
raise LineError("invalid_anchor_order", "斐波那契起点必须早于终点;未自动交换锚点。")
|
|
61
|
+
ratios = validate_ratios(ratios if ratios is not None else previous["ratios"] if previous else DEFAULT_RATIOS)
|
|
62
|
+
obj = {"type": FIBONACCI_COMMAND, "id": previous["id"] if previous else "fib_" + secrets.token_hex(12),
|
|
63
|
+
"interval": payload.get("interval"), "from": start, "to": end, "ratios": ratios,
|
|
64
|
+
"levels": fibonacci_levels(start["price"], end["price"], ratios), "geometry_basis": "linear_price_retracement",
|
|
65
|
+
"label": name if name is not None else previous["label"] if previous else "",
|
|
66
|
+
"color": color if color is not None else previous["color"] if previous else "info"}
|
|
67
|
+
if previous and previous.get("create_request_id"):
|
|
68
|
+
obj["create_request_id"] = previous["create_request_id"]
|
|
69
|
+
if action == "create":
|
|
70
|
+
if request_id:
|
|
71
|
+
obj["create_request_id"] = request_id
|
|
72
|
+
obj["id"] = "fib_" + hashlib.sha256(request_id.encode()).hexdigest()[:24]
|
|
73
|
+
retry = next((c for c in commands if c.get("type") == FIBONACCI_COMMAND and c.get("create_request_id") == request_id), None)
|
|
74
|
+
if retry:
|
|
75
|
+
if any(retry.get(k) != obj[k] for k in ("from", "to", "ratios", "label", "color")):
|
|
76
|
+
raise LineError("request_conflict", "同一 request_id 的斐波那契参数不同。")
|
|
77
|
+
return result, deepcopy(retry)
|
|
78
|
+
if sum(c.get("type") == FIBONACCI_COMMAND for c in commands) >= 30:
|
|
79
|
+
raise LineError("too_many_fibonacci", "当前图表最多保存30组 AI 斐波那契对象。")
|
|
80
|
+
commands.append(obj)
|
|
81
|
+
else:
|
|
82
|
+
commands[commands.index(previous)] = obj
|
|
83
|
+
return result, deepcopy(obj)
|
|
@@ -7,8 +7,8 @@ serve it (anonymous/free tier without HK/US/index entitlements).
|
|
|
7
7
|
Design rules (mirror docs/provider-adaptation.md):
|
|
8
8
|
- Small, explicit registries only. No runtime discovery; no remote data ever
|
|
9
9
|
adds a URL or executes code.
|
|
10
|
-
- Public, key-less HTTP endpoints only (Eastmoney
|
|
11
|
-
|
|
10
|
+
- Public, key-less HTTP endpoints only (Eastmoney daily K-lines and Tencent
|
|
11
|
+
JSON K-line/quote feeds). No scraping of HTML.
|
|
12
12
|
- Every row keeps the canonical OHLCV shape (close-time, unix seconds) and the
|
|
13
13
|
response carries ``source`` + ``source_url`` so callers can label the data as
|
|
14
14
|
free fallback instead of silently pretending it came from FTShare.
|
|
@@ -22,6 +22,7 @@ tools.fetch (which imports this module for fallback wiring).
|
|
|
22
22
|
from __future__ import annotations
|
|
23
23
|
|
|
24
24
|
import json
|
|
25
|
+
import math
|
|
25
26
|
import re
|
|
26
27
|
import threading
|
|
27
28
|
import time
|
|
@@ -239,10 +240,10 @@ def em_symbol_supported(symbol: str) -> bool:
|
|
|
239
240
|
return str(symbol or "").strip().upper() in EM_INDEX_SECIDS
|
|
240
241
|
|
|
241
242
|
|
|
242
|
-
# Tencent historical K-
|
|
243
|
-
#
|
|
244
|
-
#
|
|
245
|
-
#
|
|
243
|
+
# Tencent historical K-lines. The explicit index registry stays narrow, while
|
|
244
|
+
# A-share stocks are accepted only when the caller supplied a fully qualified
|
|
245
|
+
# Shanghai/Shenzhen equity identity (see ``_tencent_stock_code`` below).
|
|
246
|
+
# Tencent's bar array is [date, open, close, high, low, volume].
|
|
246
247
|
_TENCENT_KLINE_CODES: dict[str, str] = {
|
|
247
248
|
"100.HSI": "hkHSI",
|
|
248
249
|
"100.NDX": "usNDX",
|
|
@@ -257,16 +258,17 @@ _TENCENT_KLINE_CODES: dict[str, str] = {
|
|
|
257
258
|
}
|
|
258
259
|
|
|
259
260
|
|
|
260
|
-
def _parse_tencent_kline_payload(payload: Any, timezone_name: str) -> list[dict[str, Any]]:
|
|
261
|
-
"""Parse
|
|
261
|
+
def _parse_tencent_kline_payload(payload: Any, timezone_name: str, series: str | tuple[str, ...]) -> list[dict[str, Any]]:
|
|
262
|
+
"""Parse one of the explicitly requested Tencent K-line series names."""
|
|
262
263
|
rows: list[dict[str, Any]] = []
|
|
263
264
|
try:
|
|
264
265
|
data = payload.get("data") or {}
|
|
265
266
|
except AttributeError:
|
|
266
267
|
return rows
|
|
268
|
+
names = (series,) if isinstance(series, str) else series
|
|
267
269
|
for _code, node in data.items():
|
|
268
|
-
# node: {"day": [[date, open, close, high, low, volume], ...]
|
|
269
|
-
bars = node.get(
|
|
270
|
+
# node: {"day"|"qfqday"|"hfqday": [[date, open, close, high, low, volume], ...]}
|
|
271
|
+
bars = next((node.get(name) for name in names if isinstance(node, Mapping) and isinstance(node.get(name), list)), None)
|
|
270
272
|
if not isinstance(bars, list):
|
|
271
273
|
continue
|
|
272
274
|
for bar in bars:
|
|
@@ -277,18 +279,18 @@ def _parse_tencent_kline_payload(payload: Any, timezone_name: str) -> list[dict[
|
|
|
277
279
|
if not timestamp:
|
|
278
280
|
continue
|
|
279
281
|
try:
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
"time": timestamp,
|
|
283
|
-
"open": float(open_px),
|
|
284
|
-
"high": float(high_px),
|
|
285
|
-
"low": float(low_px),
|
|
286
|
-
"close": float(close_px),
|
|
287
|
-
"volume": float(volume) if str(volume).replace(".", "", 1).isdigit() else 0.0,
|
|
288
|
-
}
|
|
289
|
-
)
|
|
282
|
+
opened, high, low, closed = map(float, (open_px, high_px, low_px, close_px))
|
|
283
|
+
traded = float(volume)
|
|
290
284
|
except (TypeError, ValueError):
|
|
291
285
|
continue
|
|
286
|
+
if (
|
|
287
|
+
not all(math.isfinite(value) for value in (opened, high, low, closed, traded))
|
|
288
|
+
or min(opened, high, low, closed) <= 0 or traded < 0
|
|
289
|
+
or high < max(opened, low, closed) or low > min(opened, high, closed)
|
|
290
|
+
):
|
|
291
|
+
continue
|
|
292
|
+
rows.append({"time": timestamp, "open": opened, "high": high, "low": low,
|
|
293
|
+
"close": closed, "volume": traded})
|
|
292
294
|
rows.sort(key=lambda item: int(item["time"]))
|
|
293
295
|
return rows
|
|
294
296
|
|
|
@@ -312,7 +314,62 @@ def fetch_tencent_index_daily(symbol: str, *, limit: int = 120) -> list[dict[str
|
|
|
312
314
|
url = f"https://web.ifzq.gtimg.cn/appstock/app/fqkline/get?param={code},day,,,{wanted},qfq"
|
|
313
315
|
payload = _http_get_json(url, referer=None)
|
|
314
316
|
timezone_name = "Asia/Hong_Kong" if canonical == "100.HSI" else "America/New_York" if canonical == "100.NDX" else "Asia/Shanghai"
|
|
315
|
-
|
|
317
|
+
# Tencent returns qfqday for some indices and unadjusted day for others;
|
|
318
|
+
# index corporate-action adjustment is not applicable, so either verified
|
|
319
|
+
# series is acceptable here. Stock calls below remain exact by adjustment.
|
|
320
|
+
rows = _parse_tencent_kline_payload(payload, timezone_name, ("qfqday", "day"))
|
|
321
|
+
if len(rows) < 2:
|
|
322
|
+
return None
|
|
323
|
+
result = rows[-wanted:]
|
|
324
|
+
_cache_set(cache_key, result)
|
|
325
|
+
return result
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
_TENCENT_STOCK_SYMBOL = re.compile(r"(\d{6})\.(XSHG|XSHE)$")
|
|
329
|
+
_TENCENT_STOCK_PREFIXES = {
|
|
330
|
+
"XSHG": ("600", "601", "603", "605", "688", "689"),
|
|
331
|
+
"XSHE": ("000", "001", "002", "003", "300", "301", "302"),
|
|
332
|
+
}
|
|
333
|
+
_TENCENT_ADJUSTMENT_SERIES = {
|
|
334
|
+
"none": ("", "day"),
|
|
335
|
+
"forward": ("qfq", "qfqday"),
|
|
336
|
+
"backward": ("hfq", "hfqday"),
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def _tencent_stock_code(symbol: str) -> str | None:
|
|
341
|
+
"""Map only explicit, supported A-share equities to Tencent's code form."""
|
|
342
|
+
match = _TENCENT_STOCK_SYMBOL.fullmatch(str(symbol or "").strip().upper())
|
|
343
|
+
if not match:
|
|
344
|
+
return None
|
|
345
|
+
code, market = match.groups()
|
|
346
|
+
if not code.startswith(_TENCENT_STOCK_PREFIXES[market]):
|
|
347
|
+
return None
|
|
348
|
+
return ("sh" if market == "XSHG" else "sz") + code
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def fetch_tencent_stock_daily(symbol: str, *, limit: int = 120, adjust: str = "none") -> list[dict[str, Any]] | None:
|
|
352
|
+
"""Fetch qualified沪深 A-share daily K-lines from Tencent's public JSON feed.
|
|
353
|
+
|
|
354
|
+
This is a bounded second fallback after BaoStock. It supports only daily
|
|
355
|
+
source bars and preserves the caller's explicit adjustment selection; the
|
|
356
|
+
higher-level provider aggregates week/month/quarter/year intervals locally.
|
|
357
|
+
"""
|
|
358
|
+
code = _tencent_stock_code(symbol)
|
|
359
|
+
adjustment = _TENCENT_ADJUSTMENT_SERIES.get(str(adjust or "").strip().lower())
|
|
360
|
+
if not code or adjustment is None:
|
|
361
|
+
return None
|
|
362
|
+
mode, series = adjustment
|
|
363
|
+
wanted = max(2, min(int(limit), 4000))
|
|
364
|
+
cache_key = ("tencent_stock_daily", f"{code}:{wanted}:{mode or 'none'}")
|
|
365
|
+
cached = _cache_get(cache_key)
|
|
366
|
+
if cached is not None:
|
|
367
|
+
return cached
|
|
368
|
+
# An empty mode deliberately leaves the final comma: Tencent then returns
|
|
369
|
+
# the unadjusted ``day`` series instead of a default qfq series.
|
|
370
|
+
url = f"https://web.ifzq.gtimg.cn/appstock/app/fqkline/get?param={code},day,,,{wanted},{mode}"
|
|
371
|
+
payload = _http_get_json(url, referer=None)
|
|
372
|
+
rows = _parse_tencent_kline_payload(payload, "Asia/Shanghai", series)
|
|
316
373
|
if len(rows) < 2:
|
|
317
374
|
return None
|
|
318
375
|
result = rows[-wanted:]
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""Deterministic, confirmed local-extremum candidates on loaded candles."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import math
|
|
5
|
+
|
|
6
|
+
from core.rows import RowsValidationError, validate_rows
|
|
7
|
+
from tools.lines import LineError
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def confirmed_pivots(rows, *, left_bars=2, right_bars=2, mode="both", limit=20):
|
|
11
|
+
"""Return strict local highs/lows with complete left and right windows.
|
|
12
|
+
|
|
13
|
+
Equal highs/lows are deliberately not pivots. Only bars with all right-side
|
|
14
|
+
confirmation bars present are considered. Results are chronological, limited
|
|
15
|
+
to the newest ``limit`` candidates, with no alternation or trend inference.
|
|
16
|
+
"""
|
|
17
|
+
if type(left_bars) is not int or not 1 <= left_bars <= 20:
|
|
18
|
+
raise LineError("invalid_pivot_window", "left_bars 必须是1至20的整数。")
|
|
19
|
+
if type(right_bars) is not int or not 1 <= right_bars <= 20:
|
|
20
|
+
raise LineError("invalid_pivot_window", "right_bars 必须是1至20的整数。")
|
|
21
|
+
if mode not in {"high", "low", "both"}:
|
|
22
|
+
raise LineError("invalid_pivot_mode", "mode 只能是 high、low 或 both。")
|
|
23
|
+
if type(limit) is not int or not 1 <= limit <= 50:
|
|
24
|
+
raise LineError("invalid_pivot_limit", "limit 必须是1至50的整数。")
|
|
25
|
+
try:
|
|
26
|
+
candles = validate_rows(rows, min_len=left_bars + right_bars + 1)
|
|
27
|
+
except RowsValidationError:
|
|
28
|
+
raise LineError("insufficient_pivot_history", "已加载K线不足以提供完整左右确认窗口;未补取行情。") from None
|
|
29
|
+
|
|
30
|
+
candidates = []
|
|
31
|
+
for index in range(left_bars, len(candles) - right_bars):
|
|
32
|
+
row = candles[index]
|
|
33
|
+
left = candles[index - left_bars:index]
|
|
34
|
+
right = candles[index + 1:index + right_bars + 1]
|
|
35
|
+
high = float(row["high"])
|
|
36
|
+
low = float(row["low"])
|
|
37
|
+
if not math.isfinite(high) or not math.isfinite(low):
|
|
38
|
+
raise LineError("invalid_pivot_data", "K线高低价必须是有限数值。")
|
|
39
|
+
neighbors = left + right
|
|
40
|
+
if mode in {"high", "both"} and all(high > float(item["high"]) for item in neighbors):
|
|
41
|
+
candidates.append({"side": "high", "time": str(row["time"]), "price": high,
|
|
42
|
+
"bars_ago": len(candles) - 1 - index})
|
|
43
|
+
if mode in {"low", "both"} and all(low < float(item["low"]) for item in neighbors):
|
|
44
|
+
candidates.append({"side": "low", "time": str(row["time"]), "price": low,
|
|
45
|
+
"bars_ago": len(candles) - 1 - index})
|
|
46
|
+
|
|
47
|
+
selected = candidates[-limit:]
|
|
48
|
+
return {
|
|
49
|
+
"left_bars": left_bars,
|
|
50
|
+
"right_bars": right_bars,
|
|
51
|
+
"mode": mode,
|
|
52
|
+
"limit": limit,
|
|
53
|
+
"candidates": selected,
|
|
54
|
+
"candidate_count": len(selected),
|
|
55
|
+
"total_candidates": len(candidates),
|
|
56
|
+
"truncated": len(selected) < len(candidates),
|
|
57
|
+
"rule": "strict_local_extremum",
|
|
58
|
+
"tie_policy": "equal_neighbor_is_not_a_pivot",
|
|
59
|
+
"confirmation": "complete_right_window_only",
|
|
60
|
+
}
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
"""Explicit labeled time/price paths, not automatic wave recognition."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from copy import deepcopy
|
|
5
|
+
import hashlib
|
|
6
|
+
import secrets
|
|
7
|
+
|
|
8
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
9
|
+
|
|
10
|
+
from tools.lines import LineError, validate_line_fields
|
|
11
|
+
from tools.trend_lines import resolve_anchor_time
|
|
12
|
+
|
|
13
|
+
POLYLINE_COMMAND = "DRAW_AGENT_POLYLINE"
|
|
14
|
+
MAX_POINTS = 8
|
|
15
|
+
MAX_POLYLINES = 30
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class LabeledPoint(BaseModel):
|
|
19
|
+
model_config = ConfigDict(extra="forbid")
|
|
20
|
+
label: str = Field(min_length=1, max_length=16, description="点名,组内唯一,例如 A、B、C 或 1、2;不是自动识浪结果")
|
|
21
|
+
time: str = Field(min_length=1, description="已加载 K 线的日期、带时区 ISO 或 Unix 秒字符串")
|
|
22
|
+
price: float = Field(gt=0, allow_inf_nan=False, strict=True)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def normalize_point_label(label):
|
|
26
|
+
if (not isinstance(label, str) or not 1 <= len(label.strip()) <= 16
|
|
27
|
+
or any(ord(c) < 32 for c in label)):
|
|
28
|
+
raise LineError("invalid_point_label", "点名需为1至16个字符,不能空白或包含控制字符。")
|
|
29
|
+
return label.strip()
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def validate_stored_points(points):
|
|
33
|
+
"""Whitelist canonical object fields; never sort, truncate or repair a path."""
|
|
34
|
+
if not isinstance(points, list) or not 2 <= len(points) <= MAX_POINTS:
|
|
35
|
+
raise LineError("invalid_polyline_points", "折线需要2至8个明确的带标签锚点。")
|
|
36
|
+
cleaned = []
|
|
37
|
+
for point in points:
|
|
38
|
+
if not isinstance(point, dict) or type(point.get("time")) is not int or point["time"] <= 0:
|
|
39
|
+
raise LineError("invalid_polyline_points", "折线锚点时间格式无效。")
|
|
40
|
+
label = normalize_point_label(point.get("label"))
|
|
41
|
+
price, _, _ = validate_line_fields(price=point.get("price"))
|
|
42
|
+
if price is None: raise LineError("invalid_price", "每个折线锚点都需要明确价格。")
|
|
43
|
+
cleaned.append({"label": label, "time": point["time"], "price": price})
|
|
44
|
+
if len({p["label"] for p in cleaned}) != len(cleaned):
|
|
45
|
+
raise LineError("duplicate_point_label", "同组点名必须唯一,不能按重复标签猜点。")
|
|
46
|
+
if any(a["time"] >= b["time"] for a, b in zip(cleaned, cleaned[1:])):
|
|
47
|
+
raise LineError("invalid_anchor_order", "折线锚点时间必须递增;不自动排序或交换点位。")
|
|
48
|
+
return cleaned
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def resolve_points(payload, points):
|
|
52
|
+
if not isinstance(points, list) or not 2 <= len(points) <= MAX_POINTS:
|
|
53
|
+
raise LineError("invalid_polyline_points", "折线需要2至8个明确的带标签锚点。")
|
|
54
|
+
resolved = []
|
|
55
|
+
for raw in points:
|
|
56
|
+
point = raw.model_dump() if isinstance(raw, LabeledPoint) else raw
|
|
57
|
+
if not isinstance(point, dict) or set(point) != {"label", "time", "price"}:
|
|
58
|
+
raise LineError("invalid_polyline_points", "每个锚点只包含 label、time、price。")
|
|
59
|
+
resolved.append({**point, "time": resolve_anchor_time(payload, point["time"])})
|
|
60
|
+
return validate_stored_points(resolved)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def edit_polyline(payload, action, *, polyline_id=None, points=None, point_label=None,
|
|
64
|
+
point_time=None, point_price=None, name=None, color=None, request_id=None):
|
|
65
|
+
result = deepcopy(payload)
|
|
66
|
+
commands = result.get("chartCommands", [])
|
|
67
|
+
matches = [c for c in commands if c.get("type") == POLYLINE_COMMAND and c.get("id") == polyline_id]
|
|
68
|
+
if len(matches) > 1:
|
|
69
|
+
raise LineError("ambiguous_drawing_id", "同一对象 ID 不唯一,不能安全修改。")
|
|
70
|
+
previous = matches[0] if matches else None
|
|
71
|
+
if action in {"update", "delete"} and previous is None:
|
|
72
|
+
raise LineError("polyline_not_found", "当前快照不存在该 AI 标注折线,请先读回完整对象 ID。")
|
|
73
|
+
if action == "delete":
|
|
74
|
+
if any(v is not None for v in (points, point_label, point_time, point_price, name, color)):
|
|
75
|
+
raise LineError("invalid_edit_fields", "删除整组只需对象 ID。")
|
|
76
|
+
commands.remove(previous)
|
|
77
|
+
return result, deepcopy(previous)
|
|
78
|
+
if action not in {"create", "update"}:
|
|
79
|
+
raise LineError("invalid_action", "不支持的标注折线操作。")
|
|
80
|
+
_, name, color = validate_line_fields(name=name, color=color, request_id=request_id)
|
|
81
|
+
if action == "create":
|
|
82
|
+
if any(v is not None for v in (point_label, point_time, point_price)):
|
|
83
|
+
raise LineError("invalid_edit_fields", "创建需完整 points,单点修改字段只用于更新。")
|
|
84
|
+
path = resolve_points(payload, points)
|
|
85
|
+
else:
|
|
86
|
+
# Updating one point must not require the LLM to copy/reconstruct its
|
|
87
|
+
# neighbours. Full replacement/point insertion/removal are out of scope.
|
|
88
|
+
if points is not None:
|
|
89
|
+
raise LineError("polyline_replacement_not_supported", "续改请用 point_label 及 point_time / point_price,仅改目标点;不接受整组重写。")
|
|
90
|
+
path = validate_stored_points(previous["points"])
|
|
91
|
+
if point_label is not None:
|
|
92
|
+
label = normalize_point_label(point_label)
|
|
93
|
+
if point_time is None and point_price is None:
|
|
94
|
+
raise LineError("empty_point_update", "请明确目标点的新时间或价格,不能猜移动幅度。")
|
|
95
|
+
target = next((p for p in path if p["label"] == label), None)
|
|
96
|
+
if target is None:
|
|
97
|
+
raise LineError("point_not_found", "当前组内不存在该点名;请核对点名,不按位置或近似名称猜点。")
|
|
98
|
+
if point_time is not None: target["time"] = resolve_anchor_time(payload, point_time)
|
|
99
|
+
if point_price is not None: target["price"] = validate_line_fields(price=point_price)[0]
|
|
100
|
+
elif point_time is not None or point_price is not None:
|
|
101
|
+
raise LineError("point_label_required", "修改单点必须明确组内 point_label。")
|
|
102
|
+
elif name is None and color is None:
|
|
103
|
+
raise LineError("empty_update", "请指定点名及新时间 / 价格,或整组名称 / 颜色。")
|
|
104
|
+
path = validate_stored_points(path)
|
|
105
|
+
for point in path: resolve_anchor_time(payload, str(point["time"]))
|
|
106
|
+
obj = {"type": POLYLINE_COMMAND, "id": previous["id"] if previous else "poly_" + secrets.token_hex(12),
|
|
107
|
+
"interval": payload.get("interval"), "points": path,
|
|
108
|
+
"label": name if name is not None else previous["label"] if previous else "",
|
|
109
|
+
"color": color if color is not None else previous["color"] if previous else "info"}
|
|
110
|
+
if previous and previous.get("create_request_id"): obj["create_request_id"] = previous["create_request_id"]
|
|
111
|
+
if action == "create":
|
|
112
|
+
if request_id:
|
|
113
|
+
obj["create_request_id"] = request_id
|
|
114
|
+
obj["id"] = "poly_" + hashlib.sha256(request_id.encode()).hexdigest()[:24]
|
|
115
|
+
retry = next((c for c in commands if c.get("type") == POLYLINE_COMMAND and c.get("create_request_id") == request_id), None)
|
|
116
|
+
if retry:
|
|
117
|
+
if any(retry.get(k) != obj[k] for k in ("points", "label", "color", "interval")):
|
|
118
|
+
raise LineError("request_conflict", "同一 request_id 的标注折线参数不同。")
|
|
119
|
+
return result, deepcopy(retry)
|
|
120
|
+
if sum(c.get("type") == POLYLINE_COMMAND for c in commands) >= MAX_POLYLINES:
|
|
121
|
+
raise LineError("too_many_polylines", "当前图表最多保存30组 AI 标注折线。")
|
|
122
|
+
commands.append(obj)
|
|
123
|
+
else:
|
|
124
|
+
commands[commands.index(previous)] = obj
|
|
125
|
+
return result, deepcopy(obj)
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
"""Bounded, candle-aligned fill between two deterministic price sources."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from copy import deepcopy
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
import math
|
|
8
|
+
import secrets
|
|
9
|
+
from typing import Literal
|
|
10
|
+
|
|
11
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
12
|
+
|
|
13
|
+
from tools.lines import LineError, validate_line_fields
|
|
14
|
+
from tools.price_series import PriceCondition, PriceSource, calculate_price_series, candle_sequence_hash, MAX_SERIES_BARS
|
|
15
|
+
|
|
16
|
+
BAND_COMMAND = "DRAW_AGENT_PRICE_BAND"
|
|
17
|
+
MAX_PRICE_BANDS = 4
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class BollBandSource(BaseModel):
|
|
21
|
+
"""Metadata for one selected TA-Lib BBANDS group, not host-supplied prices."""
|
|
22
|
+
model_config = ConfigDict(extra="forbid")
|
|
23
|
+
kind: Literal["bbands"]
|
|
24
|
+
output: Literal["upperband", "lowerband"]
|
|
25
|
+
period: int = Field(strict=True, ge=2, le=200)
|
|
26
|
+
deviation_up: float = Field(gt=0, le=5, allow_inf_nan=False)
|
|
27
|
+
deviation_down: float = Field(gt=0, le=5, allow_inf_nan=False)
|
|
28
|
+
matype: Literal[0] = 0
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _band_source(value, output):
|
|
32
|
+
if isinstance(value, dict) and value.get("kind") == "bbands":
|
|
33
|
+
source = BollBandSource.model_validate(value).model_dump()
|
|
34
|
+
if source["output"] != output:
|
|
35
|
+
raise LineError("invalid_boll_source", "BOLL 上下轨来源不匹配。")
|
|
36
|
+
return source
|
|
37
|
+
return PriceSource.model_validate(value).model_dump(exclude_none=True)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _middle_values(values, lower, upper):
|
|
41
|
+
if not isinstance(values, list) or len(values) != len(lower):
|
|
42
|
+
raise LineError("invalid_boll_middle", "BOLL 中轨长度与当前K线不一致。")
|
|
43
|
+
for middle, low, high in zip(values, lower, upper):
|
|
44
|
+
if low is None:
|
|
45
|
+
if middle is None: continue
|
|
46
|
+
raise LineError("invalid_boll_middle", "BOLL 中轨空值须与上下轨同步。")
|
|
47
|
+
if (type(middle) not in (int, float) or not math.isfinite(middle)
|
|
48
|
+
or not low < middle < high):
|
|
49
|
+
raise LineError("invalid_boll_middle", "BOLL 中轨必须在有效上下轨之间,空值须同步。")
|
|
50
|
+
return list(values)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def calculate_price_band(rows, upper_source: PriceSource, lower_source: PriceSource,
|
|
54
|
+
condition: PriceCondition | None = None):
|
|
55
|
+
upper = calculate_price_series(rows, upper_source, condition)["values"]
|
|
56
|
+
lower = calculate_price_series(rows, lower_source, condition)["values"]
|
|
57
|
+
upper_values, lower_values = [], []
|
|
58
|
+
for high, low in zip(upper, lower):
|
|
59
|
+
if high is None or low is None:
|
|
60
|
+
upper_values.append(None); lower_values.append(None)
|
|
61
|
+
elif high <= low:
|
|
62
|
+
raise LineError("invalid_price_band_order", "条件命中的上下边界必须严格保持上方高于下方;未交换或忽略交叉K线。")
|
|
63
|
+
else:
|
|
64
|
+
upper_values.append(high); lower_values.append(low)
|
|
65
|
+
matches = sum(value is not None for value in upper_values)
|
|
66
|
+
segments = sum(value is not None and (index == 0 or upper_values[index - 1] is None)
|
|
67
|
+
for index, value in enumerate(upper_values))
|
|
68
|
+
return {"upper_values": upper_values, "lower_values": lower_values,
|
|
69
|
+
"summary": {"loaded_bars": len(rows), "matched_bars": matches,
|
|
70
|
+
"segment_count": segments, "empty": matches == 0,
|
|
71
|
+
"warmup_or_condition_gaps": len(rows) - matches, "drawing_created": False}}
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def validate_band_values(upper_values, lower_values, count):
|
|
75
|
+
if (type(count) is not int or not 1 <= count <= MAX_SERIES_BARS
|
|
76
|
+
or not isinstance(upper_values, list) or not isinstance(lower_values, list)
|
|
77
|
+
or len(upper_values) != count or len(lower_values) != count):
|
|
78
|
+
raise LineError("invalid_price_band_values", "带状序列长度与当前K线不一致。")
|
|
79
|
+
for high, low in zip(upper_values, lower_values):
|
|
80
|
+
if high is None and low is None: continue
|
|
81
|
+
if (type(high) not in (int, float) or type(low) not in (int, float)
|
|
82
|
+
or not math.isfinite(high) or not math.isfinite(low) or low <= 0 or high <= low):
|
|
83
|
+
raise LineError("invalid_price_band_values", "带状边界无效或空值未成对出现。")
|
|
84
|
+
if not any(value is not None for value in upper_values):
|
|
85
|
+
raise LineError("empty_price_band", "条件没有命中可填充K线,未创建空带。")
|
|
86
|
+
return list(upper_values), list(lower_values)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def edit_price_band(payload, action, *, band_id=None, upper_source=None, lower_source=None,
|
|
90
|
+
condition=None, upper_values=None, lower_values=None, middle_values=None, name=None, color=None,
|
|
91
|
+
request_id=None):
|
|
92
|
+
result = deepcopy(payload)
|
|
93
|
+
commands = result.get("chartCommands", [])
|
|
94
|
+
rows = next((c.get("rows", []) for c in commands if c.get("type") == "SET_CANDLES"), [])
|
|
95
|
+
matches = [c for c in commands if c.get("type") == BAND_COMMAND and c.get("id") == band_id]
|
|
96
|
+
if len(matches) > 1: raise LineError("ambiguous_drawing_id", "同一带状对象 ID 不唯一。")
|
|
97
|
+
previous = matches[0] if matches else None
|
|
98
|
+
if action in {"update", "delete"} and previous is None:
|
|
99
|
+
raise LineError("price_band_not_found", "当前图不存在该 AI 带状对象。")
|
|
100
|
+
if action == "delete":
|
|
101
|
+
if any(value is not None for value in (upper_source, lower_source, condition, upper_values,
|
|
102
|
+
lower_values, middle_values, name, color)):
|
|
103
|
+
raise LineError("invalid_edit_fields", "删除带状对象只需对象 ID。")
|
|
104
|
+
commands.remove(previous)
|
|
105
|
+
return result, deepcopy(previous)
|
|
106
|
+
if action not in {"create", "update"}: raise LineError("invalid_action", "不支持的带状对象操作。")
|
|
107
|
+
_, name, color = validate_line_fields(name=name, color=color, request_id=request_id)
|
|
108
|
+
supplied = [upper_source, lower_source, upper_values, lower_values]
|
|
109
|
+
if action == "create" and any(value is None for value in supplied):
|
|
110
|
+
raise LineError("band_result_required", "创建带状对象必须使用完整函数结果引用。")
|
|
111
|
+
if any(value is None for value in supplied) and any(value is not None for value in supplied):
|
|
112
|
+
raise LineError("band_result_required", "修改边界或条件时须重新运行函数并使用完整结果引用。")
|
|
113
|
+
if all(value is None for value in supplied) and middle_values is not None:
|
|
114
|
+
raise LineError("band_result_required", "修改 BOLL 中轨必须重新运行函数并使用完整结果引用。")
|
|
115
|
+
if action == "update" and all(value is None for value in supplied) and name is None and color is None:
|
|
116
|
+
raise LineError("empty_update", "请指定新函数结果、名称或颜色。")
|
|
117
|
+
if all(value is not None for value in supplied):
|
|
118
|
+
upper_values, lower_values = validate_band_values(upper_values, lower_values, len(rows))
|
|
119
|
+
upper_source = _band_source(upper_source, "upperband")
|
|
120
|
+
lower_source = _band_source(lower_source, "lowerband")
|
|
121
|
+
is_boll = upper_source["kind"] == "bbands"
|
|
122
|
+
if is_boll != (lower_source["kind"] == "bbands"):
|
|
123
|
+
raise LineError("invalid_boll_source", "BOLL 上下轨必须来自同一组计算。")
|
|
124
|
+
if is_boll:
|
|
125
|
+
if (condition is not None or {k: v for k, v in upper_source.items() if k != "output"}
|
|
126
|
+
!= {k: v for k, v in lower_source.items() if k != "output"}):
|
|
127
|
+
raise LineError("invalid_boll_source", "BOLL 上中下轨必须使用同一函数参数且不可附加条件。")
|
|
128
|
+
middle_values = _middle_values(middle_values, lower_values, upper_values)
|
|
129
|
+
elif middle_values is not None:
|
|
130
|
+
raise LineError("invalid_boll_middle", "普通价带不能附带 BOLL 中轨。")
|
|
131
|
+
condition = PriceCondition.model_validate(condition).model_dump(exclude_none=True) if condition is not None else None
|
|
132
|
+
else:
|
|
133
|
+
upper_values, lower_values = validate_band_values(previous["upper_values"], previous["lower_values"], len(rows))
|
|
134
|
+
upper_source, lower_source, condition = previous["upper_source"], previous["lower_source"], previous.get("condition")
|
|
135
|
+
middle_values = previous.get("middle_values")
|
|
136
|
+
obj = {"type": BAND_COMMAND, "id": previous["id"] if previous else "band_" + secrets.token_hex(12),
|
|
137
|
+
"interval": payload.get("interval"), "bar_count": len(rows),
|
|
138
|
+
"row_hash": candle_sequence_hash(rows),
|
|
139
|
+
"upper_source": upper_source, "lower_source": lower_source, "condition": condition,
|
|
140
|
+
"upper_values": upper_values, "lower_values": lower_values,
|
|
141
|
+
"label": name if name is not None else previous.get("label", "") if previous else "",
|
|
142
|
+
"color": color if color is not None else previous.get("color", "info") if previous else "info"}
|
|
143
|
+
if middle_values is not None:
|
|
144
|
+
obj["middle_values"] = middle_values
|
|
145
|
+
obj["band_hash"] = hashlib.sha256(json.dumps({"upper_source": upper_source, "lower_source": lower_source,
|
|
146
|
+
"condition": condition, "upper_values": upper_values, "lower_values": lower_values,
|
|
147
|
+
**({"middle_values": middle_values} if middle_values is not None else {})},
|
|
148
|
+
ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()).hexdigest()
|
|
149
|
+
if previous and previous.get("create_request_id"): obj["create_request_id"] = previous["create_request_id"]
|
|
150
|
+
if action == "create":
|
|
151
|
+
if request_id:
|
|
152
|
+
obj["create_request_id"] = request_id
|
|
153
|
+
obj["id"] = "band_" + hashlib.sha256(request_id.encode()).hexdigest()[:24]
|
|
154
|
+
retry = next((c for c in commands if c.get("type") == BAND_COMMAND and c.get("create_request_id") == request_id), None)
|
|
155
|
+
if retry:
|
|
156
|
+
if any(retry.get(key) != obj.get(key) for key in ("interval", "bar_count", "upper_source", "lower_source",
|
|
157
|
+
"condition", "upper_values", "lower_values", "middle_values", "label", "color")):
|
|
158
|
+
raise LineError("request_conflict", "同一 request_id 的带状参数不同。")
|
|
159
|
+
return result, deepcopy(retry)
|
|
160
|
+
if sum(c.get("type") == BAND_COMMAND for c in commands) >= MAX_PRICE_BANDS:
|
|
161
|
+
raise LineError("too_many_price_bands", "当前图最多保存4个 AI 带状对象。")
|
|
162
|
+
commands.append(obj)
|
|
163
|
+
else:
|
|
164
|
+
commands[commands.index(previous)] = obj
|
|
165
|
+
return result, deepcopy(obj)
|