@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.
Files changed (122) hide show
  1. package/lib/client.js +9 -1
  2. package/package.json +2 -5
  3. package/src/client/index.js +8 -0
  4. package/node_modules/@ftshare-lab/dsh-kline/CHANGELOG.md +0 -564
  5. package/node_modules/@ftshare-lab/dsh-kline/LICENSE +0 -21
  6. package/node_modules/@ftshare-lab/dsh-kline/PROVENANCE.md +0 -13
  7. package/node_modules/@ftshare-lab/dsh-kline/README.en.md +0 -265
  8. package/node_modules/@ftshare-lab/dsh-kline/README.md +0 -281
  9. package/node_modules/@ftshare-lab/dsh-kline/chart_service.py +0 -686
  10. package/node_modules/@ftshare-lab/dsh-kline/config/basic-symbols.json +0 -570
  11. package/node_modules/@ftshare-lab/dsh-kline/config/dsh-kline.patch.yml +0 -4
  12. package/node_modules/@ftshare-lab/dsh-kline/config/dsh-tool-catalog.json +0 -3783
  13. package/node_modules/@ftshare-lab/dsh-kline/cordis.patch.yml +0 -33
  14. package/node_modules/@ftshare-lab/dsh-kline/core/__init__.py +0 -0
  15. package/node_modules/@ftshare-lab/dsh-kline/core/adjustment.py +0 -16
  16. package/node_modules/@ftshare-lab/dsh-kline/core/calc.py +0 -683
  17. package/node_modules/@ftshare-lab/dsh-kline/core/rows.py +0 -228
  18. package/node_modules/@ftshare-lab/dsh-kline/core/ta_engine.py +0 -99
  19. package/node_modules/@ftshare-lab/dsh-kline/lib/candle-sequence.js +0 -15
  20. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-adjustment.js +0 -7
  21. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-annotations.js +0 -33
  22. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-applications.js +0 -171
  23. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-context.js +0 -164
  24. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-observation.js +0 -241
  25. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-service-status.js +0 -82
  26. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-source-status.js +0 -39
  27. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-sources.js +0 -349
  28. package/node_modules/@ftshare-lab/dsh-kline/lib/client.js +0 -15445
  29. package/node_modules/@ftshare-lab/dsh-kline/lib/drawing-feedback.js +0 -252
  30. package/node_modules/@ftshare-lab/dsh-kline/lib/fibonacci.js +0 -18
  31. package/node_modules/@ftshare-lab/dsh-kline/lib/ftshare-settings-bridge.js +0 -159
  32. package/node_modules/@ftshare-lab/dsh-kline/lib/index.js +0 -279
  33. package/node_modules/@ftshare-lab/dsh-kline/lib/labeled-polyline.js +0 -17
  34. package/node_modules/@ftshare-lab/dsh-kline/lib/price-bands.js +0 -55
  35. package/node_modules/@ftshare-lab/dsh-kline/lib/price-series.js +0 -47
  36. package/node_modules/@ftshare-lab/dsh-kline/lib/price-sticks.js +0 -32
  37. package/node_modules/@ftshare-lab/dsh-kline/lib/types/candle-sequence.d.ts +0 -2
  38. package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-adjustment.d.ts +0 -2
  39. package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-annotations.d.ts +0 -4
  40. package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-applications.d.ts +0 -26
  41. package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-context.d.ts +0 -14
  42. package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-observation.d.ts +0 -8
  43. package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-service-status.d.ts +0 -22
  44. package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-source-status.d.ts +0 -47
  45. package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-sources.d.ts +0 -25
  46. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/BetterSidebarTab.d.ts +0 -12
  47. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/ClassicShell.d.ts +0 -4
  48. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/KlineContent.d.ts +0 -37
  49. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/PaperKlinePanel.d.ts +0 -15
  50. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/canvas-panel.d.ts +0 -33
  51. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/chart-apply.d.ts +0 -13
  52. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/chart-context.d.ts +0 -23
  53. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/chart-session-resolver.d.ts +0 -2
  54. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/client-context.d.ts +0 -14
  55. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/conversation.d.ts +0 -39
  56. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/default-tab.d.ts +0 -3
  57. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/embed.d.ts +0 -37
  58. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/generated-view.d.ts +0 -2
  59. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/horizontal-lines.d.ts +0 -1
  60. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/host-services.d.ts +0 -55
  61. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/index.d.ts +0 -4
  62. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/mode-preferences.d.ts +0 -13
  63. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar-contract.d.ts +0 -52
  64. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar-register.d.ts +0 -46
  65. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar-services.d.ts +0 -45
  66. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar.d.ts +0 -47
  67. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/sidebar-integration.d.ts +0 -12
  68. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/ui-onboarding.d.ts +0 -13
  69. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/version.d.ts +0 -1
  70. package/node_modules/@ftshare-lab/dsh-kline/lib/types/drawing-feedback.d.ts +0 -5
  71. package/node_modules/@ftshare-lab/dsh-kline/lib/types/fibonacci.d.ts +0 -5
  72. package/node_modules/@ftshare-lab/dsh-kline/lib/types/ftshare-settings-bridge.d.ts +0 -50
  73. package/node_modules/@ftshare-lab/dsh-kline/lib/types/index.d.ts +0 -26
  74. package/node_modules/@ftshare-lab/dsh-kline/lib/types/labeled-polyline.d.ts +0 -11
  75. package/node_modules/@ftshare-lab/dsh-kline/lib/types/price-bands.d.ts +0 -3
  76. package/node_modules/@ftshare-lab/dsh-kline/lib/types/price-series.d.ts +0 -5
  77. package/node_modules/@ftshare-lab/dsh-kline/lib/types/price-sticks.d.ts +0 -3
  78. package/node_modules/@ftshare-lab/dsh-kline/package.json +0 -136
  79. package/node_modules/@ftshare-lab/dsh-kline/requirements.txt +0 -6
  80. package/node_modules/@ftshare-lab/dsh-kline/scripts/bootstrap.sh +0 -5
  81. package/node_modules/@ftshare-lab/dsh-kline/scripts/dsh-bootstrap.mjs +0 -179
  82. package/node_modules/@ftshare-lab/dsh-kline/scripts/dsh-mcp-plugin.mjs +0 -27
  83. package/node_modules/@ftshare-lab/dsh-kline/scripts/run-dsh-kline.mjs +0 -655
  84. package/node_modules/@ftshare-lab/dsh-kline/scripts/run-dsh-kline.sh +0 -5
  85. package/node_modules/@ftshare-lab/dsh-kline/server.py +0 -1734
  86. package/node_modules/@ftshare-lab/dsh-kline/tools/__init__.py +0 -0
  87. package/node_modules/@ftshare-lab/dsh-kline/tools/annotations.py +0 -119
  88. package/node_modules/@ftshare-lab/dsh-kline/tools/baostock_source.py +0 -176
  89. package/node_modules/@ftshare-lab/dsh-kline/tools/calc.py +0 -39
  90. package/node_modules/@ftshare-lab/dsh-kline/tools/channel_candidates.py +0 -260
  91. package/node_modules/@ftshare-lab/dsh-kline/tools/channel_preview.py +0 -82
  92. package/node_modules/@ftshare-lab/dsh-kline/tools/channels.py +0 -104
  93. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_applications.py +0 -204
  94. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_context.py +0 -186
  95. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_edits.py +0 -345
  96. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_functions.py +0 -466
  97. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_indicators.py +0 -63
  98. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_measurements.py +0 -84
  99. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_source_status.py +0 -32
  100. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_sources.py +0 -31
  101. package/node_modules/@ftshare-lab/dsh-kline/tools/draw.py +0 -394
  102. package/node_modules/@ftshare-lab/dsh-kline/tools/drawing_feedback.py +0 -45
  103. package/node_modules/@ftshare-lab/dsh-kline/tools/drawing_interaction.py +0 -117
  104. package/node_modules/@ftshare-lab/dsh-kline/tools/drawing_verification.py +0 -141
  105. package/node_modules/@ftshare-lab/dsh-kline/tools/fetch.py +0 -4681
  106. package/node_modules/@ftshare-lab/dsh-kline/tools/fibonacci.py +0 -83
  107. package/node_modules/@ftshare-lab/dsh-kline/tools/foreign_daily.py +0 -185
  108. package/node_modules/@ftshare-lab/dsh-kline/tools/free_sources.py +0 -483
  109. package/node_modules/@ftshare-lab/dsh-kline/tools/lines.py +0 -91
  110. package/node_modules/@ftshare-lab/dsh-kline/tools/pivots.py +0 -60
  111. package/node_modules/@ftshare-lab/dsh-kline/tools/polylines.py +0 -125
  112. package/node_modules/@ftshare-lab/dsh-kline/tools/price_bands.py +0 -165
  113. package/node_modules/@ftshare-lab/dsh-kline/tools/price_series.py +0 -162
  114. package/node_modules/@ftshare-lab/dsh-kline/tools/price_sticks.py +0 -114
  115. package/node_modules/@ftshare-lab/dsh-kline/tools/range_candidates.py +0 -170
  116. package/node_modules/@ftshare-lab/dsh-kline/tools/rectangles.py +0 -76
  117. package/node_modules/@ftshare-lab/dsh-kline/tools/regression_channels.py +0 -87
  118. package/node_modules/@ftshare-lab/dsh-kline/tools/ta_functions.py +0 -228
  119. package/node_modules/@ftshare-lab/dsh-kline/tools/trend_lines.py +0 -106
  120. package/node_modules/@ftshare-lab/dsh-kline/tools/watchlist.py +0 -149
  121. package/node_modules/@ftshare-lab/dsh-kline/view/ft-logo.jpg +0 -0
  122. package/node_modules/@ftshare-lab/dsh-kline/view/vendor/klinecharts.min.js +0 -7
@@ -1,119 +0,0 @@
1
- """Explicit, time/price anchored text, numeric and icon chart annotations."""
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
- ANNOTATION_COMMAND = "DRAW_AGENT_ANNOTATION"
13
- ANNOTATION_KINDS = {"text_annotation", "number_annotation", "icon_annotation"}
14
- ANNOTATION_ICONS = {"arrow_up", "arrow_down", "diamond"}
15
- MAX_ANNOTATIONS = 80
16
-
17
-
18
- def _validate_content(kind, text, value, icon=None):
19
- if kind == "text_annotation":
20
- if not isinstance(text, str) or not 1 <= len(text.strip()) <= 120 or any(ord(c) < 32 for c in text):
21
- raise LineError("invalid_annotation_text", "文字标注需为1至120个字符,且不能包含控制字符。")
22
- if value is not None or icon is not None: raise LineError("invalid_edit_fields", "文字标注不能设置数值或图标字段。")
23
- return text.strip(), None
24
- if kind == "number_annotation":
25
- if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):
26
- raise LineError("invalid_annotation_value", "数值标注必须是有限数字。")
27
- if text is not None or icon is not None: raise LineError("invalid_edit_fields", "数值标注不能设置文字或图标字段。")
28
- return None, float(value)
29
- if kind == "icon_annotation":
30
- if icon not in ANNOTATION_ICONS:
31
- raise LineError("invalid_annotation_icon", "图标标注仅支持 arrow_up、arrow_down 或 diamond。")
32
- if text is not None or value is not None: raise LineError("invalid_edit_fields", "图标标注不能设置文字或数值字段。")
33
- return None, None
34
- raise LineError("invalid_annotation_kind", "不支持的标注类型。")
35
-
36
-
37
- def validate_annotation(command):
38
- if not isinstance(command, dict) or command.get("type") != ANNOTATION_COMMAND:
39
- raise LineError("invalid_annotation", "标注对象格式无效。")
40
- kind = command.get("kind")
41
- text, value = _validate_content(kind, command.get("text"), command.get("value"), command.get("icon"))
42
- time, price = command.get("time"), command.get("price")
43
- if type(time) is not int or time <= 0 or isinstance(price, bool) or not isinstance(price, (int, float)) or not math.isfinite(price) or price <= 0:
44
- raise LineError("invalid_annotation_anchor", "标注锚点必须包含有效 K 线时间和大于零的价格。")
45
- return {"type": ANNOTATION_COMMAND, "kind": kind, "id": command["id"], "interval": command.get("interval"),
46
- "label": command.get("label", ""), "color": command.get("color", "info"), "time": time,
47
- "price": float(price), **({"text": text} if kind == "text_annotation" else
48
- {"value": value} if kind == "number_annotation" else {"icon": command["icon"]})}
49
-
50
-
51
- def edit_annotation(payload, action, *, kind, annotation_id=None, anchor_time=None, anchor_price=None,
52
- text=None, value=None, icon=None, name=None, color=None, request_id=None):
53
- result = deepcopy(payload)
54
- commands = result.get("chartCommands", [])
55
- matches = [c for c in commands if c.get("type") == ANNOTATION_COMMAND and c.get("id") == annotation_id]
56
- if len(matches) > 1: raise LineError("ambiguous_drawing_id", "同一标注 ID 不唯一,不能安全修改。")
57
- previous = matches[0] if matches else None
58
- if action in {"update", "delete"} and previous is None:
59
- raise LineError("annotation_not_found", "当前快照不存在该 AI 标注,请先读取完整对象 ID。")
60
- if previous and previous.get("kind") != kind:
61
- raise LineError("drawing_kind_mismatch", "标注 ID 与指定类型不一致。")
62
- if action == "delete":
63
- if any(v is not None for v in (anchor_time, anchor_price, text, value, icon, name, color)):
64
- raise LineError("invalid_edit_fields", "删除标注只需对象 ID。")
65
- commands.remove(previous)
66
- return result, deepcopy(previous)
67
- if action not in {"create", "update"} or kind not in ANNOTATION_KINDS:
68
- raise LineError("invalid_annotation_kind", "不支持的标注类型或操作。")
69
- _, name, color = validate_line_fields(name=name, color=color, request_id=request_id)
70
- if action == "create":
71
- if anchor_time is None or anchor_price is None:
72
- raise LineError("annotation_anchor_required", "创建标注必须明确指定已加载 K 线时间和价格。")
73
- text, value = _validate_content(kind, text, value, icon)
74
- timestamp = resolve_anchor_time(payload, anchor_time)
75
- price, _, _ = validate_line_fields(price=anchor_price)
76
- if price is None: raise LineError("invalid_annotation_anchor", "标注价格无效。")
77
- else:
78
- if anchor_time is None and anchor_price is None and text is None and value is None and icon is None and name is None and color is None:
79
- raise LineError("empty_update", "请指定标注的新位置、内容、名称或颜色。")
80
- old = validate_annotation(previous)
81
- timestamp = resolve_anchor_time(payload, anchor_time) if anchor_time is not None else old["time"]
82
- price = validate_line_fields(price=anchor_price)[0] if anchor_price is not None else old["price"]
83
- if kind == "text_annotation":
84
- if value is not None: raise LineError("invalid_edit_fields", "文字标注不能设置数值字段。")
85
- content, number = _validate_content(kind, text if text is not None else old.get("text"), None)
86
- icon = None
87
- elif kind == "number_annotation":
88
- if text is not None: raise LineError("invalid_edit_fields", "数值标注不能设置文字字段。")
89
- content, number = _validate_content(kind, None, value if value is not None else old.get("value"))
90
- icon = None
91
- else:
92
- if text is not None or value is not None: raise LineError("invalid_edit_fields", "图标标注不能设置文字或数值字段。")
93
- content, number = _validate_content(kind, None, None, icon if icon is not None else old.get("icon"))
94
- icon = icon if icon is not None else old.get("icon")
95
- text, value = content, number
96
- obj = {"type": ANNOTATION_COMMAND, "kind": kind,
97
- "id": previous["id"] if previous else "ann_" + secrets.token_hex(12),
98
- "interval": payload.get("interval"), "label": name if name is not None else previous.get("label", "") if previous else "",
99
- "color": color if color is not None else previous.get("color", "info") if previous else "info",
100
- "time": timestamp, "price": float(price)}
101
- if kind == "text_annotation": obj["text"] = text
102
- elif kind == "number_annotation": obj["value"] = value
103
- else: obj["icon"] = icon
104
- if previous and previous.get("create_request_id"): obj["create_request_id"] = previous["create_request_id"]
105
- if action == "create":
106
- if request_id:
107
- obj["create_request_id"] = request_id
108
- obj["id"] = "ann_" + hashlib.sha256(request_id.encode()).hexdigest()[:24]
109
- retry = next((c for c in commands if c.get("type") == ANNOTATION_COMMAND and c.get("create_request_id") == request_id), None)
110
- if retry:
111
- if any(retry.get(k) != obj[k] for k in ("kind", "label", "color", "time", "price", "text", "value", "icon")):
112
- raise LineError("request_conflict", "同一 request_id 的标注参数不同。")
113
- return result, deepcopy(retry)
114
- if sum(c.get("type") == ANNOTATION_COMMAND for c in commands) >= MAX_ANNOTATIONS:
115
- raise LineError("too_many_annotations", "当前图表最多保存80个 AI 标注。")
116
- commands.append(obj)
117
- else:
118
- commands[commands.index(previous)] = obj
119
- return result, deepcopy(obj)
@@ -1,176 +0,0 @@
1
- """Bounded, key-less A-share daily candle fallback via BaoStock's public SDK.
2
-
3
- The SDK keeps a process-global socket and may wait indefinitely for a reply.
4
- Run each request in a short-lived child process so a failing free service cannot
5
- block the MCP server or contaminate another chart's provider connection.
6
- """
7
-
8
- from __future__ import annotations
9
-
10
- import contextlib
11
- import importlib.util
12
- import io
13
- import json
14
- import math
15
- import os
16
- import re
17
- import socket
18
- import subprocess
19
- import sys
20
- import threading
21
- import time
22
- from copy import deepcopy
23
- from datetime import datetime, timedelta, timezone
24
- from pathlib import Path
25
- from typing import Any
26
-
27
-
28
- SOURCE = "baostock_free"
29
- SOURCE_URL = "https://www.baostock.com/"
30
- _SHANGHAI = timezone(timedelta(hours=8))
31
- _MAX_ROWS = 10_000
32
- _TIMEOUT_SECONDS = 12
33
- _FIELDS = "date,code,open,high,low,close,volume"
34
- _ADJUST_FLAGS = {"none": "3", "forward": "2", "backward": "1"}
35
- _CACHE_TTL_SECONDS = 90
36
- _CACHE_MAX_ENTRIES = 64
37
- _cache: dict[tuple[str, int, str], tuple[float, list[dict[str, Any]]]] = {}
38
- _cache_lock = threading.Lock()
39
-
40
-
41
- def source_status() -> dict[str, Any]:
42
- """Report installed capability without pretending to probe connectivity."""
43
- return {
44
- "installed": importlib.util.find_spec("baostock") is not None,
45
- "capabilities": ["cn_a_share_historical_daily_candles"],
46
- "requires_key": False,
47
- "reachability": "not_probed",
48
- "source_url": SOURCE_URL,
49
- }
50
-
51
-
52
- def eligible_stock_code(symbol: str) -> str | None:
53
- """Require an explicit exchange and an A-share stock prefix.
54
-
55
- This deliberately excludes indices, funds, B shares and bare codes. The
56
- BaoStock query does not accept our canonical symbol suffixes directly.
57
- """
58
- value = str(symbol or "").strip().upper()
59
- match = re.fullmatch(r"(\d{6})\.(XSHG|XSHE)", value)
60
- if not match:
61
- return None
62
- code, market = match.groups()
63
- if market == "XSHG" and code.startswith(("600", "601", "603", "605", "688", "689")):
64
- return f"sh.{code}"
65
- if market == "XSHE" and code.startswith(("000", "001", "002", "003", "300", "301", "302")):
66
- return f"sz.{code}"
67
- return None
68
-
69
-
70
- def _normalize_rows(raw_rows: Any, expected_code: str) -> list[dict[str, Any]]:
71
- if not isinstance(raw_rows, list) or len(raw_rows) > _MAX_ROWS:
72
- return []
73
- rows: list[dict[str, Any]] = []
74
- seen: set[int] = set()
75
- for raw in raw_rows:
76
- if not isinstance(raw, list) or len(raw) != 7 or raw[1] != expected_code:
77
- return []
78
- try:
79
- date = datetime.strptime(raw[0], "%Y-%m-%d").replace(hour=15, tzinfo=_SHANGHAI)
80
- stamp = int(date.timestamp())
81
- opened, high, low, closed, volume = map(float, raw[2:])
82
- except (TypeError, ValueError, OverflowError):
83
- return []
84
- if (
85
- stamp in seen or not all(map(math.isfinite, (opened, high, low, closed, volume)))
86
- or min(opened, high, low, closed) <= 0 or volume < 0
87
- or high < max(opened, low, closed) or low > min(opened, high, closed)
88
- ):
89
- return []
90
- seen.add(stamp)
91
- rows.append({"time": stamp, "open": opened, "high": high, "low": low, "close": closed, "volume": volume})
92
- rows.sort(key=lambda item: item["time"])
93
- return rows
94
-
95
-
96
- def fetch_stock_daily(symbol: str, *, limit: int, adjust: str) -> list[dict[str, Any]] | None:
97
- """Return recent normalized daily OHLCV, or None without changing state."""
98
- code = eligible_stock_code(symbol)
99
- if not code or adjust not in _ADJUST_FLAGS:
100
- return None
101
- wanted = max(2, min(int(limit), 4000))
102
- cache_key = (code, wanted, adjust)
103
- with _cache_lock:
104
- cached = _cache.get(cache_key)
105
- if cached and time.monotonic() - cached[0] < _CACHE_TTL_SECONDS:
106
- return deepcopy(cached[1])
107
- request = {"code": code, "limit": wanted, "adjustflag": _ADJUST_FLAGS[adjust]}
108
- # The fallback needs no account credential. Do not inherit the host's
109
- # FTShare key, DSH tokens, or unrelated secrets into the child process.
110
- child_env = {
111
- key: value for key, value in os.environ.items()
112
- if not re.search(r"(?:KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL|AUTH)", key, re.IGNORECASE)
113
- }
114
- try:
115
- process = subprocess.run(
116
- [sys.executable, str(Path(__file__).resolve()), "--worker"],
117
- input=json.dumps(request), text=True, capture_output=True,
118
- timeout=_TIMEOUT_SECONDS, check=False, env=child_env,
119
- )
120
- if process.returncode != 0 or len(process.stdout) > 1_500_000:
121
- return None
122
- payload = json.loads(process.stdout)
123
- rows = _normalize_rows(payload.get("rows"), code)
124
- if len(rows) < 2:
125
- return None
126
- result = rows[-wanted:]
127
- with _cache_lock:
128
- if len(_cache) >= _CACHE_MAX_ENTRIES:
129
- oldest = min(_cache, key=lambda item: _cache[item][0])
130
- _cache.pop(oldest, None)
131
- _cache[cache_key] = (time.monotonic(), result)
132
- return deepcopy(result)
133
- except (OSError, subprocess.TimeoutExpired, ValueError, TypeError):
134
- return None
135
-
136
-
137
- def _worker() -> int:
138
- """Isolated SDK session; all SDK chatter stays out of the JSON protocol."""
139
- try:
140
- request = json.load(sys.stdin)
141
- code = str(request["code"])
142
- wanted = int(request["limit"])
143
- flag = str(request["adjustflag"])
144
- if not re.fullmatch(r"(?:sh|sz)\.\d{6}", code) or not 2 <= wanted <= 4000 or flag not in _ADJUST_FLAGS.values():
145
- return 1
146
- import baostock as bs
147
-
148
- socket.setdefaulttimeout(5)
149
- end = datetime.now(_SHANGHAI).date()
150
- start = end - timedelta(days=min(365 * 30, max(365, int(wanted * 1.8))))
151
- with contextlib.redirect_stdout(io.StringIO()):
152
- login = bs.login()
153
- if str(login.error_code) != "0":
154
- return 1
155
- try:
156
- result = bs.query_history_k_data_plus(
157
- code, _FIELDS, start_date=start.isoformat(), end_date=end.isoformat(),
158
- frequency="d", adjustflag=flag,
159
- )
160
- if str(result.error_code) != "0" or list(result.fields or []) != _FIELDS.split(","):
161
- return 1
162
- rows = []
163
- while result.next():
164
- if len(rows) >= _MAX_ROWS:
165
- return 1
166
- rows.append(result.get_row_data())
167
- finally:
168
- bs.logout()
169
- sys.stdout.write(json.dumps({"rows": rows}, separators=(",", ":")))
170
- return 0
171
- except (Exception, KeyboardInterrupt): # noqa: BLE001 - child must fail closed
172
- return 1
173
-
174
-
175
- if __name__ == "__main__":
176
- raise SystemExit(_worker() if sys.argv[1:] == ["--worker"] else 1)
@@ -1,39 +0,0 @@
1
- """Small calculation wrapper used by the standalone dsh_kline MCP server."""
2
-
3
- from __future__ import annotations
4
-
5
- from typing import Any
6
-
7
- from core.calc import AVAILABLE_METRICS, calc_metrics as _calc_metrics
8
- from core.rows import validate_rows
9
-
10
-
11
- def run_calc_metrics(
12
- rows: Any,
13
- metrics: list[str] | None = None,
14
- *,
15
- rsi_period: int = 14,
16
- boll_period: int = 20,
17
- boll_std: float = 2.0,
18
- atr_period: int = 14,
19
- volume_ma: int = 20,
20
- ma_periods: list[int] | None = None,
21
- ) -> dict[str, Any]:
22
- normalized = validate_rows(rows, min_len=2)
23
- result = _calc_metrics(
24
- normalized,
25
- metrics=metrics,
26
- rsi_period=rsi_period,
27
- boll_period=boll_period,
28
- boll_std=boll_std,
29
- atr_period=atr_period,
30
- volume_ma=volume_ma,
31
- ma_periods=ma_periods,
32
- )
33
- result["available_metrics"] = list(AVAILABLE_METRICS)
34
- result["analysis_window"] = {
35
- "start_time": int(normalized[0]["time"]),
36
- "end_time": int(normalized[-1]["time"]),
37
- "bars": len(normalized),
38
- }
39
- return result
@@ -1,260 +0,0 @@
1
- """Read-only, rule-based three-anchor channel candidates on loaded candles.
2
-
3
- This module proposes geometry for human review. It neither publishes drawings
4
- nor claims that a candidate is the uniquely correct technical-analysis channel.
5
- """
6
- from __future__ import annotations
7
-
8
- from collections import Counter
9
- import math
10
- from statistics import median
11
-
12
- from core.rows import RowsValidationError, validate_rows
13
- from tools.lines import LineError
14
- from tools.pivots import confirmed_pivots
15
-
16
- RULE_VERSION = "confirmed_pivots_v3"
17
- MIN_TOTAL_MOVE_FRACTION = 0.03
18
- MAX_EXCESS_TO_WIDTH = 0.25
19
- MAX_OUTSIDE_BAR_FRACTION = 0.20
20
- MAX_WIDTH_FRACTION = 0.12
21
- MAX_WIDTH_TO_BASE_MOVE = 2.0
22
- MAX_CURRENT_END_AGE_BARS = 8
23
- SAME_FAMILY_SLOPE_TOLERANCE = 0.10
24
- SAME_FAMILY_WIDTH_TOLERANCE = 0.10
25
-
26
-
27
- def _measure_region(rows, *, first, start_price, slope, width, direction, start, stop):
28
- """Measure actual wicks against index-based edges, including any extension."""
29
- maximum = 0.0
30
- outside_count = 0
31
- latest_close_position = None
32
- for index in range(start, stop):
33
- base = start_price + slope * (index - first)
34
- upper, lower = (base + width, base) if direction == "ascending" else (base, base - width)
35
- row = rows[index]
36
- excess = max(0.0, row["high"] - upper, lower - row["low"])
37
- if not all(math.isfinite(value) for value in (base, upper, lower, excess)) or lower <= 0:
38
- return None
39
- maximum = max(maximum, excess)
40
- outside_count += excess > max(upper, lower) * 1e-12
41
- tolerance = max(upper, lower) * 1e-12
42
- latest_close_position = ("above_projected_upper" if row["close"] > upper + tolerance else
43
- "below_projected_lower" if row["close"] < lower - tolerance else "inside")
44
- return {"bar_count": stop - start, "outside_bar_count": outside_count,
45
- "outside_bar_fraction": outside_count / (stop - start) if stop > start else 0.0,
46
- "max_wick_excess_price": maximum, "max_wick_excess_to_width": maximum / width,
47
- "latest_close_position": latest_close_position}
48
-
49
-
50
- def _same_geometric_family(candidate, representative):
51
- """Collapse near-identical alternatives built around the same parallel pivot."""
52
- anchors, other = candidate["anchors"], representative["anchors"]
53
- if (candidate["direction"] != representative["direction"]
54
- or anchors["parallel"]["time"] != other["parallel"]["time"]):
55
- return False
56
- slope_scale = max(abs(candidate["slope_per_bar"]), abs(representative["slope_per_bar"]))
57
- width_scale = max(candidate["width"], representative["width"])
58
- return (abs(candidate["slope_per_bar"] - representative["slope_per_bar"])
59
- <= SAME_FAMILY_SLOPE_TOLERANCE * slope_scale
60
- and abs(candidate["width"] - representative["width"])
61
- <= SAME_FAMILY_WIDTH_TOLERANCE * width_scale)
62
-
63
-
64
- def channel_candidates(
65
- rows,
66
- *,
67
- direction="both",
68
- lookback_bars=120,
69
- left_bars=2,
70
- right_bars=2,
71
- min_span_bars=12,
72
- limit=3,
73
- scope="current",
74
- ):
75
- """Propose channels from two confirmed same-side pivots and one opposite pivot.
76
-
77
- Ascending channels use two rising pivot lows as the base and a pivot high
78
- between them as the parallel anchor; descending channels are symmetric.
79
- All coordinates are candle-index based, never elapsed-time or screen pixels.
80
- The anchor interval is measured in full. Current proposals must have a
81
- recent confirmed end pivot and pass an explicit arithmetic extension check
82
- through the latest loaded bar. Historical proposals never infer a current
83
- breakout. Neither scope confirms professional pattern quality.
84
- """
85
- if not isinstance(direction, str) or direction not in {"ascending", "descending", "both"}:
86
- raise LineError("invalid_channel_candidate_direction", "direction 只能是 ascending、descending 或 both。")
87
- if not isinstance(scope, str) or scope not in {"current", "historical"}:
88
- raise LineError("invalid_channel_candidate_scope", "scope 只能是 current 或 historical。")
89
- if type(lookback_bars) is not int or not 30 <= lookback_bars <= 300:
90
- raise LineError("invalid_channel_candidate_lookback", "lookback_bars 必须是30至300的整数。")
91
- if type(min_span_bars) is not int or not 10 <= min_span_bars <= 100 or min_span_bars >= lookback_bars:
92
- raise LineError("invalid_channel_candidate_span", "min_span_bars 必须是10至100且小于 lookback_bars。")
93
- if type(limit) is not int or not 1 <= limit <= 5:
94
- raise LineError("invalid_channel_candidate_limit", "limit 必须是1至5的整数。")
95
- if type(left_bars) is not int or not 1 <= left_bars <= 20 or type(right_bars) is not int or not 1 <= right_bars <= 20:
96
- raise LineError("invalid_pivot_window", "left_bars 和 right_bars 必须是1至20的整数。")
97
- # The pivot helper validates window parameters and does not use incomplete
98
- # right-hand windows. Its 50-candidate cap bounds pair enumeration.
99
- try:
100
- candles = validate_rows(rows, min_len=max(min_span_bars + 1, left_bars + right_bars + 1))
101
- except RowsValidationError:
102
- raise LineError("insufficient_channel_candidate_history", "当前已加载K线不足以计算通道候选;未补取行情。") from None
103
- selected = candles[-lookback_bars:]
104
- if any(row["low"] <= 0 or row["high"] < max(row["open"], row["close"], row["low"])
105
- or row["low"] > min(row["open"], row["close"]) for row in selected):
106
- raise LineError("invalid_channel_candidate_data", "通道候选需要高低价为正且 OHLC 一致的K线;未忽略异常柱。")
107
- pivot_result = confirmed_pivots(selected, left_bars=left_bars, right_bars=right_bars, limit=50)
108
- index_by_time = {row["time"]: index for index, row in enumerate(selected)}
109
- pivots = {side: [] for side in ("high", "low")}
110
- for pivot in pivot_result["candidates"]:
111
- pivots[pivot["side"]].append((index_by_time[int(pivot["time"])], pivot["price"]))
112
-
113
- candidates = []
114
- rejection_counts = Counter()
115
- considered_anchor_pairs = 0
116
- for trend in (("ascending", "low", "high"), ("descending", "high", "low")):
117
- name, base_side, opposite_side = trend
118
- if direction not in {"both", name}:
119
- continue
120
- base_pivots = pivots[base_side]
121
- for first_pos, (first, start_price) in enumerate(base_pivots):
122
- for last, end_price in base_pivots[first_pos + 1:]:
123
- span = last - first
124
- if span < min_span_bars:
125
- continue
126
- considered_anchor_pairs += 1
127
- slope = (end_price - start_price) / span
128
- move_fraction = abs(end_price - start_price) / start_price
129
- if (name == "ascending" and slope <= 0) or (name == "descending" and slope >= 0):
130
- rejection_counts["wrong_direction"] += 1
131
- continue
132
- if move_fraction < MIN_TOTAL_MOVE_FRACTION:
133
- rejection_counts["weak_base_move"] += 1
134
- continue
135
- opposite = []
136
- for index, price in pivots[opposite_side]:
137
- if first < index < last:
138
- base_at_pivot = start_price + slope * (index - first)
139
- width = (price - base_at_pivot) * (1 if name == "ascending" else -1)
140
- if math.isfinite(width) and width > 0:
141
- opposite.append((width, index, price))
142
- if not opposite:
143
- rejection_counts["no_interior_opposite_pivot"] += 1
144
- continue
145
- # The widest confirmed opposite pivot makes the parallel edge;
146
- # stable tie-breaking favors the earlier pivot.
147
- width, parallel_index, parallel_price = max(opposite, key=lambda value: (value[0], -value[1]))
148
- median_close = median(row["close"] for row in selected[first:last + 1])
149
- width_fraction = width / median_close
150
- width_to_base_move = width / abs(end_price - start_price)
151
- if not math.isfinite(width_fraction) or width_fraction > MAX_WIDTH_FRACTION:
152
- rejection_counts["too_wide_vs_price"] += 1
153
- continue
154
- if not math.isfinite(width_to_base_move) or width_to_base_move > MAX_WIDTH_TO_BASE_MOVE:
155
- rejection_counts["too_wide_vs_base_move"] += 1
156
- continue
157
- anchor_measurement = _measure_region(selected, first=first, start_price=start_price,
158
- slope=slope, width=width, direction=name, start=first, stop=last + 1)
159
- if (anchor_measurement is None or
160
- anchor_measurement["max_wick_excess_to_width"] > MAX_EXCESS_TO_WIDTH):
161
- rejection_counts["anchor_interval_boundary_breach"] += 1
162
- continue
163
- if anchor_measurement["outside_bar_fraction"] > MAX_OUTSIDE_BAR_FRACTION:
164
- rejection_counts["too_many_anchor_interval_breaches"] += 1
165
- continue
166
- age = len(selected) - 1 - last
167
- if scope == "current" and age > MAX_CURRENT_END_AGE_BARS:
168
- rejection_counts["end_anchor_too_old"] += 1
169
- continue
170
- post_end = {"evaluated": False, "reason": "historical_scope_no_current_inference"}
171
- if scope == "current":
172
- measured = _measure_region(selected, first=first, start_price=start_price,
173
- slope=slope, width=width, direction=name, start=last + 1, stop=len(selected))
174
- if measured is None:
175
- rejection_counts["invalid_post_end_projection"] += 1
176
- continue
177
- if (measured["max_wick_excess_to_width"] > MAX_EXCESS_TO_WIDTH
178
- or measured["latest_close_position"] != "inside"):
179
- rejection_counts["post_end_boundary_breach"] += 1
180
- continue
181
- post_end = {"evaluated": True, "basis": "arithmetic_extension_not_pattern_confirmation",
182
- **measured}
183
- anchors = {
184
- "from": {"time": selected[first]["time"], "price": start_price, "ohlc_field": base_side},
185
- "to": {"time": selected[last]["time"], "price": end_price, "ohlc_field": base_side},
186
- "parallel": {"time": selected[parallel_index]["time"], "price": parallel_price,
187
- "ohlc_field": opposite_side},
188
- }
189
- candidates.append({
190
- "direction": name,
191
- "anchors": anchors,
192
- "span_bars": span + 1,
193
- "bars_since_end": age,
194
- "slope_per_bar": slope,
195
- "width": width,
196
- "width_fraction_of_median_close": width_fraction,
197
- "width_to_base_move": width_to_base_move,
198
- "base_move_fraction": move_fraction,
199
- "max_wick_excess_price": anchor_measurement["max_wick_excess_price"],
200
- "max_wick_excess_to_width": anchor_measurement["max_wick_excess_to_width"],
201
- "outside_bar_count": anchor_measurement["outside_bar_count"],
202
- "outside_bar_fraction": anchor_measurement["outside_bar_fraction"],
203
- "post_end": post_end,
204
- "scope": scope,
205
- "anchor_rule": "two_confirmed_same_side_pivots_plus_widest_interior_opposite_pivot",
206
- "measurement_range": "anchor_interval_inclusive_post_end_separate",
207
- "_end_index": last,
208
- })
209
- # Newer, more compact, less-violated candidates first. No opaque score.
210
- candidates.sort(key=lambda item: (-item["_end_index"], item["max_wick_excess_to_width"],
211
- item["width_to_base_move"], -item["span_bars"],
212
- item["direction"], item["anchors"]["from"]["time"]))
213
- qualified_before_dedup = len(candidates)
214
- distinct = []
215
- seen_families = set()
216
- for candidate in candidates:
217
- del candidate["_end_index"]
218
- family = (candidate["direction"], candidate["anchors"]["to"]["time"],
219
- candidate["anchors"]["parallel"]["time"])
220
- if family in seen_families or any(_same_geometric_family(candidate, kept) for kept in distinct):
221
- continue
222
- seen_families.add(family)
223
- distinct.append(candidate)
224
- return {
225
- "rule_version": RULE_VERSION,
226
- "direction": direction,
227
- "scope": scope,
228
- "lookback_bars": lookback_bars,
229
- "left_bars": left_bars,
230
- "right_bars": right_bars,
231
- "min_span_bars": min_span_bars,
232
- "considered_anchor_pairs": considered_anchor_pairs,
233
- "rejection_counts": dict(sorted(rejection_counts.items())),
234
- "qualified_before_dedup": qualified_before_dedup,
235
- "deduplicated_count": qualified_before_dedup - len(distinct),
236
- "candidate_count": len(distinct),
237
- "returned": min(limit, len(distinct)),
238
- "truncated": len(distinct) > limit,
239
- "no_candidate_reason": "no_anchor_triple_passed_rules" if not distinct else None,
240
- "no_candidate_explanation": ("没有三锚点组合同时满足全部筛选规则;不能据此推断近期没有已确认拐点,或真实走势不存在通道。"
241
- if not distinct else None),
242
- "pivot_scan": {"considered": pivot_result["candidate_count"],
243
- "total": pivot_result["total_candidates"], "truncated": pivot_result["truncated"],
244
- "recent_confirmed_high_count": sum(len(selected) - 1 - index <= MAX_CURRENT_END_AGE_BARS
245
- for index, _ in pivots["high"]),
246
- "recent_confirmed_low_count": sum(len(selected) - 1 - index <= MAX_CURRENT_END_AGE_BARS
247
- for index, _ in pivots["low"])},
248
- "candidates": distinct[:limit],
249
- "thresholds": {"min_total_move_fraction": MIN_TOTAL_MOVE_FRACTION,
250
- "max_wick_excess_to_width": MAX_EXCESS_TO_WIDTH,
251
- "max_outside_bar_fraction": MAX_OUTSIDE_BAR_FRACTION,
252
- "max_width_fraction_of_median_close": MAX_WIDTH_FRACTION,
253
- "max_width_to_base_move": MAX_WIDTH_TO_BASE_MOVE,
254
- "max_current_end_age_bars": MAX_CURRENT_END_AGE_BARS,
255
- "same_family_slope_tolerance": SAME_FAMILY_SLOPE_TOLERANCE,
256
- "same_family_width_tolerance": SAME_FAMILY_WIDTH_TOLERANCE},
257
- "limitations": ["geometry_only_requires_human_review", "confirmed_pivots_lag_right_bars",
258
- "arithmetic_extension_not_breakout_confirmation", "no_drawing_created"],
259
- "drawing_created": False,
260
- }