tigeropen 0.4.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.
- package/README.md +55 -2
- package/dist/cjs/client/api-response.js +28 -7
- package/dist/cjs/client/case-convert.js +4 -3
- package/dist/cjs/client/http-client.js +124 -8
- package/dist/cjs/client/token-methods.js +42 -0
- package/dist/cjs/config/client-config.js +115 -16
- package/dist/cjs/config/config-parser.js +19 -9
- package/dist/cjs/config/index.js +4 -1
- package/dist/cjs/config/token-manager.js +54 -4
- package/dist/cjs/index.js +53 -2
- package/dist/cjs/model/enums.js +18 -1
- package/dist/cjs/model/order-helpers.js +149 -0
- package/dist/cjs/push/index.js +1 -0
- package/dist/cjs/push/push-client.js +47 -19
- package/dist/cjs/push/tick-util.js +172 -0
- package/dist/cjs/quote/quote-client.js +300 -70
- package/dist/cjs/trade/trade-client.js +174 -13
- package/dist/cjs/version.js +4 -0
- package/dist/esm/client/api-request.js +1 -1
- package/dist/esm/client/api-response.js +29 -8
- package/dist/esm/client/case-convert.js +4 -3
- package/dist/esm/client/http-client.js +128 -12
- package/dist/esm/client/index.js +6 -6
- package/dist/esm/client/token-methods.js +37 -0
- package/dist/esm/config/client-config.js +118 -20
- package/dist/esm/config/config-parser.js +19 -9
- package/dist/esm/config/index.js +4 -3
- package/dist/esm/config/token-manager.js +55 -5
- package/dist/esm/index.js +15 -1
- package/dist/esm/logger/index.js +1 -1
- package/dist/esm/model/contract-helpers.js +1 -1
- package/dist/esm/model/enums.js +17 -0
- package/dist/esm/model/order-helpers.js +142 -1
- package/dist/esm/model/order-status.js +1 -1
- package/dist/esm/push/index.js +6 -5
- package/dist/esm/push/pb/PushData.js +11 -11
- package/dist/esm/push/pb/QuoteBasicData.js +1 -1
- package/dist/esm/push/pb/Response.js +1 -1
- package/dist/esm/push/pb/index.js +17 -17
- package/dist/esm/push/proto-message.js +3 -3
- package/dist/esm/push/push-client.js +54 -26
- package/dist/esm/push/tick-util.js +165 -0
- package/dist/esm/quote/index.js +1 -1
- package/dist/esm/quote/quote-client.js +269 -72
- package/dist/esm/signer/index.js +2 -2
- package/dist/esm/trade/index.js +1 -1
- package/dist/esm/trade/trade-client.js +144 -16
- package/dist/esm/version.js +1 -0
- package/dist/types/client/api-response.d.ts +6 -4
- package/dist/types/client/case-convert.d.ts +3 -1
- package/dist/types/client/http-client.d.ts +32 -1
- package/dist/types/client/token-methods.d.ts +34 -0
- package/dist/types/config/client-config.d.ts +22 -1
- package/dist/types/config/index.d.ts +3 -1
- package/dist/types/config/token-manager.d.ts +27 -3
- package/dist/types/index.d.ts +22 -1
- package/dist/types/model/enums.d.ts +18 -2
- package/dist/types/model/order-helpers.d.ts +52 -1
- package/dist/types/model/order.d.ts +127 -10
- package/dist/types/model/quote-requests.d.ts +27 -15
- package/dist/types/model/quote.d.ts +150 -24
- package/dist/types/model/trade-requests.d.ts +118 -4
- package/dist/types/model/trade.d.ts +121 -17
- package/dist/types/push/callbacks.d.ts +3 -7
- package/dist/types/push/index.d.ts +1 -0
- package/dist/types/push/push-client.d.ts +5 -3
- package/dist/types/push/tick-util.d.ts +30 -0
- package/dist/types/quote/quote-client.d.ts +101 -36
- package/dist/types/trade/trade-client.d.ts +57 -11
- package/dist/types/version.d.ts +1 -0
- package/package.json +5 -2
package/README.md
CHANGED
|
@@ -312,7 +312,7 @@ const { createClientConfig } = require('@tigeropenapi/tigeropen');
|
|
|
312
312
|
## References
|
|
313
313
|
|
|
314
314
|
- [TypeScript SDK Documentation](https://docs.itigerup.com/docs/typescript)
|
|
315
|
-
- [Tiger Brokers OpenAPI Docs](https://
|
|
315
|
+
- [Tiger Brokers OpenAPI Docs](https://docs-en.itigerup.com/docs/)
|
|
316
316
|
- [npm package](https://www.npmjs.com/package/@tigeropenapi/tigeropen)
|
|
317
317
|
|
|
318
318
|
## License
|
|
@@ -486,8 +486,61 @@ const chain = await qc.optionChain('AAPL', '2024-01-19');
|
|
|
486
486
|
|
|
487
487
|
// 期货交易所
|
|
488
488
|
const exchanges = await qc.futureExchange();
|
|
489
|
+
|
|
490
|
+
// 逐笔成交
|
|
491
|
+
const ticks = await qc.getTradeTick({ symbols: ['AAPL'] });
|
|
492
|
+
// ticks[0].items[i].partCode — 交易所短名,如 "NYSE"、"NSDQ"
|
|
493
|
+
// ticks[0].items[i].partName — 交易所全名,如 "New York Stock Exchange, LLC (NYSE)"
|
|
494
|
+
// ticks[0].items[i].cond — 已转换的成交条件,如 "US_REGULAR_SALE",参见下方说明
|
|
489
495
|
```
|
|
490
496
|
|
|
497
|
+
### 逐笔成交 `cond` 字段说明
|
|
498
|
+
|
|
499
|
+
`trade_tick` 接口和 push 层返回的 `cond` 字段已由 SDK 转换为可读字符串,含义如下:
|
|
500
|
+
|
|
501
|
+
**美股(US)**
|
|
502
|
+
|
|
503
|
+
| 字符 | 含义 |
|
|
504
|
+
|------|------|
|
|
505
|
+
| ` `(空格)| 常规交易(Regular Sale) |
|
|
506
|
+
| `B` | 批量交易(Bunched Trade) |
|
|
507
|
+
| `C` | 现金交易(Cash Trade) |
|
|
508
|
+
| `F` | 跨市场交易(Intermarket Sweep) |
|
|
509
|
+
| `G` | 批量卖出(Bunched Sold Trade) |
|
|
510
|
+
| `H` | 离价交易(Price Variation Trade) |
|
|
511
|
+
| `I` | 碎股交易(Odd Lot Trade) |
|
|
512
|
+
| `K` | 纽交所第 127/155 条交易 |
|
|
513
|
+
| `L` | 延迟交易(Sold Last) |
|
|
514
|
+
| `M` | 中央收市价(Market Center Close Price) |
|
|
515
|
+
| `N` | 隔日交易(Next Day Trade) |
|
|
516
|
+
| `O` | 中央开盘价交易(Market Center Opening Trade) |
|
|
517
|
+
| `P` | 前参考价(Prior Reference Price) |
|
|
518
|
+
| `Q` | 中央开盘价(Market Center Open Price) |
|
|
519
|
+
| `R` | 卖方(Seller) |
|
|
520
|
+
| `T` | 盘前盘后交易(Form T) |
|
|
521
|
+
| `U` | 延长交易时段(Extended Trading Hours) |
|
|
522
|
+
| `V` | 合单交易(Contingent Trade) |
|
|
523
|
+
| `W` | 均价交易(Average Price Trade) |
|
|
524
|
+
| `X` | 跨市场交易(Cross Trade) |
|
|
525
|
+
| `Z` | 场外售出(Sold Out of Sequence) |
|
|
526
|
+
| `4` | 衍生工具定价(Derivatively Priced) |
|
|
527
|
+
| `7` | 合单交易(Qualified Contingent Trade) |
|
|
528
|
+
|
|
529
|
+
**港股(HK)**
|
|
530
|
+
|
|
531
|
+
| 字符 | 含义 |
|
|
532
|
+
|------|------|
|
|
533
|
+
| ` `(空格)| 自动对盘(Automatch Normal) |
|
|
534
|
+
| `D` | 碎股交易(Odd Lot Trade) |
|
|
535
|
+
| `U` | 竞价交易(Auction Trade) |
|
|
536
|
+
| `*` | 场外交易(Overseas Trade) |
|
|
537
|
+
| `P` | 开市前成交(Late Trade Off Exchange) |
|
|
538
|
+
| `M` | 非自动对盘(Non-Direct Off Exchange Trade) |
|
|
539
|
+
| `X` | 同券商自动对盘(Direct Off Exchange Trade) |
|
|
540
|
+
| `Y` | 同券商非自动对盘(Automatic Internalized) |
|
|
541
|
+
|
|
542
|
+
如上表所示,`cond` 值因市场(美股/港股)不同而有所区别。
|
|
543
|
+
|
|
491
544
|
## 交易
|
|
492
545
|
|
|
493
546
|
```typescript
|
|
@@ -635,7 +688,7 @@ const { createClientConfig } = require('@tigeropenapi/tigeropen');
|
|
|
635
688
|
## 参考链接
|
|
636
689
|
|
|
637
690
|
- [TypeScript SDK 文档](https://docs.itigerup.com/docs/typescript)
|
|
638
|
-
- [老虎证券 OpenAPI 文档](https://
|
|
691
|
+
- [老虎证券 OpenAPI 文档](https://docs.itigerup.com/docs/)
|
|
639
692
|
- [npm 包](https://www.npmjs.com/package/@tigeropenapi/tigeropen)
|
|
640
693
|
|
|
641
694
|
## 许可证
|
|
@@ -7,11 +7,33 @@ exports.unmarshalData = unmarshalData;
|
|
|
7
7
|
*/
|
|
8
8
|
const errors_1 = require("./errors");
|
|
9
9
|
/**
|
|
10
|
-
*
|
|
11
|
-
*
|
|
10
|
+
* Replaces bare int64 values (≥17 digits, not part of a float) with quoted
|
|
11
|
+
* strings so they survive JSON.parse without precision loss.
|
|
12
|
+
* 17+ digits are guaranteed to exceed Number.MAX_SAFE_INTEGER (≈9.007e15),
|
|
13
|
+
* so 16-digit microsecond timestamps remain as numbers.
|
|
14
|
+
*/
|
|
15
|
+
function patchLargeIntegers(text) {
|
|
16
|
+
const strings = [];
|
|
17
|
+
const masked = text.replace(/"(?:[^"\\]|\\.)*"/g, (match) => {
|
|
18
|
+
strings.push(match);
|
|
19
|
+
return '\x01' + (strings.length - 1) + '\x01';
|
|
20
|
+
});
|
|
21
|
+
// Match bare integers preceded by a JSON structural character or line start,
|
|
22
|
+
// not followed by decimal point or exponent (avoids matching float components).
|
|
23
|
+
// The `m` flag makes `^` match line-start for multi-line JSON.
|
|
24
|
+
const patched = masked.replace(/([:,\[{]|^)\s*(-?\d{17,})(?![.\deE])/gm, (full, prefix, num) => {
|
|
25
|
+
return prefix + '"' + num + '"';
|
|
26
|
+
});
|
|
27
|
+
return patched.replace(/\x01(\d+)\x01/g, (_, i) => strings[parseInt(i, 10)]);
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Parse the raw HTTP response body. Throws TigerError when code != 0.
|
|
31
|
+
*
|
|
32
|
+
* patchLargeIntegers is applied before JSON.parse to preserve int64 order IDs
|
|
33
|
+
* (e.g. 28868646234578944) as strings rather than losing precision.
|
|
12
34
|
*/
|
|
13
35
|
function parseApiResponse(body) {
|
|
14
|
-
const resp = JSON.parse(body);
|
|
36
|
+
const resp = JSON.parse(patchLargeIntegers(body));
|
|
15
37
|
if (resp.code !== 0) {
|
|
16
38
|
throw new errors_1.TigerError(resp.code, resp.message);
|
|
17
39
|
}
|
|
@@ -19,16 +41,15 @@ function parseApiResponse(body) {
|
|
|
19
41
|
}
|
|
20
42
|
/**
|
|
21
43
|
* Decode an ApiResponse.data payload into a typed value.
|
|
22
|
-
* Handles
|
|
23
|
-
*
|
|
44
|
+
* Handles double-encoded JSON (where `data` is a JSON string wrapping JSON),
|
|
45
|
+
* seen on some trade endpoints.
|
|
24
46
|
*/
|
|
25
47
|
function unmarshalData(data) {
|
|
26
48
|
if (data == null)
|
|
27
49
|
return undefined;
|
|
28
50
|
if (typeof data === 'string') {
|
|
29
|
-
// Attempt to parse JSON string (double-encoded case)
|
|
30
51
|
try {
|
|
31
|
-
return JSON.parse(data);
|
|
52
|
+
return JSON.parse(patchLargeIntegers(data));
|
|
32
53
|
}
|
|
33
54
|
catch {
|
|
34
55
|
return data;
|
|
@@ -17,7 +17,9 @@ function camelToSnake(key) {
|
|
|
17
17
|
/**
|
|
18
18
|
* Recursively convert all object keys from camelCase to snake_case.
|
|
19
19
|
* Preserves arrays, primitives, and Date/null/undefined.
|
|
20
|
-
*
|
|
20
|
+
*
|
|
21
|
+
* Note: camelToSnake is idempotent for pure snake_case keys (no uppercase
|
|
22
|
+
* letters → no replacements), so no pre-check is needed.
|
|
21
23
|
*/
|
|
22
24
|
function keysToSnakeCase(value) {
|
|
23
25
|
if (Array.isArray(value)) {
|
|
@@ -26,8 +28,7 @@ function keysToSnakeCase(value) {
|
|
|
26
28
|
if (value && typeof value === 'object' && value.constructor === Object) {
|
|
27
29
|
const out = {};
|
|
28
30
|
for (const [k, v] of Object.entries(value)) {
|
|
29
|
-
|
|
30
|
-
out[newKey] = keysToSnakeCase(v);
|
|
31
|
+
out[camelToSnake(k)] = keysToSnakeCase(v);
|
|
31
32
|
}
|
|
32
33
|
return out;
|
|
33
34
|
}
|
|
@@ -1,29 +1,60 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.HttpClient = void 0;
|
|
4
|
+
const token_manager_1 = require("../config/token-manager");
|
|
4
5
|
const sign_content_1 = require("../signer/sign-content");
|
|
5
6
|
const signer_1 = require("../signer/signer");
|
|
6
7
|
const errors_1 = require("./errors");
|
|
7
8
|
const retry_1 = require("./retry");
|
|
8
9
|
const api_response_1 = require("./api-response");
|
|
9
|
-
|
|
10
|
-
const SDK_VERSION = '0.4.0';
|
|
10
|
+
const version_1 = require("../version");
|
|
11
11
|
/** User-Agent 字符串 */
|
|
12
|
-
const USER_AGENT = `openapi-typescript-sdk-${SDK_VERSION}`;
|
|
12
|
+
const USER_AGENT = `openapi-typescript-sdk-${version_1.SDK_VERSION}`;
|
|
13
13
|
/** 默认字符集 */
|
|
14
14
|
const DEFAULT_CHARSET = 'UTF-8';
|
|
15
15
|
/** 默认签名类型 */
|
|
16
16
|
const DEFAULT_SIGN_TYPE = 'RSA';
|
|
17
17
|
/** 默认 API 版本 */
|
|
18
18
|
const DEFAULT_VERSION = '2.0';
|
|
19
|
+
/** Token 刷新 API 方法名 */
|
|
20
|
+
const METHOD_TOKEN_REFRESH = 'user_token_refresh';
|
|
21
|
+
/** 默认后台 token 检查间隔(毫秒):5 分钟 */
|
|
22
|
+
const DEFAULT_TOKEN_CHECK_INTERVAL = 5 * 60 * 1000;
|
|
19
23
|
/**
|
|
20
24
|
* HttpClient handles HTTP requests, signing, retry, and timeout
|
|
21
25
|
*/
|
|
22
26
|
class HttpClient {
|
|
23
27
|
constructor(config, retryPolicy, options) {
|
|
28
|
+
/** non-null when auto-refresh is active */
|
|
29
|
+
this.tokenManager = null;
|
|
24
30
|
this.config = config;
|
|
25
31
|
this.retryPolicy = retryPolicy ?? (0, retry_1.defaultRetryPolicy)();
|
|
26
32
|
this.targetUrl = options?.useQuoteServerUrl ? config.quoteServerUrl : config.serverUrl;
|
|
33
|
+
// Auto-start token refresh when tokenRefreshDuration is configured (mirrors Go SDK behaviour)
|
|
34
|
+
if (config.tokenRefreshDuration && config.tokenRefreshDuration > 0) {
|
|
35
|
+
const interval = config.tokenCheckInterval ?? DEFAULT_TOKEN_CHECK_INTERVAL;
|
|
36
|
+
const opts = {
|
|
37
|
+
refreshDuration: config.tokenRefreshDuration,
|
|
38
|
+
refreshInterval: interval,
|
|
39
|
+
};
|
|
40
|
+
if (config.tokenWriter) {
|
|
41
|
+
opts.tokenWriter = config.tokenWriter;
|
|
42
|
+
}
|
|
43
|
+
if (config.tokenLoader) {
|
|
44
|
+
opts.tokenLoader = config.tokenLoader;
|
|
45
|
+
}
|
|
46
|
+
this.tokenManager = this.startTokenAutoRefresh(null, opts);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Stop the background token auto-refresh timer.
|
|
51
|
+
* Call this when the HttpClient is no longer needed to avoid timer leaks.
|
|
52
|
+
*/
|
|
53
|
+
close() {
|
|
54
|
+
if (this.tokenManager) {
|
|
55
|
+
this.tokenManager.stopAutoRefresh();
|
|
56
|
+
this.tokenManager = null;
|
|
57
|
+
}
|
|
27
58
|
}
|
|
28
59
|
/**
|
|
29
60
|
* Build common request parameters
|
|
@@ -34,7 +65,11 @@ class HttpClient {
|
|
|
34
65
|
method: apiMethod,
|
|
35
66
|
charset: DEFAULT_CHARSET,
|
|
36
67
|
sign_type: DEFAULT_SIGN_TYPE,
|
|
37
|
-
timestamp:
|
|
68
|
+
timestamp: (() => {
|
|
69
|
+
const d = new Date();
|
|
70
|
+
const pad = (n) => String(n).padStart(2, '0');
|
|
71
|
+
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
|
|
72
|
+
})(),
|
|
38
73
|
version: version || DEFAULT_VERSION,
|
|
39
74
|
biz_content: bizContent,
|
|
40
75
|
};
|
|
@@ -61,6 +96,7 @@ class HttpClient {
|
|
|
61
96
|
const headers = {
|
|
62
97
|
'Content-Type': 'application/json;charset=UTF-8',
|
|
63
98
|
'User-Agent': USER_AGENT,
|
|
99
|
+
'Connection': 'close',
|
|
64
100
|
};
|
|
65
101
|
if (this.config.token) {
|
|
66
102
|
headers['Authorization'] = this.config.token;
|
|
@@ -71,7 +107,8 @@ class HttpClient {
|
|
|
71
107
|
body,
|
|
72
108
|
signal: AbortSignal.timeout(this.config.timeout * 1000),
|
|
73
109
|
});
|
|
74
|
-
|
|
110
|
+
const text = await response.text();
|
|
111
|
+
return text;
|
|
75
112
|
}
|
|
76
113
|
/**
|
|
77
114
|
* Execute a structured API request, returning a parsed ApiResponse.
|
|
@@ -98,6 +135,10 @@ class HttpClient {
|
|
|
98
135
|
}
|
|
99
136
|
catch (err) {
|
|
100
137
|
lastErr = err;
|
|
138
|
+
// Only retry on network errors, not API business errors (TigerError with code)
|
|
139
|
+
if (err.code !== undefined && err.code !== -1) {
|
|
140
|
+
throw err; // API returned a business error code, don't retry
|
|
141
|
+
}
|
|
101
142
|
if (!this.retryPolicy.shouldRetry(request.method)) {
|
|
102
143
|
throw err;
|
|
103
144
|
}
|
|
@@ -110,9 +151,10 @@ class HttpClient {
|
|
|
110
151
|
*
|
|
111
152
|
* @param apiMethod - API method name (e.g. "market_state", "place_order")
|
|
112
153
|
* @param requestJson - Raw biz_content JSON string
|
|
154
|
+
* @param version - Optional API version override (default: "2.0")
|
|
113
155
|
* @returns Raw response JSON string, unparsed
|
|
114
156
|
*/
|
|
115
|
-
async execute(apiMethod, requestJson) {
|
|
157
|
+
async execute(apiMethod, requestJson, version) {
|
|
116
158
|
// Parameter validation
|
|
117
159
|
if (!apiMethod) {
|
|
118
160
|
throw new errors_1.TigerError(-1, 'api_method must not be empty');
|
|
@@ -123,7 +165,7 @@ class HttpClient {
|
|
|
123
165
|
catch {
|
|
124
166
|
throw new errors_1.TigerError(-1, 'request_json is not valid JSON');
|
|
125
167
|
}
|
|
126
|
-
const params = this.buildCommonParams(apiMethod, requestJson);
|
|
168
|
+
const params = this.buildCommonParams(apiMethod, requestJson, version);
|
|
127
169
|
const sign = this.signParams(params);
|
|
128
170
|
params['sign'] = sign;
|
|
129
171
|
let lastErr;
|
|
@@ -144,6 +186,10 @@ class HttpClient {
|
|
|
144
186
|
}
|
|
145
187
|
catch (err) {
|
|
146
188
|
lastErr = err;
|
|
189
|
+
// Don't retry API business errors
|
|
190
|
+
if (err.code !== undefined && err.code !== -1) {
|
|
191
|
+
throw err;
|
|
192
|
+
}
|
|
147
193
|
if (!this.retryPolicy.shouldRetry(apiMethod)) {
|
|
148
194
|
throw err;
|
|
149
195
|
}
|
|
@@ -151,6 +197,75 @@ class HttpClient {
|
|
|
151
197
|
}
|
|
152
198
|
throw lastErr;
|
|
153
199
|
}
|
|
200
|
+
/**
|
|
201
|
+
* 调用 user_token_refresh 接口获取新 token,返回新 token 字符串。
|
|
202
|
+
* 此方法仅查询,不修改 config 中的 token。
|
|
203
|
+
*/
|
|
204
|
+
async queryToken() {
|
|
205
|
+
const params = this.buildCommonParams(METHOD_TOKEN_REFRESH, '{}');
|
|
206
|
+
const sign = this.signParams(params);
|
|
207
|
+
params['sign'] = sign;
|
|
208
|
+
const body = await this.doHttpPost(params);
|
|
209
|
+
const response = (0, api_response_1.parseApiResponse)(body);
|
|
210
|
+
this.verifyResponseSign(params['timestamp'], response.sign);
|
|
211
|
+
const data = (0, api_response_1.unmarshalData)(response.data);
|
|
212
|
+
const newToken = data?.token;
|
|
213
|
+
if (!newToken) {
|
|
214
|
+
throw new errors_1.TigerError(-1, '服务端返回空 token');
|
|
215
|
+
}
|
|
216
|
+
return newToken;
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* 刷新 token:调用接口获取新 token 后更新 config.token。
|
|
220
|
+
*
|
|
221
|
+
* @param tokenManager - 可选外部 TokenManager;若提供则调用 setToken() 写文件并触发回调。
|
|
222
|
+
* 若 NewHttpClient 已自动启动内部 TokenManager,其内存 token 也会同步更新。
|
|
223
|
+
*/
|
|
224
|
+
async refreshToken(tokenManager) {
|
|
225
|
+
const newToken = await this.queryToken();
|
|
226
|
+
this.config.token = newToken;
|
|
227
|
+
// Keep internal tokenManager in sync so shouldTokenRefresh stays accurate.
|
|
228
|
+
if (this.tokenManager && tokenManager !== this.tokenManager) {
|
|
229
|
+
this.tokenManager.syncToken(newToken);
|
|
230
|
+
}
|
|
231
|
+
if (tokenManager) {
|
|
232
|
+
tokenManager.setToken(newToken);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
/**
|
|
236
|
+
* 启动后台 token 自动刷新。
|
|
237
|
+
*
|
|
238
|
+
* @param tokenManager - 可为 null:SDK 内部自动创建一个仅内存的 TokenManager,
|
|
239
|
+
* 适合直接通过 token 在代码里设置、不使用文件的场景。
|
|
240
|
+
* @param options - 仅在 tokenManager 为 null 时生效,用于配置内部 TokenManager
|
|
241
|
+
* (refreshDuration / refreshInterval / tokenWriter / tokenLoader)。
|
|
242
|
+
* @returns 使用或创建的 TokenManager 实例
|
|
243
|
+
*/
|
|
244
|
+
startTokenAutoRefresh(tokenManager, options) {
|
|
245
|
+
if (!tokenManager) {
|
|
246
|
+
tokenManager = new token_manager_1.TokenManager(options);
|
|
247
|
+
// 从 config.token 同步当前 token,使 shouldTokenRefresh 能正确判断。
|
|
248
|
+
// 若 config.token 暂时为空(异步 tokenLoader 尚未 resolve),则先异步加载。
|
|
249
|
+
if (this.config.token) {
|
|
250
|
+
tokenManager.syncToken(this.config.token);
|
|
251
|
+
}
|
|
252
|
+
else if (options?.tokenLoader) {
|
|
253
|
+
// tokenLoader 可能是异步的;在后台 resolve 后同步到 config.token 和 TokenManager。
|
|
254
|
+
Promise.resolve(options.tokenLoader()).then((t) => {
|
|
255
|
+
if (t) {
|
|
256
|
+
this.config.token = t;
|
|
257
|
+
tokenManager.syncToken(t);
|
|
258
|
+
}
|
|
259
|
+
}).catch(() => { });
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
tokenManager.startAutoRefresh(async () => {
|
|
263
|
+
const newToken = await this.queryToken();
|
|
264
|
+
this.config.token = newToken;
|
|
265
|
+
return newToken;
|
|
266
|
+
});
|
|
267
|
+
return tokenManager;
|
|
268
|
+
}
|
|
154
269
|
/** Delay for the specified milliseconds */
|
|
155
270
|
sleep(ms) {
|
|
156
271
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
@@ -164,7 +279,8 @@ class HttpClient {
|
|
|
164
279
|
*/
|
|
165
280
|
verifyResponseSign(timestamp, signBase64) {
|
|
166
281
|
if (!signBase64) {
|
|
167
|
-
|
|
282
|
+
// Some endpoints don't return a signature; skip verification silently.
|
|
283
|
+
return;
|
|
168
284
|
}
|
|
169
285
|
const valid = (0, signer_1.verifyWithRSA)(this.config.tigerPublicKey, timestamp, signBase64);
|
|
170
286
|
if (!valid) {
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.queryToken = queryToken;
|
|
4
|
+
exports.refreshToken = refreshToken;
|
|
5
|
+
exports.startTokenAutoRefresh = startTokenAutoRefresh;
|
|
6
|
+
/**
|
|
7
|
+
* Call the `user_token_refresh` API and return the new token string.
|
|
8
|
+
* Read-only: does NOT update the stored token.
|
|
9
|
+
* Use `refreshToken()` to also update the in-memory config and optionally persist.
|
|
10
|
+
*/
|
|
11
|
+
async function queryToken(httpClient) {
|
|
12
|
+
return httpClient.queryToken();
|
|
13
|
+
}
|
|
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
|
+
async function refreshToken(httpClient, tokenManager) {
|
|
22
|
+
return httpClient.refreshToken(tokenManager);
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Start background token auto-refresh. Returns a TokenManager that can be
|
|
26
|
+
* used to stop the background task via `tm.stopAutoRefresh()`.
|
|
27
|
+
*
|
|
28
|
+
* @param httpClient - The underlying HTTP client
|
|
29
|
+
* @param refreshDurationSecs - Refresh threshold in seconds (minimum 30).
|
|
30
|
+
* When the token age exceeds this value the refresh is triggered.
|
|
31
|
+
* @param checkIntervalMs - How often to check whether a refresh is needed,
|
|
32
|
+
* in milliseconds. Defaults to 300 000 ms (5 minutes).
|
|
33
|
+
* @param tokenWriter - Optional callback invoked with the new token string
|
|
34
|
+
* after each successful refresh.
|
|
35
|
+
*/
|
|
36
|
+
function startTokenAutoRefresh(httpClient, refreshDurationSecs, checkIntervalMs, tokenWriter) {
|
|
37
|
+
return httpClient.startTokenAutoRefresh(null, {
|
|
38
|
+
refreshDuration: refreshDurationSecs,
|
|
39
|
+
refreshInterval: checkIntervalMs,
|
|
40
|
+
tokenWriter,
|
|
41
|
+
});
|
|
42
|
+
}
|
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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 (
|
|
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
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
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
|
|
285
|
+
tigerPublicKey,
|
|
187
286
|
};
|
|
188
287
|
}
|
|
189
288
|
/**
|