@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,83 +0,0 @@
1
- """Finite price-domain retracements. No pivot discovery or pixel interpolation."""
2
- from __future__ import annotations
3
-
4
- from copy import deepcopy
5
- import hashlib
6
- import math
7
- import secrets
8
-
9
- from tools.lines import LineError, validate_line_fields
10
- from tools.trend_lines import resolve_anchor_time
11
-
12
- FIBONACCI_COMMAND = "DRAW_AGENT_FIBONACCI"
13
- DEFAULT_RATIOS = [0, .236, .382, .5, .618, .786, 1]
14
-
15
-
16
- def validate_ratios(ratios):
17
- if (not isinstance(ratios, list) or not 1 <= len(ratios) <= 16
18
- or any(type(r) not in (int, float) or not math.isfinite(r) or not 0 <= r <= 1 for r in ratios)
19
- or any(a >= b for a, b in zip(ratios, ratios[1:]))):
20
- raise LineError("invalid_fibonacci_ratios", "回撤比例需为1至16个递增、不重复的0至1有限数值;未自动排序。")
21
- return [float(r) for r in ratios]
22
-
23
-
24
- def fibonacci_levels(start_price, end_price, ratios):
25
- start, _, _ = validate_line_fields(price=start_price)
26
- end, _, _ = validate_line_fields(price=end_price)
27
- if start == end:
28
- raise LineError("zero_fibonacci_range", "两个锚点价格不能相同。")
29
- levels = [{"ratio": r, "price": end - r * (end - start)} for r in validate_ratios(ratios)]
30
- if any(not math.isfinite(p["price"]) or p["price"] <= 0 for p in levels):
31
- raise LineError("invalid_fibonacci_price", "回撤价位必须为大于零的有限数值。")
32
- return levels
33
-
34
-
35
- def edit_fibonacci(payload, action, *, fibonacci_id=None, start_time=None, start_price=None,
36
- end_time=None, end_price=None, ratios=None, name=None, color=None, request_id=None):
37
- result = deepcopy(payload)
38
- commands = result.get("chartCommands", [])
39
- previous = next((c for c in commands if c.get("type") == FIBONACCI_COMMAND and c.get("id") == fibonacci_id), None)
40
- if action in {"update", "delete"} and previous is None:
41
- raise LineError("fibonacci_not_found", "当前快照不存在该 AI 斐波那契对象,请先读取对象 ID。")
42
- if action == "delete":
43
- commands.remove(previous)
44
- return result, deepcopy(previous)
45
- if action not in {"create", "update"}:
46
- raise LineError("invalid_action", "不支持的斐波那契操作。")
47
- values = (start_time, start_price, end_time, end_price)
48
- if action == "create" and any(v is None for v in values):
49
- raise LineError("missing_anchor", "需要明确的两个时间和价格锚点,不自动选择最近高低点。")
50
- if action == "update" and all(v is None for v in (*values, ratios, name, color)):
51
- raise LineError("empty_update", "请至少修改锚点、比例、名称或颜色。")
52
- _, name, color = validate_line_fields(name=name, color=color, request_id=request_id)
53
- anchors = []
54
- for key, time, price in (("from", start_time, start_price), ("to", end_time, end_price)):
55
- old = previous[key] if previous else {}
56
- value, _, _ = validate_line_fields(price=price if price is not None else old.get("price"))
57
- anchors.append({"time": resolve_anchor_time(payload, time) if time is not None else old["time"], "price": value})
58
- start, end = anchors
59
- if start["time"] >= end["time"]:
60
- raise LineError("invalid_anchor_order", "斐波那契起点必须早于终点;未自动交换锚点。")
61
- ratios = validate_ratios(ratios if ratios is not None else previous["ratios"] if previous else DEFAULT_RATIOS)
62
- obj = {"type": FIBONACCI_COMMAND, "id": previous["id"] if previous else "fib_" + secrets.token_hex(12),
63
- "interval": payload.get("interval"), "from": start, "to": end, "ratios": ratios,
64
- "levels": fibonacci_levels(start["price"], end["price"], ratios), "geometry_basis": "linear_price_retracement",
65
- "label": name if name is not None else previous["label"] if previous else "",
66
- "color": color if color is not None else previous["color"] if previous else "info"}
67
- if previous and previous.get("create_request_id"):
68
- obj["create_request_id"] = previous["create_request_id"]
69
- if action == "create":
70
- if request_id:
71
- obj["create_request_id"] = request_id
72
- obj["id"] = "fib_" + hashlib.sha256(request_id.encode()).hexdigest()[:24]
73
- retry = next((c for c in commands if c.get("type") == FIBONACCI_COMMAND and c.get("create_request_id") == request_id), None)
74
- if retry:
75
- if any(retry.get(k) != obj[k] for k in ("from", "to", "ratios", "label", "color")):
76
- raise LineError("request_conflict", "同一 request_id 的斐波那契参数不同。")
77
- return result, deepcopy(retry)
78
- if sum(c.get("type") == FIBONACCI_COMMAND for c in commands) >= 30:
79
- raise LineError("too_many_fibonacci", "当前图表最多保存30组 AI 斐波那契对象。")
80
- commands.append(obj)
81
- else:
82
- commands[commands.index(previous)] = obj
83
- return result, deepcopy(obj)
@@ -1,185 +0,0 @@
1
- """Bounded, keyless Tencent HK/US daily history; no FTShare or A-share routes.
2
-
3
- Prices are vendor-adjusted; volumes remain historical session shares, including
4
- across splits. A day is anchored at 16:00 exchange time (not an execution tick).
5
- See docs/free-foreign-daily.md for the verified contract and coverage limits.
6
- """
7
- from __future__ import annotations
8
-
9
- from copy import deepcopy
10
- from datetime import datetime, timedelta
11
- import json
12
- import math
13
- import re
14
- import time
15
- from typing import Any
16
- from urllib.parse import urlencode
17
- from urllib.request import Request, urlopen
18
- from zoneinfo import ZoneInfo
19
-
20
- from tools.free_sources import _cache_get, _cache_set
21
-
22
- SOURCE_URL = "https://gu.qq.com/"
23
- _BASE = "https://web.ifzq.gtimg.cn/appstock/app/"
24
- _PAGE_SIZE = 640
25
- _MAX_PAGES = 8
26
- _MAX_BYTES = 2_000_000
27
- _TIMEOUT = 6
28
- _AGENT = "Mozilla/5.0 FT-KLine/0.6"
29
-
30
-
31
- def foreign_market(symbol: str) -> str | None:
32
- if re.fullmatch(r"\d{5}\.HK", symbol):
33
- return "HK"
34
- if re.fullmatch(r"[A-Z][A-Z0-9]*(?:[.-][A-Z0-9]+)*\.US", symbol) and len(symbol) <= 28:
35
- return "US"
36
- return None
37
-
38
-
39
- def _read(url: str, *, text: bool = False) -> Any:
40
- try:
41
- request = Request(url, headers={"User-Agent": _AGENT, "Referer": SOURCE_URL})
42
- with urlopen(request, timeout=_TIMEOUT) as response:
43
- raw = response.read(_MAX_BYTES + 1)
44
- if len(raw) > _MAX_BYTES:
45
- return None
46
- return raw.decode("gbk") if text else json.loads(raw.decode("utf-8"))
47
- except Exception: # Public fallback failure must not break the primary provider.
48
- return None
49
-
50
-
51
- def _us_code(root: str) -> str | None:
52
- key = ("tencent_us_identity", root)
53
- cached = _cache_get(key)
54
- if cached:
55
- return cached
56
- # The quote supplies only an identifier, never a URL or executable input.
57
- quote = _read("https://qt.gtimg.cn/q=" + "us" + root, text=True)
58
- if not isinstance(quote, str):
59
- return None
60
- lines = re.findall(r'v_us[A-Za-z0-9_.-]+="([^"\r\n]*)";', quote)
61
- if len(lines) != 1:
62
- return None
63
- fields = lines[0].split("~")
64
- identity = fields[2] if len(fields) > 2 else ""
65
- if identity not in {root + suffix for suffix in (".OQ", ".N", ".AM")}:
66
- return None
67
- code = "us" + identity
68
- _cache_set(key, code)
69
- return code
70
-
71
-
72
- def _parse_page(payload: Any, code: str, series: str, zone: ZoneInfo, now: datetime,
73
- allow_negative: bool) -> tuple[list[dict], str | None] | None:
74
- if not isinstance(payload, dict) or payload.get("code") != 0:
75
- return None
76
- data = payload.get("data")
77
- node = data.get(code) if isinstance(data, dict) else None
78
- bars = node.get(series) if isinstance(node, dict) else None
79
- if not isinstance(bars, list) or len(bars) > _PAGE_SIZE + 1:
80
- return None
81
- rows = []
82
- reason = None
83
- previous = ""
84
- for bar in bars:
85
- try:
86
- if not isinstance(bar, list) or len(bar) < 6:
87
- return None
88
- day = datetime.strptime(bar[0], "%Y-%m-%d")
89
- if day.strftime("%Y-%m-%d") != bar[0] or bar[0] <= previous:
90
- return None
91
- previous = bar[0]
92
- o, c, h, l, volume = map(float, bar[1:6])
93
- if not all(math.isfinite(x) for x in (o, c, h, l, volume)) or volume < 0:
94
- return None
95
- if l > min(o, c) or h < max(o, c) or l > h:
96
- return None
97
- if min(o, c, h, l) <= 0:
98
- if not allow_negative:
99
- return None
100
- # Cumulative cash adjustments can make early HK qfq negative.
101
- # Keep only the contiguous newer positive-price tail, never
102
- # delete an interior invalid row and silently bridge a gap.
103
- rows.clear()
104
- reason = "non_positive_adjusted_prices"
105
- continue
106
- close = day.replace(hour=16, tzinfo=zone)
107
- cutoff = close + (timedelta(minutes=15) if zone.key == "Asia/Hong_Kong" else timedelta())
108
- if cutoff > now:
109
- continue # Do not expose an unfinished daily candle as final.
110
- rows.append({"time": int(close.timestamp()), "open": o, "close": c,
111
- "high": h, "low": l, "volume": volume})
112
- except (TypeError, ValueError, OverflowError):
113
- return None
114
- return rows, reason
115
-
116
-
117
- def fetch_foreign_daily(symbol: str, *, limit: int = 220, adjust: str = "none") -> dict | None:
118
- market = foreign_market(symbol)
119
- if market is None or adjust not in {"none", "forward", "backward"}:
120
- return None
121
- if market == "US" and adjust == "backward":
122
- return None
123
- wanted = max(2, min(int(limit), 4000))
124
- key = ("tencent_foreign_daily", f"{symbol}:{wanted}:{adjust}")
125
- cached = _cache_get(key)
126
- if cached is not None:
127
- return deepcopy(cached)
128
- code = "hk" + symbol[:5] if market == "HK" else _us_code(symbol[:-3])
129
- if not code:
130
- return None
131
- mode, series = {"none": ("", "day"), "forward": ("qfq", "qfqday"),
132
- "backward": ("hfq", "hfqday")}[adjust]
133
- route = "kline/kline" if not mode else ("hkfqkline/get" if market == "HK" else "usfqkline/get")
134
- zone = ZoneInfo("Asia/Hong_Kong" if market == "HK" else "America/New_York")
135
- now = datetime.now(zone)
136
- end = ""
137
- collected: dict[int, dict] = {}
138
- reason = "page_limit"
139
- pages = 0
140
- for _ in range(_MAX_PAGES):
141
- # Each older page overlaps the preceding boundary. Verify that prices
142
- # and share counts use the same basis before joining the two pages.
143
- count = min(_PAGE_SIZE, max(3, wanted - len(collected) + 2))
144
- url = _BASE + route + "?" + urlencode({"param": f"{code},day,,{end},{count},{mode}"})
145
- parsed = _parse_page(_read(url), code, series, zone, now, adjust == "forward")
146
- pages += 1
147
- if parsed is None:
148
- reason = "source_unavailable_or_invalid"
149
- break
150
- rows, boundary = parsed
151
- if not rows:
152
- reason = boundary or "source_history_exhausted"
153
- break
154
- if end and datetime.fromtimestamp(rows[-1]["time"], zone).date().isoformat() > end:
155
- reason = "source_ignored_history_boundary"
156
- break
157
- if collected and min(collected) not in {row["time"] for row in rows}:
158
- reason = "missing_page_overlap"
159
- break
160
- if any(stamp in collected and collected[stamp] != row for stamp, row in ((r["time"], r) for r in rows)):
161
- reason = "inconsistent_page_basis"
162
- break
163
- oldest = min(collected) if collected else None
164
- if oldest is not None and rows[0]["time"] >= oldest:
165
- reason = "source_history_exhausted"
166
- break
167
- collected.update((row["time"], row) for row in rows)
168
- if len(collected) >= wanted:
169
- reason = "requested_count_reached"
170
- break
171
- if boundary:
172
- reason = boundary
173
- break
174
- end = datetime.fromtimestamp(rows[0]["time"], zone).date().isoformat()
175
- rows = sorted(collected.values(), key=lambda row: row["time"])[-wanted:]
176
- if len(rows) < 2:
177
- return None
178
- result = {"rows": rows, "history_complete": len(rows) >= wanted,
179
- "history_start": rows[0]["time"], "history_end": rows[-1]["time"],
180
- "coverage_reason": reason, "history_pages": pages,
181
- "volume_unit": "shares", "volume_adjustment": "historical_session_shares",
182
- "price_adjustment": adjust, "timestamp_convention": "session_date_at_16_local",
183
- "source_symbol": code, "exchange_timezone": zone.key}
184
- _cache_set(key, deepcopy(result))
185
- return result