tigeropen 0.4.0 → 0.5.7

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 (116) hide show
  1. package/README.md +82 -2
  2. package/dist/cjs/auth/authentication.js +74 -0
  3. package/dist/cjs/auth/index.js +24 -0
  4. package/dist/cjs/auth/oauth2/client-registration.js +44 -0
  5. package/dist/cjs/auth/oauth2/device-authorization.js +40 -0
  6. package/dist/cjs/auth/oauth2/errors.js +64 -0
  7. package/dist/cjs/auth/oauth2/http-utils.js +112 -0
  8. package/dist/cjs/auth/oauth2/index.js +42 -0
  9. package/dist/cjs/auth/oauth2/loopback-receiver.js +215 -0
  10. package/dist/cjs/auth/oauth2/metadata.js +34 -0
  11. package/dist/cjs/auth/oauth2/oauth2-authentication.js +74 -0
  12. package/dist/cjs/auth/oauth2/session-manager.js +762 -0
  13. package/dist/cjs/auth/oauth2/token-store.js +252 -0
  14. package/dist/cjs/auth/oauth2/token.js +76 -0
  15. package/dist/cjs/client/api-response.js +28 -7
  16. package/dist/cjs/client/case-convert.js +4 -3
  17. package/dist/cjs/client/http-client.js +124 -8
  18. package/dist/cjs/client/token-methods.js +42 -0
  19. package/dist/cjs/config/client-config.js +115 -16
  20. package/dist/cjs/config/config-parser.js +19 -9
  21. package/dist/cjs/config/index.js +4 -1
  22. package/dist/cjs/config/token-manager.js +54 -4
  23. package/dist/cjs/index.js +53 -2
  24. package/dist/cjs/model/enums.js +18 -1
  25. package/dist/cjs/model/order-helpers.js +149 -0
  26. package/dist/cjs/push/index.js +1 -0
  27. package/dist/cjs/push/pb/Request.js +12 -1
  28. package/dist/cjs/push/proto-message.js +5 -1
  29. package/dist/cjs/push/push-client.js +69 -25
  30. package/dist/cjs/push/tick-util.js +172 -0
  31. package/dist/cjs/quote/quote-client.js +300 -70
  32. package/dist/cjs/trade/trade-client.js +186 -16
  33. package/dist/cjs/version.js +4 -0
  34. package/dist/esm/auth/authentication.js +68 -0
  35. package/dist/esm/auth/index.js +3 -0
  36. package/dist/esm/auth/oauth2/client-registration.js +40 -0
  37. package/dist/esm/auth/oauth2/device-authorization.js +36 -0
  38. package/dist/esm/auth/oauth2/errors.js +59 -0
  39. package/dist/esm/auth/oauth2/http-utils.js +105 -0
  40. package/dist/esm/auth/oauth2/index.js +11 -0
  41. package/dist/esm/auth/oauth2/loopback-receiver.js +178 -0
  42. package/dist/esm/auth/oauth2/metadata.js +30 -0
  43. package/dist/esm/auth/oauth2/oauth2-authentication.js +70 -0
  44. package/dist/esm/auth/oauth2/session-manager.js +725 -0
  45. package/dist/esm/auth/oauth2/token-store.js +214 -0
  46. package/dist/esm/auth/oauth2/token.js +71 -0
  47. package/dist/esm/client/api-request.js +1 -1
  48. package/dist/esm/client/api-response.js +29 -8
  49. package/dist/esm/client/case-convert.js +4 -3
  50. package/dist/esm/client/http-client.js +128 -12
  51. package/dist/esm/client/index.js +6 -6
  52. package/dist/esm/client/token-methods.js +37 -0
  53. package/dist/esm/config/client-config.js +118 -20
  54. package/dist/esm/config/config-parser.js +19 -9
  55. package/dist/esm/config/index.js +4 -3
  56. package/dist/esm/config/token-manager.js +55 -5
  57. package/dist/esm/index.js +15 -1
  58. package/dist/esm/logger/index.js +1 -1
  59. package/dist/esm/model/contract-helpers.js +1 -1
  60. package/dist/esm/model/enums.js +17 -0
  61. package/dist/esm/model/order-helpers.js +142 -1
  62. package/dist/esm/model/order-status.js +1 -1
  63. package/dist/esm/package.json +3 -0
  64. package/dist/esm/push/index.js +6 -5
  65. package/dist/esm/push/pb/PushData.js +11 -11
  66. package/dist/esm/push/pb/QuoteBasicData.js +1 -1
  67. package/dist/esm/push/pb/Request.js +12 -1
  68. package/dist/esm/push/pb/Response.js +1 -1
  69. package/dist/esm/push/pb/index.js +17 -17
  70. package/dist/esm/push/proto-message.js +8 -4
  71. package/dist/esm/push/push-client.js +76 -32
  72. package/dist/esm/push/tick-util.js +165 -0
  73. package/dist/esm/quote/index.js +1 -1
  74. package/dist/esm/quote/quote-client.js +269 -72
  75. package/dist/esm/signer/index.js +2 -2
  76. package/dist/esm/trade/index.js +1 -1
  77. package/dist/esm/trade/trade-client.js +156 -19
  78. package/dist/esm/version.js +1 -0
  79. package/dist/types/auth/authentication.d.ts +98 -0
  80. package/dist/types/auth/index.d.ts +4 -0
  81. package/dist/types/auth/oauth2/client-registration.d.ts +32 -0
  82. package/dist/types/auth/oauth2/device-authorization.d.ts +40 -0
  83. package/dist/types/auth/oauth2/errors.d.ts +46 -0
  84. package/dist/types/auth/oauth2/http-utils.d.ts +21 -0
  85. package/dist/types/auth/oauth2/index.d.ts +16 -0
  86. package/dist/types/auth/oauth2/loopback-receiver.d.ts +29 -0
  87. package/dist/types/auth/oauth2/metadata.d.ts +32 -0
  88. package/dist/types/auth/oauth2/oauth2-authentication.d.ts +31 -0
  89. package/dist/types/auth/oauth2/session-manager.d.ts +241 -0
  90. package/dist/types/auth/oauth2/token-store.d.ts +49 -0
  91. package/dist/types/auth/oauth2/token.d.ts +56 -0
  92. package/dist/types/client/api-response.d.ts +6 -4
  93. package/dist/types/client/case-convert.d.ts +3 -1
  94. package/dist/types/client/http-client.d.ts +32 -1
  95. package/dist/types/client/token-methods.d.ts +34 -0
  96. package/dist/types/config/client-config.d.ts +22 -1
  97. package/dist/types/config/index.d.ts +3 -1
  98. package/dist/types/config/token-manager.d.ts +27 -3
  99. package/dist/types/index.d.ts +22 -1
  100. package/dist/types/model/enums.d.ts +18 -2
  101. package/dist/types/model/order-helpers.d.ts +52 -1
  102. package/dist/types/model/order.d.ts +127 -10
  103. package/dist/types/model/quote-requests.d.ts +27 -15
  104. package/dist/types/model/quote.d.ts +151 -24
  105. package/dist/types/model/trade-requests.d.ts +123 -4
  106. package/dist/types/model/trade.d.ts +121 -17
  107. package/dist/types/push/callbacks.d.ts +3 -7
  108. package/dist/types/push/index.d.ts +2 -1
  109. package/dist/types/push/pb/Request.d.ts +1 -0
  110. package/dist/types/push/proto-message.d.ts +4 -1
  111. package/dist/types/push/push-client.d.ts +38 -3
  112. package/dist/types/push/tick-util.d.ts +30 -0
  113. package/dist/types/quote/quote-client.d.ts +101 -36
  114. package/dist/types/trade/trade-client.d.ts +69 -14
  115. package/dist/types/version.d.ts +1 -0
  116. package/package.json +9 -4
@@ -1,5 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SANDBOX_TIGER_PUBLIC_KEY = void 0;
3
4
  exports.loadPropertiesFile = loadPropertiesFile;
4
5
  exports.createClientConfig = createClientConfig;
5
6
  /**
@@ -17,6 +18,7 @@ const path_1 = require("path");
17
18
  const os_1 = require("os");
18
19
  const config_parser_1 = require("./config-parser");
19
20
  const domain_1 = require("./domain");
21
+ const token_manager_1 = require("./token-manager");
20
22
  /** Default config file name */
21
23
  const CONFIG_FILE_NAME = 'tiger_openapi_config.properties';
22
24
  /** Defaults */
@@ -25,11 +27,20 @@ const DEFAULT_TIMEOUT = 15;
25
27
  const DEFAULT_SERVER_URL = 'https://openapi.tigerfintech.com/gateway';
26
28
  /** Tiger public key for response signature verification (Base64-encoded) */
27
29
  const TIGER_PUBLIC_KEY = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDNF3G8SoEcCZh2rshUbayDgLLrj6rKgzNMxDL2HSnKcB0+GPOsndqSv+a4IBu9+I3fyBp5hkyMMG2+AXugd9pMpy6VxJxlNjhX1MYbNTZJUT4nudki4uh+LMOkIBHOceGNXjgB+cXqmlUnjlqha/HgboeHSnSgpM3dKSJQlIOsDwIDAQAB';
30
+ /** Sandbox / QA tiger public key for response signature verification */
31
+ exports.SANDBOX_TIGER_PUBLIC_KEY = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCbm21i11hgAENGd3/f280PSe4g9YGkS3TEXBYMidihTvHHf' +
32
+ '+tJ0PYD0o3PruI0hl3qhEjHTAxb75T5YD3SGK4IBhHn/Rk6mhqlGgI+bBrBVYaXixmHfRo75RpUUuWACyeqQk' +
33
+ 'ZckgR0McxuW9xRMIa2cXZOoL1E4SL4lXKGhKoWbwIDAQAB';
28
34
  /** Environment variable names */
29
35
  const ENV_TIGER_ID = 'TIGEROPEN_TIGER_ID';
30
36
  const ENV_PRIVATE_KEY = 'TIGEROPEN_PRIVATE_KEY';
31
37
  const ENV_ACCOUNT = 'TIGEROPEN_ACCOUNT';
38
+ const ENV_SECRET_KEY = 'TIGEROPEN_SECRET_KEY';
32
39
  const ENV_TOKEN = 'TIGEROPEN_TOKEN';
40
+ const ENV_TOKEN_FILE = 'TIGEROPEN_TOKEN_FILE';
41
+ const ENV_TIGER_PUBLIC_KEY = 'TIGEROPEN_TIGER_PUBLIC_KEY';
42
+ const ENV_SERVER_URL = 'TIGEROPEN_SERVER_URL';
43
+ const ENV_QUOTE_SERVER_URL = 'TIGEROPEN_QUOTE_SERVER_URL';
33
44
  /**
34
45
  * Load and parse a Java-style properties file.
35
46
  *
@@ -102,12 +113,32 @@ function createClientConfig(options) {
102
113
  const opts = options ?? {};
103
114
  // Load properties: explicit path > auto-discovery
104
115
  let fileProps = {};
116
+ let configFileDir;
105
117
  if (opts.propertiesFilePath) {
106
- fileProps = loadPropertiesFile(opts.propertiesFilePath);
118
+ // Support both directory path and full file path
119
+ let filePath = opts.propertiesFilePath;
120
+ if ((0, fs_1.existsSync)(filePath) && (0, fs_1.statSync)(filePath).isDirectory()) {
121
+ configFileDir = filePath;
122
+ filePath = (0, path_1.join)(filePath, CONFIG_FILE_NAME);
123
+ }
124
+ else if (!(0, fs_1.existsSync)(filePath) && !filePath.endsWith('.properties')) {
125
+ // Path doesn't exist as-is; try treating it as a directory
126
+ const asDir = (0, path_1.join)(filePath, CONFIG_FILE_NAME);
127
+ if ((0, fs_1.existsSync)(asDir)) {
128
+ configFileDir = filePath;
129
+ filePath = asDir;
130
+ }
131
+ }
132
+ else {
133
+ // It's a file path: derive directory from it
134
+ configFileDir = (0, path_1.dirname)(filePath);
135
+ }
136
+ fileProps = loadPropertiesFile(filePath);
107
137
  }
108
138
  else {
109
139
  const discovered = discoverConfigFile();
110
140
  if (discovered) {
141
+ configFileDir = (0, path_1.dirname)(discovered);
111
142
  fileProps = loadPropertiesFile(discovered);
112
143
  }
113
144
  }
@@ -115,15 +146,20 @@ function createClientConfig(options) {
115
146
  let tigerId = opts.tigerId || fileProps['tiger_id'] || '';
116
147
  let privateKey = opts.privateKey || resolvePrivateKey(fileProps) || '';
117
148
  let account = opts.account || fileProps['account'] || '';
149
+ let secretKey = opts.secretKey || fileProps['secret_key'] || undefined;
118
150
  let token = opts.token || fileProps['token'];
119
151
  const license = opts.license || fileProps['license'];
120
152
  const language = opts.language || fileProps['language'] || DEFAULT_LANGUAGE;
121
153
  const timezone = opts.timezone || fileProps['timezone'];
154
+ // tiger_public_key from properties file (e.g. for QA/sandbox environments)
155
+ let tigerPublicKey = opts.tigerPublicKey || fileProps['tiger_public_key'] || TIGER_PUBLIC_KEY;
122
156
  // Environment variables override everything
123
157
  const envTigerId = process.env[ENV_TIGER_ID];
124
158
  const envPrivateKey = process.env[ENV_PRIVATE_KEY];
125
159
  const envAccount = process.env[ENV_ACCOUNT];
160
+ const envSecretKey = process.env[ENV_SECRET_KEY];
126
161
  const envToken = process.env[ENV_TOKEN];
162
+ const envTigerPublicKey = process.env[ENV_TIGER_PUBLIC_KEY];
127
163
  if (envTigerId) {
128
164
  tigerId = envTigerId;
129
165
  }
@@ -133,9 +169,47 @@ function createClientConfig(options) {
133
169
  if (envAccount) {
134
170
  account = envAccount;
135
171
  }
172
+ if (envSecretKey) {
173
+ secretKey = envSecretKey;
174
+ }
136
175
  if (envToken) {
137
176
  token = envToken;
138
177
  }
178
+ if (envTigerPublicKey) {
179
+ tigerPublicKey = envTigerPublicKey;
180
+ }
181
+ // Token loading priority: env TIGEROPEN_TOKEN > tokenLoader > token file (TIGEROPEN_TOKEN_FILE or default)
182
+ if (!token) {
183
+ if (opts.tokenLoader) {
184
+ // tokenLoader is async-capable; we do a best-effort synchronous call here.
185
+ // If the loader returns a Promise, the token will be set later via HttpClient.
186
+ try {
187
+ const result = opts.tokenLoader();
188
+ if (result instanceof Promise) {
189
+ // Cannot await in sync constructor; HttpClient.startTokenAutoRefresh() will
190
+ // resolve this Promise and sync the token after construction.
191
+ }
192
+ else if (result) {
193
+ token = result;
194
+ }
195
+ }
196
+ catch {
197
+ // loader failed; leave token undefined
198
+ }
199
+ }
200
+ else {
201
+ // Load from token file: TIGEROPEN_TOKEN_FILE env var > config dir > default
202
+ const tokenFilePath = process.env[ENV_TOKEN_FILE]
203
+ || (configFileDir ? (0, path_1.join)(configFileDir, 'tiger_openapi_token.properties') : 'tiger_openapi_token.properties');
204
+ const tm = new token_manager_1.TokenManager({ filePath: tokenFilePath });
205
+ try {
206
+ token = tm.loadTokenSync();
207
+ }
208
+ catch {
209
+ // file not found or no token field; leave token undefined
210
+ }
211
+ }
212
+ }
139
213
  // Validate required fields
140
214
  if (!tigerId) {
141
215
  throw new Error(`tigerId is required. Set it via options.tigerId, a config file, or the ${ENV_TIGER_ID} environment variable.`);
@@ -143,47 +217,72 @@ function createClientConfig(options) {
143
217
  if (!privateKey) {
144
218
  throw new Error(`privateKey is required. Set it via options.privateKey, a config file, or the ${ENV_PRIVATE_KEY} environment variable.`);
145
219
  }
146
- // Resolve server URL: explicit > dynamic domain > default
220
+ // Resolve server URL: env var > explicit opts > file > dynamic domain > default
147
221
  const enableDynamicDomain = opts.enableDynamicDomain ?? true;
148
222
  let serverUrl;
149
223
  let quoteServerUrl;
150
- if (opts.serverUrl) {
224
+ // Query dynamic domains once (may spawn a child process); reuse for both URLs.
225
+ let domainConf = {};
226
+ const envServerUrl = process.env[ENV_SERVER_URL];
227
+ const envQuoteServerUrl = process.env[ENV_QUOTE_SERVER_URL];
228
+ const needServerUrl = !envServerUrl && !opts.serverUrl && !fileProps['server_url'];
229
+ const needQuoteServerUrl = !envQuoteServerUrl && !opts.quoteServerUrl && !fileProps['quote_server_url'];
230
+ if (enableDynamicDomain && (needServerUrl || needQuoteServerUrl)) {
231
+ domainConf = (0, domain_1.queryDomains)(license);
232
+ }
233
+ if (envServerUrl) {
234
+ serverUrl = envServerUrl;
235
+ }
236
+ else if (opts.serverUrl) {
151
237
  serverUrl = opts.serverUrl;
152
238
  }
239
+ else if (fileProps['server_url']) {
240
+ serverUrl = fileProps['server_url'];
241
+ }
153
242
  else {
154
- let dynamicUrl = '';
155
- if (enableDynamicDomain) {
156
- const domainConf = (0, domain_1.queryDomains)(license);
157
- dynamicUrl = (0, domain_1.resolveDynamicServerUrl)(domainConf, license);
158
- }
243
+ const dynamicUrl = (0, domain_1.resolveDynamicServerUrl)(domainConf, license);
159
244
  serverUrl = dynamicUrl || DEFAULT_SERVER_URL;
160
245
  }
161
- // Resolve quote server URL: explicit > dynamic domain > serverUrl fallback
162
- if (opts.quoteServerUrl) {
246
+ // Resolve quote server URL: env var > explicit opts > file > dynamic domain > serverUrl fallback
247
+ if (envQuoteServerUrl) {
248
+ quoteServerUrl = envQuoteServerUrl;
249
+ }
250
+ else if (opts.quoteServerUrl) {
163
251
  quoteServerUrl = opts.quoteServerUrl;
164
252
  }
253
+ else if (fileProps['quote_server_url']) {
254
+ quoteServerUrl = fileProps['quote_server_url'];
255
+ }
165
256
  else {
166
- let dynamicQuoteUrl = '';
167
- if (enableDynamicDomain) {
168
- const domainConf = (0, domain_1.queryDomains)(license);
169
- dynamicQuoteUrl = (0, domain_1.resolveDynamicQuoteServerUrl)(domainConf, license);
257
+ // Only use dynamic domain if serverUrl itself came from dynamic resolution (not pinned by env/opts/file).
258
+ // When serverUrl is pinned, prefer it as the quote fallback to avoid mixing environments.
259
+ const serverUrlPinned = !!(envServerUrl || opts.serverUrl || fileProps['server_url']);
260
+ if (!serverUrlPinned) {
261
+ const dynamicQuoteUrl = (0, domain_1.resolveDynamicQuoteServerUrl)(domainConf, license);
262
+ quoteServerUrl = dynamicQuoteUrl || serverUrl;
263
+ }
264
+ else {
265
+ quoteServerUrl = serverUrl;
170
266
  }
171
- quoteServerUrl = dynamicQuoteUrl || serverUrl;
172
267
  }
173
268
  return {
174
269
  tigerId,
175
270
  privateKey,
176
271
  account,
272
+ secretKey: secretKey || undefined,
177
273
  license,
178
274
  language,
179
275
  timezone,
180
276
  timeout: opts.timeout ?? DEFAULT_TIMEOUT,
181
277
  token,
182
278
  tokenRefreshDuration: opts.tokenRefreshDuration,
279
+ tokenCheckInterval: opts.tokenCheckInterval,
280
+ tokenLoader: opts.tokenLoader,
281
+ tokenWriter: opts.tokenWriter,
183
282
  serverUrl,
184
283
  quoteServerUrl,
185
284
  deviceId: detectDeviceId(),
186
- tigerPublicKey: TIGER_PUBLIC_KEY,
285
+ tigerPublicKey,
187
286
  };
188
287
  }
189
288
  /**
@@ -70,34 +70,34 @@ function parsePropertiesString(content) {
70
70
  let continuation = false;
71
71
  for (const rawLine of lines) {
72
72
  if (continuation) {
73
- // 续行:去除前导空格后拼接
74
73
  const trimmedLeft = rawLine.replace(/^[ \t]+/, '');
75
- if (trimmedLeft.endsWith('\\')) {
74
+ if (trimmedLeft === '' || trimmedLeft.startsWith('#') || trimmedLeft.startsWith('!')) {
75
+ continuation = false;
76
+ }
77
+ else if (endsWithContinuation(trimmedLeft)) {
76
78
  currentLine += trimmedLeft.slice(0, -1);
77
79
  continue;
78
80
  }
79
- currentLine += trimmedLeft;
80
- continuation = false;
81
+ else {
82
+ currentLine += trimmedLeft;
83
+ continuation = false;
84
+ }
81
85
  }
82
86
  else {
83
87
  const trimmed = rawLine.trim();
84
- // 跳过空行
85
88
  if (trimmed === '') {
86
89
  continue;
87
90
  }
88
- // 跳过注释行
89
91
  if (trimmed.startsWith('#') || trimmed.startsWith('!')) {
90
92
  continue;
91
93
  }
92
- // 检查续行
93
- if (trimmed.endsWith('\\')) {
94
+ if (endsWithContinuation(trimmed)) {
94
95
  currentLine = trimmed.slice(0, -1);
95
96
  continuation = true;
96
97
  continue;
97
98
  }
98
99
  currentLine = trimmed;
99
100
  }
100
- // 解析键值对
101
101
  const result = parseKeyValue(currentLine);
102
102
  if (result) {
103
103
  props[result[0]] = result[1];
@@ -113,6 +113,16 @@ function parsePropertiesString(content) {
113
113
  }
114
114
  return props;
115
115
  }
116
+ /**
117
+ * 判断一行是否以续行标记结尾(奇数个末尾反斜杠)。
118
+ */
119
+ function endsWithContinuation(line) {
120
+ let count = 0;
121
+ for (let i = line.length - 1; i >= 0 && line[i] === '\\'; i--) {
122
+ count++;
123
+ }
124
+ return count % 2 === 1;
125
+ }
116
126
  /**
117
127
  * 解析单行键值对,支持 = 和 : 分隔符。
118
128
  * 值中可以包含 = 或 :,只按第一个分隔符拆分。
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.resolveDynamicQuoteServerUrl = exports.resolveDynamicServerUrl = exports.queryDomains = exports.loadPropertiesFile = exports.createClientConfig = exports.parsePropertiesString = exports.parsePropertiesFile = void 0;
3
+ exports.resolveDynamicQuoteServerUrl = exports.resolveDynamicServerUrl = exports.queryDomains = exports.TokenManager = exports.SANDBOX_TIGER_PUBLIC_KEY = exports.loadPropertiesFile = exports.createClientConfig = exports.parsePropertiesString = exports.parsePropertiesFile = void 0;
4
4
  /**
5
5
  * 配置层导出
6
6
  */
@@ -10,6 +10,9 @@ Object.defineProperty(exports, "parsePropertiesString", { enumerable: true, get:
10
10
  var client_config_1 = require("./client-config");
11
11
  Object.defineProperty(exports, "createClientConfig", { enumerable: true, get: function () { return client_config_1.createClientConfig; } });
12
12
  Object.defineProperty(exports, "loadPropertiesFile", { enumerable: true, get: function () { return client_config_1.loadPropertiesFile; } });
13
+ Object.defineProperty(exports, "SANDBOX_TIGER_PUBLIC_KEY", { enumerable: true, get: function () { return client_config_1.SANDBOX_TIGER_PUBLIC_KEY; } });
14
+ var token_manager_1 = require("./token-manager");
15
+ Object.defineProperty(exports, "TokenManager", { enumerable: true, get: function () { return token_manager_1.TokenManager; } });
13
16
  var domain_1 = require("./domain");
14
17
  Object.defineProperty(exports, "queryDomains", { enumerable: true, get: function () { return domain_1.queryDomains; } });
15
18
  Object.defineProperty(exports, "resolveDynamicServerUrl", { enumerable: true, get: function () { return domain_1.resolveDynamicServerUrl; } });
@@ -21,6 +21,7 @@ class TokenManager {
21
21
  constructor(options) {
22
22
  this.token = '';
23
23
  this.timer = null;
24
+ this.fileEnabled = options?.filePath !== undefined;
24
25
  this.filePath = options?.filePath ?? DEFAULT_TOKEN_FILE;
25
26
  this.refreshInterval = options?.refreshInterval ?? DEFAULT_REFRESH_INTERVAL;
26
27
  let dur = options?.refreshDuration ?? 0;
@@ -28,9 +29,39 @@ class TokenManager {
28
29
  dur = 30;
29
30
  }
30
31
  this.refreshDuration = dur;
32
+ this.tokenLoader = options?.tokenLoader;
33
+ this.tokenWriter = options?.tokenWriter;
31
34
  }
32
- /** 从 properties 文件加载 Token */
33
- loadToken() {
35
+ /**
36
+ * 从 properties 文件(或自定义 tokenLoader)加载 Token。
37
+ * 若设置了 tokenLoader,优先调用;否则从 properties 文件读取。
38
+ */
39
+ async loadToken() {
40
+ if (this.tokenLoader) {
41
+ const token = await this.tokenLoader();
42
+ if (!token) {
43
+ throw new Error('自定义 tokenLoader 返回空值');
44
+ }
45
+ this.token = token;
46
+ return token;
47
+ }
48
+ const content = (0, fs_1.readFileSync)(this.filePath, 'utf-8');
49
+ const props = (0, config_parser_1.parsePropertiesString)(content);
50
+ const token = props['token'];
51
+ if (!token) {
52
+ throw new Error('Token 文件中未找到 token 字段');
53
+ }
54
+ this.token = token;
55
+ return token;
56
+ }
57
+ /**
58
+ * 同步版文件加载(仅用于无 tokenLoader 时的兼容入口)。
59
+ * 建议优先使用 loadToken()(异步)。
60
+ */
61
+ loadTokenSync() {
62
+ if (this.tokenLoader) {
63
+ throw new Error('tokenLoader 是异步函数,请使用 loadToken()');
64
+ }
34
65
  const content = (0, fs_1.readFileSync)(this.filePath, 'utf-8');
35
66
  const props = (0, config_parser_1.parsePropertiesString)(content);
36
67
  const token = props['token'];
@@ -44,10 +75,25 @@ class TokenManager {
44
75
  getToken() {
45
76
  return this.token;
46
77
  }
47
- /** 设置 Token 并更新文件 */
78
+ /**
79
+ * 设置 Token;若启用了文件持久化(显式传入 filePath),则同步写文件。
80
+ * 成功后触发 tokenWriter 回调(如有)。
81
+ */
48
82
  setToken(token) {
49
83
  this.token = token;
50
- this.saveTokenToFile(token);
84
+ if (this.fileEnabled) {
85
+ this.saveTokenToFile(token);
86
+ }
87
+ if (this.tokenWriter) {
88
+ this.tokenWriter(token);
89
+ }
90
+ }
91
+ /**
92
+ * 仅更新内存中的 token,不写文件,不触发 tokenWriter 回调。
93
+ * 用于多个组件共享 token 时的内部同步。
94
+ */
95
+ syncToken(token) {
96
+ this.token = token;
51
97
  }
52
98
  /** 将 Token 保存到 properties 文件 */
53
99
  saveTokenToFile(token) {
@@ -104,6 +150,10 @@ class TokenManager {
104
150
  // 刷新失败时静默跳过
105
151
  }
106
152
  }, this.refreshInterval);
153
+ // 防止 timer 阻止 Node.js 进程退出
154
+ if (this.timer.unref) {
155
+ this.timer.unref();
156
+ }
107
157
  }
108
158
  /** 停止后台刷新 */
109
159
  stopAutoRefresh() {
package/dist/cjs/index.js CHANGED
@@ -16,6 +16,57 @@
16
16
  * @packageDocumentation
17
17
  */
18
18
  Object.defineProperty(exports, "__esModule", { value: true });
19
- exports.VERSION = void 0;
19
+ exports.orderStatusCode = exports.BarPeriod = exports.License = exports.Language = exports.FinancialReportPeriod = exports.OptionAnalysisPeriod = exports.SortDirection = exports.IndustryLevel = exports.CorporateActionType = exports.OrderSortBy = exports.SegmentType = exports.QuoteRight = exports.Currency = exports.Market = exports.TimeInForce = exports.OrderType = exports.SecurityType = exports.OrderStatus = exports.normalizeOrderStatus = exports.stopLimitOrder = exports.stopOrder = exports.limitOrder = exports.marketOrder = exports.SubjectType = exports.ConnectionState = exports.PushClient = exports.TradeClient = exports.parseOptionIdentifier = exports.QuoteClient = exports.classifyErrorCode = exports.TigerError = exports.HttpClient = exports.TokenManager = exports.SANDBOX_TIGER_PUBLIC_KEY = exports.loadPropertiesFile = exports.createClientConfig = exports.VERSION = void 0;
20
20
  /** SDK 版本号 */
21
- exports.VERSION = '0.4.0';
21
+ var version_1 = require("./version");
22
+ Object.defineProperty(exports, "VERSION", { enumerable: true, get: function () { return version_1.SDK_VERSION; } });
23
+ // Config
24
+ var config_1 = require("./config");
25
+ Object.defineProperty(exports, "createClientConfig", { enumerable: true, get: function () { return config_1.createClientConfig; } });
26
+ Object.defineProperty(exports, "loadPropertiesFile", { enumerable: true, get: function () { return config_1.loadPropertiesFile; } });
27
+ Object.defineProperty(exports, "SANDBOX_TIGER_PUBLIC_KEY", { enumerable: true, get: function () { return config_1.SANDBOX_TIGER_PUBLIC_KEY; } });
28
+ var config_2 = require("./config");
29
+ Object.defineProperty(exports, "TokenManager", { enumerable: true, get: function () { return config_2.TokenManager; } });
30
+ // Transport
31
+ var client_1 = require("./client");
32
+ Object.defineProperty(exports, "HttpClient", { enumerable: true, get: function () { return client_1.HttpClient; } });
33
+ var client_2 = require("./client");
34
+ Object.defineProperty(exports, "TigerError", { enumerable: true, get: function () { return client_2.TigerError; } });
35
+ Object.defineProperty(exports, "classifyErrorCode", { enumerable: true, get: function () { return client_2.classifyErrorCode; } });
36
+ // Clients
37
+ var quote_1 = require("./quote");
38
+ Object.defineProperty(exports, "QuoteClient", { enumerable: true, get: function () { return quote_1.QuoteClient; } });
39
+ Object.defineProperty(exports, "parseOptionIdentifier", { enumerable: true, get: function () { return quote_1.parseOptionIdentifier; } });
40
+ var trade_1 = require("./trade");
41
+ Object.defineProperty(exports, "TradeClient", { enumerable: true, get: function () { return trade_1.TradeClient; } });
42
+ var push_1 = require("./push");
43
+ Object.defineProperty(exports, "PushClient", { enumerable: true, get: function () { return push_1.PushClient; } });
44
+ Object.defineProperty(exports, "ConnectionState", { enumerable: true, get: function () { return push_1.ConnectionState; } });
45
+ Object.defineProperty(exports, "SubjectType", { enumerable: true, get: function () { return push_1.SubjectType; } });
46
+ var order_helpers_1 = require("./model/order-helpers");
47
+ Object.defineProperty(exports, "marketOrder", { enumerable: true, get: function () { return order_helpers_1.marketOrder; } });
48
+ Object.defineProperty(exports, "limitOrder", { enumerable: true, get: function () { return order_helpers_1.limitOrder; } });
49
+ Object.defineProperty(exports, "stopOrder", { enumerable: true, get: function () { return order_helpers_1.stopOrder; } });
50
+ Object.defineProperty(exports, "stopLimitOrder", { enumerable: true, get: function () { return order_helpers_1.stopLimitOrder; } });
51
+ var order_status_1 = require("./model/order-status");
52
+ Object.defineProperty(exports, "normalizeOrderStatus", { enumerable: true, get: function () { return order_status_1.normalizeOrderStatus; } });
53
+ // Enums
54
+ var enums_1 = require("./model/enums");
55
+ Object.defineProperty(exports, "OrderStatus", { enumerable: true, get: function () { return enums_1.OrderStatus; } });
56
+ Object.defineProperty(exports, "SecurityType", { enumerable: true, get: function () { return enums_1.SecurityType; } });
57
+ Object.defineProperty(exports, "OrderType", { enumerable: true, get: function () { return enums_1.OrderType; } });
58
+ Object.defineProperty(exports, "TimeInForce", { enumerable: true, get: function () { return enums_1.TimeInForce; } });
59
+ Object.defineProperty(exports, "Market", { enumerable: true, get: function () { return enums_1.Market; } });
60
+ Object.defineProperty(exports, "Currency", { enumerable: true, get: function () { return enums_1.Currency; } });
61
+ Object.defineProperty(exports, "QuoteRight", { enumerable: true, get: function () { return enums_1.QuoteRight; } });
62
+ Object.defineProperty(exports, "SegmentType", { enumerable: true, get: function () { return enums_1.SegmentType; } });
63
+ Object.defineProperty(exports, "OrderSortBy", { enumerable: true, get: function () { return enums_1.OrderSortBy; } });
64
+ Object.defineProperty(exports, "CorporateActionType", { enumerable: true, get: function () { return enums_1.CorporateActionType; } });
65
+ Object.defineProperty(exports, "IndustryLevel", { enumerable: true, get: function () { return enums_1.IndustryLevel; } });
66
+ Object.defineProperty(exports, "SortDirection", { enumerable: true, get: function () { return enums_1.SortDirection; } });
67
+ Object.defineProperty(exports, "OptionAnalysisPeriod", { enumerable: true, get: function () { return enums_1.OptionAnalysisPeriod; } });
68
+ Object.defineProperty(exports, "FinancialReportPeriod", { enumerable: true, get: function () { return enums_1.FinancialReportPeriod; } });
69
+ Object.defineProperty(exports, "Language", { enumerable: true, get: function () { return enums_1.Language; } });
70
+ Object.defineProperty(exports, "License", { enumerable: true, get: function () { return enums_1.License; } });
71
+ Object.defineProperty(exports, "BarPeriod", { enumerable: true, get: function () { return enums_1.BarPeriod; } });
72
+ Object.defineProperty(exports, "orderStatusCode", { enumerable: true, get: function () { return enums_1.orderStatusCode; } });
@@ -4,7 +4,7 @@
4
4
  * 所有枚举值与 API JSON 保持一致
5
5
  */
6
6
  Object.defineProperty(exports, "__esModule", { value: true });
7
- exports.FinancialReportPeriod = exports.OptionAnalysisPeriod = exports.SortDirection = exports.IndustryLevel = exports.CorporateActionType = exports.SegmentType = exports.OrderSortBy = exports.TimeInForce = exports.License = exports.QuoteRight = exports.Language = exports.BarPeriod = exports.OrderStatus = exports.OrderType = exports.Currency = exports.SecurityType = exports.Market = void 0;
7
+ exports.FinancialReportPeriod = exports.OptionAnalysisPeriod = exports.SortDirection = exports.IndustryLevel = exports.CorporateActionType = exports.SegmentType = exports.OrderSortBy = exports.TimeInForce = exports.License = exports.QuoteRight = exports.Language = exports.BarPeriod = exports.OrderStatus = exports.PriceType = exports.OrderType = exports.Currency = exports.SecurityType = exports.Market = void 0;
8
8
  exports.orderStatusCode = orderStatusCode;
9
9
  /** 市场枚举 */
10
10
  var Market;
@@ -51,7 +51,20 @@ var OrderType;
51
51
  OrderType["TWAP"] = "TWAP";
52
52
  OrderType["VWAP"] = "VWAP";
53
53
  OrderType["OCA"] = "OCA";
54
+ OrderType["ICEBERG"] = "ICEBERG";
54
55
  })(OrderType || (exports.OrderType = OrderType = {}));
56
+ /** 冰山单价格类型 */
57
+ var PriceType;
58
+ (function (PriceType) {
59
+ /** 限价 */
60
+ PriceType["LIMIT_PRICE"] = "LIMIT_PRICE";
61
+ /** 卖一价 */
62
+ PriceType["ASK_PRICE"] = "ASK_PRICE";
63
+ /** 买一价 */
64
+ PriceType["BID_PRICE"] = "BID_PRICE";
65
+ /** 最新价 */
66
+ PriceType["LATEST_PRICE"] = "LATEST_PRICE";
67
+ })(PriceType || (exports.PriceType = PriceType = {}));
55
68
  /**
56
69
  * 订单状态枚举。对齐 Java SDK OrderStatus 定义。
57
70
  *
@@ -137,6 +150,7 @@ var TimeInForce;
137
150
  (function (TimeInForce) {
138
151
  TimeInForce["DAY"] = "DAY";
139
152
  TimeInForce["GTC"] = "GTC";
153
+ TimeInForce["GTD"] = "GTD";
140
154
  TimeInForce["OPG"] = "OPG";
141
155
  })(TimeInForce || (exports.TimeInForce = TimeInForce = {}));
142
156
  /** 订单排序字段 */
@@ -159,6 +173,9 @@ var CorporateActionType;
159
173
  CorporateActionType["Split"] = "split";
160
174
  CorporateActionType["Dividend"] = "dividend";
161
175
  CorporateActionType["Earning"] = "earning";
176
+ CorporateActionType["SymbolChange"] = "symbol_change";
177
+ CorporateActionType["Delisting"] = "delisting";
178
+ CorporateActionType["IPO"] = "ipo";
162
179
  })(CorporateActionType || (exports.CorporateActionType = CorporateActionType = {}));
163
180
  /** 行业级别 (1~4 级) */
164
181
  var IndustryLevel;
@@ -8,7 +8,15 @@ exports.trailOrder = trailOrder;
8
8
  exports.auctionLimitOrder = auctionLimitOrder;
9
9
  exports.auctionMarketOrder = auctionMarketOrder;
10
10
  exports.algoOrder = algoOrder;
11
+ exports.icebergOrder = icebergOrder;
11
12
  exports.orderLeg = orderLeg;
13
+ exports.marketOrderByAmount = marketOrderByAmount;
14
+ exports.limitOrderByAmount = limitOrderByAmount;
15
+ exports.trailOrderByPrice = trailOrderByPrice;
16
+ exports.limitOrderWithLegs = limitOrderWithLegs;
17
+ exports.comboOrder = comboOrder;
18
+ exports.ocaOrder = ocaOrder;
19
+ exports.contractLeg = contractLeg;
12
20
  const enums_1 = require("./enums");
13
21
  /** Market order */
14
22
  function marketOrder(account, symbol, secType, action, quantity) {
@@ -98,7 +106,148 @@ function algoOrder(account, symbol, secType, action, quantity, limitPrice, algoT
98
106
  outsideRth: false,
99
107
  };
100
108
  }
109
+ /**
110
+ * Iceberg order. `displaySize` is required; all other parameters are optional.
111
+ * Pass `priceType` as empty string to use the server default (LIMIT_PRICE).
112
+ * Pass `startTime` / `endTime` as 0 to omit the time window.
113
+ */
114
+ function icebergOrder(account, symbol, secType, action, quantity, limitPrice, displaySize, minDisplaySize, checkIntervals, priceType, startTime, endTime) {
115
+ const req = {
116
+ account, symbol, secType, action,
117
+ orderType: enums_1.OrderType.ICEBERG,
118
+ totalQuantity: quantity,
119
+ limitPrice,
120
+ timeInForce: enums_1.TimeInForce.DAY,
121
+ outsideRth: false,
122
+ displaySize,
123
+ priceType: priceType || enums_1.PriceType.LIMIT_PRICE,
124
+ };
125
+ if (minDisplaySize !== undefined && minDisplaySize > 0)
126
+ req.minDisplaySize = minDisplaySize;
127
+ if (checkIntervals !== undefined && checkIntervals > 0)
128
+ req.checkIntervals = checkIntervals;
129
+ if (startTime && startTime > 0)
130
+ req.startTime = startTime;
131
+ if (endTime && endTime > 0)
132
+ req.endTime = endTime;
133
+ return req;
134
+ }
101
135
  /** Attached profit / loss leg */
102
136
  function orderLeg(legType, price, timeInForce) {
103
137
  return { legType, price, timeInForce };
104
138
  }
139
+ /**
140
+ * Market order by cash amount (instead of quantity).
141
+ * Server uses `isQuantityByAmount=true` + `amount` field.
142
+ */
143
+ function marketOrderByAmount(account, symbol, secType, action, amount) {
144
+ return {
145
+ account, symbol, secType, action,
146
+ orderType: enums_1.OrderType.MKT,
147
+ totalQuantity: 0,
148
+ cashAmount: amount,
149
+ timeInForce: enums_1.TimeInForce.DAY,
150
+ outsideRth: false,
151
+ };
152
+ }
153
+ /**
154
+ * Limit order by cash amount (instead of quantity).
155
+ */
156
+ function limitOrderByAmount(account, symbol, secType, action, amount, limitPrice) {
157
+ return {
158
+ account, symbol, secType, action,
159
+ orderType: enums_1.OrderType.LMT,
160
+ totalQuantity: 0,
161
+ cashAmount: amount,
162
+ limitPrice,
163
+ timeInForce: enums_1.TimeInForce.DAY,
164
+ outsideRth: false,
165
+ };
166
+ }
167
+ /**
168
+ * Trailing stop order using a fixed price offset (auxPrice) instead of a percentage.
169
+ * Use `trailOrder()` for percentage-based trailing stops.
170
+ */
171
+ function trailOrderByPrice(account, symbol, secType, action, quantity, auxPrice) {
172
+ return {
173
+ account, symbol, secType, action,
174
+ orderType: enums_1.OrderType.TRAIL,
175
+ totalQuantity: quantity,
176
+ auxPrice,
177
+ timeInForce: enums_1.TimeInForce.DAY,
178
+ outsideRth: false,
179
+ };
180
+ }
181
+ /**
182
+ * Limit order with attached profit/loss legs (bracket order).
183
+ * At most 2 legs are supported.
184
+ *
185
+ * @param orderLegs - Array of `OrderLegRequest` (use `orderLeg()` helper)
186
+ */
187
+ function limitOrderWithLegs(account, symbol, secType, action, quantity, limitPrice, orderLegs) {
188
+ if (orderLegs.length === 0) {
189
+ throw new Error('At least 1 order leg is required for a bracket order');
190
+ }
191
+ if (orderLegs.length > 2) {
192
+ throw new Error('At most 2 order legs are supported');
193
+ }
194
+ return {
195
+ account, symbol, secType, action,
196
+ orderType: enums_1.OrderType.LMT,
197
+ totalQuantity: quantity,
198
+ limitPrice,
199
+ orderLegs,
200
+ timeInForce: enums_1.TimeInForce.DAY,
201
+ outsideRth: false,
202
+ };
203
+ }
204
+ /**
205
+ * Multi-leg (combo/MLEG) order for options combos.
206
+ *
207
+ * @param contractLegs - Array of `ContractLegRequest` (use `contractLeg()` helper)
208
+ * @param comboType - e.g. `'MLEG'`
209
+ */
210
+ function comboOrder(account, action, quantity, orderType, contractLegs, comboType = 'MLEG', limitPrice, auxPrice, trailingPercent) {
211
+ return {
212
+ account,
213
+ symbol: '', // not used for combo orders
214
+ secType: 'MLEG',
215
+ action,
216
+ orderType,
217
+ totalQuantity: quantity,
218
+ limitPrice,
219
+ auxPrice,
220
+ trailingPercent,
221
+ contractLegs,
222
+ comboType,
223
+ timeInForce: enums_1.TimeInForce.DAY,
224
+ outsideRth: false,
225
+ };
226
+ }
227
+ /**
228
+ * OCA (One-Cancels-All) order.
229
+ * Server expects `orderType: 'OCA'` and an `ocaOrders` list.
230
+ *
231
+ * @param ocaOrders - The contained orders (use any order helper to build each)
232
+ */
233
+ function ocaOrder(account, symbol, secType, action, quantity, ocaOrders) {
234
+ return {
235
+ account, symbol, secType, action,
236
+ orderType: enums_1.OrderType.OCA,
237
+ totalQuantity: quantity,
238
+ ocaOrders,
239
+ timeInForce: enums_1.TimeInForce.DAY,
240
+ outsideRth: false,
241
+ };
242
+ }
243
+ /**
244
+ * Build a single leg for a multi-leg (MLEG / combo) order.
245
+ *
246
+ * @param symbol - Underlying symbol
247
+ * @param secType - Security type (e.g. `'OPT'`)
248
+ * @param action - `'BUY'` or `'SELL'`
249
+ * @param ratio - Number of contracts for this leg
250
+ */
251
+ function contractLeg(symbol, secType, action, ratio, expiry, strike, right) {
252
+ return { symbol, secType, action, ratio, expiry, strike, right };
253
+ }