@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.
- package/lib/client.js +9 -1
- package/package.json +2 -5
- package/src/client/index.js +8 -0
- package/node_modules/@ftshare-lab/dsh-kline/CHANGELOG.md +0 -564
- package/node_modules/@ftshare-lab/dsh-kline/LICENSE +0 -21
- package/node_modules/@ftshare-lab/dsh-kline/PROVENANCE.md +0 -13
- package/node_modules/@ftshare-lab/dsh-kline/README.en.md +0 -265
- package/node_modules/@ftshare-lab/dsh-kline/README.md +0 -281
- package/node_modules/@ftshare-lab/dsh-kline/chart_service.py +0 -686
- package/node_modules/@ftshare-lab/dsh-kline/config/basic-symbols.json +0 -570
- package/node_modules/@ftshare-lab/dsh-kline/config/dsh-kline.patch.yml +0 -4
- package/node_modules/@ftshare-lab/dsh-kline/config/dsh-tool-catalog.json +0 -3783
- package/node_modules/@ftshare-lab/dsh-kline/cordis.patch.yml +0 -33
- package/node_modules/@ftshare-lab/dsh-kline/core/__init__.py +0 -0
- package/node_modules/@ftshare-lab/dsh-kline/core/adjustment.py +0 -16
- package/node_modules/@ftshare-lab/dsh-kline/core/calc.py +0 -683
- package/node_modules/@ftshare-lab/dsh-kline/core/rows.py +0 -228
- package/node_modules/@ftshare-lab/dsh-kline/core/ta_engine.py +0 -99
- package/node_modules/@ftshare-lab/dsh-kline/lib/candle-sequence.js +0 -15
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-adjustment.js +0 -7
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-annotations.js +0 -33
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-applications.js +0 -171
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-context.js +0 -164
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-observation.js +0 -241
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-service-status.js +0 -82
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-source-status.js +0 -39
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-sources.js +0 -349
- package/node_modules/@ftshare-lab/dsh-kline/lib/client.js +0 -15445
- package/node_modules/@ftshare-lab/dsh-kline/lib/drawing-feedback.js +0 -252
- package/node_modules/@ftshare-lab/dsh-kline/lib/fibonacci.js +0 -18
- package/node_modules/@ftshare-lab/dsh-kline/lib/ftshare-settings-bridge.js +0 -159
- package/node_modules/@ftshare-lab/dsh-kline/lib/index.js +0 -279
- package/node_modules/@ftshare-lab/dsh-kline/lib/labeled-polyline.js +0 -17
- package/node_modules/@ftshare-lab/dsh-kline/lib/price-bands.js +0 -55
- package/node_modules/@ftshare-lab/dsh-kline/lib/price-series.js +0 -47
- package/node_modules/@ftshare-lab/dsh-kline/lib/price-sticks.js +0 -32
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/candle-sequence.d.ts +0 -2
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-adjustment.d.ts +0 -2
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-annotations.d.ts +0 -4
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-applications.d.ts +0 -26
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-context.d.ts +0 -14
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-observation.d.ts +0 -8
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-service-status.d.ts +0 -22
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-source-status.d.ts +0 -47
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-sources.d.ts +0 -25
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/BetterSidebarTab.d.ts +0 -12
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/ClassicShell.d.ts +0 -4
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/KlineContent.d.ts +0 -37
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/PaperKlinePanel.d.ts +0 -15
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/canvas-panel.d.ts +0 -33
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/chart-apply.d.ts +0 -13
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/chart-context.d.ts +0 -23
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/chart-session-resolver.d.ts +0 -2
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/client-context.d.ts +0 -14
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/conversation.d.ts +0 -39
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/default-tab.d.ts +0 -3
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/embed.d.ts +0 -37
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/generated-view.d.ts +0 -2
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/horizontal-lines.d.ts +0 -1
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/host-services.d.ts +0 -55
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/index.d.ts +0 -4
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/mode-preferences.d.ts +0 -13
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar-contract.d.ts +0 -52
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar-register.d.ts +0 -46
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar-services.d.ts +0 -45
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar.d.ts +0 -47
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/sidebar-integration.d.ts +0 -12
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/ui-onboarding.d.ts +0 -13
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/version.d.ts +0 -1
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/drawing-feedback.d.ts +0 -5
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/fibonacci.d.ts +0 -5
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/ftshare-settings-bridge.d.ts +0 -50
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/index.d.ts +0 -26
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/labeled-polyline.d.ts +0 -11
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/price-bands.d.ts +0 -3
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/price-series.d.ts +0 -5
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/price-sticks.d.ts +0 -3
- package/node_modules/@ftshare-lab/dsh-kline/package.json +0 -136
- package/node_modules/@ftshare-lab/dsh-kline/requirements.txt +0 -6
- package/node_modules/@ftshare-lab/dsh-kline/scripts/bootstrap.sh +0 -5
- package/node_modules/@ftshare-lab/dsh-kline/scripts/dsh-bootstrap.mjs +0 -179
- package/node_modules/@ftshare-lab/dsh-kline/scripts/dsh-mcp-plugin.mjs +0 -27
- package/node_modules/@ftshare-lab/dsh-kline/scripts/run-dsh-kline.mjs +0 -655
- package/node_modules/@ftshare-lab/dsh-kline/scripts/run-dsh-kline.sh +0 -5
- package/node_modules/@ftshare-lab/dsh-kline/server.py +0 -1734
- package/node_modules/@ftshare-lab/dsh-kline/tools/__init__.py +0 -0
- package/node_modules/@ftshare-lab/dsh-kline/tools/annotations.py +0 -119
- package/node_modules/@ftshare-lab/dsh-kline/tools/baostock_source.py +0 -176
- package/node_modules/@ftshare-lab/dsh-kline/tools/calc.py +0 -39
- package/node_modules/@ftshare-lab/dsh-kline/tools/channel_candidates.py +0 -260
- package/node_modules/@ftshare-lab/dsh-kline/tools/channel_preview.py +0 -82
- package/node_modules/@ftshare-lab/dsh-kline/tools/channels.py +0 -104
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_applications.py +0 -204
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_context.py +0 -186
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_edits.py +0 -345
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_functions.py +0 -466
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_indicators.py +0 -63
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_measurements.py +0 -84
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_source_status.py +0 -32
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_sources.py +0 -31
- package/node_modules/@ftshare-lab/dsh-kline/tools/draw.py +0 -394
- package/node_modules/@ftshare-lab/dsh-kline/tools/drawing_feedback.py +0 -45
- package/node_modules/@ftshare-lab/dsh-kline/tools/drawing_interaction.py +0 -117
- package/node_modules/@ftshare-lab/dsh-kline/tools/drawing_verification.py +0 -141
- package/node_modules/@ftshare-lab/dsh-kline/tools/fetch.py +0 -4681
- package/node_modules/@ftshare-lab/dsh-kline/tools/fibonacci.py +0 -83
- package/node_modules/@ftshare-lab/dsh-kline/tools/foreign_daily.py +0 -185
- package/node_modules/@ftshare-lab/dsh-kline/tools/free_sources.py +0 -483
- package/node_modules/@ftshare-lab/dsh-kline/tools/lines.py +0 -91
- package/node_modules/@ftshare-lab/dsh-kline/tools/pivots.py +0 -60
- package/node_modules/@ftshare-lab/dsh-kline/tools/polylines.py +0 -125
- package/node_modules/@ftshare-lab/dsh-kline/tools/price_bands.py +0 -165
- package/node_modules/@ftshare-lab/dsh-kline/tools/price_series.py +0 -162
- package/node_modules/@ftshare-lab/dsh-kline/tools/price_sticks.py +0 -114
- package/node_modules/@ftshare-lab/dsh-kline/tools/range_candidates.py +0 -170
- package/node_modules/@ftshare-lab/dsh-kline/tools/rectangles.py +0 -76
- package/node_modules/@ftshare-lab/dsh-kline/tools/regression_channels.py +0 -87
- package/node_modules/@ftshare-lab/dsh-kline/tools/ta_functions.py +0 -228
- package/node_modules/@ftshare-lab/dsh-kline/tools/trend_lines.py +0 -106
- package/node_modules/@ftshare-lab/dsh-kline/tools/watchlist.py +0 -149
- package/node_modules/@ftshare-lab/dsh-kline/view/ft-logo.jpg +0 -0
- package/node_modules/@ftshare-lab/dsh-kline/view/vendor/klinecharts.min.js +0 -7
|
@@ -1,483 +0,0 @@
|
|
|
1
|
-
"""Built-in free market-data fallback for dsh_kline.
|
|
2
|
-
|
|
3
|
-
FTShare is the primary, promoted provider. This module is a *fallback* that
|
|
4
|
-
keeps basic broad-market data visible when the current FTShare plan cannot
|
|
5
|
-
serve it (anonymous/free tier without HK/US/index entitlements).
|
|
6
|
-
|
|
7
|
-
Design rules (mirror docs/provider-adaptation.md):
|
|
8
|
-
- Small, explicit registries only. No runtime discovery; no remote data ever
|
|
9
|
-
adds a URL or executes code.
|
|
10
|
-
- Public, key-less HTTP endpoints only (Eastmoney daily K-lines and Tencent
|
|
11
|
-
JSON K-line/quote feeds). No scraping of HTML.
|
|
12
|
-
- Every row keeps the canonical OHLCV shape (close-time, unix seconds) and the
|
|
13
|
-
response carries ``source`` + ``source_url`` so callers can label the data as
|
|
14
|
-
free fallback instead of silently pretending it came from FTShare.
|
|
15
|
-
- Bounded requests, short in-process cache, silent degradation on failure:
|
|
16
|
-
a transient free-source error must never break the primary chart.
|
|
17
|
-
|
|
18
|
-
This module is provider-neutral at the row level and imports nothing from
|
|
19
|
-
tools.fetch (which imports this module for fallback wiring).
|
|
20
|
-
"""
|
|
21
|
-
|
|
22
|
-
from __future__ import annotations
|
|
23
|
-
|
|
24
|
-
import json
|
|
25
|
-
import math
|
|
26
|
-
import re
|
|
27
|
-
import threading
|
|
28
|
-
import time
|
|
29
|
-
import urllib.parse
|
|
30
|
-
import urllib.request
|
|
31
|
-
from datetime import datetime, timezone, timedelta
|
|
32
|
-
from typing import Any, Mapping
|
|
33
|
-
|
|
34
|
-
# ---------------------------------------------------------------------------
|
|
35
|
-
# Registries (small and explicit)
|
|
36
|
-
# ---------------------------------------------------------------------------
|
|
37
|
-
|
|
38
|
-
_CN_TZ = timezone(timedelta(hours=8))
|
|
39
|
-
_HK_TZ = timezone(timedelta(hours=8))
|
|
40
|
-
_US_TZ = timezone(timedelta(hours=-5)) # EST; used only for weekday calendar math
|
|
41
|
-
|
|
42
|
-
_HTTP_TIMEOUT_SECONDS = 8.0
|
|
43
|
-
_CACHE_TTL_SECONDS = 60.0
|
|
44
|
-
_CACHE_MAX_ENTRIES = 96
|
|
45
|
-
|
|
46
|
-
_USER_AGENT = (
|
|
47
|
-
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
|
|
48
|
-
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36"
|
|
49
|
-
)
|
|
50
|
-
|
|
51
|
-
# Eastmoney broad-market indices that the FTShare free/anonymous tier commonly
|
|
52
|
-
# cannot serve. key = dsh_kline canonical symbol, value = eastmoney secid.
|
|
53
|
-
EM_INDEX_SECIDS: dict[str, str] = {
|
|
54
|
-
"000001.XSHG": "1.000001", # 上证指数
|
|
55
|
-
"000016.XSHG": "1.000016", # 上证50
|
|
56
|
-
"000300.XSHG": "1.000300", # 沪深300
|
|
57
|
-
"000905.XSHG": "1.000905", # 中证500
|
|
58
|
-
"000906.XSHG": "1.000906", # 中证800
|
|
59
|
-
"000852.XSHG": "1.000852", # 中证1000
|
|
60
|
-
"399001.XSHE": "0.399001", # 深证成指
|
|
61
|
-
"399006.XSHE": "0.399006", # 创业板指
|
|
62
|
-
"100.HSI": "100.HSI", # 恒生指数
|
|
63
|
-
"100.NDX": "100.NDX", # 纳斯达克100
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
EM_INDEX_NAMES: dict[str, str] = {
|
|
67
|
-
"000001.XSHG": "上证指数",
|
|
68
|
-
"000016.XSHG": "上证50",
|
|
69
|
-
"000300.XSHG": "沪深300",
|
|
70
|
-
"000905.XSHG": "中证500",
|
|
71
|
-
"000906.XSHG": "中证800",
|
|
72
|
-
"000852.XSHG": "中证1000",
|
|
73
|
-
"399001.XSHE": "深证成指",
|
|
74
|
-
"399006.XSHE": "创业板指",
|
|
75
|
-
"100.HSI": "恒生指数",
|
|
76
|
-
"100.NDX": "纳斯达克100",
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
# Tencent quote codes for the real-time broad-market ticker strip.
|
|
80
|
-
# key = dsh_kline canonical symbol.
|
|
81
|
-
TENCENT_TICKER_SOURCES: dict[str, dict[str, str]] = {
|
|
82
|
-
"100.HSI": {"code": "hkHSI", "market": "HK", "name": "恒生指数", "timezone": "Asia/Hong_Kong", "open": "09:30", "close": "16:00"},
|
|
83
|
-
"100.NDX": {"code": "usNDX", "market": "US", "name": "纳斯达克100", "timezone": "America/New_York", "open": "09:30", "close": "16:00"},
|
|
84
|
-
"000001.XSHG": {"code": "s_sh000001", "market": "CN", "name": "上证指数", "timezone": "Asia/Shanghai", "open": "09:30", "close": "15:00"},
|
|
85
|
-
"000300.XSHG": {"code": "s_sh000300", "market": "CN", "name": "沪深300", "timezone": "Asia/Shanghai", "open": "09:30", "close": "15:00"},
|
|
86
|
-
"399001.XSHE": {"code": "s_sz399001", "market": "CN", "name": "深证成指", "timezone": "Asia/Shanghai", "open": "09:30", "close": "15:00"},
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
SOURCE_URL = "https://push2his.eastmoney.com"
|
|
90
|
-
TENCENT_SOURCE_URL = "https://qt.gtimg.cn"
|
|
91
|
-
SOURCE_LABEL = "东方财富免费行情"
|
|
92
|
-
TENCENT_LABEL = "腾讯免费行情"
|
|
93
|
-
|
|
94
|
-
_cache_lock = threading.Lock()
|
|
95
|
-
_cache: dict[tuple[str, str], tuple[float, Any]] = {}
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
def _cache_get(key: tuple[str, str]) -> Any | None:
|
|
99
|
-
with _cache_lock:
|
|
100
|
-
entry = _cache.get(key)
|
|
101
|
-
if entry is None:
|
|
102
|
-
return None
|
|
103
|
-
stamp, value = entry
|
|
104
|
-
if time.time() - stamp > _CACHE_TTL_SECONDS:
|
|
105
|
-
_cache.pop(key, None)
|
|
106
|
-
return None
|
|
107
|
-
return value
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
def _cache_set(key: tuple[str, str], value: Any) -> None:
|
|
111
|
-
with _cache_lock:
|
|
112
|
-
if len(_cache) >= _CACHE_MAX_ENTRIES:
|
|
113
|
-
oldest = min(_cache, key=lambda item: _cache[item][0])
|
|
114
|
-
_cache.pop(oldest, None)
|
|
115
|
-
_cache[key] = (time.time(), value)
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
def _http_get_json(url: str, *, referer: str | None = "https://quote.eastmoney.com/") -> Any | None:
|
|
119
|
-
headers = {"User-Agent": _USER_AGENT}
|
|
120
|
-
if referer:
|
|
121
|
-
headers["Referer"] = referer
|
|
122
|
-
request = urllib.request.Request(url, headers=headers)
|
|
123
|
-
try:
|
|
124
|
-
with urllib.request.urlopen(request, timeout=_HTTP_TIMEOUT_SECONDS) as response:
|
|
125
|
-
raw = response.read()
|
|
126
|
-
return json.loads(raw.decode("utf-8", errors="replace"))
|
|
127
|
-
except Exception: # noqa: BLE001 - fallback must degrade silently
|
|
128
|
-
return None
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
def _http_get_text(url: str) -> str | None:
|
|
132
|
-
request = urllib.request.Request(url, headers={"User-Agent": _USER_AGENT})
|
|
133
|
-
try:
|
|
134
|
-
with urllib.request.urlopen(request, timeout=_HTTP_TIMEOUT_SECONDS) as response:
|
|
135
|
-
return response.read().decode("gbk", errors="replace")
|
|
136
|
-
except Exception: # noqa: BLE001
|
|
137
|
-
return None
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
# ---------------------------------------------------------------------------
|
|
141
|
-
# Eastmoney daily K-line fallback (broad-market indices)
|
|
142
|
-
# ---------------------------------------------------------------------------
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
def _em_date_to_seconds(date_text: str, timezone_name: str = "Asia/Shanghai") -> int:
|
|
146
|
-
"""Parse YYYY-MM-DD into a close-time unix-second (day bars close same day)."""
|
|
147
|
-
try:
|
|
148
|
-
parsed = datetime.strptime(str(date_text)[:10], "%Y-%m-%d")
|
|
149
|
-
except (TypeError, ValueError):
|
|
150
|
-
return 0
|
|
151
|
-
if timezone_name == "Asia/Hong_Kong":
|
|
152
|
-
local = parsed.replace(tzinfo=_HK_TZ)
|
|
153
|
-
elif timezone_name == "America/New_York":
|
|
154
|
-
local = parsed.replace(hour=16, tzinfo=_US_TZ)
|
|
155
|
-
else:
|
|
156
|
-
local = parsed.replace(hour=15, tzinfo=_CN_TZ)
|
|
157
|
-
return int(local.timestamp())
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
def _parse_em_kline_payload(payload: Any, timezone_name: str) -> list[dict[str, Any]]:
|
|
161
|
-
"""Parse eastmoney push2his klines into canonical OHLCV rows."""
|
|
162
|
-
rows: list[dict[str, Any]] = []
|
|
163
|
-
try:
|
|
164
|
-
data = payload.get("data") or {}
|
|
165
|
-
klines = data.get("klines") or []
|
|
166
|
-
except AttributeError:
|
|
167
|
-
return rows
|
|
168
|
-
for line in klines:
|
|
169
|
-
parts = str(line).split(",")
|
|
170
|
-
if len(parts) < 6:
|
|
171
|
-
continue
|
|
172
|
-
# fields2=f51(date),f52(open),f53(close),f54(high),f55(low),f56(volume)
|
|
173
|
-
date_text, open_px, close_px, high_px, low_px = parts[:5]
|
|
174
|
-
volume = parts[5] if len(parts) > 5 else ""
|
|
175
|
-
timestamp = _em_date_to_seconds(date_text, timezone_name)
|
|
176
|
-
if not timestamp:
|
|
177
|
-
continue
|
|
178
|
-
try:
|
|
179
|
-
row = {
|
|
180
|
-
"time": timestamp,
|
|
181
|
-
"open": float(open_px),
|
|
182
|
-
"high": float(high_px),
|
|
183
|
-
"low": float(low_px),
|
|
184
|
-
"close": float(close_px),
|
|
185
|
-
"volume": float(volume) if str(volume).replace(".", "", 1).isdigit() else 0.0,
|
|
186
|
-
}
|
|
187
|
-
except (TypeError, ValueError):
|
|
188
|
-
continue
|
|
189
|
-
rows.append(row)
|
|
190
|
-
rows.sort(key=lambda item: int(item["time"]))
|
|
191
|
-
return rows
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
def fetch_em_index_daily(symbol: str, *, limit: int = 120) -> list[dict[str, Any]] | None:
|
|
195
|
-
"""Fetch broad-market index daily K-lines from Eastmoney.
|
|
196
|
-
|
|
197
|
-
Only symbols present in EM_INDEX_SECIDS are routed here. Returns canonical
|
|
198
|
-
rows (oldest → newest) or None when unavailable.
|
|
199
|
-
|
|
200
|
-
The upstream API is inconsistent across backend nodes about whether
|
|
201
|
-
``lmt`` counts from the beginning or the end of the requested range, so we
|
|
202
|
-
always request a *recent* window that comfortably covers ``limit`` bars and
|
|
203
|
-
slice the newest ones from the response.
|
|
204
|
-
"""
|
|
205
|
-
secid = EM_INDEX_SECIDS.get(str(symbol or "").strip().upper())
|
|
206
|
-
if not secid:
|
|
207
|
-
return None
|
|
208
|
-
wanted = max(2, min(int(limit), 4000))
|
|
209
|
-
cache_key = ("em_index_daily", f"{secid}:{wanted}")
|
|
210
|
-
cached = _cache_get(cache_key)
|
|
211
|
-
if cached is not None:
|
|
212
|
-
return cached
|
|
213
|
-
# ~365 calendar days per year; daily bars ≈ 244/year. A factor of 2 gives
|
|
214
|
-
# headroom for weekends/holidays without bloating the response.
|
|
215
|
-
calendar_days = max(30, int(wanted * 1.7))
|
|
216
|
-
beg_date = (datetime.now(_CN_TZ) - timedelta(days=calendar_days)).strftime("%Y%m%d")
|
|
217
|
-
query = urllib.parse.urlencode(
|
|
218
|
-
{
|
|
219
|
-
"secid": secid,
|
|
220
|
-
"fields1": "f1,f2,f3,f4,f5,f6",
|
|
221
|
-
"fields2": "f51,f52,f53,f54,f55,f56,f57",
|
|
222
|
-
"klt": "101",
|
|
223
|
-
"fqt": "0",
|
|
224
|
-
"beg": beg_date,
|
|
225
|
-
"end": "20500101",
|
|
226
|
-
"lmt": str(wanted * 3),
|
|
227
|
-
}
|
|
228
|
-
)
|
|
229
|
-
url = f"{SOURCE_URL}/api/qt/stock/kline/get?{query}"
|
|
230
|
-
payload = _http_get_json(url)
|
|
231
|
-
rows = _parse_em_kline_payload(payload, "Asia/Shanghai")
|
|
232
|
-
if len(rows) < 2:
|
|
233
|
-
return None
|
|
234
|
-
result = rows[-wanted:]
|
|
235
|
-
_cache_set(cache_key, result)
|
|
236
|
-
return result
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
def em_symbol_supported(symbol: str) -> bool:
|
|
240
|
-
return str(symbol or "").strip().upper() in EM_INDEX_SECIDS
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
# Tencent historical K-lines. The explicit index registry stays narrow, while
|
|
244
|
-
# A-share stocks are accepted only when the caller supplied a fully qualified
|
|
245
|
-
# Shanghai/Shenzhen equity identity (see ``_tencent_stock_code`` below).
|
|
246
|
-
# Tencent's bar array is [date, open, close, high, low, volume].
|
|
247
|
-
_TENCENT_KLINE_CODES: dict[str, str] = {
|
|
248
|
-
"100.HSI": "hkHSI",
|
|
249
|
-
"100.NDX": "usNDX",
|
|
250
|
-
"000001.XSHG": "sh000001",
|
|
251
|
-
"000016.XSHG": "sh000016",
|
|
252
|
-
"000300.XSHG": "sh000300",
|
|
253
|
-
"000905.XSHG": "sh000905",
|
|
254
|
-
"000906.XSHG": "sh000906",
|
|
255
|
-
"000852.XSHG": "sh000852",
|
|
256
|
-
"399001.XSHE": "sz399001",
|
|
257
|
-
"399006.XSHE": "sz399006",
|
|
258
|
-
}
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
def _parse_tencent_kline_payload(payload: Any, timezone_name: str, series: str | tuple[str, ...]) -> list[dict[str, Any]]:
|
|
262
|
-
"""Parse one of the explicitly requested Tencent K-line series names."""
|
|
263
|
-
rows: list[dict[str, Any]] = []
|
|
264
|
-
try:
|
|
265
|
-
data = payload.get("data") or {}
|
|
266
|
-
except AttributeError:
|
|
267
|
-
return rows
|
|
268
|
-
names = (series,) if isinstance(series, str) else series
|
|
269
|
-
for _code, node in data.items():
|
|
270
|
-
# node: {"day"|"qfqday"|"hfqday": [[date, open, close, high, low, volume], ...]}
|
|
271
|
-
bars = next((node.get(name) for name in names if isinstance(node, Mapping) and isinstance(node.get(name), list)), None)
|
|
272
|
-
if not isinstance(bars, list):
|
|
273
|
-
continue
|
|
274
|
-
for bar in bars:
|
|
275
|
-
if not isinstance(bar, (list, tuple)) or len(bar) < 6:
|
|
276
|
-
continue
|
|
277
|
-
date_text, open_px, close_px, high_px, low_px, volume = bar[:6]
|
|
278
|
-
timestamp = _em_date_to_seconds(str(date_text), timezone_name)
|
|
279
|
-
if not timestamp:
|
|
280
|
-
continue
|
|
281
|
-
try:
|
|
282
|
-
opened, high, low, closed = map(float, (open_px, high_px, low_px, close_px))
|
|
283
|
-
traded = float(volume)
|
|
284
|
-
except (TypeError, ValueError):
|
|
285
|
-
continue
|
|
286
|
-
if (
|
|
287
|
-
not all(math.isfinite(value) for value in (opened, high, low, closed, traded))
|
|
288
|
-
or min(opened, high, low, closed) <= 0 or traded < 0
|
|
289
|
-
or high < max(opened, low, closed) or low > min(opened, high, closed)
|
|
290
|
-
):
|
|
291
|
-
continue
|
|
292
|
-
rows.append({"time": timestamp, "open": opened, "high": high, "low": low,
|
|
293
|
-
"close": closed, "volume": traded})
|
|
294
|
-
rows.sort(key=lambda item: int(item["time"]))
|
|
295
|
-
return rows
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
def fetch_tencent_index_daily(symbol: str, *, limit: int = 120) -> list[dict[str, Any]] | None:
|
|
299
|
-
"""Fetch broad-market index daily K-lines from Tencent (fallback feed).
|
|
300
|
-
|
|
301
|
-
Mirrors ``fetch_em_index_daily`` in behavior and return shape. Returns
|
|
302
|
-
canonical rows (oldest → newest) or None when unavailable.
|
|
303
|
-
"""
|
|
304
|
-
canonical = str(symbol or "").strip().upper()
|
|
305
|
-
code = _TENCENT_KLINE_CODES.get(canonical)
|
|
306
|
-
if not code:
|
|
307
|
-
return None
|
|
308
|
-
wanted = max(2, min(int(limit), 4000))
|
|
309
|
-
cache_key = ("tencent_index_daily", f"{code}:{wanted}")
|
|
310
|
-
cached = _cache_get(cache_key)
|
|
311
|
-
if cached is not None:
|
|
312
|
-
return cached
|
|
313
|
-
# Tencent returns the requested number of bars counting backwards from today.
|
|
314
|
-
url = f"https://web.ifzq.gtimg.cn/appstock/app/fqkline/get?param={code},day,,,{wanted},qfq"
|
|
315
|
-
payload = _http_get_json(url, referer=None)
|
|
316
|
-
timezone_name = "Asia/Hong_Kong" if canonical == "100.HSI" else "America/New_York" if canonical == "100.NDX" else "Asia/Shanghai"
|
|
317
|
-
# Tencent returns qfqday for some indices and unadjusted day for others;
|
|
318
|
-
# index corporate-action adjustment is not applicable, so either verified
|
|
319
|
-
# series is acceptable here. Stock calls below remain exact by adjustment.
|
|
320
|
-
rows = _parse_tencent_kline_payload(payload, timezone_name, ("qfqday", "day"))
|
|
321
|
-
if len(rows) < 2:
|
|
322
|
-
return None
|
|
323
|
-
result = rows[-wanted:]
|
|
324
|
-
_cache_set(cache_key, result)
|
|
325
|
-
return result
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
_TENCENT_STOCK_SYMBOL = re.compile(r"(\d{6})\.(XSHG|XSHE)$")
|
|
329
|
-
_TENCENT_STOCK_PREFIXES = {
|
|
330
|
-
"XSHG": ("600", "601", "603", "605", "688", "689"),
|
|
331
|
-
"XSHE": ("000", "001", "002", "003", "300", "301", "302"),
|
|
332
|
-
}
|
|
333
|
-
_TENCENT_ADJUSTMENT_SERIES = {
|
|
334
|
-
"none": ("", "day"),
|
|
335
|
-
"forward": ("qfq", "qfqday"),
|
|
336
|
-
"backward": ("hfq", "hfqday"),
|
|
337
|
-
}
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
def _tencent_stock_code(symbol: str) -> str | None:
|
|
341
|
-
"""Map only explicit, supported A-share equities to Tencent's code form."""
|
|
342
|
-
match = _TENCENT_STOCK_SYMBOL.fullmatch(str(symbol or "").strip().upper())
|
|
343
|
-
if not match:
|
|
344
|
-
return None
|
|
345
|
-
code, market = match.groups()
|
|
346
|
-
if not code.startswith(_TENCENT_STOCK_PREFIXES[market]):
|
|
347
|
-
return None
|
|
348
|
-
return ("sh" if market == "XSHG" else "sz") + code
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
def fetch_tencent_stock_daily(symbol: str, *, limit: int = 120, adjust: str = "none") -> list[dict[str, Any]] | None:
|
|
352
|
-
"""Fetch qualified沪深 A-share daily K-lines from Tencent's public JSON feed.
|
|
353
|
-
|
|
354
|
-
This is a bounded second fallback after BaoStock. It supports only daily
|
|
355
|
-
source bars and preserves the caller's explicit adjustment selection; the
|
|
356
|
-
higher-level provider aggregates week/month/quarter/year intervals locally.
|
|
357
|
-
"""
|
|
358
|
-
code = _tencent_stock_code(symbol)
|
|
359
|
-
adjustment = _TENCENT_ADJUSTMENT_SERIES.get(str(adjust or "").strip().lower())
|
|
360
|
-
if not code or adjustment is None:
|
|
361
|
-
return None
|
|
362
|
-
mode, series = adjustment
|
|
363
|
-
wanted = max(2, min(int(limit), 4000))
|
|
364
|
-
cache_key = ("tencent_stock_daily", f"{code}:{wanted}:{mode or 'none'}")
|
|
365
|
-
cached = _cache_get(cache_key)
|
|
366
|
-
if cached is not None:
|
|
367
|
-
return cached
|
|
368
|
-
# An empty mode deliberately leaves the final comma: Tencent then returns
|
|
369
|
-
# the unadjusted ``day`` series instead of a default qfq series.
|
|
370
|
-
url = f"https://web.ifzq.gtimg.cn/appstock/app/fqkline/get?param={code},day,,,{wanted},{mode}"
|
|
371
|
-
payload = _http_get_json(url, referer=None)
|
|
372
|
-
rows = _parse_tencent_kline_payload(payload, "Asia/Shanghai", series)
|
|
373
|
-
if len(rows) < 2:
|
|
374
|
-
return None
|
|
375
|
-
result = rows[-wanted:]
|
|
376
|
-
_cache_set(cache_key, result)
|
|
377
|
-
return result
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
# ---------------------------------------------------------------------------
|
|
381
|
-
# Tencent real-time quote ticker
|
|
382
|
-
# ---------------------------------------------------------------------------
|
|
383
|
-
|
|
384
|
-
_TENCENT_FIELD_COUNT_MIN = 6
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
def _parse_tencent_index(code: str, market: str, text: str) -> dict[str, Any] | None:
|
|
388
|
-
"""Parse qt.gtimg response for the configured index quote codes.
|
|
389
|
-
|
|
390
|
-
Field layouts differ by market family (verified live):
|
|
391
|
-
- CN index (s_sh000001 …): name/code/close/change/change_pct at idx1..5.
|
|
392
|
-
- HK index (hkHSI): close at idx3, prev close at idx4, tail carries change.
|
|
393
|
-
- US index (usNDX): close at idx3, prev close at idx4.
|
|
394
|
-
We compute change from prev close when present, else trust the given amount.
|
|
395
|
-
"""
|
|
396
|
-
if not text:
|
|
397
|
-
return None
|
|
398
|
-
match = re.search(r'="([^"]+)"', text)
|
|
399
|
-
if not match:
|
|
400
|
-
return None
|
|
401
|
-
fields = match.group(1).split("~")
|
|
402
|
-
if len(fields) < _TENCENT_FIELD_COUNT_MIN:
|
|
403
|
-
return None
|
|
404
|
-
try:
|
|
405
|
-
close = float(fields[3])
|
|
406
|
-
except (TypeError, ValueError, IndexError):
|
|
407
|
-
return None
|
|
408
|
-
if close <= 0:
|
|
409
|
-
return None
|
|
410
|
-
name = fields[1] if len(fields) > 1 and fields[1] else code
|
|
411
|
-
if market == "CN":
|
|
412
|
-
# CN: idx4 = change amount, idx5 = change_pct; prev close is derived.
|
|
413
|
-
try:
|
|
414
|
-
change = float(fields[4])
|
|
415
|
-
change_pct = float(fields[5])
|
|
416
|
-
except (TypeError, ValueError, IndexError):
|
|
417
|
-
return None
|
|
418
|
-
previous = close - change if change else close
|
|
419
|
-
else:
|
|
420
|
-
# HK/US: idx4 = previous close; change is derived.
|
|
421
|
-
try:
|
|
422
|
-
previous = float(fields[4])
|
|
423
|
-
except (TypeError, ValueError, IndexError):
|
|
424
|
-
return None
|
|
425
|
-
if previous <= 0:
|
|
426
|
-
return None
|
|
427
|
-
change = close - previous
|
|
428
|
-
change_pct = change / previous * 100.0
|
|
429
|
-
return {
|
|
430
|
-
"market": market,
|
|
431
|
-
"symbol": code,
|
|
432
|
-
"name": name,
|
|
433
|
-
"close": round(close, 3),
|
|
434
|
-
"change": round(change, 3),
|
|
435
|
-
"change_pct": round(change_pct, 3),
|
|
436
|
-
"time": int(time.time()),
|
|
437
|
-
}
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
def fetch_tencent_ticker_items() -> list[dict[str, Any]]:
|
|
441
|
-
"""Fetch real-time broad-index quotes for the bottom market strip.
|
|
442
|
-
|
|
443
|
-
Returns the same item shape the FTShare ticker path uses, so the view
|
|
444
|
-
renders identically. Empty list when the source is unreachable.
|
|
445
|
-
"""
|
|
446
|
-
cache_key = ("tencent_ticker", "all")
|
|
447
|
-
cached = _cache_get(cache_key)
|
|
448
|
-
if cached is not None:
|
|
449
|
-
return cached
|
|
450
|
-
items: list[dict[str, Any]] = []
|
|
451
|
-
for symbol, source in TENCENT_TICKER_SOURCES.items():
|
|
452
|
-
url = f"{TENCENT_SOURCE_URL}/q={source['code']}"
|
|
453
|
-
text = _http_get_text(url)
|
|
454
|
-
item = _parse_tencent_index(source["code"], source["market"], text or "")
|
|
455
|
-
if item is not None:
|
|
456
|
-
item["symbol"] = symbol # canonical dsh_kline symbol for click-through
|
|
457
|
-
item["name"] = source["name"]
|
|
458
|
-
# Carry session metadata so the caller can label delayed/closed
|
|
459
|
-
# without owning the market-hours table.
|
|
460
|
-
item["session_timezone"] = source.get("timezone", "Asia/Shanghai")
|
|
461
|
-
item["session_open"] = source.get("open", "09:30")
|
|
462
|
-
item["session_close"] = source.get("close", "15:00")
|
|
463
|
-
items.append(item)
|
|
464
|
-
_cache_set(cache_key, items)
|
|
465
|
-
return items
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
def tencent_symbols() -> list[str]:
|
|
469
|
-
return list(TENCENT_TICKER_SOURCES.keys())
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
def free_source_status() -> dict[str, Any]:
|
|
473
|
-
"""Safe capability summary for the built-in free feeds (no keys/secrets)."""
|
|
474
|
-
return {
|
|
475
|
-
"available": True,
|
|
476
|
-
"source": "builtin_free",
|
|
477
|
-
"label": "内置免费行情(东财 / 腾讯)",
|
|
478
|
-
"index_kline_symbols": sorted(EM_INDEX_NAMES.keys()),
|
|
479
|
-
"index_kline_count": len(EM_INDEX_NAMES),
|
|
480
|
-
"ticker_symbols": tencent_symbols(),
|
|
481
|
-
"ticker_count": len(tencent_symbols()),
|
|
482
|
-
"note": "仅供免费基础体验,行情可能延迟,请勿用于交易决策。正式/实时数据请使用 FTShare。",
|
|
483
|
-
}
|
|
@@ -1,91 +0,0 @@
|
|
|
1
|
-
"""Explicit, snapshot-scoped horizontal lines; no market fetches or auto levels."""
|
|
2
|
-
from __future__ import annotations
|
|
3
|
-
|
|
4
|
-
from copy import deepcopy
|
|
5
|
-
import hashlib
|
|
6
|
-
import math
|
|
7
|
-
import secrets
|
|
8
|
-
from typing import Any, Literal
|
|
9
|
-
|
|
10
|
-
LINE_COMMAND = "DRAW_HORIZONTAL_LINE"
|
|
11
|
-
MAX_LINES = 60
|
|
12
|
-
COLORS = {"info", "success", "warning", "danger"}
|
|
13
|
-
COLOR_ALIASES = {"blue": "info", "蓝色": "info", "green": "success", "绿色": "success",
|
|
14
|
-
"orange": "warning", "橙色": "warning", "red": "danger", "红色": "danger"}
|
|
15
|
-
ColorInput = Literal["info", "success", "warning", "danger", "blue", "green", "orange", "red", "蓝色", "绿色", "橙色", "红色"]
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
class LineError(ValueError):
|
|
19
|
-
def __init__(self, code: str, message: str) -> None:
|
|
20
|
-
super().__init__(message)
|
|
21
|
-
self.code = code
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
def horizontal_lines(payload: dict[str, Any]) -> list[dict[str, Any]]:
|
|
25
|
-
return deepcopy([c for c in payload.get("chartCommands", []) if c.get("type") == LINE_COMMAND])
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
def validate_line_fields(*, price: float | None = None, name: str | None = None,
|
|
29
|
-
color: str | None = None, request_id: str | None = None) -> tuple[float | None, str | None, str | None]:
|
|
30
|
-
"""Shared field validation; normalize colors without creating throwaway drawings."""
|
|
31
|
-
if price is not None:
|
|
32
|
-
if isinstance(price, bool) or not isinstance(price, (int, float)) or not math.isfinite(price) or price <= 0:
|
|
33
|
-
raise LineError("invalid_price", "价格必须是大于零的有限数值。")
|
|
34
|
-
if name is not None:
|
|
35
|
-
if not isinstance(name, str) or len(name.strip()) > 48 or any(ord(c) < 32 for c in name):
|
|
36
|
-
raise LineError("invalid_name", "名称最多 48 个字符,不能包含控制字符。")
|
|
37
|
-
name = name.strip()
|
|
38
|
-
if color is not None:
|
|
39
|
-
if not isinstance(color, str):
|
|
40
|
-
raise LineError("invalid_color", "颜色必须为支持的颜色名称。")
|
|
41
|
-
color = COLOR_ALIASES.get(color.strip().lower(), color.strip().lower())
|
|
42
|
-
if color not in COLORS:
|
|
43
|
-
raise LineError("invalid_color", "颜色请选择蓝色/info、绿色/success、橙色/warning 或红色/danger。")
|
|
44
|
-
if request_id is not None and (not isinstance(request_id, str) or not 1 <= len(request_id) <= 128):
|
|
45
|
-
raise LineError("invalid_request_id", "request_id 必须是 1 至 128 个字符。")
|
|
46
|
-
return float(price) if price is not None else None, name, color
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
def edit_horizontal_line(
|
|
50
|
-
payload: dict[str, Any], action: str, *, line_id: str | None = None,
|
|
51
|
-
price: float | None = None, name: str | None = None,
|
|
52
|
-
color: str | None = None, request_id: str | None = None,
|
|
53
|
-
) -> tuple[dict[str, Any], dict[str, Any]]:
|
|
54
|
-
"""Return a copy; failed validation never mutates the source chart."""
|
|
55
|
-
price, name, color = validate_line_fields(price=price, name=name, color=color, request_id=request_id)
|
|
56
|
-
result = deepcopy(payload)
|
|
57
|
-
commands = result.get("chartCommands", [])
|
|
58
|
-
if action == "create":
|
|
59
|
-
if price is None:
|
|
60
|
-
raise LineError("invalid_price", "创建水平线需要指定价格。")
|
|
61
|
-
line = {"type": LINE_COMMAND, "id": "line_" + secrets.token_hex(12),
|
|
62
|
-
"price": float(price), "label": name or "", "color": color or "info"}
|
|
63
|
-
if request_id:
|
|
64
|
-
line["create_request_id"] = request_id
|
|
65
|
-
# Retrying against the same snapshot also keeps a stable line ID.
|
|
66
|
-
line["id"] = "line_" + hashlib.sha256(request_id.encode()).hexdigest()[:24]
|
|
67
|
-
previous = next((c for c in commands if c.get("type") == LINE_COMMAND
|
|
68
|
-
and c.get("create_request_id") == request_id), None)
|
|
69
|
-
if previous:
|
|
70
|
-
if any(previous.get(k) != line[k] for k in ("price", "label", "color")):
|
|
71
|
-
raise LineError("request_conflict", "同一 request_id 的绘图参数不同,请使用新的 request_id。")
|
|
72
|
-
return result, deepcopy(previous)
|
|
73
|
-
if len(horizontal_lines(result)) >= MAX_LINES:
|
|
74
|
-
raise LineError("too_many_lines", "当前图表最多保存 60 条 AI 水平线。")
|
|
75
|
-
commands.append(line)
|
|
76
|
-
elif action in {"update", "delete"}:
|
|
77
|
-
line = next((c for c in commands if c.get("type") == LINE_COMMAND and c.get("id") == line_id), None)
|
|
78
|
-
if line is None:
|
|
79
|
-
raise LineError("line_not_found", "当前图表不存在该水平线,请先读取当前图表中的水平线 ID。")
|
|
80
|
-
if action == "delete":
|
|
81
|
-
commands.remove(line)
|
|
82
|
-
else:
|
|
83
|
-
if price is None and name is None and color is None:
|
|
84
|
-
raise LineError("empty_update", "请至少指定价格、名称或颜色中的一项。")
|
|
85
|
-
if price is not None: line["price"] = float(price)
|
|
86
|
-
if name is not None: line["label"] = name
|
|
87
|
-
if color is not None: line["color"] = color
|
|
88
|
-
else:
|
|
89
|
-
raise LineError("invalid_action", "不支持的水平线操作。")
|
|
90
|
-
result["chartCommands"] = commands
|
|
91
|
-
return result, deepcopy(line)
|
|
@@ -1,60 +0,0 @@
|
|
|
1
|
-
"""Deterministic, confirmed local-extremum candidates on loaded candles."""
|
|
2
|
-
from __future__ import annotations
|
|
3
|
-
|
|
4
|
-
import math
|
|
5
|
-
|
|
6
|
-
from core.rows import RowsValidationError, validate_rows
|
|
7
|
-
from tools.lines import LineError
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
def confirmed_pivots(rows, *, left_bars=2, right_bars=2, mode="both", limit=20):
|
|
11
|
-
"""Return strict local highs/lows with complete left and right windows.
|
|
12
|
-
|
|
13
|
-
Equal highs/lows are deliberately not pivots. Only bars with all right-side
|
|
14
|
-
confirmation bars present are considered. Results are chronological, limited
|
|
15
|
-
to the newest ``limit`` candidates, with no alternation or trend inference.
|
|
16
|
-
"""
|
|
17
|
-
if type(left_bars) is not int or not 1 <= left_bars <= 20:
|
|
18
|
-
raise LineError("invalid_pivot_window", "left_bars 必须是1至20的整数。")
|
|
19
|
-
if type(right_bars) is not int or not 1 <= right_bars <= 20:
|
|
20
|
-
raise LineError("invalid_pivot_window", "right_bars 必须是1至20的整数。")
|
|
21
|
-
if mode not in {"high", "low", "both"}:
|
|
22
|
-
raise LineError("invalid_pivot_mode", "mode 只能是 high、low 或 both。")
|
|
23
|
-
if type(limit) is not int or not 1 <= limit <= 50:
|
|
24
|
-
raise LineError("invalid_pivot_limit", "limit 必须是1至50的整数。")
|
|
25
|
-
try:
|
|
26
|
-
candles = validate_rows(rows, min_len=left_bars + right_bars + 1)
|
|
27
|
-
except RowsValidationError:
|
|
28
|
-
raise LineError("insufficient_pivot_history", "已加载K线不足以提供完整左右确认窗口;未补取行情。") from None
|
|
29
|
-
|
|
30
|
-
candidates = []
|
|
31
|
-
for index in range(left_bars, len(candles) - right_bars):
|
|
32
|
-
row = candles[index]
|
|
33
|
-
left = candles[index - left_bars:index]
|
|
34
|
-
right = candles[index + 1:index + right_bars + 1]
|
|
35
|
-
high = float(row["high"])
|
|
36
|
-
low = float(row["low"])
|
|
37
|
-
if not math.isfinite(high) or not math.isfinite(low):
|
|
38
|
-
raise LineError("invalid_pivot_data", "K线高低价必须是有限数值。")
|
|
39
|
-
neighbors = left + right
|
|
40
|
-
if mode in {"high", "both"} and all(high > float(item["high"]) for item in neighbors):
|
|
41
|
-
candidates.append({"side": "high", "time": str(row["time"]), "price": high,
|
|
42
|
-
"bars_ago": len(candles) - 1 - index})
|
|
43
|
-
if mode in {"low", "both"} and all(low < float(item["low"]) for item in neighbors):
|
|
44
|
-
candidates.append({"side": "low", "time": str(row["time"]), "price": low,
|
|
45
|
-
"bars_ago": len(candles) - 1 - index})
|
|
46
|
-
|
|
47
|
-
selected = candidates[-limit:]
|
|
48
|
-
return {
|
|
49
|
-
"left_bars": left_bars,
|
|
50
|
-
"right_bars": right_bars,
|
|
51
|
-
"mode": mode,
|
|
52
|
-
"limit": limit,
|
|
53
|
-
"candidates": selected,
|
|
54
|
-
"candidate_count": len(selected),
|
|
55
|
-
"total_candidates": len(candidates),
|
|
56
|
-
"truncated": len(selected) < len(candidates),
|
|
57
|
-
"rule": "strict_local_extremum",
|
|
58
|
-
"tie_policy": "equal_neighbor_is_not_a_pivot",
|
|
59
|
-
"confirmation": "complete_right_window_only",
|
|
60
|
-
}
|