@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
@@ -0,0 +1,412 @@
1
+ /*
2
+ * mdapi.cc - MarketData N-API class (ObjectWrap).
3
+ *
4
+ * Low-level surface consumed by src/market-data.ts. The JS wrapper adds the
5
+ * EventEmitter + Promise ergonomics and the binary->plain-object decode.
6
+ *
7
+ * Lifecycle note: Init() is deferred to _start(), which is called by JS only
8
+ * after the drain callback is wired up - so the front-connected event cannot be
9
+ * missed (fixes the constructor-time race in the original binding).
10
+ */
11
+
12
+ #include "mdapi.h"
13
+
14
+ #include <chrono>
15
+ #include <cstdio>
16
+ #include <cstring>
17
+ #include <memory>
18
+ #include <string>
19
+ #include <thread>
20
+ #include <vector>
21
+
22
+ #include "../generated/layout.gen.h"
23
+ #include "../generated/structids.gen.h"
24
+ #include "ThostFtdcMdApi.h"
25
+ #include "channel.h"
26
+ #include "mdspi.h"
27
+
28
+ namespace ctp {
29
+
30
+ namespace {
31
+
32
+ void getStr(const Napi::Object &o, const char *key, char *dst, size_t cap) {
33
+ if (!o.Has(key))
34
+ return;
35
+ Napi::Value v = o.Get(key);
36
+ if (!v.IsString())
37
+ return;
38
+ std::string s = v.As<Napi::String>().Utf8Value();
39
+ std::snprintf(dst, cap, "%s", s.c_str());
40
+ }
41
+
42
+ std::vector<std::string> toStringList(const Napi::Value &v) {
43
+ std::vector<std::string> out;
44
+ if (v.IsArray()) {
45
+ Napi::Array a = v.As<Napi::Array>();
46
+ for (uint32_t i = 0; i < a.Length(); ++i)
47
+ out.push_back(a.Get(i).As<Napi::String>().Utf8Value());
48
+ } else if (v.IsString()) {
49
+ out.push_back(v.As<Napi::String>().Utf8Value());
50
+ }
51
+ return out;
52
+ }
53
+
54
+ } // namespace
55
+
56
+ class MarketData : public Napi::ObjectWrap<MarketData> {
57
+ public:
58
+ static Napi::Function Init(Napi::Env env);
59
+ MarketData(const Napi::CallbackInfo &info);
60
+ ~MarketData();
61
+
62
+ private:
63
+ void doClose();
64
+ int subscribeImpl(const Napi::CallbackInfo &info,
65
+ int (CThostFtdcMdApi::*fn)(char *[], int));
66
+
67
+ Napi::Value GetApiVersion(const Napi::CallbackInfo &info);
68
+ Napi::Value GetTradingDay(const Napi::CallbackInfo &info);
69
+ Napi::Value SubscribeMarketData(const Napi::CallbackInfo &info);
70
+ Napi::Value UnsubscribeMarketData(const Napi::CallbackInfo &info);
71
+ Napi::Value SubscribeForQuoteRsp(const Napi::CallbackInfo &info);
72
+ Napi::Value UnsubscribeForQuoteRsp(const Napi::CallbackInfo &info);
73
+ Napi::Value ReqUserLogin(const Napi::CallbackInfo &info);
74
+ Napi::Value ReqUserLogout(const Napi::CallbackInfo &info);
75
+ Napi::Value Start(const Napi::CallbackInfo &info);
76
+ Napi::Value Buffer(const Napi::CallbackInfo &info);
77
+ Napi::Value ClaimBatch(const Napi::CallbackInfo &info);
78
+ Napi::Value ValidateBatch(const Napi::CallbackInfo &info);
79
+ Napi::Value ReadIndex(const Napi::CallbackInfo &info);
80
+ Napi::Value ReleaseBatch(const Napi::CallbackInfo &info);
81
+ Napi::Value DropCount(const Napi::CallbackInfo &info);
82
+ Napi::Value ChannelInfo(const Napi::CallbackInfo &info);
83
+ Napi::Value Close(const Napi::CallbackInfo &info);
84
+ Napi::Value AttachArm(const Napi::CallbackInfo &info);
85
+ Napi::Value InjectTestTick(const Napi::CallbackInfo &info);
86
+ Napi::Value BurstTicks(const Napi::CallbackInfo &info);
87
+
88
+ CThostFtdcMdApi *api_ = nullptr;
89
+ MdSpi *spi_ = nullptr;
90
+ EventChannel *ch_ = nullptr;
91
+ std::shared_ptr<ArmRegistry> armReg_;
92
+ bool started_ = false;
93
+ bool closed_ = false;
94
+ // test-only background producer thread (doorbell cross-thread stress).
95
+ std::thread burst_;
96
+ };
97
+
98
+ Napi::Function MarketData::Init(Napi::Env env) {
99
+ return DefineClass(
100
+ env, "MarketData",
101
+ {
102
+ InstanceMethod("getApiVersion", &MarketData::GetApiVersion),
103
+ InstanceMethod("getTradingDay", &MarketData::GetTradingDay),
104
+ InstanceMethod("subscribeMarketData", &MarketData::SubscribeMarketData),
105
+ InstanceMethod("unsubscribeMarketData", &MarketData::UnsubscribeMarketData),
106
+ InstanceMethod("subscribeForQuoteRsp", &MarketData::SubscribeForQuoteRsp),
107
+ InstanceMethod("unsubscribeForQuoteRsp", &MarketData::UnsubscribeForQuoteRsp),
108
+ InstanceMethod("reqUserLogin", &MarketData::ReqUserLogin),
109
+ InstanceMethod("reqUserLogout", &MarketData::ReqUserLogout),
110
+ InstanceMethod("_start", &MarketData::Start),
111
+ InstanceMethod("_buffer", &MarketData::Buffer),
112
+ InstanceMethod("_claim", &MarketData::ClaimBatch),
113
+ InstanceMethod("_validate", &MarketData::ValidateBatch),
114
+ InstanceMethod("_readIndex", &MarketData::ReadIndex),
115
+ InstanceMethod("_release", &MarketData::ReleaseBatch),
116
+ InstanceMethod("_dropCount", &MarketData::DropCount),
117
+ InstanceMethod("_info", &MarketData::ChannelInfo),
118
+ InstanceMethod("_attachArm", &MarketData::AttachArm),
119
+ InstanceMethod("_injectTestTick", &MarketData::InjectTestTick),
120
+ InstanceMethod("_burstTicks", &MarketData::BurstTicks),
121
+ InstanceMethod("close", &MarketData::Close),
122
+ });
123
+ }
124
+
125
+ MarketData::MarketData(const Napi::CallbackInfo &info)
126
+ : Napi::ObjectWrap<MarketData>(info) {
127
+ Napi::Env env = info.Env();
128
+ if (info.Length() < 2 || !info[0].IsString()) {
129
+ Napi::TypeError::New(env, "MarketData(flowPath, fronts)")
130
+ .ThrowAsJavaScriptException();
131
+ return;
132
+ }
133
+ std::string flowPath = info[0].As<Napi::String>().Utf8Value();
134
+
135
+ // Validate fronts BEFORE allocating anything: RegisterFront("") faults deep
136
+ // inside the CTP DLL, so drop empty addresses and reject an empty result with
137
+ // a clean JS error rather than crashing the process.
138
+ std::vector<std::string> fronts;
139
+ for (auto &addr : toStringList(info[1]))
140
+ if (!addr.empty())
141
+ fronts.push_back(addr);
142
+ if (fronts.empty()) {
143
+ Napi::TypeError::New(
144
+ env, "MarketData: at least one non-empty front address is required")
145
+ .ThrowAsJavaScriptException();
146
+ return;
147
+ }
148
+
149
+ api_ = CThostFtdcMdApi::CreateFtdcMdApi(flowPath.c_str());
150
+ if (!api_) {
151
+ Napi::Error::New(env, "CreateFtdcMdApi failed").ThrowAsJavaScriptException();
152
+ return;
153
+ }
154
+ // Market data drops the OLDEST record under backpressure: a full-market feed
155
+ // wants the freshest quote, not a stale one, when the JS loop falls behind.
156
+ ch_ = new EventChannel(8192, static_cast<size_t>(ctpMaxStructSize()),
157
+ DropPolicy::Oldest);
158
+ spi_ = new MdSpi(api_, ch_);
159
+ api_->RegisterSpi(spi_);
160
+
161
+ for (auto &addr : fronts)
162
+ api_->RegisterFront(const_cast<char *>(addr.c_str()));
163
+ }
164
+
165
+ MarketData::~MarketData() { doClose(); }
166
+
167
+ void MarketData::doClose() {
168
+ if (closed_)
169
+ return;
170
+ closed_ = true;
171
+ // Join any test-only burst producer before tearing the channel down, so it
172
+ // can never push into a freed ring.
173
+ if (burst_.joinable())
174
+ burst_.join();
175
+ // Detach the SPI's api pointer BEFORE releasing the api, so a late callback
176
+ // (or the test tick hook) can never dereference the freed api.
177
+ if (spi_) {
178
+ spi_->clearApi();
179
+ spi_->setArmRegistry(nullptr);
180
+ }
181
+ if (api_) {
182
+ api_->Release(); // stops the CTP callback thread (no more push / onTick)
183
+ api_ = nullptr;
184
+ }
185
+ armReg_.reset();
186
+ // Free the SPI and the ring here, on close(), rather than waiting for the JS
187
+ // object's GC finalizer: the ring is large (~21 MB - maxStructSize * 8192
188
+ // slots) but invisible to V8, so the GC feels no pressure and a create/close
189
+ // loop balloons RSS (measured ~32 MB/cycle for MD+Trader, unreclaimed even by
190
+ // a forced GC) before finalizers ever run. The CTP producer thread is stopped
191
+ // (Release above) and the burst thread is joined, so nothing can push anymore;
192
+ // the doorbell is aborted in ~EventChannel via stop(). Accessors null-check.
193
+ if (spi_) {
194
+ delete spi_;
195
+ spi_ = nullptr;
196
+ }
197
+ if (ch_) {
198
+ ch_->stop(); // abort doorbell TSF (idempotent)
199
+ delete ch_;
200
+ ch_ = nullptr;
201
+ }
202
+ }
203
+
204
+ Napi::Value MarketData::GetApiVersion(const Napi::CallbackInfo &info) {
205
+ return Napi::String::New(info.Env(), CThostFtdcMdApi::GetApiVersion());
206
+ }
207
+
208
+ Napi::Value MarketData::GetTradingDay(const Napi::CallbackInfo &info) {
209
+ Napi::Env env = info.Env();
210
+ if (!api_)
211
+ return env.Null();
212
+ const char *d = api_->GetTradingDay();
213
+ return Napi::String::New(env, d ? d : "");
214
+ }
215
+
216
+ int MarketData::subscribeImpl(const Napi::CallbackInfo &info,
217
+ int (CThostFtdcMdApi::*fn)(char *[], int)) {
218
+ if (!api_)
219
+ return -1;
220
+ auto ids = toStringList(info[0]);
221
+ if (ids.empty())
222
+ return 0;
223
+ std::vector<char *> ptrs(ids.size());
224
+ for (size_t i = 0; i < ids.size(); ++i)
225
+ ptrs[i] = const_cast<char *>(ids[i].c_str());
226
+ return (api_->*fn)(ptrs.data(), static_cast<int>(ids.size()));
227
+ }
228
+
229
+ Napi::Value MarketData::SubscribeMarketData(const Napi::CallbackInfo &info) {
230
+ return Napi::Number::New(info.Env(),
231
+ subscribeImpl(info, &CThostFtdcMdApi::SubscribeMarketData));
232
+ }
233
+ Napi::Value MarketData::UnsubscribeMarketData(const Napi::CallbackInfo &info) {
234
+ return Napi::Number::New(
235
+ info.Env(), subscribeImpl(info, &CThostFtdcMdApi::UnSubscribeMarketData));
236
+ }
237
+ Napi::Value MarketData::SubscribeForQuoteRsp(const Napi::CallbackInfo &info) {
238
+ return Napi::Number::New(
239
+ info.Env(), subscribeImpl(info, &CThostFtdcMdApi::SubscribeForQuoteRsp));
240
+ }
241
+ Napi::Value MarketData::UnsubscribeForQuoteRsp(const Napi::CallbackInfo &info) {
242
+ return Napi::Number::New(
243
+ info.Env(), subscribeImpl(info, &CThostFtdcMdApi::UnSubscribeForQuoteRsp));
244
+ }
245
+
246
+ Napi::Value MarketData::ReqUserLogin(const Napi::CallbackInfo &info) {
247
+ Napi::Env env = info.Env();
248
+ if (!api_)
249
+ return Napi::Number::New(env, -1);
250
+ CThostFtdcReqUserLoginField req;
251
+ std::memset(&req, 0, sizeof(req));
252
+ if (info[0].IsObject()) {
253
+ Napi::Object o = info[0].As<Napi::Object>();
254
+ getStr(o, "tradingDay", req.TradingDay, sizeof(req.TradingDay));
255
+ getStr(o, "brokerId", req.BrokerID, sizeof(req.BrokerID));
256
+ getStr(o, "userId", req.UserID, sizeof(req.UserID));
257
+ getStr(o, "password", req.Password, sizeof(req.Password));
258
+ getStr(o, "userProductInfo", req.UserProductInfo, sizeof(req.UserProductInfo));
259
+ }
260
+ int id = info[1].As<Napi::Number>().Int32Value();
261
+ return Napi::Number::New(env, api_->ReqUserLogin(&req, id));
262
+ }
263
+
264
+ Napi::Value MarketData::ReqUserLogout(const Napi::CallbackInfo &info) {
265
+ Napi::Env env = info.Env();
266
+ if (!api_)
267
+ return Napi::Number::New(env, -1);
268
+ CThostFtdcUserLogoutField req;
269
+ std::memset(&req, 0, sizeof(req));
270
+ if (info[0].IsObject()) {
271
+ Napi::Object o = info[0].As<Napi::Object>();
272
+ getStr(o, "brokerId", req.BrokerID, sizeof(req.BrokerID));
273
+ getStr(o, "userId", req.UserID, sizeof(req.UserID));
274
+ }
275
+ int id = info[1].As<Napi::Number>().Int32Value();
276
+ return Napi::Number::New(env, api_->ReqUserLogout(&req, id));
277
+ }
278
+
279
+ Napi::Value MarketData::Start(const Napi::CallbackInfo &info) {
280
+ Napi::Env env = info.Env();
281
+ if (started_ || !api_)
282
+ return env.Undefined();
283
+ napi_status st = ch_->start(env, info[0]);
284
+ if (st != napi_ok) {
285
+ Napi::Error::New(env, "failed to start event channel")
286
+ .ThrowAsJavaScriptException();
287
+ return env.Undefined();
288
+ }
289
+ api_->Init();
290
+ started_ = true;
291
+ return env.Undefined();
292
+ }
293
+
294
+ Napi::Value MarketData::Buffer(const Napi::CallbackInfo &info) {
295
+ if (!ch_)
296
+ return info.Env().Undefined();
297
+ return Napi::ArrayBuffer::New(info.Env(), ch_->data(), ch_->byteLength());
298
+ }
299
+
300
+ Napi::Value MarketData::ClaimBatch(const Napi::CallbackInfo &info) {
301
+ return Napi::Number::New(info.Env(), ch_ ? ch_->claim() : 0);
302
+ }
303
+
304
+ Napi::Value MarketData::ValidateBatch(const Napi::CallbackInfo &info) {
305
+ uint32_t claimed = info[0].As<Napi::Number>().Uint32Value();
306
+ return Napi::Number::New(info.Env(), ch_ ? ch_->validate(claimed) : 0);
307
+ }
308
+
309
+ Napi::Value MarketData::ReadIndex(const Napi::CallbackInfo &info) {
310
+ return Napi::Number::New(
311
+ info.Env(), static_cast<double>(ch_ ? ch_->readIndex() : 0));
312
+ }
313
+
314
+ Napi::Value MarketData::ReleaseBatch(const Napi::CallbackInfo &info) {
315
+ if (ch_)
316
+ ch_->release(info[0].As<Napi::Number>().Uint32Value());
317
+ return info.Env().Undefined();
318
+ }
319
+
320
+ Napi::Value MarketData::DropCount(const Napi::CallbackInfo &info) {
321
+ return Napi::Number::New(
322
+ info.Env(), static_cast<double>(ch_ ? ch_->dropCount() : 0));
323
+ }
324
+
325
+ Napi::Value MarketData::ChannelInfo(const Napi::CallbackInfo &info) {
326
+ Napi::Env env = info.Env();
327
+ Napi::Object o = Napi::Object::New(env);
328
+ const bool live = ch_ != nullptr;
329
+ o.Set("slotSize", static_cast<double>(live ? ch_->slotSize() : 0));
330
+ o.Set("numSlots", static_cast<double>(live ? ch_->numSlots() : 0));
331
+ o.Set("headerSize", static_cast<double>(live ? ch_->headerSize() : 0));
332
+ o.Set("dropOldest", live ? ch_->dropOldest() : false);
333
+ return o;
334
+ }
335
+
336
+ Napi::Value MarketData::Close(const Napi::CallbackInfo &info) {
337
+ doClose();
338
+ return info.Env().Undefined();
339
+ }
340
+
341
+ Napi::Value MarketData::AttachArm(const Napi::CallbackInfo &info) {
342
+ auto ext = info[0].As<Napi::External<std::shared_ptr<ArmRegistry>>>();
343
+ std::shared_ptr<ArmRegistry> *sp = ext.Data();
344
+ if (sp && *sp) {
345
+ armReg_ = *sp; // share ownership so the registry can't dangle
346
+ if (spi_)
347
+ spi_->setArmRegistry(armReg_.get());
348
+ }
349
+ return info.Env().Undefined();
350
+ }
351
+
352
+ Napi::Value MarketData::InjectTestTick(const Napi::CallbackInfo &info) {
353
+ // Drive the real SPI path (so arm triggers are evaluated too). Optional args
354
+ // override bid/ask, so tests can inject edge prices - e.g. a DBL_MAX "no-bid"
355
+ // sentinel (BidPrice1 at limit-down) to verify armed triggers ignore it:
356
+ // _injectTestTick(bid?, ask?)
357
+ if (spi_ && !closed_) {
358
+ CThostFtdcDepthMarketDataField f;
359
+ std::memset(&f, 0, sizeof(f));
360
+ std::snprintf(f.InstrumentID, sizeof(f.InstrumentID), "%s", "rb2510");
361
+ std::snprintf(f.ExchangeID, sizeof(f.ExchangeID), "%s", "SHFE");
362
+ f.LastPrice = 3500.5;
363
+ f.BidPrice1 = (info.Length() >= 1 && info[0].IsNumber())
364
+ ? info[0].As<Napi::Number>().DoubleValue()
365
+ : 3499.0;
366
+ f.AskPrice1 = (info.Length() >= 2 && info[1].IsNumber())
367
+ ? info[1].As<Napi::Number>().DoubleValue()
368
+ : 3501.0;
369
+ f.BidVolume1 = 10;
370
+ f.Volume = 12345;
371
+ spi_->OnRtnDepthMarketData(&f);
372
+ }
373
+ return info.Env().Undefined();
374
+ }
375
+
376
+ // test-only: spawn a background producer thread that pushes `n` synthetic depth
377
+ // ticks straight into the real channel (the exact cross-thread SPSC + coalesced
378
+ // doorbell path), each tagged with its sequence number in the requestId slot so
379
+ // JS can verify conservation (received-unique + dropped == n) and detect any
380
+ // lost wakeup (a stranded tail that never wakes the JS drain). This is the
381
+ // doorbell race the claim() seq_cst fence guards.
382
+ Napi::Value MarketData::BurstTicks(const Napi::CallbackInfo &info) {
383
+ Napi::Env env = info.Env();
384
+ if (closed_ || !ch_)
385
+ return env.Undefined();
386
+ if (burst_.joinable())
387
+ burst_.join(); // only one burst at a time
388
+ int n = info.Length() >= 1 ? info[0].As<Napi::Number>().Int32Value() : 0;
389
+ // optional inter-push jitter in microseconds (0 = none) to widen the window.
390
+ int jitterUs = info.Length() >= 2 ? info[1].As<Napi::Number>().Int32Value() : 0;
391
+ EventChannel *ch = ch_;
392
+ burst_ = std::thread([ch, n, jitterUs]() {
393
+ CThostFtdcDepthMarketDataField f;
394
+ std::memset(&f, 0, sizeof(f));
395
+ std::snprintf(f.InstrumentID, sizeof(f.InstrumentID), "%s", "rb2510");
396
+ std::snprintf(f.ExchangeID, sizeof(f.ExchangeID), "%s", "SHFE");
397
+ f.LastPrice = 3500.5;
398
+ for (int i = 0; i < n; ++i) {
399
+ f.Volume = i; // sequence echo in the payload too
400
+ // requestId field carries the sequence number (JS reads it per record).
401
+ ch->push(MD_RTN_DEPTH_MARKET_DATA, i, -1, 0, "", SID_DepthMarketData, &f,
402
+ (int)sizeof(f));
403
+ if (jitterUs > 0 && (i & 0x3F) == 0)
404
+ std::this_thread::sleep_for(std::chrono::microseconds(jitterUs));
405
+ }
406
+ });
407
+ return env.Undefined();
408
+ }
409
+
410
+ Napi::Function InitMarketData(Napi::Env env) { return MarketData::Init(env); }
411
+
412
+ } // namespace ctp
@@ -0,0 +1,14 @@
1
+ /*
2
+ * mdapi.h - exposes the MarketData N-API class constructor.
3
+ */
4
+
5
+ #ifndef CTP_NATIVE_MDAPI_H
6
+ #define CTP_NATIVE_MDAPI_H
7
+
8
+ #include <napi.h>
9
+
10
+ namespace ctp {
11
+ Napi::Function InitMarketData(Napi::Env env);
12
+ }
13
+
14
+ #endif /* CTP_NATIVE_MDAPI_H */
@@ -0,0 +1,103 @@
1
+ /*
2
+ * mdspi.cc - see mdspi.h
3
+ */
4
+
5
+ #include "mdspi.h"
6
+
7
+ #include <cstdio>
8
+
9
+ #include "../generated/structids.gen.h"
10
+
11
+ namespace ctp {
12
+
13
+ static int eid(CThostFtdcRspInfoField *e) { return e ? e->ErrorID : 0; }
14
+ static const char *emsg(CThostFtdcRspInfoField *e) {
15
+ return (e && e->ErrorID) ? e->ErrorMsg : "";
16
+ }
17
+
18
+ void MdSpi::OnFrontConnected() {
19
+ ch_->push(MD_FRONT_CONNECTED, 0, -1, 0, "", -1, nullptr, 0);
20
+ }
21
+
22
+ void MdSpi::OnFrontDisconnected(int nReason) {
23
+ int r = nReason;
24
+ ch_->push(MD_FRONT_DISCONNECTED, 0, -1, 0, "", -2, &r, sizeof(r));
25
+ }
26
+
27
+ void MdSpi::OnHeartBeatWarning(int nTimeLapse) {
28
+ int t = nTimeLapse;
29
+ ch_->push(MD_HEARTBEAT_WARNING, 0, -1, 0, "", -2, &t, sizeof(t));
30
+ }
31
+
32
+ void MdSpi::OnRspUserLogin(CThostFtdcRspUserLoginField *p,
33
+ CThostFtdcRspInfoField *e, int id, bool last) {
34
+ ch_->push(MD_RSP_USER_LOGIN, id, last ? 1 : 0, eid(e), emsg(e),
35
+ p ? SID_RspUserLogin : -1, p, p ? (int)sizeof(*p) : 0);
36
+ }
37
+
38
+ void MdSpi::OnRspUserLogout(CThostFtdcUserLogoutField *p,
39
+ CThostFtdcRspInfoField *e, int id, bool last) {
40
+ ch_->push(MD_RSP_USER_LOGOUT, id, last ? 1 : 0, eid(e), emsg(e),
41
+ p ? SID_UserLogout : -1, p, p ? (int)sizeof(*p) : 0);
42
+ }
43
+
44
+ void MdSpi::OnRspQryMulticastInstrument(CThostFtdcMulticastInstrumentField *p,
45
+ CThostFtdcRspInfoField *e, int id,
46
+ bool last) {
47
+ ch_->push(MD_RSP_QRY_MULTICAST_INSTRUMENT, id, last ? 1 : 0, eid(e), emsg(e),
48
+ p ? SID_MulticastInstrument : -1, p, p ? (int)sizeof(*p) : 0);
49
+ }
50
+
51
+ void MdSpi::OnRspError(CThostFtdcRspInfoField *e, int id, bool last) {
52
+ ch_->push(MD_RSP_ERROR, id, last ? 1 : 0, eid(e), emsg(e), -1, nullptr, 0);
53
+ }
54
+
55
+ void MdSpi::OnRspSubMarketData(CThostFtdcSpecificInstrumentField *p,
56
+ CThostFtdcRspInfoField *e, int id, bool last) {
57
+ ch_->push(MD_RSP_SUB_MARKET_DATA, id, last ? 1 : 0, eid(e), emsg(e),
58
+ p ? SID_SpecificInstrument : -1, p, p ? (int)sizeof(*p) : 0);
59
+ }
60
+
61
+ void MdSpi::OnRspUnSubMarketData(CThostFtdcSpecificInstrumentField *p,
62
+ CThostFtdcRspInfoField *e, int id, bool last) {
63
+ ch_->push(MD_RSP_UNSUB_MARKET_DATA, id, last ? 1 : 0, eid(e), emsg(e),
64
+ p ? SID_SpecificInstrument : -1, p, p ? (int)sizeof(*p) : 0);
65
+ }
66
+
67
+ void MdSpi::OnRspSubForQuoteRsp(CThostFtdcSpecificInstrumentField *p,
68
+ CThostFtdcRspInfoField *e, int id, bool last) {
69
+ ch_->push(MD_RSP_SUB_FOR_QUOTE, id, last ? 1 : 0, eid(e), emsg(e),
70
+ p ? SID_SpecificInstrument : -1, p, p ? (int)sizeof(*p) : 0);
71
+ }
72
+
73
+ void MdSpi::OnRspUnSubForQuoteRsp(CThostFtdcSpecificInstrumentField *p,
74
+ CThostFtdcRspInfoField *e, int id, bool last) {
75
+ ch_->push(MD_RSP_UNSUB_FOR_QUOTE, id, last ? 1 : 0, eid(e), emsg(e),
76
+ p ? SID_SpecificInstrument : -1, p, p ? (int)sizeof(*p) : 0);
77
+ }
78
+
79
+ void MdSpi::OnRtnDepthMarketData(CThostFtdcDepthMarketDataField *p) {
80
+ // Load the api once: a concurrent close() (clearApi) must not let us deref a
81
+ // freed api between the null-check and the call.
82
+ CThostFtdcMdApi *api = api_.load(std::memory_order_relaxed);
83
+ if (p && api) {
84
+ const char *td = api->GetTradingDay();
85
+ if (td)
86
+ std::snprintf(p->TradingDay, sizeof(p->TradingDay), "%s", td);
87
+ }
88
+ // Evaluate armed triggers first (lowest tick-to-order latency), then publish.
89
+ if (p) {
90
+ ArmRegistry *ar = armReg_.load(std::memory_order_relaxed);
91
+ if (ar)
92
+ ar->onTick(p->InstrumentID, p->BidPrice1, p->AskPrice1);
93
+ }
94
+ ch_->push(MD_RTN_DEPTH_MARKET_DATA, 0, -1, 0, "", SID_DepthMarketData, p,
95
+ p ? (int)sizeof(*p) : 0);
96
+ }
97
+
98
+ void MdSpi::OnRtnForQuoteRsp(CThostFtdcForQuoteRspField *p) {
99
+ ch_->push(MD_RTN_FOR_QUOTE, 0, -1, 0, "", SID_ForQuoteRsp, p,
100
+ p ? (int)sizeof(*p) : 0);
101
+ }
102
+
103
+ } // namespace ctp
@@ -0,0 +1,81 @@
1
+ /*
2
+ * mdspi.h - market-data SPI. Each CTP callback just pushes a binary record into
3
+ * the EventChannel (no JS, no object building) on the CTP callback thread.
4
+ *
5
+ * Event codes are mirrored in src/market-data.ts (MD_BASE + n).
6
+ */
7
+
8
+ #ifndef CTP_NATIVE_MDSPI_H
9
+ #define CTP_NATIVE_MDSPI_H
10
+
11
+ #include "ThostFtdcMdApi.h"
12
+ #include "arm.h"
13
+ #include "channel.h"
14
+ #include <atomic>
15
+
16
+ namespace ctp {
17
+
18
+ enum {
19
+ MD_BASE = 0x1000,
20
+ MD_FRONT_CONNECTED = MD_BASE + 1,
21
+ MD_FRONT_DISCONNECTED = MD_BASE + 2,
22
+ MD_HEARTBEAT_WARNING = MD_BASE + 3,
23
+ MD_RSP_USER_LOGIN = MD_BASE + 4,
24
+ MD_RSP_USER_LOGOUT = MD_BASE + 5,
25
+ MD_RSP_QRY_MULTICAST_INSTRUMENT = MD_BASE + 6,
26
+ MD_RSP_ERROR = MD_BASE + 7,
27
+ MD_RSP_SUB_MARKET_DATA = MD_BASE + 8,
28
+ MD_RSP_UNSUB_MARKET_DATA = MD_BASE + 9,
29
+ MD_RSP_SUB_FOR_QUOTE = MD_BASE + 10,
30
+ MD_RSP_UNSUB_FOR_QUOTE = MD_BASE + 11,
31
+ MD_RTN_DEPTH_MARKET_DATA = MD_BASE + 12,
32
+ MD_RTN_FOR_QUOTE = MD_BASE + 13,
33
+ };
34
+
35
+ class MdSpi : public CThostFtdcMdSpi {
36
+ public:
37
+ MdSpi(CThostFtdcMdApi *api, EventChannel *channel) : api_(api), ch_(channel) {}
38
+ ~MdSpi() {}
39
+
40
+ // Feed depth ticks to a Trader's arm registry (or nullptr to detach).
41
+ void setArmRegistry(ArmRegistry *r) { armReg_.store(r, std::memory_order_relaxed); }
42
+
43
+ // Detach the api pointer before the owning MarketData releases it, so a
44
+ // late/teardown callback (or the test tick hook) can't dereference a freed
45
+ // api. Published atomically: OnRtnDepthMarketData reads it lock-free.
46
+ void clearApi() { api_.store(nullptr, std::memory_order_relaxed); }
47
+
48
+ void OnFrontConnected() override;
49
+ void OnFrontDisconnected(int nReason) override;
50
+ void OnHeartBeatWarning(int nTimeLapse) override;
51
+ void OnRspUserLogin(CThostFtdcRspUserLoginField *p, CThostFtdcRspInfoField *e,
52
+ int id, bool last) override;
53
+ void OnRspUserLogout(CThostFtdcUserLogoutField *p, CThostFtdcRspInfoField *e,
54
+ int id, bool last) override;
55
+ void OnRspQryMulticastInstrument(CThostFtdcMulticastInstrumentField *p,
56
+ CThostFtdcRspInfoField *e, int id,
57
+ bool last) override;
58
+ void OnRspError(CThostFtdcRspInfoField *e, int id, bool last) override;
59
+ void OnRspSubMarketData(CThostFtdcSpecificInstrumentField *p,
60
+ CThostFtdcRspInfoField *e, int id, bool last) override;
61
+ void OnRspUnSubMarketData(CThostFtdcSpecificInstrumentField *p,
62
+ CThostFtdcRspInfoField *e, int id,
63
+ bool last) override;
64
+ void OnRspSubForQuoteRsp(CThostFtdcSpecificInstrumentField *p,
65
+ CThostFtdcRspInfoField *e, int id,
66
+ bool last) override;
67
+ void OnRspUnSubForQuoteRsp(CThostFtdcSpecificInstrumentField *p,
68
+ CThostFtdcRspInfoField *e, int id,
69
+ bool last) override;
70
+ void OnRtnDepthMarketData(CThostFtdcDepthMarketDataField *p) override;
71
+ void OnRtnForQuoteRsp(CThostFtdcForQuoteRspField *p) override;
72
+
73
+ private:
74
+ std::atomic<CThostFtdcMdApi *> api_;
75
+ EventChannel *ch_;
76
+ std::atomic<ArmRegistry *> armReg_{nullptr};
77
+ };
78
+
79
+ } // namespace ctp
80
+
81
+ #endif /* CTP_NATIVE_MDSPI_H */