@dshtrading/connector-tiger 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
+ `tiger`(slug)/ `Tiger`(title)/ `TIGER`(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,28 @@
1
+ import { TRADING_HK_MARKET_DATA_KEY, TigerMarketDataService } 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
+ const ROUTER_PROVIDER = "tiger";
9
+ const MARKET = "hk";
10
+ function apply(ctx, config) {
11
+ if (!config.enabled) return;
12
+ const registry = resolveMarketDataRegistry(ctx);
13
+ if (registry === void 0) {
14
+ new TigerMarketDataService(ctx, {
15
+ tigerId: config.tigerId,
16
+ accountId: config.accountId
17
+ });
18
+ return;
19
+ }
20
+ const inner = ctx.isolate(TRADING_HK_MARKET_DATA_KEY);
21
+ const service = new TigerMarketDataService(inner, {
22
+ tigerId: config.tigerId,
23
+ accountId: config.accountId
24
+ });
25
+ ctx.effect(() => registry.register(MARKET, ROUTER_PROVIDER, service));
26
+ }
27
+ //#endregion
28
+ export { apply, inject };
package/lib/index.d.ts ADDED
@@ -0,0 +1,48 @@
1
+ import { AccountBalance, INTERVAL_VOCABULARY, Interval, Kline, Order, Position, Ticker, TigerRestClient, TigerRestOptions, TradingServiceError, generateTigerSignature, toTigerSymbol } 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, TradeService } from "@dshtrading/api";
5
+ //#region src/index.d.ts
6
+ declare const name = "dsh-trading-hk-connector-tiger";
7
+ interface Config {
8
+ enabled: boolean;
9
+ env: 'demo' | 'live';
10
+ dryRun: boolean;
11
+ liveTrading: boolean;
12
+ tigerId?: string;
13
+ privateKeyRef?: string;
14
+ accountId?: string;
15
+ }
16
+ declare const Config: Schema<Config>;
17
+ declare const TRADING_HK_MARKET_DATA_KEY = "tradingHkMarketData";
18
+ declare const TRADING_HK_TRADE_KEY = "tradingHkTrade";
19
+ declare class TigerMarketDataService extends Service implements MarketDataService {
20
+ private readonly client;
21
+ constructor(ctx: Context, options?: TigerRestOptions, serviceName?: string);
22
+ getTicker(symbol: string): Promise<Ticker$1>;
23
+ getKlines(symbol: string, interval?: Interval$1, limit?: number): Promise<Kline$1[]>;
24
+ subscribeTicker(symbol: string, cb: (ticker: Ticker$1) => void, options?: {
25
+ intervalMs?: number;
26
+ }): Disposable;
27
+ }
28
+ declare class TigerTradeService extends Service implements TradeService {
29
+ private readonly client;
30
+ /** 插件配置(服务缝闸门 P0:dryRun 强制模拟 / liveTrading 总闸门)。 */
31
+ private readonly config;
32
+ constructor(ctx: Context, options: TigerRestOptions & {
33
+ config: Config;
34
+ }, serviceName?: string);
35
+ getBalance(): Promise<AccountBalance$1>;
36
+ placeOrder(order: OrderRequest): Promise<Order$1>;
37
+ cancelOrder(orderId: string): Promise<{
38
+ orderId: string;
39
+ status: 'canceled';
40
+ }>;
41
+ getPositions(): Promise<Position$1[]>;
42
+ getOrders(): Promise<Order$1[]>;
43
+ }
44
+ declare const ROUTER_PROVIDER = "tiger";
45
+ declare function routeAllows(ctx: Context, config: Config, market: string): boolean;
46
+ declare function apply(ctx: Context, config: Config): void;
47
+ //#endregion
48
+ export { type AccountBalance, Config, INTERVAL_VOCABULARY, type Interval, type Kline, type Order, type Position, ROUTER_PROVIDER, TRADING_HK_MARKET_DATA_KEY, TRADING_HK_TRADE_KEY, type Ticker, TigerMarketDataService, TigerRestClient, TigerRestOptions, TigerTradeService, TradingServiceError, apply, generateTigerSignature, name, routeAllows, toTigerSymbol };
package/lib/index.js ADDED
@@ -0,0 +1,276 @@
1
+ import { INTERVAL_VOCABULARY, TigerRestClient, TradingServiceError, generateTigerSignature, toTigerSymbol as toTigerSymbol$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-hk-connector-tiger";
7
+ const Config = Schema.object({
8
+ enabled: Schema.boolean().default(true).description("是否激活 Tiger 连接器"),
9
+ env: Schema.union(["demo", "live"]).default("demo").description("运行环境"),
10
+ dryRun: Schema.boolean().default(true).description("默认模拟下单"),
11
+ liveTrading: Schema.boolean().default(false).description("是否允许实盘交易"),
12
+ tigerId: Schema.string().description("Tiger ID"),
13
+ privateKeyRef: Schema.string().default("TIGER_PRIVATE_KEY").description("Tiger RSA 私钥环境变量名 (PEM 格式)"),
14
+ accountId: Schema.string().description("Tiger 账户 ID")
15
+ });
16
+ const TRADING_HK_MARKET_DATA_KEY = "tradingHkMarketData";
17
+ const TRADING_HK_TRADE_KEY = "tradingHkTrade";
18
+ var TigerMarketDataService = class extends Service {
19
+ client;
20
+ constructor(ctx, options = {}, serviceName = TRADING_HK_MARKET_DATA_KEY) {
21
+ super(ctx, serviceName);
22
+ this.client = new TigerRestClient(options);
23
+ }
24
+ async getTicker(symbol) {
25
+ return this.client.getTicker(symbol);
26
+ }
27
+ async getKlines(symbol, interval = "1d", limit = 100) {
28
+ return this.client.getKlines(symbol, interval, limit);
29
+ }
30
+ subscribeTicker(symbol, cb, options) {
31
+ const ms = Math.max(options?.intervalMs ?? 5e3, 1e3);
32
+ const tick = () => {
33
+ this.getTicker(symbol).then(cb, () => {});
34
+ };
35
+ tick();
36
+ const timer = setInterval(tick, ms);
37
+ return { dispose: () => clearInterval(timer) };
38
+ }
39
+ };
40
+ var TigerTradeService = class extends Service {
41
+ client;
42
+ /** 插件配置(服务缝闸门 P0:dryRun 强制模拟 / liveTrading 总闸门)。 */
43
+ config;
44
+ constructor(ctx, options, serviceName = TRADING_HK_TRADE_KEY) {
45
+ super(ctx, serviceName);
46
+ this.client = new TigerRestClient(options);
47
+ this.config = options.config;
48
+ }
49
+ async getBalance() {
50
+ return this.client.getBalance();
51
+ }
52
+ async placeOrder(order) {
53
+ const requestedDryRun = order.dryRun ?? true;
54
+ if (!requestedDryRun && !this.config.liveTrading) throw new TradingServiceError("TRADING_LIVE_TRADING_DISABLED", `Tiger 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.`);
55
+ if (requestedDryRun || this.config.dryRun) return {
56
+ id: `dry-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
57
+ symbol: order.symbol,
58
+ side: order.side,
59
+ type: order.type,
60
+ status: "filled",
61
+ ...order.price !== void 0 ? { price: order.price } : {},
62
+ quantity: order.quantity,
63
+ dryRun: true,
64
+ timestamp: Date.now()
65
+ };
66
+ return this.client.placeOrder(void 0, order);
67
+ }
68
+ async cancelOrder(orderId) {
69
+ if (!this.config.liveTrading || this.config.dryRun) throw new TradingServiceError("TRADING_LIVE_TRADING_DISABLED", "Tiger TradeService.cancelOrder rejected at the service seam: cancel is a live action and requires liveTrading=true with dryRun=false.");
70
+ return this.client.cancelOrder(void 0, orderId);
71
+ }
72
+ async getPositions() {
73
+ return this.client.getPositions();
74
+ }
75
+ async getOrders() {
76
+ return [];
77
+ }
78
+ };
79
+ const ROUTER_PROVIDER = "tiger";
80
+ function routeAllows(ctx, config, market) {
81
+ if (!config.enabled) return false;
82
+ const router = ctx.get?.("tradingMarketRouter", false);
83
+ if (router === void 0) return true;
84
+ return router.activeProvider(market) === ROUTER_PROVIDER;
85
+ }
86
+ function apply(ctx, config) {
87
+ if (!config.enabled) return;
88
+ if (!routeAllows(ctx, config, "hk")) return;
89
+ const privateKey = config.privateKeyRef ? process.env[config.privateKeyRef] : void 0;
90
+ const marketData = new TigerMarketDataService(ctx, {
91
+ tigerId: config.tigerId,
92
+ accountId: config.accountId,
93
+ privateKey
94
+ });
95
+ const trade = new TigerTradeService(ctx, {
96
+ tigerId: config.tigerId,
97
+ accountId: config.accountId,
98
+ privateKey,
99
+ config
100
+ });
101
+ ctx.inject(["tools"], (ctx) => {
102
+ const tools = ctx.tools;
103
+ const register = (t) => {
104
+ if (tools.get(t.name) === void 0) tools.register(t);
105
+ };
106
+ register(defineTool({
107
+ name: "hk_get_ticker",
108
+ description: "Get the latest trade price and quote for a HK/US stock via Tiger.",
109
+ parameters: { symbol: {
110
+ type: "string",
111
+ required: true,
112
+ description: "Stock symbol, e.g. 00700.HK"
113
+ } },
114
+ output: {
115
+ schema: { type: "string" },
116
+ render: (_a, v) => [{
117
+ type: "text",
118
+ text: v
119
+ }]
120
+ },
121
+ async execute(args) {
122
+ return JSON.stringify(await marketData.getTicker(args.symbol));
123
+ }
124
+ }));
125
+ register(defineTool({
126
+ name: "hk_get_klines",
127
+ description: "Get recent public klines for a HK/US stock via Tiger.",
128
+ parameters: {
129
+ symbol: {
130
+ type: "string",
131
+ required: true,
132
+ description: "Stock symbol, e.g. 00700.HK"
133
+ },
134
+ interval: {
135
+ type: "string",
136
+ enum: INTERVAL_VOCABULARY,
137
+ default: "1d",
138
+ description: "Interval"
139
+ },
140
+ limit: {
141
+ type: "integer",
142
+ default: 100,
143
+ description: "Limit"
144
+ }
145
+ },
146
+ output: {
147
+ schema: { type: "string" },
148
+ render: (_a, v) => [{
149
+ type: "text",
150
+ text: v
151
+ }]
152
+ },
153
+ async execute(args) {
154
+ const klines = await marketData.getKlines(args.symbol, args.interval ?? "1d", args.limit);
155
+ return JSON.stringify(klines);
156
+ }
157
+ }));
158
+ register(defineTool({
159
+ name: "hk_place_order",
160
+ description: "Place or simulate a HK/US stock order via Tiger Trade.",
161
+ parameters: {
162
+ symbol: {
163
+ type: "string",
164
+ required: true,
165
+ description: "Symbol, e.g. 00700.HK"
166
+ },
167
+ side: {
168
+ type: "string",
169
+ enum: ["buy", "sell"],
170
+ required: true,
171
+ description: "Side"
172
+ },
173
+ type: {
174
+ type: "string",
175
+ enum: ["market", "limit"],
176
+ required: true,
177
+ description: "Type"
178
+ },
179
+ quantity: {
180
+ type: "number",
181
+ required: true,
182
+ description: "Quantity (shares)"
183
+ },
184
+ price: {
185
+ type: "number",
186
+ description: "Limit price"
187
+ },
188
+ dryRun: {
189
+ type: "boolean",
190
+ default: true,
191
+ description: "Dry run"
192
+ }
193
+ },
194
+ output: {
195
+ schema: { type: "string" },
196
+ render: (_a, v) => [{
197
+ type: "text",
198
+ text: v
199
+ }]
200
+ },
201
+ async execute(args) {
202
+ if (args.dryRun !== false) {
203
+ let refPrice = args.price;
204
+ if (!refPrice || refPrice <= 0) try {
205
+ refPrice = (await marketData.getTicker(args.symbol)).price;
206
+ } catch {
207
+ refPrice = 0;
208
+ }
209
+ return JSON.stringify({
210
+ id: `sim-tiger-${Date.now()}`,
211
+ symbol: toTigerSymbol(args.symbol).canonical,
212
+ side: args.side,
213
+ type: args.type,
214
+ status: "filled",
215
+ quantity: args.quantity,
216
+ price: refPrice ?? 0,
217
+ dryRun: true,
218
+ timestamp: Date.now()
219
+ });
220
+ }
221
+ if (!config.liveTrading) return JSON.stringify({
222
+ status: "rejected",
223
+ code: "TRADING_LIVE_TRADING_DISABLED",
224
+ message: "Live trading is disabled on Tiger plugin."
225
+ });
226
+ const order = await trade.placeOrder({
227
+ symbol: args.symbol,
228
+ side: args.side,
229
+ type: args.type,
230
+ quantity: args.quantity,
231
+ price: args.price,
232
+ dryRun: false
233
+ });
234
+ return JSON.stringify(order);
235
+ }
236
+ }));
237
+ register(defineTool({
238
+ name: "hk_cancel_order",
239
+ description: "Cancel a HK order on Tiger by order ID.",
240
+ parameters: { ordId: {
241
+ type: "string",
242
+ required: true,
243
+ description: "Order ID"
244
+ } },
245
+ output: {
246
+ schema: { type: "string" },
247
+ render: (_a, v) => [{
248
+ type: "text",
249
+ text: v
250
+ }]
251
+ },
252
+ async execute(args) {
253
+ const res = await trade.cancelOrder(args.ordId);
254
+ return JSON.stringify(res);
255
+ }
256
+ }));
257
+ register(defineTool({
258
+ name: "hk_get_balance",
259
+ description: "Get HK/US account balance via Tiger.",
260
+ parameters: {},
261
+ output: {
262
+ schema: { type: "string" },
263
+ render: (_a, v) => [{
264
+ type: "text",
265
+ text: v
266
+ }]
267
+ },
268
+ async execute() {
269
+ const bal = await trade.getBalance();
270
+ return JSON.stringify(bal);
271
+ }
272
+ }));
273
+ });
274
+ }
275
+ //#endregion
276
+ export { Config, INTERVAL_VOCABULARY, ROUTER_PROVIDER, TRADING_HK_MARKET_DATA_KEY, TRADING_HK_TRADE_KEY, TigerMarketDataService, TigerRestClient, TigerTradeService, TradingServiceError, apply, generateTigerSignature, name, routeAllows, toTigerSymbol$1 as toTigerSymbol };
package/lib/rest.d.ts ADDED
@@ -0,0 +1,40 @@
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 toTigerSymbol(raw: string): {
9
+ symbol: string;
10
+ canonical: string;
11
+ secType: 'STK';
12
+ };
13
+ declare function generateTigerSignature(params: Record<string, string>, privateKeyPem: string): string;
14
+ interface TigerRestOptions {
15
+ baseUrl?: string;
16
+ tigerId?: string;
17
+ privateKey?: string;
18
+ accountId?: string;
19
+ fetchImpl?: typeof fetch;
20
+ }
21
+ declare class TigerRestClient {
22
+ readonly baseUrl: string;
23
+ readonly tigerId?: string;
24
+ readonly privateKey?: string;
25
+ readonly accountId?: string;
26
+ private readonly fetchImpl;
27
+ constructor(options?: TigerRestOptions);
28
+ private requestJson;
29
+ getTicker(symbol: string): Promise<Ticker$1>;
30
+ getKlines(symbol: string, interval?: Interval$1, limit?: number): Promise<Kline$1[]>;
31
+ getBalance(): Promise<AccountBalance$1>;
32
+ getPositions(): Promise<Position$1[]>;
33
+ placeOrder(_creds: unknown, req: OrderRequest): Promise<Order$1>;
34
+ cancelOrder(_creds: unknown, orderId: string): Promise<{
35
+ orderId: string;
36
+ status: 'canceled';
37
+ }>;
38
+ }
39
+ //#endregion
40
+ 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, type Ticker$1 as Ticker, TigerRestClient, TigerRestOptions, TradingServiceError, generateTigerSignature, toTigerSymbol };
package/lib/rest.js ADDED
@@ -0,0 +1,213 @@
1
+ import * as crypto from "node:crypto";
2
+ //#region src/rest.ts
3
+ var TradingServiceError = class extends Error {
4
+ code;
5
+ constructor(code, message, cause) {
6
+ super(message);
7
+ this.name = "TradingServiceError";
8
+ this.code = code;
9
+ if (cause !== void 0) this.cause = cause;
10
+ }
11
+ };
12
+ const INTERVAL_VOCABULARY = [
13
+ "1m",
14
+ "5m",
15
+ "15m",
16
+ "30m",
17
+ "1h",
18
+ "1d",
19
+ "1w",
20
+ "1M"
21
+ ];
22
+ function toTigerSymbol(raw) {
23
+ const clean = raw.trim().toUpperCase();
24
+ if (!clean) throw new TradingServiceError("TRADING_INVALID_ARGUMENT", "Symbol cannot be empty");
25
+ if (clean.includes(".")) return {
26
+ symbol: clean.split(".")[0],
27
+ canonical: clean,
28
+ secType: "STK"
29
+ };
30
+ if (/^\d{5}$/.test(clean)) return {
31
+ symbol: clean,
32
+ canonical: `${clean}.HK`,
33
+ secType: "STK"
34
+ };
35
+ return {
36
+ symbol: clean,
37
+ canonical: clean,
38
+ secType: "STK"
39
+ };
40
+ }
41
+ function generateTigerSignature(params, privateKeyPem) {
42
+ const content = Object.keys(params).filter((k) => k !== "sign" && params[k] !== void 0 && params[k] !== "").sort().map((k) => `${k}=${params[k]}`).join("&");
43
+ const sign = crypto.createSign("RSA-SHA256");
44
+ sign.update(content, "utf8");
45
+ sign.end();
46
+ return sign.sign(privateKeyPem, "base64");
47
+ }
48
+ var TigerRestClient = class {
49
+ baseUrl;
50
+ tigerId;
51
+ privateKey;
52
+ accountId;
53
+ fetchImpl;
54
+ constructor(options = {}) {
55
+ this.baseUrl = options.baseUrl ?? (process.env.TIGER_API_URL || "https://openapi.itiger.com/gateway");
56
+ this.tigerId = options.tigerId ?? process.env.TIGER_ID;
57
+ this.privateKey = options.privateKey ?? process.env.TIGER_PRIVATE_KEY;
58
+ this.accountId = options.accountId ?? process.env.TIGER_ACCOUNT_ID;
59
+ this.fetchImpl = options.fetchImpl ?? globalThis.fetch;
60
+ }
61
+ async requestJson(bizContent, method) {
62
+ const rawParams = {
63
+ tiger_id: this.tigerId ?? "demo",
64
+ method,
65
+ charset: "UTF-8",
66
+ sign_type: "RSA2",
67
+ timestamp: (/* @__PURE__ */ new Date()).toISOString().replace("T", " ").slice(0, 19),
68
+ version: "1.0",
69
+ biz_content: JSON.stringify(bizContent)
70
+ };
71
+ if (this.privateKey) try {
72
+ rawParams.sign = generateTigerSignature(rawParams, this.privateKey);
73
+ } catch (err) {
74
+ throw new TradingServiceError("TRADING_AUTH_FAILED", `Tiger RSA signature generation failed: ${err instanceof Error ? err.message : String(err)}`, err);
75
+ }
76
+ try {
77
+ const res = await this.fetchImpl(this.baseUrl, {
78
+ method: "POST",
79
+ headers: { "Content-Type": "application/json" },
80
+ body: JSON.stringify(rawParams)
81
+ });
82
+ if (!res.ok) throw new TradingServiceError("TRADING_UPSTREAM_ERROR", `Tiger HTTP ${res.status}: ${res.statusText}`);
83
+ return await res.json();
84
+ } catch (err) {
85
+ if (err instanceof TradingServiceError) throw err;
86
+ throw new TradingServiceError("TRADING_NETWORK", `Tiger network error: ${err instanceof Error ? err.message : String(err)}`, err);
87
+ }
88
+ }
89
+ async getTicker(symbol) {
90
+ const { symbol: sym, canonical } = toTigerSymbol(symbol);
91
+ try {
92
+ const data = await this.requestJson({ symbols: [sym] }, "quote_real_time");
93
+ if (data.code === 0 && Array.isArray(data.data) && data.data.length > 0) {
94
+ const row = data.data[0];
95
+ return {
96
+ symbol: canonical,
97
+ price: row.latestPrice,
98
+ volume: row.volume,
99
+ timestamp: row.timestamp
100
+ };
101
+ }
102
+ } catch {
103
+ const hkCode = `hk${sym.padStart(5, "0")}`;
104
+ const parts = (await (await this.fetchImpl(`https://qt.gtimg.cn/q=${hkCode}`)).text()).split("~");
105
+ return {
106
+ symbol: canonical,
107
+ price: parseFloat(parts[3] || "0"),
108
+ timestamp: Date.now()
109
+ };
110
+ }
111
+ return {
112
+ symbol: canonical,
113
+ price: 0,
114
+ timestamp: Date.now()
115
+ };
116
+ }
117
+ async getKlines(symbol, interval = "1d", limit = 100) {
118
+ const { symbol: sym, canonical } = toTigerSymbol(symbol);
119
+ try {
120
+ const items = (await this.requestJson({
121
+ symbols: [sym],
122
+ period: interval,
123
+ limit
124
+ }, "kline_quote")).data?.[0]?.items;
125
+ if (Array.isArray(items)) return items.map((r) => ({
126
+ openTime: r.time,
127
+ open: r.open,
128
+ high: r.high,
129
+ low: r.low,
130
+ close: r.close,
131
+ volume: r.volume,
132
+ closeTime: r.time + 864e5 - 1
133
+ }));
134
+ } catch {
135
+ const hkCode = `hk${sym.padStart(5, "0")}`;
136
+ const d = await (await this.fetchImpl(`https://web.ifzq.gtimg.cn/appstock/app/hkfqkline/get?param=${hkCode},day,,,${limit},qfq`)).json();
137
+ return (d.data?.[hkCode]?.qfqday ?? d.data?.[hkCode]?.day ?? []).map((item) => {
138
+ const openTime = new Date(item[0].replace(/-/g, "/")).getTime();
139
+ return {
140
+ openTime,
141
+ open: parseFloat(item[1]),
142
+ close: parseFloat(item[2]),
143
+ high: parseFloat(item[3]),
144
+ low: parseFloat(item[4]),
145
+ volume: parseFloat(item[5]),
146
+ closeTime: openTime + 864e5 - 1
147
+ };
148
+ });
149
+ }
150
+ return [];
151
+ }
152
+ async getBalance() {
153
+ if (!this.privateKey) throw new TradingServiceError("TRADING_AUTH_FAILED", "Tiger: privateKey (RSA PEM) is required for getBalance");
154
+ const acc = this.accountId;
155
+ const res = await this.requestJson({ account: acc }, "user_asset");
156
+ if (res.code !== 0 || !res.data) throw new TradingServiceError("TRADING_EXCHANGE_ERROR", `Tiger getBalance failed: ${res.message ?? `code ${res.code}`}`);
157
+ return {
158
+ currency: res.data.currency ?? "HKD",
159
+ available: res.data.cash ?? 0,
160
+ total: res.data.netLiquidation ?? res.data.cash ?? 0
161
+ };
162
+ }
163
+ async getPositions() {
164
+ if (!this.privateKey) throw new TradingServiceError("TRADING_AUTH_FAILED", "Tiger: privateKey (RSA PEM) is required for getPositions");
165
+ const res = await this.requestJson({ account: this.accountId }, "positions");
166
+ if (res.code !== 0 || !Array.isArray(res.data)) return [];
167
+ return res.data.map((p) => ({
168
+ symbol: toTigerSymbol(p.symbol).canonical,
169
+ quantity: p.quantity,
170
+ entryPrice: p.averageCost,
171
+ unrealizedPnl: p.unrealizedPnl
172
+ }));
173
+ }
174
+ async placeOrder(_creds, req) {
175
+ if (!this.privateKey) throw new TradingServiceError("TRADING_AUTH_FAILED", "Tiger: privateKey (RSA PEM) is required for placeOrder");
176
+ const { symbol: sym, canonical } = toTigerSymbol(req.symbol);
177
+ const res = await this.requestJson({
178
+ account: this.accountId,
179
+ symbol: sym,
180
+ action: req.side.toUpperCase(),
181
+ orderType: req.type === "market" ? "MKT" : "LMT",
182
+ totalQuantity: req.quantity,
183
+ limitPrice: req.price
184
+ }, "trade_order");
185
+ if (res.code !== 0 || !res.data?.id && !res.data?.orderId) throw new TradingServiceError("TRADING_EXCHANGE_ERROR", `Tiger placeOrder failed: ${res.message ?? `code ${res.code}`}`);
186
+ const id = res.data.id ?? res.data.orderId ?? `tiger-${Date.now()}`;
187
+ return {
188
+ id: String(id),
189
+ symbol: canonical,
190
+ side: req.side,
191
+ type: req.type,
192
+ status: res.data.status?.toLowerCase() ?? "new",
193
+ quantity: req.quantity,
194
+ price: req.price ?? 0,
195
+ dryRun: false,
196
+ timestamp: Date.now()
197
+ };
198
+ }
199
+ async cancelOrder(_creds, orderId) {
200
+ if (!this.privateKey) throw new TradingServiceError("TRADING_AUTH_FAILED", "Tiger: privateKey (RSA PEM) is required for cancelOrder");
201
+ const res = await this.requestJson({
202
+ account: this.accountId,
203
+ orderId
204
+ }, "cancel_order");
205
+ if (res.code !== 0) throw new TradingServiceError("TRADING_EXCHANGE_ERROR", `Tiger cancelOrder failed: ${res.message ?? `code ${res.code}`}`);
206
+ return {
207
+ orderId,
208
+ status: "canceled"
209
+ };
210
+ }
211
+ };
212
+ //#endregion
213
+ export { INTERVAL_VOCABULARY, TigerRestClient, TradingServiceError, generateTigerSignature, toTigerSymbol };
package/package.json ADDED
@@ -0,0 +1,39 @@
1
+ {
2
+ "name": "@dshtrading/connector-tiger",
3
+ "description": "【模板】交易所连接器插件脚手架:Tiger(tiger)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
+ }