@dshtrading/connector-qmt 0.1.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,34 @@
1
+ # @dshtrading/connector-template
2
+
3
+ **本包是脚手架源,不是可安装的连接器**:不入任何 bundle 依赖,仅在 `pnpm -r build/test`
4
+ 基线内保证可编译、冒烟测试绿。真实接入用生成器:
5
+
6
+ ```sh
7
+ node scripts/new-connector.mjs --slug bybit --title Bybit --market crypto
8
+ ```
9
+
10
+ 生成后按 [docs/connector-playbook.md](../../docs/connector-playbook.md) 的填写顺序
11
+ (src/rest.ts 头部清单 7 项)实现 TODO。每个 TODO 的参照段都在 connector-okx
12
+ (packages/connector-okx/),它是本仓第一个真实 TradeService 连接器。
13
+
14
+ ## 结构
15
+
16
+ - `src/rest.ts` —— 错误载体(TradingServiceError)+ 通用请求管线(超时/错误映射/
17
+ 模拟盘头/注入 fetch)直接可用;签名与端点 TODO。
18
+ - `src/index.ts` —— Config(enabled/env/dryRun/liveTrading + 三 ref 凭证组)、
19
+ 闸门三态判定、凭证解析(BYOK + 环境变量回落)、MarketDataService/TradeService 骨架、
20
+ 7 个市场前缀工具注册(duplicate-safe)、apply(enabled=false 静默退出)。
21
+ - `test/template.test.ts` —— 结构冒烟 7 用例。
22
+
23
+ ## Token
24
+
25
+ `qmt`(slug)/ `QMT`(title)/ `QMT`(ref 前缀)/
26
+ `crypto`(工具前缀)/ `Crypto`(服务键 infix)。token 未展开也可编译;
27
+ 生成器保证全部替换。
28
+
29
+ ## 注意(勿改的坑)
30
+
31
+ - 服务类用 TS 编译期 `private`(禁 ECMAScript `#`,realm 代理会炸)。
32
+ - 工具名 = 市场前缀 + 语义词(不带交易所名)——base 闸门正则只认市场前缀。
33
+ - 行 id = `dsh-trading-<market>-connector-<slug>`,全仓唯一(insert-only 铁律 #1)。
34
+ - 凭证只进 ref,绝不内置/落日志(铁律 #3/#5)。
@@ -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: Config): void;
6
+ //#endregion
7
+ export { apply, inject };
@@ -0,0 +1,42 @@
1
+ import { QmtMarketDataService, QmtTradeService, TRADING_CN_MARKET_DATA_KEY, TRADING_CN_TRADE_KEY } from "./index.js";
2
+ //#region src/dataplane.ts
3
+ const inject = [];
4
+ function resolveMarketDataRegistry(ctx) {
5
+ const candidate = ctx.get?.("tradingMarketDataRegistry", false);
6
+ return candidate !== void 0 ? candidate : void 0;
7
+ }
8
+ function resolveTradeRegistry(ctx) {
9
+ const candidate = ctx.get?.("tradingTradeRegistry", false);
10
+ return candidate !== void 0 ? candidate : void 0;
11
+ }
12
+ const ROUTER_PROVIDER = "qmt";
13
+ const MARKET = "cn";
14
+ function apply(ctx, config) {
15
+ if (!config.enabled) return;
16
+ const registry = resolveMarketDataRegistry(ctx);
17
+ if (registry === void 0) {
18
+ new QmtMarketDataService(ctx, {
19
+ gatewayUrl: config.gatewayUrl,
20
+ accountId: config.accountId
21
+ });
22
+ return;
23
+ }
24
+ const inner = ctx.isolate(TRADING_CN_MARKET_DATA_KEY);
25
+ const service = new QmtMarketDataService(inner, {
26
+ gatewayUrl: config.gatewayUrl,
27
+ accountId: config.accountId
28
+ });
29
+ ctx.effect(() => registry.register(MARKET, ROUTER_PROVIDER, service));
30
+ const tradeRegistry = resolveTradeRegistry(ctx);
31
+ if (tradeRegistry !== void 0) {
32
+ const tradeInner = ctx.isolate(TRADING_CN_TRADE_KEY);
33
+ const trade = new QmtTradeService(tradeInner, {
34
+ gatewayUrl: config.gatewayUrl,
35
+ accountId: config.accountId,
36
+ config
37
+ });
38
+ ctx.effect(() => tradeRegistry.register(MARKET, ROUTER_PROVIDER, trade));
39
+ }
40
+ }
41
+ //#endregion
42
+ export { apply, inject };
package/lib/index.d.ts ADDED
@@ -0,0 +1,47 @@
1
+ import { AccountBalance, INTERVAL_VOCABULARY, Interval, Kline, Order, Position, QmtRestClient, QmtRestOptions, Ticker, TradingServiceError, toQmtCode } from "./rest.js";
2
+ import { Context, Service } from "@deepseek-ai/cordis";
3
+ import Schema from "@deepseek-ai/schemastery";
4
+ import { AccountBalance as AccountBalance$1, Disposable, Interval as Interval$1, Kline as Kline$1, MarketDataService, Order as Order$1, OrderRequest, Position as Position$1, Ticker as Ticker$1, TradeFill, TradeService } from "@dshtrading/api";
5
+ //#region src/index.d.ts
6
+ declare const name = "dsh-trading-cn-connector-qmt";
7
+ interface Config {
8
+ enabled: boolean;
9
+ env: 'demo' | 'live';
10
+ dryRun: boolean;
11
+ liveTrading: boolean;
12
+ gatewayUrl?: string;
13
+ accountId?: string;
14
+ }
15
+ declare const Config: Schema<Config>;
16
+ declare const TRADING_CN_MARKET_DATA_KEY = "tradingCnMarketData";
17
+ declare const TRADING_CN_TRADE_KEY = "tradingCnTrade";
18
+ declare class QmtMarketDataService extends Service implements MarketDataService {
19
+ private readonly client;
20
+ constructor(ctx: Context, options?: QmtRestOptions, serviceName?: string);
21
+ getTicker(symbol: string): Promise<Ticker$1>;
22
+ getKlines(symbol: string, interval?: Interval$1, limit?: number): Promise<Kline$1[]>;
23
+ subscribeTicker(symbol: string, cb: (ticker: Ticker$1) => void, options?: {
24
+ intervalMs?: number;
25
+ }): Disposable;
26
+ }
27
+ declare class QmtTradeService extends Service implements TradeService {
28
+ private readonly client;
29
+ /** 插件配置(服务缝闸门 P0:dryRun 强制模拟 / liveTrading 总闸门)。 */
30
+ private readonly config;
31
+ constructor(ctx: Context, options: QmtRestOptions & {
32
+ config: Config;
33
+ }, serviceName?: string);
34
+ getBalance(): Promise<AccountBalance$1>;
35
+ placeOrder(order: OrderRequest): Promise<Order$1>;
36
+ cancelOrder(orderId: string, _symbol?: string): Promise<void>;
37
+ getPositions(): Promise<Position$1[]>;
38
+ getBalances(): Promise<AccountBalance$1[]>;
39
+ listOpenOrders(_symbol?: string): Promise<Order$1[]>;
40
+ listTradeFills(_symbol?: string, _limit?: number): Promise<TradeFill[]>;
41
+ getOrder(symbol: string, id: string): Promise<Order$1>;
42
+ }
43
+ declare const ROUTER_PROVIDER = "qmt";
44
+ declare function routeAllows(ctx: Context, config: Config, market: string): boolean;
45
+ declare function apply(ctx: Context, config: Config): void;
46
+ //#endregion
47
+ export { type AccountBalance, Config, INTERVAL_VOCABULARY, type Interval, type Kline, type Order, type Position, QmtMarketDataService, QmtRestClient, QmtRestOptions, QmtTradeService, ROUTER_PROVIDER, TRADING_CN_MARKET_DATA_KEY, TRADING_CN_TRADE_KEY, type Ticker, TradingServiceError, apply, name, routeAllows, toQmtCode };
package/lib/index.js ADDED
@@ -0,0 +1,294 @@
1
+ import { INTERVAL_VOCABULARY, QmtRestClient, TradingServiceError, toQmtCode as toQmtCode$1 } 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
+ const name = "dsh-trading-cn-connector-qmt";
7
+ const Config = Schema.object({
8
+ enabled: Schema.boolean().default(true).description("是否激活 QMT 连接器"),
9
+ env: Schema.union(["demo", "live"]).default("demo").description("运行环境"),
10
+ dryRun: Schema.boolean().default(true).description("默认模拟下单"),
11
+ liveTrading: Schema.boolean().default(false).description("是否允许实盘交易"),
12
+ gatewayUrl: Schema.string().default("http://127.0.0.1:5800").description("MiniQMT 本地网关地址"),
13
+ accountId: Schema.string().description("资金账号")
14
+ });
15
+ const TRADING_CN_MARKET_DATA_KEY = "tradingCnMarketData";
16
+ const TRADING_CN_TRADE_KEY = "tradingCnTrade";
17
+ var QmtMarketDataService = class extends Service {
18
+ client;
19
+ constructor(ctx, options = {}, serviceName = TRADING_CN_MARKET_DATA_KEY) {
20
+ super(ctx, serviceName);
21
+ this.client = new QmtRestClient(options);
22
+ }
23
+ async getTicker(symbol) {
24
+ return this.client.getTicker(symbol);
25
+ }
26
+ async getKlines(symbol, interval = "1d", limit = 100) {
27
+ return this.client.getKlines(symbol, interval, limit);
28
+ }
29
+ subscribeTicker(symbol, cb, options) {
30
+ const ms = Math.max(options?.intervalMs ?? 5e3, 1e3);
31
+ const tick = () => {
32
+ this.getTicker(symbol).then(cb, () => {});
33
+ };
34
+ tick();
35
+ const timer = setInterval(tick, ms);
36
+ return { dispose: () => clearInterval(timer) };
37
+ }
38
+ };
39
+ var QmtTradeService = class extends Service {
40
+ client;
41
+ /** 插件配置(服务缝闸门 P0:dryRun 强制模拟 / liveTrading 总闸门)。 */
42
+ config;
43
+ constructor(ctx, options, serviceName = TRADING_CN_TRADE_KEY) {
44
+ super(ctx, serviceName);
45
+ this.client = new QmtRestClient(options);
46
+ this.config = options.config;
47
+ }
48
+ async getBalance() {
49
+ return this.client.getBalance();
50
+ }
51
+ async placeOrder(order) {
52
+ const requestedDryRun = order.dryRun ?? true;
53
+ if (!requestedDryRun && !this.config.liveTrading) throw new TradingServiceError("TRADING_LIVE_TRADING_DISABLED", `QMT TradeService.placeOrder rejected: the request asks for real execution (dryRun=${String(order.dryRun)}) but liveTrading=false — enable liveTrading explicitly or keep dryRun=true for a simulated fill.`);
54
+ if (requestedDryRun || this.config.dryRun) return {
55
+ id: `dry-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
56
+ symbol: order.symbol,
57
+ side: order.side,
58
+ type: order.type,
59
+ status: "filled",
60
+ ...order.price !== void 0 ? { price: order.price } : {},
61
+ quantity: order.quantity,
62
+ dryRun: true,
63
+ timestamp: Date.now()
64
+ };
65
+ return this.client.placeOrder(void 0, order);
66
+ }
67
+ async cancelOrder(orderId, _symbol) {
68
+ if (!this.config.liveTrading || this.config.dryRun) throw new TradingServiceError("TRADING_LIVE_TRADING_DISABLED", "QMT TradeService.cancelOrder rejected at the service seam: cancel is a live action and requires liveTrading=true with dryRun=false.");
69
+ return this.client.cancelOrder(void 0, orderId);
70
+ }
71
+ async getPositions() {
72
+ return this.client.getPositions();
73
+ }
74
+ async getBalances() {
75
+ try {
76
+ return [await this.client.getBalance()];
77
+ } catch {
78
+ return [];
79
+ }
80
+ }
81
+ async listOpenOrders(_symbol) {
82
+ return [];
83
+ }
84
+ async listTradeFills(_symbol, _limit) {
85
+ return [];
86
+ }
87
+ async getOrder(symbol, id) {
88
+ return {
89
+ id,
90
+ symbol,
91
+ side: "buy",
92
+ type: "limit",
93
+ status: "new",
94
+ quantity: 0,
95
+ dryRun: false,
96
+ timestamp: Date.now()
97
+ };
98
+ }
99
+ };
100
+ const ROUTER_PROVIDER = "qmt";
101
+ function routeAllows(ctx, config, market) {
102
+ if (!config.enabled) return false;
103
+ const router = ctx.get?.("tradingMarketRouter", false);
104
+ if (router === void 0) return true;
105
+ return router.activeProvider(market) === "qmt";
106
+ }
107
+ function apply(ctx, config) {
108
+ if (!config.enabled) return;
109
+ if (!routeAllows(ctx, config, "cn")) return;
110
+ const marketData = new QmtMarketDataService(ctx, {
111
+ gatewayUrl: config.gatewayUrl,
112
+ accountId: config.accountId
113
+ });
114
+ const trade = new QmtTradeService(ctx, {
115
+ gatewayUrl: config.gatewayUrl,
116
+ accountId: config.accountId,
117
+ config
118
+ });
119
+ ctx.inject(["tools"], (ctx) => {
120
+ const tools = ctx.tools;
121
+ const register = (t) => {
122
+ if (tools.get(t.name) === void 0) tools.register(t);
123
+ };
124
+ register(defineTool({
125
+ name: "cn_get_ticker",
126
+ description: "Get the latest trade price and quote for an A-share stock via MiniQMT.",
127
+ parameters: { symbol: {
128
+ type: "string",
129
+ required: true,
130
+ description: "A-share stock symbol, e.g. 600519.SH"
131
+ } },
132
+ output: {
133
+ schema: { type: "string" },
134
+ render: (_a, v) => [{
135
+ type: "text",
136
+ text: v
137
+ }]
138
+ },
139
+ async execute(args) {
140
+ return JSON.stringify(await marketData.getTicker(args.symbol));
141
+ }
142
+ }));
143
+ register(defineTool({
144
+ name: "cn_get_klines",
145
+ description: "Get recent public klines for an A-share stock via MiniQMT.",
146
+ parameters: {
147
+ symbol: {
148
+ type: "string",
149
+ required: true,
150
+ description: "A-share stock symbol, e.g. 600519.SH"
151
+ },
152
+ interval: {
153
+ type: "string",
154
+ enum: INTERVAL_VOCABULARY,
155
+ default: "1d",
156
+ description: "Interval"
157
+ },
158
+ limit: {
159
+ type: "integer",
160
+ default: 100,
161
+ description: "Limit"
162
+ }
163
+ },
164
+ output: {
165
+ schema: { type: "string" },
166
+ render: (_a, v) => [{
167
+ type: "text",
168
+ text: v
169
+ }]
170
+ },
171
+ async execute(args) {
172
+ const klines = await marketData.getKlines(args.symbol, args.interval ?? "1d", args.limit);
173
+ return JSON.stringify(klines);
174
+ }
175
+ }));
176
+ register(defineTool({
177
+ name: "cn_place_order",
178
+ description: "Place or simulate an A-share order via MiniQMT gateway.",
179
+ parameters: {
180
+ symbol: {
181
+ type: "string",
182
+ required: true,
183
+ description: "A-share symbol, e.g. 600519.SH"
184
+ },
185
+ side: {
186
+ type: "string",
187
+ enum: ["buy", "sell"],
188
+ required: true,
189
+ description: "Side"
190
+ },
191
+ type: {
192
+ type: "string",
193
+ enum: ["market", "limit"],
194
+ required: true,
195
+ description: "Type"
196
+ },
197
+ quantity: {
198
+ type: "number",
199
+ required: true,
200
+ description: "Quantity (shares, e.g. 100)"
201
+ },
202
+ price: {
203
+ type: "number",
204
+ description: "Limit price"
205
+ },
206
+ dryRun: {
207
+ type: "boolean",
208
+ default: true,
209
+ description: "Dry run"
210
+ }
211
+ },
212
+ output: {
213
+ schema: { type: "string" },
214
+ render: (_a, v) => [{
215
+ type: "text",
216
+ text: v
217
+ }]
218
+ },
219
+ async execute(args) {
220
+ if (args.dryRun !== false) {
221
+ let refPrice = args.price;
222
+ if (!refPrice || refPrice <= 0) try {
223
+ refPrice = (await marketData.getTicker(args.symbol)).price;
224
+ } catch {
225
+ refPrice = 0;
226
+ }
227
+ return JSON.stringify({
228
+ id: `sim-qmt-${Date.now()}`,
229
+ symbol: toQmtCode(args.symbol),
230
+ side: args.side,
231
+ type: args.type,
232
+ status: "filled",
233
+ quantity: args.quantity,
234
+ price: refPrice ?? 0,
235
+ dryRun: true,
236
+ timestamp: Date.now()
237
+ });
238
+ }
239
+ if (!config.liveTrading) return JSON.stringify({
240
+ status: "rejected",
241
+ code: "TRADING_LIVE_TRADING_DISABLED",
242
+ message: "Live trading is disabled on QMT plugin."
243
+ });
244
+ const order = await trade.placeOrder({
245
+ symbol: args.symbol,
246
+ side: args.side,
247
+ type: args.type,
248
+ quantity: args.quantity,
249
+ price: args.price,
250
+ dryRun: false
251
+ });
252
+ return JSON.stringify(order);
253
+ }
254
+ }));
255
+ register(defineTool({
256
+ name: "cn_cancel_order",
257
+ description: "Cancel an A-share order on QMT by order ID.",
258
+ parameters: { ordId: {
259
+ type: "string",
260
+ required: true,
261
+ description: "Order ID"
262
+ } },
263
+ output: {
264
+ schema: { type: "string" },
265
+ render: (_a, v) => [{
266
+ type: "text",
267
+ text: v
268
+ }]
269
+ },
270
+ async execute(args) {
271
+ const res = await trade.cancelOrder(args.ordId);
272
+ return JSON.stringify(res);
273
+ }
274
+ }));
275
+ register(defineTool({
276
+ name: "cn_get_balance",
277
+ description: "Get A-share account balance via QMT.",
278
+ parameters: {},
279
+ output: {
280
+ schema: { type: "string" },
281
+ render: (_a, v) => [{
282
+ type: "text",
283
+ text: v
284
+ }]
285
+ },
286
+ async execute() {
287
+ const bal = await trade.getBalance();
288
+ return JSON.stringify(bal);
289
+ }
290
+ }));
291
+ });
292
+ }
293
+ //#endregion
294
+ export { Config, INTERVAL_VOCABULARY, QmtMarketDataService, QmtRestClient, QmtTradeService, ROUTER_PROVIDER, TRADING_CN_MARKET_DATA_KEY, TRADING_CN_TRADE_KEY, TradingServiceError, apply, name, routeAllows, toQmtCode$1 as toQmtCode };
package/lib/rest.d.ts ADDED
@@ -0,0 +1,35 @@
1
+ import { AccountBalance as AccountBalance$1, Interval as Interval$1, Kline as Kline$1, Order as Order$1, OrderRequest, Position as Position$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
+ declare const INTERVAL_VOCABULARY: readonly ["1m", "5m", "15m", "30m", "1h", "1d", "1w", "1M"];
8
+ declare function toQmtCode(symbol: string): string;
9
+ interface QmtRestOptions {
10
+ gatewayUrl?: string;
11
+ accountId?: string;
12
+ fetchImpl?: typeof fetch;
13
+ }
14
+ declare class QmtRestClient {
15
+ readonly gatewayUrl: string;
16
+ readonly accountId?: string;
17
+ private readonly fetchImpl;
18
+ constructor(options?: QmtRestOptions);
19
+ private requestJson;
20
+ getTicker(symbol: string): Promise<Ticker$1>;
21
+ getKlines(symbol: string, interval?: Interval$1, limit?: number): Promise<Kline$1[]>;
22
+ getBalance(accountId?: string): Promise<AccountBalance$1>;
23
+ getPositions(accountId?: string): Promise<Position$1[]>;
24
+ placeOrder(creds: {
25
+ accountId?: string;
26
+ } | undefined, req: OrderRequest): Promise<Order$1>;
27
+ cancelOrder(creds: {
28
+ accountId?: string;
29
+ } | undefined, orderId: string): Promise<{
30
+ orderId: string;
31
+ status: 'canceled';
32
+ }>;
33
+ }
34
+ //#endregion
35
+ export { type AccountBalance$1 as AccountBalance, INTERVAL_VOCABULARY, type Interval$1 as Interval, type Kline$1 as Kline, type Order$1 as Order, type Position$1 as Position, QmtRestClient, QmtRestOptions, type Ticker$1 as Ticker, TradingServiceError, toQmtCode };
package/lib/rest.js ADDED
@@ -0,0 +1,181 @@
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
+ const INTERVAL_VOCABULARY = [
12
+ "1m",
13
+ "5m",
14
+ "15m",
15
+ "30m",
16
+ "1h",
17
+ "1d",
18
+ "1w",
19
+ "1M"
20
+ ];
21
+ function toQmtCode(symbol) {
22
+ const clean = symbol.trim().toUpperCase();
23
+ if (clean.includes(".")) return clean;
24
+ if (clean.startsWith("6") || clean.startsWith("5")) return `${clean}.SH`;
25
+ if (clean.startsWith("0") || clean.startsWith("3")) return `${clean}.SZ`;
26
+ if (clean.startsWith("8") || clean.startsWith("4")) return `${clean}.BJ`;
27
+ return `${clean}.SH`;
28
+ }
29
+ var QmtRestClient = class {
30
+ gatewayUrl;
31
+ accountId;
32
+ fetchImpl;
33
+ constructor(options = {}) {
34
+ this.gatewayUrl = options.gatewayUrl ?? (process.env.QMT_GATEWAY_URL || "http://127.0.0.1:5800");
35
+ this.accountId = options.accountId ?? process.env.QMT_ACCOUNT_ID;
36
+ this.fetchImpl = options.fetchImpl ?? globalThis.fetch;
37
+ }
38
+ async requestJson(path, options = {}) {
39
+ const url = `${this.gatewayUrl}${path}`;
40
+ try {
41
+ const res = await this.fetchImpl(url, {
42
+ ...options,
43
+ headers: {
44
+ "Content-Type": "application/json",
45
+ ...options.headers
46
+ }
47
+ });
48
+ if (!res.ok) throw new TradingServiceError("TRADING_UPSTREAM_ERROR", `QMT HTTP ${res.status}: ${res.statusText}`);
49
+ return await res.json();
50
+ } catch (err) {
51
+ if (err instanceof TradingServiceError) throw err;
52
+ throw new TradingServiceError("TRADING_NETWORK", `QMT network error: ${err instanceof Error ? err.message : String(err)}`, err);
53
+ }
54
+ }
55
+ async getTicker(symbol) {
56
+ const qmtCode = toQmtCode(symbol);
57
+ try {
58
+ const data = await this.requestJson(`/api/v1/market/ticker?symbol=${encodeURIComponent(qmtCode)}`);
59
+ if (data.code === 0 && data.data) return {
60
+ symbol: qmtCode,
61
+ price: data.data.lastPrice,
62
+ volume: data.data.volume,
63
+ timestamp: data.data.timestamp ?? Date.now()
64
+ };
65
+ } catch {
66
+ const secid = qmtCode.startsWith("6") || qmtCode.startsWith("5") ? `1.${qmtCode.split(".")[0]}` : `0.${qmtCode.split(".")[0]}`;
67
+ const d = await (await this.fetchImpl(`https://push2.eastmoney.com/api/qt/stock/get?secid=${secid}&fields=f43,f47,f86`)).json();
68
+ let rawPrice = 0;
69
+ if (typeof d.data?.f43 === "number") rawPrice = d.data.f43 / 100;
70
+ else if (typeof d.data?.f43 === "string" && d.data.f43 !== "-" && d.data.f43 !== "−") {
71
+ const parsed = parseFloat(d.data.f43);
72
+ rawPrice = Number.isNaN(parsed) ? 0 : parsed / 100;
73
+ }
74
+ return {
75
+ symbol: qmtCode,
76
+ price: rawPrice > 0 ? rawPrice : 0,
77
+ volume: d.data?.f47 ?? 0,
78
+ timestamp: d.data?.f86 ? d.data.f86 * 1e3 : Date.now()
79
+ };
80
+ }
81
+ return {
82
+ symbol: qmtCode,
83
+ price: 0,
84
+ timestamp: Date.now()
85
+ };
86
+ }
87
+ async getKlines(symbol, interval = "1d", limit = 100) {
88
+ const qmtCode = toQmtCode(symbol);
89
+ try {
90
+ const data = await this.requestJson(`/api/v1/market/klines?symbol=${encodeURIComponent(qmtCode)}&period=${interval}&limit=${limit}`);
91
+ if (data.code === 0 && Array.isArray(data.data?.klines)) return data.data.klines;
92
+ } catch {
93
+ const secid = qmtCode.startsWith("6") || qmtCode.startsWith("5") ? `1.${qmtCode.split(".")[0]}` : `0.${qmtCode.split(".")[0]}`;
94
+ const d = await (await this.fetchImpl(`https://push2his.eastmoney.com/api/qt/stock/kline/get?secid=${secid}&klt=101&fqt=1&lmt=${limit}&fields2=f51,f52,f53,f54,f55,f56`)).json();
95
+ if (!d.data?.klines) return [];
96
+ return d.data.klines.map((l) => {
97
+ const p = l.split(",");
98
+ const openTime = new Date(p[0].replace(/-/g, "/")).getTime();
99
+ return {
100
+ openTime,
101
+ open: parseFloat(p[1]),
102
+ close: parseFloat(p[2]),
103
+ high: parseFloat(p[3]),
104
+ low: parseFloat(p[4]),
105
+ volume: parseFloat(p[5]),
106
+ closeTime: openTime + 864e5 - 1
107
+ };
108
+ });
109
+ }
110
+ return [];
111
+ }
112
+ async getBalance(accountId) {
113
+ const acc = accountId ?? this.accountId;
114
+ if (!acc) throw new TradingServiceError("TRADING_AUTH_FAILED", "QMT: accountId is required to query balance");
115
+ const res = await this.requestJson(`/api/v1/trade/asset?account_id=${encodeURIComponent(acc)}`);
116
+ if (res.code !== 0 || !res.data) throw new TradingServiceError("TRADING_EXCHANGE_ERROR", `QMT getBalance failed: ${res.message ?? `code ${res.code}`}`);
117
+ return {
118
+ currency: res.data.currency ?? "CNY",
119
+ available: res.data.cash ?? 0,
120
+ total: res.data.total_asset ?? res.data.cash ?? 0
121
+ };
122
+ }
123
+ async getPositions(accountId) {
124
+ const acc = accountId ?? this.accountId;
125
+ if (!acc) throw new TradingServiceError("TRADING_AUTH_FAILED", "QMT: accountId is required to query positions");
126
+ const res = await this.requestJson(`/api/v1/trade/positions?account_id=${encodeURIComponent(acc)}`);
127
+ if (res.code !== 0 || !Array.isArray(res.data)) throw new TradingServiceError("TRADING_EXCHANGE_ERROR", `QMT getPositions failed: ${res.message ?? `code ${res.code}`}`);
128
+ return res.data.map((p) => ({
129
+ symbol: toQmtCode(p.stock_code),
130
+ quantity: p.volume,
131
+ entryPrice: p.open_price,
132
+ unrealizedPnl: 0
133
+ }));
134
+ }
135
+ async placeOrder(creds, req) {
136
+ const acc = creds?.accountId ?? this.accountId;
137
+ if (!acc) throw new TradingServiceError("TRADING_AUTH_FAILED", "QMT: accountId is required to place order");
138
+ const qmtCode = toQmtCode(req.symbol);
139
+ const res = await this.requestJson("/api/v1/trade/order", {
140
+ method: "POST",
141
+ body: JSON.stringify({
142
+ account_id: acc,
143
+ stock_code: qmtCode,
144
+ order_type: req.type,
145
+ order_side: req.side,
146
+ price: req.price ?? 0,
147
+ order_volume: req.quantity
148
+ })
149
+ });
150
+ if (res.code !== 0 || !res.data?.order_id) throw new TradingServiceError("TRADING_EXCHANGE_ERROR", `QMT placeOrder failed: ${res.message ?? `code ${res.code}`}`);
151
+ return {
152
+ id: res.data.order_id,
153
+ symbol: qmtCode,
154
+ side: req.side,
155
+ type: req.type,
156
+ status: res.data.status ?? "new",
157
+ quantity: req.quantity,
158
+ price: req.price ?? 0,
159
+ dryRun: false,
160
+ timestamp: Date.now()
161
+ };
162
+ }
163
+ async cancelOrder(creds, orderId) {
164
+ const acc = creds?.accountId ?? this.accountId;
165
+ if (!acc) throw new TradingServiceError("TRADING_AUTH_FAILED", "QMT: accountId is required to cancel order");
166
+ const res = await this.requestJson("/api/v1/trade/cancel", {
167
+ method: "POST",
168
+ body: JSON.stringify({
169
+ account_id: acc,
170
+ order_id: orderId
171
+ })
172
+ });
173
+ if (res.code !== 0) throw new TradingServiceError("TRADING_EXCHANGE_ERROR", `QMT cancelOrder failed: ${res.message ?? `code ${res.code}`}`);
174
+ return {
175
+ orderId,
176
+ status: "canceled"
177
+ };
178
+ }
179
+ };
180
+ //#endregion
181
+ export { INTERVAL_VOCABULARY, QmtRestClient, TradingServiceError, toQmtCode };
package/package.json ADDED
@@ -0,0 +1,39 @@
1
+ {
2
+ "name": "@dshtrading/connector-qmt",
3
+ "description": "【模板】交易所连接器插件脚手架:QMT(qmt)v2 插件骨架 —— 市场数据服务 + 交易服务 + 三态闸门 + BYOK 凭证 ref。生成器:node scripts/new-connector.mjs --slug <exchange>",
4
+ "version": "0.1.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.1.0"
25
+ },
26
+ "peerDependencies": {
27
+ "@deepseek-ai/cordis": ">=4.0.0",
28
+ "@deepseek-ai/dsh-tools": ">=0.1.2-alpha.1",
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
+ }