@mzzsfy/dsh-stock-assistant 0.9.0 → 0.11.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 +117 -4
- package/README.md +24 -18
- package/package.json +1 -1
- package/src/application.mjs +377 -123
- package/src/budget.mjs +16 -15
- package/src/catalog.mjs +145 -93
- package/src/client.js +1067 -380
- package/src/client.js~RF25ea9e49.TMP +3301 -0
- package/src/collector.mjs +171 -93
- package/src/executor.mjs +212 -60
- package/src/index.js +5 -3
- package/src/kline-cache.mjs +10 -13
- package/src/market-model.mjs +35 -8
- package/src/memory-cache.mjs +5 -1
- package/src/provider-router.mjs +13 -7
- package/src/providers/eastmoney.mjs +128 -57
- package/src/providers/sina.mjs +63 -41
- package/src/providers/tencent.mjs +19 -5
- package/src/providers/tushare.mjs +11 -2
- package/src/providers/us-markets.mjs +4 -0
- package/src/providers/xueqiu.mjs +68 -27
- package/src/recovery.mjs +29 -14
- package/src/routes.mjs +18 -5
- package/src/schemas.mjs +15 -22
- package/src/state.mjs +17 -2
- package/src/trend-cache.mjs +114 -12
- package/src/us-symbols.mjs +30 -0
- package//345/205/274/345/256/271/346/200/247/346/265/213/350/257/225.md +239 -13
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// 东财公开行情接口适配器:quotes/catalog/search/kline。非官方端点,无SLA;延迟未知,f124为来源秒级时间戳。
|
|
2
2
|
import { normalizeQuote, makeSecurity, securityId, StockError, MARKET_META, sharesFromLots, zonedUnixSeconds } from '../market-model.mjs'
|
|
3
|
+
import { isUSExchange, marketMatchesUS, US_MARKET_EXCHANGE } from './us-markets.mjs'
|
|
3
4
|
// 官方默认端点表(key 供 instance.endpoints 覆盖, 反代/镜像场景由 ctx.endpoints 提供同名 key)
|
|
4
5
|
const DEFAULT_ENDPOINTS = {
|
|
5
6
|
quotes: 'https://push2.eastmoney.com/api/qt/ulist.np/get',
|
|
@@ -9,23 +10,77 @@ const DEFAULT_ENDPOINTS = {
|
|
|
9
10
|
trend: 'https://push2his.eastmoney.com/api/qt/stock/trends2/get',
|
|
10
11
|
}
|
|
11
12
|
const endpointOf = (ctx, key) => ctx.endpoints?.[key] || DEFAULT_ENDPOINTS[key]
|
|
12
|
-
//
|
|
13
|
-
const
|
|
14
|
-
|
|
15
|
-
const
|
|
13
|
+
// suggest 接口的公开站点参数(不是本插件凭据), 两处调用必须同源
|
|
14
|
+
const SUGGEST_TOKEN = 'D43BF722C8E33BDC906FB84D85E326E8'
|
|
15
|
+
const QUOTE_INDEX_SECID = { 'XHKG:index:HSI': '100.HSI' }
|
|
16
|
+
const EXCHANGE_BY_PREFIX = { 1: 'XSHG', 0: 'XSHE', 116: 'XHKG', ...US_MARKET_EXCHANGE, 176: 'XJPX', 177: 'XKRX', 155: 'XLON' }
|
|
16
17
|
const SECID_PREFIX = { XSHG: '1', XSHE: '0', XHKG: '116', XNAS: '105', XNYS: '106', XJPX: '176', XKRX: '177', XLON: '155' }
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
18
|
+
const US_MKTNUMS = Object.keys(US_MARKET_EXCHANGE)
|
|
19
|
+
// 缓存只加速同交易所查询,未命中时优先用静态前缀。
|
|
20
|
+
function usSecidPrefixes(security, ctx) {
|
|
21
|
+
const cached = ctx.usSymbols?.get(`US:${security.code}`)?.mktNum
|
|
22
|
+
return [...new Set([cached, SECID_PREFIX[security.exchange], ...US_MKTNUMS].filter(mktNum => marketMatchesUS(security.exchange, mktNum)).map(String))]
|
|
23
|
+
}
|
|
23
24
|
const secidFor = (security, ctx) => isUSExchange(security.exchange) ? `${usSecidPrefixes(security, ctx)[0]}.${security.code}` : `${SECID_PREFIX[security.exchange]}.${security.code}`
|
|
24
25
|
// klt 周期映射(实测): 日101/周102/月103; trends2 无 klt。
|
|
25
26
|
const KLT = { '1d': 101, '1w': 102, '1M': 103 }
|
|
26
27
|
// 目录 fs 按市场给出; 英股 m:155 含债券与结构性产品, 加 t:1 只取股票; 日韩不支持 t: 细分, 全量即股票
|
|
27
28
|
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' }
|
|
28
|
-
const
|
|
29
|
+
const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
30
|
+
const isCount = value => (typeof value === 'number' || typeof value === 'string' && /^\d+$/.test(value)) && Number.isSafeInteger(Number(value)) && Number(value) >= 0
|
|
31
|
+
|
|
32
|
+
function readDiff(data, label) {
|
|
33
|
+
const diff = data?.diff
|
|
34
|
+
if (isObject(data)) {
|
|
35
|
+
if (Array.isArray(diff)) return diff
|
|
36
|
+
if (isObject(diff) && Object.keys(diff).every(key => /^(0|[1-9]\d*)$/.test(key))) return Object.values(diff)
|
|
37
|
+
}
|
|
38
|
+
throw new StockError('BAD_PAYLOAD', `${label}字段结构异常`, 502)
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function validateStatus(body) {
|
|
42
|
+
if (!isObject(body)) throw new StockError('BAD_PAYLOAD', '来源字段结构异常', 502)
|
|
43
|
+
if (!Object.hasOwn(body, 'rc')) return
|
|
44
|
+
const rc = body.rc
|
|
45
|
+
if (!(typeof rc === 'number' || typeof rc === 'string' && /^-?\d+$/.test(rc)) || !Number.isSafeInteger(Number(rc))) throw new StockError('BAD_PAYLOAD', '来源状态字段异常', 502)
|
|
46
|
+
if (Number(body.rc) !== 0) throw new StockError('NETWORK', '东财未能处理请求', 502, { retryable: true })
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// 搜索仍收录 ETF。未提供 Classify 的来源沿用市场号及代码校验。
|
|
50
|
+
const isSearchInstrument = row => row.Classify == null || row.Classify === '' || typeof row.Classify === 'string' && /^(?:[a-z]*stock|[a-z]*etf[a-z]*|[a-z]*fund)$/i.test(row.Classify.trim())
|
|
51
|
+
function suggestRows(body) {
|
|
52
|
+
const table = body.QuotationCodeTable
|
|
53
|
+
if (table === null) return []
|
|
54
|
+
if (isObject(table)) {
|
|
55
|
+
if (table.Data === null) return []
|
|
56
|
+
if (Array.isArray(table.Data)) {
|
|
57
|
+
const rows = table.Data.filter(row => {
|
|
58
|
+
if (!isObject(row) || !isCount(row.MktNum) || typeof row.Code !== 'string' || !row.Code.trim() || typeof row.Name !== 'string' || !row.Name.trim()) return false
|
|
59
|
+
if (row.Classify != null && typeof row.Classify !== 'string') return false
|
|
60
|
+
const meta = MARKET_META[EXCHANGE_BY_PREFIX[row.MktNum]]
|
|
61
|
+
return !meta || !isSearchInstrument(row) || meta.codePattern.test(row.Code)
|
|
62
|
+
})
|
|
63
|
+
if (!table.Data.length || rows.length) return rows
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
throw new StockError('BAD_PAYLOAD', '搜索字段结构异常', 502)
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function hasHistory(body, secid, field, label) {
|
|
70
|
+
const { data } = body
|
|
71
|
+
if (data === null) return false
|
|
72
|
+
if (!isObject(data)) throw new StockError('BAD_PAYLOAD', `${label}字段结构异常`, 502)
|
|
73
|
+
const dot = secid.indexOf('.')
|
|
74
|
+
const market = secid.slice(0, dot), code = secid.slice(dot + 1)
|
|
75
|
+
if (Object.hasOwn(data, 'code') && data.code !== code || Object.hasOwn(data, 'market') && String(data.market) !== market) {
|
|
76
|
+
throw new StockError('BAD_PAYLOAD', `${label}证券身份不匹配`, 502)
|
|
77
|
+
}
|
|
78
|
+
const rows = data[field]
|
|
79
|
+
if (rows === null) return false
|
|
80
|
+
if (!Array.isArray(rows) || rows.some(row => typeof row !== 'string')) throw new StockError('BAD_PAYLOAD', `${label}字段结构异常`, 502)
|
|
81
|
+
return rows.length > 0
|
|
82
|
+
}
|
|
83
|
+
const usSymbolOf = (row, at) => ({ mktNum: String(row.MktNum), jys: row.JYS || null, at })
|
|
29
84
|
// 探针代表证券(实测可用的各市场流动性代表),quotes/kline 探针按市场取用。
|
|
30
85
|
const PROBE_SECURITY = { XSHG: '600519', XSHE: '000001', XHKG: '00700', XNAS: 'AAPL', XNYS: 'BABA', XJPX: '7203', XKRX: '005930', XLON: 'SHEL' }
|
|
31
86
|
// klines CSV 前 7 列固定语义(实测 fields2=f51-f57); f53=close 在 f54=high 前为东财原生序。
|
|
@@ -34,6 +89,8 @@ const TREND_FIELDS = 'f51,f52,f53,f54,f55,f56,f57,f58'
|
|
|
34
89
|
// 分时时间戳的来源时区: 东财统一用北京时间, 与证券所属市场无关
|
|
35
90
|
const SOURCE_ZONE = 'Asia/Shanghai'
|
|
36
91
|
const num = value => value == null || typeof value === 'number' && !Number.isFinite(value) ? null : value === '-' ? null : String(value)
|
|
92
|
+
// 换手率/量比是纯数值语义(不参与定点价格格式化), 统一收敛成 number; 缺失仍是 null
|
|
93
|
+
const rate = value => { const text = num(value); const n = Number(text); return text === null || !Number.isFinite(n) ? null : n }
|
|
37
94
|
// 风控页是 HTML: 不嗅探就会被当成「响应不是JSON」, 用户看不到「去浏览器过滑块」这条唯一出路
|
|
38
95
|
const CHALLENGE_HINT = /验证码|人机验证|安全验证|滑块|拖动|geetest|tcaptcha|captcha/i
|
|
39
96
|
const challenged = async response => {
|
|
@@ -53,10 +110,12 @@ async function getJson(ctx, url) {
|
|
|
53
110
|
}
|
|
54
111
|
if (await challenged(response)) throw new StockError('CHALLENGE', '东财要求人机验证:用浏览器打开 www.eastmoney.com 完成验证后自动恢复', 502)
|
|
55
112
|
if (!response.ok) throw new StockError('NETWORK', '来源服务暂不可用', 502, { retryable: true })
|
|
56
|
-
|
|
113
|
+
const body = await response.json().catch(() => { throw new StockError('BAD_PAYLOAD', '来源响应不是JSON', 502) })
|
|
114
|
+
validateStatus(body)
|
|
115
|
+
return body
|
|
57
116
|
}
|
|
58
117
|
export const eastmoney = {
|
|
59
|
-
descriptor: { adapterId: 'eastmoney', capabilities: ['quotes', 'catalog', 'search', 'kline', 'trend'], 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: '分时' }] },
|
|
118
|
+
descriptor: { adapterId: 'eastmoney', capabilities: ['quotes', 'catalog', 'search', 'kline', 'trend'], markets: ['XSHG', 'XSHE', 'XHKG', 'XNAS', 'XNYS', 'XJPX', 'XKRX', 'XLON'], instruments: ['equity'], maxQuoteBatch: 60, pagedCatalog: true, credential: 'none', description: '东方财富公开接口:免凭据,八市场目录,行情/K线/分时/搜索,非官方无SLA', endpointKeys: [{ key: 'quotes', label: '行情批量' }, { key: 'list', label: '证券目录' }, { key: 'search', label: '搜索联想' }, { key: 'kline', label: 'K线历史' }, { key: 'trend', label: '分时' }] },
|
|
60
119
|
async probe(request, ctx) {
|
|
61
120
|
if (request.capability === 'catalog' || request.capability === 'search') {
|
|
62
121
|
// 探针词按市场用代表证券代码(茅台/平安只对沪深有效, 其他市场返回 0 项会误判 denied)。
|
|
@@ -82,81 +141,91 @@ export const eastmoney = {
|
|
|
82
141
|
return { status: 'ready', capability: 'quotes', market: request.market, instrument: 'equity' }
|
|
83
142
|
},
|
|
84
143
|
async quotes(request, ctx) {
|
|
85
|
-
const fields = 'f2,f3,f4,f5,f6,f12,f13,f14,f15,f16,f17,f18,f124'
|
|
86
|
-
const seen = new Set(), items = []
|
|
144
|
+
const fields = 'f2,f3,f4,f5,f6,f8,f10,f12,f13,f14,f15,f16,f17,f18,f124'
|
|
145
|
+
const seen = new Set(), invalidPrices = new Set(), items = []
|
|
87
146
|
// 一次请求取一批 secid;data:null 表示整批 secid 均无效(如整批退市),降级为逐证券缺失。
|
|
88
147
|
const ingest = async symbols => {
|
|
89
148
|
const body = await getJson(ctx, `${endpointOf(ctx, 'quotes')}?secids=${[...symbols.keys()].join(',')}&fields=${fields}&fltt=2&invt=2`)
|
|
90
|
-
|
|
91
|
-
|
|
149
|
+
if (body.data === null) return
|
|
150
|
+
const rows = readDiff(body.data, '报价')
|
|
151
|
+
let hasIdentity = false
|
|
92
152
|
for (const row of rows) {
|
|
93
|
-
const
|
|
153
|
+
const exchange = EXCHANGE_BY_PREFIX[row?.f13]
|
|
154
|
+
const secid = `${row?.f13}.${row?.f12}`
|
|
155
|
+
const security = symbols.get(secid)
|
|
156
|
+
const knownIndex = security && QUOTE_INDEX_SECID[security.id] === secid
|
|
157
|
+
if (!knownIndex && !(typeof row?.f12 === 'string' && MARKET_META[exchange]?.codePattern.test(row.f12))) continue
|
|
158
|
+
hasIdentity = true
|
|
94
159
|
if (!security) continue
|
|
95
160
|
if (seen.has(security.id)) throw new StockError('BAD_PAYLOAD', '报价身份冲突', 502)
|
|
96
161
|
seen.add(security.id)
|
|
97
162
|
// fltt=2时价格为已缩放数值, "-"表示停牌等无值;f124为来源Unix秒;成交额币种按市场派生(单一事实源 MARKET_META.currency)。
|
|
163
|
+
// f8 换手率(百分数原值)、f10 量比在沪深港美同义(实测 116.00700 与 105.AAPL 均可读)
|
|
98
164
|
const quoteAt = Number.isFinite(row.f124) ? new Date(row.f124 * 1000).toISOString() : null
|
|
99
165
|
const currency = MARKET_META[security.exchange]?.currency || 'CNY'
|
|
100
|
-
|
|
101
|
-
securityId: security.id, providerInstanceId: request.providerInstanceId, adapterId: 'eastmoney', providerSymbol:
|
|
166
|
+
const quote = normalizeQuote({
|
|
167
|
+
securityId: security.id, providerInstanceId: request.providerInstanceId, adapterId: 'eastmoney', providerSymbol: secid,
|
|
102
168
|
last: num(row.f2), previousClose: num(row.f18), open: num(row.f17), high: num(row.f15), low: num(row.f16),
|
|
103
169
|
volume: sharesFromLots(num(row.f5), security.exchange), volumeUnit: 'share', amount: num(row.f6), amountUnit: currency,
|
|
170
|
+
turnoverRate: rate(row.f8), volumeRatio: rate(row.f10),
|
|
104
171
|
quoteAt, timestampKind: 'trade',
|
|
105
172
|
receivedAt: ctx.now(), delayKind: 'unknown', delaySeconds: null, securityState: 'unknown',
|
|
106
|
-
})
|
|
173
|
+
})
|
|
174
|
+
if (quote.last === null && row.f2 !== '-') invalidPrices.add(security.id)
|
|
175
|
+
else items.push(quote)
|
|
107
176
|
}
|
|
177
|
+
if (rows.length && !hasIdentity) throw new StockError('BAD_PAYLOAD', '报价没有可校验的证券身份', 502)
|
|
108
178
|
}
|
|
109
|
-
await ingest(new Map(request.securities.map(s => [secidFor(s, ctx), s])))
|
|
110
|
-
//
|
|
111
|
-
// 只对首轮落空的美股补齐剩余候选,一次批量发完,不逐证券重试。
|
|
179
|
+
await ingest(new Map(request.securities.map(s => [QUOTE_INDEX_SECID[s.id] ?? secidFor(s, ctx), s])))
|
|
180
|
+
// 只对首轮落空的证券补齐同交易所候选,一次批量发完。
|
|
112
181
|
const orphanUS = request.securities.filter(s => !seen.has(s.id) && isUSExchange(s.exchange))
|
|
113
182
|
const altSymbols = new Map()
|
|
114
183
|
for (const security of orphanUS) for (const mktNum of usSecidPrefixes(security, ctx).slice(1)) altSymbols.set(`${mktNum}.${security.code}`, security)
|
|
115
184
|
if (altSymbols.size) await ingest(altSymbols)
|
|
116
|
-
|
|
185
|
+
if (!items.length && invalidPrices.size) throw new StockError('BAD_PAYLOAD', '报价价格字段异常', 502)
|
|
186
|
+
return { providerInstanceId: request.providerInstanceId, fetchedAt: ctx.now(), items, errors: request.securities.filter(s => !seen.has(s.id) || invalidPrices.has(s.id)).map(s => ({ securityId: s.id, code: 'NO_DATA', message: '来源未返回此证券报价' })) }
|
|
117
187
|
},
|
|
118
188
|
async catalog(request, ctx) {
|
|
119
189
|
const items = [], seen = new Set()
|
|
120
190
|
const PAGE_SIZE = 100, MAX_PAGES = 50
|
|
121
191
|
// 探针只拉一页: executor 单请求 8 秒预算内完成, 全量翻页是同步通道的职责
|
|
122
192
|
const pages = request.probe ? 1 : MAX_PAGES
|
|
123
|
-
let
|
|
124
|
-
|
|
193
|
+
let complete = false, total, hasDrift = false
|
|
194
|
+
for (let page = 1; page <= pages; page++) {
|
|
195
|
+
if (page > 1) await ctx.pauseForNextPage(0)
|
|
125
196
|
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`
|
|
126
197
|
const body = await getJson(ctx, url)
|
|
127
|
-
|
|
128
|
-
if (!
|
|
129
|
-
const
|
|
130
|
-
|
|
198
|
+
if (body.data === null) break
|
|
199
|
+
if (!isCount(body.data?.total)) throw new StockError('BAD_PAYLOAD', '目录总数异常', 502)
|
|
200
|
+
const reportedTotal = Number(body.data.total)
|
|
201
|
+
const diff = reportedTotal === 0 && body.data.diff === null ? [] : readDiff(body.data, '目录')
|
|
202
|
+
if (total !== undefined && total !== reportedTotal) hasDrift = true
|
|
203
|
+
total = Math.max(total ?? reportedTotal, reportedTotal)
|
|
131
204
|
for (const row of diff) {
|
|
132
|
-
const exchange =
|
|
133
|
-
if (exchange !== request.market || typeof row.f12 !== 'string' || !MARKET_META[request.market].codePattern.test(row.f12) || typeof row.f14 !== 'string' || !row.f14) continue
|
|
205
|
+
const exchange = EXCHANGE_BY_PREFIX[row?.f13]
|
|
206
|
+
if (exchange !== request.market || typeof row.f12 !== 'string' || !MARKET_META[request.market].codePattern.test(row.f12) || typeof row.f14 !== 'string' || !row.f14.trim()) continue
|
|
134
207
|
const id = securityId(exchange, row.f12)
|
|
135
208
|
if (seen.has(id)) throw new StockError('BAD_PAYLOAD', '目录身份冲突', 502)
|
|
136
209
|
seen.add(id)
|
|
137
210
|
items.push(makeSecurity(exchange, row.f12, row.f14, { cnspell: '', catalogSource: request.providerInstanceId }))
|
|
138
211
|
}
|
|
139
|
-
if (
|
|
140
|
-
if (
|
|
141
|
-
page++
|
|
212
|
+
if (items.length === total && !hasDrift) complete = true
|
|
213
|
+
if (items.length >= total || diff.length === 0) break
|
|
142
214
|
}
|
|
143
215
|
return { providerInstanceId: request.providerInstanceId, fetchedAt: ctx.now(), items, errors: [], complete }
|
|
144
216
|
},
|
|
145
217
|
async search(request, ctx) {
|
|
146
218
|
// 不限市场时扩大候选量: 单次响应要覆盖调用方负责的多个市场
|
|
147
219
|
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
|
|
220
|
+
const url = `${endpointOf(ctx, 'search')}?input=${encodeURIComponent(request.q)}&type=14&token=${SUGGEST_TOKEN}&count=${count}`
|
|
149
221
|
const body = await getJson(ctx, url)
|
|
150
|
-
const rows = body?.QuotationCodeTable?.Data
|
|
151
|
-
if (!Array.isArray(rows)) return { providerInstanceId: request.providerInstanceId, fetchedAt: ctx.now(), items: [], errors: [] }
|
|
152
222
|
const items = []
|
|
153
|
-
for (const row of
|
|
154
|
-
const exchange =
|
|
155
|
-
if (!exchange || (request.market && exchange !== request.market)) continue
|
|
156
|
-
// 美股候选写 usSymbols(代码→MktNum/JYS), kline 美股动态归属与腾讯 suffix 唯一数据来源
|
|
157
|
-
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() })
|
|
223
|
+
for (const row of suggestRows(body)) {
|
|
224
|
+
const exchange = EXCHANGE_BY_PREFIX[row?.MktNum]
|
|
158
225
|
const meta = MARKET_META[exchange]
|
|
159
|
-
if (!meta ||
|
|
226
|
+
if (!meta || (request.market && exchange !== request.market) || !isSearchInstrument(row)) continue
|
|
227
|
+
if (typeof row.Code !== 'string' || !meta.codePattern.test(row.Code) || typeof row.Name !== 'string' || !row.Name.trim()) continue
|
|
228
|
+
if (isUSExchange(exchange)) ctx.usSymbols?.set(`US:${row.Code}`, usSymbolOf(row, ctx.now()))
|
|
160
229
|
items.push(makeSecurity(exchange, row.Code, row.Name, { cnspell: typeof row.PinYin === 'string' ? row.PinYin.toLowerCase() : '', catalogSource: request.providerInstanceId }))
|
|
161
230
|
}
|
|
162
231
|
return { providerInstanceId: request.providerInstanceId, fetchedAt: ctx.now(), items, errors: [] }
|
|
@@ -165,32 +234,34 @@ export const eastmoney = {
|
|
|
165
234
|
secidOf(request, ctx) {
|
|
166
235
|
return secidFor({ exchange: request.market, code: request.code }, ctx)
|
|
167
236
|
},
|
|
168
|
-
//
|
|
169
|
-
async withUsFallback(request, ctx, buildUrl,
|
|
170
|
-
|
|
171
|
-
|
|
237
|
+
// 默认前缀没有数据时,只允许搜索证明的同市场候选重试一次。
|
|
238
|
+
async withUsFallback(request, ctx, buildUrl, field, label) {
|
|
239
|
+
const secid = this.secidOf(request, ctx)
|
|
240
|
+
let body = await getJson(ctx, buildUrl(secid))
|
|
241
|
+
if (hasHistory(body, secid, field, label)) return body
|
|
172
242
|
if (!isUSExchange(request.market)) throw new StockError('NO_DATA', `来源未返回此证券${label}`, 422)
|
|
173
243
|
const resolved = await this.resolveUsSecid(request, ctx)
|
|
174
|
-
|
|
244
|
+
const alternate = resolved && `${resolved.mktNum}.${request.code}`
|
|
245
|
+
if (!alternate || alternate === secid) throw new StockError('NO_DATA', `来源未返回此证券${label}`, 422)
|
|
246
|
+
body = await getJson(ctx, buildUrl(alternate))
|
|
247
|
+
if (!hasHistory(body, alternate, field, label)) throw new StockError('NO_DATA', `来源未返回此证券${label}`, 422)
|
|
175
248
|
ctx.usSymbols?.set(`US:${request.code}`, resolved)
|
|
176
|
-
body = await getJson(ctx, buildUrl(`${resolved.mktNum}.${request.code}`))
|
|
177
|
-
if (!hasData(body)) throw new StockError('NO_DATA', `来源未返回此证券${label}`, 422)
|
|
178
249
|
return body
|
|
179
250
|
},
|
|
180
251
|
async kline(request, ctx) {
|
|
181
252
|
const klt = KLT[request.period]
|
|
182
253
|
if (!klt) throw new StockError('INVALID_PARAM', '东财 K 线只支持日/周/月,分时请走分时能力', 400)
|
|
183
|
-
const body = await this.withUsFallback(request, ctx, secid => `${endpointOf(ctx, 'kline')}?secid=${secid}&fields1=f1,f2,f3&fields2=${KLINE_FIELDS}&klt=${klt}&fqt=1&end=20500101&lmt=${request.limit}`,
|
|
254
|
+
const body = await this.withUsFallback(request, ctx, secid => `${endpointOf(ctx, 'kline')}?secid=${secid}&fields1=f1,f2,f3&fields2=${KLINE_FIELDS}&klt=${klt}&fqt=1&end=20500101&lmt=${request.limit}`, 'klines', 'K线')
|
|
184
255
|
return buildKlineResponse(request, body.data, ctx)
|
|
185
256
|
},
|
|
186
257
|
async resolveUsSecid(request, ctx) {
|
|
187
|
-
const url = `${endpointOf(ctx, 'search')}?input=${encodeURIComponent(request.code)}&type=14&token
|
|
258
|
+
const url = `${endpointOf(ctx, 'search')}?input=${encodeURIComponent(request.code)}&type=14&token=${SUGGEST_TOKEN}&count=5`
|
|
188
259
|
const body = await getJson(ctx, url)
|
|
189
|
-
const row = body
|
|
190
|
-
return row ?
|
|
260
|
+
const row = suggestRows(body).find(r => r?.Code === request.code && marketMatchesUS(request.market, r.MktNum) && isSearchInstrument(r))
|
|
261
|
+
return row ? usSymbolOf(row, ctx.now()) : null
|
|
191
262
|
},
|
|
192
263
|
async trend(request, ctx) {
|
|
193
|
-
const body = await this.withUsFallback(request, ctx, secid => `${endpointOf(ctx, 'trend')}?secid=${secid}&fields1=f1,f2,f3,f4,f5,f6,f7,f8&fields2=${TREND_FIELDS}&iscr=0&ndays=1`,
|
|
264
|
+
const body = await this.withUsFallback(request, ctx, secid => `${endpointOf(ctx, 'trend')}?secid=${secid}&fields1=f1,f2,f3,f4,f5,f6,f7,f8&fields2=${TREND_FIELDS}&iscr=0&ndays=1`, 'trends', '分时')
|
|
194
265
|
// 东财分时的时间戳一律按北京时间给出(八市场实测: 日股 08:00 对应东京 09:00 开盘, 英股 16:00 对应伦敦 08:00),
|
|
195
266
|
// 不是市场本地时间; 之前按市场时区解释, 日韩英的横轴整体偏了几小时。
|
|
196
267
|
const candles = body.data.trends.map(row => {
|
package/src/providers/sina.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
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
|
-
const
|
|
4
|
+
const CATALOG_ENDPOINT = 'https://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.'
|
|
5
5
|
const HEADERS = { Referer: 'https://finance.sina.com.cn/', 'User-Agent': 'Mozilla/5.0' }
|
|
6
6
|
// 报价前缀与币种随市场派生(单一事实源);美股代码在来源侧是小写
|
|
7
7
|
const BY_MARKET = {
|
|
@@ -18,9 +18,45 @@ const symbolOf = security => {
|
|
|
18
18
|
}
|
|
19
19
|
// 探针代表证券(各市场实测可达的流动性标的)
|
|
20
20
|
const PROBE_SECURITY = { XSHG: '600519', XSHE: '000001', XHKG: '00700', XNAS: 'AAPL', XNYS: 'BABA' }
|
|
21
|
-
|
|
22
|
-
const
|
|
23
|
-
const
|
|
21
|
+
const count = value => { const parsed = numberOrNull(value); return parsed === null ? null : String(Math.round(parsed)) }
|
|
22
|
+
const PAGE_SIZE = 80, MAX_PAGES = 100, PAGE_GAP = 600, SHORT_PAGE_BACKOFF = 3 * 1000
|
|
23
|
+
const CATALOG_NODES = { XSHG: { prefix: 'sh', node: 'sh_a' }, XSHE: { prefix: 'sz', node: 'sz_a' } }
|
|
24
|
+
|
|
25
|
+
async function fetchCatalogJson(path, ctx) {
|
|
26
|
+
let response
|
|
27
|
+
try {
|
|
28
|
+
response = await ctx.fetch(`${CATALOG_ENDPOINT}${path}`, { headers: HEADERS, signal: ctx.signal, redirect: 'error' })
|
|
29
|
+
} catch (e) {
|
|
30
|
+
if (ctx.signal.aborted) throw new StockError('CANCELLED', '请求已取消', 503)
|
|
31
|
+
if (e instanceof StockError) throw e
|
|
32
|
+
throw new StockError('NETWORK', '无法连接行情来源', 502, { retryable: true })
|
|
33
|
+
}
|
|
34
|
+
if (!response.ok) throw new StockError('NETWORK', '来源服务暂不可用', 502, { retryable: true })
|
|
35
|
+
return response.json().catch(e => {
|
|
36
|
+
if (ctx.signal.aborted) throw new StockError('CANCELLED', '请求已取消', 503)
|
|
37
|
+
if (!(e instanceof SyntaxError)) throw new StockError('NETWORK', '无法读取目录响应', 502, { retryable: true })
|
|
38
|
+
throw new StockError('BAD_PAYLOAD', '目录响应不是JSON', 502)
|
|
39
|
+
})
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
async function fetchCatalogTotal(market, ctx) {
|
|
43
|
+
const { node } = CATALOG_NODES[market]
|
|
44
|
+
const body = await fetchCatalogJson(`getHQNodeStockCount?node=${node}`, ctx)
|
|
45
|
+
const total = Number(body)
|
|
46
|
+
if (!(typeof body === 'number' || typeof body === 'string' && /^\d+$/.test(body.trim())) || !Number.isSafeInteger(total) || total < 0) {
|
|
47
|
+
throw new StockError('BAD_PAYLOAD', '目录总数字段异常', 502)
|
|
48
|
+
}
|
|
49
|
+
return total
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async function fetchCatalogPage(market, ctx, page, size) {
|
|
53
|
+
const { prefix, node } = CATALOG_NODES[market]
|
|
54
|
+
const rows = await fetchCatalogJson(`getHQNodeData?page=${page}&num=${size}&sort=symbol&asc=1&node=${node}`, ctx)
|
|
55
|
+
if (!Array.isArray(rows) || rows.length > size) throw new StockError('BAD_PAYLOAD', '目录字段结构异常', 502)
|
|
56
|
+
const valid = rows.filter(row => typeof row?.code === 'string' && /^\d{6}$/.test(row.code) && row.symbol === `${prefix}${row.code}` && typeof row.name === 'string' && row.name.trim())
|
|
57
|
+
if (rows.length && !valid.length) throw new StockError('BAD_PAYLOAD', '目录没有可校验的证券身份', 502)
|
|
58
|
+
return { rows: valid, size: rows.length }
|
|
59
|
+
}
|
|
24
60
|
// 各市场字段位置:沪深34列、港股25列、美股36列,同一行内的列义由前缀决定
|
|
25
61
|
const FIELD_MAP = {
|
|
26
62
|
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]}` }),
|
|
@@ -30,14 +66,11 @@ const FIELD_MAP = {
|
|
|
30
66
|
const kindOf = providerSymbol => providerSymbol.startsWith('rt_hk') ? 'hk' : providerSymbol.startsWith('gb_') ? 'us' : 'cn'
|
|
31
67
|
const MIN_FIELDS = { cn: 32, hk: 20, us: 28 }
|
|
32
68
|
export const sina = {
|
|
33
|
-
descriptor: { adapterId: 'sina', capabilities: ['quotes', 'catalog'], markets: ['XSHG', 'XSHE', 'XHKG', 'XNAS', 'XNYS'], instruments: ['equity'], maxQuoteBatch: 60, credential: 'none', description: '新浪公开接口:免凭据,沪深港美行情与沪深目录' },
|
|
69
|
+
descriptor: { adapterId: 'sina', capabilities: ['quotes', 'catalog'], markets: ['XSHG', 'XSHE', 'XHKG', 'XNAS', 'XNYS'], instruments: ['equity'], maxQuoteBatch: 60, pagedCatalog: true, credential: 'none', description: '新浪公开接口:免凭据,沪深港美行情与沪深目录' },
|
|
34
70
|
async probe(request, ctx) {
|
|
35
71
|
if (request.capability === 'catalog') {
|
|
36
|
-
|
|
37
|
-
|
|
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)
|
|
72
|
+
const { rows } = await fetchCatalogPage(request.market, ctx, 1, 5)
|
|
73
|
+
if (!rows.length) throw new StockError('NO_DATA', '来源未返回可校验数据,暂不能确认能力就绪', 422)
|
|
41
74
|
return { status: 'ready', capability: 'catalog', market: request.market, instrument: 'equity' }
|
|
42
75
|
}
|
|
43
76
|
const security = request.securities?.[0] || { exchange: request.market, code: PROBE_SECURITY[request.market] || '600519' }
|
|
@@ -46,43 +79,32 @@ export const sina = {
|
|
|
46
79
|
return { status: 'ready', capability: 'quotes', market: request.market, instrument: 'equity' }
|
|
47
80
|
},
|
|
48
81
|
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
82
|
const items = [], seen = new Set()
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
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
|
|
83
|
+
const total = await fetchCatalogTotal(request.market, ctx)
|
|
84
|
+
const pages = Math.min(Math.ceil(total / PAGE_SIZE), MAX_PAGES)
|
|
85
|
+
let hasGap = false
|
|
86
|
+
for (let page = 1; page <= pages; page++) {
|
|
87
|
+
await ctx.pauseForNextPage(page === 1 ? 0 : PAGE_GAP)
|
|
88
|
+
const expected = Math.min(PAGE_SIZE, total - (page - 1) * PAGE_SIZE)
|
|
89
|
+
let current = await fetchCatalogPage(request.market, ctx, page, PAGE_SIZE)
|
|
90
|
+
if (current.size < expected) {
|
|
91
|
+
const first = current
|
|
92
|
+
await ctx.pauseForNextPage(SHORT_PAGE_BACKOFF)
|
|
93
|
+
current = await fetchCatalogPage(request.market, ctx, page, PAGE_SIZE)
|
|
94
|
+
// 重试即使补满,丢了已见身份也不能证明完整。
|
|
95
|
+
const confirmed = new Set(current.rows.map(row => row.code))
|
|
96
|
+
if (first.rows.some(row => !confirmed.has(row.code))) hasGap = true
|
|
97
|
+
if (first.rows.length > current.rows.length) current = first
|
|
71
98
|
}
|
|
72
|
-
|
|
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
|
|
99
|
+
if (current.size !== expected || current.rows.length !== current.size) hasGap = true
|
|
100
|
+
for (const row of current.rows) {
|
|
75
101
|
const id = securityId(request.market, row.code)
|
|
76
102
|
if (seen.has(id)) throw new StockError('BAD_PAYLOAD', '目录身份冲突', 502)
|
|
77
103
|
seen.add(id)
|
|
78
104
|
items.push(makeSecurity(request.market, row.code, row.name, { cnspell: '', catalogSource: request.providerInstanceId }))
|
|
79
105
|
}
|
|
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
106
|
}
|
|
85
|
-
return { providerInstanceId: request.providerInstanceId, fetchedAt: ctx.now(), items, errors: [], complete }
|
|
107
|
+
return { providerInstanceId: request.providerInstanceId, fetchedAt: ctx.now(), items, errors: [], complete: !hasGap && total > 0 && items.length === total }
|
|
86
108
|
},
|
|
87
109
|
async quotes(request, ctx) {
|
|
88
110
|
const symbols = new Map(request.securities.map(s => [symbolOf(s), s]))
|
|
@@ -112,7 +134,7 @@ export const sina = {
|
|
|
112
134
|
const mapped = FIELD_MAP[kind](f)
|
|
113
135
|
items.push(normalizeQuote({
|
|
114
136
|
securityId: security.id, providerInstanceId: request.providerInstanceId, adapterId: 'sina', providerSymbol,
|
|
115
|
-
last:
|
|
137
|
+
last: mapped.last, previousClose: mapped.previousClose, open: mapped.open, high: mapped.high, low: mapped.low,
|
|
116
138
|
volume: count(mapped.volume), volumeUnit: 'share', amount: count(mapped.amount), amountUnit: BY_MARKET[security.exchange].currency,
|
|
117
139
|
quoteAt: parseQuoteTime(mapped.quoteAt), timestampKind: 'trade',
|
|
118
140
|
receivedAt: ctx.now(), delayKind: 'unknown', delaySeconds: null, securityState: 'unknown',
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// 腾讯公开行情接口适配器:quotes+kline+trend(备源)。非官方端点,无SLA,随时可能失效;延迟未知,行情时间戳为来源快照时间。
|
|
2
2
|
import { normalizeQuote, parseQuoteTime, StockError, MARKET_META, sharesFromLots, amountFromWan, zonedUnixSeconds } from '../market-model.mjs'
|
|
3
|
+
import { isUSExchange, marketMatchesUS } from './us-markets.mjs'
|
|
3
4
|
// 分时时间戳与东财同一基准: 腾讯给的是北京时间
|
|
4
5
|
const SOURCE_ZONE = 'Asia/Shanghai'
|
|
5
6
|
// 官方默认端点表(key 供 instance.endpoints 覆盖, 反代/镜像场景由 ctx.endpoints 提供同名 key)
|
|
@@ -13,9 +14,8 @@ const endpointOf = (ctx, key) => ctx.endpoints?.[key] || DEFAULT_ENDPOINTS[key]
|
|
|
13
14
|
const SYMBOL_PREFIX = { XSHG: 'sh', XSHE: 'sz', XHKG: 'hk' }
|
|
14
15
|
// 美股 symbol 后缀由搜索联想 JYS 字段映射(2026-10-30 实测: suggest 返回 JYS="NASDAQ"/"NYSE"/"AMEX";
|
|
15
16
|
// 腾讯侧 .OQ/.N/裸代码同价有效, .A/.U 形态返回空数据——AMEX 走裸代码兜底)。
|
|
16
|
-
const
|
|
17
|
+
const US_KLINE_SYMBOL = { 105: { jys: 'NASDAQ', suffix: 'OQ' }, 106: { jys: 'NYSE', suffix: 'N' }, 107: { jys: 'AMEX', suffix: '' } }
|
|
17
18
|
// 美股行情端点要 us 前缀(实测 usAAPL 有效, 裸 AAPL 返回空);K线另有 JYS 后缀逻辑, 不复用这张表。
|
|
18
|
-
const isUSExchange = exchange => exchange === 'XNAS' || exchange === 'XNYS'
|
|
19
19
|
const symbolOf = security => isUSExchange(security.exchange) ? `us${security.code}` : SYMBOL_PREFIX[security.exchange] ? `${SYMBOL_PREFIX[security.exchange]}${security.code}` : `${security.code}`
|
|
20
20
|
// kline request 用 market 字段(exchange 是 security 形态的字段名); 港股 code 统一 5 位对齐腾讯 hk00700 实测形态。
|
|
21
21
|
const klineSymbolOf = request => {
|
|
@@ -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
|
}))
|
|
@@ -96,9 +99,10 @@ export const tencent = {
|
|
|
96
99
|
},
|
|
97
100
|
async kline(request, ctx) {
|
|
98
101
|
let symbol = klineSymbolOf(request)
|
|
99
|
-
if (request.market
|
|
102
|
+
if (isUSExchange(request.market)) {
|
|
100
103
|
const mapped = ctx.usSymbols?.get(`US:${request.code}`)
|
|
101
|
-
const
|
|
104
|
+
const known = marketMatchesUS(request.market, mapped?.mktNum) ? US_KLINE_SYMBOL[mapped.mktNum] : undefined
|
|
105
|
+
const suffix = known && mapped.jys === known.jys ? known.suffix : undefined
|
|
102
106
|
if (suffix === undefined) throw new StockError('UNSUPPORTED_CAPABILITY', '腾讯来源的美股K线需先经搜索建立代码映射', 422)
|
|
103
107
|
symbol = suffix ? `us${request.code}.${suffix}` : `us${request.code}`
|
|
104
108
|
}
|
|
@@ -152,6 +156,9 @@ export const tencent = {
|
|
|
152
156
|
if (!rows.length || !day) throw new StockError('NO_DATA', '来源未返回此证券分时', 422)
|
|
153
157
|
const stamp = `${day[1]}-${day[2]}-${day[3]}`
|
|
154
158
|
const candles = []
|
|
159
|
+
// minute/query 的第 3、4 列是当日累计量/额(实测: 末条等于全天成交量, 且单调递增),
|
|
160
|
+
// 而 candle.volume/amount 的契约是与东财 f56/f57 一致的区间增量, 这里必须做差分
|
|
161
|
+
let prevVolume = 0, prevAmount = 0
|
|
155
162
|
for (const row of rows) {
|
|
156
163
|
const cols = String(row).split(' ')
|
|
157
164
|
// 价格必须是纯数字才收: 上游偶有畸形行, 与其把 NaN 画进图里, 不如少一点
|
|
@@ -159,7 +166,14 @@ export const tencent = {
|
|
|
159
166
|
const time = `${cols[0].padStart(4, '0').slice(0, 2)}:${cols[0].padStart(4, '0').slice(2)}`
|
|
160
167
|
const price = num(cols[1])
|
|
161
168
|
if (price == null) continue
|
|
162
|
-
|
|
169
|
+
// 累计量偶尔回退(来源补数/清理), 差分取 0 而不是画负数
|
|
170
|
+
const cumulativeVolume = sharesFromLots(num(cols[2]), request.market)
|
|
171
|
+
const cumulativeAmount = num(cols[3])
|
|
172
|
+
const volume = cumulativeVolume === null ? null : Math.max(0, cumulativeVolume - prevVolume)
|
|
173
|
+
const amount = cumulativeAmount === null ? null : Math.max(0, cumulativeAmount - prevAmount)
|
|
174
|
+
if (cumulativeVolume !== null) prevVolume = cumulativeVolume
|
|
175
|
+
if (cumulativeAmount !== null) prevAmount = cumulativeAmount
|
|
176
|
+
candles.push({ time, at: zonedUnixSeconds(`${stamp} ${time}`, SOURCE_ZONE), open: price, close: price, high: price, low: price, volume, amount, avg: null })
|
|
163
177
|
}
|
|
164
178
|
if (!candles.length) throw new StockError('NO_DATA', '来源分时数据不可解析', 422)
|
|
165
179
|
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: '来源未返回此证券报价' })) }
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
// 东财市场号映射到插件的美股身份;插件在 XNYS 下同时收录 NYSE 和 AMEX。
|
|
2
|
+
export const US_MARKET_EXCHANGE = { 105: 'XNAS', 106: 'XNYS', 107: 'XNYS' }
|
|
3
|
+
export const isUSExchange = exchange => exchange === 'XNAS' || exchange === 'XNYS'
|
|
4
|
+
export const marketMatchesUS = (market, mktNum) => isUSExchange(market) && US_MARKET_EXCHANGE[mktNum] === market
|