@hitrading/ctp-node 1.2.0 → 3.0.0
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/CHANGELOG.md +67 -0
- package/README.md +52 -31
- package/README.zh-CN.md +42 -26
- package/RELEASING.md +78 -0
- package/binding.gyp +13 -13
- package/dist/client.d.ts +40 -15
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +241 -62
- package/dist/client.js.map +1 -1
- package/dist/codec.d.ts.map +1 -1
- package/dist/codec.js +84 -19
- package/dist/codec.js.map +1 -1
- package/dist/generated/structs.gen.d.ts +5461 -5461
- package/dist/generated/structs.gen.d.ts.map +1 -1
- package/dist/generated/trader.gen.d.ts.map +1 -1
- package/dist/generated/trader.gen.js +788 -94
- package/dist/generated/trader.gen.js.map +1 -1
- package/dist/index.cjs +1896 -420
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/market-data.d.ts +48 -21
- package/dist/market-data.d.ts.map +1 -1
- package/dist/market-data.js +165 -26
- package/dist/market-data.js.map +1 -1
- package/dist/native-binding.d.ts.map +1 -1
- package/dist/native-binding.js +5 -1
- package/dist/native-binding.js.map +1 -1
- package/dist/trader.d.ts +127 -79
- package/dist/trader.d.ts.map +1 -1
- package/dist/trader.js +788 -200
- package/dist/trader.js.map +1 -1
- package/dist/validation.d.ts +27 -0
- package/dist/validation.d.ts.map +1 -0
- package/dist/validation.js +85 -0
- package/dist/validation.js.map +1 -0
- package/docs/API.md +1437 -0
- package/docs/API.zh-CN.md +1278 -0
- package/docs/MIGRATION.md +54 -0
- package/docs/assets/validation.svg +27 -0
- package/docs/integration.md +60 -0
- package/docs/native-hooks.md +281 -0
- package/docs/native-hooks.zh-CN.md +205 -0
- package/docs/troubleshooting.md +257 -0
- package/docs/troubleshooting.zh-CN.md +220 -0
- package/package.json +14 -6
- package/prebuilds/linux-x64/@hitrading+ctp-node.node +0 -0
- package/prebuilds/win32-x64/@hitrading+ctp-node.node +0 -0
- package/scripts/bench-decode.mjs +37 -0
- package/scripts/bench-fullmarket-offline.mjs +207 -0
- package/scripts/stress-fullmarket.mjs +255 -0
- package/src/addon.cc +2 -2
- package/src/client.ts +263 -65
- package/src/codec.ts +86 -19
- package/src/generated/structs.gen.ts +5461 -5461
- package/src/generated/trader.gen.ts +309 -94
- package/src/generated/traderreq.gen.cc +194 -18
- package/src/generated/traderreq.gen.h +4 -0
- package/src/generated/traderspi.gen.cc +130 -10
- package/src/generated/traderspi.gen.h +4 -2
- package/src/index.ts +8 -1
- package/src/market-data.ts +219 -43
- package/src/native/arm.cc +114 -30
- package/src/native/arm.h +16 -4
- package/src/native/channel.cc +209 -81
- package/src/native/channel.h +65 -24
- package/src/native/ctp_field.h +23 -0
- package/src/native/mdapi.cc +621 -61
- package/src/native/mdspi.cc +221 -14
- package/src/native/mdspi.h +62 -9
- package/src/native/order_capability.h +75 -0
- package/src/native/risk.cc +2051 -205
- package/src/native/risk.h +450 -57
- package/src/native/shared_handle.h +37 -0
- package/src/native/snapshot.h +120 -0
- package/src/native/traderapi.cc +749 -170
- package/src/native-binding.ts +5 -1
- package/src/trader.ts +993 -229
- package/src/validation.ts +96 -0
- /package/{tradeapi → ctpsdk}/ThostFtdcMdApi.h +0 -0
- /package/{tradeapi → ctpsdk}/ThostFtdcTraderApi.h +0 -0
- /package/{tradeapi → ctpsdk}/ThostFtdcUserApiDataType.h +0 -0
- /package/{tradeapi → ctpsdk}/ThostFtdcUserApiStruct.h +0 -0
- /package/{tradeapi → ctpsdk}/error.dtd +0 -0
- /package/{tradeapi → ctpsdk}/error.xml +0 -0
- /package/{tradeapi → ctpsdk}/linux/thostmduserapi_se.so +0 -0
- /package/{tradeapi → ctpsdk}/linux/thosttraderapi_se.so +0 -0
- /package/{tradeapi → ctpsdk}/macos/thostmduserapi_se.framework/Versions/A/Headers/ThostFtdcMdApi.h +0 -0
- /package/{tradeapi → ctpsdk}/macos/thostmduserapi_se.framework/Versions/A/Headers/ThostFtdcUserApiDataType.h +0 -0
- /package/{tradeapi → ctpsdk}/macos/thostmduserapi_se.framework/Versions/A/Headers/ThostFtdcUserApiStruct.h +0 -0
- /package/{tradeapi → ctpsdk}/macos/thostmduserapi_se.framework/Versions/A/Resources/Info.plist +0 -0
- /package/{tradeapi → ctpsdk}/macos/thostmduserapi_se.framework/Versions/A/_CodeSignature/CodeResources +0 -0
- /package/{tradeapi → ctpsdk}/macos/thostmduserapi_se.framework/Versions/A/thostmduserapi_se +0 -0
- /package/{tradeapi → ctpsdk}/macos/thosttraderapi_se.framework/Versions/A/Headers/ThostFtdcTraderApi.h +0 -0
- /package/{tradeapi → ctpsdk}/macos/thosttraderapi_se.framework/Versions/A/Headers/ThostFtdcUserApiDataType.h +0 -0
- /package/{tradeapi → ctpsdk}/macos/thosttraderapi_se.framework/Versions/A/Headers/ThostFtdcUserApiStruct.h +0 -0
- /package/{tradeapi → ctpsdk}/macos/thosttraderapi_se.framework/Versions/A/Resources/Info.plist +0 -0
- /package/{tradeapi → ctpsdk}/macos/thosttraderapi_se.framework/Versions/A/_CodeSignature/CodeResources +0 -0
- /package/{tradeapi → ctpsdk}/macos/thosttraderapi_se.framework/Versions/A/thosttraderapi_se +0 -0
- /package/{tradeapi → ctpsdk}/windows/thostmduserapi_se.dll +0 -0
- /package/{tradeapi → ctpsdk}/windows/thostmduserapi_se.lib +0 -0
- /package/{tradeapi → ctpsdk}/windows/thosttraderapi_se.dll +0 -0
- /package/{tradeapi → ctpsdk}/windows/thosttraderapi_se.lib +0 -0
package/src/client.ts
CHANGED
|
@@ -40,6 +40,10 @@ const S_ERRID = 12;
|
|
|
40
40
|
const S_SID = 16;
|
|
41
41
|
const S_PLEN = 20;
|
|
42
42
|
const S_ERRMSG = 24;
|
|
43
|
+
// At one send per 1.1 s, an accidental Promise.all over thousands of queries
|
|
44
|
+
// otherwise creates a multi-hour, unbounded Promise backlog. Normal sequential
|
|
45
|
+
// use and bounded concurrency stay fully automatic.
|
|
46
|
+
const MAX_SCHEDULED_QUERIES = 256;
|
|
43
47
|
|
|
44
48
|
export interface RspInfo {
|
|
45
49
|
errorId: number;
|
|
@@ -69,7 +73,6 @@ export interface NativeClient {
|
|
|
69
73
|
_dropCount(): number;
|
|
70
74
|
// Present only on drop-oldest channels (market data); used by drainOldest().
|
|
71
75
|
_readIndex?(): number;
|
|
72
|
-
_validate?(claimed: number): number;
|
|
73
76
|
close(): void;
|
|
74
77
|
}
|
|
75
78
|
|
|
@@ -78,12 +81,13 @@ interface Pending {
|
|
|
78
81
|
resolve: (v: unknown) => void;
|
|
79
82
|
reject: (e: unknown) => void;
|
|
80
83
|
single: boolean;
|
|
84
|
+
zeroIdEvent?: number;
|
|
85
|
+
sessionTransition?: boolean;
|
|
81
86
|
timer?: ReturnType<typeof setTimeout>;
|
|
82
87
|
}
|
|
83
88
|
|
|
84
|
-
/** One
|
|
85
|
-
*
|
|
86
|
-
* before any handler runs. */
|
|
89
|
+
/** One decoded ring record. The keep-newest path decodes a claimed batch before
|
|
90
|
+
* delivery while native ownership prevents it from being displaced. */
|
|
87
91
|
interface DecodedRecord {
|
|
88
92
|
evt: number;
|
|
89
93
|
value: unknown;
|
|
@@ -91,10 +95,8 @@ interface DecodedRecord {
|
|
|
91
95
|
}
|
|
92
96
|
|
|
93
97
|
// --- Lifecycle tripwire (dev aid) --------------------------------------------
|
|
94
|
-
//
|
|
95
|
-
//
|
|
96
|
-
// vendor SDK (its api objects are not safe to create/Init/Release repeatedly),
|
|
97
|
-
// NOT a bug in this binding. Correct usage is to create each MarketData/Trader
|
|
98
|
+
// Repeated Init()->Release() cycles have been observed to hang inside the
|
|
99
|
+
// Windows CTP vendor DLL. Correct usage is to create each MarketData/Trader
|
|
98
100
|
// ONCE and reuse it, handling reconnects in place; a "reconnect by destroy-and-
|
|
99
101
|
// recreate" bug instead churns through clients and will eventually wedge the
|
|
100
102
|
// whole process. We count clients that were started (Init) and then closed
|
|
@@ -105,10 +107,8 @@ interface DecodedRecord {
|
|
|
105
107
|
// for any sane app (a few long-lived clients) and for the test suite. See
|
|
106
108
|
// docs/native-hooks.md ("Process lifecycle").
|
|
107
109
|
function recreateWarnThreshold(raw: string | undefined): number {
|
|
108
|
-
// Default 3: the
|
|
109
|
-
//
|
|
110
|
-
// very hang it warns about. 3 lets the warning print on the close() that
|
|
111
|
-
// precedes the typical wedge, while a create-once app (one or two long-lived
|
|
110
|
+
// Default 3: this warns before the low cycle counts at which hangs have been
|
|
111
|
+
// observed, while a create-once app (one or two long-lived
|
|
112
112
|
// clients closed at shutdown) stays under it. 0 disables.
|
|
113
113
|
const DEFAULT = 3;
|
|
114
114
|
if (raw === undefined) return DEFAULT;
|
|
@@ -128,8 +128,8 @@ function noteClientReleased(): void {
|
|
|
128
128
|
recreateWarned = true;
|
|
129
129
|
console.warn(
|
|
130
130
|
`[ctp-node] ${startedThenClosed} CTP clients have been created and closed ` +
|
|
131
|
-
`in this process.
|
|
132
|
-
`
|
|
131
|
+
`in this process. Repeated CTP Init()/Release() cycles have been observed ` +
|
|
132
|
+
`to hang inside the vendor DLL's Release(), so a MarketData/Trader must be created ONCE and ` +
|
|
133
133
|
`reused: handle reconnects in place (re-run your front-connected handshake), ` +
|
|
134
134
|
`never destroy and recreate the client. Set CTP_RECREATE_WARN=0 to silence, ` +
|
|
135
135
|
`or to another number to retune. See docs/native-hooks.md (Process lifecycle).`
|
|
@@ -152,12 +152,11 @@ export abstract class CtpClient extends EventEmitter {
|
|
|
152
152
|
private headerSize = 0;
|
|
153
153
|
private readPos = 0;
|
|
154
154
|
// Overflow policy of the underlying channel (from _info()). Drop-oldest (market
|
|
155
|
-
// data) takes the buffered drainOldest() path;
|
|
155
|
+
// data) takes the buffered drainOldest() path; lossless Trader uses inline
|
|
156
156
|
// drain(). See src/native/channel.h.
|
|
157
157
|
private dropOldest = false;
|
|
158
158
|
// Reused scratch holding a whole decoded batch for the drop-oldest path, so we
|
|
159
|
-
// can validate
|
|
160
|
-
// (a torn record never reaches a handler). Indices 0..count-1 are live per drain.
|
|
159
|
+
// can validate logical displacement after decoding and before delivery.
|
|
161
160
|
private batch: (DecodedRecord | undefined)[] = [];
|
|
162
161
|
// Set the instant close() begins. close() frees the native ring synchronously,
|
|
163
162
|
// so if an event handler invoked from drain() calls close() mid-batch, the
|
|
@@ -170,12 +169,18 @@ export abstract class CtpClient extends EventEmitter {
|
|
|
170
169
|
private started = false;
|
|
171
170
|
private readonly pending = new Map<number, Pending>();
|
|
172
171
|
private reqSeq = 0;
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
172
|
+
private queryQueue: Promise<void> = Promise.resolve();
|
|
173
|
+
// The first query must be eligible immediately even during the first 1.1 s
|
|
174
|
+
// of process uptime. Later sends replace this with a monotonic timestamp.
|
|
175
|
+
private lastQuerySentAt = Number.NEGATIVE_INFINITY;
|
|
176
|
+
private requestContextEpoch = 0;
|
|
177
|
+
// Counts only deliberate login/logout transitions. Front callbacks advance
|
|
178
|
+
// the context epoch but not this counter, which lets a compound handshake
|
|
179
|
+
// distinguish the one expected login invalidation from an inline disconnect.
|
|
180
|
+
private explicitRequestTransitionSeq = 0;
|
|
181
|
+
private queryInvalidationReason = "client context changed";
|
|
182
|
+
private scheduledQueries = 0;
|
|
183
|
+
private cancelQueryDelay?: () => void;
|
|
179
184
|
/** A request that goes idle this long (no response and, for multi-row queries,
|
|
180
185
|
* no further rows) rejects, so awaiters don't hang forever. The timer resets
|
|
181
186
|
* on each row, so a large streaming query isn't cut off by total duration. */
|
|
@@ -193,8 +198,11 @@ export abstract class CtpClient extends EventEmitter {
|
|
|
193
198
|
this.layouts = parseLayouts(layoutBlob);
|
|
194
199
|
this.decoders = new Array(this.layouts.length);
|
|
195
200
|
this.events = events;
|
|
196
|
-
// A
|
|
197
|
-
|
|
201
|
+
// A front transition invalidates both in-flight requests and query calls
|
|
202
|
+
// which are still queued behind them. This also covers providers that emit
|
|
203
|
+
// a new connected event without a preceding disconnected callback.
|
|
204
|
+
this.on("front-connected", () => this.invalidateRequestContext("front connected"));
|
|
205
|
+
this.on("front-disconnected", () => this.invalidateRequestContext("front disconnected"));
|
|
198
206
|
}
|
|
199
207
|
|
|
200
208
|
/** Reject and clear every in-flight request (on disconnect / close). */
|
|
@@ -208,6 +216,63 @@ export abstract class CtpClient extends EventEmitter {
|
|
|
208
216
|
}
|
|
209
217
|
}
|
|
210
218
|
|
|
219
|
+
/** Invalidate all work tied to the previous connection/login context.
|
|
220
|
+
* Subclasses call this immediately before a login/logout transition. */
|
|
221
|
+
protected invalidateRequestContext(reason: string): void {
|
|
222
|
+
this.requestContextEpoch++;
|
|
223
|
+
this.queryInvalidationReason = reason;
|
|
224
|
+
// Wake the sole query currently waiting for its spacing deadline so it can
|
|
225
|
+
// observe the new epoch. Tail entries then reject in queue order without
|
|
226
|
+
// ever reaching native code.
|
|
227
|
+
this.cancelQueryDelay?.();
|
|
228
|
+
this.cancelQueryDelay = undefined;
|
|
229
|
+
this.rejectAllPending(reason);
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** Begin a deliberate login/logout transition. Generated/manual public
|
|
233
|
+
* transition methods use this rather than calling invalidate directly. */
|
|
234
|
+
protected beginRequestContextTransition(reason: string): void {
|
|
235
|
+
this.explicitRequestTransitionSeq++;
|
|
236
|
+
this.invalidateRequestContext(reason);
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/** Capture/validate the connection-login epoch across a compound async
|
|
240
|
+
* operation. QueryRequest protects one queued send; session/sync helpers use
|
|
241
|
+
* this token so a later step cannot silently continue on a new front. */
|
|
242
|
+
protected requestContextToken(): number {
|
|
243
|
+
return this.requestContextEpoch;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
protected requestTransitionToken(): number {
|
|
247
|
+
return this.explicitRequestTransitionSeq;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
protected assertRequestContext(token: number, operation: string): void {
|
|
251
|
+
if (this.closing) throw new Error("client closed");
|
|
252
|
+
if (token !== this.requestContextEpoch) {
|
|
253
|
+
throw new Error(`${operation} invalidated: ${this.queryInvalidationReason}`);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** Internal state hook for a response that actually matched and successfully
|
|
258
|
+
* settled the current request. Streaming stale callbacks are still emitted to
|
|
259
|
+
* users, but cannot mutate a subclass's confirmed session identity. */
|
|
260
|
+
protected onRequestResolved(
|
|
261
|
+
_eventName: string | undefined,
|
|
262
|
+
_value: unknown,
|
|
263
|
+
_options: CallbackOptions
|
|
264
|
+
): void {}
|
|
265
|
+
|
|
266
|
+
/** Linearize a session-request idle timeout with native login/logout state.
|
|
267
|
+
* Subclasses return false when the final native callback already won the
|
|
268
|
+
* race and its non-droppable response is merely waiting to be drained. */
|
|
269
|
+
protected shouldTimeoutRequest(
|
|
270
|
+
_requestId: number,
|
|
271
|
+
_sessionTransition: boolean
|
|
272
|
+
): boolean {
|
|
273
|
+
return true;
|
|
274
|
+
}
|
|
275
|
+
|
|
211
276
|
/** Wire up the ring view + doorbell. Subclasses call this in their ctor. */
|
|
212
277
|
protected start(): void {
|
|
213
278
|
const info = this.native._info();
|
|
@@ -232,7 +297,7 @@ export abstract class CtpClient extends EventEmitter {
|
|
|
232
297
|
close(): void {
|
|
233
298
|
if (this.closing) return; // idempotent; also stops any in-progress drain
|
|
234
299
|
this.closing = true;
|
|
235
|
-
this.
|
|
300
|
+
this.invalidateRequestContext("client closed");
|
|
236
301
|
if (this.started) noteClientReleased(); // dev tripwire (see top of file)
|
|
237
302
|
this.native.close();
|
|
238
303
|
}
|
|
@@ -259,6 +324,14 @@ export abstract class CtpClient extends EventEmitter {
|
|
|
259
324
|
return d;
|
|
260
325
|
}
|
|
261
326
|
|
|
327
|
+
/** Decode one struct's raw bytes (e.g. a native snapshot) into a plain object,
|
|
328
|
+
* reusing the lazily-built per-struct decoder — the same codec the ring uses,
|
|
329
|
+
* so the result is identical to a streamed record. */
|
|
330
|
+
protected decodeStruct(structId: number, bytes: Uint8Array): Record<string, unknown> {
|
|
331
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
332
|
+
return this.decoderFor(structId)(view, bytes, 0);
|
|
333
|
+
}
|
|
334
|
+
|
|
262
335
|
private drain(): void {
|
|
263
336
|
let count = this.native._claim();
|
|
264
337
|
while (count > 0) {
|
|
@@ -287,19 +360,15 @@ export abstract class CtpClient extends EventEmitter {
|
|
|
287
360
|
}
|
|
288
361
|
|
|
289
362
|
/**
|
|
290
|
-
*
|
|
291
|
-
*
|
|
292
|
-
*
|
|
293
|
-
* many of the oldest records it overwrote *during* that decode (validate()),
|
|
294
|
-
* discard those (they hold torn bytes), and only then deliver the rest — so a
|
|
295
|
-
* torn record never reaches a handler. The records we do deliver are always the
|
|
296
|
-
* freshest available, and conservation holds (received + dropped == produced).
|
|
363
|
+
* Keep-newest drain (market data). Overflow is copied into native staging,
|
|
364
|
+
* never over a slot JS may be reading. A claimed batch is owned until release,
|
|
365
|
+
* so newer records can displace only the unclaimed logical window.
|
|
297
366
|
*/
|
|
298
367
|
private drainOldest(): void {
|
|
299
368
|
let count = this.native._claim();
|
|
300
369
|
while (count > 0) {
|
|
301
370
|
if (this.closing) return;
|
|
302
|
-
// claim() may have advanced readIdx_ past
|
|
371
|
+
// claim() may have advanced readIdx_ past displaced records; resync our slot
|
|
303
372
|
// cursor to the channel's authoritative read index before decoding.
|
|
304
373
|
this.readPos = (this.native._readIndex as () => number)();
|
|
305
374
|
const numSlots = this.numSlots;
|
|
@@ -309,16 +378,11 @@ export abstract class CtpClient extends EventEmitter {
|
|
|
309
378
|
const slot = ((this.readPos + i) % numSlots) * slotSize;
|
|
310
379
|
batch[i] = this.decodeSlot(slot);
|
|
311
380
|
}
|
|
312
|
-
// How many leading (oldest) records did the producer overwrite while we
|
|
313
|
-
// were decoding? Those are torn — discard them (validate() counts them as
|
|
314
|
-
// drops). The remainder were provably untouched during decode.
|
|
315
|
-
const torn = (this.native._validate as (n: number) => number)(count);
|
|
316
|
-
for (let i = 0; i < torn; i++) batch[i] = undefined; // release torn refs
|
|
317
381
|
if (this.closing) {
|
|
318
|
-
for (let i =
|
|
382
|
+
for (let i = 0; i < count; i++) batch[i] = undefined;
|
|
319
383
|
return;
|
|
320
384
|
}
|
|
321
|
-
for (let i =
|
|
385
|
+
for (let i = 0; i < count; i++) {
|
|
322
386
|
const rec = batch[i]!;
|
|
323
387
|
batch[i] = undefined;
|
|
324
388
|
// A handler from an earlier record this batch may have called close(),
|
|
@@ -355,15 +419,10 @@ export abstract class CtpClient extends EventEmitter {
|
|
|
355
419
|
const base = slot + this.headerSize;
|
|
356
420
|
|
|
357
421
|
let value: unknown;
|
|
358
|
-
//
|
|
359
|
-
//
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
// build over an undefined layout and throw. The torn record is discarded by
|
|
363
|
-
// validate() afterward, but the throw would escape the decode loop (which is
|
|
364
|
-
// not wrapped) and crash the doorbell callback. Bounding sid keeps decodeSlot
|
|
365
|
-
// total: an out-of-range sid yields an undefined value, harmlessly dropped.
|
|
366
|
-
if (plen > 0 && sid >= 0 && sid < this.layouts.length)
|
|
422
|
+
// Keep the decoder total even if a native/provider record contains a corrupt
|
|
423
|
+
// struct id. Staged overflow no longer mutates ring bytes during this read.
|
|
424
|
+
if (plen > 0 && sid >= 0 && sid < this.layouts.length &&
|
|
425
|
+
plen >= this.layouts[sid].size)
|
|
367
426
|
value = this.decoderFor(sid)(v, u8, base);
|
|
368
427
|
else if (sid === -2 && plen >= 4) value = v.getInt32(base, true);
|
|
369
428
|
else value = undefined;
|
|
@@ -391,15 +450,23 @@ export abstract class CtpClient extends EventEmitter {
|
|
|
391
450
|
|
|
392
451
|
// Responses (Rsp*) carry isLast (0/1 -> boolean); streaming pushes (Rtn*,
|
|
393
452
|
// front, …) use -1 (-> undefined). Correlate a response to its pending
|
|
394
|
-
// request by requestId
|
|
395
|
-
//
|
|
396
|
-
//
|
|
397
|
-
//
|
|
453
|
+
// request by requestId. SimNow's MD login/logout don't echo the id (server
|
|
454
|
+
// requestId 0), so those requests tag themselves with the event they await
|
|
455
|
+
// (zeroIdEvent); an id-0 response then matches only the pending request
|
|
456
|
+
// expecting THIS event — see the id-0 branch below.
|
|
398
457
|
if (options.isLast !== undefined && this.pending.size > 0) {
|
|
399
458
|
let key: number | undefined =
|
|
400
459
|
reqId !== 0 && this.pending.has(reqId) ? reqId : undefined;
|
|
401
|
-
if (key === undefined && reqId === 0
|
|
402
|
-
|
|
460
|
+
if (key === undefined && reqId === 0) {
|
|
461
|
+
// SimNow MD login/logout may return requestId 0. Match only a request
|
|
462
|
+
// that explicitly expects THIS response event; a concurrent logout can
|
|
463
|
+
// no longer consume a login response (or vice versa).
|
|
464
|
+
for (const [candidate, pending] of this.pending) {
|
|
465
|
+
if (pending.zeroIdEvent === evt) {
|
|
466
|
+
key = candidate;
|
|
467
|
+
break;
|
|
468
|
+
}
|
|
469
|
+
}
|
|
403
470
|
}
|
|
404
471
|
const p = key !== undefined ? this.pending.get(key) : undefined;
|
|
405
472
|
if (p && key !== undefined) {
|
|
@@ -417,7 +484,13 @@ export abstract class CtpClient extends EventEmitter {
|
|
|
417
484
|
if (options.isLast === true) {
|
|
418
485
|
if (p.timer) clearTimeout(p.timer);
|
|
419
486
|
this.pending.delete(key);
|
|
420
|
-
p.
|
|
487
|
+
const result = p.single ? p.rows[0] : p.rows;
|
|
488
|
+
try {
|
|
489
|
+
this.onRequestResolved(this.events.get(evt), result, options);
|
|
490
|
+
p.resolve(result);
|
|
491
|
+
} catch (error) {
|
|
492
|
+
p.reject(error);
|
|
493
|
+
}
|
|
421
494
|
} else {
|
|
422
495
|
this.armRequestTimer(key, p); // more rows expected: reset idle timeout
|
|
423
496
|
}
|
|
@@ -444,9 +517,12 @@ export abstract class CtpClient extends EventEmitter {
|
|
|
444
517
|
// getInt32, so the pending-map key MUST stay within positive int32 or it
|
|
445
518
|
// would stop matching the echoed wire id past 2^31 requests (responses would
|
|
446
519
|
// then only ever reject on the idle timeout). Cycle 1..2^31-1; skip 0, which
|
|
447
|
-
// is the "no id" / zeroIdFallback sentinel.
|
|
448
|
-
//
|
|
449
|
-
|
|
520
|
+
// is the "no id" / zeroIdFallback sentinel. Trader armed orders reserve the
|
|
521
|
+
// upper positive-int half (0x40000000..0x7fffffff), so a native arm error can
|
|
522
|
+
// never settle an unrelated JS request with the same id. Reuse cannot
|
|
523
|
+
// collide: nothing stays pending across a billion requests (idle timeout is
|
|
524
|
+
// seconds).
|
|
525
|
+
this.reqSeq = this.reqSeq >= 0x3fffffff ? 1 : this.reqSeq + 1;
|
|
450
526
|
return this.reqSeq;
|
|
451
527
|
}
|
|
452
528
|
|
|
@@ -464,9 +540,19 @@ export abstract class CtpClient extends EventEmitter {
|
|
|
464
540
|
case -10002:
|
|
465
541
|
return "rate limited (order rate exceeded)";
|
|
466
542
|
case -10003:
|
|
467
|
-
return "blocked by
|
|
543
|
+
return "blocked by position margin limit";
|
|
468
544
|
case -10004:
|
|
469
545
|
return "blocked by max position volume (lots)";
|
|
546
|
+
case -10005:
|
|
547
|
+
return "duplicate orderRef in this front/session";
|
|
548
|
+
case -10006:
|
|
549
|
+
return "request is unavailable in the current risk mode or cannot be fully covered by configured local risk controls";
|
|
550
|
+
case -10007:
|
|
551
|
+
return "required risk state or metadata unavailable (reconcile positions/orders and refresh price, multiplier and margin inputs)";
|
|
552
|
+
case -10008:
|
|
553
|
+
return "invalid order direction/hedge flag or unsupported combOffsetFlag (single-leg only)";
|
|
554
|
+
case -10009:
|
|
555
|
+
return "session transition already in flight or ambiguous; await it, or reconnect after a timeout";
|
|
470
556
|
default:
|
|
471
557
|
return undefined;
|
|
472
558
|
}
|
|
@@ -476,7 +562,13 @@ export abstract class CtpClient extends EventEmitter {
|
|
|
476
562
|
* Send a request and resolve when its response arrives (matched by id).
|
|
477
563
|
* `single` resolves with the one row; otherwise with the accumulated rows.
|
|
478
564
|
*/
|
|
479
|
-
protected request<T>(
|
|
565
|
+
protected request<T>(
|
|
566
|
+
send: (id: number) => number,
|
|
567
|
+
single = false,
|
|
568
|
+
zeroIdEvent?: number,
|
|
569
|
+
sessionTransition = false
|
|
570
|
+
): Promise<T> {
|
|
571
|
+
if (this.closing) return Promise.reject(new Error("client closed"));
|
|
480
572
|
const id = this.nextRequestId();
|
|
481
573
|
return new Promise<T>((resolve, reject) => {
|
|
482
574
|
const entry: Pending = {
|
|
@@ -484,6 +576,8 @@ export abstract class CtpClient extends EventEmitter {
|
|
|
484
576
|
resolve: resolve as (v: unknown) => void,
|
|
485
577
|
reject,
|
|
486
578
|
single,
|
|
579
|
+
zeroIdEvent,
|
|
580
|
+
sessionTransition,
|
|
487
581
|
};
|
|
488
582
|
this.pending.set(id, entry);
|
|
489
583
|
let rc: number;
|
|
@@ -497,21 +591,124 @@ export abstract class CtpClient extends EventEmitter {
|
|
|
497
591
|
if (rc !== 0) {
|
|
498
592
|
this.pending.delete(id);
|
|
499
593
|
const msg = this.riskRejectMessage(rc) ?? `request rejected by CTP API (code ${rc})`;
|
|
500
|
-
reject(new Error(msg));
|
|
594
|
+
reject(Object.assign(new Error(msg), { ctpReturnCode: rc }));
|
|
501
595
|
return;
|
|
502
596
|
}
|
|
503
597
|
// Backstop: if the request goes idle (no response / no further rows for a
|
|
504
598
|
// multi-row query), fail rather than hang forever.
|
|
505
|
-
|
|
599
|
+
// A provider is allowed to invoke the response callback inline from
|
|
600
|
+
// send(). In that case deliver() has already settled and removed this
|
|
601
|
+
// entry; do not leave a dead timeout behind for another 30 seconds.
|
|
602
|
+
if (this.pending.get(id) === entry) this.armRequestTimer(id, entry);
|
|
506
603
|
});
|
|
507
604
|
}
|
|
508
605
|
|
|
606
|
+
/** Serialize every ReqQry* / ReqQuery* call on this CTP client.
|
|
607
|
+
* CTP commonly allows about one query per second; putting the scheduler below
|
|
608
|
+
* the generated surface means raw concurrent reqQry* calls are covered too,
|
|
609
|
+
* not only the higher-level sync helpers. */
|
|
610
|
+
protected queryRequest<T>(
|
|
611
|
+
send: (id: number) => number,
|
|
612
|
+
single = false
|
|
613
|
+
): Promise<T> {
|
|
614
|
+
if (this.closing) return Promise.reject(new Error("client closed"));
|
|
615
|
+
if (this.scheduledQueries >= MAX_SCHEDULED_QUERIES) {
|
|
616
|
+
return Promise.reject(new Error(
|
|
617
|
+
`query queue is full (${MAX_SCHEDULED_QUERIES}); await earlier queries before submitting more`
|
|
618
|
+
));
|
|
619
|
+
}
|
|
620
|
+
this.scheduledQueries++;
|
|
621
|
+
const epoch = this.requestContextEpoch;
|
|
622
|
+
let resolveOuter!: (value: T | PromiseLike<T>) => void;
|
|
623
|
+
let rejectOuter!: (reason?: unknown) => void;
|
|
624
|
+
const outer = new Promise<T>((resolve, reject) => {
|
|
625
|
+
resolveOuter = resolve;
|
|
626
|
+
rejectOuter = reject;
|
|
627
|
+
});
|
|
628
|
+
const run = this.queryQueue.then(async () => {
|
|
629
|
+
const invalidReason = () => this.closing
|
|
630
|
+
? "client closed"
|
|
631
|
+
: epoch !== this.requestContextEpoch
|
|
632
|
+
? this.queryInvalidationReason
|
|
633
|
+
: undefined;
|
|
634
|
+
let reason = invalidReason();
|
|
635
|
+
if (reason !== undefined) {
|
|
636
|
+
rejectOuter(new Error(reason));
|
|
637
|
+
return;
|
|
638
|
+
}
|
|
639
|
+
// performance.now() is monotonic; a wall-clock adjustment must not turn a
|
|
640
|
+
// one-second query interval into an hours-long delay or a rate-limit burst.
|
|
641
|
+
// Re-check after every timer: Node may round or wake a timer slightly
|
|
642
|
+
// early, and the public contract is AT LEAST 1100 ms between attempts.
|
|
643
|
+
for (;;) {
|
|
644
|
+
reason = invalidReason();
|
|
645
|
+
if (reason !== undefined) {
|
|
646
|
+
rejectOuter(new Error(reason));
|
|
647
|
+
return;
|
|
648
|
+
}
|
|
649
|
+
const wait = 1100 - (performance.now() - this.lastQuerySentAt);
|
|
650
|
+
if (wait <= 0) break;
|
|
651
|
+
await new Promise<void>((resolve) => {
|
|
652
|
+
let settled = false;
|
|
653
|
+
const finish = () => {
|
|
654
|
+
if (settled) return;
|
|
655
|
+
settled = true;
|
|
656
|
+
clearTimeout(timer);
|
|
657
|
+
if (this.cancelQueryDelay === finish) this.cancelQueryDelay = undefined;
|
|
658
|
+
resolve();
|
|
659
|
+
};
|
|
660
|
+
const timer = setTimeout(finish, Math.ceil(wait));
|
|
661
|
+
this.cancelQueryDelay = finish;
|
|
662
|
+
});
|
|
663
|
+
}
|
|
664
|
+
reason = invalidReason();
|
|
665
|
+
if (reason !== undefined) {
|
|
666
|
+
rejectOuter(new Error(reason));
|
|
667
|
+
return;
|
|
668
|
+
}
|
|
669
|
+
this.lastQuerySentAt = performance.now();
|
|
670
|
+
try {
|
|
671
|
+
resolveOuter(await this.request<T>(send, single));
|
|
672
|
+
} catch (error) {
|
|
673
|
+
rejectOuter(error);
|
|
674
|
+
}
|
|
675
|
+
});
|
|
676
|
+
// Keep failures in scheduler plumbing observable by the caller too. The
|
|
677
|
+
// queue itself deliberately recovers below so one failed query cannot
|
|
678
|
+
// poison every later query.
|
|
679
|
+
void run.then(undefined, rejectOuter);
|
|
680
|
+
const releaseScheduledSlot = () => { this.scheduledQueries--; };
|
|
681
|
+
void run.then(releaseScheduledSlot, releaseScheduledSlot);
|
|
682
|
+
this.queryQueue = run.then(
|
|
683
|
+
() => undefined,
|
|
684
|
+
() => undefined
|
|
685
|
+
);
|
|
686
|
+
return outer;
|
|
687
|
+
}
|
|
688
|
+
|
|
509
689
|
/** (Re)arm a pending request's idle timeout. Called at send and reset on each
|
|
510
690
|
* row, so a long streaming query isn't cut off by total elapsed time. */
|
|
511
691
|
private armRequestTimer(id: number, entry: Pending): void {
|
|
512
692
|
if (this.requestTimeoutMs <= 0) return;
|
|
513
693
|
if (entry.timer) clearTimeout(entry.timer);
|
|
514
694
|
entry.timer = setTimeout(() => {
|
|
695
|
+
if (this.pending.get(id) !== entry) return;
|
|
696
|
+
let shouldTimeout: boolean;
|
|
697
|
+
try {
|
|
698
|
+
shouldTimeout = this.shouldTimeoutRequest(
|
|
699
|
+
id, entry.sessionTransition === true
|
|
700
|
+
);
|
|
701
|
+
} catch (error) {
|
|
702
|
+
if (this.pending.delete(id)) entry.reject(error);
|
|
703
|
+
return;
|
|
704
|
+
}
|
|
705
|
+
if (!shouldTimeout) {
|
|
706
|
+
// Native final processing already happened under its state lock. The
|
|
707
|
+
// control response is lossless, so wait for the queued row instead of
|
|
708
|
+
// manufacturing a timeout/native-session split brain.
|
|
709
|
+
this.armRequestTimer(id, entry);
|
|
710
|
+
return;
|
|
711
|
+
}
|
|
515
712
|
if (this.pending.delete(id)) entry.reject(new Error("request timed out"));
|
|
516
713
|
}, this.requestTimeoutMs);
|
|
517
714
|
if (typeof entry.timer.unref === "function") entry.timer.unref();
|
|
@@ -525,6 +722,7 @@ export abstract class CtpClient extends EventEmitter {
|
|
|
525
722
|
* rtn-trade events, correlating by orderRef.
|
|
526
723
|
*/
|
|
527
724
|
protected submit(send: (id: number) => number): Promise<void> {
|
|
725
|
+
if (this.closing) return Promise.reject(new Error("client closed"));
|
|
528
726
|
const id = this.nextRequestId();
|
|
529
727
|
let rc: number;
|
|
530
728
|
try {
|
|
@@ -534,6 +732,6 @@ export abstract class CtpClient extends EventEmitter {
|
|
|
534
732
|
}
|
|
535
733
|
if (rc === 0) return Promise.resolve();
|
|
536
734
|
const msg = this.riskRejectMessage(rc) ?? `order rejected by CTP API (code ${rc})`;
|
|
537
|
-
return Promise.reject(new Error(msg));
|
|
735
|
+
return Promise.reject(Object.assign(new Error(msg), { ctpReturnCode: rc }));
|
|
538
736
|
}
|
|
539
737
|
}
|