@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.
@@ -2,8 +2,8 @@
2
2
  // sessions 是该市场连续竞价的时段(市场本地时间), 用来判断报价此刻处在交易中/午休/休市;
3
3
  // 只描述周内时点, 法定节假日仍以数据本身(最后一根K线的日期)为准。
4
4
  export const MARKET_META = {
5
- XSHG: { currency: 'CNY', timezone: 'Asia/Shanghai', priceScale: 2, codePattern: /^\d{6}$/, verifiedByDefault: true, sessions: [['09:30', '11:30'], ['13:00', '15:00']], tag: '沪A' },
6
- XSHE: { currency: 'CNY', timezone: 'Asia/Shanghai', priceScale: 2, codePattern: /^\d{6}$/, verifiedByDefault: true, sessions: [['09:30', '11:30'], ['13:00', '15:00']], tag: '深A' },
5
+ XSHG: { currency: 'CNY', timezone: 'Asia/Shanghai', priceScale: 2, codePattern: /^\d{6}$/, verifiedByDefault: true, auction: ['09:15', '09:25'], sessions: [['09:30', '11:30'], ['13:00', '15:00']], tag: '沪A' },
6
+ XSHE: { currency: 'CNY', timezone: 'Asia/Shanghai', priceScale: 2, codePattern: /^\d{6}$/, verifiedByDefault: true, auction: ['09:15', '09:25'], sessions: [['09:30', '11:30'], ['13:00', '15:00']], tag: '深A' },
7
7
  XHKG: { currency: 'HKD', timezone: 'Asia/Hong_Kong', priceScale: 2, codePattern: /^\d{4,5}$/, verifiedByDefault: true, sessions: [['09:30', '12:00'], ['13:00', '16:00']], tag: '港股' },
8
8
  XNAS: { currency: 'USD', timezone: 'America/New_York', priceScale: 2, codePattern: /^[A-Z]{1,5}$/, verifiedByDefault: true, sessions: [['09:30', '16:00']], tag: '纳斯达克' },
9
9
  XNYS: { currency: 'USD', timezone: 'America/New_York', priceScale: 2, codePattern: /^[A-Z]{1,5}$/, verifiedByDefault: true, sessions: [['09:30', '16:00']], tag: '纽交所' },
@@ -17,28 +17,100 @@ const SESSION_FORMATTERS = new Map()
17
17
  function sessionFormatter(timeZone) {
18
18
  let formatter = SESSION_FORMATTERS.get(timeZone)
19
19
  if (formatter === undefined) {
20
- formatter = new Intl.DateTimeFormat('en-US', { timeZone, hour12: false, weekday: 'short', hour: '2-digit', minute: '2-digit' })
20
+ formatter = new Intl.DateTimeFormat('en-US', { timeZone, hourCycle: 'h23', weekday: 'short', year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' })
21
21
  SESSION_FORMATTERS.set(timeZone, formatter)
22
22
  }
23
23
  return formatter
24
24
  }
25
-
26
- // 报价此刻落在市场交易日的哪个阶段; 周末恒为休市, 节假日不做推断(没有日历能力时会误判)
27
- export function sessionStateOf(exchange, nowMs) {
28
- const meta = MARKET_META[exchange]
29
- if (!meta?.sessions?.length) return 'unknown'
30
- const parts = sessionFormatter(meta.timezone).formatToParts(new Date(nowMs))
25
+ const toMinutes = stamp => { const [hh, mm] = stamp.split(':').map(Number); return hh * 60 + mm }
26
+ const WEEKEND = new Set(['Sat', 'Sun'])
27
+ function zonedParts(timeZone, nowMs) {
28
+ const parts = sessionFormatter(timeZone).formatToParts(new Date(nowMs))
31
29
  const pick = type => parts.find(part => part.type === type)?.value
32
- if (pick('weekday') === 'Sat' || pick('weekday') === 'Sun') return 'closed'
33
- const minutes = (Number(pick('hour')) % 24) * 60 + Number(pick('minute'))
30
+ return { weekday: pick('weekday'), date: `${pick('year')}-${pick('month')}-${pick('day')}`, minutes: (Number(pick('hour')) % 24) * 60 + Number(pick('minute')) }
31
+ }
32
+ // 市场本地日期: 日历记录、休市判断都按证券所属市场的自然日, 不能统一用北京时间
33
+ export const marketDate = (exchange, nowMs) => MARKET_META[exchange] ? zonedParts(MARKET_META[exchange].timezone, nowMs).date : new Date(nowMs).toISOString().slice(0, 10)
34
+ // 某一时区的时钟文本: 分时横轴用来源时区(东财/腾讯统一按北京时间), 与在线返回的 time 同一基准
35
+ export const clockInZone = (timeZone, unixSeconds) => {
36
+ const minutes = zonedParts(timeZone, unixSeconds * 1000).minutes
37
+ return `${String(Math.floor(minutes / 60)).padStart(2, '0')}:${String(minutes % 60).padStart(2, '0')}`
38
+ }
39
+ // 来源给的本地时刻(如 2026-11-16 09:30)换算成 Unix 秒: 分时的 at 必须是来源时刻, 让客户端按真实时间对齐横轴
40
+ const STAMP_FORMATTERS = new Map()
41
+ const stampFormatter = timeZone => {
42
+ let formatter = STAMP_FORMATTERS.get(timeZone)
43
+ if (formatter === undefined) {
44
+ formatter = new Intl.DateTimeFormat('en-US', { timeZone, hour12: false, year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' })
45
+ STAMP_FORMATTERS.set(timeZone, formatter)
46
+ }
47
+ return formatter
48
+ }
49
+ export function zonedUnixSeconds(stamp, timeZone) {
50
+ const match = /^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2})/.exec(stamp)
51
+ if (!match || !timeZone) return null
52
+ const [, y, mo, d, hh, mm] = match.map(Number)
53
+ // 先当成 UTC 造一个候选时刻, 再用该时区的偏移把它拗回去(含夏令时)
54
+ const localAsUtc = Date.UTC(y, mo - 1, d, hh, mm)
55
+ const parts = stampFormatter(timeZone).formatToParts(new Date(localAsUtc))
56
+ const rendered = Object.fromEntries(parts.map(part => [part.type, part.value]))
57
+ const asUtc = Date.UTC(Number(rendered.year), Number(rendered.month) - 1, Number(rendered.day), Number(rendered.hour) % 24, Number(rendered.minute), Number(rendered.second))
58
+ return Math.floor((localAsUtc - (asUtc - localAsUtc)) / 1000)
59
+ }
60
+ function addDays(date, days) { const [y, m, d] = date.split('-').map(Number); return new Date(Date.UTC(y, m - 1, d + days)).toISOString().slice(0, 10) }
61
+ const isWeekend = date => { const day = new Date(`${date}T00:00:00Z`).getUTCDay(); return day === 0 || day === 6 }
62
+ // 市场本地时刻 → epoch: 先按 UTC 构造, 再用该时区的实际偏移回推(两次足够覆盖 DST 偏移)
63
+ function epochOf(timeZone, date, minutes) {
64
+ const [y, m, d] = date.split('-').map(Number)
65
+ const target = Date.UTC(y, m - 1, d, Math.floor(minutes / 60), minutes % 60)
66
+ let stamp = target
67
+ for (let i = 0; i < 3; i++) {
68
+ const local = zonedParts(timeZone, stamp)
69
+ const [ly, lm, ld] = local.date.split('-').map(Number)
70
+ const delta = target - Date.UTC(ly, lm - 1, ld, Math.floor(local.minutes / 60), local.minutes % 60)
71
+ if (delta === 0) break
72
+ stamp += delta
73
+ }
74
+ return stamp
75
+ }
76
+ const firstStartOf = meta => toMinutes((meta.auction || meta.sessions[0])[0])
77
+ // 下一个交易日的首个可采集时刻; 有日历按 isOpen 跳过节假日, 无日历只能跳过周末
78
+ function nextOpenAt(meta, fromDate, calendarDays) {
79
+ for (let offset = 1; offset <= 60; offset++) {
80
+ const date = addDays(fromDate, offset)
81
+ const open = calendarDays?.get(date)
82
+ if (open === false) continue
83
+ if (open === undefined && isWeekend(date)) continue
84
+ return epochOf(meta.timezone, date, firstStartOf(meta))
85
+ }
86
+ return epochOf(meta.timezone, addDays(fromDate, 1), firstStartOf(meta))
87
+ }
88
+ // 报价此刻落在市场交易日的哪个阶段, 并给出下一次可采集时刻; 节假日只由日历记录判定
89
+ export function marketStateOf(exchange, nowMs, calendarDays = null) {
90
+ const meta = MARKET_META[exchange]
91
+ if (!meta?.sessions?.length) return { state: 'unknown' }
92
+ const local = zonedParts(meta.timezone, nowMs)
93
+ const dayOpen = calendarDays?.get(local.date)
94
+ if (dayOpen === false) return { state: 'closed', nextAt: nextOpenAt(meta, local.date, calendarDays) }
95
+ if (dayOpen === undefined && WEEKEND.has(local.weekday)) return { state: 'closed', nextAt: nextOpenAt(meta, local.date, calendarDays) }
96
+ const minutes = local.minutes
97
+ if (meta.auction) {
98
+ const [auctionFrom, auctionTo] = meta.auction.map(toMinutes)
99
+ if (minutes < auctionFrom) return { state: 'preopen', nextAt: epochOf(meta.timezone, local.date, auctionFrom) }
100
+ if (minutes < auctionTo) return { state: 'auction' }
101
+ }
34
102
  const bounds = meta.sessions.map(([from, to]) => [toMinutes(from), toMinutes(to)])
35
- if (minutes < bounds[0][0]) return 'preopen'
36
- if (bounds.some(([from, to]) => minutes >= from && minutes < to)) return 'trading'
103
+ if (minutes < bounds[0][0]) return { state: 'preopen', nextAt: epochOf(meta.timezone, local.date, bounds[0][0]) }
104
+ if (bounds.some(([from, to]) => minutes >= from && minutes < to)) return { state: 'trading' }
37
105
  // 午休只存在于两段之间: 只比前一段的收尾会把收盘后也算成午休
38
- if (bounds.some(([, to], index) => index < bounds.length - 1 && minutes >= to && minutes < bounds[index + 1][0])) return 'break'
39
- return 'closed'
106
+ const breakIndex = bounds.findIndex(([, to], index) => index < bounds.length - 1 && minutes >= to && minutes < bounds[index + 1][0])
107
+ if (breakIndex >= 0) return { state: 'break', nextAt: epochOf(meta.timezone, local.date, bounds[breakIndex + 1][0]) }
108
+ return { state: 'closed', nextAt: nextOpenAt(meta, local.date, calendarDays) }
109
+ }
110
+ // 兼容旧调用面: 只要阶段
111
+ export function sessionStateOf(exchange, nowMs) {
112
+ return marketStateOf(exchange, nowMs).state
40
113
  }
41
- const toMinutes = stamp => { const [hh, mm] = stamp.split(':').map(Number); return hh * 60 + mm }
42
114
 
43
115
  export function securityId(exchange, code, instrument = 'equity') {
44
116
  const meta = MARKET_META[exchange]
@@ -1,9 +1,13 @@
1
1
  import { fail } from './market-model.mjs'
2
+ import { CAPABILITIES } from './schemas.mjs'
3
+ const KNOWN = new Set(CAPABILITIES)
4
+ // 合同: 每个声明的能力都要有同名方法, 且 probe 返回 {status, capability, market, instrument};
5
+ // capability 必须回填被探的能力名, 否则设置页会判不可用(不能拿行情接口冒充分时)
2
6
  export function createRegistry(providers = []) {
3
7
  const entries = new Map()
4
8
  for (const provider of providers) {
5
9
  const d = provider.descriptor
6
- if (!d || entries.has(d.adapterId) || typeof provider.probe !== 'function' || d.capabilities.some(c => !['quotes', 'catalog', 'search', 'calendar', 'kline'].includes(c) || typeof provider[c] !== 'function') || (d.capabilities.includes('quotes') && !(d.maxQuoteBatch > 0))) fail('INVALID_ADAPTER', '数据适配器合同不完整', 422)
10
+ if (!d || entries.has(d.adapterId) || typeof provider.probe !== 'function' || d.capabilities.some(c => !KNOWN.has(c) || typeof provider[c] !== 'function') || (d.capabilities.includes('quotes') && !(d.maxQuoteBatch > 0))) fail('INVALID_ADAPTER', '数据适配器合同不完整', 422)
7
11
  entries.set(d.adapterId, provider)
8
12
  }
9
13
  const get = id => entries.get(id) || fail('UNKNOWN_ADAPTER', '未安装此数据适配器', 422)
@@ -1,33 +1,100 @@
1
1
  import { fail } from './market-model.mjs'
2
+ // 回探节奏: 面板活跃时每隔这么久把所有已降级路由的上级探一遍
3
+ export const RECOVERY_PROBE_MS = 5 * 60 * 1000
4
+ // 探测退避上限: 一个实例连续探不通时, 间隔按倍数涨到这么久就不再涨
5
+ export const PROBE_BACKOFF_MAX_MS = 60 * 60 * 1000
6
+ // 触发降级的错误码: 别的错误码说明问题不在网络上, 换源也没用
7
+ // 人机验证也是端起端落: 过验证码就好, 与网络故障一样按轮计次, 攒满三轮切到备源
8
+ export const TRANSIENT_CODES = ['NETWORK', 'TIMEOUT', 'CHALLENGE']
2
9
  export function createRouter(getConfig, now = Date.now, changed = () => {}) {
3
10
  const states = new Map()
11
+ // 主源与备用源构成一个环: 顺序即优先级, 降级沿环往下走一格, 走到头回到主源
12
+ const ringOf = route => [route.primaryInstanceId, ...route.fallbackInstanceIds]
4
13
  function state(route) {
5
- if (!states.has(route.id)) states.set(route.id, { providerInstanceId: route.primaryInstanceId, routeEpoch: 0, failures: 0, switchedAt: null })
14
+ if (!states.has(route.id)) states.set(route.id, { providerInstanceId: route.primaryInstanceId, routeEpoch: 0, failures: 0, ringIndex: 0, probes: new Map() })
6
15
  return states.get(route.id)
7
16
  }
17
+ function probeOf(s, instanceId) {
18
+ if (!s.probes.has(instanceId)) s.probes.set(instanceId, { failures: 0, until: 0 })
19
+ return s.probes.get(instanceId)
20
+ }
21
+ // 业务里刚失败的实例先歇一个周期再探: 降级不代表探不通, 不推进指数档位
22
+ function rest(s, instanceId) {
23
+ const probe = probeOf(s, instanceId)
24
+ probe.until = Math.max(probe.until, now() + RECOVERY_PROBE_MS)
25
+ }
26
+ // 探不通才推进档位: 坏源不该被每轮点名
27
+ function failProbe(s, instanceId) {
28
+ const probe = probeOf(s, instanceId)
29
+ probe.failures += 1
30
+ probe.until = now() + Math.min(RECOVERY_PROBE_MS * 2 ** (probe.failures - 1), PROBE_BACKOFF_MAX_MS)
31
+ }
32
+ function clearProbe(s, instanceId) {
33
+ const probe = probeOf(s, instanceId)
34
+ probe.failures = 0; probe.until = 0
35
+ }
8
36
  function find(id) { return getConfig().routes.find(r => r.id === id) || fail('NO_ROUTE', '未配置此数据路由', 422) }
9
37
  return {
10
38
  select(capability, market, instrument = 'equity') {
11
39
  const config = getConfig(), route = config.routes.find(r => r.capability === capability && r.market === market && r.instrument === instrument)
12
40
  if (!route) fail('NO_ROUTE', '未配置该市场的数据来源', 422)
13
41
  const selected = state(route), instance = config.providers.find(p => p.id === selected.providerInstanceId)
14
- if (!instance || instance.enabled === false) fail('NO_ROUTE', '数据源已停用', 422)
42
+ if (!instance) fail('NO_ROUTE', '引用的数据源不存在', 422)
43
+ if (instance.enabled === false) fail('NO_ROUTE', '数据源已停用', 422)
15
44
  return { route, instance, routeEpoch: selected.routeEpoch }
16
45
  },
17
- recordRound(id, error) {
46
+ // 环上的下一格: 降级与同轮补救共用, 走到最后一个时回到主源
47
+ nextInRing(id, instanceId) {
48
+ const ring = ringOf(find(id))
49
+ const index = ring.indexOf(instanceId)
50
+ return ring.length < 2 || index === -1 ? null : ring[(index + 1) % ring.length]
51
+ },
52
+ // 可回探的上级: 从主源往下, 跳过还在歇着或退避中的实例
53
+ recoveryCandidates(id) {
54
+ const route = find(id), s = state(route), at = now()
55
+ return s.ringIndex === 0 ? [] : ringOf(route).slice(0, s.ringIndex).filter(instanceId => probeOf(s, instanceId).until <= at)
56
+ },
57
+ // 探测汇报: 就绪就回切并清掉该实例的退避, 否则推进它的退避档位。
58
+ // 探测期间路由可能又变过, 代次不符就当作过期汇报丢掉
59
+ recordProbe(id, instanceId, ready, expectedEpoch) {
18
60
  const route = find(id), s = state(route)
19
- s.failures = error && ['NETWORK', 'TIMEOUT'].includes(error.code) ? s.failures + 1 : 0
20
- if (s.failures >= 3 && route.failoverMode === 'network' && s.providerInstanceId === route.primaryInstanceId && route.fallbackInstanceIds.length) {
21
- s.providerInstanceId = route.fallbackInstanceIds[0]; s.routeEpoch++; s.switchedAt = now(); s.failures = 0; changed(id)
61
+ if (!ready) return failProbe(s, instanceId)
62
+ const ring = ringOf(route), index = ring.indexOf(instanceId)
63
+ if (index === -1 || index >= s.ringIndex || s.routeEpoch !== expectedEpoch) return
64
+ // 探测只证明上游能出数, 不证明这个实例派得了活: 没填预算的实例切过去就是 BUDGET_UNKNOWN
65
+ const instance = getConfig().providers.find(p => p.id === instanceId)
66
+ if (!instance || instance.enabled === false || instance.budget?.requestsPerMinute === null) return
67
+ clearProbe(s, instanceId)
68
+ s.ringIndex = index; s.providerInstanceId = instanceId; s.routeEpoch++; s.failures = 0; changed(id)
69
+ },
70
+ recordRound(id, error) {
71
+ const route = find(id), s = state(route), ring = ringOf(route)
72
+ // 业务成功就是最好的证据: 当前实例的探测退避清零
73
+ if (!error) { s.failures = 0; return clearProbe(s, s.providerInstanceId) }
74
+ s.failures = TRANSIENT_CODES.includes(error.code) ? s.failures + 1 : 0
75
+ if (s.failures < 3 || route.failoverMode !== 'network' || ring.length < 2) return
76
+ // 沿环找下一个真正能用的成员: 停用或没填预算的实例派不了活, 落进去整条路由就死了
77
+ const config = getConfig()
78
+ let next = s.ringIndex
79
+ for (let step = 1; step <= ring.length; step++) {
80
+ const index = (s.ringIndex + step) % ring.length, instance = config.providers.find(p => p.id === ring[index])
81
+ if (instance && instance.enabled !== false && instance.budget?.requestsPerMinute !== null) { next = index; break }
22
82
  }
83
+ if (next === s.ringIndex) return
84
+ s.failures = 0
85
+ rest(s, ring[s.ringIndex])
86
+ s.ringIndex = next; s.providerInstanceId = ring[next]; s.routeEpoch++; changed(id)
23
87
  },
24
88
  switchPrimary(id, expectedEpoch) {
25
89
  const route = find(id), s = state(route)
26
90
  if (s.routeEpoch !== expectedEpoch) fail('ROUTE_CONFLICT', '路由已变化,请重新检查', 409)
27
- if (s.switchedAt !== null && now() - s.switchedAt < 10 * 60 * 1000) fail('ROUTE_DWELL', '备用源驻留期尚未结束', 409)
28
- s.providerInstanceId = route.primaryInstanceId; s.routeEpoch++; s.failures = 0; s.switchedAt = null; changed(id)
91
+ clearProbe(s, route.primaryInstanceId)
92
+ s.providerInstanceId = route.primaryInstanceId; s.routeEpoch++; s.failures = 0; s.ringIndex = 0; changed(id)
29
93
  },
30
- selections: () => Object.fromEntries(getConfig().routes.map(r => [r.id, { ...state(r) }])),
94
+ selections: () => Object.fromEntries(getConfig().routes.map(r => {
95
+ const s = state(r)
96
+ return [r.id, { providerInstanceId: s.providerInstanceId, routeEpoch: s.routeEpoch, failures: s.failures, ringIndex: s.ringIndex }]
97
+ })),
31
98
  reset() { states.clear() },
32
99
  }
33
100
  }