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
@@ -0,0 +1,241 @@
1
+ import { OAuth2DeviceAuthorization } from './device-authorization';
2
+ import { OAuth2Token } from './token';
3
+ import { type TokenStore } from './token-store';
4
+ export declare const ENV_ISSUER = "TIGEROPEN_OAUTH2_ISSUER";
5
+ /**
6
+ * Production authorization server. The environment variable or constructor argument
7
+ * overrides this value.
8
+ */
9
+ export declare const BUILTIN_ISSUER = "https://openapi-oauth2.tigerfintech.com";
10
+ /** How early to refresh an access token. */
11
+ export declare const DEFAULT_REFRESH_AHEAD_MILLIS: number;
12
+ /** Remaining lifetime below which a token is no longer handed out. */
13
+ export declare const MIN_USABLE_REMAINING_MILLIS: number;
14
+ /** How long to wait for the browser callback. */
15
+ export declare const DEFAULT_AUTHORIZE_TIMEOUT_SECONDS: number;
16
+ /**
17
+ * Fixed callback port for a manually configured clientId. Chosen to stay clear of the
18
+ * default Linux ephemeral range (from 32768) and of common dev ports.
19
+ */
20
+ export declare const DEFAULT_MANUAL_CALLBACK_PORT = 18888;
21
+ /**
22
+ * Application name registered by the SDK itself. Shown on the user's authorization
23
+ * page, so an entry point that registers its own client passes its own name.
24
+ */
25
+ export declare const CLIENT_NAME = "Tiger TypeScript SDK";
26
+ /** Receives the authorization URL. The SDK does not open a browser itself. */
27
+ export type AuthorizationUrlHandler = (url: string) => void | Promise<void>;
28
+ /** Receives the device authorization so the caller can display it. */
29
+ export type DeviceAuthorizationHandler = (device: OAuth2DeviceAuthorization) => void | Promise<void>;
30
+ export interface OAuth2SessionManagerOptions {
31
+ /** Authorization server; defaults to `TIGEROPEN_OAUTH2_ISSUER` or the built-in issuer */
32
+ issuer?: string;
33
+ /** Manually issued client ID; omit for dynamic registration */
34
+ clientId?: string;
35
+ /**
36
+ * Loopback port; 0 selects a system-assigned port for dynamic registration. Do not
37
+ * pass one in dynamic registration mode: it pins the registered redirect_uri to that
38
+ * port, and later dropping the argument leaves the registration behind.
39
+ */
40
+ callbackPort?: number;
41
+ /**
42
+ * Storage root; defaults to `TIGEROPEN_HOME` or `~/.tiger/openapi`. Ignored when
43
+ * `store` is provided
44
+ */
45
+ home?: string;
46
+ /**
47
+ * Persistence provider; when given, it owns its own surface and `surface` is ignored
48
+ */
49
+ store?: TokenStore;
50
+ /**
51
+ * Entry point owning the dynamic registration, e.g. `sdk-typescript`, `cli`, `mcp`.
52
+ * Each surface registers its own client, so it appears separately on the user's
53
+ * authorization page and can be revoked on its own. Tools built on this SDK must pass
54
+ * their own value
55
+ */
56
+ surface?: string;
57
+ /**
58
+ * Application name sent with dynamic registration and shown on the user's
59
+ * authorization page. A tool passing its own `surface` passes its own name too, or
60
+ * the user sees the SDK's name where the tool's belongs
61
+ */
62
+ clientName?: string;
63
+ /** Loopback callback timeout in seconds */
64
+ authorizeTimeoutSeconds?: number;
65
+ }
66
+ /** OAuth 2.0 authorization session manager. */
67
+ export declare class OAuth2SessionManager {
68
+ private readonly _issuer;
69
+ private readonly _callbackPort;
70
+ /** Fixed for the session because it determines storage keys and registration mode. */
71
+ private readonly explicitClientId;
72
+ private readonly authorizeTimeoutSeconds;
73
+ private readonly clientName;
74
+ private readonly store;
75
+ private registeredClientId;
76
+ private metadata;
77
+ private token;
78
+ private resolvedScopes;
79
+ /** In-flight refresh, so concurrent callers share one token request (single-flight). */
80
+ private refreshInFlight;
81
+ /** In-flight metadata discovery, so concurrent callers share one round trip. */
82
+ private metadataInFlight;
83
+ constructor(options?: OAuth2SessionManagerOptions);
84
+ static defaultIssuer(): string;
85
+ get issuer(): string;
86
+ /** Currently known clientId; undefined before registration in dynamic mode. */
87
+ get clientId(): string | undefined;
88
+ get hasExplicitClientId(): boolean;
89
+ get callbackPort(): number;
90
+ /** Scopes requested by this session, space-separated. Fetches metadata. */
91
+ scopes(): Promise<string>;
92
+ /**
93
+ * Create a default session and perform browser authorization when required.
94
+ *
95
+ * The callback receives the authorization URL; the SDK does not open a browser.
96
+ */
97
+ static loginWithDefaults(onAuthorizationUrl: AuthorizationUrlHandler): Promise<OAuth2SessionManager>;
98
+ /** Create a default session and perform device authorization when required. */
99
+ static loginWithDeviceCodeDefaults(onDeviceAuthorization: DeviceAuthorizationHandler): Promise<OAuth2SessionManager>;
100
+ /**
101
+ * Perform browser authorization with a loopback redirect and PKCE.
102
+ *
103
+ * @param onAuthorizationUrl callback receiving the authorization URL
104
+ */
105
+ login(onAuthorizationUrl: AuthorizationUrlHandler): Promise<OAuth2Token>;
106
+ /**
107
+ * Use the existing local authorization if usable, otherwise run a full loopback +
108
+ * PKCE authorization.
109
+ */
110
+ loginIfNeeded(onAuthorizationUrl: AuthorizationUrlHandler): Promise<OAuth2Token>;
111
+ /**
112
+ * Reuse local authorization or perform device authorization (RFC 8628).
113
+ *
114
+ * Device authorization supports environments without a local browser. Unlike loopback
115
+ * authorization with PKCE, it has no redirect binding or proof that the initiating and
116
+ * redeeming clients are the same party, increasing phishing risk. Loopback
117
+ * authorization is preferred when a local browser is available.
118
+ */
119
+ loginWithDeviceCodeIfNeeded(onDeviceAuthorization: DeviceAuthorizationHandler): Promise<OAuth2Token>;
120
+ /**
121
+ * Perform device authorization as defined by RFC 8628.
122
+ *
123
+ * This flow is intended for environments without a local browser and has the security
124
+ * limitations documented by {@link loginWithDeviceCodeIfNeeded}.
125
+ */
126
+ loginWithDeviceCode(onDeviceAuthorization: DeviceAuthorizationHandler): Promise<OAuth2Token>;
127
+ /**
128
+ * Revoke authorization under RFC 7009 and delete the local token.
129
+ *
130
+ * Dynamic client registration is retained across logout. The local token is deleted
131
+ * even if server-side revocation fails.
132
+ *
133
+ * @returns true when server-side revocation succeeds; false when only local state is
134
+ * cleared and the server credential may remain valid
135
+ */
136
+ logout(): Promise<boolean>;
137
+ /**
138
+ * Return a usable access token, refreshing near expiry.
139
+ *
140
+ * Throws `ReauthorizationRequired` when no authorization is available. Browser
141
+ * authorization is never started implicitly.
142
+ *
143
+ * A refresh being due does not make the caller wait for one. While the current token
144
+ * still has {@link MIN_USABLE_REMAINING_MILLIS} of life, a refresh already running
145
+ * elsewhere is left to finish and the current token is returned.
146
+ */
147
+ getAccessToken(): Promise<string>;
148
+ /** The current token, or undefined. Sends no requests and triggers no authorization. */
149
+ status(): OAuth2Token | undefined;
150
+ /**
151
+ * Whether asking for a token now would trigger a refresh. Reads memory only.
152
+ *
153
+ * Exists so no other component needs a refresh-ahead window of its own.
154
+ */
155
+ shouldRefreshSoon(): boolean;
156
+ isAuthorized(): boolean;
157
+ /** Refresh because the token is close to expiry. */
158
+ refresh(failedAccessToken?: string): Promise<OAuth2Token>;
159
+ /**
160
+ * Refresh after a 401 even when the token is not near expiry.
161
+ *
162
+ * @param failedAccessToken token used by the failed request; comparison with the
163
+ * current token detects rotation completed elsewhere and preserves single-flight
164
+ * refresh behavior
165
+ */
166
+ refreshAfterUnauthorized(failedAccessToken: string | undefined): Promise<OAuth2Token>;
167
+ /**
168
+ * Single-flight refresh: the first caller performs rotation while others await the
169
+ * same promise.
170
+ */
171
+ private doRefresh;
172
+ private refreshOnce;
173
+ /**
174
+ * Handle a refresh the authorization server rejected.
175
+ *
176
+ * Refresh tokens rotate, so the rejected value may already have been replaced by
177
+ * another process sharing this store. The store is re-read before any local state is
178
+ * removed, and the authorization is treated as ended only once the newest stored
179
+ * credential is rejected too.
180
+ */
181
+ private recoverOrGiveUp;
182
+ /** Exchange the given token's refresh token for a new access token and persist it. */
183
+ private exchangeRefreshToken;
184
+ /**
185
+ * Read the stored token from disk, bypassing the in-memory copy.
186
+ *
187
+ * @returns the stored token, or null when there is none or it cannot be read
188
+ */
189
+ private reloadFromStore;
190
+ /**
191
+ * Remove the local token, and the dynamic registration when that was refused.
192
+ *
193
+ * Only the credential that was refused is removed, and only while it is still the one
194
+ * on disk. Another process sharing the store may have replaced it in the meantime, and
195
+ * that replacement was never refused.
196
+ */
197
+ private forgetRejectedAuthorization;
198
+ /**
199
+ * Remove a refused dynamic client registration so the next authorization registers a
200
+ * new one. Explicit clientIds are left alone.
201
+ */
202
+ private forgetRejectedRegistration;
203
+ /**
204
+ * Return a reusable local token, refreshing it when required.
205
+ *
206
+ * @returns undefined when interactive authorization is required
207
+ */
208
+ private reusableToken;
209
+ private currentToken;
210
+ /**
211
+ * The known clientId, without triggering registration. Manual mode never reads
212
+ * `clients/`.
213
+ */
214
+ private knownClientId;
215
+ private persist;
216
+ private effectiveCallbackPort;
217
+ private resolveScopes;
218
+ private metadataOf;
219
+ /** Manual clientId > saved registration whose scopes still cover > register. */
220
+ private resolveClientId;
221
+ /**
222
+ * Register a public client under RFC 7591.
223
+ *
224
+ * Registration omits scope. The granted scope set is stored separately so a wider
225
+ * requirement triggers re-registration instead of `invalid_scope`.
226
+ */
227
+ private register;
228
+ private requestDeviceAuthorization;
229
+ /** Poll the token endpoint according to RFC 8628 response semantics. */
230
+ private pollForDeviceToken;
231
+ private exchange;
232
+ private toToken;
233
+ /**
234
+ * Attempt server-side revocation without throwing.
235
+ *
236
+ * The refresh token is preferred because RFC 7009 §2.1 permits revocation of its
237
+ * associated access tokens. RFC 7009 §2.2 also returns success for unknown or
238
+ * previously revoked tokens.
239
+ */
240
+ private revoke;
241
+ }
@@ -0,0 +1,49 @@
1
+ import { OAuth2ClientRegistration } from './client-registration';
2
+ import { OAuth2Token } from './token';
3
+ export declare const ENV_HOME = "TIGEROPEN_HOME";
4
+ /**
5
+ * Entry point owning a registration. Tools built on this SDK must pass their own value,
6
+ * otherwise they would be filed as the TypeScript SDK and share its client. Keep in
7
+ * step with the Java SDK's `sdk-java` and the Python SDK's `sdk-python`.
8
+ */
9
+ export declare const DEFAULT_SURFACE = "sdk-typescript";
10
+ /** Persistence provider contract, so a caller can store tokens somewhere else. */
11
+ export interface TokenStore {
12
+ loadToken(clientId: string, expectedIssuer?: string): OAuth2Token | null;
13
+ saveToken(token: OAuth2Token): void;
14
+ deleteToken(clientId: string): string | null;
15
+ loadClientId(issuer: string): string | null;
16
+ loadClientRegistration(issuer: string): OAuth2ClientRegistration | null;
17
+ saveClientRegistration(registration: OAuth2ClientRegistration): void;
18
+ deleteClientRegistration(issuer: string): void;
19
+ }
20
+ export declare class OAuth2TokenStore implements TokenStore {
21
+ readonly home: string;
22
+ readonly surface: string;
23
+ /**
24
+ * @param home storage root; defaults to `TIGEROPEN_HOME` then `~/.tiger/openapi`
25
+ * @param surface entry point owning the registration, e.g. `sdk-typescript`, `cli`.
26
+ * Lowercase alphanumerics and hyphens only
27
+ */
28
+ constructor(home?: string, surface?: string);
29
+ /** Load a token, treating a missing file or issuer mismatch as a cache miss. */
30
+ loadToken(clientId: string, expectedIssuer?: string): OAuth2Token | null;
31
+ saveToken(token: OAuth2Token): void;
32
+ /**
33
+ * Delete authorization state while retaining client registration.
34
+ *
35
+ * @returns the path removed, or null when there was nothing to remove. A clientId is
36
+ * not its own file name, so a caller reporting what it deleted has to be told rather
37
+ * than build the path itself
38
+ */
39
+ deleteToken(clientId: string): string | null;
40
+ loadClientId(issuer: string): string | null;
41
+ loadClientRegistration(issuer: string): OAuth2ClientRegistration | null;
42
+ saveClientRegistration(registration: OAuth2ClientRegistration): void;
43
+ /** Delete registration state after an `invalid_client` response. */
44
+ deleteClientRegistration(issuer: string): void;
45
+ private tokenFile;
46
+ private clientFile;
47
+ }
48
+ /** Return the Java-compatible 32-character SHA-256 issuer file key. */
49
+ export declare function hashIssuer(issuer: string): string;
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Persisted OAuth 2.0 authorization state.
3
+ *
4
+ * The `issuer` and `clientId` bind credentials to an authorization server and client,
5
+ * preventing credential reuse across environments. The on-disk field names are
6
+ * snake_case and shared with the Java and Python SDKs.
7
+ */
8
+ /** On-disk format version. An unrecognised version is an error, not a guess. */
9
+ export declare const TOKEN_SCHEMA_VERSION = 1;
10
+ export declare function currentMillis(): number;
11
+ /** Raw on-disk shape. */
12
+ export interface OAuth2TokenJson {
13
+ schema_version?: number;
14
+ issuer?: string;
15
+ client_id?: string;
16
+ access_token?: string;
17
+ refresh_token?: string;
18
+ token_type?: string;
19
+ scope?: string;
20
+ expires_at?: number;
21
+ }
22
+ /** An access token and its metadata. */
23
+ export declare class OAuth2Token {
24
+ schemaVersion: number;
25
+ issuer?: string;
26
+ clientId?: string;
27
+ accessToken?: string;
28
+ refreshToken?: string;
29
+ tokenType: string;
30
+ scope?: string;
31
+ /** Absolute expiry as epoch millis, not expires_in */
32
+ expiresAt: number;
33
+ constructor(init?: {
34
+ issuer?: string;
35
+ clientId?: string;
36
+ accessToken?: string;
37
+ refreshToken?: string;
38
+ tokenType?: string;
39
+ scope?: string;
40
+ expiresAt?: number;
41
+ schemaVersion?: number;
42
+ });
43
+ /** Time until expiry; negative once already expired. */
44
+ remainingMillis(): number;
45
+ /**
46
+ * @param aheadMillis how early to refresh. The window exists because time passes
47
+ * between sending a request and the server validating it, so using a token right up
48
+ * to its expiry produces intermittent 401s
49
+ */
50
+ needsRefresh(aheadMillis: number): boolean;
51
+ hasRefreshToken(): boolean;
52
+ toJSON(): OAuth2TokenJson;
53
+ static fromJSON(data: OAuth2TokenJson | null | undefined): OAuth2Token | null;
54
+ /** Prints no token values. */
55
+ toString(): string;
56
+ }
@@ -12,13 +12,15 @@ export interface ApiResponse {
12
12
  sign?: string;
13
13
  }
14
14
  /**
15
- * Parse the raw HTTP response body.
16
- * Throws TigerError when code != 0.
15
+ * Parse the raw HTTP response body. Throws TigerError when code != 0.
16
+ *
17
+ * patchLargeIntegers is applied before JSON.parse to preserve int64 order IDs
18
+ * (e.g. 28868646234578944) as strings rather than losing precision.
17
19
  */
18
20
  export declare function parseApiResponse(body: string): ApiResponse;
19
21
  /**
20
22
  * Decode an ApiResponse.data payload into a typed value.
21
- * Handles the server's occasional double-encoded JSON (where `data` is a
22
- * JSON string that itself wraps JSON), seen on some trade endpoints.
23
+ * Handles double-encoded JSON (where `data` is a JSON string wrapping JSON),
24
+ * seen on some trade endpoints.
23
25
  */
24
26
  export declare function unmarshalData<T>(data: unknown): T | undefined;
@@ -11,6 +11,8 @@ export declare function camelToSnake(key: string): string;
11
11
  /**
12
12
  * Recursively convert all object keys from camelCase to snake_case.
13
13
  * Preserves arrays, primitives, and Date/null/undefined.
14
- * Keys already containing an underscore are kept as-is (already snake_case).
14
+ *
15
+ * Note: camelToSnake is idempotent for pure snake_case keys (no uppercase
16
+ * letters → no replacements), so no pre-check is needed.
15
17
  */
16
18
  export declare function keysToSnakeCase(value: unknown): unknown;
@@ -5,6 +5,7 @@
5
5
  * Uses Node.js built-in fetch (Node 18+).
6
6
  */
7
7
  import type { ClientConfig } from '../config/client-config';
8
+ import { TokenManager, type TokenManagerOptions } from '../config/token-manager';
8
9
  import { RetryPolicy } from './retry';
9
10
  import { type ApiResponse } from './api-response';
10
11
  import type { ApiRequest } from './api-request';
@@ -16,9 +17,16 @@ export declare class HttpClient {
16
17
  private retryPolicy;
17
18
  /** Override the target URL (used by quote client to hit quote server) */
18
19
  private targetUrl;
20
+ /** non-null when auto-refresh is active */
21
+ private tokenManager;
19
22
  constructor(config: ClientConfig, retryPolicy?: RetryPolicy, options?: {
20
23
  useQuoteServerUrl?: boolean;
21
24
  });
25
+ /**
26
+ * Stop the background token auto-refresh timer.
27
+ * Call this when the HttpClient is no longer needed to avoid timer leaks.
28
+ */
29
+ close(): void;
22
30
  /**
23
31
  * Build common request parameters
24
32
  */
@@ -41,9 +49,32 @@ export declare class HttpClient {
41
49
  *
42
50
  * @param apiMethod - API method name (e.g. "market_state", "place_order")
43
51
  * @param requestJson - Raw biz_content JSON string
52
+ * @param version - Optional API version override (default: "2.0")
44
53
  * @returns Raw response JSON string, unparsed
45
54
  */
46
- execute(apiMethod: string, requestJson: string): Promise<string>;
55
+ execute(apiMethod: string, requestJson: string, version?: string): Promise<string>;
56
+ /**
57
+ * 调用 user_token_refresh 接口获取新 token,返回新 token 字符串。
58
+ * 此方法仅查询,不修改 config 中的 token。
59
+ */
60
+ queryToken(): Promise<string>;
61
+ /**
62
+ * 刷新 token:调用接口获取新 token 后更新 config.token。
63
+ *
64
+ * @param tokenManager - 可选外部 TokenManager;若提供则调用 setToken() 写文件并触发回调。
65
+ * 若 NewHttpClient 已自动启动内部 TokenManager,其内存 token 也会同步更新。
66
+ */
67
+ refreshToken(tokenManager?: TokenManager | null): Promise<void>;
68
+ /**
69
+ * 启动后台 token 自动刷新。
70
+ *
71
+ * @param tokenManager - 可为 null:SDK 内部自动创建一个仅内存的 TokenManager,
72
+ * 适合直接通过 token 在代码里设置、不使用文件的场景。
73
+ * @param options - 仅在 tokenManager 为 null 时生效,用于配置内部 TokenManager
74
+ * (refreshDuration / refreshInterval / tokenWriter / tokenLoader)。
75
+ * @returns 使用或创建的 TokenManager 实例
76
+ */
77
+ startTokenAutoRefresh(tokenManager: TokenManager | null, options?: TokenManagerOptions): TokenManager;
47
78
  /** Delay for the specified milliseconds */
48
79
  private sleep;
49
80
  /**
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Shared token management methods for TradeClient and QuoteClient.
3
+ * Both clients delegate to the underlying HttpClient; this module
4
+ * centralises the JSDoc so each client stays in sync automatically.
5
+ */
6
+ import type { HttpClient } from './http-client';
7
+ import type { TokenManager } from '../config/token-manager';
8
+ /**
9
+ * Call the `user_token_refresh` API and return the new token string.
10
+ * Read-only: does NOT update the stored token.
11
+ * Use `refreshToken()` to also update the in-memory config and optionally persist.
12
+ */
13
+ export declare function queryToken(httpClient: HttpClient): Promise<string>;
14
+ /**
15
+ * Refresh the token: call the API, update the in-memory config token, and
16
+ * optionally persist via the provided TokenManager (file + writer callback).
17
+ *
18
+ * @param httpClient - The underlying HTTP client
19
+ * @param tokenManager - optional TokenManager for file persistence and writer callback
20
+ */
21
+ export declare function refreshToken(httpClient: HttpClient, tokenManager?: TokenManager | null): Promise<void>;
22
+ /**
23
+ * Start background token auto-refresh. Returns a TokenManager that can be
24
+ * used to stop the background task via `tm.stopAutoRefresh()`.
25
+ *
26
+ * @param httpClient - The underlying HTTP client
27
+ * @param refreshDurationSecs - Refresh threshold in seconds (minimum 30).
28
+ * When the token age exceeds this value the refresh is triggered.
29
+ * @param checkIntervalMs - How often to check whether a refresh is needed,
30
+ * in milliseconds. Defaults to 300 000 ms (5 minutes).
31
+ * @param tokenWriter - Optional callback invoked with the new token string
32
+ * after each successful refresh.
33
+ */
34
+ export declare function startTokenAutoRefresh(httpClient: HttpClient, refreshDurationSecs: number, checkIntervalMs?: number, tokenWriter?: (token: string) => void): TokenManager;
@@ -1,14 +1,24 @@
1
+ /** Sandbox / QA tiger public key for response signature verification */
2
+ export declare const SANDBOX_TIGER_PUBLIC_KEY: string;
1
3
  /** Client configuration interface */
2
4
  export interface ClientConfig {
3
5
  tigerId: string;
4
6
  privateKey: string;
5
7
  account: string;
8
+ /** Institution secret key for trade authentication (institution accounts only) */
9
+ secretKey?: string;
6
10
  license?: string;
7
11
  language: string;
8
12
  timezone?: string;
9
13
  timeout: number;
10
14
  token?: string;
11
15
  tokenRefreshDuration?: number;
16
+ /** 后台 token 检查间隔(毫秒),仅 tokenRefreshDuration > 0 时生效,默认 5 分钟 */
17
+ tokenCheckInterval?: number;
18
+ /** 自定义 token 加载函数,替代默认的文件加载 */
19
+ tokenLoader?: () => Promise<string> | string;
20
+ /** token 刷新写入后的可选回调 */
21
+ tokenWriter?: (token: string) => void;
12
22
  serverUrl: string;
13
23
  /** Quote server URL for quote-specific requests; falls back to serverUrl */
14
24
  quoteServerUrl: string;
@@ -21,19 +31,30 @@ export interface ClientConfigOptions {
21
31
  tigerId?: string;
22
32
  privateKey?: string;
23
33
  account?: string;
34
+ /** Institution secret key for trade authentication (institution accounts only) */
35
+ secretKey?: string;
24
36
  license?: string;
25
37
  language?: string;
26
38
  timezone?: string;
27
39
  timeout?: number;
28
40
  token?: string;
29
41
  tokenRefreshDuration?: number;
42
+ /** 后台 token 检查间隔(毫秒),仅 tokenRefreshDuration > 0 时生效,默认 5 分钟 */
43
+ tokenCheckInterval?: number;
44
+ /** 自定义 token 加载函数,替代默认的文件加载 */
45
+ tokenLoader?: () => Promise<string> | string;
46
+ /** token 刷新写入后的可选回调 */
47
+ tokenWriter?: (token: string) => void;
30
48
  serverUrl?: string;
31
49
  /** Explicit quote server URL; resolved dynamically if not set */
32
50
  quoteServerUrl?: string;
33
51
  /** Enable dynamic domain resolution (default: true) */
34
52
  enableDynamicDomain?: boolean;
35
- /** Explicit properties file path (synchronous read) */
53
+ /** Explicit properties file path or directory (synchronous read).
54
+ * If a directory is given, appends 'tiger_openapi_config.properties' automatically. */
36
55
  propertiesFilePath?: string;
56
+ /** Override Tiger public key (e.g. for sandbox/QA environments) */
57
+ tigerPublicKey?: string;
37
58
  }
38
59
  /**
39
60
  * Load and parse a Java-style properties file.
@@ -2,6 +2,8 @@
2
2
  * 配置层导出
3
3
  */
4
4
  export { parsePropertiesFile, parsePropertiesString } from './config-parser';
5
- export { createClientConfig, loadPropertiesFile } from './client-config';
5
+ export { createClientConfig, loadPropertiesFile, SANDBOX_TIGER_PUBLIC_KEY } from './client-config';
6
6
  export type { ClientConfig, ClientConfigOptions } from './client-config';
7
+ export { TokenManager } from './token-manager';
8
+ export type { TokenManagerOptions, RefreshFn } from './token-manager';
7
9
  export { queryDomains, resolveDynamicServerUrl, resolveDynamicQuoteServerUrl } from './domain';
@@ -4,6 +4,10 @@ export interface TokenManagerOptions {
4
4
  refreshInterval?: number;
5
5
  /** Token 刷新阈值(秒),0 表示不刷新,最小 30 秒 */
6
6
  refreshDuration?: number;
7
+ /** 自定义 token 加载函数,优先于文件加载 */
8
+ tokenLoader?: () => Promise<string> | string;
9
+ /** token 写入后的回调(SetToken 成功后触发,SyncToken 不触发) */
10
+ tokenWriter?: (token: string) => void;
7
11
  }
8
12
  /** Token 刷新函数类型 */
9
13
  export type RefreshFn = () => Promise<string>;
@@ -13,16 +17,36 @@ export type RefreshFn = () => Promise<string>;
13
17
  export declare class TokenManager {
14
18
  private token;
15
19
  private filePath;
20
+ /** 仅当显式传入 filePath 时才写文件(fileEnabled = true) */
21
+ private fileEnabled;
16
22
  private refreshInterval;
17
23
  private refreshDuration;
18
24
  private timer;
25
+ private tokenLoader;
26
+ private tokenWriter;
19
27
  constructor(options?: TokenManagerOptions);
20
- /** 从 properties 文件加载 Token */
21
- loadToken(): string;
28
+ /**
29
+ * 从 properties 文件(或自定义 tokenLoader)加载 Token。
30
+ * 若设置了 tokenLoader,优先调用;否则从 properties 文件读取。
31
+ */
32
+ loadToken(): Promise<string>;
33
+ /**
34
+ * 同步版文件加载(仅用于无 tokenLoader 时的兼容入口)。
35
+ * 建议优先使用 loadToken()(异步)。
36
+ */
37
+ loadTokenSync(): string;
22
38
  /** 获取当前 Token */
23
39
  getToken(): string;
24
- /** 设置 Token 并更新文件 */
40
+ /**
41
+ * 设置 Token;若启用了文件持久化(显式传入 filePath),则同步写文件。
42
+ * 成功后触发 tokenWriter 回调(如有)。
43
+ */
25
44
  setToken(token: string): void;
45
+ /**
46
+ * 仅更新内存中的 token,不写文件,不触发 tokenWriter 回调。
47
+ * 用于多个组件共享 token 时的内部同步。
48
+ */
49
+ syncToken(token: string): void;
26
50
  /** 将 Token 保存到 properties 文件 */
27
51
  private saveTokenToFile;
28
52
  /**
@@ -15,4 +15,25 @@
15
15
  * @packageDocumentation
16
16
  */
17
17
  /** SDK 版本号 */
18
- export declare const VERSION = "0.4.0";
18
+ export { SDK_VERSION as VERSION } from './version';
19
+ export { createClientConfig, loadPropertiesFile, SANDBOX_TIGER_PUBLIC_KEY } from './config';
20
+ export type { ClientConfig, ClientConfigOptions } from './config';
21
+ export { TokenManager } from './config';
22
+ export type { TokenManagerOptions, RefreshFn } from './config';
23
+ export { HttpClient } from './client';
24
+ export { TigerError, classifyErrorCode } from './client';
25
+ export type { ErrorCategory } from './client';
26
+ export { QuoteClient, parseOptionIdentifier } from './quote';
27
+ export { TradeClient } from './trade';
28
+ export { PushClient, ConnectionState, SubjectType } from './push';
29
+ export type { PushClientOptions, AccountSubscribeOptions } from './push';
30
+ export type { Order, OrderRequest, ContractLegRequest } from './model/order';
31
+ export { marketOrder, limitOrder, stopOrder, stopLimitOrder } from './model/order-helpers';
32
+ export { normalizeOrderStatus } from './model/order-status';
33
+ export type { Contract } from './model/contract';
34
+ export type { Position } from './model/position';
35
+ export type { Asset, AssetSegment, PrimeAsset, PreviewResult, PlaceOrderResult, OrderIdResult, Transaction, ManagedAccount, AnalyticsAsset, AggregateAssets, EstimateTradableQuantity, ForexOrderResult, SegmentFund, SegmentFundAvailableItem, SegmentFundHistoryItem, FundDetails, FundingHistoryItem, PositionTransferRecord, PositionTransferDetail, PositionTransferExternalRecord, OptionExerciseCheckResult, OptionExercisePositionPageResult, OptionExerciseRecordPageResult, } from './model/trade';
36
+ export type { OrdersRequest, GetOrderRequest, OrderTransactionsRequest, PositionsRequest, AssetsRequest, ManagedAccountsRequest, DerivativeContractsRequest, AnalyticsAssetRequest, AggregateAssetsRequest, EstimateTradableQuantityRequest, ForexOrderRequest, SegmentFundRequest, FundDetailsRequest, FundingHistoryRequest, PositionTransferRequest, PositionTransferRecordsRequest, PositionTransferDetailRequest, PositionTransferExternalRecordsRequest, OptionExerciseCheckRequest, OptionExercisePositionRequest, OptionExerciseSubmitRequest, OptionExerciseRecordsRequest, OptionExerciseCancelRequest, } from './model/trade-requests';
37
+ export type { MarketState, Brief, Kline, KlineItem, Timeline, TimelineItem, TradeTick, TradeTickItem, Depth, DepthLevel, OptionExpiration, OptionChain, OptionChainRow, OptionSymbol, OptionChainFilter, OptionChainFilterGreeks, Range, FutureExchange, FutureContractInfo, FutureQuote, FutureKline, FutureKlineItem, FutureDepth, FutureTradeTickItem, FutureTradingTime, FinancialDailyItem, FinancialReportItem, CorporateAction, CorporateSymbolChange, CorporateDelisting, CorporateIPO, CapitalFlow, CapitalFlowItem, CapitalDistribution, ScannerResult, ScannerResultItem, QuotePermission, SymbolName, TradeMeta, StockDetail, StockBroker, StockBrokerItem, ShortInterest, StockIndustry, IndustryItem, IndustryStock, WarrantBrief, WarrantFilterResult, FundContractInfo, FundQuote, FundHistoryQuote, QuoteOvernight, KlineQuota, MarketScannerTag, MarketScannerTags, OptionAnalysis, OptionLeg, OptionVolatilityPoint, ExchangeRate, FinancialCurrency, BrokerDetail, TradingCalendarItem, FutureMainContractHistory, } from './model/quote';
38
+ export type { BriefRequest, DepthQuoteRequest, TradeTickRequest, KlineRequest, KlineByPageRequest, TimelineRequest, FutureBriefRequest, FutureKlineRequest, FutureKlineByPageRequest, FutureTradeTicksRequest, FutureDepthRequest, FutureContractSingleRequest, FutureContinuousContractsRequest, FutureHistoryMainContractRequest, FutureTradingTimesRequest, AllFutureContractsRequest, OptionTradeTicksRequest, OptionTimelineRequest, OptionDepthRequest, OptionSymbolsRequest, OptionAnalysisRequest, OptionQueryItem, ShortInterestRequest, StockBrokerRequest, StockDetailsRequest, StockFundamentalRequest, StockIndustryRequest, StockDelayBriefsRequest, SymbolsRequest, TradeMetasRequest, TradeRankRequest, TimelineHistoryRequest, TradingCalendarRequest, KlineQuotaRequest, QuotePermissionRequest, QuoteOvernightRequest, IndustryListRequest, IndustryStocksRequest, FundSymbolsRequest, FundContractsRequest, FundQuoteRequest, FundHistoryQuoteRequest, WarrantBriefsRequest, WarrantFilterRequest, MarketScannerTagsRequest, FinancialCurrencyRequest, FinancialExchangeRateRequest, } from './model/quote-requests';
39
+ export { OrderStatus, SecurityType, OrderType, TimeInForce, Market, Currency, QuoteRight, SegmentType, OrderSortBy, CorporateActionType, IndustryLevel, SortDirection, OptionAnalysisPeriod, FinancialReportPeriod, Language, License, BarPeriod, orderStatusCode, } from './model/enums';
@@ -42,7 +42,19 @@ export declare enum OrderType {
42
42
  AL = "AL",
43
43
  TWAP = "TWAP",
44
44
  VWAP = "VWAP",
45
- OCA = "OCA"
45
+ OCA = "OCA",
46
+ ICEBERG = "ICEBERG"
47
+ }
48
+ /** 冰山单价格类型 */
49
+ export declare enum PriceType {
50
+ /** 限价 */
51
+ LIMIT_PRICE = "LIMIT_PRICE",
52
+ /** 卖一价 */
53
+ ASK_PRICE = "ASK_PRICE",
54
+ /** 买一价 */
55
+ BID_PRICE = "BID_PRICE",
56
+ /** 最新价 */
57
+ LATEST_PRICE = "LATEST_PRICE"
46
58
  }
47
59
  /**
48
60
  * 订单状态枚举。对齐 Java SDK OrderStatus 定义。
@@ -103,6 +115,7 @@ export declare enum License {
103
115
  export declare enum TimeInForce {
104
116
  DAY = "DAY",
105
117
  GTC = "GTC",
118
+ GTD = "GTD",
106
119
  OPG = "OPG"
107
120
  }
108
121
  /** 订单排序字段 */
@@ -121,7 +134,10 @@ export declare enum SegmentType {
121
134
  export declare enum CorporateActionType {
122
135
  Split = "split",
123
136
  Dividend = "dividend",
124
- Earning = "earning"
137
+ Earning = "earning",
138
+ SymbolChange = "symbol_change",
139
+ Delisting = "delisting",
140
+ IPO = "ipo"
125
141
  }
126
142
  /** 行业级别 (1~4 级) */
127
143
  export declare enum IndustryLevel {