@hitrading/ctp-node 2.0.0 → 4.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +82 -0
- package/README.md +54 -32
- package/README.zh-CN.md +44 -27
- package/RELEASING.md +78 -0
- package/dist/client.d.ts +36 -15
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +234 -62
- package/dist/client.js.map +1 -1
- package/dist/codec.d.ts.map +1 -1
- package/dist/codec.js +84 -19
- package/dist/codec.js.map +1 -1
- package/dist/generated/structs.gen.d.ts +5461 -5461
- package/dist/generated/structs.gen.d.ts.map +1 -1
- package/dist/generated/trader.gen.d.ts.map +1 -1
- package/dist/generated/trader.gen.js +788 -94
- package/dist/generated/trader.gen.js.map +1 -1
- package/dist/index.cjs +1909 -417
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/market-data.d.ts +41 -24
- package/dist/market-data.d.ts.map +1 -1
- package/dist/market-data.js +148 -29
- package/dist/market-data.js.map +1 -1
- package/dist/native-binding.d.ts.map +1 -1
- package/dist/native-binding.js +4 -0
- package/dist/native-binding.js.map +1 -1
- package/dist/trader.d.ts +136 -79
- package/dist/trader.d.ts.map +1 -1
- package/dist/trader.js +807 -182
- package/dist/trader.js.map +1 -1
- package/dist/validation.d.ts +27 -0
- package/dist/validation.d.ts.map +1 -0
- package/dist/validation.js +85 -0
- package/dist/validation.js.map +1 -0
- package/docs/API.md +1445 -0
- package/docs/API.zh-CN.md +1285 -0
- package/docs/MIGRATION.md +54 -0
- package/docs/assets/validation.svg +27 -0
- package/docs/integration.md +60 -0
- package/docs/native-hooks.md +281 -0
- package/docs/native-hooks.zh-CN.md +205 -0
- package/docs/troubleshooting.md +257 -0
- package/docs/troubleshooting.zh-CN.md +220 -0
- package/package.json +12 -4
- package/prebuilds/linux-x64/@hitrading+ctp-node.node +0 -0
- package/prebuilds/win32-x64/@hitrading+ctp-node.node +0 -0
- package/scripts/bench-decode.mjs +37 -0
- package/scripts/bench-fullmarket-offline.mjs +207 -0
- package/scripts/stress-fullmarket.mjs +255 -0
- package/src/addon.cc +2 -2
- package/src/client.ts +255 -65
- package/src/codec.ts +86 -19
- package/src/generated/structs.gen.ts +5461 -5461
- package/src/generated/trader.gen.ts +309 -94
- package/src/generated/traderreq.gen.cc +194 -18
- package/src/generated/traderreq.gen.h +4 -0
- package/src/generated/traderspi.gen.cc +129 -15
- package/src/generated/traderspi.gen.h +4 -2
- package/src/index.ts +11 -1
- package/src/market-data.ts +199 -46
- package/src/native/arm.cc +114 -30
- package/src/native/arm.h +16 -4
- package/src/native/channel.cc +209 -81
- package/src/native/channel.h +65 -24
- package/src/native/ctp_field.h +23 -0
- package/src/native/mdapi.cc +582 -69
- package/src/native/mdspi.cc +219 -16
- package/src/native/mdspi.h +59 -10
- package/src/native/order_capability.h +78 -0
- package/src/native/risk.cc +2030 -213
- package/src/native/risk.h +431 -78
- package/src/native/shared_handle.h +37 -0
- package/src/native/snapshot.h +75 -16
- package/src/native/traderapi.cc +769 -124
- package/src/native-binding.ts +4 -0
- package/src/trader.ts +1038 -207
- package/src/validation.ts +96 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
# [4.0.0](https://github.com/hitrading/ctp-node/compare/v3.0.0...v4.0.0) (2026-07-29)
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
* feat(trader)!: strengthen session sync and order policies ([7494a99](https://github.com/hitrading/ctp-node/commit/7494a9981621e50a7336c924a8a1a142ef6da515))
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
### Bug Fixes
|
|
8
|
+
|
|
9
|
+
* **ci:** restore coverage gate on trader changes ([00f6ae5](https://github.com/hitrading/ctp-node/commit/00f6ae5e0842a19b685c9a4beaafe153dc8bf70b))
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
### BREAKING CHANGES
|
|
13
|
+
|
|
14
|
+
* session.sync.marginRates now requires { instrumentIds, hedgeFlag } instead of a string array.
|
|
15
|
+
|
|
16
|
+
# [3.0.0](https://github.com/hitrading/ctp-node/compare/v2.0.0...v3.0.0) (2026-07-12)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
* feat(risk)!: real-margin risk model with in-C++ data sourcing and MD snapshot LVC ([64436d5](https://github.com/hitrading/ctp-node/commit/64436d524f5c316d3da3ac85e7ded723b2d7677a))
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
### BREAKING CHANGES
|
|
23
|
+
|
|
24
|
+
* RiskConfig -> RiskLimits; maxPositionCost/maxMargin ->
|
|
25
|
+
maxAccountMargin (now real margin, x multiplier); halt() -> haltAll() +
|
|
26
|
+
reduceOnly(); setMaxPosition*/setMaxInstrumentCost -> setInstrumentPositionLimit(s)
|
|
27
|
+
/ setInstrumentMarginLimit(s); positionCost() -> accountMargin getter;
|
|
28
|
+
getApiVersion()/getTradingDay() -> apiVersion/tradingDay getters; seedPosition
|
|
29
|
+
-> seedPositions; net-mode (PosiDirection "1") positions are rejected; explicit
|
|
30
|
+
OrderRef must be a monotonic decimal; Node engines narrowed. See docs/MIGRATION.md.
|
|
31
|
+
|
|
32
|
+
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
|
|
33
|
+
|
|
34
|
+
# [2.0.0](https://github.com/hitrading/ctp-node/compare/v1.2.0...v2.0.0) (2026-06-17)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
### Features
|
|
38
|
+
|
|
39
|
+
* **risk:** source CTP data in C++, real-margin cap, market-data snapshot cache ([474a4dc](https://github.com/hitrading/ctp-node/commit/474a4dcdee977597f621ed7fee1fe8265772fe44))
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
### BREAKING CHANGES
|
|
43
|
+
|
|
44
|
+
* **risk:** Trader.setMultiplier and Trader.setRefPrice are removed --
|
|
45
|
+
contract multipliers and the price-deviation reference are now sourced in C++
|
|
46
|
+
(multipliers from instrument queries, the reference via trackMarketData(md)). The
|
|
47
|
+
position cost cap is now margin-based; prefer riskSet({ maxMargin }).
|
|
48
|
+
|
|
49
|
+
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
|
|
50
|
+
|
|
51
|
+
# [1.2.0](https://github.com/hitrading/ctp-node/compare/v1.1.0...v1.2.0) (2026-06-16)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
### Features
|
|
55
|
+
|
|
56
|
+
* upgrade CTP SDK 6.7.2 -> 6.7.13 ([bc6812a](https://github.com/hitrading/ctp-node/commit/bc6812a9d37d86b6f34cabd0dd9bf399f7fb9d45))
|
|
57
|
+
|
|
58
|
+
# [1.1.0](https://github.com/hitrading/ctp-node/compare/v1.0.0...v1.1.0) (2026-06-16)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
### Features
|
|
62
|
+
|
|
63
|
+
* dual ESM + CommonJS build so require() works alongside import ([addeee4](https://github.com/hitrading/ctp-node/commit/addeee4db3d2e565b15347fd33f67749633038f4))
|
|
64
|
+
|
|
65
|
+
# 1.0.0 (2026-06-16)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
### Features
|
|
69
|
+
|
|
70
|
+
* first public release of @hitrading/ctp-node ([6064b58](https://github.com/hitrading/ctp-node/commit/6064b58d5cd0455b2df0f3ddc65a555bd39d2331))
|
|
71
|
+
|
|
72
|
+
# Changelog
|
|
73
|
+
|
|
74
|
+
All notable changes to **@hitrading/ctp-node** are documented here.
|
|
75
|
+
|
|
76
|
+
This file is generated and maintained automatically by
|
|
77
|
+
[semantic-release](https://semantic-release.gitbook.io/) from the
|
|
78
|
+
[Conventional Commits](https://www.conventionalcommits.org/) history — **do not
|
|
79
|
+
edit it by hand**. Released versions are appended below on each release; see
|
|
80
|
+
[RELEASING.md](RELEASING.md) for how releases work.
|
|
81
|
+
|
|
82
|
+
<!-- semantic-release inserts released versions below this line -->
|
package/README.md
CHANGED
|
@@ -11,27 +11,37 @@
|
|
|
11
11
|
<p align="center">
|
|
12
12
|
<a href="https://github.com/hitrading/ctp-node/actions/workflows/build.yml"><img alt="CI" src="https://github.com/hitrading/ctp-node/actions/workflows/build.yml/badge.svg"></a>
|
|
13
13
|
<a href="LICENSE"><img alt="License" src="https://img.shields.io/github/license/hitrading/ctp-node?color=blue"></a>
|
|
14
|
-
<img alt="Node" src="https://img.shields.io/badge/node
|
|
14
|
+
<img alt="Node" src="https://img.shields.io/badge/node-22.22.2%2B-brightgreen">
|
|
15
15
|
<img alt="Platform" src="https://img.shields.io/badge/platform-Windows%20%7C%20Linux%20%7C%20macOS-lightgrey">
|
|
16
16
|
<img alt="TypeScript" src="https://img.shields.io/badge/TypeScript-strict-3178c6">
|
|
17
17
|
<img alt="decode" src="https://img.shields.io/badge/decode-~8M%20ticks%2Fs-ff7f0e">
|
|
18
18
|
</p>
|
|
19
19
|
|
|
20
20
|
<p align="center">
|
|
21
|
-
<img src="docs/assets/validation.svg" alt="ctp-node validation — green
|
|
21
|
+
<img src="docs/assets/validation.svg" alt="ctp-node validation — green offline suite plus a labeled historical live sample" width="780">
|
|
22
22
|
</p>
|
|
23
23
|
|
|
24
24
|
- **Plain objects, idiomatic TypeScript.** Every CTP struct is a generated `interface` with camelCase fields (`tick.lastPrice`, `tick.instrumentId`); every CTP enum is a real TS `enum`. No hand-written marshalling.
|
|
25
|
-
- **Fast.** The
|
|
25
|
+
- **Fast.** The isolated generated 46-field decoder runs at about **8M ticks/sec**. More importantly, the reproducible native-SPI-to-JS full-path probe sustained 500k ticks/sec across 18,111 real cache keys with zero drops and delivered an 18,111-tick all-contract callback storm intact on the measured host; see [Performance & memory](docs/troubleshooting.md#performance--memory) for hardware, CPU/RSS and limits.
|
|
26
26
|
- **Hybrid API.** `EventEmitter` for streaming pushes (`rtn-depth-market-data`, `rtn-order`…) + `Promise` for request/response (login, queries, orders), correlated by request id with multi-row accumulation.
|
|
27
27
|
- **Pre-trade risk in C++.** Kill-switch, max order volume, max notional, price-deviation (fat-finger) guard, account-wide and per-instrument open-position margin caps, per-instrument max position (lots, per side), and a token-bucket rate limiter are enforced on the order path in native code — a JS GC pause can't defeat them.
|
|
28
28
|
- **Stable by construction.** No hand-marshalling, threadsafe-functions released properly, `Init()` deferred so `front-connected` is never missed, compiler-truth (`offsetof`) binary layout, gb18030 decoded in JS (no Windows code-page bug).
|
|
29
29
|
|
|
30
30
|
> Targets the regime CTP actually supports (snapshot-driven, ms-tolerant strategies: CTA, arbitrage, market making). True microsecond HFT is not achievable through CTP in any language.
|
|
31
31
|
|
|
32
|
+
> **Boundary:** this package is an in-process protocol binding and local second
|
|
33
|
+
> line of risk. It does not authenticate callers, verify signed mandates, or own
|
|
34
|
+
> an external heartbeat watchdog. Production use still requires an authenticated
|
|
35
|
+
> gateway/supervisor and a fresh soak of the exact commit and packaged binaries.
|
|
36
|
+
> The protocol surface is broader than the local ledger: quantitative admission
|
|
37
|
+
> is complete only for ordinary single-leg orders; quote/exec/comb/parked and
|
|
38
|
+
> similar advanced mutations are binding-only and rejected whenever local risk
|
|
39
|
+
> is enabled. Until the exact `3.0.0-rc` artifact passes that soak and the external
|
|
40
|
+
> mandate/watchdog controls exist, the production-live decision remains **No-Go**.
|
|
41
|
+
|
|
32
42
|
## Requirements
|
|
33
43
|
|
|
34
|
-
Node
|
|
44
|
+
Node 22.22.2+ on supported even-numbered release lines (`^22.22.2 || ^24.15.0 || >=26.0.0`). This mirrors the Node.js range required by the bundled `node-gyp`; odd-numbered/EOL releases and Node 24.0–24.14 are not supported. Prebuilt binaries are shipped for **Windows and Linux (x64)** — most users need no compiler there. **macOS (and any other platform) builds from source on install**, which needs a C++ toolchain (macOS: Xcode Command Line Tools; Windows: VS Build Tools; Linux: clang/gcc). The CTP shared libraries are bundled next to the loaded addon and resolved automatically.
|
|
35
45
|
|
|
36
46
|
## Install
|
|
37
47
|
|
|
@@ -53,7 +63,7 @@ const { Trader, MarketData } = require("@hitrading/ctp-node"); // CommonJS
|
|
|
53
63
|
- **Full API reference** — every TypeScript/JavaScript interface and method, with each parameter's type and meaning, plus usage examples: [English](docs/API.md) · [简体中文](docs/API.zh-CN.md)
|
|
54
64
|
- Architecture & native internals — the lock-free data plane, the C++ risk engine, backpressure, and the create-once process-lifecycle notes: [English](docs/native-hooks.md) · [简体中文](docs/native-hooks.zh-CN.md)
|
|
55
65
|
- **Troubleshooting & FAQ** — connection/front rotation, login & authentication, query rate limits, order rejections, limit-down, lifecycle, build issues, CTP error codes: [English](docs/troubleshooting.md) · [简体中文](docs/troubleshooting.zh-CN.md)
|
|
56
|
-
- **Testing & coverage** —
|
|
66
|
+
- **Testing & coverage** — full offline regression plus a credential-gated SimNow suite that must be run separately; historical samples are not a soak result for the current candidate: [integration & testing](docs/integration.md)
|
|
57
67
|
- **Releasing** — fully automatic `semantic-release` (Conventional Commits → version + CHANGELOG + GitHub Release + npm publish): [RELEASING.md](RELEASING.md) · [CHANGELOG.md](CHANGELOG.md)
|
|
58
68
|
|
|
59
69
|
## Quick start — market data
|
|
@@ -73,8 +83,9 @@ md.on("rtn-depth-market-data", (tick) => {
|
|
|
73
83
|
console.log(tick.instrumentId, tick.lastPrice, tick.bidPrice1, tick.askPrice1);
|
|
74
84
|
});
|
|
75
85
|
|
|
76
|
-
//
|
|
77
|
-
// before
|
|
86
|
+
// After a successful MD login, market data is cached in C++ (a last-value cache,
|
|
87
|
+
// updated before each authenticated-session tick reaches JS), so you get a
|
|
88
|
+
// synchronous snapshot with no bookkeeping in JS:
|
|
78
89
|
// md.snapshot("rb2510"); // latest full depth tick (DepthMarketData) or null
|
|
79
90
|
// md.last("rb2510"); // latest price, 0 if none seen yet
|
|
80
91
|
```
|
|
@@ -87,22 +98,30 @@ import { Trader } from "@hitrading/ctp-node";
|
|
|
87
98
|
const td = new Trader("./flow/td/", "tcp://182.254.243.31:30002");
|
|
88
99
|
|
|
89
100
|
// Pre-trade risk, enforced in C++ on every order:
|
|
90
|
-
td.
|
|
91
|
-
td.trackMarketData(md); //
|
|
92
|
-
td.
|
|
93
|
-
td.
|
|
101
|
+
td.setRiskLimits({ maxOrderVolume: 10, maxOrdersPerSec: 20, maxPriceDeviation: 0.02, maxAccountMargin: 2_000_000 });
|
|
102
|
+
td.trackMarketData(md); // fresh C++ reference for deviation, notional and margin gates
|
|
103
|
+
td.setInstrumentPositionLimits({ rb2610: 100, au2610: 10, ru2610: { long: 100, short: 20 } });
|
|
104
|
+
td.setInstrumentMarginLimits({ ag2608: 2_000_000, au2608: 5_000_000 }); // per-instrument scheduled-margin caps
|
|
94
105
|
|
|
95
106
|
td.on("front-connected", async () => {
|
|
96
|
-
// One-call handshake (call again after a reconnect)
|
|
97
|
-
//
|
|
98
|
-
|
|
99
|
-
|
|
107
|
+
// One-call handshake (call again after a reconnect). Margin-rate queries need
|
|
108
|
+
// an explicit bounded trading universe and hedge flag (one CTP query per contract).
|
|
109
|
+
await td.session({
|
|
110
|
+
brokerId, userId, password, appId, authCode,
|
|
111
|
+
sync: {
|
|
112
|
+
marginRates: {
|
|
113
|
+
instrumentIds: ["rb2510", "ag2608", "au2608"],
|
|
114
|
+
hedgeFlag: "1",
|
|
115
|
+
},
|
|
116
|
+
},
|
|
117
|
+
});
|
|
100
118
|
|
|
101
119
|
// ...or hand-roll it if you need finer control:
|
|
102
120
|
// await td.reqAuthenticate({ brokerId, userId, appId, authCode });
|
|
103
121
|
// await td.reqUserLogin({ brokerId, userId, password });
|
|
104
122
|
// await td.reqSettlementInfoConfirm({ brokerId, investorId }); // real accounts
|
|
105
|
-
// await td.syncMultipliers(); await td.
|
|
123
|
+
// await td.syncMultipliers(); await td.syncMarginRates(["rb2510"]);
|
|
124
|
+
// await td.syncOrders(); await td.syncPositions(); // held snapshot must be last
|
|
106
125
|
|
|
107
126
|
// Promise-based queries return all rows:
|
|
108
127
|
const positions = await td.reqQryInvestorPosition({ brokerId, investorId });
|
|
@@ -112,7 +131,7 @@ td.on("front-connected", async () => {
|
|
|
112
131
|
// rtn-trade. orderRef is auto-assigned a unique value if you leave it blank.
|
|
113
132
|
await td.reqOrderInsert({
|
|
114
133
|
brokerId, investorId, instrumentId: "rb2510",
|
|
115
|
-
direction: "0",
|
|
134
|
+
direction: "0", combOffsetFlag: "0", // buy-open; see enums
|
|
116
135
|
limitPrice: 3500, volumeTotalOriginal: 1,
|
|
117
136
|
});
|
|
118
137
|
});
|
|
@@ -120,8 +139,9 @@ td.on("front-connected", async () => {
|
|
|
120
139
|
td.on("rtn-order", (order) => console.log("order update", order.orderStatus));
|
|
121
140
|
td.on("rtn-trade", (trade) => console.log("filled", trade.price, trade.volume));
|
|
122
141
|
|
|
123
|
-
//
|
|
124
|
-
//
|
|
142
|
+
// Atomic modes: reduceOnly() keeps closes+cancels; haltAll() blocks closes too.
|
|
143
|
+
// Multi-leg combOffsetFlag values are rejected until a per-leg ledger exists.
|
|
144
|
+
// td.reduceOnly(); / td.haltAll(); / td.resume();
|
|
125
145
|
```
|
|
126
146
|
|
|
127
147
|
### Armed orders (latency-critical)
|
|
@@ -136,11 +156,11 @@ const armed = trader.arm(md, {
|
|
|
136
156
|
side: "buy", // buy fires when ask ≤ trigger; sell when bid ≥ trigger
|
|
137
157
|
triggerPrice: 3500,
|
|
138
158
|
order: {
|
|
139
|
-
brokerId, investorId, instrumentId: "rb2510", direction: "0",
|
|
140
|
-
limitPrice: 3500, volumeTotalOriginal: 1, orderRef: "
|
|
159
|
+
brokerId, investorId, instrumentId: "rb2510", direction: "0", combOffsetFlag: "0",
|
|
160
|
+
limitPrice: 3500, volumeTotalOriginal: 1, orderRef: "900001",
|
|
141
161
|
},
|
|
142
162
|
});
|
|
143
|
-
//
|
|
163
|
+
// Removed after a successful send; refusal stays armed with bounded exponential backoff.
|
|
144
164
|
// armed.disarm();
|
|
145
165
|
```
|
|
146
166
|
|
|
@@ -155,14 +175,16 @@ Direction.Sell; // "1"
|
|
|
155
175
|
## API shape
|
|
156
176
|
|
|
157
177
|
- `new MarketData(flowPath, fronts)` / `new Trader(flowPath, fronts)` — `fronts` is a `tcp://` address or an array.
|
|
158
|
-
- Requests are camelCase methods taking a `Partial<...>` of the CTP field object and returning a `Promise`. `reqQry*` resolve with an array of rows; most requests resolve with the single response row.
|
|
178
|
+
- Requests are camelCase methods taking a `Partial<...>` of the CTP field object and returning a `Promise`. Request objects are strict plain objects: unknown/inherited/removed fields and `null` field values are rejected instead of ignored. Input arrays must be dense and use explicit own entries; sparse/prototype-provided values are rejected. `reqQry*` resolve with an array of rows; most requests resolve with the single response row.
|
|
179
|
+
- All `reqQry*` / `reqQuery*` calls on one client are snapshotted, serialized and paced internally (one in flight, at least 1100 ms between attempted sends), so callers must not add `setTimeout(1000)`. The bounded queue is per client; raw queries are paced but only `sync*` helpers retry transient flow control.
|
|
159
180
|
- Exchange-bound inserts/actions (`reqOrderInsert`, `reqOrderAction`, …) resolve on **submission** — CTP returns no success response for an accepted order, only `rtn-order` / `rtn-trade` (correlate by `orderRef`). They reject only if the send is refused (risk gate, rate limit, or a CTP API error code).
|
|
160
181
|
- Streaming events use kebab-case names (`rtn-depth-market-data`, `rtn-order`, …); handlers get `(data, options)` where `options` carries `{ requestId?, isLast?, rspInfo? }`.
|
|
161
|
-
- The latest tick per instrument is kept in a C++ last-value cache
|
|
182
|
+
- The latest tick per instrument is kept in a C++ last-value cache. It is invalid before a successful MD login; login opens a new empty epoch, and connect/disconnect, a new login/logout attempt, successful logout, and close invalidate and clear it. Only later ticks in the authenticated epoch update the cache or drive armed orders. `md.snapshot(instrumentId)` returns the latest full `DepthMarketData` (or `null`) and `md.last(instrumentId)` the latest price (0 if none) synchronously. The same epoch-bound cache backs the price-deviation guard.
|
|
162
183
|
- `client.droppedRecords` reports records dropped under backpressure. Market
|
|
163
|
-
data
|
|
164
|
-
the trader
|
|
165
|
-
|
|
184
|
+
data uses bounded keep-newest staging and retains the freshest quote;
|
|
185
|
+
the trader uses a lossless ordered overflow queue, so order/trade/query returns
|
|
186
|
+
are not deliberately discarded when its 4096-slot ring fills. Sustained Trader
|
|
187
|
+
overload can therefore consume memory: keep handlers bounded and monitor lag.
|
|
166
188
|
- `client.close()` releases the underlying CTP API. Call it **once**, at shutdown — a CTP client is create-once / reuse; reconnecting by recreating it deadlocks in the vendor DLL (see [Lifecycle](#lifecycle-create-once-reuse)).
|
|
167
189
|
|
|
168
190
|
## Lifecycle: create once, reuse
|
|
@@ -183,9 +205,9 @@ md.on("front-connected", async () => { // first connect AND every reconnect
|
|
|
183
205
|
td.on("front-connected", () => td.session({ brokerId, userId, password, appId, authCode }));
|
|
184
206
|
```
|
|
185
207
|
|
|
186
|
-
> **Why.** `close()` calls the vendor `CThostFtdc*Api::Release()
|
|
187
|
-
>
|
|
188
|
-
>
|
|
208
|
+
> **Why.** `close()` calls the vendor `CThostFtdc*Api::Release()`. Repeated
|
|
209
|
+
> `Init()`/`Release()` cycles have been observed to deadlock inside the Windows
|
|
210
|
+
> vendor DLL; the binding cannot safely recover a process from that state. A
|
|
189
211
|
> "reconnect by recreate" loop will hang the whole process (and on Windows the
|
|
190
212
|
> wedged process ignores `SIGTERM`, so it must be force-killed with `taskkill /F`
|
|
191
213
|
> — until then it locks `build\Release\ctp.node` and breaks the next native
|
|
@@ -201,8 +223,8 @@ CTP callback thread (C++) Node event loop (JS)
|
|
|
201
223
|
OnRtn.../OnRsp... → memcpy bytes ──► coalesced doorbell → drain whole batch
|
|
202
224
|
into lock-free SPSC ring, → decode each record from the ring
|
|
203
225
|
bump atomic index, ring doorbell (monomorphic generated decoder)
|
|
204
|
-
(on overflow: MD
|
|
205
|
-
trader
|
|
226
|
+
(on overflow: MD stages/evicts oldest, → plain object → emit / resolve
|
|
227
|
+
trader spills losslessly in order)
|
|
206
228
|
```
|
|
207
229
|
|
|
208
230
|
Everything below the public API is generated from the CTP headers
|
package/README.zh-CN.md
CHANGED
|
@@ -11,27 +11,33 @@
|
|
|
11
11
|
<p align="center">
|
|
12
12
|
<a href="https://github.com/hitrading/ctp-node/actions/workflows/build.yml"><img alt="CI" src="https://github.com/hitrading/ctp-node/actions/workflows/build.yml/badge.svg"></a>
|
|
13
13
|
<a href="LICENSE"><img alt="License" src="https://img.shields.io/github/license/hitrading/ctp-node?color=blue"></a>
|
|
14
|
-
<img alt="Node" src="https://img.shields.io/badge/node
|
|
14
|
+
<img alt="Node" src="https://img.shields.io/badge/node-22.22.2%2B-brightgreen">
|
|
15
15
|
<img alt="Platform" src="https://img.shields.io/badge/platform-Windows%20%7C%20Linux%20%7C%20macOS-lightgrey">
|
|
16
16
|
<img alt="TypeScript" src="https://img.shields.io/badge/TypeScript-strict-3178c6">
|
|
17
17
|
<img alt="decode" src="https://img.shields.io/badge/decode-~8M%20ticks%2Fs-ff7f0e">
|
|
18
18
|
</p>
|
|
19
19
|
|
|
20
20
|
<p align="center">
|
|
21
|
-
<img src="docs/assets/validation.svg" alt="ctp-node 验证 ——
|
|
21
|
+
<img src="docs/assets/validation.svg" alt="ctp-node 验证 —— 离线套件 + 明确标注的历史实盘样本" width="780">
|
|
22
22
|
</p>
|
|
23
23
|
|
|
24
24
|
- **纯对象、地道的 TypeScript。** 每个 CTP 结构体都是生成的 `interface`,字段为 camelCase(`tick.lastPrice`、`tick.instrumentId`);每个 CTP 枚举都是真正的 TS `enum`。无手写编解码。
|
|
25
|
-
- **快。**
|
|
25
|
+
- **快。** 独立的 46 字段生成解码器约为 **800 万 tick/秒**。更重要的是,可复现的原生 SPI→JS 全路径探针在 18,111 个真实缓存 key 下以 50 万 tick/秒持续运行且 0 丢弃,并完整接住一次 18,111 条全合约回调洪峰;硬件、CPU/RSS 与边界见[性能与内存](docs/troubleshooting.zh-CN.md#性能与内存)。
|
|
26
26
|
- **混合 API。** 流式推送用 `EventEmitter`(`rtn-depth-market-data`、`rtn-order` 等)+ 请求/响应用 `Promise`(登录、查询、报单),按 request id 关联并支持多行累积。
|
|
27
27
|
- **盘前风控在 C++ 中。** 一键熔断、单笔最大手数、最大名义价值、价格偏离(防胖手指)、账户级与按合约的开仓持仓保证金上限、按合约的最大持仓(手数、分边)、以及令牌桶限频器,都在原生代码里、报单路径上执行——JS 的 GC 停顿打不垮它们。
|
|
28
28
|
- **构造即稳定。** 无手写编解码、threadsafe-function 正确释放、`Init()` 延后以保证 `front-connected` 不丢失、编译器真值(`offsetof`)的二进制布局、GB18030 在 JS 解码(无 Windows 代码页 bug)。
|
|
29
29
|
|
|
30
30
|
> 面向 CTP 实际支持的范畴(快照驱动、容忍毫秒级的策略:CTA、套利、做市)。真正的微秒级 HFT 在任何语言下都无法通过 CTP 实现。
|
|
31
31
|
|
|
32
|
+
> **边界:** 本包是进程内协议 binding 与第二道本地风控,不负责 caller 鉴权、签名 mandate 或外部
|
|
33
|
+
> 心跳看门狗。生产使用仍需有鉴权的网关/监督进程,并对确切 commit 与打包二进制重新浸泡验证。
|
|
34
|
+
> 协议接口范围大于本地账本:定量准入只对普通单腿报单形成闭环;quote/exec/comb/parked 等高级变更
|
|
35
|
+
> 仅属于 binding 能力,启用本地风控时会拒绝。在确切的 `3.0.0-rc` 制品完成浸泡且外部
|
|
36
|
+
> mandate/watchdog 落地之前,生产实盘判定仍为 **No-Go**。
|
|
37
|
+
|
|
32
38
|
## 环境要求
|
|
33
39
|
|
|
34
|
-
Node
|
|
40
|
+
受支持的偶数版本线要求 Node 22.22.2+(`^22.22.2 || ^24.15.0 || >=26.0.0`)。该范围与内置 `node-gyp` 的 Node.js 要求一致;不支持奇数/EOL 版本及 Node 24.0–24.14。**Windows 与 Linux(x64)提供预编译二进制**,这两个平台多数用户无需编译器。**macOS(及其他平台)在安装时从源码构建**,需要 C++ 工具链(macOS:Xcode Command Line Tools;Windows:VS Build Tools;Linux:clang/gcc)。CTP 共享库随插件一起打包在旁并自动解析。
|
|
35
41
|
|
|
36
42
|
## 安装
|
|
37
43
|
|
|
@@ -53,7 +59,7 @@ const { Trader, MarketData } = require("@hitrading/ctp-node"); // CommonJS
|
|
|
53
59
|
- **完整 API 参考** —— 每一个 TypeScript/JavaScript 接口和方法,含每个参数的类型与含义,以及用法示例:[English](docs/API.md) · [简体中文](docs/API.zh-CN.md)
|
|
54
60
|
- 架构与原生内部 —— 无锁数据平面、C++ 风控引擎、背压,以及一次创建的进程生命周期说明:[English](docs/native-hooks.md) · [简体中文](docs/native-hooks.zh-CN.md)
|
|
55
61
|
- **故障排查与 FAQ** —— 连接/前置轮换、登录与认证、查询限频、报单被拒、跌停、生命周期、构建问题、CTP 错误码:[English](docs/troubleshooting.md) · [简体中文](docs/troubleshooting.zh-CN.md)
|
|
56
|
-
- **测试与覆盖率** ——
|
|
62
|
+
- **测试与覆盖率** —— 完整离线回归 + 需要凭据、必须另行执行的 SimNow 集成套件;历史样本不等于当前候选版浸泡结论:[集成与测试](docs/integration.md)
|
|
57
63
|
- **发布** —— 全自动 `semantic-release`(Conventional Commits → 版本号 + CHANGELOG + GitHub Release + npm 发布):[RELEASING.md](RELEASING.md) · [CHANGELOG.md](CHANGELOG.md)
|
|
58
64
|
|
|
59
65
|
## 快速开始 —— 行情
|
|
@@ -73,8 +79,8 @@ md.on("rtn-depth-market-data", (tick) => {
|
|
|
73
79
|
console.log(tick.instrumentId, tick.lastPrice, tick.bidPrice1, tick.askPrice1);
|
|
74
80
|
});
|
|
75
81
|
|
|
76
|
-
//
|
|
77
|
-
//
|
|
82
|
+
// MD 成功登录后,最新行情缓存在 C++ 中(一个 last-value 缓存,当前认证
|
|
83
|
+
// 会话内的 tick 到达 JS 前更新),因此无需在 JS 里记账即可同步取到快照:
|
|
78
84
|
// md.snapshot("rb2510"); // 最新完整深度行情(DepthMarketData)或 null
|
|
79
85
|
// md.last("rb2510"); // 最新价,尚无则为 0
|
|
80
86
|
```
|
|
@@ -87,21 +93,29 @@ import { Trader } from "@hitrading/ctp-node";
|
|
|
87
93
|
const td = new Trader("./flow/td/", "tcp://182.254.243.31:30002");
|
|
88
94
|
|
|
89
95
|
// 盘前风控,在 C++ 中对每笔报单执行:
|
|
90
|
-
td.
|
|
91
|
-
td.trackMarketData(md); //
|
|
92
|
-
td.
|
|
93
|
-
td.
|
|
96
|
+
td.setRiskLimits({ maxOrderVolume: 10, maxOrdersPerSec: 20, maxPriceDeviation: 0.02, maxAccountMargin: 2_000_000 });
|
|
97
|
+
td.trackMarketData(md); // 为偏离、名义价值与保证金闸提供 C++ 新鲜参考价
|
|
98
|
+
td.setInstrumentPositionLimits({ rb2610: 100, au2610: 10, ru2610: { long: 100, short: 20 } });
|
|
99
|
+
td.setInstrumentMarginLimits({ ag2608: 2_000_000, au2608: 5_000_000 }); // 按合约的计划保证金上限
|
|
94
100
|
|
|
95
101
|
td.on("front-connected", async () => {
|
|
96
|
-
//
|
|
97
|
-
|
|
98
|
-
|
|
102
|
+
// 一站式握手。保证金表需显式给出有限交易合约集和套保标志(CTP 每合约一次查询)。
|
|
103
|
+
await td.session({
|
|
104
|
+
brokerId, userId, password, appId, authCode,
|
|
105
|
+
sync: {
|
|
106
|
+
marginRates: {
|
|
107
|
+
instrumentIds: ["rb2510", "ag2608", "au2608"],
|
|
108
|
+
hedgeFlag: "1",
|
|
109
|
+
},
|
|
110
|
+
},
|
|
111
|
+
});
|
|
99
112
|
|
|
100
113
|
// ……或在需要更细控制时手写:
|
|
101
114
|
// await td.reqAuthenticate({ brokerId, userId, appId, authCode });
|
|
102
115
|
// await td.reqUserLogin({ brokerId, userId, password });
|
|
103
116
|
// await td.reqSettlementInfoConfirm({ brokerId, investorId }); // 实盘账户
|
|
104
|
-
// await td.syncMultipliers(); await td.
|
|
117
|
+
// await td.syncMultipliers(); await td.syncMarginRates(["rb2510"]);
|
|
118
|
+
// await td.syncOrders(); await td.syncPositions(); // 最后提交持仓快照
|
|
105
119
|
|
|
106
120
|
// 基于 Promise 的查询返回所有行:
|
|
107
121
|
const positions = await td.reqQryInvestorPosition({ brokerId, investorId });
|
|
@@ -110,7 +124,7 @@ td.on("front-connected", async () => {
|
|
|
110
124
|
// 不返回 ack);通过 rtn-order / rtn-trade 跟踪结果。orderRef 留空会自动分配唯一值。
|
|
111
125
|
await td.reqOrderInsert({
|
|
112
126
|
brokerId, investorId, instrumentId: "rb2510",
|
|
113
|
-
direction: "0",
|
|
127
|
+
direction: "0", combOffsetFlag: "0", // 买开;见枚举
|
|
114
128
|
limitPrice: 3500, volumeTotalOriginal: 1,
|
|
115
129
|
});
|
|
116
130
|
});
|
|
@@ -118,8 +132,10 @@ td.on("front-connected", async () => {
|
|
|
118
132
|
td.on("rtn-order", (order) => console.log("报单更新", order.orderStatus));
|
|
119
133
|
td.on("rtn-trade", (trade) => console.log("已成交", trade.price, trade.volume));
|
|
120
134
|
|
|
121
|
-
//
|
|
122
|
-
//
|
|
135
|
+
// 应急一键熔断(拦截增险入口,保留减仓/撤单):
|
|
136
|
+
// 原子模式:reduceOnly() 保留平仓与撤单;haltAll() 也拦平仓。
|
|
137
|
+
// 多腿 combOffsetFlag 在具备逐腿账本前会直接拒绝。
|
|
138
|
+
// td.reduceOnly(); / td.haltAll(); / td.resume();
|
|
123
139
|
```
|
|
124
140
|
|
|
125
141
|
### 预埋单(延迟攸关)
|
|
@@ -132,11 +148,11 @@ const armed = trader.arm(md, {
|
|
|
132
148
|
side: "buy", // buy 在 ask ≤ trigger 时触发;sell 在 bid ≥ trigger 时触发
|
|
133
149
|
triggerPrice: 3500,
|
|
134
150
|
order: {
|
|
135
|
-
brokerId, investorId, instrumentId: "rb2510", direction: "0",
|
|
136
|
-
limitPrice: 3500, volumeTotalOriginal: 1, orderRef: "
|
|
151
|
+
brokerId, investorId, instrumentId: "rb2510", direction: "0", combOffsetFlag: "0",
|
|
152
|
+
limitPrice: 3500, volumeTotalOriginal: 1, orderRef: "900001",
|
|
137
153
|
},
|
|
138
154
|
});
|
|
139
|
-
//
|
|
155
|
+
// 成功发送后删除;拒绝会保留并按有上限的指数退避重试。
|
|
140
156
|
// armed.disarm();
|
|
141
157
|
```
|
|
142
158
|
|
|
@@ -151,11 +167,12 @@ Direction.Sell; // "1"
|
|
|
151
167
|
## API 形态
|
|
152
168
|
|
|
153
169
|
- `new MarketData(flowPath, fronts)` / `new Trader(flowPath, fronts)` —— `fronts` 是一个 `tcp://` 地址或数组。
|
|
154
|
-
- 请求是 camelCase 方法,接受 CTP 字段对象的 `Partial<...>` 并返回 `Promise
|
|
170
|
+
- 请求是 camelCase 方法,接受 CTP 字段对象的 `Partial<...>` 并返回 `Promise`。请求必须是严格普通对象;未知、继承或已删除字段以及 `null` 字段值会直接报错。输入数组必须稠密且每项都是显式自有值;稀疏或由原型提供的项会被拒绝。`reqQry*` 以行数组 resolve;多数请求以单条响应行 resolve。
|
|
171
|
+
- 同一客户端内全部 `reqQry*` / `reqQuery*` 都会在调用时快照、内部串行并限频(最多一个在途,两次尝试发送至少间隔 1100 ms),调用方不要再写 `setTimeout(1000)`。有界队列按客户端隔离;原始查询只限频,只有 `sync*` 会重试瞬时流控错误。
|
|
155
172
|
- 发往交易所的 insert/action(`reqOrderInsert`、`reqOrderAction` 等)**提交成功即** resolve —— CTP 对已接受的报单不返回成功响应,只有 `rtn-order` / `rtn-trade`(用 `orderRef` 关联)。只有发送被拒(风控网关、限频、或 CTP API 错误码)才 reject。
|
|
156
173
|
- 流式事件用 kebab-case 名称(`rtn-depth-market-data`、`rtn-order` 等);处理函数收到 `(data, options)`,`options` 带 `{ requestId?, isLast?, rspInfo? }`。
|
|
157
|
-
- 每个合约的最新 tick 保存在 C++ 的 last-value
|
|
158
|
-
-
|
|
174
|
+
- 每个合约的最新 tick 保存在 C++ 的 last-value 缓存里。成功 MD 登录会开启一个全新的空 epoch;此前,以及连接/断线、新登录或登出尝试、成功登出、关闭之后,缓存都会立即失效并清空。只有当前已认证 epoch 后续收到的 tick 才能更新缓存或驱动预埋单。`md.snapshot(instrumentId)` 同步返回最新完整 `DepthMarketData`(或 `null`),`md.last(instrumentId)` 返回最新价(无则为 0)。价格偏离校验使用同一份带 epoch 约束的缓存。
|
|
175
|
+
- 行情背压使用有界 keep-newest 暂存并保留最新行情,不覆盖 JS 正在解码的槽位;交易端 4096 槽满后进入有序无损队列,不主动丢回报,但持续消费停顿会增长内存。
|
|
159
176
|
- `client.close()` 释放底层 CTP API。在关闭时调用**一次**——CTP 客户端是一次创建/复用的;靠重建来重连会在厂商 DLL 里死锁(见[生命周期](#生命周期-一次创建并复用))。
|
|
160
177
|
|
|
161
178
|
## 生命周期 一次创建并复用
|
|
@@ -172,7 +189,7 @@ md.on("front-connected", async () => { // 首次连接和每次重连
|
|
|
172
189
|
td.on("front-connected", () => td.session({ brokerId, userId, password, appId, authCode }));
|
|
173
190
|
```
|
|
174
191
|
|
|
175
|
-
> **为什么。**
|
|
192
|
+
> **为什么。** Windows 下反复 `Init()`/`Release()` 已观察到会卡在厂商 DLL 的 `Release()`;进程无法安全恢复。每个客户端只构造一次,且只在关闭时 `close()`。若一个进程内创建/关闭了异常多的客户端,会打印一次性的 `console.warn`(用 `CTP_RECREATE_WARN` 调节/禁用)。详见 [docs/native-hooks.zh-CN.md](docs/native-hooks.zh-CN.md#进程生命周期-一次创建并复用)。
|
|
176
193
|
|
|
177
194
|
## 架构
|
|
178
195
|
|
|
@@ -181,8 +198,8 @@ CTP 回调线程 (C++) Node 事件循环 (JS)
|
|
|
181
198
|
OnRtn.../OnRsp... → memcpy 字节 ──► 合并的门铃 → 整批排空
|
|
182
199
|
进无锁 SPSC 环、 → 从环里逐条解码
|
|
183
200
|
自增原子索引、敲门铃 (单态生成的解码器)
|
|
184
|
-
(
|
|
185
|
-
|
|
201
|
+
(溢出时:行情暂存并淘汰最旧、 → 纯对象 → emit / resolve
|
|
202
|
+
交易端有序无损溢出)
|
|
186
203
|
```
|
|
187
204
|
|
|
188
205
|
公开 API 之下的一切都由 CTP 头文件(`ctpsdk/ThostFtdc*.h`)经 `scripts/codegen/` 生成—— 519 个结构体接口、326 个枚举、字段布局表(经 `offsetof`),以及完整的 trader SPI + 请求分发。更新头文件后运行 `npm run gen`。
|
package/RELEASING.md
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
# Releasing
|
|
2
|
+
|
|
3
|
+
Releases are **fully automatic** via
|
|
4
|
+
[semantic-release](https://semantic-release.gitbook.io/). You never bump the
|
|
5
|
+
version, tag, write release notes, or run `npm publish` by hand — candidates use
|
|
6
|
+
[Conventional Commits](https://www.conventionalcommits.org/) on `next`; verified
|
|
7
|
+
stable changes are promoted to `master`.
|
|
8
|
+
|
|
9
|
+
## How it works
|
|
10
|
+
|
|
11
|
+
On every push to `master` (stable) or `next` (`rc` prerelease), the CI
|
|
12
|
+
[`build & prebuild`](.github/workflows/build.yml) workflow:
|
|
13
|
+
|
|
14
|
+
1. builds + tests + prebuilds on Windows / Linux, plus a decoupled best-effort
|
|
15
|
+
macOS build;
|
|
16
|
+
2. runs `semantic-release`, which reads the commits since the last release and:
|
|
17
|
+
- **decides the next version** from the commit types (see below),
|
|
18
|
+
- updates [`CHANGELOG.md`](CHANGELOG.md) and the `package.json` version,
|
|
19
|
+
- creates a **GitHub Release** with auto-generated notes and the gated
|
|
20
|
+
Windows/Linux prebuild bundle attached,
|
|
21
|
+
- **publishes `@hitrading/ctp-node`** to npm (`--access public`, with npm
|
|
22
|
+
provenance),
|
|
23
|
+
- commits the changelog + version bump back to the current release branch
|
|
24
|
+
(with `[skip ci]` so it doesn't loop).
|
|
25
|
+
|
|
26
|
+
If there are no release-worthy commits since the last release, it does nothing.
|
|
27
|
+
The macOS artifact is attached separately if its non-gating build succeeds; it
|
|
28
|
+
is not included in the npm tarball created by the release job.
|
|
29
|
+
|
|
30
|
+
## Commit message format
|
|
31
|
+
|
|
32
|
+
```
|
|
33
|
+
<type>(<optional scope>): <subject>
|
|
34
|
+
|
|
35
|
+
<optional body>
|
|
36
|
+
|
|
37
|
+
<optional footer>
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
| Commit type | Example | Release |
|
|
41
|
+
|---|---|---|
|
|
42
|
+
| `fix:` | `fix: reject a non-finite limit price in the order gate` | **patch** (0.0.x) |
|
|
43
|
+
| `feat:` | `feat: add reqQryDepthMarketData helper` | **minor** (0.x.0) |
|
|
44
|
+
| `feat!:` or a `BREAKING CHANGE:` footer | `feat!: rename arm() to armOrder()` | **major** (x.0.0) |
|
|
45
|
+
| `docs:` `chore:` `refactor:` `test:` `ci:` `perf:` `style:` | `docs: bilingual FAQ` | none (no release) |
|
|
46
|
+
|
|
47
|
+
`perf:` is configurable to a patch if you want; by default here it does not
|
|
48
|
+
release. Anything not matching a releasing type is bundled into the next release's
|
|
49
|
+
notes but doesn't itself trigger one.
|
|
50
|
+
|
|
51
|
+
## One-time setup (already in the repo, except the secret)
|
|
52
|
+
|
|
53
|
+
- `.releaserc.json` — the semantic-release plugin pipeline.
|
|
54
|
+
- `package.json` → `publishConfig: { access: public, provenance: true }`.
|
|
55
|
+
- The workflow's `release` job (`master` stable and `next` rc) with `contents`/`issues`/
|
|
56
|
+
`pull-requests`/`id-token` write permissions.
|
|
57
|
+
- **You must add the `NPM_TOKEN` repository secret** — an npm **granular**
|
|
58
|
+
access token with *Read and write* on the `@hitrading` scope and *Bypass 2FA*
|
|
59
|
+
enabled (GitHub → Settings → Secrets and variables → Actions → New repository
|
|
60
|
+
secret). The npm organization `hitrading` must exist
|
|
61
|
+
(https://www.npmjs.com/org/create — free for public packages).
|
|
62
|
+
|
|
63
|
+
## Current breaking candidate
|
|
64
|
+
|
|
65
|
+
`v2.0.0` is the latest tagged baseline. The risk and lifecycle redesign is a
|
|
66
|
+
breaking `3.0.0` candidate and the worktree package identity is
|
|
67
|
+
`3.0.0-rc.1`. Do not publish a dirty build or reuse the `v2.0.0` identity.
|
|
68
|
+
Commit the candidate on `next`; semantic-release assigns an `rc` version and
|
|
69
|
+
records the exact tag/package integrity. Generate fresh prebuilds and run the
|
|
70
|
+
full verification plus SimNow/broker soak against that exact artifact. Promote
|
|
71
|
+
the verified commit to `master` only afterwards. A stable `v3.0.0` must not be
|
|
72
|
+
inferred merely from local unit tests.
|
|
73
|
+
|
|
74
|
+
## Dry run (optional, locally)
|
|
75
|
+
|
|
76
|
+
```sh
|
|
77
|
+
npx semantic-release --dry-run --no-ci # needs GITHUB_TOKEN in the env
|
|
78
|
+
```
|
package/dist/client.d.ts
CHANGED
|
@@ -24,7 +24,6 @@ export interface NativeClient {
|
|
|
24
24
|
};
|
|
25
25
|
_dropCount(): number;
|
|
26
26
|
_readIndex?(): number;
|
|
27
|
-
_validate?(claimed: number): number;
|
|
28
27
|
close(): void;
|
|
29
28
|
}
|
|
30
29
|
export declare abstract class CtpClient extends EventEmitter {
|
|
@@ -44,12 +43,13 @@ export declare abstract class CtpClient extends EventEmitter {
|
|
|
44
43
|
private started;
|
|
45
44
|
private readonly pending;
|
|
46
45
|
private reqSeq;
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
46
|
+
private queryQueue;
|
|
47
|
+
private lastQuerySentAt;
|
|
48
|
+
private requestContextEpoch;
|
|
49
|
+
private explicitRequestTransitionSeq;
|
|
50
|
+
private queryInvalidationReason;
|
|
51
|
+
private scheduledQueries;
|
|
52
|
+
private cancelQueryDelay?;
|
|
53
53
|
/** A request that goes idle this long (no response and, for multi-row queries,
|
|
54
54
|
* no further rows) rejects, so awaiters don't hang forever. The timer resets
|
|
55
55
|
* on each row, so a large streaming query isn't cut off by total duration. */
|
|
@@ -57,6 +57,26 @@ export declare abstract class CtpClient extends EventEmitter {
|
|
|
57
57
|
protected constructor(native: any, layoutBlob: Int32Array, events: Map<number, string>);
|
|
58
58
|
/** Reject and clear every in-flight request (on disconnect / close). */
|
|
59
59
|
private rejectAllPending;
|
|
60
|
+
/** Invalidate all work tied to the previous connection/login context.
|
|
61
|
+
* Subclasses call this immediately before a login/logout transition. */
|
|
62
|
+
protected invalidateRequestContext(reason: string): void;
|
|
63
|
+
/** Begin a deliberate login/logout transition. Generated/manual public
|
|
64
|
+
* transition methods use this rather than calling invalidate directly. */
|
|
65
|
+
protected beginRequestContextTransition(reason: string): void;
|
|
66
|
+
/** Capture/validate the connection-login epoch across a compound async
|
|
67
|
+
* operation. QueryRequest protects one queued send; session/sync helpers use
|
|
68
|
+
* this token so a later step cannot silently continue on a new front. */
|
|
69
|
+
protected requestContextToken(): number;
|
|
70
|
+
protected requestTransitionToken(): number;
|
|
71
|
+
protected assertRequestContext(token: number, operation: string): void;
|
|
72
|
+
/** Internal state hook for a response that actually matched and successfully
|
|
73
|
+
* settled the current request. Streaming stale callbacks are still emitted to
|
|
74
|
+
* users, but cannot mutate a subclass's confirmed session identity. */
|
|
75
|
+
protected onRequestResolved(_eventName: string | undefined, _value: unknown, _options: CallbackOptions): void;
|
|
76
|
+
/** Linearize a session-request idle timeout with native login/logout state.
|
|
77
|
+
* Subclasses return false when the final native callback already won the
|
|
78
|
+
* race and its non-droppable response is merely waiting to be drained. */
|
|
79
|
+
protected shouldTimeoutRequest(_requestId: number, _sessionTransition: boolean): boolean;
|
|
60
80
|
/** Wire up the ring view + doorbell. Subclasses call this in their ctor. */
|
|
61
81
|
protected start(): void;
|
|
62
82
|
/** Records dropped under backpressure (ring full). Monitor this. */
|
|
@@ -76,13 +96,9 @@ export declare abstract class CtpClient extends EventEmitter {
|
|
|
76
96
|
protected decodeStruct(structId: number, bytes: Uint8Array): Record<string, unknown>;
|
|
77
97
|
private drain;
|
|
78
98
|
/**
|
|
79
|
-
*
|
|
80
|
-
*
|
|
81
|
-
*
|
|
82
|
-
* many of the oldest records it overwrote *during* that decode (validate()),
|
|
83
|
-
* discard those (they hold torn bytes), and only then deliver the rest — so a
|
|
84
|
-
* torn record never reaches a handler. The records we do deliver are always the
|
|
85
|
-
* freshest available, and conservation holds (received + dropped == produced).
|
|
99
|
+
* Keep-newest drain (market data). Overflow is copied into native staging,
|
|
100
|
+
* never over a slot JS may be reading. A claimed batch is owned until release,
|
|
101
|
+
* so newer records can displace only the unclaimed logical window.
|
|
86
102
|
*/
|
|
87
103
|
private drainOldest;
|
|
88
104
|
private dispatch;
|
|
@@ -103,7 +119,12 @@ export declare abstract class CtpClient extends EventEmitter {
|
|
|
103
119
|
* Send a request and resolve when its response arrives (matched by id).
|
|
104
120
|
* `single` resolves with the one row; otherwise with the accumulated rows.
|
|
105
121
|
*/
|
|
106
|
-
protected request<T>(send: (id: number) => number, single?: boolean): Promise<T>;
|
|
122
|
+
protected request<T>(send: (id: number) => number, single?: boolean, zeroIdEvent?: number, sessionTransition?: boolean): Promise<T>;
|
|
123
|
+
/** Serialize every ReqQry* / ReqQuery* call on this CTP client.
|
|
124
|
+
* CTP commonly allows about one query per second; putting the scheduler below
|
|
125
|
+
* the generated surface means raw concurrent reqQry* calls are covered too,
|
|
126
|
+
* not only the higher-level sync helpers. */
|
|
127
|
+
protected queryRequest<T>(send: (id: number) => number, single?: boolean): Promise<T>;
|
|
107
128
|
/** (Re)arm a pending request's idle timeout. Called at send and reset on each
|
|
108
129
|
* row, so a long streaming query isn't cut off by total elapsed time. */
|
|
109
130
|
private armRequestTimer;
|