@mzzsfy/dsh-stock-assistant 0.7.1 → 0.8.1
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 +459 -0
- package/README.md +33 -19
- package/package.json +67 -65
- package/src/application.mjs +186 -52
- package/src/catalog.mjs +50 -25
- package/src/client.js +436 -148
- package/src/collector.mjs +128 -34
- package/src/executor.mjs +59 -23
- package/src/index.js +45 -41
- package/src/kline-cache.mjs +6 -7
- package/src/market-model.mjs +88 -16
- package/src/provider-registry.mjs +5 -1
- package/src/provider-router.mjs +76 -9
- package/src/providers/eastmoney.mjs +226 -245
- package/src/providers/sina.mjs +3 -1
- package/src/providers/tencent.mjs +168 -122
- package/src/providers/tushare.mjs +92 -92
- package/src/recovery.mjs +64 -0
- package/src/route-gate.mjs +85 -29
- package/src/routes.mjs +68 -68
- package/src/schemas.mjs +126 -19
- package/src/state.mjs +9 -5
- package/src/ticks.mjs +45 -0
- package/src/trend-cache.mjs +26 -0
- package//345/205/274/345/256/271/346/200/247/346/265/213/350/257/225.md +215 -1
|
@@ -1,122 +1,168 @@
|
|
|
1
|
-
// 腾讯公开行情接口适配器:quotes+kline(备源)。非官方端点,无SLA,随时可能失效;延迟未知,行情时间戳为来源快照时间。
|
|
2
|
-
import { normalizeQuote, parseQuoteTime, StockError, MARKET_META, sharesFromLots, amountFromWan } from '../market-model.mjs'
|
|
3
|
-
//
|
|
4
|
-
const
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
//
|
|
13
|
-
const
|
|
14
|
-
//
|
|
15
|
-
|
|
16
|
-
const
|
|
17
|
-
//
|
|
18
|
-
const
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
//
|
|
28
|
-
const
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
const
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
if (
|
|
70
|
-
if (
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
throw new StockError('
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
const
|
|
106
|
-
|
|
107
|
-
const
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
if (
|
|
113
|
-
if (
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
const
|
|
119
|
-
const
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
1
|
+
// 腾讯公开行情接口适配器:quotes+kline+trend(备源)。非官方端点,无SLA,随时可能失效;延迟未知,行情时间戳为来源快照时间。
|
|
2
|
+
import { normalizeQuote, parseQuoteTime, StockError, MARKET_META, sharesFromLots, amountFromWan, zonedUnixSeconds } from '../market-model.mjs'
|
|
3
|
+
// 分时时间戳与东财同一基准: 腾讯给的是北京时间
|
|
4
|
+
const SOURCE_ZONE = 'Asia/Shanghai'
|
|
5
|
+
// 官方默认端点表(key 供 instance.endpoints 覆盖, 反代/镜像场景由 ctx.endpoints 提供同名 key)
|
|
6
|
+
const DEFAULT_ENDPOINTS = {
|
|
7
|
+
quotes: 'https://qt.gtimg.cn/q=',
|
|
8
|
+
kline: 'https://web.ifzq.gtimg.cn/appstock/app/fqkline/get',
|
|
9
|
+
trend: 'https://web.ifzq.gtimg.cn/appstock/app/minute/query?code=',
|
|
10
|
+
}
|
|
11
|
+
const endpointOf = (ctx, key) => ctx.endpoints?.[key] || DEFAULT_ENDPOINTS[key]
|
|
12
|
+
// quotes 与 kline 共用一张前缀表,防双源漂移(design.md 数据结构节)。
|
|
13
|
+
const SYMBOL_PREFIX = { XSHG: 'sh', XSHE: 'sz', XHKG: 'hk' }
|
|
14
|
+
// 美股 symbol 后缀由搜索联想 JYS 字段映射(2026-10-30 实测: suggest 返回 JYS="NASDAQ"/"NYSE"/"AMEX";
|
|
15
|
+
// 腾讯侧 .OQ/.N/裸代码同价有效, .A/.U 形态返回空数据——AMEX 走裸代码兜底)。
|
|
16
|
+
const JYS_TO_SUFFIX = { NASDAQ: 'OQ', NYSE: 'N', AMEX: '' }
|
|
17
|
+
// 美股行情端点要 us 前缀(实测 usAAPL 有效, 裸 AAPL 返回空);K线另有 JYS 后缀逻辑, 不复用这张表。
|
|
18
|
+
const isUSExchange = exchange => exchange === 'XNAS' || exchange === 'XNYS'
|
|
19
|
+
const symbolOf = security => isUSExchange(security.exchange) ? `us${security.code}` : SYMBOL_PREFIX[security.exchange] ? `${SYMBOL_PREFIX[security.exchange]}${security.code}` : `${security.code}`
|
|
20
|
+
// kline request 用 market 字段(exchange 是 security 形态的字段名); 港股 code 统一 5 位对齐腾讯 hk00700 实测形态。
|
|
21
|
+
const klineSymbolOf = request => {
|
|
22
|
+
const prefix = SYMBOL_PREFIX[request.market]
|
|
23
|
+
if (!prefix) return request.code
|
|
24
|
+
const code = request.market === 'XHKG' ? request.code.padStart(5, '0') : request.code
|
|
25
|
+
return `${prefix}${code}`
|
|
26
|
+
}
|
|
27
|
+
// kline 数据键随复权/周期漂移(qfqday/day/qfqweek/qfqmonth),取第一个数组值兜底。
|
|
28
|
+
const firstArray = data => Object.values(data).find(Array.isArray)
|
|
29
|
+
const num = v => { const n = parseFloat(v); return Number.isFinite(n) ? n : null }
|
|
30
|
+
// 行情时间戳三种写法: 沪深紧凑数字, 港股斜杠, 美股带连字符
|
|
31
|
+
const quoteStamp = raw => {
|
|
32
|
+
const compact = /^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/.exec(raw || '')
|
|
33
|
+
if (compact) return `${compact[1]}-${compact[2]}-${compact[3]} ${compact[4]}:${compact[5]}:${compact[6]}`
|
|
34
|
+
const loose = /^(\d{4})[-/](\d{2})[-/](\d{2})[ T](\d{2}):(\d{2})(?::(\d{2}))?/.exec(raw || '')
|
|
35
|
+
return loose ? `${loose[1]}-${loose[2]}-${loose[3]} ${loose[4]}:${loose[5]}:${loose[6] || '00'}` : null
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export const tencent = {
|
|
39
|
+
descriptor: { adapterId: 'tencent', capabilities: ['quotes', 'kline', 'trend'], markets: ['XSHG', 'XSHE', 'XHKG', 'XNAS', 'XNYS'], instruments: ['equity'], maxQuoteBatch: 60, credential: 'none', description: '腾讯公开接口:免凭据,行情/K线/分时备源,非官方无SLA', endpointKeys: [{ key: 'quotes', label: '行情批量' }, { key: 'kline', label: 'K线历史' }, { key: 'trend', label: '分时' }] },
|
|
40
|
+
async probe(request, ctx) {
|
|
41
|
+
// kline 探针直接拉代表证券 3 根日K(quotes 不覆盖港股);quotes 探针沿用代表证券行。
|
|
42
|
+
if (request.capability === 'kline') {
|
|
43
|
+
const code = { XSHG: '600519', XSHE: '000001', XHKG: '00700' }[request.market]
|
|
44
|
+
if (!code) throw new StockError('UNSUPPORTED_CAPABILITY', '腾讯来源不提供该市场K线', 422)
|
|
45
|
+
const result = await this.kline({ ...request, securityId: `${request.market}:equity:${code}`, code, period: '1d', adjust: 'qfq', limit: 3 }, ctx)
|
|
46
|
+
if (!result.candles.length) throw new StockError('NO_DATA', '来源未返回可校验数据,暂不能确认能力就绪', 422)
|
|
47
|
+
return { status: 'ready', capability: 'kline', market: request.market, instrument: 'equity' }
|
|
48
|
+
}
|
|
49
|
+
// 分时探针拉一次代表证券的当日分钟线: 美股没有分钟线, 直接判不支持
|
|
50
|
+
if (request.capability === 'trend') {
|
|
51
|
+
const code = { XSHG: '600519', XSHE: '000001', XHKG: '00700' }[request.market]
|
|
52
|
+
if (!code) throw new StockError('UNSUPPORTED_CAPABILITY', '腾讯来源不提供该市场分时', 422)
|
|
53
|
+
const result = await this.trend({ ...request, securityId: `${request.market}:equity:${code}`, code }, ctx)
|
|
54
|
+
if (!result.candles.length) throw new StockError('NO_DATA', '来源未返回可校验数据,暂不能确认能力就绪', 422)
|
|
55
|
+
return { status: 'ready', capability: 'trend', market: request.market, instrument: 'equity' }
|
|
56
|
+
}
|
|
57
|
+
const PROBE = { XSHG: '600519', XSHE: '000001', XHKG: '00700', XNAS: 'AAPL', XNYS: 'BABA' }
|
|
58
|
+
const security = request.securities?.[0] || { exchange: request.market, code: PROBE[request.market] || '000001' }
|
|
59
|
+
const rows = await this.quotes({ ...request, securities: [security] }, ctx)
|
|
60
|
+
if (!rows.items.length) throw new StockError('NO_DATA', '来源未返回可校验数据,暂不能确认能力就绪', 422)
|
|
61
|
+
return { status: 'ready', capability: 'quotes', market: request.market, instrument: 'equity' }
|
|
62
|
+
},
|
|
63
|
+
async quotes(request, ctx) {
|
|
64
|
+
const symbols = new Map(request.securities.map(s => [symbolOf(s), s]))
|
|
65
|
+
let response
|
|
66
|
+
try {
|
|
67
|
+
response = await ctx.fetch(endpointOf(ctx, 'quotes') + [...symbols.keys()].join(','), { headers: { 'User-Agent': 'Mozilla/5.0' }, signal: ctx.signal, redirect: 'error' })
|
|
68
|
+
} catch (e) {
|
|
69
|
+
if (ctx.signal.aborted) throw new StockError('CANCELLED', '请求已取消', 503)
|
|
70
|
+
if (e instanceof StockError) throw e
|
|
71
|
+
throw new StockError('NETWORK', '无法连接行情来源', 502, { retryable: true })
|
|
72
|
+
}
|
|
73
|
+
if (!response.ok) throw new StockError('NETWORK', '来源服务暂不可用', 502, { retryable: true })
|
|
74
|
+
const text = new TextDecoder('gbk').decode(await response.arrayBuffer())
|
|
75
|
+
const seen = new Set(), items = []
|
|
76
|
+
for (const line of text.split(';')) {
|
|
77
|
+
const match = /v_((?:sh|sz|hk)\d{5,6}|us[A-Za-z.]+)="([^"]*)"/.exec(line)
|
|
78
|
+
if (!match) continue
|
|
79
|
+
const providerSymbol = match[1], security = symbols.get(providerSymbol)
|
|
80
|
+
if (!security) continue
|
|
81
|
+
if (seen.has(providerSymbol)) throw new StockError('BAD_PAYLOAD', '报价身份冲突', 502)
|
|
82
|
+
seen.add(providerSymbol)
|
|
83
|
+
const f = match[2].split('~')
|
|
84
|
+
if (f.length < 38) throw new StockError('BAD_PAYLOAD', '来源字段数量异常', 502)
|
|
85
|
+
const volume = num(f[36]), amount = num(f[37])
|
|
86
|
+
items.push(normalizeQuote({
|
|
87
|
+
securityId: security.id, providerInstanceId: request.providerInstanceId, adapterId: 'tencent', providerSymbol,
|
|
88
|
+
last: f[3], previousClose: f[4], open: f[5], high: f[33], low: f[34],
|
|
89
|
+
volume: volume === null ? null : String(sharesFromLots(volume, security.exchange)), volumeUnit: 'share',
|
|
90
|
+
amount: amount === null ? null : String(amountFromWan(amount, security.exchange)), amountUnit: MARKET_META[security.exchange]?.currency || 'CNY',
|
|
91
|
+
quoteAt: parseQuoteTime(quoteStamp(f[30])), timestampKind: 'trade',
|
|
92
|
+
receivedAt: ctx.now(), delayKind: 'unknown', delaySeconds: null, securityState: 'unknown',
|
|
93
|
+
}))
|
|
94
|
+
}
|
|
95
|
+
return { providerInstanceId: request.providerInstanceId, fetchedAt: ctx.now(), items, errors: request.securities.filter(s => !seen.has(symbolOf(s))).map(s => ({ securityId: s.id, code: 'NO_DATA', message: '来源未返回此证券报价' })) }
|
|
96
|
+
},
|
|
97
|
+
async kline(request, ctx) {
|
|
98
|
+
let symbol = klineSymbolOf(request)
|
|
99
|
+
if (request.market === 'XNAS' || request.market === 'XNYS') {
|
|
100
|
+
const mapped = ctx.usSymbols?.get(`US:${request.code}`)
|
|
101
|
+
const suffix = mapped ? JYS_TO_SUFFIX[mapped.jys] : undefined
|
|
102
|
+
if (suffix === undefined) throw new StockError('UNSUPPORTED_CAPABILITY', '腾讯来源的美股K线需先经搜索建立代码映射', 422)
|
|
103
|
+
symbol = suffix ? `us${request.code}.${suffix}` : `us${request.code}`
|
|
104
|
+
}
|
|
105
|
+
const period = { '1d': 'day', '1w': 'week', '1M': 'month' }[request.period]
|
|
106
|
+
if (!period) throw new StockError('INVALID_PARAM', '腾讯 K 线只支持日/周/月,分时请走分时能力', 400)
|
|
107
|
+
const param = `${symbol},${period},,,${request.limit},qfq`
|
|
108
|
+
let response
|
|
109
|
+
try {
|
|
110
|
+
response = await ctx.fetch(`${endpointOf(ctx, 'kline')}?param=${param}`, { headers: { Referer: 'https://gu.qq.com/', 'User-Agent': 'Mozilla/5.0' }, signal: ctx.signal, redirect: 'error' })
|
|
111
|
+
} catch (e) {
|
|
112
|
+
if (ctx.signal.aborted) throw new StockError('CANCELLED', '请求已取消', 503)
|
|
113
|
+
if (e instanceof StockError) throw e
|
|
114
|
+
throw new StockError('NETWORK', '无法连接行情来源', 502, { retryable: true })
|
|
115
|
+
}
|
|
116
|
+
if (!response.ok) throw new StockError('NETWORK', '来源服务暂不可用', 502, { retryable: true })
|
|
117
|
+
const body = await response.json().catch(() => { throw new StockError('BAD_PAYLOAD', '来源响应不是JSON', 502) })
|
|
118
|
+
const data = body?.data?.[symbol]
|
|
119
|
+
const rows = data && firstArray(data)
|
|
120
|
+
if (!Array.isArray(rows) || !rows.length) throw new StockError('NO_DATA', '来源未返回此证券K线', 422)
|
|
121
|
+
const candles = []
|
|
122
|
+
let prevTime = ''
|
|
123
|
+
for (const row of rows) {
|
|
124
|
+
if (!Array.isArray(row) || row.length < 6) throw new StockError('BAD_PAYLOAD', 'K线列数不足', 502)
|
|
125
|
+
if (String(row[0]) <= prevTime) throw new StockError('BAD_PAYLOAD', 'K线时间戳重复或乱序', 502)
|
|
126
|
+
prevTime = String(row[0])
|
|
127
|
+
candles.push({ time: String(row[0]), open: num(row[1]), close: num(row[2]), high: num(row[3]), low: num(row[4]), volume: sharesFromLots(num(row[5]), request.market) })
|
|
128
|
+
}
|
|
129
|
+
// preClose 实测定案: data.{symbol}.qt.{symbol}[4] 为昨收(2026-10-30 实测 sz000001 值 11.54 与东财 f18 一致)。
|
|
130
|
+
const qt = Array.isArray(data?.qt?.[symbol]) ? data.qt[symbol] : null
|
|
131
|
+
const preClose = qt ? num(qt[4]) : null
|
|
132
|
+
return { providerInstanceId: request.providerInstanceId, fetchedAt: ctx.now(), complete: true, preClose, candles }
|
|
133
|
+
},
|
|
134
|
+
// 分时(备源): minute/query 给当日逐分钟价格/量/额。腾讯的分时没有开高低与均价,
|
|
135
|
+
// 移位填成同一价, 客户端按 OHLC 校验时才不会把每根丢掉。
|
|
136
|
+
async trend(request, ctx) {
|
|
137
|
+
const symbol = klineSymbolOf(request)
|
|
138
|
+
if (!SYMBOL_PREFIX[request.market]) throw new StockError('UNSUPPORTED_CAPABILITY', '腾讯分时只覆盖沪深港', 422)
|
|
139
|
+
let response
|
|
140
|
+
try {
|
|
141
|
+
response = await ctx.fetch(endpointOf(ctx, 'trend') + symbol, { headers: { Referer: 'https://gu.qq.com/', 'User-Agent': 'Mozilla/5.0' }, signal: ctx.signal, redirect: 'error' })
|
|
142
|
+
} catch (e) {
|
|
143
|
+
if (ctx.signal.aborted) throw new StockError('CANCELLED', '请求已取消', 503)
|
|
144
|
+
if (e instanceof StockError) throw e
|
|
145
|
+
throw new StockError('NETWORK', '无法连接行情来源', 502, { retryable: true })
|
|
146
|
+
}
|
|
147
|
+
if (!response.ok) throw new StockError('NETWORK', '来源服务暂不可用', 502, { retryable: true })
|
|
148
|
+
const body = await response.json().catch(() => { throw new StockError('BAD_PAYLOAD', '来源响应不是JSON', 502) })
|
|
149
|
+
const data = body?.data?.[symbol]?.data
|
|
150
|
+
const rows = Array.isArray(data?.data) ? data.data : []
|
|
151
|
+
const day = /^(\d{4})(\d{2})(\d{2})$/.exec(String(data?.date || ''))
|
|
152
|
+
if (!rows.length || !day) throw new StockError('NO_DATA', '来源未返回此证券分时', 422)
|
|
153
|
+
const stamp = `${day[1]}-${day[2]}-${day[3]}`
|
|
154
|
+
const candles = []
|
|
155
|
+
for (const row of rows) {
|
|
156
|
+
const cols = String(row).split(' ')
|
|
157
|
+
// 价格必须是纯数字才收: 上游偶有畸形行, 与其把 NaN 画进图里, 不如少一点
|
|
158
|
+
if (!/^\d{3,4}$/.test(cols[0] || '') || !/^\d+(\.\d+)?$/.test(cols[1] || '')) continue
|
|
159
|
+
const time = `${cols[0].padStart(4, '0').slice(0, 2)}:${cols[0].padStart(4, '0').slice(2)}`
|
|
160
|
+
const price = num(cols[1])
|
|
161
|
+
if (price == null) continue
|
|
162
|
+
candles.push({ time, at: zonedUnixSeconds(`${stamp} ${time}`, SOURCE_ZONE), open: price, close: price, high: price, low: price, volume: sharesFromLots(num(cols[2]), request.market), amount: num(cols[3]), avg: null })
|
|
163
|
+
}
|
|
164
|
+
if (!candles.length) throw new StockError('NO_DATA', '来源分时数据不可解析', 422)
|
|
165
|
+
const qt = Array.isArray(body?.data?.[symbol]?.qt?.[symbol]) ? body.data[symbol].qt[symbol] : null
|
|
166
|
+
return { providerInstanceId: request.providerInstanceId, fetchedAt: ctx.now(), complete: true, preClose: qt ? num(qt[4]) : null, candles }
|
|
167
|
+
},
|
|
168
|
+
}
|
|
@@ -1,92 +1,92 @@
|
|
|
1
|
-
import { makeSecurity, normalizeQuote, parseQuoteTime, StockError } from '../market-model.mjs'
|
|
2
|
-
const EXCHANGE = { XSHG: 'SSE', XSHE: 'SZSE' }
|
|
3
|
-
const SUFFIX = { XSHG: 'SH', XSHE: 'SZ' }
|
|
4
|
-
const FIELD = {
|
|
5
|
-
quotes: 'ts_code,name,pre_close,open,high,low,close,vol,amount,trade_time',
|
|
6
|
-
catalog: 'ts_code,symbol,name,cnspell,market,exchange,curr_type,list_status,list_date',
|
|
7
|
-
calendar: 'exchange,cal_date,is_open,pretrade_date',
|
|
8
|
-
}
|
|
9
|
-
const API = { quotes: 'rt_k', catalog: 'stock_basic', calendar: 'trade_cal' }
|
|
10
|
-
function bad() { throw new StockError('BAD_PAYLOAD', '行情来源响应格式异常', 502) }
|
|
11
|
-
async function query(capability, params, ctx) {
|
|
12
|
-
let response
|
|
13
|
-
try {
|
|
14
|
-
response = await ctx.fetch('https://api.tushare.pro', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ api_name: API[capability], token: ctx.credential(), params, fields: FIELD[capability] }), signal: ctx.signal, redirect: 'error' })
|
|
15
|
-
} catch (e) {
|
|
16
|
-
if (ctx.signal.aborted) throw new StockError('CANCELLED', '请求已取消', 503)
|
|
17
|
-
if (e instanceof StockError) throw e
|
|
18
|
-
throw new StockError('NETWORK', '无法连接行情来源', 502, { retryable: true })
|
|
19
|
-
}
|
|
20
|
-
if (response.status === 429) {
|
|
21
|
-
const retry = response.headers.get('retry-after'), seconds = Number(retry)
|
|
22
|
-
const ms = retry && Number.isFinite(seconds) ? seconds * 1000 : retry ? Date.parse(retry) - ctx.now() : 60 * 1000
|
|
23
|
-
throw new StockError('RATE_LIMIT', '来源请求额度受限', 429, { retryable: true, retryAfterMs: Math.max(1000, ms || 60 * 1000) })
|
|
24
|
-
}
|
|
25
|
-
if (!response.ok) throw new StockError('NETWORK', '来源服务暂不可用', 502, { retryable: true })
|
|
26
|
-
const body = await response.json().catch(bad)
|
|
27
|
-
if (body?.code !== 0) {
|
|
28
|
-
const code = body?.code === 40101 || /token.*(无效|过期|invalid)|认证/i.test(String(body?.msg)) ? 'AUTH' : body?.code === 2002 ? 'PERMISSION' : /频|limit/i.test(String(body?.msg)) ? 'RATE_LIMIT' : 'BAD_PAYLOAD'
|
|
29
|
-
throw new StockError(code, code === 'AUTH' ? '来源认证失败,请检查Host环境凭据' : code === 'PERMISSION' ? '当前账号未开通该数据能力' : code === 'RATE_LIMIT' ? '来源请求额度受限' : '来源拒绝了请求', code === 'RATE_LIMIT' ? 429 : 502, { retryAfterMs: code === 'RATE_LIMIT' ? 60 * 1000 : null })
|
|
30
|
-
}
|
|
31
|
-
const data = body.data
|
|
32
|
-
if (!Array.isArray(data?.fields) || !Array.isArray(data?.items) || new Set(data.fields).size !== data.fields.length || data.fields.some(k => typeof k !== 'string')) bad()
|
|
33
|
-
return data.items.map(row => {
|
|
34
|
-
if (!Array.isArray(row) || row.length !== data.fields.length) bad()
|
|
35
|
-
return Object.fromEntries(data.fields.map((key, i) => [key, row[i]]))
|
|
36
|
-
})
|
|
37
|
-
}
|
|
38
|
-
function symbol(security) { return `${security.code}.${SUFFIX[security.exchange]}` }
|
|
39
|
-
export const tushare = {
|
|
40
|
-
descriptor: { adapterId: 'tushare', capabilities: ['quotes', 'catalog', 'calendar'], markets: ['XSHG', 'XSHE'], instruments: ['equity'], maxQuoteBatch: 20, credential: 'DSH_STOCK_TUSHARE_TOKEN', description: 'Tushare Pro:需配置凭据,沪深目录/日历/行情,有SLA' },
|
|
41
|
-
async catalog(request, ctx) {
|
|
42
|
-
let rows = await query('catalog', { exchange: EXCHANGE[request.market], list_status: 'L' }, ctx)
|
|
43
|
-
let complete = rows.length < 6000
|
|
44
|
-
if (!complete) {
|
|
45
|
-
rows = []; complete = true
|
|
46
|
-
for (const market of request.market === 'XSHG' ? ['主板', '科创板'] : ['主板', '创业板']) {
|
|
47
|
-
const part = await query('catalog', { exchange: EXCHANGE[request.market], list_status: 'L', market }, ctx)
|
|
48
|
-
rows.push(...part); complete &&= part.length < 6000
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
const items = [], seen = new Set()
|
|
52
|
-
for (const row of rows) {
|
|
53
|
-
if (row.exchange !== EXCHANGE[request.market] || row.curr_type !== 'CNY' || row.list_status !== 'L' || !['主板', '创业板', '科创板'].includes(row.market)) continue
|
|
54
|
-
if (typeof row.symbol !== 'string' || !/^\d{6}$/.test(row.symbol) || typeof row.name !== 'string' || !row.name || row.ts_code !== `${row.symbol}.${SUFFIX[request.market]}`) bad()
|
|
55
|
-
if (seen.has(row.ts_code)) bad()
|
|
56
|
-
seen.add(row.ts_code)
|
|
57
|
-
items.push(makeSecurity(request.market, row.symbol, row.name, { cnspell: typeof row.cnspell === 'string' ? row.cnspell.toLowerCase() : '', catalogSource: request.providerInstanceId }))
|
|
58
|
-
}
|
|
59
|
-
return { providerInstanceId: request.providerInstanceId, fetchedAt: ctx.now(), items, errors: [], complete }
|
|
60
|
-
},
|
|
61
|
-
async calendar(request, ctx) {
|
|
62
|
-
const rows = await query('calendar', { exchange: EXCHANGE[request.market], start_date: request.startDate.replaceAll('-', ''), end_date: request.endDate.replaceAll('-', '') }, ctx)
|
|
63
|
-
const date = value => typeof value === 'string' && /^\d{8}$/.test(value) ? `${value.slice(0, 4)}-${value.slice(4, 6)}-${value.slice(6, 8)}` : null
|
|
64
|
-
const items = rows.map(row => {
|
|
65
|
-
if (row.exchange !== EXCHANGE[request.market] || !date(row.cal_date) || ![0, 1, '0', '1'].includes(row.is_open)) bad()
|
|
66
|
-
return { exchange: request.market, date: date(row.cal_date), isOpen: String(row.is_open) === '1', previousOpenDate: date(row.pretrade_date), source: request.providerInstanceId }
|
|
67
|
-
})
|
|
68
|
-
return { providerInstanceId: request.providerInstanceId, fetchedAt: ctx.now(), items, errors: [] }
|
|
69
|
-
},
|
|
70
|
-
async probe(request, ctx) {
|
|
71
|
-
const { capability, market } = request
|
|
72
|
-
const security = makeSecurity(market, market === 'XSHG' ? '600519' : '000001', '权限检查证券')
|
|
73
|
-
const today = new Date(ctx.now() + 8 * 60 * 60 * 1000).toISOString().slice(0, 10)
|
|
74
|
-
const result = await this[capability]({ ...request, securities: [security], startDate: today, endDate: today }, ctx)
|
|
75
|
-
if (!result.items.length) throw new StockError('NO_DATA', '来源未返回可校验数据,暂不能确认能力就绪', 422)
|
|
76
|
-
return { status: 'ready', capability, market, instrument: 'equity' }
|
|
77
|
-
},
|
|
78
|
-
async quotes(request, ctx) {
|
|
79
|
-
const rows = await query('quotes', { ts_code: request.securities.map(symbol).join(',') }, ctx)
|
|
80
|
-
const securities = new Map(request.securities.map(s => [symbol(s), s])), seen = new Set(), items = []
|
|
81
|
-
for (const row of rows) {
|
|
82
|
-
if (!securities.has(row.ts_code)) continue
|
|
83
|
-
if (seen.has(row.ts_code) || !Object.hasOwn(row, 'close') || !Object.hasOwn(row, 'pre_close')) bad()
|
|
84
|
-
seen.add(row.ts_code)
|
|
85
|
-
const security = securities.get(row.ts_code)
|
|
86
|
-
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 == null ? null : String(Number(row.vol) * 100), volumeUnit: 'share', amount: row.amount == null ? null : String(row.amount), amountUnit: 'CNY',
|
|
88
|
-
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
|
-
}
|
|
90
|
-
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: '来源未返回此证券报价' })) }
|
|
91
|
-
},
|
|
92
|
-
}
|
|
1
|
+
import { makeSecurity, normalizeQuote, parseQuoteTime, StockError } from '../market-model.mjs'
|
|
2
|
+
const EXCHANGE = { XSHG: 'SSE', XSHE: 'SZSE' }
|
|
3
|
+
const SUFFIX = { XSHG: 'SH', XSHE: 'SZ' }
|
|
4
|
+
const FIELD = {
|
|
5
|
+
quotes: 'ts_code,name,pre_close,open,high,low,close,vol,amount,trade_time',
|
|
6
|
+
catalog: 'ts_code,symbol,name,cnspell,market,exchange,curr_type,list_status,list_date',
|
|
7
|
+
calendar: 'exchange,cal_date,is_open,pretrade_date',
|
|
8
|
+
}
|
|
9
|
+
const API = { quotes: 'rt_k', catalog: 'stock_basic', calendar: 'trade_cal' }
|
|
10
|
+
function bad() { throw new StockError('BAD_PAYLOAD', '行情来源响应格式异常', 502) }
|
|
11
|
+
async function query(capability, params, ctx) {
|
|
12
|
+
let response
|
|
13
|
+
try {
|
|
14
|
+
response = await ctx.fetch('https://api.tushare.pro', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ api_name: API[capability], token: ctx.credential(), params, fields: FIELD[capability] }), signal: ctx.signal, redirect: 'error' })
|
|
15
|
+
} catch (e) {
|
|
16
|
+
if (ctx.signal.aborted) throw new StockError('CANCELLED', '请求已取消', 503)
|
|
17
|
+
if (e instanceof StockError) throw e
|
|
18
|
+
throw new StockError('NETWORK', '无法连接行情来源', 502, { retryable: true })
|
|
19
|
+
}
|
|
20
|
+
if (response.status === 429) {
|
|
21
|
+
const retry = response.headers.get('retry-after'), seconds = Number(retry)
|
|
22
|
+
const ms = retry && Number.isFinite(seconds) ? seconds * 1000 : retry ? Date.parse(retry) - ctx.now() : 60 * 1000
|
|
23
|
+
throw new StockError('RATE_LIMIT', '来源请求额度受限', 429, { retryable: true, retryAfterMs: Math.max(1000, ms || 60 * 1000) })
|
|
24
|
+
}
|
|
25
|
+
if (!response.ok) throw new StockError('NETWORK', '来源服务暂不可用', 502, { retryable: true })
|
|
26
|
+
const body = await response.json().catch(bad)
|
|
27
|
+
if (body?.code !== 0) {
|
|
28
|
+
const code = body?.code === 40101 || /token.*(无效|过期|invalid)|认证/i.test(String(body?.msg)) ? 'AUTH' : body?.code === 2002 ? 'PERMISSION' : /频|limit/i.test(String(body?.msg)) ? 'RATE_LIMIT' : 'BAD_PAYLOAD'
|
|
29
|
+
throw new StockError(code, code === 'AUTH' ? '来源认证失败,请检查Host环境凭据' : code === 'PERMISSION' ? '当前账号未开通该数据能力' : code === 'RATE_LIMIT' ? '来源请求额度受限' : '来源拒绝了请求', code === 'RATE_LIMIT' ? 429 : 502, { retryAfterMs: code === 'RATE_LIMIT' ? 60 * 1000 : null })
|
|
30
|
+
}
|
|
31
|
+
const data = body.data
|
|
32
|
+
if (!Array.isArray(data?.fields) || !Array.isArray(data?.items) || new Set(data.fields).size !== data.fields.length || data.fields.some(k => typeof k !== 'string')) bad()
|
|
33
|
+
return data.items.map(row => {
|
|
34
|
+
if (!Array.isArray(row) || row.length !== data.fields.length) bad()
|
|
35
|
+
return Object.fromEntries(data.fields.map((key, i) => [key, row[i]]))
|
|
36
|
+
})
|
|
37
|
+
}
|
|
38
|
+
function symbol(security) { return `${security.code}.${SUFFIX[security.exchange]}` }
|
|
39
|
+
export const tushare = {
|
|
40
|
+
descriptor: { adapterId: 'tushare', capabilities: ['quotes', 'catalog', 'calendar'], markets: ['XSHG', 'XSHE'], instruments: ['equity'], maxQuoteBatch: 20, credential: 'DSH_STOCK_TUSHARE_TOKEN', description: 'Tushare Pro:需配置凭据,沪深目录/日历/行情,有SLA' },
|
|
41
|
+
async catalog(request, ctx) {
|
|
42
|
+
let rows = await query('catalog', { exchange: EXCHANGE[request.market], list_status: 'L' }, ctx)
|
|
43
|
+
let complete = rows.length < 6000
|
|
44
|
+
if (!complete) {
|
|
45
|
+
rows = []; complete = true
|
|
46
|
+
for (const market of request.market === 'XSHG' ? ['主板', '科创板'] : ['主板', '创业板']) {
|
|
47
|
+
const part = await query('catalog', { exchange: EXCHANGE[request.market], list_status: 'L', market }, ctx)
|
|
48
|
+
rows.push(...part); complete &&= part.length < 6000
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
const items = [], seen = new Set()
|
|
52
|
+
for (const row of rows) {
|
|
53
|
+
if (row.exchange !== EXCHANGE[request.market] || row.curr_type !== 'CNY' || row.list_status !== 'L' || !['主板', '创业板', '科创板'].includes(row.market)) continue
|
|
54
|
+
if (typeof row.symbol !== 'string' || !/^\d{6}$/.test(row.symbol) || typeof row.name !== 'string' || !row.name || row.ts_code !== `${row.symbol}.${SUFFIX[request.market]}`) bad()
|
|
55
|
+
if (seen.has(row.ts_code)) bad()
|
|
56
|
+
seen.add(row.ts_code)
|
|
57
|
+
items.push(makeSecurity(request.market, row.symbol, row.name, { cnspell: typeof row.cnspell === 'string' ? row.cnspell.toLowerCase() : '', catalogSource: request.providerInstanceId }))
|
|
58
|
+
}
|
|
59
|
+
return { providerInstanceId: request.providerInstanceId, fetchedAt: ctx.now(), items, errors: [], complete }
|
|
60
|
+
},
|
|
61
|
+
async calendar(request, ctx) {
|
|
62
|
+
const rows = await query('calendar', { exchange: EXCHANGE[request.market], start_date: request.startDate.replaceAll('-', ''), end_date: request.endDate.replaceAll('-', '') }, ctx)
|
|
63
|
+
const date = value => typeof value === 'string' && /^\d{8}$/.test(value) ? `${value.slice(0, 4)}-${value.slice(4, 6)}-${value.slice(6, 8)}` : null
|
|
64
|
+
const items = rows.map(row => {
|
|
65
|
+
if (row.exchange !== EXCHANGE[request.market] || !date(row.cal_date) || ![0, 1, '0', '1'].includes(row.is_open)) bad()
|
|
66
|
+
return { exchange: request.market, date: date(row.cal_date), isOpen: String(row.is_open) === '1', previousOpenDate: date(row.pretrade_date), source: request.providerInstanceId }
|
|
67
|
+
})
|
|
68
|
+
return { providerInstanceId: request.providerInstanceId, fetchedAt: ctx.now(), items, errors: [] }
|
|
69
|
+
},
|
|
70
|
+
async probe(request, ctx) {
|
|
71
|
+
const { capability, market } = request
|
|
72
|
+
const security = makeSecurity(market, market === 'XSHG' ? '600519' : '000001', '权限检查证券')
|
|
73
|
+
const today = new Date(ctx.now() + 8 * 60 * 60 * 1000).toISOString().slice(0, 10)
|
|
74
|
+
const result = await this[capability]({ ...request, securities: [security], startDate: today, endDate: today }, ctx)
|
|
75
|
+
if (!result.items.length) throw new StockError('NO_DATA', '来源未返回可校验数据,暂不能确认能力就绪', 422)
|
|
76
|
+
return { status: 'ready', capability, market, instrument: 'equity' }
|
|
77
|
+
},
|
|
78
|
+
async quotes(request, ctx) {
|
|
79
|
+
const rows = await query('quotes', { ts_code: request.securities.map(symbol).join(',') }, ctx)
|
|
80
|
+
const securities = new Map(request.securities.map(s => [symbol(s), s])), seen = new Set(), items = []
|
|
81
|
+
for (const row of rows) {
|
|
82
|
+
if (!securities.has(row.ts_code)) continue
|
|
83
|
+
if (seen.has(row.ts_code) || !Object.hasOwn(row, 'close') || !Object.hasOwn(row, 'pre_close')) bad()
|
|
84
|
+
seen.add(row.ts_code)
|
|
85
|
+
const security = securities.get(row.ts_code)
|
|
86
|
+
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 == null ? null : String(Number(row.vol) * 100), volumeUnit: 'share', amount: row.amount == null ? null : String(row.amount), amountUnit: 'CNY',
|
|
88
|
+
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
|
+
}
|
|
90
|
+
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: '来源未返回此证券报价' })) }
|
|
91
|
+
},
|
|
92
|
+
}
|
package/src/recovery.mjs
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
// 降级后回头试上级: 后台定时跑, 不占用户请求时间, 也不用业务请求去猜上游好坏。
|
|
2
|
+
// 每个适配器自己实现探针(probe), 这里只负责按路由顺序点名、把汇报交给路由器。
|
|
3
|
+
export const RECOVERY_RETRY_MS = 20 * 1000
|
|
4
|
+
export function createRecovery({ getConfig, router, executor }) {
|
|
5
|
+
return async function probeRecovery() {
|
|
6
|
+
// 用户请求在跑时整轮跳过: 探测排在别人的超时后面会把详情页请求推到 10 秒线上
|
|
7
|
+
if (!executor.idle()) return
|
|
8
|
+
for (const route of getConfig().routes) {
|
|
9
|
+
if (route.failoverMode !== 'network') continue
|
|
10
|
+
const epoch = router.selections()[route.id]?.routeEpoch
|
|
11
|
+
if (epoch === undefined) continue
|
|
12
|
+
for (const id of router.recoveryCandidates(route.id)) {
|
|
13
|
+
const instance = getConfig().providers.find(p => p.id === id && p.enabled !== false && p.budget?.requestsPerMinute !== null)
|
|
14
|
+
if (!instance) continue
|
|
15
|
+
let ready = false
|
|
16
|
+
try {
|
|
17
|
+
const result = await executor.run(instance, route.capability, { market: route.market, instrument: route.instrument }, { probe: true })
|
|
18
|
+
// 探针必须由同名能力产出: 适配器拿别的能力冒充时不能当就绪
|
|
19
|
+
ready = result?.status === 'ready' && result.capability === route.capability
|
|
20
|
+
} catch {}
|
|
21
|
+
try { router.recordProbe(route.id, id, ready, epoch) } catch { break }
|
|
22
|
+
if (ready) break
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// 探测节奏跟着面板走: 有人看才探, 没人看就停; 每次重新活跃先立刻探一次, 不用干等一个周期。
|
|
29
|
+
// 上一轮没跑完就跳过这一轮: 探测要逐个实例打上游, 一轮可能比周期还长。
|
|
30
|
+
// 用户请求在跑时短重试, 不占首屏的队列
|
|
31
|
+
export function createRecoveryLoop({ probe, timers, interval, canRun = () => true }) {
|
|
32
|
+
let timer = null, retry = null, running = false, busy = false, stopped = false, inflight = Promise.resolve()
|
|
33
|
+
const run = () => {
|
|
34
|
+
if (stopped || busy) return
|
|
35
|
+
if (!canRun()) {
|
|
36
|
+
if (retry) return
|
|
37
|
+
retry = timers.setTimeout?.(() => { retry = null; run() }, RECOVERY_RETRY_MS) ?? null
|
|
38
|
+
retry?.unref?.()
|
|
39
|
+
return
|
|
40
|
+
}
|
|
41
|
+
busy = true
|
|
42
|
+
inflight = Promise.resolve().then(probe).catch(() => {}).finally(() => { busy = false })
|
|
43
|
+
}
|
|
44
|
+
const stop = () => {
|
|
45
|
+
stopped = true
|
|
46
|
+
if (timer) timers.clearInterval?.(timer)
|
|
47
|
+
if (retry) timers.clearTimeout?.(retry)
|
|
48
|
+
timer = null; retry = null; running = false
|
|
49
|
+
}
|
|
50
|
+
return {
|
|
51
|
+
sync(active) {
|
|
52
|
+
if (active === running) return
|
|
53
|
+
if (!active) return stop()
|
|
54
|
+
stopped = false
|
|
55
|
+
run()
|
|
56
|
+
timer = timers.setInterval?.(run, interval) ?? null
|
|
57
|
+
timer?.unref?.()
|
|
58
|
+
running = true
|
|
59
|
+
},
|
|
60
|
+
// 在飞的那一轮, 关闭时等它收尾
|
|
61
|
+
idle: () => inflight,
|
|
62
|
+
stop,
|
|
63
|
+
}
|
|
64
|
+
}
|