@hitrading/ctp-node 2.0.0 → 4.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +82 -0
- package/README.md +54 -32
- package/README.zh-CN.md +44 -27
- package/RELEASING.md +78 -0
- package/dist/client.d.ts +36 -15
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +234 -62
- package/dist/client.js.map +1 -1
- package/dist/codec.d.ts.map +1 -1
- package/dist/codec.js +84 -19
- package/dist/codec.js.map +1 -1
- package/dist/generated/structs.gen.d.ts +5461 -5461
- package/dist/generated/structs.gen.d.ts.map +1 -1
- package/dist/generated/trader.gen.d.ts.map +1 -1
- package/dist/generated/trader.gen.js +788 -94
- package/dist/generated/trader.gen.js.map +1 -1
- package/dist/index.cjs +1909 -417
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/market-data.d.ts +41 -24
- package/dist/market-data.d.ts.map +1 -1
- package/dist/market-data.js +148 -29
- package/dist/market-data.js.map +1 -1
- package/dist/native-binding.d.ts.map +1 -1
- package/dist/native-binding.js +4 -0
- package/dist/native-binding.js.map +1 -1
- package/dist/trader.d.ts +136 -79
- package/dist/trader.d.ts.map +1 -1
- package/dist/trader.js +807 -182
- package/dist/trader.js.map +1 -1
- package/dist/validation.d.ts +27 -0
- package/dist/validation.d.ts.map +1 -0
- package/dist/validation.js +85 -0
- package/dist/validation.js.map +1 -0
- package/docs/API.md +1445 -0
- package/docs/API.zh-CN.md +1285 -0
- package/docs/MIGRATION.md +54 -0
- package/docs/assets/validation.svg +27 -0
- package/docs/integration.md +60 -0
- package/docs/native-hooks.md +281 -0
- package/docs/native-hooks.zh-CN.md +205 -0
- package/docs/troubleshooting.md +257 -0
- package/docs/troubleshooting.zh-CN.md +220 -0
- package/package.json +12 -4
- package/prebuilds/linux-x64/@hitrading+ctp-node.node +0 -0
- package/prebuilds/win32-x64/@hitrading+ctp-node.node +0 -0
- package/scripts/bench-decode.mjs +37 -0
- package/scripts/bench-fullmarket-offline.mjs +207 -0
- package/scripts/stress-fullmarket.mjs +255 -0
- package/src/addon.cc +2 -2
- package/src/client.ts +255 -65
- package/src/codec.ts +86 -19
- package/src/generated/structs.gen.ts +5461 -5461
- package/src/generated/trader.gen.ts +309 -94
- package/src/generated/traderreq.gen.cc +194 -18
- package/src/generated/traderreq.gen.h +4 -0
- package/src/generated/traderspi.gen.cc +129 -15
- package/src/generated/traderspi.gen.h +4 -2
- package/src/index.ts +11 -1
- package/src/market-data.ts +199 -46
- package/src/native/arm.cc +114 -30
- package/src/native/arm.h +16 -4
- package/src/native/channel.cc +209 -81
- package/src/native/channel.h +65 -24
- package/src/native/ctp_field.h +23 -0
- package/src/native/mdapi.cc +582 -69
- package/src/native/mdspi.cc +219 -16
- package/src/native/mdspi.h +59 -10
- package/src/native/order_capability.h +78 -0
- package/src/native/risk.cc +2030 -213
- package/src/native/risk.h +431 -78
- package/src/native/shared_handle.h +37 -0
- package/src/native/snapshot.h +75 -16
- package/src/native/traderapi.cc +769 -124
- package/src/native-binding.ts +4 -0
- package/src/trader.ts +1038 -207
- package/src/validation.ts +96 -0
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
// Reproducible offline full-market capacity probe for the ordinary hot path:
|
|
2
|
+
// native background producer -> real MdSpi callback -> 18,111-key SnapshotCache
|
|
3
|
+
// -> keep-newest EventChannel -> generated 46-field JS decoder -> EventEmitter
|
|
4
|
+
// -> a string-keyed 20-tick rolling strategy state for the tick's real
|
|
5
|
+
// InstrumentID. No CTP credentials or network are required.
|
|
6
|
+
//
|
|
7
|
+
// Defaults run three sustained loads plus one simultaneous all-contract burst:
|
|
8
|
+
// CTP_BENCH_SCENARIOS=50000:5000,500000:30000,1000000:3000
|
|
9
|
+
// CTP_BENCH_INSTRUMENTS=18111
|
|
10
|
+
// CTP_BENCH_WINDOW=20
|
|
11
|
+
// CTP_BENCH_NATIVE_BURST=512
|
|
12
|
+
// CTP_BENCH_INSTANT=18111
|
|
13
|
+
import { mkdirSync } from "node:fs";
|
|
14
|
+
import { availableParallelism, cpus, totalmem } from "node:os";
|
|
15
|
+
import { monitorEventLoopDelay, performance } from "node:perf_hooks";
|
|
16
|
+
|
|
17
|
+
process.env.CTP_NODE_TEST_HOOKS = "1";
|
|
18
|
+
const { MarketData } = await import("../dist/index.js");
|
|
19
|
+
|
|
20
|
+
const integerEnv = (name, fallback, minimum, maximum = Number.MAX_SAFE_INTEGER) => {
|
|
21
|
+
const value = Number(process.env[name] ?? fallback);
|
|
22
|
+
if (!Number.isSafeInteger(value) || value < minimum || value > maximum)
|
|
23
|
+
throw new Error(`${name} must be an integer in ${minimum}..${maximum}`);
|
|
24
|
+
return value;
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
const parseScenarios = (raw) => raw.split(",").map((part) => {
|
|
28
|
+
const match = /^(\d+):(\d+)$/.exec(part.trim());
|
|
29
|
+
if (!match) throw new Error("CTP_BENCH_SCENARIOS must contain rate:milliseconds pairs");
|
|
30
|
+
const rate = Number(match[1]);
|
|
31
|
+
const durationMs = Number(match[2]);
|
|
32
|
+
if (!Number.isSafeInteger(rate) || rate < 1 || rate > 100_000_000 ||
|
|
33
|
+
!Number.isSafeInteger(durationMs) || durationMs < 100 || durationMs > 600_000)
|
|
34
|
+
throw new Error("benchmark scenario rate/duration is out of range");
|
|
35
|
+
const count = Math.round(rate * durationMs / 1000);
|
|
36
|
+
if (count > 100_000_000)
|
|
37
|
+
throw new Error("a benchmark scenario may produce at most 100,000,000 ticks");
|
|
38
|
+
return { rate, durationMs, count };
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
const scenarios = parseScenarios(
|
|
42
|
+
process.env.CTP_BENCH_SCENARIOS ?? "50000:5000,500000:30000,1000000:3000"
|
|
43
|
+
);
|
|
44
|
+
const instrumentCount = integerEnv("CTP_BENCH_INSTRUMENTS", 18_111, 1, 1_000_000);
|
|
45
|
+
const windowSize = integerEnv("CTP_BENCH_WINDOW", 20, 1, 100_000);
|
|
46
|
+
const nativeBurstSize = integerEnv("CTP_BENCH_NATIVE_BURST", 512, 1, 1_000_000);
|
|
47
|
+
const instantCount = integerEnv("CTP_BENCH_INSTANT", instrumentCount, 1, 100_000_000);
|
|
48
|
+
const logicalCpus = availableParallelism();
|
|
49
|
+
const mib = (bytes) => bytes / 1024 / 1024;
|
|
50
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
51
|
+
|
|
52
|
+
mkdirSync("flow-bench-fullmarket", { recursive: true });
|
|
53
|
+
const md = new MarketData("./flow-bench-fullmarket/", "tcp://127.0.0.1:1");
|
|
54
|
+
md._injectTestLifecycle("login");
|
|
55
|
+
|
|
56
|
+
// Pre-create the exact application-side cardinality so allocation churn is not
|
|
57
|
+
// mistaken for steady-state throughput. The handler still looks each state up
|
|
58
|
+
// by tick.instrumentId, including string decode/hash on every tick.
|
|
59
|
+
const states = new Map();
|
|
60
|
+
for (let i = 0; i < instrumentCount; i++) {
|
|
61
|
+
states.set(`SIM${String(i).padStart(8, "0")}`, {
|
|
62
|
+
values: new Float64Array(windowSize), cursor: 0, count: 0, sum: 0, last: 0,
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
let activeRun;
|
|
67
|
+
let checksum = 0;
|
|
68
|
+
md.on("rtn-depth-market-data", (tick) => {
|
|
69
|
+
if (!tick.instrumentId?.startsWith("SIM")) return;
|
|
70
|
+
const run = activeRun;
|
|
71
|
+
if (run) {
|
|
72
|
+
run.received++;
|
|
73
|
+
run.minSequence = Math.min(run.minSequence, tick.volume);
|
|
74
|
+
run.maxSequence = Math.max(run.maxSequence, tick.volume);
|
|
75
|
+
}
|
|
76
|
+
const state = states.get(tick.instrumentId);
|
|
77
|
+
if (!state) throw new Error(`unexpected InstrumentID ${tick.instrumentId}`);
|
|
78
|
+
const previous = state.values[state.cursor];
|
|
79
|
+
state.sum += tick.lastPrice - previous;
|
|
80
|
+
state.values[state.cursor] = tick.lastPrice;
|
|
81
|
+
state.cursor = (state.cursor + 1) % windowSize;
|
|
82
|
+
if (state.count < windowSize) state.count++;
|
|
83
|
+
state.last = tick.lastPrice;
|
|
84
|
+
checksum += state.sum / state.count;
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
const runLoad = async ({ label, count, rate, durationMs, burstSize }) => {
|
|
88
|
+
// Starting another producer joins the previous completed native thread. The
|
|
89
|
+
// counter baseline is therefore exact and cannot include an earlier run.
|
|
90
|
+
const dropStart = md.droppedRecords;
|
|
91
|
+
const run = { received: 0, minSequence: Number.POSITIVE_INFINITY, maxSequence: -1 };
|
|
92
|
+
activeRun = run;
|
|
93
|
+
let peakRss = process.memoryUsage().rss;
|
|
94
|
+
let peakHeap = process.memoryUsage().heapUsed;
|
|
95
|
+
const startRss = peakRss;
|
|
96
|
+
const startHeap = peakHeap;
|
|
97
|
+
const sampler = setInterval(() => {
|
|
98
|
+
const memory = process.memoryUsage();
|
|
99
|
+
peakRss = Math.max(peakRss, memory.rss);
|
|
100
|
+
peakHeap = Math.max(peakHeap, memory.heapUsed);
|
|
101
|
+
}, 10);
|
|
102
|
+
sampler.unref?.();
|
|
103
|
+
const delay = monitorEventLoopDelay({ resolution: 10 });
|
|
104
|
+
delay.enable();
|
|
105
|
+
const cpuStart = process.cpuUsage();
|
|
106
|
+
const eluStart = performance.eventLoopUtilization();
|
|
107
|
+
const started = performance.now();
|
|
108
|
+
|
|
109
|
+
md._produceTestTicks(count, instrumentCount, rate, burstSize);
|
|
110
|
+
const expectedMs = rate > 0 ? count / rate * 1000 : 0;
|
|
111
|
+
const deadline = performance.now() + Math.max(15_000, expectedMs * 4 + 5_000);
|
|
112
|
+
while (run.received + (md.droppedRecords - dropStart) < count &&
|
|
113
|
+
performance.now() < deadline)
|
|
114
|
+
await sleep(2);
|
|
115
|
+
// Let the final coalesced doorbell and memory sample settle.
|
|
116
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
117
|
+
|
|
118
|
+
const elapsedMs = performance.now() - started;
|
|
119
|
+
const cpu = process.cpuUsage(cpuStart);
|
|
120
|
+
const cpuMs = (cpu.user + cpu.system) / 1000;
|
|
121
|
+
const elu = performance.eventLoopUtilization(eluStart);
|
|
122
|
+
clearInterval(sampler);
|
|
123
|
+
delay.disable();
|
|
124
|
+
activeRun = undefined;
|
|
125
|
+
const memory = process.memoryUsage();
|
|
126
|
+
peakRss = Math.max(peakRss, memory.rss);
|
|
127
|
+
peakHeap = Math.max(peakHeap, memory.heapUsed);
|
|
128
|
+
const dropped = md.droppedRecords - dropStart;
|
|
129
|
+
// Windows process CPU counters are quantized at roughly one scheduler tick;
|
|
130
|
+
// a ~10 ms instantaneous burst can legitimately read as zero. Do not print a
|
|
131
|
+
// bogus percentage for sub-100 ms runs.
|
|
132
|
+
const cpuMeasurementReliable = elapsedMs >= 100;
|
|
133
|
+
const singleCoreCpuPct = cpuMeasurementReliable ? cpuMs / elapsedMs * 100 : null;
|
|
134
|
+
return {
|
|
135
|
+
label,
|
|
136
|
+
requestedRatePerSecond: rate || "instantaneous",
|
|
137
|
+
requestedDurationMs: durationMs,
|
|
138
|
+
nativeBurstSize: burstSize,
|
|
139
|
+
produced: count,
|
|
140
|
+
received: run.received,
|
|
141
|
+
dropped,
|
|
142
|
+
conservation: run.received + dropped === count,
|
|
143
|
+
elapsedMs,
|
|
144
|
+
producedPerSecond: count / (elapsedMs / 1000),
|
|
145
|
+
deliveredPerSecond: run.received / (elapsedMs / 1000),
|
|
146
|
+
minDeliveredSequence: Number.isFinite(run.minSequence) ? run.minSequence : null,
|
|
147
|
+
maxDeliveredSequence: run.maxSequence >= 0 ? run.maxSequence : null,
|
|
148
|
+
singleCoreCpuPct,
|
|
149
|
+
wholeMachineCpuPct: singleCoreCpuPct === null ? null : singleCoreCpuPct / logicalCpus,
|
|
150
|
+
eventLoopUtilizationPct: elu.utilization * 100,
|
|
151
|
+
eventLoopP99Ms: delay.percentile(99) / 1e6,
|
|
152
|
+
startRssMiB: mib(startRss),
|
|
153
|
+
startHeapMiB: mib(startHeap),
|
|
154
|
+
peakRssMiB: mib(peakRss),
|
|
155
|
+
peakHeapMiB: mib(peakHeap),
|
|
156
|
+
};
|
|
157
|
+
};
|
|
158
|
+
|
|
159
|
+
// Warm JIT/decoders and populate all native SnapshotCache keys before measuring.
|
|
160
|
+
const warmupCount = Math.max(instrumentCount, 100_000);
|
|
161
|
+
const warmup = await runLoad({
|
|
162
|
+
label: "warmup", count: warmupCount, rate: 250_000,
|
|
163
|
+
durationMs: warmupCount / 250, burstSize: nativeBurstSize,
|
|
164
|
+
});
|
|
165
|
+
if (!warmup.conservation) throw new Error("warmup failed channel conservation");
|
|
166
|
+
|
|
167
|
+
const sustained = [];
|
|
168
|
+
for (const scenario of scenarios) {
|
|
169
|
+
const result = await runLoad({
|
|
170
|
+
label: `sustained-${scenario.rate}`,
|
|
171
|
+
...scenario,
|
|
172
|
+
burstSize: nativeBurstSize,
|
|
173
|
+
});
|
|
174
|
+
sustained.push(result);
|
|
175
|
+
if (!result.conservation)
|
|
176
|
+
throw new Error(`${result.label} failed channel conservation`);
|
|
177
|
+
}
|
|
178
|
+
const instantaneous = await runLoad({
|
|
179
|
+
label: `instant-${instantCount}`,
|
|
180
|
+
count: instantCount,
|
|
181
|
+
rate: 0,
|
|
182
|
+
durationMs: null,
|
|
183
|
+
// One native callback storm; SPI and JS still run concurrently on their real
|
|
184
|
+
// separate threads. This directly tests one tick for every subscribed symbol.
|
|
185
|
+
burstSize: instantCount,
|
|
186
|
+
});
|
|
187
|
+
if (!instantaneous.conservation)
|
|
188
|
+
throw new Error("instantaneous burst failed channel conservation");
|
|
189
|
+
|
|
190
|
+
const result = {
|
|
191
|
+
node: process.version,
|
|
192
|
+
platform: `${process.platform}-${process.arch}`,
|
|
193
|
+
cpuModel: cpus()[0]?.model ?? "unknown",
|
|
194
|
+
logicalCpus,
|
|
195
|
+
totalMemoryGiB: totalmem() / 1024 / 1024 / 1024,
|
|
196
|
+
instruments: instrumentCount,
|
|
197
|
+
rollingWindow: windowSize,
|
|
198
|
+
nativeSnapshotKeysModeled: instrumentCount,
|
|
199
|
+
sustained,
|
|
200
|
+
instantaneous,
|
|
201
|
+
checksum,
|
|
202
|
+
};
|
|
203
|
+
console.log(JSON.stringify(result, null, 2));
|
|
204
|
+
|
|
205
|
+
md.close();
|
|
206
|
+
if ([...sustained, instantaneous].some((row) => !row.conservation))
|
|
207
|
+
process.exitCode = 1;
|
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
// Full-market stress test (LIVE SimNow, trading hours).
|
|
2
|
+
//
|
|
3
|
+
// Goal: subscribe to EVERY instrument in the market, run a per-instrument
|
|
4
|
+
// indicator (SMA + cross signal) on every tick, and place/cancel real orders on
|
|
5
|
+
// the most-active future under that load — while measuring whether any of it
|
|
6
|
+
// blows up memory, pins the CPU, or makes the market-data feed back up
|
|
7
|
+
// (droppedRecords > 0 = the JS loop fell behind = "行情挤压").
|
|
8
|
+
//
|
|
9
|
+
// Credentials come from env (nothing secret is written to the file). Run, e.g.:
|
|
10
|
+
// CTP_USER=xxxx CTP_PASS=yyyy node scripts/stress-fullmarket.mjs
|
|
11
|
+
// Env (all optional except USER/PASS):
|
|
12
|
+
// CTP_BROKER CTP_USER CTP_PASS CTP_APPID CTP_AUTHCODE CTP_MD_FRONT CTP_TD_FRONT
|
|
13
|
+
// CTP_RUN_MS (default 90000) CTP_MA (SMA period, default 20)
|
|
14
|
+
// CTP_TRADE (1=place/cancel test orders, default 1) CTP_ORDER_SYMBOL (auto if unset)
|
|
15
|
+
import { MarketData, Trader } from "../dist/index.js";
|
|
16
|
+
import { mkdirSync } from "node:fs";
|
|
17
|
+
import { monitorEventLoopDelay } from "node:perf_hooks";
|
|
18
|
+
import process from "node:process";
|
|
19
|
+
|
|
20
|
+
const env = process.env;
|
|
21
|
+
const cfg = {
|
|
22
|
+
brokerId: env.CTP_BROKER ?? "9999",
|
|
23
|
+
userId: env.CTP_USER ?? "",
|
|
24
|
+
password: env.CTP_PASS ?? "",
|
|
25
|
+
appId: env.CTP_APPID ?? "simnow_client_test",
|
|
26
|
+
authCode: env.CTP_AUTHCODE ?? "0000000000000000",
|
|
27
|
+
// SimNow fronts rotate; override via env. These are the 上期技术-电信二 site.
|
|
28
|
+
mdFront: env.CTP_MD_FRONT ?? "tcp://182.254.243.31:30012",
|
|
29
|
+
tdFront: env.CTP_TD_FRONT ?? "tcp://182.254.243.31:30002",
|
|
30
|
+
runMs: Number(env.CTP_RUN_MS ?? 90000),
|
|
31
|
+
maPeriod: Number(env.CTP_MA ?? 20),
|
|
32
|
+
trade: (env.CTP_TRADE ?? "1") === "1",
|
|
33
|
+
orderSymbol: env.CTP_ORDER_SYMBOL ?? "",
|
|
34
|
+
};
|
|
35
|
+
if (!cfg.userId || !cfg.password) {
|
|
36
|
+
console.error("Set CTP_USER and CTP_PASS (SimNow account).");
|
|
37
|
+
process.exit(2);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const t0 = Date.now();
|
|
41
|
+
const ts = () => new Date().toISOString().slice(11, 23);
|
|
42
|
+
const log = (...a) => console.log(ts(), ...a);
|
|
43
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
44
|
+
process.on("uncaughtException", (e) => log("!!! UNCAUGHT", e?.stack || e));
|
|
45
|
+
process.on("unhandledRejection", (e) => log("!!! UNHANDLED", e?.message || e));
|
|
46
|
+
|
|
47
|
+
mkdirSync("flow-md", { recursive: true });
|
|
48
|
+
mkdirSync("flow-td", { recursive: true });
|
|
49
|
+
|
|
50
|
+
// ---- event-loop lag monitor (the truest "are we keeping up?" metric) ----
|
|
51
|
+
const eld = monitorEventLoopDelay({ resolution: 10 });
|
|
52
|
+
eld.enable();
|
|
53
|
+
|
|
54
|
+
// ---- per-instrument strategy state (SMA over the last N lastPrices) ----
|
|
55
|
+
/** @type {Map<string, {buf:number[], i:number, sum:number, n:number, last:number, vol:number}>} */
|
|
56
|
+
const state = new Map();
|
|
57
|
+
let totalTicks = 0;
|
|
58
|
+
let signalCount = 0;
|
|
59
|
+
let strategyNanos = 0n;
|
|
60
|
+
let dropBaseline = 0;
|
|
61
|
+
|
|
62
|
+
function onTickStrategy(t) {
|
|
63
|
+
const id = t.instrumentId;
|
|
64
|
+
const px = t.lastPrice;
|
|
65
|
+
// CTP sends DBL_MAX for an untraded price; skip those.
|
|
66
|
+
if (!(px > 0) || px >= 1e300) return;
|
|
67
|
+
let s = state.get(id);
|
|
68
|
+
if (!s) { s = { buf: new Array(cfg.maPeriod).fill(0), i: 0, sum: 0, n: 0, last: 0, vol: 0 }; state.set(id, s); }
|
|
69
|
+
// rolling SMA
|
|
70
|
+
const old = s.buf[s.i];
|
|
71
|
+
s.sum += px - old;
|
|
72
|
+
s.buf[s.i] = px;
|
|
73
|
+
s.i = (s.i + 1) % cfg.maPeriod;
|
|
74
|
+
if (s.n < cfg.maPeriod) s.n++;
|
|
75
|
+
s.vol = t.volume;
|
|
76
|
+
if (s.n >= cfg.maPeriod) {
|
|
77
|
+
const ma = s.sum / s.n;
|
|
78
|
+
// simple cross signal: did price cross the MA since the last tick?
|
|
79
|
+
const wasAbove = s.last >= ma;
|
|
80
|
+
const isAbove = px >= ma;
|
|
81
|
+
if (s.last > 0 && wasAbove !== isAbove) signalCount++; // a decision point
|
|
82
|
+
s.last = px;
|
|
83
|
+
return isAbove ? 1 : -1;
|
|
84
|
+
}
|
|
85
|
+
s.last = px;
|
|
86
|
+
return 0;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// ================= Market data =================
|
|
90
|
+
const md = new MarketData("./flow-md/", cfg.mdFront);
|
|
91
|
+
md.on("error", (e) => log("[md handler error]", e?.message || e));
|
|
92
|
+
md.on("front-disconnected", (r) => log("MD front-disconnected", r));
|
|
93
|
+
let orderSymLastTick = null;
|
|
94
|
+
md.on("rtn-depth-market-data", (t) => {
|
|
95
|
+
totalTicks++;
|
|
96
|
+
const a = process.hrtime.bigint();
|
|
97
|
+
onTickStrategy(t); // run the per-tick indicator on EVERY instrument (the load)
|
|
98
|
+
strategyNanos += process.hrtime.bigint() - a;
|
|
99
|
+
if (cfg.trade && t.instrumentId === orderSym) orderSymLastTick = t;
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
let allInstruments = [];
|
|
103
|
+
md.on("front-connected", async () => {
|
|
104
|
+
log("MD connected; logging in...");
|
|
105
|
+
try {
|
|
106
|
+
await md.login({ brokerId: cfg.brokerId, userId: cfg.userId, password: cfg.password });
|
|
107
|
+
log("MD login ok. waiting for the instrument list from the trader...");
|
|
108
|
+
await instrumentsReady;
|
|
109
|
+
dropBaseline = md.droppedRecords;
|
|
110
|
+
// subscribe EVERYTHING, in chunks (the end state — all subscribed — is the stress)
|
|
111
|
+
const CHUNK = 1000;
|
|
112
|
+
for (let i = 0; i < allInstruments.length; i += CHUNK) {
|
|
113
|
+
const rc = md.subscribe(allInstruments.slice(i, i + CHUNK));
|
|
114
|
+
if (rc !== 0) log(" subscribe chunk rc", rc, "at", i);
|
|
115
|
+
await sleep(50);
|
|
116
|
+
}
|
|
117
|
+
log(`MD subscribed ALL ${allInstruments.length} instruments.`);
|
|
118
|
+
} catch (e) { log("MD flow FAILED:", e.message); }
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
// ================= Trader =================
|
|
122
|
+
const td = new Trader("./flow-td/", cfg.tdFront);
|
|
123
|
+
td.setRiskLimits({ maxOrderVolume: 2, maxOrdersPerSec: 5, maxPriceDeviation: 0.5 });
|
|
124
|
+
let orderSym = cfg.orderSymbol;
|
|
125
|
+
let orderTick = 0; // price tick of the order symbol
|
|
126
|
+
let placed = 0, accepted = 0, cancelled = 0, rejected = 0;
|
|
127
|
+
let lastOrderAt = 0;
|
|
128
|
+
const working = new Map(); // orderRef -> {frontId, sessionId, instrumentId}
|
|
129
|
+
|
|
130
|
+
let resolveInstruments;
|
|
131
|
+
const instrumentsReady = new Promise((r) => { resolveInstruments = r; });
|
|
132
|
+
|
|
133
|
+
td.on("error", (e) => log("[td handler error]", e?.message || e));
|
|
134
|
+
td.on("front-disconnected", (r) => log("TD front-disconnected", r));
|
|
135
|
+
td.on("rtn-order", (o) => {
|
|
136
|
+
if (o.instrumentId !== orderSym) return;
|
|
137
|
+
if ((o.orderStatus === "3" || o.orderStatus === "1") && !working.has(o.orderRef)) {
|
|
138
|
+
accepted++; // our resting order — cancel it ~1s later
|
|
139
|
+
working.set(o.orderRef, { frontId: o.frontId, sessionId: o.sessionId, instrumentId: o.instrumentId });
|
|
140
|
+
setTimeout(() => {
|
|
141
|
+
const w = working.get(o.orderRef);
|
|
142
|
+
if (w) td.reqOrderAction({ brokerId: cfg.brokerId, investorId: cfg.userId, instrumentId: w.instrumentId, orderRef: o.orderRef, frontId: w.frontId, sessionId: w.sessionId, actionFlag: "0" }).catch(() => {});
|
|
143
|
+
}, 1000);
|
|
144
|
+
} else if (o.orderStatus === "5") {
|
|
145
|
+
if (working.delete(o.orderRef)) cancelled++;
|
|
146
|
+
} else if (o.orderStatus === "0" || o.orderStatus === "2") {
|
|
147
|
+
working.delete(o.orderRef);
|
|
148
|
+
}
|
|
149
|
+
});
|
|
150
|
+
td.on("err-rtn-order-insert", (_d, o) => { rejected++; if (rejected <= 4) log(" order REJECTED(exch):", o.rspInfo?.errorMsg); });
|
|
151
|
+
|
|
152
|
+
td.on("front-connected", async () => {
|
|
153
|
+
log("TD connected; authenticating...");
|
|
154
|
+
try {
|
|
155
|
+
await td.reqAuthenticate({ brokerId: cfg.brokerId, userId: cfg.userId, appId: cfg.appId, authCode: cfg.authCode }).catch((e) => log("auth:", e.message));
|
|
156
|
+
const li = await td.reqUserLogin({ brokerId: cfg.brokerId, userId: cfg.userId, password: cfg.password });
|
|
157
|
+
log("TD login ok, frontId", li.frontId, "sessionId", li.sessionId);
|
|
158
|
+
await td.reqSettlementInfoConfirm({ brokerId: cfg.brokerId, investorId: cfg.userId }).catch(() => {});
|
|
159
|
+
await sleep(1200);
|
|
160
|
+
log("querying ALL instruments (one big multi-row response)...");
|
|
161
|
+
const rows = await td.reqQryInstrument({}); // no filter -> every instrument
|
|
162
|
+
// futures-like ids for subscribing + for picking an order symbol; subscribe ALL though
|
|
163
|
+
allInstruments = rows.map((r) => r.instrumentId).filter(Boolean);
|
|
164
|
+
log(`got ${allInstruments.length} instruments from the exchange.`);
|
|
165
|
+
// auto-pick an order symbol: highest priceTick-having future (short id, no option markers)
|
|
166
|
+
if (!orderSym) {
|
|
167
|
+
const fut = rows.filter((r) => /^[a-zA-Z]{1,2}\d{3,4}$/.test(r.instrumentId) && r.priceTick > 0);
|
|
168
|
+
// prefer a common liquid product family if present
|
|
169
|
+
const pick = fut.find((r) => /^(rb|ru|hc|fu|bu|m|y|p|a|c|i|j|jm|cu|al|zn|TA|MA|FG|SA)\d/i.test(r.instrumentId)) || fut[0];
|
|
170
|
+
if (pick) { orderSym = pick.instrumentId; orderTick = pick.priceTick; }
|
|
171
|
+
} else {
|
|
172
|
+
const r = rows.find((x) => x.instrumentId === orderSym);
|
|
173
|
+
orderTick = r?.priceTick || 1;
|
|
174
|
+
}
|
|
175
|
+
log("order symbol for the place/cancel stress:", orderSym || "(none — futures not found)", "tick", orderTick);
|
|
176
|
+
resolveInstruments();
|
|
177
|
+
} catch (e) { log("TD flow FAILED:", e.message, "errorId", e.errorId); resolveInstruments(); }
|
|
178
|
+
});
|
|
179
|
+
|
|
180
|
+
// place a far-below-market resting BUY, then cancel it shortly after — exercises
|
|
181
|
+
// the insert+cancel round trip under the full-market tick load, no fills.
|
|
182
|
+
function maybeTrade(t) {
|
|
183
|
+
if (!orderSym || !t) return;
|
|
184
|
+
const bid = t.bidPrice1;
|
|
185
|
+
if (!(bid > 0) || bid >= 1e300) return;
|
|
186
|
+
lastOrderAt = Date.now();
|
|
187
|
+
// a few ticks below the bid: rests behind the book (won't fill), well within
|
|
188
|
+
// daily limits, always cancellable. NO explicit orderRef -> the Trader
|
|
189
|
+
// auto-assigns a unique numeric ref (passing our own non-numeric/duplicate ref
|
|
190
|
+
// is what CTP rejects with "不允许重复报单"). The cancel is driven from rtn-order.
|
|
191
|
+
const px = Math.max(orderTick, bid - 3 * orderTick);
|
|
192
|
+
placed++;
|
|
193
|
+
td.reqOrderInsert({
|
|
194
|
+
brokerId: cfg.brokerId, investorId: cfg.userId, instrumentId: orderSym,
|
|
195
|
+
direction: "0", combOffsetFlag: "0", combHedgeFlag: "1",
|
|
196
|
+
orderPriceType: "2", limitPrice: px, volumeTotalOriginal: 1,
|
|
197
|
+
timeCondition: "3", volumeCondition: "1", contingentCondition: "1",
|
|
198
|
+
forceCloseReason: "0", isAutoSuspend: 0, userForceClose: 0,
|
|
199
|
+
}).catch((e) => { rejected++; if (rejected <= 4) log("order refused:", e.message); });
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
// ================= periodic stats =================
|
|
203
|
+
let lastCpu = process.cpuUsage();
|
|
204
|
+
let lastTicks = 0, lastT = Date.now();
|
|
205
|
+
let peakRss = 0;
|
|
206
|
+
const stat = setInterval(() => {
|
|
207
|
+
const mem = process.memoryUsage();
|
|
208
|
+
const rss = Math.round(mem.rss / 1048576);
|
|
209
|
+
const heap = Math.round(mem.heapUsed / 1048576);
|
|
210
|
+
peakRss = Math.max(peakRss, rss);
|
|
211
|
+
const now = Date.now();
|
|
212
|
+
const dt = (now - lastT) / 1000;
|
|
213
|
+
const tps = Math.round((totalTicks - lastTicks) / dt);
|
|
214
|
+
lastTicks = totalTicks; lastT = now;
|
|
215
|
+
const cpu = process.cpuUsage(lastCpu); lastCpu = process.cpuUsage();
|
|
216
|
+
const cpuPct = Math.round(((cpu.user + cpu.system) / 1000) / (dt * 1000) * 100);
|
|
217
|
+
const dropped = md.droppedRecords - dropBaseline;
|
|
218
|
+
const p50 = (eld.percentile(50) / 1e6).toFixed(1);
|
|
219
|
+
const p99 = (eld.percentile(99) / 1e6).toFixed(1);
|
|
220
|
+
const maxlag = (eld.max / 1e6).toFixed(0);
|
|
221
|
+
const avgStratNs = totalTicks ? Number(strategyNanos / BigInt(totalTicks)) : 0;
|
|
222
|
+
eld.reset();
|
|
223
|
+
log(
|
|
224
|
+
`t+${Math.round((now - t0) / 1000)}s | inst ticking ${state.size}/${allInstruments.length} | ` +
|
|
225
|
+
`ticks ${totalTicks} (${tps}/s) | DROPPED ${dropped} | RSS ${rss}MB heap ${heap}MB | ` +
|
|
226
|
+
`cpu ${cpuPct}% | loop-lag p50 ${p50} p99 ${p99} max ${maxlag} ms | ` +
|
|
227
|
+
`strat ${avgStratNs}ns/tick sig ${signalCount} | orders p${placed}/a${accepted}/c${cancelled}/r${rejected}`
|
|
228
|
+
);
|
|
229
|
+
}, 5000);
|
|
230
|
+
|
|
231
|
+
// Fire a place+cancel round-trip on a timer (independent of strategy signals) so
|
|
232
|
+
// the trade path is exercised under the full-market tick load even in a quiet
|
|
233
|
+
// session. The per-tick strategy compute above is the real CPU/backpressure load.
|
|
234
|
+
const orderTimer = cfg.trade ? setInterval(() => maybeTrade(orderSymLastTick), Number(env.CTP_ORDER_MS ?? 3000)) : null;
|
|
235
|
+
|
|
236
|
+
// ================= teardown + verdict =================
|
|
237
|
+
setTimeout(async () => {
|
|
238
|
+
clearInterval(stat);
|
|
239
|
+
if (orderTimer) clearInterval(orderTimer);
|
|
240
|
+
await sleep(200);
|
|
241
|
+
const dropped = md.droppedRecords - dropBaseline;
|
|
242
|
+
const mem = process.memoryUsage();
|
|
243
|
+
log("================= SUMMARY =================");
|
|
244
|
+
log(`run ${Math.round((Date.now() - t0) / 1000)}s | subscribed ${allInstruments.length} | instruments that ticked ${state.size}`);
|
|
245
|
+
log(`total ticks ${totalTicks} | DROPPED ${dropped} (${dropped === 0 ? "OK: feed never backed up" : "feed fell behind"})`);
|
|
246
|
+
log(`avg strategy compute ${totalTicks ? Number(strategyNanos / BigInt(totalTicks)) : 0} ns/tick | signals ${signalCount}`);
|
|
247
|
+
log(`orders placed ${placed} accepted ${accepted} cancelled ${cancelled} rejected ${rejected}`);
|
|
248
|
+
log(`peak RSS ${peakRss}MB | final RSS ${Math.round(mem.rss / 1048576)}MB heap ${Math.round(mem.heapUsed / 1048576)}MB`);
|
|
249
|
+
log(`loop-lag final p99 ${(eld.percentile(99) / 1e6).toFixed(1)}ms max ${(eld.max / 1e6).toFixed(0)}ms`);
|
|
250
|
+
md.close(); td.close();
|
|
251
|
+
await sleep(300);
|
|
252
|
+
process.exit(0);
|
|
253
|
+
}, cfg.runMs);
|
|
254
|
+
|
|
255
|
+
log("connecting... MD", cfg.mdFront, "| TD", cfg.tdFront, "| run", cfg.runMs + "ms"); // never log the userId
|
package/src/addon.cc
CHANGED
|
@@ -76,7 +76,7 @@ Napi::Value RiskSelfTest(const Napi::CallbackInfo &info) {
|
|
|
76
76
|
Napi::Object out = Napi::Object::New(env);
|
|
77
77
|
|
|
78
78
|
ctp::RiskEngine eng;
|
|
79
|
-
ctp::
|
|
79
|
+
ctp::RiskLimits cfg;
|
|
80
80
|
cfg.maxOrderVolume = 5;
|
|
81
81
|
cfg.maxPriceDeviation = 0.02;
|
|
82
82
|
eng.configure(cfg);
|
|
@@ -84,7 +84,7 @@ Napi::Value RiskSelfTest(const Napi::CallbackInfo &info) {
|
|
|
84
84
|
out.Set("normal", Verdict(env, eng.check("rb2510", 3500.0, 3500.0, 1)));
|
|
85
85
|
out.Set("tooBig", Verdict(env, eng.check("rb2510", 3500.0, 3500.0, 10)));
|
|
86
86
|
out.Set("offPrice", Verdict(env, eng.check("rb2510", 3500.0, 3000.0, 1)));
|
|
87
|
-
eng.
|
|
87
|
+
eng.reduceOnly();
|
|
88
88
|
out.Set("halted", Verdict(env, eng.check("rb2510", 3500.0, 3500.0, 1)));
|
|
89
89
|
|
|
90
90
|
ctp::RateLimiter rl;
|