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,10 +1,58 @@
1
- import { createApiRequest } from '../client/api-request';
2
- import { unmarshalData } from '../client/api-response';
1
+ /**
2
+ * QuoteClient — market-data client.
3
+ *
4
+ * All methods return strongly-typed responses from the `model` package.
5
+ * Request parameters are written in camelCase in TypeScript and are
6
+ * converted to snake_case on the wire automatically.
7
+ */
8
+ import { HttpClient } from '../client/http-client.js';
9
+ import { createApiRequest } from '../client/api-request.js';
10
+ import { unmarshalData } from '../client/api-response.js';
11
+ import * as tokenMethods from '../client/token-methods.js';
12
+ import { getTradeCondByCode, isUsStockSymbol } from '../push/tick-util.js';
13
+ /**
14
+ * resolveOptionTimezone returns the timezone string to use for expiry conversion.
15
+ * Explicit tz takes precedence; otherwise infer from symbol (.HK suffix → Asia/Hong_Kong, else America/New_York).
16
+ */
17
+ function resolveOptionTimezone(tz, symbol) {
18
+ if (tz)
19
+ return tz;
20
+ return symbol.toUpperCase().endsWith('.HK') ? 'Asia/Hong_Kong' : 'America/New_York';
21
+ }
22
+ /**
23
+ * Convert a "YYYY-MM-DD" date string to the Unix timestamp (ms) of local midnight
24
+ * in the given IANA timezone.
25
+ *
26
+ * Strategy: use Intl.DateTimeFormat to determine what UTC time corresponds to
27
+ * local midnight in the target timezone, correctly handling DST.
28
+ */
29
+ function localMidnightMs(dateStr, timezone) {
30
+ const [year, month, day] = dateStr.split('-').map(Number);
31
+ // Use noon UTC as a safe anchor (avoids DST ambiguity right at midnight)
32
+ const noonUtc = new Date(Date.UTC(year, month - 1, day, 12, 0, 0));
33
+ // Determine what hour/minute/second UTC noon appears as in the target timezone
34
+ const timeParts = new Intl.DateTimeFormat('en-US', {
35
+ timeZone: timezone,
36
+ hour: '2-digit',
37
+ minute: '2-digit',
38
+ second: '2-digit',
39
+ hour12: false,
40
+ }).formatToParts(noonUtc);
41
+ const h = parseInt(timeParts.find(p => p.type === 'hour').value, 10);
42
+ const m = parseInt(timeParts.find(p => p.type === 'minute').value, 10);
43
+ const s = parseInt(timeParts.find(p => p.type === 'second').value, 10);
44
+ // UTC offset at noon = 12:00:00 UTC − local time shown for noon UTC
45
+ // Local midnight = noon UTC − 12h + offset = noon UTC − (h*3600+m*60+s)s
46
+ return noonUtc.getTime() - (h * 3600 + m * 60 + s) * 1000;
47
+ }
3
48
  /**
4
49
  * Parse an OCC-style option identifier like "AAPL 260619C00150000"
5
50
  * into its component parts.
51
+ *
52
+ * @param timezone - Optional IANA timezone for expiry conversion (e.g. 'America/New_York').
53
+ * If omitted, defaults to America/New_York for US symbols and Asia/Hong_Kong for .HK symbols.
6
54
  */
7
- export function parseOptionIdentifier(identifier) {
55
+ export function parseOptionIdentifier(identifier, timezone) {
8
56
  const trimmed = identifier.trim();
9
57
  const spaceIdx = trimmed.indexOf(' ');
10
58
  if (spaceIdx === -1) {
@@ -21,7 +69,11 @@ export function parseOptionIdentifier(identifier) {
21
69
  const yy = parseInt(datePart.substring(0, 2), 10);
22
70
  const mm = parseInt(datePart.substring(2, 4), 10);
23
71
  const dd = parseInt(datePart.substring(4, 6), 10);
24
- const expiryMs = Date.UTC(2000 + yy, mm - 1, dd);
72
+ const resolvedTz = resolveOptionTimezone(timezone, symbol);
73
+ const paddedYear = String(2000 + yy).padStart(4, '0');
74
+ const paddedMonth = String(mm).padStart(2, '0');
75
+ const paddedDay = String(dd).padStart(2, '0');
76
+ const expiryMs = localMidnightMs(`${paddedYear}-${paddedMonth}-${paddedDay}`, resolvedTz);
25
77
  const right = rightChar === 'C' ? 'CALL' : rightChar === 'P' ? 'PUT' : '';
26
78
  if (!right)
27
79
  throw new Error(`invalid right character: ${rightChar}`);
@@ -36,56 +88,165 @@ export class QuoteClient {
36
88
  constructor(httpClient) {
37
89
  this.httpClient = httpClient;
38
90
  }
91
+ /** Create a QuoteClient directly from a ClientConfig — no need to construct HttpClient manually. */
92
+ static fromConfig(config) {
93
+ return new QuoteClient(new HttpClient(config, undefined, { useQuoteServerUrl: true }));
94
+ }
95
+ // ── Token management ──────────────────────────────────────────────────────
96
+ /** Call the `user_token_refresh` API and return the new token. Read-only. */
97
+ async queryToken() {
98
+ return tokenMethods.queryToken(this.httpClient);
99
+ }
100
+ /** Refresh the token and update the in-memory config token. */
101
+ async refreshToken(tokenManager) {
102
+ return tokenMethods.refreshToken(this.httpClient, tokenManager);
103
+ }
104
+ /**
105
+ * Start background token auto-refresh. Returns a TokenManager to stop with `tm.stopAutoRefresh()`.
106
+ *
107
+ * @param refreshDurationSecs - Refresh threshold in seconds (minimum 30).
108
+ * @param checkIntervalMs - How often to check, in milliseconds (default 300 000 / 5 min).
109
+ * @param tokenWriter - Optional callback invoked after each successful refresh.
110
+ */
111
+ startTokenAutoRefresh(refreshDurationSecs, checkIntervalMs, tokenWriter) {
112
+ return tokenMethods.startTokenAutoRefresh(this.httpClient, refreshDurationSecs, checkIntervalMs, tokenWriter);
113
+ }
39
114
  async callInto(method, bizParams, version) {
40
115
  const request = createApiRequest(method, bizParams, version);
41
116
  const response = await this.httpClient.executeRequest(request);
42
117
  return unmarshalData(response.data);
43
118
  }
119
+ /**
120
+ * Some endpoints return either a list or a single object depending on the
121
+ * server response shape (future_contract_by_contract_code /
122
+ * future_continuous_contracts). Unify into an array.
123
+ */
124
+ async callIntoListOrObject(method, bizParams, version) {
125
+ const raw = await this.callInto(method, bizParams, version);
126
+ if (raw == null)
127
+ return [];
128
+ if (Array.isArray(raw))
129
+ return raw;
130
+ return [raw];
131
+ }
132
+ /** Unwrap server {"items":[...]} envelope. */
133
+ async callIntoItems(method, bizParams, version) {
134
+ const wrap = await this.callInto(method, bizParams, version);
135
+ return wrap?.items ?? [];
136
+ }
44
137
  // === Basic market data ===
45
138
  async getMarketState(market) {
46
139
  return this.callInto('market_state', { market });
47
140
  }
48
- async getBrief(symbols) {
49
- return this.callInto('quote_real_time', { symbols });
141
+ /** Real-time stock quotes. wire: quote_real_time */
142
+ async getRealTimeQuote(req) {
143
+ return this.callInto('quote_real_time', req);
144
+ }
145
+ /** @deprecated Use getRealTimeQuote instead. */
146
+ async getBrief(req) {
147
+ return this.getRealTimeQuote(req);
50
148
  }
51
- async getKline(symbol, period) {
52
- return this.callInto('kline', { symbols: [symbol], period });
149
+ async getKline(req) {
150
+ return this.callInto('kline', req);
53
151
  }
54
- async getTimeline(symbols) {
55
- return this.callInto('timeline', { symbols });
152
+ async getTimeline(symbolsOrRequest) {
153
+ const req = Array.isArray(symbolsOrRequest) ? { symbols: symbolsOrRequest } : symbolsOrRequest;
154
+ return this.callInto('timeline', req, req.secType === 'CC' ? '3.0' : undefined);
56
155
  }
57
- async getTradeTick(symbols) {
58
- return this.callInto('trade_tick', { symbols });
156
+ /** Tick-by-tick trades. wire: trade_tick */
157
+ async getTradeTick(req) {
158
+ const out = await this.callInto('trade_tick', req);
159
+ for (const tick of out) {
160
+ const isUs = isUsStockSymbol(tick.symbol);
161
+ for (const item of tick.items) {
162
+ if (item.cond && item.cond.length > 0) {
163
+ item.cond = getTradeCondByCode(isUs, item.cond[0]);
164
+ }
165
+ }
166
+ }
167
+ return out;
59
168
  }
60
- /** Depth snapshot. market is required (US / HK supported). */
61
- async getQuoteDepth(symbol, market) {
62
- return this.callInto('quote_depth', { symbols: [symbol], market });
169
+ /** Depth snapshot. wire: quote_depth */
170
+ async getQuoteDepth(req) {
171
+ return this.callInto('quote_depth', req);
63
172
  }
64
173
  // === Options ===
65
- async getOptionExpiration(symbol) {
66
- return this.callInto('option_expiration', { symbols: [symbol] });
67
- }
68
- /** Option chain; `expiry` is "YYYY-MM-DD". */
69
- async getOptionChain(symbol, expiry) {
70
- const d = new Date(expiry + 'T00:00:00Z');
71
- const expiryMs = d.getTime();
72
- if (Number.isNaN(expiryMs)) {
73
- throw new Error(`invalid expiry date, expected YYYY-MM-DD: ${expiry}`);
74
- }
75
- return this.callInto('option_chain', { option_basic: [{ symbol, expiry: expiryMs }] }, '3.0');
174
+ async getOptionExpiration(symbols, market) {
175
+ const params = { symbols };
176
+ if (market)
177
+ params.market = market;
178
+ return this.callInto('option_expiration', params);
76
179
  }
77
- async getOptionBrief(identifiers) {
180
+ /**
181
+ * Option chain; each item is [symbol, "YYYY-MM-DD"].
182
+ *
183
+ * @param timezone - Optional IANA timezone for expiry conversion (e.g. 'America/New_York').
184
+ * If omitted, defaults to America/New_York for US symbols and Asia/Hong_Kong for .HK symbols.
185
+ * @param returnGreekValue - Whether to return Greeks (delta/gamma/theta/vega/rho).
186
+ * @param optionFilter - Optional filter for in-the-money status, IV range, open interest range, Greeks ranges.
187
+ */
188
+ async getOptionChain(items, timezone, returnGreekValue, optionFilter) {
189
+ const optionBasic = items.map(([symbol, expiry]) => {
190
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(expiry)) {
191
+ throw new Error(`invalid expiry date, expected YYYY-MM-DD: ${expiry}`);
192
+ }
193
+ const tz = resolveOptionTimezone(timezone, symbol);
194
+ const expiryMs = localMidnightMs(expiry, tz);
195
+ return { symbol, expiry: expiryMs };
196
+ });
197
+ const body = { option_basic: optionBasic };
198
+ if (returnGreekValue !== undefined)
199
+ body['return_greek_value'] = returnGreekValue;
200
+ if (optionFilter !== undefined)
201
+ body['option_filter'] = optionFilter;
202
+ return this.callInto('option_chain', body, '3.0');
203
+ }
204
+ /**
205
+ * Option K-line by OCC-style identifier.
206
+ *
207
+ * @param timezone - Optional IANA timezone for expiry conversion (e.g. 'America/New_York').
208
+ * If omitted, defaults to America/New_York for US symbols and Asia/Hong_Kong for .HK symbols.
209
+ * @param limit - Maximum number of bars to return.
210
+ * @param sortDir - Sort direction ('asc' or 'desc').
211
+ */
212
+ async getOptionKline(identifiers, period, beginTime = -1, endTime = -1, timezone, limit, sortDir) {
213
+ const resolvedBegin = beginTime === 0 ? -1 : beginTime;
214
+ const resolvedEnd = endTime === 0 ? -1 : endTime;
215
+ const optionQuery = identifiers.map((id) => {
216
+ const p = parseOptionIdentifier(id, timezone);
217
+ const entry = {
218
+ symbol: p.symbol,
219
+ expiry: p.expiryMs,
220
+ right: p.right,
221
+ strike: p.strike,
222
+ period,
223
+ begin_time: resolvedBegin,
224
+ end_time: resolvedEnd,
225
+ };
226
+ if (limit !== undefined && limit > 0)
227
+ entry['limit'] = limit;
228
+ if (sortDir !== undefined && sortDir !== '')
229
+ entry['sort_dir'] = sortDir;
230
+ return entry;
231
+ });
232
+ return this.callInto('option_kline', { option_query: optionQuery }, '2.0');
233
+ }
234
+ /**
235
+ * Real-time option quotes by OCC-style identifier.
236
+ *
237
+ * @param timezone - Optional IANA timezone for expiry conversion (e.g. 'America/New_York').
238
+ * If omitted, defaults to America/New_York for US symbols and Asia/Hong_Kong for .HK symbols.
239
+ */
240
+ async getOptionQuote(identifiers, timezone) {
78
241
  const optionBasic = identifiers.map((id) => {
79
- const p = parseOptionIdentifier(id);
242
+ const p = parseOptionIdentifier(id, timezone);
80
243
  return { symbol: p.symbol, expiry: p.expiryMs, right: p.right, strike: p.strike };
81
244
  });
82
245
  return this.callInto('option_brief', { option_basic: optionBasic }, '2.0');
83
246
  }
84
- async getOptionKline(identifier, period) {
85
- const p = parseOptionIdentifier(identifier);
86
- return this.callInto('option_kline', {
87
- option_query: [{ symbol: p.symbol, expiry: p.expiryMs, right: p.right, strike: p.strike, period }],
88
- }, '2.0');
247
+ /** @deprecated Use getOptionQuote instead. */
248
+ async getOptionBrief(identifiers) {
249
+ return this.getOptionQuote(identifiers);
89
250
  }
90
251
  // === Futures ===
91
252
  async getFutureExchange() {
@@ -94,17 +255,9 @@ export class QuoteClient {
94
255
  async getFutureContracts(exchange) {
95
256
  return this.callInto('future_contract_by_exchange_code', { exchangeCode: exchange });
96
257
  }
97
- async getFutureRealTimeQuote(contractCodes) {
98
- return this.callInto('future_real_time_quote', { contractCodes });
99
- }
100
- /** Futures K-line; use -1 for unbounded beginTime / endTime. */
101
- async getFutureKline(req) {
102
- const body = {
103
- ...req,
104
- beginTime: req.beginTime ?? -1,
105
- endTime: req.endTime ?? -1,
106
- };
107
- return this.callInto('future_kline', body);
258
+ /** Real-time futures quotes. wire: future_real_time_quote */
259
+ async getFutureRealTimeQuote(req) {
260
+ return this.callInto('future_real_time_quote', req);
108
261
  }
109
262
  // === Fundamentals ===
110
263
  async getFinancialDaily(req) {
@@ -136,4 +289,360 @@ export class QuoteClient {
136
289
  async grabQuotePermission() {
137
290
  return this.callInto('grab_quote_permission');
138
291
  }
292
+ // ==========================================================================
293
+ // Batch 3: stock basics + time series
294
+ // ==========================================================================
295
+ /** All symbol codes (string list). wire: all_symbols */
296
+ async getSymbols(req) {
297
+ return this.callInto('all_symbols', req);
298
+ }
299
+ /** All symbols with names. wire: all_symbol_names */
300
+ async getSymbolNames(req) {
301
+ return this.callInto('all_symbol_names', req);
302
+ }
303
+ /** Trade meta (lot size / tick size). wire: quote_stock_trade */
304
+ async getTradeMetas(req) {
305
+ return this.callInto('quote_stock_trade', req);
306
+ }
307
+ /** Stock details. wire: stock_detail. Server returns {items:[...]}. */
308
+ async getStockDetails(req) {
309
+ return this.callIntoItems('stock_detail', req);
310
+ }
311
+ /** Delayed stock quotes. wire: quote_delay */
312
+ async getDelayedQuote(req) {
313
+ return this.callInto('quote_delay', req);
314
+ }
315
+ /** @deprecated Use getDelayedQuote instead. */
316
+ async getStockDelayBriefs(req) {
317
+ return this.getDelayedQuote(req);
318
+ }
319
+ /** Client-side paginated K-line fetch. Loops until totalSize bars are collected, oldest-first. */
320
+ async getKlineByPage(req) {
321
+ const pageSize = req.pageSize && req.pageSize > 0 ? req.pageSize : 200;
322
+ const totalSize = req.totalSize && req.totalSize > 0 ? req.totalSize : 1000;
323
+ let beginTime = req.beginTime ?? -1;
324
+ let endTime = req.endTime ?? -1;
325
+ if (beginTime === 0)
326
+ beginTime = -1;
327
+ if (endTime === 0)
328
+ endTime = -1;
329
+ const acc = [];
330
+ while (acc.length < totalSize) {
331
+ const sub = {
332
+ symbols: req.symbol ? [req.symbol] : undefined,
333
+ secType: req.secType,
334
+ period: req.period,
335
+ right: req.right,
336
+ beginTime,
337
+ endTime,
338
+ limit: pageSize,
339
+ tradeSession: req.tradeSession,
340
+ lang: req.lang,
341
+ };
342
+ const pageOut = await this.callInto('kline', sub);
343
+ if (!pageOut || pageOut.length === 0 || !pageOut[0].items || pageOut[0].items.length === 0) {
344
+ break;
345
+ }
346
+ const items = pageOut[0].items;
347
+ acc.push(...items);
348
+ if (items.length < pageSize)
349
+ break;
350
+ let oldest = items[0].time;
351
+ for (const it of items) {
352
+ if (it.time < oldest)
353
+ oldest = it.time;
354
+ }
355
+ endTime = oldest - 1;
356
+ }
357
+ return acc;
358
+ }
359
+ /** Historical intraday timeline. wire: history_timeline */
360
+ async getTimelineHistory(req) {
361
+ return this.callInto('history_timeline', req);
362
+ }
363
+ /** Trade rank (top movers / volume). wire: trade_rank */
364
+ async getTradeRank(req) {
365
+ return this.callInto('trade_rank', req);
366
+ }
367
+ /** Short interest / shortable. wire: quote_shortable_stocks */
368
+ async getShortInterest(req) {
369
+ return this.callInto('quote_shortable_stocks', req);
370
+ }
371
+ /** Broker queue. wire: stock_broker */
372
+ async getStockBroker(req) {
373
+ return this.callInto('stock_broker', req);
374
+ }
375
+ /** Stock fundamentals (server returns grouped map). wire: stock_fundamental */
376
+ async getStockFundamental(req) {
377
+ const out = await this.callInto('stock_fundamental', req);
378
+ return out ?? {};
379
+ }
380
+ /** Stock industry classification (array). wire: stock_industry */
381
+ async getStockIndustry(req) {
382
+ return this.callInto('stock_industry', req);
383
+ }
384
+ /** Market data permission entries. wire: get_quote_permission */
385
+ async getQuotePermission(req) {
386
+ return this.callInto('get_quote_permission', req);
387
+ }
388
+ /** K-line quota usage. wire: kline_quota */
389
+ async getKlineQuota(req) {
390
+ return this.callInto('kline_quota', req);
391
+ }
392
+ // ==========================================================================
393
+ // Batch 4: option / future extensions
394
+ // ==========================================================================
395
+ /** Option tick trades. wire: option_trade_tick
396
+ *
397
+ * Server expects `biz_content` as a top-level JSON array (matches Java's
398
+ * `BatchApiModel` and Python's `MultipleContractParams.to_openapi_dict`).
399
+ * We unwrap the request here so the array is emitted directly instead of
400
+ * `{"contracts": [...]}`. Sending it as an object triggers
401
+ * `biz param error(failed to parse parameters in 'biz_content')`.
402
+ */
403
+ async getOptionTradeTicks(req) {
404
+ return this.callInto('option_trade_tick', req.contracts ?? []);
405
+ }
406
+ /** Option intraday timeline. wire: option_timeline */
407
+ async getOptionTimeline(req) {
408
+ return this.callInto('option_timeline', req);
409
+ }
410
+ /** Option depth. wire: option_depth */
411
+ async getOptionDepth(req) {
412
+ return this.callInto('option_depth', req);
413
+ }
414
+ /** Available option symbols. wire: option_symbol */
415
+ async getOptionSymbols(req) {
416
+ return this.callInto('option_symbol', req);
417
+ }
418
+ /** Option analysis (volatility). wire: option_analysis */
419
+ async getOptionAnalysis(req) {
420
+ return this.callInto('option_analysis', req);
421
+ }
422
+ /** Single futures contract by code. wire: future_contract_by_contract_code */
423
+ async getFutureContract(req) {
424
+ return this.callIntoListOrObject('future_contract_by_contract_code', req);
425
+ }
426
+ /** All futures contracts. wire: future_contracts */
427
+ async getAllFutureContracts(req) {
428
+ return this.callInto('future_contracts', req);
429
+ }
430
+ /** Current main contract. wire: future_current_contract */
431
+ async getCurrentFutureContract(req) {
432
+ return this.callInto('future_current_contract', req);
433
+ }
434
+ /** Continuous main contracts. wire: future_continuous_contracts */
435
+ async getFutureContinuousContracts(req) {
436
+ return this.callIntoListOrObject('future_continuous_contracts', req);
437
+ }
438
+ /** Historical main contracts. wire: future_main_contract */
439
+ async getFutureHistoryMainContract(req) {
440
+ return this.callInto('future_main_contract', req);
441
+ }
442
+ /** Futures K-line. wire: future_kline
443
+ * beginTime / endTime default to -1 when unset (server requires them present).
444
+ * Server expects `contract_codes` (plural) — normalize singular `contractCode`
445
+ * to the plural form so callers can pass either shape. */
446
+ async getFutureKline(req) {
447
+ const contractCodes = req.contractCodes
448
+ ?? (req.contractCode ? [req.contractCode] : undefined);
449
+ const { contractCode: _drop, ...rest } = req;
450
+ const body = {
451
+ ...rest,
452
+ ...(contractCodes ? { contractCodes } : {}),
453
+ beginTime: req.beginTime ?? -1,
454
+ endTime: req.endTime ?? -1,
455
+ };
456
+ return this.callInto('future_kline', body);
457
+ }
458
+ /** Client-side paginated futures K-line fetch. */
459
+ async getFutureKlineByPage(req) {
460
+ const pageSize = req.pageSize && req.pageSize > 0 ? req.pageSize : 200;
461
+ const totalSize = req.totalSize && req.totalSize > 0 ? req.totalSize : 1000;
462
+ let beginTime = req.beginTime ?? -1;
463
+ let endTime = req.endTime ?? -1;
464
+ if (beginTime === 0)
465
+ beginTime = -1;
466
+ if (endTime === 0)
467
+ endTime = -1;
468
+ const acc = [];
469
+ while (acc.length < totalSize) {
470
+ // Server rejects singular `contract_code` — send the plural form.
471
+ const sub = {
472
+ contractCodes: req.contractCode ? [req.contractCode] : undefined,
473
+ period: req.period,
474
+ beginTime,
475
+ endTime,
476
+ limit: pageSize,
477
+ lang: req.lang,
478
+ };
479
+ const pageOut = await this.callInto('future_kline', sub);
480
+ if (!pageOut || pageOut.length === 0 || !pageOut[0].items || pageOut[0].items.length === 0) {
481
+ break;
482
+ }
483
+ const items = pageOut[0].items;
484
+ acc.push(...items);
485
+ if (items.length < pageSize)
486
+ break;
487
+ let oldest = items[0].time;
488
+ for (const it of items) {
489
+ if (it.time < oldest)
490
+ oldest = it.time;
491
+ }
492
+ endTime = oldest - 1;
493
+ }
494
+ return acc;
495
+ }
496
+ /** Futures tick trades. wire: future_tick (API v3.0)
497
+ * Server returns {contractCode, items:[...]}; unwrap items and backfill contractCode.
498
+ * endIndex defaults to 30 when not set (consistent with Python/Go SDK). */
499
+ async getFutureTradeTicks(req) {
500
+ if (!req.endIndex)
501
+ req.endIndex = 30;
502
+ const wrap = await this.callInto('future_tick', req, '3.0');
503
+ const items = wrap?.items ?? [];
504
+ if (wrap?.contractCode) {
505
+ for (const item of items) {
506
+ if (!item.contractCode)
507
+ item.contractCode = wrap.contractCode;
508
+ }
509
+ }
510
+ return items;
511
+ }
512
+ /** Futures depth. wire: future_depth */
513
+ async getFutureDepth(req) {
514
+ return this.callInto('future_depth', req);
515
+ }
516
+ /** Futures trading times (single-object response). wire: future_trading_date */
517
+ async getFutureTradingTimes(req) {
518
+ return this.callInto('future_trading_date', req);
519
+ }
520
+ // ==========================================================================
521
+ // Batch 5: fund / warrant / industry / corporate / financial / calendar
522
+ // ==========================================================================
523
+ /** Fund symbols. wire: fund_all_symbols */
524
+ async getFundSymbols(req) {
525
+ return this.callInto('fund_all_symbols', req);
526
+ }
527
+ /** Fund contracts. wire: fund_contracts */
528
+ async getFundContracts(req) {
529
+ return this.callInto('fund_contracts', req);
530
+ }
531
+ /** Fund real-time NAV. wire: fund_quote */
532
+ async getFundQuote(req) {
533
+ return this.callInto('fund_quote', req);
534
+ }
535
+ /** Fund historical NAV. wire: fund_history_quote */
536
+ async getFundHistoryQuote(req) {
537
+ return this.callInto('fund_history_quote', req);
538
+ }
539
+ /** Real-time warrant quotes. wire: warrant_briefs */
540
+ async getWarrantQuote(req) {
541
+ return this.callInto('warrant_briefs', req);
542
+ }
543
+ /** @deprecated Use getWarrantQuote instead. */
544
+ async getWarrantBriefs(req) {
545
+ return this.getWarrantQuote(req);
546
+ }
547
+ /** Warrant filter (paged). wire: warrant_filter */
548
+ async getWarrantFilter(req) {
549
+ return this.callInto('warrant_filter', req);
550
+ }
551
+ /** Industry list. wire: industry_list
552
+ *
553
+ * `industryLevel` is required by the server — omitting it returns
554
+ * `industry level error, all supported is: [GSECTOR, GGROUP, GIND, GSUBIND]`.
555
+ * Defaults to `GGROUP` when unset, matching Python SDK's
556
+ * `IndustryLevel.GGROUP` default.
557
+ *
558
+ * Wire fields differ from other endpoints (see `IndustryItem`): server sends
559
+ * `nameCN` / `nameEN` / `industryLevel`. This method hydrates the
560
+ * backwards-compat `name` (from `nameEN || nameCN`) and mirrors
561
+ * `industryLevel` to `level` so existing callers keep working.
562
+ */
563
+ async getIndustryList(req = {}) {
564
+ const payload = { industryLevel: 'GGROUP', ...req };
565
+ const items = await this.callInto('industry_list', payload);
566
+ if (!Array.isArray(items))
567
+ return [];
568
+ for (const it of items) {
569
+ if (it.name === undefined)
570
+ it.name = it.nameEN || it.nameCN;
571
+ if (it.level === undefined)
572
+ it.level = it.industryLevel;
573
+ }
574
+ return items;
575
+ }
576
+ /** Stocks inside an industry. wire: industry_stock_list */
577
+ async getIndustryStocks(req) {
578
+ return this.callInto('industry_stock_list', req);
579
+ }
580
+ /** Corporate split (flattened). wire: corporate_action (action_type=split) */
581
+ async getCorporateSplit(req) {
582
+ const body = { ...req, actionType: 'split' };
583
+ const grouped = await this.callInto('corporate_action', body);
584
+ if (!grouped || typeof grouped !== 'object')
585
+ return [];
586
+ return Object.values(grouped).flat();
587
+ }
588
+ /** Corporate dividend (flattened). wire: corporate_action (action_type=dividend) */
589
+ async getCorporateDividend(req) {
590
+ const body = { ...req, actionType: 'dividend' };
591
+ const grouped = await this.callInto('corporate_action', body);
592
+ if (!grouped || typeof grouped !== 'object')
593
+ return [];
594
+ return Object.values(grouped).flat();
595
+ }
596
+ /** Corporate earnings calendar (flattened). wire: corporate_action (action_type=earning) */
597
+ async getCorporateEarningsCalendar(req) {
598
+ const body = { ...req, actionType: 'earning' };
599
+ const grouped = await this.callInto('corporate_action', body);
600
+ if (!grouped || typeof grouped !== 'object')
601
+ return [];
602
+ return Object.values(grouped).flat();
603
+ }
604
+ /** Corporate symbol change (flattened). wire: corporate_action (action_type=symbol_change) */
605
+ async getCorporateSymbolChange(req) {
606
+ const body = { ...req, actionType: 'symbol_change' };
607
+ const grouped = await this.callInto('corporate_action', body);
608
+ if (!grouped || typeof grouped !== 'object')
609
+ return [];
610
+ return Object.values(grouped).flat();
611
+ }
612
+ /** Corporate delisting (flattened). wire: corporate_action (action_type=delisting) */
613
+ async getCorporateDelisting(req) {
614
+ const body = { ...req, actionType: 'delisting' };
615
+ const grouped = await this.callInto('corporate_action', body);
616
+ if (!grouped || typeof grouped !== 'object')
617
+ return [];
618
+ return Object.values(grouped).flat();
619
+ }
620
+ /** Corporate IPO (flattened). wire: corporate_action (action_type=ipo) */
621
+ async getCorporateIPO(req) {
622
+ const body = { ...req, actionType: 'ipo' };
623
+ const grouped = await this.callInto('corporate_action', body);
624
+ if (!grouped || typeof grouped !== 'object')
625
+ return [];
626
+ return Object.values(grouped).flat();
627
+ }
628
+ /** Financial currency per symbol. wire: financial_currency */
629
+ async getFinancialCurrency(req) {
630
+ return this.callInto('financial_currency', req);
631
+ }
632
+ /** FX rates. wire: financial_exchange_rate */
633
+ async getFinancialExchangeRate(req) {
634
+ return this.callInto('financial_exchange_rate', req);
635
+ }
636
+ /** Trading calendar. wire: trading_calendar */
637
+ async getTradingCalendar(req) {
638
+ return this.callInto('trading_calendar', req);
639
+ }
640
+ /** Available market-scanner tags. wire: market_scanner_tags */
641
+ async getMarketScannerTags(req) {
642
+ return this.callInto('market_scanner_tags', req);
643
+ }
644
+ /** Overnight quote. wire: quote_overnight */
645
+ async getQuoteOvernight(req) {
646
+ return this.callInto('quote_overnight', req);
647
+ }
139
648
  }
@@ -1,5 +1,5 @@
1
1
  /**
2
2
  * 认证层(RSA Signer)统一导出
3
3
  */
4
- export { loadPrivateKey, signWithRSA, verifyWithRSA } from './signer';
5
- export { getSignContent } from './sign-content';
4
+ export { loadPrivateKey, signWithRSA, verifyWithRSA } from './signer.js';
5
+ export { getSignContent } from './sign-content.js';
@@ -1,4 +1,4 @@
1
1
  /**
2
2
  * 交易模块导出
3
3
  */
4
- export { TradeClient } from './trade-client';
4
+ export { TradeClient } from './trade-client.js';