@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
@@ -0,0 +1,54 @@
1
+ # Migrating 2.x → 3.0
2
+
3
+ 3.0 reshapes the risk API and moves risk data sourcing into C++. Most renames
4
+ are caught by the TypeScript compiler, but a few changes keep the **same field
5
+ name with different semantics** — re-check these explicitly.
6
+
7
+ ## ⚠️ Silent semantic changes (same name, different behaviour)
8
+
9
+ - **`RiskLimits.maxNotional` now multiplies by the contract multiplier.**
10
+ The cap is `price × volume × multiplier` (was `price × volume`). A value
11
+ carried over from 2.x therefore permits roughly `multiplier`× the notional you
12
+ previously configured (e.g. ~10× for a ×10 contract). **Re-derive your
13
+ `maxNotional`.** It also only applies to futures/TAS; other product classes
14
+ (e.g. options) fail closed for `maxNotional`.
15
+ - **`seedFromPositions()` / `syncPositions()` reject net-mode rows.**
16
+ `posiDirection` must be `'2'` (long) or `'3'` (short); net (`'1'`) is no longer
17
+ bucketed as short — it throws. Long/short position mode is required.
18
+ - **Explicit `orderRef` must be strictly greater than the session high-water
19
+ mark.** A reused or non-monotonic explicit `orderRef` is rejected client-side
20
+ (`RangeError`) before it reaches CTP.
21
+
22
+ ## Renamed / restructured APIs
23
+
24
+ | 2.x | 3.0 |
25
+ |---|---|
26
+ | `RiskConfig` | `RiskLimits` |
27
+ | `RiskLimits.maxMargin` / `maxPositionCost` | `maxAccountMargin` |
28
+ | `LotCap` | `InstrumentPositionLimit` |
29
+ | `Trader.halt()` | `Trader.reduceOnly()` (block opens, allow closes) **and** `Trader.haltAll()` (block both) |
30
+ | `Trader.seedPosition(one)` | `Trader.seedPositions([...])` (atomic replace) + `PositionSeed` |
31
+ | `Trader.setMultiplier` / `setMarginRate` (JS) | sourced in C++ from CTP; fed via `session()` / `syncMultipliers()` / `syncMarginRates()` |
32
+ | `getApiVersion()` / `getTradingDay()` | `apiVersion` / `tradingDay` getters |
33
+
34
+ Margin rates are **no longer fed from JS** — they come from CTP's margin-rate
35
+ queries inside C++. Enabled monetary caps **fail closed** until the multiplier
36
+ and margin schedule for an instrument have arrived (call `session()` or the
37
+ `sync*` helpers after login).
38
+
39
+ ## Fail-closed behaviour to be aware of
40
+
41
+ - After **any close fill**, the position ledger is marked uncertain and opening
42
+ orders fail closed (`CTP_RISK_METADATA_UNAVAILABLE`) until an authoritative
43
+ `syncPositions()` — this prevents a delayed realtime close (for a fill already
44
+ in a prior snapshot) from double-releasing exposure. Re-run `syncPositions()`
45
+ to resume opening after closes.
46
+ - `syncOrders()` marks the held-position side uncertain; run `syncPositions()`
47
+ **after** it.
48
+
49
+ ## Platform / toolchain
50
+
51
+ - **macOS** is no longer shipped as a prebuild — it builds from source on
52
+ install (Windows and Linux prebuilds are unchanged).
53
+ - **Node `engines`** is restricted to the range required by `node-gyp` 13
54
+ (`^22.22.2 || ^24.15.0 || >=26.0.0`); Node 20 and older 22 lines are excluded.
@@ -0,0 +1,27 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 860 452" font-family="ui-monospace, 'Cascadia Code', 'SF Mono', Consolas, monospace" font-size="15">
2
+ <rect width="860" height="452" rx="10" fill="#0d1117"/>
3
+ <rect width="860" height="34" rx="10" fill="#161b22"/>
4
+ <rect y="24" width="860" height="10" fill="#161b22"/>
5
+ <circle cx="22" cy="17" r="6" fill="#ff5f56"/>
6
+ <circle cx="42" cy="17" r="6" fill="#ffbd2e"/>
7
+ <circle cx="62" cy="17" r="6" fill="#27c93f"/>
8
+ <text x="430" y="22" text-anchor="middle" fill="#8b949e" font-size="13">ctp-node - validation</text>
9
+
10
+ <text x="22" y="66"><tspan fill="#58a6ff">$</tspan> <tspan fill="#c9d1d9">npm test</tspan></text>
11
+ <text x="40" y="92" fill="#3fb950">CODEC PASS | MD PASS | TRADER PASS | ARM PASS</text>
12
+ <text x="40" y="116" fill="#3fb950">RISK PASS | GB18030 PASS | LIFECYCLE PASS | BACKPRESSURE PASS</text>
13
+ <text x="40" y="140" fill="#8b949e">Offline suites are reproducible and credential-free</text>
14
+
15
+ <text x="22" y="184"><tspan fill="#58a6ff">$</tspan> <tspan fill="#c9d1d9">node scripts/stress-fullmarket.mjs</tspan></text>
16
+ <text x="40" y="210" fill="#d29922">HISTORICAL LIVE SAMPLE - not a soak result for the current candidate</text>
17
+ <text x="40" y="234" fill="#c9d1d9">subscribed 18,111 instruments; observed dropped records: 0</text>
18
+ <text x="40" y="258" fill="#c9d1d9">RSS 124 MB | strategy ~3 us/tick | loop-lag p99 23 ms</text>
19
+ <text x="40" y="282" fill="#c9d1d9">orders 19 | rested 16 | cancelled 16 | rejected 0</text>
20
+
21
+ <text x="22" y="326" fill="#8b949e" font-size="13.5">Release gate still requires a fresh broker/SimNow soak on the exact commit and artifacts.</text>
22
+ <text x="22" y="350" fill="#e6edf3" font-weight="bold">No historical observation is presented as current production certification.</text>
23
+
24
+ <line x1="22" y1="378" x2="838" y2="378" stroke="#21262d"/>
25
+ <text x="22" y="404" fill="#8b949e" font-size="13">fast-path ring | keep-newest MD | lossless Trader overflow</text>
26
+ <text x="22" y="428" fill="#8b949e" font-size="13">C++ local risk is a second line of defence, not an authenticated mandate gateway</text>
27
+ </svg>
@@ -0,0 +1,60 @@
1
+ # Integration tests (live SimNow) · 集成测试(实盘 SimNow)
2
+
3
+ Unit tests cover the **logic** (the JS suite enforces its configured coverage
4
+ thresholds; standalone C++ `risk`/`arm` suites also run on every push). These
5
+ cover the **wire behavior** against the real CTP API — what only a
6
+ live connection exposes: the connect/login handshake, the one-call
7
+ [`session()`](API.md#session) (authenticate → login → confirm settlement → sync
8
+ multipliers / optional margin rates / orders / positions), an account query (req/rsp correlation over the
9
+ wire), and the **C++ pre-trade risk gate end-to-end**. They are
10
+ **credential-gated** and never run on push.
11
+
12
+ The Windows lifecycle regression runs its vendor-DLL workload in a supervised
13
+ child process with a 60-second hard deadline. A `Release()` stall is reported as
14
+ a failed test and cannot hang the default `npm test` process indefinitely.
15
+
16
+ 单元测试覆盖**逻辑**(JS 套件强制执行已配置的覆盖率门槛;独立 C++ `risk`/`arm`
17
+ 套件也在每次 push 运行)。这套覆盖对真实
18
+ CTP API 的**线上行为**——只有真连接才暴露的东西:连接/登录握手、一站式
19
+ [`session()`](API.zh-CN.md) 握手(认证 → 登录 → 结算确认 → 乘数 / 可选保证金率 / 工作单 / 持仓)、
20
+ 账户查询(线上的请求/响应关联)、以及 **C++ 盘前风控网关的
21
+ 端到端验证**。**需要凭据**,不在每次 push 上跑。
22
+
23
+ Windows 生命周期回归把厂商 DLL 操作放在受监管子进程中,并设 60 秒硬超时;`Release()` 卡死会
24
+ 明确报测试失败,不再让默认 `npm test` 无限挂起。
25
+
26
+ > It only ever sends **oversized** orders — the risk gate rejects them before they
27
+ > reach the exchange, so **nothing ever rests** on the account.
28
+ >
29
+ > 它只发**超量**订单——会被风控网关在送达交易所前拒掉,所以**账户上不会留任何挂单**。
30
+
31
+ ## Run locally · 本地运行
32
+
33
+ ```sh
34
+ CTP_USER=<investorId> CTP_PASS=<password> npm run test:integration
35
+ ```
36
+
37
+ Without `CTP_USER` / `CTP_PASS` it **skips** (exit 0). Optional environment:
38
+
39
+ | env | default | meaning |
40
+ |---|---|---|
41
+ | `CTP_BROKER` | `9999` | broker id |
42
+ | `CTP_APPID` | `simnow_client_test` | terminal app id |
43
+ | `CTP_AUTHCODE` | `0000000000000000` | terminal auth code |
44
+ | `CTP_TD_FRONT` | 电信二 trade front | trade front; set a **7×24** SimNow front for off-session runs |
45
+
46
+ Credentials are read **only** from the environment — never written to a file or
47
+ committed. 凭据只从环境变量读取,绝不写入文件或提交。
48
+
49
+ ## CI
50
+
51
+ [`.github/workflows/integration.yml`](../.github/workflows/integration.yml) runs
52
+ it **manually** (`workflow_dispatch`) and on a **weekday schedule** (09:30
53
+ Beijing, inside the morning session). To enable it, add the repository **secrets**
54
+ `CTP_USER` and `CTP_PASS` (Settings → Secrets and variables → Actions); optionally
55
+ set the repository **variable** `CTP_TD_FRONT`. Fork pull requests never receive
56
+ the secrets, and a run without them skips green.
57
+
58
+ 手动 + 工作日定时(北京 09:30,早盘时段)运行。加仓库 **secret** `CTP_USER`/`CTP_PASS`
59
+ 即启用;前置可用仓库**变量** `CTP_TD_FRONT` 覆盖。fork PR 拿不到 secret,没凭据的运行会
60
+ 直接跳过(绿)。
@@ -0,0 +1,281 @@
1
+ <!-- LANG-SWITCH -->
2
+ **English** · [简体中文](native-hooks.zh-CN.md)
3
+
4
+ # Native-sinkable hooks (risk / rate-limit / arm)
5
+
6
+ Goal: keep ~95% of strategy work in JS/TS (fast iteration, good ecosystem) while
7
+ giving the **latency- and safety-critical** slices C++-grade determinism — no GC
8
+ pause or event-loop hiccup can defeat them. JS sets the rules; C++ enforces and
9
+ executes them.
10
+
11
+ ## Two worlds
12
+
13
+ | | C++ world | JS world |
14
+ |---|---|---|
15
+ | Runs on | CTP callback thread | Node main thread (event loop) |
16
+ | GC pauses | none | yes (occasional ms-tens-of-ms) |
17
+ | Determinism | microsecond, predictable | jitter (GC / JIT / scheduling) |
18
+
19
+ A tick first arrives on the **C++ callback thread**. A pure-JS strategy must
20
+ cross to JS and wait for the event loop — eating that jitter. "Sinking down"
21
+ keeps the critical decision on the C++ thread; JS only configures and is
22
+ notified afterward.
23
+
24
+ ## What is sunk down
25
+
26
+ 1. **Risk (pre-trade)** — `src/native/risk.h` `RiskEngine`
27
+ Hard checks run before every send: kill-switch, max order volume, max
28
+ single-order notional (fat-finger guard), price-deviation guard, open-MARGIN
29
+ caps (account-wide and per-instrument), and a per-instrument max position
30
+ (lots, capped per side). Enforced in C++ so they hold even if the JS process
31
+ is mid-GC, blocked, or buggy. *Safety win - worth it even for slow
32
+ strategies.*
33
+ - Status: **implemented with a deliberately bounded product model**. The price-deviation guard reads its reference from
34
+ the C++ MD snapshot cache (the LVC; see §4 below) via `trackMarketData(md)`
35
+ — no `setRefPrice`, no JS round-trip, and it covers armed orders too. The
36
+ single-order notional check is still notional (price × volume × multiplier
37
+ — a fat-finger guard). Futures/TAS open-order margin uses the CTP formula
38
+ `price × volume × multiplier × byMoney + volume × byVolume`, separately by
39
+ side/hedge flag. Held snapshots use CTP `UseMargin` and retain separate
40
+ instrument/side/hedge buckets so a close releases the matching schedule;
41
+ relative investor
42
+ schedules are added to the matching exchange base schedule. This is a
43
+ conservative local gate, not a universal replica of every broker margin
44
+ algorithm; unsupported product classes fail closed under monetary caps.
45
+ - **Architecture principle: latency-sensitive metadata and realtime ledger
46
+ events flow directly from SPI callbacks into C++.** Authoritative position
47
+ and working-order query snapshots are aggregated in TypeScript, then
48
+ committed through revision-checked native batch operations. Special-cased
49
+ in `scripts/codegen/generate-trader.mjs`
50
+ (emitted into `traderspi.gen.cc`):
51
+ - contract multipliers ← `OnRspQryInstrument` (internal `setInstrument`)
52
+ - per-contract/hedge margin schedules ← `OnRspQryInstrumentMarginRate`.
53
+ Long/short by-money and by-volume components are retained separately.
54
+ `OnRspQryExchangeMarginRate` supplies the base for `IsRelative` investor
55
+ schedules. Missing multipliers or either required schedule fail closed.
56
+ - login session (FrontID/SessionID, for reservation keys) ← `OnRspUserLogin`
57
+ (`setSession`), published synchronously so reservation keys are correct
58
+ before any order can be sent
59
+ - fills ← `OnRtnTrade` (`onTrade`)
60
+ - order updates ← `OnRtnOrder` (`onOrderUpdate`)
61
+
62
+ So any `reqQryInstrument` keeps multipliers current and querying
63
+ `reqQryInstrumentMarginRate` for the contracts you trade keeps the margin
64
+ cap schedule current — there is no JS metadata relay
65
+ (those C++ entry points exist only for tests / offline use). Multipliers
66
+ and margin rates are static metadata stored separately from position state,
67
+ so `resetPositions()` / a `syncPositions()` resync never wipes them.
68
+ - In-flight reservation: the position caps count `held + working` (orders
69
+ sent but not yet filled), so a burst of opens can't slip past before fills
70
+ report. Reservations are tracked per `(FrontID, SessionID, OrderRef)` and
71
+ reconciled from `OnRtnOrder` (self-correcting; released on fill/cancel/
72
+ reject and on a failed send). Terminal tombstones also retain the concrete
73
+ trading-day/exchange/instrument/`OrderSysID` fingerprint: matching late
74
+ replays are ignored, while a reused or ambiguous key fails closed until an
75
+ authoritative `syncOrders()` snapshot supersedes it. Because CTP delivers an investor's order/
76
+ trade returns to *all* their sessions, this also accounts for orders placed
77
+ from **another terminal on the same account** (their fills update the
78
+ position by instrument; their working orders consume the cap).
79
+ Trade idempotency keeps at most 65,536 exact fingerprints, retiring complete
80
+ older days first. Exhausting that budget inside one active trading day does
81
+ not evict ambiguous keys: opening inserts stay fail-closed until a later
82
+ trading day is observed and `syncPositions()` reconciles the missed epoch.
83
+ - What stays JS-driven (NOT auto-sourced): `seedPositions` / `syncPositions`
84
+ (open-position seeding) and `rebuildReservations` / `syncOrders` (rebuild
85
+ the reservation from the broker's working orders, via `reqQryOrder`). These
86
+ are deliberate resync operations. They apply revision-checked atomic
87
+ replacements, preserve working reservations, and retry if realtime callbacks
88
+ race the query. They stay explicit, JS-orchestrated calls; auto-
89
+ running them on every query would be a dangerous side-effect. Call
90
+ `syncOrders()` after login and after any reconnect.
91
+
92
+ 2. **Rate limit** — `src/native/risk.h` `RateLimiter`
93
+ Token bucket guaranteeing the seat never exceeds the exchange/CTP order rate,
94
+ immune to JS bursts after a pause.
95
+ - Status: **real** (token bucket).
96
+
97
+ 3. **Arm (latency-critical trigger)** — `src/native/arm.h` `ArmRegistry`
98
+ A narrow rule ("fire the instant ask ≤ X") evaluated on the MD callback
99
+ thread, parameterized from JS. Only for genuinely latency-sensitive
100
+ strategies.
101
+ - Status: **wired**. `trader.arm(md, spec)` shares the registry (shared_ptr)
102
+ with the MarketData feeding ticks; on a hit the order is built from the
103
+ JS-encoded template, passed through the Trader's `RiskEngine`, and sent via
104
+ `ReqOrderInsert` on the MD callback thread (no JS). A successful send removes
105
+ the arm immediately; halt/rate/metadata/send refusal keeps it armed with a
106
+ retry backoff. Ack arrives via normal trader events. Teardown-safe: the sink is cleared under the registry lock
107
+ before the API is released.
108
+
109
+ 4. **Market-data snapshot (last-value cache)** — `src/native/snapshot.h`
110
+ `SnapshotCache`
111
+ A C++ last-value cache (LVC) holding the latest full `DepthMarketDataField`
112
+ per instrument. A successful MD login activates a new empty epoch; only
113
+ later ticks in that authenticated epoch update it before publication.
114
+ Connect/disconnect, login/logout transitions and close invalidate it, so a
115
+ prior-session quote cannot become a fresh risk reference after reconnect.
116
+ Unsubscribe erases its instrument entry.
117
+ - **JS reads it synchronously**: `md.snapshot(id)` returns the full latest
118
+ tick (or `null` outside the active epoch / if none seen / unsubscribed), `md.last(id)` returns just
119
+ the last price — no waiting for a tick, no per-tick bookkeeping in your
120
+ strategy.
121
+ - **The deviation reference flows MD→risk entirely in C++.** The Trader's
122
+ price-deviation check reads the cache in C++ via `trackMarketData(md)`: the
123
+ MarketData shares the cache as a `shared_ptr` (mirroring how the armed-order
124
+ registry is shared), so the risk engine reads live prices straight from the
125
+ MD feed with no JS round-trip — and the check therefore also covers armed
126
+ orders that fire from C++ with no JS in the loop. Unauthenticated or
127
+ post-disconnect ticks remain observable protocol events but cannot drive
128
+ the cache or an armed mandate. (The `SnapshotCache`
129
+ implements `RefPriceSource`; the risk engine holds it via `setMdSnapshot`.)
130
+
131
+ ## Threading / safety model
132
+
133
+ - Config is written on the **slow path** (JS thread) and read on the **hot
134
+ path** (JS or callback thread). Risk config uses **atomics** (lock-free
135
+ reads); the rate limiter uses a tiny mutex (bounded, uncontended).
136
+ - `ArmRegistry` is indexed by instrument, so `onTick` scans only that contract's
137
+ active triggers (successful arms are erased immediately). A short mutex keeps
138
+ arm/disarm and Trader teardown linearizable with an in-flight send.
139
+ - Queue/state-producing test hooks (`_injectTestTick`, `_injectTestForQuote`,
140
+ `_injectTestLifecycle`, `_burstTicks`, `_produceTestTicks`, `_burstEvents`)
141
+ are disabled unless `CTP_NODE_TEST_HOOKS=1` is explicitly set. Never enable
142
+ them in a live process: EventChannel relies on the vendor callback stream being
143
+ its single producer, and lifecycle injection deliberately bypasses a real front.
144
+
145
+ ## Logging / observability
146
+
147
+ Deliberately, the C++ does **no synchronous logging** — blocking I/O or string
148
+ formatting on the CTP callback thread would add exactly the latency/jitter this
149
+ design avoids. The hot path stays memcpy + atomics. Observability is layered the
150
+ way low-latency systems do it:
151
+
152
+ - **Counters / events, not logs, in C++.** `droppedRecords` (market data safely
153
+ drops the oldest logical record; Trader overflow is ordered/lossless),
154
+ arm fire count, and the streaming events (`front-connected`,
155
+ `front-disconnected` with reason, `rsp-*` with `errorId`/`errorMsg`) are
156
+ surfaced to JS.
157
+ - **Reasons surfaced, not swallowed.** A pre-trade-risk rejection carries the
158
+ specific cause back to JS (e.g. `blocked by pre-trade risk: order volume
159
+ exceeds maxOrderVolume`; position caps and rate limit have their own
160
+ messages), so logs say *why*. Costs nothing on the hot path — it's set only
161
+ on the (rare) reject.
162
+ - **Do the actual logging in JS**, off the callback thread, from those events —
163
+ any async logger (pino/winston) is fine there. If C++-side audit logging is
164
+ ever needed, add an opt-in async/deferred logger (lock-free queue + background
165
+ thread, à la NanoLog/Quill) — never a synchronous one.
166
+
167
+ ## Public TS surface (the shell)
168
+
169
+ All of this is exposed on `Trader` (`src/trader.ts`):
170
+
171
+ ```ts
172
+ // Pre-trade risk (published to the C++ enforcer; takes effect immediately):
173
+ td.setRiskLimits({ maxOrderVolume: 5, maxPriceDeviation: 0.02, maxOrdersPerSec: 20, maxAccountMargin: 5_000_000 });
174
+ td.trackMarketData(md); // C++ reference for deviation + monetary valuation
175
+ td.setInstrumentPositionLimits({ rb2610: 100, ru2610: { long: 100, short: 20 } });
176
+ td.setInstrumentMarginLimits({ ag2608: 2_000_000, au2608: 5_000_000 }); // per-instrument margin caps
177
+ td.reduceOnly(); td.resume(); // block increases; closes/cancels stay available
178
+
179
+ // Synchronous market-data snapshot from the C++ last-value cache (no event wait):
180
+ const tick = md.snapshot("rb2510"); // latest full DepthMarketDataField, or null
181
+ const px = md.last("rb2510"); // just the last price (0 if none)
182
+
183
+ // Multipliers and margin rates are sourced in C++ from the SPI callbacks (no JS
184
+ // feed). A plain query keeps them current — there is nothing to relay back:
185
+ await td.reqQryInstrument({}); // multipliers <- OnRspQryInstrument
186
+ await td.reqQryInstrumentMarginRate({ instrumentId: "rb2510" }); // rate <- OnRspQryInstrumentMarginRate
187
+
188
+ // Deliberate JS-driven atomic resyncs (call explicitly, not per query):
189
+ await td.syncOrders(); // rebuild reservations; marks held side uncertain
190
+ await td.syncPositions(); // final held snapshot; preserve reservations
191
+
192
+ // Latency-critical armed trigger (fires from C++ on the MD thread):
193
+ const armed = td.arm(md, {
194
+ instrumentId: "rb2510", side: "buy", triggerPrice: 3500,
195
+ order: { /* InputOrder; orderRef auto-assigned if blank */ },
196
+ });
197
+ armed.disarm(); // remove the trigger
198
+ // One-shot; the fill/ack arrives via the normal rtn-order / rtn-trade events.
199
+ ```
200
+
201
+ ## Status
202
+
203
+ The offline suite covers the risk ledger, arm state machine, generated send path,
204
+ backpressure and lifecycle isolation. A credential-gated SimNow integration suite
205
+ is available separately; it is not evidence of continuous soak coverage. Margin
206
+ estimation models both formula components and relative+exchange-base schedules;
207
+ missing metadata fails closed. Live soak remains a separate release gate.
208
+
209
+ ## Process lifecycle: create once, reuse
210
+
211
+ `MarketData` and `Trader` are **create-once, reuse-for-the-life-of-the-process**
212
+ objects. The wrapper constructor calls the native `_start()`, which calls the
213
+ vendor `Init()`; `close()` calls the vendor `Release()`
214
+ (`CThostFtdcMdApi::Release()` / `CThostFtdcTraderApi::Release()` — see
215
+ `doClose()` in `src/native/mdapi.cc` and `src/native/traderapi.cc`).
216
+
217
+ **The observed hazard.** On the bundled Windows vendor DLLs, repeated
218
+ `Init()`→`Release()` cycles in one process have reproducibly hung inside
219
+ `Release()` — empirically after 4–11 cycles, varying with timing and CTP's
220
+ internal reconnect-thread state. The binding cannot recover a process once a
221
+ closed-source vendor call is stuck, so this candidate deliberately adopts a
222
+ create-once lifecycle. (For comparison: the raw native object *without*
223
+ `_start()` survives 80+ create/close cycles; the trigger is specifically the
224
+ `Init()`+`Release()` pairing. A front like `tcp://127.0.0.1:1` that never
225
+ connects makes it worse, because CTP's reconnect machinery is what wedges.)
226
+
227
+ **The rule: never reconnect by destroying and recreating the client.** CTP
228
+ reconnects on its own. Handle a dropped link **in place**: when `front-connected`
229
+ fires again (it fires on the first connect *and* on every auto-reconnect),
230
+ re-run your handshake on the same instance.
231
+
232
+ ```ts
233
+ const md = new MarketData("./flow/md/", front); // construct ONCE
234
+ md.on("front-connected", async () => { // first connect AND every reconnect
235
+ await md.login({ brokerId, userId, password }); // re-login in place
236
+ md.subscribe(["rb2510"]); // re-subscribe in place
237
+ });
238
+
239
+ // Trader is the same shape — re-run the one-call handshake on reconnect:
240
+ td.on("front-connected", () => td.session({ brokerId, userId, password, appId, authCode }));
241
+ ```
242
+
243
+ Call `close()` **once**, at process shutdown (or not at all — process exit tears
244
+ everything down cleanly). A reconnect-by-recreate loop will instead wedge the
245
+ whole process in the vendor DLL.
246
+
247
+ **Windows fallout when it does wedge.** A wedged process ignores `SIGTERM` (the
248
+ stuck CTP threads never observe the signal), so a timed-out / killed Node
249
+ process **lingers** and must be force-killed: `taskkill /F /PID <pid>`. Until it
250
+ dies it keeps `build\Release\ctp.node` open, so the next native build can't
251
+ overwrite the addon and fails with `LNK1104: cannot open file ... ctp.node`. If
252
+ a build suddenly can't write the addon, look for a stray `node` zombie and
253
+ `taskkill /F` it first.
254
+
255
+ **Dev tripwire.** As a backstop against a reconnect-by-recreate bug slipping
256
+ into production, `CtpClient` keeps a process-wide count of clients that were
257
+ started (`Init`) and then closed (`Release`) and emits a one-time
258
+ `console.warn` once that count crosses a threshold (default 3 — deliberately
259
+ below the ~4-cycle deadlock point so the warning prints on the `close()`
260
+ preceding the typical wedge; a higher value would never fire in time). It runs
261
+ only on `close()` — never on the hot data path — so it costs nothing where
262
+ latency matters, and a create-once app (one or two long-lived clients closed at
263
+ shutdown) never trips it. Tune or disable it with the `CTP_RECREATE_WARN` env
264
+ var: `CTP_RECREATE_WARN=0` disables it; any positive integer sets the threshold.
265
+
266
+ ## Backpressure and market-data responses
267
+
268
+ The market-data ring is `DropPolicy::Oldest`: when the JS consumer falls a full
269
+ ring (8192 records) behind a tick flood, the producer uses bounded keep-newest
270
+ staging and preferentially displaces an old unread **droppable tick** without
271
+ overwriting bytes JS is decoding; the latest staged tick is retained. Request responses (`OnRspUserLogin` /
272
+ `OnRspUserLogout` / `OnRspQryMulticastInstrument`) share this ring but are
273
+ marked non-droppable: they are retained even when doing so temporarily exceeds
274
+ the tick capacity. A stalled JS loop can still delay a response long enough for
275
+ the Promise's idle timeout (`requestTimeoutMs`, default 30 s), but the channel
276
+ does not deliberately discard it.
277
+
278
+ The **Trader** ring uses `DropPolicy::Lossless`: after 4096 slots it spills
279
+ records into an ordered queue and copies them back as the consumer advances. No
280
+ Trader callback is deliberately dropped, at the cost of memory growth during
281
+ sustained consumer stalls.
@@ -0,0 +1,205 @@
1
+ <!-- LANG-SWITCH -->
2
+ [English](native-hooks.md) · **简体中文**
3
+
4
+ # 原生可下沉钩子(风控 / 限频 / 预埋触发)
5
+
6
+ 目标:把约 95% 的策略工作留在 JS/TS(迭代快、生态好),同时给**延迟与安全攸关**的那几片
7
+ C++ 级确定性——任何 GC 停顿或事件循环卡顿都打不垮它们。JS 定规则;C++ 执行并落地。
8
+
9
+ ## 两个世界
10
+
11
+ | | C++ 世界 | JS 世界 |
12
+ |---|---|---|
13
+ | 运行于 | CTP 回调线程 | Node 主线程(事件循环) |
14
+ | GC 停顿 | 无 | 有(偶发,毫秒到几十毫秒) |
15
+ | 确定性 | 微秒级、可预测 | 抖动(GC / JIT / 调度) |
16
+
17
+ 一个 tick 首先到达 **C++ 回调线程**。纯 JS 策略必须跨到 JS 并等待事件循环——吃下那份抖动。
18
+ “下沉”把关键决策留在 C++ 线程;JS 只做配置,并在事后被通知。
19
+
20
+ ## 下沉了什么
21
+
22
+ 1. **风控(盘前)** — `src/native/risk.h` `RiskEngine`
23
+ 每次发送前都跑硬性检查:一键熔断、单笔最大手数、单笔最大名义价值(防胖手指)、价格偏离防护、
24
+ 开仓**保证金**上限(账户级与按合约)、以及按合约的最大持仓(手数,按边封顶)。在 C++ 里执行,
25
+ 因此即使 JS 进程正在 GC、被阻塞或有 bug,它们依然成立。*安全收益——即便慢策略也值得。*
26
+ - 状态:**已实现,但产品模型有意收窄**。价格偏离防护的参考价来自 C++ 行情快照缓存(LVC;见下文 §4),经
27
+ `trackMarketData(md)` 读取——无需 `setRefPrice`、无 JS 往返,且也覆盖预埋单。单笔名义价值
28
+ 检查仍是名义价值(价 × 量 × 乘数——防胖手指)。Futures/TAS 工作单保证金按 CTP 公式
29
+ `价 × 量 × 乘数 × 按金额 + 量 × 按手`,并区分多空/套保标志;持仓快照使用 `UseMargin`,且按
30
+ 合约/多空/套保标志保留独立成本桶,使平仓只释放匹配桶。
31
+ 相对投资者表与匹配的交易所基础表逐字段相加。这是保守的本地闸门,不是所有券商保证金算法的
32
+ 通用复刻;金额闸启用时,不支持的产品类别会 fail-closed。
33
+ - **架构原则:延迟敏感的元数据和实时账本事件直接从 SPI 回调进入 C++。** 权威持仓与工作单查询
34
+ 快照由 TypeScript 聚合,再通过带版本校验的 native 批操作提交。在
35
+ `scripts/codegen/generate-trader.mjs` 中特判(生成进 `traderspi.gen.cc`):
36
+ - 合约乘数 ← `OnRspQryInstrument`(内部 `setInstrument`)
37
+ - 按合约/套保标志的保证金表 ← `OnRspQryInstrumentMarginRate`。多空的按金额、按手字段分别保留。
38
+ `OnRspQryExchangeMarginRate` 提供 `IsRelative` 所需基础表;乘数或任一所需表缺失时 fail-closed。
39
+ - 登录会话(FrontID/SessionID,用于预约键)← `OnRspUserLogin`(`setSession`),登录时同步发布,
40
+ 使预约键在任何报单可发出之前就已正确。
41
+ - 成交 ← `OnRtnTrade`(`onTrade`)
42
+ - 报单更新 ← `OnRtnOrder`(`onOrderUpdate`)
43
+
44
+ 因此任何 `reqQryInstrument` 都会保持乘数最新,对你所交易的合约查询
45
+ `reqQryInstrumentMarginRate` 可填充绝对保证金表——无需 JS 转交元数据。乘数与保证金表是静态元数据,与持仓状态
46
+ 分开存储,因此 `resetPositions()` / 一次 `syncPositions()` 重同步绝不会清掉它们。
47
+ - 在途预约:持仓上限按 `held + working`(已发但未成交的报单)计算,使一连串开仓不会在成交
48
+ 回报到达前溜过。预约按 `(FrontID, SessionID, OrderRef)` 跟踪,并由 `OnRtnOrder` 对账(自我
49
+ 纠正;在成交/撤单/拒单及发送失败时释放)。终态墓碑还保存具体的交易日/交易所/合约/
50
+ `OrderSysID` 指纹:同一交易所订单的迟到回放会被忽略;复用或无法判定的键会 fail-closed,直到
51
+ 权威 `syncOrders()` 快照取代旧墓碑。由于 CTP 会把一个投资者的报单/成交回报投递到其
52
+ *所有*会话,这也把**同账户另一终端**下的报单算进去(它们的成交按合约更新持仓;它们的挂单
53
+ 占用上限)。
54
+ Trade 幂等账本最多保留 65,536 个精确指纹,并优先退休完整的较旧交易日。如果单个活跃交易日
55
+ 自身耗尽该预算,实现不会淘汰含糊的键;开仓保持 fail-closed,直至观察到下一交易日并由
56
+ `syncPositions()` 对账遗漏时段。
57
+ - 仍由 JS 驱动(**非**自动获取)的部分:`seedPositions` / `syncPositions`(播种已有开仓)与
58
+ `rebuildReservations` / `syncOrders`(经 `reqQryOrder` 从经纪商的挂单重建预约)。它们使用版本号
59
+ 校验的原子替换,保留工作单预约;若查询期间有实时回报就重试。故保持为显式、由 JS 编排的调用。
60
+ 登录后和任何重连后都要调用
61
+ `syncOrders()`。
62
+
63
+ 2. **限频** — `src/native/risk.h` `RateLimiter`
64
+ 令牌桶,保证席位永不超过交易所/CTP 的报单速率,对停顿后的 JS 突发免疫。
65
+ - 状态:**实**(令牌桶)。
66
+
67
+ 3. **预埋(延迟攸关触发器)** — `src/native/arm.h` `ArmRegistry`
68
+ 一条窄规则(“ask ≤ X 的瞬间就发”),在 MD 回调线程上判定,由 JS 参数化。仅用于真正延迟
69
+ 敏感的策略。
70
+ - 状态:**已接通**。`trader.arm(md, spec)` 与喂 tick 的 MarketData 共享同一注册表(shared_ptr);
71
+ 命中时报单由 JS 编码的模板构建,穿过该 Trader 的 `RiskEngine`,在 MD 回调线程上经
72
+ `ReqOrderInsert` 发出(无 JS)。成功提交后立即删除;熔断/限频/元数据/发送拒绝时保留并退避重试;
73
+ 回执经普通交易事件到达。拆除安全:在释放 API 之前,
74
+ 会在注册表锁内清空 sink。
75
+
76
+ 4. **行情快照(最新值缓存)** — `src/native/snapshot.h` `SnapshotCache`
77
+ 一个 C++ 最新值缓存(LVC),按合约保存最新的完整 `DepthMarketDataField`。成功 MD 登录会激活一个
78
+ 全新的空 epoch;只有当前认证 epoch 后续的 tick 才会在发布前更新它。连接/断线、登录/登出转换和
79
+ 关闭都会使缓存立即失效,因此重连后旧报价不可能伪装成新鲜风控参考价。退订按合约清除(`erase`)。
80
+ - **JS 同步读取**:`md.snapshot(id)` 返回最新的完整 tick(非活动 epoch、从未见过或已退订则为 `null`),
81
+ `md.last(id)` 只返回最新价——无需等待 tick,策略里也无需逐 tick 记账。
82
+ - **偏离参考价完全在 C++ 内由 MD→风控流转。** Trader 的价格偏离检查经 `trackMarketData(md)`
83
+ 在 C++ 里读取该缓存:MarketData 以 `shared_ptr` 共享该缓存(与预埋单注册表的共享方式如出一辙),
84
+ 故风控引擎直接从 MD 馈源读取实时价,无 JS 往返——因此该检查也覆盖那些从 C++ 触发、回路中无 JS
85
+ 的预埋单。未认证或断线后的 tick 仍作为协议事件可见,但不能更新缓存或驱动预埋 mandate。
86
+ (`SnapshotCache` 实现了 `RefPriceSource`;风控引擎经 `setMdSnapshot` 持有它。)
87
+
88
+ ## 线程 / 安全模型
89
+
90
+ - 配置写在**慢路径**(JS 线程),读在**热路径**(JS 或回调线程)。风控配置用**原子量**(无锁
91
+ 读取);限频器用一个极小的互斥锁(有界、无争用)。
92
+ - `ArmRegistry` 按合约建立索引,因此 `onTick` 只扫描该合约的活跃触发器(成功触发后立即删除)。
93
+ 短互斥区保证 arm/disarm、在途发送与 Trader teardown 线性一致。
94
+ - 会写队列或改变测试状态的钩子(`_injectTestTick`、`_injectTestForQuote`、
95
+ `_injectTestLifecycle`、`_burstTicks`、`_produceTestTicks`、`_burstEvents`)默认禁用,只有显式设置
96
+ `CTP_NODE_TEST_HOOKS=1` 才可调用。实盘进程绝不能开启:EventChannel 依赖厂商回调流是唯一生产者,
97
+ 而生命周期注入还会刻意绕过真实前置。
98
+
99
+ ## 日志 / 可观测性
100
+
101
+ 刻意地,C++ 端**不做同步日志**——在 CTP 回调线程上做阻塞 I/O 或字符串格式化,正好会引入本设计
102
+ 要避免的延迟/抖动。热路径只保留 memcpy + 原子量。可观测性按低延迟系统的惯常做法分层:
103
+
104
+ - **C++ 里用计数器/事件,而非日志。** `droppedRecords`(行情安全淘汰最旧逻辑记录;交易端有序无损
105
+ 溢出)、预埋触发计数,以及流式事件(`front-connected`、
106
+ 带原因的 `front-disconnected`、带 `errorId`/`errorMsg` 的 `rsp-*`)都暴露给 JS。
107
+ - **原因被上抛而非吞掉。** 盘前风控拒单会把具体原因带回 JS(如 `blocked by pre-trade risk:
108
+ order volume exceeds maxOrderVolume`;持仓上限和限频有各自的消息),使日志能说清*为什么*。
109
+ 在热路径上零成本——它只在(罕见的)拒单时设置。
110
+ - **真正的日志在 JS 里做**,离开回调线程,从那些事件出发——任何异步日志库(pino/winston)都行。
111
+ 若将来确需 C++ 端审计日志,加一个可选的异步/延迟日志器(无锁队列 + 后台线程,类似
112
+ NanoLog/Quill)——绝不要同步的。
113
+
114
+ ## 公开的 TS 接口(外壳)
115
+
116
+ 这些全部暴露在 `Trader` 上(`src/trader.ts`):
117
+
118
+ ```ts
119
+ // 盘前风控(发布给 C++ 执行器;立即生效):
120
+ td.setRiskLimits({ maxOrderVolume: 5, maxPriceDeviation: 0.02, maxOrdersPerSec: 20, maxAccountMargin: 5_000_000 });
121
+ td.trackMarketData(md); // 把 C++ 行情快照接为偏离与金额估值参考价
122
+ td.setInstrumentPositionLimits({ rb2610: 100, ru2610: { long: 100, short: 20 } });
123
+ td.setInstrumentMarginLimits({ ag2608: 2_000_000, au2608: 5_000_000 }); // 按合约保证金上限
124
+ td.reduceOnly(); td.resume(); // 拦截增险入口,保留减仓/撤单
125
+
126
+ // 来自 C++ 最新值缓存的同步行情快照(无需等待事件):
127
+ const tick = md.snapshot("rb2510"); // 最新的完整 DepthMarketDataField,或 null
128
+ const px = md.last("rb2510"); // 只取最新价(无则为 0)
129
+
130
+ // 乘数与保证金率在 C++ 内由 SPI 回调获取(无 JS 喂入)。一次普通查询即可保持最新——没有要回传的:
131
+ await td.reqQryInstrument({}); // 乘数 <- OnRspQryInstrument
132
+ await td.reqQryInstrumentMarginRate({ instrumentId: "rb2510" }); // 费率 <- OnRspQryInstrumentMarginRate
133
+
134
+ // 有意的、由 JS 驱动的原子重同步:
135
+ await td.syncOrders(); // 重建预约,同时标记持仓侧不确定
136
+ await td.syncPositions(); // 最后原子替换已持仓,保留预约
137
+
138
+ // 延迟攸关的预埋触发器(从 C++ 在 MD 线程上触发):
139
+ const armed = td.arm(md, {
140
+ instrumentId: "rb2510", side: "buy", triggerPrice: 3500,
141
+ order: { /* InputOrder;orderRef 留空会自动分配 */ },
142
+ });
143
+ armed.disarm(); // 移除触发器
144
+ // 一次性;成交/回执经普通的 rtn-order / rtn-trade 事件到达。
145
+ ```
146
+
147
+ ## 状态
148
+
149
+ 离线测试覆盖风控账本、arm 状态机、生成发送路径、背压和生命周期隔离。另有凭据门控的 SimNow
150
+ 集成测试,但不能把它表述成持续浸泡覆盖。金额公式覆盖按金额、按手以及相对表 + 交易所基础表;
151
+ 元数据缺失时 fail-closed,实盘浸泡仍是独立发布门槛。
152
+
153
+ ## 进程生命周期 一次创建并复用
154
+
155
+ `MarketData` 和 `Trader` 是**一次创建、进程内一直复用**的对象。包装构造函数调用原生 `_start()`,
156
+ 后者调用厂商 `Init()`;`close()` 调用厂商 `Release()`(`CThostFtdcMdApi::Release()` /
157
+ `CThostFtdcTraderApi::Release()`——见 `src/native/mdapi.cc` 和 `src/native/traderapi.cc` 里的
158
+ `doClose()`)。
159
+
160
+ **已观测风险。** 在当前随包的 Windows 厂商 DLL 上,同一进程反复
161
+ `Init()`→`Release()` 会可重现地卡在 `Release()` 内部——经验上 4–11 次,随时机和 CTP 内部
162
+ 重连线程状态而变。闭源厂商调用一旦卡住,本绑定无法让该进程恢复,因此当前候选版明确采用
163
+ “一次创建”生命周期。(对照:*不*调用 `_start()` 的裸原生对象能扛过 80+ 次 create/close 循环;触发点
164
+ 正是 `Init()`+`Release()` 这一对。一个永不连上的前置(如 `tcp://127.0.0.1:1`)会让它更糟,因为
165
+ 卡住的正是 CTP 的重连机制。)
166
+
167
+ **规则:绝不要靠销毁再重建客户端来重连。** CTP 会自行重连。**原地**处理断线:当 `front-connected`
168
+ 再次触发时(首次连接 *以及* 每次自动重连都会触发),在同一实例上重新跑握手。
169
+
170
+ ```ts
171
+ const md = new MarketData("./flow/md/", front); // 只构造一次
172
+ md.on("front-connected", async () => { // 首次连接和每次重连
173
+ await md.login({ brokerId, userId, password }); // 原地重新登录
174
+ md.subscribe(["rb2510"]); // 原地重新订阅
175
+ });
176
+
177
+ // Trader 同理——重连时重新跑一站式握手:
178
+ td.on("front-connected", () => td.session({ brokerId, userId, password, appId, authCode }));
179
+ ```
180
+
181
+ `close()` 只在进程关闭时调用**一次**(或干脆不调用——进程退出会干净地拆除一切)。
182
+ reconnect-by-recreate 循环则会把整个进程卡死在厂商 DLL 内。
183
+
184
+ **Windows 上卡死时的连带后果。** 卡死的进程会忽略 `SIGTERM`(卡住的 CTP 线程从不观测到信号),
185
+ 所以超时/被杀的 Node 进程会**残留**,必须强杀:`taskkill /F /PID <pid>`。在它死掉之前会一直占着
186
+ `build\Release\ctp.node`,于是下次原生构建无法覆盖该插件,报 `LNK1104: cannot open file ...
187
+ ctp.node`。如果构建忽然写不了插件,先找一个游离的 `node` 僵尸进程并 `taskkill /F` 掉它。
188
+
189
+ **开发期绊线。** 作为防止 reconnect-by-recreate bug 溜进生产的兜底,`CtpClient` 维护一个进程级
190
+ 计数:被启动(`Init`)后又关闭(`Release`)的客户端数,越过阈值(默认 3——刻意低于约 4 次的死锁
191
+ 点,使警告在典型卡死前的那次 `close()` 上打印;更高的值就来不及触发了)时打印一次性的
192
+ `console.warn`。它只在 `close()` 上运行——绝不在热数据路径上——故在延迟攸关处零成本,而一个
193
+ create-once 的应用(一两个长期存活、关闭时才 close 的客户端)永不触发它。用 `CTP_RECREATE_WARN`
194
+ 环境变量调节或禁用:`CTP_RECREATE_WARN=0` 禁用;任意正整数设置阈值。
195
+
196
+ ## 背压与行情响应
197
+
198
+ 行情环是 `DropPolicy::Oldest`:当 JS 消费者落后一整环(8192 条记录)于 tick 洪流时,新记录进入
199
+ 有界的 keep-newest 暂存队列,并优先淘汰较旧的**可丢 tick**;它不会覆盖 JS 正在解码的字节,且会保留最新暂存 tick。请求响应
200
+ (`OnRspUserLogin` / `OnRspUserLogout` / `OnRspQryMulticastInstrument`)与流式 tick 共用这个环,
201
+ 但会被标记为不可丢;即使因此暂时超过 tick 容量也会保留。JS 事件循环若长期停顿,响应仍可能延迟到
202
+ 等待 Promise 的空闲超时(`requestTimeoutMs`,默认 30 秒),但通道不会主动丢弃它。
203
+
204
+ **交易端**使用 `DropPolicy::Lossless`:4096 槽满后进入有序溢出队列,再随消费者前进回填。
205
+ 它不主动丢回报,但持续消费停顿会增长内存。