@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
package/dist/trader.js CHANGED
@@ -8,74 +8,290 @@
8
8
  import { native } from "./native-binding.js";
9
9
  import { TraderBase, TRADER_EVENTS, TraderEvent } from "./generated/trader.gen.js";
10
10
  import { STRUCT_ID } from "./generated/structs.gen.js";
11
+ import { assertPlainRecord, copyDenseStringArray, copyOwnFronts, copyOwnRecord, ownStringKeys, } from "./validation.js";
11
12
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
12
- /** Reject a non-finite risk/cap limit. A NaN/Inf would make every `value > limit`
13
- * comparison in C++ false, silently DISABLING the control and leaving the caller
14
- * believing a cap is active — a risk control must never fail open by accident.
15
- * Finite values (including 0/negative, which legitimately mean "disabled") pass. */
13
+ /** Reject a non-finite or negative risk/cap limit. NaN/Inf can void ordinary
14
+ * comparisons, while a mistyped negative must not silently disable a control.
15
+ * Exactly zero is the explicit disabled/clear value. */
16
16
  function assertFiniteLimit(name, v) {
17
- if (v !== undefined && !Number.isFinite(v)) {
18
- throw new TypeError(`${name} must be a finite number (got ${v})`);
17
+ if (v !== undefined && (!Number.isFinite(v) || v < 0)) {
18
+ throw new TypeError(`${name} must be a non-negative finite number (got ${v})`);
19
19
  }
20
20
  }
21
+ function assertPositiveInt32OrDisabled(name, v) {
22
+ assertFiniteLimit(name, v);
23
+ if (v !== undefined && v > 0 && (!Number.isInteger(v) || v > 0x7fffffff)) {
24
+ throw new TypeError(`${name} must be an integer in 1..2147483647 (got ${v})`);
25
+ }
26
+ }
27
+ function assertLotLimit(name, v) {
28
+ assertFiniteLimit(name, v);
29
+ if (v !== undefined && v > 0 &&
30
+ (!Number.isInteger(v) || v > 0x7fffffff)) {
31
+ throw new TypeError(`${name} must be an integer in 1..2147483647 lots`);
32
+ }
33
+ }
34
+ function assertInstrumentId(name, instrumentId) {
35
+ if (typeof instrumentId !== "string" || !instrumentId || instrumentId.includes("\0"))
36
+ throw new TypeError(`${name}: instrumentId must be non-empty and contain no NUL`);
37
+ }
38
+ const RISK_LIMIT_KEYS = new Set([
39
+ "maxOrderVolume", "maxPriceDeviation", "maxNotional",
40
+ "maxOrdersPerSec", "orderBurst", "maxCloseOrdersPerSec",
41
+ "closeOrderBurst", "maxReferenceAgeMs", "maxAccountMargin",
42
+ ]);
43
+ function assertObjectKeys(value, label, allowed) {
44
+ for (const key of ownStringKeys(value, label))
45
+ if (!allowed.has(key))
46
+ throw new TypeError(`${label}: unknown field ${key}`);
47
+ }
48
+ const SESSION_KEYS = new Set([
49
+ "brokerId", "userId", "investorId", "password", "appId", "authCode",
50
+ "confirmSettlement", "sync",
51
+ ]);
52
+ const SESSION_SYNC_KEYS = new Set(["multipliers", "marginRates", "positions", "orders"]);
53
+ const ARM_SPEC_KEYS = new Set(["instrumentId", "side", "triggerPrice", "order"]);
54
+ const POSITION_LIMIT_KEYS = new Set(["long", "short"]);
55
+ const POSITION_SEED_KEYS = new Set([
56
+ "instrumentId", "side", "hedgeFlag", "volume", "margin",
57
+ ]);
21
58
  export class Trader extends TraderBase {
22
59
  broker;
23
60
  investor;
24
61
  orderRefSeq = 0;
25
62
  constructor(flowPath, fronts) {
26
- super(new native.Trader(flowPath, fronts), native.__layoutData(), TRADER_EVENTS);
27
- // Remember credentials from the login response so sync* needs no args, and
28
- // seed the order-ref counter past the broker's max so auto-assigned refs
29
- // never collide with a prior session's (CTP rejects duplicate refs).
30
- this.on("rsp-user-login", (d) => {
31
- const r = d;
32
- if (r) {
33
- this.broker = r.brokerId;
34
- this.investor = r.userId;
35
- const mx = r.maxOrderRef ? parseInt(r.maxOrderRef, 10) : NaN;
36
- if (Number.isFinite(mx) && mx > this.orderRefSeq)
37
- this.orderRefSeq = mx;
38
- // (The login session FrontID/SessionID — used as reservation keys so our
39
- // orders never collide with another terminal's on the same account — is
40
- // published into the risk engine directly in C++ from OnRspUserLogin; no
41
- // JS relay needed.)
42
- }
43
- });
63
+ super(new native.Trader(flowPath, copyOwnFronts(fronts, "Trader fronts")), native.__layoutData(), TRADER_EVENTS);
64
+ const clearConfirmedIdentity = () => {
65
+ this.broker = undefined;
66
+ this.investor = undefined;
67
+ };
68
+ this.on("front-connected", clearConfirmedIdentity);
69
+ this.on("front-disconnected", clearConfirmedIdentity);
44
70
  this.start();
45
71
  }
46
- getApiVersion() {
47
- return this.native.getApiVersion();
72
+ /** A raw login Promise may resolve only with a structurally usable session.
73
+ * Account confirmation itself happens in session(), after request-vs-response
74
+ * identity validation; merely observing a protocol event never grants order
75
+ * authority. */
76
+ onRequestResolved(eventName, value, _options) {
77
+ if (eventName === "rsp-user-logout") {
78
+ this.broker = undefined;
79
+ this.investor = undefined;
80
+ return;
81
+ }
82
+ if (eventName !== "rsp-user-login")
83
+ return;
84
+ // A matched login response updates the confirmed identity, but only from a
85
+ // row carrying the COMPLETE, usable identity (FrontID/SessionID > 0 plus
86
+ // BrokerID/UserID) — the same acceptance condition the generated login
87
+ // validator enforces before it resolves. A partial/abnormal success row
88
+ // (e.g. FrontID 0) is rejected downstream, so caching broker/investor from
89
+ // it would strand a stale identity after the login promise rejects, breaking
90
+ // the invariant "broker/investor set ⟺ a confirmed login". We still never
91
+ // throw here (that would reject an otherwise successful login); the
92
+ // authoritative account-match + reservation-key validation lives in
93
+ // session() / _confirmSessionAccount, and direct callers stay fail-closed
94
+ // natively via acceptsOrderAccount.
95
+ const r = value;
96
+ if (!r)
97
+ return;
98
+ if (typeof r.brokerId === "string" &&
99
+ r.brokerId &&
100
+ typeof r.userId === "string" &&
101
+ r.userId &&
102
+ Number.isInteger(r.frontId) &&
103
+ Number(r.frontId) > 0 &&
104
+ Number.isInteger(r.sessionId) &&
105
+ Number(r.sessionId) > 0) {
106
+ this.broker = r.brokerId;
107
+ this.investor = r.userId;
108
+ }
109
+ const maxOrderRef = typeof r.maxOrderRef === "string" ? r.maxOrderRef.trim() : "";
110
+ if (/^\d{1,12}$/.test(maxOrderRef)) {
111
+ const maxRef = Number(maxOrderRef);
112
+ if (Number.isFinite(maxRef) && maxRef > this.orderRefSeq)
113
+ this.orderRefSeq = maxRef;
114
+ }
115
+ }
116
+ /** Generated login/logout methods call this only after their request has
117
+ * encoded successfully. Revoke the confirmed JS account at that same atomic
118
+ * transition boundary, so a concurrent sync helper cannot start with the old
119
+ * identity while native risk state is already fail-closed for the new session. */
120
+ beginRequestContextTransition(reason) {
121
+ this.broker = undefined;
122
+ this.investor = undefined;
123
+ super.beginRequestContextTransition(reason);
124
+ }
125
+ shouldTimeoutRequest(requestId, sessionTransition) {
126
+ if (!sessionTransition)
127
+ return true;
128
+ return this.native._timeoutSessionTransition(requestId);
48
129
  }
49
- getTradingDay() {
50
- return this.native.getTradingDay();
130
+ get apiVersion() {
131
+ return this.native.apiVersion();
132
+ }
133
+ get tradingDay() {
134
+ return this.native.tradingDay();
51
135
  }
52
136
  /**
53
137
  * One-call post-connect handshake. Call it from the `front-connected` handler
54
138
  * (and again after a reconnect): authenticate (if appId/authCode given) →
55
- * login → confirm settlement → sync multipliers / positions / orders. Each
139
+ * login → confirm settlement → sync multipliers / margin rates / orders /
140
+ * positions. Each
56
141
  * step just wraps the matching req / sync method, so you can hand-roll your
57
142
  * own flow instead when you need finer control. Returns the row counts from
58
143
  * the sync steps. Must run on a connected front (queries need the session up).
59
144
  */
60
145
  async session(opts) {
61
- const { brokerId, userId, password, appId, authCode } = opts;
146
+ assertObjectKeys(opts, "session options", SESSION_KEYS);
147
+ const cleanOpts = copyOwnRecord(opts, "session options");
148
+ const { brokerId, userId, password, appId, authCode } = cleanOpts;
149
+ const investorId = cleanOpts.investorId ?? userId;
150
+ if (typeof brokerId !== "string" || !brokerId ||
151
+ brokerId.includes("\0") || typeof userId !== "string" || !userId ||
152
+ userId.includes("\0") || typeof password !== "string" || !password ||
153
+ password.includes("\0")) {
154
+ throw new TypeError("session requires brokerId, userId and password");
155
+ }
156
+ if (typeof investorId !== "string" || !investorId ||
157
+ investorId.includes("\0"))
158
+ throw new TypeError("session investorId must be a non-empty string");
159
+ if (cleanOpts.confirmSettlement !== undefined && typeof cleanOpts.confirmSettlement !== "boolean")
160
+ throw new TypeError("session.confirmSettlement must be boolean");
161
+ if ((appId === undefined) !== (authCode === undefined)) {
162
+ throw new TypeError("session appId and authCode must be supplied together");
163
+ }
164
+ if (appId !== undefined && (typeof appId !== "string" || !appId ||
165
+ appId.includes("\0") || typeof authCode !== "string" || !authCode ||
166
+ authCode.includes("\0")))
167
+ throw new TypeError("session appId and authCode must be non-empty strings");
168
+ let cleanSync = {};
169
+ if (cleanOpts.sync !== undefined) {
170
+ assertObjectKeys(cleanOpts.sync, "session.sync", SESSION_SYNC_KEYS);
171
+ cleanSync = copyOwnRecord(cleanOpts.sync, "session.sync");
172
+ const { multipliers, marginRates, positions, orders } = cleanSync;
173
+ if (multipliers !== undefined && typeof multipliers !== "boolean")
174
+ cleanSync.multipliers = copyDenseStringArray(multipliers, "session.sync.multipliers");
175
+ if (marginRates !== undefined)
176
+ cleanSync.marginRates = copyDenseStringArray(marginRates, "session.sync.marginRates");
177
+ if (positions !== undefined && typeof positions !== "boolean")
178
+ throw new TypeError("session.sync.positions must be boolean");
179
+ if (orders !== undefined && typeof orders !== "boolean")
180
+ throw new TypeError("session.sync.orders must be boolean");
181
+ }
182
+ // Validate the exact CTP wire capacities before revoking a healthy prior
183
+ // context. A malformed/oversized handshake must be side-effect free.
184
+ if (appId !== undefined && authCode !== undefined)
185
+ this.encode(STRUCT_ID.ReqAuthenticate, { brokerId, userId, appId, authCode });
186
+ this.encode(STRUCT_ID.ReqUserLogin, { brokerId, userId, password });
187
+ // Encode unconditionally: InvestorID is part of the native account
188
+ // confirmation even when this environment skips settlement confirmation.
189
+ // Passing these exact CTP bytes also avoids re-encoding GB18030 identities
190
+ // through N-API's UTF-8 string conversion.
191
+ const encodedAccount = this.encode(STRUCT_ID.SettlementInfoConfirm, { brokerId, investorId });
192
+ // Revoke native mandates/session authority at the start of the whole
193
+ // handshake, including the authentication phase. A failed auth must not
194
+ // leave an old close arm capable of firing under a superseded account.
195
+ this.native._beginSessionHandshake();
196
+ // No query created under the previous login may cross this handshake. Do
197
+ // this only after all synchronous option validation has succeeded.
198
+ this.invalidateRequestContext("trader session started");
199
+ let contextToken = this.requestContextToken();
200
+ // The cached JS identity is confirmed-session state, not merely the last
201
+ // attempted credentials. Revoke it before auth/login so a failed handshake
202
+ // cannot drive a later snapshot query with stale account fields.
203
+ this.broker = undefined;
204
+ this.investor = undefined;
205
+ // A reconnect may have an event gap. Keep all opening inserts
206
+ // fail-closed throughout the handshake until both authoritative snapshots
207
+ // have independently committed.
208
+ this.native._markPositionLedgerUncertain();
209
+ this.native._markOrderLedgerUncertain();
62
210
  if (appId !== undefined && authCode !== undefined) {
63
211
  await this.reqAuthenticate({ brokerId, userId, appId, authCode });
212
+ this.assertRequestContext(contextToken, "trader session authentication");
213
+ }
214
+ // The generated login method deliberately begins exactly one new request
215
+ // context. A test double may omit that transition; either form is safe. By
216
+ // retaining the pre-call epoch unless the explicit-transition counter also
217
+ // advanced once, an inline front-disconnected callback cannot masquerade as
218
+ // the expected login transition.
219
+ const beforeLoginContext = this.requestContextToken();
220
+ const beforeLoginTransition = this.requestTransitionToken();
221
+ const loginRequest = this.reqUserLogin({ brokerId, userId, password });
222
+ const afterLoginContext = this.requestContextToken();
223
+ const afterLoginTransition = this.requestTransitionToken();
224
+ if (afterLoginTransition === beforeLoginTransition + 1 &&
225
+ afterLoginContext === beforeLoginContext + 1) {
226
+ contextToken = afterLoginContext;
227
+ }
228
+ else if (afterLoginTransition === beforeLoginTransition) {
229
+ // Test doubles normally do not implement the generated transition. Keep
230
+ // the old epoch so any synchronous front event is detected after await.
231
+ contextToken = beforeLoginContext;
232
+ }
233
+ else {
234
+ // Settle the request before surfacing the invariant violation so a
235
+ // synchronously rejected test double cannot become an unhandled promise.
236
+ try {
237
+ await loginRequest;
238
+ }
239
+ catch { /* reported as transition failure */ }
240
+ throw new Error("trader session login crossed multiple context transitions");
241
+ }
242
+ const login = await loginRequest;
243
+ this.assertRequestContext(contextToken, "trader session login");
244
+ if (!login || !Number.isInteger(login.frontId) || login.frontId <= 0 ||
245
+ !Number.isInteger(login.sessionId) || login.sessionId <= 0 ||
246
+ login.brokerId !== brokerId ||
247
+ login.userId !== userId) {
248
+ // FrontID/SessionID are part of the reservation identity. Treating an
249
+ // empty success response as ready would reuse an old/zero native session
250
+ // key and create ghost reservations when the first OnRtnOrder arrives.
251
+ this.broker = undefined;
252
+ this.investor = undefined;
253
+ throw new Error("trader login response has missing or mismatched session identity");
64
254
  }
65
- await this.reqUserLogin({ brokerId, userId, password });
66
- if (opts.confirmSettlement ?? true) {
255
+ // A successful CTP response may legally end with an empty payload. The
256
+ // request identity is still authoritative for the synchronization calls
257
+ // below; never retain a previous session's broker/investor in that case.
258
+ const confirmed = this.native._confirmSessionAccount(login.frontId, login.sessionId, encodedAccount);
259
+ if (!confirmed) {
260
+ this.broker = undefined;
261
+ this.investor = undefined;
262
+ throw new Error("native Trader session/account confirmation failed");
263
+ }
264
+ this.broker = brokerId;
265
+ this.investor = investorId;
266
+ const maxOrderRef = typeof login.maxOrderRef === "string"
267
+ ? login.maxOrderRef.trim() : "";
268
+ const maxRef = /^\d{1,12}$/.test(maxOrderRef) ? Number(maxOrderRef) : NaN;
269
+ if (Number.isFinite(maxRef) && maxRef > this.orderRefSeq)
270
+ this.orderRefSeq = maxRef;
271
+ if (cleanOpts.confirmSettlement ?? true) {
67
272
  // idempotent: confirming an already-confirmed statement is fine
68
- await this.reqSettlementInfoConfirm({ brokerId, investorId: userId });
273
+ await this.reqSettlementInfoConfirm({ brokerId, investorId });
274
+ this.assertRequestContext(contextToken, "trader session settlement confirmation");
69
275
  }
70
- const sync = opts.sync ?? {};
276
+ const sync = cleanSync;
71
277
  const mul = sync.multipliers ?? true;
72
- const result = { multipliers: 0, positions: 0, orders: 0 };
73
- if (mul)
278
+ const result = { multipliers: 0, marginRates: 0, positions: 0, orders: 0 };
279
+ if (mul) {
74
280
  result.multipliers = await this.syncMultipliers(Array.isArray(mul) ? mul : undefined);
75
- if (sync.positions ?? true)
76
- result.positions = await this.syncPositions();
77
- if (sync.orders ?? true)
281
+ this.assertRequestContext(contextToken, "trader session multiplier sync");
282
+ }
283
+ if (sync.marginRates?.length) {
284
+ result.marginRates = await this.syncMarginRates(sync.marginRates);
285
+ this.assertRequestContext(contextToken, "trader session margin sync");
286
+ }
287
+ if (sync.orders ?? true) {
78
288
  result.orders = await this.syncOrders();
289
+ this.assertRequestContext(contextToken, "trader session order sync");
290
+ }
291
+ if (sync.positions ?? true) {
292
+ result.positions = await this.syncPositions();
293
+ this.assertRequestContext(contextToken, "trader session position sync");
294
+ }
79
295
  return result;
80
296
  }
81
297
  /** Assign a unique numeric OrderRef when the caller left it blank. CTP treats
@@ -83,10 +299,105 @@ export class Trader extends TraderBase {
83
299
  * ref with "不允许重复报单", so an unset ref would otherwise collide. */
84
300
  withAutoOrderRef(order) {
85
301
  if (order.orderRef === undefined || order.orderRef === "") {
86
- return { ...order, orderRef: String(++this.orderRefSeq) };
302
+ if (this.orderRefSeq >= 999_999_999_999) {
303
+ throw new RangeError("OrderRef space exhausted for this process/session");
304
+ }
305
+ return { ...order, orderRef: String(this.orderRefSeq + 1) };
306
+ }
307
+ if (typeof order.orderRef !== "string" || !/^\d{1,12}$/.test(order.orderRef)) {
308
+ throw new TypeError("orderRef must contain 1..12 decimal digits");
309
+ }
310
+ const explicit = Number(order.orderRef);
311
+ if (explicit <= this.orderRefSeq) {
312
+ throw new RangeError(`explicit orderRef must be greater than the current high-water mark ${this.orderRefSeq}`);
87
313
  }
88
314
  return order;
89
315
  }
316
+ commitOrderRef(order) {
317
+ this.orderRefSeq = Number(order.orderRef);
318
+ }
319
+ validateOrder(order, context) {
320
+ const clean = copyOwnRecord(order, context);
321
+ if (!this.broker || !this.investor) {
322
+ throw new Error(`${context}: a confirmed Trader login is required`);
323
+ }
324
+ if (typeof clean.instrumentId !== "string" || !clean.instrumentId ||
325
+ clean.instrumentId.includes("\0") ||
326
+ (clean.direction !== "0" && clean.direction !== "1")) {
327
+ throw new TypeError(`${context}: instrumentId and direction ("0"/"1") are required`);
328
+ }
329
+ if (typeof clean.combOffsetFlag !== "string" ||
330
+ !/^[0-6]$/.test(clean.combOffsetFlag)) {
331
+ throw new TypeError(`${context}: combOffsetFlag must be one CTP offset digit 0..6; multi-leg orders are unsupported`);
332
+ }
333
+ if (clean.combHedgeFlag !== undefined &&
334
+ (typeof clean.combHedgeFlag !== "string" ||
335
+ !/^[123567]$/.test(clean.combHedgeFlag))) {
336
+ throw new TypeError(`${context}: combHedgeFlag must be one CTP hedge digit (1, 2, 3, 5, 6 or 7)`);
337
+ }
338
+ if (!Number.isInteger(clean.volumeTotalOriginal) ||
339
+ !(Number(clean.volumeTotalOriginal) > 0) ||
340
+ Number(clean.volumeTotalOriginal) > 0x7fffffff) {
341
+ throw new TypeError(`${context}: volumeTotalOriginal must be a positive int32`);
342
+ }
343
+ if (!Number.isFinite(clean.limitPrice) || !(Number(clean.limitPrice) > 0) ||
344
+ Number(clean.limitPrice) >= 1e300) {
345
+ throw new TypeError(`${context}: limitPrice must be a positive finite price`);
346
+ }
347
+ if (clean.brokerId !== undefined && clean.brokerId !== this.broker) {
348
+ throw new TypeError(`${context}: brokerId must match the confirmed login`);
349
+ }
350
+ if (clean.investorId !== undefined && clean.investorId !== this.investor) {
351
+ throw new TypeError(`${context}: investorId must match the confirmed login`);
352
+ }
353
+ const value = (key, fallback) => clean[key] === undefined ? fallback : clean[key];
354
+ const empty = (v) => v === undefined || v === "";
355
+ // This binding deliberately models only one immediate, single-instrument
356
+ // GFD limit order. Reject every semantic/dimension the native reservation
357
+ // ledger does not represent; otherwise an arm could be accepted now and
358
+ // retry an impossible template forever after its trigger fires.
359
+ if (value("orderPriceType", "2") !== "2" ||
360
+ value("timeCondition", "3") !== "3" || !empty(clean.gtdDate) ||
361
+ value("volumeCondition", "1") !== "1" ||
362
+ value("minVolume", 1) !== 1 ||
363
+ value("contingentCondition", "1") !== "1" ||
364
+ value("stopPrice", 0) !== 0 ||
365
+ value("forceCloseReason", "0") !== "0" ||
366
+ value("isAutoSuspend", 0) !== 0 ||
367
+ !empty(clean.businessUnit) || value("requestId", 0) !== 0 ||
368
+ value("userForceClose", 0) !== 0 ||
369
+ value("isSwapOrder", 0) !== 0 || !empty(clean.exchangeId) ||
370
+ !empty(clean.investUnitId) || !empty(clean.accountId) ||
371
+ !empty(clean.currencyId) || !empty(clean.clientId) ||
372
+ value("sessionReqSeq", 0) !== 0) {
373
+ throw new TypeError(`${context}: only an immediate single-instrument GFD limit order is supported`);
374
+ }
375
+ return {
376
+ ...clean,
377
+ orderPriceType: "2",
378
+ combHedgeFlag: clean.combHedgeFlag ?? "1",
379
+ timeCondition: "3",
380
+ gtdDate: "",
381
+ volumeCondition: "1",
382
+ minVolume: 1,
383
+ contingentCondition: "1",
384
+ stopPrice: 0,
385
+ forceCloseReason: "0",
386
+ isAutoSuspend: 0,
387
+ businessUnit: "",
388
+ requestId: 0,
389
+ userForceClose: 0,
390
+ isSwapOrder: 0,
391
+ exchangeId: "",
392
+ investUnitId: "",
393
+ accountId: "",
394
+ currencyId: "",
395
+ clientId: "",
396
+ sessionReqSeq: 0,
397
+ brokerId: this.broker,
398
+ investorId: this.investor,
399
+ };
400
+ }
90
401
  /**
91
402
  * Insert an order through the C++ pre-trade risk gate. Resolves on submission:
92
403
  * CTP sends no success acknowledgement for an accepted order - only
@@ -96,33 +407,54 @@ export class Trader extends TraderBase {
96
407
  * unique numeric value automatically.
97
408
  */
98
409
  reqOrderInsert(req = {}) {
99
- return super.reqOrderInsert(this.withAutoOrderRef(req));
410
+ const order = this.withAutoOrderRef(this.validateOrder(req, "reqOrderInsert"));
411
+ // Preflight field capacities before consuming the OrderRef high-water mark.
412
+ // TraderBase encodes the same object again when it submits.
413
+ this.encode(STRUCT_ID.InputOrder, order);
414
+ const result = super.reqOrderInsert(order);
415
+ this.commitOrderRef(order);
416
+ return result;
100
417
  }
101
418
  /** Publish pre-trade risk limits to the C++ enforcer (takes effect at once). */
102
- riskSet(config) {
419
+ setRiskLimits(config) {
420
+ const clean = copyOwnRecord(config, "setRiskLimits");
421
+ for (const key of ownStringKeys(clean, "setRiskLimits")) {
422
+ if (!RISK_LIMIT_KEYS.has(key))
423
+ throw new TypeError(`setRiskLimits: unknown field ${key}`);
424
+ }
103
425
  // A non-finite limit would silently disable that control (see
104
426
  // assertFiniteLimit) — reject it rather than run unprotected.
105
- assertFiniteLimit("riskSet.maxOrderVolume", config.maxOrderVolume);
106
- assertFiniteLimit("riskSet.maxPriceDeviation", config.maxPriceDeviation);
107
- assertFiniteLimit("riskSet.maxNotional", config.maxNotional);
108
- assertFiniteLimit("riskSet.maxOrdersPerSec", config.maxOrdersPerSec);
109
- assertFiniteLimit("riskSet.orderBurst", config.orderBurst);
110
- assertFiniteLimit("riskSet.maxPositionCost", config.maxPositionCost);
111
- assertFiniteLimit("riskSet.maxMargin", config.maxMargin);
112
- this.native.riskSet(config);
427
+ assertPositiveInt32OrDisabled("setRiskLimits.maxOrderVolume", clean.maxOrderVolume);
428
+ assertFiniteLimit("setRiskLimits.maxPriceDeviation", clean.maxPriceDeviation);
429
+ assertFiniteLimit("setRiskLimits.maxNotional", clean.maxNotional);
430
+ assertFiniteLimit("setRiskLimits.maxOrdersPerSec", clean.maxOrdersPerSec);
431
+ assertFiniteLimit("setRiskLimits.orderBurst", clean.orderBurst);
432
+ assertFiniteLimit("setRiskLimits.maxCloseOrdersPerSec", clean.maxCloseOrdersPerSec);
433
+ assertFiniteLimit("setRiskLimits.closeOrderBurst", clean.closeOrderBurst);
434
+ assertFiniteLimit("setRiskLimits.maxAccountMargin", clean.maxAccountMargin);
435
+ assertFiniteLimit("setRiskLimits.maxReferenceAgeMs", clean.maxReferenceAgeMs);
436
+ if (clean.maxReferenceAgeMs !== undefined && !(clean.maxReferenceAgeMs > 0)) {
437
+ throw new TypeError("setRiskLimits.maxReferenceAgeMs must be > 0");
438
+ }
439
+ this.native.setRiskLimits(clean);
113
440
  return this;
114
441
  }
115
- /** Kill-switch: C++ immediately blocks every order-opening send that reaches
116
- * the exchange at once — regular, exec, quote, for-quote, option-self-close
117
- * and comb-action inserts. Cancels and other *actions* are deliberately left
118
- * open so you can still pull working orders while halted; parked/staged orders
119
- * (not sent to the exchange immediately) are likewise not gated. Takes effect
120
- * at once; reverse with {@link resume}. */
121
- halt() {
122
- this.native.riskHalt();
442
+ /** Enter REDUCE_ONLY atomically at the final vendor-API send barrier. Armed
443
+ * opens remain registered but cannot send until resume(). */
444
+ reduceOnly() {
445
+ this.native.riskReduceOnly();
123
446
  return this;
124
447
  }
125
- /** Release the kill-switch (see {@link halt}). */
448
+ /** Enter HALT_ALL atomically: both opening and closing order inserts, advanced
449
+ * mutations and bank/futures transfers are refused, and all existing armed
450
+ * triggers are cleared. New arm() calls are rejected until resume().
451
+ * Cancellation actions remain available so working
452
+ * exchange orders can still be withdrawn. */
453
+ haltAll() {
454
+ this.native.riskHaltAll();
455
+ return this;
456
+ }
457
+ /** Return to NORMAL mode after reduceOnly() or haltAll(). */
126
458
  resume() {
127
459
  this.native.riskResume();
128
460
  return this;
@@ -131,114 +463,189 @@ export class Trader extends TraderBase {
131
463
  * Wires the feed's C++ snapshot cache straight into this Trader's risk engine,
132
464
  * so the deviation check reads current prices in C++ on the order path (no JS
133
465
  * round-trip, and it also covers armed orders that fire with no JS in the loop).
134
- * Without this, no reference is set and the deviation check is skipped. */
466
+ * Without a fresh reference, an enabled deviation check fails closed. */
135
467
  trackMarketData(md) {
136
468
  this.native._attachSnapshot(md._snapshotExternal());
137
469
  return this;
138
470
  }
139
471
  // Contract multipliers (for cost accounting) and margin rates (for the
140
- // maxMargin cap) are NOT fed from JS: the C++ risk engine sources them directly
472
+ // maxAccountMargin cap) are NOT fed from JS: the C++ risk engine sources them directly
141
473
  // from CTP's OnRspQryInstrument / OnRspQryInstrumentMarginRate callbacks (see
142
474
  // scripts/codegen/generate-trader.mjs). So any reqQryInstrument keeps
143
475
  // multipliers current, and querying reqQryInstrumentMarginRate for the
144
- // contracts you trade keeps the margin cap exact — no JS round-trip, and the
145
- // checks also cover armed orders that fire from C++ with no JS in the loop.
476
+ // syncMarginRates() loads investor plus exchange-base schedules. Missing
477
+ // metadata fails closed; IsRelative is combined with the matching base.
146
478
  /**
147
479
  * Cap the open position (in lots) for one instrument, enforced in C++ on
148
480
  * every opening order. Pass a number to cap both sides at once, or
149
481
  * `{ long, short }` to cap each side separately. Within `{ long, short }`,
150
482
  * **omitting a side leaves that side's current cap unchanged** (on a re-call it
151
- * is NOT reset to uncapped), and passing `<= 0` for a side removes its cap.
483
+ * is NOT reset to uncapped), and passing `0` for a side removes its cap.
152
484
  * Long and short are always tracked independently.
153
485
  *
154
- * The check is fill-based (counts confirmed position, like maxPositionCost),
155
- * so rapid bursts of opens can momentarily overshoot before the fills land —
156
- * size the cap with that in mind.
486
+ * Held positions and in-flight working opens are counted atomically.
157
487
  *
158
- * td.setMaxPosition("rb2610", 100); // long<=100 and short<=100
159
- * td.setMaxPosition("ru2610", { long: 100, short: 20 });
488
+ * td.setInstrumentPositionLimit("rb2610", 100);
489
+ * td.setInstrumentPositionLimit("ru2610", { long: 100, short: 20 });
160
490
  */
161
- setMaxPosition(instrumentId, max) {
162
- if (typeof max === "number") {
163
- assertFiniteLimit("setMaxPosition", max);
164
- this.native.setMaxPositionVolume(instrumentId, true, max);
165
- this.native.setMaxPositionVolume(instrumentId, false, max);
166
- }
167
- else {
168
- assertFiniteLimit("setMaxPosition.long", max.long);
169
- assertFiniteLimit("setMaxPosition.short", max.short);
170
- if (max.long !== undefined)
171
- this.native.setMaxPositionVolume(instrumentId, true, max.long);
172
- if (max.short !== undefined)
173
- this.native.setMaxPositionVolume(instrumentId, false, max.short);
174
- }
491
+ setInstrumentPositionLimit(instrumentId, limit) {
492
+ assertInstrumentId("setInstrumentPositionLimit", instrumentId);
493
+ const row = this.normalizePositionLimit(instrumentId, limit);
494
+ this.native._setInstrumentPositionLimits([row]);
175
495
  return this;
176
496
  }
177
497
  /** Cap several instruments at once, e.g.
178
498
  * `{ rb2610: 100, ru2610: { long: 100, short: 20 } }`. */
179
- setMaxPositions(limits) {
180
- for (const id of Object.keys(limits))
181
- this.setMaxPosition(id, limits[id]);
499
+ setInstrumentPositionLimits(limits) {
500
+ const rows = ownStringKeys(limits, "setInstrumentPositionLimits").map((instrumentId) => {
501
+ const limit = limits[instrumentId];
502
+ assertInstrumentId("setInstrumentPositionLimits", instrumentId);
503
+ return this.normalizePositionLimit(instrumentId, limit);
504
+ });
505
+ this.native._setInstrumentPositionLimits(rows);
182
506
  return this;
183
507
  }
508
+ normalizePositionLimit(instrumentId, limit) {
509
+ if (typeof limit === "number") {
510
+ assertLotLimit("setInstrumentPositionLimit", limit);
511
+ return copyOwnRecord({ instrumentId, long: limit, short: limit }, "setInstrumentPositionLimit");
512
+ }
513
+ assertPlainRecord(limit, "setInstrumentPositionLimit");
514
+ const clean = copyOwnRecord(limit, "setInstrumentPositionLimit");
515
+ if (clean.long === undefined && clean.short === undefined) {
516
+ throw new TypeError("setInstrumentPositionLimit requires a number or at least one of long/short");
517
+ }
518
+ for (const key of ownStringKeys(clean, "setInstrumentPositionLimit")) {
519
+ if (!POSITION_LIMIT_KEYS.has(key))
520
+ throw new TypeError(`setInstrumentPositionLimit: unknown field ${key}`);
521
+ }
522
+ assertLotLimit("setInstrumentPositionLimit.long", clean.long);
523
+ assertLotLimit("setInstrumentPositionLimit.short", clean.short);
524
+ return copyOwnRecord({ instrumentId, long: clean.long, short: clean.short }, "setInstrumentPositionLimit");
525
+ }
184
526
  /**
185
- * Cap one instrument's open-position cost (Σ open price × volume × multiplier,
186
- * long and short summed - a gross capital/concentration limit), enforced in
187
- * C++ on every opening order. This is per-instrument and independent of the
188
- * account-wide cap set via riskSet({ maxPositionCost }); both apply. Pass
189
- * `maxCost <= 0` to remove it. Fill-based, same caveat as maxPositionCost.
527
+ * Cap one instrument's scheduled open margin (CTP by-money + by-volume,
528
+ * long and short summed), enforced in C++ on every opening order. This is
529
+ * independent of the account-wide maxAccountMargin cap; both apply. Pass
530
+ * `limit = 0` to remove it. Held and in-flight exposure both count.
190
531
  */
191
- setMaxPositionCost(instrumentId, maxCost) {
192
- assertFiniteLimit("setMaxPositionCost", maxCost);
193
- this.native.setMaxInstrumentCost(instrumentId, maxCost);
532
+ setInstrumentMarginLimit(instrumentId, limit) {
533
+ assertInstrumentId("setInstrumentMarginLimit", instrumentId);
534
+ assertFiniteLimit("setInstrumentMarginLimit", limit);
535
+ this.native._setInstrumentMarginLimits([{ instrumentId, limit }]);
194
536
  return this;
195
537
  }
196
- /** Cap several instruments' open-position cost at once, e.g.
538
+ /** Cap several instruments' scheduled open margin at once, e.g.
197
539
  * `{ ag2608: 2_000_000, au2608: 5_000_000 }`. */
198
- setMaxPositionCosts(limits) {
199
- for (const id of Object.keys(limits)) {
200
- assertFiniteLimit(`setMaxPositionCosts.${id}`, limits[id]);
201
- this.native.setMaxInstrumentCost(id, limits[id]);
202
- }
540
+ setInstrumentMarginLimits(limits) {
541
+ const rows = ownStringKeys(limits, "setInstrumentMarginLimits").map((instrumentId) => {
542
+ const limit = limits[instrumentId];
543
+ assertInstrumentId("setInstrumentMarginLimits", instrumentId);
544
+ assertFiniteLimit(`setInstrumentMarginLimits.${instrumentId}`, limit);
545
+ return { instrumentId, limit };
546
+ });
547
+ this.native._setInstrumentMarginLimits(rows);
203
548
  return this;
204
549
  }
205
- /** Seed a pre-existing position into the margin/cost cap. `margin` is the real
206
- * capital occupied (CTP InvestorPosition.UseMargin) — the unit the maxMargin
207
- * cap tracks. A deliberate resync op (overwrites the held side), so it stays a
208
- * JS-driven call, unlike the passive multiplier / margin-rate feeds (sourced in
209
- * C++). */
210
- seedPosition(instrumentId, side, volume, margin) {
211
- this.native.seedPosition(instrumentId, side === "long", volume, margin);
212
- return this;
550
+ /** Atomically replace held positions from a complete manually reconciled
551
+ * snapshot. `margin` is CTP InvestorPosition.UseMargin. An empty array is an
552
+ * authoritative flat book. Partial/incremental seeding is intentionally not
553
+ * exposed because armed orders can run between JS calls. */
554
+ seedPositions(positions) {
555
+ if (!Array.isArray(positions))
556
+ throw new TypeError("seedPositions requires a complete position array");
557
+ const seeds = [];
558
+ const positionCount = positions.length;
559
+ for (let i = 0; i < positionCount; i++) {
560
+ if (!Object.prototype.hasOwnProperty.call(positions, i))
561
+ throw new TypeError(`seedPositions row ${i} must be an explicit array entry`);
562
+ const row = copyOwnRecord(positions[i], `seedPositions row ${i}`);
563
+ for (const key of ownStringKeys(row, `seedPositions row ${i}`))
564
+ if (!POSITION_SEED_KEYS.has(key))
565
+ throw new TypeError(`seedPositions row ${i}: unknown field ${key}`);
566
+ assertInstrumentId("seedPositions", row.instrumentId);
567
+ if ((row.side !== "long" && row.side !== "short") ||
568
+ typeof row.hedgeFlag !== "string" ||
569
+ !/^[123567]$/.test(row.hedgeFlag) ||
570
+ !Number.isInteger(row.volume) || row.volume < 0 ||
571
+ !Number.isFinite(row.margin) || row.margin < 0) {
572
+ throw new TypeError("seedPositions requires long/short, one hedgeFlag digit, a non-negative integer volume and non-negative finite margin");
573
+ }
574
+ seeds.push({
575
+ instrumentId: row.instrumentId,
576
+ isLong: row.side === "long",
577
+ hedgeFlag: row.hedgeFlag,
578
+ volume: row.volume,
579
+ margin: row.margin,
580
+ });
581
+ }
582
+ return this.replacePositionSeeds(seeds);
213
583
  }
214
- /** Seed open-position MARGIN from reqQryInvestorPosition() rows for GROSS-mode
215
- * accounts (posiDirection '2' = long, '3' = short; any other value, incl. net
216
- * '1', is bucketed as short). Uses each row's real UseMargin. Cost/margin caps
217
- * sum both sides so the bucket doesn't matter for them, but a per-side *volume*
218
- * cap on a net-mode instrument would track the wrong side — for net-mode
219
- * accounts, seed those via seedPosition() with the side you intend. */
584
+ replacePositionSeeds(seeds) {
585
+ for (let attempt = 0; attempt < 5; attempt++) {
586
+ const revision = this.native.riskRevision();
587
+ if (this.native.replacePositions(seeds, revision))
588
+ return this;
589
+ }
590
+ throw new Error("position snapshot could not stabilize; live state kept unchanged");
591
+ }
592
+ /** Atomically replace held position margin from complete gross-mode query rows
593
+ * (`posiDirection` '2' long, '3' short). Net/unknown direction is rejected
594
+ * because guessing a side corrupts per-side volume caps. */
220
595
  seedFromPositions(positions) {
221
- // Aggregate by instrument+side (CTP may return several rows per instrument).
596
+ const seeds = this.aggregatePositions(positions);
597
+ // Native callbacks can mutate the ledger concurrently even though this JS
598
+ // method is synchronous. Retry a revision-checked replacement rather than
599
+ // expose a clear-then-seed gap or overwrite a callback that raced us.
600
+ return this.replacePositionSeeds(seeds);
601
+ }
602
+ aggregatePositions(positions) {
603
+ // Aggregate by instrument+side+hedge flag (CTP may return several rows per
604
+ // bucket, e.g. today/history). Different hedge flags can have different
605
+ // margin schedules and must never be averaged together on close.
606
+ if (!Array.isArray(positions))
607
+ throw new TypeError("position snapshot must be an array");
222
608
  const agg = new Map();
223
- for (const p of positions) {
224
- if (!(p.position > 0))
609
+ const positionCount = positions.length;
610
+ for (let i = 0; i < positionCount; i++) {
611
+ if (!Object.prototype.hasOwnProperty.call(positions, i))
612
+ throw new TypeError(`position snapshot row ${i} must be an explicit array entry`);
613
+ const p = positions[i];
614
+ const plain = p !== null && typeof p === "object" && !Array.isArray(p) &&
615
+ (Object.getPrototypeOf(p) === Object.prototype || Object.getPrototypeOf(p) === null);
616
+ const row = plain ? copyOwnRecord(p, "position snapshot row") : undefined;
617
+ if (!row || typeof row.instrumentId !== "string" || !row.instrumentId ||
618
+ row.instrumentId.includes("\0") ||
619
+ !Number.isInteger(row.position) || row.position < 0 ||
620
+ !Number.isFinite(row.useMargin) || row.useMargin < 0 ||
621
+ (row.posiDirection !== "2" && row.posiDirection !== "3") ||
622
+ typeof row.hedgeFlag !== "string" ||
623
+ !/^[123567]$/.test(row.hedgeFlag)) {
624
+ throw new TypeError(`invalid position snapshot for ${row?.instrumentId || "<unknown>"}`);
625
+ }
626
+ if (!(row.position > 0))
225
627
  continue;
226
- const long = p.posiDirection === "2";
227
- const key = `${p.instrumentId}|${long}`;
228
- const e = agg.get(key) ?? { id: p.instrumentId, long, vol: 0, cost: 0 };
229
- e.vol += p.position;
230
- e.cost += p.useMargin; // real margin occupied (the unit the cap tracks)
628
+ const isLong = row.posiDirection === "2";
629
+ const key = `${row.instrumentId}|${isLong}|${row.hedgeFlag}`;
630
+ const e = agg.get(key) ?? { instrumentId: row.instrumentId, isLong, hedgeFlag: row.hedgeFlag, volume: 0, margin: 0 };
631
+ const volume = e.volume + row.position;
632
+ const margin = e.margin + row.useMargin;
633
+ if (!Number.isSafeInteger(volume) || !Number.isFinite(margin)) {
634
+ throw new RangeError(`position snapshot overflow for ${row.instrumentId}`);
635
+ }
636
+ e.volume = volume;
637
+ e.margin = margin; // real margin occupied (the unit the cap tracks)
231
638
  agg.set(key, e);
232
639
  }
233
- for (const e of agg.values())
234
- this.seedPosition(e.id, e.long ? "long" : "short", e.vol, e.cost);
235
- return this;
640
+ return [...agg.values()];
236
641
  }
237
- /** Current total open-position cost tracked by the C++ risk engine. */
238
- positionCost() {
239
- return this.native.positionCost();
642
+ /** Current total open-position margin tracked by the C++ risk engine. */
643
+ get accountMargin() {
644
+ return this.native.accountMargin();
240
645
  }
241
- /** Clear all tracked position cost. */
646
+ /** Clear held position state only and mark it uncertain. Working-order
647
+ * reservations are preserved; openings remain blocked until a complete
648
+ * seedFromPositions() or syncPositions() succeeds. */
242
649
  resetPositions() {
243
650
  this.native.resetPositions();
244
651
  return this;
@@ -251,58 +658,163 @@ export class Trader extends TraderBase {
251
658
  * instrument); otherwise empty is returned as-is (e.g. a genuinely flat
252
659
  * position book, so a flat account doesn't waste the full retry budget).
253
660
  */
254
- async queryWithRetry(query, requireNonEmpty, attempts = 5) {
661
+ async queryWithRetry(query, requireNonEmpty, contextToken, attempts = 5) {
255
662
  let lastErr;
256
663
  for (let i = 0; i < attempts; i++) {
257
- if (i > 0)
258
- await sleep(1100); // respect the ~1/sec query limit
259
664
  try {
665
+ this.assertRequestContext(contextToken, "query synchronization");
666
+ // Every generated ReqQry* / ReqQuery* goes through queryRequest(), whose
667
+ // shared scheduler enforces the interval. Do not sleep here as well or
668
+ // retries are needlessly spaced twice.
260
669
  const rows = await query();
670
+ this.assertRequestContext(contextToken, "query synchronization");
261
671
  if (!requireNonEmpty || rows.length > 0)
262
672
  return rows;
263
673
  }
264
674
  catch (e) {
265
- lastErr = e; // flow-control rejection - back off and retry
675
+ this.assertRequestContext(contextToken, "query synchronization");
676
+ // Native send codes -2/-3 are the CTP transient flow-control cases.
677
+ // Do not turn a permanent validation/business/disconnect failure into
678
+ // five delayed copies of the same request.
679
+ const code = e?.ctpReturnCode;
680
+ if (code !== -2 && code !== -3)
681
+ throw e;
682
+ lastErr = e;
266
683
  }
267
684
  }
268
685
  if (lastErr)
269
686
  throw lastErr;
270
- return [];
687
+ if (requireNonEmpty)
688
+ throw new Error(`CTP query returned no rows after ${attempts} attempts`);
689
+ /* c8 ignore next -- fixed positive attempts make this an internal invariant */
690
+ throw new Error("query retry invariant violated");
691
+ }
692
+ /** Empty position/order snapshots are ambiguous immediately after login. Require
693
+ * the same empty result twice, one query interval apart, before treating it as
694
+ * authoritative. */
695
+ async authoritativeQuery(query, contextToken) {
696
+ const first = await this.queryWithRetry(query, false, contextToken);
697
+ if (first.length > 0)
698
+ return first;
699
+ // The scheduler spaces this confirmation request from the first one.
700
+ return this.queryWithRetry(query, false, contextToken);
271
701
  }
272
702
  /** Query instruments so the C++ risk engine picks up their multipliers (it
273
703
  * sources them directly from OnRspQryInstrument — no JS feed). No args queries
274
704
  * all instruments (one request); otherwise the given symbols. Retries through
275
705
  * cold-start flow control. Returns the count of contracts with a multiplier. */
276
706
  async syncMultipliers(instrumentIds) {
707
+ const contextToken = this.requestContextToken();
708
+ if (instrumentIds !== undefined) {
709
+ instrumentIds = copyDenseStringArray(instrumentIds, "syncMultipliers instrumentIds");
710
+ if (instrumentIds.length === 0)
711
+ return 0; // explicit empty universe; only omitted means "query all"
712
+ }
277
713
  let count = 0;
278
714
  const apply = (rows) => {
279
- for (const r of rows) {
280
- if (r.volumeMultiple > 0)
715
+ const finalByInstrument = new Map();
716
+ for (const r of rows)
717
+ finalByInstrument.set(r.instrumentId, r);
718
+ for (const r of finalByInstrument.values()) {
719
+ if (r.instrumentId && Number.isFinite(r.volumeMultiple) &&
720
+ r.volumeMultiple > 0 && r.volumeMultiple < 1e300)
281
721
  count++;
282
722
  }
283
723
  };
284
- if (instrumentIds && instrumentIds.length) {
285
- for (let i = 0; i < instrumentIds.length; i++) {
286
- apply(await this.queryWithRetry(() => this.reqQryInstrument({ instrumentId: instrumentIds[i] }), true));
287
- if (i < instrumentIds.length - 1)
288
- await sleep(1100); // query flow control
724
+ if (instrumentIds) {
725
+ for (const instrumentId of new Set(instrumentIds)) {
726
+ apply(await this.queryWithRetry(async () => (await this.reqQryInstrument({ instrumentId })).filter((row) => row.instrumentId === instrumentId), true, contextToken));
289
727
  }
290
728
  }
291
729
  else {
292
- apply(await this.queryWithRetry(() => this.reqQryInstrument({}), true));
730
+ apply(await this.queryWithRetry(() => this.reqQryInstrument({}), true, contextToken));
293
731
  }
294
732
  return count;
295
733
  }
296
- /** Seed open-position MARGIN from CTP (reqQryInvestorPosition) into the cap.
297
- * Uses the logged-in account unless brokerId/investorId are supplied. A
298
- * deliberate resync (resets the held book first), so it stays JS-driven. */
299
- async syncPositions(opts) {
300
- const brokerId = opts?.brokerId ?? this.broker;
301
- const investorId = opts?.investorId ?? this.investor;
302
- const rows = (await this.queryWithRetry(() => this.reqQryInvestorPosition({ brokerId, investorId }), false));
303
- this.resetPositions();
304
- this.seedFromPositions(rows);
305
- return rows.filter((r) => r.position > 0).length;
734
+ /** Query investor margin schedules for a bounded universe. The exchange-base
735
+ * query is issued only when the investor row is relative; the shared query
736
+ * scheduler enforces spacing. Returns the number of usable schedules. */
737
+ async syncMarginRates(instrumentIds, hedgeFlag = "1") {
738
+ const contextToken = this.requestContextToken();
739
+ instrumentIds = copyDenseStringArray(instrumentIds, "syncMarginRates", false);
740
+ if (typeof hedgeFlag !== "string" || !/^[123567]$/.test(hedgeFlag)) {
741
+ throw new TypeError("syncMarginRates hedgeFlag must be 1, 2, 3, 5, 6 or 7");
742
+ }
743
+ const brokerId = this.broker;
744
+ const investorId = this.investor;
745
+ if (!brokerId || !investorId) {
746
+ throw new Error("syncMarginRates requires a successful trader login first");
747
+ }
748
+ let count = 0;
749
+ for (const instrumentId of new Set(instrumentIds)) {
750
+ const investorRows = await this.queryWithRetry(async () => (await this.reqQryInstrumentMarginRate({
751
+ brokerId,
752
+ investorId,
753
+ instrumentId,
754
+ hedgeFlag,
755
+ })).filter((row) => row.instrumentId === instrumentId && row.hedgeFlag === hedgeFlag), true, contextToken);
756
+ // The native map is keyed by instrument+hedge and processes callbacks in
757
+ // order, so its final state is the final row, not "any usable row".
758
+ const investor = investorRows.at(-1);
759
+ const relative = investor.isRelative !== 0;
760
+ const baseRows = relative
761
+ ? await this.queryWithRetry(async () => (await this.reqQryExchangeMarginRate({
762
+ brokerId,
763
+ instrumentId,
764
+ hedgeFlag,
765
+ })).filter((row) => row.instrumentId === instrumentId && row.hedgeFlag === hedgeFlag), true, contextToken)
766
+ : [];
767
+ const base = baseRows.at(-1);
768
+ const component = (value) => Number.isFinite(value) && value >= 0 && value < 1e300;
769
+ const scheduleUsable = (row) => !!row &&
770
+ component(row.longMarginRatioByMoney) &&
771
+ component(row.longMarginRatioByVolume) &&
772
+ component(row.shortMarginRatioByMoney) &&
773
+ component(row.shortMarginRatioByVolume) &&
774
+ (row.longMarginRatioByMoney > 0 || row.longMarginRatioByVolume > 0) &&
775
+ (row.shortMarginRatioByMoney > 0 || row.shortMarginRatioByVolume > 0);
776
+ const investorComponentsValid = component(investor.longMarginRatioByMoney) &&
777
+ component(investor.longMarginRatioByVolume) &&
778
+ component(investor.shortMarginRatioByMoney) &&
779
+ component(investor.shortMarginRatioByVolume);
780
+ if (investorComponentsValid &&
781
+ (relative ? scheduleUsable(base) : scheduleUsable(investor)))
782
+ count++;
783
+ }
784
+ return count;
785
+ }
786
+ /** Replace held position margin from CTP (`reqQryInvestorPosition`). The
787
+ * replacement is revision-checked: if an order/trade callback races the
788
+ * snapshot it retries without clearing live state or reservations. */
789
+ async syncPositions() {
790
+ const contextToken = this.requestContextToken();
791
+ if (arguments.length !== 0)
792
+ throw new TypeError("syncPositions does not accept account overrides");
793
+ const brokerId = this.broker;
794
+ const investorId = this.investor;
795
+ if (typeof brokerId !== "string" || !brokerId || brokerId.includes("\0") ||
796
+ typeof investorId !== "string" || !investorId || investorId.includes("\0"))
797
+ throw new Error("syncPositions requires a successful trader login");
798
+ this.native._markPositionLedgerUncertain();
799
+ for (let attempt = 0; attempt < 5; attempt++) {
800
+ this.assertRequestContext(contextToken, "position synchronization");
801
+ const revision = this.native.riskRevision();
802
+ const rows = await this.authoritativeQuery(async () => {
803
+ const result = (await this.reqQryInvestorPosition({ brokerId, investorId }));
804
+ if (result.some((row) => row.brokerId !== brokerId ||
805
+ row.investorId !== investorId)) {
806
+ throw new Error("position snapshot contains a mismatched account identity");
807
+ }
808
+ return result;
809
+ }, contextToken);
810
+ const seeds = this.aggregatePositions(rows);
811
+ this.assertRequestContext(contextToken, "position synchronization");
812
+ if (this.native.replacePositions(seeds, revision))
813
+ return rows.filter((r) => r.position > 0).length;
814
+ if (attempt < 4)
815
+ await sleep(100); // live order/trade changed during the snapshot; retry
816
+ }
817
+ throw new Error("position snapshot could not stabilize; live state kept unchanged");
306
818
  }
307
819
  /**
308
820
  * Rebuild the in-flight reservation from CTP's currently-working orders
@@ -313,24 +825,92 @@ export class Trader extends TraderBase {
313
825
  * of working open orders re-reserved. Run syncMultipliers() first so the
314
826
  * reserved cost uses the right contract multiplier.
315
827
  */
316
- async syncOrders(opts) {
317
- const brokerId = opts?.brokerId ?? this.broker;
318
- const investorId = opts?.investorId ?? this.investor;
319
- const rows = (await this.queryWithRetry(() => this.reqQryOrder({ brokerId, investorId }), false));
320
- // working = queueing (PartTradedQueueing '1' / NoTradeQueueing '3'); open only
321
- const working = rows
322
- .filter((o) => (o.orderStatus === "1" || o.orderStatus === "3") && o.combOffsetFlag?.[0] === "0")
323
- .map((o) => ({
324
- frontId: o.frontId,
325
- sessionId: o.sessionId,
326
- orderRef: o.orderRef,
327
- instrumentId: o.instrumentId,
328
- isLong: o.direction === "0",
329
- vol: o.volumeTotalOriginal - o.volumeTraded,
330
- price: o.limitPrice,
331
- }));
332
- this.native.rebuildReservations(working);
333
- return working.length;
828
+ async syncOrders() {
829
+ const contextToken = this.requestContextToken();
830
+ if (arguments.length !== 0)
831
+ throw new TypeError("syncOrders does not accept account overrides");
832
+ const brokerId = this.broker;
833
+ const investorId = this.investor;
834
+ if (typeof brokerId !== "string" || !brokerId || brokerId.includes("\0") ||
835
+ typeof investorId !== "string" || !investorId || investorId.includes("\0"))
836
+ throw new Error("syncOrders requires a successful trader login");
837
+ // Order snapshots must precede the final held-position snapshot. Mark both
838
+ // sides uncertain so calling syncPositions()->syncOrders() in the unsafe
839
+ // order cannot reopen trading; a later syncPositions() is required.
840
+ this.native._markPositionLedgerUncertain();
841
+ this.native._markOrderLedgerUncertain();
842
+ for (let attempt = 0; attempt < 5; attempt++) {
843
+ this.assertRequestContext(contextToken, "order synchronization");
844
+ const revision = this.native.riskRevision();
845
+ const rows = await this.authoritativeQuery(async () => {
846
+ const result = (await this.reqQryOrder({ brokerId, investorId }));
847
+ if (result.some((row) => row.brokerId !== brokerId ||
848
+ row.investorId !== investorId)) {
849
+ throw new Error("order snapshot contains a mismatched account identity");
850
+ }
851
+ return result;
852
+ }, contextToken);
853
+ // Every status except the four definitive terminals is still live. This
854
+ // includes conditional Unknown/NotTouched/Touched ('a'/'b'/'c').
855
+ const terminal = new Set(["0", "2", "4", "5"]);
856
+ const active = rows.filter((o) => !terminal.has(o.orderStatus));
857
+ for (const o of active) {
858
+ const vol = o.volumeTotalOriginal - o.volumeTraded;
859
+ if (!Number.isInteger(o.frontId) || !Number.isInteger(o.sessionId) ||
860
+ !o.orderRef || !o.instrumentId ||
861
+ (o.direction !== "0" && o.direction !== "1") ||
862
+ typeof o.combOffsetFlag !== "string" ||
863
+ typeof o.combHedgeFlag !== "string" ||
864
+ !Number.isInteger(o.volumeTotalOriginal) ||
865
+ !Number.isInteger(o.volumeTraded) || o.volumeTraded < 0 ||
866
+ o.volumeTraded > o.volumeTotalOriginal ||
867
+ !Number.isInteger(vol) || vol < 0 ||
868
+ !Number.isFinite(o.limitPrice) || o.limitPrice < 0 ||
869
+ (o.orderSysId && !o.exchangeId) ||
870
+ (/^[0-6]$/.test(o.combOffsetFlag) &&
871
+ !/^[123567]$/.test(o.combHedgeFlag))) {
872
+ throw new TypeError(`invalid working-order snapshot for ${o.orderRef || "<unknown>"}`);
873
+ }
874
+ }
875
+ const working = active.flatMap((o) => {
876
+ const vol = o.volumeTotalOriginal - o.volumeTraded;
877
+ const supportedSingleLeg = /^[0-6]$/.test(o.combOffsetFlag);
878
+ if (supportedSingleLeg && o.combOffsetFlag !== "0")
879
+ return []; // a representable close order adds no opening exposure
880
+ return [{
881
+ frontId: o.frontId,
882
+ sessionId: o.sessionId,
883
+ orderRef: o.orderRef,
884
+ instrumentId: o.instrumentId,
885
+ isLong: o.direction === "0",
886
+ hedgeFlag: o.combHedgeFlag?.[0] || "1",
887
+ vol,
888
+ price: o.limitPrice,
889
+ traded: o.volumeTraded,
890
+ // Must be byte-identical to the native realtime key built in
891
+ // traderspi.gen.cc (OnRtnOrder/OnRtnTrade):
892
+ // day|broker|investor|exchange|instrument|orderSysId. broker/investor
893
+ // are the confirmed session identity (validated == every row above),
894
+ // so a reservation rebuilt on resync correlates with the subsequent
895
+ // realtime order/trade callbacks instead of being stranded uncertain.
896
+ orderSysKey: o.tradingDay && o.exchangeId && o.orderSysId
897
+ ? `${o.tradingDay}|${brokerId}|${investorId}|${o.exchangeId}|${o.instrumentId}|${o.orderSysId}`
898
+ : "",
899
+ supportedSingleLeg,
900
+ }];
901
+ });
902
+ this.assertRequestContext(contextToken, "order synchronization");
903
+ if (this.native.rebuildReservations(working, revision)) {
904
+ const unsupported = working.filter((o) => !o.supportedSingleLeg);
905
+ if (unsupported.length > 0) {
906
+ throw new Error(`unsupported working order ${unsupported[0].orderRef}; opening inserts are fail-closed`);
907
+ }
908
+ return working.length;
909
+ }
910
+ if (attempt < 4)
911
+ await sleep(100);
912
+ }
913
+ throw new Error("order snapshot could not stabilize; live state kept unchanged");
334
914
  }
335
915
  /**
336
916
  * Arm a latency-critical trigger: when `md` sees the condition, the order is
@@ -340,26 +920,40 @@ export class Trader extends TraderBase {
340
920
  */
341
921
  arm(md, spec) {
342
922
  // Validate up front: the order fires from C++ with no JS in the loop, so a
343
- // malformed template would silently misfire (e.g. a missing combOffsetFlag
344
- // defaults to a "close" and skips the position reservation).
345
- if (!spec.instrumentId || !(spec.triggerPrice > 0)) {
923
+ // malformed template cannot reach the callback-thread send path.
924
+ const cleanSpec = copyOwnRecord(spec, "arm spec");
925
+ assertObjectKeys(cleanSpec, "arm spec", ARM_SPEC_KEYS);
926
+ if (!cleanSpec.instrumentId || cleanSpec.instrumentId.includes("\0") ||
927
+ !Number.isFinite(cleanSpec.triggerPrice) || !(cleanSpec.triggerPrice > 0) ||
928
+ cleanSpec.triggerPrice >= 1e300) {
346
929
  throw new Error("arm: spec.instrumentId and a positive triggerPrice are required");
347
930
  }
348
- const order = this.withAutoOrderRef(spec.order);
349
- if (!order.instrumentId || order.direction === undefined || !order.combOffsetFlag ||
350
- !(Number(order.volumeTotalOriginal) > 0)) {
351
- throw new Error("arm: spec.order needs instrumentId, direction, combOffsetFlag and volumeTotalOriginal > 0");
931
+ const validatedOrder = this.validateOrder(cleanSpec.order, "arm.order");
932
+ if (cleanSpec.side !== "buy" && cleanSpec.side !== "sell") {
933
+ throw new Error("arm: spec.side must be buy or sell");
352
934
  }
353
- md.attachArm(this);
935
+ if (validatedOrder.instrumentId !== cleanSpec.instrumentId) {
936
+ throw new Error("arm: spec.instrumentId must match spec.order.instrumentId");
937
+ }
938
+ if ((cleanSpec.side === "buy") !== (validatedOrder.direction === "0")) {
939
+ throw new Error("arm: spec.side must match spec.order.direction");
940
+ }
941
+ const order = this.withAutoOrderRef(validatedOrder);
354
942
  const bytes = this.encode(STRUCT_ID.InputOrder, order);
355
- const id = this.native.arm(spec.instrumentId, spec.side === "buy" ? "0" : "1", spec.triggerPrice, bytes);
943
+ md.attachArm(this);
944
+ // The triggering feed is also the authoritative fresh-price source for
945
+ // deviation/notional/margin checks. Without this wiring an armed order can
946
+ // see the trigger tick yet fail every monetary gate as "no reference".
947
+ this.trackMarketData(md);
948
+ const id = this.native.arm(cleanSpec.instrumentId, cleanSpec.side === "buy" ? "0" : "1", cleanSpec.triggerPrice, bytes);
949
+ this.commitOrderRef(order);
356
950
  return { id, disarm: () => this.native.disarm(id) };
357
951
  }
358
952
  /** Observability for armed triggers (they fire in C++ with no JS in the loop):
359
953
  * how many fired and were sent vs were refused by the risk gate / send.
360
954
  * A blocked armed order is otherwise invisible, so poll this after a trigger
361
955
  * you expected to fire. */
362
- armStats() {
956
+ get armStats() {
363
957
  return { fired: this.native._armFireCount(), blocked: this.native._armBlockedCount() };
364
958
  }
365
959
  /** @internal used by MarketData.attachArm to share the arm registry. */