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
|
@@ -1,8 +1,52 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
2
35
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
36
|
exports.TradeClient = void 0;
|
|
37
|
+
/**
|
|
38
|
+
* TradeClient — trading client.
|
|
39
|
+
*
|
|
40
|
+
* All methods return strongly-typed responses; request parameters are
|
|
41
|
+
* written in camelCase in TypeScript and converted to snake_case on the wire.
|
|
42
|
+
*
|
|
43
|
+
* v0.4.0: 所有查询类方法改为 Request 对象签名(OrdersRequest 等),补齐 17
|
|
44
|
+
* 个新方法(账户管理 / 资产分析 / 资金调拨 / 持仓划转等)。
|
|
45
|
+
*/
|
|
46
|
+
const http_client_1 = require("../client/http-client");
|
|
4
47
|
const api_request_1 = require("../client/api-request");
|
|
5
48
|
const api_response_1 = require("../client/api-response");
|
|
49
|
+
const tokenMethods = __importStar(require("../client/token-methods"));
|
|
6
50
|
const order_status_1 = require("../model/order-status");
|
|
7
51
|
/** Normalize `Order.status` field in-place (handles int → string). */
|
|
8
52
|
function normalizeOrderInPlace(o) {
|
|
@@ -25,12 +69,51 @@ function withAccount(req, account) {
|
|
|
25
69
|
}
|
|
26
70
|
/** Trading client wrapping all trade-related APIs. */
|
|
27
71
|
class TradeClient {
|
|
28
|
-
constructor(httpClient, account) {
|
|
72
|
+
constructor(httpClient, account, secretKey) {
|
|
29
73
|
this.httpClient = httpClient;
|
|
30
74
|
this.account = account;
|
|
75
|
+
this.secretKey = secretKey;
|
|
76
|
+
}
|
|
77
|
+
/** Create a TradeClient directly from a ClientConfig — no need to construct HttpClient manually. */
|
|
78
|
+
static fromConfig(config, account, secretKey) {
|
|
79
|
+
return new TradeClient(new http_client_1.HttpClient(config), account, secretKey);
|
|
80
|
+
}
|
|
81
|
+
// ── Token management ──────────────────────────────────────────────────────
|
|
82
|
+
/** Call the `user_token_refresh` API and return the new token. Read-only. */
|
|
83
|
+
async queryToken() {
|
|
84
|
+
return tokenMethods.queryToken(this.httpClient);
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Refresh the token: call the API, update the in-memory config token, and
|
|
88
|
+
* optionally persist via the provided TokenManager (file + writer callback).
|
|
89
|
+
*
|
|
90
|
+
* @param tokenManager - optional TokenManager for file persistence and writer callback
|
|
91
|
+
*/
|
|
92
|
+
async refreshToken(tokenManager) {
|
|
93
|
+
return tokenMethods.refreshToken(this.httpClient, tokenManager);
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Start background token auto-refresh. Returns a TokenManager that can be
|
|
97
|
+
* used to stop the background task via `tm.stopAutoRefresh()`.
|
|
98
|
+
*
|
|
99
|
+
* @param refreshDurationSecs - Refresh threshold in seconds (minimum 30).
|
|
100
|
+
* @param checkIntervalMs - How often to check, in milliseconds (default 300 000 / 5 min).
|
|
101
|
+
* @param tokenWriter - Optional callback invoked after each successful refresh.
|
|
102
|
+
*/
|
|
103
|
+
startTokenAutoRefresh(refreshDurationSecs, checkIntervalMs, tokenWriter) {
|
|
104
|
+
return tokenMethods.startTokenAutoRefresh(this.httpClient, refreshDurationSecs, checkIntervalMs, tokenWriter);
|
|
31
105
|
}
|
|
32
106
|
async callInto(method, bizParams) {
|
|
33
|
-
|
|
107
|
+
// Inject secretKey into every request when available (institution accounts require it).
|
|
108
|
+
// Individual methods that already set secretKey will not be overwritten (|| not &&).
|
|
109
|
+
let params = bizParams;
|
|
110
|
+
if (this.secretKey && params !== null && typeof params === 'object' && !Array.isArray(params)) {
|
|
111
|
+
const p = params;
|
|
112
|
+
if (p['secretKey'] == null && p['secret_key'] == null) {
|
|
113
|
+
params = { ...p, secretKey: this.secretKey };
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
const request = (0, api_request_1.createApiRequest)(method, params);
|
|
34
117
|
const response = await this.httpClient.executeRequest(request);
|
|
35
118
|
return (0, api_response_1.unmarshalData)(response.data);
|
|
36
119
|
}
|
|
@@ -62,17 +145,60 @@ class TradeClient {
|
|
|
62
145
|
});
|
|
63
146
|
}
|
|
64
147
|
// === Order operations ===
|
|
148
|
+
/**
|
|
149
|
+
* Prepare an order request for the wire.
|
|
150
|
+
*
|
|
151
|
+
* The gateway expects `algo_params` as a `[{tag, value}, ...]` array
|
|
152
|
+
* (matching the Python SDK's AlgoParams.to_dict serialization), not the
|
|
153
|
+
* plain object shape that reads naturally in TypeScript. This helper
|
|
154
|
+
* normalizes the object form into the array form on outbound payloads
|
|
155
|
+
* so callers can pass the natural object and TWAP/VWAP orders work end
|
|
156
|
+
* to end without wire-format workarounds.
|
|
157
|
+
*
|
|
158
|
+
* Fields with undefined/null values are dropped; empty algoParams
|
|
159
|
+
* becomes an empty array rather than being stripped, matching the
|
|
160
|
+
* Python SDK behavior when the user passes an empty AlgoParams().
|
|
161
|
+
*/
|
|
162
|
+
marshalOrderForWire(order) {
|
|
163
|
+
const { algoParams, ...rest } = order;
|
|
164
|
+
const withAccount = { ...rest, account: this.account };
|
|
165
|
+
if (algoParams === undefined)
|
|
166
|
+
return withAccount;
|
|
167
|
+
// Already a tag/value array (advanced callers who want raw control)
|
|
168
|
+
if (Array.isArray(algoParams)) {
|
|
169
|
+
withAccount.algoParams = algoParams;
|
|
170
|
+
return withAccount;
|
|
171
|
+
}
|
|
172
|
+
// Object shape → tag/value array.
|
|
173
|
+
// Keys are converted to snake_case explicitly here (e.g. `startTime` →
|
|
174
|
+
// `start_time`) so they land correctly in the `tag` string that the
|
|
175
|
+
// gateway reads. `keysToSnakeCase` only rewrites object *keys*, not
|
|
176
|
+
// string *values*, so `tag` would be left camelCase if we didn't do
|
|
177
|
+
// this conversion ourselves.
|
|
178
|
+
const tagValues = [];
|
|
179
|
+
for (const [key, value] of Object.entries(algoParams)) {
|
|
180
|
+
if (value === undefined || value === null)
|
|
181
|
+
continue;
|
|
182
|
+
const snakeKey = key.replace(/[A-Z]/g, (c) => '_' + c.toLowerCase());
|
|
183
|
+
tagValues.push({ tag: snakeKey, value });
|
|
184
|
+
}
|
|
185
|
+
withAccount.algoParams = tagValues;
|
|
186
|
+
return withAccount;
|
|
187
|
+
}
|
|
65
188
|
async placeOrder(order) {
|
|
66
|
-
return this.callInto('place_order',
|
|
189
|
+
return this.callInto('place_order', this.marshalOrderForWire(order));
|
|
67
190
|
}
|
|
68
191
|
async previewOrder(order) {
|
|
69
|
-
return this.callInto('preview_order',
|
|
192
|
+
return this.callInto('preview_order', this.marshalOrderForWire(order));
|
|
70
193
|
}
|
|
71
194
|
async modifyOrder(id, order) {
|
|
72
|
-
return this.callInto('modify_order', { ...
|
|
195
|
+
return this.callInto('modify_order', { ...this.marshalOrderForWire(order), id });
|
|
73
196
|
}
|
|
74
|
-
async cancelOrder(id) {
|
|
75
|
-
|
|
197
|
+
async cancelOrder(id, secretKey) {
|
|
198
|
+
const params = { account: this.account, id };
|
|
199
|
+
if (secretKey !== undefined)
|
|
200
|
+
params.secretKey = secretKey; // per-call override takes precedence; undefined means use config default
|
|
201
|
+
return this.callInto('cancel_order', params);
|
|
76
202
|
}
|
|
77
203
|
// === Order queries (BREAKING v0.4.0) ===
|
|
78
204
|
/**
|
|
@@ -109,14 +235,11 @@ class TradeClient {
|
|
|
109
235
|
}
|
|
110
236
|
/**
|
|
111
237
|
* Get a single order by ID (v0.4.0 new).
|
|
112
|
-
* Wire method: `orders` with id/order_id param; server returns a single Order object
|
|
113
|
-
* (not `{items:[]}` envelope).
|
|
114
|
-
*
|
|
115
238
|
* Returns `undefined` if no match.
|
|
116
239
|
*/
|
|
117
240
|
async getOrder(req) {
|
|
118
241
|
const merged = withAccount(req, this.account);
|
|
119
|
-
const out = await this.callInto('
|
|
242
|
+
const out = await this.callInto('order_no', merged);
|
|
120
243
|
if (!out || (!out.id && !out.orderId))
|
|
121
244
|
return undefined;
|
|
122
245
|
normalizeOrderInPlace(out);
|
|
@@ -194,9 +317,10 @@ class TradeClient {
|
|
|
194
317
|
async getFundDetails(req) {
|
|
195
318
|
return this.callIntoItems('fund_details', withAccount(req, this.account));
|
|
196
319
|
}
|
|
197
|
-
/** Funding history (wire method: `transfer_fund`).
|
|
320
|
+
/** Funding history (wire method: `transfer_fund`).
|
|
321
|
+
* Server returns bare list (no items wrapper). */
|
|
198
322
|
async getFundingHistory(req) {
|
|
199
|
-
return this.
|
|
323
|
+
return this.callInto('transfer_fund', withAccount(req, this.account));
|
|
200
324
|
}
|
|
201
325
|
// ===== v0.4.0 NEW: Internal / external position transfer =====
|
|
202
326
|
/**
|
|
@@ -230,5 +354,42 @@ class TradeClient {
|
|
|
230
354
|
merged.accountId = this.account;
|
|
231
355
|
return this.callIntoItems('position_transfer_external_records', merged);
|
|
232
356
|
}
|
|
357
|
+
/** 行权检验:预估行权/作废后正股持仓变化 (wire: option_exercise_check) */
|
|
358
|
+
async checkOptionExercise(req) {
|
|
359
|
+
const merged = { ...req };
|
|
360
|
+
if (!merged.account)
|
|
361
|
+
merged.account = this.account;
|
|
362
|
+
return this.callInto('option_exercise_check', merged);
|
|
363
|
+
}
|
|
364
|
+
/** 查询可行权持仓列表 (wire: option_exercise_position) */
|
|
365
|
+
async getOptionExercisePositions(req) {
|
|
366
|
+
const merged = { ...req };
|
|
367
|
+
if (!merged.account)
|
|
368
|
+
merged.account = this.account;
|
|
369
|
+
return this.callInto('option_exercise_position', merged);
|
|
370
|
+
}
|
|
371
|
+
/** 提交行权/作废申请 (wire: option_exercise_submit) */
|
|
372
|
+
async submitOptionExercise(req) {
|
|
373
|
+
const merged = { ...req };
|
|
374
|
+
if (!merged.account)
|
|
375
|
+
merged.account = this.account;
|
|
376
|
+
const result = await this.callInto('option_exercise_submit', merged);
|
|
377
|
+
return result ?? false;
|
|
378
|
+
}
|
|
379
|
+
/** 分页查询行权记录 (wire: option_exercise_record) */
|
|
380
|
+
async getOptionExerciseRecords(req) {
|
|
381
|
+
const merged = { ...req };
|
|
382
|
+
if (!merged.account)
|
|
383
|
+
merged.account = this.account;
|
|
384
|
+
return this.callInto('option_exercise_record', merged);
|
|
385
|
+
}
|
|
386
|
+
/** 撤销行权申请 (wire: option_exercise_cancel) */
|
|
387
|
+
async cancelOptionExercise(req) {
|
|
388
|
+
const merged = { ...req };
|
|
389
|
+
if (!merged.account)
|
|
390
|
+
merged.account = this.account;
|
|
391
|
+
const result = await this.callInto('option_exercise_cancel', merged);
|
|
392
|
+
return result ?? false;
|
|
393
|
+
}
|
|
233
394
|
}
|
|
234
395
|
exports.TradeClient = TradeClient;
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* Requests use camelCase parameters in TypeScript (idiomatic), but the
|
|
5
5
|
* server wire format is snake_case, so we convert keys before serializing.
|
|
6
6
|
*/
|
|
7
|
-
import { keysToSnakeCase } from './case-convert';
|
|
7
|
+
import { keysToSnakeCase } from './case-convert.js';
|
|
8
8
|
/**
|
|
9
9
|
* Create an API request, serializing business parameters to JSON as bizContent.
|
|
10
10
|
* camelCase keys are automatically converted to snake_case to match the server.
|
|
@@ -1,13 +1,35 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* API response parsing.
|
|
3
3
|
*/
|
|
4
|
-
import { TigerError } from './errors';
|
|
4
|
+
import { TigerError } from './errors.js';
|
|
5
5
|
/**
|
|
6
|
-
*
|
|
7
|
-
*
|
|
6
|
+
* Replaces bare int64 values (≥17 digits, not part of a float) with quoted
|
|
7
|
+
* strings so they survive JSON.parse without precision loss.
|
|
8
|
+
* 17+ digits are guaranteed to exceed Number.MAX_SAFE_INTEGER (≈9.007e15),
|
|
9
|
+
* so 16-digit microsecond timestamps remain as numbers.
|
|
10
|
+
*/
|
|
11
|
+
function patchLargeIntegers(text) {
|
|
12
|
+
const strings = [];
|
|
13
|
+
const masked = text.replace(/"(?:[^"\\]|\\.)*"/g, (match) => {
|
|
14
|
+
strings.push(match);
|
|
15
|
+
return '\x01' + (strings.length - 1) + '\x01';
|
|
16
|
+
});
|
|
17
|
+
// Match bare integers preceded by a JSON structural character or line start,
|
|
18
|
+
// not followed by decimal point or exponent (avoids matching float components).
|
|
19
|
+
// The `m` flag makes `^` match line-start for multi-line JSON.
|
|
20
|
+
const patched = masked.replace(/([:,\[{]|^)\s*(-?\d{17,})(?![.\deE])/gm, (full, prefix, num) => {
|
|
21
|
+
return prefix + '"' + num + '"';
|
|
22
|
+
});
|
|
23
|
+
return patched.replace(/\x01(\d+)\x01/g, (_, i) => strings[parseInt(i, 10)]);
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Parse the raw HTTP response body. Throws TigerError when code != 0.
|
|
27
|
+
*
|
|
28
|
+
* patchLargeIntegers is applied before JSON.parse to preserve int64 order IDs
|
|
29
|
+
* (e.g. 28868646234578944) as strings rather than losing precision.
|
|
8
30
|
*/
|
|
9
31
|
export function parseApiResponse(body) {
|
|
10
|
-
const resp = JSON.parse(body);
|
|
32
|
+
const resp = JSON.parse(patchLargeIntegers(body));
|
|
11
33
|
if (resp.code !== 0) {
|
|
12
34
|
throw new TigerError(resp.code, resp.message);
|
|
13
35
|
}
|
|
@@ -15,16 +37,15 @@ export function parseApiResponse(body) {
|
|
|
15
37
|
}
|
|
16
38
|
/**
|
|
17
39
|
* Decode an ApiResponse.data payload into a typed value.
|
|
18
|
-
* Handles
|
|
19
|
-
*
|
|
40
|
+
* Handles double-encoded JSON (where `data` is a JSON string wrapping JSON),
|
|
41
|
+
* seen on some trade endpoints.
|
|
20
42
|
*/
|
|
21
43
|
export function unmarshalData(data) {
|
|
22
44
|
if (data == null)
|
|
23
45
|
return undefined;
|
|
24
46
|
if (typeof data === 'string') {
|
|
25
|
-
// Attempt to parse JSON string (double-encoded case)
|
|
26
47
|
try {
|
|
27
|
-
return JSON.parse(data);
|
|
48
|
+
return JSON.parse(patchLargeIntegers(data));
|
|
28
49
|
}
|
|
29
50
|
catch {
|
|
30
51
|
return data;
|
|
@@ -13,7 +13,9 @@ export function camelToSnake(key) {
|
|
|
13
13
|
/**
|
|
14
14
|
* Recursively convert all object keys from camelCase to snake_case.
|
|
15
15
|
* Preserves arrays, primitives, and Date/null/undefined.
|
|
16
|
-
*
|
|
16
|
+
*
|
|
17
|
+
* Note: camelToSnake is idempotent for pure snake_case keys (no uppercase
|
|
18
|
+
* letters → no replacements), so no pre-check is needed.
|
|
17
19
|
*/
|
|
18
20
|
export function keysToSnakeCase(value) {
|
|
19
21
|
if (Array.isArray(value)) {
|
|
@@ -22,8 +24,7 @@ export function keysToSnakeCase(value) {
|
|
|
22
24
|
if (value && typeof value === 'object' && value.constructor === Object) {
|
|
23
25
|
const out = {};
|
|
24
26
|
for (const [k, v] of Object.entries(value)) {
|
|
25
|
-
|
|
26
|
-
out[newKey] = keysToSnakeCase(v);
|
|
27
|
+
out[camelToSnake(k)] = keysToSnakeCase(v);
|
|
27
28
|
}
|
|
28
29
|
return out;
|
|
29
30
|
}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
|
|
7
|
-
|
|
1
|
+
import { TokenManager } from '../config/token-manager.js';
|
|
2
|
+
import { getSignContent } from '../signer/sign-content.js';
|
|
3
|
+
import { signWithRSA, verifyWithRSA } from '../signer/signer.js';
|
|
4
|
+
import { TigerError } from './errors.js';
|
|
5
|
+
import { defaultRetryPolicy } from './retry.js';
|
|
6
|
+
import { parseApiResponse, unmarshalData } from './api-response.js';
|
|
7
|
+
import { SDK_VERSION } from '../version.js';
|
|
8
8
|
/** User-Agent 字符串 */
|
|
9
9
|
const USER_AGENT = `openapi-typescript-sdk-${SDK_VERSION}`;
|
|
10
10
|
/** 默认字符集 */
|
|
@@ -13,14 +13,45 @@ const DEFAULT_CHARSET = 'UTF-8';
|
|
|
13
13
|
const DEFAULT_SIGN_TYPE = 'RSA';
|
|
14
14
|
/** 默认 API 版本 */
|
|
15
15
|
const DEFAULT_VERSION = '2.0';
|
|
16
|
+
/** Token 刷新 API 方法名 */
|
|
17
|
+
const METHOD_TOKEN_REFRESH = 'user_token_refresh';
|
|
18
|
+
/** 默认后台 token 检查间隔(毫秒):5 分钟 */
|
|
19
|
+
const DEFAULT_TOKEN_CHECK_INTERVAL = 5 * 60 * 1000;
|
|
16
20
|
/**
|
|
17
21
|
* HttpClient handles HTTP requests, signing, retry, and timeout
|
|
18
22
|
*/
|
|
19
23
|
export class HttpClient {
|
|
20
24
|
constructor(config, retryPolicy, options) {
|
|
25
|
+
/** non-null when auto-refresh is active */
|
|
26
|
+
this.tokenManager = null;
|
|
21
27
|
this.config = config;
|
|
22
28
|
this.retryPolicy = retryPolicy ?? defaultRetryPolicy();
|
|
23
29
|
this.targetUrl = options?.useQuoteServerUrl ? config.quoteServerUrl : config.serverUrl;
|
|
30
|
+
// Auto-start token refresh when tokenRefreshDuration is configured (mirrors Go SDK behaviour)
|
|
31
|
+
if (config.tokenRefreshDuration && config.tokenRefreshDuration > 0) {
|
|
32
|
+
const interval = config.tokenCheckInterval ?? DEFAULT_TOKEN_CHECK_INTERVAL;
|
|
33
|
+
const opts = {
|
|
34
|
+
refreshDuration: config.tokenRefreshDuration,
|
|
35
|
+
refreshInterval: interval,
|
|
36
|
+
};
|
|
37
|
+
if (config.tokenWriter) {
|
|
38
|
+
opts.tokenWriter = config.tokenWriter;
|
|
39
|
+
}
|
|
40
|
+
if (config.tokenLoader) {
|
|
41
|
+
opts.tokenLoader = config.tokenLoader;
|
|
42
|
+
}
|
|
43
|
+
this.tokenManager = this.startTokenAutoRefresh(null, opts);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Stop the background token auto-refresh timer.
|
|
48
|
+
* Call this when the HttpClient is no longer needed to avoid timer leaks.
|
|
49
|
+
*/
|
|
50
|
+
close() {
|
|
51
|
+
if (this.tokenManager) {
|
|
52
|
+
this.tokenManager.stopAutoRefresh();
|
|
53
|
+
this.tokenManager = null;
|
|
54
|
+
}
|
|
24
55
|
}
|
|
25
56
|
/**
|
|
26
57
|
* Build common request parameters
|
|
@@ -31,7 +62,11 @@ export class HttpClient {
|
|
|
31
62
|
method: apiMethod,
|
|
32
63
|
charset: DEFAULT_CHARSET,
|
|
33
64
|
sign_type: DEFAULT_SIGN_TYPE,
|
|
34
|
-
timestamp:
|
|
65
|
+
timestamp: (() => {
|
|
66
|
+
const d = new Date();
|
|
67
|
+
const pad = (n) => String(n).padStart(2, '0');
|
|
68
|
+
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
|
|
69
|
+
})(),
|
|
35
70
|
version: version || DEFAULT_VERSION,
|
|
36
71
|
biz_content: bizContent,
|
|
37
72
|
};
|
|
@@ -58,6 +93,7 @@ export class HttpClient {
|
|
|
58
93
|
const headers = {
|
|
59
94
|
'Content-Type': 'application/json;charset=UTF-8',
|
|
60
95
|
'User-Agent': USER_AGENT,
|
|
96
|
+
'Connection': 'close',
|
|
61
97
|
};
|
|
62
98
|
if (this.config.token) {
|
|
63
99
|
headers['Authorization'] = this.config.token;
|
|
@@ -68,7 +104,8 @@ export class HttpClient {
|
|
|
68
104
|
body,
|
|
69
105
|
signal: AbortSignal.timeout(this.config.timeout * 1000),
|
|
70
106
|
});
|
|
71
|
-
|
|
107
|
+
const text = await response.text();
|
|
108
|
+
return text;
|
|
72
109
|
}
|
|
73
110
|
/**
|
|
74
111
|
* Execute a structured API request, returning a parsed ApiResponse.
|
|
@@ -95,6 +132,10 @@ export class HttpClient {
|
|
|
95
132
|
}
|
|
96
133
|
catch (err) {
|
|
97
134
|
lastErr = err;
|
|
135
|
+
// Only retry on network errors, not API business errors (TigerError with code)
|
|
136
|
+
if (err.code !== undefined && err.code !== -1) {
|
|
137
|
+
throw err; // API returned a business error code, don't retry
|
|
138
|
+
}
|
|
98
139
|
if (!this.retryPolicy.shouldRetry(request.method)) {
|
|
99
140
|
throw err;
|
|
100
141
|
}
|
|
@@ -107,9 +148,10 @@ export class HttpClient {
|
|
|
107
148
|
*
|
|
108
149
|
* @param apiMethod - API method name (e.g. "market_state", "place_order")
|
|
109
150
|
* @param requestJson - Raw biz_content JSON string
|
|
151
|
+
* @param version - Optional API version override (default: "2.0")
|
|
110
152
|
* @returns Raw response JSON string, unparsed
|
|
111
153
|
*/
|
|
112
|
-
async execute(apiMethod, requestJson) {
|
|
154
|
+
async execute(apiMethod, requestJson, version) {
|
|
113
155
|
// Parameter validation
|
|
114
156
|
if (!apiMethod) {
|
|
115
157
|
throw new TigerError(-1, 'api_method must not be empty');
|
|
@@ -120,7 +162,7 @@ export class HttpClient {
|
|
|
120
162
|
catch {
|
|
121
163
|
throw new TigerError(-1, 'request_json is not valid JSON');
|
|
122
164
|
}
|
|
123
|
-
const params = this.buildCommonParams(apiMethod, requestJson);
|
|
165
|
+
const params = this.buildCommonParams(apiMethod, requestJson, version);
|
|
124
166
|
const sign = this.signParams(params);
|
|
125
167
|
params['sign'] = sign;
|
|
126
168
|
let lastErr;
|
|
@@ -141,6 +183,10 @@ export class HttpClient {
|
|
|
141
183
|
}
|
|
142
184
|
catch (err) {
|
|
143
185
|
lastErr = err;
|
|
186
|
+
// Don't retry API business errors
|
|
187
|
+
if (err.code !== undefined && err.code !== -1) {
|
|
188
|
+
throw err;
|
|
189
|
+
}
|
|
144
190
|
if (!this.retryPolicy.shouldRetry(apiMethod)) {
|
|
145
191
|
throw err;
|
|
146
192
|
}
|
|
@@ -148,6 +194,75 @@ export class HttpClient {
|
|
|
148
194
|
}
|
|
149
195
|
throw lastErr;
|
|
150
196
|
}
|
|
197
|
+
/**
|
|
198
|
+
* 调用 user_token_refresh 接口获取新 token,返回新 token 字符串。
|
|
199
|
+
* 此方法仅查询,不修改 config 中的 token。
|
|
200
|
+
*/
|
|
201
|
+
async queryToken() {
|
|
202
|
+
const params = this.buildCommonParams(METHOD_TOKEN_REFRESH, '{}');
|
|
203
|
+
const sign = this.signParams(params);
|
|
204
|
+
params['sign'] = sign;
|
|
205
|
+
const body = await this.doHttpPost(params);
|
|
206
|
+
const response = parseApiResponse(body);
|
|
207
|
+
this.verifyResponseSign(params['timestamp'], response.sign);
|
|
208
|
+
const data = unmarshalData(response.data);
|
|
209
|
+
const newToken = data?.token;
|
|
210
|
+
if (!newToken) {
|
|
211
|
+
throw new TigerError(-1, '服务端返回空 token');
|
|
212
|
+
}
|
|
213
|
+
return newToken;
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* 刷新 token:调用接口获取新 token 后更新 config.token。
|
|
217
|
+
*
|
|
218
|
+
* @param tokenManager - 可选外部 TokenManager;若提供则调用 setToken() 写文件并触发回调。
|
|
219
|
+
* 若 NewHttpClient 已自动启动内部 TokenManager,其内存 token 也会同步更新。
|
|
220
|
+
*/
|
|
221
|
+
async refreshToken(tokenManager) {
|
|
222
|
+
const newToken = await this.queryToken();
|
|
223
|
+
this.config.token = newToken;
|
|
224
|
+
// Keep internal tokenManager in sync so shouldTokenRefresh stays accurate.
|
|
225
|
+
if (this.tokenManager && tokenManager !== this.tokenManager) {
|
|
226
|
+
this.tokenManager.syncToken(newToken);
|
|
227
|
+
}
|
|
228
|
+
if (tokenManager) {
|
|
229
|
+
tokenManager.setToken(newToken);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* 启动后台 token 自动刷新。
|
|
234
|
+
*
|
|
235
|
+
* @param tokenManager - 可为 null:SDK 内部自动创建一个仅内存的 TokenManager,
|
|
236
|
+
* 适合直接通过 token 在代码里设置、不使用文件的场景。
|
|
237
|
+
* @param options - 仅在 tokenManager 为 null 时生效,用于配置内部 TokenManager
|
|
238
|
+
* (refreshDuration / refreshInterval / tokenWriter / tokenLoader)。
|
|
239
|
+
* @returns 使用或创建的 TokenManager 实例
|
|
240
|
+
*/
|
|
241
|
+
startTokenAutoRefresh(tokenManager, options) {
|
|
242
|
+
if (!tokenManager) {
|
|
243
|
+
tokenManager = new TokenManager(options);
|
|
244
|
+
// 从 config.token 同步当前 token,使 shouldTokenRefresh 能正确判断。
|
|
245
|
+
// 若 config.token 暂时为空(异步 tokenLoader 尚未 resolve),则先异步加载。
|
|
246
|
+
if (this.config.token) {
|
|
247
|
+
tokenManager.syncToken(this.config.token);
|
|
248
|
+
}
|
|
249
|
+
else if (options?.tokenLoader) {
|
|
250
|
+
// tokenLoader 可能是异步的;在后台 resolve 后同步到 config.token 和 TokenManager。
|
|
251
|
+
Promise.resolve(options.tokenLoader()).then((t) => {
|
|
252
|
+
if (t) {
|
|
253
|
+
this.config.token = t;
|
|
254
|
+
tokenManager.syncToken(t);
|
|
255
|
+
}
|
|
256
|
+
}).catch(() => { });
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
tokenManager.startAutoRefresh(async () => {
|
|
260
|
+
const newToken = await this.queryToken();
|
|
261
|
+
this.config.token = newToken;
|
|
262
|
+
return newToken;
|
|
263
|
+
});
|
|
264
|
+
return tokenManager;
|
|
265
|
+
}
|
|
151
266
|
/** Delay for the specified milliseconds */
|
|
152
267
|
sleep(ms) {
|
|
153
268
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
@@ -161,7 +276,8 @@ export class HttpClient {
|
|
|
161
276
|
*/
|
|
162
277
|
verifyResponseSign(timestamp, signBase64) {
|
|
163
278
|
if (!signBase64) {
|
|
164
|
-
|
|
279
|
+
// Some endpoints don't return a signature; skip verification silently.
|
|
280
|
+
return;
|
|
165
281
|
}
|
|
166
282
|
const valid = verifyWithRSA(this.config.tigerPublicKey, timestamp, signBase64);
|
|
167
283
|
if (!valid) {
|
package/dist/esm/client/index.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Transport layer exports.
|
|
3
3
|
*/
|
|
4
|
-
export { HttpClient } from './http-client';
|
|
5
|
-
export { TigerError, classifyErrorCode } from './errors';
|
|
6
|
-
export { RetryPolicy, defaultRetryPolicy, isTradeOperation } from './retry';
|
|
7
|
-
export { createApiRequest } from './api-request';
|
|
8
|
-
export { parseApiResponse, unmarshalData } from './api-response';
|
|
9
|
-
export { camelToSnake, keysToSnakeCase } from './case-convert';
|
|
4
|
+
export { HttpClient } from './http-client.js';
|
|
5
|
+
export { TigerError, classifyErrorCode } from './errors.js';
|
|
6
|
+
export { RetryPolicy, defaultRetryPolicy, isTradeOperation } from './retry.js';
|
|
7
|
+
export { createApiRequest } from './api-request.js';
|
|
8
|
+
export { parseApiResponse, unmarshalData } from './api-response.js';
|
|
9
|
+
export { camelToSnake, keysToSnakeCase } from './case-convert.js';
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Call the `user_token_refresh` API and return the new token string.
|
|
3
|
+
* Read-only: does NOT update the stored token.
|
|
4
|
+
* Use `refreshToken()` to also update the in-memory config and optionally persist.
|
|
5
|
+
*/
|
|
6
|
+
export async function queryToken(httpClient) {
|
|
7
|
+
return httpClient.queryToken();
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Refresh the token: call the API, update the in-memory config token, and
|
|
11
|
+
* optionally persist via the provided TokenManager (file + writer callback).
|
|
12
|
+
*
|
|
13
|
+
* @param httpClient - The underlying HTTP client
|
|
14
|
+
* @param tokenManager - optional TokenManager for file persistence and writer callback
|
|
15
|
+
*/
|
|
16
|
+
export async function refreshToken(httpClient, tokenManager) {
|
|
17
|
+
return httpClient.refreshToken(tokenManager);
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Start background token auto-refresh. Returns a TokenManager that can be
|
|
21
|
+
* used to stop the background task via `tm.stopAutoRefresh()`.
|
|
22
|
+
*
|
|
23
|
+
* @param httpClient - The underlying HTTP client
|
|
24
|
+
* @param refreshDurationSecs - Refresh threshold in seconds (minimum 30).
|
|
25
|
+
* When the token age exceeds this value the refresh is triggered.
|
|
26
|
+
* @param checkIntervalMs - How often to check whether a refresh is needed,
|
|
27
|
+
* in milliseconds. Defaults to 300 000 ms (5 minutes).
|
|
28
|
+
* @param tokenWriter - Optional callback invoked with the new token string
|
|
29
|
+
* after each successful refresh.
|
|
30
|
+
*/
|
|
31
|
+
export function startTokenAutoRefresh(httpClient, refreshDurationSecs, checkIntervalMs, tokenWriter) {
|
|
32
|
+
return httpClient.startTokenAutoRefresh(null, {
|
|
33
|
+
refreshDuration: refreshDurationSecs,
|
|
34
|
+
refreshInterval: checkIntervalMs,
|
|
35
|
+
tokenWriter,
|
|
36
|
+
});
|
|
37
|
+
}
|