@ftshare-lab/dsh-kline 0.0.0-stage → 0.6.11

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 (211) hide show
  1. package/CHANGELOG.md +611 -0
  2. package/LICENSE +21 -0
  3. package/PROVENANCE.md +13 -0
  4. package/README.en.md +171 -0
  5. package/README.md +170 -2
  6. package/chart_service.py +687 -0
  7. package/config/basic-symbols.json +570 -0
  8. package/config/dsh-kline.patch.yml +4 -0
  9. package/config/dsh-tool-catalog.json +3875 -0
  10. package/cordis.patch.yml +33 -0
  11. package/core/__init__.py +0 -0
  12. package/core/adjustment.py +16 -0
  13. package/core/calc.py +691 -0
  14. package/core/rows.py +228 -0
  15. package/core/ta_engine.py +99 -0
  16. package/docs/anonymous-market-support.md +33 -0
  17. package/docs/automatic-drawing.md +24 -0
  18. package/docs/chart-functions.md +136 -0
  19. package/docs/drawing-examples.en.md +13 -0
  20. package/docs/drawing-examples.md +13 -0
  21. package/docs/embedding.md +77 -0
  22. package/docs/fixtures/price-pattern-real-v1.json +1 -0
  23. package/docs/free-foreign-daily.md +44 -0
  24. package/docs/guide.en.md +232 -0
  25. package/docs/guide.md +248 -0
  26. package/docs/images/abc-drawing-v0.5.0.jpg +0 -0
  27. package/docs/images/channel-drawing-v0.5.0.jpg +0 -0
  28. package/docs/images/drawing-workbench-v0.5.0.jpg +0 -0
  29. package/docs/images/dsh-kline-tab-workspace.png +0 -0
  30. package/docs/images/dsh-market.png +0 -0
  31. package/docs/images/kline-news.png +0 -0
  32. package/docs/images/kline-range-stats.png +0 -0
  33. package/docs/images/kline-support.png +0 -0
  34. package/docs/images/main-chart-comparison-v0.6.9.png +0 -0
  35. package/docs/images/market-overview-v0.6.9.png +0 -0
  36. package/docs/images/natural-language-abc-wolong-2026-10-27.png +0 -0
  37. package/docs/images/natural-language-descending-channel-wolong-2026-10-27.png +0 -0
  38. package/docs/images/platform-breakout-msft-v0.6.9.png +0 -0
  39. package/docs/npm-release.md +33 -0
  40. package/docs/price-pattern-rules-v1.md +40 -0
  41. package/docs/price-pattern-samples-v1.md +42 -0
  42. package/docs/provider-adaptation.md +73 -0
  43. package/docs/release-acceptance-v0.4.0.md +46 -0
  44. package/docs/release-acceptance-v0.4.1.md +43 -0
  45. package/docs/release-acceptance-v0.5.0.md +40 -0
  46. package/docs/release-acceptance-v0.6.0.md +33 -0
  47. package/docs/release-acceptance-v0.6.1.md +19 -0
  48. package/docs/release-acceptance-v0.6.10.md +21 -0
  49. package/docs/release-acceptance-v0.6.11.md +21 -0
  50. package/docs/release-acceptance-v0.6.2.md +31 -0
  51. package/docs/release-acceptance-v0.6.3.md +25 -0
  52. package/docs/release-acceptance-v0.6.4.md +24 -0
  53. package/docs/release-acceptance-v0.6.5.md +21 -0
  54. package/docs/release-acceptance-v0.6.6.md +21 -0
  55. package/docs/release-acceptance-v0.6.7.md +18 -0
  56. package/docs/release-acceptance-v0.6.8.md +18 -0
  57. package/docs/release-acceptance-v0.6.9.md +98 -0
  58. package/docs/release-notes-v0.5.0.md +23 -0
  59. package/docs/release-notes-v0.6.0.md +11 -0
  60. package/docs/release-notes-v0.6.1.md +20 -0
  61. package/docs/release-notes-v0.6.10.md +11 -0
  62. package/docs/release-notes-v0.6.11.md +16 -0
  63. package/docs/release-notes-v0.6.2.md +14 -0
  64. package/docs/release-notes-v0.6.3.md +26 -0
  65. package/docs/release-notes-v0.6.4.md +12 -0
  66. package/docs/release-notes-v0.6.5.md +13 -0
  67. package/docs/release-notes-v0.6.6.md +13 -0
  68. package/docs/release-notes-v0.6.7.md +17 -0
  69. package/docs/release-notes-v0.6.8.md +10 -0
  70. package/docs/release-notes-v0.6.9.md +16 -0
  71. package/lib/candle-sequence.js +15 -0
  72. package/lib/chart-adjustment.js +7 -0
  73. package/lib/chart-annotations.js +33 -0
  74. package/lib/chart-applications.js +171 -0
  75. package/lib/chart-context.js +164 -0
  76. package/lib/chart-observation.js +251 -0
  77. package/lib/chart-service-status.js +82 -0
  78. package/lib/chart-source-status.js +39 -0
  79. package/lib/chart-sources.js +354 -0
  80. package/lib/client/BetterSidebarTab.js +70 -0
  81. package/lib/client/ClassicShell.js +254 -0
  82. package/lib/client/KlineContent.js +155 -0
  83. package/lib/client/PanelHost.js +46 -0
  84. package/lib/client/chart-apply.js +73 -0
  85. package/lib/client/chart-context.js +233 -0
  86. package/lib/client/chart-handoff.js +34 -0
  87. package/lib/client/chart-session-resolver.js +74 -0
  88. package/lib/client/client-context.js +1 -0
  89. package/lib/client/conversation.js +88 -0
  90. package/lib/client/default-tab.js +83 -0
  91. package/lib/client/embed.js +50 -0
  92. package/lib/client/generated-view.js +12983 -0
  93. package/lib/client/horizontal-lines.js +19 -0
  94. package/lib/client/host-options.js +41 -0
  95. package/lib/client/host-panels.js +111 -0
  96. package/lib/client/index.js +77 -0
  97. package/lib/client/mode-preferences.js +48 -0
  98. package/lib/client/native-sidebar-contract.js +45 -0
  99. package/lib/client/native-sidebar-register.js +133 -0
  100. package/lib/client/native-sidebar-services.js +1 -0
  101. package/lib/client/native-sidebar.js +98 -0
  102. package/lib/client/sidebar-integration.js +93 -0
  103. package/lib/client/ui-onboarding.js +48 -0
  104. package/lib/client/version.js +14 -0
  105. package/lib/client.js +17581 -0
  106. package/lib/client.js.map +1 -0
  107. package/lib/drawing-feedback.js +284 -0
  108. package/lib/fibonacci.js +18 -0
  109. package/lib/ftshare-settings-bridge.js +159 -0
  110. package/lib/index.js +279 -0
  111. package/lib/labeled-polyline.js +17 -0
  112. package/lib/pattern-groups.js +91 -0
  113. package/lib/price-bands.js +55 -0
  114. package/lib/price-series.js +47 -0
  115. package/lib/price-sticks.js +32 -0
  116. package/lib/types/candle-sequence.d.ts +2 -0
  117. package/lib/types/chart-adjustment.d.ts +2 -0
  118. package/lib/types/chart-annotations.d.ts +4 -0
  119. package/lib/types/chart-applications.d.ts +26 -0
  120. package/lib/types/chart-context.d.ts +14 -0
  121. package/lib/types/chart-observation.d.ts +8 -0
  122. package/lib/types/chart-service-status.d.ts +22 -0
  123. package/lib/types/chart-source-status.d.ts +47 -0
  124. package/lib/types/chart-sources.d.ts +25 -0
  125. package/lib/types/client/BetterSidebarTab.d.ts +12 -0
  126. package/lib/types/client/ClassicShell.d.ts +4 -0
  127. package/lib/types/client/KlineContent.d.ts +37 -0
  128. package/lib/types/client/PanelHost.d.ts +25 -0
  129. package/lib/types/client/chart-apply.d.ts +13 -0
  130. package/lib/types/client/chart-context.d.ts +23 -0
  131. package/lib/types/client/chart-handoff.d.ts +5 -0
  132. package/lib/types/client/chart-session-resolver.d.ts +2 -0
  133. package/lib/types/client/client-context.d.ts +16 -0
  134. package/lib/types/client/conversation.d.ts +43 -0
  135. package/lib/types/client/default-tab.d.ts +3 -0
  136. package/lib/types/client/embed.d.ts +37 -0
  137. package/lib/types/client/generated-view.d.ts +2 -0
  138. package/lib/types/client/horizontal-lines.d.ts +1 -0
  139. package/lib/types/client/host-options.d.ts +38 -0
  140. package/lib/types/client/host-panels.d.ts +55 -0
  141. package/lib/types/client/index.d.ts +4 -0
  142. package/lib/types/client/mode-preferences.d.ts +25 -0
  143. package/lib/types/client/native-sidebar-contract.d.ts +52 -0
  144. package/lib/types/client/native-sidebar-register.d.ts +46 -0
  145. package/lib/types/client/native-sidebar-services.d.ts +45 -0
  146. package/lib/types/client/native-sidebar.d.ts +47 -0
  147. package/lib/types/client/sidebar-integration.d.ts +12 -0
  148. package/lib/types/client/ui-onboarding.d.ts +7 -0
  149. package/lib/types/client/version.d.ts +1 -0
  150. package/lib/types/drawing-feedback.d.ts +5 -0
  151. package/lib/types/fibonacci.d.ts +5 -0
  152. package/lib/types/ftshare-settings-bridge.d.ts +50 -0
  153. package/lib/types/index.d.ts +26 -0
  154. package/lib/types/labeled-polyline.d.ts +11 -0
  155. package/lib/types/pattern-groups.d.ts +2 -0
  156. package/lib/types/price-bands.d.ts +3 -0
  157. package/lib/types/price-series.d.ts +5 -0
  158. package/lib/types/price-sticks.d.ts +3 -0
  159. package/package.json +155 -4
  160. package/requirements.txt +6 -0
  161. package/screenshots.json +8 -0
  162. package/scripts/bootstrap.sh +5 -0
  163. package/scripts/dsh-bootstrap.mjs +179 -0
  164. package/scripts/dsh-mcp-plugin.mjs +27 -0
  165. package/scripts/run-dsh-kline.mjs +658 -0
  166. package/scripts/run-dsh-kline.sh +5 -0
  167. package/server.py +1755 -0
  168. package/tools/__init__.py +0 -0
  169. package/tools/annotations.py +119 -0
  170. package/tools/automatic_analysis.py +158 -0
  171. package/tools/baostock_source.py +176 -0
  172. package/tools/calc.py +39 -0
  173. package/tools/channel_candidates.py +260 -0
  174. package/tools/channel_preview.py +82 -0
  175. package/tools/channels.py +104 -0
  176. package/tools/chart_applications.py +204 -0
  177. package/tools/chart_context.py +186 -0
  178. package/tools/chart_edits.py +363 -0
  179. package/tools/chart_functions.py +451 -0
  180. package/tools/chart_indicators.py +65 -0
  181. package/tools/chart_measurements.py +84 -0
  182. package/tools/chart_source_status.py +32 -0
  183. package/tools/chart_sources.py +31 -0
  184. package/tools/closed_daily.py +68 -0
  185. package/tools/draw.py +410 -0
  186. package/tools/drawing_feedback.py +45 -0
  187. package/tools/drawing_interaction.py +117 -0
  188. package/tools/drawing_verification.py +141 -0
  189. package/tools/fetch.py +4680 -0
  190. package/tools/fibonacci.py +83 -0
  191. package/tools/foreign_daily.py +185 -0
  192. package/tools/free_sources.py +483 -0
  193. package/tools/lines.py +91 -0
  194. package/tools/nine_count.py +66 -0
  195. package/tools/pattern_groups.py +103 -0
  196. package/tools/pivots.py +60 -0
  197. package/tools/polylines.py +131 -0
  198. package/tools/price_bands.py +165 -0
  199. package/tools/price_patterns.py +311 -0
  200. package/tools/price_series.py +162 -0
  201. package/tools/price_sticks.py +114 -0
  202. package/tools/range_candidates.py +170 -0
  203. package/tools/recent_drawing_candidates.py +123 -0
  204. package/tools/rectangles.py +76 -0
  205. package/tools/regression_channels.py +87 -0
  206. package/tools/ta_functions.py +228 -0
  207. package/tools/trend_lines.py +106 -0
  208. package/tools/watchlist.py +149 -0
  209. package/view/ft-logo.jpg +0 -0
  210. package/view/kline.html +12436 -0
  211. package/view/vendor/klinecharts.min.js +7 -0
@@ -0,0 +1,32 @@
1
+ """Allowlisted diagnostic metadata, never edit authority or a replacement for guards."""
2
+ SOURCE_STATUS_REASONS = {
3
+ "not_checked": ("not_checked", "retry_observation"),
4
+ "chart_not_ready": ("not_checked", "wait_for_chart"),
5
+ "client_unsupported": ("blocked", "reload_client"),
6
+ "view_inactive": ("blocked", "activate_view"),
7
+ "ambiguous_views": ("blocked", "keep_one_active_view"),
8
+ "source_missing": ("blocked", "reopen_chart"),
9
+ "source_unavailable": ("blocked", "reopen_chart"),
10
+ "source_owner_mismatch": ("blocked", "reopen_chart"),
11
+ "source_unconfirmed": ("blocked", "check_drawing_status"),
12
+ "source_metadata_unknown": ("blocked", "check_chart_settings"),
13
+ "source_limit_exceeded": ("blocked", "reduce_range"),
14
+ "drawing_pending": ("checking", "check_drawing_status"),
15
+ "drawing_outcome_unknown": ("blocked", "check_drawing_status"),
16
+ "source_snapshot_mismatch": ("blocked", "retry_observation"),
17
+ "source_payload_invalid": ("blocked", "retry_observation"),
18
+ "source_handoff_pending": ("checking", "wait_for_report"),
19
+ "source_handoff_rejected": ("blocked", "retry_observation"),
20
+ "source_matches_view": ("aligned", "continue_guarded_workflow"),
21
+ "context_transport_unavailable": ("blocked", "retry_observation"),
22
+ "source_handoff_unavailable": ("blocked", "retry_observation"),
23
+ }
24
+
25
+
26
+ def sanitize_source_status(raw):
27
+ reason = raw.get("reason") if isinstance(raw, dict) and type(raw.get("schema_version")) is int and raw["schema_version"] == 1 else None
28
+ if not isinstance(reason, str) or reason not in SOURCE_STATUS_REASONS:
29
+ reason = "not_checked"
30
+ phase, action = SOURCE_STATUS_REASONS[reason]
31
+ return {"schema_version": 1, "scope": "source_handoff", "phase": phase, "reason": reason,
32
+ "next_action": action, "edit_authorized": False}
@@ -0,0 +1,31 @@
1
+ """Validate browser-confirmed current-view source identity; never fetch or bind here."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import re
6
+
7
+ import chart_service
8
+ from tools.lines import LineError
9
+
10
+
11
+ def require_confirmed_view_source(payload: dict, context: dict, token: str) -> None:
12
+ guard = payload.get("view_source_guard")
13
+ if not guard:
14
+ return
15
+ try:
16
+ if (not isinstance(guard, dict) or guard.get("protocol") != "browser-source-v1"
17
+ or guard.get("chart_session") != token or guard.get("conversation_id") != context.get("conversation_id")
18
+ or not isinstance(guard.get("context_ref"), str)
19
+ or not re.fullmatch(r"[A-Za-z0-9_-]{32}", guard["context_ref"])
20
+ or not isinstance(token, str) or not re.fullmatch(r"[A-Za-z0-9_-]{32}", token)):
21
+ raise ValueError("owner")
22
+ path = chart_service.RUNTIME_DIR / "sources" / str(chart_service.HOST_PROCESS_ID) / guard["context_ref"] / (token + ".json")
23
+ if path.stat().st_size > chart_service.MAX_REQUEST_BYTES:
24
+ raise ValueError("size")
25
+ proof = json.loads(path.read_text(encoding="utf-8"))
26
+ if (proof.get("status") != "confirmed" or proof.get("host_process_id") != chart_service.HOST_PROCESS_ID
27
+ or proof.get("chart_session") != token or proof.get("context_ref") != guard["context_ref"]
28
+ or proof.get("conversation_id") != guard["conversation_id"] or proof.get("view_id") != guard.get("view_id")):
29
+ raise ValueError("proof")
30
+ except (OSError, ValueError, TypeError, KeyError, AttributeError):
31
+ raise LineError("chart_source_not_confirmed", "当前图来源尚未由所属网页核对绑定;请等待重新上报并读取新上下文,不重取行情或使用旧图绕过。") from None
@@ -0,0 +1,68 @@
1
+ """Conservative exchange-local closed daily bars for read-only analyses."""
2
+ from __future__ import annotations
3
+
4
+ from datetime import datetime, time, timezone
5
+ from zoneinfo import ZoneInfo
6
+
7
+ from core.rows import RowsValidationError, validate_rows
8
+ from tools.lines import LineError
9
+
10
+ MARKETS = {
11
+ "CN": (ZoneInfo("Asia/Shanghai"), time(15, 40)),
12
+ "HK": (ZoneInfo("Asia/Hong_Kong"), time(16, 20)),
13
+ "US": (ZoneInfo("America/New_York"), time(16, 10)),
14
+ }
15
+
16
+
17
+ def market_for_symbol(symbol: str) -> str | None:
18
+ suffix = str(symbol or "").upper().rsplit(".", 1)[-1]
19
+ return "CN" if suffix in {"XSHG", "XSHE", "SH", "SZ"} else suffix if suffix in {"HK", "US"} else None
20
+
21
+
22
+ def closed_daily(rows, *, symbol: str, interval: str, source_interval: str | None = None,
23
+ interval_value: int | None = 1, provider: str | None = None,
24
+ now: datetime | None = None):
25
+ if interval != "day" or source_interval not in {None, "day"} or interval_value != 1:
26
+ raise LineError("daily_analysis_only", "形态与九转首版仅支持单日线;请在当前图切换后重新分析。")
27
+ try:
28
+ candles = validate_rows(rows, min_len=1)
29
+ except RowsValidationError:
30
+ raise LineError("daily_analysis_unavailable", "当前图缺少有效的已加载日线。") from None
31
+ market = market_for_symbol(symbol)
32
+ clock = now or datetime.now(timezone.utc)
33
+ if clock.tzinfo is None:
34
+ raise ValueError("now must be timezone-aware")
35
+ quality = []
36
+ if market is None:
37
+ quality.append("market_unknown_current_day_excluded")
38
+ # UTC prior days are surely historical regardless of the exchange zone.
39
+ cutoff_date = clock.astimezone(timezone.utc).date()
40
+ accepted = [r for r in candles if datetime.fromtimestamp(r["time"], timezone.utc).date() < cutoff_date]
41
+ return accepted, {"market": None, "timezone": None, "as_of": accepted[-1]["time"] if accepted else None,
42
+ "quality": quality, "excluded": len(candles) - len(accepted)}
43
+ zone, close_time = MARKETS[market]
44
+ local = clock.astimezone(zone)
45
+ accepted = []
46
+ for row in candles:
47
+ bar = datetime.fromtimestamp(row["time"], zone)
48
+ utc_day = datetime.fromtimestamp(row["time"], timezone.utc).date()
49
+ if bar.date() < local.date() and utc_day == local.date():
50
+ # A date-only UTC-midnight stamp for today's US session appears as
51
+ # yesterday evening in New York. It is not proof of a closed bar.
52
+ quality.append("date_semantics_uncertain_current_day_excluded")
53
+ elif bar.date() < local.date():
54
+ accepted.append(row)
55
+ elif bar.date() > local.date():
56
+ quality.append("future_daily_bar_excluded")
57
+ elif provider in {None, "unknown", "external"}:
58
+ quality.append("source_unknown_current_day_excluded")
59
+ elif bar.time() < time(9, 0) or bar.time() > time(23, 0):
60
+ quality.append("date_semantics_uncertain_current_day_excluded")
61
+ elif local.time() >= close_time:
62
+ accepted.append(row)
63
+ else:
64
+ quality.append("current_day_not_conservatively_closed")
65
+ return accepted, {"market": market, "timezone": zone.key,
66
+ "as_of": accepted[-1]["time"] if accepted else None,
67
+ "quality": sorted(set(quality)), "excluded": len(candles) - len(accepted),
68
+ "cutoff_local": close_time.strftime("%H:%M")}
package/tools/draw.py ADDED
@@ -0,0 +1,410 @@
1
+ """Build standalone dsh_kline chart payloads and indicator commands.
2
+
3
+ All indicator series come from core.calc (same module as calc_metrics).
4
+ Public times are unix **seconds**; view multiplies by 1000 for klinecharts.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import Any
10
+ from urllib.parse import urlparse
11
+
12
+ from core.calc import (
13
+ DEFAULT_ATR_PERIOD,
14
+ DEFAULT_BOLL_PERIOD,
15
+ DEFAULT_BOLL_STD,
16
+ DEFAULT_KDJ,
17
+ DEFAULT_MACD,
18
+ DEFAULT_MA_PERIODS,
19
+ DEFAULT_EMA_PERIOD,
20
+ DEFAULT_RSI_PERIOD,
21
+ DEFAULT_VOLUME_MA,
22
+ series_atr,
23
+ series_boll,
24
+ series_kdj,
25
+ series_ma,
26
+ series_ema,
27
+ series_macd,
28
+ series_rsi,
29
+ series_vwap,
30
+ series_vol_ma,
31
+ )
32
+ from core.rows import validate_rows
33
+ from core.ta_engine import ENGINE_VERSION, NATIVE_VERSION
34
+
35
+ SUPPORTED_INDICATORS = ("ma", "ema", "vwap", "vol", "macd", "kdj", "boll", "rsi", "atr")
36
+
37
+
38
+ def _safe_https_url(value: Any) -> str | None:
39
+ """Accept attribution URLs only when they are absolute HTTPS URLs."""
40
+ candidate = str(value or "").strip()
41
+ if not candidate or len(candidate) > 500:
42
+ return None
43
+ parsed = urlparse(candidate)
44
+ return candidate if parsed.scheme == "https" and parsed.netloc else None
45
+
46
+
47
+ def _map_to_str_keys(m: dict[int, float]) -> dict[str, float]:
48
+ """JSON object keys must be strings; values stay numbers. Keys are seconds."""
49
+ return {str(int(k)): float(v) for k, v in m.items()}
50
+
51
+
52
+ def _normalize_marks(marks: Any) -> list[dict[str, Any]]:
53
+ out: list[dict[str, Any]] = []
54
+ if not isinstance(marks, list):
55
+ return out
56
+ for index, m in enumerate(marks):
57
+ if not isinstance(m, dict):
58
+ continue
59
+ try:
60
+ t = int(m.get("time") or m.get("timestamp") or 0)
61
+ except Exception:
62
+ continue
63
+ if t > 10_000_000_000:
64
+ t = int(t / 1000)
65
+ if t <= 0:
66
+ continue
67
+ price = m.get("price")
68
+ try:
69
+ price_f = float(price) if price is not None else None
70
+ except Exception:
71
+ price_f = None
72
+ out.append(
73
+ {
74
+ "id": str(m.get("id") or f"marker:{t}:{index}")[:128],
75
+ "time": t,
76
+ "price": price_f,
77
+ "text": str(m.get("text") or m.get("label") or "标注")[:48],
78
+ "color": str(m.get("color") or "warning"),
79
+ }
80
+ )
81
+ return out
82
+
83
+
84
+ def _normalize_lines(lines: Any) -> list[dict[str, Any]]:
85
+ out: list[dict[str, Any]] = []
86
+ if not isinstance(lines, list):
87
+ return out
88
+ for index, ln in enumerate(lines):
89
+ if not isinstance(ln, dict):
90
+ continue
91
+ fr = ln.get("from") or {}
92
+ to = ln.get("to") or {}
93
+ try:
94
+ t0 = int(fr.get("time") or 0)
95
+ t1 = int(to.get("time") or 0)
96
+ p0 = float(fr.get("price"))
97
+ p1 = float(to.get("price"))
98
+ except Exception:
99
+ continue
100
+ if t0 > 10_000_000_000:
101
+ t0 = int(t0 / 1000)
102
+ if t1 > 10_000_000_000:
103
+ t1 = int(t1 / 1000)
104
+ if t0 <= 0 or t1 <= 0 or t0 == t1:
105
+ continue
106
+ out.append(
107
+ {
108
+ "id": str(ln.get("id") or f"line:{t0}:{t1}:{index}")[:128],
109
+ "from": {"time": t0, "price": p0},
110
+ "to": {"time": t1, "price": p1},
111
+ "label": str(ln.get("label") or ln.get("text") or ""),
112
+ "color": str(ln.get("color") or "danger"),
113
+ }
114
+ )
115
+ return out
116
+
117
+
118
+ def _normalize_comparisons(comparisons: Any) -> list[dict[str, Any]]:
119
+ """Validate optional benchmark series for direct, one-shot chart rendering."""
120
+ if not isinstance(comparisons, list):
121
+ return []
122
+ normalized: list[dict[str, Any]] = []
123
+ for item in comparisons[:12]:
124
+ if not isinstance(item, dict):
125
+ continue
126
+ symbol = str(item.get("symbol") or "").strip()
127
+ rows = item.get("rows")
128
+ if not symbol or not isinstance(rows, list):
129
+ continue
130
+ try:
131
+ normalized_rows = validate_rows(rows, min_len=2)
132
+ except (TypeError, ValueError):
133
+ continue
134
+ normalized.append(
135
+ {
136
+ "symbol": symbol[:48],
137
+ "name": str(item.get("name") or symbol)[:120],
138
+ "rows": normalized_rows,
139
+ "exchange_timezone": str(item.get("exchange_timezone") or "")[:64],
140
+ "interval": str(item.get("interval") or "day")[:16],
141
+ "visible": item.get("visible") is not False,
142
+ }
143
+ )
144
+ return normalized
145
+
146
+
147
+ def build_chart_commands(
148
+ rows: list[dict[str, Any]],
149
+ *,
150
+ indicators: list[str] | None = None,
151
+ ma_periods: list[int] | None = None,
152
+ ema_period: int = DEFAULT_EMA_PERIOD,
153
+ marks: Any = None,
154
+ lines: Any = None,
155
+ boll_period: int = DEFAULT_BOLL_PERIOD,
156
+ boll_std: float = DEFAULT_BOLL_STD,
157
+ volume_ma: int = DEFAULT_VOLUME_MA,
158
+ rsi_period: int = DEFAULT_RSI_PERIOD,
159
+ atr_period: int = DEFAULT_ATR_PERIOD,
160
+ ) -> list[dict[str, Any]]:
161
+ """Build chartCommands. Indicator series keys are **seconds** (view ×1000)."""
162
+ requested_indicators = ["ma", "vol"] if indicators is None else indicators
163
+ inds = [str(x).lower() for x in requested_indicators if str(x).lower() in SUPPORTED_INDICATORS]
164
+ periods = list(ma_periods or DEFAULT_MA_PERIODS)
165
+ cmds: list[dict[str, Any]] = []
166
+
167
+ if rows:
168
+ cmds.append(
169
+ {
170
+ "type": "SET_CANDLES",
171
+ "rows": rows, # view needs candles; host LLM content should still not dump them
172
+ }
173
+ )
174
+ cmds.append(
175
+ {
176
+ "type": "SET_RANGE",
177
+ "start": int(rows[0]["time"]),
178
+ "end": int(rows[-1]["time"]),
179
+ }
180
+ )
181
+
182
+ # MA series
183
+ if "ma" in inds:
184
+ ma_maps = series_ma(rows, periods)
185
+ data = {name: _map_to_str_keys(m) for name, m in ma_maps.items()}
186
+ cmds.append(
187
+ {
188
+ "type": "SET_INDICATOR_SERIES",
189
+ "name": "ma",
190
+ "pane": "candle",
191
+ "params": {"periods": periods},
192
+ "data": data, # keys = seconds (stringified)
193
+ "note": "data keys are unix seconds; view multiplies by 1000 for klinecharts",
194
+ }
195
+ )
196
+
197
+ if "ema" in inds:
198
+ cmds.append({
199
+ "type": "SET_INDICATOR_SERIES", "name": "ema", "pane": "candle",
200
+ "params": {"period": int(ema_period)},
201
+ "data": {"ema": _map_to_str_keys(series_ema(rows, ema_period))},
202
+ "note": "data keys are unix seconds; view multiplies by 1000 for klinecharts",
203
+ })
204
+
205
+ if "vwap" in inds:
206
+ cmds.append(
207
+ {
208
+ "type": "SET_INDICATOR_SERIES",
209
+ "name": "vwap",
210
+ "pane": "candle",
211
+ "params": {"anchor": "loaded_context"},
212
+ "data": {"vwap": _map_to_str_keys(series_vwap(rows))},
213
+ "note": "data keys are unix seconds; view multiplies by 1000 for klinecharts",
214
+ }
215
+ )
216
+
217
+ if "vol" in inds:
218
+ vol_map = series_vol_ma(rows, volume_ma)
219
+ # raw volume is already on candles; only pass MA for overlay reference if needed
220
+ cmds.append(
221
+ {
222
+ "type": "SET_INDICATOR_SERIES",
223
+ "name": "vol",
224
+ "pane": "vol",
225
+ "params": {"ma_period": int(volume_ma)},
226
+ "data": {"vol_ma": _map_to_str_keys(vol_map)},
227
+ "note": "data keys are unix seconds; view multiplies by 1000 for klinecharts",
228
+ }
229
+ )
230
+
231
+ if "macd" in inds:
232
+ macd = series_macd(rows, *DEFAULT_MACD)
233
+ cmds.append(
234
+ {
235
+ "type": "SET_INDICATOR_SERIES",
236
+ "name": "macd",
237
+ "pane": "macd",
238
+ "params": {"fast": DEFAULT_MACD[0], "slow": DEFAULT_MACD[1], "signal": DEFAULT_MACD[2]},
239
+ "data": {
240
+ "dif": _map_to_str_keys(macd["dif"]),
241
+ "dea": _map_to_str_keys(macd["dea"]),
242
+ "hist": _map_to_str_keys(macd["hist"]),
243
+ },
244
+ "note": "data keys are unix seconds; view multiplies by 1000 for klinecharts",
245
+ }
246
+ )
247
+
248
+ if "kdj" in inds:
249
+ kdj = series_kdj(rows, *DEFAULT_KDJ)
250
+ cmds.append(
251
+ {
252
+ "type": "SET_INDICATOR_SERIES",
253
+ "name": "kdj",
254
+ "pane": "kdj",
255
+ "params": {"n": DEFAULT_KDJ[0], "m1": DEFAULT_KDJ[1], "m2": DEFAULT_KDJ[2]},
256
+ "data": {
257
+ "k": _map_to_str_keys(kdj["k"]),
258
+ "d": _map_to_str_keys(kdj["d"]),
259
+ "j": _map_to_str_keys(kdj["j"]),
260
+ },
261
+ "note": "data keys are unix seconds; view multiplies by 1000 for klinecharts",
262
+ }
263
+ )
264
+
265
+ if "boll" in inds:
266
+ boll = series_boll(rows, period=boll_period, std_mult=boll_std)
267
+ cmds.append(
268
+ {
269
+ "type": "SET_INDICATOR_SERIES",
270
+ "name": "boll",
271
+ "pane": "candle",
272
+ "params": {"period": int(boll_period), "std_mult": float(boll_std)},
273
+ "data": {
274
+ "mid": _map_to_str_keys(boll["mid"]),
275
+ "upper": _map_to_str_keys(boll["upper"]),
276
+ "lower": _map_to_str_keys(boll["lower"]),
277
+ },
278
+ "note": "data keys are unix seconds; view multiplies by 1000 for klinecharts",
279
+ }
280
+ )
281
+
282
+ if "rsi" in inds:
283
+ rsi = series_rsi(rows, period=rsi_period)
284
+ cmds.append(
285
+ {
286
+ "type": "SET_INDICATOR_SERIES",
287
+ "name": "rsi",
288
+ "pane": "rsi",
289
+ "params": {"period": int(rsi_period)},
290
+ "data": {"rsi": _map_to_str_keys(rsi)},
291
+ "note": "data keys are unix seconds; view multiplies by 1000 for klinecharts",
292
+ }
293
+ )
294
+
295
+ if "atr" in inds:
296
+ atr = series_atr(rows, period=atr_period)
297
+ cmds.append(
298
+ {
299
+ "type": "SET_INDICATOR_SERIES",
300
+ "name": "atr",
301
+ "pane": "atr",
302
+ "params": {"period": int(atr_period)},
303
+ "data": {"atr": _map_to_str_keys(atr)},
304
+ "note": "data keys are unix seconds; view multiplies by 1000 for klinecharts",
305
+ }
306
+ )
307
+
308
+ for ln in _normalize_lines(lines):
309
+ cmds.append(
310
+ {
311
+ "type": "DRAW_TREND_LINE",
312
+ "id": ln["id"],
313
+ "from": ln["from"],
314
+ "to": ln["to"],
315
+ "label": ln["label"],
316
+ "color": ln["color"],
317
+ }
318
+ )
319
+
320
+ for mk in _normalize_marks(marks):
321
+ # fallback price to nearest bar high if missing (labels sit above candle)
322
+ price = mk["price"]
323
+ if price is None:
324
+ nearest = min(rows, key=lambda r: abs(int(r["time"]) - mk["time"])) if rows else None
325
+ price = float(nearest["high"]) if nearest else 0.0
326
+ cmds.append(
327
+ {
328
+ "type": "TEXT_MARKER",
329
+ "id": mk["id"],
330
+ "time": mk["time"],
331
+ "price": float(price),
332
+ "text": mk["text"],
333
+ "color": mk["color"],
334
+ }
335
+ )
336
+
337
+ return cmds
338
+
339
+
340
+ def draw_kline(
341
+ rows: Any,
342
+ *,
343
+ indicators: list[str] | None = None,
344
+ indicators_explicit: bool | None = None,
345
+ ma_periods: list[int] | None = None,
346
+ ema_period: int = DEFAULT_EMA_PERIOD,
347
+ marks: Any = None,
348
+ lines: Any = None,
349
+ comparisons: Any = None,
350
+ security_workspace: Any = None,
351
+ symbol: str | None = None,
352
+ name: str | None = None,
353
+ data_source: str | None = None,
354
+ data_source_url: str | None = None,
355
+ interval: str = "day",
356
+ boll_period: int = DEFAULT_BOLL_PERIOD,
357
+ boll_std: float = DEFAULT_BOLL_STD,
358
+ volume_ma: int = DEFAULT_VOLUME_MA,
359
+ rsi_period: int = DEFAULT_RSI_PERIOD,
360
+ atr_period: int = DEFAULT_ATR_PERIOD,
361
+ ) -> dict[str, Any]:
362
+ """Return a self-contained chart session payload."""
363
+ norm = validate_rows(rows, min_len=2)
364
+ requested_indicators = ["ma", "vol"] if indicators is None else indicators
365
+ inds = [str(x).lower() for x in requested_indicators if str(x).lower() in SUPPORTED_INDICATORS]
366
+ cmds = build_chart_commands(
367
+ norm,
368
+ indicators=inds,
369
+ ma_periods=ma_periods,
370
+ ema_period=ema_period,
371
+ marks=marks,
372
+ lines=lines,
373
+ boll_period=boll_period,
374
+ boll_std=boll_std,
375
+ volume_ma=volume_ma,
376
+ rsi_period=rsi_period,
377
+ atr_period=atr_period,
378
+ )
379
+ comparison_series = _normalize_comparisons(comparisons)
380
+ if comparison_series:
381
+ cmds.append({"type": "SET_COMPARISON_SERIES", "series": comparison_series})
382
+ # Structured payload for the view (includes SET_CANDLES rows).
383
+ # Content text stays compact for host LLM context.
384
+ payload = {
385
+ "calculation_engine": {"name": "TA-Lib", "wrapper_version": ENGINE_VERSION,
386
+ "native_version": NATIVE_VERSION},
387
+ "symbol": symbol or "",
388
+ "name": name or symbol or "",
389
+ "interval": (interval or "day").lower(),
390
+ "count": len(norm),
391
+ "start_time": int(norm[0]["time"]),
392
+ "end_time": int(norm[-1]["time"]),
393
+ "indicators": inds,
394
+ "indicators_explicit": bool(indicators_explicit),
395
+ "chartCommands": cmds,
396
+ # Convenience cards for view header
397
+ "last_close": float(norm[-1]["close"]),
398
+ "last_time": int(norm[-1]["time"]),
399
+ }
400
+ if isinstance(security_workspace, dict):
401
+ # The app only consumes this provider-neutral schema. Supplying it with
402
+ # the draw payload keeps news/company data visible even when the host
403
+ # cannot issue a second in-app tools/call request.
404
+ payload["security_workspace"] = security_workspace
405
+ if data_source and str(data_source).strip():
406
+ payload["data_meta"] = {"source": str(data_source).strip()[:120]}
407
+ source_url = _safe_https_url(data_source_url)
408
+ if source_url:
409
+ payload["data_meta"]["source_url"] = source_url
410
+ return payload
@@ -0,0 +1,45 @@
1
+ """Whitelisted browser object observations; never upgrade them to pixel verification."""
2
+ from __future__ import annotations
3
+
4
+ KINDS = {"horizontal_line", "trend_line", "channel", "rectangle", "fibonacci_retracement", "labeled_polyline", "text_annotation", "number_annotation", "icon_annotation", "series_line", "price_band", "price_sticks", "price_pattern", "nine_count"}
5
+ REASONS = {
6
+ "created": {"overlay_registered", "outside_time_viewport", "indicator_registered"},
7
+ "hidden": {"period_mismatch", "anchors_not_loaded", "snapshot_outside_loaded_history"},
8
+ "removed": {"overlay_removed", "indicator_removed"},
9
+ "failed": {"invalid_geometry", "overlay_missing", "overlay_mismatch", "overlay_still_present", "creation_failed", "indicator_missing", "indicator_still_present"},
10
+ "unknown": {"overlay_api_unavailable", "overlay_lookup_failed", "overlay_mismatch", "context_not_ready", "application_rolled_back", "rollback_unknown", "indicator_api_unavailable"},
11
+ }
12
+
13
+
14
+ def _empty(status):
15
+ return {"schema_version": 1, "report_status": status, "evidence_scope": "chart_object_api",
16
+ "render_verified": False, "pixel_verified": False, "items": []}
17
+
18
+
19
+ def sanitize_drawing_feedback(raw, allowed):
20
+ if raw is None: return _empty("not_reported")
21
+ if isinstance(raw, dict) and isinstance(raw.get("report_status"), str) and raw["report_status"] in {"not_reported", "invalid"}:
22
+ return _empty(raw["report_status"])
23
+ try:
24
+ if (not isinstance(raw, dict) or type(raw.get("schema_version")) is not int or raw["schema_version"] != 1
25
+ or raw.get("phase") not in {"current", "applied", "rolled_back", "rollback_unknown"}
26
+ or not isinstance(raw.get("items"), list) or len(raw["items"]) > 360): raise ValueError("report")
27
+ objects = {d["id"]: d["kind"] for d in allowed}; seen = set(); items = []
28
+ for item in raw["items"]:
29
+ identity, kind, status, reason, visibility = (item[k] for k in ("id", "kind", "status", "reason", "visibility"))
30
+ if (not isinstance(identity, str) or not 1 <= len(identity) <= 256 or identity in seen or objects.get(identity) != kind
31
+ or kind not in KINDS or status not in REASONS or reason not in REASONS[status]
32
+ or visibility not in {"unknown", "outside_time_viewport", "not_applicable"}
33
+ or (reason == "outside_time_viewport") != (visibility == "outside_time_viewport")): raise ValueError("item")
34
+ seen.add(identity)
35
+ overlap = item.get("time_range_overlap")
36
+ if overlap is not None and type(overlap) is not bool: raise ValueError("time_range_overlap")
37
+ items.append({"id": identity, "kind": kind, "status": status, "reason": reason, "visibility": visibility,
38
+ "outside_loaded_price_envelope": item.get("outside_loaded_price_envelope") is True,
39
+ "time_range_overlap": overlap})
40
+ if len(seen) != len(objects): raise ValueError("coverage")
41
+ scope = raw.get("evidence_scope")
42
+ if scope not in {"chart_object_api", "indicator_registry", "mixed_chart_api_and_indicator_registry"}:
43
+ scope = "chart_object_api"
44
+ return {**_empty("reported"), "phase": raw["phase"], "evidence_scope": scope, "items": items}
45
+ except (ValueError, TypeError, KeyError, AttributeError): return _empty("invalid")