@hitrading/ctp-node 1.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 (102) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +208 -0
  3. package/README.zh-CN.md +185 -0
  4. package/binding.gyp +90 -0
  5. package/dist/client.d.ts +115 -0
  6. package/dist/client.d.ts.map +1 -0
  7. package/dist/client.js +466 -0
  8. package/dist/client.js.map +1 -0
  9. package/dist/codec.d.ts +29 -0
  10. package/dist/codec.d.ts.map +1 -0
  11. package/dist/codec.js +131 -0
  12. package/dist/codec.js.map +1 -0
  13. package/dist/generated/enums.gen.d.ts +2257 -0
  14. package/dist/generated/enums.gen.d.ts.map +1 -0
  15. package/dist/generated/enums.gen.js +2576 -0
  16. package/dist/generated/enums.gen.js.map +1 -0
  17. package/dist/generated/structs.gen.d.ts +11041 -0
  18. package/dist/generated/structs.gen.d.ts.map +1 -0
  19. package/dist/generated/structs.gen.js +939 -0
  20. package/dist/generated/structs.gen.js.map +1 -0
  21. package/dist/generated/trader.gen.d.ts +273 -0
  22. package/dist/generated/trader.gen.d.ts.map +1 -0
  23. package/dist/generated/trader.gen.js +653 -0
  24. package/dist/generated/trader.gen.js.map +1 -0
  25. package/dist/index.d.ts +9 -0
  26. package/dist/index.d.ts.map +1 -0
  27. package/dist/index.js +9 -0
  28. package/dist/index.js.map +1 -0
  29. package/dist/market-data.d.ts +66 -0
  30. package/dist/market-data.d.ts.map +1 -0
  31. package/dist/market-data.js +105 -0
  32. package/dist/market-data.js.map +1 -0
  33. package/dist/native-binding.d.ts +2 -0
  34. package/dist/native-binding.d.ts.map +1 -0
  35. package/dist/native-binding.js +22 -0
  36. package/dist/native-binding.js.map +1 -0
  37. package/dist/trader.d.ts +234 -0
  38. package/dist/trader.d.ts.map +1 -0
  39. package/dist/trader.js +388 -0
  40. package/dist/trader.js.map +1 -0
  41. package/package.json +69 -0
  42. package/prebuilds/linux-x64/@hitrading+ctp-node.node +0 -0
  43. package/prebuilds/linux-x64/thostmduserapi_se.so +0 -0
  44. package/prebuilds/linux-x64/thosttraderapi_se.so +0 -0
  45. package/prebuilds/win32-x64/@hitrading+ctp-node.node +0 -0
  46. package/prebuilds/win32-x64/thostmduserapi_se.dll +0 -0
  47. package/prebuilds/win32-x64/thosttraderapi_se.dll +0 -0
  48. package/src/addon.cc +171 -0
  49. package/src/client.ts +539 -0
  50. package/src/codec.ts +160 -0
  51. package/src/generated/enums.gen.ts +2576 -0
  52. package/src/generated/layout.gen.cc +5771 -0
  53. package/src/generated/layout.gen.h +8 -0
  54. package/src/generated/structids.gen.h +470 -0
  55. package/src/generated/structs.gen.ts +12437 -0
  56. package/src/generated/trader.gen.ts +656 -0
  57. package/src/generated/traderreq.gen.cc +706 -0
  58. package/src/generated/traderreq.gen.h +127 -0
  59. package/src/generated/traderspi.gen.cc +636 -0
  60. package/src/generated/traderspi.gen.h +334 -0
  61. package/src/index.ts +14 -0
  62. package/src/market-data.ts +145 -0
  63. package/src/native/arm.cc +77 -0
  64. package/src/native/arm.h +71 -0
  65. package/src/native/channel.cc +175 -0
  66. package/src/native/channel.h +117 -0
  67. package/src/native/gbk.cc +54 -0
  68. package/src/native/gbk.h +17 -0
  69. package/src/native/mdapi.cc +412 -0
  70. package/src/native/mdapi.h +14 -0
  71. package/src/native/mdspi.cc +103 -0
  72. package/src/native/mdspi.h +81 -0
  73. package/src/native/risk.cc +461 -0
  74. package/src/native/risk.h +183 -0
  75. package/src/native/traderapi.cc +533 -0
  76. package/src/native/traderapi.h +14 -0
  77. package/src/native-binding.ts +25 -0
  78. package/src/trader.ts +522 -0
  79. package/tradeapi/ThostFtdcMdApi.h +168 -0
  80. package/tradeapi/ThostFtdcTraderApi.h +914 -0
  81. package/tradeapi/ThostFtdcUserApiDataType.h +7068 -0
  82. package/tradeapi/ThostFtdcUserApiStruct.h +12386 -0
  83. package/tradeapi/error.dtd +9 -0
  84. package/tradeapi/error.xml +284 -0
  85. package/tradeapi/linux/thostmduserapi_se.so +0 -0
  86. package/tradeapi/linux/thosttraderapi_se.so +0 -0
  87. package/tradeapi/macos/thostmduserapi_se.framework/Versions/A/Headers/ThostFtdcMdApi.h +168 -0
  88. package/tradeapi/macos/thostmduserapi_se.framework/Versions/A/Headers/ThostFtdcUserApiDataType.h +7068 -0
  89. package/tradeapi/macos/thostmduserapi_se.framework/Versions/A/Headers/ThostFtdcUserApiStruct.h +12386 -0
  90. package/tradeapi/macos/thostmduserapi_se.framework/Versions/A/Resources/Info.plist +46 -0
  91. package/tradeapi/macos/thostmduserapi_se.framework/Versions/A/_CodeSignature/CodeResources +149 -0
  92. package/tradeapi/macos/thostmduserapi_se.framework/Versions/A/thostmduserapi_se +0 -0
  93. package/tradeapi/macos/thosttraderapi_se.framework/Versions/A/Headers/ThostFtdcTraderApi.h +914 -0
  94. package/tradeapi/macos/thosttraderapi_se.framework/Versions/A/Headers/ThostFtdcUserApiDataType.h +7068 -0
  95. package/tradeapi/macos/thosttraderapi_se.framework/Versions/A/Headers/ThostFtdcUserApiStruct.h +12386 -0
  96. package/tradeapi/macos/thosttraderapi_se.framework/Versions/A/Resources/Info.plist +46 -0
  97. package/tradeapi/macos/thosttraderapi_se.framework/Versions/A/_CodeSignature/CodeResources +149 -0
  98. package/tradeapi/macos/thosttraderapi_se.framework/Versions/A/thosttraderapi_se +0 -0
  99. package/tradeapi/windows/thostmduserapi_se.dll +0 -0
  100. package/tradeapi/windows/thostmduserapi_se.lib +0 -0
  101. package/tradeapi/windows/thosttraderapi_se.dll +0 -0
  102. package/tradeapi/windows/thosttraderapi_se.lib +0 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,208 @@
1
+ <!-- LANG-SWITCH -->
2
+ <p align="right"><b>English</b> · <a href="README.zh-CN.md">简体中文</a></p>
3
+
4
+ <h1 align="center">ctp-node</h1>
5
+
6
+ <p align="center">
7
+ <b>High-performance, type-safe <a href="http://www.sfit.com.cn/">CTP</a> (上期技术) binding for Node.js</b><br/>
8
+ for programmatic / quantitative Chinese-futures trading.
9
+ </p>
10
+
11
+ <p align="center">
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
+ <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">
15
+ <img alt="Platform" src="https://img.shields.io/badge/platform-Windows%20%7C%20Linux%20%7C%20macOS-lightgrey">
16
+ <img alt="TypeScript" src="https://img.shields.io/badge/TypeScript-strict-3178c6">
17
+ <img alt="decode" src="https://img.shields.io/badge/decode-~8M%20ticks%2Fs-ff7f0e">
18
+ </p>
19
+
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">
22
+ </p>
23
+
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).
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.
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
+
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
+
32
+ ## Requirements
33
+
34
+ Node ≥ 18. Prebuilt binaries are shipped for Windows/Linux/macOS (x64), so most users need no compiler. Other platforms build from source on install and need a C++ toolchain (Windows: VS Build Tools; Linux/macOS: clang/gcc). The CTP shared libraries are bundled next to the loaded addon and resolved automatically.
35
+
36
+ ## Install
37
+
38
+ ```sh
39
+ npm install @hitrading/ctp-node
40
+ ```
41
+
42
+ ## Documentation
43
+
44
+ - **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)
45
+ - 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)
46
+ - **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)
47
+ - **Releasing** — fully automatic `semantic-release` (Conventional Commits → version + CHANGELOG + GitHub Release + npm publish): [RELEASING.md](RELEASING.md) · [CHANGELOG.md](CHANGELOG.md)
48
+
49
+ ## Quick start — market data
50
+
51
+ ```ts
52
+ import { MarketData } from "@hitrading/ctp-node";
53
+
54
+ const md = new MarketData("./flow/md/", "tcp://180.168.146.187:10212");
55
+
56
+ md.on("front-connected", async () => {
57
+ await md.login({ brokerId: "9999", userId: "xxxx", password: "xxxx" });
58
+ md.subscribe(["rb2510", "ag2512"]);
59
+ });
60
+
61
+ md.on("rtn-depth-market-data", (tick) => {
62
+ // tick is a plain object with camelCase fields
63
+ console.log(tick.instrumentId, tick.lastPrice, tick.bidPrice1, tick.askPrice1);
64
+ });
65
+ ```
66
+
67
+ ## Quick start — trading
68
+
69
+ ```ts
70
+ import { Trader } from "@hitrading/ctp-node";
71
+
72
+ const td = new Trader("./flow/td/", "tcp://180.168.146.187:10202");
73
+
74
+ // Pre-trade risk, enforced in C++ on every order:
75
+ td.riskSet({ maxOrderVolume: 10, maxOrdersPerSec: 20, maxPriceDeviation: 0.02, maxPositionCost: 5_000_000 });
76
+ td.trackMarketData(md); // feed live prices for the price-deviation guard
77
+ td.setMaxPositions({ rb2610: 100, au2610: 10, ru2610: { long: 100, short: 20 } }); // per-instrument lot caps
78
+ td.setMaxPositionCosts({ ag2608: 2_000_000, au2608: 5_000_000 }); // per-instrument cost caps
79
+
80
+ td.on("front-connected", async () => {
81
+ // One-call handshake (call again after a reconnect): authenticate → login →
82
+ // confirm settlement → sync multipliers / positions / orders. Risk inputs are
83
+ // fetched from CTP automatically — no manual multipliers/seeding.
84
+ await td.session({ brokerId, userId, password, appId, authCode });
85
+
86
+ // ...or hand-roll it if you need finer control:
87
+ // await td.reqAuthenticate({ brokerId, userId, appId, authCode });
88
+ // await td.reqUserLogin({ brokerId, userId, password });
89
+ // await td.reqSettlementInfoConfirm({ brokerId, investorId }); // real accounts
90
+ // await td.syncMultipliers(); await td.syncPositions(); await td.syncOrders();
91
+
92
+ // Promise-based queries return all rows:
93
+ const positions = await td.reqQryInvestorPosition({ brokerId, investorId });
94
+
95
+ // Orders go through the C++ risk gate. reqOrderInsert resolves on submission
96
+ // (CTP sends no ack for an accepted order); track the outcome via rtn-order /
97
+ // rtn-trade. orderRef is auto-assigned a unique value if you leave it blank.
98
+ await td.reqOrderInsert({
99
+ brokerId, investorId, instrumentId: "rb2510",
100
+ direction: "0", // see Direction enum
101
+ limitPrice: 3500, volumeTotalOriginal: 1,
102
+ });
103
+ });
104
+
105
+ td.on("rtn-order", (order) => console.log("order update", order.orderStatus));
106
+ td.on("rtn-trade", (trade) => console.log("filled", trade.price, trade.volume));
107
+
108
+ // Emergency kill-switch (blocks all sends in C++ immediately):
109
+ // td.halt(); / td.resume();
110
+ ```
111
+
112
+ ### Armed orders (latency-critical)
113
+
114
+ Fire an order from C++ the instant the market hits your trigger — evaluated on
115
+ the market-data callback thread, through the risk gate, with **no JS in the
116
+ loop** (no event-loop hop, no GC exposure):
117
+
118
+ ```ts
119
+ const armed = trader.arm(md, {
120
+ instrumentId: "rb2510",
121
+ side: "buy", // buy fires when ask ≤ trigger; sell when bid ≥ trigger
122
+ triggerPrice: 3500,
123
+ order: {
124
+ brokerId, investorId, instrumentId: "rb2510", direction: "0",
125
+ limitPrice: 3500, volumeTotalOriginal: 1, orderRef: "snipe-1",
126
+ },
127
+ });
128
+ // One-shot. The ack/fill arrives via the normal rtn-order events (match orderRef).
129
+ // armed.disarm();
130
+ ```
131
+
132
+ Enums are exported and typed:
133
+
134
+ ```ts
135
+ import { Direction, OffsetFlag } from "@hitrading/ctp-node";
136
+ Direction.Buy; // "0"
137
+ Direction.Sell; // "1"
138
+ ```
139
+
140
+ ## API shape
141
+
142
+ - `new MarketData(flowPath, fronts)` / `new Trader(flowPath, fronts)` — `fronts` is a `tcp://` address or an array.
143
+ - 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.
144
+ - 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).
145
+ - Streaming events use kebab-case names (`rtn-depth-market-data`, `rtn-order`, …); handlers get `(data, options)` where `options` carries `{ requestId?, isLast?, rspInfo? }`.
146
+ - `client.droppedRecords` reports records dropped under backpressure. Market
147
+ data drops the **oldest** unread record (so you always see the freshest quote);
148
+ the trader drops the **newest** instead, so a queued order/trade return is never
149
+ silently discarded. Monitor it either way.
150
+ - `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)).
151
+
152
+ ## Lifecycle: create once, reuse
153
+
154
+ Create a `MarketData` / `Trader` **once** and keep it for the life of the
155
+ process. CTP reconnects on its own; handle a dropped link **in place** by
156
+ re-running your handshake when `front-connected` fires again (it fires on the
157
+ first connect *and* on every auto-reconnect) — never by destroying and
158
+ recreating the client.
159
+
160
+ ```ts
161
+ const md = new MarketData("./flow/md/", front);
162
+ md.on("front-connected", async () => { // first connect AND every reconnect
163
+ await md.login({ brokerId, userId, password });
164
+ md.subscribe(["rb2510"]);
165
+ });
166
+ // Trader: re-run the one-call handshake the same way
167
+ td.on("front-connected", () => td.session({ brokerId, userId, password, appId, authCode }));
168
+ ```
169
+
170
+ > **Why.** `close()` calls the vendor `CThostFtdc*Api::Release()`, and the CTP
171
+ > DLLs **deadlock inside `Release()` after a few `Init()`/`Release()` cycles in
172
+ > one process** — a limitation of the CTP SDK itself, not of this binding. A
173
+ > "reconnect by recreate" loop will hang the whole process (and on Windows the
174
+ > wedged process ignores `SIGTERM`, so it must be force-killed with `taskkill /F`
175
+ > — until then it locks `build\Release\ctp.node` and breaks the next native
176
+ > build). Construct each client once and call `close()` only at shutdown. A
177
+ > one-time `console.warn` fires if an unusual number of clients are
178
+ > created/closed in a process (tune/disable with `CTP_RECREATE_WARN`). Details:
179
+ > [docs/native-hooks.md](docs/native-hooks.md#process-lifecycle-create-once-reuse).
180
+
181
+ ## Architecture
182
+
183
+ ```
184
+ CTP callback thread (C++) Node event loop (JS)
185
+ OnRtn.../OnRsp... → memcpy bytes ──► coalesced doorbell → drain whole batch
186
+ into lock-free SPSC ring, → decode each record from the ring
187
+ bump atomic index, ring doorbell (monomorphic generated decoder)
188
+ (on overflow: MD drops oldest, → plain object → emit / resolve
189
+ trader drops newest/reliable)
190
+ ```
191
+
192
+ Everything below the public API is generated from the CTP headers
193
+ (`tradeapi/ThostFtdc*.h`) by `scripts/codegen/` — 466 struct interfaces, 318
194
+ enums, field layout tables (via `offsetof`), and the full trader SPI + request
195
+ dispatch. Run `npm run gen` after updating the headers.
196
+
197
+ ## Build from source
198
+
199
+ ```sh
200
+ npm run gen # regenerate from CTP headers
201
+ npm run build # gen + native (node-gyp) + tsc
202
+ npm test # codec round-trip + md + trader (no network needed)
203
+ npm run bench # decode throughput
204
+ ```
205
+
206
+ ## License
207
+
208
+ Apache-2.0
@@ -0,0 +1,185 @@
1
+ <!-- LANG-SWITCH -->
2
+ <p align="right"><a href="README.md">English</a> · <b>简体中文</b></p>
3
+
4
+ <h1 align="center">ctp-node</h1>
5
+
6
+ <p align="center">
7
+ <b>面向 Node.js 的高性能、类型安全的 <a href="http://www.sfit.com.cn/">CTP</a>(上期技术)绑定</b><br/>
8
+ 用于程序化 / 量化期货交易。
9
+ </p>
10
+
11
+ <p align="center">
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
+ <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">
15
+ <img alt="Platform" src="https://img.shields.io/badge/platform-Windows%20%7C%20Linux%20%7C%20macOS-lightgrey">
16
+ <img alt="TypeScript" src="https://img.shields.io/badge/TypeScript-strict-3178c6">
17
+ <img alt="decode" src="https://img.shields.io/badge/decode-~8M%20ticks%2Fs-ff7f0e">
18
+ </p>
19
+
20
+ <p align="center">
21
+ <img src="docs/assets/validation.svg" alt="ctp-node 验证 —— 测试套件全绿 + 全市场实盘压测(18,111 合约,0 丢弃)" width="780">
22
+ </p>
23
+
24
+ - **纯对象、地道的 TypeScript。** 每个 CTP 结构体都是生成的 `interface`,字段为 camelCase(`tick.lastPrice`、`tick.instrumentId`);每个 CTP 枚举都是真正的 TS `enum`。无手写编解码。
25
+ - **快。** CTP 回调线程只把字节 memcpy 进无锁环;JS 直接从环里解码成纯对象,**约 800 万 tick/秒**(相对 5 万/秒的开盘集合竞价突发有 166 倍余量)。
26
+ - **混合 API。** 流式推送用 `EventEmitter`(`rtn-depth-market-data`、`rtn-order` 等)+ 请求/响应用 `Promise`(登录、查询、报单),按 request id 关联并支持多行累积。
27
+ - **盘前风控在 C++ 中。** 一键熔断、单笔最大手数、最大名义价值、价格偏离(防胖手指)、账户级与按合约的开仓持仓成本上限、按合约的最大持仓(手数、分边)、以及令牌桶限频器,都在原生代码里、报单路径上执行——JS 的 GC 停顿打不垮它们。
28
+ - **构造即稳定。** 无手写编解码、threadsafe-function 正确释放、`Init()` 延后以保证 `front-connected` 不丢失、编译器真值(`offsetof`)的二进制布局、GB18030 在 JS 解码(无 Windows 代码页 bug)。
29
+
30
+ > 面向 CTP 实际支持的范畴(快照驱动、容忍毫秒级的策略:CTA、套利、做市)。真正的微秒级 HFT 在任何语言下都无法通过 CTP 实现。
31
+
32
+ ## 环境要求
33
+
34
+ Node ≥ 18。Windows/Linux/macOS(x64)提供预编译二进制,多数用户无需编译器。其他平台在安装时从源码构建,需要 C++ 工具链(Windows:VS Build Tools;Linux/macOS:clang/gcc)。CTP 共享库随插件一起打包在旁并自动解析。
35
+
36
+ ## 安装
37
+
38
+ ```sh
39
+ npm install @hitrading/ctp-node
40
+ ```
41
+
42
+ ## 文档
43
+
44
+ - **完整 API 参考** —— 每一个 TypeScript/JavaScript 接口和方法,含每个参数的类型与含义,以及用法示例:[English](docs/API.md) · [简体中文](docs/API.zh-CN.md)
45
+ - 架构与原生内部 —— 无锁数据平面、C++ 风控引擎、背压,以及一次创建的进程生命周期说明:[English](docs/native-hooks.md) · [简体中文](docs/native-hooks.zh-CN.md)
46
+ - **故障排查与 FAQ** —— 连接/前置轮换、登录与认证、查询限频、报单被拒、跌停、生命周期、构建问题、CTP 错误码:[English](docs/troubleshooting.md) · [简体中文](docs/troubleshooting.zh-CN.md)
47
+ - **发布** —— 全自动 `semantic-release`(Conventional Commits → 版本号 + CHANGELOG + GitHub Release + npm 发布):[RELEASING.md](RELEASING.md) · [CHANGELOG.md](CHANGELOG.md)
48
+
49
+ ## 快速开始 —— 行情
50
+
51
+ ```ts
52
+ import { MarketData } from "@hitrading/ctp-node";
53
+
54
+ const md = new MarketData("./flow/md/", "tcp://182.254.243.31:30012");
55
+
56
+ md.on("front-connected", async () => {
57
+ await md.login({ brokerId: "9999", userId: "xxxx", password: "xxxx" });
58
+ md.subscribe(["rb2510", "ag2512"]);
59
+ });
60
+
61
+ md.on("rtn-depth-market-data", (tick) => {
62
+ // tick 是带 camelCase 字段的纯对象
63
+ console.log(tick.instrumentId, tick.lastPrice, tick.bidPrice1, tick.askPrice1);
64
+ });
65
+ ```
66
+
67
+ ## 快速开始 —— 交易
68
+
69
+ ```ts
70
+ import { Trader } from "@hitrading/ctp-node";
71
+
72
+ const td = new Trader("./flow/td/", "tcp://182.254.243.31:30002");
73
+
74
+ // 盘前风控,在 C++ 中对每笔报单执行:
75
+ td.riskSet({ maxOrderVolume: 10, maxOrdersPerSec: 20, maxPriceDeviation: 0.02, maxPositionCost: 5_000_000 });
76
+ td.trackMarketData(md); // 为价格偏离校验喂入实时价
77
+ td.setMaxPositions({ rb2610: 100, au2610: 10, ru2610: { long: 100, short: 20 } }); // 按合约手数上限
78
+ td.setMaxPositionCosts({ ag2608: 2_000_000, au2608: 5_000_000 }); // 按合约成本上限
79
+
80
+ td.on("front-connected", async () => {
81
+ // 一站式握手(重连后再调一次):认证 → 登录 → 确认结算单 → 同步乘数 / 持仓 / 报单。
82
+ // 风控输入自动从 CTP 拉取——无需手动设乘数/播种。
83
+ await td.session({ brokerId, userId, password, appId, authCode });
84
+
85
+ // ……或在需要更细控制时手写:
86
+ // await td.reqAuthenticate({ brokerId, userId, appId, authCode });
87
+ // await td.reqUserLogin({ brokerId, userId, password });
88
+ // await td.reqSettlementInfoConfirm({ brokerId, investorId }); // 实盘账户
89
+ // await td.syncMultipliers(); await td.syncPositions(); await td.syncOrders();
90
+
91
+ // 基于 Promise 的查询返回所有行:
92
+ const positions = await td.reqQryInvestorPosition({ brokerId, investorId });
93
+
94
+ // 报单走 C++ 风控网关。reqOrderInsert 提交成功即 resolve(CTP 对已接受的报单
95
+ // 不返回 ack);通过 rtn-order / rtn-trade 跟踪结果。orderRef 留空会自动分配唯一值。
96
+ await td.reqOrderInsert({
97
+ brokerId, investorId, instrumentId: "rb2510",
98
+ direction: "0", // 见 Direction 枚举
99
+ limitPrice: 3500, volumeTotalOriginal: 1,
100
+ });
101
+ });
102
+
103
+ td.on("rtn-order", (order) => console.log("报单更新", order.orderStatus));
104
+ td.on("rtn-trade", (trade) => console.log("已成交", trade.price, trade.volume));
105
+
106
+ // 应急一键熔断(在 C++ 中立即拦截所有发送):
107
+ // td.halt(); / td.resume();
108
+ ```
109
+
110
+ ### 预埋单(延迟攸关)
111
+
112
+ 在市场触及你的触发条件的瞬间从 C++ 发出报单——在行情回调线程上判定,穿过风控网关,**JS 不在回路中**(无事件循环跳转、无 GC 暴露):
113
+
114
+ ```ts
115
+ const armed = trader.arm(md, {
116
+ instrumentId: "rb2510",
117
+ side: "buy", // buy 在 ask ≤ trigger 时触发;sell 在 bid ≥ trigger 时触发
118
+ triggerPrice: 3500,
119
+ order: {
120
+ brokerId, investorId, instrumentId: "rb2510", direction: "0",
121
+ limitPrice: 3500, volumeTotalOriginal: 1, orderRef: "snipe-1",
122
+ },
123
+ });
124
+ // 一次性。回执/成交经普通的 rtn-order 事件到达(按 orderRef 匹配)。
125
+ // armed.disarm();
126
+ ```
127
+
128
+ 枚举已导出且带类型:
129
+
130
+ ```ts
131
+ import { Direction, OffsetFlag } from "@hitrading/ctp-node";
132
+ Direction.Buy; // "0"
133
+ Direction.Sell; // "1"
134
+ ```
135
+
136
+ ## API 形态
137
+
138
+ - `new MarketData(flowPath, fronts)` / `new Trader(flowPath, fronts)` —— `fronts` 是一个 `tcp://` 地址或数组。
139
+ - 请求是 camelCase 方法,接受 CTP 字段对象的 `Partial<...>` 并返回 `Promise`。`reqQry*` 以行数组 resolve;多数请求以单条响应行 resolve。
140
+ - 发往交易所的 insert/action(`reqOrderInsert`、`reqOrderAction` 等)**提交成功即** resolve —— CTP 对已接受的报单不返回成功响应,只有 `rtn-order` / `rtn-trade`(用 `orderRef` 关联)。只有发送被拒(风控网关、限频、或 CTP API 错误码)才 reject。
141
+ - 流式事件用 kebab-case 名称(`rtn-depth-market-data`、`rtn-order` 等);处理函数收到 `(data, options)`,`options` 带 `{ requestId?, isLast?, rspInfo? }`。
142
+ - `client.droppedRecords` 报告背压下丢弃的记录数。行情丢弃**最旧**的未读记录(使你总能看到最新报价);交易端则丢弃**最新**的,使排队中的报单/成交回报永不被静默丢弃。两者都应监控。
143
+ - `client.close()` 释放底层 CTP API。在关闭时调用**一次**——CTP 客户端是一次创建/复用的;靠重建来重连会在厂商 DLL 里死锁(见[生命周期](#生命周期-一次创建并复用))。
144
+
145
+ ## 生命周期 一次创建并复用
146
+
147
+ `MarketData` / `Trader` 只创建**一次**并持有到进程结束。CTP 会自行重连;通过在 `front-connected` 再次触发(首次连接 *以及* 每次自动重连都会触发)时原地重跑握手来**原地**处理断线——绝不要销毁再重建客户端。
148
+
149
+ ```ts
150
+ const md = new MarketData("./flow/md/", front);
151
+ md.on("front-connected", async () => { // 首次连接和每次重连
152
+ await md.login({ brokerId, userId, password });
153
+ md.subscribe(["rb2510"]);
154
+ });
155
+ // Trader 同样:原地重跑一站式握手
156
+ td.on("front-connected", () => td.session({ brokerId, userId, password, appId, authCode }));
157
+ ```
158
+
159
+ > **为什么。** `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#进程生命周期-一次创建并复用)。
160
+
161
+ ## 架构
162
+
163
+ ```
164
+ CTP 回调线程 (C++) Node 事件循环 (JS)
165
+ OnRtn.../OnRsp... → memcpy 字节 ──► 合并的门铃 → 整批排空
166
+ 进无锁 SPSC 环、 → 从环里逐条解码
167
+ 自增原子索引、敲门铃 (单态生成的解码器)
168
+ (溢出时:行情丢最旧、 → 纯对象 → emit / resolve
169
+ 交易端丢最新/可靠)
170
+ ```
171
+
172
+ 公开 API 之下的一切都由 CTP 头文件(`tradeapi/ThostFtdc*.h`)经 `scripts/codegen/` 生成—— 466 个结构体接口、318 个枚举、字段布局表(经 `offsetof`),以及完整的 trader SPI + 请求分发。更新头文件后运行 `npm run gen`。
173
+
174
+ ## 从源码构建
175
+
176
+ ```sh
177
+ npm run gen # 从 CTP 头文件重新生成
178
+ npm run build # gen + 原生 (node-gyp) + tsc
179
+ npm test # 编解码往返 + md + trader(无需网络)
180
+ npm run bench # 解码吞吐
181
+ ```
182
+
183
+ ## 许可证
184
+
185
+ Apache-2.0