@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/binding.gyp ADDED
@@ -0,0 +1,90 @@
1
+ {
2
+ "targets": [
3
+ {
4
+ "target_name": "ctp",
5
+ "sources": [
6
+ "src/addon.cc",
7
+ "src/native/risk.cc",
8
+ "src/native/arm.cc",
9
+ "src/native/channel.cc",
10
+ "src/native/gbk.cc",
11
+ "src/native/mdspi.cc",
12
+ "src/native/mdapi.cc",
13
+ "src/native/traderapi.cc",
14
+ "src/generated/layout.gen.cc",
15
+ "src/generated/traderspi.gen.cc",
16
+ "src/generated/traderreq.gen.cc"
17
+ ],
18
+ "include_dirs": [
19
+ "<!(node -p \"require('node-addon-api').include_dir\")",
20
+ "tradeapi"
21
+ ],
22
+ "defines": [
23
+ "NAPI_VERSION=8",
24
+ "NAPI_CPP_EXCEPTIONS"
25
+ ],
26
+ "cflags!": [ "-fno-exceptions" ],
27
+ "cflags_cc!": [ "-fno-exceptions" ],
28
+ "conditions": [
29
+ ["OS=='win'", {
30
+ "library_dirs": [ "<(module_root_dir)/tradeapi/windows" ],
31
+ "libraries": [
32
+ "thostmduserapi_se.lib",
33
+ "thosttraderapi_se.lib"
34
+ ],
35
+ "msvs_settings": {
36
+ "VCCLCompilerTool": {
37
+ "ExceptionHandling": 1
38
+ }
39
+ },
40
+ "copies": [
41
+ {
42
+ "destination": "<(PRODUCT_DIR)",
43
+ "files": [
44
+ "<(module_root_dir)/tradeapi/windows/thostmduserapi_se.dll",
45
+ "<(module_root_dir)/tradeapi/windows/thosttraderapi_se.dll"
46
+ ]
47
+ }
48
+ ]
49
+ }],
50
+ ["OS=='linux'", {
51
+ "libraries": [
52
+ "<(module_root_dir)/tradeapi/linux/thostmduserapi_se.so",
53
+ "<(module_root_dir)/tradeapi/linux/thosttraderapi_se.so",
54
+ "-Wl,-rpath,'$$ORIGIN'",
55
+ "-Wl,-rpath,<(module_root_dir)/tradeapi/linux"
56
+ ],
57
+ "cflags_cc": [ "-std=c++17", "-fexceptions" ],
58
+ "copies": [
59
+ {
60
+ "destination": "<(PRODUCT_DIR)",
61
+ "files": [
62
+ "<(module_root_dir)/tradeapi/linux/thostmduserapi_se.so",
63
+ "<(module_root_dir)/tradeapi/linux/thosttraderapi_se.so"
64
+ ]
65
+ }
66
+ ]
67
+ }],
68
+ ["OS=='mac'", {
69
+ "include_dirs": [
70
+ "<(module_root_dir)/tradeapi/macos/thostmduserapi_se.framework/Versions/A/Headers",
71
+ "<(module_root_dir)/tradeapi/macos/thosttraderapi_se.framework/Versions/A/Headers"
72
+ ],
73
+ "libraries": [
74
+ "-F<(module_root_dir)/tradeapi/macos",
75
+ "-framework thostmduserapi_se",
76
+ "-framework thosttraderapi_se",
77
+ "-liconv",
78
+ "-Wl,-rpath,@loader_path",
79
+ "-Wl,-rpath,<(module_root_dir)/tradeapi/macos"
80
+ ],
81
+ "xcode_settings": {
82
+ "GCC_ENABLE_CPP_EXCEPTIONS": "YES",
83
+ "CLANG_CXX_LANGUAGE_STANDARD": "c++17",
84
+ "MACOSX_DEPLOYMENT_TARGET": "10.15"
85
+ }
86
+ }]
87
+ ]
88
+ }
89
+ ]
90
+ }
@@ -0,0 +1,115 @@
1
+ import { EventEmitter } from "node:events";
2
+ export interface RspInfo {
3
+ errorId: number;
4
+ errorMsg: string;
5
+ }
6
+ export interface CallbackOptions {
7
+ /** Request id this record answers (for req/rsp correlation). */
8
+ requestId?: number;
9
+ /** Whether this is the last record of the response. */
10
+ isLast?: boolean;
11
+ /** Present only when CTP reported an error (errorId !== 0). */
12
+ rspInfo?: RspInfo;
13
+ }
14
+ export interface NativeClient {
15
+ _start(drain: () => void): void;
16
+ _buffer(): ArrayBuffer;
17
+ _claim(): number;
18
+ _release(n: number): void;
19
+ _info(): {
20
+ slotSize: number;
21
+ numSlots: number;
22
+ headerSize: number;
23
+ dropOldest: boolean;
24
+ };
25
+ _dropCount(): number;
26
+ _readIndex?(): number;
27
+ _validate?(claimed: number): number;
28
+ close(): void;
29
+ }
30
+ export declare abstract class CtpClient extends EventEmitter {
31
+ protected readonly native: any;
32
+ private readonly layouts;
33
+ private readonly decoders;
34
+ private readonly events;
35
+ private view;
36
+ private u8;
37
+ private slotSize;
38
+ private numSlots;
39
+ private headerSize;
40
+ private readPos;
41
+ private dropOldest;
42
+ private batch;
43
+ private closing;
44
+ private started;
45
+ private readonly pending;
46
+ private reqSeq;
47
+ /** Event ids whose requestId-0 response should resolve the oldest pending
48
+ * request. Needed only for SimNow market-data login/logout, which don't echo
49
+ * the id; scoping to those events means an unrelated id-0 response
50
+ * (sub/unsub/error) can't hijack them. The trader echoes ids and leaves this
51
+ * empty. */
52
+ protected readonly zeroIdFallbackEvents: Set<number>;
53
+ /** A request that goes idle this long (no response and, for multi-row queries,
54
+ * no further rows) rejects, so awaiters don't hang forever. The timer resets
55
+ * on each row, so a large streaming query isn't cut off by total duration. */
56
+ protected requestTimeoutMs: number;
57
+ protected constructor(native: any, layoutBlob: Int32Array, events: Map<number, string>);
58
+ /** Reject and clear every in-flight request (on disconnect / close). */
59
+ private rejectAllPending;
60
+ /** Wire up the ring view + doorbell. Subclasses call this in their ctor. */
61
+ protected start(): void;
62
+ /** Records dropped under backpressure (ring full). Monitor this. */
63
+ get droppedRecords(): number;
64
+ close(): void;
65
+ /** Re-surface an exception thrown by a user event handler without letting it
66
+ * break the drain loop. By the time this runs (next tick) the ring has
67
+ * already advanced, so the feed never wedges. If the app subscribes to
68
+ * 'error' the exception is routed there (catchable); otherwise it is rethrown
69
+ * as an uncaughtException — the normal fate of a throwing EventEmitter
70
+ * listener, just deferred so the data plane stays consistent. */
71
+ private surfaceHandlerError;
72
+ private decoderFor;
73
+ private drain;
74
+ /**
75
+ * Drop-oldest drain (market data). The producer overwrites the oldest unread
76
+ * record when full and never blocks, so the consumer can be lapped mid-read.
77
+ * We therefore decode the whole claimed batch first, then ask the channel how
78
+ * many of the oldest records it overwrote *during* that decode (validate()),
79
+ * discard those (they hold torn bytes), and only then deliver the rest — so a
80
+ * torn record never reaches a handler. The records we do deliver are always the
81
+ * freshest available, and conservation holds (received + dropped == produced).
82
+ */
83
+ private drainOldest;
84
+ private dispatch;
85
+ /** Decode one slot into a record (pure read of the ring; no side effects). */
86
+ private decodeSlot;
87
+ /** Settle any matching in-flight request, then emit the named event. Side
88
+ * effects only — reads no ring memory, so it is safe to call after the
89
+ * producer may have advanced (drainOldest decodes before this runs). */
90
+ private deliver;
91
+ /** Encode a plain object into a struct's raw bytes (for req* encoders). */
92
+ protected encode(structId: number, obj: Record<string, unknown>): Uint8Array;
93
+ protected nextRequestId(): number;
94
+ /** Message for a non-zero send code. Risk sentinels get a specific message;
95
+ * the generic pre-trade-risk block also appends the C++ reason (e.g. which
96
+ * limit) so logs say *why*. Returns undefined for non-risk codes. */
97
+ private riskRejectMessage;
98
+ /**
99
+ * Send a request and resolve when its response arrives (matched by id).
100
+ * `single` resolves with the one row; otherwise with the accumulated rows.
101
+ */
102
+ protected request<T>(send: (id: number) => number, single?: boolean): Promise<T>;
103
+ /** (Re)arm a pending request's idle timeout. Called at send and reset on each
104
+ * row, so a long streaming query isn't cut off by total elapsed time. */
105
+ private armRequestTimer;
106
+ /**
107
+ * Submit a fire-and-forget order/action. Exchange-bound inserts get no
108
+ * success response from CTP (only a rejection), so this resolves as soon as
109
+ * CTP accepts the send and rejects if the send is refused. Track the order's
110
+ * actual lifecycle (accepted / filled / cancelled) via the rtn-order and
111
+ * rtn-trade events, correlating by orderRef.
112
+ */
113
+ protected submit(send: (id: number) => number): Promise<void>;
114
+ }
115
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"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"}
package/dist/client.js ADDED
@@ -0,0 +1,466 @@
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
+ import { EventEmitter } from "node:events";
13
+ import { parseLayouts, buildDecoder, encodeStruct, readStr, } from "./codec.js";
14
+ import { STRUCTS } from "./generated/structs.gen.js";
15
+ import { native as addon } from "./native-binding.js";
16
+ /** Encode a request string field: ASCII fast path; GB18030 (CTP's wire charset,
17
+ * via native) for the rare non-ASCII field. */
18
+ function encodeReqString(s) {
19
+ for (let i = 0; i < s.length; i++) {
20
+ if (s.charCodeAt(i) > 0x7f)
21
+ return new Uint8Array(addon.__gbkEncode(s));
22
+ }
23
+ const a = new Uint8Array(s.length);
24
+ for (let i = 0; i < s.length; i++)
25
+ a[i] = s.charCodeAt(i);
26
+ return a;
27
+ }
28
+ const S_EVENT = 0;
29
+ const S_REQID = 4;
30
+ const S_ISLAST = 8;
31
+ const S_ERRID = 12;
32
+ const S_SID = 16;
33
+ const S_PLEN = 20;
34
+ const S_ERRMSG = 24;
35
+ // --- Lifecycle tripwire (dev aid) --------------------------------------------
36
+ // The CTP vendor DLLs deadlock inside Release() after a handful of
37
+ // Init()->Release() cycles in one process - a long-standing limitation of the
38
+ // vendor SDK (its api objects are not safe to create/Init/Release repeatedly),
39
+ // NOT a bug in this binding. Correct usage is to create each MarketData/Trader
40
+ // ONCE and reuse it, handling reconnects in place; a "reconnect by destroy-and-
41
+ // recreate" bug instead churns through clients and will eventually wedge the
42
+ // whole process. We count clients that were started (Init) and then closed
43
+ // (Release) process-wide and warn ONCE past a threshold, so that bug surfaces in
44
+ // dev / logs before it hangs in production. This lives only on close()
45
+ // (teardown) - never the hot data path - so it costs nothing where latency
46
+ // matters. Tune with CTP_RECREATE_WARN (0 disables); the default stays silent
47
+ // for any sane app (a few long-lived clients) and for the test suite. See
48
+ // docs/native-hooks.md ("Process lifecycle").
49
+ function recreateWarnThreshold(raw) {
50
+ // Default 3: the vendor DLL deadlocks inside Release() after only ~4
51
+ // Init()/Release() cycles, so a higher threshold would never fire before the
52
+ // very hang it warns about. 3 lets the warning print on the close() that
53
+ // precedes the typical wedge, while a create-once app (one or two long-lived
54
+ // clients closed at shutdown) stays under it. 0 disables.
55
+ const DEFAULT = 3;
56
+ if (raw === undefined)
57
+ return DEFAULT;
58
+ const n = Number(raw);
59
+ return Number.isFinite(n) && n >= 0 ? Math.floor(n) : DEFAULT;
60
+ }
61
+ const RECREATE_WARN_THRESHOLD = recreateWarnThreshold(process.env.CTP_RECREATE_WARN);
62
+ let startedThenClosed = 0;
63
+ let recreateWarned = false;
64
+ function noteClientReleased() {
65
+ startedThenClosed += 1;
66
+ if (RECREATE_WARN_THRESHOLD > 0 &&
67
+ !recreateWarned &&
68
+ startedThenClosed > RECREATE_WARN_THRESHOLD) {
69
+ recreateWarned = true;
70
+ console.warn(`[ctp-node] ${startedThenClosed} CTP clients have been created and closed ` +
71
+ `in this process. The CTP vendor DLLs deadlock inside Release() after a few ` +
72
+ `Init()/Release() cycles, so a MarketData/Trader must be created ONCE and ` +
73
+ `reused: handle reconnects in place (re-run your front-connected handshake), ` +
74
+ `never destroy and recreate the client. Set CTP_RECREATE_WARN=0 to silence, ` +
75
+ `or to another number to retune. See docs/native-hooks.md (Process lifecycle).`);
76
+ }
77
+ }
78
+ export class CtpClient extends EventEmitter {
79
+ // Inherently dynamic N-API object; the NativeClient interface documents the
80
+ // contract the data plane relies on.
81
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
82
+ native;
83
+ layouts;
84
+ decoders;
85
+ events;
86
+ view;
87
+ u8;
88
+ slotSize = 0;
89
+ numSlots = 0;
90
+ headerSize = 0;
91
+ readPos = 0;
92
+ // Overflow policy of the underlying channel (from _info()). Drop-oldest (market
93
+ // data) takes the buffered drainOldest() path; drop-newest (trader) the inline
94
+ // drain(). See src/native/channel.h.
95
+ dropOldest = false;
96
+ // Reused scratch holding a whole decoded batch for the drop-oldest path, so we
97
+ // can validate against producer overruns *after* decoding and before delivering
98
+ // (a torn record never reaches a handler). Indices 0..count-1 are live per drain.
99
+ batch = [];
100
+ // Set the instant close() begins. close() frees the native ring synchronously,
101
+ // so if an event handler invoked from drain() calls close() mid-batch, the
102
+ // rest of that batch must NOT keep reading the (now freed) ring view. Every
103
+ // drain loop checks this and bails the moment it flips.
104
+ closing = false;
105
+ // True once start() has run the native Init(). Gates the lifecycle tripwire
106
+ // above: only a started-then-closed client is an Init()/Release() pair (the
107
+ // cycle the vendor DLL deadlocks on); a never-started object closes harmlessly.
108
+ started = false;
109
+ pending = new Map();
110
+ reqSeq = 0;
111
+ /** Event ids whose requestId-0 response should resolve the oldest pending
112
+ * request. Needed only for SimNow market-data login/logout, which don't echo
113
+ * the id; scoping to those events means an unrelated id-0 response
114
+ * (sub/unsub/error) can't hijack them. The trader echoes ids and leaves this
115
+ * empty. */
116
+ zeroIdFallbackEvents = new Set();
117
+ /** A request that goes idle this long (no response and, for multi-row queries,
118
+ * no further rows) rejects, so awaiters don't hang forever. The timer resets
119
+ * on each row, so a large streaming query isn't cut off by total duration. */
120
+ requestTimeoutMs = 30000;
121
+ constructor(
122
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
123
+ native, layoutBlob, events) {
124
+ super();
125
+ this.setMaxListeners(0);
126
+ this.native = native;
127
+ this.layouts = parseLayouts(layoutBlob);
128
+ this.decoders = new Array(this.layouts.length);
129
+ this.events = events;
130
+ // A dropped connection won't deliver in-flight responses - fail them fast.
131
+ this.on("front-disconnected", () => this.rejectAllPending("front disconnected"));
132
+ }
133
+ /** Reject and clear every in-flight request (on disconnect / close). */
134
+ rejectAllPending(reason) {
135
+ if (this.pending.size === 0)
136
+ return;
137
+ const err = new Error(reason);
138
+ for (const [id, p] of this.pending) {
139
+ if (p.timer)
140
+ clearTimeout(p.timer);
141
+ this.pending.delete(id);
142
+ p.reject(err);
143
+ }
144
+ }
145
+ /** Wire up the ring view + doorbell. Subclasses call this in their ctor. */
146
+ start() {
147
+ const info = this.native._info();
148
+ this.slotSize = info.slotSize;
149
+ this.numSlots = info.numSlots;
150
+ this.headerSize = info.headerSize;
151
+ this.dropOldest = !!info.dropOldest;
152
+ const ab = this.native._buffer();
153
+ this.view = new DataView(ab);
154
+ this.u8 = new Uint8Array(ab);
155
+ this.native._start(this.dropOldest ? () => this.drainOldest() : () => this.drain());
156
+ this.started = true;
157
+ }
158
+ /** Records dropped under backpressure (ring full). Monitor this. */
159
+ get droppedRecords() {
160
+ return this.native._dropCount();
161
+ }
162
+ close() {
163
+ if (this.closing)
164
+ return; // idempotent; also stops any in-progress drain
165
+ this.closing = true;
166
+ this.rejectAllPending("client closed");
167
+ if (this.started)
168
+ noteClientReleased(); // dev tripwire (see top of file)
169
+ this.native.close();
170
+ }
171
+ /** Re-surface an exception thrown by a user event handler without letting it
172
+ * break the drain loop. By the time this runs (next tick) the ring has
173
+ * already advanced, so the feed never wedges. If the app subscribes to
174
+ * 'error' the exception is routed there (catchable); otherwise it is rethrown
175
+ * as an uncaughtException — the normal fate of a throwing EventEmitter
176
+ * listener, just deferred so the data plane stays consistent. */
177
+ surfaceHandlerError(err) {
178
+ setImmediate(() => {
179
+ if (this.listenerCount("error") > 0)
180
+ this.emit("error", err);
181
+ else
182
+ throw err;
183
+ });
184
+ }
185
+ decoderFor(id) {
186
+ let d = this.decoders[id];
187
+ if (d === undefined) {
188
+ d = buildDecoder(id, this.layouts[id]);
189
+ this.decoders[id] = d;
190
+ }
191
+ return d;
192
+ }
193
+ drain() {
194
+ let count = this.native._claim();
195
+ while (count > 0) {
196
+ const numSlots = this.numSlots;
197
+ const slotSize = this.slotSize;
198
+ for (let i = 0; i < count; i++) {
199
+ // A handler in the previous dispatch() may have called close(), which
200
+ // frees the ring; stop before reading freed memory for the next record.
201
+ if (this.closing)
202
+ return;
203
+ const slot = ((this.readPos + i) % numSlots) * slotSize;
204
+ try {
205
+ this.dispatch(slot);
206
+ }
207
+ catch (err) {
208
+ // A user event handler threw. Never let it wedge the data plane: the
209
+ // ring MUST keep advancing, else this record re-delivers forever and
210
+ // every record behind it stalls (silently, under Node's default
211
+ // listener-exception policy). Absorb here; re-surface on the next tick.
212
+ this.surfaceHandlerError(err);
213
+ }
214
+ }
215
+ if (this.closing)
216
+ return;
217
+ this.native._release(count);
218
+ this.readPos += count;
219
+ count = this.native._claim();
220
+ }
221
+ }
222
+ /**
223
+ * Drop-oldest drain (market data). The producer overwrites the oldest unread
224
+ * record when full and never blocks, so the consumer can be lapped mid-read.
225
+ * We therefore decode the whole claimed batch first, then ask the channel how
226
+ * many of the oldest records it overwrote *during* that decode (validate()),
227
+ * discard those (they hold torn bytes), and only then deliver the rest — so a
228
+ * torn record never reaches a handler. The records we do deliver are always the
229
+ * freshest available, and conservation holds (received + dropped == produced).
230
+ */
231
+ drainOldest() {
232
+ let count = this.native._claim();
233
+ while (count > 0) {
234
+ if (this.closing)
235
+ return;
236
+ // claim() may have advanced readIdx_ past lapped records; resync our slot
237
+ // cursor to the channel's authoritative read index before decoding.
238
+ this.readPos = this.native._readIndex();
239
+ const numSlots = this.numSlots;
240
+ const slotSize = this.slotSize;
241
+ const batch = this.batch;
242
+ for (let i = 0; i < count; i++) {
243
+ const slot = ((this.readPos + i) % numSlots) * slotSize;
244
+ batch[i] = this.decodeSlot(slot);
245
+ }
246
+ // How many leading (oldest) records did the producer overwrite while we
247
+ // were decoding? Those are torn — discard them (validate() counts them as
248
+ // drops). The remainder were provably untouched during decode.
249
+ const torn = this.native._validate(count);
250
+ for (let i = 0; i < torn; i++)
251
+ batch[i] = undefined; // release torn refs
252
+ if (this.closing) {
253
+ for (let i = torn; i < count; i++)
254
+ batch[i] = undefined;
255
+ return;
256
+ }
257
+ for (let i = torn; i < count; i++) {
258
+ const rec = batch[i];
259
+ batch[i] = undefined;
260
+ // A handler from an earlier record this batch may have called close(),
261
+ // which frees the ring. The decoded objects are safe (already copied out
262
+ // of the ring), but stop delivering so app semantics match drain().
263
+ if (this.closing)
264
+ continue;
265
+ try {
266
+ this.deliver(rec);
267
+ }
268
+ catch (err) {
269
+ this.surfaceHandlerError(err);
270
+ }
271
+ }
272
+ if (this.closing)
273
+ return;
274
+ this.native._release(count);
275
+ this.readPos += count;
276
+ count = this.native._claim();
277
+ }
278
+ }
279
+ dispatch(slot) {
280
+ this.deliver(this.decodeSlot(slot));
281
+ }
282
+ /** Decode one slot into a record (pure read of the ring; no side effects). */
283
+ decodeSlot(slot) {
284
+ const v = this.view;
285
+ const u8 = this.u8;
286
+ const evt = v.getInt32(slot + S_EVENT, true);
287
+ const reqId = v.getInt32(slot + S_REQID, true);
288
+ const isLastRaw = v.getInt32(slot + S_ISLAST, true);
289
+ const errId = v.getInt32(slot + S_ERRID, true);
290
+ const sid = v.getInt32(slot + S_SID, true);
291
+ const plen = v.getInt32(slot + S_PLEN, true);
292
+ const base = slot + this.headerSize;
293
+ let value;
294
+ // sid bounds check (sid < layouts.length): under the drop-oldest path a slot
295
+ // may be overwritten while we decode it (a torn read). The header int32s are
296
+ // normally read old-or-new intact, but DataView.getInt32 atomicity isn't
297
+ // guaranteed, so a torn sid could land out of range; decoderFor() would then
298
+ // build over an undefined layout and throw. The torn record is discarded by
299
+ // validate() afterward, but the throw would escape the decode loop (which is
300
+ // not wrapped) and crash the doorbell callback. Bounding sid keeps decodeSlot
301
+ // total: an out-of-range sid yields an undefined value, harmlessly dropped.
302
+ if (plen > 0 && sid >= 0 && sid < this.layouts.length)
303
+ value = this.decoderFor(sid)(v, u8, base);
304
+ else if (sid === -2 && plen >= 4)
305
+ value = v.getInt32(base, true);
306
+ else
307
+ value = undefined;
308
+ const rspInfo = errId !== 0
309
+ ? { errorId: errId, errorMsg: readStr(u8, slot + S_ERRMSG, 81) }
310
+ : undefined;
311
+ const options = {
312
+ requestId: reqId !== 0 ? reqId : undefined,
313
+ isLast: isLastRaw === -1 ? undefined : isLastRaw === 1,
314
+ rspInfo,
315
+ };
316
+ return { evt, value, options };
317
+ }
318
+ /** Settle any matching in-flight request, then emit the named event. Side
319
+ * effects only — reads no ring memory, so it is safe to call after the
320
+ * producer may have advanced (drainOldest decodes before this runs). */
321
+ deliver(rec) {
322
+ const { evt, value, options } = rec;
323
+ const reqId = options.requestId ?? 0;
324
+ const rspInfo = options.rspInfo;
325
+ // Responses (Rsp*) carry isLast (0/1 -> boolean); streaming pushes (Rtn*,
326
+ // front, …) use -1 (-> undefined). Correlate a response to its pending
327
+ // request by requestId; only for the configured zeroIdFallbackEvent
328
+ // (MarketData's login) do we resolve a server requestId of 0 against the
329
+ // oldest pending request — SimNow's MD login doesn't echo the id. Scoping to
330
+ // that one event keeps an unrelated id-0 response from hijacking a request.
331
+ if (options.isLast !== undefined && this.pending.size > 0) {
332
+ let key = reqId !== 0 && this.pending.has(reqId) ? reqId : undefined;
333
+ if (key === undefined && reqId === 0 && this.zeroIdFallbackEvents.has(evt)) {
334
+ key = this.pending.keys().next().value;
335
+ }
336
+ const p = key !== undefined ? this.pending.get(key) : undefined;
337
+ if (p && key !== undefined) {
338
+ if (rspInfo) {
339
+ if (p.timer)
340
+ clearTimeout(p.timer);
341
+ this.pending.delete(key);
342
+ p.reject(Object.assign(new Error(rspInfo.errorMsg || `CTP error ${rspInfo.errorId}`), rspInfo));
343
+ }
344
+ else {
345
+ if (value !== undefined)
346
+ p.rows.push(value);
347
+ if (options.isLast === true) {
348
+ if (p.timer)
349
+ clearTimeout(p.timer);
350
+ this.pending.delete(key);
351
+ p.resolve(p.single ? p.rows[0] : p.rows);
352
+ }
353
+ else {
354
+ this.armRequestTimer(key, p); // more rows expected: reset idle timeout
355
+ }
356
+ }
357
+ }
358
+ }
359
+ const name = this.events.get(evt);
360
+ this.emit(name ?? `event:${evt}`, value, options);
361
+ }
362
+ /** Encode a plain object into a struct's raw bytes (for req* encoders). */
363
+ encode(structId, obj) {
364
+ return encodeStruct(this.layouts[structId], STRUCTS[structId].fields, obj, encodeReqString);
365
+ }
366
+ nextRequestId() {
367
+ // CTP echoes the requestId as an int32, and dispatch() reads it back via
368
+ // getInt32, so the pending-map key MUST stay within positive int32 or it
369
+ // would stop matching the echoed wire id past 2^31 requests (responses would
370
+ // then only ever reject on the idle timeout). Cycle 1..2^31-1; skip 0, which
371
+ // is the "no id" / zeroIdFallback sentinel. (Reuse can't collide: nothing
372
+ // stays pending across 2^31 requests — the idle timeout is seconds.)
373
+ this.reqSeq = this.reqSeq >= 0x7fffffff ? 1 : this.reqSeq + 1;
374
+ return this.reqSeq;
375
+ }
376
+ /** Message for a non-zero send code. Risk sentinels get a specific message;
377
+ * the generic pre-trade-risk block also appends the C++ reason (e.g. which
378
+ * limit) so logs say *why*. Returns undefined for non-risk codes. */
379
+ riskRejectMessage(rc) {
380
+ switch (rc) {
381
+ case -10001: {
382
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
383
+ const reason = typeof this.native.lastRiskReason === "function" ? this.native.lastRiskReason() : "";
384
+ return reason ? `blocked by pre-trade risk: ${reason}` : "blocked by pre-trade risk";
385
+ }
386
+ case -10002:
387
+ return "rate limited (order rate exceeded)";
388
+ case -10003:
389
+ return "blocked by max position cost";
390
+ case -10004:
391
+ return "blocked by max position volume (lots)";
392
+ default:
393
+ return undefined;
394
+ }
395
+ }
396
+ /**
397
+ * Send a request and resolve when its response arrives (matched by id).
398
+ * `single` resolves with the one row; otherwise with the accumulated rows.
399
+ */
400
+ request(send, single = false) {
401
+ const id = this.nextRequestId();
402
+ return new Promise((resolve, reject) => {
403
+ const entry = {
404
+ rows: [],
405
+ resolve: resolve,
406
+ reject,
407
+ single,
408
+ };
409
+ this.pending.set(id, entry);
410
+ let rc;
411
+ try {
412
+ rc = send(id);
413
+ }
414
+ catch (e) {
415
+ this.pending.delete(id);
416
+ reject(e);
417
+ return;
418
+ }
419
+ if (rc !== 0) {
420
+ this.pending.delete(id);
421
+ const msg = this.riskRejectMessage(rc) ?? `request rejected by CTP API (code ${rc})`;
422
+ reject(new Error(msg));
423
+ return;
424
+ }
425
+ // Backstop: if the request goes idle (no response / no further rows for a
426
+ // multi-row query), fail rather than hang forever.
427
+ this.armRequestTimer(id, entry);
428
+ });
429
+ }
430
+ /** (Re)arm a pending request's idle timeout. Called at send and reset on each
431
+ * row, so a long streaming query isn't cut off by total elapsed time. */
432
+ armRequestTimer(id, entry) {
433
+ if (this.requestTimeoutMs <= 0)
434
+ return;
435
+ if (entry.timer)
436
+ clearTimeout(entry.timer);
437
+ entry.timer = setTimeout(() => {
438
+ if (this.pending.delete(id))
439
+ entry.reject(new Error("request timed out"));
440
+ }, this.requestTimeoutMs);
441
+ if (typeof entry.timer.unref === "function")
442
+ entry.timer.unref();
443
+ }
444
+ /**
445
+ * Submit a fire-and-forget order/action. Exchange-bound inserts get no
446
+ * success response from CTP (only a rejection), so this resolves as soon as
447
+ * CTP accepts the send and rejects if the send is refused. Track the order's
448
+ * actual lifecycle (accepted / filled / cancelled) via the rtn-order and
449
+ * rtn-trade events, correlating by orderRef.
450
+ */
451
+ submit(send) {
452
+ const id = this.nextRequestId();
453
+ let rc;
454
+ try {
455
+ rc = send(id);
456
+ }
457
+ catch (e) {
458
+ return Promise.reject(e);
459
+ }
460
+ if (rc === 0)
461
+ return Promise.resolve();
462
+ const msg = this.riskRejectMessage(rc) ?? `order rejected by CTP API (code ${rc})`;
463
+ return Promise.reject(new Error(msg));
464
+ }
465
+ }
466
+ //# sourceMappingURL=client.js.map