@hitrading/ctp-node 2.0.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/CHANGELOG.md +67 -0
  2. package/README.md +47 -32
  3. package/README.zh-CN.md +37 -27
  4. package/RELEASING.md +78 -0
  5. package/dist/client.d.ts +36 -15
  6. package/dist/client.d.ts.map +1 -1
  7. package/dist/client.js +234 -62
  8. package/dist/client.js.map +1 -1
  9. package/dist/codec.d.ts.map +1 -1
  10. package/dist/codec.js +84 -19
  11. package/dist/codec.js.map +1 -1
  12. package/dist/generated/structs.gen.d.ts +5461 -5461
  13. package/dist/generated/structs.gen.d.ts.map +1 -1
  14. package/dist/generated/trader.gen.d.ts.map +1 -1
  15. package/dist/generated/trader.gen.js +788 -94
  16. package/dist/generated/trader.gen.js.map +1 -1
  17. package/dist/index.cjs +1875 -415
  18. package/dist/index.d.cts +1 -1
  19. package/dist/index.d.ts +1 -1
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/index.js.map +1 -1
  22. package/dist/market-data.d.ts +41 -24
  23. package/dist/market-data.d.ts.map +1 -1
  24. package/dist/market-data.js +148 -29
  25. package/dist/market-data.js.map +1 -1
  26. package/dist/native-binding.d.ts.map +1 -1
  27. package/dist/native-binding.js +4 -0
  28. package/dist/native-binding.js.map +1 -1
  29. package/dist/trader.d.ts +111 -71
  30. package/dist/trader.d.ts.map +1 -1
  31. package/dist/trader.js +774 -180
  32. package/dist/trader.js.map +1 -1
  33. package/dist/validation.d.ts +27 -0
  34. package/dist/validation.d.ts.map +1 -0
  35. package/dist/validation.js +85 -0
  36. package/dist/validation.js.map +1 -0
  37. package/docs/API.md +1437 -0
  38. package/docs/API.zh-CN.md +1278 -0
  39. package/docs/MIGRATION.md +54 -0
  40. package/docs/assets/validation.svg +27 -0
  41. package/docs/integration.md +60 -0
  42. package/docs/native-hooks.md +281 -0
  43. package/docs/native-hooks.zh-CN.md +205 -0
  44. package/docs/troubleshooting.md +257 -0
  45. package/docs/troubleshooting.zh-CN.md +220 -0
  46. package/package.json +12 -4
  47. package/prebuilds/linux-x64/@hitrading+ctp-node.node +0 -0
  48. package/prebuilds/win32-x64/@hitrading+ctp-node.node +0 -0
  49. package/scripts/bench-decode.mjs +37 -0
  50. package/scripts/bench-fullmarket-offline.mjs +207 -0
  51. package/scripts/stress-fullmarket.mjs +255 -0
  52. package/src/addon.cc +2 -2
  53. package/src/client.ts +255 -65
  54. package/src/codec.ts +86 -19
  55. package/src/generated/structs.gen.ts +5461 -5461
  56. package/src/generated/trader.gen.ts +309 -94
  57. package/src/generated/traderreq.gen.cc +194 -18
  58. package/src/generated/traderreq.gen.h +4 -0
  59. package/src/generated/traderspi.gen.cc +129 -15
  60. package/src/generated/traderspi.gen.h +4 -2
  61. package/src/index.ts +8 -1
  62. package/src/market-data.ts +199 -46
  63. package/src/native/arm.cc +114 -30
  64. package/src/native/arm.h +16 -4
  65. package/src/native/channel.cc +209 -81
  66. package/src/native/channel.h +65 -24
  67. package/src/native/ctp_field.h +23 -0
  68. package/src/native/mdapi.cc +582 -69
  69. package/src/native/mdspi.cc +219 -16
  70. package/src/native/mdspi.h +59 -10
  71. package/src/native/order_capability.h +75 -0
  72. package/src/native/risk.cc +2030 -213
  73. package/src/native/risk.h +431 -78
  74. package/src/native/shared_handle.h +37 -0
  75. package/src/native/snapshot.h +75 -16
  76. package/src/native/traderapi.cc +753 -124
  77. package/src/native-binding.ts +4 -0
  78. package/src/trader.ts +971 -204
  79. package/src/validation.ts +96 -0
package/dist/index.cjs CHANGED
@@ -1425,20 +1425,117 @@ var STRUCT_ID = {
1425
1425
  "FrontInfo": 518
1426
1426
  };
1427
1427
 
1428
+ // dist/validation.js
1429
+ function assertPlainRecord(value, label) {
1430
+ if (value === null || typeof value !== "object" || Array.isArray(value))
1431
+ throw new TypeError(`${label} must be a plain object`);
1432
+ const prototype = Object.getPrototypeOf(value);
1433
+ if (prototype !== Object.prototype && prototype !== null)
1434
+ throw new TypeError(`${label} must be a plain object`);
1435
+ }
1436
+ function ownStringKeys(value, label) {
1437
+ assertPlainRecord(value, label);
1438
+ const keys = Reflect.ownKeys(value);
1439
+ if (keys.some((key) => typeof key !== "string"))
1440
+ throw new TypeError(`${label} contains an unsupported symbol field`);
1441
+ return keys;
1442
+ }
1443
+ function copyOwnRecord(value, label) {
1444
+ const source = value;
1445
+ const copy = /* @__PURE__ */ Object.create(null);
1446
+ for (const key of ownStringKeys(value, label)) {
1447
+ const field = source[key];
1448
+ if (field !== void 0)
1449
+ copy[key] = field;
1450
+ }
1451
+ return copy;
1452
+ }
1453
+ function copyDenseStringArray(value, label, allowEmpty = true) {
1454
+ if (!Array.isArray(value))
1455
+ throw new TypeError(`${label} must be ${allowEmpty ? "an" : "a non-empty"} instrument-id array`);
1456
+ const length = value.length;
1457
+ if (!allowEmpty && length === 0)
1458
+ throw new TypeError(`${label} must be a non-empty instrument-id array`);
1459
+ const copy = new Array(length);
1460
+ for (let i = 0; i < length; i++) {
1461
+ if (!Object.prototype.hasOwnProperty.call(value, i)) {
1462
+ throw new TypeError(`${label} must contain dense, non-empty strings without NUL`);
1463
+ }
1464
+ const item = value[i];
1465
+ if (typeof item !== "string" || item.length === 0 || item.includes("\0"))
1466
+ throw new TypeError(`${label} must contain dense, non-empty strings without NUL`);
1467
+ copy[i] = item;
1468
+ }
1469
+ return copy;
1470
+ }
1471
+ function copyOwnFronts(value, label) {
1472
+ if (typeof value === "string") {
1473
+ if (value.includes("\0"))
1474
+ throw new TypeError(`${label} must not contain NUL`);
1475
+ return value;
1476
+ }
1477
+ if (!Array.isArray(value))
1478
+ throw new TypeError(`${label} must be a string or string array`);
1479
+ const length = value.length;
1480
+ const copy = new Array(length);
1481
+ for (let i = 0; i < length; i++) {
1482
+ if (!Object.prototype.hasOwnProperty.call(value, i)) {
1483
+ throw new TypeError(`${label} must contain only explicit strings without NUL`);
1484
+ }
1485
+ const item = value[i];
1486
+ if (typeof item !== "string" || item.includes("\0"))
1487
+ throw new TypeError(`${label} must contain only explicit strings without NUL`);
1488
+ copy[i] = item;
1489
+ }
1490
+ return copy;
1491
+ }
1492
+
1428
1493
  // dist/codec.js
1429
1494
  function parseLayouts(data) {
1495
+ if (!(data instanceof Int32Array))
1496
+ throw new TypeError("codec: layout data must be an Int32Array");
1497
+ if (data.length === 0)
1498
+ throw new Error("codec: empty layout data");
1430
1499
  const out = [];
1431
1500
  let p = 0;
1432
- const n = data[p++];
1501
+ const next = (label) => {
1502
+ if (p >= data.length)
1503
+ throw new Error(`codec: truncated layout data at ${label}`);
1504
+ return data[p++];
1505
+ };
1506
+ const n = next("struct count");
1507
+ let descriptorCount = 0;
1508
+ while (STRUCTS[descriptorCount]?.id === descriptorCount)
1509
+ descriptorCount++;
1510
+ if (n !== descriptorCount)
1511
+ throw new Error(`codec: struct-count mismatch (layout ${n} vs descriptor ${descriptorCount})`);
1433
1512
  for (let i = 0; i < n; i++) {
1434
- const size = data[p++];
1435
- const fc = data[p++];
1513
+ const size = next(`struct ${i} size`);
1514
+ const fc = next(`struct ${i} field count`);
1515
+ if (size <= 0 || fc < 0)
1516
+ throw new Error(`codec: invalid layout header for struct ${i}`);
1517
+ const desc = STRUCTS[i];
1518
+ if (!desc || fc !== desc.fields.length)
1519
+ throw new Error(`codec: field-count mismatch for struct ${i}`);
1436
1520
  const fields = new Array(fc);
1521
+ const occupied = [];
1437
1522
  for (let j = 0; j < fc; j++) {
1438
- fields[j] = { offset: data[p++], size: data[p++], kind: data[p++] };
1523
+ const offset = next(`struct ${i} field ${j} offset`);
1524
+ const fieldSize = next(`struct ${i} field ${j} size`);
1525
+ const kind = next(`struct ${i} field ${j} kind`);
1526
+ const fixedSize = kind === 1 ? 4 : kind === 2 ? 2 : kind === 3 ? 8 : void 0;
1527
+ if (offset < 0 || fieldSize <= 0 || offset + fieldSize > size || kind < 0 || kind > 3 || fixedSize !== void 0 && fieldSize !== fixedSize || kind !== desc.fields[j].kind) {
1528
+ throw new Error(`codec: invalid layout for struct ${i} field ${j}`);
1529
+ }
1530
+ if (occupied.some(([start, end]) => offset < end && start < offset + fieldSize))
1531
+ throw new Error(`codec: overlapping layout for struct ${i} field ${j}`);
1532
+ occupied.push([offset, offset + fieldSize]);
1533
+ fields[j] = { offset, size: fieldSize, kind };
1439
1534
  }
1440
1535
  out.push({ size, fields });
1441
1536
  }
1537
+ if (p !== data.length)
1538
+ throw new Error(`codec: trailing layout data (${data.length - p} int32 values)`);
1442
1539
  return out;
1443
1540
  }
1444
1541
  var gbk = new TextDecoder("gb18030");
@@ -1496,29 +1593,57 @@ function buildDecoder(structId, layout) {
1496
1593
  }
1497
1594
  var utf8Encoder = new TextEncoder();
1498
1595
  function encodeStruct(layout, fields, obj, encodeStr = (s) => utf8Encoder.encode(s)) {
1596
+ const objectKeys = ownStringKeys(obj, "codec: request");
1597
+ if (fields.length !== layout.fields.length) {
1598
+ throw new Error(`codec: encode field-count mismatch (${layout.fields.length} layout vs ${fields.length} descriptor)`);
1599
+ }
1600
+ const knownFields = new Set(fields.map((field) => field.js));
1601
+ for (const key of objectKeys) {
1602
+ if (!knownFields.has(key))
1603
+ throw new TypeError(`codec: unknown request field ${key}`);
1604
+ }
1499
1605
  const out = new Uint8Array(layout.size);
1500
1606
  const view = new DataView(out.buffer);
1501
1607
  for (let i = 0; i < layout.fields.length; i++) {
1502
1608
  const f = layout.fields[i];
1503
- const v = obj[fields[i].js];
1504
- if (v === void 0 || v === null)
1609
+ const fieldName = fields[i].js;
1610
+ const v = Object.prototype.hasOwnProperty.call(obj, fieldName) ? obj[fieldName] : void 0;
1611
+ if (v === void 0)
1505
1612
  continue;
1506
1613
  switch (f.kind) {
1507
1614
  case 0: {
1508
- const bytes = encodeStr(String(v));
1615
+ if (typeof v !== "string")
1616
+ throw new TypeError(`${fields[i].js} must be a string`);
1617
+ if (v.includes("\0"))
1618
+ throw new RangeError(`${fields[i].js} must not contain NUL`);
1619
+ const bytes = encodeStr(v);
1509
1620
  const cap = f.size === 1 ? 1 : f.size - 1;
1510
- out.set(bytes.subarray(0, Math.min(bytes.length, cap)), f.offset);
1621
+ if (bytes.length > cap) {
1622
+ throw new RangeError(`${fields[i].js} exceeds CTP field capacity (${bytes.length} encoded bytes > ${cap})`);
1623
+ }
1624
+ out.set(bytes, f.offset);
1511
1625
  break;
1512
1626
  }
1513
- case 1:
1514
- view.setInt32(f.offset, Number(v) | 0, true);
1627
+ case 1: {
1628
+ if (typeof v !== "number" || !Number.isInteger(v) || v < -2147483648 || v > 2147483647)
1629
+ throw new RangeError(`${fields[i].js} must be an int32`);
1630
+ view.setInt32(f.offset, v, true);
1515
1631
  break;
1516
- case 2:
1517
- view.setInt16(f.offset, Number(v) | 0, true);
1632
+ }
1633
+ case 2: {
1634
+ if (typeof v !== "number" || !Number.isInteger(v) || v < -32768 || v > 32767)
1635
+ throw new RangeError(`${fields[i].js} must be an int16`);
1636
+ view.setInt16(f.offset, v, true);
1518
1637
  break;
1519
- case 3:
1520
- view.setFloat64(f.offset, Number(v), true);
1638
+ }
1639
+ case 3: {
1640
+ if (typeof v !== "number" || !Number.isFinite(v))
1641
+ throw new RangeError(`${fields[i].js} must be finite`);
1642
+ view.setFloat64(f.offset, v, true);
1521
1643
  break;
1644
+ }
1645
+ default:
1646
+ throw new Error(`codec: unknown encode kind ${f.kind} for ${fields[i].js}`);
1522
1647
  }
1523
1648
  }
1524
1649
  return out;
@@ -1542,6 +1667,7 @@ var S_ERRID = 12;
1542
1667
  var S_SID = 16;
1543
1668
  var S_PLEN = 20;
1544
1669
  var S_ERRMSG = 24;
1670
+ var MAX_SCHEDULED_QUERIES = 256;
1545
1671
  function recreateWarnThreshold(raw) {
1546
1672
  const DEFAULT = 3;
1547
1673
  if (raw === void 0)
@@ -1556,7 +1682,7 @@ function noteClientReleased() {
1556
1682
  startedThenClosed += 1;
1557
1683
  if (RECREATE_WARN_THRESHOLD > 0 && !recreateWarned && startedThenClosed > RECREATE_WARN_THRESHOLD) {
1558
1684
  recreateWarned = true;
1559
- console.warn(`[ctp-node] ${startedThenClosed} CTP clients have been created and closed in this process. The CTP vendor DLLs deadlock inside Release() after a few Init()/Release() cycles, so a MarketData/Trader must be created ONCE and reused: handle reconnects in place (re-run your front-connected handshake), never destroy and recreate the client. Set CTP_RECREATE_WARN=0 to silence, or to another number to retune. See docs/native-hooks.md (Process lifecycle).`);
1685
+ console.warn(`[ctp-node] ${startedThenClosed} CTP clients have been created and closed in this process. Repeated CTP Init()/Release() cycles have been observed to hang inside the vendor DLL's Release(), so a MarketData/Trader must be created ONCE and reused: handle reconnects in place (re-run your front-connected handshake), never destroy and recreate the client. Set CTP_RECREATE_WARN=0 to silence, or to another number to retune. See docs/native-hooks.md (Process lifecycle).`);
1560
1686
  }
1561
1687
  }
1562
1688
  var CtpClient = class extends import_node_events.EventEmitter {
@@ -1574,12 +1700,11 @@ var CtpClient = class extends import_node_events.EventEmitter {
1574
1700
  headerSize = 0;
1575
1701
  readPos = 0;
1576
1702
  // Overflow policy of the underlying channel (from _info()). Drop-oldest (market
1577
- // data) takes the buffered drainOldest() path; drop-newest (trader) the inline
1703
+ // data) takes the buffered drainOldest() path; lossless Trader uses inline
1578
1704
  // drain(). See src/native/channel.h.
1579
1705
  dropOldest = false;
1580
1706
  // Reused scratch holding a whole decoded batch for the drop-oldest path, so we
1581
- // can validate against producer overruns *after* decoding and before delivering
1582
- // (a torn record never reaches a handler). Indices 0..count-1 are live per drain.
1707
+ // can validate logical displacement after decoding and before delivery.
1583
1708
  batch = [];
1584
1709
  // Set the instant close() begins. close() frees the native ring synchronously,
1585
1710
  // so if an event handler invoked from drain() calls close() mid-batch, the
@@ -1592,12 +1717,18 @@ var CtpClient = class extends import_node_events.EventEmitter {
1592
1717
  started = false;
1593
1718
  pending = /* @__PURE__ */ new Map();
1594
1719
  reqSeq = 0;
1595
- /** Event ids whose requestId-0 response should resolve the oldest pending
1596
- * request. Needed only for SimNow market-data login/logout, which don't echo
1597
- * the id; scoping to those events means an unrelated id-0 response
1598
- * (sub/unsub/error) can't hijack them. The trader echoes ids and leaves this
1599
- * empty. */
1600
- zeroIdFallbackEvents = /* @__PURE__ */ new Set();
1720
+ queryQueue = Promise.resolve();
1721
+ // The first query must be eligible immediately even during the first 1.1 s
1722
+ // of process uptime. Later sends replace this with a monotonic timestamp.
1723
+ lastQuerySentAt = Number.NEGATIVE_INFINITY;
1724
+ requestContextEpoch = 0;
1725
+ // Counts only deliberate login/logout transitions. Front callbacks advance
1726
+ // the context epoch but not this counter, which lets a compound handshake
1727
+ // distinguish the one expected login invalidation from an inline disconnect.
1728
+ explicitRequestTransitionSeq = 0;
1729
+ queryInvalidationReason = "client context changed";
1730
+ scheduledQueries = 0;
1731
+ cancelQueryDelay;
1601
1732
  /** A request that goes idle this long (no response and, for multi-row queries,
1602
1733
  * no further rows) rejects, so awaiters don't hang forever. The timer resets
1603
1734
  * on each row, so a large streaming query isn't cut off by total duration. */
@@ -1609,7 +1740,8 @@ var CtpClient = class extends import_node_events.EventEmitter {
1609
1740
  this.layouts = parseLayouts(layoutBlob);
1610
1741
  this.decoders = new Array(this.layouts.length);
1611
1742
  this.events = events;
1612
- this.on("front-disconnected", () => this.rejectAllPending("front disconnected"));
1743
+ this.on("front-connected", () => this.invalidateRequestContext("front connected"));
1744
+ this.on("front-disconnected", () => this.invalidateRequestContext("front disconnected"));
1613
1745
  }
1614
1746
  /** Reject and clear every in-flight request (on disconnect / close). */
1615
1747
  rejectAllPending(reason) {
@@ -1623,6 +1755,48 @@ var CtpClient = class extends import_node_events.EventEmitter {
1623
1755
  p.reject(err);
1624
1756
  }
1625
1757
  }
1758
+ /** Invalidate all work tied to the previous connection/login context.
1759
+ * Subclasses call this immediately before a login/logout transition. */
1760
+ invalidateRequestContext(reason) {
1761
+ this.requestContextEpoch++;
1762
+ this.queryInvalidationReason = reason;
1763
+ this.cancelQueryDelay?.();
1764
+ this.cancelQueryDelay = void 0;
1765
+ this.rejectAllPending(reason);
1766
+ }
1767
+ /** Begin a deliberate login/logout transition. Generated/manual public
1768
+ * transition methods use this rather than calling invalidate directly. */
1769
+ beginRequestContextTransition(reason) {
1770
+ this.explicitRequestTransitionSeq++;
1771
+ this.invalidateRequestContext(reason);
1772
+ }
1773
+ /** Capture/validate the connection-login epoch across a compound async
1774
+ * operation. QueryRequest protects one queued send; session/sync helpers use
1775
+ * this token so a later step cannot silently continue on a new front. */
1776
+ requestContextToken() {
1777
+ return this.requestContextEpoch;
1778
+ }
1779
+ requestTransitionToken() {
1780
+ return this.explicitRequestTransitionSeq;
1781
+ }
1782
+ assertRequestContext(token, operation) {
1783
+ if (this.closing)
1784
+ throw new Error("client closed");
1785
+ if (token !== this.requestContextEpoch) {
1786
+ throw new Error(`${operation} invalidated: ${this.queryInvalidationReason}`);
1787
+ }
1788
+ }
1789
+ /** Internal state hook for a response that actually matched and successfully
1790
+ * settled the current request. Streaming stale callbacks are still emitted to
1791
+ * users, but cannot mutate a subclass's confirmed session identity. */
1792
+ onRequestResolved(_eventName, _value, _options) {
1793
+ }
1794
+ /** Linearize a session-request idle timeout with native login/logout state.
1795
+ * Subclasses return false when the final native callback already won the
1796
+ * race and its non-droppable response is merely waiting to be drained. */
1797
+ shouldTimeoutRequest(_requestId, _sessionTransition) {
1798
+ return true;
1799
+ }
1626
1800
  /** Wire up the ring view + doorbell. Subclasses call this in their ctor. */
1627
1801
  start() {
1628
1802
  const info = this.native._info();
@@ -1644,7 +1818,7 @@ var CtpClient = class extends import_node_events.EventEmitter {
1644
1818
  if (this.closing)
1645
1819
  return;
1646
1820
  this.closing = true;
1647
- this.rejectAllPending("client closed");
1821
+ this.invalidateRequestContext("client closed");
1648
1822
  if (this.started)
1649
1823
  noteClientReleased();
1650
1824
  this.native.close();
@@ -1701,13 +1875,9 @@ var CtpClient = class extends import_node_events.EventEmitter {
1701
1875
  }
1702
1876
  }
1703
1877
  /**
1704
- * Drop-oldest drain (market data). The producer overwrites the oldest unread
1705
- * record when full and never blocks, so the consumer can be lapped mid-read.
1706
- * We therefore decode the whole claimed batch first, then ask the channel how
1707
- * many of the oldest records it overwrote *during* that decode (validate()),
1708
- * discard those (they hold torn bytes), and only then deliver the rest — so a
1709
- * torn record never reaches a handler. The records we do deliver are always the
1710
- * freshest available, and conservation holds (received + dropped == produced).
1878
+ * Keep-newest drain (market data). Overflow is copied into native staging,
1879
+ * never over a slot JS may be reading. A claimed batch is owned until release,
1880
+ * so newer records can displace only the unclaimed logical window.
1711
1881
  */
1712
1882
  drainOldest() {
1713
1883
  let count = this.native._claim();
@@ -1722,15 +1892,12 @@ var CtpClient = class extends import_node_events.EventEmitter {
1722
1892
  const slot = (this.readPos + i) % numSlots * slotSize;
1723
1893
  batch[i] = this.decodeSlot(slot);
1724
1894
  }
1725
- const torn = this.native._validate(count);
1726
- for (let i = 0; i < torn; i++)
1727
- batch[i] = void 0;
1728
1895
  if (this.closing) {
1729
- for (let i = torn; i < count; i++)
1896
+ for (let i = 0; i < count; i++)
1730
1897
  batch[i] = void 0;
1731
1898
  return;
1732
1899
  }
1733
- for (let i = torn; i < count; i++) {
1900
+ for (let i = 0; i < count; i++) {
1734
1901
  const rec = batch[i];
1735
1902
  batch[i] = void 0;
1736
1903
  if (this.closing)
@@ -1763,7 +1930,7 @@ var CtpClient = class extends import_node_events.EventEmitter {
1763
1930
  const plen = v.getInt32(slot + S_PLEN, true);
1764
1931
  const base = slot + this.headerSize;
1765
1932
  let value;
1766
- if (plen > 0 && sid >= 0 && sid < this.layouts.length)
1933
+ if (plen > 0 && sid >= 0 && sid < this.layouts.length && plen >= this.layouts[sid].size)
1767
1934
  value = this.decoderFor(sid)(v, u8, base);
1768
1935
  else if (sid === -2 && plen >= 4)
1769
1936
  value = v.getInt32(base, true);
@@ -1786,8 +1953,13 @@ var CtpClient = class extends import_node_events.EventEmitter {
1786
1953
  const rspInfo = options.rspInfo;
1787
1954
  if (options.isLast !== void 0 && this.pending.size > 0) {
1788
1955
  let key = reqId !== 0 && this.pending.has(reqId) ? reqId : void 0;
1789
- if (key === void 0 && reqId === 0 && this.zeroIdFallbackEvents.has(evt)) {
1790
- key = this.pending.keys().next().value;
1956
+ if (key === void 0 && reqId === 0) {
1957
+ for (const [candidate, pending] of this.pending) {
1958
+ if (pending.zeroIdEvent === evt) {
1959
+ key = candidate;
1960
+ break;
1961
+ }
1962
+ }
1791
1963
  }
1792
1964
  const p = key !== void 0 ? this.pending.get(key) : void 0;
1793
1965
  if (p && key !== void 0) {
@@ -1803,7 +1975,13 @@ var CtpClient = class extends import_node_events.EventEmitter {
1803
1975
  if (p.timer)
1804
1976
  clearTimeout(p.timer);
1805
1977
  this.pending.delete(key);
1806
- p.resolve(p.single ? p.rows[0] : p.rows);
1978
+ const result = p.single ? p.rows[0] : p.rows;
1979
+ try {
1980
+ this.onRequestResolved(this.events.get(evt), result, options);
1981
+ p.resolve(result);
1982
+ } catch (error) {
1983
+ p.reject(error);
1984
+ }
1807
1985
  } else {
1808
1986
  this.armRequestTimer(key, p);
1809
1987
  }
@@ -1818,7 +1996,7 @@ var CtpClient = class extends import_node_events.EventEmitter {
1818
1996
  return encodeStruct(this.layouts[structId], STRUCTS[structId].fields, obj, encodeReqString);
1819
1997
  }
1820
1998
  nextRequestId() {
1821
- this.reqSeq = this.reqSeq >= 2147483647 ? 1 : this.reqSeq + 1;
1999
+ this.reqSeq = this.reqSeq >= 1073741823 ? 1 : this.reqSeq + 1;
1822
2000
  return this.reqSeq;
1823
2001
  }
1824
2002
  /** Message for a non-zero send code. Risk sentinels get a specific message;
@@ -1833,9 +2011,19 @@ var CtpClient = class extends import_node_events.EventEmitter {
1833
2011
  case -10002:
1834
2012
  return "rate limited (order rate exceeded)";
1835
2013
  case -10003:
1836
- return "blocked by max position cost";
2014
+ return "blocked by position margin limit";
1837
2015
  case -10004:
1838
2016
  return "blocked by max position volume (lots)";
2017
+ case -10005:
2018
+ return "duplicate orderRef in this front/session";
2019
+ case -10006:
2020
+ return "request is unavailable in the current risk mode or cannot be fully covered by configured local risk controls";
2021
+ case -10007:
2022
+ return "required risk state or metadata unavailable (reconcile positions/orders and refresh price, multiplier and margin inputs)";
2023
+ case -10008:
2024
+ return "invalid order direction/hedge flag or unsupported combOffsetFlag (single-leg only)";
2025
+ case -10009:
2026
+ return "session transition already in flight or ambiguous; await it, or reconnect after a timeout";
1839
2027
  default:
1840
2028
  return void 0;
1841
2029
  }
@@ -1844,14 +2032,18 @@ var CtpClient = class extends import_node_events.EventEmitter {
1844
2032
  * Send a request and resolve when its response arrives (matched by id).
1845
2033
  * `single` resolves with the one row; otherwise with the accumulated rows.
1846
2034
  */
1847
- request(send, single = false) {
2035
+ request(send, single = false, zeroIdEvent, sessionTransition = false) {
2036
+ if (this.closing)
2037
+ return Promise.reject(new Error("client closed"));
1848
2038
  const id = this.nextRequestId();
1849
2039
  return new Promise((resolve, reject) => {
1850
2040
  const entry = {
1851
2041
  rows: [],
1852
2042
  resolve,
1853
2043
  reject,
1854
- single
2044
+ single,
2045
+ zeroIdEvent,
2046
+ sessionTransition
1855
2047
  };
1856
2048
  this.pending.set(id, entry);
1857
2049
  let rc;
@@ -1865,11 +2057,81 @@ var CtpClient = class extends import_node_events.EventEmitter {
1865
2057
  if (rc !== 0) {
1866
2058
  this.pending.delete(id);
1867
2059
  const msg = this.riskRejectMessage(rc) ?? `request rejected by CTP API (code ${rc})`;
1868
- reject(new Error(msg));
2060
+ reject(Object.assign(new Error(msg), { ctpReturnCode: rc }));
2061
+ return;
2062
+ }
2063
+ if (this.pending.get(id) === entry)
2064
+ this.armRequestTimer(id, entry);
2065
+ });
2066
+ }
2067
+ /** Serialize every ReqQry* / ReqQuery* call on this CTP client.
2068
+ * CTP commonly allows about one query per second; putting the scheduler below
2069
+ * the generated surface means raw concurrent reqQry* calls are covered too,
2070
+ * not only the higher-level sync helpers. */
2071
+ queryRequest(send, single = false) {
2072
+ if (this.closing)
2073
+ return Promise.reject(new Error("client closed"));
2074
+ if (this.scheduledQueries >= MAX_SCHEDULED_QUERIES) {
2075
+ return Promise.reject(new Error(`query queue is full (${MAX_SCHEDULED_QUERIES}); await earlier queries before submitting more`));
2076
+ }
2077
+ this.scheduledQueries++;
2078
+ const epoch = this.requestContextEpoch;
2079
+ let resolveOuter;
2080
+ let rejectOuter;
2081
+ const outer = new Promise((resolve, reject) => {
2082
+ resolveOuter = resolve;
2083
+ rejectOuter = reject;
2084
+ });
2085
+ const run = this.queryQueue.then(async () => {
2086
+ const invalidReason = () => this.closing ? "client closed" : epoch !== this.requestContextEpoch ? this.queryInvalidationReason : void 0;
2087
+ let reason = invalidReason();
2088
+ if (reason !== void 0) {
2089
+ rejectOuter(new Error(reason));
2090
+ return;
2091
+ }
2092
+ for (; ; ) {
2093
+ reason = invalidReason();
2094
+ if (reason !== void 0) {
2095
+ rejectOuter(new Error(reason));
2096
+ return;
2097
+ }
2098
+ const wait = 1100 - (performance.now() - this.lastQuerySentAt);
2099
+ if (wait <= 0)
2100
+ break;
2101
+ await new Promise((resolve) => {
2102
+ let settled = false;
2103
+ const finish = () => {
2104
+ if (settled)
2105
+ return;
2106
+ settled = true;
2107
+ clearTimeout(timer);
2108
+ if (this.cancelQueryDelay === finish)
2109
+ this.cancelQueryDelay = void 0;
2110
+ resolve();
2111
+ };
2112
+ const timer = setTimeout(finish, Math.ceil(wait));
2113
+ this.cancelQueryDelay = finish;
2114
+ });
2115
+ }
2116
+ reason = invalidReason();
2117
+ if (reason !== void 0) {
2118
+ rejectOuter(new Error(reason));
1869
2119
  return;
1870
2120
  }
1871
- this.armRequestTimer(id, entry);
2121
+ this.lastQuerySentAt = performance.now();
2122
+ try {
2123
+ resolveOuter(await this.request(send, single));
2124
+ } catch (error) {
2125
+ rejectOuter(error);
2126
+ }
1872
2127
  });
2128
+ void run.then(void 0, rejectOuter);
2129
+ const releaseScheduledSlot = () => {
2130
+ this.scheduledQueries--;
2131
+ };
2132
+ void run.then(releaseScheduledSlot, releaseScheduledSlot);
2133
+ this.queryQueue = run.then(() => void 0, () => void 0);
2134
+ return outer;
1873
2135
  }
1874
2136
  /** (Re)arm a pending request's idle timeout. Called at send and reset on each
1875
2137
  * row, so a long streaming query isn't cut off by total elapsed time. */
@@ -1879,6 +2141,20 @@ var CtpClient = class extends import_node_events.EventEmitter {
1879
2141
  if (entry.timer)
1880
2142
  clearTimeout(entry.timer);
1881
2143
  entry.timer = setTimeout(() => {
2144
+ if (this.pending.get(id) !== entry)
2145
+ return;
2146
+ let shouldTimeout;
2147
+ try {
2148
+ shouldTimeout = this.shouldTimeoutRequest(id, entry.sessionTransition === true);
2149
+ } catch (error) {
2150
+ if (this.pending.delete(id))
2151
+ entry.reject(error);
2152
+ return;
2153
+ }
2154
+ if (!shouldTimeout) {
2155
+ this.armRequestTimer(id, entry);
2156
+ return;
2157
+ }
1882
2158
  if (this.pending.delete(id))
1883
2159
  entry.reject(new Error("request timed out"));
1884
2160
  }, this.requestTimeoutMs);
@@ -1893,6 +2169,8 @@ var CtpClient = class extends import_node_events.EventEmitter {
1893
2169
  * rtn-trade events, correlating by orderRef.
1894
2170
  */
1895
2171
  submit(send) {
2172
+ if (this.closing)
2173
+ return Promise.reject(new Error("client closed"));
1896
2174
  const id = this.nextRequestId();
1897
2175
  let rc;
1898
2176
  try {
@@ -1903,118 +2181,7 @@ var CtpClient = class extends import_node_events.EventEmitter {
1903
2181
  if (rc === 0)
1904
2182
  return Promise.resolve();
1905
2183
  const msg = this.riskRejectMessage(rc) ?? `order rejected by CTP API (code ${rc})`;
1906
- return Promise.reject(new Error(msg));
1907
- }
1908
- };
1909
-
1910
- // dist/market-data.js
1911
- var MD_BASE = 4096;
1912
- var MD_EVENTS = /* @__PURE__ */ new Map([
1913
- [MD_BASE + 1, "front-connected"],
1914
- [MD_BASE + 2, "front-disconnected"],
1915
- [MD_BASE + 3, "heart-beat-warning"],
1916
- [MD_BASE + 4, "rsp-user-login"],
1917
- [MD_BASE + 5, "rsp-user-logout"],
1918
- [MD_BASE + 6, "rsp-qry-multicast-instrument"],
1919
- [MD_BASE + 7, "rsp-error"],
1920
- [MD_BASE + 8, "rsp-sub-market-data"],
1921
- [MD_BASE + 9, "rsp-unsub-market-data"],
1922
- [MD_BASE + 10, "rsp-sub-for-quote"],
1923
- [MD_BASE + 11, "rsp-unsub-for-quote"],
1924
- [MD_BASE + 12, "rtn-depth-market-data"],
1925
- [MD_BASE + 13, "rtn-for-quote"]
1926
- ]);
1927
- var MarketDataEvent;
1928
- (function(MarketDataEvent2) {
1929
- MarketDataEvent2["FrontConnected"] = "front-connected";
1930
- MarketDataEvent2["FrontDisconnected"] = "front-disconnected";
1931
- MarketDataEvent2["HeartBeatWarning"] = "heart-beat-warning";
1932
- MarketDataEvent2["RspUserLogin"] = "rsp-user-login";
1933
- MarketDataEvent2["RspUserLogout"] = "rsp-user-logout";
1934
- MarketDataEvent2["RspQryMulticastInstrument"] = "rsp-qry-multicast-instrument";
1935
- MarketDataEvent2["RspError"] = "rsp-error";
1936
- MarketDataEvent2["RspSubMarketData"] = "rsp-sub-market-data";
1937
- MarketDataEvent2["RspUnSubMarketData"] = "rsp-unsub-market-data";
1938
- MarketDataEvent2["RspSubForQuote"] = "rsp-sub-for-quote";
1939
- MarketDataEvent2["RspUnSubForQuote"] = "rsp-unsub-for-quote";
1940
- MarketDataEvent2["RtnDepthMarketData"] = "rtn-depth-market-data";
1941
- MarketDataEvent2["RtnForQuote"] = "rtn-for-quote";
1942
- })(MarketDataEvent || (MarketDataEvent = {}));
1943
- var MarketData = class extends CtpClient {
1944
- constructor(flowPath, fronts) {
1945
- super(new native.MarketData(flowPath, fronts), native.__layoutData(), MD_EVENTS);
1946
- this.zeroIdFallbackEvents.add(MD_BASE + 4);
1947
- this.zeroIdFallbackEvents.add(MD_BASE + 5);
1948
- this.start();
1949
- }
1950
- getApiVersion() {
1951
- return this.native.getApiVersion();
1952
- }
1953
- getTradingDay() {
1954
- return this.native.getTradingDay();
1955
- }
1956
- /** Subscribe to depth market data. Returns the CTP send code (0 = ok). */
1957
- subscribe(instrumentIds) {
1958
- return this.native.subscribeMarketData(instrumentIds);
1959
- }
1960
- unsubscribe(instrumentIds) {
1961
- return this.native.unsubscribeMarketData(instrumentIds);
1962
- }
1963
- subscribeForQuote(instrumentIds) {
1964
- return this.native.subscribeForQuoteRsp(instrumentIds);
1965
- }
1966
- unsubscribeForQuote(instrumentIds) {
1967
- return this.native.unsubscribeForQuoteRsp(instrumentIds);
1968
- }
1969
- /** Latest cached depth tick for an instrument — the C++ last-value cache,
1970
- * updated on every tick before it reaches JS. Returns null if none has been
1971
- * seen (or it was unsubscribed). Synchronous: no waiting for an event, no
1972
- * per-tick bookkeeping in your strategy. */
1973
- snapshot(instrumentId) {
1974
- const bytes = this.native.snapshot(instrumentId);
1975
- return bytes ? this.decodeStruct(STRUCT_ID.DepthMarketData, bytes) : null;
1976
- }
1977
- /** Latest price for an instrument from the cache (0 if none seen). Synchronous. */
1978
- last(instrumentId) {
1979
- return this.native.last(instrumentId);
1980
- }
1981
- /** @internal Hand the C++ snapshot cache to a Trader (Trader.trackMarketData),
1982
- * so the Trader's deviation check reads live prices in C++ — no JS round-trip. */
1983
- _snapshotExternal() {
1984
- return this.native._snapshotExternal();
1985
- }
1986
- /** Log in; resolves with the login response (or rejects on CTP error). */
1987
- login(req = {}) {
1988
- return this.request((id) => this.native.reqUserLogin(req, id), true);
1989
- }
1990
- logout(req = {}) {
1991
- return this.request((id) => this.native.reqUserLogout(req, id), true);
1992
- }
1993
- armedTrader;
1994
- /** Route this market data's ticks to a Trader's armed triggers (see Trader.arm).
1995
- * A MarketData feeds exactly one Trader's registry; attaching a second,
1996
- * different Trader throws rather than silently stealing the feed. */
1997
- attachArm(trader) {
1998
- if (this.armedTrader && this.armedTrader !== trader) {
1999
- throw new Error("this MarketData already feeds another Trader's armed triggers");
2000
- }
2001
- this.armedTrader = trader;
2002
- this.native._attachArm(trader._armRegistry());
2003
- }
2004
- /** @internal test-only: inject a synthetic depth tick into the ring. Optional
2005
- * bid/ask override the defaults (3499/3501) so tests can drive edge prices
2006
- * (e.g. a DBL_MAX no-bid sentinel) through the real arm/onTick path. */
2007
- _injectTestTick(bid, ask) {
2008
- this.native._injectTestTick(bid, ask);
2009
- }
2010
- /** @internal test-only: spawn a background producer thread that pushes `n`
2011
- * synthetic ticks into the ring (cross-thread doorbell stress). Each tick's
2012
- * requestId carries its sequence number. */
2013
- _burstTicks(n, jitterUs = 0) {
2014
- this.native._burstTicks(n, jitterUs);
2015
- }
2016
- on(event, cb) {
2017
- return super.on(event, cb);
2184
+ return Promise.reject(Object.assign(new Error(msg), { ctpReturnCode: rc }));
2018
2185
  }
2019
2186
  };
2020
2187
 
@@ -2385,10 +2552,33 @@ var TraderBase = class extends CtpClient {
2385
2552
  return this.request((id) => this.native._req(1, this.encode(STRUCT_ID.ReqAuthenticate, req), id), true);
2386
2553
  }
2387
2554
  reqUserLogin(req = {}) {
2388
- return this.request((id) => this.native._req(2, this.encode(STRUCT_ID.ReqUserLogin, req), id), true);
2555
+ let cleanReq;
2556
+ let encoded;
2557
+ try {
2558
+ cleanReq = copyOwnRecord(req, "reqUserLogin request");
2559
+ encoded = this.encode(STRUCT_ID.ReqUserLogin, cleanReq);
2560
+ } catch (error) {
2561
+ return Promise.reject(error);
2562
+ }
2563
+ this.beginRequestContextTransition("trader session transition started");
2564
+ return this.request((id) => this.native._req(2, encoded, id), true, void 0, true).then((value) => {
2565
+ const row = value;
2566
+ if (!row || typeof row.brokerId !== "string" || !row.brokerId || typeof row.userId !== "string" || !row.userId || !Number.isInteger(row.frontId) || Number(row.frontId) <= 0 || !Number.isInteger(row.sessionId) || Number(row.sessionId) <= 0 || typeof cleanReq.brokerId === "string" && cleanReq.brokerId && row.brokerId !== cleanReq.brokerId || typeof cleanReq.userId === "string" && cleanReq.userId && row.userId !== cleanReq.userId)
2567
+ throw new Error("trader login response has missing or mismatched session identity");
2568
+ return value;
2569
+ });
2389
2570
  }
2390
2571
  reqUserLogout(req = {}) {
2391
- return this.request((id) => this.native._req(3, this.encode(STRUCT_ID.UserLogout, req), id), true);
2572
+ let cleanReq;
2573
+ let encoded;
2574
+ try {
2575
+ cleanReq = copyOwnRecord(req, "reqUserLogout request");
2576
+ encoded = this.encode(STRUCT_ID.UserLogout, cleanReq);
2577
+ } catch (error) {
2578
+ return Promise.reject(error);
2579
+ }
2580
+ this.beginRequestContextTransition("trader session transition started");
2581
+ return this.request((id) => this.native._req(3, encoded, id), true, void 0, true);
2392
2582
  }
2393
2583
  reqUserPasswordUpdate(req = {}) {
2394
2584
  return this.request((id) => this.native._req(4, this.encode(STRUCT_ID.UserPasswordUpdate, req), id), true);
@@ -2406,13 +2596,55 @@ var TraderBase = class extends CtpClient {
2406
2596
  return this.request((id) => this.native._req(8, this.encode(STRUCT_ID.ReqGenUserText, req), id), true);
2407
2597
  }
2408
2598
  reqUserLoginWithCaptcha(req = {}) {
2409
- return this.request((id) => this.native._req(9, this.encode(STRUCT_ID.ReqUserLoginWithCaptcha, req), id), true);
2599
+ let cleanReq;
2600
+ let encoded;
2601
+ try {
2602
+ cleanReq = copyOwnRecord(req, "reqUserLoginWithCaptcha request");
2603
+ encoded = this.encode(STRUCT_ID.ReqUserLoginWithCaptcha, cleanReq);
2604
+ } catch (error) {
2605
+ return Promise.reject(error);
2606
+ }
2607
+ this.beginRequestContextTransition("trader session transition started");
2608
+ return this.request((id) => this.native._req(9, encoded, id), true, void 0, true).then((value) => {
2609
+ const row = value;
2610
+ if (!row || typeof row.brokerId !== "string" || !row.brokerId || typeof row.userId !== "string" || !row.userId || !Number.isInteger(row.frontId) || Number(row.frontId) <= 0 || !Number.isInteger(row.sessionId) || Number(row.sessionId) <= 0 || typeof cleanReq.brokerId === "string" && cleanReq.brokerId && row.brokerId !== cleanReq.brokerId || typeof cleanReq.userId === "string" && cleanReq.userId && row.userId !== cleanReq.userId)
2611
+ throw new Error("trader login response has missing or mismatched session identity");
2612
+ return value;
2613
+ });
2410
2614
  }
2411
2615
  reqUserLoginWithText(req = {}) {
2412
- return this.request((id) => this.native._req(10, this.encode(STRUCT_ID.ReqUserLoginWithText, req), id), true);
2616
+ let cleanReq;
2617
+ let encoded;
2618
+ try {
2619
+ cleanReq = copyOwnRecord(req, "reqUserLoginWithText request");
2620
+ encoded = this.encode(STRUCT_ID.ReqUserLoginWithText, cleanReq);
2621
+ } catch (error) {
2622
+ return Promise.reject(error);
2623
+ }
2624
+ this.beginRequestContextTransition("trader session transition started");
2625
+ return this.request((id) => this.native._req(10, encoded, id), true, void 0, true).then((value) => {
2626
+ const row = value;
2627
+ if (!row || typeof row.brokerId !== "string" || !row.brokerId || typeof row.userId !== "string" || !row.userId || !Number.isInteger(row.frontId) || Number(row.frontId) <= 0 || !Number.isInteger(row.sessionId) || Number(row.sessionId) <= 0 || typeof cleanReq.brokerId === "string" && cleanReq.brokerId && row.brokerId !== cleanReq.brokerId || typeof cleanReq.userId === "string" && cleanReq.userId && row.userId !== cleanReq.userId)
2628
+ throw new Error("trader login response has missing or mismatched session identity");
2629
+ return value;
2630
+ });
2413
2631
  }
2414
2632
  reqUserLoginWithOtp(req = {}) {
2415
- return this.request((id) => this.native._req(11, this.encode(STRUCT_ID.ReqUserLoginWithOTP, req), id), true);
2633
+ let cleanReq;
2634
+ let encoded;
2635
+ try {
2636
+ cleanReq = copyOwnRecord(req, "reqUserLoginWithOtp request");
2637
+ encoded = this.encode(STRUCT_ID.ReqUserLoginWithOTP, cleanReq);
2638
+ } catch (error) {
2639
+ return Promise.reject(error);
2640
+ }
2641
+ this.beginRequestContextTransition("trader session transition started");
2642
+ return this.request((id) => this.native._req(11, encoded, id), true, void 0, true).then((value) => {
2643
+ const row = value;
2644
+ if (!row || typeof row.brokerId !== "string" || !row.brokerId || typeof row.userId !== "string" || !row.userId || !Number.isInteger(row.frontId) || Number(row.frontId) <= 0 || !Number.isInteger(row.sessionId) || Number(row.sessionId) <= 0 || typeof cleanReq.brokerId === "string" && cleanReq.brokerId && row.brokerId !== cleanReq.brokerId || typeof cleanReq.userId === "string" && cleanReq.userId && row.userId !== cleanReq.userId)
2645
+ throw new Error("trader login response has missing or mismatched session identity");
2646
+ return value;
2647
+ });
2416
2648
  }
2417
2649
  reqOrderInsert(req = {}) {
2418
2650
  return this.submit((id) => this.native._req(12, this.encode(STRUCT_ID.InputOrder, req), id));
@@ -2427,7 +2659,13 @@ var TraderBase = class extends CtpClient {
2427
2659
  return this.submit((id) => this.native._req(15, this.encode(STRUCT_ID.InputOrderAction, req), id));
2428
2660
  }
2429
2661
  reqQryMaxOrderVolume(req = {}) {
2430
- return this.request((id) => this.native._req(16, this.encode(STRUCT_ID.QryMaxOrderVolume, req), id), false);
2662
+ let encoded;
2663
+ try {
2664
+ encoded = this.encode(STRUCT_ID.QryMaxOrderVolume, req);
2665
+ } catch (error) {
2666
+ return Promise.reject(error);
2667
+ }
2668
+ return this.queryRequest((id) => this.native._req(16, encoded, id), false);
2431
2669
  }
2432
2670
  reqSettlementInfoConfirm(req = {}) {
2433
2671
  return this.request((id) => this.native._req(17, this.encode(STRUCT_ID.SettlementInfoConfirm, req), id), true);
@@ -2466,163 +2704,481 @@ var TraderBase = class extends CtpClient {
2466
2704
  return this.submit((id) => this.native._req(28, this.encode(STRUCT_ID.InputCombAction, req), id));
2467
2705
  }
2468
2706
  reqQryOrder(req = {}) {
2469
- return this.request((id) => this.native._req(29, this.encode(STRUCT_ID.QryOrder, req), id), false);
2707
+ let encoded;
2708
+ try {
2709
+ encoded = this.encode(STRUCT_ID.QryOrder, req);
2710
+ } catch (error) {
2711
+ return Promise.reject(error);
2712
+ }
2713
+ return this.queryRequest((id) => this.native._req(29, encoded, id), false);
2470
2714
  }
2471
2715
  reqQryTrade(req = {}) {
2472
- return this.request((id) => this.native._req(30, this.encode(STRUCT_ID.QryTrade, req), id), false);
2716
+ let encoded;
2717
+ try {
2718
+ encoded = this.encode(STRUCT_ID.QryTrade, req);
2719
+ } catch (error) {
2720
+ return Promise.reject(error);
2721
+ }
2722
+ return this.queryRequest((id) => this.native._req(30, encoded, id), false);
2473
2723
  }
2474
2724
  reqQryInvestorPosition(req = {}) {
2475
- return this.request((id) => this.native._req(31, this.encode(STRUCT_ID.QryInvestorPosition, req), id), false);
2725
+ let encoded;
2726
+ try {
2727
+ encoded = this.encode(STRUCT_ID.QryInvestorPosition, req);
2728
+ } catch (error) {
2729
+ return Promise.reject(error);
2730
+ }
2731
+ return this.queryRequest((id) => this.native._req(31, encoded, id), false);
2476
2732
  }
2477
2733
  reqQryTradingAccount(req = {}) {
2478
- return this.request((id) => this.native._req(32, this.encode(STRUCT_ID.QryTradingAccount, req), id), false);
2734
+ let encoded;
2735
+ try {
2736
+ encoded = this.encode(STRUCT_ID.QryTradingAccount, req);
2737
+ } catch (error) {
2738
+ return Promise.reject(error);
2739
+ }
2740
+ return this.queryRequest((id) => this.native._req(32, encoded, id), false);
2479
2741
  }
2480
2742
  reqQryInvestor(req = {}) {
2481
- return this.request((id) => this.native._req(33, this.encode(STRUCT_ID.QryInvestor, req), id), false);
2743
+ let encoded;
2744
+ try {
2745
+ encoded = this.encode(STRUCT_ID.QryInvestor, req);
2746
+ } catch (error) {
2747
+ return Promise.reject(error);
2748
+ }
2749
+ return this.queryRequest((id) => this.native._req(33, encoded, id), false);
2482
2750
  }
2483
2751
  reqQryTradingCode(req = {}) {
2484
- return this.request((id) => this.native._req(34, this.encode(STRUCT_ID.QryTradingCode, req), id), false);
2752
+ let encoded;
2753
+ try {
2754
+ encoded = this.encode(STRUCT_ID.QryTradingCode, req);
2755
+ } catch (error) {
2756
+ return Promise.reject(error);
2757
+ }
2758
+ return this.queryRequest((id) => this.native._req(34, encoded, id), false);
2485
2759
  }
2486
2760
  reqQryInstrumentMarginRate(req = {}) {
2487
- return this.request((id) => this.native._req(35, this.encode(STRUCT_ID.QryInstrumentMarginRate, req), id), false);
2761
+ let encoded;
2762
+ try {
2763
+ encoded = this.encode(STRUCT_ID.QryInstrumentMarginRate, req);
2764
+ } catch (error) {
2765
+ return Promise.reject(error);
2766
+ }
2767
+ return this.queryRequest((id) => this.native._req(35, encoded, id), false);
2488
2768
  }
2489
2769
  reqQryInstrumentCommissionRate(req = {}) {
2490
- return this.request((id) => this.native._req(36, this.encode(STRUCT_ID.QryInstrumentCommissionRate, req), id), false);
2770
+ let encoded;
2771
+ try {
2772
+ encoded = this.encode(STRUCT_ID.QryInstrumentCommissionRate, req);
2773
+ } catch (error) {
2774
+ return Promise.reject(error);
2775
+ }
2776
+ return this.queryRequest((id) => this.native._req(36, encoded, id), false);
2491
2777
  }
2492
2778
  reqQryUserSession(req = {}) {
2493
- return this.request((id) => this.native._req(37, this.encode(STRUCT_ID.QryUserSession, req), id), false);
2779
+ let encoded;
2780
+ try {
2781
+ encoded = this.encode(STRUCT_ID.QryUserSession, req);
2782
+ } catch (error) {
2783
+ return Promise.reject(error);
2784
+ }
2785
+ return this.queryRequest((id) => this.native._req(37, encoded, id), false);
2494
2786
  }
2495
2787
  reqQryExchange(req = {}) {
2496
- return this.request((id) => this.native._req(38, this.encode(STRUCT_ID.QryExchange, req), id), false);
2788
+ let encoded;
2789
+ try {
2790
+ encoded = this.encode(STRUCT_ID.QryExchange, req);
2791
+ } catch (error) {
2792
+ return Promise.reject(error);
2793
+ }
2794
+ return this.queryRequest((id) => this.native._req(38, encoded, id), false);
2497
2795
  }
2498
2796
  reqQryProduct(req = {}) {
2499
- return this.request((id) => this.native._req(39, this.encode(STRUCT_ID.QryProduct, req), id), false);
2797
+ let encoded;
2798
+ try {
2799
+ encoded = this.encode(STRUCT_ID.QryProduct, req);
2800
+ } catch (error) {
2801
+ return Promise.reject(error);
2802
+ }
2803
+ return this.queryRequest((id) => this.native._req(39, encoded, id), false);
2500
2804
  }
2501
2805
  reqQryInstrument(req = {}) {
2502
- return this.request((id) => this.native._req(40, this.encode(STRUCT_ID.QryInstrument, req), id), false);
2806
+ let encoded;
2807
+ try {
2808
+ encoded = this.encode(STRUCT_ID.QryInstrument, req);
2809
+ } catch (error) {
2810
+ return Promise.reject(error);
2811
+ }
2812
+ return this.queryRequest((id) => this.native._req(40, encoded, id), false);
2503
2813
  }
2504
2814
  reqQryDepthMarketData(req = {}) {
2505
- return this.request((id) => this.native._req(41, this.encode(STRUCT_ID.QryDepthMarketData, req), id), false);
2815
+ let encoded;
2816
+ try {
2817
+ encoded = this.encode(STRUCT_ID.QryDepthMarketData, req);
2818
+ } catch (error) {
2819
+ return Promise.reject(error);
2820
+ }
2821
+ return this.queryRequest((id) => this.native._req(41, encoded, id), false);
2506
2822
  }
2507
2823
  reqQryTraderOffer(req = {}) {
2508
- return this.request((id) => this.native._req(42, this.encode(STRUCT_ID.QryTraderOffer, req), id), false);
2824
+ let encoded;
2825
+ try {
2826
+ encoded = this.encode(STRUCT_ID.QryTraderOffer, req);
2827
+ } catch (error) {
2828
+ return Promise.reject(error);
2829
+ }
2830
+ return this.queryRequest((id) => this.native._req(42, encoded, id), false);
2509
2831
  }
2510
2832
  reqQrySettlementInfo(req = {}) {
2511
- return this.request((id) => this.native._req(43, this.encode(STRUCT_ID.QrySettlementInfo, req), id), false);
2833
+ let encoded;
2834
+ try {
2835
+ encoded = this.encode(STRUCT_ID.QrySettlementInfo, req);
2836
+ } catch (error) {
2837
+ return Promise.reject(error);
2838
+ }
2839
+ return this.queryRequest((id) => this.native._req(43, encoded, id), false);
2512
2840
  }
2513
2841
  reqQryTransferBank(req = {}) {
2514
- return this.request((id) => this.native._req(44, this.encode(STRUCT_ID.QryTransferBank, req), id), false);
2842
+ let encoded;
2843
+ try {
2844
+ encoded = this.encode(STRUCT_ID.QryTransferBank, req);
2845
+ } catch (error) {
2846
+ return Promise.reject(error);
2847
+ }
2848
+ return this.queryRequest((id) => this.native._req(44, encoded, id), false);
2515
2849
  }
2516
2850
  reqQryInvestorPositionDetail(req = {}) {
2517
- return this.request((id) => this.native._req(45, this.encode(STRUCT_ID.QryInvestorPositionDetail, req), id), false);
2851
+ let encoded;
2852
+ try {
2853
+ encoded = this.encode(STRUCT_ID.QryInvestorPositionDetail, req);
2854
+ } catch (error) {
2855
+ return Promise.reject(error);
2856
+ }
2857
+ return this.queryRequest((id) => this.native._req(45, encoded, id), false);
2518
2858
  }
2519
2859
  reqQryNotice(req = {}) {
2520
- return this.request((id) => this.native._req(46, this.encode(STRUCT_ID.QryNotice, req), id), false);
2860
+ let encoded;
2861
+ try {
2862
+ encoded = this.encode(STRUCT_ID.QryNotice, req);
2863
+ } catch (error) {
2864
+ return Promise.reject(error);
2865
+ }
2866
+ return this.queryRequest((id) => this.native._req(46, encoded, id), false);
2521
2867
  }
2522
2868
  reqQrySettlementInfoConfirm(req = {}) {
2523
- return this.request((id) => this.native._req(47, this.encode(STRUCT_ID.QrySettlementInfoConfirm, req), id), false);
2869
+ let encoded;
2870
+ try {
2871
+ encoded = this.encode(STRUCT_ID.QrySettlementInfoConfirm, req);
2872
+ } catch (error) {
2873
+ return Promise.reject(error);
2874
+ }
2875
+ return this.queryRequest((id) => this.native._req(47, encoded, id), false);
2524
2876
  }
2525
2877
  reqQryInvestorPositionCombineDetail(req = {}) {
2526
- return this.request((id) => this.native._req(48, this.encode(STRUCT_ID.QryInvestorPositionCombineDetail, req), id), false);
2878
+ let encoded;
2879
+ try {
2880
+ encoded = this.encode(STRUCT_ID.QryInvestorPositionCombineDetail, req);
2881
+ } catch (error) {
2882
+ return Promise.reject(error);
2883
+ }
2884
+ return this.queryRequest((id) => this.native._req(48, encoded, id), false);
2527
2885
  }
2528
2886
  reqQryCfmmcTradingAccountKey(req = {}) {
2529
- return this.request((id) => this.native._req(49, this.encode(STRUCT_ID.QryCFMMCTradingAccountKey, req), id), false);
2887
+ let encoded;
2888
+ try {
2889
+ encoded = this.encode(STRUCT_ID.QryCFMMCTradingAccountKey, req);
2890
+ } catch (error) {
2891
+ return Promise.reject(error);
2892
+ }
2893
+ return this.queryRequest((id) => this.native._req(49, encoded, id), false);
2530
2894
  }
2531
2895
  reqQryEWarrantOffset(req = {}) {
2532
- return this.request((id) => this.native._req(50, this.encode(STRUCT_ID.QryEWarrantOffset, req), id), false);
2896
+ let encoded;
2897
+ try {
2898
+ encoded = this.encode(STRUCT_ID.QryEWarrantOffset, req);
2899
+ } catch (error) {
2900
+ return Promise.reject(error);
2901
+ }
2902
+ return this.queryRequest((id) => this.native._req(50, encoded, id), false);
2533
2903
  }
2534
2904
  reqQryInvestorProductGroupMargin(req = {}) {
2535
- return this.request((id) => this.native._req(51, this.encode(STRUCT_ID.QryInvestorProductGroupMargin, req), id), false);
2905
+ let encoded;
2906
+ try {
2907
+ encoded = this.encode(STRUCT_ID.QryInvestorProductGroupMargin, req);
2908
+ } catch (error) {
2909
+ return Promise.reject(error);
2910
+ }
2911
+ return this.queryRequest((id) => this.native._req(51, encoded, id), false);
2536
2912
  }
2537
2913
  reqQryExchangeMarginRate(req = {}) {
2538
- return this.request((id) => this.native._req(52, this.encode(STRUCT_ID.QryExchangeMarginRate, req), id), false);
2914
+ let encoded;
2915
+ try {
2916
+ encoded = this.encode(STRUCT_ID.QryExchangeMarginRate, req);
2917
+ } catch (error) {
2918
+ return Promise.reject(error);
2919
+ }
2920
+ return this.queryRequest((id) => this.native._req(52, encoded, id), false);
2539
2921
  }
2540
2922
  reqQryExchangeMarginRateAdjust(req = {}) {
2541
- return this.request((id) => this.native._req(53, this.encode(STRUCT_ID.QryExchangeMarginRateAdjust, req), id), false);
2923
+ let encoded;
2924
+ try {
2925
+ encoded = this.encode(STRUCT_ID.QryExchangeMarginRateAdjust, req);
2926
+ } catch (error) {
2927
+ return Promise.reject(error);
2928
+ }
2929
+ return this.queryRequest((id) => this.native._req(53, encoded, id), false);
2542
2930
  }
2543
2931
  reqQryExchangeRate(req = {}) {
2544
- return this.request((id) => this.native._req(54, this.encode(STRUCT_ID.QryExchangeRate, req), id), false);
2932
+ let encoded;
2933
+ try {
2934
+ encoded = this.encode(STRUCT_ID.QryExchangeRate, req);
2935
+ } catch (error) {
2936
+ return Promise.reject(error);
2937
+ }
2938
+ return this.queryRequest((id) => this.native._req(54, encoded, id), false);
2545
2939
  }
2546
2940
  reqQrySecAgentAcidMap(req = {}) {
2547
- return this.request((id) => this.native._req(55, this.encode(STRUCT_ID.QrySecAgentACIDMap, req), id), false);
2941
+ let encoded;
2942
+ try {
2943
+ encoded = this.encode(STRUCT_ID.QrySecAgentACIDMap, req);
2944
+ } catch (error) {
2945
+ return Promise.reject(error);
2946
+ }
2947
+ return this.queryRequest((id) => this.native._req(55, encoded, id), false);
2548
2948
  }
2549
2949
  reqQryProductExchRate(req = {}) {
2550
- return this.request((id) => this.native._req(56, this.encode(STRUCT_ID.QryProductExchRate, req), id), false);
2950
+ let encoded;
2951
+ try {
2952
+ encoded = this.encode(STRUCT_ID.QryProductExchRate, req);
2953
+ } catch (error) {
2954
+ return Promise.reject(error);
2955
+ }
2956
+ return this.queryRequest((id) => this.native._req(56, encoded, id), false);
2551
2957
  }
2552
2958
  reqQryProductGroup(req = {}) {
2553
- return this.request((id) => this.native._req(57, this.encode(STRUCT_ID.QryProductGroup, req), id), false);
2959
+ let encoded;
2960
+ try {
2961
+ encoded = this.encode(STRUCT_ID.QryProductGroup, req);
2962
+ } catch (error) {
2963
+ return Promise.reject(error);
2964
+ }
2965
+ return this.queryRequest((id) => this.native._req(57, encoded, id), false);
2554
2966
  }
2555
2967
  reqQryMmInstrumentCommissionRate(req = {}) {
2556
- return this.request((id) => this.native._req(58, this.encode(STRUCT_ID.QryMMInstrumentCommissionRate, req), id), false);
2968
+ let encoded;
2969
+ try {
2970
+ encoded = this.encode(STRUCT_ID.QryMMInstrumentCommissionRate, req);
2971
+ } catch (error) {
2972
+ return Promise.reject(error);
2973
+ }
2974
+ return this.queryRequest((id) => this.native._req(58, encoded, id), false);
2557
2975
  }
2558
2976
  reqQryMmOptionInstrCommRate(req = {}) {
2559
- return this.request((id) => this.native._req(59, this.encode(STRUCT_ID.QryMMOptionInstrCommRate, req), id), false);
2977
+ let encoded;
2978
+ try {
2979
+ encoded = this.encode(STRUCT_ID.QryMMOptionInstrCommRate, req);
2980
+ } catch (error) {
2981
+ return Promise.reject(error);
2982
+ }
2983
+ return this.queryRequest((id) => this.native._req(59, encoded, id), false);
2560
2984
  }
2561
2985
  reqQryInstrumentOrderCommRate(req = {}) {
2562
- return this.request((id) => this.native._req(60, this.encode(STRUCT_ID.QryInstrumentOrderCommRate, req), id), false);
2986
+ let encoded;
2987
+ try {
2988
+ encoded = this.encode(STRUCT_ID.QryInstrumentOrderCommRate, req);
2989
+ } catch (error) {
2990
+ return Promise.reject(error);
2991
+ }
2992
+ return this.queryRequest((id) => this.native._req(60, encoded, id), false);
2563
2993
  }
2564
2994
  reqQrySecAgentTradingAccount(req = {}) {
2565
- return this.request((id) => this.native._req(61, this.encode(STRUCT_ID.QryTradingAccount, req), id), false);
2995
+ let encoded;
2996
+ try {
2997
+ encoded = this.encode(STRUCT_ID.QryTradingAccount, req);
2998
+ } catch (error) {
2999
+ return Promise.reject(error);
3000
+ }
3001
+ return this.queryRequest((id) => this.native._req(61, encoded, id), false);
2566
3002
  }
2567
3003
  reqQrySecAgentCheckMode(req = {}) {
2568
- return this.request((id) => this.native._req(62, this.encode(STRUCT_ID.QrySecAgentCheckMode, req), id), false);
3004
+ let encoded;
3005
+ try {
3006
+ encoded = this.encode(STRUCT_ID.QrySecAgentCheckMode, req);
3007
+ } catch (error) {
3008
+ return Promise.reject(error);
3009
+ }
3010
+ return this.queryRequest((id) => this.native._req(62, encoded, id), false);
2569
3011
  }
2570
3012
  reqQrySecAgentTradeInfo(req = {}) {
2571
- return this.request((id) => this.native._req(63, this.encode(STRUCT_ID.QrySecAgentTradeInfo, req), id), false);
3013
+ let encoded;
3014
+ try {
3015
+ encoded = this.encode(STRUCT_ID.QrySecAgentTradeInfo, req);
3016
+ } catch (error) {
3017
+ return Promise.reject(error);
3018
+ }
3019
+ return this.queryRequest((id) => this.native._req(63, encoded, id), false);
2572
3020
  }
2573
3021
  reqQryOptionInstrTradeCost(req = {}) {
2574
- return this.request((id) => this.native._req(64, this.encode(STRUCT_ID.QryOptionInstrTradeCost, req), id), false);
3022
+ let encoded;
3023
+ try {
3024
+ encoded = this.encode(STRUCT_ID.QryOptionInstrTradeCost, req);
3025
+ } catch (error) {
3026
+ return Promise.reject(error);
3027
+ }
3028
+ return this.queryRequest((id) => this.native._req(64, encoded, id), false);
2575
3029
  }
2576
3030
  reqQryOptionInstrCommRate(req = {}) {
2577
- return this.request((id) => this.native._req(65, this.encode(STRUCT_ID.QryOptionInstrCommRate, req), id), false);
3031
+ let encoded;
3032
+ try {
3033
+ encoded = this.encode(STRUCT_ID.QryOptionInstrCommRate, req);
3034
+ } catch (error) {
3035
+ return Promise.reject(error);
3036
+ }
3037
+ return this.queryRequest((id) => this.native._req(65, encoded, id), false);
2578
3038
  }
2579
3039
  reqQryExecOrder(req = {}) {
2580
- return this.request((id) => this.native._req(66, this.encode(STRUCT_ID.QryExecOrder, req), id), false);
3040
+ let encoded;
3041
+ try {
3042
+ encoded = this.encode(STRUCT_ID.QryExecOrder, req);
3043
+ } catch (error) {
3044
+ return Promise.reject(error);
3045
+ }
3046
+ return this.queryRequest((id) => this.native._req(66, encoded, id), false);
2581
3047
  }
2582
3048
  reqQryForQuote(req = {}) {
2583
- return this.request((id) => this.native._req(67, this.encode(STRUCT_ID.QryForQuote, req), id), false);
3049
+ let encoded;
3050
+ try {
3051
+ encoded = this.encode(STRUCT_ID.QryForQuote, req);
3052
+ } catch (error) {
3053
+ return Promise.reject(error);
3054
+ }
3055
+ return this.queryRequest((id) => this.native._req(67, encoded, id), false);
2584
3056
  }
2585
3057
  reqQryQuote(req = {}) {
2586
- return this.request((id) => this.native._req(68, this.encode(STRUCT_ID.QryQuote, req), id), false);
3058
+ let encoded;
3059
+ try {
3060
+ encoded = this.encode(STRUCT_ID.QryQuote, req);
3061
+ } catch (error) {
3062
+ return Promise.reject(error);
3063
+ }
3064
+ return this.queryRequest((id) => this.native._req(68, encoded, id), false);
2587
3065
  }
2588
3066
  reqQryOptionSelfClose(req = {}) {
2589
- return this.request((id) => this.native._req(69, this.encode(STRUCT_ID.QryOptionSelfClose, req), id), false);
3067
+ let encoded;
3068
+ try {
3069
+ encoded = this.encode(STRUCT_ID.QryOptionSelfClose, req);
3070
+ } catch (error) {
3071
+ return Promise.reject(error);
3072
+ }
3073
+ return this.queryRequest((id) => this.native._req(69, encoded, id), false);
2590
3074
  }
2591
3075
  reqQryInvestUnit(req = {}) {
2592
- return this.request((id) => this.native._req(70, this.encode(STRUCT_ID.QryInvestUnit, req), id), false);
3076
+ let encoded;
3077
+ try {
3078
+ encoded = this.encode(STRUCT_ID.QryInvestUnit, req);
3079
+ } catch (error) {
3080
+ return Promise.reject(error);
3081
+ }
3082
+ return this.queryRequest((id) => this.native._req(70, encoded, id), false);
2593
3083
  }
2594
3084
  reqQryCombInstrumentGuard(req = {}) {
2595
- return this.request((id) => this.native._req(71, this.encode(STRUCT_ID.QryCombInstrumentGuard, req), id), false);
3085
+ let encoded;
3086
+ try {
3087
+ encoded = this.encode(STRUCT_ID.QryCombInstrumentGuard, req);
3088
+ } catch (error) {
3089
+ return Promise.reject(error);
3090
+ }
3091
+ return this.queryRequest((id) => this.native._req(71, encoded, id), false);
2596
3092
  }
2597
3093
  reqQryCombAction(req = {}) {
2598
- return this.request((id) => this.native._req(72, this.encode(STRUCT_ID.QryCombAction, req), id), false);
3094
+ let encoded;
3095
+ try {
3096
+ encoded = this.encode(STRUCT_ID.QryCombAction, req);
3097
+ } catch (error) {
3098
+ return Promise.reject(error);
3099
+ }
3100
+ return this.queryRequest((id) => this.native._req(72, encoded, id), false);
2599
3101
  }
2600
3102
  reqQryTransferSerial(req = {}) {
2601
- return this.request((id) => this.native._req(73, this.encode(STRUCT_ID.QryTransferSerial, req), id), false);
3103
+ let encoded;
3104
+ try {
3105
+ encoded = this.encode(STRUCT_ID.QryTransferSerial, req);
3106
+ } catch (error) {
3107
+ return Promise.reject(error);
3108
+ }
3109
+ return this.queryRequest((id) => this.native._req(73, encoded, id), false);
2602
3110
  }
2603
3111
  reqQryAccountregister(req = {}) {
2604
- return this.request((id) => this.native._req(74, this.encode(STRUCT_ID.QryAccountregister, req), id), false);
3112
+ let encoded;
3113
+ try {
3114
+ encoded = this.encode(STRUCT_ID.QryAccountregister, req);
3115
+ } catch (error) {
3116
+ return Promise.reject(error);
3117
+ }
3118
+ return this.queryRequest((id) => this.native._req(74, encoded, id), false);
2605
3119
  }
2606
3120
  reqQryContractBank(req = {}) {
2607
- return this.request((id) => this.native._req(75, this.encode(STRUCT_ID.QryContractBank, req), id), false);
3121
+ let encoded;
3122
+ try {
3123
+ encoded = this.encode(STRUCT_ID.QryContractBank, req);
3124
+ } catch (error) {
3125
+ return Promise.reject(error);
3126
+ }
3127
+ return this.queryRequest((id) => this.native._req(75, encoded, id), false);
2608
3128
  }
2609
3129
  reqQryParkedOrder(req = {}) {
2610
- return this.request((id) => this.native._req(76, this.encode(STRUCT_ID.QryParkedOrder, req), id), false);
3130
+ let encoded;
3131
+ try {
3132
+ encoded = this.encode(STRUCT_ID.QryParkedOrder, req);
3133
+ } catch (error) {
3134
+ return Promise.reject(error);
3135
+ }
3136
+ return this.queryRequest((id) => this.native._req(76, encoded, id), false);
2611
3137
  }
2612
3138
  reqQryParkedOrderAction(req = {}) {
2613
- return this.request((id) => this.native._req(77, this.encode(STRUCT_ID.QryParkedOrderAction, req), id), false);
3139
+ let encoded;
3140
+ try {
3141
+ encoded = this.encode(STRUCT_ID.QryParkedOrderAction, req);
3142
+ } catch (error) {
3143
+ return Promise.reject(error);
3144
+ }
3145
+ return this.queryRequest((id) => this.native._req(77, encoded, id), false);
2614
3146
  }
2615
3147
  reqQryTradingNotice(req = {}) {
2616
- return this.request((id) => this.native._req(78, this.encode(STRUCT_ID.QryTradingNotice, req), id), false);
3148
+ let encoded;
3149
+ try {
3150
+ encoded = this.encode(STRUCT_ID.QryTradingNotice, req);
3151
+ } catch (error) {
3152
+ return Promise.reject(error);
3153
+ }
3154
+ return this.queryRequest((id) => this.native._req(78, encoded, id), false);
2617
3155
  }
2618
3156
  reqQryBrokerTradingParams(req = {}) {
2619
- return this.request((id) => this.native._req(79, this.encode(STRUCT_ID.QryBrokerTradingParams, req), id), false);
2620
- }
3157
+ let encoded;
3158
+ try {
3159
+ encoded = this.encode(STRUCT_ID.QryBrokerTradingParams, req);
3160
+ } catch (error) {
3161
+ return Promise.reject(error);
3162
+ }
3163
+ return this.queryRequest((id) => this.native._req(79, encoded, id), false);
3164
+ }
2621
3165
  reqQryBrokerTradingAlgos(req = {}) {
2622
- return this.request((id) => this.native._req(80, this.encode(STRUCT_ID.QryBrokerTradingAlgos, req), id), false);
3166
+ let encoded;
3167
+ try {
3168
+ encoded = this.encode(STRUCT_ID.QryBrokerTradingAlgos, req);
3169
+ } catch (error) {
3170
+ return Promise.reject(error);
3171
+ }
3172
+ return this.queryRequest((id) => this.native._req(80, encoded, id), false);
2623
3173
  }
2624
3174
  reqQueryCfmmcTradingAccountToken(req = {}) {
2625
- return this.request((id) => this.native._req(81, this.encode(STRUCT_ID.QueryCFMMCTradingAccountToken, req), id), true);
3175
+ let encoded;
3176
+ try {
3177
+ encoded = this.encode(STRUCT_ID.QueryCFMMCTradingAccountToken, req);
3178
+ } catch (error) {
3179
+ return Promise.reject(error);
3180
+ }
3181
+ return this.queryRequest((id) => this.native._req(81, encoded, id), true);
2626
3182
  }
2627
3183
  reqFromBankToFutureByFuture(req = {}) {
2628
3184
  return this.request((id) => this.native._req(82, this.encode(STRUCT_ID.ReqTransfer, req), id), true);
@@ -2631,100 +3187,292 @@ var TraderBase = class extends CtpClient {
2631
3187
  return this.request((id) => this.native._req(83, this.encode(STRUCT_ID.ReqTransfer, req), id), true);
2632
3188
  }
2633
3189
  reqQueryBankAccountMoneyByFuture(req = {}) {
2634
- return this.request((id) => this.native._req(84, this.encode(STRUCT_ID.ReqQueryAccount, req), id), true);
3190
+ let encoded;
3191
+ try {
3192
+ encoded = this.encode(STRUCT_ID.ReqQueryAccount, req);
3193
+ } catch (error) {
3194
+ return Promise.reject(error);
3195
+ }
3196
+ return this.queryRequest((id) => this.native._req(84, encoded, id), true);
2635
3197
  }
2636
3198
  reqQryClassifiedInstrument(req = {}) {
2637
- return this.request((id) => this.native._req(85, this.encode(STRUCT_ID.QryClassifiedInstrument, req), id), false);
3199
+ let encoded;
3200
+ try {
3201
+ encoded = this.encode(STRUCT_ID.QryClassifiedInstrument, req);
3202
+ } catch (error) {
3203
+ return Promise.reject(error);
3204
+ }
3205
+ return this.queryRequest((id) => this.native._req(85, encoded, id), false);
2638
3206
  }
2639
3207
  reqQryCombPromotionParam(req = {}) {
2640
- return this.request((id) => this.native._req(86, this.encode(STRUCT_ID.QryCombPromotionParam, req), id), false);
3208
+ let encoded;
3209
+ try {
3210
+ encoded = this.encode(STRUCT_ID.QryCombPromotionParam, req);
3211
+ } catch (error) {
3212
+ return Promise.reject(error);
3213
+ }
3214
+ return this.queryRequest((id) => this.native._req(86, encoded, id), false);
2641
3215
  }
2642
3216
  reqQryRiskSettleInvstPosition(req = {}) {
2643
- return this.request((id) => this.native._req(87, this.encode(STRUCT_ID.QryRiskSettleInvstPosition, req), id), false);
3217
+ let encoded;
3218
+ try {
3219
+ encoded = this.encode(STRUCT_ID.QryRiskSettleInvstPosition, req);
3220
+ } catch (error) {
3221
+ return Promise.reject(error);
3222
+ }
3223
+ return this.queryRequest((id) => this.native._req(87, encoded, id), false);
2644
3224
  }
2645
3225
  reqQryRiskSettleProductStatus(req = {}) {
2646
- return this.request((id) => this.native._req(88, this.encode(STRUCT_ID.QryRiskSettleProductStatus, req), id), false);
3226
+ let encoded;
3227
+ try {
3228
+ encoded = this.encode(STRUCT_ID.QryRiskSettleProductStatus, req);
3229
+ } catch (error) {
3230
+ return Promise.reject(error);
3231
+ }
3232
+ return this.queryRequest((id) => this.native._req(88, encoded, id), false);
2647
3233
  }
2648
3234
  reqQrySpbmFutureParameter(req = {}) {
2649
- return this.request((id) => this.native._req(89, this.encode(STRUCT_ID.QrySPBMFutureParameter, req), id), false);
3235
+ let encoded;
3236
+ try {
3237
+ encoded = this.encode(STRUCT_ID.QrySPBMFutureParameter, req);
3238
+ } catch (error) {
3239
+ return Promise.reject(error);
3240
+ }
3241
+ return this.queryRequest((id) => this.native._req(89, encoded, id), false);
2650
3242
  }
2651
3243
  reqQrySpbmOptionParameter(req = {}) {
2652
- return this.request((id) => this.native._req(90, this.encode(STRUCT_ID.QrySPBMOptionParameter, req), id), false);
3244
+ let encoded;
3245
+ try {
3246
+ encoded = this.encode(STRUCT_ID.QrySPBMOptionParameter, req);
3247
+ } catch (error) {
3248
+ return Promise.reject(error);
3249
+ }
3250
+ return this.queryRequest((id) => this.native._req(90, encoded, id), false);
2653
3251
  }
2654
3252
  reqQrySpbmIntraParameter(req = {}) {
2655
- return this.request((id) => this.native._req(91, this.encode(STRUCT_ID.QrySPBMIntraParameter, req), id), false);
3253
+ let encoded;
3254
+ try {
3255
+ encoded = this.encode(STRUCT_ID.QrySPBMIntraParameter, req);
3256
+ } catch (error) {
3257
+ return Promise.reject(error);
3258
+ }
3259
+ return this.queryRequest((id) => this.native._req(91, encoded, id), false);
2656
3260
  }
2657
3261
  reqQrySpbmInterParameter(req = {}) {
2658
- return this.request((id) => this.native._req(92, this.encode(STRUCT_ID.QrySPBMInterParameter, req), id), false);
3262
+ let encoded;
3263
+ try {
3264
+ encoded = this.encode(STRUCT_ID.QrySPBMInterParameter, req);
3265
+ } catch (error) {
3266
+ return Promise.reject(error);
3267
+ }
3268
+ return this.queryRequest((id) => this.native._req(92, encoded, id), false);
2659
3269
  }
2660
3270
  reqQrySpbmPortfDefinition(req = {}) {
2661
- return this.request((id) => this.native._req(93, this.encode(STRUCT_ID.QrySPBMPortfDefinition, req), id), false);
3271
+ let encoded;
3272
+ try {
3273
+ encoded = this.encode(STRUCT_ID.QrySPBMPortfDefinition, req);
3274
+ } catch (error) {
3275
+ return Promise.reject(error);
3276
+ }
3277
+ return this.queryRequest((id) => this.native._req(93, encoded, id), false);
2662
3278
  }
2663
3279
  reqQrySpbmInvestorPortfDef(req = {}) {
2664
- return this.request((id) => this.native._req(94, this.encode(STRUCT_ID.QrySPBMInvestorPortfDef, req), id), false);
3280
+ let encoded;
3281
+ try {
3282
+ encoded = this.encode(STRUCT_ID.QrySPBMInvestorPortfDef, req);
3283
+ } catch (error) {
3284
+ return Promise.reject(error);
3285
+ }
3286
+ return this.queryRequest((id) => this.native._req(94, encoded, id), false);
2665
3287
  }
2666
3288
  reqQryInvestorPortfMarginRatio(req = {}) {
2667
- return this.request((id) => this.native._req(95, this.encode(STRUCT_ID.QryInvestorPortfMarginRatio, req), id), false);
3289
+ let encoded;
3290
+ try {
3291
+ encoded = this.encode(STRUCT_ID.QryInvestorPortfMarginRatio, req);
3292
+ } catch (error) {
3293
+ return Promise.reject(error);
3294
+ }
3295
+ return this.queryRequest((id) => this.native._req(95, encoded, id), false);
2668
3296
  }
2669
3297
  reqQryInvestorProdSpbmDetail(req = {}) {
2670
- return this.request((id) => this.native._req(96, this.encode(STRUCT_ID.QryInvestorProdSPBMDetail, req), id), false);
3298
+ let encoded;
3299
+ try {
3300
+ encoded = this.encode(STRUCT_ID.QryInvestorProdSPBMDetail, req);
3301
+ } catch (error) {
3302
+ return Promise.reject(error);
3303
+ }
3304
+ return this.queryRequest((id) => this.native._req(96, encoded, id), false);
2671
3305
  }
2672
3306
  reqQryInvestorCommoditySpmmMargin(req = {}) {
2673
- return this.request((id) => this.native._req(97, this.encode(STRUCT_ID.QryInvestorCommoditySPMMMargin, req), id), false);
3307
+ let encoded;
3308
+ try {
3309
+ encoded = this.encode(STRUCT_ID.QryInvestorCommoditySPMMMargin, req);
3310
+ } catch (error) {
3311
+ return Promise.reject(error);
3312
+ }
3313
+ return this.queryRequest((id) => this.native._req(97, encoded, id), false);
2674
3314
  }
2675
3315
  reqQryInvestorCommodityGroupSpmmMargin(req = {}) {
2676
- return this.request((id) => this.native._req(98, this.encode(STRUCT_ID.QryInvestorCommodityGroupSPMMMargin, req), id), false);
3316
+ let encoded;
3317
+ try {
3318
+ encoded = this.encode(STRUCT_ID.QryInvestorCommodityGroupSPMMMargin, req);
3319
+ } catch (error) {
3320
+ return Promise.reject(error);
3321
+ }
3322
+ return this.queryRequest((id) => this.native._req(98, encoded, id), false);
2677
3323
  }
2678
3324
  reqQrySpmmInstParam(req = {}) {
2679
- return this.request((id) => this.native._req(99, this.encode(STRUCT_ID.QrySPMMInstParam, req), id), false);
3325
+ let encoded;
3326
+ try {
3327
+ encoded = this.encode(STRUCT_ID.QrySPMMInstParam, req);
3328
+ } catch (error) {
3329
+ return Promise.reject(error);
3330
+ }
3331
+ return this.queryRequest((id) => this.native._req(99, encoded, id), false);
2680
3332
  }
2681
3333
  reqQrySpmmProductParam(req = {}) {
2682
- return this.request((id) => this.native._req(100, this.encode(STRUCT_ID.QrySPMMProductParam, req), id), false);
3334
+ let encoded;
3335
+ try {
3336
+ encoded = this.encode(STRUCT_ID.QrySPMMProductParam, req);
3337
+ } catch (error) {
3338
+ return Promise.reject(error);
3339
+ }
3340
+ return this.queryRequest((id) => this.native._req(100, encoded, id), false);
2683
3341
  }
2684
3342
  reqQrySpbmAddOnInterParameter(req = {}) {
2685
- return this.request((id) => this.native._req(101, this.encode(STRUCT_ID.QrySPBMAddOnInterParameter, req), id), false);
3343
+ let encoded;
3344
+ try {
3345
+ encoded = this.encode(STRUCT_ID.QrySPBMAddOnInterParameter, req);
3346
+ } catch (error) {
3347
+ return Promise.reject(error);
3348
+ }
3349
+ return this.queryRequest((id) => this.native._req(101, encoded, id), false);
2686
3350
  }
2687
3351
  reqQryRcamsCombProductInfo(req = {}) {
2688
- return this.request((id) => this.native._req(102, this.encode(STRUCT_ID.QryRCAMSCombProductInfo, req), id), false);
3352
+ let encoded;
3353
+ try {
3354
+ encoded = this.encode(STRUCT_ID.QryRCAMSCombProductInfo, req);
3355
+ } catch (error) {
3356
+ return Promise.reject(error);
3357
+ }
3358
+ return this.queryRequest((id) => this.native._req(102, encoded, id), false);
2689
3359
  }
2690
3360
  reqQryRcamsInstrParameter(req = {}) {
2691
- return this.request((id) => this.native._req(103, this.encode(STRUCT_ID.QryRCAMSInstrParameter, req), id), false);
3361
+ let encoded;
3362
+ try {
3363
+ encoded = this.encode(STRUCT_ID.QryRCAMSInstrParameter, req);
3364
+ } catch (error) {
3365
+ return Promise.reject(error);
3366
+ }
3367
+ return this.queryRequest((id) => this.native._req(103, encoded, id), false);
2692
3368
  }
2693
3369
  reqQryRcamsIntraParameter(req = {}) {
2694
- return this.request((id) => this.native._req(104, this.encode(STRUCT_ID.QryRCAMSIntraParameter, req), id), false);
3370
+ let encoded;
3371
+ try {
3372
+ encoded = this.encode(STRUCT_ID.QryRCAMSIntraParameter, req);
3373
+ } catch (error) {
3374
+ return Promise.reject(error);
3375
+ }
3376
+ return this.queryRequest((id) => this.native._req(104, encoded, id), false);
2695
3377
  }
2696
3378
  reqQryRcamsInterParameter(req = {}) {
2697
- return this.request((id) => this.native._req(105, this.encode(STRUCT_ID.QryRCAMSInterParameter, req), id), false);
3379
+ let encoded;
3380
+ try {
3381
+ encoded = this.encode(STRUCT_ID.QryRCAMSInterParameter, req);
3382
+ } catch (error) {
3383
+ return Promise.reject(error);
3384
+ }
3385
+ return this.queryRequest((id) => this.native._req(105, encoded, id), false);
2698
3386
  }
2699
3387
  reqQryRcamsShortOptAdjustParam(req = {}) {
2700
- return this.request((id) => this.native._req(106, this.encode(STRUCT_ID.QryRCAMSShortOptAdjustParam, req), id), false);
3388
+ let encoded;
3389
+ try {
3390
+ encoded = this.encode(STRUCT_ID.QryRCAMSShortOptAdjustParam, req);
3391
+ } catch (error) {
3392
+ return Promise.reject(error);
3393
+ }
3394
+ return this.queryRequest((id) => this.native._req(106, encoded, id), false);
2701
3395
  }
2702
3396
  reqQryRcamsInvestorCombPosition(req = {}) {
2703
- return this.request((id) => this.native._req(107, this.encode(STRUCT_ID.QryRCAMSInvestorCombPosition, req), id), false);
3397
+ let encoded;
3398
+ try {
3399
+ encoded = this.encode(STRUCT_ID.QryRCAMSInvestorCombPosition, req);
3400
+ } catch (error) {
3401
+ return Promise.reject(error);
3402
+ }
3403
+ return this.queryRequest((id) => this.native._req(107, encoded, id), false);
2704
3404
  }
2705
3405
  reqQryInvestorProdRcamsMargin(req = {}) {
2706
- return this.request((id) => this.native._req(108, this.encode(STRUCT_ID.QryInvestorProdRCAMSMargin, req), id), false);
3406
+ let encoded;
3407
+ try {
3408
+ encoded = this.encode(STRUCT_ID.QryInvestorProdRCAMSMargin, req);
3409
+ } catch (error) {
3410
+ return Promise.reject(error);
3411
+ }
3412
+ return this.queryRequest((id) => this.native._req(108, encoded, id), false);
2707
3413
  }
2708
3414
  reqQryRuleInstrParameter(req = {}) {
2709
- return this.request((id) => this.native._req(109, this.encode(STRUCT_ID.QryRULEInstrParameter, req), id), false);
3415
+ let encoded;
3416
+ try {
3417
+ encoded = this.encode(STRUCT_ID.QryRULEInstrParameter, req);
3418
+ } catch (error) {
3419
+ return Promise.reject(error);
3420
+ }
3421
+ return this.queryRequest((id) => this.native._req(109, encoded, id), false);
2710
3422
  }
2711
3423
  reqQryRuleIntraParameter(req = {}) {
2712
- return this.request((id) => this.native._req(110, this.encode(STRUCT_ID.QryRULEIntraParameter, req), id), false);
3424
+ let encoded;
3425
+ try {
3426
+ encoded = this.encode(STRUCT_ID.QryRULEIntraParameter, req);
3427
+ } catch (error) {
3428
+ return Promise.reject(error);
3429
+ }
3430
+ return this.queryRequest((id) => this.native._req(110, encoded, id), false);
2713
3431
  }
2714
3432
  reqQryRuleInterParameter(req = {}) {
2715
- return this.request((id) => this.native._req(111, this.encode(STRUCT_ID.QryRULEInterParameter, req), id), false);
3433
+ let encoded;
3434
+ try {
3435
+ encoded = this.encode(STRUCT_ID.QryRULEInterParameter, req);
3436
+ } catch (error) {
3437
+ return Promise.reject(error);
3438
+ }
3439
+ return this.queryRequest((id) => this.native._req(111, encoded, id), false);
2716
3440
  }
2717
3441
  reqQryInvestorProdRuleMargin(req = {}) {
2718
- return this.request((id) => this.native._req(112, this.encode(STRUCT_ID.QryInvestorProdRULEMargin, req), id), false);
3442
+ let encoded;
3443
+ try {
3444
+ encoded = this.encode(STRUCT_ID.QryInvestorProdRULEMargin, req);
3445
+ } catch (error) {
3446
+ return Promise.reject(error);
3447
+ }
3448
+ return this.queryRequest((id) => this.native._req(112, encoded, id), false);
2719
3449
  }
2720
3450
  reqQryInvestorPortfSetting(req = {}) {
2721
- return this.request((id) => this.native._req(113, this.encode(STRUCT_ID.QryInvestorPortfSetting, req), id), false);
3451
+ let encoded;
3452
+ try {
3453
+ encoded = this.encode(STRUCT_ID.QryInvestorPortfSetting, req);
3454
+ } catch (error) {
3455
+ return Promise.reject(error);
3456
+ }
3457
+ return this.queryRequest((id) => this.native._req(113, encoded, id), false);
2722
3458
  }
2723
3459
  reqQryInvestorInfoCommRec(req = {}) {
2724
- return this.request((id) => this.native._req(114, this.encode(STRUCT_ID.QryInvestorInfoCommRec, req), id), false);
3460
+ let encoded;
3461
+ try {
3462
+ encoded = this.encode(STRUCT_ID.QryInvestorInfoCommRec, req);
3463
+ } catch (error) {
3464
+ return Promise.reject(error);
3465
+ }
3466
+ return this.queryRequest((id) => this.native._req(114, encoded, id), false);
2725
3467
  }
2726
3468
  reqQryCombLeg(req = {}) {
2727
- return this.request((id) => this.native._req(115, this.encode(STRUCT_ID.QryCombLeg, req), id), false);
3469
+ let encoded;
3470
+ try {
3471
+ encoded = this.encode(STRUCT_ID.QryCombLeg, req);
3472
+ } catch (error) {
3473
+ return Promise.reject(error);
3474
+ }
3475
+ return this.queryRequest((id) => this.native._req(115, encoded, id), false);
2728
3476
  }
2729
3477
  reqOffsetSetting(req = {}) {
2730
3478
  return this.request((id) => this.native._req(116, this.encode(STRUCT_ID.InputOffsetSetting, req), id), true);
@@ -2733,7 +3481,13 @@ var TraderBase = class extends CtpClient {
2733
3481
  return this.request((id) => this.native._req(117, this.encode(STRUCT_ID.InputOffsetSetting, req), id), true);
2734
3482
  }
2735
3483
  reqQryOffsetSetting(req = {}) {
2736
- return this.request((id) => this.native._req(118, this.encode(STRUCT_ID.QryOffsetSetting, req), id), false);
3484
+ let encoded;
3485
+ try {
3486
+ encoded = this.encode(STRUCT_ID.QryOffsetSetting, req);
3487
+ } catch (error) {
3488
+ return Promise.reject(error);
3489
+ }
3490
+ return this.queryRequest((id) => this.native._req(118, encoded, id), false);
2737
3491
  }
2738
3492
  reqGenSmsCode(req = {}) {
2739
3493
  return this.request((id) => this.native._req(119, this.encode(STRUCT_ID.ReqGenSMSCode, req), id), true);
@@ -2745,7 +3499,13 @@ var TraderBase = class extends CtpClient {
2745
3499
  return this.request((id) => this.native._req(121, this.encode(STRUCT_ID.InputSpdApplyAction, req), id), true);
2746
3500
  }
2747
3501
  reqQrySpdApply(req = {}) {
2748
- return this.request((id) => this.native._req(122, this.encode(STRUCT_ID.QrySpdApply, req), id), false);
3502
+ let encoded;
3503
+ try {
3504
+ encoded = this.encode(STRUCT_ID.QrySpdApply, req);
3505
+ } catch (error) {
3506
+ return Promise.reject(error);
3507
+ }
3508
+ return this.queryRequest((id) => this.native._req(122, encoded, id), false);
2749
3509
  }
2750
3510
  reqHedgeCfm(req = {}) {
2751
3511
  return this.request((id) => this.native._req(123, this.encode(STRUCT_ID.InputHedgeCfm, req), id), true);
@@ -2754,67 +3514,248 @@ var TraderBase = class extends CtpClient {
2754
3514
  return this.request((id) => this.native._req(124, this.encode(STRUCT_ID.InputHedgeCfmAction, req), id), true);
2755
3515
  }
2756
3516
  reqQryHedgeCfm(req = {}) {
2757
- return this.request((id) => this.native._req(125, this.encode(STRUCT_ID.QryHedgeCfm, req), id), false);
3517
+ let encoded;
3518
+ try {
3519
+ encoded = this.encode(STRUCT_ID.QryHedgeCfm, req);
3520
+ } catch (error) {
3521
+ return Promise.reject(error);
3522
+ }
3523
+ return this.queryRequest((id) => this.native._req(125, encoded, id), false);
2758
3524
  }
2759
3525
  };
2760
3526
 
2761
3527
  // dist/trader.js
2762
3528
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
2763
3529
  function assertFiniteLimit(name, v) {
2764
- if (v !== void 0 && !Number.isFinite(v)) {
2765
- throw new TypeError(`${name} must be a finite number (got ${v})`);
3530
+ if (v !== void 0 && (!Number.isFinite(v) || v < 0)) {
3531
+ throw new TypeError(`${name} must be a non-negative finite number (got ${v})`);
2766
3532
  }
2767
3533
  }
3534
+ function assertPositiveInt32OrDisabled(name, v) {
3535
+ assertFiniteLimit(name, v);
3536
+ if (v !== void 0 && v > 0 && (!Number.isInteger(v) || v > 2147483647)) {
3537
+ throw new TypeError(`${name} must be an integer in 1..2147483647 (got ${v})`);
3538
+ }
3539
+ }
3540
+ function assertLotLimit(name, v) {
3541
+ assertFiniteLimit(name, v);
3542
+ if (v !== void 0 && v > 0 && (!Number.isInteger(v) || v > 2147483647)) {
3543
+ throw new TypeError(`${name} must be an integer in 1..2147483647 lots`);
3544
+ }
3545
+ }
3546
+ function assertInstrumentId(name, instrumentId) {
3547
+ if (typeof instrumentId !== "string" || !instrumentId || instrumentId.includes("\0"))
3548
+ throw new TypeError(`${name}: instrumentId must be non-empty and contain no NUL`);
3549
+ }
3550
+ var RISK_LIMIT_KEYS = /* @__PURE__ */ new Set([
3551
+ "maxOrderVolume",
3552
+ "maxPriceDeviation",
3553
+ "maxNotional",
3554
+ "maxOrdersPerSec",
3555
+ "orderBurst",
3556
+ "maxCloseOrdersPerSec",
3557
+ "closeOrderBurst",
3558
+ "maxReferenceAgeMs",
3559
+ "maxAccountMargin"
3560
+ ]);
3561
+ function assertObjectKeys(value, label, allowed) {
3562
+ for (const key of ownStringKeys(value, label))
3563
+ if (!allowed.has(key))
3564
+ throw new TypeError(`${label}: unknown field ${key}`);
3565
+ }
3566
+ var SESSION_KEYS = /* @__PURE__ */ new Set([
3567
+ "brokerId",
3568
+ "userId",
3569
+ "investorId",
3570
+ "password",
3571
+ "appId",
3572
+ "authCode",
3573
+ "confirmSettlement",
3574
+ "sync"
3575
+ ]);
3576
+ var SESSION_SYNC_KEYS = /* @__PURE__ */ new Set(["multipliers", "marginRates", "positions", "orders"]);
3577
+ var ARM_SPEC_KEYS = /* @__PURE__ */ new Set(["instrumentId", "side", "triggerPrice", "order"]);
3578
+ var POSITION_LIMIT_KEYS = /* @__PURE__ */ new Set(["long", "short"]);
3579
+ var POSITION_SEED_KEYS = /* @__PURE__ */ new Set([
3580
+ "instrumentId",
3581
+ "side",
3582
+ "hedgeFlag",
3583
+ "volume",
3584
+ "margin"
3585
+ ]);
2768
3586
  var Trader = class extends TraderBase {
2769
3587
  broker;
2770
3588
  investor;
2771
3589
  orderRefSeq = 0;
2772
3590
  constructor(flowPath, fronts) {
2773
- super(new native.Trader(flowPath, fronts), native.__layoutData(), TRADER_EVENTS);
2774
- this.on("rsp-user-login", (d) => {
2775
- const r = d;
2776
- if (r) {
2777
- this.broker = r.brokerId;
2778
- this.investor = r.userId;
2779
- const mx = r.maxOrderRef ? parseInt(r.maxOrderRef, 10) : NaN;
2780
- if (Number.isFinite(mx) && mx > this.orderRefSeq)
2781
- this.orderRefSeq = mx;
2782
- }
2783
- });
3591
+ super(new native.Trader(flowPath, copyOwnFronts(fronts, "Trader fronts")), native.__layoutData(), TRADER_EVENTS);
3592
+ const clearConfirmedIdentity = () => {
3593
+ this.broker = void 0;
3594
+ this.investor = void 0;
3595
+ };
3596
+ this.on("front-connected", clearConfirmedIdentity);
3597
+ this.on("front-disconnected", clearConfirmedIdentity);
2784
3598
  this.start();
2785
3599
  }
2786
- getApiVersion() {
2787
- return this.native.getApiVersion();
3600
+ /** A raw login Promise may resolve only with a structurally usable session.
3601
+ * Account confirmation itself happens in session(), after request-vs-response
3602
+ * identity validation; merely observing a protocol event never grants order
3603
+ * authority. */
3604
+ onRequestResolved(eventName, value, _options) {
3605
+ if (eventName === "rsp-user-logout") {
3606
+ this.broker = void 0;
3607
+ this.investor = void 0;
3608
+ return;
3609
+ }
3610
+ if (eventName !== "rsp-user-login")
3611
+ return;
3612
+ const r = value;
3613
+ if (!r)
3614
+ return;
3615
+ if (typeof r.brokerId === "string" && r.brokerId && typeof r.userId === "string" && r.userId && Number.isInteger(r.frontId) && Number(r.frontId) > 0 && Number.isInteger(r.sessionId) && Number(r.sessionId) > 0) {
3616
+ this.broker = r.brokerId;
3617
+ this.investor = r.userId;
3618
+ }
3619
+ const maxOrderRef = typeof r.maxOrderRef === "string" ? r.maxOrderRef.trim() : "";
3620
+ if (/^\d{1,12}$/.test(maxOrderRef)) {
3621
+ const maxRef = Number(maxOrderRef);
3622
+ if (Number.isFinite(maxRef) && maxRef > this.orderRefSeq)
3623
+ this.orderRefSeq = maxRef;
3624
+ }
3625
+ }
3626
+ /** Generated login/logout methods call this only after their request has
3627
+ * encoded successfully. Revoke the confirmed JS account at that same atomic
3628
+ * transition boundary, so a concurrent sync helper cannot start with the old
3629
+ * identity while native risk state is already fail-closed for the new session. */
3630
+ beginRequestContextTransition(reason) {
3631
+ this.broker = void 0;
3632
+ this.investor = void 0;
3633
+ super.beginRequestContextTransition(reason);
3634
+ }
3635
+ shouldTimeoutRequest(requestId, sessionTransition) {
3636
+ if (!sessionTransition)
3637
+ return true;
3638
+ return this.native._timeoutSessionTransition(requestId);
3639
+ }
3640
+ get apiVersion() {
3641
+ return this.native.apiVersion();
2788
3642
  }
2789
- getTradingDay() {
2790
- return this.native.getTradingDay();
3643
+ get tradingDay() {
3644
+ return this.native.tradingDay();
2791
3645
  }
2792
3646
  /**
2793
3647
  * One-call post-connect handshake. Call it from the `front-connected` handler
2794
3648
  * (and again after a reconnect): authenticate (if appId/authCode given) →
2795
- * login → confirm settlement → sync multipliers / positions / orders. Each
3649
+ * login → confirm settlement → sync multipliers / margin rates / orders /
3650
+ * positions. Each
2796
3651
  * step just wraps the matching req / sync method, so you can hand-roll your
2797
3652
  * own flow instead when you need finer control. Returns the row counts from
2798
3653
  * the sync steps. Must run on a connected front (queries need the session up).
2799
3654
  */
2800
3655
  async session(opts) {
2801
- const { brokerId, userId, password, appId, authCode } = opts;
3656
+ assertObjectKeys(opts, "session options", SESSION_KEYS);
3657
+ const cleanOpts = copyOwnRecord(opts, "session options");
3658
+ const { brokerId, userId, password, appId, authCode } = cleanOpts;
3659
+ const investorId = cleanOpts.investorId ?? userId;
3660
+ if (typeof brokerId !== "string" || !brokerId || brokerId.includes("\0") || typeof userId !== "string" || !userId || userId.includes("\0") || typeof password !== "string" || !password || password.includes("\0")) {
3661
+ throw new TypeError("session requires brokerId, userId and password");
3662
+ }
3663
+ if (typeof investorId !== "string" || !investorId || investorId.includes("\0"))
3664
+ throw new TypeError("session investorId must be a non-empty string");
3665
+ if (cleanOpts.confirmSettlement !== void 0 && typeof cleanOpts.confirmSettlement !== "boolean")
3666
+ throw new TypeError("session.confirmSettlement must be boolean");
3667
+ if (appId === void 0 !== (authCode === void 0)) {
3668
+ throw new TypeError("session appId and authCode must be supplied together");
3669
+ }
3670
+ if (appId !== void 0 && (typeof appId !== "string" || !appId || appId.includes("\0") || typeof authCode !== "string" || !authCode || authCode.includes("\0")))
3671
+ throw new TypeError("session appId and authCode must be non-empty strings");
3672
+ let cleanSync = {};
3673
+ if (cleanOpts.sync !== void 0) {
3674
+ assertObjectKeys(cleanOpts.sync, "session.sync", SESSION_SYNC_KEYS);
3675
+ cleanSync = copyOwnRecord(cleanOpts.sync, "session.sync");
3676
+ const { multipliers, marginRates, positions, orders } = cleanSync;
3677
+ if (multipliers !== void 0 && typeof multipliers !== "boolean")
3678
+ cleanSync.multipliers = copyDenseStringArray(multipliers, "session.sync.multipliers");
3679
+ if (marginRates !== void 0)
3680
+ cleanSync.marginRates = copyDenseStringArray(marginRates, "session.sync.marginRates");
3681
+ if (positions !== void 0 && typeof positions !== "boolean")
3682
+ throw new TypeError("session.sync.positions must be boolean");
3683
+ if (orders !== void 0 && typeof orders !== "boolean")
3684
+ throw new TypeError("session.sync.orders must be boolean");
3685
+ }
3686
+ if (appId !== void 0 && authCode !== void 0)
3687
+ this.encode(STRUCT_ID.ReqAuthenticate, { brokerId, userId, appId, authCode });
3688
+ this.encode(STRUCT_ID.ReqUserLogin, { brokerId, userId, password });
3689
+ const encodedAccount = this.encode(STRUCT_ID.SettlementInfoConfirm, { brokerId, investorId });
3690
+ this.native._beginSessionHandshake();
3691
+ this.invalidateRequestContext("trader session started");
3692
+ let contextToken = this.requestContextToken();
3693
+ this.broker = void 0;
3694
+ this.investor = void 0;
3695
+ this.native._markPositionLedgerUncertain();
3696
+ this.native._markOrderLedgerUncertain();
2802
3697
  if (appId !== void 0 && authCode !== void 0) {
2803
3698
  await this.reqAuthenticate({ brokerId, userId, appId, authCode });
3699
+ this.assertRequestContext(contextToken, "trader session authentication");
3700
+ }
3701
+ const beforeLoginContext = this.requestContextToken();
3702
+ const beforeLoginTransition = this.requestTransitionToken();
3703
+ const loginRequest = this.reqUserLogin({ brokerId, userId, password });
3704
+ const afterLoginContext = this.requestContextToken();
3705
+ const afterLoginTransition = this.requestTransitionToken();
3706
+ if (afterLoginTransition === beforeLoginTransition + 1 && afterLoginContext === beforeLoginContext + 1) {
3707
+ contextToken = afterLoginContext;
3708
+ } else if (afterLoginTransition === beforeLoginTransition) {
3709
+ contextToken = beforeLoginContext;
3710
+ } else {
3711
+ try {
3712
+ await loginRequest;
3713
+ } catch {
3714
+ }
3715
+ throw new Error("trader session login crossed multiple context transitions");
3716
+ }
3717
+ const login = await loginRequest;
3718
+ this.assertRequestContext(contextToken, "trader session login");
3719
+ if (!login || !Number.isInteger(login.frontId) || login.frontId <= 0 || !Number.isInteger(login.sessionId) || login.sessionId <= 0 || login.brokerId !== brokerId || login.userId !== userId) {
3720
+ this.broker = void 0;
3721
+ this.investor = void 0;
3722
+ throw new Error("trader login response has missing or mismatched session identity");
3723
+ }
3724
+ const confirmed = this.native._confirmSessionAccount(login.frontId, login.sessionId, encodedAccount);
3725
+ if (!confirmed) {
3726
+ this.broker = void 0;
3727
+ this.investor = void 0;
3728
+ throw new Error("native Trader session/account confirmation failed");
2804
3729
  }
2805
- await this.reqUserLogin({ brokerId, userId, password });
2806
- if (opts.confirmSettlement ?? true) {
2807
- await this.reqSettlementInfoConfirm({ brokerId, investorId: userId });
3730
+ this.broker = brokerId;
3731
+ this.investor = investorId;
3732
+ const maxOrderRef = typeof login.maxOrderRef === "string" ? login.maxOrderRef.trim() : "";
3733
+ const maxRef = /^\d{1,12}$/.test(maxOrderRef) ? Number(maxOrderRef) : NaN;
3734
+ if (Number.isFinite(maxRef) && maxRef > this.orderRefSeq)
3735
+ this.orderRefSeq = maxRef;
3736
+ if (cleanOpts.confirmSettlement ?? true) {
3737
+ await this.reqSettlementInfoConfirm({ brokerId, investorId });
3738
+ this.assertRequestContext(contextToken, "trader session settlement confirmation");
2808
3739
  }
2809
- const sync = opts.sync ?? {};
3740
+ const sync = cleanSync;
2810
3741
  const mul = sync.multipliers ?? true;
2811
- const result = { multipliers: 0, positions: 0, orders: 0 };
2812
- if (mul)
3742
+ const result = { multipliers: 0, marginRates: 0, positions: 0, orders: 0 };
3743
+ if (mul) {
2813
3744
  result.multipliers = await this.syncMultipliers(Array.isArray(mul) ? mul : void 0);
2814
- if (sync.positions ?? true)
2815
- result.positions = await this.syncPositions();
2816
- if (sync.orders ?? true)
3745
+ this.assertRequestContext(contextToken, "trader session multiplier sync");
3746
+ }
3747
+ if (sync.marginRates?.length) {
3748
+ result.marginRates = await this.syncMarginRates(sync.marginRates);
3749
+ this.assertRequestContext(contextToken, "trader session margin sync");
3750
+ }
3751
+ if (sync.orders ?? true) {
2817
3752
  result.orders = await this.syncOrders();
3753
+ this.assertRequestContext(contextToken, "trader session order sync");
3754
+ }
3755
+ if (sync.positions ?? true) {
3756
+ result.positions = await this.syncPositions();
3757
+ this.assertRequestContext(contextToken, "trader session position sync");
3758
+ }
2818
3759
  return result;
2819
3760
  }
2820
3761
  /** Assign a unique numeric OrderRef when the caller left it blank. CTP treats
@@ -2822,10 +3763,80 @@ var Trader = class extends TraderBase {
2822
3763
  * ref with "不允许重复报单", so an unset ref would otherwise collide. */
2823
3764
  withAutoOrderRef(order) {
2824
3765
  if (order.orderRef === void 0 || order.orderRef === "") {
2825
- return { ...order, orderRef: String(++this.orderRefSeq) };
3766
+ if (this.orderRefSeq >= 999999999999) {
3767
+ throw new RangeError("OrderRef space exhausted for this process/session");
3768
+ }
3769
+ return { ...order, orderRef: String(this.orderRefSeq + 1) };
3770
+ }
3771
+ if (typeof order.orderRef !== "string" || !/^\d{1,12}$/.test(order.orderRef)) {
3772
+ throw new TypeError("orderRef must contain 1..12 decimal digits");
3773
+ }
3774
+ const explicit = Number(order.orderRef);
3775
+ if (explicit <= this.orderRefSeq) {
3776
+ throw new RangeError(`explicit orderRef must be greater than the current high-water mark ${this.orderRefSeq}`);
2826
3777
  }
2827
3778
  return order;
2828
3779
  }
3780
+ commitOrderRef(order) {
3781
+ this.orderRefSeq = Number(order.orderRef);
3782
+ }
3783
+ validateOrder(order, context) {
3784
+ const clean = copyOwnRecord(order, context);
3785
+ if (!this.broker || !this.investor) {
3786
+ throw new Error(`${context}: a confirmed Trader login is required`);
3787
+ }
3788
+ if (typeof clean.instrumentId !== "string" || !clean.instrumentId || clean.instrumentId.includes("\0") || clean.direction !== "0" && clean.direction !== "1") {
3789
+ throw new TypeError(`${context}: instrumentId and direction ("0"/"1") are required`);
3790
+ }
3791
+ if (typeof clean.combOffsetFlag !== "string" || !/^[0-6]$/.test(clean.combOffsetFlag)) {
3792
+ throw new TypeError(`${context}: combOffsetFlag must be one CTP offset digit 0..6; multi-leg orders are unsupported`);
3793
+ }
3794
+ if (clean.combHedgeFlag !== void 0 && (typeof clean.combHedgeFlag !== "string" || !/^[123567]$/.test(clean.combHedgeFlag))) {
3795
+ throw new TypeError(`${context}: combHedgeFlag must be one CTP hedge digit (1, 2, 3, 5, 6 or 7)`);
3796
+ }
3797
+ if (!Number.isInteger(clean.volumeTotalOriginal) || !(Number(clean.volumeTotalOriginal) > 0) || Number(clean.volumeTotalOriginal) > 2147483647) {
3798
+ throw new TypeError(`${context}: volumeTotalOriginal must be a positive int32`);
3799
+ }
3800
+ if (!Number.isFinite(clean.limitPrice) || !(Number(clean.limitPrice) > 0) || Number(clean.limitPrice) >= 1e300) {
3801
+ throw new TypeError(`${context}: limitPrice must be a positive finite price`);
3802
+ }
3803
+ if (clean.brokerId !== void 0 && clean.brokerId !== this.broker) {
3804
+ throw new TypeError(`${context}: brokerId must match the confirmed login`);
3805
+ }
3806
+ if (clean.investorId !== void 0 && clean.investorId !== this.investor) {
3807
+ throw new TypeError(`${context}: investorId must match the confirmed login`);
3808
+ }
3809
+ const value = (key, fallback) => clean[key] === void 0 ? fallback : clean[key];
3810
+ const empty = (v) => v === void 0 || v === "";
3811
+ if (value("orderPriceType", "2") !== "2" || value("timeCondition", "3") !== "3" || !empty(clean.gtdDate) || value("volumeCondition", "1") !== "1" || value("minVolume", 1) !== 1 || value("contingentCondition", "1") !== "1" || value("stopPrice", 0) !== 0 || value("forceCloseReason", "0") !== "0" || value("isAutoSuspend", 0) !== 0 || !empty(clean.businessUnit) || value("requestId", 0) !== 0 || value("userForceClose", 0) !== 0 || value("isSwapOrder", 0) !== 0 || !empty(clean.exchangeId) || !empty(clean.investUnitId) || !empty(clean.accountId) || !empty(clean.currencyId) || !empty(clean.clientId) || value("sessionReqSeq", 0) !== 0) {
3812
+ throw new TypeError(`${context}: only an immediate single-instrument GFD limit order is supported`);
3813
+ }
3814
+ return {
3815
+ ...clean,
3816
+ orderPriceType: "2",
3817
+ combHedgeFlag: clean.combHedgeFlag ?? "1",
3818
+ timeCondition: "3",
3819
+ gtdDate: "",
3820
+ volumeCondition: "1",
3821
+ minVolume: 1,
3822
+ contingentCondition: "1",
3823
+ stopPrice: 0,
3824
+ forceCloseReason: "0",
3825
+ isAutoSuspend: 0,
3826
+ businessUnit: "",
3827
+ requestId: 0,
3828
+ userForceClose: 0,
3829
+ isSwapOrder: 0,
3830
+ exchangeId: "",
3831
+ investUnitId: "",
3832
+ accountId: "",
3833
+ currencyId: "",
3834
+ clientId: "",
3835
+ sessionReqSeq: 0,
3836
+ brokerId: this.broker,
3837
+ investorId: this.investor
3838
+ };
3839
+ }
2829
3840
  /**
2830
3841
  * Insert an order through the C++ pre-trade risk gate. Resolves on submission:
2831
3842
  * CTP sends no success acknowledgement for an accepted order - only
@@ -2835,31 +3846,50 @@ var Trader = class extends TraderBase {
2835
3846
  * unique numeric value automatically.
2836
3847
  */
2837
3848
  reqOrderInsert(req = {}) {
2838
- return super.reqOrderInsert(this.withAutoOrderRef(req));
3849
+ const order = this.withAutoOrderRef(this.validateOrder(req, "reqOrderInsert"));
3850
+ this.encode(STRUCT_ID.InputOrder, order);
3851
+ const result = super.reqOrderInsert(order);
3852
+ this.commitOrderRef(order);
3853
+ return result;
2839
3854
  }
2840
3855
  /** Publish pre-trade risk limits to the C++ enforcer (takes effect at once). */
2841
- riskSet(config) {
2842
- assertFiniteLimit("riskSet.maxOrderVolume", config.maxOrderVolume);
2843
- assertFiniteLimit("riskSet.maxPriceDeviation", config.maxPriceDeviation);
2844
- assertFiniteLimit("riskSet.maxNotional", config.maxNotional);
2845
- assertFiniteLimit("riskSet.maxOrdersPerSec", config.maxOrdersPerSec);
2846
- assertFiniteLimit("riskSet.orderBurst", config.orderBurst);
2847
- assertFiniteLimit("riskSet.maxPositionCost", config.maxPositionCost);
2848
- assertFiniteLimit("riskSet.maxMargin", config.maxMargin);
2849
- this.native.riskSet(config);
3856
+ setRiskLimits(config) {
3857
+ const clean = copyOwnRecord(config, "setRiskLimits");
3858
+ for (const key of ownStringKeys(clean, "setRiskLimits")) {
3859
+ if (!RISK_LIMIT_KEYS.has(key))
3860
+ throw new TypeError(`setRiskLimits: unknown field ${key}`);
3861
+ }
3862
+ assertPositiveInt32OrDisabled("setRiskLimits.maxOrderVolume", clean.maxOrderVolume);
3863
+ assertFiniteLimit("setRiskLimits.maxPriceDeviation", clean.maxPriceDeviation);
3864
+ assertFiniteLimit("setRiskLimits.maxNotional", clean.maxNotional);
3865
+ assertFiniteLimit("setRiskLimits.maxOrdersPerSec", clean.maxOrdersPerSec);
3866
+ assertFiniteLimit("setRiskLimits.orderBurst", clean.orderBurst);
3867
+ assertFiniteLimit("setRiskLimits.maxCloseOrdersPerSec", clean.maxCloseOrdersPerSec);
3868
+ assertFiniteLimit("setRiskLimits.closeOrderBurst", clean.closeOrderBurst);
3869
+ assertFiniteLimit("setRiskLimits.maxAccountMargin", clean.maxAccountMargin);
3870
+ assertFiniteLimit("setRiskLimits.maxReferenceAgeMs", clean.maxReferenceAgeMs);
3871
+ if (clean.maxReferenceAgeMs !== void 0 && !(clean.maxReferenceAgeMs > 0)) {
3872
+ throw new TypeError("setRiskLimits.maxReferenceAgeMs must be > 0");
3873
+ }
3874
+ this.native.setRiskLimits(clean);
3875
+ return this;
3876
+ }
3877
+ /** Enter REDUCE_ONLY atomically at the final vendor-API send barrier. Armed
3878
+ * opens remain registered but cannot send until resume(). */
3879
+ reduceOnly() {
3880
+ this.native.riskReduceOnly();
2850
3881
  return this;
2851
3882
  }
2852
- /** Kill-switch: C++ immediately blocks every order-opening send that reaches
2853
- * the exchange at once — regular, exec, quote, for-quote, option-self-close
2854
- * and comb-action inserts. Cancels and other *actions* are deliberately left
2855
- * open so you can still pull working orders while halted; parked/staged orders
2856
- * (not sent to the exchange immediately) are likewise not gated. Takes effect
2857
- * at once; reverse with {@link resume}. */
2858
- halt() {
2859
- this.native.riskHalt();
3883
+ /** Enter HALT_ALL atomically: both opening and closing order inserts, advanced
3884
+ * mutations and bank/futures transfers are refused, and all existing armed
3885
+ * triggers are cleared. New arm() calls are rejected until resume().
3886
+ * Cancellation actions remain available so working
3887
+ * exchange orders can still be withdrawn. */
3888
+ haltAll() {
3889
+ this.native.riskHaltAll();
2860
3890
  return this;
2861
3891
  }
2862
- /** Release the kill-switch (see {@link halt}). */
3892
+ /** Return to NORMAL mode after reduceOnly() or haltAll(). */
2863
3893
  resume() {
2864
3894
  this.native.riskResume();
2865
3895
  return this;
@@ -2868,112 +3898,172 @@ var Trader = class extends TraderBase {
2868
3898
  * Wires the feed's C++ snapshot cache straight into this Trader's risk engine,
2869
3899
  * so the deviation check reads current prices in C++ on the order path (no JS
2870
3900
  * round-trip, and it also covers armed orders that fire with no JS in the loop).
2871
- * Without this, no reference is set and the deviation check is skipped. */
3901
+ * Without a fresh reference, an enabled deviation check fails closed. */
2872
3902
  trackMarketData(md) {
2873
3903
  this.native._attachSnapshot(md._snapshotExternal());
2874
3904
  return this;
2875
3905
  }
2876
3906
  // Contract multipliers (for cost accounting) and margin rates (for the
2877
- // maxMargin cap) are NOT fed from JS: the C++ risk engine sources them directly
3907
+ // maxAccountMargin cap) are NOT fed from JS: the C++ risk engine sources them directly
2878
3908
  // from CTP's OnRspQryInstrument / OnRspQryInstrumentMarginRate callbacks (see
2879
3909
  // scripts/codegen/generate-trader.mjs). So any reqQryInstrument keeps
2880
3910
  // multipliers current, and querying reqQryInstrumentMarginRate for the
2881
- // contracts you trade keeps the margin cap exact — no JS round-trip, and the
2882
- // checks also cover armed orders that fire from C++ with no JS in the loop.
3911
+ // syncMarginRates() loads investor plus exchange-base schedules. Missing
3912
+ // metadata fails closed; IsRelative is combined with the matching base.
2883
3913
  /**
2884
3914
  * Cap the open position (in lots) for one instrument, enforced in C++ on
2885
3915
  * every opening order. Pass a number to cap both sides at once, or
2886
3916
  * `{ long, short }` to cap each side separately. Within `{ long, short }`,
2887
3917
  * **omitting a side leaves that side's current cap unchanged** (on a re-call it
2888
- * is NOT reset to uncapped), and passing `<= 0` for a side removes its cap.
3918
+ * is NOT reset to uncapped), and passing `0` for a side removes its cap.
2889
3919
  * Long and short are always tracked independently.
2890
3920
  *
2891
- * The check is fill-based (counts confirmed position, like maxPositionCost),
2892
- * so rapid bursts of opens can momentarily overshoot before the fills land —
2893
- * size the cap with that in mind.
3921
+ * Held positions and in-flight working opens are counted atomically.
2894
3922
  *
2895
- * td.setMaxPosition("rb2610", 100); // long<=100 and short<=100
2896
- * td.setMaxPosition("ru2610", { long: 100, short: 20 });
3923
+ * td.setInstrumentPositionLimit("rb2610", 100);
3924
+ * td.setInstrumentPositionLimit("ru2610", { long: 100, short: 20 });
2897
3925
  */
2898
- setMaxPosition(instrumentId, max) {
2899
- if (typeof max === "number") {
2900
- assertFiniteLimit("setMaxPosition", max);
2901
- this.native.setMaxPositionVolume(instrumentId, true, max);
2902
- this.native.setMaxPositionVolume(instrumentId, false, max);
2903
- } else {
2904
- assertFiniteLimit("setMaxPosition.long", max.long);
2905
- assertFiniteLimit("setMaxPosition.short", max.short);
2906
- if (max.long !== void 0)
2907
- this.native.setMaxPositionVolume(instrumentId, true, max.long);
2908
- if (max.short !== void 0)
2909
- this.native.setMaxPositionVolume(instrumentId, false, max.short);
2910
- }
3926
+ setInstrumentPositionLimit(instrumentId, limit) {
3927
+ assertInstrumentId("setInstrumentPositionLimit", instrumentId);
3928
+ const row = this.normalizePositionLimit(instrumentId, limit);
3929
+ this.native._setInstrumentPositionLimits([row]);
2911
3930
  return this;
2912
3931
  }
2913
3932
  /** Cap several instruments at once, e.g.
2914
3933
  * `{ rb2610: 100, ru2610: { long: 100, short: 20 } }`. */
2915
- setMaxPositions(limits) {
2916
- for (const id of Object.keys(limits))
2917
- this.setMaxPosition(id, limits[id]);
3934
+ setInstrumentPositionLimits(limits) {
3935
+ const rows = ownStringKeys(limits, "setInstrumentPositionLimits").map((instrumentId) => {
3936
+ const limit = limits[instrumentId];
3937
+ assertInstrumentId("setInstrumentPositionLimits", instrumentId);
3938
+ return this.normalizePositionLimit(instrumentId, limit);
3939
+ });
3940
+ this.native._setInstrumentPositionLimits(rows);
2918
3941
  return this;
2919
3942
  }
3943
+ normalizePositionLimit(instrumentId, limit) {
3944
+ if (typeof limit === "number") {
3945
+ assertLotLimit("setInstrumentPositionLimit", limit);
3946
+ return copyOwnRecord({ instrumentId, long: limit, short: limit }, "setInstrumentPositionLimit");
3947
+ }
3948
+ assertPlainRecord(limit, "setInstrumentPositionLimit");
3949
+ const clean = copyOwnRecord(limit, "setInstrumentPositionLimit");
3950
+ if (clean.long === void 0 && clean.short === void 0) {
3951
+ throw new TypeError("setInstrumentPositionLimit requires a number or at least one of long/short");
3952
+ }
3953
+ for (const key of ownStringKeys(clean, "setInstrumentPositionLimit")) {
3954
+ if (!POSITION_LIMIT_KEYS.has(key))
3955
+ throw new TypeError(`setInstrumentPositionLimit: unknown field ${key}`);
3956
+ }
3957
+ assertLotLimit("setInstrumentPositionLimit.long", clean.long);
3958
+ assertLotLimit("setInstrumentPositionLimit.short", clean.short);
3959
+ return copyOwnRecord({ instrumentId, long: clean.long, short: clean.short }, "setInstrumentPositionLimit");
3960
+ }
2920
3961
  /**
2921
- * Cap one instrument's open-position cost (Σ open price × volume × multiplier,
2922
- * long and short summed - a gross capital/concentration limit), enforced in
2923
- * C++ on every opening order. This is per-instrument and independent of the
2924
- * account-wide cap set via riskSet({ maxPositionCost }); both apply. Pass
2925
- * `maxCost <= 0` to remove it. Fill-based, same caveat as maxPositionCost.
3962
+ * Cap one instrument's scheduled open margin (CTP by-money + by-volume,
3963
+ * long and short summed), enforced in C++ on every opening order. This is
3964
+ * independent of the account-wide maxAccountMargin cap; both apply. Pass
3965
+ * `limit = 0` to remove it. Held and in-flight exposure both count.
2926
3966
  */
2927
- setMaxPositionCost(instrumentId, maxCost) {
2928
- assertFiniteLimit("setMaxPositionCost", maxCost);
2929
- this.native.setMaxInstrumentCost(instrumentId, maxCost);
3967
+ setInstrumentMarginLimit(instrumentId, limit) {
3968
+ assertInstrumentId("setInstrumentMarginLimit", instrumentId);
3969
+ assertFiniteLimit("setInstrumentMarginLimit", limit);
3970
+ this.native._setInstrumentMarginLimits([{ instrumentId, limit }]);
2930
3971
  return this;
2931
3972
  }
2932
- /** Cap several instruments' open-position cost at once, e.g.
3973
+ /** Cap several instruments' scheduled open margin at once, e.g.
2933
3974
  * `{ ag2608: 2_000_000, au2608: 5_000_000 }`. */
2934
- setMaxPositionCosts(limits) {
2935
- for (const id of Object.keys(limits)) {
2936
- assertFiniteLimit(`setMaxPositionCosts.${id}`, limits[id]);
2937
- this.native.setMaxInstrumentCost(id, limits[id]);
2938
- }
3975
+ setInstrumentMarginLimits(limits) {
3976
+ const rows = ownStringKeys(limits, "setInstrumentMarginLimits").map((instrumentId) => {
3977
+ const limit = limits[instrumentId];
3978
+ assertInstrumentId("setInstrumentMarginLimits", instrumentId);
3979
+ assertFiniteLimit(`setInstrumentMarginLimits.${instrumentId}`, limit);
3980
+ return { instrumentId, limit };
3981
+ });
3982
+ this.native._setInstrumentMarginLimits(rows);
2939
3983
  return this;
2940
3984
  }
2941
- /** Seed a pre-existing position into the margin/cost cap. `margin` is the real
2942
- * capital occupied (CTP InvestorPosition.UseMargin) — the unit the maxMargin
2943
- * cap tracks. A deliberate resync op (overwrites the held side), so it stays a
2944
- * JS-driven call, unlike the passive multiplier / margin-rate feeds (sourced in
2945
- * C++). */
2946
- seedPosition(instrumentId, side, volume, margin) {
2947
- this.native.seedPosition(instrumentId, side === "long", volume, margin);
2948
- return this;
3985
+ /** Atomically replace held positions from a complete manually reconciled
3986
+ * snapshot. `margin` is CTP InvestorPosition.UseMargin. An empty array is an
3987
+ * authoritative flat book. Partial/incremental seeding is intentionally not
3988
+ * exposed because armed orders can run between JS calls. */
3989
+ seedPositions(positions) {
3990
+ if (!Array.isArray(positions))
3991
+ throw new TypeError("seedPositions requires a complete position array");
3992
+ const seeds = [];
3993
+ const positionCount = positions.length;
3994
+ for (let i = 0; i < positionCount; i++) {
3995
+ if (!Object.prototype.hasOwnProperty.call(positions, i))
3996
+ throw new TypeError(`seedPositions row ${i} must be an explicit array entry`);
3997
+ const row = copyOwnRecord(positions[i], `seedPositions row ${i}`);
3998
+ for (const key of ownStringKeys(row, `seedPositions row ${i}`))
3999
+ if (!POSITION_SEED_KEYS.has(key))
4000
+ throw new TypeError(`seedPositions row ${i}: unknown field ${key}`);
4001
+ assertInstrumentId("seedPositions", row.instrumentId);
4002
+ if (row.side !== "long" && row.side !== "short" || typeof row.hedgeFlag !== "string" || !/^[123567]$/.test(row.hedgeFlag) || !Number.isInteger(row.volume) || row.volume < 0 || !Number.isFinite(row.margin) || row.margin < 0) {
4003
+ throw new TypeError("seedPositions requires long/short, one hedgeFlag digit, a non-negative integer volume and non-negative finite margin");
4004
+ }
4005
+ seeds.push({
4006
+ instrumentId: row.instrumentId,
4007
+ isLong: row.side === "long",
4008
+ hedgeFlag: row.hedgeFlag,
4009
+ volume: row.volume,
4010
+ margin: row.margin
4011
+ });
4012
+ }
4013
+ return this.replacePositionSeeds(seeds);
2949
4014
  }
2950
- /** Seed open-position MARGIN from reqQryInvestorPosition() rows for GROSS-mode
2951
- * accounts (posiDirection '2' = long, '3' = short; any other value, incl. net
2952
- * '1', is bucketed as short). Uses each row's real UseMargin. Cost/margin caps
2953
- * sum both sides so the bucket doesn't matter for them, but a per-side *volume*
2954
- * cap on a net-mode instrument would track the wrong side — for net-mode
2955
- * accounts, seed those via seedPosition() with the side you intend. */
4015
+ replacePositionSeeds(seeds) {
4016
+ for (let attempt = 0; attempt < 5; attempt++) {
4017
+ const revision = this.native.riskRevision();
4018
+ if (this.native.replacePositions(seeds, revision))
4019
+ return this;
4020
+ }
4021
+ throw new Error("position snapshot could not stabilize; live state kept unchanged");
4022
+ }
4023
+ /** Atomically replace held position margin from complete gross-mode query rows
4024
+ * (`posiDirection` '2' long, '3' short). Net/unknown direction is rejected
4025
+ * because guessing a side corrupts per-side volume caps. */
2956
4026
  seedFromPositions(positions) {
4027
+ const seeds = this.aggregatePositions(positions);
4028
+ return this.replacePositionSeeds(seeds);
4029
+ }
4030
+ aggregatePositions(positions) {
4031
+ if (!Array.isArray(positions))
4032
+ throw new TypeError("position snapshot must be an array");
2957
4033
  const agg = /* @__PURE__ */ new Map();
2958
- for (const p of positions) {
2959
- if (!(p.position > 0))
4034
+ const positionCount = positions.length;
4035
+ for (let i = 0; i < positionCount; i++) {
4036
+ if (!Object.prototype.hasOwnProperty.call(positions, i))
4037
+ throw new TypeError(`position snapshot row ${i} must be an explicit array entry`);
4038
+ const p = positions[i];
4039
+ const plain = p !== null && typeof p === "object" && !Array.isArray(p) && (Object.getPrototypeOf(p) === Object.prototype || Object.getPrototypeOf(p) === null);
4040
+ const row = plain ? copyOwnRecord(p, "position snapshot row") : void 0;
4041
+ if (!row || typeof row.instrumentId !== "string" || !row.instrumentId || row.instrumentId.includes("\0") || !Number.isInteger(row.position) || row.position < 0 || !Number.isFinite(row.useMargin) || row.useMargin < 0 || row.posiDirection !== "2" && row.posiDirection !== "3" || typeof row.hedgeFlag !== "string" || !/^[123567]$/.test(row.hedgeFlag)) {
4042
+ throw new TypeError(`invalid position snapshot for ${row?.instrumentId || "<unknown>"}`);
4043
+ }
4044
+ if (!(row.position > 0))
2960
4045
  continue;
2961
- const long = p.posiDirection === "2";
2962
- const key = `${p.instrumentId}|${long}`;
2963
- const e = agg.get(key) ?? { id: p.instrumentId, long, vol: 0, cost: 0 };
2964
- e.vol += p.position;
2965
- e.cost += p.useMargin;
4046
+ const isLong = row.posiDirection === "2";
4047
+ const key = `${row.instrumentId}|${isLong}|${row.hedgeFlag}`;
4048
+ const e = agg.get(key) ?? { instrumentId: row.instrumentId, isLong, hedgeFlag: row.hedgeFlag, volume: 0, margin: 0 };
4049
+ const volume = e.volume + row.position;
4050
+ const margin = e.margin + row.useMargin;
4051
+ if (!Number.isSafeInteger(volume) || !Number.isFinite(margin)) {
4052
+ throw new RangeError(`position snapshot overflow for ${row.instrumentId}`);
4053
+ }
4054
+ e.volume = volume;
4055
+ e.margin = margin;
2966
4056
  agg.set(key, e);
2967
4057
  }
2968
- for (const e of agg.values())
2969
- this.seedPosition(e.id, e.long ? "long" : "short", e.vol, e.cost);
2970
- return this;
4058
+ return [...agg.values()];
2971
4059
  }
2972
- /** Current total open-position cost tracked by the C++ risk engine. */
2973
- positionCost() {
2974
- return this.native.positionCost();
4060
+ /** Current total open-position margin tracked by the C++ risk engine. */
4061
+ get accountMargin() {
4062
+ return this.native.accountMargin();
2975
4063
  }
2976
- /** Clear all tracked position cost. */
4064
+ /** Clear held position state only and mark it uncertain. Working-order
4065
+ * reservations are preserved; openings remain blocked until a complete
4066
+ * seedFromPositions() or syncPositions() succeeds. */
2977
4067
  resetPositions() {
2978
4068
  this.native.resetPositions();
2979
4069
  return this;
@@ -2986,56 +4076,136 @@ var Trader = class extends TraderBase {
2986
4076
  * instrument); otherwise empty is returned as-is (e.g. a genuinely flat
2987
4077
  * position book, so a flat account doesn't waste the full retry budget).
2988
4078
  */
2989
- async queryWithRetry(query, requireNonEmpty, attempts = 5) {
4079
+ async queryWithRetry(query, requireNonEmpty, contextToken, attempts = 5) {
2990
4080
  let lastErr;
2991
4081
  for (let i = 0; i < attempts; i++) {
2992
- if (i > 0)
2993
- await sleep(1100);
2994
4082
  try {
4083
+ this.assertRequestContext(contextToken, "query synchronization");
2995
4084
  const rows = await query();
4085
+ this.assertRequestContext(contextToken, "query synchronization");
2996
4086
  if (!requireNonEmpty || rows.length > 0)
2997
4087
  return rows;
2998
4088
  } catch (e) {
4089
+ this.assertRequestContext(contextToken, "query synchronization");
4090
+ const code = e?.ctpReturnCode;
4091
+ if (code !== -2 && code !== -3)
4092
+ throw e;
2999
4093
  lastErr = e;
3000
4094
  }
3001
4095
  }
3002
4096
  if (lastErr)
3003
4097
  throw lastErr;
3004
- return [];
4098
+ if (requireNonEmpty)
4099
+ throw new Error(`CTP query returned no rows after ${attempts} attempts`);
4100
+ throw new Error("query retry invariant violated");
4101
+ }
4102
+ /** Empty position/order snapshots are ambiguous immediately after login. Require
4103
+ * the same empty result twice, one query interval apart, before treating it as
4104
+ * authoritative. */
4105
+ async authoritativeQuery(query, contextToken) {
4106
+ const first = await this.queryWithRetry(query, false, contextToken);
4107
+ if (first.length > 0)
4108
+ return first;
4109
+ return this.queryWithRetry(query, false, contextToken);
3005
4110
  }
3006
4111
  /** Query instruments so the C++ risk engine picks up their multipliers (it
3007
4112
  * sources them directly from OnRspQryInstrument — no JS feed). No args queries
3008
4113
  * all instruments (one request); otherwise the given symbols. Retries through
3009
4114
  * cold-start flow control. Returns the count of contracts with a multiplier. */
3010
4115
  async syncMultipliers(instrumentIds) {
4116
+ const contextToken = this.requestContextToken();
4117
+ if (instrumentIds !== void 0) {
4118
+ instrumentIds = copyDenseStringArray(instrumentIds, "syncMultipliers instrumentIds");
4119
+ if (instrumentIds.length === 0)
4120
+ return 0;
4121
+ }
3011
4122
  let count = 0;
3012
4123
  const apply = (rows) => {
3013
- for (const r of rows) {
3014
- if (r.volumeMultiple > 0)
4124
+ const finalByInstrument = /* @__PURE__ */ new Map();
4125
+ for (const r of rows)
4126
+ finalByInstrument.set(r.instrumentId, r);
4127
+ for (const r of finalByInstrument.values()) {
4128
+ if (r.instrumentId && Number.isFinite(r.volumeMultiple) && r.volumeMultiple > 0 && r.volumeMultiple < 1e300)
3015
4129
  count++;
3016
4130
  }
3017
4131
  };
3018
- if (instrumentIds && instrumentIds.length) {
3019
- for (let i = 0; i < instrumentIds.length; i++) {
3020
- apply(await this.queryWithRetry(() => this.reqQryInstrument({ instrumentId: instrumentIds[i] }), true));
3021
- if (i < instrumentIds.length - 1)
3022
- await sleep(1100);
4132
+ if (instrumentIds) {
4133
+ for (const instrumentId of new Set(instrumentIds)) {
4134
+ apply(await this.queryWithRetry(async () => (await this.reqQryInstrument({ instrumentId })).filter((row) => row.instrumentId === instrumentId), true, contextToken));
3023
4135
  }
3024
4136
  } else {
3025
- apply(await this.queryWithRetry(() => this.reqQryInstrument({}), true));
4137
+ apply(await this.queryWithRetry(() => this.reqQryInstrument({}), true, contextToken));
4138
+ }
4139
+ return count;
4140
+ }
4141
+ /** Query investor margin schedules for a bounded universe. The exchange-base
4142
+ * query is issued only when the investor row is relative; the shared query
4143
+ * scheduler enforces spacing. Returns the number of usable schedules. */
4144
+ async syncMarginRates(instrumentIds, hedgeFlag = "1") {
4145
+ const contextToken = this.requestContextToken();
4146
+ instrumentIds = copyDenseStringArray(instrumentIds, "syncMarginRates", false);
4147
+ if (typeof hedgeFlag !== "string" || !/^[123567]$/.test(hedgeFlag)) {
4148
+ throw new TypeError("syncMarginRates hedgeFlag must be 1, 2, 3, 5, 6 or 7");
4149
+ }
4150
+ const brokerId = this.broker;
4151
+ const investorId = this.investor;
4152
+ if (!brokerId || !investorId) {
4153
+ throw new Error("syncMarginRates requires a successful trader login first");
4154
+ }
4155
+ let count = 0;
4156
+ for (const instrumentId of new Set(instrumentIds)) {
4157
+ const investorRows = await this.queryWithRetry(async () => (await this.reqQryInstrumentMarginRate({
4158
+ brokerId,
4159
+ investorId,
4160
+ instrumentId,
4161
+ hedgeFlag
4162
+ })).filter((row) => row.instrumentId === instrumentId && row.hedgeFlag === hedgeFlag), true, contextToken);
4163
+ const investor = investorRows.at(-1);
4164
+ const relative = investor.isRelative !== 0;
4165
+ const baseRows = relative ? await this.queryWithRetry(async () => (await this.reqQryExchangeMarginRate({
4166
+ brokerId,
4167
+ instrumentId,
4168
+ hedgeFlag
4169
+ })).filter((row) => row.instrumentId === instrumentId && row.hedgeFlag === hedgeFlag), true, contextToken) : [];
4170
+ const base = baseRows.at(-1);
4171
+ const component = (value) => Number.isFinite(value) && value >= 0 && value < 1e300;
4172
+ const scheduleUsable = (row) => !!row && component(row.longMarginRatioByMoney) && component(row.longMarginRatioByVolume) && component(row.shortMarginRatioByMoney) && component(row.shortMarginRatioByVolume) && (row.longMarginRatioByMoney > 0 || row.longMarginRatioByVolume > 0) && (row.shortMarginRatioByMoney > 0 || row.shortMarginRatioByVolume > 0);
4173
+ const investorComponentsValid = component(investor.longMarginRatioByMoney) && component(investor.longMarginRatioByVolume) && component(investor.shortMarginRatioByMoney) && component(investor.shortMarginRatioByVolume);
4174
+ if (investorComponentsValid && (relative ? scheduleUsable(base) : scheduleUsable(investor)))
4175
+ count++;
3026
4176
  }
3027
4177
  return count;
3028
4178
  }
3029
- /** Seed open-position MARGIN from CTP (reqQryInvestorPosition) into the cap.
3030
- * Uses the logged-in account unless brokerId/investorId are supplied. A
3031
- * deliberate resync (resets the held book first), so it stays JS-driven. */
3032
- async syncPositions(opts) {
3033
- const brokerId = opts?.brokerId ?? this.broker;
3034
- const investorId = opts?.investorId ?? this.investor;
3035
- const rows = await this.queryWithRetry(() => this.reqQryInvestorPosition({ brokerId, investorId }), false);
3036
- this.resetPositions();
3037
- this.seedFromPositions(rows);
3038
- return rows.filter((r) => r.position > 0).length;
4179
+ /** Replace held position margin from CTP (`reqQryInvestorPosition`). The
4180
+ * replacement is revision-checked: if an order/trade callback races the
4181
+ * snapshot it retries without clearing live state or reservations. */
4182
+ async syncPositions() {
4183
+ const contextToken = this.requestContextToken();
4184
+ if (arguments.length !== 0)
4185
+ throw new TypeError("syncPositions does not accept account overrides");
4186
+ const brokerId = this.broker;
4187
+ const investorId = this.investor;
4188
+ if (typeof brokerId !== "string" || !brokerId || brokerId.includes("\0") || typeof investorId !== "string" || !investorId || investorId.includes("\0"))
4189
+ throw new Error("syncPositions requires a successful trader login");
4190
+ this.native._markPositionLedgerUncertain();
4191
+ for (let attempt = 0; attempt < 5; attempt++) {
4192
+ this.assertRequestContext(contextToken, "position synchronization");
4193
+ const revision = this.native.riskRevision();
4194
+ const rows = await this.authoritativeQuery(async () => {
4195
+ const result = await this.reqQryInvestorPosition({ brokerId, investorId });
4196
+ if (result.some((row) => row.brokerId !== brokerId || row.investorId !== investorId)) {
4197
+ throw new Error("position snapshot contains a mismatched account identity");
4198
+ }
4199
+ return result;
4200
+ }, contextToken);
4201
+ const seeds = this.aggregatePositions(rows);
4202
+ this.assertRequestContext(contextToken, "position synchronization");
4203
+ if (this.native.replacePositions(seeds, revision))
4204
+ return rows.filter((r) => r.position > 0).length;
4205
+ if (attempt < 4)
4206
+ await sleep(100);
4207
+ }
4208
+ throw new Error("position snapshot could not stabilize; live state kept unchanged");
3039
4209
  }
3040
4210
  /**
3041
4211
  * Rebuild the in-flight reservation from CTP's currently-working orders
@@ -3046,21 +4216,71 @@ var Trader = class extends TraderBase {
3046
4216
  * of working open orders re-reserved. Run syncMultipliers() first so the
3047
4217
  * reserved cost uses the right contract multiplier.
3048
4218
  */
3049
- async syncOrders(opts) {
3050
- const brokerId = opts?.brokerId ?? this.broker;
3051
- const investorId = opts?.investorId ?? this.investor;
3052
- const rows = await this.queryWithRetry(() => this.reqQryOrder({ brokerId, investorId }), false);
3053
- const working = rows.filter((o) => (o.orderStatus === "1" || o.orderStatus === "3") && o.combOffsetFlag?.[0] === "0").map((o) => ({
3054
- frontId: o.frontId,
3055
- sessionId: o.sessionId,
3056
- orderRef: o.orderRef,
3057
- instrumentId: o.instrumentId,
3058
- isLong: o.direction === "0",
3059
- vol: o.volumeTotalOriginal - o.volumeTraded,
3060
- price: o.limitPrice
3061
- }));
3062
- this.native.rebuildReservations(working);
3063
- return working.length;
4219
+ async syncOrders() {
4220
+ const contextToken = this.requestContextToken();
4221
+ if (arguments.length !== 0)
4222
+ throw new TypeError("syncOrders does not accept account overrides");
4223
+ const brokerId = this.broker;
4224
+ const investorId = this.investor;
4225
+ if (typeof brokerId !== "string" || !brokerId || brokerId.includes("\0") || typeof investorId !== "string" || !investorId || investorId.includes("\0"))
4226
+ throw new Error("syncOrders requires a successful trader login");
4227
+ this.native._markPositionLedgerUncertain();
4228
+ this.native._markOrderLedgerUncertain();
4229
+ for (let attempt = 0; attempt < 5; attempt++) {
4230
+ this.assertRequestContext(contextToken, "order synchronization");
4231
+ const revision = this.native.riskRevision();
4232
+ const rows = await this.authoritativeQuery(async () => {
4233
+ const result = await this.reqQryOrder({ brokerId, investorId });
4234
+ if (result.some((row) => row.brokerId !== brokerId || row.investorId !== investorId)) {
4235
+ throw new Error("order snapshot contains a mismatched account identity");
4236
+ }
4237
+ return result;
4238
+ }, contextToken);
4239
+ const terminal = /* @__PURE__ */ new Set(["0", "2", "4", "5"]);
4240
+ const active = rows.filter((o) => !terminal.has(o.orderStatus));
4241
+ for (const o of active) {
4242
+ const vol = o.volumeTotalOriginal - o.volumeTraded;
4243
+ if (!Number.isInteger(o.frontId) || !Number.isInteger(o.sessionId) || !o.orderRef || !o.instrumentId || o.direction !== "0" && o.direction !== "1" || typeof o.combOffsetFlag !== "string" || typeof o.combHedgeFlag !== "string" || !Number.isInteger(o.volumeTotalOriginal) || !Number.isInteger(o.volumeTraded) || o.volumeTraded < 0 || o.volumeTraded > o.volumeTotalOriginal || !Number.isInteger(vol) || vol < 0 || !Number.isFinite(o.limitPrice) || o.limitPrice < 0 || o.orderSysId && !o.exchangeId || /^[0-6]$/.test(o.combOffsetFlag) && !/^[123567]$/.test(o.combHedgeFlag)) {
4244
+ throw new TypeError(`invalid working-order snapshot for ${o.orderRef || "<unknown>"}`);
4245
+ }
4246
+ }
4247
+ const working = active.flatMap((o) => {
4248
+ const vol = o.volumeTotalOriginal - o.volumeTraded;
4249
+ const supportedSingleLeg = /^[0-6]$/.test(o.combOffsetFlag);
4250
+ if (supportedSingleLeg && o.combOffsetFlag !== "0")
4251
+ return [];
4252
+ return [{
4253
+ frontId: o.frontId,
4254
+ sessionId: o.sessionId,
4255
+ orderRef: o.orderRef,
4256
+ instrumentId: o.instrumentId,
4257
+ isLong: o.direction === "0",
4258
+ hedgeFlag: o.combHedgeFlag?.[0] || "1",
4259
+ vol,
4260
+ price: o.limitPrice,
4261
+ traded: o.volumeTraded,
4262
+ // Must be byte-identical to the native realtime key built in
4263
+ // traderspi.gen.cc (OnRtnOrder/OnRtnTrade):
4264
+ // day|broker|investor|exchange|instrument|orderSysId. broker/investor
4265
+ // are the confirmed session identity (validated == every row above),
4266
+ // so a reservation rebuilt on resync correlates with the subsequent
4267
+ // realtime order/trade callbacks instead of being stranded uncertain.
4268
+ orderSysKey: o.tradingDay && o.exchangeId && o.orderSysId ? `${o.tradingDay}|${brokerId}|${investorId}|${o.exchangeId}|${o.instrumentId}|${o.orderSysId}` : "",
4269
+ supportedSingleLeg
4270
+ }];
4271
+ });
4272
+ this.assertRequestContext(contextToken, "order synchronization");
4273
+ if (this.native.rebuildReservations(working, revision)) {
4274
+ const unsupported = working.filter((o) => !o.supportedSingleLeg);
4275
+ if (unsupported.length > 0) {
4276
+ throw new Error(`unsupported working order ${unsupported[0].orderRef}; opening inserts are fail-closed`);
4277
+ }
4278
+ return working.length;
4279
+ }
4280
+ if (attempt < 4)
4281
+ await sleep(100);
4282
+ }
4283
+ throw new Error("order snapshot could not stabilize; live state kept unchanged");
3064
4284
  }
3065
4285
  /**
3066
4286
  * Arm a latency-critical trigger: when `md` sees the condition, the order is
@@ -3069,23 +4289,34 @@ var Trader = class extends TraderBase {
3069
4289
  * rtn-order / rsp-order-insert events (correlate by the order's orderRef).
3070
4290
  */
3071
4291
  arm(md, spec) {
3072
- if (!spec.instrumentId || !(spec.triggerPrice > 0)) {
4292
+ const cleanSpec = copyOwnRecord(spec, "arm spec");
4293
+ assertObjectKeys(cleanSpec, "arm spec", ARM_SPEC_KEYS);
4294
+ if (!cleanSpec.instrumentId || cleanSpec.instrumentId.includes("\0") || !Number.isFinite(cleanSpec.triggerPrice) || !(cleanSpec.triggerPrice > 0) || cleanSpec.triggerPrice >= 1e300) {
3073
4295
  throw new Error("arm: spec.instrumentId and a positive triggerPrice are required");
3074
4296
  }
3075
- const order = this.withAutoOrderRef(spec.order);
3076
- if (!order.instrumentId || order.direction === void 0 || !order.combOffsetFlag || !(Number(order.volumeTotalOriginal) > 0)) {
3077
- throw new Error("arm: spec.order needs instrumentId, direction, combOffsetFlag and volumeTotalOriginal > 0");
4297
+ const validatedOrder = this.validateOrder(cleanSpec.order, "arm.order");
4298
+ if (cleanSpec.side !== "buy" && cleanSpec.side !== "sell") {
4299
+ throw new Error("arm: spec.side must be buy or sell");
3078
4300
  }
3079
- md.attachArm(this);
4301
+ if (validatedOrder.instrumentId !== cleanSpec.instrumentId) {
4302
+ throw new Error("arm: spec.instrumentId must match spec.order.instrumentId");
4303
+ }
4304
+ if (cleanSpec.side === "buy" !== (validatedOrder.direction === "0")) {
4305
+ throw new Error("arm: spec.side must match spec.order.direction");
4306
+ }
4307
+ const order = this.withAutoOrderRef(validatedOrder);
3080
4308
  const bytes = this.encode(STRUCT_ID.InputOrder, order);
3081
- const id = this.native.arm(spec.instrumentId, spec.side === "buy" ? "0" : "1", spec.triggerPrice, bytes);
4309
+ md.attachArm(this);
4310
+ this.trackMarketData(md);
4311
+ const id = this.native.arm(cleanSpec.instrumentId, cleanSpec.side === "buy" ? "0" : "1", cleanSpec.triggerPrice, bytes);
4312
+ this.commitOrderRef(order);
3082
4313
  return { id, disarm: () => this.native.disarm(id) };
3083
4314
  }
3084
4315
  /** Observability for armed triggers (they fire in C++ with no JS in the loop):
3085
4316
  * how many fired and were sent vs were refused by the risk gate / send.
3086
4317
  * A blocked armed order is otherwise invisible, so poll this after a trigger
3087
4318
  * you expected to fire. */
3088
- armStats() {
4319
+ get armStats() {
3089
4320
  return { fired: this.native._armFireCount(), blocked: this.native._armBlockedCount() };
3090
4321
  }
3091
4322
  /** @internal used by MarketData.attachArm to share the arm registry. */
@@ -3105,6 +4336,235 @@ var Trader = class extends TraderBase {
3105
4336
  }
3106
4337
  };
3107
4338
 
4339
+ // dist/market-data.js
4340
+ var MD_BASE = 4096;
4341
+ var MD_EVENTS = /* @__PURE__ */ new Map([
4342
+ [MD_BASE + 1, "front-connected"],
4343
+ [MD_BASE + 2, "front-disconnected"],
4344
+ [MD_BASE + 3, "heart-beat-warning"],
4345
+ [MD_BASE + 4, "rsp-user-login"],
4346
+ [MD_BASE + 5, "rsp-user-logout"],
4347
+ [MD_BASE + 6, "rsp-qry-multicast-instrument"],
4348
+ [MD_BASE + 7, "rsp-error"],
4349
+ [MD_BASE + 8, "rsp-sub-market-data"],
4350
+ [MD_BASE + 9, "rsp-unsub-market-data"],
4351
+ [MD_BASE + 10, "rsp-sub-for-quote"],
4352
+ [MD_BASE + 11, "rsp-unsub-for-quote"],
4353
+ [MD_BASE + 12, "rtn-depth-market-data"],
4354
+ [MD_BASE + 13, "rtn-for-quote"]
4355
+ ]);
4356
+ var MarketDataEvent;
4357
+ (function(MarketDataEvent2) {
4358
+ MarketDataEvent2["FrontConnected"] = "front-connected";
4359
+ MarketDataEvent2["FrontDisconnected"] = "front-disconnected";
4360
+ MarketDataEvent2["HeartBeatWarning"] = "heart-beat-warning";
4361
+ MarketDataEvent2["RspUserLogin"] = "rsp-user-login";
4362
+ MarketDataEvent2["RspUserLogout"] = "rsp-user-logout";
4363
+ MarketDataEvent2["RspQryMulticastInstrument"] = "rsp-qry-multicast-instrument";
4364
+ MarketDataEvent2["RspError"] = "rsp-error";
4365
+ MarketDataEvent2["RspSubMarketData"] = "rsp-sub-market-data";
4366
+ MarketDataEvent2["RspUnSubMarketData"] = "rsp-unsub-market-data";
4367
+ MarketDataEvent2["RspSubForQuote"] = "rsp-sub-for-quote";
4368
+ MarketDataEvent2["RspUnSubForQuote"] = "rsp-unsub-for-quote";
4369
+ MarketDataEvent2["RtnDepthMarketData"] = "rtn-depth-market-data";
4370
+ MarketDataEvent2["RtnForQuote"] = "rtn-for-quote";
4371
+ })(MarketDataEvent || (MarketDataEvent = {}));
4372
+ function snapshotInstrumentIds(instrumentIds) {
4373
+ return copyDenseStringArray(instrumentIds, "instrumentIds");
4374
+ }
4375
+ function requestShapeError(value, allowed, label) {
4376
+ let keys;
4377
+ try {
4378
+ keys = ownStringKeys(value, label);
4379
+ } catch (error) {
4380
+ return error instanceof TypeError ? error : new TypeError(`${label} must be a plain object`);
4381
+ }
4382
+ for (const key of keys)
4383
+ if (!allowed.has(key))
4384
+ return new TypeError(`${label}: unknown field ${key}`);
4385
+ return void 0;
4386
+ }
4387
+ var LOGIN_KEYS = /* @__PURE__ */ new Set([
4388
+ "tradingDay",
4389
+ "brokerId",
4390
+ "userId",
4391
+ "password",
4392
+ "userProductInfo",
4393
+ "interfaceProductInfo",
4394
+ "protocolInfo",
4395
+ "macAddress",
4396
+ "oneTimePassword",
4397
+ "loginRemark",
4398
+ "clientIpPort",
4399
+ "clientIpAddress",
4400
+ "smsCode"
4401
+ ]);
4402
+ var LOGOUT_KEYS = /* @__PURE__ */ new Set(["brokerId", "userId"]);
4403
+ var MULTICAST_QUERY_KEYS = /* @__PURE__ */ new Set(["topicId", "instrumentId"]);
4404
+ var MarketData = class extends CtpClient {
4405
+ sessionTransition;
4406
+ constructor(flowPath, fronts) {
4407
+ super(new native.MarketData(flowPath, copyOwnFronts(fronts, "MarketData fronts")), native.__layoutData(), MD_EVENTS);
4408
+ this.start();
4409
+ }
4410
+ get apiVersion() {
4411
+ return this.native.apiVersion();
4412
+ }
4413
+ get tradingDay() {
4414
+ return this.native.tradingDay();
4415
+ }
4416
+ /** Subscribe to depth market data. Returns the CTP send code (0 = ok). */
4417
+ subscribe(instrumentIds) {
4418
+ const ids = snapshotInstrumentIds(instrumentIds);
4419
+ return this.native.subscribeMarketData(ids);
4420
+ }
4421
+ unsubscribe(instrumentIds) {
4422
+ const ids = snapshotInstrumentIds(instrumentIds);
4423
+ return this.native.unsubscribeMarketData(ids);
4424
+ }
4425
+ subscribeForQuote(instrumentIds) {
4426
+ const ids = snapshotInstrumentIds(instrumentIds);
4427
+ return this.native.subscribeForQuoteRsp(ids);
4428
+ }
4429
+ unsubscribeForQuote(instrumentIds) {
4430
+ const ids = snapshotInstrumentIds(instrumentIds);
4431
+ return this.native.unsubscribeForQuoteRsp(ids);
4432
+ }
4433
+ /** Latest cached depth tick for an instrument — the C++ last-value cache,
4434
+ * updated on every authenticated-session tick before it reaches JS. Returns
4435
+ * null before login, after disconnect/logout, if none has been seen, or if it
4436
+ * was unsubscribed. Synchronous: no waiting for an event. */
4437
+ snapshot(instrumentId) {
4438
+ const bytes = this.native.snapshot(instrumentId);
4439
+ return bytes ? this.decodeStruct(STRUCT_ID.DepthMarketData, bytes) : null;
4440
+ }
4441
+ /** Latest price for an instrument from the cache (0 if none seen). Synchronous. */
4442
+ last(instrumentId) {
4443
+ return this.native.last(instrumentId);
4444
+ }
4445
+ /** @internal Hand the C++ snapshot cache to a Trader (Trader.trackMarketData),
4446
+ * so the Trader's deviation check reads live prices in C++ — no JS round-trip. */
4447
+ _snapshotExternal() {
4448
+ return this.native._snapshotExternal();
4449
+ }
4450
+ /** Log in; resolves with the login response (or rejects on CTP error). */
4451
+ login(req = {}) {
4452
+ const shapeError = requestShapeError(req, LOGIN_KEYS, "login request");
4453
+ if (shapeError)
4454
+ return Promise.reject(shapeError);
4455
+ const clean = copyOwnRecord(req, "login request");
4456
+ let encoded;
4457
+ try {
4458
+ encoded = this.encode(STRUCT_ID.ReqUserLogin, clean);
4459
+ } catch (error) {
4460
+ return Promise.reject(error);
4461
+ }
4462
+ return this.runSessionTransition(() => {
4463
+ this.beginRequestContextTransition("market-data login started");
4464
+ return this.request((id) => this.native.reqUserLogin(encoded, id), true, MD_BASE + 4, true);
4465
+ });
4466
+ }
4467
+ logout(req = {}) {
4468
+ const shapeError = requestShapeError(req, LOGOUT_KEYS, "logout request");
4469
+ if (shapeError)
4470
+ return Promise.reject(shapeError);
4471
+ const clean = copyOwnRecord(req, "logout request");
4472
+ let encoded;
4473
+ try {
4474
+ encoded = this.encode(STRUCT_ID.UserLogout, clean);
4475
+ } catch (error) {
4476
+ return Promise.reject(error);
4477
+ }
4478
+ return this.runSessionTransition(() => {
4479
+ this.beginRequestContextTransition("market-data logout started");
4480
+ return this.request((id) => this.native.reqUserLogout(encoded, id), true, MD_BASE + 5, true);
4481
+ });
4482
+ }
4483
+ shouldTimeoutRequest(requestId, sessionTransition) {
4484
+ if (!sessionTransition)
4485
+ return true;
4486
+ return this.native._timeoutSessionTransition(requestId);
4487
+ }
4488
+ // MarketData confirms a successful login natively: OnRspUserLogin activates the
4489
+ // snapshot cache on the MD channel, which legitimately carries no
4490
+ // FrontID/SessionID (those are the trade front's order-routing identity). There
4491
+ // is deliberately no onRequestResolved override here — the base no-op is
4492
+ // correct, and a successful MD login must never be rejected for lacking a trade
4493
+ // session id.
4494
+ /** SimNow may return requestId=0 for MD login/logout. Never overlap these
4495
+ * transitions: otherwise a late id-0 login response cannot be attributed to
4496
+ * one epoch. If a request times out while native still considers it pending,
4497
+ * native stays fail-closed until the next front transition. */
4498
+ runSessionTransition(start) {
4499
+ if (this.sessionTransition) {
4500
+ return Promise.reject(new Error("market-data login/logout transition already in flight; await it first"));
4501
+ }
4502
+ const promise = start();
4503
+ this.sessionTransition = promise;
4504
+ const finish = () => {
4505
+ if (this.sessionTransition !== promise)
4506
+ return;
4507
+ try {
4508
+ this.native._abandonSessionTransition();
4509
+ } catch {
4510
+ } finally {
4511
+ this.sessionTransition = void 0;
4512
+ }
4513
+ };
4514
+ void promise.then(finish, finish);
4515
+ return promise;
4516
+ }
4517
+ /** Query multicast instruments. Multi-row response, serialized through this
4518
+ * client's conservative query scheduler. */
4519
+ reqQryMulticastInstrument(req = {}) {
4520
+ const shapeError = requestShapeError(req, MULTICAST_QUERY_KEYS, "multicast query");
4521
+ if (shapeError)
4522
+ return Promise.reject(shapeError);
4523
+ const clean = copyOwnRecord(req, "multicast query");
4524
+ return this.queryRequest((id) => this.native.reqQryMulticastInstrument(clean, id));
4525
+ }
4526
+ /** Route this market data's ticks to a Trader's armed triggers (see Trader.arm).
4527
+ * A MarketData feeds exactly one live Trader's registry. Native ownership
4528
+ * rejects replacement while that Trader is live, but permits replacing a
4529
+ * registry whose Trader has already closed. */
4530
+ attachArm(trader) {
4531
+ if (!(trader instanceof Trader))
4532
+ throw new TypeError("attachArm requires a Trader from this package instance");
4533
+ const registry = trader._armRegistry();
4534
+ this.native._attachArm(registry);
4535
+ }
4536
+ /** @internal test-only: inject a synthetic depth tick into the ring. Optional
4537
+ * bid/ask override the defaults (3499/3501) so tests can drive edge prices
4538
+ * (e.g. a DBL_MAX no-bid sentinel) through the real arm/onTick path. */
4539
+ _injectTestTick(bid, ask) {
4540
+ this.native._injectTestTick(bid, ask);
4541
+ }
4542
+ /** @internal test-only: inject one RFQ business notification through MdSpi. */
4543
+ _injectTestForQuote() {
4544
+ this.native._injectTestForQuote();
4545
+ }
4546
+ /** @internal test-only: drive a real native MD lifecycle callback. */
4547
+ _injectTestLifecycle(state) {
4548
+ this.native._injectTestLifecycle(state);
4549
+ }
4550
+ /** @internal test-only: spawn a background producer thread that pushes `n`
4551
+ * synthetic ticks into the ring (cross-thread doorbell stress). Each tick's
4552
+ * requestId carries its sequence number. */
4553
+ _burstTicks(n, jitterUs = 0, injectControl = false) {
4554
+ this.native._burstTicks(n, jitterUs, injectControl);
4555
+ }
4556
+ /** @internal test-only: produce ticks on a native background thread through
4557
+ * the real MD SPI. `ratePerSecond=0` is an instantaneous burst; otherwise
4558
+ * ticks arrive as paced `burstSize` batches. Instrument IDs rotate across
4559
+ * SIM00000000.. and `volume` is the zero-based global sequence. */
4560
+ _produceTestTicks(count, instrumentCount, ratePerSecond = 0, burstSize = 512) {
4561
+ this.native._produceTestTicks(count, instrumentCount, ratePerSecond, burstSize);
4562
+ }
4563
+ on(event, cb) {
4564
+ return super.on(event, cb);
4565
+ }
4566
+ };
4567
+
3108
4568
  // dist/generated/enums.gen.js
3109
4569
  var ExchangeProperty;
3110
4570
  (function(ExchangeProperty2) {