@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.
Files changed (104) hide show
  1. package/CHANGELOG.md +67 -0
  2. package/README.md +52 -31
  3. package/README.zh-CN.md +42 -26
  4. package/RELEASING.md +78 -0
  5. package/binding.gyp +13 -13
  6. package/dist/client.d.ts +40 -15
  7. package/dist/client.d.ts.map +1 -1
  8. package/dist/client.js +241 -62
  9. package/dist/client.js.map +1 -1
  10. package/dist/codec.d.ts.map +1 -1
  11. package/dist/codec.js +84 -19
  12. package/dist/codec.js.map +1 -1
  13. package/dist/generated/structs.gen.d.ts +5461 -5461
  14. package/dist/generated/structs.gen.d.ts.map +1 -1
  15. package/dist/generated/trader.gen.d.ts.map +1 -1
  16. package/dist/generated/trader.gen.js +788 -94
  17. package/dist/generated/trader.gen.js.map +1 -1
  18. package/dist/index.cjs +1896 -420
  19. package/dist/index.d.cts +1 -1
  20. package/dist/index.d.ts +1 -1
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.js.map +1 -1
  23. package/dist/market-data.d.ts +48 -21
  24. package/dist/market-data.d.ts.map +1 -1
  25. package/dist/market-data.js +165 -26
  26. package/dist/market-data.js.map +1 -1
  27. package/dist/native-binding.d.ts.map +1 -1
  28. package/dist/native-binding.js +5 -1
  29. package/dist/native-binding.js.map +1 -1
  30. package/dist/trader.d.ts +127 -79
  31. package/dist/trader.d.ts.map +1 -1
  32. package/dist/trader.js +788 -200
  33. package/dist/trader.js.map +1 -1
  34. package/dist/validation.d.ts +27 -0
  35. package/dist/validation.d.ts.map +1 -0
  36. package/dist/validation.js +85 -0
  37. package/dist/validation.js.map +1 -0
  38. package/docs/API.md +1437 -0
  39. package/docs/API.zh-CN.md +1278 -0
  40. package/docs/MIGRATION.md +54 -0
  41. package/docs/assets/validation.svg +27 -0
  42. package/docs/integration.md +60 -0
  43. package/docs/native-hooks.md +281 -0
  44. package/docs/native-hooks.zh-CN.md +205 -0
  45. package/docs/troubleshooting.md +257 -0
  46. package/docs/troubleshooting.zh-CN.md +220 -0
  47. package/package.json +14 -6
  48. package/prebuilds/linux-x64/@hitrading+ctp-node.node +0 -0
  49. package/prebuilds/win32-x64/@hitrading+ctp-node.node +0 -0
  50. package/scripts/bench-decode.mjs +37 -0
  51. package/scripts/bench-fullmarket-offline.mjs +207 -0
  52. package/scripts/stress-fullmarket.mjs +255 -0
  53. package/src/addon.cc +2 -2
  54. package/src/client.ts +263 -65
  55. package/src/codec.ts +86 -19
  56. package/src/generated/structs.gen.ts +5461 -5461
  57. package/src/generated/trader.gen.ts +309 -94
  58. package/src/generated/traderreq.gen.cc +194 -18
  59. package/src/generated/traderreq.gen.h +4 -0
  60. package/src/generated/traderspi.gen.cc +130 -10
  61. package/src/generated/traderspi.gen.h +4 -2
  62. package/src/index.ts +8 -1
  63. package/src/market-data.ts +219 -43
  64. package/src/native/arm.cc +114 -30
  65. package/src/native/arm.h +16 -4
  66. package/src/native/channel.cc +209 -81
  67. package/src/native/channel.h +65 -24
  68. package/src/native/ctp_field.h +23 -0
  69. package/src/native/mdapi.cc +621 -61
  70. package/src/native/mdspi.cc +221 -14
  71. package/src/native/mdspi.h +62 -9
  72. package/src/native/order_capability.h +75 -0
  73. package/src/native/risk.cc +2051 -205
  74. package/src/native/risk.h +450 -57
  75. package/src/native/shared_handle.h +37 -0
  76. package/src/native/snapshot.h +120 -0
  77. package/src/native/traderapi.cc +749 -170
  78. package/src/native-binding.ts +5 -1
  79. package/src/trader.ts +993 -229
  80. package/src/validation.ts +96 -0
  81. /package/{tradeapi → ctpsdk}/ThostFtdcMdApi.h +0 -0
  82. /package/{tradeapi → ctpsdk}/ThostFtdcTraderApi.h +0 -0
  83. /package/{tradeapi → ctpsdk}/ThostFtdcUserApiDataType.h +0 -0
  84. /package/{tradeapi → ctpsdk}/ThostFtdcUserApiStruct.h +0 -0
  85. /package/{tradeapi → ctpsdk}/error.dtd +0 -0
  86. /package/{tradeapi → ctpsdk}/error.xml +0 -0
  87. /package/{tradeapi → ctpsdk}/linux/thostmduserapi_se.so +0 -0
  88. /package/{tradeapi → ctpsdk}/linux/thosttraderapi_se.so +0 -0
  89. /package/{tradeapi → ctpsdk}/macos/thostmduserapi_se.framework/Versions/A/Headers/ThostFtdcMdApi.h +0 -0
  90. /package/{tradeapi → ctpsdk}/macos/thostmduserapi_se.framework/Versions/A/Headers/ThostFtdcUserApiDataType.h +0 -0
  91. /package/{tradeapi → ctpsdk}/macos/thostmduserapi_se.framework/Versions/A/Headers/ThostFtdcUserApiStruct.h +0 -0
  92. /package/{tradeapi → ctpsdk}/macos/thostmduserapi_se.framework/Versions/A/Resources/Info.plist +0 -0
  93. /package/{tradeapi → ctpsdk}/macos/thostmduserapi_se.framework/Versions/A/_CodeSignature/CodeResources +0 -0
  94. /package/{tradeapi → ctpsdk}/macos/thostmduserapi_se.framework/Versions/A/thostmduserapi_se +0 -0
  95. /package/{tradeapi → ctpsdk}/macos/thosttraderapi_se.framework/Versions/A/Headers/ThostFtdcTraderApi.h +0 -0
  96. /package/{tradeapi → ctpsdk}/macos/thosttraderapi_se.framework/Versions/A/Headers/ThostFtdcUserApiDataType.h +0 -0
  97. /package/{tradeapi → ctpsdk}/macos/thosttraderapi_se.framework/Versions/A/Headers/ThostFtdcUserApiStruct.h +0 -0
  98. /package/{tradeapi → ctpsdk}/macos/thosttraderapi_se.framework/Versions/A/Resources/Info.plist +0 -0
  99. /package/{tradeapi → ctpsdk}/macos/thosttraderapi_se.framework/Versions/A/_CodeSignature/CodeResources +0 -0
  100. /package/{tradeapi → ctpsdk}/macos/thosttraderapi_se.framework/Versions/A/thosttraderapi_se +0 -0
  101. /package/{tradeapi → ctpsdk}/windows/thostmduserapi_se.dll +0 -0
  102. /package/{tradeapi → ctpsdk}/windows/thostmduserapi_se.lib +0 -0
  103. /package/{tradeapi → ctpsdk}/windows/thosttraderapi_se.dll +0 -0
  104. /package/{tradeapi → ctpsdk}/windows/thosttraderapi_se.lib +0 -0
@@ -7,13 +7,24 @@
7
7
 
8
8
  import { native } from "./native-binding.js";
9
9
  import { CtpClient, type CallbackOptions } from "./client.js";
10
+ import { Trader } from "./trader.js";
10
11
  import type {
11
12
  DepthMarketData,
12
13
  ForQuoteRsp,
13
14
  SpecificInstrument,
15
+ QryMulticastInstrument,
16
+ MulticastInstrument,
17
+ ReqUserLogin,
14
18
  RspUserLogin,
15
19
  UserLogout,
16
20
  } from "./generated/structs.gen.js";
21
+ import { STRUCT_ID } from "./generated/structs.gen.js";
22
+ import {
23
+ copyDenseStringArray,
24
+ copyOwnFronts,
25
+ copyOwnRecord,
26
+ ownStringKeys,
27
+ } from "./validation.js";
17
28
 
18
29
  const MD_BASE = 0x1000;
19
30
  const MD_EVENTS = new Map<number, string>([
@@ -32,13 +43,7 @@ const MD_EVENTS = new Map<number, string>([
32
43
  [MD_BASE + 13, "rtn-for-quote"],
33
44
  ]);
34
45
 
35
- export interface MdLoginReq {
36
- tradingDay?: string;
37
- brokerId?: string;
38
- userId?: string;
39
- password?: string;
40
- userProductInfo?: string;
41
- }
46
+ export type MdLoginReq = Partial<ReqUserLogin>;
42
47
 
43
48
  /** Market-data event names (symbolic; plain strings also work). */
44
49
  export enum MarketDataEvent {
@@ -57,62 +62,199 @@ export enum MarketDataEvent {
57
62
  RtnForQuote = "rtn-for-quote",
58
63
  }
59
64
 
65
+ function snapshotInstrumentIds(instrumentIds: string[]): string[] {
66
+ return copyDenseStringArray(instrumentIds, "instrumentIds");
67
+ }
68
+
69
+ function requestShapeError(
70
+ value: unknown,
71
+ allowed: ReadonlySet<string>,
72
+ label: string
73
+ ): TypeError | undefined {
74
+ let keys: string[];
75
+ try {
76
+ keys = ownStringKeys(value, label);
77
+ } catch (error) {
78
+ return error instanceof TypeError ? error : new TypeError(`${label} must be a plain object`);
79
+ }
80
+ for (const key of keys)
81
+ if (!allowed.has(key)) return new TypeError(`${label}: unknown field ${key}`);
82
+ return undefined;
83
+ }
84
+
85
+ const LOGIN_KEYS = new Set([
86
+ "tradingDay", "brokerId", "userId", "password", "userProductInfo",
87
+ "interfaceProductInfo", "protocolInfo", "macAddress", "oneTimePassword",
88
+ "loginRemark", "clientIpPort", "clientIpAddress", "smsCode",
89
+ ]);
90
+ const LOGOUT_KEYS = new Set(["brokerId", "userId"]);
91
+ const MULTICAST_QUERY_KEYS = new Set(["topicId", "instrumentId"]);
92
+
60
93
  export class MarketData extends CtpClient {
94
+ private sessionTransition?: Promise<unknown>;
95
+
61
96
  constructor(flowPath: string, fronts: string | string[]) {
62
- super(new native.MarketData(flowPath, fronts), native.__layoutData(), MD_EVENTS);
63
- // SimNow's MD login/logout responses come back with requestId 0. Scope the
64
- // id-0 fallback to those two events (which are never concurrent) so an id-0
65
- // sub/unsub/error response can't hijack a pending login()/logout().
66
- this.zeroIdFallbackEvents.add(MD_BASE + 4); // rsp-user-login
67
- this.zeroIdFallbackEvents.add(MD_BASE + 5); // rsp-user-logout
97
+ super(
98
+ new native.MarketData(flowPath, copyOwnFronts(fronts, "MarketData fronts")),
99
+ native.__layoutData(),
100
+ MD_EVENTS
101
+ );
68
102
  this.start();
69
103
  }
70
104
 
71
- getApiVersion(): string {
72
- return (this.native as Record<string, () => string>).getApiVersion();
105
+ get apiVersion(): string {
106
+ return (this.native as Record<string, () => string>).apiVersion();
73
107
  }
74
- getTradingDay(): string {
75
- return (this.native as Record<string, () => string>).getTradingDay();
108
+ get tradingDay(): string {
109
+ return (this.native as Record<string, () => string>).tradingDay();
76
110
  }
77
111
 
78
112
  /** Subscribe to depth market data. Returns the CTP send code (0 = ok). */
79
113
  subscribe(instrumentIds: string[]): number {
80
- return (this.native as { subscribeMarketData(a: string[]): number }).subscribeMarketData(instrumentIds);
114
+ const ids = snapshotInstrumentIds(instrumentIds);
115
+ return (this.native as { subscribeMarketData(a: string[]): number }).subscribeMarketData(ids);
81
116
  }
82
117
  unsubscribe(instrumentIds: string[]): number {
83
- return (this.native as { unsubscribeMarketData(a: string[]): number }).unsubscribeMarketData(instrumentIds);
118
+ const ids = snapshotInstrumentIds(instrumentIds);
119
+ return (this.native as { unsubscribeMarketData(a: string[]): number }).unsubscribeMarketData(ids);
84
120
  }
85
121
  subscribeForQuote(instrumentIds: string[]): number {
86
- return (this.native as { subscribeForQuoteRsp(a: string[]): number }).subscribeForQuoteRsp(instrumentIds);
122
+ const ids = snapshotInstrumentIds(instrumentIds);
123
+ return (this.native as { subscribeForQuoteRsp(a: string[]): number }).subscribeForQuoteRsp(ids);
87
124
  }
88
125
  unsubscribeForQuote(instrumentIds: string[]): number {
89
- return (this.native as { unsubscribeForQuoteRsp(a: string[]): number }).unsubscribeForQuoteRsp(instrumentIds);
126
+ const ids = snapshotInstrumentIds(instrumentIds);
127
+ return (this.native as { unsubscribeForQuoteRsp(a: string[]): number }).unsubscribeForQuoteRsp(ids);
128
+ }
129
+
130
+ /** Latest cached depth tick for an instrument — the C++ last-value cache,
131
+ * updated on every authenticated-session tick before it reaches JS. Returns
132
+ * null before login, after disconnect/logout, if none has been seen, or if it
133
+ * was unsubscribed. Synchronous: no waiting for an event. */
134
+ snapshot(instrumentId: string): DepthMarketData | null {
135
+ const bytes = (this.native as { snapshot(id: string): Uint8Array | null }).snapshot(instrumentId);
136
+ return bytes
137
+ ? (this.decodeStruct(STRUCT_ID.DepthMarketData, bytes) as unknown as DepthMarketData)
138
+ : null;
139
+ }
140
+
141
+ /** Latest price for an instrument from the cache (0 if none seen). Synchronous. */
142
+ last(instrumentId: string): number {
143
+ return (this.native as { last(id: string): number }).last(instrumentId);
144
+ }
145
+
146
+ /** @internal Hand the C++ snapshot cache to a Trader (Trader.trackMarketData),
147
+ * so the Trader's deviation check reads live prices in C++ — no JS round-trip. */
148
+ _snapshotExternal(): unknown {
149
+ return (this.native as { _snapshotExternal(): unknown })._snapshotExternal();
90
150
  }
91
151
 
92
152
  /** Log in; resolves with the login response (or rejects on CTP error). */
93
- login(req: MdLoginReq = {}): Promise<RspUserLogin> {
94
- return this.request<RspUserLogin>(
95
- (id) => (this.native as { reqUserLogin(r: MdLoginReq, id: number): number }).reqUserLogin(req, id),
96
- true
97
- );
153
+ login(req: MdLoginReq = {}): Promise<RspUserLogin | undefined> {
154
+ const shapeError = requestShapeError(req, LOGIN_KEYS, "login request");
155
+ if (shapeError) return Promise.reject(shapeError);
156
+ const clean = copyOwnRecord(req, "login request");
157
+ let encoded: Uint8Array;
158
+ try { encoded = this.encode(STRUCT_ID.ReqUserLogin, clean); }
159
+ catch (error) { return Promise.reject(error); }
160
+ return this.runSessionTransition(() => {
161
+ this.beginRequestContextTransition("market-data login started");
162
+ return this.request<RspUserLogin | undefined>(
163
+ (id) => (this.native as { reqUserLogin(r: Uint8Array, id: number): number }).reqUserLogin(encoded, id),
164
+ true,
165
+ MD_BASE + 4,
166
+ true
167
+ );
168
+ });
169
+ }
170
+ logout(req: { brokerId?: string; userId?: string } = {}): Promise<UserLogout | undefined> {
171
+ const shapeError = requestShapeError(req, LOGOUT_KEYS, "logout request");
172
+ if (shapeError) return Promise.reject(shapeError);
173
+ const clean = copyOwnRecord(req, "logout request");
174
+ let encoded: Uint8Array;
175
+ try { encoded = this.encode(STRUCT_ID.UserLogout, clean); }
176
+ catch (error) { return Promise.reject(error); }
177
+ return this.runSessionTransition(() => {
178
+ this.beginRequestContextTransition("market-data logout started");
179
+ return this.request<UserLogout | undefined>(
180
+ (id) => (this.native as { reqUserLogout(r: Uint8Array, id: number): number }).reqUserLogout(encoded, id),
181
+ true,
182
+ MD_BASE + 5,
183
+ true
184
+ );
185
+ });
186
+ }
187
+
188
+ protected override shouldTimeoutRequest(
189
+ requestId: number,
190
+ sessionTransition: boolean
191
+ ): boolean {
192
+ if (!sessionTransition) return true;
193
+ return (this.native as { _timeoutSessionTransition(id: number): boolean })
194
+ ._timeoutSessionTransition(requestId);
195
+ }
196
+
197
+ // MarketData confirms a successful login natively: OnRspUserLogin activates the
198
+ // snapshot cache on the MD channel, which legitimately carries no
199
+ // FrontID/SessionID (those are the trade front's order-routing identity). There
200
+ // is deliberately no onRequestResolved override here — the base no-op is
201
+ // correct, and a successful MD login must never be rejected for lacking a trade
202
+ // session id.
203
+
204
+ /** SimNow may return requestId=0 for MD login/logout. Never overlap these
205
+ * transitions: otherwise a late id-0 login response cannot be attributed to
206
+ * one epoch. If a request times out while native still considers it pending,
207
+ * native stays fail-closed until the next front transition. */
208
+ private runSessionTransition<T>(start: () => Promise<T>): Promise<T> {
209
+ if (this.sessionTransition) {
210
+ return Promise.reject(new Error(
211
+ "market-data login/logout transition already in flight; await it first"
212
+ ));
213
+ }
214
+ const promise = start();
215
+ this.sessionTransition = promise;
216
+ const finish = () => {
217
+ if (this.sessionTransition !== promise) return;
218
+ try {
219
+ (this.native as { _abandonSessionTransition(): void })
220
+ ._abandonSessionTransition();
221
+ } catch {
222
+ // close() may have torn the native object down between settlement and
223
+ // this microtask; the native close path already invalidated the epoch.
224
+ } finally {
225
+ this.sessionTransition = undefined;
226
+ }
227
+ };
228
+ void promise.then(finish, finish);
229
+ return promise;
98
230
  }
99
- logout(req: { brokerId?: string; userId?: string } = {}): Promise<UserLogout> {
100
- return this.request<UserLogout>(
101
- (id) => (this.native as { reqUserLogout(r: object, id: number): number }).reqUserLogout(req, id),
102
- true
231
+
232
+ /** Query multicast instruments. Multi-row response, serialized through this
233
+ * client's conservative query scheduler. */
234
+ reqQryMulticastInstrument(
235
+ req: Partial<QryMulticastInstrument> = {}
236
+ ): Promise<MulticastInstrument[]> {
237
+ const shapeError = requestShapeError(req, MULTICAST_QUERY_KEYS, "multicast query");
238
+ if (shapeError) return Promise.reject(shapeError);
239
+ const clean = copyOwnRecord(req, "multicast query");
240
+ return this.queryRequest<MulticastInstrument[]>((id) =>
241
+ (this.native as {
242
+ reqQryMulticastInstrument(r: Partial<QryMulticastInstrument>, id: number): number;
243
+ }).reqQryMulticastInstrument(clean, id)
103
244
  );
104
245
  }
105
246
 
106
- private armedTrader?: object;
107
247
  /** Route this market data's ticks to a Trader's armed triggers (see Trader.arm).
108
- * A MarketData feeds exactly one Trader's registry; attaching a second,
109
- * different Trader throws rather than silently stealing the feed. */
110
- attachArm(trader: { _armRegistry(): unknown }): void {
111
- if (this.armedTrader && this.armedTrader !== trader) {
112
- throw new Error("this MarketData already feeds another Trader's armed triggers");
113
- }
114
- this.armedTrader = trader;
115
- this.native._attachArm(trader._armRegistry());
248
+ * A MarketData feeds exactly one live Trader's registry. Native ownership
249
+ * rejects replacement while that Trader is live, but permits replacing a
250
+ * registry whose Trader has already closed. */
251
+ attachArm(trader: Trader): void {
252
+ if (!(trader instanceof Trader))
253
+ throw new TypeError("attachArm requires a Trader from this package instance");
254
+ // Resolve and attach first. Native shared ownership is authoritative and
255
+ // avoids retaining a closed Trader JS object for the MarketData lifetime.
256
+ const registry = trader._armRegistry();
257
+ this.native._attachArm(registry);
116
258
  }
117
259
 
118
260
  /** @internal test-only: inject a synthetic depth tick into the ring. Optional
@@ -122,11 +264,40 @@ export class MarketData extends CtpClient {
122
264
  (this.native as { _injectTestTick(b?: number, a?: number): void })._injectTestTick(bid, ask);
123
265
  }
124
266
 
267
+ /** @internal test-only: inject one RFQ business notification through MdSpi. */
268
+ _injectTestForQuote(): void {
269
+ (this.native as { _injectTestForQuote(): void })._injectTestForQuote();
270
+ }
271
+
272
+ /** @internal test-only: drive a real native MD lifecycle callback. */
273
+ _injectTestLifecycle(
274
+ state: "connected" | "disconnected" | "login" | "login-error" | "logout" |
275
+ "login-pending" | "abandon" | "late-login"
276
+ ): void {
277
+ (this.native as { _injectTestLifecycle(s: string): void })._injectTestLifecycle(state);
278
+ }
279
+
125
280
  /** @internal test-only: spawn a background producer thread that pushes `n`
126
281
  * synthetic ticks into the ring (cross-thread doorbell stress). Each tick's
127
282
  * requestId carries its sequence number. */
128
- _burstTicks(n: number, jitterUs = 0): void {
129
- (this.native as { _burstTicks(n: number, j: number): void })._burstTicks(n, jitterUs);
283
+ _burstTicks(n: number, jitterUs = 0, injectControl = false): void {
284
+ (this.native as { _burstTicks(n: number, j: number, c: boolean): void })
285
+ ._burstTicks(n, jitterUs, injectControl);
286
+ }
287
+
288
+ /** @internal test-only: produce ticks on a native background thread through
289
+ * the real MD SPI. `ratePerSecond=0` is an instantaneous burst; otherwise
290
+ * ticks arrive as paced `burstSize` batches. Instrument IDs rotate across
291
+ * SIM00000000.. and `volume` is the zero-based global sequence. */
292
+ _produceTestTicks(
293
+ count: number,
294
+ instrumentCount: number,
295
+ ratePerSecond = 0,
296
+ burstSize = 512
297
+ ): void {
298
+ (this.native as {
299
+ _produceTestTicks(n: number, instruments: number, rate: number, burst: number): void;
300
+ })._produceTestTicks(count, instrumentCount, ratePerSecond, burstSize);
130
301
  }
131
302
 
132
303
  // Typed event signatures.
@@ -135,8 +306,13 @@ export class MarketData extends CtpClient {
135
306
  on(event: "front-connected", cb: (data: undefined, opts: CallbackOptions) => void): this;
136
307
  on(event: "front-disconnected", cb: (reason: number, opts: CallbackOptions) => void): this;
137
308
  on(event: "heart-beat-warning", cb: (lapse: number, opts: CallbackOptions) => void): this;
138
- on(event: "rsp-user-login", cb: (data: RspUserLogin, opts: CallbackOptions) => void): this;
139
- on(event: "rsp-sub-market-data", cb: (data: SpecificInstrument, opts: CallbackOptions) => void): this;
309
+ on(event: "rsp-user-login", cb: (data: RspUserLogin | undefined, opts: CallbackOptions) => void): this;
310
+ on(event: "rsp-user-logout", cb: (data: UserLogout | undefined, opts: CallbackOptions) => void): this;
311
+ on(event: "rsp-sub-market-data", cb: (data: SpecificInstrument | undefined, opts: CallbackOptions) => void): this;
312
+ on(event: "rsp-unsub-market-data", cb: (data: SpecificInstrument | undefined, opts: CallbackOptions) => void): this;
313
+ on(event: "rsp-sub-for-quote", cb: (data: SpecificInstrument | undefined, opts: CallbackOptions) => void): this;
314
+ on(event: "rsp-unsub-for-quote", cb: (data: SpecificInstrument | undefined, opts: CallbackOptions) => void): this;
315
+ on(event: "rsp-qry-multicast-instrument", cb: (data: MulticastInstrument | undefined, opts: CallbackOptions) => void): this;
140
316
  on(event: "rsp-error", cb: (data: undefined, opts: CallbackOptions) => void): this;
141
317
  on(event: string, cb: (...args: never[]) => void): this;
142
318
  on(event: string, cb: (...args: never[]) => void): this {
package/src/native/arm.cc CHANGED
@@ -4,6 +4,8 @@
4
4
 
5
5
  #include "arm.h"
6
6
 
7
+ #include <algorithm>
8
+
7
9
  namespace ctp {
8
10
 
9
11
  void ArmRegistry::setSink(OrderSink *sink) {
@@ -12,65 +14,147 @@ void ArmRegistry::setSink(OrderSink *sink) {
12
14
  }
13
15
 
14
16
  void ArmRegistry::clearSink() {
15
- std::lock_guard<std::mutex> lk(m_);
17
+ std::unique_lock<std::mutex> lk(m_);
16
18
  sink_ = nullptr;
19
+ armedByInstrument_.clear();
20
+ instrumentById_.clear();
21
+ count_.store(0, std::memory_order_release);
22
+ idleCv_.wait(lk, [&] { return inFlight_ == 0; });
23
+ }
24
+
25
+ bool ArmRegistry::hasSink() const {
26
+ std::lock_guard<std::mutex> lk(m_);
27
+ return sink_ != nullptr;
28
+ }
29
+
30
+ void ArmRegistry::clear() {
31
+ std::lock_guard<std::mutex> lk(m_);
32
+ armedByInstrument_.clear();
33
+ instrumentById_.clear();
34
+ count_.store(0, std::memory_order_release);
17
35
  }
18
36
 
19
37
  uint64_t ArmRegistry::arm(ArmSpec spec) {
20
38
  std::lock_guard<std::mutex> lk(m_);
21
39
  spec.id = nextId_++;
22
- spec.fired = false;
23
- armed_.push_back(std::move(spec));
24
- count_.store(armed_.size(), std::memory_order_relaxed);
25
- return armed_.back().id;
40
+ spec.lastRc = 0;
41
+ spec.nextAttempt = {};
42
+ spec.retryDelayMs = 100;
43
+ spec.firing = false;
44
+ const uint64_t id = spec.id;
45
+ const std::string instrument = spec.instrumentId;
46
+ armedByInstrument_[instrument].push_back(std::move(spec));
47
+ instrumentById_[id] = instrument;
48
+ count_.store(instrumentById_.size(), std::memory_order_release);
49
+ return id;
26
50
  }
27
51
 
28
52
  bool ArmRegistry::disarm(uint64_t id) {
29
53
  std::lock_guard<std::mutex> lk(m_);
30
- for (auto it = armed_.begin(); it != armed_.end(); ++it) {
31
- if (it->id == id) {
32
- armed_.erase(it);
33
- count_.store(armed_.size(), std::memory_order_relaxed);
34
- return true;
54
+ auto idx = instrumentById_.find(id);
55
+ if (idx == instrumentById_.end())
56
+ return false;
57
+ auto bucket = armedByInstrument_.find(idx->second);
58
+ if (bucket != armedByInstrument_.end()) {
59
+ auto &arms = bucket->second;
60
+ for (auto it = arms.begin(); it != arms.end(); ++it) {
61
+ if (it->id == id) {
62
+ arms.erase(it);
63
+ break;
64
+ }
35
65
  }
66
+ if (arms.empty())
67
+ armedByInstrument_.erase(bucket);
36
68
  }
37
- return false;
69
+ instrumentById_.erase(idx);
70
+ count_.store(instrumentById_.size(), std::memory_order_release);
71
+ return true;
38
72
  }
39
73
 
40
74
  size_t ArmRegistry::size() const {
41
75
  std::lock_guard<std::mutex> lk(m_);
42
- return armed_.size();
76
+ return instrumentById_.size();
43
77
  }
44
78
 
45
79
  void ArmRegistry::onTick(const char *instrumentId, double bid, double ask) {
46
- if (count_.load(std::memory_order_relaxed) == 0)
80
+ if (count_.load(std::memory_order_acquire) == 0)
47
81
  return; // no arms: zero overhead on the tick hot path
48
82
 
49
- std::lock_guard<std::mutex> lk(m_);
50
- if (!sink_)
51
- return;
52
-
53
- for (auto &a : armed_) {
54
- if (a.fired || a.instrumentId != instrumentId)
55
- continue;
83
+ const std::string instrument = instrumentId ? instrumentId : "";
84
+ for (;;) {
85
+ ArmSpec attempt;
86
+ OrderSink *sink = nullptr;
87
+ const auto now = std::chrono::steady_clock::now();
88
+ {
89
+ std::lock_guard<std::mutex> lk(m_);
90
+ if (!sink_)
91
+ return;
92
+ auto bucket = armedByInstrument_.find(instrument);
93
+ if (bucket == armedByInstrument_.end())
94
+ return;
95
+ ArmSpec *candidate = nullptr;
96
+ for (ArmSpec &a : bucket->second) {
97
+ if (a.firing ||
98
+ (a.nextAttempt.time_since_epoch().count() != 0 &&
99
+ now < a.nextAttempt))
100
+ continue;
56
101
  // The bid/ask must be a real, finite, sub-sentinel price. CTP writes DBL_MAX
57
102
  // (~1.8e308) into BidPrice1/AskPrice1 when a side is empty - e.g. at
58
103
  // limit-down there are no bids, so BidPrice1 == DBL_MAX. Without the
59
104
  // `< 1e300` guard a SELL trigger (bid >= triggerPrice) would fire on that
60
105
  // sentinel: a spurious market sell at the worst possible moment. Mirrors the
61
106
  // sentinel band rejected everywhere in risk.cc (sanePositive).
62
- const bool hit = (a.side == '0')
63
- ? (ask > 0.0 && ask < 1e300 && ask <= a.triggerPrice)
64
- : (bid > 0.0 && bid < 1e300 && bid >= a.triggerPrice);
65
- if (!hit)
66
- continue;
67
- a.fired = true; // one-shot: consumed on the first trigger, sent or blocked
68
- // build order + risk + ReqOrderInsert on this thread; record the outcome so
69
- // a risk-blocked/failed armed order isn't silent (fireCount would mislead).
70
- if (sink_->fireArmed(a) == 0)
107
+ const bool hit = (a.side == '0')
108
+ ? (ask > 0.0 && ask < 1e300 && ask <= a.triggerPrice)
109
+ : (bid > 0.0 && bid < 1e300 && bid >= a.triggerPrice);
110
+ if (hit) {
111
+ candidate = &a;
112
+ break;
113
+ }
114
+ }
115
+ if (!candidate)
116
+ return;
117
+ candidate->firing = true;
118
+ attempt = *candidate;
119
+ sink = sink_;
120
+ ++inFlight_;
121
+ }
122
+ // One-shot means one successful submission. A transient halt, rate limit, or
123
+ // metadata outage must not silently consume the mandate; keep it armed and
124
+ // retry no faster than every 100ms while the condition remains true.
125
+ // Never hold the registry mutex across a vendor request. A provider may
126
+ // synchronously emit a front callback which clears this same registry.
127
+ const int rc = sink->fireArmed(attempt);
128
+ {
129
+ std::lock_guard<std::mutex> lk(m_);
130
+ --inFlight_;
131
+ idleCv_.notify_all();
132
+ auto idx = instrumentById_.find(attempt.id);
133
+ if (idx == instrumentById_.end())
134
+ continue; // disarmed/session-cleared while the request was in flight
135
+ auto bucket = armedByInstrument_.find(idx->second);
136
+ if (bucket == armedByInstrument_.end())
137
+ continue;
138
+ auto &arms = bucket->second;
139
+ auto it = std::find_if(arms.begin(), arms.end(),
140
+ [&](const ArmSpec &a) { return a.id == attempt.id; });
141
+ if (it == arms.end())
142
+ continue;
143
+ it->firing = false;
144
+ it->lastRc = rc;
145
+ if (rc == 0) {
71
146
  fireCount_.fetch_add(1, std::memory_order_relaxed);
72
- else
147
+ instrumentById_.erase(attempt.id);
148
+ arms.erase(it); // remove from this instrument's hot bucket immediately
149
+ count_.store(instrumentById_.size(), std::memory_order_release);
150
+ } else {
73
151
  blockedCount_.fetch_add(1, std::memory_order_relaxed);
152
+ it->nextAttempt = now + std::chrono::milliseconds(it->retryDelayMs);
153
+ it->retryDelayMs = std::min<uint32_t>(5000, it->retryDelayMs * 2);
154
+ }
155
+ if (arms.empty())
156
+ armedByInstrument_.erase(bucket);
157
+ }
74
158
  }
75
159
  }
76
160
 
package/src/native/arm.h CHANGED
@@ -17,9 +17,12 @@
17
17
  #define CTP_NATIVE_ARM_H
18
18
 
19
19
  #include <atomic>
20
+ #include <chrono>
21
+ #include <condition_variable>
20
22
  #include <cstdint>
21
23
  #include <mutex>
22
24
  #include <string>
25
+ #include <unordered_map>
23
26
  #include <vector>
24
27
 
25
28
  namespace ctp {
@@ -30,7 +33,10 @@ struct ArmSpec {
30
33
  char side = '0'; // '0' buy: fire when ask<=trigger; '1' sell: bid>=trigger
31
34
  double triggerPrice = 0.0;
32
35
  std::vector<uint8_t> orderTemplate; // pre-encoded CThostFtdcInputOrderField
33
- bool fired = false;
36
+ int lastRc = 0;
37
+ std::chrono::steady_clock::time_point nextAttempt{};
38
+ uint32_t retryDelayMs = 100;
39
+ bool firing = false;
34
40
  };
35
41
 
36
42
  // Implemented by the Trader. Called on the MD callback thread; must be
@@ -44,13 +50,16 @@ class ArmRegistry {
44
50
  public:
45
51
  void setSink(OrderSink *sink); // link (Trader ctor)
46
52
  void clearSink(); // unlink under lock (Trader teardown)
53
+ bool hasSink() const; // safe attach/replacement check
54
+ void clear(); // remove every arm, keep the Trader sink linked
47
55
 
48
56
  uint64_t arm(ArmSpec spec); // JS thread
49
57
  bool disarm(uint64_t id); // JS thread
50
58
  size_t size() const;
51
- // Armed triggers that fired and were SENT (fireArmed returned 0).
59
+ // Armed triggers that were successfully SENT (fireArmed returned 0).
52
60
  uint64_t fireCount() const { return fireCount_.load(std::memory_order_relaxed); }
53
- // Armed triggers that fired but were REFUSED by the risk gate / send (rc!=0).
61
+ // Attempts refused by the risk gate / send (rc!=0). Refused triggers remain
62
+ // armed and retry with bounded exponential backoff; this is an attempt counter.
54
63
  uint64_t blockedCount() const { return blockedCount_.load(std::memory_order_relaxed); }
55
64
 
56
65
  // Hot path: MD callback thread, once per depth tick.
@@ -58,7 +67,10 @@ public:
58
67
 
59
68
  private:
60
69
  mutable std::mutex m_;
61
- std::vector<ArmSpec> armed_;
70
+ std::condition_variable idleCv_;
71
+ size_t inFlight_ = 0;
72
+ std::unordered_map<std::string, std::vector<ArmSpec>> armedByInstrument_;
73
+ std::unordered_map<uint64_t, std::string> instrumentById_;
62
74
  uint64_t nextId_ = 1;
63
75
  std::atomic<size_t> count_{0}; // lock-free "any arms?" gate
64
76
  std::atomic<uint64_t> fireCount_{0};