@mzzsfy/dsh-stock-assistant 0.4.0 → 0.5.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/README.md +20 -12
- package/package.json +1 -1
- package/src/application.mjs +28 -4
- package/src/client.js +28 -5
- package/src/executor.mjs +7 -4
- package/src/index.js +3 -2
- package/src/providers/eastmoney.mjs +40 -41
- package/src/providers/finnhub.mjs +53 -0
- package/src/providers/tushare.mjs +1 -1
- package/src/routes.mjs +1 -0
- package/src/schemas.mjs +7 -7
- package/src/state.mjs +8 -0
- package//345/205/274/345/256/271/346/200/247/346/265/213/350/257/225.md +20 -2
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
DSH 全局股票工具。左侧“股票”入口打开独立主页面,无会话也可使用。切换、关闭 DSH 会话或临时打开其他工具,不会清除股票工具的搜索、详情、排序、滚动位置和设置草稿。
|
|
4
4
|
|
|
5
|
-
支持八个市场(沪/深 A 股、港股、美股 NYSE/NASDAQ
|
|
5
|
+
支持八个市场(沪/深 A 股、港股、美股 NYSE/NASDAQ、日经、韩证、伦敦):自选(置顶、分组、组内涨跌统计与折叠、拖拽排序、别名、删除撤销)、名称/代码/拼音首字母搜索(多市场候选带币种徽标)、行情与 K 线图表(分时/日K/周K/月K,MA/EMA/BOLL/BBI 可分别开关、成交量副图、昨收/价格标记/区间高低参考线,lightweight-charts 渲染)、价格标记(成本/卖价,单只最多 12 条,等权成本均价与浮盈/潜在收益)、悬浮盯盘(列表与图形双模式、只盯勾选的标的、可拖动、常驻在所有面板之上)、基础详情、涨跌排序、手动刷新、暂停采集,以及数据源与能力路由设置(含"应用推荐配置"与按市场配置 K 线)。不做交易、持仓管理或资讯;价格提醒仅限自选标记价穿越,经页内/系统通知或已安装的通知插件呈现。
|
|
6
6
|
|
|
7
7
|
## 数据结构与持久化
|
|
8
8
|
|
|
@@ -24,7 +24,7 @@ DSH 全局股票工具。左侧“股票”入口打开独立主页面,无会
|
|
|
24
24
|
|
|
25
25
|
## 初次使用
|
|
26
26
|
|
|
27
|
-
|
|
27
|
+
全新安装即内置默认数据源:东财、新浪、腾讯、雪球四个免凭据公开源(东财主源,新浪/腾讯/雪球按市场做报价或 K 线备用;保守预算 60 次/分起步),八个市场的目录、搜索、报价、K 线共 32 条能力路由全部配好,无需任何注册。打开后即可「检查所有来源能力」→ 保存 → 同步目录 → 用「浏览市场」翻页浏览全市场证券并直接加自选,或按代码/中文名/拼音首字母搜索。日经、韩证、伦敦三个市场由东财全球搜索与目录页覆盖,其成交额字段来源恒给 0,界面按缺失呈现而不是显示「0」。
|
|
28
28
|
|
|
29
29
|
- 顶栏「浏览市场」提供无目的浏览:按市场分页查看全部 A 股,行内一键加自选;目录未同步时页内有同步引导。
|
|
30
30
|
- 搜索在目录未就绪时不再死路:错误提示带「前往浏览市场」直达入口。
|
|
@@ -32,7 +32,7 @@ DSH 全局股票工具。左侧“股票”入口打开独立主页面,无会
|
|
|
32
32
|
|
|
33
33
|
需要目录/日历(搜索、日历休市调度)或更正式的数据合同(权限表、配额文档、服务协议)时走 Tushare:
|
|
34
34
|
|
|
35
|
-
1.
|
|
35
|
+
1. 当前 main 的凭据优先由宿主凭据服务托管:在“股票 → 设置 → 数据源”实例卡的密钥输入框直接录入(写入宿主凭据存储,不回显、不落插件配置);服务接口不全时回退 **启动 DSH 的 Host 进程环境变量** `DSH_STOCK_TUSHARE_TOKEN`(或同层 `.env`)。0.4.0 发布版没有凭据服务,只读该环境变量。插件只保存引用名/变量名与数据路由;修改引用名不会迁移已有密钥。
|
|
36
36
|
2. 打开“股票 → 设置”,添加数据源实例,填写账号实际允许的请求预算。同一账号的实例使用同一“共享额度组”。新实例额度默认为未知;未填写时只允许每组最多每10秒一次主动探针,实际目录同步与报价采集均禁用,不假设任何免费套餐额度。
|
|
37
37
|
3. 为上海/深圳分别选择证券目录、报价、交易日历来源。可以只启用自己需要的市场和能力。
|
|
38
38
|
4. 点击“检查所有来源能力”。所有被引用能力检查就绪后保存。检查消耗该来源请求额度,检查通过不代表任何第三方展示许可。
|
|
@@ -45,11 +45,12 @@ Tushare 的 `rt_k`、`stock_basic`、`trade_cal` 权限分别由账号决定。
|
|
|
45
45
|
|
|
46
46
|
## 数据源适配器
|
|
47
47
|
|
|
48
|
-
|
|
48
|
+
生产内置六个适配器,各自独立文件(`src/providers/`),互不依赖:
|
|
49
49
|
|
|
50
50
|
| 适配器 | 能力 | 凭据 | 边界 |
|
|
51
51
|
| --- | --- | --- | --- |
|
|
52
|
-
| `tushare` | quotes / catalog / calendar |
|
|
52
|
+
| `tushare` | quotes / catalog / calendar | 宿主凭据服务或环境变量(默认引用 `DSH_STOCK_TUSHARE_TOKEN`) | 唯一有正式权限表、配额文档与服务协议的渠道;三种能力可分开路由 |
|
|
53
|
+
| `finnhub` | quotes | 宿主凭据服务或环境变量(默认引用 `DSH_STOCK_FINNHUB_TOKEN`) | 美股 XNAS/XNYS 实时报价;免费档不含 K 线,单只一请求,不适合持续轮询 |
|
|
53
54
|
| `tencent` | quotes / kline | 免凭据 | 公开网页接口;非官方、无 SLA,协议随时可能变化 |
|
|
54
55
|
| `sina` | quotes / catalog | 免凭据 | 同上;价格恒三位小数,适配器裁剪到分;目录仅沪深 |
|
|
55
56
|
| `eastmoney` | quotes / catalog / search / kline | 免凭据 | 同上;目录分页抓全量(单市场约2500只,页频受限流退避约束),联想搜索支持中文/代码/首字母拼音;K 线含分时与日/周/月,分时时间戳统一按北京时间解析 |
|
|
@@ -59,9 +60,9 @@ Tushare 的 `rt_k`、`stock_basic`、`trade_cal` 权限分别由账号决定。
|
|
|
59
60
|
|
|
60
61
|
混合路由:可把沪深行情分别路由到不同来源(沪市腾讯、深市东财、新浪备用等),目录/搜索用东财、日历用 Tushare——全部在设置页按市场/能力勾选。同一报价的现价、昨收、涨跌和时间始终来自同一适配器,不混拼字段。
|
|
61
62
|
|
|
62
|
-
免凭据机制:实例 `
|
|
63
|
+
免凭据机制:实例 `credentialRef=null` 时跳过凭据解析(宿主凭据服务或进程环境变量),但 schema 强制其声明保守预算(防无界请求);凭据型适配器切换回档时自动恢复引用名输入框。
|
|
63
64
|
|
|
64
|
-
新增平台步骤:在 `src/providers/` 实现标准合同(`descriptor.credential` 声明 `'
|
|
65
|
+
新增平台步骤:在 `src/providers/` 实现标准合同(`descriptor.credential` 声明 `'none'` 或默认引用名 + 能力方法 + `probe`),在 `application.mjs` 的 registry 登记,测试放 `test/public-providers.test.mjs` 或 `test/<adapter>.test.mjs`。UI、存储、自选模型零改动。
|
|
65
66
|
|
|
66
67
|
报价路由可选一个备用源,自动切换默认关闭。开启后,连续三轮完全由 NETWORK/TIMEOUT 失败才整条路由切换;权限错误、额度限制与逐证券缺失不触发。切换增加运行代次并丢弃旧请求,最短驻留10分钟,回主源必须手动检查。设置视图显示当前备用选择与回主源操作。
|
|
67
68
|
|
|
@@ -75,9 +76,15 @@ HTTP 路径前缀 `/api/stock-assistant`:`snapshot/search/watchlist/preference
|
|
|
75
76
|
|
|
76
77
|
## 安装与开发
|
|
77
78
|
|
|
78
|
-
|
|
79
|
+
已发布 npm(当前 0.4.0),安装与升级走正式包:
|
|
79
80
|
|
|
80
|
-
|
|
81
|
+
```sh
|
|
82
|
+
dsh plugin --profile web add @mzzsfy/dsh-stock-assistant
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
随后重启该 profile 的宿主。仓库 README 对应 `main`(可能含尚未发版的改动),npm 页面上的说明是发版时的快照。仓库开发挂载遵循根目录 `scripts/dev-link.mjs dsh-stock-assistant`(工作副本 junction),装载层变更不走热重载,同样需要重启宿主。
|
|
86
|
+
|
|
87
|
+
要求 Node>=22,宿主已有 `webServer`(包括upgrade)、`storageDomain` 与有效 backend。0.4.0 发布版只读 Host 进程环境变量、不注入 `credentials`;当前 main 已把它列入注入服务,由宿主凭据服务托管,接口不全时回退环境变量。client 需要 `slots/locale/layout`。缺必需服务干净禁用。公共 client 依赖由 `dsh-session-manager` 的唯一占位项承载,本包只声明 dependency/external,不插第二条占位。Host/client使用同代 common-tools 0.3.x。
|
|
81
88
|
|
|
82
89
|
```sh
|
|
83
90
|
npm install --omit=peer
|
|
@@ -92,9 +99,10 @@ npm test
|
|
|
92
99
|
|
|
93
100
|
| 版本 | 状态 | 证据边界 |
|
|
94
101
|
| --- | --- | --- |
|
|
95
|
-
| 0.2.
|
|
96
|
-
| 0.2.1-rc.
|
|
102
|
+
| 0.2.2-rc.1 | compatible | 2026-11-09 隔离真宿主:导航入口、自选/搜索/浏览市场/详情/K线/悬浮盯盘/设置、真实东财行情与八市场路由;截图资产同源采集 |
|
|
103
|
+
| 0.2.1-rc.5 | compatible | manifest 登记;仅有 `.compat/0.2.1-rc.5` 的 crash-only 装载记录(page true),未做功能复测 |
|
|
104
|
+
| 0.2.1-rc.2 / 0.2.1-rc.3 | compatible | 早期隔离验证:导航入口、main 页面、样式、快照路由、WS ready→invalidate、重载后偏好保留;rc.3 另验证无凭据 AUTH 检查拒绝与保存守卫 |
|
|
97
105
|
| 其余版本 | unknown | 未实测不声明 |
|
|
98
106
|
|
|
99
|
-
逐项证据和局限见[兼容性测试](./兼容性测试.md)。实现规格与研究分别见[开发文档](../../docs/开发-股票侧边栏插件.md)、[调研文档](../../docs/调研-股票侧边栏插件.md)。
|
|
107
|
+
逐项证据和局限见[兼容性测试](./兼容性测试.md),变更记录见[CHANGELOG](./CHANGELOG.md)。界面截图(2026-11-09 隔离宿主实采)见[assets/screenshots/dsh-stock-assistant](../../assets/screenshots/dsh-stock-assistant)。实现规格与研究分别见[开发文档](../../docs/开发-股票侧边栏插件.md)、[调研文档](../../docs/调研-股票侧边栏插件.md)。
|
|
100
108
|
|
package/package.json
CHANGED
package/src/application.mjs
CHANGED
|
@@ -7,6 +7,7 @@ import { tencent } from './providers/tencent.mjs'
|
|
|
7
7
|
import { sina } from './providers/sina.mjs'
|
|
8
8
|
import { eastmoney } from './providers/eastmoney.mjs'
|
|
9
9
|
import { xueqiu } from './providers/xueqiu.mjs'
|
|
10
|
+
import { finnhub } from './providers/finnhub.mjs'
|
|
10
11
|
import { openState, digest } from './state.mjs'
|
|
11
12
|
import { parseConfiguration, preferencesSchema, defaultConfig, klineQuerySchema } from './schemas.mjs'
|
|
12
13
|
import { createWatchlistService } from './service.mjs'
|
|
@@ -21,8 +22,13 @@ const WINDOW = 5 * 60 * 1000
|
|
|
21
22
|
const US_SYMBOL_TTL = 24 * 60 * 60 * 1000
|
|
22
23
|
const US_SYMBOL_LIMIT = 500
|
|
23
24
|
const PROBE_LIMIT = 512
|
|
24
|
-
export async function createApplication({ storageDomain, providers = [tushare, tencent, sina, eastmoney, xueqiu], publish = () => {}, env = process.env, fetch = globalThis.fetch, now = Date.now, timers = globalThis, vendorAvailable = true }) {
|
|
25
|
+
export async function createApplication({ storageDomain, providers = [tushare, tencent, sina, eastmoney, xueqiu, finnhub], publish = () => {}, env = process.env, credentials = null, fetch = globalThis.fetch, now = Date.now, timers = globalThis, vendorAvailable = true }) {
|
|
25
26
|
const serverEpoch = randomUUID(), checks = new Map()
|
|
27
|
+
// 凭据解析: 宿主提供 credentials 服务时交给它(插件存储层优先, 再逐层回退到进程环境与 .env 文件),
|
|
28
|
+
// 否则退回进程环境变量。引用只表示"哪个密钥", 值始终由宿主保管。
|
|
29
|
+
// 接口按能力逐个核对: 宿主给的对象缺哪个方法, 就只退回哪条路径, 而不是在取数时炸掉。
|
|
30
|
+
const credentialStore = credentials && ['resolve', 'set', 'unset'].every(method => typeof credentials[method] === 'function') ? credentials : null
|
|
31
|
+
const resolveCredential = credentialStore ? async ref => (await credentialStore.resolve(ref))?.value : async ref => env[ref]
|
|
26
32
|
// 目标粒度探针缓存: instanceId:capability:market → {status, until}; 配置保存校验按目标增量引用, 不随无关字段改动失效
|
|
27
33
|
const probeCache = new Map()
|
|
28
34
|
let snapshotSeq = 0, stopped = false, collector, catalog, demand
|
|
@@ -30,11 +36,17 @@ export async function createApplication({ storageDomain, providers = [tushare, t
|
|
|
30
36
|
const touched = () => snapshotSeq++
|
|
31
37
|
const changed = () => { touched(); publish({ type: 'invalidate', serverEpoch, snapshotSeq, scopes: ['snapshot'] }) }
|
|
32
38
|
const state = await openState(storageDomain, changed, now)
|
|
39
|
+
// 凭据存在性只给设置页看, 而解析是异步的、快照是同步的: 保存配置与启动时各算一次, 快照读这份结果。
|
|
40
|
+
const credentialPresence = new Map()
|
|
41
|
+
const refreshCredentialPresence = async () => {
|
|
42
|
+
for (const p of state.get().providers) credentialPresence.set(p.id, p.credentialRef === null || !!(await resolveCredential(p.credentialRef)))
|
|
43
|
+
}
|
|
44
|
+
await refreshCredentialPresence()
|
|
33
45
|
const registry = createRegistry(providers), budget = createBudget(now)
|
|
34
46
|
// 代理 dispatcher 工厂: undici ProxyAgent(实例级上游出口), 包不可用时该实例代理静默降级直连
|
|
35
47
|
let proxyFactory = null
|
|
36
48
|
try { const undici = await import('undici'); proxyFactory = url => new undici.ProxyAgent(url) } catch {}
|
|
37
|
-
const executor = createExecutor({ registry, budget, env, fetch, now, timers, usSymbols, proxyFactory })
|
|
49
|
+
const executor = createExecutor({ registry, budget, env, resolveCredential, fetch, now, timers, usSymbols, proxyFactory })
|
|
38
50
|
const getControl = state.get
|
|
39
51
|
const router = createRouter(getControl, now, () => collector?.reset())
|
|
40
52
|
const klineCache = createKlineCache({ cacheTable: state.cache, now })
|
|
@@ -61,7 +73,7 @@ export async function createApplication({ storageDomain, providers = [tushare, t
|
|
|
61
73
|
const watchlist = createWatchlistService(state, catalog.resolve, now)
|
|
62
74
|
const snapshot = () => {
|
|
63
75
|
const control = state.get(); delete control.operations
|
|
64
|
-
return { serverEpoch, snapshotSeq, routingRevision: control.routingRevision, control, quotes: collector.entries(), routeSelections: router.selections(), catalogs: catalog.status(), adapters: registry.descriptors(), suggested: defaultConfig(), ensureError, vendorAvailable, providerStatus: control.providers.map(p => ({ id: p.id, credentialPresent: p.
|
|
76
|
+
return { serverEpoch, snapshotSeq, routingRevision: control.routingRevision, control, quotes: collector.entries(), routeSelections: router.selections(), catalogs: catalog.status(), adapters: registry.descriptors(), suggested: defaultConfig(), ensureError, vendorAvailable, providerStatus: control.providers.map(p => ({ id: p.id, credentialPresent: p.credentialRef === null || credentialPresence.get(p.id) === true, credentialRef: p.credentialRef, proxy: !!p.proxy, endpointsCovered: Object.keys(p.endpoints || {}).length, recentRequests: executor.recentRequests(p.id) })), klineReady: Object.fromEntries(control.routes.filter(r => r.capability === 'kline').map(r => [r.market, true])), markets: Object.fromEntries(Object.entries(MARKET_META).map(([market, meta]) => [market, { currency: meta.currency, verified: meta.verifiedByDefault }])) }
|
|
65
77
|
}
|
|
66
78
|
function assertLive() { if (stopped) fail('STOPPED', '股票工具已停止', 503) }
|
|
67
79
|
async function providerCheck(input, signal) {
|
|
@@ -108,7 +120,7 @@ export async function createApplication({ storageDomain, providers = [tushare, t
|
|
|
108
120
|
if (JSON.stringify(current.providers) === JSON.stringify(config.providers) && JSON.stringify(current.routes) === JSON.stringify(config.routes)) return current
|
|
109
121
|
return { ...current, ...config, routingRevision: current.routingRevision + 1 }
|
|
110
122
|
})
|
|
111
|
-
if (!result.unchanged) { router.reset(); collector.reset() }
|
|
123
|
+
if (!result.unchanged) { router.reset(); collector.reset(); await refreshCredentialPresence() }
|
|
112
124
|
return result
|
|
113
125
|
}
|
|
114
126
|
|
|
@@ -201,6 +213,18 @@ export async function createApplication({ storageDomain, providers = [tushare, t
|
|
|
201
213
|
const result = await catalog.sync(input.market); collector.reconcile(); return result
|
|
202
214
|
},
|
|
203
215
|
async watchlist(operation) { assertLive(); const result = await watchlist.execute(operation); collector.reconcile(); return result },
|
|
216
|
+
// 密钥只写宿主的凭据存储, 不回显也不落插件状态;引用必须已被某个数据源声明, 插件不越界写别人的密钥空间。
|
|
217
|
+
async credential(input) {
|
|
218
|
+
assertLive()
|
|
219
|
+
if (!credentialStore) fail('UNSUPPORTED', '宿主未提供凭据服务', 501)
|
|
220
|
+
const ref = z.string().regex(/^[A-Z][A-Z0-9_]{0,63}$/).parse(input.ref)
|
|
221
|
+
if (!state.get().providers.some(p => p.credentialRef === ref)) fail('INVALID_REQUEST', '该凭据未被任何数据源使用', 422)
|
|
222
|
+
const value = input.value === null ? null : z.string().min(1).max(512).parse(input.value)
|
|
223
|
+
if (value === null) await credentialStore.unset(ref)
|
|
224
|
+
else await credentialStore.set(ref, value)
|
|
225
|
+
await refreshCredentialPresence()
|
|
226
|
+
return { ref, present: value !== null }
|
|
227
|
+
},
|
|
204
228
|
async preferences(operation) {
|
|
205
229
|
assertLive()
|
|
206
230
|
const parsed = preferencesSchema.partial().safeParse(operation.payload)
|
package/src/client.js
CHANGED
|
@@ -1740,7 +1740,29 @@ window.__ModuleLoader__.load({
|
|
|
1740
1740
|
state.errorCode === 'CATALOG_NOT_READY' ? h('div', { className: 'ssb-banner', style: { margin: 0 } }, '目录未就绪。可以直接浏览市场添加自选。', h(Button, { onClick: () => runtime.updateView({ view: 'browse' }) }, '前往浏览市场')) : null,
|
|
1741
1741
|
h('div', { className: 'ssb-toolbar', style: { margin: 0 } }, h(Button, { primary: true, disabled: !view.selectedId || !!data?.control.watchlist.items[view.selectedId] || state.busy.write, onClick: quiet(async () => { await runtime.mutate('add', { securityId: view.selectedId }); runtime.updateView({ view: 'list', selectedId: null }) }) }, data?.control.watchlist.items[view.selectedId] ? '已在自选' : '确认添加'))))
|
|
1742
1742
|
}
|
|
1743
|
-
const defaultProvider = (id, adapterId = 'tushare') => ({ id, adapterId, enabled: true,
|
|
1743
|
+
const defaultProvider = (id, adapterId = 'tushare') => ({ id, adapterId, enabled: true, credentialRef: adapterId === 'tushare' ? 'DSH_STOCK_TUSHARE_TOKEN' : null, quotaGroup: adapterId + '-account', budget: { requestsPerMinute: adapterId === 'tushare' ? null : 60, dailyRequestLimit: null, billingUnit: 'request', symbolCreditsPerMinute: null, capabilityLimits: {} } })
|
|
1744
|
+
// 密钥输入: 值直接写宿主的凭据存储, 不进配置草稿, 也不回显。保存后重新拉一次快照让"已配置"状态跟上
|
|
1745
|
+
function CredentialField({ runtime, refName, present }) {
|
|
1746
|
+
const [value, setValue] = React.useState(''), [busy, setBusy] = React.useState(false), [notice, setNotice] = React.useState('')
|
|
1747
|
+
const submit = async next => {
|
|
1748
|
+
if (busy) return
|
|
1749
|
+
setBusy(true); setNotice('')
|
|
1750
|
+
try {
|
|
1751
|
+
await runtime.api('/credential', 'POST', { ref: refName, value: next })
|
|
1752
|
+
setValue('')
|
|
1753
|
+
setNotice(next === null ? '已清除' : '已保存')
|
|
1754
|
+
runtime.applySnapshot(await runtime.api('/snapshot'), true)
|
|
1755
|
+
} catch (e) { setNotice(e.message || '保存失败') }
|
|
1756
|
+
finally { setBusy(false) }
|
|
1757
|
+
}
|
|
1758
|
+
return h('div', { className: 'ssb-credential', style: { gridColumn: '1 / -1' } },
|
|
1759
|
+
h('label', { className: 'ssb-field' }, h('span', null, present ? '密钥(已配置,留空表示不修改)' : '密钥(未配置)'),
|
|
1760
|
+
h('input', { type: 'password', value, autoComplete: 'new-password', spellCheck: false, placeholder: present ? '留空则不修改' : '粘贴密钥后保存', onChange: e => setValue(e.target.value) })),
|
|
1761
|
+
h('div', { className: 'ssb-credential-actions' },
|
|
1762
|
+
h(Button, { disabled: busy || !value.trim(), onClick: () => submit(value.trim()) }, '保存密钥'),
|
|
1763
|
+
present ? h(Button, { disabled: busy, onClick: () => submit(null) }, '清除') : null,
|
|
1764
|
+
notice ? h('span', { className: 'ssb-muted', role: 'status' }, notice) : null))
|
|
1765
|
+
}
|
|
1744
1766
|
const routeFor = (market, capability, instance) => ({ id: `${market.toLowerCase()}-${capability}`, capability, market, instrument: 'equity', primaryInstanceId: instance, fallbackInstanceIds: [], failoverMode: 'off', maxDelaySeconds: null, acceptUnknownDelay: true })
|
|
1745
1767
|
function SettingsView({ runtime, state }) {
|
|
1746
1768
|
const saved = state.data.control
|
|
@@ -1779,14 +1801,15 @@ window.__ModuleLoader__.load({
|
|
|
1779
1801
|
adapter?.description ? h('p', { className: 'ssb-provider-desc ssb-muted' }, adapter.description) : null,
|
|
1780
1802
|
expanded ? h('div', { className: 'ssb-provider-body', disabled: state.busy.configuration },
|
|
1781
1803
|
h('div', { className: 'ssb-provider-head' },
|
|
1782
|
-
h('label', { className: 'ssb-field ssb-provider-adapter' }, h('span', null, '适配器'), h('select', { value: p.adapterId, onChange: e => { const adapterId = e.target.value, descriptor = state.data.adapters.find(a => a.adapterId === adapterId); providerChange(p.id, { adapterId,
|
|
1804
|
+
h('label', { className: 'ssb-field ssb-provider-adapter' }, h('span', null, '适配器'), h('select', { value: p.adapterId, onChange: e => { const adapterId = e.target.value, descriptor = state.data.adapters.find(a => a.adapterId === adapterId); providerChange(p.id, { adapterId, credentialRef: descriptor?.credential === 'none' ? null : descriptor?.credential || null, quotaGroup: adapterId + '-account', budget: descriptor?.credential === 'none' && p.budget.requestsPerMinute === null ? { ...p.budget, requestsPerMinute: 60 } : p.budget }) } }, ...state.data.adapters.map(a => h('option', { value: a.adapterId, key: a.adapterId }, a.adapterId + (a.credential === 'none' ? '(免凭据)' : ''))))),
|
|
1783
1805
|
h('div', { className: 'ssb-provider-switches' },
|
|
1784
1806
|
h(Toggle, { label: '启用', checked: p.enabled, onChange: value => providerChange(p.id, { enabled: value }) }),
|
|
1785
1807
|
h(Button, { danger: true, onClick: () => change({ providers: draft.providers.filter(other => other.id !== p.id), routes: draft.routes.filter(r => r.primaryInstanceId !== p.id).map(r => ({ ...r, fallbackInstanceIds: r.fallbackInstanceIds.filter(id => id !== p.id), failoverMode: r.fallbackInstanceIds.includes(p.id) ? 'off' : r.failoverMode })) }) }, '移除'))),
|
|
1786
1808
|
h('div', { className: 'ssb-provider-advanced-open' },
|
|
1787
1809
|
h('div', { className: 'ssb-form-grid' },
|
|
1788
|
-
openSource ? h('span', { className: 'ssb-muted', style: { gridColumn: '1 / -1' } }, '公开来源,无需凭据') : field('
|
|
1810
|
+
openSource ? h('span', { className: 'ssb-muted', style: { gridColumn: '1 / -1' } }, '公开来源,无需凭据') : field('密钥引用名', p.credentialRef, value => providerChange(p.id, { credentialRef: value }), { autoComplete: 'off', spellCheck: false }),
|
|
1789
1811
|
field('共享额度组(同账号保持一致)', p.quotaGroup, value => providerChange(p.id, { quotaGroup: value })),
|
|
1812
|
+
openSource || !p.credentialRef ? null : h(CredentialField, { key: 'cred-' + p.id, runtime, refName: p.credentialRef, present: status?.credentialPresent }),
|
|
1790
1813
|
field('每分钟请求上限(留空仅允许探针)', p.budget.requestsPerMinute, value => providerChange(p.id, { budget: { ...p.budget, requestsPerMinute: value ? Number(value) : null } }), { type: 'number', min: 1 }),
|
|
1791
1814
|
field('每日请求上限(留空无限制)', p.budget.dailyRequestLimit, value => providerChange(p.id, { budget: { ...p.budget, dailyRequestLimit: value ? Number(value) : null } }), { type: 'number', min: 1 }),
|
|
1792
1815
|
h('label', { className: 'ssb-field' }, h('span', null, '计费单位'), h('select', { value: p.budget.billingUnit, onChange: e => providerChange(p.id, { budget: { ...p.budget, billingUnit: e.target.value } }) }, h('option', { value: 'request' }, '请求'), h('option', { value: 'symbol' }, '证券'))),
|
|
@@ -1902,7 +1925,7 @@ window.__ModuleLoader__.load({
|
|
|
1902
1925
|
const busyConfig = state.busy.configuration || state.busy.check
|
|
1903
1926
|
return h('section', { className: 'ssb-settings' },
|
|
1904
1927
|
h('div', { className: 'ssb-settings-head' },
|
|
1905
|
-
h('div', { className: 'ssb-settings-intro' }, h('h2', null, '设置'), h('p', { className: 'ssb-muted' }, `${enabled} 个数据源 · ${controlRoutes.length} 条能力路由 · ${markets}
|
|
1928
|
+
h('div', { className: 'ssb-settings-intro' }, h('h2', null, '设置'), h('p', { className: 'ssb-muted' }, `${enabled} 个数据源 · ${controlRoutes.length} 条能力路由 · ${markets} 个市场;凭据由宿主凭据服务保管(接口不全时回退环境变量),这里只保存引用名与数据路由`)),
|
|
1906
1929
|
h('div', { className: 'ssb-toolbar' }, h(Button, { primary: true, disabled: busyConfig, title: '写入内置免凭据数据源与八市场能力路由,探针不可用的目标自动剔除;自选与显示偏好不受影响', onClick: quiet(() => runtime.applyRecommended()) }, state.checkProgress || (busyConfig ? '正在应用…' : '应用推荐配置')))),
|
|
1907
1930
|
h('div', { className: 'ssb-tablist', role: 'tablist', 'aria-label': '设置分区' }, ...TABS.map(([key, label]) => h('button', { key, role: 'tab', 'aria-selected': tab === key, className: `ssb-tab${tab === key ? ' ssb-tab-on' : ''}`, onClick: () => change({ tab: key }, false) }, label))),
|
|
1908
1931
|
pane)
|
|
@@ -2045,7 +2068,7 @@ window.__ModuleLoader__.load({
|
|
|
2045
2068
|
.ssb-float-picker .ssb-switch { font-size:11px; }
|
|
2046
2069
|
.ssb-group-head { display:flex; align-items:center; gap:8px; flex-wrap:wrap; height:32px; padding:0 12px; border-top:1px solid var(--ssb-border); background:var(--ssb-bg-sub); font-size:12px; color:var(--ssb-text-sub); }
|
|
2047
2070
|
.ssb-dot { display:inline-block; width:6px; height:6px; border-radius:50%; background:var(--ssb-ok); flex:0 0 auto; }.ssb-dot.ssb-dot-warn { background:var(--ssb-warn); }.ssb-dot.ssb-dot-danger { background:var(--ssb-danger); }.ssb-dot.ssb-dot-idle { background:var(--ssb-text-dim); }
|
|
2048
|
-
.ssb-facts { display:grid; grid-template-columns:1fr 1fr; gap:8px; border-top:1px solid var(--ssb-border); padding-top:16px; margin-top:16px; }.ssb-mark-list { list-style:none; margin:0; padding:0; display:flex; flex-direction:column; gap:6px; }.ssb-mark-row { display:flex; align-items:center; gap:8px; }.ssb-mark-row .ssb-number { flex:1; }.ssb-mark-kind { min-width:2.5em; color:var(--ssb-text-dim); font-size:12px; }.ssb-facts dt { color:var(--ssb-text-sub); }.ssb-facts dd { margin:0; text-align:right; overflow-wrap:anywhere; font-family:var(--ds-font-family-code); }.ssb-alias-form { display:grid; gap:6px; margin-top:0; }.ssb-alias-form label { display:grid; gap:6px; }.ssb-alias-form button { justify-self:start; min-width:96px; }.ssb-detail-forms { display:grid; grid-template-columns:repeat(auto-fit,minmax(176px,1fr)); gap:16px; border-top:1px solid var(--ssb-border); padding-top:16px; margin-top:16px; }
|
|
2071
|
+
.ssb-facts { display:grid; grid-template-columns:1fr 1fr; gap:8px; border-top:1px solid var(--ssb-border); padding-top:16px; margin-top:16px; }.ssb-mark-list { list-style:none; margin:0; padding:0; display:flex; flex-direction:column; gap:6px; }.ssb-mark-row { display:flex; align-items:center; gap:8px; }.ssb-mark-row .ssb-number { flex:1; }.ssb-mark-kind { min-width:2.5em; color:var(--ssb-text-dim); font-size:12px; }.ssb-credential { display:grid; gap:8px; justify-items:start; }.ssb-credential .ssb-field { width:100%; }.ssb-credential-actions { display:flex; align-items:center; gap:8px; }.ssb-facts dt { color:var(--ssb-text-sub); }.ssb-facts dd { margin:0; text-align:right; overflow-wrap:anywhere; font-family:var(--ds-font-family-code); }.ssb-alias-form { display:grid; gap:6px; margin-top:0; }.ssb-alias-form label { display:grid; gap:6px; }.ssb-alias-form button { justify-self:start; min-width:96px; }.ssb-detail-forms { display:grid; grid-template-columns:repeat(auto-fit,minmax(176px,1fr)); gap:16px; border-top:1px solid var(--ssb-border); padding-top:16px; margin-top:16px; }
|
|
2049
2072
|
.ssb-settings-head { display:flex; align-items:flex-start; justify-content:space-between; gap:16px; flex-wrap:wrap; }.ssb-settings-intro { min-width:0; display:grid; gap:6px; }.ssb-settings-intro p { margin:0; }
|
|
2050
2073
|
.ssb-provider-head { display:flex; align-items:flex-end; justify-content:space-between; gap:12px; flex-wrap:wrap; }.ssb-provider-adapter { flex:0 0 240px; }.ssb-provider-switches { display:flex; align-items:center; gap:10px; flex-wrap:wrap; }.ssb-provider-desc { margin:8px 0 0; }.ssb-provider-advanced { margin-top:8px; }.ssb-provider-advanced > summary { cursor:pointer; }
|
|
2051
2074
|
/* 摘要行: 数据源与市场默认收成一行, 点开才展开编辑区 */
|
package/src/executor.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { StockError, fail } from './market-model.mjs'
|
|
2
2
|
// 每实例上游请求环形日志容量: 概览"最近请求"展示面
|
|
3
3
|
const REQUEST_LOG_LIMIT = 20
|
|
4
|
-
export function createExecutor({ registry, budget, env = process.env, fetch: fetchImpl = globalThis.fetch, now = Date.now, timers = globalThis, usSymbols = new Map(), proxyFactory = null }) {
|
|
4
|
+
export function createExecutor({ registry, budget, env = process.env, resolveCredential = async ref => env[ref], fetch: fetchImpl = globalThis.fetch, now = Date.now, timers = globalThis, usSymbols = new Map(), proxyFactory = null }) {
|
|
5
5
|
const queues = new Map(), controllers = new Set(), starts = new Map()
|
|
6
6
|
const requestLogs = new Map(), proxies = new Map()
|
|
7
7
|
let stopped = false, running = 0
|
|
@@ -56,10 +56,14 @@ export function createExecutor({ registry, budget, env = process.env, fetch: fet
|
|
|
56
56
|
const adapter = registry.get(instance.adapterId), method = options.probe ? 'probe' : capability
|
|
57
57
|
if (typeof adapter[method] !== 'function') fail('UNSUPPORTED_CAPABILITY', '来源不支持该能力', 422)
|
|
58
58
|
let used = false, timeout
|
|
59
|
+
// 凭据每次操作解析一次, 不跨操作缓存: 存储层改了密钥, 下一次请求就生效, 不必重启插件。
|
|
60
|
+
// 解析在超时计时之前完成——读本地存储不该占用上游的 8 秒预算。
|
|
61
|
+
const secret = instance.credentialRef === null ? undefined : await resolveCredential(instance.credentialRef)
|
|
62
|
+
if (instance.credentialRef !== null && !secret) fail('AUTH', '未配置凭据', 422)
|
|
59
63
|
// 超时计时覆盖整个能力调用;分页适配器每次网络活动重置计时,空闲超过窗口才判超时。
|
|
60
64
|
const armTimeout = () => { timers.clearTimeout(timeout); timeout = timers.setTimeout(() => controller.abort(new StockError('TIMEOUT', '来源请求超时', 504, { retryable: true })), 8 * 1000) }
|
|
61
65
|
armTimeout()
|
|
62
|
-
const ctx = { now, signal: controller.signal, usSymbols, endpoints: instance.endpoints || null, credential: () =>
|
|
66
|
+
const ctx = { now, signal: controller.signal, usSymbols, endpoints: instance.endpoints || null, credential: () => secret,
|
|
63
67
|
fetch: async (...args) => {
|
|
64
68
|
if (used) {
|
|
65
69
|
const gap = Math.max(0, starts.get(instance.quotaGroup) + (instance.budget?.requestsPerMinute === null ? 10 * 1000 : 1000) - now())
|
|
@@ -77,8 +81,7 @@ export function createExecutor({ registry, budget, env = process.env, fetch: fet
|
|
|
77
81
|
armTimeout()
|
|
78
82
|
return response
|
|
79
83
|
} }
|
|
80
|
-
// 免凭据实例(
|
|
81
|
-
if (instance.credentialEnv !== null && !env[instance.credentialEnv]) fail('AUTH', '未在Host环境中配置凭据', 422)
|
|
84
|
+
// 免凭据实例(credentialRef=null)解析结果恒为空, 上述守卫不触发。
|
|
82
85
|
const work = Promise.resolve(adapter[method]({ ...request, providerInstanceId: instance.id, capability }, ctx))
|
|
83
86
|
const result = await new Promise((resolve, reject) => {
|
|
84
87
|
const aborted = () => reject(controller.signal.reason instanceof StockError ? controller.signal.reason : new StockError('CANCELLED', '请求已取消', 503))
|
package/src/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export const name = 'dsh-stock-assistant'
|
|
2
|
-
export const inject = ['webServer', 'storageDomain']
|
|
2
|
+
export const inject = ['webServer', 'storageDomain', 'credentials']
|
|
3
3
|
import { setupCommonTools, createChangeNotifier } from '@mzzsfy/dsh-common-tools/host'
|
|
4
4
|
import { createApplication } from './application.mjs'
|
|
5
5
|
import { registerRoutes } from './routes.mjs'
|
|
@@ -18,7 +18,8 @@ export async function apply(ctx) {
|
|
|
18
18
|
// vendor 可读性预判定先于应用构建: vendorAvailable=false 随快照下发→client 直接降级数字详情
|
|
19
19
|
let vendorAvailable = true
|
|
20
20
|
try { vendorAvailable = vendorReadable() } catch { vendorAvailable = false }
|
|
21
|
-
|
|
21
|
+
// 凭据服务由宿主提供; 接口不全时应用层会整体退回进程环境变量, 不因此拒绝启动
|
|
22
|
+
application = await createApplication({ storageDomain: ctx.storageDomain, credentials: ctx.credentials ?? null, publish: () => notifier?.refresh(), vendorAvailable })
|
|
22
23
|
if (disposed) { await application.close(); return }
|
|
23
24
|
bus = setupCommonTools(ctx)
|
|
24
25
|
notifier = createChangeNotifier(() => bus.publish({ type: 'invalidate', serverEpoch: application.snapshot().serverEpoch, snapshotSeq: application.snapshot().snapshotSeq }))
|
|
@@ -9,15 +9,18 @@ const DEFAULT_ENDPOINTS = {
|
|
|
9
9
|
trend: 'https://push2his.eastmoney.com/api/qt/stock/trends2/get',
|
|
10
10
|
}
|
|
11
11
|
const endpointOf = (ctx, key) => ctx.endpoints?.[key] || DEFAULT_ENDPOINTS[key]
|
|
12
|
-
//
|
|
12
|
+
// 沪深市场代码(其余市场的 secid 前缀见 SECID_PREFIX)
|
|
13
13
|
const MARKET = { XSHG: '1', XSHE: '0' }
|
|
14
14
|
// 搜索联想 MktNum→交易所全集(实测: 1/0 沪深, 116 港, 105/106/107 美三大, 176/177/155 日韩英)
|
|
15
15
|
const SEARCH_EXCHANGE = { 1: 'XSHG', 0: 'XSHE', 116: 'XHKG', 105: 'XNAS', 106: 'XNYS', 107: 'XNYS', 176: 'XJPX', 177: 'XKRX', 155: 'XLON' }
|
|
16
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
17
|
// 美股三大市场号: 105 纳斯达克 / 106 纽约 / 107 美交所。secid 前缀必须精确匹配, 探针期据此逐个试探。
|
|
19
18
|
const US_MKTNUMS = ['105', '106', '107']
|
|
20
19
|
const isUSExchange = exchange => exchange === 'XNAS' || exchange === 'XNYS'
|
|
20
|
+
// 美股 secid 前缀候选序: 搜索缓存 > 交易所静态前缀 > 其余美股市场号。XNYS 实横跨 106 与 107, 静态前缀只取其一。
|
|
21
|
+
// 缓存只加速重复查询, 缺失或过期不改变正确性: 进程重启后 usSymbols 为空, 取报价不得依赖此前的搜索行为。
|
|
22
|
+
const usSecidPrefixes = (security, ctx) => [...new Set([ctx.usSymbols?.get(`US:${security.code}`)?.mktNum, SECID_PREFIX[security.exchange], ...US_MKTNUMS].filter(mktNum => US_MKTNUMS.includes(mktNum)))]
|
|
23
|
+
const secidFor = (security, ctx) => isUSExchange(security.exchange) ? `${usSecidPrefixes(security, ctx)[0]}.${security.code}` : `${SECID_PREFIX[security.exchange]}.${security.code}`
|
|
21
24
|
// klt 周期映射(实测): 日101/周102/月103; trends2 无 klt。
|
|
22
25
|
const KLT = { '1d': 101, '1w': 102, '1M': 103 }
|
|
23
26
|
// 目录 fs 按市场给出; 英股 m:155 含债券与结构性产品, 加 t:1 只取股票; 日韩不支持 t: 细分, 全量即股票
|
|
@@ -30,8 +33,6 @@ const KLINE_FIELDS = 'f51,f52,f53,f54,f55,f56,f57'
|
|
|
30
33
|
const TREND_FIELDS = 'f51,f52,f53,f54,f55,f56,f57,f58'
|
|
31
34
|
// 分时时间戳的来源时区: 东财统一用北京时间, 与证券所属市场无关
|
|
32
35
|
const SOURCE_ZONE = 'Asia/Shanghai'
|
|
33
|
-
// quotes secid 与 kline secidOf 同源(八市场前缀表);美股 quotes 同样走 usSymbols 动态归属。
|
|
34
|
-
const symbolOf = security => `${SECID_PREFIX[security.exchange]}.${security.code}`
|
|
35
36
|
const num = value => value == null || typeof value === 'number' && !Number.isFinite(value) ? null : value === '-' ? null : String(value)
|
|
36
37
|
async function getJson(ctx, url) {
|
|
37
38
|
let response
|
|
@@ -61,41 +62,44 @@ export const eastmoney = {
|
|
|
61
62
|
if (!result.candles.length) throw new StockError('NO_DATA', '来源未返回可校验数据,暂不能确认能力就绪', 422)
|
|
62
63
|
return { status: 'ready', capability: 'kline', market: request.market, instrument: 'equity' }
|
|
63
64
|
}
|
|
64
|
-
//
|
|
65
|
+
// 美股前缀的逐个试探已收敛进 quotes,探针只需一次结果,避免探针与真实取价走两套路径
|
|
65
66
|
const security = request.securities?.[0] || { exchange: request.market, code: PROBE_SECURITY[request.market] || '000001' }
|
|
66
|
-
const
|
|
67
|
-
|
|
68
|
-
|
|
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)
|
|
67
|
+
const rows = await this.quotes({ ...request, securities: [security] }, ctx)
|
|
68
|
+
if (!rows.items.length) throw new StockError('NO_DATA', '来源未返回可校验数据,暂不能确认能力就绪', 422)
|
|
69
|
+
return { status: 'ready', capability: 'quotes', market: request.market, instrument: 'equity' }
|
|
73
70
|
},
|
|
74
71
|
async quotes(request, ctx) {
|
|
75
|
-
|
|
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: '来源未返回此证券报价' })) }
|
|
72
|
+
const fields = 'f2,f3,f4,f5,f6,f12,f13,f14,f15,f16,f17,f18,f124'
|
|
82
73
|
const seen = new Set(), items = []
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
74
|
+
// 一次请求取一批 secid;data:null 表示整批 secid 均无效(如整批退市),降级为逐证券缺失。
|
|
75
|
+
const ingest = async symbols => {
|
|
76
|
+
const body = await getJson(ctx, `${endpointOf(ctx, 'quotes')}?secids=${[...symbols.keys()].join(',')}&fields=${fields}&fltt=2&invt=2`)
|
|
77
|
+
const rows = body?.data?.diff
|
|
78
|
+
if (!Array.isArray(rows)) return
|
|
79
|
+
for (const row of rows) {
|
|
80
|
+
const security = symbols.get(`${row.f13}.${row.f12}`)
|
|
81
|
+
if (!security) continue
|
|
82
|
+
if (seen.has(security.id)) throw new StockError('BAD_PAYLOAD', '报价身份冲突', 502)
|
|
83
|
+
seen.add(security.id)
|
|
84
|
+
// fltt=2时价格为已缩放数值, "-"表示停牌等无值;f124为来源Unix秒;成交额币种按市场派生(单一事实源 MARKET_META.currency)。
|
|
85
|
+
const quoteAt = Number.isFinite(row.f124) ? new Date(row.f124 * 1000).toISOString() : null
|
|
86
|
+
const currency = MARKET_META[security.exchange]?.currency || 'CNY'
|
|
87
|
+
items.push(normalizeQuote({
|
|
88
|
+
securityId: security.id, providerInstanceId: request.providerInstanceId, adapterId: 'eastmoney', providerSymbol: `${row.f13}.${row.f12}`,
|
|
89
|
+
last: num(row.f2), previousClose: num(row.f18), open: num(row.f17), high: num(row.f15), low: num(row.f16),
|
|
90
|
+
volume: sharesFromLots(num(row.f5), security.exchange), volumeUnit: 'share', amount: num(row.f6), amountUnit: currency,
|
|
91
|
+
quoteAt, timestampKind: 'trade',
|
|
92
|
+
receivedAt: ctx.now(), delayKind: 'unknown', delaySeconds: null, securityState: 'unknown',
|
|
93
|
+
}))
|
|
94
|
+
}
|
|
98
95
|
}
|
|
96
|
+
await ingest(new Map(request.securities.map(s => [secidFor(s, ctx), s])))
|
|
97
|
+
// 美股前缀兜底: 静态前缀只对应一个市场号,而交易所归属未必精确(实测 NYSE 的票分属 106/107)。
|
|
98
|
+
// 只对首轮落空的美股补齐剩余候选,一次批量发完,不逐证券重试。
|
|
99
|
+
const orphanUS = request.securities.filter(s => !seen.has(s.id) && isUSExchange(s.exchange))
|
|
100
|
+
const altSymbols = new Map()
|
|
101
|
+
for (const security of orphanUS) for (const mktNum of usSecidPrefixes(security, ctx).slice(1)) altSymbols.set(`${mktNum}.${security.code}`, security)
|
|
102
|
+
if (altSymbols.size) await ingest(altSymbols)
|
|
99
103
|
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
104
|
},
|
|
101
105
|
async catalog(request, ctx) {
|
|
@@ -144,14 +148,9 @@ export const eastmoney = {
|
|
|
144
148
|
}
|
|
145
149
|
return { providerInstanceId: request.providerInstanceId, fetchedAt: ctx.now(), items, errors: [] }
|
|
146
150
|
},
|
|
147
|
-
//
|
|
151
|
+
// 与 quotes 同源的 secid;猜错时调用方走 suggest 重试路径(搜索结果是市场号的权威来源)。
|
|
148
152
|
secidOf(request, ctx) {
|
|
149
|
-
|
|
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}`
|
|
153
|
+
return secidFor({ exchange: request.market, code: request.code }, ctx)
|
|
155
154
|
},
|
|
156
155
|
async kline(request, ctx) {
|
|
157
156
|
if (request.period === 'trend') return this.trend(request, ctx)
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// Finnhub 免费公开接口: 美股实时报价。没有批量端点, 每次一只;官方明确不建议持续轮询, 额度按分钟计。
|
|
2
|
+
import { MARKET_META, normalizeQuote, StockError } from '../market-model.mjs'
|
|
3
|
+
const DEFAULT_ENDPOINTS = { quotes: 'https://finnhub.io/api/v1/quote' }
|
|
4
|
+
const endpointOf = (ctx, key) => ctx.endpoints?.[key] || DEFAULT_ENDPOINTS[key]
|
|
5
|
+
// 免费档只开放 /quote: K线与盘口都标 Premium Access Required, 所以本适配器只声明报价能力。
|
|
6
|
+
const PROBE_SECURITY = 'AAPL'
|
|
7
|
+
// 无效代码由来源返回全 0 字段而非 404, 现价 0 即视为无此证券
|
|
8
|
+
const EMPTY_PRICE = 0
|
|
9
|
+
const MINUTE_MS = 60 * 1000
|
|
10
|
+
async function getJson(ctx, url) {
|
|
11
|
+
let response
|
|
12
|
+
try {
|
|
13
|
+
response = await ctx.fetch(url, { headers: { 'User-Agent': 'Mozilla/5.0' }, signal: ctx.signal, redirect: 'error' })
|
|
14
|
+
} catch (e) {
|
|
15
|
+
if (ctx.signal.aborted) throw new StockError('CANCELLED', '请求已取消', 503)
|
|
16
|
+
if (e instanceof StockError) throw e
|
|
17
|
+
throw new StockError('NETWORK', '无法连接行情来源', 502, { retryable: true })
|
|
18
|
+
}
|
|
19
|
+
if (response.status === 401 || response.status === 403) throw new StockError('AUTH', '来源拒绝了该凭据', 401)
|
|
20
|
+
if (response.status === 429) throw new StockError('RATE_LIMIT', '来源限流', 429, { retryAfterMs: MINUTE_MS })
|
|
21
|
+
if (!response.ok) throw new StockError('NETWORK', '来源服务暂不可用', 502, { retryable: true })
|
|
22
|
+
return response.json().catch(() => { throw new StockError('BAD_PAYLOAD', '来源响应不是JSON', 502) })
|
|
23
|
+
}
|
|
24
|
+
export const finnhub = {
|
|
25
|
+
descriptor: { adapterId: 'finnhub', capabilities: ['quotes'], markets: ['XNAS', 'XNYS'], instruments: ['equity'], maxQuoteBatch: 1, credential: 'DSH_STOCK_FINNHUB_TOKEN', description: 'Finnhub:需配置凭据,美股实时报价,免费档不含K线,单只一请求', endpointKeys: [{ key: 'quotes', label: '实时报价' }] },
|
|
26
|
+
async probe(request, ctx) {
|
|
27
|
+
const security = { id: `${request.market}:equity:${PROBE_SECURITY}`, exchange: request.market, code: PROBE_SECURITY }
|
|
28
|
+
const result = await this.quotes({ ...request, securities: [security] }, ctx)
|
|
29
|
+
if (!result.items.length) throw new StockError('NO_DATA', '来源未返回可校验数据,暂不能确认能力就绪', 422)
|
|
30
|
+
return { status: 'ready', capability: 'quotes', market: request.market, instrument: 'equity' }
|
|
31
|
+
},
|
|
32
|
+
async quotes(request, ctx) {
|
|
33
|
+
const token = ctx.credential(), items = [], errors = []
|
|
34
|
+
for (const security of request.securities) {
|
|
35
|
+
const body = await getJson(ctx, `${endpointOf(ctx, 'quotes')}?symbol=${encodeURIComponent(security.code)}&token=${encodeURIComponent(token)}`)
|
|
36
|
+
if (!Number.isFinite(body?.c) || body.c === EMPTY_PRICE) {
|
|
37
|
+
errors.push({ securityId: security.id, code: 'NO_DATA', message: '来源未返回此证券报价' })
|
|
38
|
+
continue
|
|
39
|
+
}
|
|
40
|
+
// t 是最后一笔成交的 Unix 秒。延迟交给 collector 按时差派生: 盘后拉取时差本来就大,
|
|
41
|
+
// 适配器硬声明实时等于替来源撒谎。
|
|
42
|
+
items.push(normalizeQuote({
|
|
43
|
+
securityId: security.id, providerInstanceId: request.providerInstanceId, adapterId: 'finnhub', providerSymbol: security.code,
|
|
44
|
+
last: body.c, previousClose: body.pc ?? null, open: body.o ?? null, high: body.h ?? null, low: body.l ?? null,
|
|
45
|
+
volume: null, volumeUnit: 'share', amount: null, amountUnit: MARKET_META[security.exchange]?.currency || 'USD',
|
|
46
|
+
quoteAt: Number.isFinite(body.t) && body.t > 0 ? new Date(body.t * 1000).toISOString() : null,
|
|
47
|
+
timestampKind: 'trade',
|
|
48
|
+
receivedAt: ctx.now(), delayKind: 'unknown', delaySeconds: null, securityState: 'unknown',
|
|
49
|
+
}))
|
|
50
|
+
}
|
|
51
|
+
return { providerInstanceId: request.providerInstanceId, fetchedAt: ctx.now(), items, errors }
|
|
52
|
+
},
|
|
53
|
+
}
|
|
@@ -37,7 +37,7 @@ async function query(capability, params, ctx) {
|
|
|
37
37
|
}
|
|
38
38
|
function symbol(security) { return `${security.code}.${SUFFIX[security.exchange]}` }
|
|
39
39
|
export const tushare = {
|
|
40
|
-
descriptor: { adapterId: 'tushare', capabilities: ['quotes', 'catalog', 'calendar'], markets: ['XSHG', 'XSHE'], instruments: ['equity'], maxQuoteBatch: 20, credential: '
|
|
40
|
+
descriptor: { adapterId: 'tushare', capabilities: ['quotes', 'catalog', 'calendar'], markets: ['XSHG', 'XSHE'], instruments: ['equity'], maxQuoteBatch: 20, credential: 'DSH_STOCK_TUSHARE_TOKEN', description: 'Tushare Pro:需配置凭据,沪深目录/日历/行情,有SLA' },
|
|
41
41
|
async catalog(request, ctx) {
|
|
42
42
|
let rows = await query('catalog', { exchange: EXCHANGE[request.market], list_status: 'L' }, ctx)
|
|
43
43
|
let complete = rows.length < 6000
|
package/src/routes.mjs
CHANGED
|
@@ -25,6 +25,7 @@ export function registerRoutes(webServer, app) {
|
|
|
25
25
|
preferences: ['POST', input => { operationSchema.parse(input); return app.preferences({ ...input, payload: input.patch }) }],
|
|
26
26
|
configuration: ['POST', input => { operationSchema.parse(input); return app.configuration({ ...input, payload: { providers: input.providers, routes: input.routes } }) }],
|
|
27
27
|
'provider-check': ['POST', (input, signal) => app.providerCheck(input, signal)],
|
|
28
|
+
credential: ['POST', input => app.credential(input)],
|
|
28
29
|
'catalog-sync': ['POST', input => app.sync(input)],
|
|
29
30
|
'route-selection': ['POST', (input, signal) => app.routeSelection(input, signal)],
|
|
30
31
|
refresh: ['POST', (input, signal) => app.refresh(input, signal)],
|
package/src/schemas.mjs
CHANGED
|
@@ -13,12 +13,12 @@ const rate = z.number().int().positive().max(100000)
|
|
|
13
13
|
export const capability = z.enum(['quotes', 'catalog', 'search', 'calendar', 'kline'])
|
|
14
14
|
export const marketSchema = z.enum(Object.keys(MARKET_META))
|
|
15
15
|
export const providerSchema = z.strictObject({
|
|
16
|
-
id, adapterId: id, enabled: z.boolean(),
|
|
16
|
+
id, adapterId: id, enabled: z.boolean(), credentialRef: z.string().regex(/^[A-Z][A-Z0-9_]{0,63}$/).nullable(), quotaGroup: id,
|
|
17
17
|
budget: z.strictObject({ requestsPerMinute: rate.nullable(), dailyRequestLimit: rate.nullable(), billingUnit: z.enum(['request', 'symbol']), symbolCreditsPerMinute: rate.nullable(), capabilityLimits: z.partialRecord(capability, rate) }),
|
|
18
18
|
endpoints: z.record(z.string().url()).optional(),
|
|
19
19
|
// 上游出口代理(反代/正向代理统一走 URL): http(s)://[user:pass@]host:port, 凭据在 userinfo
|
|
20
20
|
proxy: z.string().url().refine(v => v.startsWith('http://') || v.startsWith('https://'), '代理仅支持 http(s) URL').optional(),
|
|
21
|
-
}).refine(p => p.
|
|
21
|
+
}).refine(p => p.credentialRef !== null || p.budget.requestsPerMinute !== null, '免凭据来源必须声明保守预算')
|
|
22
22
|
export const routeSchema = z.strictObject({
|
|
23
23
|
id, capability, market: marketSchema, instrument: z.literal('equity'), primaryInstanceId: id,
|
|
24
24
|
fallbackInstanceIds: z.array(id).max(1), failoverMode: z.enum(['off', 'network']), maxDelaySeconds: z.number().nonnegative().nullable(), acceptUnknownDelay: z.boolean(),
|
|
@@ -47,7 +47,7 @@ export function parseConfiguration(value) {
|
|
|
47
47
|
if (providerIds.has(p.id)) fail('DUPLICATE_PROVIDER', '数据源实例名称重复', 422)
|
|
48
48
|
providerIds.add(p.id)
|
|
49
49
|
if (p.budget.billingUnit === 'symbol' && p.budget.symbolCreditsPerMinute === null) fail('INVALID_BUDGET', '按证券计费必须提供证券额度', 422)
|
|
50
|
-
const same = config.providers.filter(other => other.adapterId === p.adapterId && other.
|
|
50
|
+
const same = config.providers.filter(other => other.adapterId === p.adapterId && other.credentialRef === p.credentialRef)
|
|
51
51
|
if (same.some(other => other.quotaGroup !== p.quotaGroup)) fail('INVALID_BUDGET', '同账号引用必须共享额度组', 422)
|
|
52
52
|
}
|
|
53
53
|
const routeIds = new Set()
|
|
@@ -74,10 +74,10 @@ export const domainSpec = { name: 'stock_assistant', version: 1, layout: 'single
|
|
|
74
74
|
export const defaultConfig = () => {
|
|
75
75
|
const budget = (requestsPerMinute, capabilityLimits = {}) => ({ requestsPerMinute, dailyRequestLimit: null, billingUnit: 'request', symbolCreditsPerMinute: null, capabilityLimits })
|
|
76
76
|
const providers = [
|
|
77
|
-
{ id: 'em-default', adapterId: 'eastmoney', enabled: true,
|
|
78
|
-
{ id: 'sn-backup', adapterId: 'sina', enabled: true,
|
|
79
|
-
{ id: 'tx-backup', adapterId: 'tencent', enabled: true,
|
|
80
|
-
{ id: 'xq-backup', adapterId: 'xueqiu', enabled: true,
|
|
77
|
+
{ id: 'em-default', adapterId: 'eastmoney', enabled: true, credentialRef: null, quotaGroup: 'free-quote', budget: budget(60, { kline: 30 }) },
|
|
78
|
+
{ id: 'sn-backup', adapterId: 'sina', enabled: true, credentialRef: null, quotaGroup: 'free-list', budget: budget(120, { catalog: 60 }) },
|
|
79
|
+
{ id: 'tx-backup', adapterId: 'tencent', enabled: true, credentialRef: null, quotaGroup: 'free-backup', budget: budget(60, { kline: 20 }) },
|
|
80
|
+
{ id: 'xq-backup', adapterId: 'xueqiu', enabled: true, credentialRef: null, quotaGroup: 'free-xq', budget: budget(60) },
|
|
81
81
|
]
|
|
82
82
|
// 备用源只在探针可验证的组合上声明: 腾讯美股K线需先由搜索建立代码映射, 探针期必然不可用
|
|
83
83
|
const klineBackup = new Set(['XSHG', 'XSHE', 'XHKG'])
|
package/src/state.mjs
CHANGED
|
@@ -6,8 +6,16 @@ export const digest = value => createHash('sha256').update(JSON.stringify(value)
|
|
|
6
6
|
export async function openState(storageDomain, changed = () => {}, now = Date.now) {
|
|
7
7
|
const domain = await storageDomain.open(domainSpec)
|
|
8
8
|
const table = domain.table('control'), cache = domain.table('cache')
|
|
9
|
+
// 存量数据: 数据源实例的凭据字段曾叫 credentialEnv, 现在交给宿主的凭据服务保管, 更名 credentialRef。
|
|
10
|
+
// 老数据里那一栏本来就只存引用名(值是环境变量里的), 改名即可, 不改语义。
|
|
11
|
+
const renameCredentialField = root => {
|
|
12
|
+
if (!root || !Array.isArray(root.providers)) return root
|
|
13
|
+
if (!root.providers.some(p => p && 'credentialEnv' in p)) return root
|
|
14
|
+
return { ...root, providers: root.providers.map(({ credentialEnv, ...rest }) => ({ ...rest, credentialRef: credentialEnv ?? null })) }
|
|
15
|
+
}
|
|
9
16
|
try {
|
|
10
17
|
if (!table.get('root')) await table.put('root', initialControl())
|
|
18
|
+
else if (renameCredentialField(table.get('root')) !== table.get('root')) await table.put('root', renameCredentialField(table.get('root')))
|
|
11
19
|
controlSchema.parse(table.get('root'))
|
|
12
20
|
} catch (e) { await domain.close(); throw e }
|
|
13
21
|
let tail = Promise.resolve(), stopped = false
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# 股票工具兼容性与验收记录
|
|
2
2
|
|
|
3
|
-
日期:2026-10-29
|
|
3
|
+
日期:2026-10-29(本文按轮次累积,最新一轮见 2026-11-09 节)。包版本 0.1.0(当时;当前 0.4.0),Node v24.14.1,Windows。验证由当前主会话执行,用户明确禁止子agent;不声称独立审查通过。本记录将已验证行为与未验证环境事实分开,不以测试通过推导真实账户可用。
|
|
4
4
|
|
|
5
5
|
## 环境与范围
|
|
6
6
|
|
|
@@ -85,7 +85,7 @@
|
|
|
85
85
|
|
|
86
86
|
## 未验证与当前边界
|
|
87
87
|
|
|
88
|
-
- 0.2.1-rc.2
|
|
88
|
+
- 本节(2026-10-29)未覆盖的版本:0.2.1-rc.5 只有 `.compat/0.2.1-rc.5` 的 crash-only 装载记录(page true)与 manifest 登记;0.2.2-rc.1 由 2026-11-09 节补齐。历史轮次结论不外推。真实浏览器多窗口同时写、实际关闭最后一条宿主会话、30次P95打开时延、150%浏览器缩放及所有5分钟网络组合尚未逐项实测。生产HMR开发通道未经本插件改动验证(未改生产profile,无可热重载对象;client为请求现读)。
|
|
89
89
|
- client factory测试能证明代码不引用session,不代替真实宿主全部会话操作人工验收;测试夹具SSE桥不代替真宿主WS。两者证据分开记录。
|
|
90
90
|
- 当前内置生产适配器仅Tushare;混平台抽象由两独立测试适配器覆盖。真实平台字段、权限、预算及来源最终时效需授权账户单独核对。
|
|
91
91
|
- 收盘边界最后对账、目录上限板块细分、U09/C05/C06/C07/P12驻留等缺口已补固定结构测试,最终计数57/57。未逐项复刻全部57条BDD的每个环境组合,测试名与BDD ID的对应关系以断言语义为准。
|
|
@@ -182,6 +182,24 @@
|
|
|
182
182
|
- 悬浮窗的轮询状态机没有端到端用例:`pollPlan` 各分支已由纯函数用例锁定,但从「面板报价冻结」到「状态翻回」的整链只在真机上确认过。
|
|
183
183
|
- 开市发现延迟:安静档最快一分钟一拍,第十拍才真刷新,所以收盘后开市最多要等十拍(默认间隔下约十分钟)才恢复实时。
|
|
184
184
|
|
|
185
|
+
## 2026-11-09 隔离宿主 0.2.2-rc.1 与商店截图采集
|
|
186
|
+
|
|
187
|
+
商店详情页需要与当前版本一致的界面证据,同时不改生产 profile/宿主。本轮用仓库 compat 工位新开隔离实例,采集真实界面截图并顺带回归主路径。
|
|
188
|
+
|
|
189
|
+
- **环境**:`node scripts/compat/run.mjs --version 0.2.2-rc.1 --port 9297 --work-root .work/shots --only dsh-stock-assistant --keep`。`DSH_HOME` 指向 `.work/shots/0.2.2-rc.1/home`;`--only` 只决定 `dsh.profile.bundles` 白名单(基座 + dshmarket + 本包),profile dependencies 仍按隔离工位装全仓包、未启用。端口 9297,生产 3080 与 `~/.dsh` 未读写。宿主以 dev-link 同款 junction 指向工作副本。
|
|
190
|
+
- **数据**:经真实 HTTP 合约(搜索候选→`watchlist add`→`group`/`pin`/`marks`)写入 10 只演示自选,覆盖沪、深、港、美股 NASDAQ/NYSE、日、韩、英八个市场;分组为消费/新能源/金融/港股/美股/海外,贵州茅台置顶并带成本 1400/卖价 1800 两条标记。上证目录经 `catalog-sync` 同步 2468 只,用于浏览市场页。
|
|
191
|
+
- **实测面**:
|
|
192
|
+
- 导航入口「股票」进入 main,自选表 10 行全部取到真实东财报价,分组段头统计、置顶区、持仓盈亏与来源健康点正常
|
|
193
|
+
- 详情抽屉:日 K 250 根、MA5/10/20/60 与 EMA/BOLL/BBI 指标线、成本/卖价标记线、区间最高/最低;鼠标悬停出十字线读数(日期/开高低收/涨跌/量/指标值)
|
|
194
|
+
- 悬浮盯盘:图形形态(含勾选面板、成本/卖价标记线与价格刻度);列表形态本轮未截图
|
|
195
|
+
- 搜索:多市场候选(美股 + ETF + 英股)带币种徽标,「已在自选」态正确
|
|
196
|
+
- 浏览市场:八市场页签、上证指数概览、目录列表首屏
|
|
197
|
+
- 设置:4 个默认数据源、32 条能力路由、8 个市场,数据源卡与市场路由网格渲染正常
|
|
198
|
+
- **截图产物**:`assets/screenshots/dsh-stock-assistant/` 下 `board.png`、`kline.png`、`floating.png`、`market.png`、`search.png`、`settings.png`、`settings-routes.png`(均 1600×1000,浅色主题,隔离实例实采);`packages/dsh-stock-assistant/screenshots.json` 按上游 `probe-screenshots` 规则声明 7 条 GitHub 直链(上限 8)。
|
|
199
|
+
- **回归基线**:同工作树 `npm test` 329/329 通过(2026-11-09 23:25,含 Finnhub 与宿主凭据托管用例)。测试计数随工作树变动,提交前以当次输出为准。
|
|
200
|
+
- **边界**:Tushare 与 Finnhub 需要真实凭据,本轮未配置、未消耗任何账户额度;未验证多窗口并发写、会话关闭/恢复、暗色主题截图;截图完成后工作树继续有 finnhub/凭据托管改动,截图只覆盖默认免凭据数据源形态。设置页简介文案已随凭据托管同步,`settings*.png` 为重拍版。
|
|
201
|
+
- **收尾**:按 `.work/shots/0.2.2-rc.1/live.json` 的宿主 pid 与模拟器 pid 组杀(Windows `taskkill /T /F`),并确认 9297/16800 无监听;`keep-stop.mjs` 只认 `.compat` 工位、不适用于自定义 `--work-root`,未使用。`live.json` 保留作证据;演示数据、会话与日志只落 `.work/shots`(不入库),生产宿主未启停。
|
|
202
|
+
|
|
185
203
|
## 宿主升级回归项(本包相关)
|
|
186
204
|
|
|
187
205
|
- **插件 client bundle 缓存失效缺陷(DASH 本体)**:`/plugins/??...&rev=` 聚合 bundle 的 rev 不包含第三方插件 client 内容(多次宿主重启 rev 恒为 a8db260a2844),插件升级后浏览器按 URL 命中磁盘缓存继续执行旧 client;服务端 bundle 内容已更新(fetch no-store 可取到新代码)。用户侧需强刷或等 rev 变化;宿主修复 rev 内容寻址后,本包 client 级 UX 修复(内联一键开启、RATE_LIMIT 自动重试)需在真机回归一遍运行时表现(测试已覆盖逻辑,运行时验证被该缺陷阻断)。
|