@hitrading/ctp-node 1.2.0 → 3.0.0

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