@hitrading/ctp-node 2.0.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/CHANGELOG.md +67 -0
  2. package/README.md +47 -32
  3. package/README.zh-CN.md +37 -27
  4. package/RELEASING.md +78 -0
  5. package/dist/client.d.ts +36 -15
  6. package/dist/client.d.ts.map +1 -1
  7. package/dist/client.js +234 -62
  8. package/dist/client.js.map +1 -1
  9. package/dist/codec.d.ts.map +1 -1
  10. package/dist/codec.js +84 -19
  11. package/dist/codec.js.map +1 -1
  12. package/dist/generated/structs.gen.d.ts +5461 -5461
  13. package/dist/generated/structs.gen.d.ts.map +1 -1
  14. package/dist/generated/trader.gen.d.ts.map +1 -1
  15. package/dist/generated/trader.gen.js +788 -94
  16. package/dist/generated/trader.gen.js.map +1 -1
  17. package/dist/index.cjs +1875 -415
  18. package/dist/index.d.cts +1 -1
  19. package/dist/index.d.ts +1 -1
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/index.js.map +1 -1
  22. package/dist/market-data.d.ts +41 -24
  23. package/dist/market-data.d.ts.map +1 -1
  24. package/dist/market-data.js +148 -29
  25. package/dist/market-data.js.map +1 -1
  26. package/dist/native-binding.d.ts.map +1 -1
  27. package/dist/native-binding.js +4 -0
  28. package/dist/native-binding.js.map +1 -1
  29. package/dist/trader.d.ts +111 -71
  30. package/dist/trader.d.ts.map +1 -1
  31. package/dist/trader.js +774 -180
  32. package/dist/trader.js.map +1 -1
  33. package/dist/validation.d.ts +27 -0
  34. package/dist/validation.d.ts.map +1 -0
  35. package/dist/validation.js +85 -0
  36. package/dist/validation.js.map +1 -0
  37. package/docs/API.md +1437 -0
  38. package/docs/API.zh-CN.md +1278 -0
  39. package/docs/MIGRATION.md +54 -0
  40. package/docs/assets/validation.svg +27 -0
  41. package/docs/integration.md +60 -0
  42. package/docs/native-hooks.md +281 -0
  43. package/docs/native-hooks.zh-CN.md +205 -0
  44. package/docs/troubleshooting.md +257 -0
  45. package/docs/troubleshooting.zh-CN.md +220 -0
  46. package/package.json +12 -4
  47. package/prebuilds/linux-x64/@hitrading+ctp-node.node +0 -0
  48. package/prebuilds/win32-x64/@hitrading+ctp-node.node +0 -0
  49. package/scripts/bench-decode.mjs +37 -0
  50. package/scripts/bench-fullmarket-offline.mjs +207 -0
  51. package/scripts/stress-fullmarket.mjs +255 -0
  52. package/src/addon.cc +2 -2
  53. package/src/client.ts +255 -65
  54. package/src/codec.ts +86 -19
  55. package/src/generated/structs.gen.ts +5461 -5461
  56. package/src/generated/trader.gen.ts +309 -94
  57. package/src/generated/traderreq.gen.cc +194 -18
  58. package/src/generated/traderreq.gen.h +4 -0
  59. package/src/generated/traderspi.gen.cc +129 -15
  60. package/src/generated/traderspi.gen.h +4 -2
  61. package/src/index.ts +8 -1
  62. package/src/market-data.ts +199 -46
  63. package/src/native/arm.cc +114 -30
  64. package/src/native/arm.h +16 -4
  65. package/src/native/channel.cc +209 -81
  66. package/src/native/channel.h +65 -24
  67. package/src/native/ctp_field.h +23 -0
  68. package/src/native/mdapi.cc +582 -69
  69. package/src/native/mdspi.cc +219 -16
  70. package/src/native/mdspi.h +59 -10
  71. package/src/native/order_capability.h +75 -0
  72. package/src/native/risk.cc +2030 -213
  73. package/src/native/risk.h +431 -78
  74. package/src/native/shared_handle.h +37 -0
  75. package/src/native/snapshot.h +75 -16
  76. package/src/native/traderapi.cc +753 -124
  77. package/src/native-binding.ts +4 -0
  78. package/src/trader.ts +971 -204
  79. package/src/validation.ts +96 -0
@@ -11,45 +11,112 @@
11
11
 
12
12
  #include "mdapi.h"
13
13
 
14
+ #include <array>
14
15
  #include <chrono>
16
+ #include <cmath>
15
17
  #include <cstdio>
16
18
  #include <cstring>
17
19
  #include <memory>
18
20
  #include <string>
19
21
  #include <thread>
22
+ #include <utility>
20
23
  #include <vector>
21
24
 
22
25
  #include "../generated/layout.gen.h"
23
26
  #include "../generated/structids.gen.h"
24
27
  #include "ThostFtdcMdApi.h"
25
28
  #include "channel.h"
29
+ #include "gbk.h"
26
30
  #include "mdspi.h"
31
+ #include "shared_handle.h"
27
32
  #include "snapshot.h"
28
33
 
29
34
  namespace ctp {
30
35
 
31
36
  namespace {
32
37
 
33
- void getStr(const Napi::Object &o, const char *key, char *dst, size_t cap) {
38
+ // Returned when an MD login/logout cannot be linearized against an in-flight
39
+ // session transition (CTP echoes request id 0 on the MD channel, so two
40
+ // overlapping transitions cannot be correlated). Mirrors the JS-side risk-reject
41
+ // code surfaced by client.ts riskRejectMessage().
42
+ constexpr int kSessionTransitionUnavailable = -10009;
43
+
44
+ bool testHooksEnabled(Napi::Env env) {
45
+ Napi::Value process = env.Global().Get("process");
46
+ if (!process.IsObject())
47
+ return false;
48
+ Napi::Value environment = process.As<Napi::Object>().Get("env");
49
+ if (!environment.IsObject())
50
+ return false;
51
+ Napi::Value value =
52
+ environment.As<Napi::Object>().Get("CTP_NODE_TEST_HOOKS");
53
+ return value.IsString() && value.As<Napi::String>().Utf8Value() == "1";
54
+ }
55
+
56
+ bool getStr(const Napi::Object &o, const char *key, char *dst, size_t cap) {
34
57
  if (!o.Has(key))
35
- return;
58
+ return true;
36
59
  Napi::Value v = o.Get(key);
37
- if (!v.IsString())
38
- return;
60
+ if (!v.IsString()) {
61
+ Napi::TypeError::New(o.Env(), std::string(key) + " must be a string")
62
+ .ThrowAsJavaScriptException();
63
+ return false;
64
+ }
39
65
  std::string s = v.As<Napi::String>().Utf8Value();
40
- std::snprintf(dst, cap, "%s", s.c_str());
66
+ if (s.find('\0') != std::string::npos) {
67
+ Napi::RangeError::New(o.Env(), std::string(key) + " must not contain NUL")
68
+ .ThrowAsJavaScriptException();
69
+ return false;
70
+ }
71
+ std::string encoded = gbkEncode(s.data(), s.size());
72
+ if (cap == 0 || encoded.size() >= cap) {
73
+ Napi::RangeError::New(o.Env(), std::string(key) +
74
+ " exceeds CTP field byte capacity")
75
+ .ThrowAsJavaScriptException();
76
+ return false;
77
+ }
78
+ std::memcpy(dst, encoded.data(), encoded.size());
79
+ dst[encoded.size()] = '\0';
80
+ return true;
41
81
  }
42
82
 
43
- std::vector<std::string> toStringList(const Napi::Value &v) {
44
- std::vector<std::string> out;
83
+ bool toStringList(const Napi::Value &v, std::vector<std::string> &out,
84
+ const char *label) {
45
85
  if (v.IsArray()) {
46
86
  Napi::Array a = v.As<Napi::Array>();
47
- for (uint32_t i = 0; i < a.Length(); ++i)
48
- out.push_back(a.Get(i).As<Napi::String>().Utf8Value());
87
+ for (uint32_t i = 0; i < a.Length(); ++i) {
88
+ Napi::Value item = a.Get(i);
89
+ if (!item.IsString()) {
90
+ Napi::TypeError::New(v.Env(), std::string(label) +
91
+ " must contain only strings")
92
+ .ThrowAsJavaScriptException();
93
+ return false;
94
+ }
95
+ std::string value = item.As<Napi::String>().Utf8Value();
96
+ if (value.find('\0') != std::string::npos) {
97
+ Napi::RangeError::New(v.Env(), std::string(label) +
98
+ " must not contain NUL")
99
+ .ThrowAsJavaScriptException();
100
+ return false;
101
+ }
102
+ out.push_back(std::move(value));
103
+ }
49
104
  } else if (v.IsString()) {
50
- out.push_back(v.As<Napi::String>().Utf8Value());
105
+ std::string value = v.As<Napi::String>().Utf8Value();
106
+ if (value.find('\0') != std::string::npos) {
107
+ Napi::RangeError::New(v.Env(), std::string(label) +
108
+ " must not contain NUL")
109
+ .ThrowAsJavaScriptException();
110
+ return false;
111
+ }
112
+ out.push_back(std::move(value));
113
+ } else {
114
+ Napi::TypeError::New(v.Env(), std::string(label) +
115
+ " must be a string or string array")
116
+ .ThrowAsJavaScriptException();
117
+ return false;
51
118
  }
52
- return out;
119
+ return true;
53
120
  }
54
121
 
55
122
  } // namespace
@@ -62,8 +129,10 @@ public:
62
129
 
63
130
  private:
64
131
  void doClose();
132
+ bool detachBufferForClose();
65
133
  int subscribeImpl(const Napi::CallbackInfo &info,
66
- int (CThostFtdcMdApi::*fn)(char *[], int));
134
+ int (CThostFtdcMdApi::*fn)(char *[], int),
135
+ std::vector<std::string> *acceptedIds = nullptr);
67
136
 
68
137
  Napi::Value GetApiVersion(const Napi::CallbackInfo &info);
69
138
  Napi::Value GetTradingDay(const Napi::CallbackInfo &info);
@@ -73,10 +142,10 @@ private:
73
142
  Napi::Value UnsubscribeForQuoteRsp(const Napi::CallbackInfo &info);
74
143
  Napi::Value ReqUserLogin(const Napi::CallbackInfo &info);
75
144
  Napi::Value ReqUserLogout(const Napi::CallbackInfo &info);
145
+ Napi::Value ReqQryMulticastInstrument(const Napi::CallbackInfo &info);
76
146
  Napi::Value Start(const Napi::CallbackInfo &info);
77
147
  Napi::Value Buffer(const Napi::CallbackInfo &info);
78
148
  Napi::Value ClaimBatch(const Napi::CallbackInfo &info);
79
- Napi::Value ValidateBatch(const Napi::CallbackInfo &info);
80
149
  Napi::Value ReadIndex(const Napi::CallbackInfo &info);
81
150
  Napi::Value ReleaseBatch(const Napi::CallbackInfo &info);
82
151
  Napi::Value DropCount(const Napi::CallbackInfo &info);
@@ -87,7 +156,12 @@ private:
87
156
  Napi::Value Last(const Napi::CallbackInfo &info);
88
157
  Napi::Value SnapshotExternal(const Napi::CallbackInfo &info);
89
158
  Napi::Value InjectTestTick(const Napi::CallbackInfo &info);
159
+ Napi::Value InjectTestForQuote(const Napi::CallbackInfo &info);
160
+ Napi::Value InjectTestLifecycle(const Napi::CallbackInfo &info);
161
+ Napi::Value AbandonSessionTransition(const Napi::CallbackInfo &info);
162
+ Napi::Value TimeoutSessionTransition(const Napi::CallbackInfo &info);
90
163
  Napi::Value BurstTicks(const Napi::CallbackInfo &info);
164
+ Napi::Value ProduceTestTicks(const Napi::CallbackInfo &info);
91
165
 
92
166
  CThostFtdcMdApi *api_ = nullptr;
93
167
  MdSpi *spi_ = nullptr;
@@ -96,6 +170,8 @@ private:
96
170
  // Latest-tick cache (LVC). shared_ptr so a Trader can borrow it (trackMarketData)
97
171
  // for its in-C++ deviation reference, like the arm registry.
98
172
  std::shared_ptr<SnapshotCache> snap_ = std::make_shared<SnapshotCache>();
173
+ napi_env env_ = nullptr;
174
+ napi_ref bufferRef_ = nullptr;
99
175
  bool started_ = false;
100
176
  bool closed_ = false;
101
177
  // test-only background producer thread (doorbell cross-thread stress).
@@ -106,18 +182,19 @@ Napi::Function MarketData::Init(Napi::Env env) {
106
182
  return DefineClass(
107
183
  env, "MarketData",
108
184
  {
109
- InstanceMethod("getApiVersion", &MarketData::GetApiVersion),
110
- InstanceMethod("getTradingDay", &MarketData::GetTradingDay),
185
+ InstanceMethod("apiVersion", &MarketData::GetApiVersion),
186
+ InstanceMethod("tradingDay", &MarketData::GetTradingDay),
111
187
  InstanceMethod("subscribeMarketData", &MarketData::SubscribeMarketData),
112
188
  InstanceMethod("unsubscribeMarketData", &MarketData::UnsubscribeMarketData),
113
189
  InstanceMethod("subscribeForQuoteRsp", &MarketData::SubscribeForQuoteRsp),
114
190
  InstanceMethod("unsubscribeForQuoteRsp", &MarketData::UnsubscribeForQuoteRsp),
115
191
  InstanceMethod("reqUserLogin", &MarketData::ReqUserLogin),
116
192
  InstanceMethod("reqUserLogout", &MarketData::ReqUserLogout),
193
+ InstanceMethod("reqQryMulticastInstrument",
194
+ &MarketData::ReqQryMulticastInstrument),
117
195
  InstanceMethod("_start", &MarketData::Start),
118
196
  InstanceMethod("_buffer", &MarketData::Buffer),
119
197
  InstanceMethod("_claim", &MarketData::ClaimBatch),
120
- InstanceMethod("_validate", &MarketData::ValidateBatch),
121
198
  InstanceMethod("_readIndex", &MarketData::ReadIndex),
122
199
  InstanceMethod("_release", &MarketData::ReleaseBatch),
123
200
  InstanceMethod("_dropCount", &MarketData::DropCount),
@@ -127,13 +204,20 @@ Napi::Function MarketData::Init(Napi::Env env) {
127
204
  InstanceMethod("last", &MarketData::Last),
128
205
  InstanceMethod("_snapshotExternal", &MarketData::SnapshotExternal),
129
206
  InstanceMethod("_injectTestTick", &MarketData::InjectTestTick),
207
+ InstanceMethod("_injectTestForQuote", &MarketData::InjectTestForQuote),
208
+ InstanceMethod("_injectTestLifecycle", &MarketData::InjectTestLifecycle),
209
+ InstanceMethod("_abandonSessionTransition",
210
+ &MarketData::AbandonSessionTransition),
211
+ InstanceMethod("_timeoutSessionTransition",
212
+ &MarketData::TimeoutSessionTransition),
130
213
  InstanceMethod("_burstTicks", &MarketData::BurstTicks),
214
+ InstanceMethod("_produceTestTicks", &MarketData::ProduceTestTicks),
131
215
  InstanceMethod("close", &MarketData::Close),
132
216
  });
133
217
  }
134
218
 
135
219
  MarketData::MarketData(const Napi::CallbackInfo &info)
136
- : Napi::ObjectWrap<MarketData>(info) {
220
+ : Napi::ObjectWrap<MarketData>(info), env_(info.Env()) {
137
221
  Napi::Env env = info.Env();
138
222
  if (info.Length() < 2 || !info[0].IsString()) {
139
223
  Napi::TypeError::New(env, "MarketData(flowPath, fronts)")
@@ -141,12 +225,20 @@ MarketData::MarketData(const Napi::CallbackInfo &info)
141
225
  return;
142
226
  }
143
227
  std::string flowPath = info[0].As<Napi::String>().Utf8Value();
228
+ if (flowPath.find('\0') != std::string::npos) {
229
+ Napi::RangeError::New(env, "MarketData flowPath must not contain NUL")
230
+ .ThrowAsJavaScriptException();
231
+ return;
232
+ }
144
233
 
145
234
  // Validate fronts BEFORE allocating anything: RegisterFront("") faults deep
146
235
  // inside the CTP DLL, so drop empty addresses and reject an empty result with
147
236
  // a clean JS error rather than crashing the process.
148
237
  std::vector<std::string> fronts;
149
- for (auto &addr : toStringList(info[1]))
238
+ std::vector<std::string> requestedFronts;
239
+ if (!toStringList(info[1], requestedFronts, "fronts"))
240
+ return;
241
+ for (auto &addr : requestedFronts)
150
242
  if (!addr.empty())
151
243
  fronts.push_back(addr);
152
244
  if (fronts.empty()) {
@@ -165,7 +257,7 @@ MarketData::MarketData(const Napi::CallbackInfo &info)
165
257
  // wants the freshest quote, not a stale one, when the JS loop falls behind.
166
258
  ch_ = new EventChannel(8192, static_cast<size_t>(ctpMaxStructSize()),
167
259
  DropPolicy::Oldest);
168
- spi_ = new MdSpi(api_, ch_);
260
+ spi_ = new MdSpi(ch_);
169
261
  spi_->setSnapshotCache(snap_.get());
170
262
  api_->RegisterSpi(spi_);
171
263
 
@@ -175,6 +267,41 @@ MarketData::MarketData(const Napi::CallbackInfo &info)
175
267
 
176
268
  MarketData::~MarketData() { doClose(); }
177
269
 
270
+ bool MarketData::detachBufferForClose() {
271
+ if (!bufferRef_)
272
+ return true;
273
+
274
+ // Treat every N-API failure as "still attached". close() may intentionally
275
+ // retain the native channel in that impossible-on-supported-Node fallback,
276
+ // but it must never free backing memory while JS might still reference it.
277
+ bool safeToFreeRing = false;
278
+ napi_value buffer = nullptr;
279
+ if (env_ &&
280
+ napi_get_reference_value(env_, bufferRef_, &buffer) == napi_ok &&
281
+ buffer != nullptr) {
282
+ bool detached = false;
283
+ if (napi_is_detached_arraybuffer(env_, buffer, &detached) == napi_ok) {
284
+ if (detached) {
285
+ safeToFreeRing = true;
286
+ } else if (napi_detach_arraybuffer(env_, buffer) == napi_ok) {
287
+ // Verify the postcondition instead of assuming a successful status made
288
+ // the external ArrayBuffer inaccessible.
289
+ detached = false;
290
+ safeToFreeRing =
291
+ napi_is_detached_arraybuffer(env_, buffer, &detached) == napi_ok &&
292
+ detached;
293
+ }
294
+ }
295
+ }
296
+ // Once detached, retaining the JS object is unnecessary. On the fail-safe
297
+ // branch the channel itself is leaked below, so dropping our reference is
298
+ // also safe even if user code still holds the attached ArrayBuffer.
299
+ if (env_)
300
+ napi_delete_reference(env_, bufferRef_);
301
+ bufferRef_ = nullptr;
302
+ return safeToFreeRing;
303
+ }
304
+
178
305
  void MarketData::doClose() {
179
306
  if (closed_)
180
307
  return;
@@ -183,20 +310,25 @@ void MarketData::doClose() {
183
310
  // can never push into a freed ring.
184
311
  if (burst_.joinable())
185
312
  burst_.join();
186
- // Detach the SPI's api pointer BEFORE releasing the api, so a late callback
187
- // (or the test tick hook) can never dereference the freed api.
188
313
  if (spi_) {
189
- spi_->clearApi();
190
314
  spi_->setArmRegistry(nullptr);
191
315
  spi_->setSnapshotCache(nullptr);
192
316
  }
193
- if (snap_)
194
- snap_->clear(); // free the LVC; a Trader still holding it sees an empty cache
195
317
  if (api_) {
196
318
  api_->Release(); // stops the CTP callback thread (no more push / onTick)
197
319
  api_ = nullptr;
198
320
  }
321
+ // A callback may have loaded the old raw cache pointer immediately before
322
+ // setSnapshotCache(nullptr). Release() joins that producer; clear only after
323
+ // it returns so such an in-flight callback cannot repopulate a closed feed
324
+ // with a deceptively fresh risk-reference quote.
325
+ if (snap_)
326
+ snap_->clear(); // a Trader still holding it now sees an empty cache
199
327
  armReg_.reset();
328
+ // Every _buffer() call returns the same externally-backed ArrayBuffer. Detach
329
+ // it before freeing the ring so a caller that retained the ArrayBuffer (or a
330
+ // typed view over it) observes byteLength 0 instead of a dangling pointer.
331
+ const bool safeToFreeRing = detachBufferForClose();
200
332
  // Free the SPI and the ring here, on close(), rather than waiting for the JS
201
333
  // object's GC finalizer: the ring is large (~21 MB - maxStructSize * 8192
202
334
  // slots) but invisible to V8, so the GC feels no pressure and a create/close
@@ -210,7 +342,11 @@ void MarketData::doClose() {
210
342
  }
211
343
  if (ch_) {
212
344
  ch_->stop(); // abort doorbell TSF (idempotent)
213
- delete ch_;
345
+ if (safeToFreeRing)
346
+ delete ch_;
347
+ // If detachment failed, intentionally leak the stopped channel and its
348
+ // ring. This is the only fail-safe outcome that cannot create a dangling
349
+ // external ArrayBuffer.
214
350
  ch_ = nullptr;
215
351
  }
216
352
  }
@@ -222,33 +358,44 @@ Napi::Value MarketData::GetApiVersion(const Napi::CallbackInfo &info) {
222
358
  Napi::Value MarketData::GetTradingDay(const Napi::CallbackInfo &info) {
223
359
  Napi::Env env = info.Env();
224
360
  if (!api_)
225
- return env.Null();
361
+ return Napi::String::New(env, "");
226
362
  const char *d = api_->GetTradingDay();
227
363
  return Napi::String::New(env, d ? d : "");
228
364
  }
229
365
 
230
366
  int MarketData::subscribeImpl(const Napi::CallbackInfo &info,
231
- int (CThostFtdcMdApi::*fn)(char *[], int)) {
367
+ int (CThostFtdcMdApi::*fn)(char *[], int),
368
+ std::vector<std::string> *acceptedIds) {
232
369
  if (!api_)
233
370
  return -1;
234
- auto ids = toStringList(info[0]);
371
+ std::vector<std::string> ids;
372
+ if (!toStringList(info[0], ids, "instrumentIds"))
373
+ return -1;
235
374
  if (ids.empty())
236
375
  return 0;
237
376
  std::vector<char *> ptrs(ids.size());
238
377
  for (size_t i = 0; i < ids.size(); ++i)
239
378
  ptrs[i] = const_cast<char *>(ids[i].c_str());
240
- return (api_->*fn)(ptrs.data(), static_cast<int>(ids.size()));
379
+ const int rc = (api_->*fn)(ptrs.data(), static_cast<int>(ids.size()));
380
+ if (rc == 0 && acceptedIds)
381
+ *acceptedIds = std::move(ids);
382
+ return rc;
241
383
  }
242
384
 
243
385
  Napi::Value MarketData::SubscribeMarketData(const Napi::CallbackInfo &info) {
244
- return Napi::Number::New(info.Env(),
245
- subscribeImpl(info, &CThostFtdcMdApi::SubscribeMarketData));
386
+ std::vector<std::string> ids;
387
+ const int rc = subscribeImpl(info, &CThostFtdcMdApi::SubscribeMarketData,
388
+ &ids);
389
+ if (rc == 0 && spi_)
390
+ spi_->noteSubscriptionRequest(ids, true);
391
+ return Napi::Number::New(info.Env(), rc);
246
392
  }
247
393
  Napi::Value MarketData::UnsubscribeMarketData(const Napi::CallbackInfo &info) {
248
- int rc = subscribeImpl(info, &CThostFtdcMdApi::UnSubscribeMarketData);
249
- if (snap_)
250
- for (auto &id : toStringList(info[0]))
251
- snap_->erase(id); // drop the LVC entry for an unsubscribed instrument
394
+ std::vector<std::string> ids;
395
+ const int rc = subscribeImpl(info, &CThostFtdcMdApi::UnSubscribeMarketData,
396
+ &ids);
397
+ if (rc == 0 && spi_)
398
+ spi_->noteSubscriptionRequest(ids, false);
252
399
  return Napi::Number::New(info.Env(), rc);
253
400
  }
254
401
  Napi::Value MarketData::SubscribeForQuoteRsp(const Napi::CallbackInfo &info) {
@@ -264,33 +411,110 @@ Napi::Value MarketData::ReqUserLogin(const Napi::CallbackInfo &info) {
264
411
  Napi::Env env = info.Env();
265
412
  if (!api_)
266
413
  return Napi::Number::New(env, -1);
267
- CThostFtdcReqUserLoginField req;
268
- std::memset(&req, 0, sizeof(req));
269
- if (info[0].IsObject()) {
270
- Napi::Object o = info[0].As<Napi::Object>();
271
- getStr(o, "tradingDay", req.TradingDay, sizeof(req.TradingDay));
272
- getStr(o, "brokerId", req.BrokerID, sizeof(req.BrokerID));
273
- getStr(o, "userId", req.UserID, sizeof(req.UserID));
274
- getStr(o, "password", req.Password, sizeof(req.Password));
275
- getStr(o, "userProductInfo", req.UserProductInfo, sizeof(req.UserProductInfo));
414
+ if (info.Length() < 2 || !info[0].IsTypedArray() || !info[1].IsNumber()) {
415
+ Napi::TypeError::New(
416
+ env, "reqUserLogin requires encoded ReqUserLogin bytes and request id")
417
+ .ThrowAsJavaScriptException();
418
+ return env.Undefined();
419
+ }
420
+ Napi::TypedArray typed = info[0].As<Napi::TypedArray>();
421
+ if (typed.TypedArrayType() != napi_uint8_array) {
422
+ Napi::TypeError::New(env, "reqUserLogin bytes must be a Uint8Array")
423
+ .ThrowAsJavaScriptException();
424
+ return env.Undefined();
425
+ }
426
+ Napi::Uint8Array bytes = info[0].As<Napi::Uint8Array>();
427
+ if (bytes.ByteLength() != sizeof(CThostFtdcReqUserLoginField)) {
428
+ Napi::RangeError::New(env, "invalid encoded ReqUserLogin byte length")
429
+ .ThrowAsJavaScriptException();
430
+ return env.Undefined();
276
431
  }
277
- int id = info[1].As<Napi::Number>().Int32Value();
278
- return Napi::Number::New(env, api_->ReqUserLogin(&req, id));
432
+ CThostFtdcReqUserLoginField req;
433
+ std::memcpy(&req, bytes.Data(), sizeof(req));
434
+ const int id = info[1].As<Napi::Number>().Int32Value();
435
+ if (!spi_ || !spi_->beginLogin(id))
436
+ return Napi::Number::New(env, kSessionTransitionUnavailable);
437
+ const int rc = api_->ReqUserLogin(&req, id);
438
+ if (rc != 0)
439
+ spi_->invalidateSession(); // no callback is attributable to this failed send
440
+ return Napi::Number::New(env, rc);
279
441
  }
280
442
 
281
443
  Napi::Value MarketData::ReqUserLogout(const Napi::CallbackInfo &info) {
282
444
  Napi::Env env = info.Env();
283
445
  if (!api_)
284
446
  return Napi::Number::New(env, -1);
447
+ if (info.Length() < 2 || !info[0].IsTypedArray() || !info[1].IsNumber()) {
448
+ Napi::TypeError::New(
449
+ env, "reqUserLogout requires encoded UserLogout bytes and request id")
450
+ .ThrowAsJavaScriptException();
451
+ return env.Undefined();
452
+ }
453
+ Napi::TypedArray typed = info[0].As<Napi::TypedArray>();
454
+ if (typed.TypedArrayType() != napi_uint8_array) {
455
+ Napi::TypeError::New(env, "reqUserLogout bytes must be a Uint8Array")
456
+ .ThrowAsJavaScriptException();
457
+ return env.Undefined();
458
+ }
459
+ Napi::Uint8Array bytes = info[0].As<Napi::Uint8Array>();
460
+ if (bytes.ByteLength() != sizeof(CThostFtdcUserLogoutField)) {
461
+ Napi::RangeError::New(env, "invalid encoded UserLogout byte length")
462
+ .ThrowAsJavaScriptException();
463
+ return env.Undefined();
464
+ }
285
465
  CThostFtdcUserLogoutField req;
466
+ std::memcpy(&req, bytes.Data(), sizeof(req));
467
+ const int id = info[1].As<Napi::Number>().Int32Value();
468
+ if (!spi_ || !spi_->beginLogout(id))
469
+ return Napi::Number::New(env, kSessionTransitionUnavailable);
470
+ const int rc = api_->ReqUserLogout(&req, id);
471
+ if (rc != 0)
472
+ spi_->invalidateSession();
473
+ return Napi::Number::New(env, rc);
474
+ }
475
+
476
+ Napi::Value MarketData::ReqQryMulticastInstrument(
477
+ const Napi::CallbackInfo &info) {
478
+ Napi::Env env = info.Env();
479
+ if (!api_)
480
+ return Napi::Number::New(env, -1);
481
+ if (info.Length() < 2 || !info[0].IsObject() || info[0].IsArray() ||
482
+ !info[1].IsNumber()) {
483
+ Napi::TypeError::New(env,
484
+ "reqQryMulticastInstrument requires an object and request id")
485
+ .ThrowAsJavaScriptException();
486
+ return env.Undefined();
487
+ }
488
+ CThostFtdcQryMulticastInstrumentField req;
286
489
  std::memset(&req, 0, sizeof(req));
287
- if (info[0].IsObject()) {
288
- Napi::Object o = info[0].As<Napi::Object>();
289
- getStr(o, "brokerId", req.BrokerID, sizeof(req.BrokerID));
290
- getStr(o, "userId", req.UserID, sizeof(req.UserID));
490
+ Napi::Object o = info[0].As<Napi::Object>();
491
+ if (o.Has("topicId")) {
492
+ Napi::Value topic = o.Get("topicId");
493
+ if (!topic.IsNumber() ||
494
+ !std::isfinite(topic.As<Napi::Number>().DoubleValue()) ||
495
+ std::floor(topic.As<Napi::Number>().DoubleValue()) !=
496
+ topic.As<Napi::Number>().DoubleValue() ||
497
+ topic.As<Napi::Number>().DoubleValue() < -2147483648.0 ||
498
+ topic.As<Napi::Number>().DoubleValue() > 2147483647.0) {
499
+ Napi::TypeError::New(env, "topicId must be an int32")
500
+ .ThrowAsJavaScriptException();
501
+ return env.Undefined();
502
+ }
503
+ req.TopicID = topic.As<Napi::Number>().Int32Value();
291
504
  }
292
- int id = info[1].As<Napi::Number>().Int32Value();
293
- return Napi::Number::New(env, api_->ReqUserLogout(&req, id));
505
+ if (!getStr(o, "instrumentId", req.InstrumentID,
506
+ sizeof(req.InstrumentID)))
507
+ return env.Undefined();
508
+ const double requestId = info[1].As<Napi::Number>().DoubleValue();
509
+ if (!std::isfinite(requestId) || std::floor(requestId) != requestId ||
510
+ requestId < 1.0 || requestId > 2147483647.0) {
511
+ Napi::TypeError::New(env, "request id must be a positive int32")
512
+ .ThrowAsJavaScriptException();
513
+ return env.Undefined();
514
+ }
515
+ return Napi::Number::New(
516
+ env, api_->ReqQryMulticastInstrument(&req,
517
+ static_cast<int>(requestId)));
294
518
  }
295
519
 
296
520
  Napi::Value MarketData::Start(const Napi::CallbackInfo &info) {
@@ -311,18 +535,32 @@ Napi::Value MarketData::Start(const Napi::CallbackInfo &info) {
311
535
  Napi::Value MarketData::Buffer(const Napi::CallbackInfo &info) {
312
536
  if (!ch_)
313
537
  return info.Env().Undefined();
314
- return Napi::ArrayBuffer::New(info.Env(), ch_->data(), ch_->byteLength());
538
+ if (bufferRef_) {
539
+ napi_value cached = nullptr;
540
+ if (napi_get_reference_value(info.Env(), bufferRef_, &cached) == napi_ok &&
541
+ cached != nullptr)
542
+ return Napi::Value(info.Env(), cached);
543
+ // Never overwrite a live reference handle with a second external
544
+ // ArrayBuffer. If retrieval fails, fail closed and preserve the original
545
+ // backing-object relationship for doClose() to handle safely.
546
+ Napi::Error::New(info.Env(), "cached event-channel buffer is unavailable")
547
+ .ThrowAsJavaScriptException();
548
+ return info.Env().Undefined();
549
+ }
550
+ Napi::ArrayBuffer buffer =
551
+ Napi::ArrayBuffer::New(info.Env(), ch_->data(), ch_->byteLength());
552
+ if (napi_create_reference(info.Env(), buffer, 1, &bufferRef_) != napi_ok) {
553
+ Napi::Error::New(info.Env(), "failed to retain event-channel buffer")
554
+ .ThrowAsJavaScriptException();
555
+ return info.Env().Undefined();
556
+ }
557
+ return buffer;
315
558
  }
316
559
 
317
560
  Napi::Value MarketData::ClaimBatch(const Napi::CallbackInfo &info) {
318
561
  return Napi::Number::New(info.Env(), ch_ ? ch_->claim() : 0);
319
562
  }
320
563
 
321
- Napi::Value MarketData::ValidateBatch(const Napi::CallbackInfo &info) {
322
- uint32_t claimed = info[0].As<Napi::Number>().Uint32Value();
323
- return Napi::Number::New(info.Env(), ch_ ? ch_->validate(claimed) : 0);
324
- }
325
-
326
564
  Napi::Value MarketData::ReadIndex(const Napi::CallbackInfo &info) {
327
565
  return Napi::Number::New(
328
566
  info.Env(), static_cast<double>(ch_ ? ch_->readIndex() : 0));
@@ -356,12 +594,41 @@ Napi::Value MarketData::Close(const Napi::CallbackInfo &info) {
356
594
  }
357
595
 
358
596
  Napi::Value MarketData::AttachArm(const Napi::CallbackInfo &info) {
359
- auto ext = info[0].As<Napi::External<std::shared_ptr<ArmRegistry>>>();
360
- std::shared_ptr<ArmRegistry> *sp = ext.Data();
361
- if (sp && *sp) {
362
- armReg_ = *sp; // share ownership so the registry can't dangle
597
+ if (closed_ || !spi_) {
598
+ Napi::Error::New(info.Env(), "cannot attach arms to a closed MarketData")
599
+ .ThrowAsJavaScriptException();
600
+ return info.Env().Undefined();
601
+ }
602
+ if (info.Length() < 1 || !info[0].IsExternal()) {
603
+ Napi::TypeError::New(info.Env(), "invalid Trader arm-registry handle")
604
+ .ThrowAsJavaScriptException();
605
+ return info.Env().Undefined();
606
+ }
607
+ auto ext = info[0].As<Napi::External<SharedHandle>>();
608
+ SharedHandle *handle = ext.Data();
609
+ if (!handle || handle->magic != SharedHandle::kMagic ||
610
+ handle->kind != SharedHandleKind::ArmRegistry || !handle->arm) {
611
+ Napi::TypeError::New(info.Env(), "invalid Trader arm-registry handle")
612
+ .ThrowAsJavaScriptException();
613
+ return info.Env().Undefined();
614
+ }
615
+ const std::shared_ptr<ArmRegistry> &registry = handle->arm;
616
+ {
617
+ if (!registry->hasSink()) {
618
+ Napi::Error::New(info.Env(), "cannot attach a closed Trader arm registry")
619
+ .ThrowAsJavaScriptException();
620
+ return info.Env().Undefined();
621
+ }
622
+ if (armReg_ && armReg_.get() != registry.get() && armReg_->hasSink()) {
623
+ Napi::Error::New(
624
+ info.Env(),
625
+ "MarketData is already attached to another live Trader arm registry")
626
+ .ThrowAsJavaScriptException();
627
+ return info.Env().Undefined();
628
+ }
629
+ armReg_ = registry; // share ownership so the registry can't dangle
363
630
  if (spi_)
364
- spi_->setArmRegistry(armReg_.get());
631
+ spi_->setArmRegistry(armReg_);
365
632
  }
366
633
  return info.Env().Undefined();
367
634
  }
@@ -390,13 +657,20 @@ Napi::Value MarketData::Last(const Napi::CallbackInfo &info) {
390
657
  // prices in C++ (Trader._attachSnapshot). Mirrors the arm-registry sharing: a
391
658
  // heap shared_ptr copy with a finalizer, so the cache can't dangle.
392
659
  Napi::Value MarketData::SnapshotExternal(const Napi::CallbackInfo &info) {
393
- auto *sp = new std::shared_ptr<SnapshotCache>(snap_);
394
- return Napi::External<std::shared_ptr<SnapshotCache>>::New(
395
- info.Env(), sp,
396
- [](Napi::Env, std::shared_ptr<SnapshotCache> *p) { delete p; });
660
+ auto *handle = new SharedHandle();
661
+ handle->kind = SharedHandleKind::SnapshotCache;
662
+ handle->snapshot = snap_;
663
+ return Napi::External<SharedHandle>::New(
664
+ info.Env(), handle, [](Napi::Env, SharedHandle *p) { delete p; });
397
665
  }
398
666
 
399
667
  Napi::Value MarketData::InjectTestTick(const Napi::CallbackInfo &info) {
668
+ if (!testHooksEnabled(info.Env())) {
669
+ Napi::Error::New(info.Env(),
670
+ "test hook disabled; set CTP_NODE_TEST_HOOKS=1 explicitly")
671
+ .ThrowAsJavaScriptException();
672
+ return info.Env().Undefined();
673
+ }
400
674
  // Drive the real SPI path (so arm triggers are evaluated too). Optional args
401
675
  // override bid/ask, so tests can inject edge prices - e.g. a DBL_MAX "no-bid"
402
676
  // sentinel (BidPrice1 at limit-down) to verify armed triggers ignore it:
@@ -420,6 +694,116 @@ Napi::Value MarketData::InjectTestTick(const Napi::CallbackInfo &info) {
420
694
  return info.Env().Undefined();
421
695
  }
422
696
 
697
+ Napi::Value MarketData::InjectTestForQuote(const Napi::CallbackInfo &info) {
698
+ Napi::Env env = info.Env();
699
+ if (!testHooksEnabled(env)) {
700
+ Napi::Error::New(env,
701
+ "test hook disabled; set CTP_NODE_TEST_HOOKS=1 explicitly")
702
+ .ThrowAsJavaScriptException();
703
+ return env.Undefined();
704
+ }
705
+ if (spi_ && !closed_) {
706
+ CThostFtdcForQuoteRspField response;
707
+ std::memset(&response, 0, sizeof(response));
708
+ std::snprintf(response.TradingDay, sizeof(response.TradingDay), "%s",
709
+ "20260711");
710
+ std::snprintf(response.InstrumentID, sizeof(response.InstrumentID), "%s",
711
+ "rb2510");
712
+ std::snprintf(response.ExchangeID, sizeof(response.ExchangeID), "%s",
713
+ "SHFE");
714
+ spi_->OnRtnForQuoteRsp(&response);
715
+ }
716
+ return env.Undefined();
717
+ }
718
+
719
+ Napi::Value MarketData::AbandonSessionTransition(
720
+ const Napi::CallbackInfo &info) {
721
+ if (spi_ && !closed_)
722
+ spi_->abandonSessionTransition();
723
+ return info.Env().Undefined();
724
+ }
725
+
726
+ Napi::Value MarketData::TimeoutSessionTransition(
727
+ const Napi::CallbackInfo &info) {
728
+ if (!spi_ || closed_ || info.Length() < 1 || !info[0].IsNumber())
729
+ return Napi::Boolean::New(info.Env(), true);
730
+ const double raw = info[0].As<Napi::Number>().DoubleValue();
731
+ if (!std::isfinite(raw) || std::floor(raw) != raw || raw <= 0.0 ||
732
+ raw > 2147483647.0)
733
+ return Napi::Boolean::New(info.Env(), true);
734
+ return Napi::Boolean::New(
735
+ info.Env(),
736
+ spi_->timeoutSessionTransition(static_cast<int>(raw)));
737
+ }
738
+
739
+ // Test-only lifecycle driver. It calls the real SPI callbacks so snapshot
740
+ // validity, control-event publication and JS request-context listeners are
741
+ // exercised together rather than mutating SnapshotCache behind the SPI.
742
+ Napi::Value MarketData::InjectTestLifecycle(const Napi::CallbackInfo &info) {
743
+ Napi::Env env = info.Env();
744
+ if (!testHooksEnabled(env)) {
745
+ Napi::Error::New(env,
746
+ "test hook disabled; set CTP_NODE_TEST_HOOKS=1 explicitly")
747
+ .ThrowAsJavaScriptException();
748
+ return env.Undefined();
749
+ }
750
+ if (closed_ || !spi_)
751
+ return env.Undefined();
752
+ if (info.Length() < 1 || !info[0].IsString()) {
753
+ Napi::TypeError::New(env, "test lifecycle state must be a string")
754
+ .ThrowAsJavaScriptException();
755
+ return env.Undefined();
756
+ }
757
+
758
+ const std::string state = info[0].As<Napi::String>().Utf8Value();
759
+ if (state == "connected") {
760
+ spi_->OnFrontConnected();
761
+ } else if (state == "disconnected") {
762
+ spi_->OnFrontDisconnected(0x1001);
763
+ } else if (state == "login") {
764
+ CThostFtdcRspUserLoginField response;
765
+ std::memset(&response, 0, sizeof(response));
766
+ std::snprintf(response.TradingDay, sizeof(response.TradingDay), "%s",
767
+ "20260711");
768
+ std::snprintf(response.BrokerID, sizeof(response.BrokerID), "%s", "9999");
769
+ std::snprintf(response.UserID, sizeof(response.UserID), "%s", "test");
770
+ if (spi_->beginLogin(9001))
771
+ spi_->OnRspUserLogin(&response, nullptr, 0, true);
772
+ } else if (state == "login-error") {
773
+ CThostFtdcRspInfoField error;
774
+ std::memset(&error, 0, sizeof(error));
775
+ error.ErrorID = 1;
776
+ std::snprintf(error.ErrorMsg, sizeof(error.ErrorMsg), "%s", "test login error");
777
+ if (spi_->beginLogin(9002))
778
+ spi_->OnRspUserLogin(nullptr, &error, 0, true);
779
+ } else if (state == "logout") {
780
+ CThostFtdcUserLogoutField response;
781
+ std::memset(&response, 0, sizeof(response));
782
+ std::snprintf(response.BrokerID, sizeof(response.BrokerID), "%s", "9999");
783
+ std::snprintf(response.UserID, sizeof(response.UserID), "%s", "test");
784
+ if (spi_->beginLogout(9003))
785
+ spi_->OnRspUserLogout(&response, nullptr, 0, true);
786
+ } else if (state == "login-pending") {
787
+ (void)spi_->beginLogin(9004);
788
+ } else if (state == "abandon") {
789
+ spi_->abandonSessionTransition();
790
+ } else if (state == "late-login") {
791
+ CThostFtdcRspUserLoginField response;
792
+ std::memset(&response, 0, sizeof(response));
793
+ std::snprintf(response.TradingDay, sizeof(response.TradingDay), "%s",
794
+ "20260711");
795
+ std::snprintf(response.BrokerID, sizeof(response.BrokerID), "%s", "9999");
796
+ std::snprintf(response.UserID, sizeof(response.UserID), "%s", "late");
797
+ spi_->OnRspUserLogin(&response, nullptr, 0, true);
798
+ } else {
799
+ Napi::RangeError::New(
800
+ env,
801
+ "test lifecycle state must be connected, disconnected, login, login-error, logout, login-pending, abandon or late-login")
802
+ .ThrowAsJavaScriptException();
803
+ }
804
+ return env.Undefined();
805
+ }
806
+
423
807
  // test-only: spawn a background producer thread that pushes `n` synthetic depth
424
808
  // ticks straight into the real channel (the exact cross-thread SPSC + coalesced
425
809
  // doorbell path), each tagged with its sequence number in the requestId slot so
@@ -428,6 +812,12 @@ Napi::Value MarketData::InjectTestTick(const Napi::CallbackInfo &info) {
428
812
  // doorbell race the claim() seq_cst fence guards.
429
813
  Napi::Value MarketData::BurstTicks(const Napi::CallbackInfo &info) {
430
814
  Napi::Env env = info.Env();
815
+ if (!testHooksEnabled(env)) {
816
+ Napi::Error::New(env,
817
+ "test hook disabled; set CTP_NODE_TEST_HOOKS=1 explicitly")
818
+ .ThrowAsJavaScriptException();
819
+ return env.Undefined();
820
+ }
431
821
  if (closed_ || !ch_)
432
822
  return env.Undefined();
433
823
  if (burst_.joinable())
@@ -435,18 +825,25 @@ Napi::Value MarketData::BurstTicks(const Napi::CallbackInfo &info) {
435
825
  int n = info.Length() >= 1 ? info[0].As<Napi::Number>().Int32Value() : 0;
436
826
  // optional inter-push jitter in microseconds (0 = none) to widen the window.
437
827
  int jitterUs = info.Length() >= 2 ? info[1].As<Napi::Number>().Int32Value() : 0;
828
+ const bool injectControl =
829
+ info.Length() >= 3 && info[2].ToBoolean().Value();
438
830
  EventChannel *ch = ch_;
439
- burst_ = std::thread([ch, n, jitterUs]() {
831
+ burst_ = std::thread([ch, n, jitterUs, injectControl]() {
440
832
  CThostFtdcDepthMarketDataField f;
441
833
  std::memset(&f, 0, sizeof(f));
442
834
  std::snprintf(f.InstrumentID, sizeof(f.InstrumentID), "%s", "rb2510");
443
835
  std::snprintf(f.ExchangeID, sizeof(f.ExchangeID), "%s", "SHFE");
444
836
  f.LastPrice = 3500.5;
445
837
  for (int i = 0; i < n; ++i) {
838
+ if (injectControl && i == n / 2) {
839
+ int marker = 123;
840
+ ch->push(MD_HEARTBEAT_WARNING, 0, -1, 0, "", -2, &marker,
841
+ sizeof(marker)); // non-droppable control callback
842
+ }
446
843
  f.Volume = i; // sequence echo in the payload too
447
844
  // requestId field carries the sequence number (JS reads it per record).
448
845
  ch->push(MD_RTN_DEPTH_MARKET_DATA, i, -1, 0, "", SID_DepthMarketData, &f,
449
- (int)sizeof(f));
846
+ (int)sizeof(f), true);
450
847
  if (jitterUs > 0 && (i & 0x3F) == 0)
451
848
  std::this_thread::sleep_for(std::chrono::microseconds(jitterUs));
452
849
  }
@@ -454,6 +851,122 @@ Napi::Value MarketData::BurstTicks(const Napi::CallbackInfo &info) {
454
851
  return env.Undefined();
455
852
  }
456
853
 
854
+ // Test-only full hot-path producer. Unlike _burstTicks (which intentionally
855
+ // targets EventChannel directly), this calls MdSpi::OnRtnDepthMarketData from a
856
+ // native background thread. Consequently it exercises TradingDay enrichment,
857
+ // SnapshotCache cardinality, arm lookup, channel overflow and JS decoding with
858
+ // distinct InstrumentID values.
859
+ //
860
+ // _produceTestTicks(count, instrumentCount, ratePerSecond = 0,
861
+ // burstSize = 512)
862
+ //
863
+ // ratePerSecond=0 emits one instantaneous burst. A positive rate emits
864
+ // burstSize-tick micro-bursts on a steady-clock schedule. Volume carries the
865
+ // zero-based global sequence; InstrumentID rotates SIM00000000..N-1.
866
+ Napi::Value MarketData::ProduceTestTicks(const Napi::CallbackInfo &info) {
867
+ Napi::Env env = info.Env();
868
+ if (!testHooksEnabled(env)) {
869
+ Napi::Error::New(env,
870
+ "test hook disabled; set CTP_NODE_TEST_HOOKS=1 explicitly")
871
+ .ThrowAsJavaScriptException();
872
+ return env.Undefined();
873
+ }
874
+ if (closed_ || !spi_)
875
+ return env.Undefined();
876
+
877
+ auto boundedInteger = [&](size_t index, const char *name, int minimum,
878
+ int maximum, int fallback, int &out) -> bool {
879
+ if (info.Length() <= index) {
880
+ out = fallback;
881
+ return true;
882
+ }
883
+ if (!info[index].IsNumber()) {
884
+ Napi::TypeError::New(env, std::string(name) + " must be an integer")
885
+ .ThrowAsJavaScriptException();
886
+ return false;
887
+ }
888
+ const double value = info[index].As<Napi::Number>().DoubleValue();
889
+ if (!std::isfinite(value) || std::floor(value) != value ||
890
+ value < minimum || value > maximum) {
891
+ Napi::RangeError::New(
892
+ env, std::string(name) + " must be an integer in " +
893
+ std::to_string(minimum) + ".." + std::to_string(maximum))
894
+ .ThrowAsJavaScriptException();
895
+ return false;
896
+ }
897
+ out = static_cast<int>(value);
898
+ return true;
899
+ };
900
+
901
+ int count = 0;
902
+ int instrumentCount = 0;
903
+ int ratePerSecond = 0;
904
+ int burstSize = 512;
905
+ if (!boundedInteger(0, "count", 0, 100000000, 0, count) ||
906
+ !boundedInteger(1, "instrumentCount", 1, 1000000, 1,
907
+ instrumentCount) ||
908
+ !boundedInteger(2, "ratePerSecond", 0, 100000000, 0,
909
+ ratePerSecond) ||
910
+ !boundedInteger(3, "burstSize", 1, 1000000, 512, burstSize))
911
+ return env.Undefined();
912
+
913
+ if (burst_.joinable())
914
+ burst_.join(); // one native test producer at a time
915
+ MdSpi *spi = spi_;
916
+ burst_ = std::thread(
917
+ [spi, count, instrumentCount, ratePerSecond, burstSize]() {
918
+ CThostFtdcDepthMarketDataField tick;
919
+ std::memset(&tick, 0, sizeof(tick));
920
+ std::snprintf(tick.ExchangeID, sizeof(tick.ExchangeID), "%s", "SIM");
921
+ std::snprintf(tick.ActionDay, sizeof(tick.ActionDay), "%s", "20260711");
922
+ std::snprintf(tick.UpdateTime, sizeof(tick.UpdateTime), "%s", "09:30:00");
923
+ tick.BidVolume1 = 10;
924
+ tick.AskVolume1 = 11;
925
+
926
+ // Build the synthetic contract universe once. Per-tick snprintf would
927
+ // measure string formatting in the generator rather than the binding's
928
+ // SPI/cache/channel hot path and substantially inflate reported CPU.
929
+ using InstrumentBytes =
930
+ std::array<char, sizeof(CThostFtdcDepthMarketDataField::InstrumentID)>;
931
+ std::vector<InstrumentBytes> instrumentIds(
932
+ static_cast<size_t>(instrumentCount));
933
+ std::vector<double> prices(static_cast<size_t>(instrumentCount));
934
+ for (int instrument = 0; instrument < instrumentCount; ++instrument) {
935
+ auto &bytes = instrumentIds[static_cast<size_t>(instrument)];
936
+ std::snprintf(bytes.data(), bytes.size(), "SIM%08d", instrument);
937
+ prices[static_cast<size_t>(instrument)] =
938
+ 3500.0 + static_cast<double>(instrument % 100) * 0.2;
939
+ }
940
+
941
+ const auto started = std::chrono::steady_clock::now();
942
+ for (int i = 0; i < count; ++i) {
943
+ // Pace the start of each micro-burst. If SPI/JS work is already slower
944
+ // than the target, sleep_until returns immediately rather than adding
945
+ // delay or creating catch-up timer drift.
946
+ if (ratePerSecond > 0 && i > 0 && i % burstSize == 0) {
947
+ const auto target = started + std::chrono::duration_cast<
948
+ std::chrono::steady_clock::duration>(
949
+ std::chrono::duration<double>(
950
+ static_cast<double>(i) / ratePerSecond));
951
+ std::this_thread::sleep_until(target);
952
+ }
953
+
954
+ const int instrument = i % instrumentCount;
955
+ std::memcpy(
956
+ tick.InstrumentID,
957
+ instrumentIds[static_cast<size_t>(instrument)].data(),
958
+ sizeof(tick.InstrumentID));
959
+ tick.LastPrice = prices[static_cast<size_t>(instrument)];
960
+ tick.BidPrice1 = tick.LastPrice - 0.2;
961
+ tick.AskPrice1 = tick.LastPrice + 0.2;
962
+ tick.Volume = i; // zero-based sequence for loss/order verification
963
+ tick.UpdateMillisec = i % 1000;
964
+ spi->OnRtnDepthMarketData(&tick);
965
+ }
966
+ });
967
+ return env.Undefined();
968
+ }
969
+
457
970
  Napi::Function InitMarketData(Napi::Env env) { return MarketData::Init(env); }
458
971
 
459
972
  } // namespace ctp