@mzzsfy/dsh-stock-assistant 0.9.0 → 0.10.0
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/CHANGELOG.md +85 -4
- package/README.md +16 -12
- package/package.json +1 -1
- package/src/application.mjs +185 -72
- package/src/catalog.mjs +51 -40
- package/src/client.js +604 -208
- package/src/collector.mjs +169 -91
- package/src/executor.mjs +97 -20
- package/src/index.js +5 -3
- package/src/market-model.mjs +35 -8
- package/src/memory-cache.mjs +5 -1
- package/src/provider-router.mjs +9 -3
- package/src/providers/eastmoney.mjs +9 -3
- package/src/providers/sina.mjs +2 -2
- package/src/providers/tencent.mjs +14 -1
- package/src/providers/tushare.mjs +11 -2
- package/src/providers/xueqiu.mjs +9 -7
- package/src/routes.mjs +11 -1
- package/src/schemas.mjs +12 -17
- package/src/state.mjs +17 -2
- package/src/trend-cache.mjs +96 -11
- package/src/us-symbols.mjs +30 -0
- package//345/205/274/345/256/271/346/200/247/346/265/213/350/257/225.md +215 -13
package/src/market-model.mjs
CHANGED
|
@@ -31,6 +31,26 @@ function zonedParts(timeZone, nowMs) {
|
|
|
31
31
|
}
|
|
32
32
|
// 市场本地日期: 日历记录、休市判断都按证券所属市场的自然日, 不能统一用北京时间
|
|
33
33
|
export const marketDate = (exchange, nowMs) => MARKET_META[exchange] ? zonedParts(MARKET_META[exchange].timezone, nowMs).date : new Date(nowMs).toISOString().slice(0, 10)
|
|
34
|
+
// 报价时刻是否已过该市场当日收盘: 只有收盘后的成交才算当日收盘价
|
|
35
|
+
export const isAfterMarketClose = (exchange, ms) => {
|
|
36
|
+
const meta = MARKET_META[exchange]
|
|
37
|
+
return !!meta?.sessions?.length && zonedParts(meta.timezone, ms).minutes >= toMinutes(meta.sessions.at(-1)[1])
|
|
38
|
+
}
|
|
39
|
+
// 最近一个已收盘交易日的市场本地日期: 闭市报价只有属于这一天(或今天已收盘)才算最新收盘
|
|
40
|
+
function lastCloseDateOf(meta, local, calendarDays) {
|
|
41
|
+
const close = toMinutes(meta.sessions.at(-1)[1])
|
|
42
|
+
const declared = calendarDays?.get(local.date)
|
|
43
|
+
const tradingDay = declared !== false && !(declared === undefined && WEEKEND.has(local.weekday))
|
|
44
|
+
if (tradingDay && local.minutes >= close) return local.date
|
|
45
|
+
for (let offset = 1; offset <= 60; offset++) {
|
|
46
|
+
const date = addDays(local.date, -offset)
|
|
47
|
+
const open = calendarDays?.get(date)
|
|
48
|
+
if (open === false) continue
|
|
49
|
+
if (open === undefined && isWeekend(date)) continue
|
|
50
|
+
return date
|
|
51
|
+
}
|
|
52
|
+
return local.date
|
|
53
|
+
}
|
|
34
54
|
// 某一时区的时钟文本: 分时横轴用来源时区(东财/腾讯统一按北京时间), 与在线返回的 time 同一基准
|
|
35
55
|
export const clockInZone = (timeZone, unixSeconds) => {
|
|
36
56
|
const minutes = zonedParts(timeZone, unixSeconds * 1000).minutes
|
|
@@ -90,22 +110,23 @@ export function marketStateOf(exchange, nowMs, calendarDays = null) {
|
|
|
90
110
|
const meta = MARKET_META[exchange]
|
|
91
111
|
if (!meta?.sessions?.length) return { state: 'unknown' }
|
|
92
112
|
const local = zonedParts(meta.timezone, nowMs)
|
|
113
|
+
const lastCloseDate = lastCloseDateOf(meta, local, calendarDays)
|
|
93
114
|
const dayOpen = calendarDays?.get(local.date)
|
|
94
|
-
if (dayOpen === false) return { state: 'closed', nextAt: nextOpenAt(meta, local.date, calendarDays) }
|
|
95
|
-
if (dayOpen === undefined && WEEKEND.has(local.weekday)) return { state: 'closed', nextAt: nextOpenAt(meta, local.date, calendarDays) }
|
|
115
|
+
if (dayOpen === false) return { state: 'closed', nextAt: nextOpenAt(meta, local.date, calendarDays), lastCloseDate }
|
|
116
|
+
if (dayOpen === undefined && WEEKEND.has(local.weekday)) return { state: 'closed', nextAt: nextOpenAt(meta, local.date, calendarDays), lastCloseDate }
|
|
96
117
|
const minutes = local.minutes
|
|
97
118
|
if (meta.auction) {
|
|
98
119
|
const [auctionFrom, auctionTo] = meta.auction.map(toMinutes)
|
|
99
|
-
if (minutes < auctionFrom) return { state: 'preopen', nextAt: epochOf(meta.timezone, local.date, auctionFrom) }
|
|
100
|
-
if (minutes < auctionTo) return { state: 'auction' }
|
|
120
|
+
if (minutes < auctionFrom) return { state: 'preopen', nextAt: epochOf(meta.timezone, local.date, auctionFrom), lastCloseDate }
|
|
121
|
+
if (minutes < auctionTo) return { state: 'auction', lastCloseDate }
|
|
101
122
|
}
|
|
102
123
|
const bounds = meta.sessions.map(([from, to]) => [toMinutes(from), toMinutes(to)])
|
|
103
|
-
if (minutes < bounds[0][0]) return { state: 'preopen', nextAt: epochOf(meta.timezone, local.date, bounds[0][0]) }
|
|
104
|
-
if (bounds.some(([from, to]) => minutes >= from && minutes < to)) return { state: 'trading' }
|
|
124
|
+
if (minutes < bounds[0][0]) return { state: 'preopen', nextAt: epochOf(meta.timezone, local.date, bounds[0][0]), lastCloseDate }
|
|
125
|
+
if (bounds.some(([from, to]) => minutes >= from && minutes < to)) return { state: 'trading', lastCloseDate }
|
|
105
126
|
// 午休只存在于两段之间: 只比前一段的收尾会把收盘后也算成午休
|
|
106
127
|
const breakIndex = bounds.findIndex(([, to], index) => index < bounds.length - 1 && minutes >= to && minutes < bounds[index + 1][0])
|
|
107
|
-
if (breakIndex >= 0) return { state: 'break', nextAt: epochOf(meta.timezone, local.date, bounds[breakIndex + 1][0]) }
|
|
108
|
-
return { state: 'closed', nextAt: nextOpenAt(meta, local.date, calendarDays) }
|
|
128
|
+
if (breakIndex >= 0) return { state: 'break', nextAt: epochOf(meta.timezone, local.date, bounds[breakIndex + 1][0]), lastCloseDate }
|
|
129
|
+
return { state: 'closed', nextAt: nextOpenAt(meta, local.date, calendarDays), lastCloseDate }
|
|
109
130
|
}
|
|
110
131
|
// 兼容旧调用面: 只要阶段
|
|
111
132
|
export function sessionStateOf(exchange, nowMs) {
|
|
@@ -140,6 +161,12 @@ function decimal(n) {
|
|
|
140
161
|
const abs = n < 0n ? -n : n
|
|
141
162
|
return `${sign}${abs / 100n}.${String(abs % 100n).padStart(2, '0')}`
|
|
142
163
|
}
|
|
164
|
+
// 上游的"没有数据"有两种写法: null 与空串。两者都必须保持缺失, 不能顺着 Number() 变成 0
|
|
165
|
+
export function numberOrNull(value) {
|
|
166
|
+
if (value == null || value === '') return null
|
|
167
|
+
const parsed = Number(value)
|
|
168
|
+
return Number.isFinite(parsed) ? parsed : null
|
|
169
|
+
}
|
|
143
170
|
export function normalizeQuote(input) {
|
|
144
171
|
const last = cents(input.last), previous = cents(input.previousClose)
|
|
145
172
|
const change = last !== null && previous !== null ? last - previous : null
|
package/src/memory-cache.mjs
CHANGED
|
@@ -4,16 +4,20 @@ const CACHE_LIMIT = 512
|
|
|
4
4
|
// 与数据域 table 同形的最小实现: catalog 只遍历 entries, kline-cache 只 get/put/delete
|
|
5
5
|
export function createMemoryCache({ limit = CACHE_LIMIT } = {}) {
|
|
6
6
|
const records = new Map()
|
|
7
|
+
// 版本号让消费方按"这份缓存变过没有"做记忆化: 目录展平与校验是整表成本, 不该每次搜索都付
|
|
8
|
+
let version = 0
|
|
7
9
|
return {
|
|
8
10
|
get: key => records.get(key),
|
|
9
11
|
async put(key, value) {
|
|
12
|
+
version += 1
|
|
10
13
|
records.delete(key)
|
|
11
14
|
records.set(key, value)
|
|
12
15
|
// 超限先丢最久未写的: 缓存的命门是内存, 不是命中率
|
|
13
16
|
while (records.size > limit) records.delete(records.keys().next().value)
|
|
14
17
|
},
|
|
15
|
-
async delete(key) {
|
|
18
|
+
async delete(key) { const removed = records.delete(key); if (removed) version += 1; return removed },
|
|
16
19
|
entries: () => records.entries(),
|
|
17
20
|
get size() { return records.size },
|
|
21
|
+
get version() { return version },
|
|
18
22
|
}
|
|
19
23
|
}
|
package/src/provider-router.mjs
CHANGED
|
@@ -44,10 +44,16 @@ export function createRouter(getConfig, now = Date.now, changed = () => {}) {
|
|
|
44
44
|
return { route, instance, routeEpoch: selected.routeEpoch }
|
|
45
45
|
},
|
|
46
46
|
// 环上的下一格: 降级与同轮补救共用, 走到最后一个时回到主源
|
|
47
|
-
|
|
48
|
-
|
|
47
|
+
// skip 用于跳过派不了活的实例(停用或没填预算), 与 recordRound 的挑选口径一致
|
|
48
|
+
nextInRing(id, instanceId, skip = () => false) {
|
|
49
|
+
const route = find(id), ring = ringOf(route), config = getConfig()
|
|
49
50
|
const index = ring.indexOf(instanceId)
|
|
50
|
-
|
|
51
|
+
if (ring.length < 2 || index === -1) return null
|
|
52
|
+
for (let step = 1; step < ring.length; step++) {
|
|
53
|
+
const candidate = ring[(index + step) % ring.length]
|
|
54
|
+
if (!skip(config.providers.find(p => p.id === candidate))) return candidate
|
|
55
|
+
}
|
|
56
|
+
return null
|
|
51
57
|
},
|
|
52
58
|
// 可回探的上级: 从主源往下, 跳过还在歇着或退避中的实例
|
|
53
59
|
recoveryCandidates(id) {
|
|
@@ -9,6 +9,8 @@ const DEFAULT_ENDPOINTS = {
|
|
|
9
9
|
trend: 'https://push2his.eastmoney.com/api/qt/stock/trends2/get',
|
|
10
10
|
}
|
|
11
11
|
const endpointOf = (ctx, key) => ctx.endpoints?.[key] || DEFAULT_ENDPOINTS[key]
|
|
12
|
+
// suggest 接口的公开站点参数(不是本插件凭据), 两处调用必须同源
|
|
13
|
+
const SUGGEST_TOKEN = 'D43BF722C8E33BDC906FB84D85E326E8'
|
|
12
14
|
// 沪深市场代码(其余市场的 secid 前缀见 SECID_PREFIX)
|
|
13
15
|
const MARKET = { XSHG: '1', XSHE: '0' }
|
|
14
16
|
// 搜索联想 MktNum→交易所全集(实测: 1/0 沪深, 116 港, 105/106/107 美三大, 176/177/155 日韩英)
|
|
@@ -34,6 +36,8 @@ const TREND_FIELDS = 'f51,f52,f53,f54,f55,f56,f57,f58'
|
|
|
34
36
|
// 分时时间戳的来源时区: 东财统一用北京时间, 与证券所属市场无关
|
|
35
37
|
const SOURCE_ZONE = 'Asia/Shanghai'
|
|
36
38
|
const num = value => value == null || typeof value === 'number' && !Number.isFinite(value) ? null : value === '-' ? null : String(value)
|
|
39
|
+
// 换手率/量比是纯数值语义(不参与定点价格格式化), 统一收敛成 number; 缺失仍是 null
|
|
40
|
+
const rate = value => { const text = num(value); const n = Number(text); return text === null || !Number.isFinite(n) ? null : n }
|
|
37
41
|
// 风控页是 HTML: 不嗅探就会被当成「响应不是JSON」, 用户看不到「去浏览器过滑块」这条唯一出路
|
|
38
42
|
const CHALLENGE_HINT = /验证码|人机验证|安全验证|滑块|拖动|geetest|tcaptcha|captcha/i
|
|
39
43
|
const challenged = async response => {
|
|
@@ -82,7 +86,7 @@ export const eastmoney = {
|
|
|
82
86
|
return { status: 'ready', capability: 'quotes', market: request.market, instrument: 'equity' }
|
|
83
87
|
},
|
|
84
88
|
async quotes(request, ctx) {
|
|
85
|
-
const fields = 'f2,f3,f4,f5,f6,f12,f13,f14,f15,f16,f17,f18,f124'
|
|
89
|
+
const fields = 'f2,f3,f4,f5,f6,f8,f10,f12,f13,f14,f15,f16,f17,f18,f124'
|
|
86
90
|
const seen = new Set(), items = []
|
|
87
91
|
// 一次请求取一批 secid;data:null 表示整批 secid 均无效(如整批退市),降级为逐证券缺失。
|
|
88
92
|
const ingest = async symbols => {
|
|
@@ -95,12 +99,14 @@ export const eastmoney = {
|
|
|
95
99
|
if (seen.has(security.id)) throw new StockError('BAD_PAYLOAD', '报价身份冲突', 502)
|
|
96
100
|
seen.add(security.id)
|
|
97
101
|
// fltt=2时价格为已缩放数值, "-"表示停牌等无值;f124为来源Unix秒;成交额币种按市场派生(单一事实源 MARKET_META.currency)。
|
|
102
|
+
// f8 换手率(百分数原值)、f10 量比在沪深港美同义(实测 116.00700 与 105.AAPL 均可读)
|
|
98
103
|
const quoteAt = Number.isFinite(row.f124) ? new Date(row.f124 * 1000).toISOString() : null
|
|
99
104
|
const currency = MARKET_META[security.exchange]?.currency || 'CNY'
|
|
100
105
|
items.push(normalizeQuote({
|
|
101
106
|
securityId: security.id, providerInstanceId: request.providerInstanceId, adapterId: 'eastmoney', providerSymbol: `${row.f13}.${row.f12}`,
|
|
102
107
|
last: num(row.f2), previousClose: num(row.f18), open: num(row.f17), high: num(row.f15), low: num(row.f16),
|
|
103
108
|
volume: sharesFromLots(num(row.f5), security.exchange), volumeUnit: 'share', amount: num(row.f6), amountUnit: currency,
|
|
109
|
+
turnoverRate: rate(row.f8), volumeRatio: rate(row.f10),
|
|
104
110
|
quoteAt, timestampKind: 'trade',
|
|
105
111
|
receivedAt: ctx.now(), delayKind: 'unknown', delaySeconds: null, securityState: 'unknown',
|
|
106
112
|
}))
|
|
@@ -145,7 +151,7 @@ export const eastmoney = {
|
|
|
145
151
|
async search(request, ctx) {
|
|
146
152
|
// 不限市场时扩大候选量: 单次响应要覆盖调用方负责的多个市场
|
|
147
153
|
const count = request.market ? Math.min(20, request.limit || 10) : Math.min(50, (request.limit || 10) * 3)
|
|
148
|
-
const url = `${endpointOf(ctx, 'search')}?input=${encodeURIComponent(request.q)}&type=14&token
|
|
154
|
+
const url = `${endpointOf(ctx, 'search')}?input=${encodeURIComponent(request.q)}&type=14&token=${SUGGEST_TOKEN}&count=${count}`
|
|
149
155
|
const body = await getJson(ctx, url)
|
|
150
156
|
const rows = body?.QuotationCodeTable?.Data
|
|
151
157
|
if (!Array.isArray(rows)) return { providerInstanceId: request.providerInstanceId, fetchedAt: ctx.now(), items: [], errors: [] }
|
|
@@ -184,7 +190,7 @@ export const eastmoney = {
|
|
|
184
190
|
return buildKlineResponse(request, body.data, ctx)
|
|
185
191
|
},
|
|
186
192
|
async resolveUsSecid(request, ctx) {
|
|
187
|
-
const url = `${endpointOf(ctx, 'search')}?input=${encodeURIComponent(request.code)}&type=14&token
|
|
193
|
+
const url = `${endpointOf(ctx, 'search')}?input=${encodeURIComponent(request.code)}&type=14&token=${SUGGEST_TOKEN}&count=5`
|
|
188
194
|
const body = await getJson(ctx, url)
|
|
189
195
|
const row = body?.QuotationCodeTable?.Data?.find(r => r.Code === request.code && /^10[567]$/.test(r.MktNum || ''))
|
|
190
196
|
return row ? { mktNum: row.MktNum, jys: row.JYS || null, at: ctx.now() } : null
|
package/src/providers/sina.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// 新浪公开行情接口适配器:quotes(沪深港美)/catalog(沪深)。非官方端点,需Referer,无SLA;延迟未知,时间为来源快照时间。
|
|
2
|
-
import { normalizeQuote, parseQuoteTime, makeSecurity, securityId, StockError } from '../market-model.mjs'
|
|
2
|
+
import { normalizeQuote, numberOrNull, parseQuoteTime, makeSecurity, securityId, StockError } from '../market-model.mjs'
|
|
3
3
|
const ENDPOINT = 'https://hq.sinajs.cn/list='
|
|
4
4
|
const LIST_ENDPOINT = 'https://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.getHQNodeData'
|
|
5
5
|
const HEADERS = { Referer: 'https://finance.sina.com.cn/', 'User-Agent': 'Mozilla/5.0' }
|
|
@@ -20,7 +20,7 @@ const symbolOf = security => {
|
|
|
20
20
|
const PROBE_SECURITY = { XSHG: '600519', XSHE: '000001', XHKG: '00700', XNAS: 'AAPL', XNYS: 'BABA' }
|
|
21
21
|
// 新浪价格固定三位以上小数,A股最小变动0.01,裁剪到两位不损失精度;港美同理按分呈现
|
|
22
22
|
const trim = value => /^\d+(\.\d+)?$/.test(value) ? Number(value).toFixed(2) : value
|
|
23
|
-
const count = value =>
|
|
23
|
+
const count = value => { const parsed = numberOrNull(value); return parsed === null ? null : String(Math.round(parsed)) }
|
|
24
24
|
// 各市场字段位置:沪深34列、港股25列、美股36列,同一行内的列义由前缀决定
|
|
25
25
|
const FIELD_MAP = {
|
|
26
26
|
cn: f => ({ open: f[1], previousClose: f[2], last: f[3], high: f[4], low: f[5], volume: f[8], amount: f[9], quoteAt: `${f[30]} ${f[31]}` }),
|
|
@@ -83,11 +83,14 @@ export const tencent = {
|
|
|
83
83
|
const f = match[2].split('~')
|
|
84
84
|
if (f.length < 38) throw new StockError('BAD_PAYLOAD', '来源字段数量异常', 502)
|
|
85
85
|
const volume = num(f[36]), amount = num(f[37])
|
|
86
|
+
// 换手率/量比只在沪深口径成立: 实测港股 f[38] 恒 0、f[49] 是周高, 美股同列位是别的字段
|
|
87
|
+
const cn = security.exchange === 'XSHG' || security.exchange === 'XSHE'
|
|
86
88
|
items.push(normalizeQuote({
|
|
87
89
|
securityId: security.id, providerInstanceId: request.providerInstanceId, adapterId: 'tencent', providerSymbol,
|
|
88
90
|
last: f[3], previousClose: f[4], open: f[5], high: f[33], low: f[34],
|
|
89
91
|
volume: volume === null ? null : String(sharesFromLots(volume, security.exchange)), volumeUnit: 'share',
|
|
90
92
|
amount: amount === null ? null : String(amountFromWan(amount, security.exchange)), amountUnit: MARKET_META[security.exchange]?.currency || 'CNY',
|
|
93
|
+
...(cn ? { turnoverRate: num(f[38]), volumeRatio: num(f[49]) } : {}),
|
|
91
94
|
quoteAt: parseQuoteTime(quoteStamp(f[30])), timestampKind: 'trade',
|
|
92
95
|
receivedAt: ctx.now(), delayKind: 'unknown', delaySeconds: null, securityState: 'unknown',
|
|
93
96
|
}))
|
|
@@ -152,6 +155,9 @@ export const tencent = {
|
|
|
152
155
|
if (!rows.length || !day) throw new StockError('NO_DATA', '来源未返回此证券分时', 422)
|
|
153
156
|
const stamp = `${day[1]}-${day[2]}-${day[3]}`
|
|
154
157
|
const candles = []
|
|
158
|
+
// minute/query 的第 3、4 列是当日累计量/额(实测: 末条等于全天成交量, 且单调递增),
|
|
159
|
+
// 而 candle.volume/amount 的契约是与东财 f56/f57 一致的区间增量, 这里必须做差分
|
|
160
|
+
let prevVolume = 0, prevAmount = 0
|
|
155
161
|
for (const row of rows) {
|
|
156
162
|
const cols = String(row).split(' ')
|
|
157
163
|
// 价格必须是纯数字才收: 上游偶有畸形行, 与其把 NaN 画进图里, 不如少一点
|
|
@@ -159,7 +165,14 @@ export const tencent = {
|
|
|
159
165
|
const time = `${cols[0].padStart(4, '0').slice(0, 2)}:${cols[0].padStart(4, '0').slice(2)}`
|
|
160
166
|
const price = num(cols[1])
|
|
161
167
|
if (price == null) continue
|
|
162
|
-
|
|
168
|
+
// 累计量偶尔回退(来源补数/清理), 差分取 0 而不是画负数
|
|
169
|
+
const cumulativeVolume = sharesFromLots(num(cols[2]), request.market)
|
|
170
|
+
const cumulativeAmount = num(cols[3])
|
|
171
|
+
const volume = cumulativeVolume === null ? null : Math.max(0, cumulativeVolume - prevVolume)
|
|
172
|
+
const amount = cumulativeAmount === null ? null : Math.max(0, cumulativeAmount - prevAmount)
|
|
173
|
+
if (cumulativeVolume !== null) prevVolume = cumulativeVolume
|
|
174
|
+
if (cumulativeAmount !== null) prevAmount = cumulativeAmount
|
|
175
|
+
candles.push({ time, at: zonedUnixSeconds(`${stamp} ${time}`, SOURCE_ZONE), open: price, close: price, high: price, low: price, volume, amount, avg: null })
|
|
163
176
|
}
|
|
164
177
|
if (!candles.length) throw new StockError('NO_DATA', '来源分时数据不可解析', 422)
|
|
165
178
|
const qt = Array.isArray(body?.data?.[symbol]?.qt?.[symbol]) ? body.data[symbol].qt[symbol] : null
|
|
@@ -1,6 +1,15 @@
|
|
|
1
|
-
import { makeSecurity, normalizeQuote, parseQuoteTime, StockError } from '../market-model.mjs'
|
|
1
|
+
import { makeSecurity, normalizeQuote, numberOrNull, parseQuoteTime, StockError } from '../market-model.mjs'
|
|
2
2
|
const EXCHANGE = { XSHG: 'SSE', XSHE: 'SZSE' }
|
|
3
3
|
const SUFFIX = { XSHG: 'SH', XSHE: 'SZ' }
|
|
4
|
+
// 成交量: 来源按手, 对外按股; 缺失保持缺失, 不折成 0
|
|
5
|
+
const lotsToShares = (volume, market) => {
|
|
6
|
+
const lots = numberOrNull(volume)
|
|
7
|
+
return lots === null ? null : String(lots * 100)
|
|
8
|
+
}
|
|
9
|
+
const amountOf = value => {
|
|
10
|
+
const parsed = numberOrNull(value)
|
|
11
|
+
return parsed === null ? null : String(parsed)
|
|
12
|
+
}
|
|
4
13
|
const FIELD = {
|
|
5
14
|
quotes: 'ts_code,name,pre_close,open,high,low,close,vol,amount,trade_time',
|
|
6
15
|
catalog: 'ts_code,symbol,name,cnspell,market,exchange,curr_type,list_status,list_date',
|
|
@@ -84,7 +93,7 @@ export const tushare = {
|
|
|
84
93
|
seen.add(row.ts_code)
|
|
85
94
|
const security = securities.get(row.ts_code)
|
|
86
95
|
items.push(normalizeQuote({ securityId: security.id, last: row.close, previousClose: row.pre_close, open: row.open, high: row.high, low: row.low,
|
|
87
|
-
volume: row.vol
|
|
96
|
+
volume: lotsToShares(row.vol, request.market), volumeUnit: 'share', amount: amountOf(row.amount), amountUnit: 'CNY',
|
|
88
97
|
providerInstanceId: request.providerInstanceId, adapterId: 'tushare', providerSymbol: row.ts_code, quoteAt: parseQuoteTime(row.trade_time), timestampKind: 'trade', receivedAt: ctx.now(), delayKind: 'unknown', delaySeconds: null, securityState: 'unknown' }))
|
|
89
98
|
}
|
|
90
99
|
return { providerInstanceId: request.providerInstanceId, fetchedAt: ctx.now(), items, errors: request.securities.filter(s => !seen.has(symbol(s))).map(s => ({ securityId: s.id, code: 'NO_DATA', message: '来源未返回此证券报价' })) }
|
package/src/providers/xueqiu.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// 雪球公开行情接口适配器:quotes(沪深港美)。
|
|
2
2
|
// 与新浪/东财的差别:同一请求可混装多市场,且额外给出换手率/振幅/市值/总股本。
|
|
3
3
|
// 接口需要 xq_a_token cookie,匿名访问首页即可拿到,本适配器惰性获取并按 TTL 缓存。
|
|
4
|
-
import { normalizeQuote, parseQuoteTime, StockError } from '../market-model.mjs'
|
|
4
|
+
import { normalizeQuote, numberOrNull, parseQuoteTime, StockError } from '../market-model.mjs'
|
|
5
5
|
const ENDPOINT = 'https://stock.xueqiu.com/v5/stock/batch/quote.json'
|
|
6
6
|
const HOME = 'https://xueqiu.com/'
|
|
7
7
|
const HEADERS = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36' }
|
|
@@ -11,7 +11,8 @@ let token = { value: null, until: 0 }
|
|
|
11
11
|
// 沪深用大写市场前缀, 港股与美股直接用代码本身(实测 HK00700 返回空, 00700 才有数据)
|
|
12
12
|
const symbolOf = security => (security.exchange === 'XSHG' ? 'SH' : security.exchange === 'XSHE' ? 'SZ' : '') + security.code
|
|
13
13
|
const PROBE_SECURITY = { XSHG: '600519', XSHE: '000001', XHKG: '00700', XNAS: 'AAPL', XNYS: 'BABA' }
|
|
14
|
-
|
|
14
|
+
// 缺失(undefined/null/'')一律当缺失: Number(null) 是 0, 只比有限性会把「来源没给」显示成 0 价/0 量
|
|
15
|
+
const quote = value => { const n = numberOrNull(value); return n === null ? null : n.toFixed(2) }
|
|
15
16
|
|
|
16
17
|
export const xueqiu = {
|
|
17
18
|
descriptor: { adapterId: 'xueqiu', capabilities: ['quotes'], markets: ['XSHG', 'XSHE', 'XHKG', 'XNAS', 'XNYS'], instruments: ['equity'], maxQuoteBatch: 60, credential: 'none', description: '雪球公开接口:免凭据(匿名 token),沪深港美行情,可混装多市场,额外提供换手率与市值' },
|
|
@@ -50,15 +51,16 @@ export const xueqiu = {
|
|
|
50
51
|
if (seen.has(security.id)) throw new StockError('BAD_PAYLOAD', '报价身份冲突', 502)
|
|
51
52
|
seen.add(security.id)
|
|
52
53
|
// 雪球 volume 统一是股, amount 统一是元; 时间戳是毫秒 Unix
|
|
54
|
+
const volume = numberOrNull(row.volume), amount = numberOrNull(row.amount), marketCapital = numberOrNull(row.market_capital), stamp = numberOrNull(row.timestamp)
|
|
53
55
|
result.push(normalizeQuote({
|
|
54
56
|
securityId: security.id, providerInstanceId: request.providerInstanceId, adapterId: 'xueqiu', providerSymbol: row.symbol,
|
|
55
57
|
last: quote(row.current), previousClose: quote(row.last_close), open: quote(row.open), high: quote(row.high), low: quote(row.low),
|
|
56
|
-
volume:
|
|
57
|
-
amount:
|
|
58
|
-
quoteAt:
|
|
58
|
+
volume: volume === null ? null : String(Math.round(volume)), volumeUnit: 'share',
|
|
59
|
+
amount: amount === null ? null : String(Math.round(amount)), amountUnit: String(row.currency || ''),
|
|
60
|
+
quoteAt: stamp === null ? null : new Date(stamp).toISOString(), timestampKind: 'trade',
|
|
59
61
|
receivedAt: ctx.now(), delayKind: 'unknown', delaySeconds: null, securityState: 'unknown',
|
|
60
|
-
turnoverRate:
|
|
61
|
-
marketCapital:
|
|
62
|
+
turnoverRate: numberOrNull(row.turnover_rate),
|
|
63
|
+
marketCapital: marketCapital === null ? null : Math.round(marketCapital),
|
|
62
64
|
}))
|
|
63
65
|
}
|
|
64
66
|
return { providerInstanceId: request.providerInstanceId, fetchedAt: ctx.now(), items: result, errors: request.securities.filter(s => !seen.has(s.id)).map(s => ({ securityId: s.id, code: 'NO_DATA', message: '来源未返回此证券报价' })) }
|
package/src/routes.mjs
CHANGED
|
@@ -2,6 +2,9 @@ import { z } from 'zod'
|
|
|
2
2
|
import { StockError, fail } from './market-model.mjs'
|
|
3
3
|
import { withRouteGate } from './route-gate.mjs'
|
|
4
4
|
const PREFIX = '/api/stock-assistant'
|
|
5
|
+
// catalog-sync 分页抓全量目录: 单独预算; 探针与其余路由都由应用层推导(见 application.providerCheckTimeoutMs / routeTimeoutMs),
|
|
6
|
+
// 应用层给不出时退回这里的兜底值
|
|
7
|
+
const PROVIDER_CHECK_TIMEOUT_MS = 60 * 1000, CATALOG_SYNC_TIMEOUT_MS = 120 * 1000, DEFAULT_ROUTE_TIMEOUT_MS = 10 * 1000
|
|
5
8
|
const operationSchema = z.object({ operationId: z.uuid(), expectedRevision: z.number().int().nonnegative() })
|
|
6
9
|
async function body(req) {
|
|
7
10
|
const chunks = []; let size = 0
|
|
@@ -44,11 +47,15 @@ export function registerRoutes(webServer, app, ctx) {
|
|
|
44
47
|
const controller = new AbortController(); controllers.add(controller)
|
|
45
48
|
const onClose = () => { if (!res.writableEnded) controller.abort() }
|
|
46
49
|
res.on('close', onClose)
|
|
47
|
-
const timeout = name === 'provider-check' ? 60 * 1000 : name === 'catalog-sync' ? 120 * 1000 : 10 * 1000
|
|
48
50
|
let timer
|
|
49
51
|
try {
|
|
50
52
|
const input = method === 'GET' ? Object.fromEntries(new URL(req.url, 'http://local').searchParams) : await body(req)
|
|
51
53
|
if (method === 'POST' && (input === null || typeof input !== 'object' || Array.isArray(input))) fail('INVALID_REQUEST', '请求内容必须为JSON对象')
|
|
54
|
+
// 应用层没给或给了非数值时退回默认预算: 传进 setTimeout 的必须是有限正数。
|
|
55
|
+
// 取值放进 try: 这里抛错也必须有响应写出, 否则请求悬挂到客户端超时。
|
|
56
|
+
// 探针的预算要按待测目标数算, 所以必须等输入解析完再取
|
|
57
|
+
const derived = name === 'provider-check' ? app.providerCheckTimeoutMs?.(input) : app.routeTimeoutMs?.()
|
|
58
|
+
const timeout = name === 'catalog-sync' ? CATALOG_SYNC_TIMEOUT_MS : Number.isFinite(derived) && derived > 0 ? derived : name === 'provider-check' ? PROVIDER_CHECK_TIMEOUT_MS : DEFAULT_ROUTE_TIMEOUT_MS
|
|
52
59
|
const data = await Promise.race([
|
|
53
60
|
Promise.resolve(action(input, controller.signal)),
|
|
54
61
|
// 超时错误随 abort reason 一起下发: 即使 abort 监听先被同步派发, 也拿到 TIMEOUT 而不是 CANCELLED
|
|
@@ -58,6 +65,9 @@ export function registerRoutes(webServer, app, ctx) {
|
|
|
58
65
|
json(res, 200, { ok: true, data })
|
|
59
66
|
} catch (e) {
|
|
60
67
|
const error = e instanceof StockError ? e : new StockError('INVALID_REQUEST', e instanceof z.ZodError ? '请求参数格式错误' : '股票工具请求失败', e instanceof z.ZodError ? 400 : 500)
|
|
68
|
+
// 服务端失败必须有痕迹: 只记路由与错误码, 不记文案(文案可能带上游地址与凭据形态)。
|
|
69
|
+
// 客户端关页/切详情触发的取消不是故障, 记成 5xx 只会让日志看起来一直在报错
|
|
70
|
+
if (error.status >= 500 && error.code !== 'CANCELLED') ctx?.logger?.warn?.(`股票助手请求失败: ${name} ${error.code} (${error.status})`)
|
|
61
71
|
json(res, error.status, { ok: false, error: { code: error.code, message: error.message, retryable: error.retryable, retryAfterMs: error.retryAfterMs }, ...(error.details === undefined ? {} : { details: error.details }), ...(error.revision === undefined ? {} : { revision: error.revision }), ...(e.snapshot ? { snapshot: e.snapshot } : {}) })
|
|
62
72
|
} finally { clearTimeout(timer); controllers.delete(controller); res.removeListener('close', onClose) }
|
|
63
73
|
}
|
package/src/schemas.mjs
CHANGED
|
@@ -58,7 +58,7 @@ export const klineQuerySchema = z.strictObject({
|
|
|
58
58
|
securityId: z.string().regex(/^[\w]+:equity:[\w.]{1,15}$/),
|
|
59
59
|
period: z.enum(['trend', '1d', '1w', '1M']),
|
|
60
60
|
limit: z.coerce.number().int().min(20).max(1000).default(250),
|
|
61
|
-
//
|
|
61
|
+
// 日、周、月 K 线可强制跳过缓存;分时仍遵守共享刷新窗口。
|
|
62
62
|
force: z.enum(['0', '1']).optional(),
|
|
63
63
|
})
|
|
64
64
|
// 手动刷新的证券参数: 自选 id 字符串或客户端持有的完整身份(浏览/搜索 peek)。形状在这里定死,
|
|
@@ -69,7 +69,11 @@ const refreshSecuritySchema = z.union([
|
|
|
69
69
|
return parts.length === 3 && parts[1] === 'equity' && MARKET_META[parts[0]] !== undefined && /^[\w.]{1,15}$/.test(parts[2])
|
|
70
70
|
}, '证券标识无效'),
|
|
71
71
|
z.object({ id: z.string().min(1).max(64), exchange: marketSchema, code: z.string().min(1).max(20), officialName: z.string().min(1).max(100).optional() })
|
|
72
|
-
|
|
72
|
+
// 代码形状必须与市场一致: 否则 makeSecurity 抛普通 Error, 路由层会把它折叠成 500 而不是 400
|
|
73
|
+
.superRefine((value, ctx) => {
|
|
74
|
+
if (value.id !== `${value.exchange}:equity:${value.code}`) ctx.addIssue({ code: 'custom', message: '证券身份不一致' })
|
|
75
|
+
if (!MARKET_META[value.exchange]?.codePattern.test(value.code)) ctx.addIssue({ code: 'custom', message: '证券代码与市场不符' })
|
|
76
|
+
}),
|
|
73
77
|
])
|
|
74
78
|
export const refreshSecuritiesSchema = z.array(refreshSecuritySchema).max(100)
|
|
75
79
|
// 路由上限: 八市场 × 全部能力, 全开也要装得下
|
|
@@ -117,7 +121,7 @@ export function parseConfiguration(value) {
|
|
|
117
121
|
}
|
|
118
122
|
// 分时路由的迁移版本: 存量库只补一次(补缺失路由 + 给单源分时登记备源), 用户随后删掉分时路由不该在下次启动被复活
|
|
119
123
|
export const TREND_ROUTE_MIGRATION = 2
|
|
120
|
-
export const controlSchema = z.object({ revision: z.number().int().nonnegative(), routingRevision: z.number().int().nonnegative(), routeMigration: z.number().int().nonnegative().default(0), watchlist: z.object({ order: z.array(z.string()).max(100), items: z.record(z.string(), securitySchema.safeExtend({ alias: z.string(), pinned: z.boolean(), marks: marksSchema, tags: z.array(tagName).max(MAX_TAGS).refine(list => new Set(list).size === list.length, '标签不能重复').default([]) })) }), preferences: preferencesSchema, providers: z.array(providerSchema), routes: z.array(routeSchema), operations: z.array(z.object({ id: z.uuid(), hash: z.string(), at: z.number(), result: z.object({ revision: z.number() }).passthrough(), action: z.string()
|
|
124
|
+
export const controlSchema = z.object({ revision: z.number().int().nonnegative(), routingRevision: z.number().int().nonnegative(), routeMigration: z.number().int().nonnegative().default(0), watchlist: z.object({ order: z.array(z.string()).max(100), items: z.record(z.string(), securitySchema.safeExtend({ alias: z.string(), pinned: z.boolean(), marks: marksSchema, tags: z.array(tagName).max(MAX_TAGS).refine(list => new Set(list).size === list.length, '标签不能重复').default([]) })) }), preferences: preferencesSchema, providers: z.array(providerSchema), routes: z.array(routeSchema), operations: z.array(z.object({ id: z.uuid(), hash: z.string(), at: z.number(), result: z.object({ revision: z.number() }).passthrough(), action: z.string() })).max(256) }).superRefine((control, ctx) => {
|
|
121
125
|
const w = control.watchlist
|
|
122
126
|
if (new Set(w.order).size !== w.order.length || w.order.length !== Object.keys(w.items).length || w.order.some(id => w.items[id]?.id !== id)) ctx.addIssue({ code: 'custom', message: '自选序列与证券不一致' })
|
|
123
127
|
let unpinned = false
|
|
@@ -171,25 +175,16 @@ const normalizeCredentialField = root => {
|
|
|
171
175
|
const providers = root.providers.map(p => { const next = normalizeProvider(p); if (next !== p) changed = true; return next })
|
|
172
176
|
return changed ? { ...root, providers } : root
|
|
173
177
|
}
|
|
174
|
-
//
|
|
175
|
-
//
|
|
178
|
+
// 幂等台账曾经存过一份完整的配置副本(含代理/端点明文): 现在只留幂等键与结果,
|
|
179
|
+
// 读入时把存量条目里的 payload 丢掉。丢弃必须发生在归一化里, 否则明文会留在盘上直到下一次无关写入。
|
|
176
180
|
const normalizeOperations = root => {
|
|
177
181
|
if (!Array.isArray(root?.operations)) return root
|
|
178
182
|
let changed = false
|
|
179
183
|
const operations = root.operations.map(operation => {
|
|
180
|
-
|
|
181
|
-
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) return operation
|
|
182
|
-
let next = payload
|
|
183
|
-
if (Array.isArray(payload.providers)) {
|
|
184
|
-
let providersChanged = false
|
|
185
|
-
const providers = payload.providers.map(p => { const candidate = normalizeProvider(p); if (candidate !== p) providersChanged = true; return candidate })
|
|
186
|
-
if (providersChanged) next = { ...next, providers }
|
|
187
|
-
}
|
|
188
|
-
const endpoints = normalizeEndpointMap(next.endpoints)
|
|
189
|
-
if (endpoints !== next.endpoints) next = { ...next, endpoints }
|
|
190
|
-
if (next === payload) return operation
|
|
184
|
+
if (!operation || typeof operation !== 'object' || !('payload' in operation)) return operation
|
|
191
185
|
changed = true
|
|
192
|
-
|
|
186
|
+
const { payload, ...rest } = operation
|
|
187
|
+
return rest
|
|
193
188
|
})
|
|
194
189
|
return changed ? { ...root, operations } : root
|
|
195
190
|
}
|
package/src/state.mjs
CHANGED
|
@@ -20,8 +20,23 @@ export async function openState(storageDomain, changed = () => {}, now = Date.no
|
|
|
20
20
|
} catch (e) { await Promise.allSettled([domain.close()]); throw e }
|
|
21
21
|
const cache = createMemoryCache({ limit: CATALOG_CACHE_LIMIT }), klineCache = createMemoryCache({ limit: KLINE_CACHE_LIMIT }), trendCache = createMemoryCache({ limit: TREND_CACHE_LIMIT })
|
|
22
22
|
let tail = Promise.resolve(), stopped = false
|
|
23
|
+
// 读侧按版本记忆化: 控制记录只在 mutate 里整体替换, 同一版本读出来的内容恒定,
|
|
24
|
+
// 每次深拷贝会把"每标的取一次配置"的热路径变成每秒数毫秒的开销。
|
|
25
|
+
// 返回的对象深冻结: 读侧原地改会在严格模式下直接抛错, 而不是悄悄污染共享快照。
|
|
26
|
+
const deepFreeze = value => {
|
|
27
|
+
if (value && typeof value === 'object') { for (const child of Object.values(value)) deepFreeze(child); Object.freeze(value) }
|
|
28
|
+
return value
|
|
29
|
+
}
|
|
30
|
+
// 缓存键同时看两个版本: 路由换代也会改变读到的语义, 只认 revision 会漏掉只改路由版本的写入
|
|
31
|
+
const versionOf = root => `${root.revision}:${root.routingRevision}`
|
|
32
|
+
let snapshot = null, snapshotVersion = ''
|
|
33
|
+
const current = () => {
|
|
34
|
+
const root = table.get('root'), version = versionOf(root)
|
|
35
|
+
if (version !== snapshotVersion) { snapshot = deepFreeze(structuredClone(root)); snapshotVersion = version }
|
|
36
|
+
return snapshot
|
|
37
|
+
}
|
|
23
38
|
return {
|
|
24
|
-
get: () =>
|
|
39
|
+
get: () => current(),
|
|
25
40
|
cache, klineCache, trendCache,
|
|
26
41
|
replay(operation) {
|
|
27
42
|
const prior = table.get('root').operations.find(o => o.id === operation.operationId && now() - o.at < DAY)
|
|
@@ -44,7 +59,7 @@ export async function openState(storageDomain, changed = () => {}, now = Date.no
|
|
|
44
59
|
next.revision = current.revision + 1
|
|
45
60
|
const result = { revision: next.revision, unchanged: false, ...(next.operationResult || {}) }
|
|
46
61
|
delete next.operationResult
|
|
47
|
-
next.operations = [...current.operations.filter(o => now() - o.at < DAY), { id: operation.operationId, hash, at: now(), result, action: operation.action
|
|
62
|
+
next.operations = [...current.operations.filter(o => now() - o.at < DAY), { id: operation.operationId, hash, at: now(), result, action: operation.action }].slice(-256)
|
|
48
63
|
try { controlSchema.parse(next) } catch (e) { fail('INVARIANT_VIOLATION', '写入结果违反内部不变式', 500, { cause: e }) }
|
|
49
64
|
try {
|
|
50
65
|
await table.update('root', stored => {
|
package/src/trend-cache.mjs
CHANGED
|
@@ -1,26 +1,111 @@
|
|
|
1
|
-
import { marketDate } from './market-model.mjs'
|
|
2
|
-
//
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
const
|
|
6
|
-
|
|
1
|
+
import { marketDate, StockError } from './market-model.mjs'
|
|
2
|
+
// 数据日期取最后一根分时的时间,避免把盘前收到的上个交易日数据当成当天数据。
|
|
3
|
+
const windowKeyOf = ({ market, code, limit, routeKey = '' }) => `trend:${market}:${code}:${limit}:${routeKey}`
|
|
4
|
+
// 离线缓存不按路由代次拆分: 当天真实分时换源后仍是同一只股票的有效兜底
|
|
5
|
+
const cacheKeyOf = ({ market, code, limit }) => `trend:${market}:${code}:${limit}`
|
|
6
|
+
const TREND_INTERVAL_MS = 60 * 1000
|
|
7
|
+
const MAX_WINDOWS = 1024
|
|
8
|
+
const cancelled = () => new StockError('CANCELLED', '分时请求已取消', 503)
|
|
9
|
+
const cooling = retryAfterMs => new StockError('RATE_LIMIT', '分时尚未到刷新时间', 429, { retryable: true, retryAfterMs })
|
|
10
|
+
export function trendSessionDate(market, payload) {
|
|
11
|
+
const at = payload?.candles?.at(-1)?.at
|
|
7
12
|
return Number.isFinite(at) ? marketDate(market, at * 1000) : null
|
|
8
13
|
}
|
|
9
14
|
export function createTrendCache({ table, now = Date.now }) {
|
|
15
|
+
const flights = new Map(), windows = new Map()
|
|
16
|
+
const wait = async (flight, signal) => {
|
|
17
|
+
flight.waiters++
|
|
18
|
+
const sharedSignal = flight.controller.signal
|
|
19
|
+
const waitingSignal = signal ? AbortSignal.any([signal, sharedSignal]) : sharedSignal
|
|
20
|
+
let onAbort
|
|
21
|
+
try {
|
|
22
|
+
return await Promise.race([flight.promise, new Promise((_, reject) => {
|
|
23
|
+
onAbort = () => reject(cancelled())
|
|
24
|
+
waitingSignal.addEventListener('abort', onAbort, { once: true })
|
|
25
|
+
if (waitingSignal.aborted) onAbort()
|
|
26
|
+
})])
|
|
27
|
+
} finally {
|
|
28
|
+
waitingSignal.removeEventListener('abort', onAbort)
|
|
29
|
+
if (--flight.waiters === 0 && !flight.settled) flight.controller.abort(cancelled())
|
|
30
|
+
}
|
|
31
|
+
}
|
|
10
32
|
return {
|
|
33
|
+
async fetch(key, signal, fetchTrend) {
|
|
34
|
+
if (signal?.aborted) throw cancelled()
|
|
35
|
+
const day = marketDate(key.market, now())
|
|
36
|
+
let id = `${windowKeyOf(key)}:${day}`
|
|
37
|
+
const currentFlight = flights.get(id)
|
|
38
|
+
if (currentFlight && !currentFlight.controller.signal.aborted) return wait(currentFlight, signal)
|
|
39
|
+
const at = now(), previous = windows.get(id)
|
|
40
|
+
if (previous?.nextAt > at) {
|
|
41
|
+
if (previous.error) {
|
|
42
|
+
if (previous.error.code === 'CANCELLED') throw cooling(previous.nextAt - at)
|
|
43
|
+
const { code, message, status, retryable, routeEpoch } = previous.error
|
|
44
|
+
throw new StockError(code, message, status, { retryable, routeEpoch, retryAfterMs: previous.nextAt - at })
|
|
45
|
+
}
|
|
46
|
+
if (previous.result) return previous.result
|
|
47
|
+
throw cooling(previous.nextAt - at)
|
|
48
|
+
}
|
|
49
|
+
for (const [windowId, window] of windows) {
|
|
50
|
+
if (window.nextAt <= at && !flights.has(windowId)) windows.delete(windowId)
|
|
51
|
+
}
|
|
52
|
+
if (windows.size >= MAX_WINDOWS && !previous) throw cooling(TREND_INTERVAL_MS)
|
|
53
|
+
const window = { nextAt: at + TREND_INTERVAL_MS }, controller = new AbortController()
|
|
54
|
+
windows.set(id, window)
|
|
55
|
+
const flight = { controller, waiters: 0, settled: false, promise: null }
|
|
56
|
+
flights.set(id, flight)
|
|
57
|
+
// 本轮触发切源时,备源已经由同一轮尝试。把在飞与冷却移到新选择,避免换代马上重复回源。
|
|
58
|
+
const moveTo = nextKey => {
|
|
59
|
+
if (flights.get(id) !== flight) return
|
|
60
|
+
const nextId = `${windowKeyOf(nextKey)}:${day}`
|
|
61
|
+
// 目标键已有另一轮在飞或冷却: 让那一轮保持原样, 本轮的窗口留在旧键
|
|
62
|
+
if (flights.has(nextId) || windows.has(nextId)) return
|
|
63
|
+
flights.delete(id)
|
|
64
|
+
windows.delete(id)
|
|
65
|
+
id = nextId
|
|
66
|
+
flights.set(id, flight)
|
|
67
|
+
windows.set(id, window)
|
|
68
|
+
}
|
|
69
|
+
flight.promise = Promise.resolve().then(async () => {
|
|
70
|
+
try {
|
|
71
|
+
if (controller.signal.aborted) throw cancelled()
|
|
72
|
+
const result = await fetchTrend(controller.signal, moveTo)
|
|
73
|
+
if (controller.signal.aborted) throw cancelled()
|
|
74
|
+
// 空响应只占刷新窗口。非空结果(含盘前上一交易日)可在同一窗口内复用;
|
|
75
|
+
// 只有属于当天的完整真分时才写离线表。
|
|
76
|
+
if (!result.candles?.length || (!result.offline && result.complete !== false)) window.result = result
|
|
77
|
+
return result
|
|
78
|
+
} catch (error) {
|
|
79
|
+
window.error = error
|
|
80
|
+
if (error.retryAfterMs > 0) window.nextAt = Math.max(window.nextAt, now() + error.retryAfterMs)
|
|
81
|
+
throw error
|
|
82
|
+
} finally {
|
|
83
|
+
// 执行器排队和同轮补救也耗时,从整轮收尾算下一次刷新时间。
|
|
84
|
+
window.nextAt = Math.max(window.nextAt, now() + TREND_INTERVAL_MS)
|
|
85
|
+
flight.settled = true
|
|
86
|
+
if (flights.get(id) === flight) flights.delete(id)
|
|
87
|
+
}
|
|
88
|
+
})
|
|
89
|
+
return wait(flight, signal)
|
|
90
|
+
},
|
|
91
|
+
dispose() {
|
|
92
|
+
for (const flight of flights.values()) flight.controller.abort(cancelled())
|
|
93
|
+
flights.clear()
|
|
94
|
+
windows.clear()
|
|
95
|
+
},
|
|
11
96
|
async get(key) {
|
|
12
|
-
const raw = await table.get(
|
|
97
|
+
const raw = await table.get(cacheKeyOf(key))
|
|
13
98
|
// 过期即删: 否则旧记录继续占着淘汰池, 还会被后来者当成"当日缓存"
|
|
14
99
|
const stale = !raw || raw.kind !== 'trend' || !raw.payload?.candles?.length || raw.sessionDate !== marketDate(key.market, now())
|
|
15
100
|
if (!stale) return raw
|
|
16
|
-
if (raw) await table.delete(
|
|
101
|
+
if (raw) await table.delete(cacheKeyOf(key)).catch(() => {})
|
|
17
102
|
return null
|
|
18
103
|
},
|
|
19
104
|
// 空结果(上游成功但没数据)和兜底结果都不写: 缓存只存"完整的一次真分时"
|
|
20
105
|
async put(key, result) {
|
|
21
|
-
const sessionDate =
|
|
22
|
-
if (!sessionDate || result.complete === false || result.offline) return
|
|
23
|
-
await table.put(
|
|
106
|
+
const sessionDate = trendSessionDate(key.market, result)
|
|
107
|
+
if (!sessionDate || result.complete === false || result.offline || sessionDate !== marketDate(key.market, now())) return
|
|
108
|
+
await table.put(cacheKeyOf(key), { kind: 'trend', sessionDate, cachedAt: now(), payload: result }).catch(() => {})
|
|
24
109
|
},
|
|
25
110
|
}
|
|
26
111
|
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
// 美股代码 → 交易所标识(mktNum/JYS)的映射: 上游只在部分接口给出, 下游拼 secid 与后缀时要用。
|
|
2
|
+
// 写入方是适配器(ctx.usSymbols), 没有自然的回收点, 所以上限与过期都由容器自己保证。
|
|
3
|
+
// 必须保持 Map 接口: 适配器只用 get/set, 测试里大量注入裸 Map。
|
|
4
|
+
export const US_SYMBOL_LIMIT = 500
|
|
5
|
+
export const US_SYMBOL_TTL = 24 * 60 * 60 * 1000
|
|
6
|
+
|
|
7
|
+
class UsSymbols extends Map {
|
|
8
|
+
constructor({ now, limit, ttl }) {
|
|
9
|
+
super()
|
|
10
|
+
this.now = now
|
|
11
|
+
this.limit = limit
|
|
12
|
+
this.ttl = ttl
|
|
13
|
+
}
|
|
14
|
+
get(key) {
|
|
15
|
+
const entry = super.get(key)
|
|
16
|
+
if (entry === undefined) return undefined
|
|
17
|
+
// 过期的映射等于没有: 留着只会让拼错 secid 的请求打到一个早就换过的市场
|
|
18
|
+
if (this.now() - entry.at > this.ttl) { this.delete(key); return undefined }
|
|
19
|
+
return entry
|
|
20
|
+
}
|
|
21
|
+
// 写入即移到尾部: Map 的迭代序就是淘汰序, 不重排会让最活跃的映射停在头部先被淘汰
|
|
22
|
+
set(key, value) {
|
|
23
|
+
this.delete(key)
|
|
24
|
+
super.set(key, value)
|
|
25
|
+
while (this.size > this.limit) this.delete(this.keys().next().value)
|
|
26
|
+
return this
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export const createUsSymbols = ({ now = Date.now, limit = US_SYMBOL_LIMIT, ttl = US_SYMBOL_TTL } = {}) => new UsSymbols({ now, limit, ttl })
|