@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.
Files changed (104) hide show
  1. package/CHANGELOG.md +67 -0
  2. package/README.md +52 -31
  3. package/README.zh-CN.md +42 -26
  4. package/RELEASING.md +78 -0
  5. package/binding.gyp +13 -13
  6. package/dist/client.d.ts +40 -15
  7. package/dist/client.d.ts.map +1 -1
  8. package/dist/client.js +241 -62
  9. package/dist/client.js.map +1 -1
  10. package/dist/codec.d.ts.map +1 -1
  11. package/dist/codec.js +84 -19
  12. package/dist/codec.js.map +1 -1
  13. package/dist/generated/structs.gen.d.ts +5461 -5461
  14. package/dist/generated/structs.gen.d.ts.map +1 -1
  15. package/dist/generated/trader.gen.d.ts.map +1 -1
  16. package/dist/generated/trader.gen.js +788 -94
  17. package/dist/generated/trader.gen.js.map +1 -1
  18. package/dist/index.cjs +1896 -420
  19. package/dist/index.d.cts +1 -1
  20. package/dist/index.d.ts +1 -1
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.js.map +1 -1
  23. package/dist/market-data.d.ts +48 -21
  24. package/dist/market-data.d.ts.map +1 -1
  25. package/dist/market-data.js +165 -26
  26. package/dist/market-data.js.map +1 -1
  27. package/dist/native-binding.d.ts.map +1 -1
  28. package/dist/native-binding.js +5 -1
  29. package/dist/native-binding.js.map +1 -1
  30. package/dist/trader.d.ts +127 -79
  31. package/dist/trader.d.ts.map +1 -1
  32. package/dist/trader.js +788 -200
  33. package/dist/trader.js.map +1 -1
  34. package/dist/validation.d.ts +27 -0
  35. package/dist/validation.d.ts.map +1 -0
  36. package/dist/validation.js +85 -0
  37. package/dist/validation.js.map +1 -0
  38. package/docs/API.md +1437 -0
  39. package/docs/API.zh-CN.md +1278 -0
  40. package/docs/MIGRATION.md +54 -0
  41. package/docs/assets/validation.svg +27 -0
  42. package/docs/integration.md +60 -0
  43. package/docs/native-hooks.md +281 -0
  44. package/docs/native-hooks.zh-CN.md +205 -0
  45. package/docs/troubleshooting.md +257 -0
  46. package/docs/troubleshooting.zh-CN.md +220 -0
  47. package/package.json +14 -6
  48. package/prebuilds/linux-x64/@hitrading+ctp-node.node +0 -0
  49. package/prebuilds/win32-x64/@hitrading+ctp-node.node +0 -0
  50. package/scripts/bench-decode.mjs +37 -0
  51. package/scripts/bench-fullmarket-offline.mjs +207 -0
  52. package/scripts/stress-fullmarket.mjs +255 -0
  53. package/src/addon.cc +2 -2
  54. package/src/client.ts +263 -65
  55. package/src/codec.ts +86 -19
  56. package/src/generated/structs.gen.ts +5461 -5461
  57. package/src/generated/trader.gen.ts +309 -94
  58. package/src/generated/traderreq.gen.cc +194 -18
  59. package/src/generated/traderreq.gen.h +4 -0
  60. package/src/generated/traderspi.gen.cc +130 -10
  61. package/src/generated/traderspi.gen.h +4 -2
  62. package/src/index.ts +8 -1
  63. package/src/market-data.ts +219 -43
  64. package/src/native/arm.cc +114 -30
  65. package/src/native/arm.h +16 -4
  66. package/src/native/channel.cc +209 -81
  67. package/src/native/channel.h +65 -24
  68. package/src/native/ctp_field.h +23 -0
  69. package/src/native/mdapi.cc +621 -61
  70. package/src/native/mdspi.cc +221 -14
  71. package/src/native/mdspi.h +62 -9
  72. package/src/native/order_capability.h +75 -0
  73. package/src/native/risk.cc +2051 -205
  74. package/src/native/risk.h +450 -57
  75. package/src/native/shared_handle.h +37 -0
  76. package/src/native/snapshot.h +120 -0
  77. package/src/native/traderapi.cc +749 -170
  78. package/src/native-binding.ts +5 -1
  79. package/src/trader.ts +993 -229
  80. package/src/validation.ts +96 -0
  81. /package/{tradeapi → ctpsdk}/ThostFtdcMdApi.h +0 -0
  82. /package/{tradeapi → ctpsdk}/ThostFtdcTraderApi.h +0 -0
  83. /package/{tradeapi → ctpsdk}/ThostFtdcUserApiDataType.h +0 -0
  84. /package/{tradeapi → ctpsdk}/ThostFtdcUserApiStruct.h +0 -0
  85. /package/{tradeapi → ctpsdk}/error.dtd +0 -0
  86. /package/{tradeapi → ctpsdk}/error.xml +0 -0
  87. /package/{tradeapi → ctpsdk}/linux/thostmduserapi_se.so +0 -0
  88. /package/{tradeapi → ctpsdk}/linux/thosttraderapi_se.so +0 -0
  89. /package/{tradeapi → ctpsdk}/macos/thostmduserapi_se.framework/Versions/A/Headers/ThostFtdcMdApi.h +0 -0
  90. /package/{tradeapi → ctpsdk}/macos/thostmduserapi_se.framework/Versions/A/Headers/ThostFtdcUserApiDataType.h +0 -0
  91. /package/{tradeapi → ctpsdk}/macos/thostmduserapi_se.framework/Versions/A/Headers/ThostFtdcUserApiStruct.h +0 -0
  92. /package/{tradeapi → ctpsdk}/macos/thostmduserapi_se.framework/Versions/A/Resources/Info.plist +0 -0
  93. /package/{tradeapi → ctpsdk}/macos/thostmduserapi_se.framework/Versions/A/_CodeSignature/CodeResources +0 -0
  94. /package/{tradeapi → ctpsdk}/macos/thostmduserapi_se.framework/Versions/A/thostmduserapi_se +0 -0
  95. /package/{tradeapi → ctpsdk}/macos/thosttraderapi_se.framework/Versions/A/Headers/ThostFtdcTraderApi.h +0 -0
  96. /package/{tradeapi → ctpsdk}/macos/thosttraderapi_se.framework/Versions/A/Headers/ThostFtdcUserApiDataType.h +0 -0
  97. /package/{tradeapi → ctpsdk}/macos/thosttraderapi_se.framework/Versions/A/Headers/ThostFtdcUserApiStruct.h +0 -0
  98. /package/{tradeapi → ctpsdk}/macos/thosttraderapi_se.framework/Versions/A/Resources/Info.plist +0 -0
  99. /package/{tradeapi → ctpsdk}/macos/thosttraderapi_se.framework/Versions/A/_CodeSignature/CodeResources +0 -0
  100. /package/{tradeapi → ctpsdk}/macos/thosttraderapi_se.framework/Versions/A/thosttraderapi_se +0 -0
  101. /package/{tradeapi → ctpsdk}/windows/thostmduserapi_se.dll +0 -0
  102. /package/{tradeapi → ctpsdk}/windows/thostmduserapi_se.lib +0 -0
  103. /package/{tradeapi → ctpsdk}/windows/thosttraderapi_se.dll +0 -0
  104. /package/{tradeapi → ctpsdk}/windows/thosttraderapi_se.lib +0 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,67 @@
1
+ # [3.0.0](https://github.com/hitrading/ctp-node/compare/v2.0.0...v3.0.0) (2026-07-12)
2
+
3
+
4
+ * feat(risk)!: real-margin risk model with in-C++ data sourcing and MD snapshot LVC ([64436d5](https://github.com/hitrading/ctp-node/commit/64436d524f5c316d3da3ac85e7ded723b2d7677a))
5
+
6
+
7
+ ### BREAKING CHANGES
8
+
9
+ * RiskConfig -> RiskLimits; maxPositionCost/maxMargin ->
10
+ maxAccountMargin (now real margin, x multiplier); halt() -> haltAll() +
11
+ reduceOnly(); setMaxPosition*/setMaxInstrumentCost -> setInstrumentPositionLimit(s)
12
+ / setInstrumentMarginLimit(s); positionCost() -> accountMargin getter;
13
+ getApiVersion()/getTradingDay() -> apiVersion/tradingDay getters; seedPosition
14
+ -> seedPositions; net-mode (PosiDirection "1") positions are rejected; explicit
15
+ OrderRef must be a monotonic decimal; Node engines narrowed. See docs/MIGRATION.md.
16
+
17
+ Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
18
+
19
+ # [2.0.0](https://github.com/hitrading/ctp-node/compare/v1.2.0...v2.0.0) (2026-06-17)
20
+
21
+
22
+ ### Features
23
+
24
+ * **risk:** source CTP data in C++, real-margin cap, market-data snapshot cache ([474a4dc](https://github.com/hitrading/ctp-node/commit/474a4dcdee977597f621ed7fee1fe8265772fe44))
25
+
26
+
27
+ ### BREAKING CHANGES
28
+
29
+ * **risk:** Trader.setMultiplier and Trader.setRefPrice are removed --
30
+ contract multipliers and the price-deviation reference are now sourced in C++
31
+ (multipliers from instrument queries, the reference via trackMarketData(md)). The
32
+ position cost cap is now margin-based; prefer riskSet({ maxMargin }).
33
+
34
+ Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
35
+
36
+ # [1.2.0](https://github.com/hitrading/ctp-node/compare/v1.1.0...v1.2.0) (2026-06-16)
37
+
38
+
39
+ ### Features
40
+
41
+ * upgrade CTP SDK 6.7.2 -> 6.7.13 ([bc6812a](https://github.com/hitrading/ctp-node/commit/bc6812a9d37d86b6f34cabd0dd9bf399f7fb9d45))
42
+
43
+ # [1.1.0](https://github.com/hitrading/ctp-node/compare/v1.0.0...v1.1.0) (2026-06-16)
44
+
45
+
46
+ ### Features
47
+
48
+ * dual ESM + CommonJS build so require() works alongside import ([addeee4](https://github.com/hitrading/ctp-node/commit/addeee4db3d2e565b15347fd33f67749633038f4))
49
+
50
+ # 1.0.0 (2026-06-16)
51
+
52
+
53
+ ### Features
54
+
55
+ * first public release of @hitrading/ctp-node ([6064b58](https://github.com/hitrading/ctp-node/commit/6064b58d5cd0455b2df0f3ddc65a555bd39d2331))
56
+
57
+ # Changelog
58
+
59
+ All notable changes to **@hitrading/ctp-node** are documented here.
60
+
61
+ This file is generated and maintained automatically by
62
+ [semantic-release](https://semantic-release.gitbook.io/) from the
63
+ [Conventional Commits](https://www.conventionalcommits.org/) history — **do not
64
+ edit it by hand**. Released versions are appended below on each release; see
65
+ [RELEASING.md](RELEASING.md) for how releases work.
66
+
67
+ <!-- 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-%E2%89%A5%2018-brightgreen">
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 test suite + live full-market stress (18,111 instruments, 0 dropped)" width="780">
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 CTP callback thread only memcpy's bytes into a lock-free ring; JS decodes straight from it into plain objects at **~8M ticks/sec** (166× headroom over a 50k/sec open-auction burst).
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
- - **Pre-trade risk in C++.** Kill-switch, max order volume, max notional, price-deviation (fat-finger) guard, account-wide and per-instrument open-position cost 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.
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 ≥ 18. 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.
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** — unit tests (JS ≥ 95 %, C++ `risk`/`arm` standalone ≥ 98 %) plus the credential-gated live SimNow integration suite: [integration & testing](docs/integration.md)
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
@@ -72,6 +82,12 @@ md.on("rtn-depth-market-data", (tick) => {
72
82
  // tick is a plain object with camelCase fields
73
83
  console.log(tick.instrumentId, tick.lastPrice, tick.bidPrice1, tick.askPrice1);
74
84
  });
85
+
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:
89
+ // md.snapshot("rb2510"); // latest full depth tick (DepthMarketData) or null
90
+ // md.last("rb2510"); // latest price, 0 if none seen yet
75
91
  ```
76
92
 
77
93
  ## Quick start — trading
@@ -82,22 +98,23 @@ import { Trader } from "@hitrading/ctp-node";
82
98
  const td = new Trader("./flow/td/", "tcp://182.254.243.31:30002");
83
99
 
84
100
  // Pre-trade risk, enforced in C++ on every order:
85
- td.riskSet({ maxOrderVolume: 10, maxOrdersPerSec: 20, maxPriceDeviation: 0.02, maxPositionCost: 5_000_000 });
86
- td.trackMarketData(md); // feed live prices for the price-deviation guard
87
- td.setMaxPositions({ rb2610: 100, au2610: 10, ru2610: { long: 100, short: 20 } }); // per-instrument lot caps
88
- td.setMaxPositionCosts({ ag2608: 2_000_000, au2608: 5_000_000 }); // per-instrument cost caps
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
89
105
 
90
106
  td.on("front-connected", async () => {
91
- // One-call handshake (call again after a reconnect): authenticate → login →
92
- // confirm settlement → sync multipliers / positions / orders. Risk inputs are
93
- // fetched from CTP automatically — no manual multipliers/seeding.
94
- await td.session({ brokerId, userId, password, appId, authCode });
107
+ // One-call handshake (call again after a reconnect). Margin-rate queries need
108
+ // an explicit bounded trading universe (one CTP query per contract).
109
+ await td.session({ brokerId, userId, password, appId, authCode,
110
+ sync: { marginRates: ["rb2510", "ag2608", "au2608"] } });
95
111
 
96
112
  // ...or hand-roll it if you need finer control:
97
113
  // await td.reqAuthenticate({ brokerId, userId, appId, authCode });
98
114
  // await td.reqUserLogin({ brokerId, userId, password });
99
115
  // await td.reqSettlementInfoConfirm({ brokerId, investorId }); // real accounts
100
- // await td.syncMultipliers(); await td.syncPositions(); await td.syncOrders();
116
+ // await td.syncMultipliers(); await td.syncMarginRates(["rb2510"]);
117
+ // await td.syncOrders(); await td.syncPositions(); // held snapshot must be last
101
118
 
102
119
  // Promise-based queries return all rows:
103
120
  const positions = await td.reqQryInvestorPosition({ brokerId, investorId });
@@ -107,7 +124,7 @@ td.on("front-connected", async () => {
107
124
  // rtn-trade. orderRef is auto-assigned a unique value if you leave it blank.
108
125
  await td.reqOrderInsert({
109
126
  brokerId, investorId, instrumentId: "rb2510",
110
- direction: "0", // see Direction enum
127
+ direction: "0", combOffsetFlag: "0", // buy-open; see enums
111
128
  limitPrice: 3500, volumeTotalOriginal: 1,
112
129
  });
113
130
  });
@@ -115,8 +132,9 @@ td.on("front-connected", async () => {
115
132
  td.on("rtn-order", (order) => console.log("order update", order.orderStatus));
116
133
  td.on("rtn-trade", (trade) => console.log("filled", trade.price, trade.volume));
117
134
 
118
- // Emergency kill-switch (blocks all sends in C++ immediately):
119
- // td.halt(); / td.resume();
135
+ // Atomic modes: reduceOnly() keeps closes+cancels; haltAll() blocks closes too.
136
+ // Multi-leg combOffsetFlag values are rejected until a per-leg ledger exists.
137
+ // td.reduceOnly(); / td.haltAll(); / td.resume();
120
138
  ```
121
139
 
122
140
  ### Armed orders (latency-critical)
@@ -131,11 +149,11 @@ const armed = trader.arm(md, {
131
149
  side: "buy", // buy fires when ask ≤ trigger; sell when bid ≥ trigger
132
150
  triggerPrice: 3500,
133
151
  order: {
134
- brokerId, investorId, instrumentId: "rb2510", direction: "0",
135
- limitPrice: 3500, volumeTotalOriginal: 1, orderRef: "snipe-1",
152
+ brokerId, investorId, instrumentId: "rb2510", direction: "0", combOffsetFlag: "0",
153
+ limitPrice: 3500, volumeTotalOriginal: 1, orderRef: "900001",
136
154
  },
137
155
  });
138
- // One-shot. The ack/fill arrives via the normal rtn-order events (match orderRef).
156
+ // Removed after a successful send; refusal stays armed with bounded exponential backoff.
139
157
  // armed.disarm();
140
158
  ```
141
159
 
@@ -150,13 +168,16 @@ Direction.Sell; // "1"
150
168
  ## API shape
151
169
 
152
170
  - `new MarketData(flowPath, fronts)` / `new Trader(flowPath, fronts)` — `fronts` is a `tcp://` address or an array.
153
- - 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.
171
+ - 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.
172
+ - 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.
154
173
  - 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).
155
174
  - Streaming events use kebab-case names (`rtn-depth-market-data`, `rtn-order`, …); handlers get `(data, options)` where `options` carries `{ requestId?, isLast?, rspInfo? }`.
175
+ - 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.
156
176
  - `client.droppedRecords` reports records dropped under backpressure. Market
157
- data drops the **oldest** unread record (so you always see the freshest quote);
158
- the trader drops the **newest** instead, so a queued order/trade return is never
159
- silently discarded. Monitor it either way.
177
+ data uses bounded keep-newest staging and retains the freshest quote;
178
+ the trader uses a lossless ordered overflow queue, so order/trade/query returns
179
+ are not deliberately discarded when its 4096-slot ring fills. Sustained Trader
180
+ overload can therefore consume memory: keep handlers bounded and monitor lag.
160
181
  - `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)).
161
182
 
162
183
  ## Lifecycle: create once, reuse
@@ -177,9 +198,9 @@ md.on("front-connected", async () => { // first connect AND every reconnect
177
198
  td.on("front-connected", () => td.session({ brokerId, userId, password, appId, authCode }));
178
199
  ```
179
200
 
180
- > **Why.** `close()` calls the vendor `CThostFtdc*Api::Release()`, and the CTP
181
- > DLLs **deadlock inside `Release()` after a few `Init()`/`Release()` cycles in
182
- > one process** — a limitation of the CTP SDK itself, not of this binding. A
201
+ > **Why.** `close()` calls the vendor `CThostFtdc*Api::Release()`. Repeated
202
+ > `Init()`/`Release()` cycles have been observed to deadlock inside the Windows
203
+ > vendor DLL; the binding cannot safely recover a process from that state. A
183
204
  > "reconnect by recreate" loop will hang the whole process (and on Windows the
184
205
  > wedged process ignores `SIGTERM`, so it must be force-killed with `taskkill /F`
185
206
  > — until then it locks `build\Release\ctp.node` and breaks the next native
@@ -195,12 +216,12 @@ CTP callback thread (C++) Node event loop (JS)
195
216
  OnRtn.../OnRsp... → memcpy bytes ──► coalesced doorbell → drain whole batch
196
217
  into lock-free SPSC ring, → decode each record from the ring
197
218
  bump atomic index, ring doorbell (monomorphic generated decoder)
198
- (on overflow: MD drops oldest, → plain object → emit / resolve
199
- trader drops newest/reliable)
219
+ (on overflow: MD stages/evicts oldest, → plain object → emit / resolve
220
+ trader spills losslessly in order)
200
221
  ```
201
222
 
202
223
  Everything below the public API is generated from the CTP headers
203
- (`tradeapi/ThostFtdc*.h`) by `scripts/codegen/` — 466 struct interfaces, 318
224
+ (`ctpsdk/ThostFtdc*.h`) by `scripts/codegen/` — 519 struct interfaces, 326
204
225
  enums, field layout tables (via `offsetof`), and the full trader SPI + request
205
226
  dispatch. Run `npm run gen` after updating the headers.
206
227
 
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-%E2%89%A5%2018-brightgreen">
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 验证 —— 测试套件全绿 + 全市场实盘压测(18,111 合约,0 丢弃)" width="780">
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
- - **快。** CTP 回调线程只把字节 memcpy 进无锁环;JS 直接从环里解码成纯对象,**约 800 万 tick/秒**(相对 5 万/秒的开盘集合竞价突发有 166 倍余量)。
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
- - **盘前风控在 C++ 中。** 一键熔断、单笔最大手数、最大名义价值、价格偏离(防胖手指)、账户级与按合约的开仓持仓成本上限、按合约的最大持仓(手数、分边)、以及令牌桶限频器,都在原生代码里、报单路径上执行——JS 的 GC 停顿打不垮它们。
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 ≥ 18。**Windows 与 Linux(x64)提供预编译二进制**,这两个平台多数用户无需编译器。**macOS(及其他平台)在安装时从源码构建**,需要 C++ 工具链(macOS:Xcode Command Line Tools;Windows:VS Build Tools;Linux:clang/gcc)。CTP 共享库随插件一起打包在旁并自动解析。
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
- - **测试与覆盖率** —— 单元测试(JS ≥ 95 %、C++ `risk`/`arm` 独立 ≥ 98 %)+ 凭据门控的实盘 SimNow 集成套件:[集成与测试](docs/integration.md)
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
  ## 快速开始 —— 行情
@@ -72,6 +78,11 @@ md.on("rtn-depth-market-data", (tick) => {
72
78
  // tick 是带 camelCase 字段的纯对象
73
79
  console.log(tick.instrumentId, tick.lastPrice, tick.bidPrice1, tick.askPrice1);
74
80
  });
81
+
82
+ // MD 成功登录后,最新行情缓存在 C++ 中(一个 last-value 缓存,当前认证
83
+ // 会话内的 tick 到达 JS 前更新),因此无需在 JS 里记账即可同步取到快照:
84
+ // md.snapshot("rb2510"); // 最新完整深度行情(DepthMarketData)或 null
85
+ // md.last("rb2510"); // 最新价,尚无则为 0
75
86
  ```
76
87
 
77
88
  ## 快速开始 —— 交易
@@ -82,21 +93,22 @@ import { Trader } from "@hitrading/ctp-node";
82
93
  const td = new Trader("./flow/td/", "tcp://182.254.243.31:30002");
83
94
 
84
95
  // 盘前风控,在 C++ 中对每笔报单执行:
85
- td.riskSet({ maxOrderVolume: 10, maxOrdersPerSec: 20, maxPriceDeviation: 0.02, maxPositionCost: 5_000_000 });
86
- td.trackMarketData(md); // 为价格偏离校验喂入实时价
87
- td.setMaxPositions({ rb2610: 100, au2610: 10, ru2610: { long: 100, short: 20 } }); // 按合约手数上限
88
- td.setMaxPositionCosts({ ag2608: 2_000_000, au2608: 5_000_000 }); // 按合约成本上限
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 }); // 按合约的计划保证金上限
89
100
 
90
101
  td.on("front-connected", async () => {
91
- // 一站式握手(重连后再调一次):认证 → 登录 → 确认结算单 → 同步乘数 / 持仓 / 报单。
92
- // 风控输入自动从 CTP 拉取——无需手动设乘数/播种。
93
- await td.session({ brokerId, userId, password, appId, authCode });
102
+ // 一站式握手。保证金表需显式给出有限交易合约集(CTP 每合约一次查询)。
103
+ await td.session({ brokerId, userId, password, appId, authCode,
104
+ sync: { marginRates: ["rb2510", "ag2608", "au2608"] } });
94
105
 
95
106
  // ……或在需要更细控制时手写:
96
107
  // await td.reqAuthenticate({ brokerId, userId, appId, authCode });
97
108
  // await td.reqUserLogin({ brokerId, userId, password });
98
109
  // await td.reqSettlementInfoConfirm({ brokerId, investorId }); // 实盘账户
99
- // await td.syncMultipliers(); await td.syncPositions(); await td.syncOrders();
110
+ // await td.syncMultipliers(); await td.syncMarginRates(["rb2510"]);
111
+ // await td.syncOrders(); await td.syncPositions(); // 最后提交持仓快照
100
112
 
101
113
  // 基于 Promise 的查询返回所有行:
102
114
  const positions = await td.reqQryInvestorPosition({ brokerId, investorId });
@@ -105,7 +117,7 @@ td.on("front-connected", async () => {
105
117
  // 不返回 ack);通过 rtn-order / rtn-trade 跟踪结果。orderRef 留空会自动分配唯一值。
106
118
  await td.reqOrderInsert({
107
119
  brokerId, investorId, instrumentId: "rb2510",
108
- direction: "0", // 见 Direction 枚举
120
+ direction: "0", combOffsetFlag: "0", // 买开;见枚举
109
121
  limitPrice: 3500, volumeTotalOriginal: 1,
110
122
  });
111
123
  });
@@ -113,8 +125,10 @@ td.on("front-connected", async () => {
113
125
  td.on("rtn-order", (order) => console.log("报单更新", order.orderStatus));
114
126
  td.on("rtn-trade", (trade) => console.log("已成交", trade.price, trade.volume));
115
127
 
116
- // 应急一键熔断(在 C++ 中立即拦截所有发送):
117
- // td.halt(); / td.resume();
128
+ // 应急一键熔断(拦截增险入口,保留减仓/撤单):
129
+ // 原子模式:reduceOnly() 保留平仓与撤单;haltAll() 也拦平仓。
130
+ // 多腿 combOffsetFlag 在具备逐腿账本前会直接拒绝。
131
+ // td.reduceOnly(); / td.haltAll(); / td.resume();
118
132
  ```
119
133
 
120
134
  ### 预埋单(延迟攸关)
@@ -127,11 +141,11 @@ const armed = trader.arm(md, {
127
141
  side: "buy", // buy 在 ask ≤ trigger 时触发;sell 在 bid ≥ trigger 时触发
128
142
  triggerPrice: 3500,
129
143
  order: {
130
- brokerId, investorId, instrumentId: "rb2510", direction: "0",
131
- limitPrice: 3500, volumeTotalOriginal: 1, orderRef: "snipe-1",
144
+ brokerId, investorId, instrumentId: "rb2510", direction: "0", combOffsetFlag: "0",
145
+ limitPrice: 3500, volumeTotalOriginal: 1, orderRef: "900001",
132
146
  },
133
147
  });
134
- // 一次性。回执/成交经普通的 rtn-order 事件到达(按 orderRef 匹配)。
148
+ // 成功发送后删除;拒绝会保留并按有上限的指数退避重试。
135
149
  // armed.disarm();
136
150
  ```
137
151
 
@@ -146,10 +160,12 @@ Direction.Sell; // "1"
146
160
  ## API 形态
147
161
 
148
162
  - `new MarketData(flowPath, fronts)` / `new Trader(flowPath, fronts)` —— `fronts` 是一个 `tcp://` 地址或数组。
149
- - 请求是 camelCase 方法,接受 CTP 字段对象的 `Partial<...>` 并返回 `Promise`。`reqQry*` 以行数组 resolve;多数请求以单条响应行 resolve。
163
+ - 请求是 camelCase 方法,接受 CTP 字段对象的 `Partial<...>` 并返回 `Promise`。请求必须是严格普通对象;未知、继承或已删除字段以及 `null` 字段值会直接报错。输入数组必须稠密且每项都是显式自有值;稀疏或由原型提供的项会被拒绝。`reqQry*` 以行数组 resolve;多数请求以单条响应行 resolve。
164
+ - 同一客户端内全部 `reqQry*` / `reqQuery*` 都会在调用时快照、内部串行并限频(最多一个在途,两次尝试发送至少间隔 1100 ms),调用方不要再写 `setTimeout(1000)`。有界队列按客户端隔离;原始查询只限频,只有 `sync*` 会重试瞬时流控错误。
150
165
  - 发往交易所的 insert/action(`reqOrderInsert`、`reqOrderAction` 等)**提交成功即** resolve —— CTP 对已接受的报单不返回成功响应,只有 `rtn-order` / `rtn-trade`(用 `orderRef` 关联)。只有发送被拒(风控网关、限频、或 CTP API 错误码)才 reject。
151
166
  - 流式事件用 kebab-case 名称(`rtn-depth-market-data`、`rtn-order` 等);处理函数收到 `(data, options)`,`options` 带 `{ requestId?, isLast?, rspInfo? }`。
152
- - `client.droppedRecords` 报告背压下丢弃的记录数。行情丢弃**最旧**的未读记录(使你总能看到最新报价);交易端则丢弃**最新**的,使排队中的报单/成交回报永不被静默丢弃。两者都应监控。
167
+ - 每个合约的最新 tick 保存在 C++ 的 last-value 缓存里。成功 MD 登录会开启一个全新的空 epoch;此前,以及连接/断线、新登录或登出尝试、成功登出、关闭之后,缓存都会立即失效并清空。只有当前已认证 epoch 后续收到的 tick 才能更新缓存或驱动预埋单。`md.snapshot(instrumentId)` 同步返回最新完整 `DepthMarketData`(或 `null`),`md.last(instrumentId)` 返回最新价(无则为 0)。价格偏离校验使用同一份带 epoch 约束的缓存。
168
+ - 行情背压使用有界 keep-newest 暂存并保留最新行情,不覆盖 JS 正在解码的槽位;交易端 4096 槽满后进入有序无损队列,不主动丢回报,但持续消费停顿会增长内存。
153
169
  - `client.close()` 释放底层 CTP API。在关闭时调用**一次**——CTP 客户端是一次创建/复用的;靠重建来重连会在厂商 DLL 里死锁(见[生命周期](#生命周期-一次创建并复用))。
154
170
 
155
171
  ## 生命周期 一次创建并复用
@@ -166,7 +182,7 @@ md.on("front-connected", async () => { // 首次连接和每次重连
166
182
  td.on("front-connected", () => td.session({ brokerId, userId, password, appId, authCode }));
167
183
  ```
168
184
 
169
- > **为什么。** `close()` 调用厂商 `CThostFtdc*Api::Release()`,而 CTP DLL 在一个进程内做几次 `Init()`/`Release()` 循环后会**在 `Release()` 内部死锁**——这是 CTP SDK 本身的限制,不是本绑定的。"reconnect by recreate" 循环会卡死整个进程(且在 Windows 上卡死的进程会忽略 `SIGTERM`,必须用 `taskkill /F` 强杀——在那之前它会锁住 `build\Release\ctp.node`、使下次原生构建失败)。每个客户端只构造一次,且只在关闭时 `close()`。若一个进程内创建/关闭了异常多的客户端,会打印一次性的 `console.warn`(用 `CTP_RECREATE_WARN` 调节/禁用)。详见 [docs/native-hooks.zh-CN.md](docs/native-hooks.zh-CN.md#进程生命周期-一次创建并复用)。
185
+ > **为什么。** Windows 下反复 `Init()`/`Release()` 已观察到会卡在厂商 DLL 的 `Release()`;进程无法安全恢复。每个客户端只构造一次,且只在关闭时 `close()`。若一个进程内创建/关闭了异常多的客户端,会打印一次性的 `console.warn`(用 `CTP_RECREATE_WARN` 调节/禁用)。详见 [docs/native-hooks.zh-CN.md](docs/native-hooks.zh-CN.md#进程生命周期-一次创建并复用)。
170
186
 
171
187
  ## 架构
172
188
 
@@ -175,11 +191,11 @@ CTP 回调线程 (C++) Node 事件循环 (JS)
175
191
  OnRtn.../OnRsp... → memcpy 字节 ──► 合并的门铃 → 整批排空
176
192
  进无锁 SPSC 环、 → 从环里逐条解码
177
193
  自增原子索引、敲门铃 (单态生成的解码器)
178
- (溢出时:行情丢最旧、 → 纯对象 → emit / resolve
179
- 交易端丢最新/可靠)
194
+ (溢出时:行情暂存并淘汰最旧、 → 纯对象 → emit / resolve
195
+ 交易端有序无损溢出)
180
196
  ```
181
197
 
182
- 公开 API 之下的一切都由 CTP 头文件(`tradeapi/ThostFtdc*.h`)经 `scripts/codegen/` 生成—— 466 个结构体接口、318 个枚举、字段布局表(经 `offsetof`),以及完整的 trader SPI + 请求分发。更新头文件后运行 `npm run gen`。
198
+ 公开 API 之下的一切都由 CTP 头文件(`ctpsdk/ThostFtdc*.h`)经 `scripts/codegen/` 生成—— 519 个结构体接口、326 个枚举、字段布局表(经 `offsetof`),以及完整的 trader SPI + 请求分发。更新头文件后运行 `npm run gen`。
183
199
 
184
200
  ## 从源码构建
185
201
 
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/binding.gyp CHANGED
@@ -17,7 +17,7 @@
17
17
  ],
18
18
  "include_dirs": [
19
19
  "<!(node -p \"require('node-addon-api').include_dir\")",
20
- "tradeapi"
20
+ "ctpsdk"
21
21
  ],
22
22
  "defines": [
23
23
  "NAPI_VERSION=8",
@@ -27,7 +27,7 @@
27
27
  "cflags_cc!": [ "-fno-exceptions" ],
28
28
  "conditions": [
29
29
  ["OS=='win'", {
30
- "library_dirs": [ "<(module_root_dir)/tradeapi/windows" ],
30
+ "library_dirs": [ "<(module_root_dir)/ctpsdk/windows" ],
31
31
  "libraries": [
32
32
  "thostmduserapi_se.lib",
33
33
  "thosttraderapi_se.lib"
@@ -41,42 +41,42 @@
41
41
  {
42
42
  "destination": "<(PRODUCT_DIR)",
43
43
  "files": [
44
- "<(module_root_dir)/tradeapi/windows/thostmduserapi_se.dll",
45
- "<(module_root_dir)/tradeapi/windows/thosttraderapi_se.dll"
44
+ "<(module_root_dir)/ctpsdk/windows/thostmduserapi_se.dll",
45
+ "<(module_root_dir)/ctpsdk/windows/thosttraderapi_se.dll"
46
46
  ]
47
47
  }
48
48
  ]
49
49
  }],
50
50
  ["OS=='linux'", {
51
51
  "libraries": [
52
- "<(module_root_dir)/tradeapi/linux/thostmduserapi_se.so",
53
- "<(module_root_dir)/tradeapi/linux/thosttraderapi_se.so",
52
+ "<(module_root_dir)/ctpsdk/linux/thostmduserapi_se.so",
53
+ "<(module_root_dir)/ctpsdk/linux/thosttraderapi_se.so",
54
54
  "-Wl,-rpath,'$$ORIGIN'",
55
- "-Wl,-rpath,<(module_root_dir)/tradeapi/linux"
55
+ "-Wl,-rpath,<(module_root_dir)/ctpsdk/linux"
56
56
  ],
57
57
  "cflags_cc": [ "-std=c++17", "-fexceptions" ],
58
58
  "copies": [
59
59
  {
60
60
  "destination": "<(PRODUCT_DIR)",
61
61
  "files": [
62
- "<(module_root_dir)/tradeapi/linux/thostmduserapi_se.so",
63
- "<(module_root_dir)/tradeapi/linux/thosttraderapi_se.so"
62
+ "<(module_root_dir)/ctpsdk/linux/thostmduserapi_se.so",
63
+ "<(module_root_dir)/ctpsdk/linux/thosttraderapi_se.so"
64
64
  ]
65
65
  }
66
66
  ]
67
67
  }],
68
68
  ["OS=='mac'", {
69
69
  "include_dirs": [
70
- "<(module_root_dir)/tradeapi/macos/thostmduserapi_se.framework/Versions/A/Headers",
71
- "<(module_root_dir)/tradeapi/macos/thosttraderapi_se.framework/Versions/A/Headers"
70
+ "<(module_root_dir)/ctpsdk/macos/thostmduserapi_se.framework/Versions/A/Headers",
71
+ "<(module_root_dir)/ctpsdk/macos/thosttraderapi_se.framework/Versions/A/Headers"
72
72
  ],
73
73
  "libraries": [
74
- "-F<(module_root_dir)/tradeapi/macos",
74
+ "-F<(module_root_dir)/ctpsdk/macos",
75
75
  "-framework thostmduserapi_se",
76
76
  "-framework thosttraderapi_se",
77
77
  "-liconv",
78
78
  "-Wl,-rpath,@loader_path",
79
- "-Wl,-rpath,<(module_root_dir)/tradeapi/macos"
79
+ "-Wl,-rpath,<(module_root_dir)/ctpsdk/macos"
80
80
  ],
81
81
  "xcode_settings": {
82
82
  "GCC_ENABLE_CPP_EXCEPTIONS": "YES",