@hitrading/ctp-node 1.2.0 → 3.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +67 -0
- package/README.md +52 -31
- package/README.zh-CN.md +42 -26
- package/RELEASING.md +78 -0
- package/binding.gyp +13 -13
- package/dist/client.d.ts +40 -15
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +241 -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 +1896 -420
- 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 +48 -21
- package/dist/market-data.d.ts.map +1 -1
- package/dist/market-data.js +165 -26
- package/dist/market-data.js.map +1 -1
- package/dist/native-binding.d.ts.map +1 -1
- package/dist/native-binding.js +5 -1
- package/dist/native-binding.js.map +1 -1
- package/dist/trader.d.ts +127 -79
- package/dist/trader.d.ts.map +1 -1
- package/dist/trader.js +788 -200
- 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 +1437 -0
- package/docs/API.zh-CN.md +1278 -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 +14 -6
- 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 +263 -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 +130 -10
- package/src/generated/traderspi.gen.h +4 -2
- package/src/index.ts +8 -1
- package/src/market-data.ts +219 -43
- 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 +621 -61
- package/src/native/mdspi.cc +221 -14
- package/src/native/mdspi.h +62 -9
- package/src/native/order_capability.h +75 -0
- package/src/native/risk.cc +2051 -205
- package/src/native/risk.h +450 -57
- package/src/native/shared_handle.h +37 -0
- package/src/native/snapshot.h +120 -0
- package/src/native/traderapi.cc +749 -170
- package/src/native-binding.ts +5 -1
- package/src/trader.ts +993 -229
- package/src/validation.ts +96 -0
- /package/{tradeapi → ctpsdk}/ThostFtdcMdApi.h +0 -0
- /package/{tradeapi → ctpsdk}/ThostFtdcTraderApi.h +0 -0
- /package/{tradeapi → ctpsdk}/ThostFtdcUserApiDataType.h +0 -0
- /package/{tradeapi → ctpsdk}/ThostFtdcUserApiStruct.h +0 -0
- /package/{tradeapi → ctpsdk}/error.dtd +0 -0
- /package/{tradeapi → ctpsdk}/error.xml +0 -0
- /package/{tradeapi → ctpsdk}/linux/thostmduserapi_se.so +0 -0
- /package/{tradeapi → ctpsdk}/linux/thosttraderapi_se.so +0 -0
- /package/{tradeapi → ctpsdk}/macos/thostmduserapi_se.framework/Versions/A/Headers/ThostFtdcMdApi.h +0 -0
- /package/{tradeapi → ctpsdk}/macos/thostmduserapi_se.framework/Versions/A/Headers/ThostFtdcUserApiDataType.h +0 -0
- /package/{tradeapi → ctpsdk}/macos/thostmduserapi_se.framework/Versions/A/Headers/ThostFtdcUserApiStruct.h +0 -0
- /package/{tradeapi → ctpsdk}/macos/thostmduserapi_se.framework/Versions/A/Resources/Info.plist +0 -0
- /package/{tradeapi → ctpsdk}/macos/thostmduserapi_se.framework/Versions/A/_CodeSignature/CodeResources +0 -0
- /package/{tradeapi → ctpsdk}/macos/thostmduserapi_se.framework/Versions/A/thostmduserapi_se +0 -0
- /package/{tradeapi → ctpsdk}/macos/thosttraderapi_se.framework/Versions/A/Headers/ThostFtdcTraderApi.h +0 -0
- /package/{tradeapi → ctpsdk}/macos/thosttraderapi_se.framework/Versions/A/Headers/ThostFtdcUserApiDataType.h +0 -0
- /package/{tradeapi → ctpsdk}/macos/thosttraderapi_se.framework/Versions/A/Headers/ThostFtdcUserApiStruct.h +0 -0
- /package/{tradeapi → ctpsdk}/macos/thosttraderapi_se.framework/Versions/A/Resources/Info.plist +0 -0
- /package/{tradeapi → ctpsdk}/macos/thosttraderapi_se.framework/Versions/A/_CodeSignature/CodeResources +0 -0
- /package/{tradeapi → ctpsdk}/macos/thosttraderapi_se.framework/Versions/A/thosttraderapi_se +0 -0
- /package/{tradeapi → ctpsdk}/windows/thostmduserapi_se.dll +0 -0
- /package/{tradeapi → ctpsdk}/windows/thostmduserapi_se.lib +0 -0
- /package/{tradeapi → ctpsdk}/windows/thosttraderapi_se.dll +0 -0
- /package/{tradeapi → ctpsdk}/windows/thosttraderapi_se.lib +0 -0
package/dist/index.cjs
CHANGED
|
@@ -373,7 +373,7 @@ var import_node_process = __toESM(require("node:process"), 1);
|
|
|
373
373
|
var require2 = (0, import_node_module.createRequire)(import_meta_url_shim);
|
|
374
374
|
var pkgRoot = (0, import_node_path.join)((0, import_node_path.dirname)((0, import_node_url.fileURLToPath)(import_meta_url_shim)), "..");
|
|
375
375
|
if (import_node_process.default.platform === "win32") {
|
|
376
|
-
import_node_process.default.env.PATH = `${(0, import_node_path.join)(pkgRoot, "
|
|
376
|
+
import_node_process.default.env.PATH = `${(0, import_node_path.join)(pkgRoot, "ctpsdk", "windows")};${import_node_process.default.env.PATH ?? ""}`;
|
|
377
377
|
}
|
|
378
378
|
var loadAddon = require2("node-gyp-build");
|
|
379
379
|
var native = loadAddon(pkgRoot);
|
|
@@ -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();
|
|
@@ -1671,6 +1845,13 @@ var CtpClient = class extends import_node_events.EventEmitter {
|
|
|
1671
1845
|
}
|
|
1672
1846
|
return d;
|
|
1673
1847
|
}
|
|
1848
|
+
/** Decode one struct's raw bytes (e.g. a native snapshot) into a plain object,
|
|
1849
|
+
* reusing the lazily-built per-struct decoder — the same codec the ring uses,
|
|
1850
|
+
* so the result is identical to a streamed record. */
|
|
1851
|
+
decodeStruct(structId, bytes) {
|
|
1852
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
1853
|
+
return this.decoderFor(structId)(view, bytes, 0);
|
|
1854
|
+
}
|
|
1674
1855
|
drain() {
|
|
1675
1856
|
let count = this.native._claim();
|
|
1676
1857
|
while (count > 0) {
|
|
@@ -1694,13 +1875,9 @@ var CtpClient = class extends import_node_events.EventEmitter {
|
|
|
1694
1875
|
}
|
|
1695
1876
|
}
|
|
1696
1877
|
/**
|
|
1697
|
-
*
|
|
1698
|
-
*
|
|
1699
|
-
*
|
|
1700
|
-
* many of the oldest records it overwrote *during* that decode (validate()),
|
|
1701
|
-
* discard those (they hold torn bytes), and only then deliver the rest — so a
|
|
1702
|
-
* torn record never reaches a handler. The records we do deliver are always the
|
|
1703
|
-
* 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.
|
|
1704
1881
|
*/
|
|
1705
1882
|
drainOldest() {
|
|
1706
1883
|
let count = this.native._claim();
|
|
@@ -1715,15 +1892,12 @@ var CtpClient = class extends import_node_events.EventEmitter {
|
|
|
1715
1892
|
const slot = (this.readPos + i) % numSlots * slotSize;
|
|
1716
1893
|
batch[i] = this.decodeSlot(slot);
|
|
1717
1894
|
}
|
|
1718
|
-
const torn = this.native._validate(count);
|
|
1719
|
-
for (let i = 0; i < torn; i++)
|
|
1720
|
-
batch[i] = void 0;
|
|
1721
1895
|
if (this.closing) {
|
|
1722
|
-
for (let i =
|
|
1896
|
+
for (let i = 0; i < count; i++)
|
|
1723
1897
|
batch[i] = void 0;
|
|
1724
1898
|
return;
|
|
1725
1899
|
}
|
|
1726
|
-
for (let i =
|
|
1900
|
+
for (let i = 0; i < count; i++) {
|
|
1727
1901
|
const rec = batch[i];
|
|
1728
1902
|
batch[i] = void 0;
|
|
1729
1903
|
if (this.closing)
|
|
@@ -1756,7 +1930,7 @@ var CtpClient = class extends import_node_events.EventEmitter {
|
|
|
1756
1930
|
const plen = v.getInt32(slot + S_PLEN, true);
|
|
1757
1931
|
const base = slot + this.headerSize;
|
|
1758
1932
|
let value;
|
|
1759
|
-
if (plen > 0 && sid >= 0 && sid < this.layouts.length)
|
|
1933
|
+
if (plen > 0 && sid >= 0 && sid < this.layouts.length && plen >= this.layouts[sid].size)
|
|
1760
1934
|
value = this.decoderFor(sid)(v, u8, base);
|
|
1761
1935
|
else if (sid === -2 && plen >= 4)
|
|
1762
1936
|
value = v.getInt32(base, true);
|
|
@@ -1779,8 +1953,13 @@ var CtpClient = class extends import_node_events.EventEmitter {
|
|
|
1779
1953
|
const rspInfo = options.rspInfo;
|
|
1780
1954
|
if (options.isLast !== void 0 && this.pending.size > 0) {
|
|
1781
1955
|
let key = reqId !== 0 && this.pending.has(reqId) ? reqId : void 0;
|
|
1782
|
-
if (key === void 0 && reqId === 0
|
|
1783
|
-
|
|
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
|
+
}
|
|
1784
1963
|
}
|
|
1785
1964
|
const p = key !== void 0 ? this.pending.get(key) : void 0;
|
|
1786
1965
|
if (p && key !== void 0) {
|
|
@@ -1796,7 +1975,13 @@ var CtpClient = class extends import_node_events.EventEmitter {
|
|
|
1796
1975
|
if (p.timer)
|
|
1797
1976
|
clearTimeout(p.timer);
|
|
1798
1977
|
this.pending.delete(key);
|
|
1799
|
-
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
|
+
}
|
|
1800
1985
|
} else {
|
|
1801
1986
|
this.armRequestTimer(key, p);
|
|
1802
1987
|
}
|
|
@@ -1811,7 +1996,7 @@ var CtpClient = class extends import_node_events.EventEmitter {
|
|
|
1811
1996
|
return encodeStruct(this.layouts[structId], STRUCTS[structId].fields, obj, encodeReqString);
|
|
1812
1997
|
}
|
|
1813
1998
|
nextRequestId() {
|
|
1814
|
-
this.reqSeq = this.reqSeq >=
|
|
1999
|
+
this.reqSeq = this.reqSeq >= 1073741823 ? 1 : this.reqSeq + 1;
|
|
1815
2000
|
return this.reqSeq;
|
|
1816
2001
|
}
|
|
1817
2002
|
/** Message for a non-zero send code. Risk sentinels get a specific message;
|
|
@@ -1826,9 +2011,19 @@ var CtpClient = class extends import_node_events.EventEmitter {
|
|
|
1826
2011
|
case -10002:
|
|
1827
2012
|
return "rate limited (order rate exceeded)";
|
|
1828
2013
|
case -10003:
|
|
1829
|
-
return "blocked by
|
|
2014
|
+
return "blocked by position margin limit";
|
|
1830
2015
|
case -10004:
|
|
1831
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";
|
|
1832
2027
|
default:
|
|
1833
2028
|
return void 0;
|
|
1834
2029
|
}
|
|
@@ -1837,14 +2032,18 @@ var CtpClient = class extends import_node_events.EventEmitter {
|
|
|
1837
2032
|
* Send a request and resolve when its response arrives (matched by id).
|
|
1838
2033
|
* `single` resolves with the one row; otherwise with the accumulated rows.
|
|
1839
2034
|
*/
|
|
1840
|
-
request(send, single = false) {
|
|
2035
|
+
request(send, single = false, zeroIdEvent, sessionTransition = false) {
|
|
2036
|
+
if (this.closing)
|
|
2037
|
+
return Promise.reject(new Error("client closed"));
|
|
1841
2038
|
const id = this.nextRequestId();
|
|
1842
2039
|
return new Promise((resolve, reject) => {
|
|
1843
2040
|
const entry = {
|
|
1844
2041
|
rows: [],
|
|
1845
2042
|
resolve,
|
|
1846
2043
|
reject,
|
|
1847
|
-
single
|
|
2044
|
+
single,
|
|
2045
|
+
zeroIdEvent,
|
|
2046
|
+
sessionTransition
|
|
1848
2047
|
};
|
|
1849
2048
|
this.pending.set(id, entry);
|
|
1850
2049
|
let rc;
|
|
@@ -1858,12 +2057,82 @@ var CtpClient = class extends import_node_events.EventEmitter {
|
|
|
1858
2057
|
if (rc !== 0) {
|
|
1859
2058
|
this.pending.delete(id);
|
|
1860
2059
|
const msg = this.riskRejectMessage(rc) ?? `request rejected by CTP API (code ${rc})`;
|
|
1861
|
-
reject(new Error(msg));
|
|
2060
|
+
reject(Object.assign(new Error(msg), { ctpReturnCode: rc }));
|
|
1862
2061
|
return;
|
|
1863
2062
|
}
|
|
1864
|
-
this.
|
|
2063
|
+
if (this.pending.get(id) === entry)
|
|
2064
|
+
this.armRequestTimer(id, entry);
|
|
1865
2065
|
});
|
|
1866
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));
|
|
2119
|
+
return;
|
|
2120
|
+
}
|
|
2121
|
+
this.lastQuerySentAt = performance.now();
|
|
2122
|
+
try {
|
|
2123
|
+
resolveOuter(await this.request(send, single));
|
|
2124
|
+
} catch (error) {
|
|
2125
|
+
rejectOuter(error);
|
|
2126
|
+
}
|
|
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;
|
|
2135
|
+
}
|
|
1867
2136
|
/** (Re)arm a pending request's idle timeout. Called at send and reset on each
|
|
1868
2137
|
* row, so a long streaming query isn't cut off by total elapsed time. */
|
|
1869
2138
|
armRequestTimer(id, entry) {
|
|
@@ -1872,6 +2141,20 @@ var CtpClient = class extends import_node_events.EventEmitter {
|
|
|
1872
2141
|
if (entry.timer)
|
|
1873
2142
|
clearTimeout(entry.timer);
|
|
1874
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
|
+
}
|
|
1875
2158
|
if (this.pending.delete(id))
|
|
1876
2159
|
entry.reject(new Error("request timed out"));
|
|
1877
2160
|
}, this.requestTimeoutMs);
|
|
@@ -1886,6 +2169,8 @@ var CtpClient = class extends import_node_events.EventEmitter {
|
|
|
1886
2169
|
* rtn-trade events, correlating by orderRef.
|
|
1887
2170
|
*/
|
|
1888
2171
|
submit(send) {
|
|
2172
|
+
if (this.closing)
|
|
2173
|
+
return Promise.reject(new Error("client closed"));
|
|
1889
2174
|
const id = this.nextRequestId();
|
|
1890
2175
|
let rc;
|
|
1891
2176
|
try {
|
|
@@ -1896,101 +2181,7 @@ var CtpClient = class extends import_node_events.EventEmitter {
|
|
|
1896
2181
|
if (rc === 0)
|
|
1897
2182
|
return Promise.resolve();
|
|
1898
2183
|
const msg = this.riskRejectMessage(rc) ?? `order rejected by CTP API (code ${rc})`;
|
|
1899
|
-
return Promise.reject(new Error(msg));
|
|
1900
|
-
}
|
|
1901
|
-
};
|
|
1902
|
-
|
|
1903
|
-
// dist/market-data.js
|
|
1904
|
-
var MD_BASE = 4096;
|
|
1905
|
-
var MD_EVENTS = /* @__PURE__ */ new Map([
|
|
1906
|
-
[MD_BASE + 1, "front-connected"],
|
|
1907
|
-
[MD_BASE + 2, "front-disconnected"],
|
|
1908
|
-
[MD_BASE + 3, "heart-beat-warning"],
|
|
1909
|
-
[MD_BASE + 4, "rsp-user-login"],
|
|
1910
|
-
[MD_BASE + 5, "rsp-user-logout"],
|
|
1911
|
-
[MD_BASE + 6, "rsp-qry-multicast-instrument"],
|
|
1912
|
-
[MD_BASE + 7, "rsp-error"],
|
|
1913
|
-
[MD_BASE + 8, "rsp-sub-market-data"],
|
|
1914
|
-
[MD_BASE + 9, "rsp-unsub-market-data"],
|
|
1915
|
-
[MD_BASE + 10, "rsp-sub-for-quote"],
|
|
1916
|
-
[MD_BASE + 11, "rsp-unsub-for-quote"],
|
|
1917
|
-
[MD_BASE + 12, "rtn-depth-market-data"],
|
|
1918
|
-
[MD_BASE + 13, "rtn-for-quote"]
|
|
1919
|
-
]);
|
|
1920
|
-
var MarketDataEvent;
|
|
1921
|
-
(function(MarketDataEvent2) {
|
|
1922
|
-
MarketDataEvent2["FrontConnected"] = "front-connected";
|
|
1923
|
-
MarketDataEvent2["FrontDisconnected"] = "front-disconnected";
|
|
1924
|
-
MarketDataEvent2["HeartBeatWarning"] = "heart-beat-warning";
|
|
1925
|
-
MarketDataEvent2["RspUserLogin"] = "rsp-user-login";
|
|
1926
|
-
MarketDataEvent2["RspUserLogout"] = "rsp-user-logout";
|
|
1927
|
-
MarketDataEvent2["RspQryMulticastInstrument"] = "rsp-qry-multicast-instrument";
|
|
1928
|
-
MarketDataEvent2["RspError"] = "rsp-error";
|
|
1929
|
-
MarketDataEvent2["RspSubMarketData"] = "rsp-sub-market-data";
|
|
1930
|
-
MarketDataEvent2["RspUnSubMarketData"] = "rsp-unsub-market-data";
|
|
1931
|
-
MarketDataEvent2["RspSubForQuote"] = "rsp-sub-for-quote";
|
|
1932
|
-
MarketDataEvent2["RspUnSubForQuote"] = "rsp-unsub-for-quote";
|
|
1933
|
-
MarketDataEvent2["RtnDepthMarketData"] = "rtn-depth-market-data";
|
|
1934
|
-
MarketDataEvent2["RtnForQuote"] = "rtn-for-quote";
|
|
1935
|
-
})(MarketDataEvent || (MarketDataEvent = {}));
|
|
1936
|
-
var MarketData = class extends CtpClient {
|
|
1937
|
-
constructor(flowPath, fronts) {
|
|
1938
|
-
super(new native.MarketData(flowPath, fronts), native.__layoutData(), MD_EVENTS);
|
|
1939
|
-
this.zeroIdFallbackEvents.add(MD_BASE + 4);
|
|
1940
|
-
this.zeroIdFallbackEvents.add(MD_BASE + 5);
|
|
1941
|
-
this.start();
|
|
1942
|
-
}
|
|
1943
|
-
getApiVersion() {
|
|
1944
|
-
return this.native.getApiVersion();
|
|
1945
|
-
}
|
|
1946
|
-
getTradingDay() {
|
|
1947
|
-
return this.native.getTradingDay();
|
|
1948
|
-
}
|
|
1949
|
-
/** Subscribe to depth market data. Returns the CTP send code (0 = ok). */
|
|
1950
|
-
subscribe(instrumentIds) {
|
|
1951
|
-
return this.native.subscribeMarketData(instrumentIds);
|
|
1952
|
-
}
|
|
1953
|
-
unsubscribe(instrumentIds) {
|
|
1954
|
-
return this.native.unsubscribeMarketData(instrumentIds);
|
|
1955
|
-
}
|
|
1956
|
-
subscribeForQuote(instrumentIds) {
|
|
1957
|
-
return this.native.subscribeForQuoteRsp(instrumentIds);
|
|
1958
|
-
}
|
|
1959
|
-
unsubscribeForQuote(instrumentIds) {
|
|
1960
|
-
return this.native.unsubscribeForQuoteRsp(instrumentIds);
|
|
1961
|
-
}
|
|
1962
|
-
/** Log in; resolves with the login response (or rejects on CTP error). */
|
|
1963
|
-
login(req = {}) {
|
|
1964
|
-
return this.request((id) => this.native.reqUserLogin(req, id), true);
|
|
1965
|
-
}
|
|
1966
|
-
logout(req = {}) {
|
|
1967
|
-
return this.request((id) => this.native.reqUserLogout(req, id), true);
|
|
1968
|
-
}
|
|
1969
|
-
armedTrader;
|
|
1970
|
-
/** Route this market data's ticks to a Trader's armed triggers (see Trader.arm).
|
|
1971
|
-
* A MarketData feeds exactly one Trader's registry; attaching a second,
|
|
1972
|
-
* different Trader throws rather than silently stealing the feed. */
|
|
1973
|
-
attachArm(trader) {
|
|
1974
|
-
if (this.armedTrader && this.armedTrader !== trader) {
|
|
1975
|
-
throw new Error("this MarketData already feeds another Trader's armed triggers");
|
|
1976
|
-
}
|
|
1977
|
-
this.armedTrader = trader;
|
|
1978
|
-
this.native._attachArm(trader._armRegistry());
|
|
1979
|
-
}
|
|
1980
|
-
/** @internal test-only: inject a synthetic depth tick into the ring. Optional
|
|
1981
|
-
* bid/ask override the defaults (3499/3501) so tests can drive edge prices
|
|
1982
|
-
* (e.g. a DBL_MAX no-bid sentinel) through the real arm/onTick path. */
|
|
1983
|
-
_injectTestTick(bid, ask) {
|
|
1984
|
-
this.native._injectTestTick(bid, ask);
|
|
1985
|
-
}
|
|
1986
|
-
/** @internal test-only: spawn a background producer thread that pushes `n`
|
|
1987
|
-
* synthetic ticks into the ring (cross-thread doorbell stress). Each tick's
|
|
1988
|
-
* requestId carries its sequence number. */
|
|
1989
|
-
_burstTicks(n, jitterUs = 0) {
|
|
1990
|
-
this.native._burstTicks(n, jitterUs);
|
|
1991
|
-
}
|
|
1992
|
-
on(event, cb) {
|
|
1993
|
-
return super.on(event, cb);
|
|
2184
|
+
return Promise.reject(Object.assign(new Error(msg), { ctpReturnCode: rc }));
|
|
1994
2185
|
}
|
|
1995
2186
|
};
|
|
1996
2187
|
|
|
@@ -2361,10 +2552,33 @@ var TraderBase = class extends CtpClient {
|
|
|
2361
2552
|
return this.request((id) => this.native._req(1, this.encode(STRUCT_ID.ReqAuthenticate, req), id), true);
|
|
2362
2553
|
}
|
|
2363
2554
|
reqUserLogin(req = {}) {
|
|
2364
|
-
|
|
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
|
+
});
|
|
2365
2570
|
}
|
|
2366
2571
|
reqUserLogout(req = {}) {
|
|
2367
|
-
|
|
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);
|
|
2368
2582
|
}
|
|
2369
2583
|
reqUserPasswordUpdate(req = {}) {
|
|
2370
2584
|
return this.request((id) => this.native._req(4, this.encode(STRUCT_ID.UserPasswordUpdate, req), id), true);
|
|
@@ -2382,13 +2596,55 @@ var TraderBase = class extends CtpClient {
|
|
|
2382
2596
|
return this.request((id) => this.native._req(8, this.encode(STRUCT_ID.ReqGenUserText, req), id), true);
|
|
2383
2597
|
}
|
|
2384
2598
|
reqUserLoginWithCaptcha(req = {}) {
|
|
2385
|
-
|
|
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
|
+
});
|
|
2386
2614
|
}
|
|
2387
2615
|
reqUserLoginWithText(req = {}) {
|
|
2388
|
-
|
|
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
|
+
});
|
|
2389
2631
|
}
|
|
2390
2632
|
reqUserLoginWithOtp(req = {}) {
|
|
2391
|
-
|
|
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
|
+
});
|
|
2392
2648
|
}
|
|
2393
2649
|
reqOrderInsert(req = {}) {
|
|
2394
2650
|
return this.submit((id) => this.native._req(12, this.encode(STRUCT_ID.InputOrder, req), id));
|
|
@@ -2403,7 +2659,13 @@ var TraderBase = class extends CtpClient {
|
|
|
2403
2659
|
return this.submit((id) => this.native._req(15, this.encode(STRUCT_ID.InputOrderAction, req), id));
|
|
2404
2660
|
}
|
|
2405
2661
|
reqQryMaxOrderVolume(req = {}) {
|
|
2406
|
-
|
|
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);
|
|
2407
2669
|
}
|
|
2408
2670
|
reqSettlementInfoConfirm(req = {}) {
|
|
2409
2671
|
return this.request((id) => this.native._req(17, this.encode(STRUCT_ID.SettlementInfoConfirm, req), id), true);
|
|
@@ -2442,163 +2704,481 @@ var TraderBase = class extends CtpClient {
|
|
|
2442
2704
|
return this.submit((id) => this.native._req(28, this.encode(STRUCT_ID.InputCombAction, req), id));
|
|
2443
2705
|
}
|
|
2444
2706
|
reqQryOrder(req = {}) {
|
|
2445
|
-
|
|
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);
|
|
2446
2714
|
}
|
|
2447
2715
|
reqQryTrade(req = {}) {
|
|
2448
|
-
|
|
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);
|
|
2449
2723
|
}
|
|
2450
2724
|
reqQryInvestorPosition(req = {}) {
|
|
2451
|
-
|
|
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);
|
|
2452
2732
|
}
|
|
2453
2733
|
reqQryTradingAccount(req = {}) {
|
|
2454
|
-
|
|
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);
|
|
2455
2741
|
}
|
|
2456
2742
|
reqQryInvestor(req = {}) {
|
|
2457
|
-
|
|
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);
|
|
2458
2750
|
}
|
|
2459
2751
|
reqQryTradingCode(req = {}) {
|
|
2460
|
-
|
|
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);
|
|
2461
2759
|
}
|
|
2462
2760
|
reqQryInstrumentMarginRate(req = {}) {
|
|
2463
|
-
|
|
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);
|
|
2464
2768
|
}
|
|
2465
2769
|
reqQryInstrumentCommissionRate(req = {}) {
|
|
2466
|
-
|
|
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);
|
|
2467
2777
|
}
|
|
2468
2778
|
reqQryUserSession(req = {}) {
|
|
2469
|
-
|
|
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);
|
|
2470
2786
|
}
|
|
2471
2787
|
reqQryExchange(req = {}) {
|
|
2472
|
-
|
|
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);
|
|
2473
2795
|
}
|
|
2474
2796
|
reqQryProduct(req = {}) {
|
|
2475
|
-
|
|
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);
|
|
2476
2804
|
}
|
|
2477
2805
|
reqQryInstrument(req = {}) {
|
|
2478
|
-
|
|
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);
|
|
2479
2813
|
}
|
|
2480
2814
|
reqQryDepthMarketData(req = {}) {
|
|
2481
|
-
|
|
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);
|
|
2482
2822
|
}
|
|
2483
2823
|
reqQryTraderOffer(req = {}) {
|
|
2484
|
-
|
|
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);
|
|
2485
2831
|
}
|
|
2486
2832
|
reqQrySettlementInfo(req = {}) {
|
|
2487
|
-
|
|
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);
|
|
2488
2840
|
}
|
|
2489
2841
|
reqQryTransferBank(req = {}) {
|
|
2490
|
-
|
|
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);
|
|
2491
2849
|
}
|
|
2492
2850
|
reqQryInvestorPositionDetail(req = {}) {
|
|
2493
|
-
|
|
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);
|
|
2494
2858
|
}
|
|
2495
2859
|
reqQryNotice(req = {}) {
|
|
2496
|
-
|
|
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);
|
|
2497
2867
|
}
|
|
2498
2868
|
reqQrySettlementInfoConfirm(req = {}) {
|
|
2499
|
-
|
|
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);
|
|
2500
2876
|
}
|
|
2501
2877
|
reqQryInvestorPositionCombineDetail(req = {}) {
|
|
2502
|
-
|
|
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);
|
|
2503
2885
|
}
|
|
2504
2886
|
reqQryCfmmcTradingAccountKey(req = {}) {
|
|
2505
|
-
|
|
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);
|
|
2506
2894
|
}
|
|
2507
2895
|
reqQryEWarrantOffset(req = {}) {
|
|
2508
|
-
|
|
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);
|
|
2509
2903
|
}
|
|
2510
2904
|
reqQryInvestorProductGroupMargin(req = {}) {
|
|
2511
|
-
|
|
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);
|
|
2512
2912
|
}
|
|
2513
2913
|
reqQryExchangeMarginRate(req = {}) {
|
|
2514
|
-
|
|
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);
|
|
2515
2921
|
}
|
|
2516
2922
|
reqQryExchangeMarginRateAdjust(req = {}) {
|
|
2517
|
-
|
|
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);
|
|
2518
2930
|
}
|
|
2519
2931
|
reqQryExchangeRate(req = {}) {
|
|
2520
|
-
|
|
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);
|
|
2521
2939
|
}
|
|
2522
2940
|
reqQrySecAgentAcidMap(req = {}) {
|
|
2523
|
-
|
|
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);
|
|
2524
2948
|
}
|
|
2525
2949
|
reqQryProductExchRate(req = {}) {
|
|
2526
|
-
|
|
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);
|
|
2527
2957
|
}
|
|
2528
2958
|
reqQryProductGroup(req = {}) {
|
|
2529
|
-
|
|
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);
|
|
2530
2966
|
}
|
|
2531
2967
|
reqQryMmInstrumentCommissionRate(req = {}) {
|
|
2532
|
-
|
|
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);
|
|
2533
2975
|
}
|
|
2534
2976
|
reqQryMmOptionInstrCommRate(req = {}) {
|
|
2535
|
-
|
|
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);
|
|
2536
2984
|
}
|
|
2537
2985
|
reqQryInstrumentOrderCommRate(req = {}) {
|
|
2538
|
-
|
|
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);
|
|
2539
2993
|
}
|
|
2540
2994
|
reqQrySecAgentTradingAccount(req = {}) {
|
|
2541
|
-
|
|
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);
|
|
2542
3002
|
}
|
|
2543
3003
|
reqQrySecAgentCheckMode(req = {}) {
|
|
2544
|
-
|
|
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);
|
|
2545
3011
|
}
|
|
2546
3012
|
reqQrySecAgentTradeInfo(req = {}) {
|
|
2547
|
-
|
|
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);
|
|
2548
3020
|
}
|
|
2549
3021
|
reqQryOptionInstrTradeCost(req = {}) {
|
|
2550
|
-
|
|
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);
|
|
2551
3029
|
}
|
|
2552
3030
|
reqQryOptionInstrCommRate(req = {}) {
|
|
2553
|
-
|
|
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);
|
|
2554
3038
|
}
|
|
2555
3039
|
reqQryExecOrder(req = {}) {
|
|
2556
|
-
|
|
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);
|
|
2557
3047
|
}
|
|
2558
3048
|
reqQryForQuote(req = {}) {
|
|
2559
|
-
|
|
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);
|
|
2560
3056
|
}
|
|
2561
3057
|
reqQryQuote(req = {}) {
|
|
2562
|
-
|
|
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);
|
|
2563
3065
|
}
|
|
2564
3066
|
reqQryOptionSelfClose(req = {}) {
|
|
2565
|
-
|
|
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);
|
|
2566
3074
|
}
|
|
2567
3075
|
reqQryInvestUnit(req = {}) {
|
|
2568
|
-
|
|
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);
|
|
2569
3083
|
}
|
|
2570
3084
|
reqQryCombInstrumentGuard(req = {}) {
|
|
2571
|
-
|
|
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);
|
|
2572
3092
|
}
|
|
2573
3093
|
reqQryCombAction(req = {}) {
|
|
2574
|
-
|
|
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);
|
|
2575
3101
|
}
|
|
2576
3102
|
reqQryTransferSerial(req = {}) {
|
|
2577
|
-
|
|
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);
|
|
2578
3110
|
}
|
|
2579
3111
|
reqQryAccountregister(req = {}) {
|
|
2580
|
-
|
|
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);
|
|
2581
3119
|
}
|
|
2582
3120
|
reqQryContractBank(req = {}) {
|
|
2583
|
-
|
|
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);
|
|
2584
3128
|
}
|
|
2585
3129
|
reqQryParkedOrder(req = {}) {
|
|
2586
|
-
|
|
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);
|
|
2587
3137
|
}
|
|
2588
3138
|
reqQryParkedOrderAction(req = {}) {
|
|
2589
|
-
|
|
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);
|
|
2590
3146
|
}
|
|
2591
3147
|
reqQryTradingNotice(req = {}) {
|
|
2592
|
-
|
|
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);
|
|
2593
3155
|
}
|
|
2594
3156
|
reqQryBrokerTradingParams(req = {}) {
|
|
2595
|
-
|
|
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);
|
|
2596
3164
|
}
|
|
2597
3165
|
reqQryBrokerTradingAlgos(req = {}) {
|
|
2598
|
-
|
|
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);
|
|
2599
3173
|
}
|
|
2600
3174
|
reqQueryCfmmcTradingAccountToken(req = {}) {
|
|
2601
|
-
|
|
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);
|
|
2602
3182
|
}
|
|
2603
3183
|
reqFromBankToFutureByFuture(req = {}) {
|
|
2604
3184
|
return this.request((id) => this.native._req(82, this.encode(STRUCT_ID.ReqTransfer, req), id), true);
|
|
@@ -2607,100 +3187,292 @@ var TraderBase = class extends CtpClient {
|
|
|
2607
3187
|
return this.request((id) => this.native._req(83, this.encode(STRUCT_ID.ReqTransfer, req), id), true);
|
|
2608
3188
|
}
|
|
2609
3189
|
reqQueryBankAccountMoneyByFuture(req = {}) {
|
|
2610
|
-
|
|
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);
|
|
2611
3197
|
}
|
|
2612
3198
|
reqQryClassifiedInstrument(req = {}) {
|
|
2613
|
-
|
|
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);
|
|
2614
3206
|
}
|
|
2615
3207
|
reqQryCombPromotionParam(req = {}) {
|
|
2616
|
-
|
|
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);
|
|
2617
3215
|
}
|
|
2618
3216
|
reqQryRiskSettleInvstPosition(req = {}) {
|
|
2619
|
-
|
|
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);
|
|
2620
3224
|
}
|
|
2621
3225
|
reqQryRiskSettleProductStatus(req = {}) {
|
|
2622
|
-
|
|
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);
|
|
2623
3233
|
}
|
|
2624
3234
|
reqQrySpbmFutureParameter(req = {}) {
|
|
2625
|
-
|
|
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);
|
|
2626
3242
|
}
|
|
2627
3243
|
reqQrySpbmOptionParameter(req = {}) {
|
|
2628
|
-
|
|
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);
|
|
2629
3251
|
}
|
|
2630
3252
|
reqQrySpbmIntraParameter(req = {}) {
|
|
2631
|
-
|
|
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);
|
|
2632
3260
|
}
|
|
2633
3261
|
reqQrySpbmInterParameter(req = {}) {
|
|
2634
|
-
|
|
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);
|
|
2635
3269
|
}
|
|
2636
3270
|
reqQrySpbmPortfDefinition(req = {}) {
|
|
2637
|
-
|
|
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);
|
|
2638
3278
|
}
|
|
2639
3279
|
reqQrySpbmInvestorPortfDef(req = {}) {
|
|
2640
|
-
|
|
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);
|
|
2641
3287
|
}
|
|
2642
3288
|
reqQryInvestorPortfMarginRatio(req = {}) {
|
|
2643
|
-
|
|
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);
|
|
2644
3296
|
}
|
|
2645
3297
|
reqQryInvestorProdSpbmDetail(req = {}) {
|
|
2646
|
-
|
|
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);
|
|
2647
3305
|
}
|
|
2648
3306
|
reqQryInvestorCommoditySpmmMargin(req = {}) {
|
|
2649
|
-
|
|
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);
|
|
2650
3314
|
}
|
|
2651
3315
|
reqQryInvestorCommodityGroupSpmmMargin(req = {}) {
|
|
2652
|
-
|
|
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);
|
|
2653
3323
|
}
|
|
2654
3324
|
reqQrySpmmInstParam(req = {}) {
|
|
2655
|
-
|
|
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);
|
|
2656
3332
|
}
|
|
2657
3333
|
reqQrySpmmProductParam(req = {}) {
|
|
2658
|
-
|
|
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);
|
|
2659
3341
|
}
|
|
2660
3342
|
reqQrySpbmAddOnInterParameter(req = {}) {
|
|
2661
|
-
|
|
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);
|
|
2662
3350
|
}
|
|
2663
3351
|
reqQryRcamsCombProductInfo(req = {}) {
|
|
2664
|
-
|
|
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);
|
|
2665
3359
|
}
|
|
2666
3360
|
reqQryRcamsInstrParameter(req = {}) {
|
|
2667
|
-
|
|
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);
|
|
2668
3368
|
}
|
|
2669
3369
|
reqQryRcamsIntraParameter(req = {}) {
|
|
2670
|
-
|
|
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);
|
|
2671
3377
|
}
|
|
2672
3378
|
reqQryRcamsInterParameter(req = {}) {
|
|
2673
|
-
|
|
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);
|
|
2674
3386
|
}
|
|
2675
3387
|
reqQryRcamsShortOptAdjustParam(req = {}) {
|
|
2676
|
-
|
|
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);
|
|
2677
3395
|
}
|
|
2678
3396
|
reqQryRcamsInvestorCombPosition(req = {}) {
|
|
2679
|
-
|
|
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);
|
|
2680
3404
|
}
|
|
2681
3405
|
reqQryInvestorProdRcamsMargin(req = {}) {
|
|
2682
|
-
|
|
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);
|
|
2683
3413
|
}
|
|
2684
3414
|
reqQryRuleInstrParameter(req = {}) {
|
|
2685
|
-
|
|
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);
|
|
2686
3422
|
}
|
|
2687
3423
|
reqQryRuleIntraParameter(req = {}) {
|
|
2688
|
-
|
|
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);
|
|
2689
3431
|
}
|
|
2690
3432
|
reqQryRuleInterParameter(req = {}) {
|
|
2691
|
-
|
|
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);
|
|
2692
3440
|
}
|
|
2693
3441
|
reqQryInvestorProdRuleMargin(req = {}) {
|
|
2694
|
-
|
|
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);
|
|
2695
3449
|
}
|
|
2696
3450
|
reqQryInvestorPortfSetting(req = {}) {
|
|
2697
|
-
|
|
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);
|
|
2698
3458
|
}
|
|
2699
3459
|
reqQryInvestorInfoCommRec(req = {}) {
|
|
2700
|
-
|
|
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);
|
|
2701
3467
|
}
|
|
2702
3468
|
reqQryCombLeg(req = {}) {
|
|
2703
|
-
|
|
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);
|
|
2704
3476
|
}
|
|
2705
3477
|
reqOffsetSetting(req = {}) {
|
|
2706
3478
|
return this.request((id) => this.native._req(116, this.encode(STRUCT_ID.InputOffsetSetting, req), id), true);
|
|
@@ -2709,7 +3481,13 @@ var TraderBase = class extends CtpClient {
|
|
|
2709
3481
|
return this.request((id) => this.native._req(117, this.encode(STRUCT_ID.InputOffsetSetting, req), id), true);
|
|
2710
3482
|
}
|
|
2711
3483
|
reqQryOffsetSetting(req = {}) {
|
|
2712
|
-
|
|
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);
|
|
2713
3491
|
}
|
|
2714
3492
|
reqGenSmsCode(req = {}) {
|
|
2715
3493
|
return this.request((id) => this.native._req(119, this.encode(STRUCT_ID.ReqGenSMSCode, req), id), true);
|
|
@@ -2721,7 +3499,13 @@ var TraderBase = class extends CtpClient {
|
|
|
2721
3499
|
return this.request((id) => this.native._req(121, this.encode(STRUCT_ID.InputSpdApplyAction, req), id), true);
|
|
2722
3500
|
}
|
|
2723
3501
|
reqQrySpdApply(req = {}) {
|
|
2724
|
-
|
|
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);
|
|
2725
3509
|
}
|
|
2726
3510
|
reqHedgeCfm(req = {}) {
|
|
2727
3511
|
return this.request((id) => this.native._req(123, this.encode(STRUCT_ID.InputHedgeCfm, req), id), true);
|
|
@@ -2730,70 +3514,248 @@ var TraderBase = class extends CtpClient {
|
|
|
2730
3514
|
return this.request((id) => this.native._req(124, this.encode(STRUCT_ID.InputHedgeCfmAction, req), id), true);
|
|
2731
3515
|
}
|
|
2732
3516
|
reqQryHedgeCfm(req = {}) {
|
|
2733
|
-
|
|
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);
|
|
2734
3524
|
}
|
|
2735
3525
|
};
|
|
2736
3526
|
|
|
2737
3527
|
// dist/trader.js
|
|
2738
3528
|
var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
2739
3529
|
function assertFiniteLimit(name, v) {
|
|
2740
|
-
if (v !== void 0 && !Number.isFinite(v)) {
|
|
2741
|
-
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`);
|
|
2742
3544
|
}
|
|
2743
3545
|
}
|
|
3546
|
+
function assertInstrumentId(name, instrumentId) {
|
|
3547
|
+
if (typeof instrumentId !== "string" || !instrumentId || instrumentId.includes("\0"))
|
|
3548
|
+
throw new TypeError(`${name}: instrumentId must be non-empty and contain no NUL`);
|
|
3549
|
+
}
|
|
3550
|
+
var RISK_LIMIT_KEYS = /* @__PURE__ */ new Set([
|
|
3551
|
+
"maxOrderVolume",
|
|
3552
|
+
"maxPriceDeviation",
|
|
3553
|
+
"maxNotional",
|
|
3554
|
+
"maxOrdersPerSec",
|
|
3555
|
+
"orderBurst",
|
|
3556
|
+
"maxCloseOrdersPerSec",
|
|
3557
|
+
"closeOrderBurst",
|
|
3558
|
+
"maxReferenceAgeMs",
|
|
3559
|
+
"maxAccountMargin"
|
|
3560
|
+
]);
|
|
3561
|
+
function assertObjectKeys(value, label, allowed) {
|
|
3562
|
+
for (const key of ownStringKeys(value, label))
|
|
3563
|
+
if (!allowed.has(key))
|
|
3564
|
+
throw new TypeError(`${label}: unknown field ${key}`);
|
|
3565
|
+
}
|
|
3566
|
+
var SESSION_KEYS = /* @__PURE__ */ new Set([
|
|
3567
|
+
"brokerId",
|
|
3568
|
+
"userId",
|
|
3569
|
+
"investorId",
|
|
3570
|
+
"password",
|
|
3571
|
+
"appId",
|
|
3572
|
+
"authCode",
|
|
3573
|
+
"confirmSettlement",
|
|
3574
|
+
"sync"
|
|
3575
|
+
]);
|
|
3576
|
+
var SESSION_SYNC_KEYS = /* @__PURE__ */ new Set(["multipliers", "marginRates", "positions", "orders"]);
|
|
3577
|
+
var ARM_SPEC_KEYS = /* @__PURE__ */ new Set(["instrumentId", "side", "triggerPrice", "order"]);
|
|
3578
|
+
var POSITION_LIMIT_KEYS = /* @__PURE__ */ new Set(["long", "short"]);
|
|
3579
|
+
var POSITION_SEED_KEYS = /* @__PURE__ */ new Set([
|
|
3580
|
+
"instrumentId",
|
|
3581
|
+
"side",
|
|
3582
|
+
"hedgeFlag",
|
|
3583
|
+
"volume",
|
|
3584
|
+
"margin"
|
|
3585
|
+
]);
|
|
2744
3586
|
var Trader = class extends TraderBase {
|
|
2745
3587
|
broker;
|
|
2746
3588
|
investor;
|
|
2747
3589
|
orderRefSeq = 0;
|
|
2748
3590
|
constructor(flowPath, fronts) {
|
|
2749
|
-
super(new native.Trader(flowPath, fronts), native.__layoutData(), TRADER_EVENTS);
|
|
2750
|
-
|
|
2751
|
-
|
|
2752
|
-
|
|
2753
|
-
|
|
2754
|
-
|
|
2755
|
-
|
|
2756
|
-
if (Number.isFinite(mx) && mx > this.orderRefSeq)
|
|
2757
|
-
this.orderRefSeq = mx;
|
|
2758
|
-
if (typeof r.frontId === "number" && typeof r.sessionId === "number") {
|
|
2759
|
-
this.native.setSession(r.frontId, r.sessionId);
|
|
2760
|
-
}
|
|
2761
|
-
}
|
|
2762
|
-
});
|
|
3591
|
+
super(new native.Trader(flowPath, copyOwnFronts(fronts, "Trader fronts")), native.__layoutData(), TRADER_EVENTS);
|
|
3592
|
+
const clearConfirmedIdentity = () => {
|
|
3593
|
+
this.broker = void 0;
|
|
3594
|
+
this.investor = void 0;
|
|
3595
|
+
};
|
|
3596
|
+
this.on("front-connected", clearConfirmedIdentity);
|
|
3597
|
+
this.on("front-disconnected", clearConfirmedIdentity);
|
|
2763
3598
|
this.start();
|
|
2764
3599
|
}
|
|
2765
|
-
|
|
2766
|
-
|
|
3600
|
+
/** A raw login Promise may resolve only with a structurally usable session.
|
|
3601
|
+
* Account confirmation itself happens in session(), after request-vs-response
|
|
3602
|
+
* identity validation; merely observing a protocol event never grants order
|
|
3603
|
+
* authority. */
|
|
3604
|
+
onRequestResolved(eventName, value, _options) {
|
|
3605
|
+
if (eventName === "rsp-user-logout") {
|
|
3606
|
+
this.broker = void 0;
|
|
3607
|
+
this.investor = void 0;
|
|
3608
|
+
return;
|
|
3609
|
+
}
|
|
3610
|
+
if (eventName !== "rsp-user-login")
|
|
3611
|
+
return;
|
|
3612
|
+
const r = value;
|
|
3613
|
+
if (!r)
|
|
3614
|
+
return;
|
|
3615
|
+
if (typeof r.brokerId === "string" && r.brokerId && typeof r.userId === "string" && r.userId && Number.isInteger(r.frontId) && Number(r.frontId) > 0 && Number.isInteger(r.sessionId) && Number(r.sessionId) > 0) {
|
|
3616
|
+
this.broker = r.brokerId;
|
|
3617
|
+
this.investor = r.userId;
|
|
3618
|
+
}
|
|
3619
|
+
const maxOrderRef = typeof r.maxOrderRef === "string" ? r.maxOrderRef.trim() : "";
|
|
3620
|
+
if (/^\d{1,12}$/.test(maxOrderRef)) {
|
|
3621
|
+
const maxRef = Number(maxOrderRef);
|
|
3622
|
+
if (Number.isFinite(maxRef) && maxRef > this.orderRefSeq)
|
|
3623
|
+
this.orderRefSeq = maxRef;
|
|
3624
|
+
}
|
|
3625
|
+
}
|
|
3626
|
+
/** Generated login/logout methods call this only after their request has
|
|
3627
|
+
* encoded successfully. Revoke the confirmed JS account at that same atomic
|
|
3628
|
+
* transition boundary, so a concurrent sync helper cannot start with the old
|
|
3629
|
+
* identity while native risk state is already fail-closed for the new session. */
|
|
3630
|
+
beginRequestContextTransition(reason) {
|
|
3631
|
+
this.broker = void 0;
|
|
3632
|
+
this.investor = void 0;
|
|
3633
|
+
super.beginRequestContextTransition(reason);
|
|
3634
|
+
}
|
|
3635
|
+
shouldTimeoutRequest(requestId, sessionTransition) {
|
|
3636
|
+
if (!sessionTransition)
|
|
3637
|
+
return true;
|
|
3638
|
+
return this.native._timeoutSessionTransition(requestId);
|
|
2767
3639
|
}
|
|
2768
|
-
|
|
2769
|
-
return this.native.
|
|
3640
|
+
get apiVersion() {
|
|
3641
|
+
return this.native.apiVersion();
|
|
3642
|
+
}
|
|
3643
|
+
get tradingDay() {
|
|
3644
|
+
return this.native.tradingDay();
|
|
2770
3645
|
}
|
|
2771
3646
|
/**
|
|
2772
3647
|
* One-call post-connect handshake. Call it from the `front-connected` handler
|
|
2773
3648
|
* (and again after a reconnect): authenticate (if appId/authCode given) →
|
|
2774
|
-
* login → confirm settlement → sync multipliers /
|
|
3649
|
+
* login → confirm settlement → sync multipliers / margin rates / orders /
|
|
3650
|
+
* positions. Each
|
|
2775
3651
|
* step just wraps the matching req / sync method, so you can hand-roll your
|
|
2776
3652
|
* own flow instead when you need finer control. Returns the row counts from
|
|
2777
3653
|
* the sync steps. Must run on a connected front (queries need the session up).
|
|
2778
3654
|
*/
|
|
2779
3655
|
async session(opts) {
|
|
2780
|
-
|
|
3656
|
+
assertObjectKeys(opts, "session options", SESSION_KEYS);
|
|
3657
|
+
const cleanOpts = copyOwnRecord(opts, "session options");
|
|
3658
|
+
const { brokerId, userId, password, appId, authCode } = cleanOpts;
|
|
3659
|
+
const investorId = cleanOpts.investorId ?? userId;
|
|
3660
|
+
if (typeof brokerId !== "string" || !brokerId || brokerId.includes("\0") || typeof userId !== "string" || !userId || userId.includes("\0") || typeof password !== "string" || !password || password.includes("\0")) {
|
|
3661
|
+
throw new TypeError("session requires brokerId, userId and password");
|
|
3662
|
+
}
|
|
3663
|
+
if (typeof investorId !== "string" || !investorId || investorId.includes("\0"))
|
|
3664
|
+
throw new TypeError("session investorId must be a non-empty string");
|
|
3665
|
+
if (cleanOpts.confirmSettlement !== void 0 && typeof cleanOpts.confirmSettlement !== "boolean")
|
|
3666
|
+
throw new TypeError("session.confirmSettlement must be boolean");
|
|
3667
|
+
if (appId === void 0 !== (authCode === void 0)) {
|
|
3668
|
+
throw new TypeError("session appId and authCode must be supplied together");
|
|
3669
|
+
}
|
|
3670
|
+
if (appId !== void 0 && (typeof appId !== "string" || !appId || appId.includes("\0") || typeof authCode !== "string" || !authCode || authCode.includes("\0")))
|
|
3671
|
+
throw new TypeError("session appId and authCode must be non-empty strings");
|
|
3672
|
+
let cleanSync = {};
|
|
3673
|
+
if (cleanOpts.sync !== void 0) {
|
|
3674
|
+
assertObjectKeys(cleanOpts.sync, "session.sync", SESSION_SYNC_KEYS);
|
|
3675
|
+
cleanSync = copyOwnRecord(cleanOpts.sync, "session.sync");
|
|
3676
|
+
const { multipliers, marginRates, positions, orders } = cleanSync;
|
|
3677
|
+
if (multipliers !== void 0 && typeof multipliers !== "boolean")
|
|
3678
|
+
cleanSync.multipliers = copyDenseStringArray(multipliers, "session.sync.multipliers");
|
|
3679
|
+
if (marginRates !== void 0)
|
|
3680
|
+
cleanSync.marginRates = copyDenseStringArray(marginRates, "session.sync.marginRates");
|
|
3681
|
+
if (positions !== void 0 && typeof positions !== "boolean")
|
|
3682
|
+
throw new TypeError("session.sync.positions must be boolean");
|
|
3683
|
+
if (orders !== void 0 && typeof orders !== "boolean")
|
|
3684
|
+
throw new TypeError("session.sync.orders must be boolean");
|
|
3685
|
+
}
|
|
3686
|
+
if (appId !== void 0 && authCode !== void 0)
|
|
3687
|
+
this.encode(STRUCT_ID.ReqAuthenticate, { brokerId, userId, appId, authCode });
|
|
3688
|
+
this.encode(STRUCT_ID.ReqUserLogin, { brokerId, userId, password });
|
|
3689
|
+
const encodedAccount = this.encode(STRUCT_ID.SettlementInfoConfirm, { brokerId, investorId });
|
|
3690
|
+
this.native._beginSessionHandshake();
|
|
3691
|
+
this.invalidateRequestContext("trader session started");
|
|
3692
|
+
let contextToken = this.requestContextToken();
|
|
3693
|
+
this.broker = void 0;
|
|
3694
|
+
this.investor = void 0;
|
|
3695
|
+
this.native._markPositionLedgerUncertain();
|
|
3696
|
+
this.native._markOrderLedgerUncertain();
|
|
2781
3697
|
if (appId !== void 0 && authCode !== void 0) {
|
|
2782
3698
|
await this.reqAuthenticate({ brokerId, userId, appId, authCode });
|
|
3699
|
+
this.assertRequestContext(contextToken, "trader session authentication");
|
|
3700
|
+
}
|
|
3701
|
+
const beforeLoginContext = this.requestContextToken();
|
|
3702
|
+
const beforeLoginTransition = this.requestTransitionToken();
|
|
3703
|
+
const loginRequest = this.reqUserLogin({ brokerId, userId, password });
|
|
3704
|
+
const afterLoginContext = this.requestContextToken();
|
|
3705
|
+
const afterLoginTransition = this.requestTransitionToken();
|
|
3706
|
+
if (afterLoginTransition === beforeLoginTransition + 1 && afterLoginContext === beforeLoginContext + 1) {
|
|
3707
|
+
contextToken = afterLoginContext;
|
|
3708
|
+
} else if (afterLoginTransition === beforeLoginTransition) {
|
|
3709
|
+
contextToken = beforeLoginContext;
|
|
3710
|
+
} else {
|
|
3711
|
+
try {
|
|
3712
|
+
await loginRequest;
|
|
3713
|
+
} catch {
|
|
3714
|
+
}
|
|
3715
|
+
throw new Error("trader session login crossed multiple context transitions");
|
|
3716
|
+
}
|
|
3717
|
+
const login = await loginRequest;
|
|
3718
|
+
this.assertRequestContext(contextToken, "trader session login");
|
|
3719
|
+
if (!login || !Number.isInteger(login.frontId) || login.frontId <= 0 || !Number.isInteger(login.sessionId) || login.sessionId <= 0 || login.brokerId !== brokerId || login.userId !== userId) {
|
|
3720
|
+
this.broker = void 0;
|
|
3721
|
+
this.investor = void 0;
|
|
3722
|
+
throw new Error("trader login response has missing or mismatched session identity");
|
|
3723
|
+
}
|
|
3724
|
+
const confirmed = this.native._confirmSessionAccount(login.frontId, login.sessionId, encodedAccount);
|
|
3725
|
+
if (!confirmed) {
|
|
3726
|
+
this.broker = void 0;
|
|
3727
|
+
this.investor = void 0;
|
|
3728
|
+
throw new Error("native Trader session/account confirmation failed");
|
|
2783
3729
|
}
|
|
2784
|
-
|
|
2785
|
-
|
|
2786
|
-
|
|
3730
|
+
this.broker = brokerId;
|
|
3731
|
+
this.investor = investorId;
|
|
3732
|
+
const maxOrderRef = typeof login.maxOrderRef === "string" ? login.maxOrderRef.trim() : "";
|
|
3733
|
+
const maxRef = /^\d{1,12}$/.test(maxOrderRef) ? Number(maxOrderRef) : NaN;
|
|
3734
|
+
if (Number.isFinite(maxRef) && maxRef > this.orderRefSeq)
|
|
3735
|
+
this.orderRefSeq = maxRef;
|
|
3736
|
+
if (cleanOpts.confirmSettlement ?? true) {
|
|
3737
|
+
await this.reqSettlementInfoConfirm({ brokerId, investorId });
|
|
3738
|
+
this.assertRequestContext(contextToken, "trader session settlement confirmation");
|
|
2787
3739
|
}
|
|
2788
|
-
const sync =
|
|
3740
|
+
const sync = cleanSync;
|
|
2789
3741
|
const mul = sync.multipliers ?? true;
|
|
2790
|
-
const result = { multipliers: 0, positions: 0, orders: 0 };
|
|
2791
|
-
if (mul)
|
|
3742
|
+
const result = { multipliers: 0, marginRates: 0, positions: 0, orders: 0 };
|
|
3743
|
+
if (mul) {
|
|
2792
3744
|
result.multipliers = await this.syncMultipliers(Array.isArray(mul) ? mul : void 0);
|
|
2793
|
-
|
|
2794
|
-
|
|
2795
|
-
if (sync.
|
|
3745
|
+
this.assertRequestContext(contextToken, "trader session multiplier sync");
|
|
3746
|
+
}
|
|
3747
|
+
if (sync.marginRates?.length) {
|
|
3748
|
+
result.marginRates = await this.syncMarginRates(sync.marginRates);
|
|
3749
|
+
this.assertRequestContext(contextToken, "trader session margin sync");
|
|
3750
|
+
}
|
|
3751
|
+
if (sync.orders ?? true) {
|
|
2796
3752
|
result.orders = await this.syncOrders();
|
|
3753
|
+
this.assertRequestContext(contextToken, "trader session order sync");
|
|
3754
|
+
}
|
|
3755
|
+
if (sync.positions ?? true) {
|
|
3756
|
+
result.positions = await this.syncPositions();
|
|
3757
|
+
this.assertRequestContext(contextToken, "trader session position sync");
|
|
3758
|
+
}
|
|
2797
3759
|
return result;
|
|
2798
3760
|
}
|
|
2799
3761
|
/** Assign a unique numeric OrderRef when the caller left it blank. CTP treats
|
|
@@ -2801,10 +3763,80 @@ var Trader = class extends TraderBase {
|
|
|
2801
3763
|
* ref with "不允许重复报单", so an unset ref would otherwise collide. */
|
|
2802
3764
|
withAutoOrderRef(order) {
|
|
2803
3765
|
if (order.orderRef === void 0 || order.orderRef === "") {
|
|
2804
|
-
|
|
3766
|
+
if (this.orderRefSeq >= 999999999999) {
|
|
3767
|
+
throw new RangeError("OrderRef space exhausted for this process/session");
|
|
3768
|
+
}
|
|
3769
|
+
return { ...order, orderRef: String(this.orderRefSeq + 1) };
|
|
3770
|
+
}
|
|
3771
|
+
if (typeof order.orderRef !== "string" || !/^\d{1,12}$/.test(order.orderRef)) {
|
|
3772
|
+
throw new TypeError("orderRef must contain 1..12 decimal digits");
|
|
3773
|
+
}
|
|
3774
|
+
const explicit = Number(order.orderRef);
|
|
3775
|
+
if (explicit <= this.orderRefSeq) {
|
|
3776
|
+
throw new RangeError(`explicit orderRef must be greater than the current high-water mark ${this.orderRefSeq}`);
|
|
2805
3777
|
}
|
|
2806
3778
|
return order;
|
|
2807
3779
|
}
|
|
3780
|
+
commitOrderRef(order) {
|
|
3781
|
+
this.orderRefSeq = Number(order.orderRef);
|
|
3782
|
+
}
|
|
3783
|
+
validateOrder(order, context) {
|
|
3784
|
+
const clean = copyOwnRecord(order, context);
|
|
3785
|
+
if (!this.broker || !this.investor) {
|
|
3786
|
+
throw new Error(`${context}: a confirmed Trader login is required`);
|
|
3787
|
+
}
|
|
3788
|
+
if (typeof clean.instrumentId !== "string" || !clean.instrumentId || clean.instrumentId.includes("\0") || clean.direction !== "0" && clean.direction !== "1") {
|
|
3789
|
+
throw new TypeError(`${context}: instrumentId and direction ("0"/"1") are required`);
|
|
3790
|
+
}
|
|
3791
|
+
if (typeof clean.combOffsetFlag !== "string" || !/^[0-6]$/.test(clean.combOffsetFlag)) {
|
|
3792
|
+
throw new TypeError(`${context}: combOffsetFlag must be one CTP offset digit 0..6; multi-leg orders are unsupported`);
|
|
3793
|
+
}
|
|
3794
|
+
if (clean.combHedgeFlag !== void 0 && (typeof clean.combHedgeFlag !== "string" || !/^[123567]$/.test(clean.combHedgeFlag))) {
|
|
3795
|
+
throw new TypeError(`${context}: combHedgeFlag must be one CTP hedge digit (1, 2, 3, 5, 6 or 7)`);
|
|
3796
|
+
}
|
|
3797
|
+
if (!Number.isInteger(clean.volumeTotalOriginal) || !(Number(clean.volumeTotalOriginal) > 0) || Number(clean.volumeTotalOriginal) > 2147483647) {
|
|
3798
|
+
throw new TypeError(`${context}: volumeTotalOriginal must be a positive int32`);
|
|
3799
|
+
}
|
|
3800
|
+
if (!Number.isFinite(clean.limitPrice) || !(Number(clean.limitPrice) > 0) || Number(clean.limitPrice) >= 1e300) {
|
|
3801
|
+
throw new TypeError(`${context}: limitPrice must be a positive finite price`);
|
|
3802
|
+
}
|
|
3803
|
+
if (clean.brokerId !== void 0 && clean.brokerId !== this.broker) {
|
|
3804
|
+
throw new TypeError(`${context}: brokerId must match the confirmed login`);
|
|
3805
|
+
}
|
|
3806
|
+
if (clean.investorId !== void 0 && clean.investorId !== this.investor) {
|
|
3807
|
+
throw new TypeError(`${context}: investorId must match the confirmed login`);
|
|
3808
|
+
}
|
|
3809
|
+
const value = (key, fallback) => clean[key] === void 0 ? fallback : clean[key];
|
|
3810
|
+
const empty = (v) => v === void 0 || v === "";
|
|
3811
|
+
if (value("orderPriceType", "2") !== "2" || value("timeCondition", "3") !== "3" || !empty(clean.gtdDate) || value("volumeCondition", "1") !== "1" || value("minVolume", 1) !== 1 || value("contingentCondition", "1") !== "1" || value("stopPrice", 0) !== 0 || value("forceCloseReason", "0") !== "0" || value("isAutoSuspend", 0) !== 0 || !empty(clean.businessUnit) || value("requestId", 0) !== 0 || value("userForceClose", 0) !== 0 || value("isSwapOrder", 0) !== 0 || !empty(clean.exchangeId) || !empty(clean.investUnitId) || !empty(clean.accountId) || !empty(clean.currencyId) || !empty(clean.clientId) || value("sessionReqSeq", 0) !== 0) {
|
|
3812
|
+
throw new TypeError(`${context}: only an immediate single-instrument GFD limit order is supported`);
|
|
3813
|
+
}
|
|
3814
|
+
return {
|
|
3815
|
+
...clean,
|
|
3816
|
+
orderPriceType: "2",
|
|
3817
|
+
combHedgeFlag: clean.combHedgeFlag ?? "1",
|
|
3818
|
+
timeCondition: "3",
|
|
3819
|
+
gtdDate: "",
|
|
3820
|
+
volumeCondition: "1",
|
|
3821
|
+
minVolume: 1,
|
|
3822
|
+
contingentCondition: "1",
|
|
3823
|
+
stopPrice: 0,
|
|
3824
|
+
forceCloseReason: "0",
|
|
3825
|
+
isAutoSuspend: 0,
|
|
3826
|
+
businessUnit: "",
|
|
3827
|
+
requestId: 0,
|
|
3828
|
+
userForceClose: 0,
|
|
3829
|
+
isSwapOrder: 0,
|
|
3830
|
+
exchangeId: "",
|
|
3831
|
+
investUnitId: "",
|
|
3832
|
+
accountId: "",
|
|
3833
|
+
currencyId: "",
|
|
3834
|
+
clientId: "",
|
|
3835
|
+
sessionReqSeq: 0,
|
|
3836
|
+
brokerId: this.broker,
|
|
3837
|
+
investorId: this.investor
|
|
3838
|
+
};
|
|
3839
|
+
}
|
|
2808
3840
|
/**
|
|
2809
3841
|
* Insert an order through the C++ pre-trade risk gate. Resolves on submission:
|
|
2810
3842
|
* CTP sends no success acknowledgement for an accepted order - only
|
|
@@ -2814,140 +3846,224 @@ var Trader = class extends TraderBase {
|
|
|
2814
3846
|
* unique numeric value automatically.
|
|
2815
3847
|
*/
|
|
2816
3848
|
reqOrderInsert(req = {}) {
|
|
2817
|
-
|
|
3849
|
+
const order = this.withAutoOrderRef(this.validateOrder(req, "reqOrderInsert"));
|
|
3850
|
+
this.encode(STRUCT_ID.InputOrder, order);
|
|
3851
|
+
const result = super.reqOrderInsert(order);
|
|
3852
|
+
this.commitOrderRef(order);
|
|
3853
|
+
return result;
|
|
2818
3854
|
}
|
|
2819
3855
|
/** Publish pre-trade risk limits to the C++ enforcer (takes effect at once). */
|
|
2820
|
-
|
|
2821
|
-
|
|
2822
|
-
|
|
2823
|
-
|
|
2824
|
-
|
|
2825
|
-
|
|
2826
|
-
|
|
2827
|
-
|
|
3856
|
+
setRiskLimits(config) {
|
|
3857
|
+
const clean = copyOwnRecord(config, "setRiskLimits");
|
|
3858
|
+
for (const key of ownStringKeys(clean, "setRiskLimits")) {
|
|
3859
|
+
if (!RISK_LIMIT_KEYS.has(key))
|
|
3860
|
+
throw new TypeError(`setRiskLimits: unknown field ${key}`);
|
|
3861
|
+
}
|
|
3862
|
+
assertPositiveInt32OrDisabled("setRiskLimits.maxOrderVolume", clean.maxOrderVolume);
|
|
3863
|
+
assertFiniteLimit("setRiskLimits.maxPriceDeviation", clean.maxPriceDeviation);
|
|
3864
|
+
assertFiniteLimit("setRiskLimits.maxNotional", clean.maxNotional);
|
|
3865
|
+
assertFiniteLimit("setRiskLimits.maxOrdersPerSec", clean.maxOrdersPerSec);
|
|
3866
|
+
assertFiniteLimit("setRiskLimits.orderBurst", clean.orderBurst);
|
|
3867
|
+
assertFiniteLimit("setRiskLimits.maxCloseOrdersPerSec", clean.maxCloseOrdersPerSec);
|
|
3868
|
+
assertFiniteLimit("setRiskLimits.closeOrderBurst", clean.closeOrderBurst);
|
|
3869
|
+
assertFiniteLimit("setRiskLimits.maxAccountMargin", clean.maxAccountMargin);
|
|
3870
|
+
assertFiniteLimit("setRiskLimits.maxReferenceAgeMs", clean.maxReferenceAgeMs);
|
|
3871
|
+
if (clean.maxReferenceAgeMs !== void 0 && !(clean.maxReferenceAgeMs > 0)) {
|
|
3872
|
+
throw new TypeError("setRiskLimits.maxReferenceAgeMs must be > 0");
|
|
3873
|
+
}
|
|
3874
|
+
this.native.setRiskLimits(clean);
|
|
2828
3875
|
return this;
|
|
2829
3876
|
}
|
|
2830
|
-
/**
|
|
2831
|
-
*
|
|
2832
|
-
|
|
2833
|
-
|
|
2834
|
-
* (not sent to the exchange immediately) are likewise not gated. Takes effect
|
|
2835
|
-
* at once; reverse with {@link resume}. */
|
|
2836
|
-
halt() {
|
|
2837
|
-
this.native.riskHalt();
|
|
3877
|
+
/** Enter REDUCE_ONLY atomically at the final vendor-API send barrier. Armed
|
|
3878
|
+
* opens remain registered but cannot send until resume(). */
|
|
3879
|
+
reduceOnly() {
|
|
3880
|
+
this.native.riskReduceOnly();
|
|
2838
3881
|
return this;
|
|
2839
3882
|
}
|
|
2840
|
-
/**
|
|
2841
|
-
|
|
2842
|
-
|
|
3883
|
+
/** Enter HALT_ALL atomically: both opening and closing order inserts, advanced
|
|
3884
|
+
* mutations and bank/futures transfers are refused, and all existing armed
|
|
3885
|
+
* triggers are cleared. New arm() calls are rejected until resume().
|
|
3886
|
+
* Cancellation actions remain available so working
|
|
3887
|
+
* exchange orders can still be withdrawn. */
|
|
3888
|
+
haltAll() {
|
|
3889
|
+
this.native.riskHaltAll();
|
|
2843
3890
|
return this;
|
|
2844
3891
|
}
|
|
2845
|
-
/**
|
|
2846
|
-
|
|
2847
|
-
this.native.
|
|
3892
|
+
/** Return to NORMAL mode after reduceOnly() or haltAll(). */
|
|
3893
|
+
resume() {
|
|
3894
|
+
this.native.riskResume();
|
|
2848
3895
|
return this;
|
|
2849
3896
|
}
|
|
2850
|
-
/**
|
|
2851
|
-
*
|
|
3897
|
+
/** Use a MarketData feed as the live reference for the maxPriceDeviation check.
|
|
3898
|
+
* Wires the feed's C++ snapshot cache straight into this Trader's risk engine,
|
|
3899
|
+
* so the deviation check reads current prices in C++ on the order path (no JS
|
|
3900
|
+
* round-trip, and it also covers armed orders that fire with no JS in the loop).
|
|
3901
|
+
* Without a fresh reference, an enabled deviation check fails closed. */
|
|
2852
3902
|
trackMarketData(md) {
|
|
2853
|
-
|
|
2854
|
-
return this;
|
|
2855
|
-
}
|
|
2856
|
-
/** Set a contract's multiplier (合约乘数) for position-cost accounting. */
|
|
2857
|
-
setMultiplier(instrumentId, multiplier) {
|
|
2858
|
-
this.native.setMultiplier(instrumentId, multiplier);
|
|
3903
|
+
this.native._attachSnapshot(md._snapshotExternal());
|
|
2859
3904
|
return this;
|
|
2860
3905
|
}
|
|
3906
|
+
// Contract multipliers (for cost accounting) and margin rates (for the
|
|
3907
|
+
// maxAccountMargin cap) are NOT fed from JS: the C++ risk engine sources them directly
|
|
3908
|
+
// from CTP's OnRspQryInstrument / OnRspQryInstrumentMarginRate callbacks (see
|
|
3909
|
+
// scripts/codegen/generate-trader.mjs). So any reqQryInstrument keeps
|
|
3910
|
+
// multipliers current, and querying reqQryInstrumentMarginRate for the
|
|
3911
|
+
// syncMarginRates() loads investor plus exchange-base schedules. Missing
|
|
3912
|
+
// metadata fails closed; IsRelative is combined with the matching base.
|
|
2861
3913
|
/**
|
|
2862
3914
|
* Cap the open position (in lots) for one instrument, enforced in C++ on
|
|
2863
3915
|
* every opening order. Pass a number to cap both sides at once, or
|
|
2864
3916
|
* `{ long, short }` to cap each side separately. Within `{ long, short }`,
|
|
2865
3917
|
* **omitting a side leaves that side's current cap unchanged** (on a re-call it
|
|
2866
|
-
* is NOT reset to uncapped), and passing
|
|
3918
|
+
* is NOT reset to uncapped), and passing `0` for a side removes its cap.
|
|
2867
3919
|
* Long and short are always tracked independently.
|
|
2868
3920
|
*
|
|
2869
|
-
*
|
|
2870
|
-
* so rapid bursts of opens can momentarily overshoot before the fills land —
|
|
2871
|
-
* size the cap with that in mind.
|
|
3921
|
+
* Held positions and in-flight working opens are counted atomically.
|
|
2872
3922
|
*
|
|
2873
|
-
* td.
|
|
2874
|
-
* td.
|
|
3923
|
+
* td.setInstrumentPositionLimit("rb2610", 100);
|
|
3924
|
+
* td.setInstrumentPositionLimit("ru2610", { long: 100, short: 20 });
|
|
2875
3925
|
*/
|
|
2876
|
-
|
|
2877
|
-
|
|
2878
|
-
|
|
2879
|
-
|
|
2880
|
-
this.native.setMaxPositionVolume(instrumentId, false, max);
|
|
2881
|
-
} else {
|
|
2882
|
-
assertFiniteLimit("setMaxPosition.long", max.long);
|
|
2883
|
-
assertFiniteLimit("setMaxPosition.short", max.short);
|
|
2884
|
-
if (max.long !== void 0)
|
|
2885
|
-
this.native.setMaxPositionVolume(instrumentId, true, max.long);
|
|
2886
|
-
if (max.short !== void 0)
|
|
2887
|
-
this.native.setMaxPositionVolume(instrumentId, false, max.short);
|
|
2888
|
-
}
|
|
3926
|
+
setInstrumentPositionLimit(instrumentId, limit) {
|
|
3927
|
+
assertInstrumentId("setInstrumentPositionLimit", instrumentId);
|
|
3928
|
+
const row = this.normalizePositionLimit(instrumentId, limit);
|
|
3929
|
+
this.native._setInstrumentPositionLimits([row]);
|
|
2889
3930
|
return this;
|
|
2890
3931
|
}
|
|
2891
3932
|
/** Cap several instruments at once, e.g.
|
|
2892
3933
|
* `{ rb2610: 100, ru2610: { long: 100, short: 20 } }`. */
|
|
2893
|
-
|
|
2894
|
-
|
|
2895
|
-
|
|
3934
|
+
setInstrumentPositionLimits(limits) {
|
|
3935
|
+
const rows = ownStringKeys(limits, "setInstrumentPositionLimits").map((instrumentId) => {
|
|
3936
|
+
const limit = limits[instrumentId];
|
|
3937
|
+
assertInstrumentId("setInstrumentPositionLimits", instrumentId);
|
|
3938
|
+
return this.normalizePositionLimit(instrumentId, limit);
|
|
3939
|
+
});
|
|
3940
|
+
this.native._setInstrumentPositionLimits(rows);
|
|
2896
3941
|
return this;
|
|
2897
3942
|
}
|
|
3943
|
+
normalizePositionLimit(instrumentId, limit) {
|
|
3944
|
+
if (typeof limit === "number") {
|
|
3945
|
+
assertLotLimit("setInstrumentPositionLimit", limit);
|
|
3946
|
+
return copyOwnRecord({ instrumentId, long: limit, short: limit }, "setInstrumentPositionLimit");
|
|
3947
|
+
}
|
|
3948
|
+
assertPlainRecord(limit, "setInstrumentPositionLimit");
|
|
3949
|
+
const clean = copyOwnRecord(limit, "setInstrumentPositionLimit");
|
|
3950
|
+
if (clean.long === void 0 && clean.short === void 0) {
|
|
3951
|
+
throw new TypeError("setInstrumentPositionLimit requires a number or at least one of long/short");
|
|
3952
|
+
}
|
|
3953
|
+
for (const key of ownStringKeys(clean, "setInstrumentPositionLimit")) {
|
|
3954
|
+
if (!POSITION_LIMIT_KEYS.has(key))
|
|
3955
|
+
throw new TypeError(`setInstrumentPositionLimit: unknown field ${key}`);
|
|
3956
|
+
}
|
|
3957
|
+
assertLotLimit("setInstrumentPositionLimit.long", clean.long);
|
|
3958
|
+
assertLotLimit("setInstrumentPositionLimit.short", clean.short);
|
|
3959
|
+
return copyOwnRecord({ instrumentId, long: clean.long, short: clean.short }, "setInstrumentPositionLimit");
|
|
3960
|
+
}
|
|
2898
3961
|
/**
|
|
2899
|
-
* Cap one instrument's open
|
|
2900
|
-
* long and short summed
|
|
2901
|
-
*
|
|
2902
|
-
*
|
|
2903
|
-
* `maxCost <= 0` to remove it. Fill-based, same caveat as maxPositionCost.
|
|
3962
|
+
* Cap one instrument's scheduled open margin (CTP by-money + by-volume,
|
|
3963
|
+
* long and short summed), enforced in C++ on every opening order. This is
|
|
3964
|
+
* independent of the account-wide maxAccountMargin cap; both apply. Pass
|
|
3965
|
+
* `limit = 0` to remove it. Held and in-flight exposure both count.
|
|
2904
3966
|
*/
|
|
2905
|
-
|
|
2906
|
-
|
|
2907
|
-
|
|
3967
|
+
setInstrumentMarginLimit(instrumentId, limit) {
|
|
3968
|
+
assertInstrumentId("setInstrumentMarginLimit", instrumentId);
|
|
3969
|
+
assertFiniteLimit("setInstrumentMarginLimit", limit);
|
|
3970
|
+
this.native._setInstrumentMarginLimits([{ instrumentId, limit }]);
|
|
2908
3971
|
return this;
|
|
2909
3972
|
}
|
|
2910
|
-
/** Cap several instruments' open
|
|
3973
|
+
/** Cap several instruments' scheduled open margin at once, e.g.
|
|
2911
3974
|
* `{ ag2608: 2_000_000, au2608: 5_000_000 }`. */
|
|
2912
|
-
|
|
2913
|
-
|
|
2914
|
-
|
|
2915
|
-
|
|
2916
|
-
|
|
3975
|
+
setInstrumentMarginLimits(limits) {
|
|
3976
|
+
const rows = ownStringKeys(limits, "setInstrumentMarginLimits").map((instrumentId) => {
|
|
3977
|
+
const limit = limits[instrumentId];
|
|
3978
|
+
assertInstrumentId("setInstrumentMarginLimits", instrumentId);
|
|
3979
|
+
assertFiniteLimit(`setInstrumentMarginLimits.${instrumentId}`, limit);
|
|
3980
|
+
return { instrumentId, limit };
|
|
3981
|
+
});
|
|
3982
|
+
this.native._setInstrumentMarginLimits(rows);
|
|
2917
3983
|
return this;
|
|
2918
3984
|
}
|
|
2919
|
-
/**
|
|
2920
|
-
|
|
2921
|
-
|
|
2922
|
-
|
|
3985
|
+
/** Atomically replace held positions from a complete manually reconciled
|
|
3986
|
+
* snapshot. `margin` is CTP InvestorPosition.UseMargin. An empty array is an
|
|
3987
|
+
* authoritative flat book. Partial/incremental seeding is intentionally not
|
|
3988
|
+
* exposed because armed orders can run between JS calls. */
|
|
3989
|
+
seedPositions(positions) {
|
|
3990
|
+
if (!Array.isArray(positions))
|
|
3991
|
+
throw new TypeError("seedPositions requires a complete position array");
|
|
3992
|
+
const seeds = [];
|
|
3993
|
+
const positionCount = positions.length;
|
|
3994
|
+
for (let i = 0; i < positionCount; i++) {
|
|
3995
|
+
if (!Object.prototype.hasOwnProperty.call(positions, i))
|
|
3996
|
+
throw new TypeError(`seedPositions row ${i} must be an explicit array entry`);
|
|
3997
|
+
const row = copyOwnRecord(positions[i], `seedPositions row ${i}`);
|
|
3998
|
+
for (const key of ownStringKeys(row, `seedPositions row ${i}`))
|
|
3999
|
+
if (!POSITION_SEED_KEYS.has(key))
|
|
4000
|
+
throw new TypeError(`seedPositions row ${i}: unknown field ${key}`);
|
|
4001
|
+
assertInstrumentId("seedPositions", row.instrumentId);
|
|
4002
|
+
if (row.side !== "long" && row.side !== "short" || typeof row.hedgeFlag !== "string" || !/^[123567]$/.test(row.hedgeFlag) || !Number.isInteger(row.volume) || row.volume < 0 || !Number.isFinite(row.margin) || row.margin < 0) {
|
|
4003
|
+
throw new TypeError("seedPositions requires long/short, one hedgeFlag digit, a non-negative integer volume and non-negative finite margin");
|
|
4004
|
+
}
|
|
4005
|
+
seeds.push({
|
|
4006
|
+
instrumentId: row.instrumentId,
|
|
4007
|
+
isLong: row.side === "long",
|
|
4008
|
+
hedgeFlag: row.hedgeFlag,
|
|
4009
|
+
volume: row.volume,
|
|
4010
|
+
margin: row.margin
|
|
4011
|
+
});
|
|
4012
|
+
}
|
|
4013
|
+
return this.replacePositionSeeds(seeds);
|
|
4014
|
+
}
|
|
4015
|
+
replacePositionSeeds(seeds) {
|
|
4016
|
+
for (let attempt = 0; attempt < 5; attempt++) {
|
|
4017
|
+
const revision = this.native.riskRevision();
|
|
4018
|
+
if (this.native.replacePositions(seeds, revision))
|
|
4019
|
+
return this;
|
|
4020
|
+
}
|
|
4021
|
+
throw new Error("position snapshot could not stabilize; live state kept unchanged");
|
|
2923
4022
|
}
|
|
2924
|
-
/**
|
|
2925
|
-
*
|
|
2926
|
-
*
|
|
2927
|
-
* matter for them, but a per-side *volume* cap on a net-mode instrument would
|
|
2928
|
-
* track the wrong side — for net-mode accounts, seed those via seedPosition()
|
|
2929
|
-
* with the side you intend. */
|
|
4023
|
+
/** Atomically replace held position margin from complete gross-mode query rows
|
|
4024
|
+
* (`posiDirection` '2' long, '3' short). Net/unknown direction is rejected
|
|
4025
|
+
* because guessing a side corrupts per-side volume caps. */
|
|
2930
4026
|
seedFromPositions(positions) {
|
|
4027
|
+
const seeds = this.aggregatePositions(positions);
|
|
4028
|
+
return this.replacePositionSeeds(seeds);
|
|
4029
|
+
}
|
|
4030
|
+
aggregatePositions(positions) {
|
|
4031
|
+
if (!Array.isArray(positions))
|
|
4032
|
+
throw new TypeError("position snapshot must be an array");
|
|
2931
4033
|
const agg = /* @__PURE__ */ new Map();
|
|
2932
|
-
|
|
2933
|
-
|
|
4034
|
+
const positionCount = positions.length;
|
|
4035
|
+
for (let i = 0; i < positionCount; i++) {
|
|
4036
|
+
if (!Object.prototype.hasOwnProperty.call(positions, i))
|
|
4037
|
+
throw new TypeError(`position snapshot row ${i} must be an explicit array entry`);
|
|
4038
|
+
const p = positions[i];
|
|
4039
|
+
const plain = p !== null && typeof p === "object" && !Array.isArray(p) && (Object.getPrototypeOf(p) === Object.prototype || Object.getPrototypeOf(p) === null);
|
|
4040
|
+
const row = plain ? copyOwnRecord(p, "position snapshot row") : void 0;
|
|
4041
|
+
if (!row || typeof row.instrumentId !== "string" || !row.instrumentId || row.instrumentId.includes("\0") || !Number.isInteger(row.position) || row.position < 0 || !Number.isFinite(row.useMargin) || row.useMargin < 0 || row.posiDirection !== "2" && row.posiDirection !== "3" || typeof row.hedgeFlag !== "string" || !/^[123567]$/.test(row.hedgeFlag)) {
|
|
4042
|
+
throw new TypeError(`invalid position snapshot for ${row?.instrumentId || "<unknown>"}`);
|
|
4043
|
+
}
|
|
4044
|
+
if (!(row.position > 0))
|
|
2934
4045
|
continue;
|
|
2935
|
-
const
|
|
2936
|
-
const key = `${
|
|
2937
|
-
const e = agg.get(key) ?? {
|
|
2938
|
-
e.
|
|
2939
|
-
e.
|
|
4046
|
+
const isLong = row.posiDirection === "2";
|
|
4047
|
+
const key = `${row.instrumentId}|${isLong}|${row.hedgeFlag}`;
|
|
4048
|
+
const e = agg.get(key) ?? { instrumentId: row.instrumentId, isLong, hedgeFlag: row.hedgeFlag, volume: 0, margin: 0 };
|
|
4049
|
+
const volume = e.volume + row.position;
|
|
4050
|
+
const margin = e.margin + row.useMargin;
|
|
4051
|
+
if (!Number.isSafeInteger(volume) || !Number.isFinite(margin)) {
|
|
4052
|
+
throw new RangeError(`position snapshot overflow for ${row.instrumentId}`);
|
|
4053
|
+
}
|
|
4054
|
+
e.volume = volume;
|
|
4055
|
+
e.margin = margin;
|
|
2940
4056
|
agg.set(key, e);
|
|
2941
4057
|
}
|
|
2942
|
-
|
|
2943
|
-
this.seedPosition(e.id, e.long ? "long" : "short", e.vol, e.cost);
|
|
2944
|
-
return this;
|
|
4058
|
+
return [...agg.values()];
|
|
2945
4059
|
}
|
|
2946
|
-
/** Current total open-position
|
|
2947
|
-
|
|
2948
|
-
return this.native.
|
|
4060
|
+
/** Current total open-position margin tracked by the C++ risk engine. */
|
|
4061
|
+
get accountMargin() {
|
|
4062
|
+
return this.native.accountMargin();
|
|
2949
4063
|
}
|
|
2950
|
-
/** Clear
|
|
4064
|
+
/** Clear held position state only and mark it uncertain. Working-order
|
|
4065
|
+
* reservations are preserved; openings remain blocked until a complete
|
|
4066
|
+
* seedFromPositions() or syncPositions() succeeds. */
|
|
2951
4067
|
resetPositions() {
|
|
2952
4068
|
this.native.resetPositions();
|
|
2953
4069
|
return this;
|
|
@@ -2960,56 +4076,136 @@ var Trader = class extends TraderBase {
|
|
|
2960
4076
|
* instrument); otherwise empty is returned as-is (e.g. a genuinely flat
|
|
2961
4077
|
* position book, so a flat account doesn't waste the full retry budget).
|
|
2962
4078
|
*/
|
|
2963
|
-
async queryWithRetry(query, requireNonEmpty, attempts = 5) {
|
|
4079
|
+
async queryWithRetry(query, requireNonEmpty, contextToken, attempts = 5) {
|
|
2964
4080
|
let lastErr;
|
|
2965
4081
|
for (let i = 0; i < attempts; i++) {
|
|
2966
|
-
if (i > 0)
|
|
2967
|
-
await sleep(1100);
|
|
2968
4082
|
try {
|
|
4083
|
+
this.assertRequestContext(contextToken, "query synchronization");
|
|
2969
4084
|
const rows = await query();
|
|
4085
|
+
this.assertRequestContext(contextToken, "query synchronization");
|
|
2970
4086
|
if (!requireNonEmpty || rows.length > 0)
|
|
2971
4087
|
return rows;
|
|
2972
4088
|
} catch (e) {
|
|
4089
|
+
this.assertRequestContext(contextToken, "query synchronization");
|
|
4090
|
+
const code = e?.ctpReturnCode;
|
|
4091
|
+
if (code !== -2 && code !== -3)
|
|
4092
|
+
throw e;
|
|
2973
4093
|
lastErr = e;
|
|
2974
4094
|
}
|
|
2975
4095
|
}
|
|
2976
4096
|
if (lastErr)
|
|
2977
4097
|
throw lastErr;
|
|
2978
|
-
|
|
2979
|
-
|
|
2980
|
-
|
|
2981
|
-
|
|
2982
|
-
|
|
4098
|
+
if (requireNonEmpty)
|
|
4099
|
+
throw new Error(`CTP query returned no rows after ${attempts} attempts`);
|
|
4100
|
+
throw new Error("query retry invariant violated");
|
|
4101
|
+
}
|
|
4102
|
+
/** Empty position/order snapshots are ambiguous immediately after login. Require
|
|
4103
|
+
* the same empty result twice, one query interval apart, before treating it as
|
|
4104
|
+
* authoritative. */
|
|
4105
|
+
async authoritativeQuery(query, contextToken) {
|
|
4106
|
+
const first = await this.queryWithRetry(query, false, contextToken);
|
|
4107
|
+
if (first.length > 0)
|
|
4108
|
+
return first;
|
|
4109
|
+
return this.queryWithRetry(query, false, contextToken);
|
|
4110
|
+
}
|
|
4111
|
+
/** Query instruments so the C++ risk engine picks up their multipliers (it
|
|
4112
|
+
* sources them directly from OnRspQryInstrument — no JS feed). No args queries
|
|
4113
|
+
* all instruments (one request); otherwise the given symbols. Retries through
|
|
4114
|
+
* cold-start flow control. Returns the count of contracts with a multiplier. */
|
|
2983
4115
|
async syncMultipliers(instrumentIds) {
|
|
4116
|
+
const contextToken = this.requestContextToken();
|
|
4117
|
+
if (instrumentIds !== void 0) {
|
|
4118
|
+
instrumentIds = copyDenseStringArray(instrumentIds, "syncMultipliers instrumentIds");
|
|
4119
|
+
if (instrumentIds.length === 0)
|
|
4120
|
+
return 0;
|
|
4121
|
+
}
|
|
2984
4122
|
let count = 0;
|
|
2985
4123
|
const apply = (rows) => {
|
|
2986
|
-
|
|
2987
|
-
|
|
2988
|
-
|
|
4124
|
+
const finalByInstrument = /* @__PURE__ */ new Map();
|
|
4125
|
+
for (const r of rows)
|
|
4126
|
+
finalByInstrument.set(r.instrumentId, r);
|
|
4127
|
+
for (const r of finalByInstrument.values()) {
|
|
4128
|
+
if (r.instrumentId && Number.isFinite(r.volumeMultiple) && r.volumeMultiple > 0 && r.volumeMultiple < 1e300)
|
|
2989
4129
|
count++;
|
|
2990
|
-
}
|
|
2991
4130
|
}
|
|
2992
4131
|
};
|
|
2993
|
-
if (instrumentIds
|
|
2994
|
-
for (
|
|
2995
|
-
apply(await this.queryWithRetry(() => this.reqQryInstrument({ instrumentId
|
|
2996
|
-
if (i < instrumentIds.length - 1)
|
|
2997
|
-
await sleep(1100);
|
|
4132
|
+
if (instrumentIds) {
|
|
4133
|
+
for (const instrumentId of new Set(instrumentIds)) {
|
|
4134
|
+
apply(await this.queryWithRetry(async () => (await this.reqQryInstrument({ instrumentId })).filter((row) => row.instrumentId === instrumentId), true, contextToken));
|
|
2998
4135
|
}
|
|
2999
4136
|
} else {
|
|
3000
|
-
apply(await this.queryWithRetry(() => this.reqQryInstrument({}), true));
|
|
4137
|
+
apply(await this.queryWithRetry(() => this.reqQryInstrument({}), true, contextToken));
|
|
4138
|
+
}
|
|
4139
|
+
return count;
|
|
4140
|
+
}
|
|
4141
|
+
/** Query investor margin schedules for a bounded universe. The exchange-base
|
|
4142
|
+
* query is issued only when the investor row is relative; the shared query
|
|
4143
|
+
* scheduler enforces spacing. Returns the number of usable schedules. */
|
|
4144
|
+
async syncMarginRates(instrumentIds, hedgeFlag = "1") {
|
|
4145
|
+
const contextToken = this.requestContextToken();
|
|
4146
|
+
instrumentIds = copyDenseStringArray(instrumentIds, "syncMarginRates", false);
|
|
4147
|
+
if (typeof hedgeFlag !== "string" || !/^[123567]$/.test(hedgeFlag)) {
|
|
4148
|
+
throw new TypeError("syncMarginRates hedgeFlag must be 1, 2, 3, 5, 6 or 7");
|
|
4149
|
+
}
|
|
4150
|
+
const brokerId = this.broker;
|
|
4151
|
+
const investorId = this.investor;
|
|
4152
|
+
if (!brokerId || !investorId) {
|
|
4153
|
+
throw new Error("syncMarginRates requires a successful trader login first");
|
|
4154
|
+
}
|
|
4155
|
+
let count = 0;
|
|
4156
|
+
for (const instrumentId of new Set(instrumentIds)) {
|
|
4157
|
+
const investorRows = await this.queryWithRetry(async () => (await this.reqQryInstrumentMarginRate({
|
|
4158
|
+
brokerId,
|
|
4159
|
+
investorId,
|
|
4160
|
+
instrumentId,
|
|
4161
|
+
hedgeFlag
|
|
4162
|
+
})).filter((row) => row.instrumentId === instrumentId && row.hedgeFlag === hedgeFlag), true, contextToken);
|
|
4163
|
+
const investor = investorRows.at(-1);
|
|
4164
|
+
const relative = investor.isRelative !== 0;
|
|
4165
|
+
const baseRows = relative ? await this.queryWithRetry(async () => (await this.reqQryExchangeMarginRate({
|
|
4166
|
+
brokerId,
|
|
4167
|
+
instrumentId,
|
|
4168
|
+
hedgeFlag
|
|
4169
|
+
})).filter((row) => row.instrumentId === instrumentId && row.hedgeFlag === hedgeFlag), true, contextToken) : [];
|
|
4170
|
+
const base = baseRows.at(-1);
|
|
4171
|
+
const component = (value) => Number.isFinite(value) && value >= 0 && value < 1e300;
|
|
4172
|
+
const scheduleUsable = (row) => !!row && component(row.longMarginRatioByMoney) && component(row.longMarginRatioByVolume) && component(row.shortMarginRatioByMoney) && component(row.shortMarginRatioByVolume) && (row.longMarginRatioByMoney > 0 || row.longMarginRatioByVolume > 0) && (row.shortMarginRatioByMoney > 0 || row.shortMarginRatioByVolume > 0);
|
|
4173
|
+
const investorComponentsValid = component(investor.longMarginRatioByMoney) && component(investor.longMarginRatioByVolume) && component(investor.shortMarginRatioByMoney) && component(investor.shortMarginRatioByVolume);
|
|
4174
|
+
if (investorComponentsValid && (relative ? scheduleUsable(base) : scheduleUsable(investor)))
|
|
4175
|
+
count++;
|
|
3001
4176
|
}
|
|
3002
4177
|
return count;
|
|
3003
4178
|
}
|
|
3004
|
-
/**
|
|
3005
|
-
*
|
|
3006
|
-
|
|
3007
|
-
|
|
3008
|
-
const
|
|
3009
|
-
|
|
3010
|
-
|
|
3011
|
-
this.
|
|
3012
|
-
|
|
4179
|
+
/** Replace held position margin from CTP (`reqQryInvestorPosition`). The
|
|
4180
|
+
* replacement is revision-checked: if an order/trade callback races the
|
|
4181
|
+
* snapshot it retries without clearing live state or reservations. */
|
|
4182
|
+
async syncPositions() {
|
|
4183
|
+
const contextToken = this.requestContextToken();
|
|
4184
|
+
if (arguments.length !== 0)
|
|
4185
|
+
throw new TypeError("syncPositions does not accept account overrides");
|
|
4186
|
+
const brokerId = this.broker;
|
|
4187
|
+
const investorId = this.investor;
|
|
4188
|
+
if (typeof brokerId !== "string" || !brokerId || brokerId.includes("\0") || typeof investorId !== "string" || !investorId || investorId.includes("\0"))
|
|
4189
|
+
throw new Error("syncPositions requires a successful trader login");
|
|
4190
|
+
this.native._markPositionLedgerUncertain();
|
|
4191
|
+
for (let attempt = 0; attempt < 5; attempt++) {
|
|
4192
|
+
this.assertRequestContext(contextToken, "position synchronization");
|
|
4193
|
+
const revision = this.native.riskRevision();
|
|
4194
|
+
const rows = await this.authoritativeQuery(async () => {
|
|
4195
|
+
const result = await this.reqQryInvestorPosition({ brokerId, investorId });
|
|
4196
|
+
if (result.some((row) => row.brokerId !== brokerId || row.investorId !== investorId)) {
|
|
4197
|
+
throw new Error("position snapshot contains a mismatched account identity");
|
|
4198
|
+
}
|
|
4199
|
+
return result;
|
|
4200
|
+
}, contextToken);
|
|
4201
|
+
const seeds = this.aggregatePositions(rows);
|
|
4202
|
+
this.assertRequestContext(contextToken, "position synchronization");
|
|
4203
|
+
if (this.native.replacePositions(seeds, revision))
|
|
4204
|
+
return rows.filter((r) => r.position > 0).length;
|
|
4205
|
+
if (attempt < 4)
|
|
4206
|
+
await sleep(100);
|
|
4207
|
+
}
|
|
4208
|
+
throw new Error("position snapshot could not stabilize; live state kept unchanged");
|
|
3013
4209
|
}
|
|
3014
4210
|
/**
|
|
3015
4211
|
* Rebuild the in-flight reservation from CTP's currently-working orders
|
|
@@ -3020,31 +4216,71 @@ var Trader = class extends TraderBase {
|
|
|
3020
4216
|
* of working open orders re-reserved. Run syncMultipliers() first so the
|
|
3021
4217
|
* reserved cost uses the right contract multiplier.
|
|
3022
4218
|
*/
|
|
3023
|
-
async syncOrders(
|
|
3024
|
-
const
|
|
3025
|
-
|
|
3026
|
-
|
|
3027
|
-
const
|
|
3028
|
-
|
|
3029
|
-
|
|
3030
|
-
|
|
3031
|
-
|
|
3032
|
-
|
|
3033
|
-
|
|
3034
|
-
|
|
3035
|
-
|
|
3036
|
-
|
|
3037
|
-
|
|
3038
|
-
|
|
3039
|
-
|
|
3040
|
-
|
|
3041
|
-
|
|
3042
|
-
|
|
3043
|
-
|
|
3044
|
-
|
|
3045
|
-
|
|
3046
|
-
|
|
3047
|
-
|
|
4219
|
+
async syncOrders() {
|
|
4220
|
+
const contextToken = this.requestContextToken();
|
|
4221
|
+
if (arguments.length !== 0)
|
|
4222
|
+
throw new TypeError("syncOrders does not accept account overrides");
|
|
4223
|
+
const brokerId = this.broker;
|
|
4224
|
+
const investorId = this.investor;
|
|
4225
|
+
if (typeof brokerId !== "string" || !brokerId || brokerId.includes("\0") || typeof investorId !== "string" || !investorId || investorId.includes("\0"))
|
|
4226
|
+
throw new Error("syncOrders requires a successful trader login");
|
|
4227
|
+
this.native._markPositionLedgerUncertain();
|
|
4228
|
+
this.native._markOrderLedgerUncertain();
|
|
4229
|
+
for (let attempt = 0; attempt < 5; attempt++) {
|
|
4230
|
+
this.assertRequestContext(contextToken, "order synchronization");
|
|
4231
|
+
const revision = this.native.riskRevision();
|
|
4232
|
+
const rows = await this.authoritativeQuery(async () => {
|
|
4233
|
+
const result = await this.reqQryOrder({ brokerId, investorId });
|
|
4234
|
+
if (result.some((row) => row.brokerId !== brokerId || row.investorId !== investorId)) {
|
|
4235
|
+
throw new Error("order snapshot contains a mismatched account identity");
|
|
4236
|
+
}
|
|
4237
|
+
return result;
|
|
4238
|
+
}, contextToken);
|
|
4239
|
+
const terminal = /* @__PURE__ */ new Set(["0", "2", "4", "5"]);
|
|
4240
|
+
const active = rows.filter((o) => !terminal.has(o.orderStatus));
|
|
4241
|
+
for (const o of active) {
|
|
4242
|
+
const vol = o.volumeTotalOriginal - o.volumeTraded;
|
|
4243
|
+
if (!Number.isInteger(o.frontId) || !Number.isInteger(o.sessionId) || !o.orderRef || !o.instrumentId || o.direction !== "0" && o.direction !== "1" || typeof o.combOffsetFlag !== "string" || typeof o.combHedgeFlag !== "string" || !Number.isInteger(o.volumeTotalOriginal) || !Number.isInteger(o.volumeTraded) || o.volumeTraded < 0 || o.volumeTraded > o.volumeTotalOriginal || !Number.isInteger(vol) || vol < 0 || !Number.isFinite(o.limitPrice) || o.limitPrice < 0 || o.orderSysId && !o.exchangeId || /^[0-6]$/.test(o.combOffsetFlag) && !/^[123567]$/.test(o.combHedgeFlag)) {
|
|
4244
|
+
throw new TypeError(`invalid working-order snapshot for ${o.orderRef || "<unknown>"}`);
|
|
4245
|
+
}
|
|
4246
|
+
}
|
|
4247
|
+
const working = active.flatMap((o) => {
|
|
4248
|
+
const vol = o.volumeTotalOriginal - o.volumeTraded;
|
|
4249
|
+
const supportedSingleLeg = /^[0-6]$/.test(o.combOffsetFlag);
|
|
4250
|
+
if (supportedSingleLeg && o.combOffsetFlag !== "0")
|
|
4251
|
+
return [];
|
|
4252
|
+
return [{
|
|
4253
|
+
frontId: o.frontId,
|
|
4254
|
+
sessionId: o.sessionId,
|
|
4255
|
+
orderRef: o.orderRef,
|
|
4256
|
+
instrumentId: o.instrumentId,
|
|
4257
|
+
isLong: o.direction === "0",
|
|
4258
|
+
hedgeFlag: o.combHedgeFlag?.[0] || "1",
|
|
4259
|
+
vol,
|
|
4260
|
+
price: o.limitPrice,
|
|
4261
|
+
traded: o.volumeTraded,
|
|
4262
|
+
// Must be byte-identical to the native realtime key built in
|
|
4263
|
+
// traderspi.gen.cc (OnRtnOrder/OnRtnTrade):
|
|
4264
|
+
// day|broker|investor|exchange|instrument|orderSysId. broker/investor
|
|
4265
|
+
// are the confirmed session identity (validated == every row above),
|
|
4266
|
+
// so a reservation rebuilt on resync correlates with the subsequent
|
|
4267
|
+
// realtime order/trade callbacks instead of being stranded uncertain.
|
|
4268
|
+
orderSysKey: o.tradingDay && o.exchangeId && o.orderSysId ? `${o.tradingDay}|${brokerId}|${investorId}|${o.exchangeId}|${o.instrumentId}|${o.orderSysId}` : "",
|
|
4269
|
+
supportedSingleLeg
|
|
4270
|
+
}];
|
|
4271
|
+
});
|
|
4272
|
+
this.assertRequestContext(contextToken, "order synchronization");
|
|
4273
|
+
if (this.native.rebuildReservations(working, revision)) {
|
|
4274
|
+
const unsupported = working.filter((o) => !o.supportedSingleLeg);
|
|
4275
|
+
if (unsupported.length > 0) {
|
|
4276
|
+
throw new Error(`unsupported working order ${unsupported[0].orderRef}; opening inserts are fail-closed`);
|
|
4277
|
+
}
|
|
4278
|
+
return working.length;
|
|
4279
|
+
}
|
|
4280
|
+
if (attempt < 4)
|
|
4281
|
+
await sleep(100);
|
|
4282
|
+
}
|
|
4283
|
+
throw new Error("order snapshot could not stabilize; live state kept unchanged");
|
|
3048
4284
|
}
|
|
3049
4285
|
/**
|
|
3050
4286
|
* Arm a latency-critical trigger: when `md` sees the condition, the order is
|
|
@@ -3053,23 +4289,34 @@ var Trader = class extends TraderBase {
|
|
|
3053
4289
|
* rtn-order / rsp-order-insert events (correlate by the order's orderRef).
|
|
3054
4290
|
*/
|
|
3055
4291
|
arm(md, spec) {
|
|
3056
|
-
|
|
4292
|
+
const cleanSpec = copyOwnRecord(spec, "arm spec");
|
|
4293
|
+
assertObjectKeys(cleanSpec, "arm spec", ARM_SPEC_KEYS);
|
|
4294
|
+
if (!cleanSpec.instrumentId || cleanSpec.instrumentId.includes("\0") || !Number.isFinite(cleanSpec.triggerPrice) || !(cleanSpec.triggerPrice > 0) || cleanSpec.triggerPrice >= 1e300) {
|
|
3057
4295
|
throw new Error("arm: spec.instrumentId and a positive triggerPrice are required");
|
|
3058
4296
|
}
|
|
3059
|
-
const
|
|
3060
|
-
if (
|
|
3061
|
-
throw new Error("arm: spec.
|
|
4297
|
+
const validatedOrder = this.validateOrder(cleanSpec.order, "arm.order");
|
|
4298
|
+
if (cleanSpec.side !== "buy" && cleanSpec.side !== "sell") {
|
|
4299
|
+
throw new Error("arm: spec.side must be buy or sell");
|
|
3062
4300
|
}
|
|
3063
|
-
|
|
4301
|
+
if (validatedOrder.instrumentId !== cleanSpec.instrumentId) {
|
|
4302
|
+
throw new Error("arm: spec.instrumentId must match spec.order.instrumentId");
|
|
4303
|
+
}
|
|
4304
|
+
if (cleanSpec.side === "buy" !== (validatedOrder.direction === "0")) {
|
|
4305
|
+
throw new Error("arm: spec.side must match spec.order.direction");
|
|
4306
|
+
}
|
|
4307
|
+
const order = this.withAutoOrderRef(validatedOrder);
|
|
3064
4308
|
const bytes = this.encode(STRUCT_ID.InputOrder, order);
|
|
3065
|
-
|
|
4309
|
+
md.attachArm(this);
|
|
4310
|
+
this.trackMarketData(md);
|
|
4311
|
+
const id = this.native.arm(cleanSpec.instrumentId, cleanSpec.side === "buy" ? "0" : "1", cleanSpec.triggerPrice, bytes);
|
|
4312
|
+
this.commitOrderRef(order);
|
|
3066
4313
|
return { id, disarm: () => this.native.disarm(id) };
|
|
3067
4314
|
}
|
|
3068
4315
|
/** Observability for armed triggers (they fire in C++ with no JS in the loop):
|
|
3069
4316
|
* how many fired and were sent vs were refused by the risk gate / send.
|
|
3070
4317
|
* A blocked armed order is otherwise invisible, so poll this after a trigger
|
|
3071
4318
|
* you expected to fire. */
|
|
3072
|
-
armStats() {
|
|
4319
|
+
get armStats() {
|
|
3073
4320
|
return { fired: this.native._armFireCount(), blocked: this.native._armBlockedCount() };
|
|
3074
4321
|
}
|
|
3075
4322
|
/** @internal used by MarketData.attachArm to share the arm registry. */
|
|
@@ -3089,6 +4336,235 @@ var Trader = class extends TraderBase {
|
|
|
3089
4336
|
}
|
|
3090
4337
|
};
|
|
3091
4338
|
|
|
4339
|
+
// dist/market-data.js
|
|
4340
|
+
var MD_BASE = 4096;
|
|
4341
|
+
var MD_EVENTS = /* @__PURE__ */ new Map([
|
|
4342
|
+
[MD_BASE + 1, "front-connected"],
|
|
4343
|
+
[MD_BASE + 2, "front-disconnected"],
|
|
4344
|
+
[MD_BASE + 3, "heart-beat-warning"],
|
|
4345
|
+
[MD_BASE + 4, "rsp-user-login"],
|
|
4346
|
+
[MD_BASE + 5, "rsp-user-logout"],
|
|
4347
|
+
[MD_BASE + 6, "rsp-qry-multicast-instrument"],
|
|
4348
|
+
[MD_BASE + 7, "rsp-error"],
|
|
4349
|
+
[MD_BASE + 8, "rsp-sub-market-data"],
|
|
4350
|
+
[MD_BASE + 9, "rsp-unsub-market-data"],
|
|
4351
|
+
[MD_BASE + 10, "rsp-sub-for-quote"],
|
|
4352
|
+
[MD_BASE + 11, "rsp-unsub-for-quote"],
|
|
4353
|
+
[MD_BASE + 12, "rtn-depth-market-data"],
|
|
4354
|
+
[MD_BASE + 13, "rtn-for-quote"]
|
|
4355
|
+
]);
|
|
4356
|
+
var MarketDataEvent;
|
|
4357
|
+
(function(MarketDataEvent2) {
|
|
4358
|
+
MarketDataEvent2["FrontConnected"] = "front-connected";
|
|
4359
|
+
MarketDataEvent2["FrontDisconnected"] = "front-disconnected";
|
|
4360
|
+
MarketDataEvent2["HeartBeatWarning"] = "heart-beat-warning";
|
|
4361
|
+
MarketDataEvent2["RspUserLogin"] = "rsp-user-login";
|
|
4362
|
+
MarketDataEvent2["RspUserLogout"] = "rsp-user-logout";
|
|
4363
|
+
MarketDataEvent2["RspQryMulticastInstrument"] = "rsp-qry-multicast-instrument";
|
|
4364
|
+
MarketDataEvent2["RspError"] = "rsp-error";
|
|
4365
|
+
MarketDataEvent2["RspSubMarketData"] = "rsp-sub-market-data";
|
|
4366
|
+
MarketDataEvent2["RspUnSubMarketData"] = "rsp-unsub-market-data";
|
|
4367
|
+
MarketDataEvent2["RspSubForQuote"] = "rsp-sub-for-quote";
|
|
4368
|
+
MarketDataEvent2["RspUnSubForQuote"] = "rsp-unsub-for-quote";
|
|
4369
|
+
MarketDataEvent2["RtnDepthMarketData"] = "rtn-depth-market-data";
|
|
4370
|
+
MarketDataEvent2["RtnForQuote"] = "rtn-for-quote";
|
|
4371
|
+
})(MarketDataEvent || (MarketDataEvent = {}));
|
|
4372
|
+
function snapshotInstrumentIds(instrumentIds) {
|
|
4373
|
+
return copyDenseStringArray(instrumentIds, "instrumentIds");
|
|
4374
|
+
}
|
|
4375
|
+
function requestShapeError(value, allowed, label) {
|
|
4376
|
+
let keys;
|
|
4377
|
+
try {
|
|
4378
|
+
keys = ownStringKeys(value, label);
|
|
4379
|
+
} catch (error) {
|
|
4380
|
+
return error instanceof TypeError ? error : new TypeError(`${label} must be a plain object`);
|
|
4381
|
+
}
|
|
4382
|
+
for (const key of keys)
|
|
4383
|
+
if (!allowed.has(key))
|
|
4384
|
+
return new TypeError(`${label}: unknown field ${key}`);
|
|
4385
|
+
return void 0;
|
|
4386
|
+
}
|
|
4387
|
+
var LOGIN_KEYS = /* @__PURE__ */ new Set([
|
|
4388
|
+
"tradingDay",
|
|
4389
|
+
"brokerId",
|
|
4390
|
+
"userId",
|
|
4391
|
+
"password",
|
|
4392
|
+
"userProductInfo",
|
|
4393
|
+
"interfaceProductInfo",
|
|
4394
|
+
"protocolInfo",
|
|
4395
|
+
"macAddress",
|
|
4396
|
+
"oneTimePassword",
|
|
4397
|
+
"loginRemark",
|
|
4398
|
+
"clientIpPort",
|
|
4399
|
+
"clientIpAddress",
|
|
4400
|
+
"smsCode"
|
|
4401
|
+
]);
|
|
4402
|
+
var LOGOUT_KEYS = /* @__PURE__ */ new Set(["brokerId", "userId"]);
|
|
4403
|
+
var MULTICAST_QUERY_KEYS = /* @__PURE__ */ new Set(["topicId", "instrumentId"]);
|
|
4404
|
+
var MarketData = class extends CtpClient {
|
|
4405
|
+
sessionTransition;
|
|
4406
|
+
constructor(flowPath, fronts) {
|
|
4407
|
+
super(new native.MarketData(flowPath, copyOwnFronts(fronts, "MarketData fronts")), native.__layoutData(), MD_EVENTS);
|
|
4408
|
+
this.start();
|
|
4409
|
+
}
|
|
4410
|
+
get apiVersion() {
|
|
4411
|
+
return this.native.apiVersion();
|
|
4412
|
+
}
|
|
4413
|
+
get tradingDay() {
|
|
4414
|
+
return this.native.tradingDay();
|
|
4415
|
+
}
|
|
4416
|
+
/** Subscribe to depth market data. Returns the CTP send code (0 = ok). */
|
|
4417
|
+
subscribe(instrumentIds) {
|
|
4418
|
+
const ids = snapshotInstrumentIds(instrumentIds);
|
|
4419
|
+
return this.native.subscribeMarketData(ids);
|
|
4420
|
+
}
|
|
4421
|
+
unsubscribe(instrumentIds) {
|
|
4422
|
+
const ids = snapshotInstrumentIds(instrumentIds);
|
|
4423
|
+
return this.native.unsubscribeMarketData(ids);
|
|
4424
|
+
}
|
|
4425
|
+
subscribeForQuote(instrumentIds) {
|
|
4426
|
+
const ids = snapshotInstrumentIds(instrumentIds);
|
|
4427
|
+
return this.native.subscribeForQuoteRsp(ids);
|
|
4428
|
+
}
|
|
4429
|
+
unsubscribeForQuote(instrumentIds) {
|
|
4430
|
+
const ids = snapshotInstrumentIds(instrumentIds);
|
|
4431
|
+
return this.native.unsubscribeForQuoteRsp(ids);
|
|
4432
|
+
}
|
|
4433
|
+
/** Latest cached depth tick for an instrument — the C++ last-value cache,
|
|
4434
|
+
* updated on every authenticated-session tick before it reaches JS. Returns
|
|
4435
|
+
* null before login, after disconnect/logout, if none has been seen, or if it
|
|
4436
|
+
* was unsubscribed. Synchronous: no waiting for an event. */
|
|
4437
|
+
snapshot(instrumentId) {
|
|
4438
|
+
const bytes = this.native.snapshot(instrumentId);
|
|
4439
|
+
return bytes ? this.decodeStruct(STRUCT_ID.DepthMarketData, bytes) : null;
|
|
4440
|
+
}
|
|
4441
|
+
/** Latest price for an instrument from the cache (0 if none seen). Synchronous. */
|
|
4442
|
+
last(instrumentId) {
|
|
4443
|
+
return this.native.last(instrumentId);
|
|
4444
|
+
}
|
|
4445
|
+
/** @internal Hand the C++ snapshot cache to a Trader (Trader.trackMarketData),
|
|
4446
|
+
* so the Trader's deviation check reads live prices in C++ — no JS round-trip. */
|
|
4447
|
+
_snapshotExternal() {
|
|
4448
|
+
return this.native._snapshotExternal();
|
|
4449
|
+
}
|
|
4450
|
+
/** Log in; resolves with the login response (or rejects on CTP error). */
|
|
4451
|
+
login(req = {}) {
|
|
4452
|
+
const shapeError = requestShapeError(req, LOGIN_KEYS, "login request");
|
|
4453
|
+
if (shapeError)
|
|
4454
|
+
return Promise.reject(shapeError);
|
|
4455
|
+
const clean = copyOwnRecord(req, "login request");
|
|
4456
|
+
let encoded;
|
|
4457
|
+
try {
|
|
4458
|
+
encoded = this.encode(STRUCT_ID.ReqUserLogin, clean);
|
|
4459
|
+
} catch (error) {
|
|
4460
|
+
return Promise.reject(error);
|
|
4461
|
+
}
|
|
4462
|
+
return this.runSessionTransition(() => {
|
|
4463
|
+
this.beginRequestContextTransition("market-data login started");
|
|
4464
|
+
return this.request((id) => this.native.reqUserLogin(encoded, id), true, MD_BASE + 4, true);
|
|
4465
|
+
});
|
|
4466
|
+
}
|
|
4467
|
+
logout(req = {}) {
|
|
4468
|
+
const shapeError = requestShapeError(req, LOGOUT_KEYS, "logout request");
|
|
4469
|
+
if (shapeError)
|
|
4470
|
+
return Promise.reject(shapeError);
|
|
4471
|
+
const clean = copyOwnRecord(req, "logout request");
|
|
4472
|
+
let encoded;
|
|
4473
|
+
try {
|
|
4474
|
+
encoded = this.encode(STRUCT_ID.UserLogout, clean);
|
|
4475
|
+
} catch (error) {
|
|
4476
|
+
return Promise.reject(error);
|
|
4477
|
+
}
|
|
4478
|
+
return this.runSessionTransition(() => {
|
|
4479
|
+
this.beginRequestContextTransition("market-data logout started");
|
|
4480
|
+
return this.request((id) => this.native.reqUserLogout(encoded, id), true, MD_BASE + 5, true);
|
|
4481
|
+
});
|
|
4482
|
+
}
|
|
4483
|
+
shouldTimeoutRequest(requestId, sessionTransition) {
|
|
4484
|
+
if (!sessionTransition)
|
|
4485
|
+
return true;
|
|
4486
|
+
return this.native._timeoutSessionTransition(requestId);
|
|
4487
|
+
}
|
|
4488
|
+
// MarketData confirms a successful login natively: OnRspUserLogin activates the
|
|
4489
|
+
// snapshot cache on the MD channel, which legitimately carries no
|
|
4490
|
+
// FrontID/SessionID (those are the trade front's order-routing identity). There
|
|
4491
|
+
// is deliberately no onRequestResolved override here — the base no-op is
|
|
4492
|
+
// correct, and a successful MD login must never be rejected for lacking a trade
|
|
4493
|
+
// session id.
|
|
4494
|
+
/** SimNow may return requestId=0 for MD login/logout. Never overlap these
|
|
4495
|
+
* transitions: otherwise a late id-0 login response cannot be attributed to
|
|
4496
|
+
* one epoch. If a request times out while native still considers it pending,
|
|
4497
|
+
* native stays fail-closed until the next front transition. */
|
|
4498
|
+
runSessionTransition(start) {
|
|
4499
|
+
if (this.sessionTransition) {
|
|
4500
|
+
return Promise.reject(new Error("market-data login/logout transition already in flight; await it first"));
|
|
4501
|
+
}
|
|
4502
|
+
const promise = start();
|
|
4503
|
+
this.sessionTransition = promise;
|
|
4504
|
+
const finish = () => {
|
|
4505
|
+
if (this.sessionTransition !== promise)
|
|
4506
|
+
return;
|
|
4507
|
+
try {
|
|
4508
|
+
this.native._abandonSessionTransition();
|
|
4509
|
+
} catch {
|
|
4510
|
+
} finally {
|
|
4511
|
+
this.sessionTransition = void 0;
|
|
4512
|
+
}
|
|
4513
|
+
};
|
|
4514
|
+
void promise.then(finish, finish);
|
|
4515
|
+
return promise;
|
|
4516
|
+
}
|
|
4517
|
+
/** Query multicast instruments. Multi-row response, serialized through this
|
|
4518
|
+
* client's conservative query scheduler. */
|
|
4519
|
+
reqQryMulticastInstrument(req = {}) {
|
|
4520
|
+
const shapeError = requestShapeError(req, MULTICAST_QUERY_KEYS, "multicast query");
|
|
4521
|
+
if (shapeError)
|
|
4522
|
+
return Promise.reject(shapeError);
|
|
4523
|
+
const clean = copyOwnRecord(req, "multicast query");
|
|
4524
|
+
return this.queryRequest((id) => this.native.reqQryMulticastInstrument(clean, id));
|
|
4525
|
+
}
|
|
4526
|
+
/** Route this market data's ticks to a Trader's armed triggers (see Trader.arm).
|
|
4527
|
+
* A MarketData feeds exactly one live Trader's registry. Native ownership
|
|
4528
|
+
* rejects replacement while that Trader is live, but permits replacing a
|
|
4529
|
+
* registry whose Trader has already closed. */
|
|
4530
|
+
attachArm(trader) {
|
|
4531
|
+
if (!(trader instanceof Trader))
|
|
4532
|
+
throw new TypeError("attachArm requires a Trader from this package instance");
|
|
4533
|
+
const registry = trader._armRegistry();
|
|
4534
|
+
this.native._attachArm(registry);
|
|
4535
|
+
}
|
|
4536
|
+
/** @internal test-only: inject a synthetic depth tick into the ring. Optional
|
|
4537
|
+
* bid/ask override the defaults (3499/3501) so tests can drive edge prices
|
|
4538
|
+
* (e.g. a DBL_MAX no-bid sentinel) through the real arm/onTick path. */
|
|
4539
|
+
_injectTestTick(bid, ask) {
|
|
4540
|
+
this.native._injectTestTick(bid, ask);
|
|
4541
|
+
}
|
|
4542
|
+
/** @internal test-only: inject one RFQ business notification through MdSpi. */
|
|
4543
|
+
_injectTestForQuote() {
|
|
4544
|
+
this.native._injectTestForQuote();
|
|
4545
|
+
}
|
|
4546
|
+
/** @internal test-only: drive a real native MD lifecycle callback. */
|
|
4547
|
+
_injectTestLifecycle(state) {
|
|
4548
|
+
this.native._injectTestLifecycle(state);
|
|
4549
|
+
}
|
|
4550
|
+
/** @internal test-only: spawn a background producer thread that pushes `n`
|
|
4551
|
+
* synthetic ticks into the ring (cross-thread doorbell stress). Each tick's
|
|
4552
|
+
* requestId carries its sequence number. */
|
|
4553
|
+
_burstTicks(n, jitterUs = 0, injectControl = false) {
|
|
4554
|
+
this.native._burstTicks(n, jitterUs, injectControl);
|
|
4555
|
+
}
|
|
4556
|
+
/** @internal test-only: produce ticks on a native background thread through
|
|
4557
|
+
* the real MD SPI. `ratePerSecond=0` is an instantaneous burst; otherwise
|
|
4558
|
+
* ticks arrive as paced `burstSize` batches. Instrument IDs rotate across
|
|
4559
|
+
* SIM00000000.. and `volume` is the zero-based global sequence. */
|
|
4560
|
+
_produceTestTicks(count, instrumentCount, ratePerSecond = 0, burstSize = 512) {
|
|
4561
|
+
this.native._produceTestTicks(count, instrumentCount, ratePerSecond, burstSize);
|
|
4562
|
+
}
|
|
4563
|
+
on(event, cb) {
|
|
4564
|
+
return super.on(event, cb);
|
|
4565
|
+
}
|
|
4566
|
+
};
|
|
4567
|
+
|
|
3092
4568
|
// dist/generated/enums.gen.js
|
|
3093
4569
|
var ExchangeProperty;
|
|
3094
4570
|
(function(ExchangeProperty2) {
|