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