@hitrading/ctp-node 1.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.
Files changed (102) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +208 -0
  3. package/README.zh-CN.md +185 -0
  4. package/binding.gyp +90 -0
  5. package/dist/client.d.ts +115 -0
  6. package/dist/client.d.ts.map +1 -0
  7. package/dist/client.js +466 -0
  8. package/dist/client.js.map +1 -0
  9. package/dist/codec.d.ts +29 -0
  10. package/dist/codec.d.ts.map +1 -0
  11. package/dist/codec.js +131 -0
  12. package/dist/codec.js.map +1 -0
  13. package/dist/generated/enums.gen.d.ts +2257 -0
  14. package/dist/generated/enums.gen.d.ts.map +1 -0
  15. package/dist/generated/enums.gen.js +2576 -0
  16. package/dist/generated/enums.gen.js.map +1 -0
  17. package/dist/generated/structs.gen.d.ts +11041 -0
  18. package/dist/generated/structs.gen.d.ts.map +1 -0
  19. package/dist/generated/structs.gen.js +939 -0
  20. package/dist/generated/structs.gen.js.map +1 -0
  21. package/dist/generated/trader.gen.d.ts +273 -0
  22. package/dist/generated/trader.gen.d.ts.map +1 -0
  23. package/dist/generated/trader.gen.js +653 -0
  24. package/dist/generated/trader.gen.js.map +1 -0
  25. package/dist/index.d.ts +9 -0
  26. package/dist/index.d.ts.map +1 -0
  27. package/dist/index.js +9 -0
  28. package/dist/index.js.map +1 -0
  29. package/dist/market-data.d.ts +66 -0
  30. package/dist/market-data.d.ts.map +1 -0
  31. package/dist/market-data.js +105 -0
  32. package/dist/market-data.js.map +1 -0
  33. package/dist/native-binding.d.ts +2 -0
  34. package/dist/native-binding.d.ts.map +1 -0
  35. package/dist/native-binding.js +22 -0
  36. package/dist/native-binding.js.map +1 -0
  37. package/dist/trader.d.ts +234 -0
  38. package/dist/trader.d.ts.map +1 -0
  39. package/dist/trader.js +388 -0
  40. package/dist/trader.js.map +1 -0
  41. package/package.json +69 -0
  42. package/prebuilds/linux-x64/@hitrading+ctp-node.node +0 -0
  43. package/prebuilds/linux-x64/thostmduserapi_se.so +0 -0
  44. package/prebuilds/linux-x64/thosttraderapi_se.so +0 -0
  45. package/prebuilds/win32-x64/@hitrading+ctp-node.node +0 -0
  46. package/prebuilds/win32-x64/thostmduserapi_se.dll +0 -0
  47. package/prebuilds/win32-x64/thosttraderapi_se.dll +0 -0
  48. package/src/addon.cc +171 -0
  49. package/src/client.ts +539 -0
  50. package/src/codec.ts +160 -0
  51. package/src/generated/enums.gen.ts +2576 -0
  52. package/src/generated/layout.gen.cc +5771 -0
  53. package/src/generated/layout.gen.h +8 -0
  54. package/src/generated/structids.gen.h +470 -0
  55. package/src/generated/structs.gen.ts +12437 -0
  56. package/src/generated/trader.gen.ts +656 -0
  57. package/src/generated/traderreq.gen.cc +706 -0
  58. package/src/generated/traderreq.gen.h +127 -0
  59. package/src/generated/traderspi.gen.cc +636 -0
  60. package/src/generated/traderspi.gen.h +334 -0
  61. package/src/index.ts +14 -0
  62. package/src/market-data.ts +145 -0
  63. package/src/native/arm.cc +77 -0
  64. package/src/native/arm.h +71 -0
  65. package/src/native/channel.cc +175 -0
  66. package/src/native/channel.h +117 -0
  67. package/src/native/gbk.cc +54 -0
  68. package/src/native/gbk.h +17 -0
  69. package/src/native/mdapi.cc +412 -0
  70. package/src/native/mdapi.h +14 -0
  71. package/src/native/mdspi.cc +103 -0
  72. package/src/native/mdspi.h +81 -0
  73. package/src/native/risk.cc +461 -0
  74. package/src/native/risk.h +183 -0
  75. package/src/native/traderapi.cc +533 -0
  76. package/src/native/traderapi.h +14 -0
  77. package/src/native-binding.ts +25 -0
  78. package/src/trader.ts +522 -0
  79. package/tradeapi/ThostFtdcMdApi.h +168 -0
  80. package/tradeapi/ThostFtdcTraderApi.h +914 -0
  81. package/tradeapi/ThostFtdcUserApiDataType.h +7068 -0
  82. package/tradeapi/ThostFtdcUserApiStruct.h +12386 -0
  83. package/tradeapi/error.dtd +9 -0
  84. package/tradeapi/error.xml +284 -0
  85. package/tradeapi/linux/thostmduserapi_se.so +0 -0
  86. package/tradeapi/linux/thosttraderapi_se.so +0 -0
  87. package/tradeapi/macos/thostmduserapi_se.framework/Versions/A/Headers/ThostFtdcMdApi.h +168 -0
  88. package/tradeapi/macos/thostmduserapi_se.framework/Versions/A/Headers/ThostFtdcUserApiDataType.h +7068 -0
  89. package/tradeapi/macos/thostmduserapi_se.framework/Versions/A/Headers/ThostFtdcUserApiStruct.h +12386 -0
  90. package/tradeapi/macos/thostmduserapi_se.framework/Versions/A/Resources/Info.plist +46 -0
  91. package/tradeapi/macos/thostmduserapi_se.framework/Versions/A/_CodeSignature/CodeResources +149 -0
  92. package/tradeapi/macos/thostmduserapi_se.framework/Versions/A/thostmduserapi_se +0 -0
  93. package/tradeapi/macos/thosttraderapi_se.framework/Versions/A/Headers/ThostFtdcTraderApi.h +914 -0
  94. package/tradeapi/macos/thosttraderapi_se.framework/Versions/A/Headers/ThostFtdcUserApiDataType.h +7068 -0
  95. package/tradeapi/macos/thosttraderapi_se.framework/Versions/A/Headers/ThostFtdcUserApiStruct.h +12386 -0
  96. package/tradeapi/macos/thosttraderapi_se.framework/Versions/A/Resources/Info.plist +46 -0
  97. package/tradeapi/macos/thosttraderapi_se.framework/Versions/A/_CodeSignature/CodeResources +149 -0
  98. package/tradeapi/macos/thosttraderapi_se.framework/Versions/A/thosttraderapi_se +0 -0
  99. package/tradeapi/windows/thostmduserapi_se.dll +0 -0
  100. package/tradeapi/windows/thostmduserapi_se.lib +0 -0
  101. package/tradeapi/windows/thosttraderapi_se.dll +0 -0
  102. package/tradeapi/windows/thosttraderapi_se.lib +0 -0
package/src/client.ts ADDED
@@ -0,0 +1,539 @@
1
+ /*
2
+ * client.ts - shared base for MarketData and Trader.
3
+ *
4
+ * Owns the JS side of the data plane: on each coalesced doorbell it drains the
5
+ * whole ring, decodes each record straight from the zero-copy buffer into a
6
+ * plain object, and dispatches it - emitting a named event AND, when the record
7
+ * is a response to an in-flight request (matched by requestId), settling its
8
+ * Promise (accumulating multi-row query responses until isLast).
9
+ *
10
+ * Slot header offsets must match src/native/channel.h.
11
+ */
12
+
13
+ import { EventEmitter } from "node:events";
14
+ import {
15
+ parseLayouts,
16
+ buildDecoder,
17
+ encodeStruct,
18
+ readStr,
19
+ type Decoder,
20
+ type StructLayout,
21
+ } from "./codec.js";
22
+ import { STRUCTS } from "./generated/structs.gen.js";
23
+ import { native as addon } from "./native-binding.js";
24
+
25
+ /** Encode a request string field: ASCII fast path; GB18030 (CTP's wire charset,
26
+ * via native) for the rare non-ASCII field. */
27
+ function encodeReqString(s: string): Uint8Array {
28
+ for (let i = 0; i < s.length; i++) {
29
+ if (s.charCodeAt(i) > 0x7f) return new Uint8Array(addon.__gbkEncode(s));
30
+ }
31
+ const a = new Uint8Array(s.length);
32
+ for (let i = 0; i < s.length; i++) a[i] = s.charCodeAt(i);
33
+ return a;
34
+ }
35
+
36
+ const S_EVENT = 0;
37
+ const S_REQID = 4;
38
+ const S_ISLAST = 8;
39
+ const S_ERRID = 12;
40
+ const S_SID = 16;
41
+ const S_PLEN = 20;
42
+ const S_ERRMSG = 24;
43
+
44
+ export interface RspInfo {
45
+ errorId: number;
46
+ errorMsg: string;
47
+ }
48
+
49
+ export interface CallbackOptions {
50
+ /** Request id this record answers (for req/rsp correlation). */
51
+ requestId?: number;
52
+ /** Whether this is the last record of the response. */
53
+ isLast?: boolean;
54
+ /** Present only when CTP reported an error (errorId !== 0). */
55
+ rspInfo?: RspInfo;
56
+ }
57
+
58
+ export interface NativeClient {
59
+ _start(drain: () => void): void;
60
+ _buffer(): ArrayBuffer;
61
+ _claim(): number;
62
+ _release(n: number): void;
63
+ _info(): {
64
+ slotSize: number;
65
+ numSlots: number;
66
+ headerSize: number;
67
+ dropOldest: boolean;
68
+ };
69
+ _dropCount(): number;
70
+ // Present only on drop-oldest channels (market data); used by drainOldest().
71
+ _readIndex?(): number;
72
+ _validate?(claimed: number): number;
73
+ close(): void;
74
+ }
75
+
76
+ interface Pending {
77
+ rows: unknown[];
78
+ resolve: (v: unknown) => void;
79
+ reject: (e: unknown) => void;
80
+ single: boolean;
81
+ timer?: ReturnType<typeof setTimeout>;
82
+ }
83
+
84
+ /** One record decoded out of the ring, split from delivery so the drop-oldest
85
+ * path can decode a whole batch, then discard any torn (overwritten) records,
86
+ * before any handler runs. */
87
+ interface DecodedRecord {
88
+ evt: number;
89
+ value: unknown;
90
+ options: CallbackOptions;
91
+ }
92
+
93
+ // --- Lifecycle tripwire (dev aid) --------------------------------------------
94
+ // The CTP vendor DLLs deadlock inside Release() after a handful of
95
+ // Init()->Release() cycles in one process - a long-standing limitation of the
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
+ // ONCE and reuse it, handling reconnects in place; a "reconnect by destroy-and-
99
+ // recreate" bug instead churns through clients and will eventually wedge the
100
+ // whole process. We count clients that were started (Init) and then closed
101
+ // (Release) process-wide and warn ONCE past a threshold, so that bug surfaces in
102
+ // dev / logs before it hangs in production. This lives only on close()
103
+ // (teardown) - never the hot data path - so it costs nothing where latency
104
+ // matters. Tune with CTP_RECREATE_WARN (0 disables); the default stays silent
105
+ // for any sane app (a few long-lived clients) and for the test suite. See
106
+ // docs/native-hooks.md ("Process lifecycle").
107
+ function recreateWarnThreshold(raw: string | undefined): number {
108
+ // Default 3: the vendor DLL deadlocks inside Release() after only ~4
109
+ // Init()/Release() cycles, so a higher threshold would never fire before the
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
112
+ // clients closed at shutdown) stays under it. 0 disables.
113
+ const DEFAULT = 3;
114
+ if (raw === undefined) return DEFAULT;
115
+ const n = Number(raw);
116
+ return Number.isFinite(n) && n >= 0 ? Math.floor(n) : DEFAULT;
117
+ }
118
+ const RECREATE_WARN_THRESHOLD = recreateWarnThreshold(process.env.CTP_RECREATE_WARN);
119
+ let startedThenClosed = 0;
120
+ let recreateWarned = false;
121
+ function noteClientReleased(): void {
122
+ startedThenClosed += 1;
123
+ if (
124
+ RECREATE_WARN_THRESHOLD > 0 &&
125
+ !recreateWarned &&
126
+ startedThenClosed > RECREATE_WARN_THRESHOLD
127
+ ) {
128
+ recreateWarned = true;
129
+ console.warn(
130
+ `[ctp-node] ${startedThenClosed} CTP clients have been created and closed ` +
131
+ `in this process. The CTP vendor DLLs deadlock inside Release() after a few ` +
132
+ `Init()/Release() cycles, so a MarketData/Trader must be created ONCE and ` +
133
+ `reused: handle reconnects in place (re-run your front-connected handshake), ` +
134
+ `never destroy and recreate the client. Set CTP_RECREATE_WARN=0 to silence, ` +
135
+ `or to another number to retune. See docs/native-hooks.md (Process lifecycle).`
136
+ );
137
+ }
138
+ }
139
+
140
+ export abstract class CtpClient extends EventEmitter {
141
+ // Inherently dynamic N-API object; the NativeClient interface documents the
142
+ // contract the data plane relies on.
143
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
144
+ protected readonly native: any;
145
+ private readonly layouts: StructLayout[];
146
+ private readonly decoders: (Decoder | undefined)[];
147
+ private readonly events: Map<number, string>;
148
+ private view!: DataView;
149
+ private u8!: Uint8Array;
150
+ private slotSize = 0;
151
+ private numSlots = 0;
152
+ private headerSize = 0;
153
+ private readPos = 0;
154
+ // Overflow policy of the underlying channel (from _info()). Drop-oldest (market
155
+ // data) takes the buffered drainOldest() path; drop-newest (trader) the inline
156
+ // drain(). See src/native/channel.h.
157
+ private dropOldest = false;
158
+ // Reused scratch holding a whole decoded batch for the drop-oldest path, so we
159
+ // can validate against producer overruns *after* decoding and before delivering
160
+ // (a torn record never reaches a handler). Indices 0..count-1 are live per drain.
161
+ private batch: (DecodedRecord | undefined)[] = [];
162
+ // Set the instant close() begins. close() frees the native ring synchronously,
163
+ // so if an event handler invoked from drain() calls close() mid-batch, the
164
+ // rest of that batch must NOT keep reading the (now freed) ring view. Every
165
+ // drain loop checks this and bails the moment it flips.
166
+ private closing = false;
167
+ // True once start() has run the native Init(). Gates the lifecycle tripwire
168
+ // above: only a started-then-closed client is an Init()/Release() pair (the
169
+ // cycle the vendor DLL deadlocks on); a never-started object closes harmlessly.
170
+ private started = false;
171
+ private readonly pending = new Map<number, Pending>();
172
+ private reqSeq = 0;
173
+ /** Event ids whose requestId-0 response should resolve the oldest pending
174
+ * request. Needed only for SimNow market-data login/logout, which don't echo
175
+ * the id; scoping to those events means an unrelated id-0 response
176
+ * (sub/unsub/error) can't hijack them. The trader echoes ids and leaves this
177
+ * empty. */
178
+ protected readonly zeroIdFallbackEvents = new Set<number>();
179
+ /** A request that goes idle this long (no response and, for multi-row queries,
180
+ * no further rows) rejects, so awaiters don't hang forever. The timer resets
181
+ * on each row, so a large streaming query isn't cut off by total duration. */
182
+ protected requestTimeoutMs = 30000;
183
+
184
+ protected constructor(
185
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
186
+ native: any,
187
+ layoutBlob: Int32Array,
188
+ events: Map<number, string>
189
+ ) {
190
+ super();
191
+ this.setMaxListeners(0);
192
+ this.native = native;
193
+ this.layouts = parseLayouts(layoutBlob);
194
+ this.decoders = new Array(this.layouts.length);
195
+ this.events = events;
196
+ // A dropped connection won't deliver in-flight responses - fail them fast.
197
+ this.on("front-disconnected", () => this.rejectAllPending("front disconnected"));
198
+ }
199
+
200
+ /** Reject and clear every in-flight request (on disconnect / close). */
201
+ private rejectAllPending(reason: string): void {
202
+ if (this.pending.size === 0) return;
203
+ const err = new Error(reason);
204
+ for (const [id, p] of this.pending) {
205
+ if (p.timer) clearTimeout(p.timer);
206
+ this.pending.delete(id);
207
+ p.reject(err);
208
+ }
209
+ }
210
+
211
+ /** Wire up the ring view + doorbell. Subclasses call this in their ctor. */
212
+ protected start(): void {
213
+ const info = this.native._info();
214
+ this.slotSize = info.slotSize;
215
+ this.numSlots = info.numSlots;
216
+ this.headerSize = info.headerSize;
217
+ this.dropOldest = !!info.dropOldest;
218
+ const ab = this.native._buffer();
219
+ this.view = new DataView(ab);
220
+ this.u8 = new Uint8Array(ab);
221
+ this.native._start(
222
+ this.dropOldest ? () => this.drainOldest() : () => this.drain()
223
+ );
224
+ this.started = true;
225
+ }
226
+
227
+ /** Records dropped under backpressure (ring full). Monitor this. */
228
+ get droppedRecords(): number {
229
+ return this.native._dropCount();
230
+ }
231
+
232
+ close(): void {
233
+ if (this.closing) return; // idempotent; also stops any in-progress drain
234
+ this.closing = true;
235
+ this.rejectAllPending("client closed");
236
+ if (this.started) noteClientReleased(); // dev tripwire (see top of file)
237
+ this.native.close();
238
+ }
239
+
240
+ /** Re-surface an exception thrown by a user event handler without letting it
241
+ * break the drain loop. By the time this runs (next tick) the ring has
242
+ * already advanced, so the feed never wedges. If the app subscribes to
243
+ * 'error' the exception is routed there (catchable); otherwise it is rethrown
244
+ * as an uncaughtException — the normal fate of a throwing EventEmitter
245
+ * listener, just deferred so the data plane stays consistent. */
246
+ private surfaceHandlerError(err: unknown): void {
247
+ setImmediate(() => {
248
+ if (this.listenerCount("error") > 0) this.emit("error", err);
249
+ else throw err;
250
+ });
251
+ }
252
+
253
+ private decoderFor(id: number): Decoder {
254
+ let d = this.decoders[id];
255
+ if (d === undefined) {
256
+ d = buildDecoder(id, this.layouts[id]);
257
+ this.decoders[id] = d;
258
+ }
259
+ return d;
260
+ }
261
+
262
+ private drain(): void {
263
+ let count = this.native._claim();
264
+ while (count > 0) {
265
+ const numSlots = this.numSlots;
266
+ const slotSize = this.slotSize;
267
+ for (let i = 0; i < count; i++) {
268
+ // A handler in the previous dispatch() may have called close(), which
269
+ // frees the ring; stop before reading freed memory for the next record.
270
+ if (this.closing) return;
271
+ const slot = ((this.readPos + i) % numSlots) * slotSize;
272
+ try {
273
+ this.dispatch(slot);
274
+ } catch (err) {
275
+ // A user event handler threw. Never let it wedge the data plane: the
276
+ // ring MUST keep advancing, else this record re-delivers forever and
277
+ // every record behind it stalls (silently, under Node's default
278
+ // listener-exception policy). Absorb here; re-surface on the next tick.
279
+ this.surfaceHandlerError(err);
280
+ }
281
+ }
282
+ if (this.closing) return;
283
+ this.native._release(count);
284
+ this.readPos += count;
285
+ count = this.native._claim();
286
+ }
287
+ }
288
+
289
+ /**
290
+ * Drop-oldest drain (market data). The producer overwrites the oldest unread
291
+ * record when full and never blocks, so the consumer can be lapped mid-read.
292
+ * We therefore decode the whole claimed batch first, then ask the channel how
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).
297
+ */
298
+ private drainOldest(): void {
299
+ let count = this.native._claim();
300
+ while (count > 0) {
301
+ if (this.closing) return;
302
+ // claim() may have advanced readIdx_ past lapped records; resync our slot
303
+ // cursor to the channel's authoritative read index before decoding.
304
+ this.readPos = (this.native._readIndex as () => number)();
305
+ const numSlots = this.numSlots;
306
+ const slotSize = this.slotSize;
307
+ const batch = this.batch;
308
+ for (let i = 0; i < count; i++) {
309
+ const slot = ((this.readPos + i) % numSlots) * slotSize;
310
+ batch[i] = this.decodeSlot(slot);
311
+ }
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
+ if (this.closing) {
318
+ for (let i = torn; i < count; i++) batch[i] = undefined;
319
+ return;
320
+ }
321
+ for (let i = torn; i < count; i++) {
322
+ const rec = batch[i]!;
323
+ batch[i] = undefined;
324
+ // A handler from an earlier record this batch may have called close(),
325
+ // which frees the ring. The decoded objects are safe (already copied out
326
+ // of the ring), but stop delivering so app semantics match drain().
327
+ if (this.closing) continue;
328
+ try {
329
+ this.deliver(rec);
330
+ } catch (err) {
331
+ this.surfaceHandlerError(err);
332
+ }
333
+ }
334
+ if (this.closing) return;
335
+ this.native._release(count);
336
+ this.readPos += count;
337
+ count = this.native._claim();
338
+ }
339
+ }
340
+
341
+ private dispatch(slot: number): void {
342
+ this.deliver(this.decodeSlot(slot));
343
+ }
344
+
345
+ /** Decode one slot into a record (pure read of the ring; no side effects). */
346
+ private decodeSlot(slot: number): DecodedRecord {
347
+ const v = this.view;
348
+ const u8 = this.u8;
349
+ const evt = v.getInt32(slot + S_EVENT, true);
350
+ const reqId = v.getInt32(slot + S_REQID, true);
351
+ const isLastRaw = v.getInt32(slot + S_ISLAST, true);
352
+ const errId = v.getInt32(slot + S_ERRID, true);
353
+ const sid = v.getInt32(slot + S_SID, true);
354
+ const plen = v.getInt32(slot + S_PLEN, true);
355
+ const base = slot + this.headerSize;
356
+
357
+ let value: unknown;
358
+ // sid bounds check (sid < layouts.length): under the drop-oldest path a slot
359
+ // may be overwritten while we decode it (a torn read). The header int32s are
360
+ // normally read old-or-new intact, but DataView.getInt32 atomicity isn't
361
+ // guaranteed, so a torn sid could land out of range; decoderFor() would then
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)
367
+ value = this.decoderFor(sid)(v, u8, base);
368
+ else if (sid === -2 && plen >= 4) value = v.getInt32(base, true);
369
+ else value = undefined;
370
+
371
+ const rspInfo: RspInfo | undefined =
372
+ errId !== 0
373
+ ? { errorId: errId, errorMsg: readStr(u8, slot + S_ERRMSG, 81) }
374
+ : undefined;
375
+
376
+ const options: CallbackOptions = {
377
+ requestId: reqId !== 0 ? reqId : undefined,
378
+ isLast: isLastRaw === -1 ? undefined : isLastRaw === 1,
379
+ rspInfo,
380
+ };
381
+ return { evt, value, options };
382
+ }
383
+
384
+ /** Settle any matching in-flight request, then emit the named event. Side
385
+ * effects only — reads no ring memory, so it is safe to call after the
386
+ * producer may have advanced (drainOldest decodes before this runs). */
387
+ private deliver(rec: DecodedRecord): void {
388
+ const { evt, value, options } = rec;
389
+ const reqId = options.requestId ?? 0;
390
+ const rspInfo = options.rspInfo;
391
+
392
+ // Responses (Rsp*) carry isLast (0/1 -> boolean); streaming pushes (Rtn*,
393
+ // front, …) use -1 (-> undefined). Correlate a response to its pending
394
+ // request by requestId; only for the configured zeroIdFallbackEvent
395
+ // (MarketData's login) do we resolve a server requestId of 0 against the
396
+ // oldest pending request — SimNow's MD login doesn't echo the id. Scoping to
397
+ // that one event keeps an unrelated id-0 response from hijacking a request.
398
+ if (options.isLast !== undefined && this.pending.size > 0) {
399
+ let key: number | undefined =
400
+ reqId !== 0 && this.pending.has(reqId) ? reqId : undefined;
401
+ if (key === undefined && reqId === 0 && this.zeroIdFallbackEvents.has(evt)) {
402
+ key = this.pending.keys().next().value;
403
+ }
404
+ const p = key !== undefined ? this.pending.get(key) : undefined;
405
+ if (p && key !== undefined) {
406
+ if (rspInfo) {
407
+ if (p.timer) clearTimeout(p.timer);
408
+ this.pending.delete(key);
409
+ p.reject(
410
+ Object.assign(
411
+ new Error(rspInfo.errorMsg || `CTP error ${rspInfo.errorId}`),
412
+ rspInfo
413
+ )
414
+ );
415
+ } else {
416
+ if (value !== undefined) p.rows.push(value);
417
+ if (options.isLast === true) {
418
+ if (p.timer) clearTimeout(p.timer);
419
+ this.pending.delete(key);
420
+ p.resolve(p.single ? p.rows[0] : p.rows);
421
+ } else {
422
+ this.armRequestTimer(key, p); // more rows expected: reset idle timeout
423
+ }
424
+ }
425
+ }
426
+ }
427
+
428
+ const name = this.events.get(evt);
429
+ this.emit(name ?? `event:${evt}`, value, options);
430
+ }
431
+
432
+ /** Encode a plain object into a struct's raw bytes (for req* encoders). */
433
+ protected encode(structId: number, obj: Record<string, unknown>): Uint8Array {
434
+ return encodeStruct(
435
+ this.layouts[structId],
436
+ STRUCTS[structId].fields,
437
+ obj,
438
+ encodeReqString
439
+ );
440
+ }
441
+
442
+ protected nextRequestId(): number {
443
+ // CTP echoes the requestId as an int32, and dispatch() reads it back via
444
+ // getInt32, so the pending-map key MUST stay within positive int32 or it
445
+ // would stop matching the echoed wire id past 2^31 requests (responses would
446
+ // then only ever reject on the idle timeout). Cycle 1..2^31-1; skip 0, which
447
+ // is the "no id" / zeroIdFallback sentinel. (Reuse can't collide: nothing
448
+ // stays pending across 2^31 requests — the idle timeout is seconds.)
449
+ this.reqSeq = this.reqSeq >= 0x7fffffff ? 1 : this.reqSeq + 1;
450
+ return this.reqSeq;
451
+ }
452
+
453
+ /** Message for a non-zero send code. Risk sentinels get a specific message;
454
+ * the generic pre-trade-risk block also appends the C++ reason (e.g. which
455
+ * limit) so logs say *why*. Returns undefined for non-risk codes. */
456
+ private riskRejectMessage(rc: number): string | undefined {
457
+ switch (rc) {
458
+ case -10001: {
459
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
460
+ const reason =
461
+ typeof this.native.lastRiskReason === "function" ? this.native.lastRiskReason() : "";
462
+ return reason ? `blocked by pre-trade risk: ${reason}` : "blocked by pre-trade risk";
463
+ }
464
+ case -10002:
465
+ return "rate limited (order rate exceeded)";
466
+ case -10003:
467
+ return "blocked by max position cost";
468
+ case -10004:
469
+ return "blocked by max position volume (lots)";
470
+ default:
471
+ return undefined;
472
+ }
473
+ }
474
+
475
+ /**
476
+ * Send a request and resolve when its response arrives (matched by id).
477
+ * `single` resolves with the one row; otherwise with the accumulated rows.
478
+ */
479
+ protected request<T>(send: (id: number) => number, single = false): Promise<T> {
480
+ const id = this.nextRequestId();
481
+ return new Promise<T>((resolve, reject) => {
482
+ const entry: Pending = {
483
+ rows: [],
484
+ resolve: resolve as (v: unknown) => void,
485
+ reject,
486
+ single,
487
+ };
488
+ this.pending.set(id, entry);
489
+ let rc: number;
490
+ try {
491
+ rc = send(id);
492
+ } catch (e) {
493
+ this.pending.delete(id);
494
+ reject(e);
495
+ return;
496
+ }
497
+ if (rc !== 0) {
498
+ this.pending.delete(id);
499
+ const msg = this.riskRejectMessage(rc) ?? `request rejected by CTP API (code ${rc})`;
500
+ reject(new Error(msg));
501
+ return;
502
+ }
503
+ // Backstop: if the request goes idle (no response / no further rows for a
504
+ // multi-row query), fail rather than hang forever.
505
+ this.armRequestTimer(id, entry);
506
+ });
507
+ }
508
+
509
+ /** (Re)arm a pending request's idle timeout. Called at send and reset on each
510
+ * row, so a long streaming query isn't cut off by total elapsed time. */
511
+ private armRequestTimer(id: number, entry: Pending): void {
512
+ if (this.requestTimeoutMs <= 0) return;
513
+ if (entry.timer) clearTimeout(entry.timer);
514
+ entry.timer = setTimeout(() => {
515
+ if (this.pending.delete(id)) entry.reject(new Error("request timed out"));
516
+ }, this.requestTimeoutMs);
517
+ if (typeof entry.timer.unref === "function") entry.timer.unref();
518
+ }
519
+
520
+ /**
521
+ * Submit a fire-and-forget order/action. Exchange-bound inserts get no
522
+ * success response from CTP (only a rejection), so this resolves as soon as
523
+ * CTP accepts the send and rejects if the send is refused. Track the order's
524
+ * actual lifecycle (accepted / filled / cancelled) via the rtn-order and
525
+ * rtn-trade events, correlating by orderRef.
526
+ */
527
+ protected submit(send: (id: number) => number): Promise<void> {
528
+ const id = this.nextRequestId();
529
+ let rc: number;
530
+ try {
531
+ rc = send(id);
532
+ } catch (e) {
533
+ return Promise.reject(e);
534
+ }
535
+ if (rc === 0) return Promise.resolve();
536
+ const msg = this.riskRejectMessage(rc) ?? `order rejected by CTP API (code ${rc})`;
537
+ return Promise.reject(new Error(msg));
538
+ }
539
+ }
package/src/codec.ts ADDED
@@ -0,0 +1,160 @@
1
+ /*
2
+ * codec.ts — turn the C++ layout blob into fast, plain-object decoders.
3
+ *
4
+ * Offsets/sizes come from native (offsetof/sizeof truth); field names + kinds
5
+ * from the generated descriptors. For each struct we compile a monomorphic
6
+ * literal decoder via `new Function` once, so the hot path is a single fixed-
7
+ * shape object literal (V8 builds these at tens of millions/sec) — no per-field
8
+ * dispatch, no per-tick native calls.
9
+ *
10
+ * Strings decode lazily-friendly with an ASCII fast path and fall back to
11
+ * gb18030 (Node full-ICU) only when high bytes appear — which also sidesteps
12
+ * the old binding's Windows code-page bug.
13
+ */
14
+
15
+ import { STRUCTS } from "./generated/structs.gen.js";
16
+
17
+ export interface FieldLayout {
18
+ offset: number;
19
+ size: number;
20
+ kind: number; // 0 string, 1 int32, 2 int16, 3 double
21
+ }
22
+ export interface StructLayout {
23
+ size: number;
24
+ fields: FieldLayout[];
25
+ }
26
+
27
+ /** Parse the packed Int32 blob from native `__layoutData()`. */
28
+ export function parseLayouts(data: Int32Array): StructLayout[] {
29
+ const out: StructLayout[] = [];
30
+ let p = 0;
31
+ const n = data[p++];
32
+ for (let i = 0; i < n; i++) {
33
+ const size = data[p++];
34
+ const fc = data[p++];
35
+ const fields: FieldLayout[] = new Array(fc);
36
+ for (let j = 0; j < fc; j++) {
37
+ fields[j] = { offset: data[p++], size: data[p++], kind: data[p++] };
38
+ }
39
+ out.push({ size, fields });
40
+ }
41
+ return out;
42
+ }
43
+
44
+ const gbk = new TextDecoder("gb18030");
45
+
46
+ /** Read a fixed-width C string field; ASCII fast path, gb18030 fallback. */
47
+ export function readStr(u8: Uint8Array, off: number, size: number): string {
48
+ let end = off;
49
+ const lim = off + size;
50
+ let ascii = true;
51
+ while (end < lim && u8[end] !== 0) {
52
+ if (u8[end] >= 0x80) ascii = false;
53
+ end++;
54
+ }
55
+ if (end === off) return "";
56
+ if (ascii) {
57
+ let s = "";
58
+ for (let i = off; i < end; i++) s += String.fromCharCode(u8[i]);
59
+ return s;
60
+ }
61
+ return gbk.decode(u8.subarray(off, end));
62
+ }
63
+
64
+ export type Decoder = (
65
+ view: DataView,
66
+ u8: Uint8Array,
67
+ base: number
68
+ ) => Record<string, unknown>;
69
+
70
+ /** Compile a plain-object decoder for one struct from its layout. */
71
+ export function buildDecoder(structId: number, layout: StructLayout): Decoder {
72
+ const desc = STRUCTS[structId];
73
+ if (!desc) throw new Error(`codec: no descriptor for struct id ${structId}`);
74
+ if (desc.fields.length !== layout.fields.length) {
75
+ throw new Error(
76
+ `codec: field-count mismatch for ${desc.name} ` +
77
+ `(layout ${layout.fields.length} vs descriptor ${desc.fields.length})`
78
+ );
79
+ }
80
+
81
+ const parts: string[] = [];
82
+ for (let i = 0; i < layout.fields.length; i++) {
83
+ const f = layout.fields[i];
84
+ const name = JSON.stringify(desc.fields[i].js);
85
+ const o = f.offset;
86
+ switch (f.kind) {
87
+ case 0:
88
+ parts.push(`${name}: readStr(u8, base + ${o}, ${f.size})`);
89
+ break;
90
+ case 1:
91
+ parts.push(`${name}: view.getInt32(base + ${o}, true)`);
92
+ break;
93
+ case 2:
94
+ parts.push(`${name}: view.getInt16(base + ${o}, true)`);
95
+ break;
96
+ case 3:
97
+ parts.push(`${name}: view.getFloat64(base + ${o}, true)`);
98
+ break;
99
+ default:
100
+ throw new Error(`codec: unknown kind ${f.kind} for ${desc.name}`);
101
+ }
102
+ }
103
+
104
+ const body = `return function decode(view, u8, base) { return { ${parts.join(
105
+ ", "
106
+ )} }; };`;
107
+ const factory = new Function("readStr", body) as (r: typeof readStr) => Decoder;
108
+ return factory(readStr);
109
+ }
110
+
111
+ /** Build decoders for every struct (lazy callers can also build one at a time). */
112
+ export function buildAllDecoders(layouts: StructLayout[]): Decoder[] {
113
+ return layouts.map((l, id) => buildDecoder(id, l));
114
+ }
115
+
116
+ const utf8Encoder = new TextEncoder();
117
+
118
+ /**
119
+ * Encode a plain object into a struct's raw bytes (reverse of the decoder).
120
+ * Cold path (requests are infrequent vs ticks), so a simple loop is fine.
121
+ * char[N] string fields reserve a null terminator; single-char fields write 1
122
+ * byte. Request fields are ASCII in practice (ids/codes), so UTF-8 == bytes.
123
+ */
124
+ export function encodeStruct(
125
+ layout: StructLayout,
126
+ fields: { js: string; kind: number }[],
127
+ obj: Record<string, unknown>,
128
+ encodeStr: (s: string) => Uint8Array = (s) => utf8Encoder.encode(s)
129
+ ): Uint8Array {
130
+ const out = new Uint8Array(layout.size);
131
+ const view = new DataView(out.buffer);
132
+ for (let i = 0; i < layout.fields.length; i++) {
133
+ const f = layout.fields[i];
134
+ const v = obj[fields[i].js];
135
+ if (v === undefined || v === null) continue;
136
+ switch (f.kind) {
137
+ case 0: {
138
+ // CTP char[N] fields hold up to N-1 bytes + a reserved NUL terminator
139
+ // (including the comb*Flag arrays, which are at most N-1 legs), so always
140
+ // keep the last byte 0. The buffer is zero-initialized, so writing at most
141
+ // N-1 bytes leaves a valid NUL-terminated (or shorter) string; over-long
142
+ // input is truncated rather than sent to CTP without a terminator.
143
+ const bytes = encodeStr(String(v));
144
+ const cap = f.size === 1 ? 1 : f.size - 1;
145
+ out.set(bytes.subarray(0, Math.min(bytes.length, cap)), f.offset);
146
+ break;
147
+ }
148
+ case 1:
149
+ view.setInt32(f.offset, Number(v) | 0, true);
150
+ break;
151
+ case 2:
152
+ view.setInt16(f.offset, Number(v) | 0, true);
153
+ break;
154
+ case 3:
155
+ view.setFloat64(f.offset, Number(v), true);
156
+ break;
157
+ }
158
+ }
159
+ return out;
160
+ }