@dsh-ft/dsh-fft-paper-trading 0.7.1 → 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 (130) hide show
  1. package/lib/client.js +1 -1
  2. package/package.json +1 -4
  3. package/node_modules/@ftshare-lab/dsh-kline/CHANGELOG.md +0 -611
  4. package/node_modules/@ftshare-lab/dsh-kline/LICENSE +0 -21
  5. package/node_modules/@ftshare-lab/dsh-kline/PROVENANCE.md +0 -13
  6. package/node_modules/@ftshare-lab/dsh-kline/README.en.md +0 -171
  7. package/node_modules/@ftshare-lab/dsh-kline/README.md +0 -171
  8. package/node_modules/@ftshare-lab/dsh-kline/chart_service.py +0 -687
  9. package/node_modules/@ftshare-lab/dsh-kline/config/basic-symbols.json +0 -570
  10. package/node_modules/@ftshare-lab/dsh-kline/config/dsh-kline.patch.yml +0 -4
  11. package/node_modules/@ftshare-lab/dsh-kline/config/dsh-tool-catalog.json +0 -3875
  12. package/node_modules/@ftshare-lab/dsh-kline/cordis.patch.yml +0 -33
  13. package/node_modules/@ftshare-lab/dsh-kline/core/__init__.py +0 -0
  14. package/node_modules/@ftshare-lab/dsh-kline/core/adjustment.py +0 -16
  15. package/node_modules/@ftshare-lab/dsh-kline/core/calc.py +0 -691
  16. package/node_modules/@ftshare-lab/dsh-kline/core/rows.py +0 -228
  17. package/node_modules/@ftshare-lab/dsh-kline/core/ta_engine.py +0 -99
  18. package/node_modules/@ftshare-lab/dsh-kline/lib/candle-sequence.js +0 -15
  19. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-adjustment.js +0 -7
  20. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-annotations.js +0 -33
  21. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-applications.js +0 -171
  22. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-context.js +0 -164
  23. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-observation.js +0 -251
  24. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-service-status.js +0 -82
  25. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-source-status.js +0 -39
  26. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-sources.js +0 -354
  27. package/node_modules/@ftshare-lab/dsh-kline/lib/client.js +0 -17581
  28. package/node_modules/@ftshare-lab/dsh-kline/lib/drawing-feedback.js +0 -284
  29. package/node_modules/@ftshare-lab/dsh-kline/lib/fibonacci.js +0 -18
  30. package/node_modules/@ftshare-lab/dsh-kline/lib/ftshare-settings-bridge.js +0 -159
  31. package/node_modules/@ftshare-lab/dsh-kline/lib/index.js +0 -279
  32. package/node_modules/@ftshare-lab/dsh-kline/lib/labeled-polyline.js +0 -17
  33. package/node_modules/@ftshare-lab/dsh-kline/lib/pattern-groups.js +0 -91
  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/PanelHost.d.ts +0 -25
  50. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/chart-apply.d.ts +0 -13
  51. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/chart-context.d.ts +0 -23
  52. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/chart-handoff.d.ts +0 -5
  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 -16
  55. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/conversation.d.ts +0 -43
  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-options.d.ts +0 -38
  61. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/host-panels.d.ts +0 -55
  62. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/index.d.ts +0 -4
  63. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/mode-preferences.d.ts +0 -25
  64. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar-contract.d.ts +0 -52
  65. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar-register.d.ts +0 -46
  66. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar-services.d.ts +0 -45
  67. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar.d.ts +0 -47
  68. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/sidebar-integration.d.ts +0 -12
  69. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/ui-onboarding.d.ts +0 -7
  70. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/version.d.ts +0 -1
  71. package/node_modules/@ftshare-lab/dsh-kline/lib/types/drawing-feedback.d.ts +0 -5
  72. package/node_modules/@ftshare-lab/dsh-kline/lib/types/fibonacci.d.ts +0 -5
  73. package/node_modules/@ftshare-lab/dsh-kline/lib/types/ftshare-settings-bridge.d.ts +0 -50
  74. package/node_modules/@ftshare-lab/dsh-kline/lib/types/index.d.ts +0 -26
  75. package/node_modules/@ftshare-lab/dsh-kline/lib/types/labeled-polyline.d.ts +0 -11
  76. package/node_modules/@ftshare-lab/dsh-kline/lib/types/pattern-groups.d.ts +0 -2
  77. package/node_modules/@ftshare-lab/dsh-kline/lib/types/price-bands.d.ts +0 -3
  78. package/node_modules/@ftshare-lab/dsh-kline/lib/types/price-series.d.ts +0 -5
  79. package/node_modules/@ftshare-lab/dsh-kline/lib/types/price-sticks.d.ts +0 -3
  80. package/node_modules/@ftshare-lab/dsh-kline/package.json +0 -157
  81. package/node_modules/@ftshare-lab/dsh-kline/requirements.txt +0 -6
  82. package/node_modules/@ftshare-lab/dsh-kline/scripts/bootstrap.sh +0 -5
  83. package/node_modules/@ftshare-lab/dsh-kline/scripts/dsh-bootstrap.mjs +0 -179
  84. package/node_modules/@ftshare-lab/dsh-kline/scripts/dsh-mcp-plugin.mjs +0 -27
  85. package/node_modules/@ftshare-lab/dsh-kline/scripts/run-dsh-kline.mjs +0 -658
  86. package/node_modules/@ftshare-lab/dsh-kline/scripts/run-dsh-kline.sh +0 -5
  87. package/node_modules/@ftshare-lab/dsh-kline/server.py +0 -1755
  88. package/node_modules/@ftshare-lab/dsh-kline/tools/__init__.py +0 -0
  89. package/node_modules/@ftshare-lab/dsh-kline/tools/annotations.py +0 -119
  90. package/node_modules/@ftshare-lab/dsh-kline/tools/automatic_analysis.py +0 -158
  91. package/node_modules/@ftshare-lab/dsh-kline/tools/baostock_source.py +0 -176
  92. package/node_modules/@ftshare-lab/dsh-kline/tools/calc.py +0 -39
  93. package/node_modules/@ftshare-lab/dsh-kline/tools/channel_candidates.py +0 -260
  94. package/node_modules/@ftshare-lab/dsh-kline/tools/channel_preview.py +0 -82
  95. package/node_modules/@ftshare-lab/dsh-kline/tools/channels.py +0 -104
  96. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_applications.py +0 -204
  97. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_context.py +0 -186
  98. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_edits.py +0 -363
  99. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_functions.py +0 -451
  100. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_indicators.py +0 -65
  101. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_measurements.py +0 -84
  102. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_source_status.py +0 -32
  103. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_sources.py +0 -31
  104. package/node_modules/@ftshare-lab/dsh-kline/tools/closed_daily.py +0 -68
  105. package/node_modules/@ftshare-lab/dsh-kline/tools/draw.py +0 -410
  106. package/node_modules/@ftshare-lab/dsh-kline/tools/drawing_feedback.py +0 -45
  107. package/node_modules/@ftshare-lab/dsh-kline/tools/drawing_interaction.py +0 -117
  108. package/node_modules/@ftshare-lab/dsh-kline/tools/drawing_verification.py +0 -141
  109. package/node_modules/@ftshare-lab/dsh-kline/tools/fetch.py +0 -4680
  110. package/node_modules/@ftshare-lab/dsh-kline/tools/fibonacci.py +0 -83
  111. package/node_modules/@ftshare-lab/dsh-kline/tools/foreign_daily.py +0 -185
  112. package/node_modules/@ftshare-lab/dsh-kline/tools/free_sources.py +0 -483
  113. package/node_modules/@ftshare-lab/dsh-kline/tools/lines.py +0 -91
  114. package/node_modules/@ftshare-lab/dsh-kline/tools/nine_count.py +0 -66
  115. package/node_modules/@ftshare-lab/dsh-kline/tools/pattern_groups.py +0 -103
  116. package/node_modules/@ftshare-lab/dsh-kline/tools/pivots.py +0 -60
  117. package/node_modules/@ftshare-lab/dsh-kline/tools/polylines.py +0 -131
  118. package/node_modules/@ftshare-lab/dsh-kline/tools/price_bands.py +0 -165
  119. package/node_modules/@ftshare-lab/dsh-kline/tools/price_patterns.py +0 -311
  120. package/node_modules/@ftshare-lab/dsh-kline/tools/price_series.py +0 -162
  121. package/node_modules/@ftshare-lab/dsh-kline/tools/price_sticks.py +0 -114
  122. package/node_modules/@ftshare-lab/dsh-kline/tools/range_candidates.py +0 -170
  123. package/node_modules/@ftshare-lab/dsh-kline/tools/recent_drawing_candidates.py +0 -123
  124. package/node_modules/@ftshare-lab/dsh-kline/tools/rectangles.py +0 -76
  125. package/node_modules/@ftshare-lab/dsh-kline/tools/regression_channels.py +0 -87
  126. package/node_modules/@ftshare-lab/dsh-kline/tools/ta_functions.py +0 -228
  127. package/node_modules/@ftshare-lab/dsh-kline/tools/trend_lines.py +0 -106
  128. package/node_modules/@ftshare-lab/dsh-kline/tools/watchlist.py +0 -149
  129. package/node_modules/@ftshare-lab/dsh-kline/view/ft-logo.jpg +0 -0
  130. package/node_modules/@ftshare-lab/dsh-kline/view/vendor/klinecharts.min.js +0 -7
@@ -1,228 +0,0 @@
1
- """Canonical OHLCV row helpers for dsh_kline.
2
-
3
- Public API time unit: **unix seconds** (int) end-to-end.
4
- The **only** place that multiplies by 1000 is the view (klinecharts needs ms).
5
-
6
- Bar time (v1, pinned to 8001):
7
- Canonical ``time`` = bar **close** timestamp. When the upstream source provides
8
- an explicit start timestamp, ``open_time`` retains it as optional metadata.
9
- FTShare: prefer ``ts_millis`` (close), never silently prefer ``ts_millis_open``.
10
- Day bars: open/close same calendar day → fine.
11
- Minute bars: close-time shifts marks by ~1 interval — known landmine; v1 is
12
- day-first. Document only; do not switch to open without migrating 8001 marks.
13
- """
14
-
15
- from __future__ import annotations
16
-
17
- from datetime import datetime, timezone, timedelta
18
- import math
19
- from typing import Any
20
-
21
- # Values above this are treated as milliseconds regardless of field name.
22
- # unix-sec for year ~2286 ≈ 1e10; ms values for modern dates are ≥ 1e12.
23
- _MS_THRESHOLD = 10_000_000_000 # 1e10
24
-
25
- # A-share calendar dates are wall-clock China. Fixed offset (no DST) so the same
26
- # "YYYY-MM-DD" is reproducible on UTC servers and Shanghai laptops.
27
- _CN_TZ = timezone(timedelta(hours=8))
28
-
29
-
30
- class RowsValidationError(ValueError):
31
- """Raised when incoming rows fail the contract gate."""
32
-
33
-
34
- def _to_float(v: Any) -> float | None:
35
- if v is None or v == "":
36
- return None
37
- try:
38
- return float(v)
39
- except (TypeError, ValueError):
40
- return None
41
-
42
-
43
- def _date_text_to_sec(date_txt: str) -> int | None:
44
- """Parse YYYY-MM-DD as Asia/Shanghai midnight → unix seconds (portable)."""
45
- try:
46
- dt = datetime.strptime(date_txt[:10], "%Y-%m-%d").replace(tzinfo=_CN_TZ)
47
- return int(dt.timestamp())
48
- except Exception:
49
- return None
50
-
51
-
52
- def _to_time_sec(v: Any) -> int | None:
53
- """Coerce a timestamp-like value to unix **seconds**.
54
-
55
- Magnitude-based ms detection (not field-name-based):
56
- if value > 1e10, treat as ms and ÷1000. Handles callers who stuff ms into
57
- a field named ``time``.
58
- """
59
- n = _to_float(v)
60
- if n is None or not math.isfinite(n) or n <= 0:
61
- return None
62
- if n > _MS_THRESHOLD:
63
- n = n / 1000.0
64
- return int(n)
65
-
66
-
67
- def _pick_raw_time(raw: dict[str, Any]) -> Any:
68
- """Pick bar **close** timestamp from heterogeneous keys.
69
-
70
- Semantic lock: every accepted field is interpreted as **close** time.
71
- If a data source puts open-time under ``ts``/``timestamp`` without also
72
- providing the FTShare close/open pair, the caller must align it first —
73
- otherwise marks silently drift vs 8001.
74
-
75
- Priority (locked):
76
- 0. FTShare pair present (both ``ts_millis`` + ``ts_millis_open``):
77
- **always** ``ts_millis`` (close). Beats generic ``ts``/``time`` so a
78
- coincidental open-named ``ts`` cannot steal the bar clock.
79
- 1. Explicit host canonical: ``time`` / ``timestamp`` / ``ts``
80
- 2. FTShare close alone: ``ts_millis``
81
- 3. Last resort open: ``ts_millis_open`` only if close missing
82
- """
83
- has_close = raw.get("ts_millis") is not None and raw.get("ts_millis") != ""
84
- has_open = raw.get("ts_millis_open") is not None and raw.get("ts_millis_open") != ""
85
-
86
- # FTShare contract detected → force close. Do not let generic ``ts`` win.
87
- if has_close and has_open:
88
- return raw.get("ts_millis")
89
-
90
- # Explicit host-provided canonical (interpreted as close by semantic lock).
91
- for key in ("time", "timestamp", "ts"):
92
- if raw.get(key) is not None and raw.get(key) != "":
93
- return raw.get(key)
94
-
95
- if has_close:
96
- return raw.get("ts_millis")
97
-
98
- if has_open:
99
- return raw.get("ts_millis_open")
100
-
101
- return None
102
-
103
-
104
- def _pick_raw_open_time(raw: dict[str, Any]) -> Any:
105
- """Return an explicit bar-open timestamp without changing ``time`` semantics."""
106
- for key in ("ts_millis_open", "open_time", "open_timestamp", "start_time"):
107
- if raw.get(key) is not None and raw.get(key) != "":
108
- return raw.get(key)
109
- return None
110
-
111
-
112
- def normalize_rows(rows: Any) -> list[dict[str, Any]]:
113
- """Normalize heterogeneous candle dicts to canonical rows (no length check).
114
-
115
- Accepts keys:
116
- time / timestamp / ts / ts_millis / ts_millis_open / date / trade_date
117
- open high low close volume/vol
118
- turnover / amount (optional passthrough — no v1 metric uses it)
119
-
120
- Output always:
121
- {time: sec, open, high, low, close, volume, [open_time?], [turnover?]}
122
- sorted ascending by time; duplicate times keep last.
123
- """
124
- out: list[dict[str, Any]] = []
125
- if not isinstance(rows, list):
126
- return out
127
- for raw in rows:
128
- if not isinstance(raw, dict):
129
- continue
130
- t = _to_time_sec(_pick_raw_time(raw))
131
- if t is None:
132
- date_txt = str(raw.get("date") or raw.get("trade_date") or "").strip()[:10]
133
- if date_txt:
134
- t = _date_text_to_sec(date_txt)
135
- o = _to_float(raw.get("open"))
136
- h = _to_float(raw.get("high"))
137
- l = _to_float(raw.get("low"))
138
- c = _to_float(raw.get("close"))
139
- vol = _to_float(raw.get("volume") if raw.get("volume") is not None else raw.get("vol"))
140
- volume = 0.0 if vol is None else float(vol)
141
- if t is None or None in (o, h, l, c) or not all(
142
- math.isfinite(float(value)) for value in (o, h, l, c, volume)
143
- ):
144
- # Drop incomplete bars (OHLC missing). validate_rows may still fail
145
- # if too few remain.
146
- continue
147
- row: dict[str, Any] = {
148
- "time": int(t),
149
- "open": float(o),
150
- "high": float(h),
151
- "low": float(l),
152
- "close": float(c),
153
- "volume": volume,
154
- }
155
- open_time = _to_time_sec(_pick_raw_open_time(raw))
156
- if open_time is not None and open_time <= int(t):
157
- row["open_time"] = int(open_time)
158
- turnover = _to_float(
159
- raw.get("turnover") if raw.get("turnover") is not None else raw.get("amount")
160
- )
161
- if turnover is not None:
162
- row["turnover"] = float(turnover)
163
- out.append(row)
164
-
165
- # Contract: sort by time ascending (even if input was shuffled).
166
- out.sort(key=lambda r: r["time"])
167
- # De-dup by time (keep last) — basic hygiene; advanced "reject dups" is P1.
168
- dedup: dict[int, dict[str, Any]] = {}
169
- for r in out:
170
- dedup[int(r["time"])] = r
171
- return [dedup[k] for k in sorted(dedup)]
172
-
173
-
174
- def validate_rows(rows: Any, *, min_len: int = 2, strict_prices: bool = False) -> list[dict[str, Any]]:
175
- """Contract gate for calc_* / draw_*.
176
-
177
- P0 basics (hard fail):
178
- 1. empty / fewer than min_len valid bars
179
- 2. OHLC missing after normalize (absorbed into length failure;
180
- if input is non-empty list but all bars lack OHLC → explicit message)
181
- 3. timestamps sorted ascending (normalize always sorts)
182
-
183
- Set strict_prices for public OHLCV input. Pivot/shape algorithms also use
184
- synthetic high/low sequences, so their existing contract stays unchanged.
185
- """
186
- if rows is None:
187
- raise RowsValidationError("rows is required (got None)")
188
- if not isinstance(rows, list):
189
- raise RowsValidationError(f"rows must be a list, got {type(rows).__name__}")
190
- if len(rows) == 0:
191
- raise RowsValidationError("rows is empty")
192
-
193
- for index, raw in enumerate(rows):
194
- if not isinstance(raw, dict):
195
- continue
196
- raw_time = _to_float(_pick_raw_time(raw))
197
- if raw_time is not None and not math.isfinite(raw_time):
198
- raise RowsValidationError(f"bar {index}: timestamp must be finite")
199
-
200
- raw_count = len(rows)
201
- norm = normalize_rows(rows)
202
-
203
- if raw_count > 0 and len(norm) == 0:
204
- raise RowsValidationError(
205
- f"no valid bars after normalize (input had {raw_count} items; "
206
- "need time + open/high/low/close on each bar)"
207
- )
208
- if len(norm) < min_len:
209
- raise RowsValidationError(
210
- f"need at least {min_len} valid bars, got {len(norm)} "
211
- f"(input items={raw_count})"
212
- )
213
-
214
- # Defensive: enforce monotonic times (normalize already sorts + dedups).
215
- prev = None
216
- for r in norm:
217
- t = int(r["time"])
218
- if strict_prices and r["high"] < r["low"]:
219
- raise RowsValidationError(f"bar at {t}: high must be at least low")
220
- if strict_prices and r["volume"] < 0:
221
- raise RowsValidationError(f"bar at {t}: volume must be non-negative")
222
- if prev is not None and t < prev:
223
- raise RowsValidationError(
224
- f"timestamps not sorted after normalize (saw {t} after {prev})"
225
- )
226
- prev = t
227
-
228
- return norm
@@ -1,99 +0,0 @@
1
- """Pinned TA-Lib engine shared by public analysis and built-in indicators."""
2
-
3
- from __future__ import annotations
4
-
5
- import math
6
- from typing import Any
7
-
8
- import numpy as np
9
- import talib
10
- from talib import abstract
11
-
12
-
13
- ENGINE_VERSION = "0.8.2"
14
- FUNCTION_COUNT = 201
15
- if talib.__version__ != ENGINE_VERSION or len(talib.get_functions()) != FUNCTION_COUNT:
16
- raise RuntimeError("TA-Lib version/catalog mismatch; legacy formulas are not a fallback")
17
-
18
- NATIVE_VERSION = getattr(talib, "__ta_version__", b"unknown")
19
- if isinstance(NATIVE_VERSION, bytes):
20
- NATIVE_VERSION = NATIVE_VERSION.decode("utf-8", errors="replace")
21
-
22
-
23
- def arrays(rows: list[dict[str, Any]]) -> dict[str, np.ndarray]:
24
- return {key: np.asarray([float(row[key]) for row in rows], dtype=np.float64)
25
- for key in ("open", "high", "low", "close", "volume")}
26
-
27
-
28
- def finite_map(rows: list[dict[str, Any]], values: Any, digits: int = 6) -> dict[int, float]:
29
- result: dict[int, float] = {}
30
- for row, value in zip(rows, values):
31
- number = float(value)
32
- if math.isfinite(number):
33
- result[int(row["time"])] = round(number, digits)
34
- return result
35
-
36
-
37
- def catalog() -> list[dict[str, Any]]:
38
- return [{"name": name, **abstract.Function(name).info} for name in talib.get_functions()]
39
-
40
-
41
- def calculate(name: str, rows: list[dict[str, Any]], *, parameters: dict[str, int | float] | None = None,
42
- price_sources: dict[str, str] | None = None, periods_constant: int = 14) -> tuple[dict[str, Any], dict[str, list[int | float | None]]]:
43
- if name not in talib.get_functions():
44
- raise ValueError("unknown TA-Lib function")
45
- if not 1 <= len(rows) <= 4000:
46
- raise ValueError("TA-Lib requires 1..4000 loaded candles")
47
- function = abstract.Function(name)
48
- info = function.info
49
- defaults = info["parameters"]
50
- selected = dict(parameters or {})
51
- if set(selected) - set(defaults):
52
- raise ValueError("unsupported TA-Lib parameter")
53
- for key, value in selected.items():
54
- default = defaults[key]
55
- if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):
56
- raise ValueError("TA-Lib parameters must be finite numbers")
57
- if type(default) is int and (type(value) is not int or abs(value) > 4000):
58
- raise ValueError("TA-Lib integer parameter out of bounds")
59
- if type(default) is float:
60
- if abs(value) > 1_000_000:
61
- raise ValueError("TA-Lib numeric parameter out of bounds")
62
- # JSON callers naturally send 2 for a deviation of 2.0. The
63
- # TA-Lib abstract wrapper requires an actual Python float.
64
- selected[key] = float(value)
65
- function.parameters = selected
66
- sources = dict(price_sources or {})
67
- allowed_roles = set(info["input_names"]) & {"price", "price0", "price1"}
68
- if set(sources) - allowed_roles:
69
- raise ValueError(f"{name} price_sources keys must be {sorted(allowed_roles)}; "
70
- "see list_ta_functions input_names, not low-level TA-Lib names")
71
- if any(value not in {"open", "high", "low", "close"} for value in sources.values()):
72
- raise ValueError("price_sources values must be open, high, low, or close")
73
- if sources:
74
- function.input_names = sources
75
- data = arrays(rows)
76
- if name == "MAVP":
77
- if type(periods_constant) is not int or not 2 <= periods_constant <= 4000:
78
- raise ValueError("MAVP periods_constant must be an integer from 2 to 4000")
79
- minperiod = selected.get("minperiod", defaults["minperiod"])
80
- maxperiod = selected.get("maxperiod", defaults["maxperiod"])
81
- if not minperiod <= periods_constant <= maxperiod:
82
- raise ValueError("MAVP periods_constant must be within minperiod and maxperiod")
83
- data["periods"] = np.full(len(rows), float(periods_constant), dtype=np.float64)
84
- elif periods_constant != 14:
85
- raise ValueError("periods_constant applies only to MAVP")
86
- function.set_input_arrays(data)
87
- raw = function()
88
- outputs = raw if isinstance(raw, (list, tuple)) else [raw]
89
- names = list(info["output_names"])
90
- if len(outputs) != len(names):
91
- raise RuntimeError("TA-Lib output metadata mismatch")
92
- values: dict[str, list[int | float | None]] = {}
93
- for output_name, output in zip(names, outputs):
94
- vector = np.asarray(output)
95
- if len(vector) != len(rows):
96
- raise RuntimeError("TA-Lib output length mismatch")
97
- integer_output = np.issubdtype(vector.dtype, np.integer)
98
- values[output_name] = [int(x) if integer_output else float(x) if math.isfinite(float(x)) else None for x in vector]
99
- return info, values
@@ -1,15 +0,0 @@
1
- /** Non-authorizing row identity for candle-index-aligned drawings. */
2
- export function candleSequenceHash(rows) {
3
- const bytes = new DataView(new ArrayBuffer(8));
4
- let hash = 0xcbf29ce484222325n;
5
- for (const row of rows)
6
- for (const key of ['time', 'open', 'high', 'low', 'close', 'volume']) {
7
- const value = row?.[key];
8
- if (typeof value !== 'number' || !Number.isFinite(value))
9
- throw Error('invalid_candle_sequence');
10
- bytes.setFloat64(0, value, false);
11
- for (let i = 0; i < 8; i++)
12
- hash = BigInt.asUintN(64, (hash ^ BigInt(bytes.getUint8(i))) * 0x100000001b3n);
13
- }
14
- return hash.toString(16).padStart(16, '0');
15
- }
@@ -1,7 +0,0 @@
1
- /** Metadata aliases only; never transform prices or guess missing adjustment. */
2
- export function normalizeAdjustment(value) {
3
- if (typeof value !== 'string')
4
- return null;
5
- const aliases = { none: 'none', forward: 'forward', backward: 'backward', qfq: 'forward', hfq: 'backward' };
6
- return Object.hasOwn(aliases, value.trim().toLowerCase()) ? aliases[value.trim().toLowerCase()] : null;
7
- }
@@ -1,33 +0,0 @@
1
- /** Canonical AI-owned text, numeric and icon annotations anchored to exact chart bars. */
2
- export const CHART_ANNOTATION_ICONS = ['arrow_up', 'arrow_down', 'diamond'];
3
- export function sanitizeChartAnnotation(raw) {
4
- if (raw?.type !== 'DRAW_AGENT_ANNOTATION' || !['text_annotation', 'number_annotation', 'icon_annotation'].includes(raw.kind)
5
- || typeof raw.id !== 'string' || !raw.id || raw.id.length > 128
6
- || !Number.isSafeInteger(raw.time) || raw.time <= 0 || typeof raw.price !== 'number' || !Number.isFinite(raw.price) || raw.price <= 0
7
- || !['info', 'warning', 'success', 'danger'].includes(raw.color ?? 'info')
8
- || typeof (raw.interval ?? 'day') !== 'string')
9
- throw Error('invalid_chart_annotation');
10
- const result = { type: raw.type, kind: raw.kind, id: raw.id, interval: raw.interval, label: raw.label ?? '', color: raw.color ?? 'info', time: raw.time, price: raw.price };
11
- if (typeof result.label !== 'string' || result.label.length > 48 || /[\x00-\x1f]/.test(result.label))
12
- throw Error('invalid_chart_annotation');
13
- if (raw.kind === 'text_annotation') {
14
- if (typeof raw.text !== 'string' || !raw.text.trim() || raw.text.trim().length > 120 || /[\x00-\x1f]/.test(raw.text))
15
- throw Error('invalid_chart_annotation');
16
- result.text = raw.text.trim();
17
- }
18
- else if (raw.kind === 'number_annotation') {
19
- if (typeof raw.value !== 'number' || !Number.isFinite(raw.value))
20
- throw Error('invalid_chart_annotation');
21
- result.value = raw.value;
22
- }
23
- else {
24
- if (!CHART_ANNOTATION_ICONS.includes(raw.icon))
25
- throw Error('invalid_chart_annotation');
26
- result.icon = raw.icon;
27
- }
28
- return result;
29
- }
30
- export function chartAnnotationText(command) {
31
- const clean = sanitizeChartAnnotation(command);
32
- return clean.kind === 'text_annotation' ? clean.text : clean.kind === 'number_annotation' ? String(clean.value) : clean.icon;
33
- }
@@ -1,171 +0,0 @@
1
- /** Single-delivery applications. Only a matching live-view state can confirm a candidate. */
2
- import { createHash, randomBytes } from 'node:crypto';
3
- import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
4
- import { join } from 'node:path';
5
- import { drawingInventory, observationKey } from "./chart-observation.js";
6
- import { sanitizeDrawingFeedback } from "./drawing-feedback.js";
7
- const TOKEN = /^[A-Za-z0-9_-]{32}$/;
8
- const TERMINAL = new Set(['applied', 'rejected', 'failed', 'outcome_unknown']);
9
- export class ChartApplications {
10
- runtime;
11
- now;
12
- constructor(runtime, now = () => Date.now()) { this.runtime = runtime; this.now = now; }
13
- directory(ref) { if (!TOKEN.test(ref))
14
- throw Error('invalid_apply_ref'); return join(this.runtime, 'edits', String(process.pid), ref); }
15
- path(ref, token) { if (!TOKEN.test(token))
16
- throw Error('invalid_apply_token'); return join(this.directory(ref), 'applications', token + '.json'); }
17
- async read(path) {
18
- const content = await readFile(path, 'utf8');
19
- if (content.length > 8 * 1024 * 1024)
20
- throw Error('invalid_apply_record');
21
- return JSON.parse(content);
22
- }
23
- async write(path, value) {
24
- await mkdir(join(path, '..'), { recursive: true, mode: 0o700 });
25
- const temporary = path + '.' + randomBytes(8).toString('hex') + '.tmp';
26
- await writeFile(temporary, JSON.stringify(value), { mode: 0o600, flag: 'wx' });
27
- await rename(temporary, path);
28
- }
29
- recoveryPath(conversation) {
30
- if (typeof conversation !== 'string' || !conversation || conversation.length > 1024)
31
- throw Error('invalid_recovery_owner');
32
- return join(this.runtime, 'recoveries', String(process.pid), createHash('sha256').update(conversation).digest('hex') + '.json');
33
- }
34
- async recover(conversation) {
35
- // A recovery checkpoint is an explicitly confirmed historical chart, not
36
- // a fallback current-view observation or a globally latest publication.
37
- const checkpoint = await this.read(this.recoveryPath(conversation));
38
- if (checkpoint.host_process_id !== process.pid || checkpoint.conversation_id !== conversation
39
- || !TOKEN.test(checkpoint.candidate_chart_session) || !TOKEN.test(checkpoint.context_ref))
40
- throw Error('invalid_recovery_checkpoint');
41
- const app = await this.read(this.path(checkpoint.context_ref, checkpoint.candidate_chart_session));
42
- if (app.status !== 'applied' || app.confirmed_chart_session !== checkpoint.candidate_chart_session
43
- || app.host_process_id !== process.pid || app.conversation_id !== conversation || app.context_ref !== checkpoint.context_ref)
44
- throw Error('unconfirmed_recovery');
45
- const candidate = await this.candidate(app);
46
- const ancestors = [], seen = new Set([checkpoint.candidate_chart_session]);
47
- let parent = candidate.drawing_parent_session;
48
- while (parent) {
49
- if (!TOKEN.test(parent) || seen.has(parent) || ancestors.length >= 64)
50
- throw Error('invalid_recovery_lineage');
51
- seen.add(parent);
52
- ancestors.push(parent);
53
- const saved = await this.read(join(this.runtime, 'sessions', parent + '.json'));
54
- if (saved.ok !== true || saved.session !== parent || saved.host_process_id !== process.pid)
55
- throw Error('invalid_recovery_lineage');
56
- const guard = saved.payload?.drawing_guard || saved.payload?.view_source_guard;
57
- if (!guard)
58
- break;
59
- if (guard.conversation_id !== conversation)
60
- throw Error('invalid_recovery_lineage');
61
- parent = saved.payload.drawing_parent_session;
62
- }
63
- const { drawing_guard, ...payload } = candidate;
64
- return { ok: true, session: checkpoint.candidate_chart_session, recovery: true, conversation_id: conversation,
65
- symbol: payload.symbol, name: payload.name, published_at: app.acknowledged_at_ms,
66
- recovery_scope: 'confirmed_historical_chart', render_verified: false,
67
- recovery_source_sessions: ancestors,
68
- payload: { ...payload, _live_chart_session: checkpoint.candidate_chart_session, _live_application_pending: false } };
69
- }
70
- validate(app, view, token) {
71
- if (app.host_process_id !== process.pid || app.context_ref !== view.ref || app.candidate_chart_session !== token
72
- || app.conversation_id !== view.conversation || app.view_id !== view.view)
73
- throw Error('invalid_apply_owner');
74
- }
75
- async candidate(app) {
76
- const saved = await this.read(join(this.runtime, 'sessions', app.candidate_chart_session + '.json'));
77
- const guard = saved.payload?.drawing_guard;
78
- if (saved.host_process_id !== process.pid || saved.session !== app.candidate_chart_session || saved.ok !== true
79
- || guard?.protocol !== 'prepared-only-v1' || guard.context_ref !== app.context_ref || guard.view_id !== app.view_id
80
- || guard.conversation_id !== app.conversation_id || guard.expected_revision !== app.expected_revision
81
- || guard.request_id !== app.request_id)
82
- throw Error('invalid_apply_candidate');
83
- return saved.payload;
84
- }
85
- publicReceipt(app) {
86
- return { candidate_chart_session: app.candidate_chart_session, lease_id: app.lease_id, apply_status: app.status,
87
- confirmed_chart_session: app.confirmed_chart_session ?? null, render_verified: false, confirmation_scope: app.status === 'applied' ? 'view_state_only' : 'not_confirmed',
88
- drawing_feedback: app.drawing_feedback ?? sanitizeDrawingFeedback(null, []) };
89
- }
90
- async acknowledge(view, receipt) {
91
- const token = receipt?.candidate_chart_session, lease = receipt?.lease_id;
92
- if (typeof token !== 'string' || !TOKEN.test(token) || typeof lease !== 'string' || !TOKEN.test(lease)
93
- || !['applied', 'rejected', 'failed', 'outcome_unknown'].includes(receipt.status))
94
- throw Error('invalid_apply_receipt');
95
- const path = this.path(view.ref, token), app = await this.read(path);
96
- this.validate(app, view, token);
97
- if (app.lease_id !== lease || !['delivered', 'applied', 'rejected', 'failed', 'outcome_unknown'].includes(app.status))
98
- throw Error('invalid_apply_lease');
99
- if (TERMINAL.has(app.status) && (app.status !== 'outcome_unknown' || app.acknowledged_at_ms !== undefined))
100
- return this.publicReceipt(app);
101
- const payload = await this.candidate(app);
102
- const allowed = [...new Map([...app.base_state.drawings.filter((d) => d.origin === 'ai'), ...drawingInventory(payload)].map((d) => [d.id, d])).values()];
103
- app.drawing_feedback = sanitizeDrawingFeedback(receipt.drawing_feedback, allowed);
104
- if (receipt.status === 'applied') {
105
- const expected = { ...app.base_state, source_chart_session: token,
106
- drawings: [...app.base_state.drawings.filter((d) => d.origin !== 'ai'), ...drawingInventory(payload)] };
107
- if (observationKey(view.state) !== observationKey(expected)) {
108
- app.status = 'outcome_unknown';
109
- app.reason = 'ack_state_mismatch';
110
- }
111
- else {
112
- app.status = 'applied';
113
- app.confirmed_chart_session = token;
114
- app.reason = 'state_confirmed';
115
- }
116
- }
117
- else {
118
- app.status = receipt.status;
119
- app.reason = ['local_state_changed', 'inactive', 'apply_failed', 'rollback_failed', 'invalid_delivery'].includes(receipt.reason)
120
- ? receipt.reason : 'view_reported_failure';
121
- }
122
- app.acknowledged_at_ms = this.now();
123
- await this.write(path, app);
124
- if (app.status === 'applied') {
125
- // Only a new successful receipt advances the per-conversation pointer.
126
- // A duplicate historical receipt cannot roll it back to an older chart.
127
- try {
128
- await this.write(this.recoveryPath(view.conversation), { host_process_id: process.pid, conversation_id: view.conversation,
129
- context_ref: view.ref, candidate_chart_session: token });
130
- }
131
- catch { }
132
- }
133
- return { ...this.publicReceipt(app), new_receipt: true };
134
- }
135
- async dispatch(view) {
136
- let index;
137
- try {
138
- index = await this.read(join(this.directory(view.ref), 'pending.json'));
139
- }
140
- catch (error) {
141
- if (error?.code === 'ENOENT')
142
- return undefined;
143
- throw error;
144
- }
145
- const token = index.candidate_chart_session, path = this.path(view.ref, token), app = await this.read(path);
146
- this.validate(app, view, token);
147
- if (!Number.isSafeInteger(app.expires_at_ms))
148
- throw Error('invalid_apply_deadline');
149
- if (this.now() > app.expires_at_ms && ['queued', 'delivered'].includes(app.status)) {
150
- app.status = app.status === 'queued' ? 'rejected' : 'outcome_unknown';
151
- app.reason = 'delivery_expired';
152
- await this.write(path, app);
153
- }
154
- if (app.status !== 'queued')
155
- return undefined; // Never resend a delivery whose reply may have been lost.
156
- if (view.applyCapable !== true || !view.active || view.ambiguous || view.revision !== app.expected_revision || observationKey(view.state) !== observationKey(app.base_state)) {
157
- app.status = 'rejected';
158
- app.reason = 'dispatch_state_changed';
159
- await this.write(path, app);
160
- return undefined;
161
- }
162
- const payload = await this.candidate(app);
163
- app.status = 'delivered';
164
- app.lease_id = randomBytes(24).toString('base64url');
165
- app.delivered_at_ms = this.now();
166
- await this.write(path, app); // Record delivery before sending it to a browser.
167
- return { candidate_chart_session: token, context_ref: view.ref, conversation_id: view.conversation, view_id: view.view,
168
- expected_revision: view.revision, lease_id: app.lease_id, expires_at_ms: app.expires_at_ms, base_state: app.base_state,
169
- payload: { symbol: payload.symbol, interval: payload.interval, chartCommands: payload.chartCommands.filter((c) => ['DRAW_HORIZONTAL_LINE', 'DRAW_AGENT_TREND_LINE', 'DRAW_AGENT_CHANNEL', 'DRAW_AGENT_RECTANGLE', 'DRAW_AGENT_FIBONACCI', 'DRAW_AGENT_POLYLINE', 'DRAW_AGENT_ANNOTATION', 'DRAW_AGENT_SERIES_LINE', 'DRAW_AGENT_PRICE_BAND', 'DRAW_AGENT_PRICE_STICKS', 'DRAW_AGENT_PRICE_PATTERN', 'DRAW_AGENT_NINE_COUNT'].includes(c.type)) } };
170
- }
171
- }