@mzzsfy/dsh-stock-assistant 0.0.0-stage → 0.3.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.
@@ -0,0 +1,234 @@
1
+ // 东财公开行情接口适配器:quotes/catalog/search/kline。非官方端点,无SLA;延迟未知,f124为来源秒级时间戳。
2
+ import { normalizeQuote, makeSecurity, securityId, StockError, MARKET_META, sharesFromLots } from '../market-model.mjs'
3
+ // 官方默认端点表(key 供 instance.endpoints 覆盖, 反代/镜像场景由 ctx.endpoints 提供同名 key)
4
+ const DEFAULT_ENDPOINTS = {
5
+ quotes: 'https://push2.eastmoney.com/api/qt/ulist.np/get',
6
+ list: 'https://push2.eastmoney.com/api/qt/clist/get',
7
+ search: 'https://searchapi.eastmoney.com/api/suggest/get',
8
+ kline: 'https://push2his.eastmoney.com/api/qt/stock/kline/get',
9
+ trend: 'https://push2his.eastmoney.com/api/qt/stock/trends2/get',
10
+ }
11
+ const endpointOf = (ctx, key) => ctx.endpoints?.[key] || DEFAULT_ENDPOINTS[key]
12
+ // 东财市场代码:XSHG=1,XSHE=0;美股 secid 前缀由搜索 MktNum 动态归属(usSymbols),其余市场实测前缀。
13
+ const MARKET = { XSHG: '1', XSHE: '0' }
14
+ // 搜索联想 MktNum→交易所全集(实测: 1/0 沪深, 116 港, 105/106/107 美三大, 176/177/155 日韩英)
15
+ const SEARCH_EXCHANGE = { 1: 'XSHG', 0: 'XSHE', 116: 'XHKG', 105: 'XNAS', 106: 'XNYS', 107: 'XNYS', 176: 'XJPX', 177: 'XKRX', 155: 'XLON' }
16
+ const SECID_PREFIX = { XSHG: '1', XSHE: '0', XHKG: '116', XNAS: '105', XNYS: '106', XJPX: '176', XKRX: '177', XLON: '155' }
17
+ const US_DEFAULT_MKT = '105'
18
+ // 美股三大市场号: 105 纳斯达克 / 106 纽约 / 107 美交所。secid 前缀必须精确匹配, 探针期据此逐个试探。
19
+ const US_MKTNUMS = ['105', '106', '107']
20
+ const isUSExchange = exchange => exchange === 'XNAS' || exchange === 'XNYS'
21
+ // klt 周期映射(实测): 日101/周102/月103; trends2 无 klt。
22
+ const KLT = { '1d': 101, '1w': 102, '1M': 103 }
23
+ // 目录 fs 按市场给出; 英股 m:155 含债券与结构性产品, 加 t:1 只取股票; 日韩不支持 t: 细分, 全量即股票
24
+ const LIST_FS = { XSHG: 'm:1+t:2,m:1+t:23', XSHE: 'm:0+t:6,m:0+t:80', XHKG: 'm:116+t:3,m:116+t:4', XNAS: 'm:105+t:1', XNYS: 'm:106+t:1,m:107+t:1', XJPX: 'm:176', XKRX: 'm:177', XLON: 'm:155+t:1' }
25
+ const SYMBOL_PREFIX = { 1: 'XSHG', 0: 'XSHE', 116: 'XHKG', 105: 'XNAS', 106: 'XNYS', 107: 'XNYS', 176: 'XJPX', 177: 'XKRX', 155: 'XLON' }
26
+ // 探针代表证券(实测可用的各市场流动性代表),quotes/kline 探针按市场取用。
27
+ const PROBE_SECURITY = { XSHG: '600519', XSHE: '000001', XHKG: '00700', XNAS: 'AAPL', XNYS: 'BABA', XJPX: '7203', XKRX: '005930', XLON: 'SHEL' }
28
+ // klines CSV 前 7 列固定语义(实测 fields2=f51-f57); f53=close 在 f54=high 前为东财原生序。
29
+ const KLINE_FIELDS = 'f51,f52,f53,f54,f55,f56,f57'
30
+ const TREND_FIELDS = 'f51,f52,f53,f54,f55,f56,f57,f58'
31
+ // 分时时间戳的来源时区: 东财统一用北京时间, 与证券所属市场无关
32
+ const SOURCE_ZONE = 'Asia/Shanghai'
33
+ // quotes secid 与 kline secidOf 同源(八市场前缀表);美股 quotes 同样走 usSymbols 动态归属。
34
+ const symbolOf = security => `${SECID_PREFIX[security.exchange]}.${security.code}`
35
+ const num = value => value == null || typeof value === 'number' && !Number.isFinite(value) ? null : value === '-' ? null : String(value)
36
+ async function getJson(ctx, url) {
37
+ let response
38
+ try {
39
+ response = await ctx.fetch(url, { headers: { Referer: 'https://quote.eastmoney.com/', 'User-Agent': 'Mozilla/5.0' }, signal: ctx.signal, redirect: 'error' })
40
+ } catch (e) {
41
+ if (ctx.signal.aborted) throw new StockError('CANCELLED', '请求已取消', 503)
42
+ if (e instanceof StockError) throw e
43
+ throw new StockError('NETWORK', '无法连接行情来源', 502, { retryable: true })
44
+ }
45
+ if (!response.ok) throw new StockError('NETWORK', '来源服务暂不可用', 502, { retryable: true })
46
+ return response.json().catch(() => { throw new StockError('BAD_PAYLOAD', '来源响应不是JSON', 502) })
47
+ }
48
+ export const eastmoney = {
49
+ descriptor: { adapterId: 'eastmoney', capabilities: ['quotes', 'catalog', 'search', 'kline'], markets: ['XSHG', 'XSHE', 'XHKG', 'XNAS', 'XNYS', 'XJPX', 'XKRX', 'XLON'], instruments: ['equity'], maxQuoteBatch: 60, credential: 'none', description: '东方财富公开接口:免凭据,八市场目录,行情/K线/搜索,非官方无SLA', endpointKeys: [{ key: 'quotes', label: '行情批量' }, { key: 'list', label: '证券目录' }, { key: 'search', label: '搜索联想' }, { key: 'kline', label: 'K线历史' }, { key: 'trend', label: '分时' }] },
50
+ async probe(request, ctx) {
51
+ if (request.capability === 'catalog' || request.capability === 'search') {
52
+ // 探针词按市场用代表证券代码(茅台/平安只对沪深有效, 其他市场返回 0 项会误判 denied)。
53
+ const result = await this[request.capability]({ ...request, probe: true, q: PROBE_SECURITY[request.market] || '平安', limit: 5 }, ctx)
54
+ if (!result.items.length) throw new StockError('NO_DATA', '来源未返回可校验数据,暂不能确认能力就绪', 422)
55
+ return { status: 'ready', capability: request.capability, market: request.market, instrument: 'equity' }
56
+ }
57
+ // kline 探针直接拉代表证券 3 根日K(实测列义/端点全链),quotes 探针沿用行情行。
58
+ if (request.capability === 'kline') {
59
+ const code = PROBE_SECURITY[request.market] || '000001'
60
+ const result = await this.kline({ ...request, securityId: `${request.market}:equity:${code}`, code, period: '1d', adjust: 'qfq', limit: 3 }, ctx)
61
+ if (!result.candles.length) throw new StockError('NO_DATA', '来源未返回可校验数据,暂不能确认能力就绪', 422)
62
+ return { status: 'ready', capability: 'kline', market: request.market, instrument: 'equity' }
63
+ }
64
+ // 美股 secid 前缀由搜索建立的映射决定, 探针期还没有映射; 逐个候选前缀试一次, 命中即视为就绪
65
+ const security = request.securities?.[0] || { exchange: request.market, code: PROBE_SECURITY[request.market] || '000001' }
66
+ const candidates = isUSExchange(security.exchange) ? US_MKTNUMS : [null]
67
+ for (const mktNum of candidates) {
68
+ const scope = mktNum ? { ...ctx, usSymbols: new Map([[`US:${security.code}`, { mktNum, at: ctx.now() }]]) } : ctx
69
+ const rows = await this.quotes({ ...request, securities: [security] }, scope)
70
+ if (rows.items.length) return { status: 'ready', capability: 'quotes', market: request.market, instrument: 'equity' }
71
+ }
72
+ throw new StockError('NO_DATA', '来源未返回可校验数据,暂不能确认能力就绪', 422)
73
+ },
74
+ async quotes(request, ctx) {
75
+ // 美股 secid 走 usSymbols 动态归属(miss 默认 NASDAQ);其余市场静态前缀表。
76
+ const secidOf = security => isUSExchange(security.exchange) ? `${ctx.usSymbols?.get(`US:${security.code}`)?.mktNum || US_DEFAULT_MKT}.${security.code}` : `${SECID_PREFIX[security.exchange]}.${security.code}`
77
+ const symbols = new Map(request.securities.map(s => [secidOf(s), s]))
78
+ const body = await getJson(ctx, `${endpointOf(ctx, 'quotes')}?secids=${[...symbols.keys()].join(',')}&fields=f2,f3,f4,f5,f6,f12,f13,f14,f15,f16,f17,f18,f124&fltt=2&invt=2`)
79
+ const rows = body?.data?.diff
80
+ // data:null表示全部secids无效(如整批退市),降级为逐证券缺失,不让单批坏行瘫痪路由。
81
+ if (!Array.isArray(rows)) return { providerInstanceId: request.providerInstanceId, fetchedAt: ctx.now(), items: [], errors: request.securities.map(s => ({ securityId: s.id, code: 'NO_DATA', message: '来源未返回此证券报价' })) }
82
+ const seen = new Set(), items = []
83
+ for (const row of rows) {
84
+ const security = symbols.get(`${row.f13}.${row.f12}`)
85
+ if (!security) continue
86
+ if (seen.has(security.id)) throw new StockError('BAD_PAYLOAD', '报价身份冲突', 502)
87
+ seen.add(security.id)
88
+ // fltt=2时价格为已缩放数值, "-"表示停牌等无值;f124为来源Unix秒;成交额币种按市场派生(单一事实源 MARKET_META.currency)。
89
+ const quoteAt = Number.isFinite(row.f124) ? new Date(row.f124 * 1000).toISOString() : null
90
+ const currency = MARKET_META[security.exchange]?.currency || 'CNY'
91
+ items.push(normalizeQuote({
92
+ securityId: security.id, providerInstanceId: request.providerInstanceId, adapterId: 'eastmoney', providerSymbol: `${row.f13}.${row.f12}`,
93
+ last: num(row.f2), previousClose: num(row.f18), open: num(row.f17), high: num(row.f15), low: num(row.f16),
94
+ volume: sharesFromLots(num(row.f5), security.exchange), volumeUnit: 'share', amount: num(row.f6), amountUnit: currency,
95
+ quoteAt, timestampKind: 'trade',
96
+ receivedAt: ctx.now(), delayKind: 'unknown', delaySeconds: null, securityState: 'unknown',
97
+ }))
98
+ }
99
+ return { providerInstanceId: request.providerInstanceId, fetchedAt: ctx.now(), items, errors: request.securities.filter(s => !seen.has(s.id)).map(s => ({ securityId: s.id, code: 'NO_DATA', message: '来源未返回此证券报价' })) }
100
+ },
101
+ async catalog(request, ctx) {
102
+ const items = [], seen = new Set()
103
+ const PAGE_SIZE = 100, MAX_PAGES = 50
104
+ // 探针只拉一页: executor 单请求 8 秒预算内完成, 全量翻页是同步通道的职责
105
+ const pages = request.probe ? 1 : MAX_PAGES
106
+ let page = 1, complete = true
107
+ while (page <= pages) {
108
+ const url = `${endpointOf(ctx, 'list')}?pn=${page}&pz=${PAGE_SIZE}&po=1&np=1&fltt=2&invt=2&fid=f12&fs=${LIST_FS[request.market]}&fields=f12,f13,f14`
109
+ const body = await getJson(ctx, url)
110
+ const diff = body?.data?.diff
111
+ if (!Array.isArray(diff)) throw new StockError('BAD_PAYLOAD', '目录字段结构异常', 502)
112
+ const total = Number(body.data.total)
113
+ if (!Number.isFinite(total)) throw new StockError('BAD_PAYLOAD', '目录总数缺失', 502)
114
+ for (const row of diff) {
115
+ const exchange = SYMBOL_PREFIX[row.f13]
116
+ if (exchange !== request.market || typeof row.f12 !== 'string' || !MARKET_META[request.market].codePattern.test(row.f12) || typeof row.f14 !== 'string' || !row.f14) continue
117
+ const id = securityId(exchange, row.f12)
118
+ if (seen.has(id)) throw new StockError('BAD_PAYLOAD', '目录身份冲突', 502)
119
+ seen.add(id)
120
+ items.push(makeSecurity(exchange, row.f12, row.f14, { cnspell: '', catalogSource: request.providerInstanceId }))
121
+ }
122
+ if (total > MAX_PAGES * PAGE_SIZE) complete = false
123
+ if (page * PAGE_SIZE >= total || diff.length === 0) break
124
+ page++
125
+ }
126
+ return { providerInstanceId: request.providerInstanceId, fetchedAt: ctx.now(), items, errors: [], complete }
127
+ },
128
+ async search(request, ctx) {
129
+ // 不限市场时扩大候选量: 单次响应要覆盖调用方负责的多个市场
130
+ const count = request.market ? Math.min(20, request.limit || 10) : Math.min(50, (request.limit || 10) * 3)
131
+ const url = `${endpointOf(ctx, 'search')}?input=${encodeURIComponent(request.q)}&type=14&token=D43BF722C8E33BDC906FB84D85E326E8&count=${count}`
132
+ const body = await getJson(ctx, url)
133
+ const rows = body?.QuotationCodeTable?.Data
134
+ if (!Array.isArray(rows)) return { providerInstanceId: request.providerInstanceId, fetchedAt: ctx.now(), items: [], errors: [] }
135
+ const items = []
136
+ for (const row of rows) {
137
+ const exchange = SEARCH_EXCHANGE[row.MktNum]
138
+ if (!exchange || (request.market && exchange !== request.market)) continue
139
+ // 美股候选写 usSymbols(代码→MktNum/JYS), kline 美股动态归属与腾讯 suffix 唯一数据来源
140
+ if (isUSExchange(exchange) && ctx.usSymbols && US_MKTNUMS.includes(String(row.MktNum))) ctx.usSymbols.set(`US:${row.Code}`, { mktNum: row.MktNum, jys: row.JYS || null, at: ctx.now() })
141
+ const meta = MARKET_META[exchange]
142
+ if (!meta || !meta.codePattern.test(row.Code)) continue
143
+ items.push(makeSecurity(exchange, row.Code, row.Name, { cnspell: typeof row.PinYin === 'string' ? row.PinYin.toLowerCase() : '', catalogSource: request.providerInstanceId }))
144
+ }
145
+ return { providerInstanceId: request.providerInstanceId, fetchedAt: ctx.now(), items, errors: [] }
146
+ },
147
+ // 美股 secid 前缀: usSymbols 命中按 MktNum, miss 默认沪深外美股主市场 NASDAQ;猜错时调用方走 suggest 重试路径。
148
+ secidOf(request, ctx) {
149
+ const { market, code } = request
150
+ if (market === 'XNAS' || market === 'XNYS') {
151
+ const mktNum = ctx.usSymbols?.get(`US:${code}`)?.mktNum
152
+ return `${mktNum || US_DEFAULT_MKT}.${code}`
153
+ }
154
+ return `${SECID_PREFIX[market]}.${code}`
155
+ },
156
+ async kline(request, ctx) {
157
+ if (request.period === 'trend') return this.trend(request, ctx)
158
+ const secid = this.secidOf(request, ctx)
159
+ const url = `${endpointOf(ctx, 'kline')}?secid=${secid}&fields1=f1,f2,f3&fields2=${KLINE_FIELDS}&klt=${KLT[request.period]}&fqt=1&end=20500101&lmt=${request.limit}`
160
+ const body = await getJson(ctx, url)
161
+ if (!body?.data?.klines) {
162
+ if (request.market !== 'XNAS' && request.market !== 'XNYS') throw new StockError('NO_DATA', '来源未返回此证券K线', 422)
163
+ // 美股默认前缀猜错: 经搜索联想解析真实 MktNum, 重试一次;仍失败 NO_DATA。
164
+ const resolved = await this.resolveUsSecid(request, ctx)
165
+ if (!resolved) throw new StockError('NO_DATA', '来源未返回此证券K线', 422)
166
+ ctx.usSymbols?.set(`US:${request.code}`, resolved)
167
+ const retryUrl = url.replace(`secid=${secid}`, `secid=${resolved.mktNum}.${request.code}`)
168
+ const retryBody = await getJson(ctx, retryUrl)
169
+ if (!retryBody?.data?.klines) throw new StockError('NO_DATA', '来源未返回此证券K线', 422)
170
+ return buildKlineResponse(request, retryBody.data, ctx)
171
+ }
172
+ return buildKlineResponse(request, body.data, ctx)
173
+ },
174
+ async resolveUsSecid(request, ctx) {
175
+ const url = `${endpointOf(ctx, 'search')}?input=${encodeURIComponent(request.code)}&type=14&token=D43BF722C8E33BDC906FB84D85E326E8&count=5`
176
+ const body = await getJson(ctx, url)
177
+ const row = body?.QuotationCodeTable?.Data?.find(r => r.Code === request.code && /^10[567]$/.test(r.MktNum || ''))
178
+ return row ? { mktNum: row.MktNum, jys: row.JYS || null, at: ctx.now() } : null
179
+ },
180
+ async trend(request, ctx) {
181
+ const secid = this.secidOf(request, ctx)
182
+ const url = `${endpointOf(ctx, 'trend')}?secid=${secid}&fields1=f1,f2,f3,f4,f5,f6,f7,f8&fields2=${TREND_FIELDS}&iscr=0&ndays=1`
183
+ const body = await getJson(ctx, url)
184
+ if (!body?.data?.trends) throw new StockError('NO_DATA', '来源未返回此证券分时', 422)
185
+ // 东财分时的时间戳一律按北京时间给出(八市场实测: 日股 08:00 对应东京 09:00 开盘, 英股 16:00 对应伦敦 08:00),
186
+ // 不是市场本地时间; 之前按市场时区解释, 日韩英的横轴整体偏了几小时。
187
+ const candles = body.data.trends.map(row => {
188
+ const cols = row.split(',')
189
+ if (cols.length < 8) throw new StockError('BAD_PAYLOAD', '分时列数不足', 502)
190
+ const [, time] = cols[0].split(' ')
191
+ const num = v => { const n = parseFloat(v); return Number.isFinite(n) ? n : null }
192
+ // at 是来源时刻的 Unix 秒:只留 HH:MM 会让客户端按索引自造时间轴,横轴整体平移
193
+ // f56 与日K 同为手: 沪深要按 100 股换算, 否则分时图例的量和日K/详情差两个数量级
194
+ return { time, at: zonedUnixSeconds(cols[0], SOURCE_ZONE), open: num(cols[1]), close: num(cols[2]), high: num(cols[3]), low: num(cols[4]), volume: sharesFromLots(num(cols[5]), request.market), amount: num(cols[6]), avg: num(cols[7]) }
195
+ })
196
+ return { providerInstanceId: request.providerInstanceId, fetchedAt: ctx.now(), complete: true, preClose: num_or_null(body.data.preClose), candles }
197
+ },
198
+ }
199
+
200
+ function num_or_null(v) { const n = parseFloat(v); return Number.isFinite(n) ? n : null }
201
+
202
+
203
+ // 把指定时区的"YYYY-MM-DD HH:MM"换算成 Unix 秒, 时刻属于哪个时区由调用方给定;
204
+ // 无时区元数据或格式不符时返回 null, 调用方回退自造时间轴
205
+ function zonedUnixSeconds(stamp, timeZone) {
206
+ const match = /^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2})/.exec(stamp)
207
+ if (!match || !timeZone) return null
208
+ const [, y, mo, d, hh, mm] = match.map(Number)
209
+ const localAsUtc = Date.UTC(y, mo - 1, d, hh, mm)
210
+ const parts = new Intl.DateTimeFormat('en-US', {
211
+ timeZone, hour12: false,
212
+ year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit',
213
+ }).formatToParts(new Date(localAsUtc))
214
+ const rendered = Object.fromEntries(parts.map((part) => [part.type, part.value]))
215
+ const asUtc = Date.UTC(Number(rendered.year), Number(rendered.month) - 1, Number(rendered.day),
216
+ Number(rendered.hour) % 24, Number(rendered.minute), Number(rendered.second))
217
+ return Math.floor((localAsUtc - (asUtc - localAsUtc)) / 1000)
218
+ }
219
+
220
+ // klines CSV → 合同响应: 逐行解析/升序/重复拒绝; complete 由 dktotal 与请求量判定(源截断标志)。
221
+ function buildKlineResponse(request, data, ctx) {
222
+ const candles = []
223
+ let prevTime = ''
224
+ for (const row of data.klines) {
225
+ const cols = row.split(',')
226
+ if (cols.length < 7) throw new StockError('BAD_PAYLOAD', 'K线列数不足', 502)
227
+ if (cols[0] <= prevTime) throw new StockError('BAD_PAYLOAD', 'K线时间戳重复或乱序', 502)
228
+ prevTime = cols[0]
229
+ const num = v => { const n = parseFloat(v); return Number.isFinite(n) ? n : null }
230
+ candles.push({ time: cols[0], open: num(cols[1]), close: num(cols[2]), high: num(cols[3]), low: num(cols[4]), volume: sharesFromLots(num(cols[5]), request.market), amount: num(cols[6]) })
231
+ }
232
+ const total = Number(data.dktotal)
233
+ return { providerInstanceId: request.providerInstanceId, fetchedAt: ctx.now(), complete: Number.isFinite(total) ? request.limit <= total : true, preClose: num_or_null(data.preKPrice), candles }
234
+ }
@@ -0,0 +1,121 @@
1
+ // 新浪公开行情接口适配器:quotes(沪深港美)/catalog(沪深)。非官方端点,需Referer,无SLA;延迟未知,时间为来源快照时间。
2
+ import { normalizeQuote, parseQuoteTime, makeSecurity, securityId, StockError } from '../market-model.mjs'
3
+ const ENDPOINT = 'https://hq.sinajs.cn/list='
4
+ const LIST_ENDPOINT = 'https://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.getHQNodeData'
5
+ const HEADERS = { Referer: 'https://finance.sina.com.cn/', 'User-Agent': 'Mozilla/5.0' }
6
+ // 报价前缀与币种随市场派生(单一事实源);美股代码在来源侧是小写
7
+ const BY_MARKET = {
8
+ XSHG: { prefix: 'sh', currency: 'CNY' },
9
+ XSHE: { prefix: 'sz', currency: 'CNY' },
10
+ XHKG: { prefix: 'rt_hk', currency: 'HKD' },
11
+ XNAS: { prefix: 'gb_', currency: 'USD' },
12
+ XNYS: { prefix: 'gb_', currency: 'USD' },
13
+ }
14
+ const symbolOf = security => {
15
+ const meta = BY_MARKET[security.exchange]
16
+ const code = meta.prefix === 'gb_' ? String(security.code).toLowerCase() : security.code
17
+ return `${meta.prefix}${code}`
18
+ }
19
+ // 探针代表证券(各市场实测可达的流动性标的)
20
+ const PROBE_SECURITY = { XSHG: '600519', XSHE: '000001', XHKG: '00700', XNAS: 'AAPL', XNYS: 'BABA' }
21
+ // 新浪价格固定三位以上小数,A股最小变动0.01,裁剪到两位不损失精度;港美同理按分呈现
22
+ const trim = value => /^\d+(\.\d+)?$/.test(value) ? Number(value).toFixed(2) : value
23
+ const count = value => value == null || Number.isNaN(Number(value)) ? null : String(Math.round(Number(value)))
24
+ // 各市场字段位置:沪深34列、港股25列、美股36列,同一行内的列义由前缀决定
25
+ const FIELD_MAP = {
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]}` }),
27
+ hk: f => ({ open: f[2], previousClose: f[3], high: f[4], low: f[5], last: f[6], volume: f[12], amount: f[11], quoteAt: `${String(f[17]).replace(/\//g, '-')} ${f[18]}` }),
28
+ us: f => ({ open: f[5], previousClose: f[26], last: f[1], high: f[6], low: f[7], volume: f[10], quoteAt: f[3] }),
29
+ }
30
+ const kindOf = providerSymbol => providerSymbol.startsWith('rt_hk') ? 'hk' : providerSymbol.startsWith('gb_') ? 'us' : 'cn'
31
+ const MIN_FIELDS = { cn: 32, hk: 20, us: 28 }
32
+ export const sina = {
33
+ descriptor: { adapterId: 'sina', capabilities: ['quotes', 'catalog'], markets: ['XSHG', 'XSHE', 'XHKG', 'XNAS', 'XNYS'], instruments: ['equity'], maxQuoteBatch: 60, credential: 'none', description: '新浪公开接口:免凭据,沪深港美行情与沪深目录' },
34
+ async probe(request, ctx) {
35
+ if (request.capability === 'catalog') {
36
+ // 探针只拉一页验证端点连通,不做全量分页。
37
+ const response = await ctx.fetch(`${LIST_ENDPOINT}?page=1&num=5&sort=symbol&asc=1&node=${request.market === 'XSHG' ? 'sh_a' : 'sz_a'}`, { headers: HEADERS, signal: ctx.signal, redirect: 'error' })
38
+ if (!response.ok) throw new StockError('NETWORK', '来源服务暂不可用', 502, { retryable: true })
39
+ const rows = await response.json()
40
+ if (!Array.isArray(rows) || !rows.length) throw new StockError('NO_DATA', '来源未返回可校验数据,暂不能确认能力就绪', 422)
41
+ return { status: 'ready', capability: 'catalog', market: request.market, instrument: 'equity' }
42
+ }
43
+ const security = request.securities?.[0] || { exchange: request.market, code: PROBE_SECURITY[request.market] || '600519' }
44
+ const rows = await this.quotes({ ...request, securities: [security] }, ctx)
45
+ if (!rows.items.length) throw new StockError('NO_DATA', '来源未返回可校验数据,暂不能确认能力就绪', 422)
46
+ return { status: 'ready', capability: 'quotes', market: request.market, instrument: 'equity' }
47
+ },
48
+ async catalog(request, ctx) {
49
+ // 分市场节点sh_a/sz_a直接取本市场全量,分页间保持来源要求的节流间隔。
50
+ const PAGE_SIZE = 80, MAX_PAGES = 100, PAGE_GAP = 600
51
+ const prefix = request.market === 'XSHG' ? 'sh' : 'sz', node = request.market === 'XSHG' ? 'sh_a' : 'sz_a'
52
+ const items = [], seen = new Set()
53
+ let page = 1, complete = true, retriedShort = false
54
+ while (page <= MAX_PAGES) {
55
+ let rows
56
+ try {
57
+ const response = await ctx.fetch(`${LIST_ENDPOINT}?page=${page}&num=${PAGE_SIZE}&sort=symbol&asc=1&node=${node}`, { headers: HEADERS, signal: ctx.signal, redirect: 'error' })
58
+ if (!response.ok) throw new StockError('NETWORK', '来源服务暂不可用', 502, { retryable: true })
59
+ rows = await response.json()
60
+ } catch (e) {
61
+ if (ctx.signal.aborted) throw new StockError('CANCELLED', '请求已取消', 503)
62
+ if (e instanceof StockError) throw e
63
+ throw new StockError('NETWORK', '无法连接行情来源', 502, { retryable: true })
64
+ }
65
+ if (!Array.isArray(rows)) throw new StockError('BAD_PAYLOAD', '目录字段结构异常', 502)
66
+ if (rows.length < PAGE_SIZE && !retriedShort) {
67
+ // 连续请求过密时来源会降级返回短页,退避后重拉本页一次再终止。
68
+ retriedShort = true
69
+ await new Promise((resolve, reject) => { const t = setTimeout(resolve, 3 * 1000); ctx.signal.addEventListener('abort', () => { clearTimeout(t); reject(new StockError('CANCELLED', '请求已取消', 503)) }, { once: true }) })
70
+ continue
71
+ }
72
+ retriedShort = false
73
+ for (const row of rows) {
74
+ if (typeof row.symbol !== 'string' || !row.symbol.startsWith(prefix) || !/^\d{6}$/.test(row.code || '') || typeof row.name !== 'string' || !row.name) continue
75
+ const id = securityId(request.market, row.code)
76
+ if (seen.has(id)) throw new StockError('BAD_PAYLOAD', '目录身份冲突', 502)
77
+ seen.add(id)
78
+ items.push(makeSecurity(request.market, row.code, row.name, { cnspell: '', catalogSource: request.providerInstanceId }))
79
+ }
80
+ if (rows.length < PAGE_SIZE) break
81
+ if (page === MAX_PAGES) complete = false
82
+ page++
83
+ await new Promise((resolve, reject) => { const t = setTimeout(resolve, PAGE_GAP); ctx.signal.addEventListener('abort', () => { clearTimeout(t); reject(new StockError('CANCELLED', '请求已取消', 503)) }, { once: true }) })
84
+ }
85
+ return { providerInstanceId: request.providerInstanceId, fetchedAt: ctx.now(), items, errors: [], complete }
86
+ },
87
+ async quotes(request, ctx) {
88
+ const symbols = new Map(request.securities.map(s => [symbolOf(s), s]))
89
+ let response
90
+ try {
91
+ response = await ctx.fetch(ENDPOINT + [...symbols.keys()].join(','), { headers: HEADERS, signal: ctx.signal, redirect: 'error' })
92
+ } catch (e) {
93
+ if (ctx.signal.aborted) throw new StockError('CANCELLED', '请求已取消', 503)
94
+ if (e instanceof StockError) throw e
95
+ throw new StockError('NETWORK', '无法连接行情来源', 502, { retryable: true })
96
+ }
97
+ if (!response.ok) throw new StockError('NETWORK', '来源服务暂不可用', 502, { retryable: true })
98
+ const text = new TextDecoder('gbk').decode(await response.arrayBuffer())
99
+ const seen = new Set(), items = []
100
+ for (const line of text.split(';')) {
101
+ const match = /var hq_str_(\w+)="([^"]*)"/.exec(line)
102
+ if (!match) continue
103
+ const providerSymbol = match[1], security = symbols.get(providerSymbol)
104
+ if (!security) continue
105
+ if (seen.has(providerSymbol)) throw new StockError('BAD_PAYLOAD', '报价身份冲突', 502)
106
+ seen.add(providerSymbol)
107
+ const f = match[2].split(','), kind = kindOf(providerSymbol)
108
+ // 停牌行来源返回空串,按无值处理而不是伪造零价
109
+ if (f.length < MIN_FIELDS[kind]) throw new StockError('BAD_PAYLOAD', '来源字段数量异常', 502)
110
+ const mapped = FIELD_MAP[kind](f)
111
+ items.push(normalizeQuote({
112
+ securityId: security.id, providerInstanceId: request.providerInstanceId, adapterId: 'sina', providerSymbol,
113
+ last: trim(mapped.last), previousClose: trim(mapped.previousClose), open: trim(mapped.open), high: trim(mapped.high), low: trim(mapped.low),
114
+ volume: count(mapped.volume), volumeUnit: 'share', amount: count(mapped.amount), amountUnit: BY_MARKET[security.exchange].currency,
115
+ quoteAt: parseQuoteTime(mapped.quoteAt), timestampKind: 'trade',
116
+ receivedAt: ctx.now(), delayKind: 'unknown', delaySeconds: null, securityState: 'unknown',
117
+ }))
118
+ }
119
+ 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: '来源未返回此证券报价' })) }
120
+ },
121
+ }
@@ -0,0 +1,122 @@
1
+ // 腾讯公开行情接口适配器:quotes+kline(备源)。非官方端点,无SLA,随时可能失效;延迟未知,行情时间戳为来源快照时间。
2
+ import { normalizeQuote, parseQuoteTime, StockError, MARKET_META, sharesFromLots, amountFromWan } from '../market-model.mjs'
3
+ // 官方默认端点表(key 供 instance.endpoints 覆盖, 反代/镜像场景由 ctx.endpoints 提供同名 key)
4
+ const DEFAULT_ENDPOINTS = {
5
+ quotes: 'https://qt.gtimg.cn/q=',
6
+ kline: 'https://web.ifzq.gtimg.cn/appstock/app/fqkline/get',
7
+ }
8
+ const endpointOf = (ctx, key) => ctx.endpoints?.[key] || DEFAULT_ENDPOINTS[key]
9
+ // quotes 与 kline 共用一张前缀表,防双源漂移(design.md 数据结构节)。
10
+ const SYMBOL_PREFIX = { XSHG: 'sh', XSHE: 'sz', XHKG: 'hk' }
11
+ // 美股 symbol 后缀由搜索联想 JYS 字段映射(2026-10-30 实测: suggest 返回 JYS="NASDAQ"/"NYSE"/"AMEX";
12
+ // 腾讯侧 .OQ/.N/裸代码同价有效, .A/.U 形态返回空数据——AMEX 走裸代码兜底)。
13
+ const JYS_TO_SUFFIX = { NASDAQ: 'OQ', NYSE: 'N', AMEX: '' }
14
+ // 美股行情端点要 us 前缀(实测 usAAPL 有效, 裸 AAPL 返回空);K线另有 JYS 后缀逻辑, 不复用这张表。
15
+ const isUSExchange = exchange => exchange === 'XNAS' || exchange === 'XNYS'
16
+ const symbolOf = security => isUSExchange(security.exchange) ? `us${security.code}` : SYMBOL_PREFIX[security.exchange] ? `${SYMBOL_PREFIX[security.exchange]}${security.code}` : `${security.code}`
17
+ // kline request 用 market 字段(exchange 是 security 形态的字段名); 港股 code 统一 5 位对齐腾讯 hk00700 实测形态。
18
+ const klineSymbolOf = request => {
19
+ const prefix = SYMBOL_PREFIX[request.market]
20
+ if (!prefix) return request.code
21
+ const code = request.market === 'XHKG' ? request.code.padStart(5, '0') : request.code
22
+ return `${prefix}${code}`
23
+ }
24
+ // kline 数据键随复权/周期漂移(qfqday/day/qfqweek/qfqmonth),取第一个数组值兜底。
25
+ const firstArray = data => Object.values(data).find(Array.isArray)
26
+ const num = v => { const n = parseFloat(v); return Number.isFinite(n) ? n : null }
27
+ // 行情时间戳三种写法: 沪深紧凑数字, 港股斜杠, 美股带连字符
28
+ const quoteStamp = raw => {
29
+ const compact = /^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/.exec(raw || '')
30
+ if (compact) return `${compact[1]}-${compact[2]}-${compact[3]} ${compact[4]}:${compact[5]}:${compact[6]}`
31
+ const loose = /^(\d{4})[-/](\d{2})[-/](\d{2})[ T](\d{2}):(\d{2})(?::(\d{2}))?/.exec(raw || '')
32
+ return loose ? `${loose[1]}-${loose[2]}-${loose[3]} ${loose[4]}:${loose[5]}:${loose[6] || '00'}` : null
33
+ }
34
+
35
+ export const tencent = {
36
+ descriptor: { adapterId: 'tencent', capabilities: ['quotes', 'kline'], markets: ['XSHG', 'XSHE', 'XHKG', 'XNAS', 'XNYS'], instruments: ['equity'], maxQuoteBatch: 60, credential: 'none', description: '腾讯公开接口:免凭据,行情与K线备源,非官方无SLA', endpointKeys: [{ key: 'quotes', label: '行情批量' }, { key: 'kline', label: 'K线历史' }] },
37
+ async probe(request, ctx) {
38
+ // kline 探针直接拉代表证券 3 根日K(quotes 不覆盖港股);quotes 探针沿用代表证券行。
39
+ if (request.capability === 'kline') {
40
+ const code = { XSHG: '600519', XSHE: '000001', XHKG: '00700' }[request.market]
41
+ if (!code) throw new StockError('UNSUPPORTED_CAPABILITY', '腾讯来源不提供该市场K线', 422)
42
+ const result = await this.kline({ ...request, securityId: `${request.market}:equity:${code}`, code, period: '1d', adjust: 'qfq', limit: 3 }, ctx)
43
+ if (!result.candles.length) throw new StockError('NO_DATA', '来源未返回可校验数据,暂不能确认能力就绪', 422)
44
+ return { status: 'ready', capability: 'kline', market: request.market, instrument: 'equity' }
45
+ }
46
+ const PROBE = { XSHG: '600519', XSHE: '000001', XHKG: '00700', XNAS: 'AAPL', XNYS: 'BABA' }
47
+ const security = request.securities?.[0] || { exchange: request.market, code: PROBE[request.market] || '000001' }
48
+ const rows = await this.quotes({ ...request, securities: [security] }, ctx)
49
+ if (!rows.items.length) throw new StockError('NO_DATA', '来源未返回可校验数据,暂不能确认能力就绪', 422)
50
+ return { status: 'ready', capability: 'quotes', market: request.market, instrument: 'equity' }
51
+ },
52
+ async quotes(request, ctx) {
53
+ const symbols = new Map(request.securities.map(s => [symbolOf(s), s]))
54
+ let response
55
+ try {
56
+ response = await ctx.fetch(endpointOf(ctx, 'quotes') + [...symbols.keys()].join(','), { headers: { 'User-Agent': 'Mozilla/5.0' }, signal: ctx.signal, redirect: 'error' })
57
+ } catch (e) {
58
+ if (ctx.signal.aborted) throw new StockError('CANCELLED', '请求已取消', 503)
59
+ if (e instanceof StockError) throw e
60
+ throw new StockError('NETWORK', '无法连接行情来源', 502, { retryable: true })
61
+ }
62
+ if (!response.ok) throw new StockError('NETWORK', '来源服务暂不可用', 502, { retryable: true })
63
+ const text = new TextDecoder('gbk').decode(await response.arrayBuffer())
64
+ const seen = new Set(), items = []
65
+ for (const line of text.split(';')) {
66
+ const match = /v_((?:sh|sz|hk)\d{5,6}|us[A-Za-z.]+)="([^"]*)"/.exec(line)
67
+ if (!match) continue
68
+ const providerSymbol = match[1], security = symbols.get(providerSymbol)
69
+ if (!security) continue
70
+ if (seen.has(providerSymbol)) throw new StockError('BAD_PAYLOAD', '报价身份冲突', 502)
71
+ seen.add(providerSymbol)
72
+ const f = match[2].split('~')
73
+ if (f.length < 38) throw new StockError('BAD_PAYLOAD', '来源字段数量异常', 502)
74
+ const volume = num(f[36]), amount = num(f[37])
75
+ items.push(normalizeQuote({
76
+ securityId: security.id, providerInstanceId: request.providerInstanceId, adapterId: 'tencent', providerSymbol,
77
+ last: f[3], previousClose: f[4], open: f[5], high: f[33], low: f[34],
78
+ volume: volume === null ? null : String(sharesFromLots(volume, security.exchange)), volumeUnit: 'share',
79
+ amount: amount === null ? null : String(amountFromWan(amount, security.exchange)), amountUnit: MARKET_META[security.exchange]?.currency || 'CNY',
80
+ quoteAt: parseQuoteTime(quoteStamp(f[30])), timestampKind: 'trade',
81
+ receivedAt: ctx.now(), delayKind: 'unknown', delaySeconds: null, securityState: 'unknown',
82
+ }))
83
+ }
84
+ 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: '来源未返回此证券报价' })) }
85
+ },
86
+ async kline(request, ctx) {
87
+ if (request.period === 'trend') throw new StockError('UNSUPPORTED_CAPABILITY', '腾讯来源不提供分时数据', 422)
88
+ let symbol = klineSymbolOf(request)
89
+ if (request.market === 'XNAS' || request.market === 'XNYS') {
90
+ const mapped = ctx.usSymbols?.get(`US:${request.code}`)
91
+ const suffix = mapped ? JYS_TO_SUFFIX[mapped.jys] : undefined
92
+ if (suffix === undefined) throw new StockError('UNSUPPORTED_CAPABILITY', '腾讯来源的美股K线需先经搜索建立代码映射', 422)
93
+ symbol = suffix ? `us${request.code}.${suffix}` : `us${request.code}`
94
+ }
95
+ const param = `${symbol},${{ '1d': 'day', '1w': 'week', '1M': 'month' }[request.period]},,,${request.limit},qfq`
96
+ let response
97
+ try {
98
+ 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' })
99
+ } catch (e) {
100
+ if (ctx.signal.aborted) throw new StockError('CANCELLED', '请求已取消', 503)
101
+ if (e instanceof StockError) throw e
102
+ throw new StockError('NETWORK', '无法连接行情来源', 502, { retryable: true })
103
+ }
104
+ if (!response.ok) throw new StockError('NETWORK', '来源服务暂不可用', 502, { retryable: true })
105
+ const body = await response.json().catch(() => { throw new StockError('BAD_PAYLOAD', '来源响应不是JSON', 502) })
106
+ const data = body?.data?.[symbol]
107
+ const rows = data && firstArray(data)
108
+ if (!Array.isArray(rows) || !rows.length) throw new StockError('NO_DATA', '来源未返回此证券K线', 422)
109
+ const candles = []
110
+ let prevTime = ''
111
+ for (const row of rows) {
112
+ if (!Array.isArray(row) || row.length < 6) throw new StockError('BAD_PAYLOAD', 'K线列数不足', 502)
113
+ if (String(row[0]) <= prevTime) throw new StockError('BAD_PAYLOAD', 'K线时间戳重复或乱序', 502)
114
+ prevTime = String(row[0])
115
+ 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) })
116
+ }
117
+ // preClose 实测定案: data.{symbol}.qt.{symbol}[4] 为昨收(2026-10-30 实测 sz000001 值 11.54 与东财 f18 一致)。
118
+ const qt = Array.isArray(data?.qt?.[symbol]) ? data.qt[symbol] : null
119
+ const preClose = qt ? num(qt[4]) : null
120
+ return { providerInstanceId: request.providerInstanceId, fetchedAt: ctx.now(), complete: true, preClose, candles }
121
+ },
122
+ }
@@ -0,0 +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: 'env', description: 'Tushare Pro:需在Host环境配置凭据,沪深目录/日历/行情,有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
+ }