@hitrading/ctp-node 2.0.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 (79) hide show
  1. package/CHANGELOG.md +67 -0
  2. package/README.md +47 -32
  3. package/README.zh-CN.md +37 -27
  4. package/RELEASING.md +78 -0
  5. package/dist/client.d.ts +36 -15
  6. package/dist/client.d.ts.map +1 -1
  7. package/dist/client.js +234 -62
  8. package/dist/client.js.map +1 -1
  9. package/dist/codec.d.ts.map +1 -1
  10. package/dist/codec.js +84 -19
  11. package/dist/codec.js.map +1 -1
  12. package/dist/generated/structs.gen.d.ts +5461 -5461
  13. package/dist/generated/structs.gen.d.ts.map +1 -1
  14. package/dist/generated/trader.gen.d.ts.map +1 -1
  15. package/dist/generated/trader.gen.js +788 -94
  16. package/dist/generated/trader.gen.js.map +1 -1
  17. package/dist/index.cjs +1875 -415
  18. package/dist/index.d.cts +1 -1
  19. package/dist/index.d.ts +1 -1
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/index.js.map +1 -1
  22. package/dist/market-data.d.ts +41 -24
  23. package/dist/market-data.d.ts.map +1 -1
  24. package/dist/market-data.js +148 -29
  25. package/dist/market-data.js.map +1 -1
  26. package/dist/native-binding.d.ts.map +1 -1
  27. package/dist/native-binding.js +4 -0
  28. package/dist/native-binding.js.map +1 -1
  29. package/dist/trader.d.ts +111 -71
  30. package/dist/trader.d.ts.map +1 -1
  31. package/dist/trader.js +774 -180
  32. package/dist/trader.js.map +1 -1
  33. package/dist/validation.d.ts +27 -0
  34. package/dist/validation.d.ts.map +1 -0
  35. package/dist/validation.js +85 -0
  36. package/dist/validation.js.map +1 -0
  37. package/docs/API.md +1437 -0
  38. package/docs/API.zh-CN.md +1278 -0
  39. package/docs/MIGRATION.md +54 -0
  40. package/docs/assets/validation.svg +27 -0
  41. package/docs/integration.md +60 -0
  42. package/docs/native-hooks.md +281 -0
  43. package/docs/native-hooks.zh-CN.md +205 -0
  44. package/docs/troubleshooting.md +257 -0
  45. package/docs/troubleshooting.zh-CN.md +220 -0
  46. package/package.json +12 -4
  47. package/prebuilds/linux-x64/@hitrading+ctp-node.node +0 -0
  48. package/prebuilds/win32-x64/@hitrading+ctp-node.node +0 -0
  49. package/scripts/bench-decode.mjs +37 -0
  50. package/scripts/bench-fullmarket-offline.mjs +207 -0
  51. package/scripts/stress-fullmarket.mjs +255 -0
  52. package/src/addon.cc +2 -2
  53. package/src/client.ts +255 -65
  54. package/src/codec.ts +86 -19
  55. package/src/generated/structs.gen.ts +5461 -5461
  56. package/src/generated/trader.gen.ts +309 -94
  57. package/src/generated/traderreq.gen.cc +194 -18
  58. package/src/generated/traderreq.gen.h +4 -0
  59. package/src/generated/traderspi.gen.cc +129 -15
  60. package/src/generated/traderspi.gen.h +4 -2
  61. package/src/index.ts +8 -1
  62. package/src/market-data.ts +199 -46
  63. package/src/native/arm.cc +114 -30
  64. package/src/native/arm.h +16 -4
  65. package/src/native/channel.cc +209 -81
  66. package/src/native/channel.h +65 -24
  67. package/src/native/ctp_field.h +23 -0
  68. package/src/native/mdapi.cc +582 -69
  69. package/src/native/mdspi.cc +219 -16
  70. package/src/native/mdspi.h +59 -10
  71. package/src/native/order_capability.h +75 -0
  72. package/src/native/risk.cc +2030 -213
  73. package/src/native/risk.h +431 -78
  74. package/src/native/shared_handle.h +37 -0
  75. package/src/native/snapshot.h +75 -16
  76. package/src/native/traderapi.cc +753 -124
  77. package/src/native-binding.ts +4 -0
  78. package/src/trader.ts +971 -204
  79. package/src/validation.ts +96 -0
@@ -7,14 +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";
17
21
  import { STRUCT_ID } from "./generated/structs.gen.js";
22
+ import {
23
+ copyDenseStringArray,
24
+ copyOwnFronts,
25
+ copyOwnRecord,
26
+ ownStringKeys,
27
+ } from "./validation.js";
18
28
 
19
29
  const MD_BASE = 0x1000;
20
30
  const MD_EVENTS = new Map<number, string>([
@@ -33,13 +43,7 @@ const MD_EVENTS = new Map<number, string>([
33
43
  [MD_BASE + 13, "rtn-for-quote"],
34
44
  ]);
35
45
 
36
- export interface MdLoginReq {
37
- tradingDay?: string;
38
- brokerId?: string;
39
- userId?: string;
40
- password?: string;
41
- userProductInfo?: string;
42
- }
46
+ export type MdLoginReq = Partial<ReqUserLogin>;
43
47
 
44
48
  /** Market-data event names (symbolic; plain strings also work). */
45
49
  export enum MarketDataEvent {
@@ -58,42 +62,75 @@ export enum MarketDataEvent {
58
62
  RtnForQuote = "rtn-for-quote",
59
63
  }
60
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
+
61
93
  export class MarketData extends CtpClient {
94
+ private sessionTransition?: Promise<unknown>;
95
+
62
96
  constructor(flowPath: string, fronts: string | string[]) {
63
- super(new native.MarketData(flowPath, fronts), native.__layoutData(), MD_EVENTS);
64
- // SimNow's MD login/logout responses come back with requestId 0. Scope the
65
- // id-0 fallback to those two events (which are never concurrent) so an id-0
66
- // sub/unsub/error response can't hijack a pending login()/logout().
67
- this.zeroIdFallbackEvents.add(MD_BASE + 4); // rsp-user-login
68
- 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
+ );
69
102
  this.start();
70
103
  }
71
104
 
72
- getApiVersion(): string {
73
- return (this.native as Record<string, () => string>).getApiVersion();
105
+ get apiVersion(): string {
106
+ return (this.native as Record<string, () => string>).apiVersion();
74
107
  }
75
- getTradingDay(): string {
76
- return (this.native as Record<string, () => string>).getTradingDay();
108
+ get tradingDay(): string {
109
+ return (this.native as Record<string, () => string>).tradingDay();
77
110
  }
78
111
 
79
112
  /** Subscribe to depth market data. Returns the CTP send code (0 = ok). */
80
113
  subscribe(instrumentIds: string[]): number {
81
- 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);
82
116
  }
83
117
  unsubscribe(instrumentIds: string[]): number {
84
- 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);
85
120
  }
86
121
  subscribeForQuote(instrumentIds: string[]): number {
87
- 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);
88
124
  }
89
125
  unsubscribeForQuote(instrumentIds: string[]): number {
90
- 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);
91
128
  }
92
129
 
93
130
  /** Latest cached depth tick for an instrument — the C++ last-value cache,
94
- * updated on every tick before it reaches JS. Returns null if none has been
95
- * seen (or it was unsubscribed). Synchronous: no waiting for an event, no
96
- * per-tick bookkeeping in your strategy. */
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. */
97
134
  snapshot(instrumentId: string): DepthMarketData | null {
98
135
  const bytes = (this.native as { snapshot(id: string): Uint8Array | null }).snapshot(instrumentId);
99
136
  return bytes
@@ -113,29 +150,111 @@ export class MarketData extends CtpClient {
113
150
  }
114
151
 
115
152
  /** Log in; resolves with the login response (or rejects on CTP error). */
116
- login(req: MdLoginReq = {}): Promise<RspUserLogin> {
117
- return this.request<RspUserLogin>(
118
- (id) => (this.native as { reqUserLogin(r: MdLoginReq, id: number): number }).reqUserLogin(req, id),
119
- true
120
- );
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);
121
195
  }
122
- logout(req: { brokerId?: string; userId?: string } = {}): Promise<UserLogout> {
123
- return this.request<UserLogout>(
124
- (id) => (this.native as { reqUserLogout(r: object, id: number): number }).reqUserLogout(req, id),
125
- true
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;
230
+ }
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)
126
244
  );
127
245
  }
128
246
 
129
- private armedTrader?: object;
130
247
  /** Route this market data's ticks to a Trader's armed triggers (see Trader.arm).
131
- * A MarketData feeds exactly one Trader's registry; attaching a second,
132
- * different Trader throws rather than silently stealing the feed. */
133
- attachArm(trader: { _armRegistry(): unknown }): void {
134
- if (this.armedTrader && this.armedTrader !== trader) {
135
- throw new Error("this MarketData already feeds another Trader's armed triggers");
136
- }
137
- this.armedTrader = trader;
138
- 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);
139
258
  }
140
259
 
141
260
  /** @internal test-only: inject a synthetic depth tick into the ring. Optional
@@ -145,11 +264,40 @@ export class MarketData extends CtpClient {
145
264
  (this.native as { _injectTestTick(b?: number, a?: number): void })._injectTestTick(bid, ask);
146
265
  }
147
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
+
148
280
  /** @internal test-only: spawn a background producer thread that pushes `n`
149
281
  * synthetic ticks into the ring (cross-thread doorbell stress). Each tick's
150
282
  * requestId carries its sequence number. */
151
- _burstTicks(n: number, jitterUs = 0): void {
152
- (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);
153
301
  }
154
302
 
155
303
  // Typed event signatures.
@@ -158,8 +306,13 @@ export class MarketData extends CtpClient {
158
306
  on(event: "front-connected", cb: (data: undefined, opts: CallbackOptions) => void): this;
159
307
  on(event: "front-disconnected", cb: (reason: number, opts: CallbackOptions) => void): this;
160
308
  on(event: "heart-beat-warning", cb: (lapse: number, opts: CallbackOptions) => void): this;
161
- on(event: "rsp-user-login", cb: (data: RspUserLogin, opts: CallbackOptions) => void): this;
162
- 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;
163
316
  on(event: "rsp-error", cb: (data: undefined, opts: CallbackOptions) => void): this;
164
317
  on(event: string, cb: (...args: never[]) => void): this;
165
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};