tigeropen 0.3.0 → 0.5.5

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.
Files changed (84) hide show
  1. package/README.md +55 -2
  2. package/dist/cjs/client/api-response.js +28 -7
  3. package/dist/cjs/client/case-convert.js +4 -3
  4. package/dist/cjs/client/http-client.js +124 -8
  5. package/dist/cjs/client/token-methods.js +42 -0
  6. package/dist/cjs/config/client-config.js +115 -16
  7. package/dist/cjs/config/config-parser.js +19 -9
  8. package/dist/cjs/config/index.js +4 -1
  9. package/dist/cjs/config/token-manager.js +54 -4
  10. package/dist/cjs/index.js +53 -2
  11. package/dist/cjs/model/enums.js +106 -7
  12. package/dist/cjs/model/order-helpers.js +149 -0
  13. package/dist/cjs/model/order-status.js +46 -0
  14. package/dist/cjs/model/quote-requests.js +11 -0
  15. package/dist/cjs/model/trade-requests.js +13 -0
  16. package/dist/cjs/push/index.js +1 -0
  17. package/dist/cjs/push/pb/OrderStatusData.js +24 -0
  18. package/dist/cjs/push/proto-message.js +6 -0
  19. package/dist/cjs/push/push-client.js +117 -19
  20. package/dist/cjs/push/push-message.js +4 -0
  21. package/dist/cjs/push/tick-util.js +172 -0
  22. package/dist/cjs/quote/quote-client.js +584 -42
  23. package/dist/cjs/trade/trade-client.js +334 -32
  24. package/dist/cjs/version.js +4 -0
  25. package/dist/esm/client/api-request.js +1 -1
  26. package/dist/esm/client/api-response.js +29 -8
  27. package/dist/esm/client/case-convert.js +4 -3
  28. package/dist/esm/client/http-client.js +128 -12
  29. package/dist/esm/client/index.js +6 -6
  30. package/dist/esm/client/token-methods.js +37 -0
  31. package/dist/esm/config/client-config.js +118 -20
  32. package/dist/esm/config/config-parser.js +19 -9
  33. package/dist/esm/config/index.js +4 -3
  34. package/dist/esm/config/token-manager.js +55 -5
  35. package/dist/esm/index.js +15 -1
  36. package/dist/esm/logger/index.js +1 -1
  37. package/dist/esm/model/contract-helpers.js +1 -1
  38. package/dist/esm/model/enums.js +104 -6
  39. package/dist/esm/model/order-helpers.js +142 -1
  40. package/dist/esm/model/order-status.js +43 -0
  41. package/dist/esm/model/quote-requests.js +10 -0
  42. package/dist/esm/model/trade-requests.js +12 -0
  43. package/dist/esm/push/index.js +6 -5
  44. package/dist/esm/push/pb/OrderStatusData.js +24 -0
  45. package/dist/esm/push/pb/PushData.js +11 -11
  46. package/dist/esm/push/pb/QuoteBasicData.js +1 -1
  47. package/dist/esm/push/pb/Response.js +1 -1
  48. package/dist/esm/push/pb/index.js +17 -17
  49. package/dist/esm/push/proto-message.js +9 -3
  50. package/dist/esm/push/push-client.js +124 -26
  51. package/dist/esm/push/push-message.js +4 -0
  52. package/dist/esm/push/tick-util.js +165 -0
  53. package/dist/esm/quote/index.js +1 -1
  54. package/dist/esm/quote/quote-client.js +553 -44
  55. package/dist/esm/signer/index.js +2 -2
  56. package/dist/esm/trade/index.js +1 -1
  57. package/dist/esm/trade/trade-client.js +303 -34
  58. package/dist/esm/version.js +1 -0
  59. package/dist/types/client/api-response.d.ts +6 -4
  60. package/dist/types/client/case-convert.d.ts +3 -1
  61. package/dist/types/client/http-client.d.ts +32 -1
  62. package/dist/types/client/token-methods.d.ts +34 -0
  63. package/dist/types/config/client-config.d.ts +22 -1
  64. package/dist/types/config/index.d.ts +3 -1
  65. package/dist/types/config/token-manager.d.ts +27 -3
  66. package/dist/types/index.d.ts +22 -1
  67. package/dist/types/model/enums.d.ts +77 -7
  68. package/dist/types/model/order-helpers.d.ts +52 -1
  69. package/dist/types/model/order-status.d.ts +14 -0
  70. package/dist/types/model/order.d.ts +127 -10
  71. package/dist/types/model/quote-requests.d.ts +356 -0
  72. package/dist/types/model/quote.d.ts +391 -4
  73. package/dist/types/model/trade-requests.d.ts +309 -0
  74. package/dist/types/model/trade.d.ts +231 -5
  75. package/dist/types/push/callbacks.d.ts +3 -7
  76. package/dist/types/push/index.d.ts +1 -0
  77. package/dist/types/push/pb/OrderStatusData.d.ts +4 -0
  78. package/dist/types/push/push-client.d.ts +36 -3
  79. package/dist/types/push/push-message.d.ts +4 -0
  80. package/dist/types/push/tick-util.d.ts +30 -0
  81. package/dist/types/quote/quote-client.d.ts +193 -15
  82. package/dist/types/trade/trade-client.d.ts +136 -18
  83. package/dist/types/version.d.ts +1 -0
  84. package/package.json +5 -2
@@ -1,13 +1,83 @@
1
- import { createApiRequest } from '../client/api-request';
2
- import { unmarshalData } from '../client/api-response';
1
+ /**
2
+ * TradeClient — trading client.
3
+ *
4
+ * All methods return strongly-typed responses; request parameters are
5
+ * written in camelCase in TypeScript and converted to snake_case on the wire.
6
+ *
7
+ * v0.4.0: 所有查询类方法改为 Request 对象签名(OrdersRequest 等),补齐 17
8
+ * 个新方法(账户管理 / 资产分析 / 资金调拨 / 持仓划转等)。
9
+ */
10
+ import { HttpClient } from '../client/http-client.js';
11
+ import { createApiRequest } from '../client/api-request.js';
12
+ import { unmarshalData } from '../client/api-response.js';
13
+ import * as tokenMethods from '../client/token-methods.js';
14
+ import { normalizeOrderStatus } from '../model/order-status.js';
15
+ /** Normalize `Order.status` field in-place (handles int → string). */
16
+ function normalizeOrderInPlace(o) {
17
+ if (o && o.status !== undefined && o.status !== null) {
18
+ o.status = normalizeOrderStatus(o.status);
19
+ }
20
+ }
21
+ /** Normalize every Order in a list in-place. */
22
+ function normalizeOrders(orders) {
23
+ for (const o of orders)
24
+ normalizeOrderInPlace(o);
25
+ return orders;
26
+ }
27
+ /** Shallow-copy a request object and fill account if empty. */
28
+ function withAccount(req, account) {
29
+ const r = { ...(req ?? {}) };
30
+ if (!r.account)
31
+ r.account = account;
32
+ return r;
33
+ }
3
34
  /** Trading client wrapping all trade-related APIs. */
4
35
  export class TradeClient {
5
- constructor(httpClient, account) {
36
+ constructor(httpClient, account, secretKey) {
6
37
  this.httpClient = httpClient;
7
38
  this.account = account;
39
+ this.secretKey = secretKey;
40
+ }
41
+ /** Create a TradeClient directly from a ClientConfig — no need to construct HttpClient manually. */
42
+ static fromConfig(config, account, secretKey) {
43
+ return new TradeClient(new HttpClient(config), account, secretKey);
44
+ }
45
+ // ── Token management ──────────────────────────────────────────────────────
46
+ /** Call the `user_token_refresh` API and return the new token. Read-only. */
47
+ async queryToken() {
48
+ return tokenMethods.queryToken(this.httpClient);
49
+ }
50
+ /**
51
+ * Refresh the token: call the API, update the in-memory config token, and
52
+ * optionally persist via the provided TokenManager (file + writer callback).
53
+ *
54
+ * @param tokenManager - optional TokenManager for file persistence and writer callback
55
+ */
56
+ async refreshToken(tokenManager) {
57
+ return tokenMethods.refreshToken(this.httpClient, tokenManager);
58
+ }
59
+ /**
60
+ * Start background token auto-refresh. Returns a TokenManager that can be
61
+ * used to stop the background task via `tm.stopAutoRefresh()`.
62
+ *
63
+ * @param refreshDurationSecs - Refresh threshold in seconds (minimum 30).
64
+ * @param checkIntervalMs - How often to check, in milliseconds (default 300 000 / 5 min).
65
+ * @param tokenWriter - Optional callback invoked after each successful refresh.
66
+ */
67
+ startTokenAutoRefresh(refreshDurationSecs, checkIntervalMs, tokenWriter) {
68
+ return tokenMethods.startTokenAutoRefresh(this.httpClient, refreshDurationSecs, checkIntervalMs, tokenWriter);
8
69
  }
9
70
  async callInto(method, bizParams) {
10
- const request = createApiRequest(method, bizParams);
71
+ // Inject secretKey into every request when available (institution accounts require it).
72
+ // Individual methods that already set secretKey will not be overwritten (|| not &&).
73
+ let params = bizParams;
74
+ if (this.secretKey && params !== null && typeof params === 'object' && !Array.isArray(params)) {
75
+ const p = params;
76
+ if (p['secretKey'] == null && p['secret_key'] == null) {
77
+ params = { ...p, secretKey: this.secretKey };
78
+ }
79
+ }
80
+ const request = createApiRequest(method, params);
11
81
  const response = await this.httpClient.executeRequest(request);
12
82
  return unmarshalData(response.data);
13
83
  }
@@ -39,51 +109,250 @@ export class TradeClient {
39
109
  });
40
110
  }
41
111
  // === Order operations ===
112
+ /**
113
+ * Prepare an order request for the wire.
114
+ *
115
+ * The gateway expects `algo_params` as a `[{tag, value}, ...]` array
116
+ * (matching the Python SDK's AlgoParams.to_dict serialization), not the
117
+ * plain object shape that reads naturally in TypeScript. This helper
118
+ * normalizes the object form into the array form on outbound payloads
119
+ * so callers can pass the natural object and TWAP/VWAP orders work end
120
+ * to end without wire-format workarounds.
121
+ *
122
+ * Fields with undefined/null values are dropped; empty algoParams
123
+ * becomes an empty array rather than being stripped, matching the
124
+ * Python SDK behavior when the user passes an empty AlgoParams().
125
+ */
126
+ marshalOrderForWire(order) {
127
+ const { algoParams, ...rest } = order;
128
+ const withAccount = { ...rest, account: this.account };
129
+ if (algoParams === undefined)
130
+ return withAccount;
131
+ // Already a tag/value array (advanced callers who want raw control)
132
+ if (Array.isArray(algoParams)) {
133
+ withAccount.algoParams = algoParams;
134
+ return withAccount;
135
+ }
136
+ // Object shape → tag/value array.
137
+ // Keys are converted to snake_case explicitly here (e.g. `startTime` →
138
+ // `start_time`) so they land correctly in the `tag` string that the
139
+ // gateway reads. `keysToSnakeCase` only rewrites object *keys*, not
140
+ // string *values*, so `tag` would be left camelCase if we didn't do
141
+ // this conversion ourselves.
142
+ const tagValues = [];
143
+ for (const [key, value] of Object.entries(algoParams)) {
144
+ if (value === undefined || value === null)
145
+ continue;
146
+ const snakeKey = key.replace(/[A-Z]/g, (c) => '_' + c.toLowerCase());
147
+ tagValues.push({ tag: snakeKey, value });
148
+ }
149
+ withAccount.algoParams = tagValues;
150
+ return withAccount;
151
+ }
42
152
  async placeOrder(order) {
43
- return this.callInto('place_order', { ...order, account: this.account });
153
+ return this.callInto('place_order', this.marshalOrderForWire(order));
44
154
  }
45
155
  async previewOrder(order) {
46
- return this.callInto('preview_order', { ...order, account: this.account });
156
+ return this.callInto('preview_order', this.marshalOrderForWire(order));
47
157
  }
48
158
  async modifyOrder(id, order) {
49
- return this.callInto('modify_order', { ...order, account: this.account, id });
159
+ return this.callInto('modify_order', { ...this.marshalOrderForWire(order), id });
50
160
  }
51
- async cancelOrder(id) {
52
- return this.callInto('cancel_order', { account: this.account, id });
161
+ async cancelOrder(id, secretKey) {
162
+ const params = { account: this.account, id };
163
+ if (secretKey !== undefined)
164
+ params.secretKey = secretKey; // per-call override takes precedence; undefined means use config default
165
+ return this.callInto('cancel_order', params);
53
166
  }
54
- // === Order queries ===
55
- async getOrders() {
56
- return this.callIntoItems('orders', { account: this.account });
167
+ // === Order queries (BREAKING v0.4.0) ===
168
+ /**
169
+ * Query all historical orders. v0.4.0: optional OrdersRequest for filtering.
170
+ *
171
+ * @example
172
+ * // Default (unfiltered)
173
+ * await tc.getOrders();
174
+ * // Filter by status
175
+ * await tc.getOrders({ states: ['Filled'], limit: 100 });
176
+ */
177
+ async getOrders(req) {
178
+ return normalizeOrders(await this.callIntoItems('orders', withAccount(req, this.account)));
57
179
  }
58
- async getActiveOrders() {
59
- return this.callIntoItems('active_orders', { account: this.account });
180
+ /** Query active (open) orders. v0.4.0: supports ParentId to filter attached legs. */
181
+ async getActiveOrders(req) {
182
+ return normalizeOrders(await this.callIntoItems('active_orders', withAccount(req, this.account)));
60
183
  }
61
- async getInactiveOrders() {
62
- return this.callIntoItems('inactive_orders', { account: this.account });
184
+ /** Query inactive/cancelled orders. */
185
+ async getInactiveOrders(req) {
186
+ return normalizeOrders(await this.callIntoItems('inactive_orders', withAccount(req, this.account)));
63
187
  }
64
188
  /**
65
- * Filled orders in a time range (ms timestamps required by the server).
66
- * Use `Date.now() - 30*24*3600*1000` for "last 30 days".
189
+ * Query filled orders. v0.4.0 BREAKING: signature changed from positional
190
+ * (startDateMs, endDateMs) to OrdersRequest object.
191
+ *
192
+ * @example
193
+ * // Last 30 days
194
+ * const now = Date.now();
195
+ * await tc.getFilledOrders({ startDate: now - 30*24*3600*1000, endDate: now });
67
196
  */
68
- async getFilledOrders(startDateMs, endDateMs) {
69
- return this.callIntoItems('filled_orders', {
70
- account: this.account, startDate: startDateMs, endDate: endDateMs,
71
- });
197
+ async getFilledOrders(req) {
198
+ return normalizeOrders(await this.callIntoItems('filled_orders', withAccount(req, this.account)));
72
199
  }
73
- /** Transactions for a specific order; `symbol` and `secType` are required. */
74
- async getOrderTransactions(id, symbol, secType) {
75
- return this.callIntoItems('order_transactions', {
76
- account: this.account, orderId: id, symbol, secType,
77
- });
200
+ /**
201
+ * Get a single order by ID (v0.4.0 new).
202
+ * Returns `undefined` if no match.
203
+ */
204
+ async getOrder(req) {
205
+ const merged = withAccount(req, this.account);
206
+ const out = await this.callInto('order_no', merged);
207
+ if (!out || (!out.id && !out.orderId))
208
+ return undefined;
209
+ normalizeOrderInPlace(out);
210
+ return out;
211
+ }
212
+ /**
213
+ * Query order transaction details. v0.4.0 BREAKING: all fields now optional
214
+ * (previously symbol/secType required).
215
+ */
216
+ async getOrderTransactions(req) {
217
+ return this.callIntoItems('order_transactions', withAccount(req, this.account));
218
+ }
219
+ // === Positions & assets (BREAKING v0.4.0) ===
220
+ /** Query positions. v0.4.0: supports Symbol / SecType / Currency / Market filters. */
221
+ async getPositions(req) {
222
+ return this.callIntoItems('positions', withAccount(req, this.account));
223
+ }
224
+ /** Query assets. v0.4.0: supports sub-account list and aggregation options. */
225
+ async getAssets(req) {
226
+ return this.callIntoItems('assets', withAccount(req, this.account));
227
+ }
228
+ /** Query prime assets. v0.4.0: takes AssetsRequest for filters. */
229
+ async getPrimeAssets(req) {
230
+ return this.callInto('prime_assets', withAccount(req, this.account));
231
+ }
232
+ // ===== v0.4.0 NEW: Account management =====
233
+ /** Query managed sub-accounts (institutional). */
234
+ async getManagedAccounts(req) {
235
+ return this.callIntoItems('accounts', withAccount(req, this.account));
236
+ }
237
+ /**
238
+ * Query derivative contracts list. Same wire as getQuoteContract but accepts
239
+ * full request struct. Python: `get_derivative_contracts`.
240
+ */
241
+ async getDerivativeContracts(req) {
242
+ return this.callIntoItems('quote_contract', withAccount(req, this.account));
243
+ }
244
+ // ===== v0.4.0 NEW: Asset analytics =====
245
+ /** Daily P&L / net-value / holding-value analytics. */
246
+ async getAnalyticsAsset(req) {
247
+ return this.callIntoItems('analytics_asset', withAccount(req, this.account));
248
+ }
249
+ /** Aggregate assets (prime) by base currency. */
250
+ async getAggregateAssets(req) {
251
+ return this.callInto('aggregate_assets', withAccount(req, this.account));
252
+ }
253
+ /** Estimate tradable quantity given order parameters. */
254
+ async getEstimateTradableQuantity(req) {
255
+ return this.callInto('estimate_tradable_quantity', withAccount(req, this.account));
256
+ }
257
+ // ===== v0.4.0 NEW: Forex =====
258
+ /** Place forex order (sub-account base-currency swap). */
259
+ async placeForexOrder(req) {
260
+ return this.callInto('place_forex_order', withAccount(req, this.account));
261
+ }
262
+ // ===== v0.4.0 NEW: Segment fund transfer =====
263
+ /** Query amount available for inter-segment transfer. Returns array. */
264
+ async getSegmentFundAvailable(req) {
265
+ return this.callInto('segment_fund_available', withAccount(req, this.account));
266
+ }
267
+ /** Query segment fund transfer history. Server returns plain array (no items wrapper). */
268
+ async getSegmentFundHistory(req) {
269
+ return this.callInto('segment_fund_history', withAccount(req, this.account));
270
+ }
271
+ /** Execute an inter-segment fund transfer. */
272
+ async transferSegmentFund(req) {
273
+ return this.callInto('transfer_segment_fund', withAccount(req, this.account));
274
+ }
275
+ /** Cancel a pending inter-segment transfer. */
276
+ async cancelSegmentFund(req) {
277
+ return this.callInto('cancel_segment_fund', withAccount(req, this.account));
278
+ }
279
+ // ===== v0.4.0 NEW: Fund details / history =====
280
+ /** Fund-movement details (by segment / currency / fund-type). */
281
+ async getFundDetails(req) {
282
+ return this.callIntoItems('fund_details', withAccount(req, this.account));
283
+ }
284
+ /** Funding history (wire method: `transfer_fund`).
285
+ * Server returns bare list (no items wrapper). */
286
+ async getFundingHistory(req) {
287
+ return this.callInto('transfer_fund', withAccount(req, this.account));
288
+ }
289
+ // ===== v0.4.0 NEW: Internal / external position transfer =====
290
+ /**
291
+ * Internal position transfer (cross sub-account).
292
+ * @note Uses `fromAccount` / `toAccount` (not `account`).
293
+ */
294
+ async transferPosition(req) {
295
+ const merged = { ...req };
296
+ if (!merged.fromAccount)
297
+ merged.fromAccount = this.account;
298
+ return this.callInto('position_transfer', merged);
299
+ }
300
+ /** Query internal position transfer records. Uses `accountId` (wire: `account_id`). */
301
+ async getPositionTransferRecords(req) {
302
+ const merged = { ...req };
303
+ if (!merged.accountId)
304
+ merged.accountId = this.account;
305
+ return this.callIntoItems('position_transfer_records', merged);
306
+ }
307
+ /** Query single internal position transfer detail by ID. */
308
+ async getPositionTransferDetail(req) {
309
+ const merged = { ...req };
310
+ if (!merged.accountId)
311
+ merged.accountId = this.account;
312
+ return this.callInto('position_transfer_detail', merged);
313
+ }
314
+ /** Query external position transfer records (DWAC / FOP / etc.). */
315
+ async getPositionTransferExternalRecords(req) {
316
+ const merged = { ...req };
317
+ if (!merged.accountId)
318
+ merged.accountId = this.account;
319
+ return this.callIntoItems('position_transfer_external_records', merged);
320
+ }
321
+ /** 行权检验:预估行权/作废后正股持仓变化 (wire: option_exercise_check) */
322
+ async checkOptionExercise(req) {
323
+ const merged = { ...req };
324
+ if (!merged.account)
325
+ merged.account = this.account;
326
+ return this.callInto('option_exercise_check', merged);
327
+ }
328
+ /** 查询可行权持仓列表 (wire: option_exercise_position) */
329
+ async getOptionExercisePositions(req) {
330
+ const merged = { ...req };
331
+ if (!merged.account)
332
+ merged.account = this.account;
333
+ return this.callInto('option_exercise_position', merged);
78
334
  }
79
- // === Positions & assets ===
80
- async getPositions() {
81
- return this.callIntoItems('positions', { account: this.account });
335
+ /** 提交行权/作废申请 (wire: option_exercise_submit) */
336
+ async submitOptionExercise(req) {
337
+ const merged = { ...req };
338
+ if (!merged.account)
339
+ merged.account = this.account;
340
+ const result = await this.callInto('option_exercise_submit', merged);
341
+ return result ?? false;
82
342
  }
83
- async getAssets() {
84
- return this.callIntoItems('assets', { account: this.account });
343
+ /** 分页查询行权记录 (wire: option_exercise_record) */
344
+ async getOptionExerciseRecords(req) {
345
+ const merged = { ...req };
346
+ if (!merged.account)
347
+ merged.account = this.account;
348
+ return this.callInto('option_exercise_record', merged);
85
349
  }
86
- async getPrimeAssets() {
87
- return this.callInto('prime_assets', { account: this.account });
350
+ /** 撤销行权申请 (wire: option_exercise_cancel) */
351
+ async cancelOptionExercise(req) {
352
+ const merged = { ...req };
353
+ if (!merged.account)
354
+ merged.account = this.account;
355
+ const result = await this.callInto('option_exercise_cancel', merged);
356
+ return result ?? false;
88
357
  }
89
358
  }
@@ -0,0 +1 @@
1
+ export const SDK_VERSION = '0.4.8';
@@ -12,13 +12,15 @@ export interface ApiResponse {
12
12
  sign?: string;
13
13
  }
14
14
  /**
15
- * Parse the raw HTTP response body.
16
- * Throws TigerError when code != 0.
15
+ * Parse the raw HTTP response body. Throws TigerError when code != 0.
16
+ *
17
+ * patchLargeIntegers is applied before JSON.parse to preserve int64 order IDs
18
+ * (e.g. 28868646234578944) as strings rather than losing precision.
17
19
  */
18
20
  export declare function parseApiResponse(body: string): ApiResponse;
19
21
  /**
20
22
  * Decode an ApiResponse.data payload into a typed value.
21
- * Handles the server's occasional double-encoded JSON (where `data` is a
22
- * JSON string that itself wraps JSON), seen on some trade endpoints.
23
+ * Handles double-encoded JSON (where `data` is a JSON string wrapping JSON),
24
+ * seen on some trade endpoints.
23
25
  */
24
26
  export declare function unmarshalData<T>(data: unknown): T | undefined;
@@ -11,6 +11,8 @@ export declare function camelToSnake(key: string): string;
11
11
  /**
12
12
  * Recursively convert all object keys from camelCase to snake_case.
13
13
  * Preserves arrays, primitives, and Date/null/undefined.
14
- * Keys already containing an underscore are kept as-is (already snake_case).
14
+ *
15
+ * Note: camelToSnake is idempotent for pure snake_case keys (no uppercase
16
+ * letters → no replacements), so no pre-check is needed.
15
17
  */
16
18
  export declare function keysToSnakeCase(value: unknown): unknown;
@@ -5,6 +5,7 @@
5
5
  * Uses Node.js built-in fetch (Node 18+).
6
6
  */
7
7
  import type { ClientConfig } from '../config/client-config';
8
+ import { TokenManager, type TokenManagerOptions } from '../config/token-manager';
8
9
  import { RetryPolicy } from './retry';
9
10
  import { type ApiResponse } from './api-response';
10
11
  import type { ApiRequest } from './api-request';
@@ -16,9 +17,16 @@ export declare class HttpClient {
16
17
  private retryPolicy;
17
18
  /** Override the target URL (used by quote client to hit quote server) */
18
19
  private targetUrl;
20
+ /** non-null when auto-refresh is active */
21
+ private tokenManager;
19
22
  constructor(config: ClientConfig, retryPolicy?: RetryPolicy, options?: {
20
23
  useQuoteServerUrl?: boolean;
21
24
  });
25
+ /**
26
+ * Stop the background token auto-refresh timer.
27
+ * Call this when the HttpClient is no longer needed to avoid timer leaks.
28
+ */
29
+ close(): void;
22
30
  /**
23
31
  * Build common request parameters
24
32
  */
@@ -41,9 +49,32 @@ export declare class HttpClient {
41
49
  *
42
50
  * @param apiMethod - API method name (e.g. "market_state", "place_order")
43
51
  * @param requestJson - Raw biz_content JSON string
52
+ * @param version - Optional API version override (default: "2.0")
44
53
  * @returns Raw response JSON string, unparsed
45
54
  */
46
- execute(apiMethod: string, requestJson: string): Promise<string>;
55
+ execute(apiMethod: string, requestJson: string, version?: string): Promise<string>;
56
+ /**
57
+ * 调用 user_token_refresh 接口获取新 token,返回新 token 字符串。
58
+ * 此方法仅查询,不修改 config 中的 token。
59
+ */
60
+ queryToken(): Promise<string>;
61
+ /**
62
+ * 刷新 token:调用接口获取新 token 后更新 config.token。
63
+ *
64
+ * @param tokenManager - 可选外部 TokenManager;若提供则调用 setToken() 写文件并触发回调。
65
+ * 若 NewHttpClient 已自动启动内部 TokenManager,其内存 token 也会同步更新。
66
+ */
67
+ refreshToken(tokenManager?: TokenManager | null): Promise<void>;
68
+ /**
69
+ * 启动后台 token 自动刷新。
70
+ *
71
+ * @param tokenManager - 可为 null:SDK 内部自动创建一个仅内存的 TokenManager,
72
+ * 适合直接通过 token 在代码里设置、不使用文件的场景。
73
+ * @param options - 仅在 tokenManager 为 null 时生效,用于配置内部 TokenManager
74
+ * (refreshDuration / refreshInterval / tokenWriter / tokenLoader)。
75
+ * @returns 使用或创建的 TokenManager 实例
76
+ */
77
+ startTokenAutoRefresh(tokenManager: TokenManager | null, options?: TokenManagerOptions): TokenManager;
47
78
  /** Delay for the specified milliseconds */
48
79
  private sleep;
49
80
  /**
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Shared token management methods for TradeClient and QuoteClient.
3
+ * Both clients delegate to the underlying HttpClient; this module
4
+ * centralises the JSDoc so each client stays in sync automatically.
5
+ */
6
+ import type { HttpClient } from './http-client';
7
+ import type { TokenManager } from '../config/token-manager';
8
+ /**
9
+ * Call the `user_token_refresh` API and return the new token string.
10
+ * Read-only: does NOT update the stored token.
11
+ * Use `refreshToken()` to also update the in-memory config and optionally persist.
12
+ */
13
+ export declare function queryToken(httpClient: HttpClient): Promise<string>;
14
+ /**
15
+ * Refresh the token: call the API, update the in-memory config token, and
16
+ * optionally persist via the provided TokenManager (file + writer callback).
17
+ *
18
+ * @param httpClient - The underlying HTTP client
19
+ * @param tokenManager - optional TokenManager for file persistence and writer callback
20
+ */
21
+ export declare function refreshToken(httpClient: HttpClient, tokenManager?: TokenManager | null): Promise<void>;
22
+ /**
23
+ * Start background token auto-refresh. Returns a TokenManager that can be
24
+ * used to stop the background task via `tm.stopAutoRefresh()`.
25
+ *
26
+ * @param httpClient - The underlying HTTP client
27
+ * @param refreshDurationSecs - Refresh threshold in seconds (minimum 30).
28
+ * When the token age exceeds this value the refresh is triggered.
29
+ * @param checkIntervalMs - How often to check whether a refresh is needed,
30
+ * in milliseconds. Defaults to 300 000 ms (5 minutes).
31
+ * @param tokenWriter - Optional callback invoked with the new token string
32
+ * after each successful refresh.
33
+ */
34
+ export declare function startTokenAutoRefresh(httpClient: HttpClient, refreshDurationSecs: number, checkIntervalMs?: number, tokenWriter?: (token: string) => void): TokenManager;
@@ -1,14 +1,24 @@
1
+ /** Sandbox / QA tiger public key for response signature verification */
2
+ export declare const SANDBOX_TIGER_PUBLIC_KEY: string;
1
3
  /** Client configuration interface */
2
4
  export interface ClientConfig {
3
5
  tigerId: string;
4
6
  privateKey: string;
5
7
  account: string;
8
+ /** Institution secret key for trade authentication (institution accounts only) */
9
+ secretKey?: string;
6
10
  license?: string;
7
11
  language: string;
8
12
  timezone?: string;
9
13
  timeout: number;
10
14
  token?: string;
11
15
  tokenRefreshDuration?: number;
16
+ /** 后台 token 检查间隔(毫秒),仅 tokenRefreshDuration > 0 时生效,默认 5 分钟 */
17
+ tokenCheckInterval?: number;
18
+ /** 自定义 token 加载函数,替代默认的文件加载 */
19
+ tokenLoader?: () => Promise<string> | string;
20
+ /** token 刷新写入后的可选回调 */
21
+ tokenWriter?: (token: string) => void;
12
22
  serverUrl: string;
13
23
  /** Quote server URL for quote-specific requests; falls back to serverUrl */
14
24
  quoteServerUrl: string;
@@ -21,19 +31,30 @@ export interface ClientConfigOptions {
21
31
  tigerId?: string;
22
32
  privateKey?: string;
23
33
  account?: string;
34
+ /** Institution secret key for trade authentication (institution accounts only) */
35
+ secretKey?: string;
24
36
  license?: string;
25
37
  language?: string;
26
38
  timezone?: string;
27
39
  timeout?: number;
28
40
  token?: string;
29
41
  tokenRefreshDuration?: number;
42
+ /** 后台 token 检查间隔(毫秒),仅 tokenRefreshDuration > 0 时生效,默认 5 分钟 */
43
+ tokenCheckInterval?: number;
44
+ /** 自定义 token 加载函数,替代默认的文件加载 */
45
+ tokenLoader?: () => Promise<string> | string;
46
+ /** token 刷新写入后的可选回调 */
47
+ tokenWriter?: (token: string) => void;
30
48
  serverUrl?: string;
31
49
  /** Explicit quote server URL; resolved dynamically if not set */
32
50
  quoteServerUrl?: string;
33
51
  /** Enable dynamic domain resolution (default: true) */
34
52
  enableDynamicDomain?: boolean;
35
- /** Explicit properties file path (synchronous read) */
53
+ /** Explicit properties file path or directory (synchronous read).
54
+ * If a directory is given, appends 'tiger_openapi_config.properties' automatically. */
36
55
  propertiesFilePath?: string;
56
+ /** Override Tiger public key (e.g. for sandbox/QA environments) */
57
+ tigerPublicKey?: string;
37
58
  }
38
59
  /**
39
60
  * Load and parse a Java-style properties file.
@@ -2,6 +2,8 @@
2
2
  * 配置层导出
3
3
  */
4
4
  export { parsePropertiesFile, parsePropertiesString } from './config-parser';
5
- export { createClientConfig, loadPropertiesFile } from './client-config';
5
+ export { createClientConfig, loadPropertiesFile, SANDBOX_TIGER_PUBLIC_KEY } from './client-config';
6
6
  export type { ClientConfig, ClientConfigOptions } from './client-config';
7
+ export { TokenManager } from './token-manager';
8
+ export type { TokenManagerOptions, RefreshFn } from './token-manager';
7
9
  export { queryDomains, resolveDynamicServerUrl, resolveDynamicQuoteServerUrl } from './domain';
@@ -4,6 +4,10 @@ export interface TokenManagerOptions {
4
4
  refreshInterval?: number;
5
5
  /** Token 刷新阈值(秒),0 表示不刷新,最小 30 秒 */
6
6
  refreshDuration?: number;
7
+ /** 自定义 token 加载函数,优先于文件加载 */
8
+ tokenLoader?: () => Promise<string> | string;
9
+ /** token 写入后的回调(SetToken 成功后触发,SyncToken 不触发) */
10
+ tokenWriter?: (token: string) => void;
7
11
  }
8
12
  /** Token 刷新函数类型 */
9
13
  export type RefreshFn = () => Promise<string>;
@@ -13,16 +17,36 @@ export type RefreshFn = () => Promise<string>;
13
17
  export declare class TokenManager {
14
18
  private token;
15
19
  private filePath;
20
+ /** 仅当显式传入 filePath 时才写文件(fileEnabled = true) */
21
+ private fileEnabled;
16
22
  private refreshInterval;
17
23
  private refreshDuration;
18
24
  private timer;
25
+ private tokenLoader;
26
+ private tokenWriter;
19
27
  constructor(options?: TokenManagerOptions);
20
- /** 从 properties 文件加载 Token */
21
- loadToken(): string;
28
+ /**
29
+ * 从 properties 文件(或自定义 tokenLoader)加载 Token。
30
+ * 若设置了 tokenLoader,优先调用;否则从 properties 文件读取。
31
+ */
32
+ loadToken(): Promise<string>;
33
+ /**
34
+ * 同步版文件加载(仅用于无 tokenLoader 时的兼容入口)。
35
+ * 建议优先使用 loadToken()(异步)。
36
+ */
37
+ loadTokenSync(): string;
22
38
  /** 获取当前 Token */
23
39
  getToken(): string;
24
- /** 设置 Token 并更新文件 */
40
+ /**
41
+ * 设置 Token;若启用了文件持久化(显式传入 filePath),则同步写文件。
42
+ * 成功后触发 tokenWriter 回调(如有)。
43
+ */
25
44
  setToken(token: string): void;
45
+ /**
46
+ * 仅更新内存中的 token,不写文件,不触发 tokenWriter 回调。
47
+ * 用于多个组件共享 token 时的内部同步。
48
+ */
49
+ syncToken(token: string): void;
26
50
  /** 将 Token 保存到 properties 文件 */
27
51
  private saveTokenToFile;
28
52
  /**
@@ -15,4 +15,25 @@
15
15
  * @packageDocumentation
16
16
  */
17
17
  /** SDK 版本号 */
18
- export declare const VERSION = "0.3.0";
18
+ export { SDK_VERSION as VERSION } from './version';
19
+ export { createClientConfig, loadPropertiesFile, SANDBOX_TIGER_PUBLIC_KEY } from './config';
20
+ export type { ClientConfig, ClientConfigOptions } from './config';
21
+ export { TokenManager } from './config';
22
+ export type { TokenManagerOptions, RefreshFn } from './config';
23
+ export { HttpClient } from './client';
24
+ export { TigerError, classifyErrorCode } from './client';
25
+ export type { ErrorCategory } from './client';
26
+ export { QuoteClient, parseOptionIdentifier } from './quote';
27
+ export { TradeClient } from './trade';
28
+ export { PushClient, ConnectionState, SubjectType } from './push';
29
+ export type { PushClientOptions } from './push';
30
+ export type { Order, OrderRequest, ContractLegRequest } from './model/order';
31
+ export { marketOrder, limitOrder, stopOrder, stopLimitOrder } from './model/order-helpers';
32
+ export { normalizeOrderStatus } from './model/order-status';
33
+ export type { Contract } from './model/contract';
34
+ export type { Position } from './model/position';
35
+ export type { Asset, AssetSegment, PrimeAsset, PreviewResult, PlaceOrderResult, OrderIdResult, Transaction, ManagedAccount, AnalyticsAsset, AggregateAssets, EstimateTradableQuantity, ForexOrderResult, SegmentFund, SegmentFundAvailableItem, SegmentFundHistoryItem, FundDetails, FundingHistoryItem, PositionTransferRecord, PositionTransferDetail, PositionTransferExternalRecord, OptionExerciseCheckResult, OptionExercisePositionPageResult, OptionExerciseRecordPageResult, } from './model/trade';
36
+ export type { OrdersRequest, GetOrderRequest, OrderTransactionsRequest, PositionsRequest, AssetsRequest, ManagedAccountsRequest, DerivativeContractsRequest, AnalyticsAssetRequest, AggregateAssetsRequest, EstimateTradableQuantityRequest, ForexOrderRequest, SegmentFundRequest, FundDetailsRequest, FundingHistoryRequest, PositionTransferRequest, PositionTransferRecordsRequest, PositionTransferDetailRequest, PositionTransferExternalRecordsRequest, OptionExerciseCheckRequest, OptionExercisePositionRequest, OptionExerciseSubmitRequest, OptionExerciseRecordsRequest, OptionExerciseCancelRequest, } from './model/trade-requests';
37
+ export type { MarketState, Brief, Kline, KlineItem, Timeline, TimelineItem, TradeTick, TradeTickItem, Depth, DepthLevel, OptionExpiration, OptionChain, OptionChainRow, OptionSymbol, OptionChainFilter, OptionChainFilterGreeks, Range, FutureExchange, FutureContractInfo, FutureQuote, FutureKline, FutureKlineItem, FutureDepth, FutureTradeTickItem, FutureTradingTime, FinancialDailyItem, FinancialReportItem, CorporateAction, CorporateSymbolChange, CorporateDelisting, CorporateIPO, CapitalFlow, CapitalFlowItem, CapitalDistribution, ScannerResult, ScannerResultItem, QuotePermission, SymbolName, TradeMeta, StockDetail, StockBroker, StockBrokerItem, ShortInterest, StockIndustry, IndustryItem, IndustryStock, WarrantBrief, WarrantFilterResult, FundContractInfo, FundQuote, FundHistoryQuote, QuoteOvernight, KlineQuota, MarketScannerTag, MarketScannerTags, OptionAnalysis, OptionLeg, OptionVolatilityPoint, ExchangeRate, FinancialCurrency, BrokerDetail, TradingCalendarItem, FutureMainContractHistory, } from './model/quote';
38
+ export type { BriefRequest, DepthQuoteRequest, TradeTickRequest, KlineRequest, KlineByPageRequest, TimelineRequest, FutureBriefRequest, FutureKlineRequest, FutureKlineByPageRequest, FutureTradeTicksRequest, FutureDepthRequest, FutureContractSingleRequest, FutureContinuousContractsRequest, FutureHistoryMainContractRequest, FutureTradingTimesRequest, AllFutureContractsRequest, OptionTradeTicksRequest, OptionTimelineRequest, OptionDepthRequest, OptionSymbolsRequest, OptionAnalysisRequest, OptionQueryItem, ShortInterestRequest, StockBrokerRequest, StockDetailsRequest, StockFundamentalRequest, StockIndustryRequest, StockDelayBriefsRequest, SymbolsRequest, TradeMetasRequest, TradeRankRequest, TimelineHistoryRequest, TradingCalendarRequest, KlineQuotaRequest, QuotePermissionRequest, QuoteOvernightRequest, IndustryListRequest, IndustryStocksRequest, FundSymbolsRequest, FundContractsRequest, FundQuoteRequest, FundHistoryQuoteRequest, WarrantBriefsRequest, WarrantFilterRequest, MarketScannerTagsRequest, FinancialCurrencyRequest, FinancialExchangeRateRequest, } from './model/quote-requests';
39
+ export { OrderStatus, SecurityType, OrderType, TimeInForce, Market, Currency, QuoteRight, SegmentType, OrderSortBy, CorporateActionType, IndustryLevel, SortDirection, OptionAnalysisPeriod, FinancialReportPeriod, Language, License, BarPeriod, orderStatusCode, } from './model/enums';