@dshtrading/connector-xysz 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/LICENSE ADDED
@@ -0,0 +1,75 @@
1
+ Copyright (c) 2026 zhu1090093659 (dsh-trading)
2
+
3
+ # PolyForm Noncommercial License 1.0.0
4
+
5
+ <https://polyformproject.org/licenses/noncommercial/1.0.0>
6
+
7
+ ## Acceptance
8
+
9
+ In order to get any license under these terms, you must agree to them as both strict obligations and conditions to all your licenses.
10
+
11
+ ## Copyright License
12
+
13
+ The licensor grants you a copyright license for the software to do everything you might do with the software that would otherwise infringe the licensor's copyright in it for any permitted purpose. However, you may only distribute the software according to [Distribution License](#distribution-license) and make changes or new works based on the software according to [Changes and New Works License](#changes-and-new-works-license).
14
+
15
+ ## Distribution License
16
+
17
+ The licensor grants you an additional copyright license to distribute copies of the software. Your license to distribute covers distributing the software with changes and new works permitted by [Changes and New Works License](#changes-and-new-works-license).
18
+
19
+ ## Notices
20
+
21
+ You must ensure that anyone who gets a copy of any part of the software from you also gets a copy of these terms or the URL for them above, as well as copies of any plain-text lines beginning with `Required Notice:` that the licensor provided with the software. For example:
22
+
23
+ > Required Notice: Copyright Yoyodyne, Inc. (http://example.com)
24
+
25
+ ## Changes and New Works License
26
+
27
+ The licensor grants you an additional copyright license to make changes and new works based on the software for any permitted purpose.
28
+
29
+ ## Patent License
30
+
31
+ The licensor grants you a patent license for the software that covers patent claims the licensor can license, or becomes able to license, that you would infringe by using the software.
32
+
33
+ ## Noncommercial Purposes
34
+
35
+ Any noncommercial purpose is a permitted purpose.
36
+
37
+ ## Personal Uses
38
+
39
+ Personal use for research, experiment, and testing for the benefit of public knowledge, personal study, private entertainment, hobby projects, amateur pursuits, or religious observance, without any anticipated commercial application, is use for a permitted purpose.
40
+
41
+ ## Noncommercial Organizations
42
+
43
+ Use by any charitable organization, educational institution, public research organization, public safety or health organization, environmental protection organization, or government institution is use for a permitted purpose regardless of the source of funding or obligations resulting from the funding.
44
+
45
+ ## Fair Use
46
+
47
+ You may have "fair use" rights for the software under the law. These terms do not limit them.
48
+
49
+ ## No Other Rights
50
+
51
+ These terms do not allow you to sublicense or transfer any of your licenses to anyone else, or prevent the licensor from granting licenses to anyone else. These terms do not imply any other licenses.
52
+
53
+ ## Patent Defense
54
+
55
+ If you make any written claim that the software infringes or contributes to infringement of any patent, your patent license for the software granted under these terms ends immediately. If your company makes such a claim, your patent license ends immediately for work on behalf of your company.
56
+
57
+ ## Violations
58
+
59
+ The first time you are notified in writing that you have violated any of these terms, or done anything with the software not covered by your licenses, your licenses can nonetheless continue if you come into full compliance with these terms, and take practical steps to correct past violations, within 32 days of receiving notice. Otherwise, all your licenses end immediately.
60
+
61
+ ## No Liability
62
+
63
+ ***As far as the law allows, the software comes as is, without any warranty or condition, and the licensor will not be liable to you for any damages arising out of these terms or the use or nature of the software, under any kind of legal claim.***
64
+
65
+ ## Definitions
66
+
67
+ The **licensor** is the individual or entity offering these terms, and the **software** is the software the licensor makes available under these terms.
68
+
69
+ **You** refers to the individual or entity agreeing to these terms.
70
+
71
+ **Your company** is any legal entity, sole proprietorship, or other kind of organization that you work for, plus all organizations that have control over, are under the control of, or are under common control with that organization. **Control** means ownership of substantially all the assets of an entity, or the power to direct its management and policies by vote, contract, or otherwise. Control can be direct or indirect.
72
+
73
+ **Your licenses** are all the licenses granted to you for the software under these terms.
74
+
75
+ **Use** means anything you do with the software requiring one of your licenses.
package/README.md ADDED
@@ -0,0 +1,64 @@
1
+ # @dshtrading/connector-xysz
2
+
3
+ 中国银河证券**星耀数智**(AmazingData / tgw)A 股数据源适配器。**数据面-only**:
4
+ 提供 \`tradingCnMarketData\` 与 \`cn_*\` 行情工具,无交易通道(星耀数智是行情与资讯数据服务)。
5
+
6
+ ## 架构
7
+
8
+ 上游不是公开 Web 端点,而是券商 SDK:
9
+
10
+ connector-xysz ──HTTP──> xysz-api(FastAPI 封装,局域网 Ubuntu 机器)
11
+ └──AmazingData/tgw Python SDK──> 101.230.159.235:8600
12
+
13
+ AmazingData 是**有状态**的 Python SDK(调用前必须 \`ad.login()\`),不能在 Node 侧直连;
14
+ \`xysz-api\` 承担登录单例与 SDK 调用串行化(见该服务 README)。本连接器只认 \`apiUrl\`。
15
+
16
+ ## 配置
17
+
18
+ | 字段 | 默认 | 说明 |
19
+ |---|---|---|
20
+ | \`enabled\` | \`false\` | 互斥激活总开关(同一市场同一时刻至多一个数据源激活) |
21
+ | \`apiUrl\` | \`http://127.0.0.1:8191\` | xysz-api 地址;可用环境变量 \`XYSZ_API_URL\` |
22
+ | \`timeoutMs\` | \`60000\` | 单次上游请求超时 |
23
+
24
+ ## 接线
25
+
26
+ - **数据面行**:\`packages/cn/cordis.patch.yml\` → \`dsh-trading-cn-dataplane-xysz\`
27
+ (注册 \`(cn, xysz)\` 进 \`tradingMarketDataRegistry\`,不占根市场键)。
28
+ - **preset 行**:\`packages/cn/assets/preset/cn-trader/agent.cordis.yml\` →
29
+ \`dsh-trading-cn-connector-xysz\`(在既有 \`tradingCnMarketData\` isolate 组内)。
30
+ - **provider 词汇**:\`packages/router/src/index.ts\` 的 \`PROVIDER_VOCABULARY\` 加 \`xysz\`;
31
+ 设置页显示名 \`packages/client-ui-settings\`(\`PROVIDER_LABELS\` + \`locales.ts\` 中英)。
32
+ - **profile overrides**:\`node scripts/sync-profile-overrides.mjs --all --dsh-home ~/.dsh-trading\`
33
+ (坑 #15;注意 \`--dsh-home\`,Web 会话的 \`DSH_HOME\` 指向 ~/.dsh 会找错 profile 集)。
34
+
35
+ 用户切换:设置 → 数据源 → cn → 银河星耀数智(AmazingData)。
36
+
37
+ ## 工具
38
+
39
+ | 工具 | 说明 |
40
+ |---|---|
41
+ | \`cn_get_ticker\` | 最新行情(价/昨收/涨跌幅/买卖一档) |
42
+ | \`cn_get_klines\` | K 线(1m/3m/5m/15m/30m/1h/2h/1d/1w/1M,A 股全历史) |
43
+ | \`cn_get_orderbook\` | 五档盘口 |
44
+ | \`cn_list_instruments\` | A 股名册(沪深北 ~5570 只,含中文简称) |
45
+ | \`cn_get_fundamentals\` | 基本面快照(简称/板块 + 52 周高低) |
46
+
47
+ ## 契约
48
+
49
+ - **符号**:入参接受规范形 \`600519.SH\`、裸 6 位 \`600519\`、前缀形 \`sh600519\`;
50
+ 输出一律规范形。港股/加密形态显式拒绝(\`TRADING_UNSUPPORTED_SYMBOL\`,fail-closed)。
51
+ - **周期**:本连接器支持 \`1m/3m/5m/15m/30m/1h/2h/1d/1w/1M\`;上游未覆盖的周期
52
+ (如 \`4h\`/\`3d\`)抛 \`TRADING_UNSUPPORTED_INTERVAL\`,不静默降级。
53
+ - **错误映射**:上游 400 → \`TRADING_UNSUPPORTED_SYMBOL\`;5xx/502 → \`TRADING_UPSTREAM_ERROR\`;
54
+ 不可达 → \`TRADING_NETWORK\`;非 JSON → \`TRADING_EXCHANGE_ERROR\`。
55
+ - **服务类字段**用 TS 编译期 \`private\`(禁 ECMAScript \`#\`,cordis realm 代理会炸)。
56
+
57
+ ## 出网验证(铁律)
58
+
59
+ node spikes/impl-xysz/r3-real-network-verify.mjs # 连接器链路 13 项
60
+ node spikes/impl-xysz/r3-dataplane-e2e.mjs # 数据面装配 + loader 解析面
61
+
62
+ 证据落 \`spikes/impl-xysz/r3-*.raw.json\` + \`r3-verify-summary.json\`。
63
+ 前置:xysz-api 在跑;8191 被 ufw 拦时先开隧道
64
+ \`ssh -f -N -L 127.0.0.1:8191:127.0.0.1:8191 local1\`。
@@ -0,0 +1,7 @@
1
+ import { Config } from "./index.js";
2
+ import { Context } from "@deepseek-ai/cordis";
3
+ //#region src/dataplane.d.ts
4
+ declare const inject: string[];
5
+ declare function apply(ctx: Context, config?: Partial<Config>): void;
6
+ //#endregion
7
+ export { Config, apply, inject };
@@ -0,0 +1,26 @@
1
+ import { Config, ROUTER_PROVIDER, TRADING_CN_MARKET_DATA_KEY, XyszMarketDataService } from "./index.js";
2
+ //#region src/dataplane.ts
3
+ const inject = [];
4
+ /** 解析注册表服务;老部署(base/router 未升级)返回 undefined → 调用方回退直接 provide。 */
5
+ function resolveMarketDataRegistry(ctx) {
6
+ const candidate = ctx.get?.("tradingMarketDataRegistry", false);
7
+ return candidate !== void 0 ? candidate : void 0;
8
+ }
9
+ const MARKET = "cn";
10
+ function apply(ctx, config) {
11
+ if (config?.enabled === false) return;
12
+ const options = {
13
+ apiUrl: config?.apiUrl ?? "http://127.0.0.1:8191",
14
+ timeoutMs: config?.timeoutMs ?? 6e4
15
+ };
16
+ const registry = resolveMarketDataRegistry(ctx);
17
+ if (registry === void 0) {
18
+ new XyszMarketDataService(ctx, options);
19
+ return;
20
+ }
21
+ const inner = ctx.isolate(TRADING_CN_MARKET_DATA_KEY);
22
+ const service = new XyszMarketDataService(inner, options);
23
+ ctx.effect(() => registry.register(MARKET, ROUTER_PROVIDER, service));
24
+ }
25
+ //#endregion
26
+ export { Config, apply, inject };
package/lib/index.d.ts ADDED
@@ -0,0 +1,42 @@
1
+ import { INTERVAL_VOCABULARY, Interval, Kline, Orderbook, StockFundamentals, Ticker, TradingServiceError, XyszRestClient, XyszRestOptions, XyszSymbol, assertSupportedInterval, toXyszSymbol } from "./rest.js";
2
+ import { Context, Service } from "@deepseek-ai/cordis";
3
+ import Schema from "@deepseek-ai/schemastery";
4
+ import { Disposable, Interval as Interval$1, Kline as Kline$1, MarketDataService, Orderbook as Orderbook$1, StockFundamentals as StockFundamentals$1, Ticker as Ticker$1 } from "@dshtrading/api";
5
+ //#region src/index.d.ts
6
+ /** 插件名 = preset 行 id(全仓唯一,insert-only 铁律 #1)。 */
7
+ declare const name = "dsh-trading-cn-connector-xysz";
8
+ interface Config {
9
+ /** 互斥激活总开关(默认 false):false 时本插件不注册任何服务/工具。 */
10
+ enabled: boolean;
11
+ /** 星耀数智 FastAPI 封装服务地址(局域网 192.168.31.50:8191 或本机 SSH 隧道 127.0.0.1:8191)。 */
12
+ apiUrl?: string;
13
+ /** 单次上游请求超时(ms)。 */
14
+ timeoutMs?: number;
15
+ }
16
+ declare const Config: Schema<Config>;
17
+ /** 需要宿主提供的 Cordis 服务。 */
18
+ declare const inject: string[];
19
+ /** 行情服务键(@dshtrading/api 的 Context 增强:tradingCnMarketData)。 */
20
+ declare const TRADING_CN_MARKET_DATA_KEY = "tradingCnMarketData";
21
+ /** 路由 provider slug(开放词汇 = 数据源 slug)。 */
22
+ declare const ROUTER_PROVIDER = "xysz";
23
+ declare class XyszMarketDataService extends Service implements MarketDataService {
24
+ private readonly client;
25
+ constructor(ctx: Context, options?: XyszRestOptions, serviceName?: string);
26
+ getTicker(symbol: string): Promise<Ticker$1>;
27
+ getKlines(symbol: string, interval?: Interval$1, limit?: number): Promise<Kline$1[]>;
28
+ getOrderbook(symbol: string): Promise<Orderbook$1>;
29
+ listInstruments(query?: string): Promise<Array<{
30
+ symbol: string;
31
+ name?: string;
32
+ }>>;
33
+ getFundamentals(symbol: string): Promise<StockFundamentals$1>;
34
+ subscribeTicker(symbol: string, cb: (ticker: Ticker$1) => void, options?: {
35
+ intervalMs?: number;
36
+ }): Disposable;
37
+ }
38
+ /** 路由闸门:选中的 provider 不是本连接器时让位(老部署无路由则放行)。 */
39
+ declare function routeAllows(ctx: Context, config: Config, market?: string): boolean;
40
+ declare function apply(ctx: Context, config: Config): void;
41
+ //#endregion
42
+ export { Config, INTERVAL_VOCABULARY, type Interval, type Kline, type Orderbook, ROUTER_PROVIDER, type StockFundamentals, TRADING_CN_MARKET_DATA_KEY, type Ticker, TradingServiceError, XyszMarketDataService, XyszRestClient, XyszRestOptions, XyszSymbol, apply, assertSupportedInterval, inject, name, routeAllows, toXyszSymbol };
package/lib/index.js ADDED
@@ -0,0 +1,182 @@
1
+ import { INTERVAL_VOCABULARY, TradingServiceError, XyszRestClient, assertSupportedInterval, toXyszSymbol } from "./rest.js";
2
+ import { Service } from "@deepseek-ai/cordis";
3
+ import { defineTool } from "@deepseek-ai/dsh-tools";
4
+ import Schema from "@deepseek-ai/schemastery";
5
+ //#region src/index.ts
6
+ /** 插件名 = preset 行 id(全仓唯一,insert-only 铁律 #1)。 */
7
+ const name = "dsh-trading-cn-connector-xysz";
8
+ const Config = Schema.object({
9
+ enabled: Schema.boolean().default(false).description("是否激活星耀数智连接器(同一市场同一时刻至多一个数据源激活)"),
10
+ apiUrl: Schema.string().default("http://127.0.0.1:8191").description("星耀数智 AmazingData REST 封装服务地址"),
11
+ timeoutMs: Schema.number().default(6e4).description("上游请求超时(毫秒)")
12
+ });
13
+ /** 需要宿主提供的 Cordis 服务。 */
14
+ const inject = ["tools"];
15
+ /** 行情服务键(@dshtrading/api 的 Context 增强:tradingCnMarketData)。 */
16
+ const TRADING_CN_MARKET_DATA_KEY = "tradingCnMarketData";
17
+ /** 路由 provider slug(开放词汇 = 数据源 slug)。 */
18
+ const ROUTER_PROVIDER = "xysz";
19
+ const SUBSCRIBE_MIN_MS = 1e3;
20
+ const SUBSCRIBE_DEFAULT_MS = 5e3;
21
+ var XyszMarketDataService = class extends Service {
22
+ client;
23
+ constructor(ctx, options = {}, serviceName = TRADING_CN_MARKET_DATA_KEY) {
24
+ super(ctx, serviceName);
25
+ this.client = new XyszRestClient(options);
26
+ }
27
+ async getTicker(symbol) {
28
+ return this.client.getTicker(symbol);
29
+ }
30
+ async getKlines(symbol, interval = "1d", limit = 100) {
31
+ return this.client.getKlines(symbol, interval, limit);
32
+ }
33
+ async getOrderbook(symbol) {
34
+ return this.client.getOrderbook(symbol);
35
+ }
36
+ async listInstruments(query) {
37
+ return this.client.listInstruments(query);
38
+ }
39
+ async getFundamentals(symbol) {
40
+ return this.client.getFundamentals(symbol);
41
+ }
42
+ subscribeTicker(symbol, cb, options) {
43
+ const ms = Math.max(options?.intervalMs ?? SUBSCRIBE_DEFAULT_MS, SUBSCRIBE_MIN_MS);
44
+ const tick = () => {
45
+ this.getTicker(symbol).then(cb, () => {});
46
+ };
47
+ tick();
48
+ const timer = setInterval(tick, ms);
49
+ return { dispose: () => clearInterval(timer) };
50
+ }
51
+ };
52
+ /** 路由闸门:选中的 provider 不是本连接器时让位(老部署无路由则放行)。 */
53
+ function routeAllows(ctx, config, market = "cn") {
54
+ if (!config.enabled) return false;
55
+ const router = ctx.get?.("tradingMarketRouter", false);
56
+ if (router === void 0) return true;
57
+ return router.activeProvider(market) === ROUTER_PROVIDER;
58
+ }
59
+ function apply(ctx, config) {
60
+ if (!config.enabled) return;
61
+ if (!routeAllows(ctx, config, "cn")) return;
62
+ const options = {};
63
+ if (config.apiUrl !== void 0) options.apiUrl = config.apiUrl;
64
+ if (config.timeoutMs !== void 0) options.timeoutMs = config.timeoutMs;
65
+ const marketData = new XyszMarketDataService(ctx, options);
66
+ ctx.inject(["tools"], (ctx) => {
67
+ const tools = ctx.tools;
68
+ const register = (t) => {
69
+ if (tools.get(t.name) === void 0) tools.register(t);
70
+ };
71
+ register(defineTool({
72
+ name: "cn_get_ticker",
73
+ description: "Get the latest Level-1 quote for an A-share stock from 中国银河证券星耀数智 (AmazingData). Symbol accepts the canonical A-share form (600519.SH) or a bare 6-digit code (600519). Returns last price, previous close, change percent and bid/ask-1 from the authoritative exchange feed.",
74
+ parameters: { symbol: {
75
+ type: "string",
76
+ required: true,
77
+ description: "A-share symbol, e.g. 600519.SH (or 600519)"
78
+ } },
79
+ output: {
80
+ schema: { type: "string" },
81
+ render: (_a, v) => [{
82
+ type: "text",
83
+ text: v
84
+ }]
85
+ },
86
+ async execute(args) {
87
+ return JSON.stringify(await marketData.getTicker(args.symbol));
88
+ }
89
+ }));
90
+ register(defineTool({
91
+ name: "cn_get_klines",
92
+ description: "Get historical K-lines for A-share stocks from 中国银河证券星耀数智 (AmazingData). Intervals: " + INTERVAL_VOCABULARY.join("/") + " (dsh-trading vocabulary; upstream serves the full A-share history since 2013). Returns up to limit most recent candles in ascending time order.",
93
+ parameters: {
94
+ symbol: {
95
+ type: "string",
96
+ required: true,
97
+ description: "A-share symbol, e.g. 600519.SH (or 600519)"
98
+ },
99
+ interval: {
100
+ type: "string",
101
+ enum: [...INTERVAL_VOCABULARY],
102
+ default: "1d",
103
+ description: "K-line interval"
104
+ },
105
+ limit: {
106
+ type: "integer",
107
+ default: 100,
108
+ description: "Number of most recent candles (ascending)"
109
+ }
110
+ },
111
+ output: {
112
+ schema: { type: "string" },
113
+ render: (_a, v) => [{
114
+ type: "text",
115
+ text: v
116
+ }]
117
+ },
118
+ async execute(args) {
119
+ const klines = await marketData.getKlines(args.symbol, args.interval ?? "1d", args.limit ?? 100);
120
+ return JSON.stringify(klines);
121
+ }
122
+ }));
123
+ register(defineTool({
124
+ name: "cn_get_orderbook",
125
+ description: "Get the 5-level order book (bid/ask prices and sizes) for an A-share stock from 中国银河证券星耀数智 (AmazingData). Derived from the latest exchange Level-1 snapshot row of the current trading day.",
126
+ parameters: { symbol: {
127
+ type: "string",
128
+ required: true,
129
+ description: "A-share symbol, e.g. 600519.SH (or 600519)"
130
+ } },
131
+ output: {
132
+ schema: { type: "string" },
133
+ render: (_a, v) => [{
134
+ type: "text",
135
+ text: v
136
+ }]
137
+ },
138
+ async execute(args) {
139
+ return JSON.stringify(await marketData.getOrderbook(args.symbol));
140
+ }
141
+ }));
142
+ register(defineTool({
143
+ name: "cn_list_instruments",
144
+ description: "List the A-share instrument universe (Shanghai/Shenzhen/Beijing, about 5500 symbols with Chinese short names) from 中国银河证券星耀数智 (AmazingData). Optional query filters by code or name substring.",
145
+ parameters: { query: {
146
+ type: "string",
147
+ description: "Optional code or name filter, e.g. 茅台 or 6005"
148
+ } },
149
+ output: {
150
+ schema: { type: "string" },
151
+ render: (_a, v) => [{
152
+ type: "text",
153
+ text: v
154
+ }]
155
+ },
156
+ async execute(args) {
157
+ return JSON.stringify(await marketData.listInstruments(args.query));
158
+ }
159
+ }));
160
+ register(defineTool({
161
+ name: "cn_get_fundamentals",
162
+ description: "Get an A-share fundamental snapshot from 中国银河证券星耀数智 (AmazingData): company short name, listing board/date and the 52-week high/low derived from weekly K-lines.",
163
+ parameters: { symbol: {
164
+ type: "string",
165
+ required: true,
166
+ description: "A-share symbol, e.g. 600519.SH (or 600519)"
167
+ } },
168
+ output: {
169
+ schema: { type: "string" },
170
+ render: (_a, v) => [{
171
+ type: "text",
172
+ text: v
173
+ }]
174
+ },
175
+ async execute(args) {
176
+ return JSON.stringify(await marketData.getFundamentals(args.symbol));
177
+ }
178
+ }));
179
+ });
180
+ }
181
+ //#endregion
182
+ export { Config, INTERVAL_VOCABULARY, ROUTER_PROVIDER, TRADING_CN_MARKET_DATA_KEY, TradingServiceError, XyszMarketDataService, XyszRestClient, apply, assertSupportedInterval, inject, name, routeAllows, toXyszSymbol };
package/lib/rest.d.ts ADDED
@@ -0,0 +1,45 @@
1
+ import { Interval as Interval$1, Kline as Kline$1, Orderbook as Orderbook$1, StockFundamentals as StockFundamentals$1, Ticker as Ticker$1, TradingErrorCode } from "@dshtrading/api";
2
+ //#region src/rest.d.ts
3
+ declare class TradingServiceError extends Error {
4
+ readonly code: TradingErrorCode;
5
+ constructor(code: TradingErrorCode, message: string, cause?: unknown);
6
+ }
7
+ /** dsh-trading 规范 interval 词汇(星耀数智上游覆盖 A 股全部周期)。 */
8
+ declare const INTERVAL_VOCABULARY: readonly ["1m", "3m", "5m", "15m", "30m", "1h", "2h", "1d", "1w", "1M"];
9
+ /** 星耀数智上游支持的周期(与 xysz-api 的 _INTERVAL_TO_PERIOD 一一对应)。 */
10
+ declare function assertSupportedInterval(interval: Interval$1): void;
11
+ interface XyszSymbol {
12
+ /** A 股规范形(docs/symbol-vocabulary.md:NNNNNN.SH / NNNNNN.SZ / NNNNNN.BJ)。 */
13
+ readonly canonical: string;
14
+ readonly code: string;
15
+ readonly exchange: 'SH' | 'SZ' | 'BJ';
16
+ }
17
+ /**
18
+ * A 股符号归一:接受规范形 600519.SH、裸 6 位 600519、带市场前缀形
19
+ * sh600519 / 600519.sh;港股、加密等跨市场形态显式拒绝(fail-closed)。
20
+ */
21
+ declare function toXyszSymbol(symbol: string): XyszSymbol;
22
+ interface XyszRestOptions {
23
+ /** 星耀数智 FastAPI 封装服务基址(缺省读 XYSZ_API_URL,再缺省回本机隧道端口)。 */
24
+ apiUrl?: string;
25
+ fetchImpl?: typeof fetch;
26
+ /** 单次请求超时(ms)。 */
27
+ timeoutMs?: number;
28
+ }
29
+ declare class XyszRestClient {
30
+ readonly apiUrl: string;
31
+ private readonly fetchImpl;
32
+ private readonly timeoutMs;
33
+ constructor(options?: XyszRestOptions);
34
+ private requestJson;
35
+ getTicker(symbol: string): Promise<Ticker$1>;
36
+ getKlines(symbol: string, interval?: Interval$1, limit?: number): Promise<Kline$1[]>;
37
+ getOrderbook(symbol: string): Promise<Orderbook$1>;
38
+ listInstruments(query?: string): Promise<Array<{
39
+ symbol: string;
40
+ name?: string;
41
+ }>>;
42
+ getFundamentals(symbol: string): Promise<StockFundamentals$1>;
43
+ }
44
+ //#endregion
45
+ export { INTERVAL_VOCABULARY, type Interval$1 as Interval, type Kline$1 as Kline, type Orderbook$1 as Orderbook, type StockFundamentals$1 as StockFundamentals, type Ticker$1 as Ticker, TradingServiceError, XyszRestClient, XyszRestOptions, XyszSymbol, assertSupportedInterval, toXyszSymbol };
package/lib/rest.js ADDED
@@ -0,0 +1,190 @@
1
+ //#region src/rest.ts
2
+ var TradingServiceError = class extends Error {
3
+ code;
4
+ constructor(code, message, cause) {
5
+ super(message);
6
+ this.name = "TradingServiceError";
7
+ this.code = code;
8
+ if (cause !== void 0) this.cause = cause;
9
+ }
10
+ };
11
+ /** dsh-trading 规范 interval 词汇(星耀数智上游覆盖 A 股全部周期)。 */
12
+ const INTERVAL_VOCABULARY = [
13
+ "1m",
14
+ "3m",
15
+ "5m",
16
+ "15m",
17
+ "30m",
18
+ "1h",
19
+ "2h",
20
+ "1d",
21
+ "1w",
22
+ "1M"
23
+ ];
24
+ /** 星耀数智上游支持的周期(与 xysz-api 的 _INTERVAL_TO_PERIOD 一一对应)。 */
25
+ function assertSupportedInterval(interval) {
26
+ if (!INTERVAL_VOCABULARY.includes(interval)) throw new TradingServiceError("TRADING_UNSUPPORTED_INTERVAL", "Xysz upstream does not serve interval \"" + interval + "\"; supported: " + INTERVAL_VOCABULARY.join(", "));
27
+ }
28
+ const EXCHANGE_BY_PREFIX = [
29
+ [/^(6|9)/, "SH"],
30
+ [/^(0|2|3)/, "SZ"],
31
+ [/^(4|8)/, "BJ"]
32
+ ];
33
+ /**
34
+ * A 股符号归一:接受规范形 600519.SH、裸 6 位 600519、带市场前缀形
35
+ * sh600519 / 600519.sh;港股、加密等跨市场形态显式拒绝(fail-closed)。
36
+ */
37
+ function toXyszSymbol(symbol) {
38
+ const clean = symbol.trim().toUpperCase();
39
+ if (clean === "") throw new TradingServiceError("TRADING_UNSUPPORTED_SYMBOL", "Xysz: empty symbol");
40
+ if (/\.HK$/.test(clean) || /^HK\.?\d/.test(clean) || /(USDT|BTC|ETH)$/.test(clean)) throw new TradingServiceError("TRADING_UNSUPPORTED_SYMBOL", "Xysz cn: " + JSON.stringify(symbol) + " is not an A-share symbol (this connector serves cn/A-share only)");
41
+ const dotted = /^(\d{6})\.(SH|SZ|BJ)$/.exec(clean);
42
+ if (dotted) {
43
+ const code = dotted[1];
44
+ const exchange = dotted[2];
45
+ return {
46
+ canonical: code + "." + exchange,
47
+ code,
48
+ exchange
49
+ };
50
+ }
51
+ const bare = /^(\d{6})$/.exec(clean);
52
+ if (bare) {
53
+ const code = bare[1];
54
+ const matched = EXCHANGE_BY_PREFIX.find(([re]) => re.test(code));
55
+ const exchange = matched !== void 0 ? matched[1] : "SZ";
56
+ return {
57
+ canonical: code + "." + exchange,
58
+ code,
59
+ exchange
60
+ };
61
+ }
62
+ const prefixed = /^(SH|SZ|BJ)\.?(\d{6})$/.exec(clean);
63
+ if (prefixed) {
64
+ const code = prefixed[2];
65
+ const exchange = prefixed[1];
66
+ return {
67
+ canonical: code + "." + exchange,
68
+ code,
69
+ exchange
70
+ };
71
+ }
72
+ throw new TradingServiceError("TRADING_UNSUPPORTED_SYMBOL", "Xysz cn: malformed A-share symbol " + JSON.stringify(symbol) + " — expected NNNNNN.SH / NNNNNN.SZ / NNNNNN.BJ, a bare 6-digit code, or sh600519");
73
+ }
74
+ var XyszRestClient = class {
75
+ apiUrl;
76
+ fetchImpl;
77
+ timeoutMs;
78
+ constructor(options = {}) {
79
+ this.apiUrl = (options.apiUrl ?? process.env.XYSZ_API_URL ?? "http://127.0.0.1:8191").replace(/\/+$/, "");
80
+ this.fetchImpl = options.fetchImpl ?? globalThis.fetch;
81
+ this.timeoutMs = options.timeoutMs ?? 6e4;
82
+ }
83
+ async requestJson(path, params = {}) {
84
+ const search = new URLSearchParams();
85
+ for (const [key, value] of Object.entries(params)) if (value !== void 0) search.set(key, String(value));
86
+ const url = this.apiUrl + path + (search.size > 0 ? "?" + search.toString() : "");
87
+ let res;
88
+ try {
89
+ res = await this.fetchImpl(url, { signal: AbortSignal.timeout(this.timeoutMs) });
90
+ } catch (err) {
91
+ throw new TradingServiceError("TRADING_NETWORK", "Xysz upstream unreachable at " + this.apiUrl + ": " + (err instanceof Error ? err.message : String(err)), err);
92
+ }
93
+ if (!res.ok) {
94
+ const detail = (await res.text().catch(() => "")).slice(0, 400);
95
+ if (res.status === 400) throw new TradingServiceError("TRADING_UNSUPPORTED_SYMBOL", "Xysz upstream rejected the request: " + detail);
96
+ throw new TradingServiceError("TRADING_UPSTREAM_ERROR", "Xysz upstream HTTP " + res.status + " for " + path + ": " + detail);
97
+ }
98
+ try {
99
+ return await res.json();
100
+ } catch (err) {
101
+ throw new TradingServiceError("TRADING_EXCHANGE_ERROR", "Xysz upstream returned non-JSON for " + path, err);
102
+ }
103
+ }
104
+ async getTicker(symbol) {
105
+ const { canonical } = toXyszSymbol(symbol);
106
+ const data = await this.requestJson("/api/v1/ticker", { symbol: canonical });
107
+ const price = typeof data.price === "number" && Number.isFinite(data.price) ? data.price : 0;
108
+ const optional = {};
109
+ for (const [src, dst] of [
110
+ ["volume", "volume"],
111
+ ["prevClose", "prevClose"],
112
+ ["changePercent", "changePercent"],
113
+ ["bid", "bid"],
114
+ ["ask", "ask"]
115
+ ]) {
116
+ const value = data[src];
117
+ if (typeof value === "number" && Number.isFinite(value)) optional[dst] = value;
118
+ }
119
+ return {
120
+ symbol: canonical,
121
+ price,
122
+ timestamp: typeof data.timestamp === "number" ? data.timestamp : Date.now(),
123
+ ...optional
124
+ };
125
+ }
126
+ async getKlines(symbol, interval = "1d", limit = 100) {
127
+ assertSupportedInterval(interval);
128
+ const { canonical } = toXyszSymbol(symbol);
129
+ const data = await this.requestJson("/api/v1/klines", {
130
+ symbol: canonical,
131
+ interval,
132
+ limit
133
+ });
134
+ const rows = Array.isArray(data.klines) ? data.klines : [];
135
+ const klines = [];
136
+ for (const row of rows) {
137
+ if (typeof row.openTime !== "number" || typeof row.open !== "number" || typeof row.high !== "number" || typeof row.low !== "number" || typeof row.close !== "number") continue;
138
+ klines.push({
139
+ openTime: row.openTime,
140
+ open: row.open,
141
+ high: row.high,
142
+ low: row.low,
143
+ close: row.close,
144
+ volume: typeof row.volume === "number" ? row.volume : 0,
145
+ closeTime: row.openTime
146
+ });
147
+ }
148
+ return klines;
149
+ }
150
+ async getOrderbook(symbol) {
151
+ const { canonical } = toXyszSymbol(symbol);
152
+ const data = await this.requestJson("/api/v1/orderbook", { symbol: canonical });
153
+ const levels = (rows) => (rows ?? []).filter((r) => typeof r.price === "number" && r.price > 0).map((r) => ({
154
+ price: r.price,
155
+ amount: typeof r.amount === "number" ? r.amount : 0
156
+ }));
157
+ return {
158
+ symbol: canonical,
159
+ bids: levels(data.bids),
160
+ asks: levels(data.asks),
161
+ timestamp: typeof data.timestamp === "number" ? data.timestamp : Date.now()
162
+ };
163
+ }
164
+ async listInstruments(query) {
165
+ const data = await this.requestJson("/api/v1/instruments", {
166
+ security_type: "EXTRA_STOCK_A",
167
+ with_names: true
168
+ });
169
+ const items = Array.isArray(data.items) ? data.items : [];
170
+ if (query === void 0 || query.trim() === "") return items;
171
+ const needle = query.trim().toUpperCase();
172
+ return items.filter((it) => it.symbol.toUpperCase().includes(needle) || (it.name ?? "").toUpperCase().includes(needle));
173
+ }
174
+ async getFundamentals(symbol) {
175
+ const { canonical } = toXyszSymbol(symbol);
176
+ const data = await this.requestJson("/api/v1/fundamentals", { symbol: canonical });
177
+ const name = typeof data.name === "string" && data.name !== "" ? data.name : void 0;
178
+ const high = typeof data.fiftyTwoWeekHigh === "number" ? data.fiftyTwoWeekHigh : void 0;
179
+ const low = typeof data.fiftyTwoWeekLow === "number" ? data.fiftyTwoWeekLow : void 0;
180
+ return {
181
+ symbol: canonical,
182
+ timestamp: typeof data.timestamp === "number" ? data.timestamp : Date.now(),
183
+ ...name !== void 0 ? { name } : {},
184
+ ...high !== void 0 ? { fiftyTwoWeekHigh: high } : {},
185
+ ...low !== void 0 ? { fiftyTwoWeekLow: low } : {}
186
+ };
187
+ }
188
+ };
189
+ //#endregion
190
+ export { INTERVAL_VOCABULARY, TradingServiceError, XyszRestClient, assertSupportedInterval, toXyszSymbol };
package/package.json ADDED
@@ -0,0 +1,39 @@
1
+ {
2
+ "name": "@dshtrading/connector-xysz",
3
+ "description": "中国银河证券星耀数智(AmazingData / tgw)A 股数据源连接器(数据面-only):经本机/局域网的 FastAPI 封装服务 xysz-api 提供 tradingCnMarketData 与 cn_* 行情工具,无交易通道",
4
+ "version": "0.5.0",
5
+ "type": "module",
6
+ "main": "lib/index.js",
7
+ "types": "./lib/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./lib/index.d.ts",
11
+ "default": "./lib/index.js"
12
+ },
13
+ "./dataplane": {
14
+ "types": "./lib/dataplane.d.ts",
15
+ "default": "./lib/dataplane.js"
16
+ },
17
+ "./package.json": "./package.json"
18
+ },
19
+ "files": [
20
+ "lib"
21
+ ],
22
+ "license": "PolyForm-Noncommercial-1.0.0",
23
+ "dependencies": {
24
+ "@dshtrading/api": "^0.5.0"
25
+ },
26
+ "peerDependencies": {
27
+ "@deepseek-ai/cordis": ">=4.0.0",
28
+ "@deepseek-ai/dsh-tools": ">=0.2.0-rc.2",
29
+ "@deepseek-ai/schemastery": ">=3.18.0"
30
+ },
31
+ "devDependencies": {
32
+ "tsdown": "^0.22.0",
33
+ "vitest": "^3.0.0"
34
+ },
35
+ "scripts": {
36
+ "build": "tsdown",
37
+ "test": "vitest run"
38
+ }
39
+ }