@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,683 +0,0 @@
1
- """Single source of truth for indicators and metrics.
2
-
3
- Rules (locked):
4
- - Public API times are unix **seconds**.
5
- - `calc_metrics` / `draw_kline` share the same functions + same defaults.
6
- - Summary schemas are stable; full series returned only for chart rendering.
7
- - No RSI divergence in v1.
8
- - duration always emits both `duration_bars` and `duration_days` (calendar).
9
- """
10
-
11
- from __future__ import annotations
12
-
13
- import math
14
- from typing import Any, Iterable
15
-
16
- from core.ta_engine import ENGINE_VERSION, NATIVE_VERSION, arrays as _ta_arrays, finite_map as _ta_map, talib
17
-
18
-
19
- # ---------------------------------------------------------------------------
20
- # Defaults (shared by calc_metrics + draw_kline)
21
- # ---------------------------------------------------------------------------
22
- DEFAULT_MA_PERIODS = [5, 10, 20, 30, 60]
23
- DEFAULT_LOOKBACK = 60
24
- DEFAULT_TOLERANCE_PCT = 0.5 # support/resistance touch band
25
- DEFAULT_RSI_PERIOD = 14
26
- DEFAULT_BOLL_PERIOD = 20
27
- DEFAULT_BOLL_STD = 2.0
28
- DEFAULT_ATR_PERIOD = 14
29
- DEFAULT_VOLUME_MA = 20
30
- DEFAULT_VOLUME_RATIO = 1.5
31
- DEFAULT_MACD = (12, 26, 9)
32
- DEFAULT_KDJ = (9, 3, 3)
33
-
34
-
35
- # ---------------------------------------------------------------------------
36
- # Helpers
37
- # ---------------------------------------------------------------------------
38
- def _finite(v: Any) -> float | None:
39
- try:
40
- f = float(v)
41
- except (TypeError, ValueError):
42
- return None
43
- if not math.isfinite(f):
44
- return None
45
- return f
46
-
47
-
48
- def _round(v: float | None, n: int = 4) -> float | None:
49
- if v is None:
50
- return None
51
- return round(float(v), n)
52
-
53
-
54
- def _calendar_days(t0: int, t1: int) -> int:
55
- """Calendar days between two unix-second timestamps (inclusive-ish span)."""
56
- if t1 < t0:
57
- t0, t1 = t1, t0
58
- return max(0, int((t1 - t0) // 86400))
59
-
60
-
61
- def _closes(rows: list[dict[str, Any]]) -> list[float]:
62
- return [float(r["close"]) for r in rows]
63
-
64
-
65
- def _highs(rows: list[dict[str, Any]]) -> list[float]:
66
- return [float(r["high"]) for r in rows]
67
-
68
-
69
- def _lows(rows: list[dict[str, Any]]) -> list[float]:
70
- return [float(r["low"]) for r in rows]
71
-
72
-
73
- def _volumes(rows: list[dict[str, Any]]) -> list[float]:
74
- return [float(r.get("volume") or 0.0) for r in rows]
75
-
76
-
77
- def _times(rows: list[dict[str, Any]]) -> list[int]:
78
- return [int(r["time"]) for r in rows]
79
-
80
-
81
- # ---------------------------------------------------------------------------
82
- # Full series (used by draw_kline / SET_INDICATOR_SERIES)
83
- # Keys of returned maps are **seconds** (str for JSON safety optional — we use int keys
84
- # in python, tools will stringify).
85
- # ---------------------------------------------------------------------------
86
- def series_ma(
87
- rows: list[dict[str, Any]],
88
- periods: Iterable[int] | None = None,
89
- ) -> dict[str, dict[int, float]]:
90
- """Return {f"ma{p}": {time_sec: value}} for each period."""
91
- periods = list(periods or DEFAULT_MA_PERIODS)
92
- if not rows:
93
- return {f"ma{int(p)}": {} for p in periods}
94
- close = _ta_arrays(rows)["close"]
95
- return {f"ma{int(p)}": _ta_map(rows, talib.SMA(close, timeperiod=int(p))) for p in periods}
96
-
97
-
98
- def series_vol_ma(
99
- rows: list[dict[str, Any]],
100
- period: int = DEFAULT_VOLUME_MA,
101
- ) -> dict[int, float]:
102
- if not rows:
103
- return {}
104
- volume = _ta_arrays(rows)["volume"]
105
- return _ta_map(rows, talib.SMA(volume, timeperiod=int(period)), digits=4)
106
-
107
-
108
- def series_macd(
109
- rows: list[dict[str, Any]],
110
- fast: int = DEFAULT_MACD[0],
111
- slow: int = DEFAULT_MACD[1],
112
- signal: int = DEFAULT_MACD[2],
113
- ) -> dict[str, dict[int, float]]:
114
- """TA-Lib MACD; hist is DIF-DEA without the former x2 convention."""
115
- if not rows:
116
- return {"dif": {}, "dea": {}, "hist": {}}
117
- close = _ta_arrays(rows)["close"]
118
- dif, dea, hist = talib.MACD(close, fastperiod=int(fast), slowperiod=int(slow), signalperiod=int(signal))
119
- return {"dif": _ta_map(rows, dif), "dea": _ta_map(rows, dea), "hist": _ta_map(rows, hist)}
120
-
121
-
122
- def series_kdj(
123
- rows: list[dict[str, Any]],
124
- n: int = DEFAULT_KDJ[0],
125
- m1: int = DEFAULT_KDJ[1],
126
- m2: int = DEFAULT_KDJ[2],
127
- ) -> dict[str, dict[int, float]]:
128
- if not rows:
129
- return {"k": {}, "d": {}, "j": {}}
130
- values = _ta_arrays(rows)
131
- k, d, j = talib.KDJ(values["high"], values["low"], values["close"],
132
- fastk_period=int(n), slowk_period=int(m1), slowk_matype=13,
133
- slowd_period=int(m2), slowd_matype=13)
134
- return {"k": _ta_map(rows, k, 4), "d": _ta_map(rows, d, 4), "j": _ta_map(rows, j, 4)}
135
-
136
-
137
- def series_boll(
138
- rows: list[dict[str, Any]],
139
- period: int = DEFAULT_BOLL_PERIOD,
140
- std_mult: float = DEFAULT_BOLL_STD,
141
- ) -> dict[str, dict[int, float]]:
142
- if not rows:
143
- return {"mid": {}, "upper": {}, "lower": {}}
144
- close = _ta_arrays(rows)["close"]
145
- upper, mid, lower = talib.BBANDS(close, timeperiod=int(period), nbdevup=float(std_mult),
146
- nbdevdn=float(std_mult), matype=0)
147
- return {"mid": _ta_map(rows, mid), "upper": _ta_map(rows, upper), "lower": _ta_map(rows, lower)}
148
-
149
-
150
- def series_rsi(
151
- rows: list[dict[str, Any]],
152
- period: int = DEFAULT_RSI_PERIOD,
153
- ) -> dict[int, float]:
154
- if not rows:
155
- return {}
156
- close = _ta_arrays(rows)["close"]
157
- return _ta_map(rows, talib.RSI(close, timeperiod=int(period)), digits=4)
158
-
159
-
160
- def series_vwap(rows: list[dict[str, Any]]) -> dict[int, float]:
161
- """TA-Lib path-dependent VWAP anchored at the first supplied bar."""
162
- if not rows:
163
- return {}
164
- values = _ta_arrays(rows)
165
- return _ta_map(rows, talib.VWAP(values["high"], values["low"], values["close"], values["volume"]))
166
-
167
-
168
- def series_atr(
169
- rows: list[dict[str, Any]],
170
- period: int = DEFAULT_ATR_PERIOD,
171
- ) -> dict[int, float]:
172
- if not rows:
173
- return {}
174
- values = _ta_arrays(rows)
175
- return _ta_map(rows, talib.ATR(values["high"], values["low"], values["close"], timeperiod=int(period)))
176
-
177
-
178
- # ---------------------------------------------------------------------------
179
- # Metric summaries (stable schemas for host LLM)
180
- # ---------------------------------------------------------------------------
181
- def metric_max_drawdown(rows: list[dict[str, Any]]) -> dict[str, Any]:
182
- """Peak-to-trough max drawdown on close series."""
183
- if not rows:
184
- return {
185
- "max_drawdown_pct": None,
186
- "peak": None,
187
- "trough": None,
188
- "duration_bars": 0,
189
- "duration_days": 0,
190
- }
191
- peak_idx = 0
192
- peak_price = float(rows[0]["close"])
193
- worst = 0.0
194
- worst_peak_idx = 0
195
- worst_trough_idx = 0
196
- for i, r in enumerate(rows):
197
- c = float(r["close"])
198
- if c > peak_price:
199
- peak_price = c
200
- peak_idx = i
201
- if peak_price > 0:
202
- dd = c / peak_price - 1.0
203
- if dd < worst:
204
- worst = dd
205
- worst_peak_idx = peak_idx
206
- worst_trough_idx = i
207
- peak = rows[worst_peak_idx]
208
- trough = rows[worst_trough_idx]
209
- t0, t1 = int(peak["time"]), int(trough["time"])
210
- return {
211
- "max_drawdown_pct": round(worst * 100.0, 4),
212
- "peak": {
213
- "time": t0,
214
- "price": round(float(peak["close"]), 4),
215
- "idx": worst_peak_idx,
216
- },
217
- "trough": {
218
- "time": t1,
219
- "price": round(float(trough["close"]), 4),
220
- "idx": worst_trough_idx,
221
- },
222
- "duration_bars": max(0, worst_trough_idx - worst_peak_idx),
223
- "duration_days": _calendar_days(t0, t1),
224
- }
225
-
226
-
227
- def metric_support_resistance(
228
- rows: list[dict[str, Any]],
229
- *,
230
- lookback: int = DEFAULT_LOOKBACK,
231
- tolerance_pct: float = DEFAULT_TOLERANCE_PCT,
232
- max_levels: int = 5,
233
- ) -> dict[str, Any]:
234
- """Fractal swing highs/lows clustered by tolerance_pct."""
235
- n = len(rows)
236
- lookback = max(5, min(int(lookback), n))
237
- window = rows[-lookback:]
238
- offset = n - len(window)
239
- # fractal: local max/min with 2-bar wings
240
- swings_high: list[tuple[int, float]] = []
241
- swings_low: list[tuple[int, float]] = []
242
- for i in range(2, len(window) - 2):
243
- h = float(window[i]["high"])
244
- l = float(window[i]["low"])
245
- if (
246
- h >= float(window[i - 1]["high"])
247
- and h >= float(window[i - 2]["high"])
248
- and h >= float(window[i + 1]["high"])
249
- and h >= float(window[i + 2]["high"])
250
- ):
251
- swings_high.append((offset + i, h))
252
- if (
253
- l <= float(window[i - 1]["low"])
254
- and l <= float(window[i - 2]["low"])
255
- and l <= float(window[i + 1]["low"])
256
- and l <= float(window[i + 2]["low"])
257
- ):
258
- swings_low.append((offset + i, l))
259
-
260
- def cluster(levels: list[tuple[int, float]], *, kind: str) -> list[dict[str, Any]]:
261
- if not levels:
262
- return []
263
- # sort by price
264
- levels = sorted(levels, key=lambda x: x[1])
265
- clusters: list[list[tuple[int, float]]] = []
266
- for idx, price in levels:
267
- placed = False
268
- for cl in clusters:
269
- rep = sum(p for _, p in cl) / len(cl)
270
- if rep > 0 and abs(price - rep) / rep * 100.0 <= tolerance_pct:
271
- cl.append((idx, price))
272
- placed = True
273
- break
274
- if not placed:
275
- clusters.append([(idx, price)])
276
- out: list[dict[str, Any]] = []
277
- last_close = float(rows[-1]["close"])
278
- for cl in clusters:
279
- prices = [p for _, p in cl]
280
- idxs = [i for i, _ in cl]
281
- level = sum(prices) / len(prices)
282
- # A later bar crossing the level invalidates its original role.
283
- # Keep historical pivots out of the current support/resistance set.
284
- later = rows[max(idxs) + 1:]
285
- if kind == "support" and any(float(r["low"]) < level for r in later):
286
- continue
287
- if kind == "resistance" and any(float(r["high"]) > level for r in later):
288
- continue
289
- # touches: bars whose high/low within band
290
- band = level * (tolerance_pct / 100.0)
291
- touches = 0
292
- for r in window:
293
- if kind == "resistance":
294
- if abs(float(r["high"]) - level) <= band:
295
- touches += 1
296
- elif abs(float(r["low"]) - level) <= band:
297
- touches += 1
298
- out.append(
299
- {
300
- "price": round(level, 4),
301
- "touches": int(touches),
302
- "strength": round(min(1.0, touches / 5.0), 3),
303
- "last_idx": int(max(idxs)),
304
- "last_time": int(rows[max(idxs)]["time"]),
305
- "side": "above" if level >= last_close else "below",
306
- }
307
- )
308
- # Rank all candidates first. Side filtering happens before the limit so
309
- # stale levels cannot consume the five available slots.
310
- out.sort(key=lambda x: (-x["touches"], abs(x["price"] - last_close)))
311
- return out
312
-
313
- last_close = float(rows[-1]["close"])
314
- supports = [x for x in cluster(swings_low, kind="support") if x["price"] <= last_close][:max_levels]
315
- resistances = [
316
- x
317
- for x in cluster(swings_high, kind="resistance")
318
- if x["price"] >= last_close
319
- ][:max_levels]
320
- return {
321
- "method": "fractal",
322
- "lookback": lookback,
323
- "tolerance_pct": float(tolerance_pct),
324
- "support": supports,
325
- "resistance": resistances,
326
- }
327
-
328
-
329
- def metric_ma_cross(
330
- rows: list[dict[str, Any]],
331
- *,
332
- ma_periods: list[int] | None = None,
333
- ) -> dict[str, Any]:
334
- """All C(n,2) pairs among ma_periods. Distinguish empty crosses vs not requested.
335
-
336
- Schema:
337
- {
338
- "periods": [5,10,20],
339
- "pairs": ["5x10","5x20","10x20"],
340
- "crosses": [{time, idx, type: golden|death, fast, slow, price}],
341
- "pair_stats": {"5x10": {"cross_count": 0, "last": null}, ...}
342
- }
343
- """
344
- periods = sorted({int(p) for p in (ma_periods or DEFAULT_MA_PERIODS) if int(p) > 0})
345
- pairs = [(periods[i], periods[j]) for i in range(len(periods)) for j in range(i + 1, len(periods))]
346
- pair_keys = [f"{a}x{b}" for a, b in pairs]
347
- series = series_ma(rows, periods)
348
- closes = _closes(rows)
349
- times = _times(rows)
350
- crosses: list[dict[str, Any]] = []
351
- pair_stats: dict[str, Any] = {k: {"cross_count": 0, "last": None} for k in pair_keys}
352
-
353
- for a, b in pairs:
354
- key = f"{a}x{b}"
355
- ma_a = series.get(f"ma{a}", {})
356
- ma_b = series.get(f"ma{b}", {})
357
- prev_diff: float | None = None
358
- for i, t in enumerate(times):
359
- va = ma_a.get(int(t))
360
- vb = ma_b.get(int(t))
361
- if va is None or vb is None:
362
- prev_diff = None
363
- continue
364
- diff = va - vb
365
- # Exact touch (diff==0) carries no cross direction; keep previous sign.
366
- # Using <=0 / >=0 would phantom-cross on flat MA equalities (limit-up days).
367
- if diff == 0:
368
- continue
369
- if prev_diff is not None:
370
- # golden: fast crosses above slow (a is faster = smaller period)
371
- if prev_diff < 0 < diff:
372
- item = {
373
- "time": int(t),
374
- "idx": i,
375
- "type": "golden",
376
- "fast": a,
377
- "slow": b,
378
- "price": round(closes[i], 4),
379
- }
380
- crosses.append(item)
381
- pair_stats[key]["cross_count"] += 1
382
- pair_stats[key]["last"] = item
383
- elif prev_diff > 0 > diff:
384
- item = {
385
- "time": int(t),
386
- "idx": i,
387
- "type": "death",
388
- "fast": a,
389
- "slow": b,
390
- "price": round(closes[i], 4),
391
- }
392
- crosses.append(item)
393
- pair_stats[key]["cross_count"] += 1
394
- pair_stats[key]["last"] = item
395
- prev_diff = diff
396
-
397
- crosses.sort(key=lambda x: x["time"])
398
- return {
399
- "periods": periods,
400
- "pairs": pair_keys,
401
- "crosses": crosses,
402
- "pair_stats": pair_stats,
403
- # Convenience: empty crosses means computed but none found (pairs non-empty).
404
- # Missing pair key in pair_stats would mean "not computed" — we always fill all pairs.
405
- }
406
-
407
-
408
- def metric_volume_breakout(
409
- rows: list[dict[str, Any]],
410
- *,
411
- volume_ma: int = DEFAULT_VOLUME_MA,
412
- volume_ratio: float = DEFAULT_VOLUME_RATIO,
413
- ma_period: int = 20,
414
- ) -> dict[str, Any]:
415
- """Volume spike + close cross above/below MA."""
416
- times = _times(rows)
417
- closes = _closes(rows)
418
- vols = _volumes(rows)
419
- ma_map = series_ma(rows, [ma_period]).get(f"ma{ma_period}", {})
420
- vol_ma_map = series_vol_ma(rows, volume_ma)
421
- events: list[dict[str, Any]] = []
422
- for i in range(1, len(rows)):
423
- t = int(times[i])
424
- t_prev = int(times[i - 1])
425
- ma = ma_map.get(t)
426
- ma_prev = ma_map.get(t_prev)
427
- vma = vol_ma_map.get(t)
428
- if ma is None or ma_prev is None or not vma or vma <= 0:
429
- continue
430
- ratio = vols[i] / vma
431
- if ratio < volume_ratio:
432
- continue
433
- c, c_prev = closes[i], closes[i - 1]
434
- direction = None
435
- if c_prev <= ma_prev and c > ma:
436
- direction = "breakout_up"
437
- elif c_prev >= ma_prev and c < ma:
438
- direction = "breakdown"
439
- if not direction:
440
- continue
441
- events.append(
442
- {
443
- "time": t,
444
- "idx": i,
445
- "price": round(c, 4),
446
- "ma": round(ma, 4),
447
- "volume": round(vols[i], 2),
448
- "volume_ma": round(vma, 2),
449
- "volume_ratio": round(ratio, 3),
450
- "direction": direction,
451
- "ma_period": ma_period,
452
- }
453
- )
454
- return {
455
- "volume_ma": int(volume_ma),
456
- "volume_ratio": float(volume_ratio),
457
- "ma_period": int(ma_period),
458
- "events": events,
459
- "count": len(events),
460
- }
461
-
462
-
463
- def metric_bollinger(
464
- rows: list[dict[str, Any]],
465
- *,
466
- period: int = DEFAULT_BOLL_PERIOD,
467
- std_mult: float = DEFAULT_BOLL_STD,
468
- ) -> dict[str, Any]:
469
- series = series_boll(rows, period=period, std_mult=std_mult)
470
- last_t = int(rows[-1]["time"])
471
- last_c = float(rows[-1]["close"])
472
- mid = series["mid"].get(last_t)
473
- upper = series["upper"].get(last_t)
474
- lower = series["lower"].get(last_t)
475
- width_pct = None
476
- pct_b = None
477
- if mid is not None and upper is not None and lower is not None and upper != lower and mid != 0:
478
- width_pct = round((upper - lower) / mid * 100.0, 4)
479
- pct_b = round((last_c - lower) / (upper - lower), 4)
480
- return {
481
- "period": int(period),
482
- "std_mult": float(std_mult),
483
- "last": {
484
- "time": last_t,
485
- "close": round(last_c, 4),
486
- "mid": _round(mid),
487
- "upper": _round(upper),
488
- "lower": _round(lower),
489
- "width_pct": width_pct,
490
- "pct_b": pct_b,
491
- },
492
- }
493
-
494
-
495
- def metric_rsi(
496
- rows: list[dict[str, Any]],
497
- *,
498
- period: int = DEFAULT_RSI_PERIOD,
499
- ) -> dict[str, Any]:
500
- """RSI summary. No divergence in v1."""
501
- s = series_rsi(rows, period=period)
502
- if not s:
503
- return {"period": int(period), "last": None, "overbought": [], "oversold": []}
504
- last_t = max(s)
505
- last_v = s[last_t]
506
- overbought = [
507
- {"time": t, "value": v} for t, v in s.items() if v >= 70
508
- ][-10:]
509
- oversold = [
510
- {"time": t, "value": v} for t, v in s.items() if v <= 30
511
- ][-10:]
512
- return {
513
- "period": int(period),
514
- "last": {"time": int(last_t), "value": last_v},
515
- "overbought": overbought,
516
- "oversold": oversold,
517
- # divergence intentionally omitted in v1
518
- }
519
-
520
-
521
- def metric_atr(
522
- rows: list[dict[str, Any]],
523
- *,
524
- period: int = DEFAULT_ATR_PERIOD,
525
- ) -> dict[str, Any]:
526
- s = series_atr(rows, period=period)
527
- if not s:
528
- return {"period": int(period), "last": None, "atr_pct": None}
529
- last_t = max(s)
530
- last_atr = s[last_t]
531
- last_c = float(rows[-1]["close"])
532
- atr_pct = round(last_atr / last_c * 100.0, 4) if last_c else None
533
- return {
534
- "period": int(period),
535
- "last": {"time": int(last_t), "value": last_atr},
536
- "atr_pct": atr_pct,
537
- }
538
-
539
-
540
- # ---------------------------------------------------------------------------
541
- # Public aggregators
542
- # ---------------------------------------------------------------------------
543
- AVAILABLE_METRICS = (
544
- "max_drawdown",
545
- "support_resistance",
546
- "ma_cross",
547
- "volume_breakout",
548
- "bollinger",
549
- "rsi",
550
- "atr",
551
- )
552
-
553
-
554
- def calc_metrics(
555
- rows: list[dict[str, Any]],
556
- metrics: list[str] | None = None,
557
- *,
558
- lookback: int = DEFAULT_LOOKBACK,
559
- ma_periods: list[int] | None = None,
560
- tolerance_pct: float = DEFAULT_TOLERANCE_PCT,
561
- rsi_period: int = DEFAULT_RSI_PERIOD,
562
- boll_period: int = DEFAULT_BOLL_PERIOD,
563
- boll_std: float = DEFAULT_BOLL_STD,
564
- atr_period: int = DEFAULT_ATR_PERIOD,
565
- volume_ma: int = DEFAULT_VOLUME_MA,
566
- volume_ratio: float = DEFAULT_VOLUME_RATIO,
567
- ) -> dict[str, Any]:
568
- """Compute selected metric **summaries** (no full series)."""
569
- wanted = list(metrics or list(AVAILABLE_METRICS))
570
- # preserve order, drop unknown
571
- ordered = [m for m in wanted if m in AVAILABLE_METRICS]
572
- unknown = [m for m in wanted if m not in AVAILABLE_METRICS]
573
- result: dict[str, Any] = {
574
- "calculation_engine": {"name": "TA-Lib", "wrapper_version": ENGINE_VERSION,
575
- "native_version": NATIVE_VERSION},
576
- "count": len(rows),
577
- "start_time": int(rows[0]["time"]) if rows else None,
578
- "end_time": int(rows[-1]["time"]) if rows else None,
579
- "metrics_computed": ordered,
580
- "metrics_unknown": unknown,
581
- }
582
- for m in ordered:
583
- if m == "max_drawdown":
584
- result[m] = metric_max_drawdown(rows)
585
- elif m == "support_resistance":
586
- result[m] = metric_support_resistance(
587
- rows, lookback=lookback, tolerance_pct=tolerance_pct
588
- )
589
- elif m == "ma_cross":
590
- result[m] = metric_ma_cross(rows, ma_periods=ma_periods)
591
- elif m == "volume_breakout":
592
- result[m] = metric_volume_breakout(
593
- rows, volume_ma=volume_ma, volume_ratio=volume_ratio
594
- )
595
- elif m == "bollinger":
596
- result[m] = metric_bollinger(rows, period=boll_period, std_mult=boll_std)
597
- elif m == "rsi":
598
- result[m] = metric_rsi(rows, period=rsi_period)
599
- elif m == "atr":
600
- result[m] = metric_atr(rows, period=atr_period)
601
- return result
602
-
603
-
604
- def calc_range(
605
- rows: list[dict[str, Any]],
606
- *,
607
- start_time: int | None = None,
608
- end_time: int | None = None,
609
- start_idx: int | None = None,
610
- end_idx: int | None = None,
611
- ) -> dict[str, Any]:
612
- """Interval stats over a sub-range of rows."""
613
- n = len(rows)
614
- if n == 0:
615
- raise ValueError("empty rows")
616
-
617
- if start_idx is not None or end_idx is not None:
618
- s = 0 if start_idx is None else max(0, min(n - 1, int(start_idx)))
619
- e = n - 1 if end_idx is None else max(0, min(n - 1, int(end_idx)))
620
- else:
621
- s, e = 0, n - 1
622
- if start_time is not None:
623
- st = int(start_time)
624
- # nearest >= start_time, else last
625
- s = next((i for i, r in enumerate(rows) if int(r["time"]) >= st), n - 1)
626
- if end_time is not None:
627
- et = int(end_time)
628
- e = next(
629
- (i for i in range(n - 1, -1, -1) if int(rows[i]["time"]) <= et),
630
- 0,
631
- )
632
- if e < s:
633
- s, e = e, s
634
- win = rows[s : e + 1]
635
- if len(win) < 1:
636
- raise ValueError("empty range window")
637
-
638
- first, last = win[0], win[-1]
639
- o = float(first["open"])
640
- c = float(last["close"])
641
- hh = max(float(r["high"]) for r in win)
642
- ll = min(float(r["low"]) for r in win)
643
- ret_pct = (c / o - 1.0) * 100.0 if o else 0.0
644
- amp_pct = (hh - ll) / o * 100.0 if o else 0.0
645
- up_days = sum(1 for r in win if float(r["close"]) >= float(r["open"]))
646
- down_days = len(win) - up_days
647
- # consecutive runs
648
- max_up = max_down = cur_up = cur_down = 0
649
- for r in win:
650
- if float(r["close"]) >= float(r["open"]):
651
- cur_up += 1
652
- cur_down = 0
653
- else:
654
- cur_down += 1
655
- cur_up = 0
656
- max_up = max(max_up, cur_up)
657
- max_down = max(max_down, cur_down)
658
- total_vol = sum(float(r.get("volume") or 0) for r in win)
659
- avg_vol = total_vol / len(win) if win else 0.0
660
- dd = metric_max_drawdown(win)
661
- t0, t1 = int(first["time"]), int(last["time"])
662
- return {
663
- "start_idx": s,
664
- "end_idx": e,
665
- "start_time": t0,
666
- "end_time": t1,
667
- "bars": len(win),
668
- "duration_bars": len(win),
669
- "duration_days": _calendar_days(t0, t1),
670
- "open": round(o, 4),
671
- "close": round(c, 4),
672
- "high": round(hh, 4),
673
- "low": round(ll, 4),
674
- "return_pct": round(ret_pct, 4),
675
- "amplitude_pct": round(amp_pct, 4),
676
- "up_bars": up_days,
677
- "down_bars": down_days,
678
- "max_up_streak": max_up,
679
- "max_down_streak": max_down,
680
- "total_volume": round(total_vol, 2),
681
- "avg_volume": round(avg_vol, 2),
682
- "max_drawdown": dd,
683
- }