@hitrading/ctp-node 2.0.0 → 4.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +82 -0
- package/README.md +54 -32
- package/README.zh-CN.md +44 -27
- package/RELEASING.md +78 -0
- package/dist/client.d.ts +36 -15
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +234 -62
- package/dist/client.js.map +1 -1
- package/dist/codec.d.ts.map +1 -1
- package/dist/codec.js +84 -19
- package/dist/codec.js.map +1 -1
- package/dist/generated/structs.gen.d.ts +5461 -5461
- package/dist/generated/structs.gen.d.ts.map +1 -1
- package/dist/generated/trader.gen.d.ts.map +1 -1
- package/dist/generated/trader.gen.js +788 -94
- package/dist/generated/trader.gen.js.map +1 -1
- package/dist/index.cjs +1909 -417
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/market-data.d.ts +41 -24
- package/dist/market-data.d.ts.map +1 -1
- package/dist/market-data.js +148 -29
- package/dist/market-data.js.map +1 -1
- package/dist/native-binding.d.ts.map +1 -1
- package/dist/native-binding.js +4 -0
- package/dist/native-binding.js.map +1 -1
- package/dist/trader.d.ts +136 -79
- package/dist/trader.d.ts.map +1 -1
- package/dist/trader.js +807 -182
- package/dist/trader.js.map +1 -1
- package/dist/validation.d.ts +27 -0
- package/dist/validation.d.ts.map +1 -0
- package/dist/validation.js +85 -0
- package/dist/validation.js.map +1 -0
- package/docs/API.md +1445 -0
- package/docs/API.zh-CN.md +1285 -0
- package/docs/MIGRATION.md +54 -0
- package/docs/assets/validation.svg +27 -0
- package/docs/integration.md +60 -0
- package/docs/native-hooks.md +281 -0
- package/docs/native-hooks.zh-CN.md +205 -0
- package/docs/troubleshooting.md +257 -0
- package/docs/troubleshooting.zh-CN.md +220 -0
- package/package.json +12 -4
- package/prebuilds/linux-x64/@hitrading+ctp-node.node +0 -0
- package/prebuilds/win32-x64/@hitrading+ctp-node.node +0 -0
- package/scripts/bench-decode.mjs +37 -0
- package/scripts/bench-fullmarket-offline.mjs +207 -0
- package/scripts/stress-fullmarket.mjs +255 -0
- package/src/addon.cc +2 -2
- package/src/client.ts +255 -65
- package/src/codec.ts +86 -19
- package/src/generated/structs.gen.ts +5461 -5461
- package/src/generated/trader.gen.ts +309 -94
- package/src/generated/traderreq.gen.cc +194 -18
- package/src/generated/traderreq.gen.h +4 -0
- package/src/generated/traderspi.gen.cc +129 -15
- package/src/generated/traderspi.gen.h +4 -2
- package/src/index.ts +11 -1
- package/src/market-data.ts +199 -46
- package/src/native/arm.cc +114 -30
- package/src/native/arm.h +16 -4
- package/src/native/channel.cc +209 -81
- package/src/native/channel.h +65 -24
- package/src/native/ctp_field.h +23 -0
- package/src/native/mdapi.cc +582 -69
- package/src/native/mdspi.cc +219 -16
- package/src/native/mdspi.h +59 -10
- package/src/native/order_capability.h +78 -0
- package/src/native/risk.cc +2030 -213
- package/src/native/risk.h +431 -78
- package/src/native/shared_handle.h +37 -0
- package/src/native/snapshot.h +75 -16
- package/src/native/traderapi.cc +769 -124
- package/src/native-binding.ts +4 -0
- package/src/trader.ts +1038 -207
- 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
|
|
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 =
|
|
1435
|
-
const fc =
|
|
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
|
-
|
|
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
|
|
1504
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
1517
|
-
|
|
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
|
-
|
|
1520
|
-
|
|
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.
|
|
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;
|
|
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
|
|
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
|
-
|
|
1596
|
-
|
|
1597
|
-
|
|
1598
|
-
|
|
1599
|
-
|
|
1600
|
-
|
|
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-
|
|
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.
|
|
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
|
-
*
|
|
1705
|
-
*
|
|
1706
|
-
*
|
|
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 =
|
|
1896
|
+
for (let i = 0; i < count; i++)
|
|
1730
1897
|
batch[i] = void 0;
|
|
1731
1898
|
return;
|
|
1732
1899
|
}
|
|
1733
|
-
for (let 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
|
|
1790
|
-
|
|
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.
|
|
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 >=
|
|
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
|
|
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.
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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,277 @@ 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
|
-
|
|
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})`);
|
|
3532
|
+
}
|
|
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`);
|
|
2766
3544
|
}
|
|
2767
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 MARGIN_RATE_SYNC_KEYS = /* @__PURE__ */ new Set(["instrumentIds", "hedgeFlag"]);
|
|
3578
|
+
var ARM_SPEC_KEYS = /* @__PURE__ */ new Set(["instrumentId", "side", "triggerPrice", "order"]);
|
|
3579
|
+
var POSITION_LIMIT_KEYS = /* @__PURE__ */ new Set(["long", "short"]);
|
|
3580
|
+
var POSITION_SEED_KEYS = /* @__PURE__ */ new Set([
|
|
3581
|
+
"instrumentId",
|
|
3582
|
+
"side",
|
|
3583
|
+
"hedgeFlag",
|
|
3584
|
+
"volume",
|
|
3585
|
+
"margin"
|
|
3586
|
+
]);
|
|
2768
3587
|
var Trader = class extends TraderBase {
|
|
2769
3588
|
broker;
|
|
2770
3589
|
investor;
|
|
2771
3590
|
orderRefSeq = 0;
|
|
2772
3591
|
constructor(flowPath, fronts) {
|
|
2773
|
-
super(new native.Trader(flowPath, fronts), native.__layoutData(), TRADER_EVENTS);
|
|
2774
|
-
|
|
2775
|
-
|
|
2776
|
-
|
|
2777
|
-
|
|
2778
|
-
|
|
2779
|
-
|
|
2780
|
-
if (Number.isFinite(mx) && mx > this.orderRefSeq)
|
|
2781
|
-
this.orderRefSeq = mx;
|
|
2782
|
-
}
|
|
2783
|
-
});
|
|
3592
|
+
super(new native.Trader(flowPath, copyOwnFronts(fronts, "Trader fronts")), native.__layoutData(), TRADER_EVENTS);
|
|
3593
|
+
const clearConfirmedIdentity = () => {
|
|
3594
|
+
this.broker = void 0;
|
|
3595
|
+
this.investor = void 0;
|
|
3596
|
+
};
|
|
3597
|
+
this.on("front-connected", clearConfirmedIdentity);
|
|
3598
|
+
this.on("front-disconnected", clearConfirmedIdentity);
|
|
2784
3599
|
this.start();
|
|
2785
3600
|
}
|
|
2786
|
-
|
|
2787
|
-
|
|
3601
|
+
/** A raw login Promise may resolve only with a structurally usable session.
|
|
3602
|
+
* Account confirmation itself happens in session(), after request-vs-response
|
|
3603
|
+
* identity validation; merely observing a protocol event never grants order
|
|
3604
|
+
* authority. */
|
|
3605
|
+
onRequestResolved(eventName, value, _options) {
|
|
3606
|
+
if (eventName === "rsp-user-logout") {
|
|
3607
|
+
this.broker = void 0;
|
|
3608
|
+
this.investor = void 0;
|
|
3609
|
+
return;
|
|
3610
|
+
}
|
|
3611
|
+
if (eventName !== "rsp-user-login")
|
|
3612
|
+
return;
|
|
3613
|
+
const r = value;
|
|
3614
|
+
if (!r)
|
|
3615
|
+
return;
|
|
3616
|
+
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) {
|
|
3617
|
+
this.broker = r.brokerId;
|
|
3618
|
+
this.investor = r.userId;
|
|
3619
|
+
}
|
|
3620
|
+
const maxOrderRef = typeof r.maxOrderRef === "string" ? r.maxOrderRef.trim() : "";
|
|
3621
|
+
if (/^\d{1,12}$/.test(maxOrderRef)) {
|
|
3622
|
+
const maxRef = Number(maxOrderRef);
|
|
3623
|
+
if (Number.isFinite(maxRef) && maxRef > this.orderRefSeq)
|
|
3624
|
+
this.orderRefSeq = maxRef;
|
|
3625
|
+
}
|
|
3626
|
+
}
|
|
3627
|
+
/** Generated login/logout methods call this only after their request has
|
|
3628
|
+
* encoded successfully. Revoke the confirmed JS account at that same atomic
|
|
3629
|
+
* transition boundary, so a concurrent sync helper cannot start with the old
|
|
3630
|
+
* identity while native risk state is already fail-closed for the new session. */
|
|
3631
|
+
beginRequestContextTransition(reason) {
|
|
3632
|
+
this.broker = void 0;
|
|
3633
|
+
this.investor = void 0;
|
|
3634
|
+
super.beginRequestContextTransition(reason);
|
|
2788
3635
|
}
|
|
2789
|
-
|
|
2790
|
-
|
|
3636
|
+
shouldTimeoutRequest(requestId, sessionTransition) {
|
|
3637
|
+
if (!sessionTransition)
|
|
3638
|
+
return true;
|
|
3639
|
+
return this.native._timeoutSessionTransition(requestId);
|
|
3640
|
+
}
|
|
3641
|
+
get apiVersion() {
|
|
3642
|
+
return this.native.apiVersion();
|
|
3643
|
+
}
|
|
3644
|
+
get tradingDay() {
|
|
3645
|
+
return this.native.tradingDay();
|
|
2791
3646
|
}
|
|
2792
3647
|
/**
|
|
2793
3648
|
* One-call post-connect handshake. Call it from the `front-connected` handler
|
|
2794
3649
|
* (and again after a reconnect): authenticate (if appId/authCode given) →
|
|
2795
|
-
* login → confirm settlement → sync multipliers /
|
|
3650
|
+
* login → confirm settlement → sync multipliers / margin rates / orders /
|
|
3651
|
+
* positions. Each
|
|
2796
3652
|
* step just wraps the matching req / sync method, so you can hand-roll your
|
|
2797
|
-
* own flow instead when you need finer control. Returns the
|
|
2798
|
-
* the sync steps. Must run on a connected
|
|
3653
|
+
* own flow instead when you need finer control. Returns the request-correlated
|
|
3654
|
+
* login identity and row counts from the sync steps. Must run on a connected
|
|
3655
|
+
* front (queries need the session up).
|
|
2799
3656
|
*/
|
|
2800
3657
|
async session(opts) {
|
|
2801
|
-
|
|
3658
|
+
assertObjectKeys(opts, "session options", SESSION_KEYS);
|
|
3659
|
+
const cleanOpts = copyOwnRecord(opts, "session options");
|
|
3660
|
+
const { brokerId, userId, password, appId, authCode } = cleanOpts;
|
|
3661
|
+
const investorId = cleanOpts.investorId ?? userId;
|
|
3662
|
+
if (typeof brokerId !== "string" || !brokerId || brokerId.includes("\0") || typeof userId !== "string" || !userId || userId.includes("\0") || typeof password !== "string" || !password || password.includes("\0")) {
|
|
3663
|
+
throw new TypeError("session requires brokerId, userId and password");
|
|
3664
|
+
}
|
|
3665
|
+
if (typeof investorId !== "string" || !investorId || investorId.includes("\0"))
|
|
3666
|
+
throw new TypeError("session investorId must be a non-empty string");
|
|
3667
|
+
if (cleanOpts.confirmSettlement !== void 0 && typeof cleanOpts.confirmSettlement !== "boolean")
|
|
3668
|
+
throw new TypeError("session.confirmSettlement must be boolean");
|
|
3669
|
+
if (appId === void 0 !== (authCode === void 0)) {
|
|
3670
|
+
throw new TypeError("session appId and authCode must be supplied together");
|
|
3671
|
+
}
|
|
3672
|
+
if (appId !== void 0 && (typeof appId !== "string" || !appId || appId.includes("\0") || typeof authCode !== "string" || !authCode || authCode.includes("\0")))
|
|
3673
|
+
throw new TypeError("session appId and authCode must be non-empty strings");
|
|
3674
|
+
let cleanSync = {};
|
|
3675
|
+
if (cleanOpts.sync !== void 0) {
|
|
3676
|
+
assertObjectKeys(cleanOpts.sync, "session.sync", SESSION_SYNC_KEYS);
|
|
3677
|
+
cleanSync = copyOwnRecord(cleanOpts.sync, "session.sync");
|
|
3678
|
+
const { multipliers, marginRates, positions, orders } = cleanSync;
|
|
3679
|
+
if (multipliers !== void 0 && typeof multipliers !== "boolean")
|
|
3680
|
+
cleanSync.multipliers = copyDenseStringArray(multipliers, "session.sync.multipliers");
|
|
3681
|
+
if (marginRates !== void 0) {
|
|
3682
|
+
assertObjectKeys(marginRates, "session.sync.marginRates", MARGIN_RATE_SYNC_KEYS);
|
|
3683
|
+
const cleanMarginRates = copyOwnRecord(marginRates, "session.sync.marginRates");
|
|
3684
|
+
const instrumentIds = copyDenseStringArray(cleanMarginRates.instrumentIds, "session.sync.marginRates.instrumentIds", false);
|
|
3685
|
+
const hedgeFlag = cleanMarginRates.hedgeFlag;
|
|
3686
|
+
if (typeof hedgeFlag !== "string" || !/^[123567]$/.test(hedgeFlag)) {
|
|
3687
|
+
throw new TypeError("session.sync.marginRates.hedgeFlag must be 1, 2, 3, 5, 6 or 7");
|
|
3688
|
+
}
|
|
3689
|
+
cleanSync.marginRates = {
|
|
3690
|
+
instrumentIds,
|
|
3691
|
+
hedgeFlag
|
|
3692
|
+
};
|
|
3693
|
+
}
|
|
3694
|
+
if (positions !== void 0 && typeof positions !== "boolean")
|
|
3695
|
+
throw new TypeError("session.sync.positions must be boolean");
|
|
3696
|
+
if (orders !== void 0 && typeof orders !== "boolean")
|
|
3697
|
+
throw new TypeError("session.sync.orders must be boolean");
|
|
3698
|
+
}
|
|
3699
|
+
if (appId !== void 0 && authCode !== void 0)
|
|
3700
|
+
this.encode(STRUCT_ID.ReqAuthenticate, { brokerId, userId, appId, authCode });
|
|
3701
|
+
this.encode(STRUCT_ID.ReqUserLogin, { brokerId, userId, password });
|
|
3702
|
+
const encodedAccount = this.encode(STRUCT_ID.SettlementInfoConfirm, { brokerId, investorId });
|
|
3703
|
+
this.native._beginSessionHandshake();
|
|
3704
|
+
this.invalidateRequestContext("trader session started");
|
|
3705
|
+
let contextToken = this.requestContextToken();
|
|
3706
|
+
this.broker = void 0;
|
|
3707
|
+
this.investor = void 0;
|
|
3708
|
+
this.native._markPositionLedgerUncertain();
|
|
3709
|
+
this.native._markOrderLedgerUncertain();
|
|
2802
3710
|
if (appId !== void 0 && authCode !== void 0) {
|
|
2803
3711
|
await this.reqAuthenticate({ brokerId, userId, appId, authCode });
|
|
3712
|
+
this.assertRequestContext(contextToken, "trader session authentication");
|
|
2804
3713
|
}
|
|
2805
|
-
|
|
2806
|
-
|
|
2807
|
-
|
|
3714
|
+
const beforeLoginContext = this.requestContextToken();
|
|
3715
|
+
const beforeLoginTransition = this.requestTransitionToken();
|
|
3716
|
+
const loginRequest = this.reqUserLogin({ brokerId, userId, password });
|
|
3717
|
+
const afterLoginContext = this.requestContextToken();
|
|
3718
|
+
const afterLoginTransition = this.requestTransitionToken();
|
|
3719
|
+
if (afterLoginTransition === beforeLoginTransition + 1 && afterLoginContext === beforeLoginContext + 1) {
|
|
3720
|
+
contextToken = afterLoginContext;
|
|
3721
|
+
} else if (afterLoginTransition === beforeLoginTransition) {
|
|
3722
|
+
contextToken = beforeLoginContext;
|
|
3723
|
+
} else {
|
|
3724
|
+
try {
|
|
3725
|
+
await loginRequest;
|
|
3726
|
+
} catch {
|
|
3727
|
+
}
|
|
3728
|
+
throw new Error("trader session login crossed multiple context transitions");
|
|
3729
|
+
}
|
|
3730
|
+
const login = await loginRequest;
|
|
3731
|
+
this.assertRequestContext(contextToken, "trader session login");
|
|
3732
|
+
if (!login || !Number.isInteger(login.frontId) || login.frontId <= 0 || !Number.isInteger(login.sessionId) || login.sessionId <= 0 || login.brokerId !== brokerId || login.userId !== userId) {
|
|
3733
|
+
this.broker = void 0;
|
|
3734
|
+
this.investor = void 0;
|
|
3735
|
+
throw new Error("trader login response has missing or mismatched session identity");
|
|
3736
|
+
}
|
|
3737
|
+
const maxOrderRef = typeof login.maxOrderRef === "string" ? login.maxOrderRef.trim() : "";
|
|
3738
|
+
if (maxOrderRef !== "" && !/^\d{1,12}$/.test(maxOrderRef)) {
|
|
3739
|
+
this.broker = void 0;
|
|
3740
|
+
this.investor = void 0;
|
|
3741
|
+
throw new Error("trader login response has an invalid MaxOrderRef");
|
|
3742
|
+
}
|
|
3743
|
+
const maxRef = maxOrderRef === "" ? 0 : Number(maxOrderRef);
|
|
3744
|
+
const confirmed = this.native._confirmSessionAccount(login.frontId, login.sessionId, encodedAccount);
|
|
3745
|
+
if (!confirmed) {
|
|
3746
|
+
this.broker = void 0;
|
|
3747
|
+
this.investor = void 0;
|
|
3748
|
+
throw new Error("native Trader session/account confirmation failed");
|
|
2808
3749
|
}
|
|
2809
|
-
|
|
3750
|
+
this.broker = brokerId;
|
|
3751
|
+
this.investor = investorId;
|
|
3752
|
+
if (maxRef > this.orderRefSeq)
|
|
3753
|
+
this.orderRefSeq = maxRef;
|
|
3754
|
+
if (cleanOpts.confirmSettlement ?? true) {
|
|
3755
|
+
await this.reqSettlementInfoConfirm({ brokerId, investorId });
|
|
3756
|
+
this.assertRequestContext(contextToken, "trader session settlement confirmation");
|
|
3757
|
+
}
|
|
3758
|
+
const sync = cleanSync;
|
|
2810
3759
|
const mul = sync.multipliers ?? true;
|
|
2811
|
-
const result = {
|
|
2812
|
-
|
|
3760
|
+
const result = {
|
|
3761
|
+
identity: Object.freeze({
|
|
3762
|
+
frontId: login.frontId,
|
|
3763
|
+
sessionId: login.sessionId,
|
|
3764
|
+
maxOrderRef: maxRef
|
|
3765
|
+
}),
|
|
3766
|
+
multipliers: 0,
|
|
3767
|
+
marginRates: 0,
|
|
3768
|
+
positions: 0,
|
|
3769
|
+
orders: 0
|
|
3770
|
+
};
|
|
3771
|
+
if (mul) {
|
|
2813
3772
|
result.multipliers = await this.syncMultipliers(Array.isArray(mul) ? mul : void 0);
|
|
2814
|
-
|
|
2815
|
-
|
|
2816
|
-
|
|
3773
|
+
this.assertRequestContext(contextToken, "trader session multiplier sync");
|
|
3774
|
+
}
|
|
3775
|
+
const marginRateSync = sync.marginRates;
|
|
3776
|
+
if (marginRateSync !== void 0) {
|
|
3777
|
+
result.marginRates = await this.syncMarginRates(marginRateSync.instrumentIds, marginRateSync.hedgeFlag);
|
|
3778
|
+
this.assertRequestContext(contextToken, "trader session margin sync");
|
|
3779
|
+
}
|
|
3780
|
+
if (sync.orders ?? true) {
|
|
2817
3781
|
result.orders = await this.syncOrders();
|
|
3782
|
+
this.assertRequestContext(contextToken, "trader session order sync");
|
|
3783
|
+
}
|
|
3784
|
+
if (sync.positions ?? true) {
|
|
3785
|
+
result.positions = await this.syncPositions();
|
|
3786
|
+
this.assertRequestContext(contextToken, "trader session position sync");
|
|
3787
|
+
}
|
|
2818
3788
|
return result;
|
|
2819
3789
|
}
|
|
2820
3790
|
/** Assign a unique numeric OrderRef when the caller left it blank. CTP treats
|
|
@@ -2822,10 +3792,83 @@ var Trader = class extends TraderBase {
|
|
|
2822
3792
|
* ref with "不允许重复报单", so an unset ref would otherwise collide. */
|
|
2823
3793
|
withAutoOrderRef(order) {
|
|
2824
3794
|
if (order.orderRef === void 0 || order.orderRef === "") {
|
|
2825
|
-
|
|
3795
|
+
if (this.orderRefSeq >= 999999999999) {
|
|
3796
|
+
throw new RangeError("OrderRef space exhausted for this process/session");
|
|
3797
|
+
}
|
|
3798
|
+
return { ...order, orderRef: String(this.orderRefSeq + 1) };
|
|
3799
|
+
}
|
|
3800
|
+
if (typeof order.orderRef !== "string" || !/^\d{1,12}$/.test(order.orderRef)) {
|
|
3801
|
+
throw new TypeError("orderRef must contain 1..12 decimal digits");
|
|
3802
|
+
}
|
|
3803
|
+
const explicit = Number(order.orderRef);
|
|
3804
|
+
if (explicit <= this.orderRefSeq) {
|
|
3805
|
+
throw new RangeError(`explicit orderRef must be greater than the current high-water mark ${this.orderRefSeq}`);
|
|
2826
3806
|
}
|
|
2827
3807
|
return order;
|
|
2828
3808
|
}
|
|
3809
|
+
commitOrderRef(order) {
|
|
3810
|
+
this.orderRefSeq = Number(order.orderRef);
|
|
3811
|
+
}
|
|
3812
|
+
validateOrder(order, context) {
|
|
3813
|
+
const clean = copyOwnRecord(order, context);
|
|
3814
|
+
if (!this.broker || !this.investor) {
|
|
3815
|
+
throw new Error(`${context}: a confirmed Trader login is required`);
|
|
3816
|
+
}
|
|
3817
|
+
if (typeof clean.instrumentId !== "string" || !clean.instrumentId || clean.instrumentId.includes("\0") || clean.direction !== "0" && clean.direction !== "1") {
|
|
3818
|
+
throw new TypeError(`${context}: instrumentId and direction ("0"/"1") are required`);
|
|
3819
|
+
}
|
|
3820
|
+
if (typeof clean.combOffsetFlag !== "string" || !/^[0-6]$/.test(clean.combOffsetFlag)) {
|
|
3821
|
+
throw new TypeError(`${context}: combOffsetFlag must be one CTP offset digit 0..6; multi-leg orders are unsupported`);
|
|
3822
|
+
}
|
|
3823
|
+
if (clean.combHedgeFlag !== void 0 && (typeof clean.combHedgeFlag !== "string" || !/^[123567]$/.test(clean.combHedgeFlag))) {
|
|
3824
|
+
throw new TypeError(`${context}: combHedgeFlag must be one CTP hedge digit (1, 2, 3, 5, 6 or 7)`);
|
|
3825
|
+
}
|
|
3826
|
+
if (!Number.isInteger(clean.volumeTotalOriginal) || !(Number(clean.volumeTotalOriginal) > 0) || Number(clean.volumeTotalOriginal) > 2147483647) {
|
|
3827
|
+
throw new TypeError(`${context}: volumeTotalOriginal must be a positive int32`);
|
|
3828
|
+
}
|
|
3829
|
+
if (!Number.isFinite(clean.limitPrice) || !(Number(clean.limitPrice) > 0) || Number(clean.limitPrice) >= 1e300) {
|
|
3830
|
+
throw new TypeError(`${context}: limitPrice must be a positive finite price`);
|
|
3831
|
+
}
|
|
3832
|
+
if (clean.brokerId !== void 0 && clean.brokerId !== this.broker) {
|
|
3833
|
+
throw new TypeError(`${context}: brokerId must match the confirmed login`);
|
|
3834
|
+
}
|
|
3835
|
+
if (clean.investorId !== void 0 && clean.investorId !== this.investor) {
|
|
3836
|
+
throw new TypeError(`${context}: investorId must match the confirmed login`);
|
|
3837
|
+
}
|
|
3838
|
+
const value = (key, fallback) => clean[key] === void 0 ? fallback : clean[key];
|
|
3839
|
+
const empty = (v) => v === void 0 || v === "";
|
|
3840
|
+
const timeCondition = value("timeCondition", "3");
|
|
3841
|
+
const volumeCondition = value("volumeCondition", "1");
|
|
3842
|
+
const supportedExecutionPolicy = timeCondition === "3" && volumeCondition === "1" || timeCondition === "1" && (volumeCondition === "1" || volumeCondition === "3");
|
|
3843
|
+
if (value("orderPriceType", "2") !== "2" || !supportedExecutionPolicy || !empty(clean.gtdDate) || 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) {
|
|
3844
|
+
throw new TypeError(`${context}: only single-instrument GFD, FAK or FOK limit orders are supported`);
|
|
3845
|
+
}
|
|
3846
|
+
return {
|
|
3847
|
+
...clean,
|
|
3848
|
+
orderPriceType: "2",
|
|
3849
|
+
combHedgeFlag: clean.combHedgeFlag ?? "1",
|
|
3850
|
+
timeCondition,
|
|
3851
|
+
gtdDate: "",
|
|
3852
|
+
volumeCondition,
|
|
3853
|
+
minVolume: 1,
|
|
3854
|
+
contingentCondition: "1",
|
|
3855
|
+
stopPrice: 0,
|
|
3856
|
+
forceCloseReason: "0",
|
|
3857
|
+
isAutoSuspend: 0,
|
|
3858
|
+
businessUnit: "",
|
|
3859
|
+
requestId: 0,
|
|
3860
|
+
userForceClose: 0,
|
|
3861
|
+
isSwapOrder: 0,
|
|
3862
|
+
exchangeId: "",
|
|
3863
|
+
investUnitId: "",
|
|
3864
|
+
accountId: "",
|
|
3865
|
+
currencyId: "",
|
|
3866
|
+
clientId: "",
|
|
3867
|
+
sessionReqSeq: 0,
|
|
3868
|
+
brokerId: this.broker,
|
|
3869
|
+
investorId: this.investor
|
|
3870
|
+
};
|
|
3871
|
+
}
|
|
2829
3872
|
/**
|
|
2830
3873
|
* Insert an order through the C++ pre-trade risk gate. Resolves on submission:
|
|
2831
3874
|
* CTP sends no success acknowledgement for an accepted order - only
|
|
@@ -2835,31 +3878,50 @@ var Trader = class extends TraderBase {
|
|
|
2835
3878
|
* unique numeric value automatically.
|
|
2836
3879
|
*/
|
|
2837
3880
|
reqOrderInsert(req = {}) {
|
|
2838
|
-
|
|
3881
|
+
const order = this.withAutoOrderRef(this.validateOrder(req, "reqOrderInsert"));
|
|
3882
|
+
this.encode(STRUCT_ID.InputOrder, order);
|
|
3883
|
+
const result = super.reqOrderInsert(order);
|
|
3884
|
+
this.commitOrderRef(order);
|
|
3885
|
+
return result;
|
|
2839
3886
|
}
|
|
2840
3887
|
/** Publish pre-trade risk limits to the C++ enforcer (takes effect at once). */
|
|
2841
|
-
|
|
2842
|
-
|
|
2843
|
-
|
|
2844
|
-
|
|
2845
|
-
|
|
2846
|
-
|
|
2847
|
-
|
|
2848
|
-
assertFiniteLimit("
|
|
2849
|
-
|
|
3888
|
+
setRiskLimits(config) {
|
|
3889
|
+
const clean = copyOwnRecord(config, "setRiskLimits");
|
|
3890
|
+
for (const key of ownStringKeys(clean, "setRiskLimits")) {
|
|
3891
|
+
if (!RISK_LIMIT_KEYS.has(key))
|
|
3892
|
+
throw new TypeError(`setRiskLimits: unknown field ${key}`);
|
|
3893
|
+
}
|
|
3894
|
+
assertPositiveInt32OrDisabled("setRiskLimits.maxOrderVolume", clean.maxOrderVolume);
|
|
3895
|
+
assertFiniteLimit("setRiskLimits.maxPriceDeviation", clean.maxPriceDeviation);
|
|
3896
|
+
assertFiniteLimit("setRiskLimits.maxNotional", clean.maxNotional);
|
|
3897
|
+
assertFiniteLimit("setRiskLimits.maxOrdersPerSec", clean.maxOrdersPerSec);
|
|
3898
|
+
assertFiniteLimit("setRiskLimits.orderBurst", clean.orderBurst);
|
|
3899
|
+
assertFiniteLimit("setRiskLimits.maxCloseOrdersPerSec", clean.maxCloseOrdersPerSec);
|
|
3900
|
+
assertFiniteLimit("setRiskLimits.closeOrderBurst", clean.closeOrderBurst);
|
|
3901
|
+
assertFiniteLimit("setRiskLimits.maxAccountMargin", clean.maxAccountMargin);
|
|
3902
|
+
assertFiniteLimit("setRiskLimits.maxReferenceAgeMs", clean.maxReferenceAgeMs);
|
|
3903
|
+
if (clean.maxReferenceAgeMs !== void 0 && !(clean.maxReferenceAgeMs > 0)) {
|
|
3904
|
+
throw new TypeError("setRiskLimits.maxReferenceAgeMs must be > 0");
|
|
3905
|
+
}
|
|
3906
|
+
this.native.setRiskLimits(clean);
|
|
3907
|
+
return this;
|
|
3908
|
+
}
|
|
3909
|
+
/** Enter REDUCE_ONLY atomically at the final vendor-API send barrier. Armed
|
|
3910
|
+
* opens remain registered but cannot send until resume(). */
|
|
3911
|
+
reduceOnly() {
|
|
3912
|
+
this.native.riskReduceOnly();
|
|
2850
3913
|
return this;
|
|
2851
3914
|
}
|
|
2852
|
-
/**
|
|
2853
|
-
*
|
|
2854
|
-
*
|
|
2855
|
-
*
|
|
2856
|
-
*
|
|
2857
|
-
|
|
2858
|
-
|
|
2859
|
-
this.native.riskHalt();
|
|
3915
|
+
/** Enter HALT_ALL atomically: both opening and closing order inserts, advanced
|
|
3916
|
+
* mutations and bank/futures transfers are refused, and all existing armed
|
|
3917
|
+
* triggers are cleared. New arm() calls are rejected until resume().
|
|
3918
|
+
* Cancellation actions remain available so working
|
|
3919
|
+
* exchange orders can still be withdrawn. */
|
|
3920
|
+
haltAll() {
|
|
3921
|
+
this.native.riskHaltAll();
|
|
2860
3922
|
return this;
|
|
2861
3923
|
}
|
|
2862
|
-
/**
|
|
3924
|
+
/** Return to NORMAL mode after reduceOnly() or haltAll(). */
|
|
2863
3925
|
resume() {
|
|
2864
3926
|
this.native.riskResume();
|
|
2865
3927
|
return this;
|
|
@@ -2868,112 +3930,172 @@ var Trader = class extends TraderBase {
|
|
|
2868
3930
|
* Wires the feed's C++ snapshot cache straight into this Trader's risk engine,
|
|
2869
3931
|
* so the deviation check reads current prices in C++ on the order path (no JS
|
|
2870
3932
|
* round-trip, and it also covers armed orders that fire with no JS in the loop).
|
|
2871
|
-
* Without
|
|
3933
|
+
* Without a fresh reference, an enabled deviation check fails closed. */
|
|
2872
3934
|
trackMarketData(md) {
|
|
2873
3935
|
this.native._attachSnapshot(md._snapshotExternal());
|
|
2874
3936
|
return this;
|
|
2875
3937
|
}
|
|
2876
3938
|
// Contract multipliers (for cost accounting) and margin rates (for the
|
|
2877
|
-
//
|
|
3939
|
+
// maxAccountMargin cap) are NOT fed from JS: the C++ risk engine sources them directly
|
|
2878
3940
|
// from CTP's OnRspQryInstrument / OnRspQryInstrumentMarginRate callbacks (see
|
|
2879
3941
|
// scripts/codegen/generate-trader.mjs). So any reqQryInstrument keeps
|
|
2880
3942
|
// multipliers current, and querying reqQryInstrumentMarginRate for the
|
|
2881
|
-
//
|
|
2882
|
-
//
|
|
3943
|
+
// syncMarginRates() loads investor plus exchange-base schedules. Missing
|
|
3944
|
+
// metadata fails closed; IsRelative is combined with the matching base.
|
|
2883
3945
|
/**
|
|
2884
3946
|
* Cap the open position (in lots) for one instrument, enforced in C++ on
|
|
2885
3947
|
* every opening order. Pass a number to cap both sides at once, or
|
|
2886
3948
|
* `{ long, short }` to cap each side separately. Within `{ long, short }`,
|
|
2887
3949
|
* **omitting a side leaves that side's current cap unchanged** (on a re-call it
|
|
2888
|
-
* is NOT reset to uncapped), and passing
|
|
3950
|
+
* is NOT reset to uncapped), and passing `0` for a side removes its cap.
|
|
2889
3951
|
* Long and short are always tracked independently.
|
|
2890
3952
|
*
|
|
2891
|
-
*
|
|
2892
|
-
* so rapid bursts of opens can momentarily overshoot before the fills land —
|
|
2893
|
-
* size the cap with that in mind.
|
|
3953
|
+
* Held positions and in-flight working opens are counted atomically.
|
|
2894
3954
|
*
|
|
2895
|
-
* td.
|
|
2896
|
-
* td.
|
|
3955
|
+
* td.setInstrumentPositionLimit("rb2610", 100);
|
|
3956
|
+
* td.setInstrumentPositionLimit("ru2610", { long: 100, short: 20 });
|
|
2897
3957
|
*/
|
|
2898
|
-
|
|
2899
|
-
|
|
2900
|
-
|
|
2901
|
-
|
|
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
|
-
}
|
|
3958
|
+
setInstrumentPositionLimit(instrumentId, limit) {
|
|
3959
|
+
assertInstrumentId("setInstrumentPositionLimit", instrumentId);
|
|
3960
|
+
const row = this.normalizePositionLimit(instrumentId, limit);
|
|
3961
|
+
this.native._setInstrumentPositionLimits([row]);
|
|
2911
3962
|
return this;
|
|
2912
3963
|
}
|
|
2913
3964
|
/** Cap several instruments at once, e.g.
|
|
2914
3965
|
* `{ rb2610: 100, ru2610: { long: 100, short: 20 } }`. */
|
|
2915
|
-
|
|
2916
|
-
|
|
2917
|
-
|
|
3966
|
+
setInstrumentPositionLimits(limits) {
|
|
3967
|
+
const rows = ownStringKeys(limits, "setInstrumentPositionLimits").map((instrumentId) => {
|
|
3968
|
+
const limit = limits[instrumentId];
|
|
3969
|
+
assertInstrumentId("setInstrumentPositionLimits", instrumentId);
|
|
3970
|
+
return this.normalizePositionLimit(instrumentId, limit);
|
|
3971
|
+
});
|
|
3972
|
+
this.native._setInstrumentPositionLimits(rows);
|
|
2918
3973
|
return this;
|
|
2919
3974
|
}
|
|
3975
|
+
normalizePositionLimit(instrumentId, limit) {
|
|
3976
|
+
if (typeof limit === "number") {
|
|
3977
|
+
assertLotLimit("setInstrumentPositionLimit", limit);
|
|
3978
|
+
return copyOwnRecord({ instrumentId, long: limit, short: limit }, "setInstrumentPositionLimit");
|
|
3979
|
+
}
|
|
3980
|
+
assertPlainRecord(limit, "setInstrumentPositionLimit");
|
|
3981
|
+
const clean = copyOwnRecord(limit, "setInstrumentPositionLimit");
|
|
3982
|
+
if (clean.long === void 0 && clean.short === void 0) {
|
|
3983
|
+
throw new TypeError("setInstrumentPositionLimit requires a number or at least one of long/short");
|
|
3984
|
+
}
|
|
3985
|
+
for (const key of ownStringKeys(clean, "setInstrumentPositionLimit")) {
|
|
3986
|
+
if (!POSITION_LIMIT_KEYS.has(key))
|
|
3987
|
+
throw new TypeError(`setInstrumentPositionLimit: unknown field ${key}`);
|
|
3988
|
+
}
|
|
3989
|
+
assertLotLimit("setInstrumentPositionLimit.long", clean.long);
|
|
3990
|
+
assertLotLimit("setInstrumentPositionLimit.short", clean.short);
|
|
3991
|
+
return copyOwnRecord({ instrumentId, long: clean.long, short: clean.short }, "setInstrumentPositionLimit");
|
|
3992
|
+
}
|
|
2920
3993
|
/**
|
|
2921
|
-
* Cap one instrument's open
|
|
2922
|
-
* long and short summed
|
|
2923
|
-
*
|
|
2924
|
-
*
|
|
2925
|
-
* `maxCost <= 0` to remove it. Fill-based, same caveat as maxPositionCost.
|
|
3994
|
+
* Cap one instrument's scheduled open margin (CTP by-money + by-volume,
|
|
3995
|
+
* long and short summed), enforced in C++ on every opening order. This is
|
|
3996
|
+
* independent of the account-wide maxAccountMargin cap; both apply. Pass
|
|
3997
|
+
* `limit = 0` to remove it. Held and in-flight exposure both count.
|
|
2926
3998
|
*/
|
|
2927
|
-
|
|
2928
|
-
|
|
2929
|
-
|
|
3999
|
+
setInstrumentMarginLimit(instrumentId, limit) {
|
|
4000
|
+
assertInstrumentId("setInstrumentMarginLimit", instrumentId);
|
|
4001
|
+
assertFiniteLimit("setInstrumentMarginLimit", limit);
|
|
4002
|
+
this.native._setInstrumentMarginLimits([{ instrumentId, limit }]);
|
|
2930
4003
|
return this;
|
|
2931
4004
|
}
|
|
2932
|
-
/** Cap several instruments' open
|
|
4005
|
+
/** Cap several instruments' scheduled open margin at once, e.g.
|
|
2933
4006
|
* `{ ag2608: 2_000_000, au2608: 5_000_000 }`. */
|
|
2934
|
-
|
|
2935
|
-
|
|
2936
|
-
|
|
2937
|
-
|
|
2938
|
-
|
|
4007
|
+
setInstrumentMarginLimits(limits) {
|
|
4008
|
+
const rows = ownStringKeys(limits, "setInstrumentMarginLimits").map((instrumentId) => {
|
|
4009
|
+
const limit = limits[instrumentId];
|
|
4010
|
+
assertInstrumentId("setInstrumentMarginLimits", instrumentId);
|
|
4011
|
+
assertFiniteLimit(`setInstrumentMarginLimits.${instrumentId}`, limit);
|
|
4012
|
+
return { instrumentId, limit };
|
|
4013
|
+
});
|
|
4014
|
+
this.native._setInstrumentMarginLimits(rows);
|
|
2939
4015
|
return this;
|
|
2940
4016
|
}
|
|
2941
|
-
/**
|
|
2942
|
-
*
|
|
2943
|
-
*
|
|
2944
|
-
*
|
|
2945
|
-
|
|
2946
|
-
|
|
2947
|
-
|
|
2948
|
-
|
|
4017
|
+
/** Atomically replace held positions from a complete manually reconciled
|
|
4018
|
+
* snapshot. `margin` is CTP InvestorPosition.UseMargin. An empty array is an
|
|
4019
|
+
* authoritative flat book. Partial/incremental seeding is intentionally not
|
|
4020
|
+
* exposed because armed orders can run between JS calls. */
|
|
4021
|
+
seedPositions(positions) {
|
|
4022
|
+
if (!Array.isArray(positions))
|
|
4023
|
+
throw new TypeError("seedPositions requires a complete position array");
|
|
4024
|
+
const seeds = [];
|
|
4025
|
+
const positionCount = positions.length;
|
|
4026
|
+
for (let i = 0; i < positionCount; i++) {
|
|
4027
|
+
if (!Object.prototype.hasOwnProperty.call(positions, i))
|
|
4028
|
+
throw new TypeError(`seedPositions row ${i} must be an explicit array entry`);
|
|
4029
|
+
const row = copyOwnRecord(positions[i], `seedPositions row ${i}`);
|
|
4030
|
+
for (const key of ownStringKeys(row, `seedPositions row ${i}`))
|
|
4031
|
+
if (!POSITION_SEED_KEYS.has(key))
|
|
4032
|
+
throw new TypeError(`seedPositions row ${i}: unknown field ${key}`);
|
|
4033
|
+
assertInstrumentId("seedPositions", row.instrumentId);
|
|
4034
|
+
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) {
|
|
4035
|
+
throw new TypeError("seedPositions requires long/short, one hedgeFlag digit, a non-negative integer volume and non-negative finite margin");
|
|
4036
|
+
}
|
|
4037
|
+
seeds.push({
|
|
4038
|
+
instrumentId: row.instrumentId,
|
|
4039
|
+
isLong: row.side === "long",
|
|
4040
|
+
hedgeFlag: row.hedgeFlag,
|
|
4041
|
+
volume: row.volume,
|
|
4042
|
+
margin: row.margin
|
|
4043
|
+
});
|
|
4044
|
+
}
|
|
4045
|
+
return this.replacePositionSeeds(seeds);
|
|
2949
4046
|
}
|
|
2950
|
-
|
|
2951
|
-
|
|
2952
|
-
|
|
2953
|
-
|
|
2954
|
-
|
|
2955
|
-
|
|
4047
|
+
replacePositionSeeds(seeds) {
|
|
4048
|
+
for (let attempt = 0; attempt < 5; attempt++) {
|
|
4049
|
+
const revision = this.native.riskRevision();
|
|
4050
|
+
if (this.native.replacePositions(seeds, revision))
|
|
4051
|
+
return this;
|
|
4052
|
+
}
|
|
4053
|
+
throw new Error("position snapshot could not stabilize; live state kept unchanged");
|
|
4054
|
+
}
|
|
4055
|
+
/** Atomically replace held position margin from complete gross-mode query rows
|
|
4056
|
+
* (`posiDirection` '2' long, '3' short). Net/unknown direction is rejected
|
|
4057
|
+
* because guessing a side corrupts per-side volume caps. */
|
|
2956
4058
|
seedFromPositions(positions) {
|
|
4059
|
+
const seeds = this.aggregatePositions(positions);
|
|
4060
|
+
return this.replacePositionSeeds(seeds);
|
|
4061
|
+
}
|
|
4062
|
+
aggregatePositions(positions) {
|
|
4063
|
+
if (!Array.isArray(positions))
|
|
4064
|
+
throw new TypeError("position snapshot must be an array");
|
|
2957
4065
|
const agg = /* @__PURE__ */ new Map();
|
|
2958
|
-
|
|
2959
|
-
|
|
4066
|
+
const positionCount = positions.length;
|
|
4067
|
+
for (let i = 0; i < positionCount; i++) {
|
|
4068
|
+
if (!Object.prototype.hasOwnProperty.call(positions, i))
|
|
4069
|
+
throw new TypeError(`position snapshot row ${i} must be an explicit array entry`);
|
|
4070
|
+
const p = positions[i];
|
|
4071
|
+
const plain = p !== null && typeof p === "object" && !Array.isArray(p) && (Object.getPrototypeOf(p) === Object.prototype || Object.getPrototypeOf(p) === null);
|
|
4072
|
+
const row = plain ? copyOwnRecord(p, "position snapshot row") : void 0;
|
|
4073
|
+
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)) {
|
|
4074
|
+
throw new TypeError(`invalid position snapshot for ${row?.instrumentId || "<unknown>"}`);
|
|
4075
|
+
}
|
|
4076
|
+
if (!(row.position > 0))
|
|
2960
4077
|
continue;
|
|
2961
|
-
const
|
|
2962
|
-
const key = `${
|
|
2963
|
-
const e = agg.get(key) ?? {
|
|
2964
|
-
e.
|
|
2965
|
-
e.
|
|
4078
|
+
const isLong = row.posiDirection === "2";
|
|
4079
|
+
const key = `${row.instrumentId}|${isLong}|${row.hedgeFlag}`;
|
|
4080
|
+
const e = agg.get(key) ?? { instrumentId: row.instrumentId, isLong, hedgeFlag: row.hedgeFlag, volume: 0, margin: 0 };
|
|
4081
|
+
const volume = e.volume + row.position;
|
|
4082
|
+
const margin = e.margin + row.useMargin;
|
|
4083
|
+
if (!Number.isSafeInteger(volume) || !Number.isFinite(margin)) {
|
|
4084
|
+
throw new RangeError(`position snapshot overflow for ${row.instrumentId}`);
|
|
4085
|
+
}
|
|
4086
|
+
e.volume = volume;
|
|
4087
|
+
e.margin = margin;
|
|
2966
4088
|
agg.set(key, e);
|
|
2967
4089
|
}
|
|
2968
|
-
|
|
2969
|
-
this.seedPosition(e.id, e.long ? "long" : "short", e.vol, e.cost);
|
|
2970
|
-
return this;
|
|
4090
|
+
return [...agg.values()];
|
|
2971
4091
|
}
|
|
2972
|
-
/** Current total open-position
|
|
2973
|
-
|
|
2974
|
-
return this.native.
|
|
4092
|
+
/** Current total open-position margin tracked by the C++ risk engine. */
|
|
4093
|
+
get accountMargin() {
|
|
4094
|
+
return this.native.accountMargin();
|
|
2975
4095
|
}
|
|
2976
|
-
/** Clear
|
|
4096
|
+
/** Clear held position state only and mark it uncertain. Working-order
|
|
4097
|
+
* reservations are preserved; openings remain blocked until a complete
|
|
4098
|
+
* seedFromPositions() or syncPositions() succeeds. */
|
|
2977
4099
|
resetPositions() {
|
|
2978
4100
|
this.native.resetPositions();
|
|
2979
4101
|
return this;
|
|
@@ -2986,56 +4108,136 @@ var Trader = class extends TraderBase {
|
|
|
2986
4108
|
* instrument); otherwise empty is returned as-is (e.g. a genuinely flat
|
|
2987
4109
|
* position book, so a flat account doesn't waste the full retry budget).
|
|
2988
4110
|
*/
|
|
2989
|
-
async queryWithRetry(query, requireNonEmpty, attempts = 5) {
|
|
4111
|
+
async queryWithRetry(query, requireNonEmpty, contextToken, attempts = 5) {
|
|
2990
4112
|
let lastErr;
|
|
2991
4113
|
for (let i = 0; i < attempts; i++) {
|
|
2992
|
-
if (i > 0)
|
|
2993
|
-
await sleep(1100);
|
|
2994
4114
|
try {
|
|
4115
|
+
this.assertRequestContext(contextToken, "query synchronization");
|
|
2995
4116
|
const rows = await query();
|
|
4117
|
+
this.assertRequestContext(contextToken, "query synchronization");
|
|
2996
4118
|
if (!requireNonEmpty || rows.length > 0)
|
|
2997
4119
|
return rows;
|
|
2998
4120
|
} catch (e) {
|
|
4121
|
+
this.assertRequestContext(contextToken, "query synchronization");
|
|
4122
|
+
const code = e?.ctpReturnCode;
|
|
4123
|
+
if (code !== -2 && code !== -3)
|
|
4124
|
+
throw e;
|
|
2999
4125
|
lastErr = e;
|
|
3000
4126
|
}
|
|
3001
4127
|
}
|
|
3002
4128
|
if (lastErr)
|
|
3003
4129
|
throw lastErr;
|
|
3004
|
-
|
|
4130
|
+
if (requireNonEmpty)
|
|
4131
|
+
throw new Error(`CTP query returned no rows after ${attempts} attempts`);
|
|
4132
|
+
throw new Error("query retry invariant violated");
|
|
4133
|
+
}
|
|
4134
|
+
/** Empty position/order snapshots are ambiguous immediately after login. Require
|
|
4135
|
+
* the same empty result twice, one query interval apart, before treating it as
|
|
4136
|
+
* authoritative. */
|
|
4137
|
+
async authoritativeQuery(query, contextToken) {
|
|
4138
|
+
const first = await this.queryWithRetry(query, false, contextToken);
|
|
4139
|
+
if (first.length > 0)
|
|
4140
|
+
return first;
|
|
4141
|
+
return this.queryWithRetry(query, false, contextToken);
|
|
3005
4142
|
}
|
|
3006
4143
|
/** Query instruments so the C++ risk engine picks up their multipliers (it
|
|
3007
4144
|
* sources them directly from OnRspQryInstrument — no JS feed). No args queries
|
|
3008
4145
|
* all instruments (one request); otherwise the given symbols. Retries through
|
|
3009
4146
|
* cold-start flow control. Returns the count of contracts with a multiplier. */
|
|
3010
4147
|
async syncMultipliers(instrumentIds) {
|
|
4148
|
+
const contextToken = this.requestContextToken();
|
|
4149
|
+
if (instrumentIds !== void 0) {
|
|
4150
|
+
instrumentIds = copyDenseStringArray(instrumentIds, "syncMultipliers instrumentIds");
|
|
4151
|
+
if (instrumentIds.length === 0)
|
|
4152
|
+
return 0;
|
|
4153
|
+
}
|
|
3011
4154
|
let count = 0;
|
|
3012
4155
|
const apply = (rows) => {
|
|
3013
|
-
|
|
3014
|
-
|
|
4156
|
+
const finalByInstrument = /* @__PURE__ */ new Map();
|
|
4157
|
+
for (const r of rows)
|
|
4158
|
+
finalByInstrument.set(r.instrumentId, r);
|
|
4159
|
+
for (const r of finalByInstrument.values()) {
|
|
4160
|
+
if (r.instrumentId && Number.isFinite(r.volumeMultiple) && r.volumeMultiple > 0 && r.volumeMultiple < 1e300)
|
|
3015
4161
|
count++;
|
|
3016
4162
|
}
|
|
3017
4163
|
};
|
|
3018
|
-
if (instrumentIds
|
|
3019
|
-
for (
|
|
3020
|
-
apply(await this.queryWithRetry(() => this.reqQryInstrument({ instrumentId
|
|
3021
|
-
if (i < instrumentIds.length - 1)
|
|
3022
|
-
await sleep(1100);
|
|
4164
|
+
if (instrumentIds) {
|
|
4165
|
+
for (const instrumentId of new Set(instrumentIds)) {
|
|
4166
|
+
apply(await this.queryWithRetry(async () => (await this.reqQryInstrument({ instrumentId })).filter((row) => row.instrumentId === instrumentId), true, contextToken));
|
|
3023
4167
|
}
|
|
3024
4168
|
} else {
|
|
3025
|
-
apply(await this.queryWithRetry(() => this.reqQryInstrument({}), true));
|
|
4169
|
+
apply(await this.queryWithRetry(() => this.reqQryInstrument({}), true, contextToken));
|
|
3026
4170
|
}
|
|
3027
4171
|
return count;
|
|
3028
4172
|
}
|
|
3029
|
-
/**
|
|
3030
|
-
*
|
|
3031
|
-
*
|
|
3032
|
-
async
|
|
3033
|
-
const
|
|
3034
|
-
|
|
3035
|
-
|
|
3036
|
-
|
|
3037
|
-
|
|
3038
|
-
|
|
4173
|
+
/** Query investor margin schedules for a bounded universe. The exchange-base
|
|
4174
|
+
* query is issued only when the investor row is relative; the shared query
|
|
4175
|
+
* scheduler enforces spacing. Returns the number of usable schedules. */
|
|
4176
|
+
async syncMarginRates(instrumentIds, hedgeFlag = "1") {
|
|
4177
|
+
const contextToken = this.requestContextToken();
|
|
4178
|
+
instrumentIds = copyDenseStringArray(instrumentIds, "syncMarginRates", false);
|
|
4179
|
+
if (typeof hedgeFlag !== "string" || !/^[123567]$/.test(hedgeFlag)) {
|
|
4180
|
+
throw new TypeError("syncMarginRates hedgeFlag must be 1, 2, 3, 5, 6 or 7");
|
|
4181
|
+
}
|
|
4182
|
+
const brokerId = this.broker;
|
|
4183
|
+
const investorId = this.investor;
|
|
4184
|
+
if (!brokerId || !investorId) {
|
|
4185
|
+
throw new Error("syncMarginRates requires a successful trader login first");
|
|
4186
|
+
}
|
|
4187
|
+
let count = 0;
|
|
4188
|
+
for (const instrumentId of new Set(instrumentIds)) {
|
|
4189
|
+
const investorRows = await this.queryWithRetry(async () => (await this.reqQryInstrumentMarginRate({
|
|
4190
|
+
brokerId,
|
|
4191
|
+
investorId,
|
|
4192
|
+
instrumentId,
|
|
4193
|
+
hedgeFlag
|
|
4194
|
+
})).filter((row) => row.instrumentId === instrumentId && row.hedgeFlag === hedgeFlag), true, contextToken);
|
|
4195
|
+
const investor = investorRows.at(-1);
|
|
4196
|
+
const relative = investor.isRelative !== 0;
|
|
4197
|
+
const baseRows = relative ? await this.queryWithRetry(async () => (await this.reqQryExchangeMarginRate({
|
|
4198
|
+
brokerId,
|
|
4199
|
+
instrumentId,
|
|
4200
|
+
hedgeFlag
|
|
4201
|
+
})).filter((row) => row.instrumentId === instrumentId && row.hedgeFlag === hedgeFlag), true, contextToken) : [];
|
|
4202
|
+
const base = baseRows.at(-1);
|
|
4203
|
+
const component = (value) => Number.isFinite(value) && value >= 0 && value < 1e300;
|
|
4204
|
+
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);
|
|
4205
|
+
const investorComponentsValid = component(investor.longMarginRatioByMoney) && component(investor.longMarginRatioByVolume) && component(investor.shortMarginRatioByMoney) && component(investor.shortMarginRatioByVolume);
|
|
4206
|
+
if (investorComponentsValid && (relative ? scheduleUsable(base) : scheduleUsable(investor)))
|
|
4207
|
+
count++;
|
|
4208
|
+
}
|
|
4209
|
+
return count;
|
|
4210
|
+
}
|
|
4211
|
+
/** Replace held position margin from CTP (`reqQryInvestorPosition`). The
|
|
4212
|
+
* replacement is revision-checked: if an order/trade callback races the
|
|
4213
|
+
* snapshot it retries without clearing live state or reservations. */
|
|
4214
|
+
async syncPositions() {
|
|
4215
|
+
const contextToken = this.requestContextToken();
|
|
4216
|
+
if (arguments.length !== 0)
|
|
4217
|
+
throw new TypeError("syncPositions does not accept account overrides");
|
|
4218
|
+
const brokerId = this.broker;
|
|
4219
|
+
const investorId = this.investor;
|
|
4220
|
+
if (typeof brokerId !== "string" || !brokerId || brokerId.includes("\0") || typeof investorId !== "string" || !investorId || investorId.includes("\0"))
|
|
4221
|
+
throw new Error("syncPositions requires a successful trader login");
|
|
4222
|
+
this.native._markPositionLedgerUncertain();
|
|
4223
|
+
for (let attempt = 0; attempt < 5; attempt++) {
|
|
4224
|
+
this.assertRequestContext(contextToken, "position synchronization");
|
|
4225
|
+
const revision = this.native.riskRevision();
|
|
4226
|
+
const rows = await this.authoritativeQuery(async () => {
|
|
4227
|
+
const result = await this.reqQryInvestorPosition({ brokerId, investorId });
|
|
4228
|
+
if (result.some((row) => row.brokerId !== brokerId || row.investorId !== investorId)) {
|
|
4229
|
+
throw new Error("position snapshot contains a mismatched account identity");
|
|
4230
|
+
}
|
|
4231
|
+
return result;
|
|
4232
|
+
}, contextToken);
|
|
4233
|
+
const seeds = this.aggregatePositions(rows);
|
|
4234
|
+
this.assertRequestContext(contextToken, "position synchronization");
|
|
4235
|
+
if (this.native.replacePositions(seeds, revision))
|
|
4236
|
+
return rows.filter((r) => r.position > 0).length;
|
|
4237
|
+
if (attempt < 4)
|
|
4238
|
+
await sleep(100);
|
|
4239
|
+
}
|
|
4240
|
+
throw new Error("position snapshot could not stabilize; live state kept unchanged");
|
|
3039
4241
|
}
|
|
3040
4242
|
/**
|
|
3041
4243
|
* Rebuild the in-flight reservation from CTP's currently-working orders
|
|
@@ -3046,21 +4248,71 @@ var Trader = class extends TraderBase {
|
|
|
3046
4248
|
* of working open orders re-reserved. Run syncMultipliers() first so the
|
|
3047
4249
|
* reserved cost uses the right contract multiplier.
|
|
3048
4250
|
*/
|
|
3049
|
-
async syncOrders(
|
|
3050
|
-
const
|
|
3051
|
-
|
|
3052
|
-
|
|
3053
|
-
const
|
|
3054
|
-
|
|
3055
|
-
|
|
3056
|
-
|
|
3057
|
-
|
|
3058
|
-
|
|
3059
|
-
|
|
3060
|
-
|
|
3061
|
-
|
|
3062
|
-
|
|
3063
|
-
|
|
4251
|
+
async syncOrders() {
|
|
4252
|
+
const contextToken = this.requestContextToken();
|
|
4253
|
+
if (arguments.length !== 0)
|
|
4254
|
+
throw new TypeError("syncOrders does not accept account overrides");
|
|
4255
|
+
const brokerId = this.broker;
|
|
4256
|
+
const investorId = this.investor;
|
|
4257
|
+
if (typeof brokerId !== "string" || !brokerId || brokerId.includes("\0") || typeof investorId !== "string" || !investorId || investorId.includes("\0"))
|
|
4258
|
+
throw new Error("syncOrders requires a successful trader login");
|
|
4259
|
+
this.native._markPositionLedgerUncertain();
|
|
4260
|
+
this.native._markOrderLedgerUncertain();
|
|
4261
|
+
for (let attempt = 0; attempt < 5; attempt++) {
|
|
4262
|
+
this.assertRequestContext(contextToken, "order synchronization");
|
|
4263
|
+
const revision = this.native.riskRevision();
|
|
4264
|
+
const rows = await this.authoritativeQuery(async () => {
|
|
4265
|
+
const result = await this.reqQryOrder({ brokerId, investorId });
|
|
4266
|
+
if (result.some((row) => row.brokerId !== brokerId || row.investorId !== investorId)) {
|
|
4267
|
+
throw new Error("order snapshot contains a mismatched account identity");
|
|
4268
|
+
}
|
|
4269
|
+
return result;
|
|
4270
|
+
}, contextToken);
|
|
4271
|
+
const terminal = /* @__PURE__ */ new Set(["0", "2", "4", "5"]);
|
|
4272
|
+
const active = rows.filter((o) => !terminal.has(o.orderStatus));
|
|
4273
|
+
for (const o of active) {
|
|
4274
|
+
const vol = o.volumeTotalOriginal - o.volumeTraded;
|
|
4275
|
+
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)) {
|
|
4276
|
+
throw new TypeError(`invalid working-order snapshot for ${o.orderRef || "<unknown>"}`);
|
|
4277
|
+
}
|
|
4278
|
+
}
|
|
4279
|
+
const working = active.flatMap((o) => {
|
|
4280
|
+
const vol = o.volumeTotalOriginal - o.volumeTraded;
|
|
4281
|
+
const supportedSingleLeg = /^[0-6]$/.test(o.combOffsetFlag);
|
|
4282
|
+
if (supportedSingleLeg && o.combOffsetFlag !== "0")
|
|
4283
|
+
return [];
|
|
4284
|
+
return [{
|
|
4285
|
+
frontId: o.frontId,
|
|
4286
|
+
sessionId: o.sessionId,
|
|
4287
|
+
orderRef: o.orderRef,
|
|
4288
|
+
instrumentId: o.instrumentId,
|
|
4289
|
+
isLong: o.direction === "0",
|
|
4290
|
+
hedgeFlag: o.combHedgeFlag?.[0] || "1",
|
|
4291
|
+
vol,
|
|
4292
|
+
price: o.limitPrice,
|
|
4293
|
+
traded: o.volumeTraded,
|
|
4294
|
+
// Must be byte-identical to the native realtime key built in
|
|
4295
|
+
// traderspi.gen.cc (OnRtnOrder/OnRtnTrade):
|
|
4296
|
+
// day|broker|investor|exchange|instrument|orderSysId. broker/investor
|
|
4297
|
+
// are the confirmed session identity (validated == every row above),
|
|
4298
|
+
// so a reservation rebuilt on resync correlates with the subsequent
|
|
4299
|
+
// realtime order/trade callbacks instead of being stranded uncertain.
|
|
4300
|
+
orderSysKey: o.tradingDay && o.exchangeId && o.orderSysId ? `${o.tradingDay}|${brokerId}|${investorId}|${o.exchangeId}|${o.instrumentId}|${o.orderSysId}` : "",
|
|
4301
|
+
supportedSingleLeg
|
|
4302
|
+
}];
|
|
4303
|
+
});
|
|
4304
|
+
this.assertRequestContext(contextToken, "order synchronization");
|
|
4305
|
+
if (this.native.rebuildReservations(working, revision)) {
|
|
4306
|
+
const unsupported = working.filter((o) => !o.supportedSingleLeg);
|
|
4307
|
+
if (unsupported.length > 0) {
|
|
4308
|
+
throw new Error(`unsupported working order ${unsupported[0].orderRef}; opening inserts are fail-closed`);
|
|
4309
|
+
}
|
|
4310
|
+
return working.length;
|
|
4311
|
+
}
|
|
4312
|
+
if (attempt < 4)
|
|
4313
|
+
await sleep(100);
|
|
4314
|
+
}
|
|
4315
|
+
throw new Error("order snapshot could not stabilize; live state kept unchanged");
|
|
3064
4316
|
}
|
|
3065
4317
|
/**
|
|
3066
4318
|
* Arm a latency-critical trigger: when `md` sees the condition, the order is
|
|
@@ -3069,23 +4321,34 @@ var Trader = class extends TraderBase {
|
|
|
3069
4321
|
* rtn-order / rsp-order-insert events (correlate by the order's orderRef).
|
|
3070
4322
|
*/
|
|
3071
4323
|
arm(md, spec) {
|
|
3072
|
-
|
|
4324
|
+
const cleanSpec = copyOwnRecord(spec, "arm spec");
|
|
4325
|
+
assertObjectKeys(cleanSpec, "arm spec", ARM_SPEC_KEYS);
|
|
4326
|
+
if (!cleanSpec.instrumentId || cleanSpec.instrumentId.includes("\0") || !Number.isFinite(cleanSpec.triggerPrice) || !(cleanSpec.triggerPrice > 0) || cleanSpec.triggerPrice >= 1e300) {
|
|
3073
4327
|
throw new Error("arm: spec.instrumentId and a positive triggerPrice are required");
|
|
3074
4328
|
}
|
|
3075
|
-
const
|
|
3076
|
-
if (
|
|
3077
|
-
throw new Error("arm: spec.
|
|
4329
|
+
const validatedOrder = this.validateOrder(cleanSpec.order, "arm.order");
|
|
4330
|
+
if (cleanSpec.side !== "buy" && cleanSpec.side !== "sell") {
|
|
4331
|
+
throw new Error("arm: spec.side must be buy or sell");
|
|
3078
4332
|
}
|
|
3079
|
-
|
|
4333
|
+
if (validatedOrder.instrumentId !== cleanSpec.instrumentId) {
|
|
4334
|
+
throw new Error("arm: spec.instrumentId must match spec.order.instrumentId");
|
|
4335
|
+
}
|
|
4336
|
+
if (cleanSpec.side === "buy" !== (validatedOrder.direction === "0")) {
|
|
4337
|
+
throw new Error("arm: spec.side must match spec.order.direction");
|
|
4338
|
+
}
|
|
4339
|
+
const order = this.withAutoOrderRef(validatedOrder);
|
|
3080
4340
|
const bytes = this.encode(STRUCT_ID.InputOrder, order);
|
|
3081
|
-
|
|
4341
|
+
md.attachArm(this);
|
|
4342
|
+
this.trackMarketData(md);
|
|
4343
|
+
const id = this.native.arm(cleanSpec.instrumentId, cleanSpec.side === "buy" ? "0" : "1", cleanSpec.triggerPrice, bytes);
|
|
4344
|
+
this.commitOrderRef(order);
|
|
3082
4345
|
return { id, disarm: () => this.native.disarm(id) };
|
|
3083
4346
|
}
|
|
3084
4347
|
/** Observability for armed triggers (they fire in C++ with no JS in the loop):
|
|
3085
4348
|
* how many fired and were sent vs were refused by the risk gate / send.
|
|
3086
4349
|
* A blocked armed order is otherwise invisible, so poll this after a trigger
|
|
3087
4350
|
* you expected to fire. */
|
|
3088
|
-
armStats() {
|
|
4351
|
+
get armStats() {
|
|
3089
4352
|
return { fired: this.native._armFireCount(), blocked: this.native._armBlockedCount() };
|
|
3090
4353
|
}
|
|
3091
4354
|
/** @internal used by MarketData.attachArm to share the arm registry. */
|
|
@@ -3105,6 +4368,235 @@ var Trader = class extends TraderBase {
|
|
|
3105
4368
|
}
|
|
3106
4369
|
};
|
|
3107
4370
|
|
|
4371
|
+
// dist/market-data.js
|
|
4372
|
+
var MD_BASE = 4096;
|
|
4373
|
+
var MD_EVENTS = /* @__PURE__ */ new Map([
|
|
4374
|
+
[MD_BASE + 1, "front-connected"],
|
|
4375
|
+
[MD_BASE + 2, "front-disconnected"],
|
|
4376
|
+
[MD_BASE + 3, "heart-beat-warning"],
|
|
4377
|
+
[MD_BASE + 4, "rsp-user-login"],
|
|
4378
|
+
[MD_BASE + 5, "rsp-user-logout"],
|
|
4379
|
+
[MD_BASE + 6, "rsp-qry-multicast-instrument"],
|
|
4380
|
+
[MD_BASE + 7, "rsp-error"],
|
|
4381
|
+
[MD_BASE + 8, "rsp-sub-market-data"],
|
|
4382
|
+
[MD_BASE + 9, "rsp-unsub-market-data"],
|
|
4383
|
+
[MD_BASE + 10, "rsp-sub-for-quote"],
|
|
4384
|
+
[MD_BASE + 11, "rsp-unsub-for-quote"],
|
|
4385
|
+
[MD_BASE + 12, "rtn-depth-market-data"],
|
|
4386
|
+
[MD_BASE + 13, "rtn-for-quote"]
|
|
4387
|
+
]);
|
|
4388
|
+
var MarketDataEvent;
|
|
4389
|
+
(function(MarketDataEvent2) {
|
|
4390
|
+
MarketDataEvent2["FrontConnected"] = "front-connected";
|
|
4391
|
+
MarketDataEvent2["FrontDisconnected"] = "front-disconnected";
|
|
4392
|
+
MarketDataEvent2["HeartBeatWarning"] = "heart-beat-warning";
|
|
4393
|
+
MarketDataEvent2["RspUserLogin"] = "rsp-user-login";
|
|
4394
|
+
MarketDataEvent2["RspUserLogout"] = "rsp-user-logout";
|
|
4395
|
+
MarketDataEvent2["RspQryMulticastInstrument"] = "rsp-qry-multicast-instrument";
|
|
4396
|
+
MarketDataEvent2["RspError"] = "rsp-error";
|
|
4397
|
+
MarketDataEvent2["RspSubMarketData"] = "rsp-sub-market-data";
|
|
4398
|
+
MarketDataEvent2["RspUnSubMarketData"] = "rsp-unsub-market-data";
|
|
4399
|
+
MarketDataEvent2["RspSubForQuote"] = "rsp-sub-for-quote";
|
|
4400
|
+
MarketDataEvent2["RspUnSubForQuote"] = "rsp-unsub-for-quote";
|
|
4401
|
+
MarketDataEvent2["RtnDepthMarketData"] = "rtn-depth-market-data";
|
|
4402
|
+
MarketDataEvent2["RtnForQuote"] = "rtn-for-quote";
|
|
4403
|
+
})(MarketDataEvent || (MarketDataEvent = {}));
|
|
4404
|
+
function snapshotInstrumentIds(instrumentIds) {
|
|
4405
|
+
return copyDenseStringArray(instrumentIds, "instrumentIds");
|
|
4406
|
+
}
|
|
4407
|
+
function requestShapeError(value, allowed, label) {
|
|
4408
|
+
let keys;
|
|
4409
|
+
try {
|
|
4410
|
+
keys = ownStringKeys(value, label);
|
|
4411
|
+
} catch (error) {
|
|
4412
|
+
return error instanceof TypeError ? error : new TypeError(`${label} must be a plain object`);
|
|
4413
|
+
}
|
|
4414
|
+
for (const key of keys)
|
|
4415
|
+
if (!allowed.has(key))
|
|
4416
|
+
return new TypeError(`${label}: unknown field ${key}`);
|
|
4417
|
+
return void 0;
|
|
4418
|
+
}
|
|
4419
|
+
var LOGIN_KEYS = /* @__PURE__ */ new Set([
|
|
4420
|
+
"tradingDay",
|
|
4421
|
+
"brokerId",
|
|
4422
|
+
"userId",
|
|
4423
|
+
"password",
|
|
4424
|
+
"userProductInfo",
|
|
4425
|
+
"interfaceProductInfo",
|
|
4426
|
+
"protocolInfo",
|
|
4427
|
+
"macAddress",
|
|
4428
|
+
"oneTimePassword",
|
|
4429
|
+
"loginRemark",
|
|
4430
|
+
"clientIpPort",
|
|
4431
|
+
"clientIpAddress",
|
|
4432
|
+
"smsCode"
|
|
4433
|
+
]);
|
|
4434
|
+
var LOGOUT_KEYS = /* @__PURE__ */ new Set(["brokerId", "userId"]);
|
|
4435
|
+
var MULTICAST_QUERY_KEYS = /* @__PURE__ */ new Set(["topicId", "instrumentId"]);
|
|
4436
|
+
var MarketData = class extends CtpClient {
|
|
4437
|
+
sessionTransition;
|
|
4438
|
+
constructor(flowPath, fronts) {
|
|
4439
|
+
super(new native.MarketData(flowPath, copyOwnFronts(fronts, "MarketData fronts")), native.__layoutData(), MD_EVENTS);
|
|
4440
|
+
this.start();
|
|
4441
|
+
}
|
|
4442
|
+
get apiVersion() {
|
|
4443
|
+
return this.native.apiVersion();
|
|
4444
|
+
}
|
|
4445
|
+
get tradingDay() {
|
|
4446
|
+
return this.native.tradingDay();
|
|
4447
|
+
}
|
|
4448
|
+
/** Subscribe to depth market data. Returns the CTP send code (0 = ok). */
|
|
4449
|
+
subscribe(instrumentIds) {
|
|
4450
|
+
const ids = snapshotInstrumentIds(instrumentIds);
|
|
4451
|
+
return this.native.subscribeMarketData(ids);
|
|
4452
|
+
}
|
|
4453
|
+
unsubscribe(instrumentIds) {
|
|
4454
|
+
const ids = snapshotInstrumentIds(instrumentIds);
|
|
4455
|
+
return this.native.unsubscribeMarketData(ids);
|
|
4456
|
+
}
|
|
4457
|
+
subscribeForQuote(instrumentIds) {
|
|
4458
|
+
const ids = snapshotInstrumentIds(instrumentIds);
|
|
4459
|
+
return this.native.subscribeForQuoteRsp(ids);
|
|
4460
|
+
}
|
|
4461
|
+
unsubscribeForQuote(instrumentIds) {
|
|
4462
|
+
const ids = snapshotInstrumentIds(instrumentIds);
|
|
4463
|
+
return this.native.unsubscribeForQuoteRsp(ids);
|
|
4464
|
+
}
|
|
4465
|
+
/** Latest cached depth tick for an instrument — the C++ last-value cache,
|
|
4466
|
+
* updated on every authenticated-session tick before it reaches JS. Returns
|
|
4467
|
+
* null before login, after disconnect/logout, if none has been seen, or if it
|
|
4468
|
+
* was unsubscribed. Synchronous: no waiting for an event. */
|
|
4469
|
+
snapshot(instrumentId) {
|
|
4470
|
+
const bytes = this.native.snapshot(instrumentId);
|
|
4471
|
+
return bytes ? this.decodeStruct(STRUCT_ID.DepthMarketData, bytes) : null;
|
|
4472
|
+
}
|
|
4473
|
+
/** Latest price for an instrument from the cache (0 if none seen). Synchronous. */
|
|
4474
|
+
last(instrumentId) {
|
|
4475
|
+
return this.native.last(instrumentId);
|
|
4476
|
+
}
|
|
4477
|
+
/** @internal Hand the C++ snapshot cache to a Trader (Trader.trackMarketData),
|
|
4478
|
+
* so the Trader's deviation check reads live prices in C++ — no JS round-trip. */
|
|
4479
|
+
_snapshotExternal() {
|
|
4480
|
+
return this.native._snapshotExternal();
|
|
4481
|
+
}
|
|
4482
|
+
/** Log in; resolves with the login response (or rejects on CTP error). */
|
|
4483
|
+
login(req = {}) {
|
|
4484
|
+
const shapeError = requestShapeError(req, LOGIN_KEYS, "login request");
|
|
4485
|
+
if (shapeError)
|
|
4486
|
+
return Promise.reject(shapeError);
|
|
4487
|
+
const clean = copyOwnRecord(req, "login request");
|
|
4488
|
+
let encoded;
|
|
4489
|
+
try {
|
|
4490
|
+
encoded = this.encode(STRUCT_ID.ReqUserLogin, clean);
|
|
4491
|
+
} catch (error) {
|
|
4492
|
+
return Promise.reject(error);
|
|
4493
|
+
}
|
|
4494
|
+
return this.runSessionTransition(() => {
|
|
4495
|
+
this.beginRequestContextTransition("market-data login started");
|
|
4496
|
+
return this.request((id) => this.native.reqUserLogin(encoded, id), true, MD_BASE + 4, true);
|
|
4497
|
+
});
|
|
4498
|
+
}
|
|
4499
|
+
logout(req = {}) {
|
|
4500
|
+
const shapeError = requestShapeError(req, LOGOUT_KEYS, "logout request");
|
|
4501
|
+
if (shapeError)
|
|
4502
|
+
return Promise.reject(shapeError);
|
|
4503
|
+
const clean = copyOwnRecord(req, "logout request");
|
|
4504
|
+
let encoded;
|
|
4505
|
+
try {
|
|
4506
|
+
encoded = this.encode(STRUCT_ID.UserLogout, clean);
|
|
4507
|
+
} catch (error) {
|
|
4508
|
+
return Promise.reject(error);
|
|
4509
|
+
}
|
|
4510
|
+
return this.runSessionTransition(() => {
|
|
4511
|
+
this.beginRequestContextTransition("market-data logout started");
|
|
4512
|
+
return this.request((id) => this.native.reqUserLogout(encoded, id), true, MD_BASE + 5, true);
|
|
4513
|
+
});
|
|
4514
|
+
}
|
|
4515
|
+
shouldTimeoutRequest(requestId, sessionTransition) {
|
|
4516
|
+
if (!sessionTransition)
|
|
4517
|
+
return true;
|
|
4518
|
+
return this.native._timeoutSessionTransition(requestId);
|
|
4519
|
+
}
|
|
4520
|
+
// MarketData confirms a successful login natively: OnRspUserLogin activates the
|
|
4521
|
+
// snapshot cache on the MD channel, which legitimately carries no
|
|
4522
|
+
// FrontID/SessionID (those are the trade front's order-routing identity). There
|
|
4523
|
+
// is deliberately no onRequestResolved override here — the base no-op is
|
|
4524
|
+
// correct, and a successful MD login must never be rejected for lacking a trade
|
|
4525
|
+
// session id.
|
|
4526
|
+
/** SimNow may return requestId=0 for MD login/logout. Never overlap these
|
|
4527
|
+
* transitions: otherwise a late id-0 login response cannot be attributed to
|
|
4528
|
+
* one epoch. If a request times out while native still considers it pending,
|
|
4529
|
+
* native stays fail-closed until the next front transition. */
|
|
4530
|
+
runSessionTransition(start) {
|
|
4531
|
+
if (this.sessionTransition) {
|
|
4532
|
+
return Promise.reject(new Error("market-data login/logout transition already in flight; await it first"));
|
|
4533
|
+
}
|
|
4534
|
+
const promise = start();
|
|
4535
|
+
this.sessionTransition = promise;
|
|
4536
|
+
const finish = () => {
|
|
4537
|
+
if (this.sessionTransition !== promise)
|
|
4538
|
+
return;
|
|
4539
|
+
try {
|
|
4540
|
+
this.native._abandonSessionTransition();
|
|
4541
|
+
} catch {
|
|
4542
|
+
} finally {
|
|
4543
|
+
this.sessionTransition = void 0;
|
|
4544
|
+
}
|
|
4545
|
+
};
|
|
4546
|
+
void promise.then(finish, finish);
|
|
4547
|
+
return promise;
|
|
4548
|
+
}
|
|
4549
|
+
/** Query multicast instruments. Multi-row response, serialized through this
|
|
4550
|
+
* client's conservative query scheduler. */
|
|
4551
|
+
reqQryMulticastInstrument(req = {}) {
|
|
4552
|
+
const shapeError = requestShapeError(req, MULTICAST_QUERY_KEYS, "multicast query");
|
|
4553
|
+
if (shapeError)
|
|
4554
|
+
return Promise.reject(shapeError);
|
|
4555
|
+
const clean = copyOwnRecord(req, "multicast query");
|
|
4556
|
+
return this.queryRequest((id) => this.native.reqQryMulticastInstrument(clean, id));
|
|
4557
|
+
}
|
|
4558
|
+
/** Route this market data's ticks to a Trader's armed triggers (see Trader.arm).
|
|
4559
|
+
* A MarketData feeds exactly one live Trader's registry. Native ownership
|
|
4560
|
+
* rejects replacement while that Trader is live, but permits replacing a
|
|
4561
|
+
* registry whose Trader has already closed. */
|
|
4562
|
+
attachArm(trader) {
|
|
4563
|
+
if (!(trader instanceof Trader))
|
|
4564
|
+
throw new TypeError("attachArm requires a Trader from this package instance");
|
|
4565
|
+
const registry = trader._armRegistry();
|
|
4566
|
+
this.native._attachArm(registry);
|
|
4567
|
+
}
|
|
4568
|
+
/** @internal test-only: inject a synthetic depth tick into the ring. Optional
|
|
4569
|
+
* bid/ask override the defaults (3499/3501) so tests can drive edge prices
|
|
4570
|
+
* (e.g. a DBL_MAX no-bid sentinel) through the real arm/onTick path. */
|
|
4571
|
+
_injectTestTick(bid, ask) {
|
|
4572
|
+
this.native._injectTestTick(bid, ask);
|
|
4573
|
+
}
|
|
4574
|
+
/** @internal test-only: inject one RFQ business notification through MdSpi. */
|
|
4575
|
+
_injectTestForQuote() {
|
|
4576
|
+
this.native._injectTestForQuote();
|
|
4577
|
+
}
|
|
4578
|
+
/** @internal test-only: drive a real native MD lifecycle callback. */
|
|
4579
|
+
_injectTestLifecycle(state) {
|
|
4580
|
+
this.native._injectTestLifecycle(state);
|
|
4581
|
+
}
|
|
4582
|
+
/** @internal test-only: spawn a background producer thread that pushes `n`
|
|
4583
|
+
* synthetic ticks into the ring (cross-thread doorbell stress). Each tick's
|
|
4584
|
+
* requestId carries its sequence number. */
|
|
4585
|
+
_burstTicks(n, jitterUs = 0, injectControl = false) {
|
|
4586
|
+
this.native._burstTicks(n, jitterUs, injectControl);
|
|
4587
|
+
}
|
|
4588
|
+
/** @internal test-only: produce ticks on a native background thread through
|
|
4589
|
+
* the real MD SPI. `ratePerSecond=0` is an instantaneous burst; otherwise
|
|
4590
|
+
* ticks arrive as paced `burstSize` batches. Instrument IDs rotate across
|
|
4591
|
+
* SIM00000000.. and `volume` is the zero-based global sequence. */
|
|
4592
|
+
_produceTestTicks(count, instrumentCount, ratePerSecond = 0, burstSize = 512) {
|
|
4593
|
+
this.native._produceTestTicks(count, instrumentCount, ratePerSecond, burstSize);
|
|
4594
|
+
}
|
|
4595
|
+
on(event, cb) {
|
|
4596
|
+
return super.on(event, cb);
|
|
4597
|
+
}
|
|
4598
|
+
};
|
|
4599
|
+
|
|
3108
4600
|
// dist/generated/enums.gen.js
|
|
3109
4601
|
var ExchangeProperty;
|
|
3110
4602
|
(function(ExchangeProperty2) {
|