@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/src/trader.ts CHANGED
@@ -12,46 +12,97 @@ import { STRUCT_ID } from "./generated/structs.gen.js";
12
12
  import type { CallbackOptions } from "./client.js";
13
13
  import type { Order, Trade, InputOrder, RspUserLogin } from "./generated/structs.gen.js";
14
14
  import type { MarketData } from "./market-data.js";
15
+ import {
16
+ assertPlainRecord,
17
+ copyDenseStringArray,
18
+ copyOwnFronts,
19
+ copyOwnRecord,
20
+ ownStringKeys,
21
+ } from "./validation.js";
15
22
 
16
23
  const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
17
24
 
18
25
  /** Pre-trade risk limits, enforced in C++ before each order is sent. */
19
- export interface RiskConfig {
26
+ export interface RiskLimits {
20
27
  /** Max volume per single order. Omit/0 = disabled. */
21
28
  maxOrderVolume?: number;
22
29
  /** Reject if order price deviates from the reference by > this ratio (e.g.
23
30
  * 0.02 = 2%). Feed the reference via trackMarketData(md) (the MD snapshot is
24
- * read in C++); with no reference the check is skipped. */
31
+ * read in C++); missing or stale data rejects opening orders. */
25
32
  maxPriceDeviation?: number;
26
- /** Max notional (price × volume) per order. Omit/0 = disabled. */
33
+ /** Max futures notional (price × volume × multiplier) per opening order.
34
+ * Unknown/unsupported product metadata fails closed. Omit/0 = disabled. */
27
35
  maxNotional?: number;
28
- /** Max order sends per second (token bucket). Omit/0 = disabled. */
36
+ /** Max opening-order sends per second (token bucket). Omit/0 = disabled. */
29
37
  maxOrdersPerSec?: number;
30
38
  /** Token-bucket burst; defaults to maxOrdersPerSec. */
31
39
  orderBurst?: number;
32
- /** @deprecated Use {@link maxMargin}. Back-compat alias; now also margin-based
33
- * (the tracked open cost is real margin once margin rates are known).
34
- * maxMargin takes precedence when both are set. */
35
- maxPositionCost?: number;
40
+ /** Independent rate for risk-reducing close inserts. Disabled by default so
41
+ * emergency exits are not throttled by the opening-order bucket. */
42
+ maxCloseOrdersPerSec?: number;
43
+ /** Close-order token-bucket burst; defaults to maxCloseOrdersPerSec. */
44
+ closeOrderBurst?: number;
45
+ /** Maximum age of the market-data reference used by the deviation guard.
46
+ * Default 3000 ms. Missing or older data fails closed when the guard is on. */
47
+ maxReferenceAgeMs?: number;
36
48
  /** Cap on total open-position MARGIN (Σ open price × volume × multiplier ×
37
- * marginRate) — the real capital occupied, a zero-lag hard cap enforced in
49
+ * absolute by-money/by-volume margin schedule) — a zero-lag hard cap enforced in
38
50
  * C++ on every opening order (regular AND armed). 0/undefined = disabled.
39
51
  * Margin rates are fed automatically from CTP's OnRspQryInstrumentMarginRate
40
52
  * inside C++ (populate them by calling reqQryInstrumentMarginRate); until a
41
- * contract's rate is known it counts at full notional (conservative).
53
+ * multiplier or usable absolute schedule is missing, opening orders fail
54
+ * closed. Both by-money and per-lot components are included; relative
55
+ * investor schedules are combined with their exchange base schedule.
42
56
  * Multipliers / existing positions are picked up via syncMultipliers() /
43
57
  * syncPositions(). */
44
- maxMargin?: number;
58
+ maxAccountMargin?: number;
45
59
  }
46
60
 
47
61
  /** A per-instrument lot cap: a single number caps both sides at that value;
48
62
  * `{ long, short }` caps each side separately (omit a side to leave it open). */
49
- export type LotCap = number | { long?: number; short?: number };
63
+ export type InstrumentPositionLimit =
64
+ number | { long?: number; short?: number };
65
+
66
+ /** One bucket in a complete manually reconciled held-position snapshot. */
67
+ export interface PositionSeed {
68
+ instrumentId: string;
69
+ side: "long" | "short";
70
+ hedgeFlag: "1" | "2" | "3" | "5" | "6" | "7";
71
+ volume: number;
72
+ margin: number;
73
+ }
74
+
75
+ /** A bounded margin-rate sync scoped to the hedge flag used by the orders that
76
+ * will consume those schedules in the native risk ledger. */
77
+ export interface MarginRateSyncOptions {
78
+ instrumentIds: string[];
79
+ hedgeFlag: "1" | "2" | "3" | "5" | "6" | "7";
80
+ }
81
+
82
+ /** The request-correlated identity established by a successful trader login. */
83
+ export interface TraderSessionIdentity {
84
+ readonly frontId: number;
85
+ readonly sessionId: number;
86
+ /** MaxOrderRef reported by this login response. The process-wide automatic
87
+ * allocator may retain a higher high-water mark from earlier sends. */
88
+ readonly maxOrderRef: number;
89
+ }
90
+
91
+ export interface TraderSessionResult {
92
+ identity: TraderSessionIdentity;
93
+ multipliers: number;
94
+ marginRates: number;
95
+ positions: number;
96
+ orders: number;
97
+ }
50
98
 
51
99
  /** Options for the one-call post-connect handshake, {@link Trader.session}. */
52
100
  export interface SessionOptions {
53
101
  brokerId: string;
54
102
  userId: string;
103
+ /** Trading account. Defaults to userId for ordinary retail accounts; set it
104
+ * explicitly when the login operator UserID differs from InvestorID. */
105
+ investorId?: string;
55
106
  password: string;
56
107
  /** Terminal authentication (real accounts require it; SimNow uses
57
108
  * appId "simnow_client_test" / authCode of 16 zeros). Omit both to skip. */
@@ -61,9 +112,17 @@ export interface SessionOptions {
61
112
  * before trading (brokers reject orders otherwise). Default true; set false
62
113
  * for environments that don't need it. */
63
114
  confirmSettlement?: boolean;
64
- /** Which risk inputs to fetch after login (default: all). `multipliers` may
65
- * be `true` (all instruments) or a list of symbols. */
66
- sync?: { multipliers?: boolean | string[]; positions?: boolean; orders?: boolean };
115
+ /** Which risk inputs to fetch after login. Multipliers/positions/orders default
116
+ * on; margin rates require an explicit contract list and hedge flag.
117
+ * `multipliers` may be `true` (all instruments) or a list of symbols. */
118
+ sync?: {
119
+ multipliers?: boolean | string[];
120
+ /** Contracts and hedge flag whose margin schedules should be queried.
121
+ * Omitted by default because CTP requires one rate query per contract. */
122
+ marginRates?: MarginRateSyncOptions;
123
+ positions?: boolean;
124
+ orders?: boolean;
125
+ };
67
126
  }
68
127
 
69
128
  /** A latency-critical armed order: evaluated and fired in C++ on the market-data
@@ -84,75 +143,369 @@ export interface ArmHandle {
84
143
  disarm(): boolean;
85
144
  }
86
145
 
87
- /** Reject a non-finite risk/cap limit. A NaN/Inf would make every `value > limit`
88
- * comparison in C++ false, silently DISABLING the control and leaving the caller
89
- * believing a cap is active — a risk control must never fail open by accident.
90
- * Finite values (including 0/negative, which legitimately mean "disabled") pass. */
146
+ /** Reject a non-finite or negative risk/cap limit. NaN/Inf can void ordinary
147
+ * comparisons, while a mistyped negative must not silently disable a control.
148
+ * Exactly zero is the explicit disabled/clear value. */
91
149
  function assertFiniteLimit(name: string, v: number | undefined): void {
92
- if (v !== undefined && !Number.isFinite(v)) {
93
- throw new TypeError(`${name} must be a finite number (got ${v})`);
150
+ if (v !== undefined && (!Number.isFinite(v) || v < 0)) {
151
+ throw new TypeError(`${name} must be a non-negative finite number (got ${v})`);
152
+ }
153
+ }
154
+
155
+ function assertPositiveInt32OrDisabled(name: string, v: number | undefined): void {
156
+ assertFiniteLimit(name, v);
157
+ if (v !== undefined && v > 0 && (!Number.isInteger(v) || v > 0x7fffffff)) {
158
+ throw new TypeError(`${name} must be an integer in 1..2147483647 (got ${v})`);
94
159
  }
95
160
  }
96
161
 
162
+ function assertLotLimit(name: string, v: number | undefined): void {
163
+ assertFiniteLimit(name, v);
164
+ if (v !== undefined && v > 0 &&
165
+ (!Number.isInteger(v) || v > 0x7fffffff)) {
166
+ throw new TypeError(`${name} must be an integer in 1..2147483647 lots`);
167
+ }
168
+ }
169
+
170
+ function assertInstrumentId(
171
+ name: string,
172
+ instrumentId: unknown
173
+ ): asserts instrumentId is string {
174
+ if (typeof instrumentId !== "string" || !instrumentId || instrumentId.includes("\0"))
175
+ throw new TypeError(`${name}: instrumentId must be non-empty and contain no NUL`);
176
+ }
177
+
178
+ const RISK_LIMIT_KEYS = new Set<keyof RiskLimits>([
179
+ "maxOrderVolume", "maxPriceDeviation", "maxNotional",
180
+ "maxOrdersPerSec", "orderBurst", "maxCloseOrdersPerSec",
181
+ "closeOrderBurst", "maxReferenceAgeMs", "maxAccountMargin",
182
+ ]);
183
+
184
+ function assertObjectKeys(
185
+ value: unknown,
186
+ label: string,
187
+ allowed: ReadonlySet<string>
188
+ ): asserts value is Record<string, unknown> {
189
+ for (const key of ownStringKeys(value, label))
190
+ if (!allowed.has(key)) throw new TypeError(`${label}: unknown field ${key}`);
191
+ }
192
+
193
+ const SESSION_KEYS = new Set([
194
+ "brokerId", "userId", "investorId", "password", "appId", "authCode",
195
+ "confirmSettlement", "sync",
196
+ ]);
197
+ const SESSION_SYNC_KEYS = new Set(["multipliers", "marginRates", "positions", "orders"]);
198
+ const MARGIN_RATE_SYNC_KEYS = new Set(["instrumentIds", "hedgeFlag"]);
199
+ const ARM_SPEC_KEYS = new Set(["instrumentId", "side", "triggerPrice", "order"]);
200
+ const POSITION_LIMIT_KEYS = new Set(["long", "short"]);
201
+ const POSITION_SEED_KEYS = new Set([
202
+ "instrumentId", "side", "hedgeFlag", "volume", "margin",
203
+ ]);
204
+
97
205
  export class Trader extends TraderBase {
98
206
  private broker?: string;
99
207
  private investor?: string;
100
208
  private orderRefSeq = 0;
101
209
 
102
210
  constructor(flowPath: string, fronts: string | string[]) {
103
- super(new native.Trader(flowPath, fronts), native.__layoutData(), TRADER_EVENTS);
104
- // Remember credentials from the login response so sync* needs no args, and
105
- // seed the order-ref counter past the broker's max so auto-assigned refs
106
- // never collide with a prior session's (CTP rejects duplicate refs).
107
- this.on("rsp-user-login", (d: unknown) => {
108
- const r = d as
109
- | { brokerId?: string; userId?: string; maxOrderRef?: string; frontId?: number; sessionId?: number }
110
- | undefined;
111
- if (r) {
112
- this.broker = r.brokerId;
113
- this.investor = r.userId;
114
- const mx = r.maxOrderRef ? parseInt(r.maxOrderRef, 10) : NaN;
115
- if (Number.isFinite(mx) && mx > this.orderRefSeq) this.orderRefSeq = mx;
116
- // (The login session FrontID/SessionID — used as reservation keys so our
117
- // orders never collide with another terminal's on the same account — is
118
- // published into the risk engine directly in C++ from OnRspUserLogin; no
119
- // JS relay needed.)
120
- }
121
- });
211
+ super(
212
+ new native.Trader(flowPath, copyOwnFronts(fronts, "Trader fronts")),
213
+ native.__layoutData(),
214
+ TRADER_EVENTS
215
+ );
216
+ const clearConfirmedIdentity = () => {
217
+ this.broker = undefined;
218
+ this.investor = undefined;
219
+ };
220
+ this.on("front-connected", clearConfirmedIdentity);
221
+ this.on("front-disconnected", clearConfirmedIdentity);
122
222
  this.start();
123
223
  }
124
224
 
125
- getApiVersion(): string {
126
- return this.native.getApiVersion();
225
+ /** A raw login Promise may resolve only with a structurally usable session.
226
+ * Account confirmation itself happens in session(), after request-vs-response
227
+ * identity validation; merely observing a protocol event never grants order
228
+ * authority. */
229
+ protected override onRequestResolved(
230
+ eventName: string | undefined,
231
+ value: unknown,
232
+ _options: CallbackOptions
233
+ ): void {
234
+ if (eventName === "rsp-user-logout") {
235
+ this.broker = undefined;
236
+ this.investor = undefined;
237
+ return;
238
+ }
239
+ if (eventName !== "rsp-user-login") return;
240
+ // A matched login response updates the confirmed identity, but only from a
241
+ // row carrying the COMPLETE, usable identity (FrontID/SessionID > 0 plus
242
+ // BrokerID/UserID) — the same acceptance condition the generated login
243
+ // validator enforces before it resolves. A partial/abnormal success row
244
+ // (e.g. FrontID 0) is rejected downstream, so caching broker/investor from
245
+ // it would strand a stale identity after the login promise rejects, breaking
246
+ // the invariant "broker/investor set ⟺ a confirmed login". We still never
247
+ // throw here (that would reject an otherwise successful login); the
248
+ // authoritative account-match + reservation-key validation lives in
249
+ // session() / _confirmSessionAccount, and direct callers stay fail-closed
250
+ // natively via acceptsOrderAccount.
251
+ const r = value as
252
+ | {
253
+ brokerId?: string;
254
+ userId?: string;
255
+ frontId?: unknown;
256
+ sessionId?: unknown;
257
+ maxOrderRef?: string;
258
+ }
259
+ | undefined;
260
+ if (!r) return;
261
+ if (
262
+ typeof r.brokerId === "string" &&
263
+ r.brokerId &&
264
+ typeof r.userId === "string" &&
265
+ r.userId &&
266
+ Number.isInteger(r.frontId) &&
267
+ Number(r.frontId) > 0 &&
268
+ Number.isInteger(r.sessionId) &&
269
+ Number(r.sessionId) > 0
270
+ ) {
271
+ this.broker = r.brokerId;
272
+ this.investor = r.userId;
273
+ }
274
+ const maxOrderRef =
275
+ typeof r.maxOrderRef === "string" ? r.maxOrderRef.trim() : "";
276
+ if (/^\d{1,12}$/.test(maxOrderRef)) {
277
+ const maxRef = Number(maxOrderRef);
278
+ if (Number.isFinite(maxRef) && maxRef > this.orderRefSeq)
279
+ this.orderRefSeq = maxRef;
280
+ }
281
+ }
282
+
283
+ /** Generated login/logout methods call this only after their request has
284
+ * encoded successfully. Revoke the confirmed JS account at that same atomic
285
+ * transition boundary, so a concurrent sync helper cannot start with the old
286
+ * identity while native risk state is already fail-closed for the new session. */
287
+ protected override beginRequestContextTransition(reason: string): void {
288
+ this.broker = undefined;
289
+ this.investor = undefined;
290
+ super.beginRequestContextTransition(reason);
127
291
  }
128
- getTradingDay(): string {
129
- return this.native.getTradingDay();
292
+
293
+ protected override shouldTimeoutRequest(
294
+ requestId: number,
295
+ sessionTransition: boolean
296
+ ): boolean {
297
+ if (!sessionTransition) return true;
298
+ return this.native._timeoutSessionTransition(requestId) as boolean;
299
+ }
300
+
301
+ get apiVersion(): string {
302
+ return this.native.apiVersion();
303
+ }
304
+ get tradingDay(): string {
305
+ return this.native.tradingDay();
130
306
  }
131
307
 
132
308
  /**
133
309
  * One-call post-connect handshake. Call it from the `front-connected` handler
134
310
  * (and again after a reconnect): authenticate (if appId/authCode given) →
135
- * login → confirm settlement → sync multipliers / positions / orders. Each
311
+ * login → confirm settlement → sync multipliers / margin rates / orders /
312
+ * positions. Each
136
313
  * step just wraps the matching req / sync method, so you can hand-roll your
137
- * own flow instead when you need finer control. Returns the row counts from
138
- * the sync steps. Must run on a connected front (queries need the session up).
314
+ * own flow instead when you need finer control. Returns the request-correlated
315
+ * login identity and row counts from the sync steps. Must run on a connected
316
+ * front (queries need the session up).
139
317
  */
140
- async session(opts: SessionOptions): Promise<{ multipliers: number; positions: number; orders: number }> {
141
- const { brokerId, userId, password, appId, authCode } = opts;
318
+ async session(opts: SessionOptions): Promise<TraderSessionResult> {
319
+ assertObjectKeys(opts, "session options", SESSION_KEYS);
320
+ const cleanOpts = copyOwnRecord(opts, "session options");
321
+ const { brokerId, userId, password, appId, authCode } = cleanOpts;
322
+ const investorId = cleanOpts.investorId ?? userId;
323
+ if (typeof brokerId !== "string" || !brokerId ||
324
+ brokerId.includes("\0") || typeof userId !== "string" || !userId ||
325
+ userId.includes("\0") || typeof password !== "string" || !password ||
326
+ password.includes("\0")) {
327
+ throw new TypeError("session requires brokerId, userId and password");
328
+ }
329
+ if (typeof investorId !== "string" || !investorId ||
330
+ investorId.includes("\0"))
331
+ throw new TypeError("session investorId must be a non-empty string");
332
+ if (cleanOpts.confirmSettlement !== undefined && typeof cleanOpts.confirmSettlement !== "boolean")
333
+ throw new TypeError("session.confirmSettlement must be boolean");
334
+ if ((appId === undefined) !== (authCode === undefined)) {
335
+ throw new TypeError("session appId and authCode must be supplied together");
336
+ }
337
+ if (appId !== undefined && (typeof appId !== "string" || !appId ||
338
+ appId.includes("\0") || typeof authCode !== "string" || !authCode ||
339
+ authCode.includes("\0")))
340
+ throw new TypeError("session appId and authCode must be non-empty strings");
341
+ let cleanSync: NonNullable<SessionOptions["sync"]> = {};
342
+ if (cleanOpts.sync !== undefined) {
343
+ assertObjectKeys(cleanOpts.sync, "session.sync", SESSION_SYNC_KEYS);
344
+ cleanSync = copyOwnRecord(cleanOpts.sync, "session.sync");
345
+ const { multipliers, marginRates, positions, orders } = cleanSync;
346
+ if (multipliers !== undefined && typeof multipliers !== "boolean")
347
+ cleanSync.multipliers = copyDenseStringArray(
348
+ multipliers, "session.sync.multipliers"
349
+ );
350
+ if (marginRates !== undefined) {
351
+ assertObjectKeys(
352
+ marginRates, "session.sync.marginRates", MARGIN_RATE_SYNC_KEYS
353
+ );
354
+ const cleanMarginRates = copyOwnRecord(
355
+ marginRates, "session.sync.marginRates"
356
+ );
357
+ const instrumentIds = copyDenseStringArray(
358
+ cleanMarginRates.instrumentIds,
359
+ "session.sync.marginRates.instrumentIds",
360
+ false
361
+ );
362
+ const hedgeFlag = cleanMarginRates.hedgeFlag;
363
+ if (typeof hedgeFlag !== "string" || !/^[123567]$/.test(hedgeFlag)) {
364
+ throw new TypeError(
365
+ "session.sync.marginRates.hedgeFlag must be 1, 2, 3, 5, 6 or 7"
366
+ );
367
+ }
368
+ cleanSync.marginRates = {
369
+ instrumentIds,
370
+ hedgeFlag: hedgeFlag as MarginRateSyncOptions["hedgeFlag"],
371
+ };
372
+ }
373
+ if (positions !== undefined && typeof positions !== "boolean")
374
+ throw new TypeError("session.sync.positions must be boolean");
375
+ if (orders !== undefined && typeof orders !== "boolean")
376
+ throw new TypeError("session.sync.orders must be boolean");
377
+ }
378
+ // Validate the exact CTP wire capacities before revoking a healthy prior
379
+ // context. A malformed/oversized handshake must be side-effect free.
380
+ if (appId !== undefined && authCode !== undefined)
381
+ this.encode(STRUCT_ID.ReqAuthenticate,
382
+ { brokerId, userId, appId, authCode });
383
+ this.encode(STRUCT_ID.ReqUserLogin, { brokerId, userId, password });
384
+ // Encode unconditionally: InvestorID is part of the native account
385
+ // confirmation even when this environment skips settlement confirmation.
386
+ // Passing these exact CTP bytes also avoids re-encoding GB18030 identities
387
+ // through N-API's UTF-8 string conversion.
388
+ const encodedAccount = this.encode(STRUCT_ID.SettlementInfoConfirm,
389
+ { brokerId, investorId });
390
+ // Revoke native mandates/session authority at the start of the whole
391
+ // handshake, including the authentication phase. A failed auth must not
392
+ // leave an old close arm capable of firing under a superseded account.
393
+ this.native._beginSessionHandshake();
394
+ // No query created under the previous login may cross this handshake. Do
395
+ // this only after all synchronous option validation has succeeded.
396
+ this.invalidateRequestContext("trader session started");
397
+ let contextToken = this.requestContextToken();
398
+ // The cached JS identity is confirmed-session state, not merely the last
399
+ // attempted credentials. Revoke it before auth/login so a failed handshake
400
+ // cannot drive a later snapshot query with stale account fields.
401
+ this.broker = undefined;
402
+ this.investor = undefined;
403
+ // A reconnect may have an event gap. Keep all opening inserts
404
+ // fail-closed throughout the handshake until both authoritative snapshots
405
+ // have independently committed.
406
+ this.native._markPositionLedgerUncertain();
407
+ this.native._markOrderLedgerUncertain();
142
408
  if (appId !== undefined && authCode !== undefined) {
143
409
  await this.reqAuthenticate({ brokerId, userId, appId, authCode });
410
+ this.assertRequestContext(contextToken, "trader session authentication");
411
+ }
412
+ // The generated login method deliberately begins exactly one new request
413
+ // context. A test double may omit that transition; either form is safe. By
414
+ // retaining the pre-call epoch unless the explicit-transition counter also
415
+ // advanced once, an inline front-disconnected callback cannot masquerade as
416
+ // the expected login transition.
417
+ const beforeLoginContext = this.requestContextToken();
418
+ const beforeLoginTransition = this.requestTransitionToken();
419
+ const loginRequest = this.reqUserLogin({ brokerId, userId, password });
420
+ const afterLoginContext = this.requestContextToken();
421
+ const afterLoginTransition = this.requestTransitionToken();
422
+ if (afterLoginTransition === beforeLoginTransition + 1 &&
423
+ afterLoginContext === beforeLoginContext + 1) {
424
+ contextToken = afterLoginContext;
425
+ } else if (afterLoginTransition === beforeLoginTransition) {
426
+ // Test doubles normally do not implement the generated transition. Keep
427
+ // the old epoch so any synchronous front event is detected after await.
428
+ contextToken = beforeLoginContext;
429
+ } else {
430
+ // Settle the request before surfacing the invariant violation so a
431
+ // synchronously rejected test double cannot become an unhandled promise.
432
+ try { await loginRequest; } catch { /* reported as transition failure */ }
433
+ throw new Error("trader session login crossed multiple context transitions");
144
434
  }
145
- await this.reqUserLogin({ brokerId, userId, password });
146
- if (opts.confirmSettlement ?? true) {
435
+ const login = await loginRequest as
436
+ RspUserLogin | undefined;
437
+ this.assertRequestContext(contextToken, "trader session login");
438
+ if (!login || !Number.isInteger(login.frontId) || login.frontId <= 0 ||
439
+ !Number.isInteger(login.sessionId) || login.sessionId <= 0 ||
440
+ login.brokerId !== brokerId ||
441
+ login.userId !== userId) {
442
+ // FrontID/SessionID are part of the reservation identity. Treating an
443
+ // empty success response as ready would reuse an old/zero native session
444
+ // key and create ghost reservations when the first OnRtnOrder arrives.
445
+ this.broker = undefined;
446
+ this.investor = undefined;
447
+ throw new Error("trader login response has missing or mismatched session identity");
448
+ }
449
+ const maxOrderRef = typeof login.maxOrderRef === "string"
450
+ ? login.maxOrderRef.trim() : "";
451
+ if (maxOrderRef !== "" && !/^\d{1,12}$/.test(maxOrderRef)) {
452
+ this.broker = undefined;
453
+ this.investor = undefined;
454
+ throw new Error("trader login response has an invalid MaxOrderRef");
455
+ }
456
+ const maxRef = maxOrderRef === "" ? 0 : Number(maxOrderRef);
457
+ // A successful CTP response may legally end with an empty payload. The
458
+ // request identity is still authoritative for the synchronization calls
459
+ // below; never retain a previous session's broker/investor in that case.
460
+ const confirmed = this.native._confirmSessionAccount(
461
+ login.frontId, login.sessionId, encodedAccount
462
+ ) as boolean;
463
+ if (!confirmed) {
464
+ this.broker = undefined;
465
+ this.investor = undefined;
466
+ throw new Error("native Trader session/account confirmation failed");
467
+ }
468
+ this.broker = brokerId;
469
+ this.investor = investorId;
470
+ if (maxRef > this.orderRefSeq) this.orderRefSeq = maxRef;
471
+ if (cleanOpts.confirmSettlement ?? true) {
147
472
  // idempotent: confirming an already-confirmed statement is fine
148
- await this.reqSettlementInfoConfirm({ brokerId, investorId: userId });
473
+ await this.reqSettlementInfoConfirm({ brokerId, investorId });
474
+ this.assertRequestContext(contextToken, "trader session settlement confirmation");
149
475
  }
150
- const sync = opts.sync ?? {};
476
+ const sync = cleanSync;
151
477
  const mul = sync.multipliers ?? true;
152
- const result = { multipliers: 0, positions: 0, orders: 0 };
153
- if (mul) result.multipliers = await this.syncMultipliers(Array.isArray(mul) ? mul : undefined);
154
- if (sync.positions ?? true) result.positions = await this.syncPositions();
155
- if (sync.orders ?? true) result.orders = await this.syncOrders();
478
+ const result: TraderSessionResult = {
479
+ identity: Object.freeze({
480
+ frontId: login.frontId,
481
+ sessionId: login.sessionId,
482
+ maxOrderRef: maxRef,
483
+ }),
484
+ multipliers: 0,
485
+ marginRates: 0,
486
+ positions: 0,
487
+ orders: 0,
488
+ };
489
+ if (mul) {
490
+ result.multipliers = await this.syncMultipliers(Array.isArray(mul) ? mul : undefined);
491
+ this.assertRequestContext(contextToken, "trader session multiplier sync");
492
+ }
493
+ const marginRateSync = sync.marginRates;
494
+ if (marginRateSync !== undefined) {
495
+ result.marginRates = await this.syncMarginRates(
496
+ marginRateSync.instrumentIds,
497
+ marginRateSync.hedgeFlag
498
+ );
499
+ this.assertRequestContext(contextToken, "trader session margin sync");
500
+ }
501
+ if (sync.orders ?? true) {
502
+ result.orders = await this.syncOrders();
503
+ this.assertRequestContext(contextToken, "trader session order sync");
504
+ }
505
+ if (sync.positions ?? true) {
506
+ result.positions = await this.syncPositions();
507
+ this.assertRequestContext(contextToken, "trader session position sync");
508
+ }
156
509
  return result;
157
510
  }
158
511
 
@@ -161,11 +514,116 @@ export class Trader extends TraderBase {
161
514
  * ref with "不允许重复报单", so an unset ref would otherwise collide. */
162
515
  private withAutoOrderRef(order: Partial<InputOrder>): Partial<InputOrder> {
163
516
  if (order.orderRef === undefined || order.orderRef === "") {
164
- return { ...order, orderRef: String(++this.orderRefSeq) };
517
+ if (this.orderRefSeq >= 999_999_999_999) {
518
+ throw new RangeError("OrderRef space exhausted for this process/session");
519
+ }
520
+ return { ...order, orderRef: String(this.orderRefSeq + 1) };
521
+ }
522
+ if (typeof order.orderRef !== "string" || !/^\d{1,12}$/.test(order.orderRef)) {
523
+ throw new TypeError("orderRef must contain 1..12 decimal digits");
524
+ }
525
+ const explicit = Number(order.orderRef);
526
+ if (explicit <= this.orderRefSeq) {
527
+ throw new RangeError(
528
+ `explicit orderRef must be greater than the current high-water mark ${this.orderRefSeq}`
529
+ );
165
530
  }
166
531
  return order;
167
532
  }
168
533
 
534
+ private commitOrderRef(order: Partial<InputOrder>): void {
535
+ this.orderRefSeq = Number(order.orderRef);
536
+ }
537
+
538
+ private validateOrder(order: Partial<InputOrder>, context: string): Partial<InputOrder> {
539
+ const clean = copyOwnRecord(order, context);
540
+ if (!this.broker || !this.investor) {
541
+ throw new Error(`${context}: a confirmed Trader login is required`);
542
+ }
543
+ if (typeof clean.instrumentId !== "string" || !clean.instrumentId ||
544
+ clean.instrumentId.includes("\0") ||
545
+ (clean.direction !== "0" && clean.direction !== "1")) {
546
+ throw new TypeError(`${context}: instrumentId and direction ("0"/"1") are required`);
547
+ }
548
+ if (typeof clean.combOffsetFlag !== "string" ||
549
+ !/^[0-6]$/.test(clean.combOffsetFlag)) {
550
+ throw new TypeError(`${context}: combOffsetFlag must be one CTP offset digit 0..6; multi-leg orders are unsupported`);
551
+ }
552
+ if (clean.combHedgeFlag !== undefined &&
553
+ (typeof clean.combHedgeFlag !== "string" ||
554
+ !/^[123567]$/.test(clean.combHedgeFlag))) {
555
+ throw new TypeError(`${context}: combHedgeFlag must be one CTP hedge digit (1, 2, 3, 5, 6 or 7)`);
556
+ }
557
+ if (!Number.isInteger(clean.volumeTotalOriginal) ||
558
+ !(Number(clean.volumeTotalOriginal) > 0) ||
559
+ Number(clean.volumeTotalOriginal) > 0x7fffffff) {
560
+ throw new TypeError(`${context}: volumeTotalOriginal must be a positive int32`);
561
+ }
562
+ if (!Number.isFinite(clean.limitPrice) || !(Number(clean.limitPrice) > 0) ||
563
+ Number(clean.limitPrice) >= 1e300) {
564
+ throw new TypeError(`${context}: limitPrice must be a positive finite price`);
565
+ }
566
+ if (clean.brokerId !== undefined && clean.brokerId !== this.broker) {
567
+ throw new TypeError(`${context}: brokerId must match the confirmed login`);
568
+ }
569
+ if (clean.investorId !== undefined && clean.investorId !== this.investor) {
570
+ throw new TypeError(`${context}: investorId must match the confirmed login`);
571
+ }
572
+ const value = <K extends keyof InputOrder>(key: K, fallback: InputOrder[K]) =>
573
+ clean[key] === undefined ? fallback : clean[key];
574
+ const empty = (v: unknown) => v === undefined || v === "";
575
+ // The reservation ledger models ordinary single-instrument limit orders.
576
+ // Admit only the three execution policies whose live remainder is fully
577
+ // represented by CTP order/trade callbacks: GFD, FAK and FOK.
578
+ const timeCondition = value("timeCondition", "3");
579
+ const volumeCondition = value("volumeCondition", "1");
580
+ const supportedExecutionPolicy =
581
+ (timeCondition === "3" && volumeCondition === "1") ||
582
+ (timeCondition === "1" && (volumeCondition === "1" || volumeCondition === "3"));
583
+ if (value("orderPriceType", "2") !== "2" ||
584
+ !supportedExecutionPolicy || !empty(clean.gtdDate) ||
585
+ value("minVolume", 1) !== 1 ||
586
+ value("contingentCondition", "1") !== "1" ||
587
+ value("stopPrice", 0) !== 0 ||
588
+ value("forceCloseReason", "0") !== "0" ||
589
+ value("isAutoSuspend", 0) !== 0 ||
590
+ !empty(clean.businessUnit) || value("requestId", 0) !== 0 ||
591
+ value("userForceClose", 0) !== 0 ||
592
+ value("isSwapOrder", 0) !== 0 || !empty(clean.exchangeId) ||
593
+ !empty(clean.investUnitId) || !empty(clean.accountId) ||
594
+ !empty(clean.currencyId) || !empty(clean.clientId) ||
595
+ value("sessionReqSeq", 0) !== 0) {
596
+ throw new TypeError(
597
+ `${context}: only single-instrument GFD, FAK or FOK limit orders are supported`
598
+ );
599
+ }
600
+ return {
601
+ ...clean,
602
+ orderPriceType: "2",
603
+ combHedgeFlag: clean.combHedgeFlag ?? "1",
604
+ timeCondition,
605
+ gtdDate: "",
606
+ volumeCondition,
607
+ minVolume: 1,
608
+ contingentCondition: "1",
609
+ stopPrice: 0,
610
+ forceCloseReason: "0",
611
+ isAutoSuspend: 0,
612
+ businessUnit: "",
613
+ requestId: 0,
614
+ userForceClose: 0,
615
+ isSwapOrder: 0,
616
+ exchangeId: "",
617
+ investUnitId: "",
618
+ accountId: "",
619
+ currencyId: "",
620
+ clientId: "",
621
+ sessionReqSeq: 0,
622
+ brokerId: this.broker,
623
+ investorId: this.investor,
624
+ };
625
+ }
626
+
169
627
  /**
170
628
  * Insert an order through the C++ pre-trade risk gate. Resolves on submission:
171
629
  * CTP sends no success acknowledgement for an accepted order - only
@@ -175,34 +633,55 @@ export class Trader extends TraderBase {
175
633
  * unique numeric value automatically.
176
634
  */
177
635
  reqOrderInsert(req: Partial<InputOrder> = {}): Promise<void> {
178
- return super.reqOrderInsert(this.withAutoOrderRef(req));
636
+ const order = this.withAutoOrderRef(this.validateOrder(req, "reqOrderInsert"));
637
+ // Preflight field capacities before consuming the OrderRef high-water mark.
638
+ // TraderBase encodes the same object again when it submits.
639
+ this.encode(STRUCT_ID.InputOrder, order as Record<string, unknown>);
640
+ const result = super.reqOrderInsert(order);
641
+ this.commitOrderRef(order);
642
+ return result;
179
643
  }
180
644
 
181
645
  /** Publish pre-trade risk limits to the C++ enforcer (takes effect at once). */
182
- riskSet(config: RiskConfig): this {
646
+ setRiskLimits(config: RiskLimits): this {
647
+ const clean = copyOwnRecord(config, "setRiskLimits");
648
+ for (const key of ownStringKeys(clean, "setRiskLimits")) {
649
+ if (!RISK_LIMIT_KEYS.has(key as keyof RiskLimits))
650
+ throw new TypeError(`setRiskLimits: unknown field ${key}`);
651
+ }
183
652
  // A non-finite limit would silently disable that control (see
184
653
  // assertFiniteLimit) — reject it rather than run unprotected.
185
- assertFiniteLimit("riskSet.maxOrderVolume", config.maxOrderVolume);
186
- assertFiniteLimit("riskSet.maxPriceDeviation", config.maxPriceDeviation);
187
- assertFiniteLimit("riskSet.maxNotional", config.maxNotional);
188
- assertFiniteLimit("riskSet.maxOrdersPerSec", config.maxOrdersPerSec);
189
- assertFiniteLimit("riskSet.orderBurst", config.orderBurst);
190
- assertFiniteLimit("riskSet.maxPositionCost", config.maxPositionCost);
191
- assertFiniteLimit("riskSet.maxMargin", config.maxMargin);
192
- this.native.riskSet(config);
654
+ assertPositiveInt32OrDisabled("setRiskLimits.maxOrderVolume", clean.maxOrderVolume);
655
+ assertFiniteLimit("setRiskLimits.maxPriceDeviation", clean.maxPriceDeviation);
656
+ assertFiniteLimit("setRiskLimits.maxNotional", clean.maxNotional);
657
+ assertFiniteLimit("setRiskLimits.maxOrdersPerSec", clean.maxOrdersPerSec);
658
+ assertFiniteLimit("setRiskLimits.orderBurst", clean.orderBurst);
659
+ assertFiniteLimit("setRiskLimits.maxCloseOrdersPerSec", clean.maxCloseOrdersPerSec);
660
+ assertFiniteLimit("setRiskLimits.closeOrderBurst", clean.closeOrderBurst);
661
+ assertFiniteLimit("setRiskLimits.maxAccountMargin", clean.maxAccountMargin);
662
+ assertFiniteLimit("setRiskLimits.maxReferenceAgeMs", clean.maxReferenceAgeMs);
663
+ if (clean.maxReferenceAgeMs !== undefined && !(clean.maxReferenceAgeMs > 0)) {
664
+ throw new TypeError("setRiskLimits.maxReferenceAgeMs must be > 0");
665
+ }
666
+ this.native.setRiskLimits(clean);
667
+ return this;
668
+ }
669
+ /** Enter REDUCE_ONLY atomically at the final vendor-API send barrier. Armed
670
+ * opens remain registered but cannot send until resume(). */
671
+ reduceOnly(): this {
672
+ this.native.riskReduceOnly();
193
673
  return this;
194
674
  }
195
- /** Kill-switch: C++ immediately blocks every order-opening send that reaches
196
- * the exchange at once — regular, exec, quote, for-quote, option-self-close
197
- * and comb-action inserts. Cancels and other *actions* are deliberately left
198
- * open so you can still pull working orders while halted; parked/staged orders
199
- * (not sent to the exchange immediately) are likewise not gated. Takes effect
200
- * at once; reverse with {@link resume}. */
201
- halt(): this {
202
- this.native.riskHalt();
675
+ /** Enter HALT_ALL atomically: both opening and closing order inserts, advanced
676
+ * mutations and bank/futures transfers are refused, and all existing armed
677
+ * triggers are cleared. New arm() calls are rejected until resume().
678
+ * Cancellation actions remain available so working
679
+ * exchange orders can still be withdrawn. */
680
+ haltAll(): this {
681
+ this.native.riskHaltAll();
203
682
  return this;
204
683
  }
205
- /** Release the kill-switch (see {@link halt}). */
684
+ /** Return to NORMAL mode after reduceOnly() or haltAll(). */
206
685
  resume(): this {
207
686
  this.native.riskResume();
208
687
  return this;
@@ -212,129 +691,240 @@ export class Trader extends TraderBase {
212
691
  * Wires the feed's C++ snapshot cache straight into this Trader's risk engine,
213
692
  * so the deviation check reads current prices in C++ on the order path (no JS
214
693
  * round-trip, and it also covers armed orders that fire with no JS in the loop).
215
- * Without this, no reference is set and the deviation check is skipped. */
694
+ * Without a fresh reference, an enabled deviation check fails closed. */
216
695
  trackMarketData(md: MarketData): this {
217
696
  this.native._attachSnapshot(md._snapshotExternal());
218
697
  return this;
219
698
  }
220
699
 
221
700
  // Contract multipliers (for cost accounting) and margin rates (for the
222
- // maxMargin cap) are NOT fed from JS: the C++ risk engine sources them directly
701
+ // maxAccountMargin cap) are NOT fed from JS: the C++ risk engine sources them directly
223
702
  // from CTP's OnRspQryInstrument / OnRspQryInstrumentMarginRate callbacks (see
224
703
  // scripts/codegen/generate-trader.mjs). So any reqQryInstrument keeps
225
704
  // multipliers current, and querying reqQryInstrumentMarginRate for the
226
- // contracts you trade keeps the margin cap exact — no JS round-trip, and the
227
- // checks also cover armed orders that fire from C++ with no JS in the loop.
705
+ // syncMarginRates() loads investor plus exchange-base schedules. Missing
706
+ // metadata fails closed; IsRelative is combined with the matching base.
228
707
 
229
708
  /**
230
709
  * Cap the open position (in lots) for one instrument, enforced in C++ on
231
710
  * every opening order. Pass a number to cap both sides at once, or
232
711
  * `{ long, short }` to cap each side separately. Within `{ long, short }`,
233
712
  * **omitting a side leaves that side's current cap unchanged** (on a re-call it
234
- * is NOT reset to uncapped), and passing `<= 0` for a side removes its cap.
713
+ * is NOT reset to uncapped), and passing `0` for a side removes its cap.
235
714
  * Long and short are always tracked independently.
236
715
  *
237
- * The check is fill-based (counts confirmed position, like maxPositionCost),
238
- * so rapid bursts of opens can momentarily overshoot before the fills land —
239
- * size the cap with that in mind.
716
+ * Held positions and in-flight working opens are counted atomically.
240
717
  *
241
- * td.setMaxPosition("rb2610", 100); // long<=100 and short<=100
242
- * td.setMaxPosition("ru2610", { long: 100, short: 20 });
718
+ * td.setInstrumentPositionLimit("rb2610", 100);
719
+ * td.setInstrumentPositionLimit("ru2610", { long: 100, short: 20 });
243
720
  */
244
- setMaxPosition(instrumentId: string, max: LotCap): this {
245
- if (typeof max === "number") {
246
- assertFiniteLimit("setMaxPosition", max);
247
- this.native.setMaxPositionVolume(instrumentId, true, max);
248
- this.native.setMaxPositionVolume(instrumentId, false, max);
249
- } else {
250
- assertFiniteLimit("setMaxPosition.long", max.long);
251
- assertFiniteLimit("setMaxPosition.short", max.short);
252
- if (max.long !== undefined) this.native.setMaxPositionVolume(instrumentId, true, max.long);
253
- if (max.short !== undefined) this.native.setMaxPositionVolume(instrumentId, false, max.short);
254
- }
721
+ setInstrumentPositionLimit(
722
+ instrumentId: string,
723
+ limit: InstrumentPositionLimit
724
+ ): this {
725
+ assertInstrumentId("setInstrumentPositionLimit", instrumentId);
726
+ const row = this.normalizePositionLimit(instrumentId, limit);
727
+ this.native._setInstrumentPositionLimits([row]);
255
728
  return this;
256
729
  }
257
730
 
258
731
  /** Cap several instruments at once, e.g.
259
732
  * `{ rb2610: 100, ru2610: { long: 100, short: 20 } }`. */
260
- setMaxPositions(limits: Record<string, LotCap>): this {
261
- for (const id of Object.keys(limits)) this.setMaxPosition(id, limits[id]);
733
+ setInstrumentPositionLimits(
734
+ limits: Record<string, InstrumentPositionLimit>
735
+ ): this {
736
+ const rows = ownStringKeys(limits, "setInstrumentPositionLimits").map((instrumentId) => {
737
+ const limit = limits[instrumentId];
738
+ assertInstrumentId("setInstrumentPositionLimits", instrumentId);
739
+ return this.normalizePositionLimit(instrumentId, limit);
740
+ });
741
+ this.native._setInstrumentPositionLimits(rows);
262
742
  return this;
263
743
  }
264
744
 
745
+ private normalizePositionLimit(
746
+ instrumentId: string,
747
+ limit: InstrumentPositionLimit
748
+ ): { instrumentId: string; long?: number; short?: number } {
749
+ if (typeof limit === "number") {
750
+ assertLotLimit("setInstrumentPositionLimit", limit);
751
+ return copyOwnRecord(
752
+ { instrumentId, long: limit, short: limit },
753
+ "setInstrumentPositionLimit"
754
+ );
755
+ }
756
+ assertPlainRecord(limit, "setInstrumentPositionLimit");
757
+ const clean = copyOwnRecord(limit, "setInstrumentPositionLimit");
758
+ if (clean.long === undefined && clean.short === undefined) {
759
+ throw new TypeError("setInstrumentPositionLimit requires a number or at least one of long/short");
760
+ }
761
+ for (const key of ownStringKeys(clean, "setInstrumentPositionLimit")) {
762
+ if (!POSITION_LIMIT_KEYS.has(key))
763
+ throw new TypeError(`setInstrumentPositionLimit: unknown field ${key}`);
764
+ }
765
+ assertLotLimit("setInstrumentPositionLimit.long", clean.long);
766
+ assertLotLimit("setInstrumentPositionLimit.short", clean.short);
767
+ return copyOwnRecord(
768
+ { instrumentId, long: clean.long, short: clean.short },
769
+ "setInstrumentPositionLimit"
770
+ );
771
+ }
772
+
265
773
  /**
266
- * Cap one instrument's open-position cost (Σ open price × volume × multiplier,
267
- * long and short summed - a gross capital/concentration limit), enforced in
268
- * C++ on every opening order. This is per-instrument and independent of the
269
- * account-wide cap set via riskSet({ maxPositionCost }); both apply. Pass
270
- * `maxCost <= 0` to remove it. Fill-based, same caveat as maxPositionCost.
774
+ * Cap one instrument's scheduled open margin (CTP by-money + by-volume,
775
+ * long and short summed), enforced in C++ on every opening order. This is
776
+ * independent of the account-wide maxAccountMargin cap; both apply. Pass
777
+ * `limit = 0` to remove it. Held and in-flight exposure both count.
271
778
  */
272
- setMaxPositionCost(instrumentId: string, maxCost: number): this {
273
- assertFiniteLimit("setMaxPositionCost", maxCost);
274
- this.native.setMaxInstrumentCost(instrumentId, maxCost);
779
+ setInstrumentMarginLimit(instrumentId: string, limit: number): this {
780
+ assertInstrumentId("setInstrumentMarginLimit", instrumentId);
781
+ assertFiniteLimit("setInstrumentMarginLimit", limit);
782
+ this.native._setInstrumentMarginLimits([{ instrumentId, limit }]);
275
783
  return this;
276
784
  }
277
785
 
278
- /** Cap several instruments' open-position cost at once, e.g.
786
+ /** Cap several instruments' scheduled open margin at once, e.g.
279
787
  * `{ ag2608: 2_000_000, au2608: 5_000_000 }`. */
280
- setMaxPositionCosts(limits: Record<string, number>): this {
281
- for (const id of Object.keys(limits)) {
282
- assertFiniteLimit(`setMaxPositionCosts.${id}`, limits[id]);
283
- this.native.setMaxInstrumentCost(id, limits[id]);
284
- }
788
+ setInstrumentMarginLimits(limits: Record<string, number>): this {
789
+ const rows = ownStringKeys(limits, "setInstrumentMarginLimits").map((instrumentId) => {
790
+ const limit = limits[instrumentId];
791
+ assertInstrumentId("setInstrumentMarginLimits", instrumentId);
792
+ assertFiniteLimit(`setInstrumentMarginLimits.${instrumentId}`, limit);
793
+ return { instrumentId, limit };
794
+ });
795
+ this.native._setInstrumentMarginLimits(rows);
285
796
  return this;
286
797
  }
287
798
 
288
- /** Seed a pre-existing position into the margin/cost cap. `margin` is the real
289
- * capital occupied (CTP InvestorPosition.UseMargin) — the unit the maxMargin
290
- * cap tracks. A deliberate resync op (overwrites the held side), so it stays a
291
- * JS-driven call, unlike the passive multiplier / margin-rate feeds (sourced in
292
- * C++). */
293
- seedPosition(
294
- instrumentId: string,
295
- side: "long" | "short",
296
- volume: number,
297
- margin: number
799
+ /** Atomically replace held positions from a complete manually reconciled
800
+ * snapshot. `margin` is CTP InvestorPosition.UseMargin. An empty array is an
801
+ * authoritative flat book. Partial/incremental seeding is intentionally not
802
+ * exposed because armed orders can run between JS calls. */
803
+ seedPositions(positions: ReadonlyArray<PositionSeed>): this {
804
+ if (!Array.isArray(positions))
805
+ throw new TypeError("seedPositions requires a complete position array");
806
+ const seeds: Array<{
807
+ instrumentId: string; isLong: boolean; hedgeFlag: string;
808
+ volume: number; margin: number;
809
+ }> = [];
810
+ const positionCount = positions.length;
811
+ for (let i = 0; i < positionCount; i++) {
812
+ if (!Object.prototype.hasOwnProperty.call(positions, i))
813
+ throw new TypeError(`seedPositions row ${i} must be an explicit array entry`);
814
+ const row = copyOwnRecord(positions[i], `seedPositions row ${i}`);
815
+ for (const key of ownStringKeys(row, `seedPositions row ${i}`))
816
+ if (!POSITION_SEED_KEYS.has(key))
817
+ throw new TypeError(`seedPositions row ${i}: unknown field ${key}`);
818
+ assertInstrumentId("seedPositions", row.instrumentId);
819
+ if ((row.side !== "long" && row.side !== "short") ||
820
+ typeof row.hedgeFlag !== "string" ||
821
+ !/^[123567]$/.test(row.hedgeFlag) ||
822
+ !Number.isInteger(row.volume) || row.volume < 0 ||
823
+ !Number.isFinite(row.margin) || row.margin < 0) {
824
+ throw new TypeError(
825
+ "seedPositions requires long/short, one hedgeFlag digit, a non-negative integer volume and non-negative finite margin"
826
+ );
827
+ }
828
+ seeds.push({
829
+ instrumentId: row.instrumentId,
830
+ isLong: row.side === "long",
831
+ hedgeFlag: row.hedgeFlag,
832
+ volume: row.volume,
833
+ margin: row.margin,
834
+ });
835
+ }
836
+ return this.replacePositionSeeds(seeds);
837
+ }
838
+
839
+ private replacePositionSeeds(
840
+ seeds: Array<{
841
+ instrumentId: string; isLong: boolean; hedgeFlag: string;
842
+ volume: number; margin: number;
843
+ }>
298
844
  ): this {
299
- this.native.seedPosition(instrumentId, side === "long", volume, margin);
300
- return this;
845
+ for (let attempt = 0; attempt < 5; attempt++) {
846
+ const revision: number = this.native.riskRevision();
847
+ if (this.native.replacePositions(seeds, revision) as boolean)
848
+ return this;
849
+ }
850
+ throw new Error("position snapshot could not stabilize; live state kept unchanged");
301
851
  }
302
852
 
303
- /** Seed open-position MARGIN from reqQryInvestorPosition() rows for GROSS-mode
304
- * accounts (posiDirection '2' = long, '3' = short; any other value, incl. net
305
- * '1', is bucketed as short). Uses each row's real UseMargin. Cost/margin caps
306
- * sum both sides so the bucket doesn't matter for them, but a per-side *volume*
307
- * cap on a net-mode instrument would track the wrong side — for net-mode
308
- * accounts, seed those via seedPosition() with the side you intend. */
853
+ /** Atomically replace held position margin from complete gross-mode query rows
854
+ * (`posiDirection` '2' long, '3' short). Net/unknown direction is rejected
855
+ * because guessing a side corrupts per-side volume caps. */
309
856
  seedFromPositions(
310
857
  positions: ReadonlyArray<{
311
858
  instrumentId: string;
312
859
  posiDirection: string;
860
+ hedgeFlag: string;
313
861
  position: number;
314
862
  useMargin: number;
315
863
  }>
316
864
  ): this {
317
- // Aggregate by instrument+side (CTP may return several rows per instrument).
318
- const agg = new Map<string, { id: string; long: boolean; vol: number; cost: number }>();
319
- for (const p of positions) {
320
- if (!(p.position > 0)) continue;
321
- const long = p.posiDirection === "2";
322
- const key = `${p.instrumentId}|${long}`;
323
- const e = agg.get(key) ?? { id: p.instrumentId, long, vol: 0, cost: 0 };
324
- e.vol += p.position;
325
- e.cost += p.useMargin; // real margin occupied (the unit the cap tracks)
865
+ const seeds = this.aggregatePositions(positions);
866
+ // Native callbacks can mutate the ledger concurrently even though this JS
867
+ // method is synchronous. Retry a revision-checked replacement rather than
868
+ // expose a clear-then-seed gap or overwrite a callback that raced us.
869
+ return this.replacePositionSeeds(seeds);
870
+ }
871
+
872
+ private aggregatePositions(
873
+ positions: ReadonlyArray<{
874
+ instrumentId: string;
875
+ posiDirection: string;
876
+ hedgeFlag: string;
877
+ position: number;
878
+ useMargin: number;
879
+ }>
880
+ ): Array<{ instrumentId: string; isLong: boolean; hedgeFlag: string; volume: number; margin: number }> {
881
+ // Aggregate by instrument+side+hedge flag (CTP may return several rows per
882
+ // bucket, e.g. today/history). Different hedge flags can have different
883
+ // margin schedules and must never be averaged together on close.
884
+ if (!Array.isArray(positions))
885
+ throw new TypeError("position snapshot must be an array");
886
+ const agg = new Map<string, { instrumentId: string; isLong: boolean; hedgeFlag: string; volume: number; margin: number }>();
887
+ const positionCount = positions.length;
888
+ for (let i = 0; i < positionCount; i++) {
889
+ if (!Object.prototype.hasOwnProperty.call(positions, i))
890
+ throw new TypeError(`position snapshot row ${i} must be an explicit array entry`);
891
+ const p = positions[i];
892
+ const plain = p !== null && typeof p === "object" && !Array.isArray(p) &&
893
+ (Object.getPrototypeOf(p) === Object.prototype || Object.getPrototypeOf(p) === null);
894
+ const row = plain ? copyOwnRecord(p, "position snapshot row") : undefined;
895
+ if (!row || typeof row.instrumentId !== "string" || !row.instrumentId ||
896
+ row.instrumentId.includes("\0") ||
897
+ !Number.isInteger(row.position) || row.position < 0 ||
898
+ !Number.isFinite(row.useMargin) || row.useMargin < 0 ||
899
+ (row.posiDirection !== "2" && row.posiDirection !== "3") ||
900
+ typeof row.hedgeFlag !== "string" ||
901
+ !/^[123567]$/.test(row.hedgeFlag)) {
902
+ throw new TypeError(`invalid position snapshot for ${row?.instrumentId || "<unknown>"}`);
903
+ }
904
+ if (!(row.position > 0)) continue;
905
+ const isLong = row.posiDirection === "2";
906
+ const key = `${row.instrumentId}|${isLong}|${row.hedgeFlag}`;
907
+ const e = agg.get(key) ?? { instrumentId: row.instrumentId, isLong, hedgeFlag: row.hedgeFlag, volume: 0, margin: 0 };
908
+ const volume = e.volume + row.position;
909
+ const margin = e.margin + row.useMargin;
910
+ if (!Number.isSafeInteger(volume) || !Number.isFinite(margin)) {
911
+ throw new RangeError(`position snapshot overflow for ${row.instrumentId}`);
912
+ }
913
+ e.volume = volume;
914
+ e.margin = margin; // real margin occupied (the unit the cap tracks)
326
915
  agg.set(key, e);
327
916
  }
328
- for (const e of agg.values()) this.seedPosition(e.id, e.long ? "long" : "short", e.vol, e.cost);
329
- return this;
917
+ return [...agg.values()];
330
918
  }
331
919
 
332
- /** Current total open-position cost tracked by the C++ risk engine. */
333
- positionCost(): number {
334
- return this.native.positionCost();
920
+ /** Current total open-position margin tracked by the C++ risk engine. */
921
+ get accountMargin(): number {
922
+ return this.native.accountMargin();
335
923
  }
336
924
 
337
- /** Clear all tracked position cost. */
925
+ /** Clear held position state only and mark it uncertain. Working-order
926
+ * reservations are preserved; openings remain blocked until a complete
927
+ * seedFromPositions() or syncPositions() succeeds. */
338
928
  resetPositions(): this {
339
929
  this.native.resetPositions();
340
930
  return this;
@@ -351,20 +941,47 @@ export class Trader extends TraderBase {
351
941
  private async queryWithRetry<T>(
352
942
  query: () => Promise<T[]>,
353
943
  requireNonEmpty: boolean,
944
+ contextToken: number,
354
945
  attempts = 5
355
946
  ): Promise<T[]> {
356
947
  let lastErr: unknown;
357
948
  for (let i = 0; i < attempts; i++) {
358
- if (i > 0) await sleep(1100); // respect the ~1/sec query limit
359
949
  try {
950
+ this.assertRequestContext(contextToken, "query synchronization");
951
+ // Every generated ReqQry* / ReqQuery* goes through queryRequest(), whose
952
+ // shared scheduler enforces the interval. Do not sleep here as well or
953
+ // retries are needlessly spaced twice.
360
954
  const rows = await query();
955
+ this.assertRequestContext(contextToken, "query synchronization");
361
956
  if (!requireNonEmpty || rows.length > 0) return rows;
362
957
  } catch (e) {
363
- lastErr = e; // flow-control rejection - back off and retry
958
+ this.assertRequestContext(contextToken, "query synchronization");
959
+ // Native send codes -2/-3 are the CTP transient flow-control cases.
960
+ // Do not turn a permanent validation/business/disconnect failure into
961
+ // five delayed copies of the same request.
962
+ const code = (e as { ctpReturnCode?: unknown })?.ctpReturnCode;
963
+ if (code !== -2 && code !== -3) throw e;
964
+ lastErr = e;
364
965
  }
365
966
  }
366
967
  if (lastErr) throw lastErr;
367
- return [];
968
+ if (requireNonEmpty)
969
+ throw new Error(`CTP query returned no rows after ${attempts} attempts`);
970
+ /* c8 ignore next -- fixed positive attempts make this an internal invariant */
971
+ throw new Error("query retry invariant violated");
972
+ }
973
+
974
+ /** Empty position/order snapshots are ambiguous immediately after login. Require
975
+ * the same empty result twice, one query interval apart, before treating it as
976
+ * authoritative. */
977
+ private async authoritativeQuery<T>(
978
+ query: () => Promise<T[]>,
979
+ contextToken: number
980
+ ): Promise<T[]> {
981
+ const first = await this.queryWithRetry(query, false, contextToken);
982
+ if (first.length > 0) return first;
983
+ // The scheduler spaces this confirmation request from the first one.
984
+ return this.queryWithRetry(query, false, contextToken);
368
985
  }
369
986
 
370
987
  /** Query instruments so the C++ risk engine picks up their multipliers (it
@@ -372,41 +989,167 @@ export class Trader extends TraderBase {
372
989
  * all instruments (one request); otherwise the given symbols. Retries through
373
990
  * cold-start flow control. Returns the count of contracts with a multiplier. */
374
991
  async syncMultipliers(instrumentIds?: string[]): Promise<number> {
992
+ const contextToken = this.requestContextToken();
993
+ if (instrumentIds !== undefined) {
994
+ instrumentIds = copyDenseStringArray(
995
+ instrumentIds, "syncMultipliers instrumentIds"
996
+ );
997
+ if (instrumentIds.length === 0)
998
+ return 0; // explicit empty universe; only omitted means "query all"
999
+ }
375
1000
  let count = 0;
376
1001
  const apply = (rows: unknown[]) => {
377
- for (const r of rows as Array<{ instrumentId: string; volumeMultiple: number }>) {
378
- if (r.volumeMultiple > 0) count++;
1002
+ const finalByInstrument = new Map<string, { instrumentId: string; volumeMultiple: number }>();
1003
+ for (const r of rows as Array<{ instrumentId: string; volumeMultiple: number }>)
1004
+ finalByInstrument.set(r.instrumentId, r);
1005
+ for (const r of finalByInstrument.values()) {
1006
+ if (r.instrumentId && Number.isFinite(r.volumeMultiple) &&
1007
+ r.volumeMultiple > 0 && r.volumeMultiple < 1e300) count++;
379
1008
  }
380
1009
  };
381
- if (instrumentIds && instrumentIds.length) {
382
- for (let i = 0; i < instrumentIds.length; i++) {
383
- apply(await this.queryWithRetry(() => this.reqQryInstrument({ instrumentId: instrumentIds[i] }), true));
384
- if (i < instrumentIds.length - 1) await sleep(1100); // query flow control
1010
+ if (instrumentIds) {
1011
+ for (const instrumentId of new Set(instrumentIds)) {
1012
+ apply(await this.queryWithRetry(async () =>
1013
+ ((await this.reqQryInstrument({ instrumentId })) as Array<{
1014
+ instrumentId: string; volumeMultiple: number;
1015
+ }>).filter((row) => row.instrumentId === instrumentId), true, contextToken));
385
1016
  }
386
1017
  } else {
387
- apply(await this.queryWithRetry(() => this.reqQryInstrument({}), true));
1018
+ apply(await this.queryWithRetry(
1019
+ () => this.reqQryInstrument({}), true, contextToken
1020
+ ));
388
1021
  }
389
1022
  return count;
390
1023
  }
391
1024
 
392
- /** Seed open-position MARGIN from CTP (reqQryInvestorPosition) into the cap.
393
- * Uses the logged-in account unless brokerId/investorId are supplied. A
394
- * deliberate resync (resets the held book first), so it stays JS-driven. */
395
- async syncPositions(opts?: { brokerId?: string; investorId?: string }): Promise<number> {
396
- const brokerId = opts?.brokerId ?? this.broker;
397
- const investorId = opts?.investorId ?? this.investor;
398
- const rows = (await this.queryWithRetry(
399
- () => this.reqQryInvestorPosition({ brokerId, investorId }),
400
- false
401
- )) as Array<{
1025
+ /** Query investor margin schedules for a bounded universe. The exchange-base
1026
+ * query is issued only when the investor row is relative; the shared query
1027
+ * scheduler enforces spacing. Returns the number of usable schedules. */
1028
+ async syncMarginRates(
1029
+ instrumentIds: string[],
1030
+ hedgeFlag: "1" | "2" | "3" | "5" | "6" | "7" = "1"
1031
+ ): Promise<number> {
1032
+ const contextToken = this.requestContextToken();
1033
+ instrumentIds = copyDenseStringArray(instrumentIds, "syncMarginRates", false);
1034
+ if (typeof hedgeFlag !== "string" || !/^[123567]$/.test(hedgeFlag)) {
1035
+ throw new TypeError("syncMarginRates hedgeFlag must be 1, 2, 3, 5, 6 or 7");
1036
+ }
1037
+ const brokerId = this.broker;
1038
+ const investorId = this.investor;
1039
+ if (!brokerId || !investorId) {
1040
+ throw new Error("syncMarginRates requires a successful trader login first");
1041
+ }
1042
+ let count = 0;
1043
+ for (const instrumentId of new Set(instrumentIds)) {
1044
+ type InvestorMarginRow = {
1045
+ instrumentId: string;
1046
+ hedgeFlag: string;
1047
+ isRelative: number;
1048
+ longMarginRatioByMoney: number;
1049
+ longMarginRatioByVolume: number;
1050
+ shortMarginRatioByMoney: number;
1051
+ shortMarginRatioByVolume: number;
1052
+ };
1053
+ const investorRows = await this.queryWithRetry(async () =>
1054
+ ((await this.reqQryInstrumentMarginRate({
1055
+ brokerId,
1056
+ investorId,
1057
+ instrumentId,
1058
+ hedgeFlag,
1059
+ })) as InvestorMarginRow[]).filter(
1060
+ (row) => row.instrumentId === instrumentId && row.hedgeFlag === hedgeFlag
1061
+ ), true, contextToken);
1062
+ // The native map is keyed by instrument+hedge and processes callbacks in
1063
+ // order, so its final state is the final row, not "any usable row".
1064
+ const investor = investorRows.at(-1)!;
1065
+ const relative = investor.isRelative !== 0;
1066
+ type ExchangeMarginRow = {
1067
+ instrumentId: string;
1068
+ hedgeFlag: string;
1069
+ longMarginRatioByMoney: number;
1070
+ longMarginRatioByVolume: number;
1071
+ shortMarginRatioByMoney: number;
1072
+ shortMarginRatioByVolume: number;
1073
+ };
1074
+ const baseRows = relative
1075
+ ? await this.queryWithRetry(async () =>
1076
+ ((await this.reqQryExchangeMarginRate({
1077
+ brokerId,
1078
+ instrumentId,
1079
+ hedgeFlag,
1080
+ })) as ExchangeMarginRow[]).filter(
1081
+ (row) => row.instrumentId === instrumentId && row.hedgeFlag === hedgeFlag
1082
+ ), true, contextToken)
1083
+ : [];
1084
+ const base = baseRows.at(-1);
1085
+ const component = (value: number) =>
1086
+ Number.isFinite(value) && value >= 0 && value < 1e300;
1087
+ const scheduleUsable = (row: {
1088
+ longMarginRatioByMoney: number;
1089
+ longMarginRatioByVolume: number;
1090
+ shortMarginRatioByMoney: number;
1091
+ shortMarginRatioByVolume: number;
1092
+ } | undefined) => !!row &&
1093
+ component(row.longMarginRatioByMoney) &&
1094
+ component(row.longMarginRatioByVolume) &&
1095
+ component(row.shortMarginRatioByMoney) &&
1096
+ component(row.shortMarginRatioByVolume) &&
1097
+ (row.longMarginRatioByMoney > 0 || row.longMarginRatioByVolume > 0) &&
1098
+ (row.shortMarginRatioByMoney > 0 || row.shortMarginRatioByVolume > 0);
1099
+ const investorComponentsValid =
1100
+ component(investor.longMarginRatioByMoney) &&
1101
+ component(investor.longMarginRatioByVolume) &&
1102
+ component(investor.shortMarginRatioByMoney) &&
1103
+ component(investor.shortMarginRatioByVolume);
1104
+ if (investorComponentsValid &&
1105
+ (relative ? scheduleUsable(base) : scheduleUsable(investor)))
1106
+ count++;
1107
+ }
1108
+ return count;
1109
+ }
1110
+
1111
+ /** Replace held position margin from CTP (`reqQryInvestorPosition`). The
1112
+ * replacement is revision-checked: if an order/trade callback races the
1113
+ * snapshot it retries without clearing live state or reservations. */
1114
+ async syncPositions(): Promise<number> {
1115
+ const contextToken = this.requestContextToken();
1116
+ if (arguments.length !== 0)
1117
+ throw new TypeError("syncPositions does not accept account overrides");
1118
+ const brokerId = this.broker;
1119
+ const investorId = this.investor;
1120
+ if (typeof brokerId !== "string" || !brokerId || brokerId.includes("\0") ||
1121
+ typeof investorId !== "string" || !investorId || investorId.includes("\0"))
1122
+ throw new Error("syncPositions requires a successful trader login");
1123
+ this.native._markPositionLedgerUncertain();
1124
+ type PositionRow = {
1125
+ brokerId: string;
1126
+ investorId: string;
402
1127
  instrumentId: string;
403
1128
  posiDirection: string;
404
1129
  position: number;
405
1130
  useMargin: number;
406
- }>;
407
- this.resetPositions();
408
- this.seedFromPositions(rows);
409
- return rows.filter((r) => r.position > 0).length;
1131
+ hedgeFlag: string;
1132
+ };
1133
+ for (let attempt = 0; attempt < 5; attempt++) {
1134
+ this.assertRequestContext(contextToken, "position synchronization");
1135
+ const revision: number = this.native.riskRevision();
1136
+ const rows = await this.authoritativeQuery(async () => {
1137
+ const result = (await this.reqQryInvestorPosition({ brokerId, investorId })) as
1138
+ PositionRow[];
1139
+ if (result.some((row) => row.brokerId !== brokerId ||
1140
+ row.investorId !== investorId)) {
1141
+ throw new Error("position snapshot contains a mismatched account identity");
1142
+ }
1143
+ return result;
1144
+ }, contextToken);
1145
+ const seeds = this.aggregatePositions(rows);
1146
+ this.assertRequestContext(contextToken, "position synchronization");
1147
+ if (this.native.replacePositions(seeds, revision) as boolean)
1148
+ return rows.filter((r) => r.position > 0).length;
1149
+ if (attempt < 4)
1150
+ await sleep(100); // live order/trade changed during the snapshot; retry
1151
+ }
1152
+ throw new Error("position snapshot could not stabilize; live state kept unchanged");
410
1153
  }
411
1154
 
412
1155
  /**
@@ -418,38 +1161,112 @@ export class Trader extends TraderBase {
418
1161
  * of working open orders re-reserved. Run syncMultipliers() first so the
419
1162
  * reserved cost uses the right contract multiplier.
420
1163
  */
421
- async syncOrders(opts?: { brokerId?: string; investorId?: string }): Promise<number> {
422
- const brokerId = opts?.brokerId ?? this.broker;
423
- const investorId = opts?.investorId ?? this.investor;
424
- const rows = (await this.queryWithRetry(
425
- () => this.reqQryOrder({ brokerId, investorId }),
426
- false
427
- )) as Array<{
1164
+ async syncOrders(): Promise<number> {
1165
+ const contextToken = this.requestContextToken();
1166
+ if (arguments.length !== 0)
1167
+ throw new TypeError("syncOrders does not accept account overrides");
1168
+ const brokerId = this.broker;
1169
+ const investorId = this.investor;
1170
+ if (typeof brokerId !== "string" || !brokerId || brokerId.includes("\0") ||
1171
+ typeof investorId !== "string" || !investorId || investorId.includes("\0"))
1172
+ throw new Error("syncOrders requires a successful trader login");
1173
+ // Order snapshots must precede the final held-position snapshot. Mark both
1174
+ // sides uncertain so calling syncPositions()->syncOrders() in the unsafe
1175
+ // order cannot reopen trading; a later syncPositions() is required.
1176
+ this.native._markPositionLedgerUncertain();
1177
+ this.native._markOrderLedgerUncertain();
1178
+ type OrderRow = {
1179
+ brokerId: string;
1180
+ investorId: string;
428
1181
  frontId: number;
429
1182
  sessionId: number;
430
1183
  orderRef: string;
1184
+ tradingDay: string;
1185
+ exchangeId: string;
1186
+ orderSysId: string;
431
1187
  instrumentId: string;
432
1188
  combOffsetFlag: string;
433
1189
  direction: string;
1190
+ combHedgeFlag: string;
434
1191
  orderStatus: string;
435
1192
  limitPrice: number;
436
1193
  volumeTotalOriginal: number;
437
1194
  volumeTraded: number;
438
- }>;
439
- // working = queueing (PartTradedQueueing '1' / NoTradeQueueing '3'); open only
440
- const working = rows
441
- .filter((o) => (o.orderStatus === "1" || o.orderStatus === "3") && o.combOffsetFlag?.[0] === "0")
442
- .map((o) => ({
443
- frontId: o.frontId,
444
- sessionId: o.sessionId,
445
- orderRef: o.orderRef,
446
- instrumentId: o.instrumentId,
447
- isLong: o.direction === "0",
448
- vol: o.volumeTotalOriginal - o.volumeTraded,
449
- price: o.limitPrice,
450
- }));
451
- this.native.rebuildReservations(working);
452
- return working.length;
1195
+ };
1196
+ for (let attempt = 0; attempt < 5; attempt++) {
1197
+ this.assertRequestContext(contextToken, "order synchronization");
1198
+ const revision: number = this.native.riskRevision();
1199
+ const rows = await this.authoritativeQuery(async () => {
1200
+ const result = (await this.reqQryOrder({ brokerId, investorId })) as
1201
+ OrderRow[];
1202
+ if (result.some((row) => row.brokerId !== brokerId ||
1203
+ row.investorId !== investorId)) {
1204
+ throw new Error("order snapshot contains a mismatched account identity");
1205
+ }
1206
+ return result;
1207
+ }, contextToken);
1208
+ // Every status except the four definitive terminals is still live. This
1209
+ // includes conditional Unknown/NotTouched/Touched ('a'/'b'/'c').
1210
+ const terminal = new Set(["0", "2", "4", "5"]);
1211
+ const active = rows.filter((o) => !terminal.has(o.orderStatus));
1212
+ for (const o of active) {
1213
+ const vol = o.volumeTotalOriginal - o.volumeTraded;
1214
+ if (!Number.isInteger(o.frontId) || !Number.isInteger(o.sessionId) ||
1215
+ !o.orderRef || !o.instrumentId ||
1216
+ (o.direction !== "0" && o.direction !== "1") ||
1217
+ typeof o.combOffsetFlag !== "string" ||
1218
+ typeof o.combHedgeFlag !== "string" ||
1219
+ !Number.isInteger(o.volumeTotalOriginal) ||
1220
+ !Number.isInteger(o.volumeTraded) || o.volumeTraded < 0 ||
1221
+ o.volumeTraded > o.volumeTotalOriginal ||
1222
+ !Number.isInteger(vol) || vol < 0 ||
1223
+ !Number.isFinite(o.limitPrice) || o.limitPrice < 0 ||
1224
+ (o.orderSysId && !o.exchangeId) ||
1225
+ (/^[0-6]$/.test(o.combOffsetFlag) &&
1226
+ !/^[123567]$/.test(o.combHedgeFlag))) {
1227
+ throw new TypeError(`invalid working-order snapshot for ${o.orderRef || "<unknown>"}`);
1228
+ }
1229
+ }
1230
+ const working = active.flatMap((o) => {
1231
+ const vol = o.volumeTotalOriginal - o.volumeTraded;
1232
+ const supportedSingleLeg = /^[0-6]$/.test(o.combOffsetFlag);
1233
+ if (supportedSingleLeg && o.combOffsetFlag !== "0")
1234
+ return []; // a representable close order adds no opening exposure
1235
+ return [{
1236
+ frontId: o.frontId,
1237
+ sessionId: o.sessionId,
1238
+ orderRef: o.orderRef,
1239
+ instrumentId: o.instrumentId,
1240
+ isLong: o.direction === "0",
1241
+ hedgeFlag: o.combHedgeFlag?.[0] || "1",
1242
+ vol,
1243
+ price: o.limitPrice,
1244
+ traded: o.volumeTraded,
1245
+ // Must be byte-identical to the native realtime key built in
1246
+ // traderspi.gen.cc (OnRtnOrder/OnRtnTrade):
1247
+ // day|broker|investor|exchange|instrument|orderSysId. broker/investor
1248
+ // are the confirmed session identity (validated == every row above),
1249
+ // so a reservation rebuilt on resync correlates with the subsequent
1250
+ // realtime order/trade callbacks instead of being stranded uncertain.
1251
+ orderSysKey: o.tradingDay && o.exchangeId && o.orderSysId
1252
+ ? `${o.tradingDay}|${brokerId}|${investorId}|${o.exchangeId}|${o.instrumentId}|${o.orderSysId}`
1253
+ : "",
1254
+ supportedSingleLeg,
1255
+ }];
1256
+ });
1257
+ this.assertRequestContext(contextToken, "order synchronization");
1258
+ if (this.native.rebuildReservations(working, revision) as boolean) {
1259
+ const unsupported = working.filter((o) => !o.supportedSingleLeg);
1260
+ if (unsupported.length > 0) {
1261
+ throw new Error(
1262
+ `unsupported working order ${unsupported[0].orderRef}; opening inserts are fail-closed`
1263
+ );
1264
+ }
1265
+ return working.length;
1266
+ }
1267
+ if (attempt < 4) await sleep(100);
1268
+ }
1269
+ throw new Error("order snapshot could not stabilize; live state kept unchanged");
453
1270
  }
454
1271
 
455
1272
  /**
@@ -460,24 +1277,38 @@ export class Trader extends TraderBase {
460
1277
  */
461
1278
  arm(md: MarketData, spec: ArmSpec): ArmHandle {
462
1279
  // Validate up front: the order fires from C++ with no JS in the loop, so a
463
- // malformed template would silently misfire (e.g. a missing combOffsetFlag
464
- // defaults to a "close" and skips the position reservation).
465
- if (!spec.instrumentId || !(spec.triggerPrice > 0)) {
1280
+ // malformed template cannot reach the callback-thread send path.
1281
+ const cleanSpec = copyOwnRecord(spec, "arm spec");
1282
+ assertObjectKeys(cleanSpec, "arm spec", ARM_SPEC_KEYS);
1283
+ if (!cleanSpec.instrumentId || cleanSpec.instrumentId.includes("\0") ||
1284
+ !Number.isFinite(cleanSpec.triggerPrice) || !(cleanSpec.triggerPrice > 0) ||
1285
+ cleanSpec.triggerPrice >= 1e300) {
466
1286
  throw new Error("arm: spec.instrumentId and a positive triggerPrice are required");
467
1287
  }
468
- const order = this.withAutoOrderRef(spec.order);
469
- if (!order.instrumentId || order.direction === undefined || !order.combOffsetFlag ||
470
- !(Number(order.volumeTotalOriginal) > 0)) {
471
- throw new Error("arm: spec.order needs instrumentId, direction, combOffsetFlag and volumeTotalOriginal > 0");
1288
+ const validatedOrder = this.validateOrder(cleanSpec.order, "arm.order");
1289
+ if (cleanSpec.side !== "buy" && cleanSpec.side !== "sell") {
1290
+ throw new Error("arm: spec.side must be buy or sell");
472
1291
  }
473
- md.attachArm(this);
1292
+ if (validatedOrder.instrumentId !== cleanSpec.instrumentId) {
1293
+ throw new Error("arm: spec.instrumentId must match spec.order.instrumentId");
1294
+ }
1295
+ if ((cleanSpec.side === "buy") !== (validatedOrder.direction === "0")) {
1296
+ throw new Error("arm: spec.side must match spec.order.direction");
1297
+ }
1298
+ const order = this.withAutoOrderRef(validatedOrder);
474
1299
  const bytes = this.encode(STRUCT_ID.InputOrder, order as Record<string, unknown>);
1300
+ md.attachArm(this);
1301
+ // The triggering feed is also the authoritative fresh-price source for
1302
+ // deviation/notional/margin checks. Without this wiring an armed order can
1303
+ // see the trigger tick yet fail every monetary gate as "no reference".
1304
+ this.trackMarketData(md);
475
1305
  const id: number = this.native.arm(
476
- spec.instrumentId,
477
- spec.side === "buy" ? "0" : "1",
478
- spec.triggerPrice,
1306
+ cleanSpec.instrumentId,
1307
+ cleanSpec.side === "buy" ? "0" : "1",
1308
+ cleanSpec.triggerPrice,
479
1309
  bytes
480
1310
  );
1311
+ this.commitOrderRef(order);
481
1312
  return { id, disarm: () => this.native.disarm(id) as boolean };
482
1313
  }
483
1314
 
@@ -485,7 +1316,7 @@ export class Trader extends TraderBase {
485
1316
  * how many fired and were sent vs were refused by the risk gate / send.
486
1317
  * A blocked armed order is otherwise invisible, so poll this after a trigger
487
1318
  * you expected to fire. */
488
- armStats(): { fired: number; blocked: number } {
1319
+ get armStats(): { fired: number; blocked: number } {
489
1320
  return { fired: this.native._armFireCount(), blocked: this.native._armBlockedCount() };
490
1321
  }
491
1322
 
@@ -508,8 +1339,8 @@ export class Trader extends TraderBase {
508
1339
  on(event: "rtn-trade", cb: (data: Trade, opts: CallbackOptions) => void): this;
509
1340
  on(event: "front-connected", cb: (data: undefined, opts: CallbackOptions) => void): this;
510
1341
  on(event: "front-disconnected", cb: (reason: number, opts: CallbackOptions) => void): this;
511
- on(event: "rsp-user-login", cb: (data: RspUserLogin, opts: CallbackOptions) => void): this;
512
- on(event: "err-rtn-order-insert", cb: (data: InputOrder, opts: CallbackOptions) => void): this;
1342
+ on(event: "rsp-user-login", cb: (data: RspUserLogin | undefined, opts: CallbackOptions) => void): this;
1343
+ on(event: "err-rtn-order-insert", cb: (data: InputOrder | undefined, opts: CallbackOptions) => void): this;
513
1344
  on(event: string, cb: (...args: never[]) => void): this;
514
1345
  on(event: string, cb: (...args: never[]) => void): this {
515
1346
  return super.on(event, cb as (...args: unknown[]) => void);