@hitrading/ctp-node 2.0.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 (79) hide show
  1. package/CHANGELOG.md +67 -0
  2. package/README.md +47 -32
  3. package/README.zh-CN.md +37 -27
  4. package/RELEASING.md +78 -0
  5. package/dist/client.d.ts +36 -15
  6. package/dist/client.d.ts.map +1 -1
  7. package/dist/client.js +234 -62
  8. package/dist/client.js.map +1 -1
  9. package/dist/codec.d.ts.map +1 -1
  10. package/dist/codec.js +84 -19
  11. package/dist/codec.js.map +1 -1
  12. package/dist/generated/structs.gen.d.ts +5461 -5461
  13. package/dist/generated/structs.gen.d.ts.map +1 -1
  14. package/dist/generated/trader.gen.d.ts.map +1 -1
  15. package/dist/generated/trader.gen.js +788 -94
  16. package/dist/generated/trader.gen.js.map +1 -1
  17. package/dist/index.cjs +1875 -415
  18. package/dist/index.d.cts +1 -1
  19. package/dist/index.d.ts +1 -1
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/index.js.map +1 -1
  22. package/dist/market-data.d.ts +41 -24
  23. package/dist/market-data.d.ts.map +1 -1
  24. package/dist/market-data.js +148 -29
  25. package/dist/market-data.js.map +1 -1
  26. package/dist/native-binding.d.ts.map +1 -1
  27. package/dist/native-binding.js +4 -0
  28. package/dist/native-binding.js.map +1 -1
  29. package/dist/trader.d.ts +111 -71
  30. package/dist/trader.d.ts.map +1 -1
  31. package/dist/trader.js +774 -180
  32. package/dist/trader.js.map +1 -1
  33. package/dist/validation.d.ts +27 -0
  34. package/dist/validation.d.ts.map +1 -0
  35. package/dist/validation.js +85 -0
  36. package/dist/validation.js.map +1 -0
  37. package/docs/API.md +1437 -0
  38. package/docs/API.zh-CN.md +1278 -0
  39. package/docs/MIGRATION.md +54 -0
  40. package/docs/assets/validation.svg +27 -0
  41. package/docs/integration.md +60 -0
  42. package/docs/native-hooks.md +281 -0
  43. package/docs/native-hooks.zh-CN.md +205 -0
  44. package/docs/troubleshooting.md +257 -0
  45. package/docs/troubleshooting.zh-CN.md +220 -0
  46. package/package.json +12 -4
  47. package/prebuilds/linux-x64/@hitrading+ctp-node.node +0 -0
  48. package/prebuilds/win32-x64/@hitrading+ctp-node.node +0 -0
  49. package/scripts/bench-decode.mjs +37 -0
  50. package/scripts/bench-fullmarket-offline.mjs +207 -0
  51. package/scripts/stress-fullmarket.mjs +255 -0
  52. package/src/addon.cc +2 -2
  53. package/src/client.ts +255 -65
  54. package/src/codec.ts +86 -19
  55. package/src/generated/structs.gen.ts +5461 -5461
  56. package/src/generated/trader.gen.ts +309 -94
  57. package/src/generated/traderreq.gen.cc +194 -18
  58. package/src/generated/traderreq.gen.h +4 -0
  59. package/src/generated/traderspi.gen.cc +129 -15
  60. package/src/generated/traderspi.gen.h +4 -2
  61. package/src/index.ts +8 -1
  62. package/src/market-data.ts +199 -46
  63. package/src/native/arm.cc +114 -30
  64. package/src/native/arm.h +16 -4
  65. package/src/native/channel.cc +209 -81
  66. package/src/native/channel.h +65 -24
  67. package/src/native/ctp_field.h +23 -0
  68. package/src/native/mdapi.cc +582 -69
  69. package/src/native/mdspi.cc +219 -16
  70. package/src/native/mdspi.h +59 -10
  71. package/src/native/order_capability.h +75 -0
  72. package/src/native/risk.cc +2030 -213
  73. package/src/native/risk.h +431 -78
  74. package/src/native/shared_handle.h +37 -0
  75. package/src/native/snapshot.h +75 -16
  76. package/src/native/traderapi.cc +753 -124
  77. package/src/native-binding.ts +4 -0
  78. package/src/trader.ts +971 -204
  79. package/src/validation.ts +96 -0
@@ -0,0 +1,257 @@
1
+ <!-- LANG-SWITCH -->
2
+ **English** · [简体中文](troubleshooting.zh-CN.md)
3
+
4
+ # Troubleshooting & FAQ
5
+
6
+ Common failures and how to fix them. See also the [API reference](API.md) and the
7
+ [native internals](native-hooks.md).
8
+
9
+ - [Connection](#connection) · [Login / authentication](#login--authentication) · [Queries & rate limits](#queries--rate-limits)
10
+ - [Order rejections](#order-rejections) · [Limit-up / limit-down](#limit-up--limit-down) · [Performance & memory](#performance--memory)
11
+ - [Lifecycle & reconnect](#lifecycle--reconnect) · [Build & install](#build--install) · [Error-code reference](#error-code-reference)
12
+
13
+ ---
14
+
15
+ ## Connection
16
+
17
+ ### `front-connected` never fires / no ticks arrive
18
+
19
+ The front address is wrong or unreachable. SimNow **rotates its fronts** — the
20
+ old `180.168.146.187:10201/10211` are dead; as of writing the live site is
21
+ **上期技术-电信二**: trade `tcp://182.254.243.31:30002`, md `tcp://182.254.243.31:30012`.
22
+
23
+ 1. Find your current fronts in the SimNow client under **代理及服务器配置** (the
24
+ 交易服务器地址 / 行情服务器地址 it shows, with a live ping).
25
+ 2. Pass them explicitly: `new Trader("./flow/td/", "tcp://HOST:PORT")` /
26
+ `new MarketData("./flow/md/", "tcp://HOST:PORT")`.
27
+ 3. Confirm raw TCP reachability first:
28
+ ```js
29
+ require("net").connect({ host: "182.254.243.31", port: 30002, timeout: 5000 })
30
+ .on("connect", () => console.log("TCP OPEN")).on("error", (e) => console.log(e.code));
31
+ ```
32
+ `timeout`/`ECONNREFUSED` = wrong front or blocked egress (VPN/firewall), not a
33
+ binding problem.
34
+
35
+ ### Connects but no market data
36
+
37
+ Connected ≠ subscribed. You must `await md.login(...)` then `md.subscribe([...])`
38
+ inside the `front-connected` handler. Also: a contract only ticks when it trades —
39
+ outside its session (e.g. night-session-only products during the day) it is
40
+ silent even when subscribed.
41
+
42
+ ---
43
+
44
+ ## Login / authentication
45
+
46
+ | Symptom | Cause | Fix |
47
+ |---|---|---|
48
+ | login rejects, "CTP:不合法的登录" | wrong brokerId / userId / password | SimNow brokerId is `9999`; check the account. |
49
+ | `reqAuthenticate` fails | wrong appId / authCode (terminal authentication) | SimNow: `appId: "simnow_client_test"`, `authCode: "0000000000000000"`. Real accounts use the broker-issued values. |
50
+ | "CTP:还没有初始化" | called a request before `front-connected` | do login/queries inside the `front-connected` handler. |
51
+ | orders rejected right after login on a real account | settlement statement not confirmed | call `reqSettlementInfoConfirm(...)` (or just use `session()`, which does it). |
52
+ | first query after login is empty / rejected | account/front not ready yet | use the `sync*` helpers (they retry transient flow-control/empty readiness); raw queries are paced but not automatically retried. |
53
+
54
+ `session()` does authenticate → login → confirm → sync in the right order with
55
+ the right retries — prefer it over hand-rolling unless you need fine control.
56
+
57
+ ```ts
58
+ td.on("front-connected", () => td.session({
59
+ brokerId: "9999", userId: "id", password: "pw",
60
+ appId: "simnow_client_test", authCode: "0000000000000000",
61
+ }).catch((e) => console.error("session failed", e.errorId, e.errorMsg)));
62
+ ```
63
+
64
+ ---
65
+
66
+ ## Queries & rate limits
67
+
68
+ CTP throttles **queries to ~1 per second** per session. Issuing them too fast (or
69
+ too soon after login) returns empty or rejects with a flow-control error.
70
+
71
+ - Use `syncMultipliers()` / `syncOrders()` / `syncPositions()` — they retry
72
+ transient `-2`/`-3` flow-control failures and required empty cold-start data.
73
+ - Do **not** add `setTimeout(1000)` around raw `reqQry*` / `reqQuery*` calls.
74
+ Every query on the same client is snapshotted at invocation and enters one
75
+ FIFO scheduler: at most one is in flight and attempted sends are at least
76
+ 1100 ms apart. A disconnect/login/logout invalidates unsent old-session work.
77
+ - Scheduling is per `Trader`/`MarketData` instance, not process-global. If
78
+ several instances share a broker/account-wide quota, coordinate those at the
79
+ application gateway. The queue is bounded at 256; await earlier work rather
80
+ than creating an hours-long `Promise.all` backlog.
81
+ - Send-side flow control also applies to **orders**: CTP caps the send rate.
82
+ Configure `setRiskLimits({ maxOrdersPerSec, orderBurst })` so the C++ token bucket
83
+ paces you under the limit instead of getting exchange rejections.
84
+
85
+ The send-return codes for this: `-2` = too many unhandled requests in flight,
86
+ `-3` = per-second send rate exceeded (see [reference](#error-code-reference)).
87
+
88
+ ---
89
+
90
+ ## Order rejections
91
+
92
+ `reqOrderInsert()` **resolves on submission** and only rejects if the *send* is
93
+ refused; an order rejected by the **exchange** comes back as an
94
+ `err-rtn-order-insert` event (with `options.rspInfo.errorMsg`), and status
95
+ changes arrive as `rtn-order`. Watch both.
96
+
97
+ | `errorMsg` (CTP, Chinese) | Meaning | Fix |
98
+ |---|---|---|
99
+ | `不允许重复报单` | duplicate / non-numeric `OrderRef` | **Don't pass your own `orderRef`** — leave it blank and the Trader auto-assigns a unique numeric ref (seeded past the broker's `maxOrderRef`). If you must set it, use a strictly increasing number. |
100
+ | `资金不足` | insufficient margin | reduce size, or close other positions; check `reqQryTradingAccount().available`. |
101
+ | `平仓量超过持仓量` / `可平仓位不足` | closing more than you hold | check the position; on SHFE/INE pick the right offset (close-today vs close-yesterday). |
102
+ | `平今/平昨` errors | wrong offset flag on SHFE/INE | use `OffsetFlag.CloseToday` (`"3"`) vs `OffsetFlag.CloseYesterday` (`"4"`), not plain `Close`. |
103
+ | `报单价格超出涨跌停板` | price beyond the daily limit | clamp the price to within ±limit; for a resting (non-filling) order use a few ticks off the touch, not far. |
104
+ | `报单字段有误` | malformed `InputOrder` | include the full field set CTP needs (`combHedgeFlag`, `orderPriceType`, `timeCondition`, `volumeCondition`, `contingentCondition`, `forceCloseReason`, …). See the [order recipe](API.md#recipes). |
105
+ | `CTP:撤单找不到对应报单` | cancelling an order that's already gone | the order already filled/cancelled; ignore. |
106
+
107
+ If your own pre-trade risk blocked it, the **rejected Promise** message says so
108
+ (`blocked by pre-trade risk: ...`, `rate limited`, `position ... limit`) — that's
109
+ your `setRiskLimits`/`setInstrumentPositionLimit`/risk mode, not the exchange.
110
+
111
+ ---
112
+
113
+ ## Limit-up / limit-down
114
+
115
+ At **limit-down** there are no bids, and at **limit-up** no asks. CTP fills the
116
+ empty side with the sentinel `DBL_MAX` (`Number.MAX_VALUE`, ~1.8e308), **not** 0.
117
+
118
+ - **Armed triggers** already guard this: a sell arms on `bid ≥ trigger`, and the
119
+ binding ignores a `DBL_MAX` bid so it can't fire a panic sell at limit-down
120
+ (likewise buys vs a `DBL_MAX` ask).
121
+ - **Your own logic must guard it too** — before using `tick.bidPrice1` /
122
+ `lastPrice`, check `px > 0 && px < 1e300`. The risk engine's reference-price,
123
+ cost, and notional paths already reject the sentinel.
124
+ - **Cancelling at limit-down works** — `reqOrderAction` isn't price-gated, and
125
+ both `reduceOnly()` and `haltAll()` deliberately leave cancels open so you can
126
+ always pull resting orders while new inserts are restricted.
127
+
128
+ ```ts
129
+ md.on("rtn-depth-market-data", (t) => {
130
+ if (!(t.bidPrice1 > 0) || t.bidPrice1 >= 1e300) return; // no bid (limit-down)
131
+ // ...safe to use the quote
132
+ });
133
+ ```
134
+
135
+ ---
136
+
137
+ ## Performance & memory
138
+
139
+ In one historical live sample (not continuous soak coverage), subscribing the
140
+ **entire market** (SimNow, 18,111 instruments, per-tick SMA on every one +
141
+ timer-driven order/cancel) plateaued at ~124 MB RSS, CPU 0–2%, **0 dropped
142
+ records**, ~3 µs/tick strategy cost and normal event-loop lag.
143
+
144
+ The exact `3.0.0-rc.1` candidate also has a reproducible offline probe:
145
+
146
+ ```bash
147
+ npm run bench:fullmarket
148
+ ```
149
+
150
+ On 2026-07-11, Node 24.18.0 / Windows 11 / Intel Core Ultra 9 285K (24 logical
151
+ CPUs, 96 GiB RAM), the full path used a native background callback thread and
152
+ the real `MdSpi`: 18,111 distinct `InstrumentID` values, the native snapshot
153
+ lock/cache, channel, generated 46-field decoder, EventEmitter, and 18,111
154
+ string-keyed 20-tick rolling states looked up through each real
155
+ `tick.instrumentId`.
156
+
157
+ - 50k/s for 5 s: 250,000/250,000 delivered, 0 drops, 129 MiB peak RSS, 1.55%
158
+ of one CPU core, 6.1% event-loop utilization.
159
+ - 500k/s for 30 s: 15,000,000/15,000,000 delivered, 0 drops, 247 MiB peak RSS,
160
+ 6.62% of one CPU core (0.28% of the 24-core machine), 26.2% ELU. The run
161
+ stayed below that RSS ceiling; 30 seconds is not a proof against a longer-term leak.
162
+ - 1M/s for 3 s: 2,994,819 delivered and 5,181 keep-newest drops (0.173%),
163
+ 242 MiB peak RSS, 73.8% of one core and 64.3% ELU. This is beyond the measured
164
+ zero-loss envelope.
165
+ - One back-to-back callback storm containing one tick for every 18,111 symbol:
166
+ 18,111/18,111 delivered, 0 drops, drained in about 10.9 ms.
167
+
168
+ This verifies at least 10x zero-loss throughput over a 50k/s reference load on
169
+ that host; it does not promise the same margin on other CPUs or with a heavier
170
+ handler. The producer includes the binding's native callback loop but not CTP
171
+ network parsing. A CTP callback stream is serial, so “simultaneous” instruments
172
+ are modeled as the tight back-to-back callback storm above. The historical live
173
+ run is supporting evidence, not a current-candidate soak. Re-run
174
+ `scripts/stress-fullmarket.mjs` for 30–60 minutes during an opening/auction with
175
+ the exact packaged artifact before production acceptance.
176
+
177
+ - **`droppedRecords > 0` and climbing** = your JS handlers can't keep up and the
178
+ market-data ring is shedding the oldest ticks ("行情挤压"). Move heavy work off
179
+ the tick path (batch it, or offload to a worker). Trader callbacks spill into
180
+ an ordered lossless queue; prolonged handler stalls therefore grow memory
181
+ instead of dropping order/trade returns.
182
+ - **Memory grows unbounded** usually means the app retains objects. It can also
183
+ mean the Trader event loop is continuously slower than callback production:
184
+ its correctness-first overflow queue is lossless and intentionally unbounded.
185
+ Keep handlers and retained state bounded.
186
+ - The fixed MD ring is ~21.2 MiB and its bounded keep-newest tick staging can
187
+ temporarily hold roughly another ring of payloads; non-droppable MD control
188
+ responses are lossless and therefore are not part of that tick bound. The
189
+ fixed Trader ring is ~10.6 MiB. MD tick overload remains bounded by dropping
190
+ oldest ticks and retaining the freshest;
191
+ the Trader's lossless overflow is intentionally unbounded and can reach GiB
192
+ if JS stops consuming for long enough.
193
+ - **The big `reqQryInstrument({})`** (all ~18k instruments) streams over ~30–50 s
194
+ and resolves as one array — expected; budget for that cold-start time.
195
+
196
+ ---
197
+
198
+ ## Lifecycle & reconnect
199
+
200
+ **Never reconnect by destroying and recreating a client.** The CTP vendor DLL
201
+ deadlocks inside `Release()` after a few `Init()`/`Release()` cycles per process.
202
+ CTP reconnects on its own — re-run your handshake **in place** on every
203
+ `front-connected`. Call `close()` once, at shutdown. See
204
+ [native-hooks.md → Process lifecycle](native-hooks.md#process-lifecycle-create-once-reuse).
205
+
206
+ - A one-time `console.warn` (`CTP_RECREATE_WARN`) fires if you create/close too
207
+ many clients in one process — heed it.
208
+ - **Windows: the process hangs on exit / can't be killed** — a wedged CTP
209
+ `Release()` ignores `SIGTERM`; `taskkill /F /PID <pid>`. Until it dies it locks
210
+ `build\Release\ctp.node` (see build errors below).
211
+
212
+ ---
213
+
214
+ ## Build & install
215
+
216
+ | Symptom | Cause | Fix |
217
+ |---|---|---|
218
+ | `LNK1104: cannot open file ... ctp.node` | a wedged/zombie `node` process still holds the addon | find and `taskkill /F` the stray node process, then rebuild. |
219
+ | `fatal error LNK1103: 调试信息损坏` | stale/corrupt build object (e.g. interrupted/parallel build) | `npx node-gyp rebuild` (clean rebuild). |
220
+ | `MODULE_NOT_FOUND: node-addon-api` on a consumer install | source build with the build deps missing | fixed — `node-addon-api`/`node-gyp` are runtime `dependencies`; on an unshipped platform a C++ toolchain + Python are still required. |
221
+ | `.node` won't load on macOS arm64 / linux arm64 | no prebuild for that platform | it builds from source on install; ensure a toolchain is present. |
222
+ | C4819 codepage warning during build | Chinese comments in `.cc` under a GBK code page | harmless; ignore. |
223
+
224
+ ---
225
+
226
+ ## Error-code reference
227
+
228
+ **Send-return codes** (the value `reqXxx` passes back; for resolve-on-submit
229
+ methods like `reqOrderInsert` a non-zero one rejects the Promise):
230
+
231
+ | Code | Meaning |
232
+ |---|---|
233
+ | `0` | accepted / sent |
234
+ | `-1` | network send failed (not connected, or CTP refused the send) |
235
+ | `-2` | too many unhandled requests in flight |
236
+ | `-3` | per-second send rate exceeded (CTP flow control) |
237
+ | `-10001` | blocked by this binding's pre-trade risk (the rejection message carries the specific cause) |
238
+ | `-10002` | blocked by the configured open or close rate limiter |
239
+ | `-10003` | blocked by a margin cap (`maxAccountMargin` / `setInstrumentMarginLimit`; by-money + by-volume schedule) |
240
+ | `-10004` | blocked by a position-**volume** cap (`setInstrumentPositionLimit`) |
241
+ | `-10005` | duplicate `OrderRef` in this front/session |
242
+ | `-10006` | complex insert cannot traverse configured local risk and failed closed |
243
+ | `-10007` | required price/multiplier/margin metadata missing or relative |
244
+ | `-10008` | invalid order direction or offset flag |
245
+ | `-10009` | market-data login/logout refused: a session transition is already in flight or ambiguous (await it, or reconnect after a timeout) |
246
+
247
+ **Exchange/broker errors** arrive as `rspInfo` (`{ errorId, errorMsg }`) on the
248
+ relevant event, and on a rejected request Promise as `err.errorId` /
249
+ `err.errorMsg`. `errorId 0` = success; non-zero carries a Chinese `errorMsg`
250
+ (GB18030-decoded for you) — the message is the reliable, human-readable cause, so
251
+ log it. Common ones are in the [order-rejection](#order-rejections) and
252
+ [login](#login--authentication) tables above.
253
+
254
+ ```ts
255
+ try { await td.reqUserLogin({ brokerId: "9999", userId: "id", password: "bad" }); }
256
+ catch (e) { console.error(`CTP ${e.errorId}: ${e.errorMsg}`); }
257
+ ```
@@ -0,0 +1,220 @@
1
+ <!-- LANG-SWITCH -->
2
+ [English](troubleshooting.md) · **简体中文**
3
+
4
+ # 故障排查与 FAQ
5
+
6
+ 常见故障及修复方法。另见 [API 参考](API.zh-CN.md) 与 [原生内部](native-hooks.zh-CN.md)。
7
+
8
+ - [连接](#连接) · [登录 / 认证](#登录--认证) · [查询与限频](#查询与限频)
9
+ - [报单被拒](#报单被拒) · [涨停 / 跌停](#涨停--跌停) · [性能与内存](#性能与内存)
10
+ - [生命周期与重连](#生命周期与重连) · [构建与安装](#构建与安装) · [错误码参考](#错误码参考)
11
+
12
+ ---
13
+
14
+ ## 连接
15
+
16
+ ### `front-connected` 从不触发 / 收不到行情
17
+
18
+ 前置地址错误或不可达。SimNow **会轮换前置**——旧的 `180.168.146.187:10201/10211` 已停用;
19
+ 撰写时在用的站点是 **上期技术-电信二**:交易 `tcp://182.254.243.31:30002`、行情
20
+ `tcp://182.254.243.31:30012`。
21
+
22
+ 1. 在 SimNow 客户端的 **代理及服务器配置** 里查看你当前的前置(它显示的「交易服务器地址 / 行情
23
+ 服务器地址」及实时延迟)。
24
+ 2. 显式传入:`new Trader("./flow/td/", "tcp://HOST:PORT")` /
25
+ `new MarketData("./flow/md/", "tcp://HOST:PORT")`。
26
+ 3. 先确认裸 TCP 可达:
27
+ ```js
28
+ require("net").connect({ host: "182.254.243.31", port: 30002, timeout: 5000 })
29
+ .on("connect", () => console.log("TCP OPEN")).on("error", (e) => console.log(e.code));
30
+ ```
31
+ `timeout`/`ECONNREFUSED` = 前置错误或出网被挡(VPN/防火墙),不是绑定的问题。
32
+
33
+ ### 连上了但没有行情
34
+
35
+ 连上 ≠ 已订阅。你必须在 `front-connected` 处理函数里先 `await md.login(...)`,再
36
+ `md.subscribe([...])`。另外:合约只有在交易时才有 tick——不在其交易时段(如只在夜盘交易的品种在
37
+ 白天)时,即使订阅了也静默。
38
+
39
+ ---
40
+
41
+ ## 登录 / 认证
42
+
43
+ | 症状 | 原因 | 修复 |
44
+ |---|---|---|
45
+ | 登录被拒,"CTP:不合法的登录" | brokerId / userId / password 错误 | SimNow 的 brokerId 是 `9999`;核对账户。 |
46
+ | `reqAuthenticate` 失败 | appId / authCode 错误(终端认证) | SimNow:`appId: "simnow_client_test"`、`authCode: "0000000000000000"`。实盘用券商下发的值。 |
47
+ | "CTP:还没有初始化" | 在 `front-connected` 之前就发了请求 | 在 `front-connected` 处理函数里做登录/查询。 |
48
+ | 实盘登录后报单立刻被拒 | 未确认结算单 | 调 `reqSettlementInfoConfirm(...)`(或直接用 `session()`,它会做)。 |
49
+ | 登录后第一笔查询为空/被拒 | 查得太早(冷启动) | 用 `sync*` 辅助方法(它们会穿越限频重试),或等约 1 秒。 |
50
+
51
+ `session()` 会按正确顺序、带正确重试地完成 认证 → 登录 → 确认 → 同步——除非你要精细控制,否则优先
52
+ 用它而非手写。
53
+
54
+ ```ts
55
+ td.on("front-connected", () => td.session({
56
+ brokerId: "9999", userId: "id", password: "pw",
57
+ appId: "simnow_client_test", authCode: "0000000000000000",
58
+ }).catch((e) => console.error("session 失败", e.errorId, e.errorMsg)));
59
+ ```
60
+
61
+ ---
62
+
63
+ ## 查询与限频
64
+
65
+ CTP 对每个会话的**查询限频约每秒一次**。查得太快(或登录后太早)会返回空或以限流错误被拒。
66
+
67
+ - 使用 `syncMultipliers()` / `syncOrders()` / `syncPositions()`——它们会重试瞬时 `-2`/`-3`
68
+ 限流错误,以及必须存在但冷启动时暂为空的数据。
69
+ - 原始 `reqQry*` / `reqQuery*` **不需要**调用方再写 `setTimeout(1000)`。同一个客户端内的所有查询
70
+ 在调用时即快照参数,并进入一个 FIFO 调度器:最多一个查询在途,两次尝试发送至少间隔 1100 ms;
71
+ 断线、登录或登出会拒绝旧会话中尚未发送的查询。
72
+ - 调度器按 `Trader`/`MarketData` 实例隔离,并非进程全局。若多个实例共享券商/账户级配额,仍需由
73
+ 应用网关统一协调。队列上限为 256;应 await 较早的查询,不要制造持续数小时的 `Promise.all` 堆积。
74
+ - 发送侧限频也作用于**报单**:CTP 限制发送速率。配置
75
+ `setRiskLimits({ maxOrdersPerSec, orderBurst })`,让 C++ 令牌桶把你的发送节流到限制以下,而不是吃
76
+ 交易所拒单。
77
+ - 对应的发送返回码:`-2` = 在途未处理请求过多,`-3` = 每秒发送速率超限(见[参考](#错误码参考))。
78
+
79
+ ---
80
+
81
+ ## 报单被拒
82
+
83
+ `reqOrderInsert()` **提交成功即 resolve**,仅当*发送*被拒时才 reject;被**交易所**拒绝的报单以
84
+ `err-rtn-order-insert` 事件回来(带 `options.rspInfo.errorMsg`),状态变化通过 `rtn-order` 到达。
85
+ 两者都要监听。
86
+
87
+ | `errorMsg`(CTP 中文) | 含义 | 修复 |
88
+ |---|---|---|
89
+ | `不允许重复报单` | `OrderRef` 重复 / 非数字 | **不要自己传 `orderRef`**——留空,Trader 会自动分配唯一数字 ref(播种在券商 `maxOrderRef` 之上)。若必须设置,用严格递增的数字。 |
90
+ | `资金不足` | 保证金不足 | 减小手数,或平掉其他持仓;查 `reqQryTradingAccount().available`。 |
91
+ | `平仓量超过持仓量` / `可平仓位不足` | 平的比持有的多 | 核对持仓;SHFE/INE 上选对开平(平今 vs 平昨)。 |
92
+ | 平今/平昨 相关错误 | SHFE/INE 上开平标志错误 | 用 `OffsetFlag.CloseToday`(`"3"`)vs `OffsetFlag.CloseYesterday`(`"4"`),而非普通 `Close`。 |
93
+ | `报单价格超出涨跌停板` | 价格超出当日涨跌停 | 把价格夹到 ±限内;要挂着不成交的单,用离盘口几个 tick 的价格,而非很远。 |
94
+ | `报单字段有误` | `InputOrder` 字段不全 | 带上 CTP 需要的完整字段(`combHedgeFlag`、`orderPriceType`、`timeCondition`、`volumeCondition`、`contingentCondition`、`forceCloseReason`……)。见[下单示例](API.zh-CN.md#实战示例)。 |
95
+ | `CTP:撤单找不到对应报单` | 撤一笔已经没了的单 | 该单已成交/已撤;忽略即可。 |
96
+
97
+ 如果是你自己的盘前风控拦的,**被 reject 的 Promise** 消息会说明
98
+ (`blocked by pre-trade risk: ...`、`rate limited`、`position ... limit`)——那是你的
99
+ `setRiskLimits`/`setInstrumentPositionLimit`/风控模式,不是交易所。
100
+
101
+ ---
102
+
103
+ ## 涨停 / 跌停
104
+
105
+ **跌停**时没有买盘,**涨停**时没有卖盘。CTP 用哨兵值 `DBL_MAX`(`Number.MAX_VALUE`,约 1.8e308)
106
+ 填充空的那一边,**而非** 0。
107
+
108
+ - **预埋触发器**已对此防护:卖单在 `bid ≥ trigger` 时触发,绑定会忽略 `DBL_MAX` 的 bid,因此不会
109
+ 在跌停时触发恐慌性卖出(买单对 `DBL_MAX` 的 ask 同理)。
110
+ - **你自己的逻辑也必须防护**——使用 `tick.bidPrice1` / `lastPrice` 前,检查
111
+ `px > 0 && px < 1e300`。风控引擎的参考价、成本、名义价值路径已经拒绝该哨兵值。
112
+ - **跌停时撤单可用**——`reqOrderAction` 不受价格限制,`reduceOnly()` 与 `haltAll()` 都故意保持撤单
113
+ 开放,因此限制新报单时你仍能撤回挂单。
114
+
115
+ ```ts
116
+ md.on("rtn-depth-market-data", (t) => {
117
+ if (!(t.bidPrice1 > 0) || t.bidPrice1 >= 1e300) return; // 没有买盘(跌停)
118
+ // ……可以安全使用该报价
119
+ });
120
+ ```
121
+
122
+ ---
123
+
124
+ ## 性能与内存
125
+
126
+ 一次历史实测(不是持续浸泡覆盖)订阅了**全市场**(SimNow,18,111 个合约,并做逐 tick SMA +
127
+ 定时下单/撤单):RSS 稳定在约 124 MB,CPU 0–2%,**0 条丢弃**,策略约 3 µs/tick,事件循环延迟正常。
128
+
129
+ 确切的 `3.0.0-rc.1` 候选版还提供可复现的离线探针:
130
+
131
+ ```bash
132
+ npm run bench:fullmarket
133
+ ```
134
+
135
+ 2026-07-11 在 Node 24.18.0 / Windows 11 / Intel Core Ultra 9 285K(24 个逻辑 CPU、96 GiB 内存)上,
136
+ 完整路径由原生后台线程调用真实 `MdSpi`:18,111 个不同 `InstrumentID`、原生快照锁/缓存、队列、
137
+ 生成的 46 字段解码器、EventEmitter,以及通过每条真实 `tick.instrumentId` 查找的 18,111 份字符串键
138
+ 20-tick 滚动状态。
139
+
140
+ - 5 万/s、5 秒:250,000/250,000 全收,0 丢弃;峰值 RSS 129 MiB;占单核 1.55%,ELU 6.1%。
141
+ - 50 万/s、30 秒:15,000,000/15,000,000 全收,0 丢弃;峰值 RSS 247 MiB;占单核 6.62%
142
+ (整台 24 核机器的 0.28%),ELU 26.2%。该 30 秒窗口始终低于这一 RSS 峰值,但它不能单独证明
143
+ 更长时间绝无泄漏。
144
+ - 100 万/s、3 秒:交付 2,994,819,keep-newest 丢弃 5,181(0.173%);峰值 RSS 242 MiB;
145
+ 占单核 73.8%,ELU 64.3%。这已超出实测零丢失区间。
146
+ - 一次把 18,111 个合约各 1 tick 紧密连续回调:18,111/18,111 全收、0 丢弃,约 10.9 ms 排空。
147
+
148
+ 这证明该机器相对 5 万/s 参考负载至少有 10 倍的零丢失吞吐余量,不保证其他 CPU 或更重处理函数仍有
149
+ 同样余量。producer 包含本 binding 的原生回调循环,但不含 CTP 网络解析。CTP 回调流本身是串行的,
150
+ 所以所谓「同时」按上述紧密连续 callback storm 建模。历史实盘只能作旁证,不能代替当前候选制品浸泡;
151
+ 生产验收前仍应在开盘/集合竞价对确切打包制品运行 `scripts/stress-fullmarket.mjs` 30–60 分钟。
152
+
153
+ - **`droppedRecords > 0` 且持续上涨** = 你的 JS 处理函数跟不上,行情环正在丢弃最旧的 tick
154
+ (「行情挤压」)。把重活移出 tick 路径(批处理,或交给 worker)。交易端回报进入有序无损队列,
155
+ 长时间阻塞处理函数会增长内存而不是丢回报。
156
+ - **内存无上限增长** 通常是应用保留对象,也可能是交易端消费持续慢于回报生产。只保留有界状态,
157
+ 并让交易回报处理函数保持短小。
158
+ - 行情固定环约 21.2 MiB;有界 keep-newest tick 暂存区最多还会暂存约一环 payload。不可丢的 MD 控制
159
+ 回报不计入 tick 上限。交易固定环约 10.6 MiB。行情过载会丢最旧 tick、保留最新值,因此 tick 有界;
160
+ 交易端为不丢回报采用无界溢出区,若 JS 长时间停止消费,内存理论上可以增长到 GiB 级。
161
+ - **大的 `reqQryInstrument({})`**(约 1.8 万个合约)会流式传输约 30–50 秒并以一个数组 resolve——
162
+ 正常现象;为这段冷启动时间留预算。
163
+
164
+ ---
165
+
166
+ ## 生命周期与重连
167
+
168
+ **绝不要靠销毁再重建客户端来重连。** CTP 厂商 DLL 在一个进程内做几次 `Init()`/`Release()` 循环
169
+ 后会在 `Release()` 内部死锁。CTP 会自行重连——在每次 `front-connected` **原地**重跑握手。`close()`
170
+ 只在关闭时调一次。见 [native-hooks.zh-CN.md → 进程生命周期](native-hooks.zh-CN.md#进程生命周期-一次创建并复用)。
171
+
172
+ - 若你在一个进程内创建/关闭了过多客户端,会打印一次性的 `console.warn`(`CTP_RECREATE_WARN`)——
173
+ 请重视它。
174
+ - **Windows:进程退出时卡住 / 杀不掉**——卡死的 CTP `Release()` 会忽略 `SIGTERM`;用
175
+ `taskkill /F /PID <pid>`。在它死掉前会一直占着 `build\Release\ctp.node`(见下方构建错误)。
176
+
177
+ ---
178
+
179
+ ## 构建与安装
180
+
181
+ | 症状 | 原因 | 修复 |
182
+ |---|---|---|
183
+ | `LNK1104: cannot open file ... ctp.node` | 一个卡死/僵尸 `node` 进程还占着该插件 | 找到并 `taskkill /F` 掉游离的 node 进程,再重新构建。 |
184
+ | `fatal error LNK1103: 调试信息损坏` | 陈旧/损坏的构建产物(如被中断/并行构建) | `npx node-gyp rebuild`(干净重建)。 |
185
+ | 使用方安装时 `MODULE_NOT_FOUND: node-addon-api` | 源码构建但缺构建依赖 | 已修复——`node-addon-api`/`node-gyp` 是运行时 `dependencies`;在未预编译的平台上仍需 C++ 工具链 + Python。 |
186
+ | macOS arm64 / linux arm64 上 `.node` 加载失败 | 该平台无预编译 | 安装时从源码构建;确保有工具链。 |
187
+ | 构建时 C4819 代码页警告 | GBK 代码页下 `.cc` 里的中文注释 | 无害;忽略。 |
188
+
189
+ ---
190
+
191
+ ## 错误码参考
192
+
193
+ **发送返回码**(`reqXxx` 回传的值;对 `reqOrderInsert` 这类提交即 resolve 的方法,非零值会让
194
+ Promise reject):
195
+
196
+ | 码 | 含义 |
197
+ |---|---|
198
+ | `0` | 已接受 / 已发送 |
199
+ | `-1` | 网络发送失败(未连接,或 CTP 拒绝发送) |
200
+ | `-2` | 在途未处理请求过多 |
201
+ | `-3` | 每秒发送速率超限(CTP 限流) |
202
+ | `-10001` | 被本绑定的盘前风控拦截(拒单消息含具体原因) |
203
+ | `-10002` | 被已配置的开仓或平仓限频器拦截 |
204
+ | `-10003` | 被持仓**保证金**上限拦截(账户级 `maxAccountMargin`,或按合约的 `setInstrumentMarginLimit`;公式含按金额与按手部分) |
205
+ | `-10004` | 被持仓**手数**上限拦截(`setInstrumentPositionLimit`) |
206
+ | `-10005` | 同一 front/session 内的重复 `OrderRef` |
207
+ | `-10006` | 复杂报单无法穿过已配置的本地风控,已 fail-closed |
208
+ | `-10007` | 缺少必要的价格/乘数/保证金元数据,或为相对值 |
209
+ | `-10008` | 无效的报单方向或开平标志 |
210
+ | `-10009` | 行情登录/登出被拒:会话切换正在进行或状态不明(请等待其完成,或超时后重连) |
211
+
212
+ **交易所/券商错误**以 `rspInfo`(`{ errorId, errorMsg }`)出现在相应事件上,被 reject 的请求
213
+ Promise 上则是 `err.errorId` / `err.errorMsg`。`errorId 0` = 成功;非零带一个中文 `errorMsg`
214
+ (已替你 GB18030 解码)——消息是可靠、可读的原因,请记录它。常见的见上面的
215
+ [报单被拒](#报单被拒) 和 [登录](#登录--认证) 表格。
216
+
217
+ ```ts
218
+ try { await td.reqUserLogin({ brokerId: "9999", userId: "id", password: "bad" }); }
219
+ catch (e) { console.error(`CTP ${e.errorId}: ${e.errorMsg}`); }
220
+ ```
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hitrading/ctp-node",
3
- "version": "2.0.0",
3
+ "version": "3.0.0",
4
4
  "description": "High-performance, type-safe CTP (Chinese futures) binding for Node.js",
5
5
  "keywords": [
6
6
  "ctp",
@@ -42,6 +42,13 @@
42
42
  }
43
43
  },
44
44
  "files": [
45
+ "README.zh-CN.md",
46
+ "CHANGELOG.md",
47
+ "RELEASING.md",
48
+ "docs/",
49
+ "scripts/bench-decode.mjs",
50
+ "scripts/bench-fullmarket-offline.mjs",
51
+ "scripts/stress-fullmarket.mjs",
45
52
  "dist/",
46
53
  "src/",
47
54
  "ctpsdk/",
@@ -49,20 +56,21 @@
49
56
  "binding.gyp"
50
57
  ],
51
58
  "engines": {
52
- "node": ">=18"
59
+ "node": "^22.22.2 || ^24.15.0 || >=26.0.0"
53
60
  },
54
61
  "scripts": {
55
62
  "gen": "node scripts/codegen/generate.mjs && node scripts/codegen/generate-trader.mjs",
56
63
  "build:native": "node-gyp rebuild",
57
64
  "build:ts": "tsc && node scripts/bundle-cjs.mjs",
58
65
  "build": "npm run gen && npm run build:native && npm run build:ts",
59
- "prebuild": "prebuildify --napi --strip",
66
+ "prebuild:napi": "prebuildify --napi --strip",
60
67
  "install": "node-gyp-build",
61
68
  "test": "node scripts/test-codec.mjs && node scripts/test-md.mjs && node scripts/test-trader.mjs && node scripts/test-arm.mjs && node scripts/test-gbk.mjs && node scripts/test-lifecycle.mjs && node scripts/test-backpressure.mjs && node scripts/test-codec-edge.mjs && node scripts/test-md-unit.mjs && node scripts/test-client-unit.mjs && node scripts/test-trader-unit.mjs && node scripts/smoke-cjs.cjs",
62
69
  "coverage": "c8 --config .c8rc.json npm test",
63
70
  "test:cpp": "node scripts/test-cpp.mjs",
64
71
  "test:integration": "node scripts/integration/run.mjs",
65
72
  "bench": "node scripts/bench-decode.mjs",
73
+ "bench:fullmarket": "node scripts/bench-fullmarket-offline.mjs",
66
74
  "smoke": "node scripts/smoke.mjs"
67
75
  },
68
76
  "devDependencies": {
@@ -74,7 +82,7 @@
74
82
  },
75
83
  "dependencies": {
76
84
  "node-addon-api": "^8.3.0",
77
- "node-gyp": "^11.2.0",
85
+ "node-gyp": "^13.0.1",
78
86
  "node-gyp-build": "^4.8.4"
79
87
  },
80
88
  "license": "Apache-2.0"
@@ -0,0 +1,37 @@
1
+ // Micro-benchmark: raw decode-to-plain-object throughput for DepthMarketData.
2
+ // This is the hot-path cost that decides whether JS can keep up with the
3
+ // open-auction flood. Real CTP load is ~thousands/sec steady, tens of
4
+ // thousands/sec in bursts.
5
+ import { parseLayouts, buildDecoder } from "../dist/codec.js";
6
+ import { STRUCT_ID } from "../dist/generated/structs.gen.js";
7
+ // Load the addon through the package's own binding (node-gyp-build: prebuilt
8
+ // binary or the local source build) so this benchmark runs in the published
9
+ // layout too, not only a dev tree with build/Release. Same pattern as the codec
10
+ // tests, which also read native.__layoutData()/__sampleDepthMarketData().
11
+ import { native } from "../dist/native-binding.js";
12
+
13
+ const layouts = parseLayouts(native.__layoutData());
14
+ const id = STRUCT_ID.DepthMarketData;
15
+ const decode = buildDecoder(id, layouts[id]);
16
+ const buf = native.__sampleDepthMarketData();
17
+ const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
18
+ const u8 = new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
19
+
20
+ for (let i = 0; i < 200_000; i++) decode(view, u8, 0); // warm up JIT
21
+
22
+ const N = 5_000_000;
23
+ let sink = 0;
24
+ const t0 = process.hrtime.bigint();
25
+ for (let i = 0; i < N; i++) {
26
+ const o = decode(view, u8, 0);
27
+ sink += o.lastPrice + o.bidPrice1;
28
+ }
29
+ const t1 = process.hrtime.bigint();
30
+
31
+ const ms = Number(t1 - t0) / 1e6;
32
+ const perSec = N / (ms / 1000);
33
+ console.log(`decode DepthMarketData (46 fields -> plain object):`);
34
+ console.log(` ${N.toLocaleString()} ops in ${ms.toFixed(0)} ms = ${(perSec / 1e6).toFixed(2)} M/sec`);
35
+ console.log(` ~${(1e9 / perSec).toFixed(0)} ns per tick`);
36
+ console.log(` headroom vs 50,000 ticks/sec burst: ${Math.round(perSec / 50000)}x`);
37
+ if (!Number.isFinite(sink)) process.exitCode = 1;