@hitrading/ctp-node 1.2.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/CHANGELOG.md +67 -0
  2. package/README.md +52 -31
  3. package/README.zh-CN.md +42 -26
  4. package/RELEASING.md +78 -0
  5. package/binding.gyp +13 -13
  6. package/dist/client.d.ts +40 -15
  7. package/dist/client.d.ts.map +1 -1
  8. package/dist/client.js +241 -62
  9. package/dist/client.js.map +1 -1
  10. package/dist/codec.d.ts.map +1 -1
  11. package/dist/codec.js +84 -19
  12. package/dist/codec.js.map +1 -1
  13. package/dist/generated/structs.gen.d.ts +5461 -5461
  14. package/dist/generated/structs.gen.d.ts.map +1 -1
  15. package/dist/generated/trader.gen.d.ts.map +1 -1
  16. package/dist/generated/trader.gen.js +788 -94
  17. package/dist/generated/trader.gen.js.map +1 -1
  18. package/dist/index.cjs +1896 -420
  19. package/dist/index.d.cts +1 -1
  20. package/dist/index.d.ts +1 -1
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.js.map +1 -1
  23. package/dist/market-data.d.ts +48 -21
  24. package/dist/market-data.d.ts.map +1 -1
  25. package/dist/market-data.js +165 -26
  26. package/dist/market-data.js.map +1 -1
  27. package/dist/native-binding.d.ts.map +1 -1
  28. package/dist/native-binding.js +5 -1
  29. package/dist/native-binding.js.map +1 -1
  30. package/dist/trader.d.ts +127 -79
  31. package/dist/trader.d.ts.map +1 -1
  32. package/dist/trader.js +788 -200
  33. package/dist/trader.js.map +1 -1
  34. package/dist/validation.d.ts +27 -0
  35. package/dist/validation.d.ts.map +1 -0
  36. package/dist/validation.js +85 -0
  37. package/dist/validation.js.map +1 -0
  38. package/docs/API.md +1437 -0
  39. package/docs/API.zh-CN.md +1278 -0
  40. package/docs/MIGRATION.md +54 -0
  41. package/docs/assets/validation.svg +27 -0
  42. package/docs/integration.md +60 -0
  43. package/docs/native-hooks.md +281 -0
  44. package/docs/native-hooks.zh-CN.md +205 -0
  45. package/docs/troubleshooting.md +257 -0
  46. package/docs/troubleshooting.zh-CN.md +220 -0
  47. package/package.json +14 -6
  48. package/prebuilds/linux-x64/@hitrading+ctp-node.node +0 -0
  49. package/prebuilds/win32-x64/@hitrading+ctp-node.node +0 -0
  50. package/scripts/bench-decode.mjs +37 -0
  51. package/scripts/bench-fullmarket-offline.mjs +207 -0
  52. package/scripts/stress-fullmarket.mjs +255 -0
  53. package/src/addon.cc +2 -2
  54. package/src/client.ts +263 -65
  55. package/src/codec.ts +86 -19
  56. package/src/generated/structs.gen.ts +5461 -5461
  57. package/src/generated/trader.gen.ts +309 -94
  58. package/src/generated/traderreq.gen.cc +194 -18
  59. package/src/generated/traderreq.gen.h +4 -0
  60. package/src/generated/traderspi.gen.cc +130 -10
  61. package/src/generated/traderspi.gen.h +4 -2
  62. package/src/index.ts +8 -1
  63. package/src/market-data.ts +219 -43
  64. package/src/native/arm.cc +114 -30
  65. package/src/native/arm.h +16 -4
  66. package/src/native/channel.cc +209 -81
  67. package/src/native/channel.h +65 -24
  68. package/src/native/ctp_field.h +23 -0
  69. package/src/native/mdapi.cc +621 -61
  70. package/src/native/mdspi.cc +221 -14
  71. package/src/native/mdspi.h +62 -9
  72. package/src/native/order_capability.h +75 -0
  73. package/src/native/risk.cc +2051 -205
  74. package/src/native/risk.h +450 -57
  75. package/src/native/shared_handle.h +37 -0
  76. package/src/native/snapshot.h +120 -0
  77. package/src/native/traderapi.cc +749 -170
  78. package/src/native-binding.ts +5 -1
  79. package/src/trader.ts +993 -229
  80. package/src/validation.ts +96 -0
  81. /package/{tradeapi → ctpsdk}/ThostFtdcMdApi.h +0 -0
  82. /package/{tradeapi → ctpsdk}/ThostFtdcTraderApi.h +0 -0
  83. /package/{tradeapi → ctpsdk}/ThostFtdcUserApiDataType.h +0 -0
  84. /package/{tradeapi → ctpsdk}/ThostFtdcUserApiStruct.h +0 -0
  85. /package/{tradeapi → ctpsdk}/error.dtd +0 -0
  86. /package/{tradeapi → ctpsdk}/error.xml +0 -0
  87. /package/{tradeapi → ctpsdk}/linux/thostmduserapi_se.so +0 -0
  88. /package/{tradeapi → ctpsdk}/linux/thosttraderapi_se.so +0 -0
  89. /package/{tradeapi → ctpsdk}/macos/thostmduserapi_se.framework/Versions/A/Headers/ThostFtdcMdApi.h +0 -0
  90. /package/{tradeapi → ctpsdk}/macos/thostmduserapi_se.framework/Versions/A/Headers/ThostFtdcUserApiDataType.h +0 -0
  91. /package/{tradeapi → ctpsdk}/macos/thostmduserapi_se.framework/Versions/A/Headers/ThostFtdcUserApiStruct.h +0 -0
  92. /package/{tradeapi → ctpsdk}/macos/thostmduserapi_se.framework/Versions/A/Resources/Info.plist +0 -0
  93. /package/{tradeapi → ctpsdk}/macos/thostmduserapi_se.framework/Versions/A/_CodeSignature/CodeResources +0 -0
  94. /package/{tradeapi → ctpsdk}/macos/thostmduserapi_se.framework/Versions/A/thostmduserapi_se +0 -0
  95. /package/{tradeapi → ctpsdk}/macos/thosttraderapi_se.framework/Versions/A/Headers/ThostFtdcTraderApi.h +0 -0
  96. /package/{tradeapi → ctpsdk}/macos/thosttraderapi_se.framework/Versions/A/Headers/ThostFtdcUserApiDataType.h +0 -0
  97. /package/{tradeapi → ctpsdk}/macos/thosttraderapi_se.framework/Versions/A/Headers/ThostFtdcUserApiStruct.h +0 -0
  98. /package/{tradeapi → ctpsdk}/macos/thosttraderapi_se.framework/Versions/A/Resources/Info.plist +0 -0
  99. /package/{tradeapi → ctpsdk}/macos/thosttraderapi_se.framework/Versions/A/_CodeSignature/CodeResources +0 -0
  100. /package/{tradeapi → ctpsdk}/macos/thosttraderapi_se.framework/Versions/A/thosttraderapi_se +0 -0
  101. /package/{tradeapi → ctpsdk}/windows/thostmduserapi_se.dll +0 -0
  102. /package/{tradeapi → ctpsdk}/windows/thostmduserapi_se.lib +0 -0
  103. /package/{tradeapi → ctpsdk}/windows/thosttraderapi_se.dll +0 -0
  104. /package/{tradeapi → ctpsdk}/windows/thosttraderapi_se.lib +0 -0
@@ -11,44 +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"
32
+ #include "snapshot.h"
27
33
 
28
34
  namespace ctp {
29
35
 
30
36
  namespace {
31
37
 
32
- 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) {
33
57
  if (!o.Has(key))
34
- return;
58
+ return true;
35
59
  Napi::Value v = o.Get(key);
36
- if (!v.IsString())
37
- return;
60
+ if (!v.IsString()) {
61
+ Napi::TypeError::New(o.Env(), std::string(key) + " must be a string")
62
+ .ThrowAsJavaScriptException();
63
+ return false;
64
+ }
38
65
  std::string s = v.As<Napi::String>().Utf8Value();
39
- 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;
40
81
  }
41
82
 
42
- std::vector<std::string> toStringList(const Napi::Value &v) {
43
- std::vector<std::string> out;
83
+ bool toStringList(const Napi::Value &v, std::vector<std::string> &out,
84
+ const char *label) {
44
85
  if (v.IsArray()) {
45
86
  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());
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
+ }
48
104
  } else if (v.IsString()) {
49
- 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;
50
118
  }
51
- return out;
119
+ return true;
52
120
  }
53
121
 
54
122
  } // namespace
@@ -61,8 +129,10 @@ public:
61
129
 
62
130
  private:
63
131
  void doClose();
132
+ bool detachBufferForClose();
64
133
  int subscribeImpl(const Napi::CallbackInfo &info,
65
- int (CThostFtdcMdApi::*fn)(char *[], int));
134
+ int (CThostFtdcMdApi::*fn)(char *[], int),
135
+ std::vector<std::string> *acceptedIds = nullptr);
66
136
 
67
137
  Napi::Value GetApiVersion(const Napi::CallbackInfo &info);
68
138
  Napi::Value GetTradingDay(const Napi::CallbackInfo &info);
@@ -72,23 +142,36 @@ private:
72
142
  Napi::Value UnsubscribeForQuoteRsp(const Napi::CallbackInfo &info);
73
143
  Napi::Value ReqUserLogin(const Napi::CallbackInfo &info);
74
144
  Napi::Value ReqUserLogout(const Napi::CallbackInfo &info);
145
+ Napi::Value ReqQryMulticastInstrument(const Napi::CallbackInfo &info);
75
146
  Napi::Value Start(const Napi::CallbackInfo &info);
76
147
  Napi::Value Buffer(const Napi::CallbackInfo &info);
77
148
  Napi::Value ClaimBatch(const Napi::CallbackInfo &info);
78
- Napi::Value ValidateBatch(const Napi::CallbackInfo &info);
79
149
  Napi::Value ReadIndex(const Napi::CallbackInfo &info);
80
150
  Napi::Value ReleaseBatch(const Napi::CallbackInfo &info);
81
151
  Napi::Value DropCount(const Napi::CallbackInfo &info);
82
152
  Napi::Value ChannelInfo(const Napi::CallbackInfo &info);
83
153
  Napi::Value Close(const Napi::CallbackInfo &info);
84
154
  Napi::Value AttachArm(const Napi::CallbackInfo &info);
155
+ Napi::Value Snapshot(const Napi::CallbackInfo &info);
156
+ Napi::Value Last(const Napi::CallbackInfo &info);
157
+ Napi::Value SnapshotExternal(const Napi::CallbackInfo &info);
85
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);
86
163
  Napi::Value BurstTicks(const Napi::CallbackInfo &info);
164
+ Napi::Value ProduceTestTicks(const Napi::CallbackInfo &info);
87
165
 
88
166
  CThostFtdcMdApi *api_ = nullptr;
89
167
  MdSpi *spi_ = nullptr;
90
168
  EventChannel *ch_ = nullptr;
91
169
  std::shared_ptr<ArmRegistry> armReg_;
170
+ // Latest-tick cache (LVC). shared_ptr so a Trader can borrow it (trackMarketData)
171
+ // for its in-C++ deviation reference, like the arm registry.
172
+ std::shared_ptr<SnapshotCache> snap_ = std::make_shared<SnapshotCache>();
173
+ napi_env env_ = nullptr;
174
+ napi_ref bufferRef_ = nullptr;
92
175
  bool started_ = false;
93
176
  bool closed_ = false;
94
177
  // test-only background producer thread (doorbell cross-thread stress).
@@ -99,31 +182,42 @@ Napi::Function MarketData::Init(Napi::Env env) {
99
182
  return DefineClass(
100
183
  env, "MarketData",
101
184
  {
102
- InstanceMethod("getApiVersion", &MarketData::GetApiVersion),
103
- InstanceMethod("getTradingDay", &MarketData::GetTradingDay),
185
+ InstanceMethod("apiVersion", &MarketData::GetApiVersion),
186
+ InstanceMethod("tradingDay", &MarketData::GetTradingDay),
104
187
  InstanceMethod("subscribeMarketData", &MarketData::SubscribeMarketData),
105
188
  InstanceMethod("unsubscribeMarketData", &MarketData::UnsubscribeMarketData),
106
189
  InstanceMethod("subscribeForQuoteRsp", &MarketData::SubscribeForQuoteRsp),
107
190
  InstanceMethod("unsubscribeForQuoteRsp", &MarketData::UnsubscribeForQuoteRsp),
108
191
  InstanceMethod("reqUserLogin", &MarketData::ReqUserLogin),
109
192
  InstanceMethod("reqUserLogout", &MarketData::ReqUserLogout),
193
+ InstanceMethod("reqQryMulticastInstrument",
194
+ &MarketData::ReqQryMulticastInstrument),
110
195
  InstanceMethod("_start", &MarketData::Start),
111
196
  InstanceMethod("_buffer", &MarketData::Buffer),
112
197
  InstanceMethod("_claim", &MarketData::ClaimBatch),
113
- InstanceMethod("_validate", &MarketData::ValidateBatch),
114
198
  InstanceMethod("_readIndex", &MarketData::ReadIndex),
115
199
  InstanceMethod("_release", &MarketData::ReleaseBatch),
116
200
  InstanceMethod("_dropCount", &MarketData::DropCount),
117
201
  InstanceMethod("_info", &MarketData::ChannelInfo),
118
202
  InstanceMethod("_attachArm", &MarketData::AttachArm),
203
+ InstanceMethod("snapshot", &MarketData::Snapshot),
204
+ InstanceMethod("last", &MarketData::Last),
205
+ InstanceMethod("_snapshotExternal", &MarketData::SnapshotExternal),
119
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),
120
213
  InstanceMethod("_burstTicks", &MarketData::BurstTicks),
214
+ InstanceMethod("_produceTestTicks", &MarketData::ProduceTestTicks),
121
215
  InstanceMethod("close", &MarketData::Close),
122
216
  });
123
217
  }
124
218
 
125
219
  MarketData::MarketData(const Napi::CallbackInfo &info)
126
- : Napi::ObjectWrap<MarketData>(info) {
220
+ : Napi::ObjectWrap<MarketData>(info), env_(info.Env()) {
127
221
  Napi::Env env = info.Env();
128
222
  if (info.Length() < 2 || !info[0].IsString()) {
129
223
  Napi::TypeError::New(env, "MarketData(flowPath, fronts)")
@@ -131,12 +225,20 @@ MarketData::MarketData(const Napi::CallbackInfo &info)
131
225
  return;
132
226
  }
133
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
+ }
134
233
 
135
234
  // Validate fronts BEFORE allocating anything: RegisterFront("") faults deep
136
235
  // inside the CTP DLL, so drop empty addresses and reject an empty result with
137
236
  // a clean JS error rather than crashing the process.
138
237
  std::vector<std::string> fronts;
139
- 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)
140
242
  if (!addr.empty())
141
243
  fronts.push_back(addr);
142
244
  if (fronts.empty()) {
@@ -155,7 +257,8 @@ MarketData::MarketData(const Napi::CallbackInfo &info)
155
257
  // wants the freshest quote, not a stale one, when the JS loop falls behind.
156
258
  ch_ = new EventChannel(8192, static_cast<size_t>(ctpMaxStructSize()),
157
259
  DropPolicy::Oldest);
158
- spi_ = new MdSpi(api_, ch_);
260
+ spi_ = new MdSpi(ch_);
261
+ spi_->setSnapshotCache(snap_.get());
159
262
  api_->RegisterSpi(spi_);
160
263
 
161
264
  for (auto &addr : fronts)
@@ -164,6 +267,41 @@ MarketData::MarketData(const Napi::CallbackInfo &info)
164
267
 
165
268
  MarketData::~MarketData() { doClose(); }
166
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
+
167
305
  void MarketData::doClose() {
168
306
  if (closed_)
169
307
  return;
@@ -172,17 +310,25 @@ void MarketData::doClose() {
172
310
  // can never push into a freed ring.
173
311
  if (burst_.joinable())
174
312
  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
313
  if (spi_) {
178
- spi_->clearApi();
179
314
  spi_->setArmRegistry(nullptr);
315
+ spi_->setSnapshotCache(nullptr);
180
316
  }
181
317
  if (api_) {
182
318
  api_->Release(); // stops the CTP callback thread (no more push / onTick)
183
319
  api_ = nullptr;
184
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
185
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();
186
332
  // Free the SPI and the ring here, on close(), rather than waiting for the JS
187
333
  // object's GC finalizer: the ring is large (~21 MB - maxStructSize * 8192
188
334
  // slots) but invisible to V8, so the GC feels no pressure and a create/close
@@ -196,7 +342,11 @@ void MarketData::doClose() {
196
342
  }
197
343
  if (ch_) {
198
344
  ch_->stop(); // abort doorbell TSF (idempotent)
199
- 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.
200
350
  ch_ = nullptr;
201
351
  }
202
352
  }
@@ -208,31 +358,45 @@ Napi::Value MarketData::GetApiVersion(const Napi::CallbackInfo &info) {
208
358
  Napi::Value MarketData::GetTradingDay(const Napi::CallbackInfo &info) {
209
359
  Napi::Env env = info.Env();
210
360
  if (!api_)
211
- return env.Null();
361
+ return Napi::String::New(env, "");
212
362
  const char *d = api_->GetTradingDay();
213
363
  return Napi::String::New(env, d ? d : "");
214
364
  }
215
365
 
216
366
  int MarketData::subscribeImpl(const Napi::CallbackInfo &info,
217
- int (CThostFtdcMdApi::*fn)(char *[], int)) {
367
+ int (CThostFtdcMdApi::*fn)(char *[], int),
368
+ std::vector<std::string> *acceptedIds) {
218
369
  if (!api_)
219
370
  return -1;
220
- auto ids = toStringList(info[0]);
371
+ std::vector<std::string> ids;
372
+ if (!toStringList(info[0], ids, "instrumentIds"))
373
+ return -1;
221
374
  if (ids.empty())
222
375
  return 0;
223
376
  std::vector<char *> ptrs(ids.size());
224
377
  for (size_t i = 0; i < ids.size(); ++i)
225
378
  ptrs[i] = const_cast<char *>(ids[i].c_str());
226
- 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;
227
383
  }
228
384
 
229
385
  Napi::Value MarketData::SubscribeMarketData(const Napi::CallbackInfo &info) {
230
- return Napi::Number::New(info.Env(),
231
- 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);
232
392
  }
233
393
  Napi::Value MarketData::UnsubscribeMarketData(const Napi::CallbackInfo &info) {
234
- return Napi::Number::New(
235
- info.Env(), subscribeImpl(info, &CThostFtdcMdApi::UnSubscribeMarketData));
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);
399
+ return Napi::Number::New(info.Env(), rc);
236
400
  }
237
401
  Napi::Value MarketData::SubscribeForQuoteRsp(const Napi::CallbackInfo &info) {
238
402
  return Napi::Number::New(
@@ -247,33 +411,110 @@ Napi::Value MarketData::ReqUserLogin(const Napi::CallbackInfo &info) {
247
411
  Napi::Env env = info.Env();
248
412
  if (!api_)
249
413
  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));
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();
259
431
  }
260
- int id = info[1].As<Napi::Number>().Int32Value();
261
- 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);
262
441
  }
263
442
 
264
443
  Napi::Value MarketData::ReqUserLogout(const Napi::CallbackInfo &info) {
265
444
  Napi::Env env = info.Env();
266
445
  if (!api_)
267
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
+ }
268
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;
269
489
  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));
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();
274
504
  }
275
- int id = info[1].As<Napi::Number>().Int32Value();
276
- 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)));
277
518
  }
278
519
 
279
520
  Napi::Value MarketData::Start(const Napi::CallbackInfo &info) {
@@ -294,18 +535,32 @@ Napi::Value MarketData::Start(const Napi::CallbackInfo &info) {
294
535
  Napi::Value MarketData::Buffer(const Napi::CallbackInfo &info) {
295
536
  if (!ch_)
296
537
  return info.Env().Undefined();
297
- 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;
298
558
  }
299
559
 
300
560
  Napi::Value MarketData::ClaimBatch(const Napi::CallbackInfo &info) {
301
561
  return Napi::Number::New(info.Env(), ch_ ? ch_->claim() : 0);
302
562
  }
303
563
 
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
564
  Napi::Value MarketData::ReadIndex(const Napi::CallbackInfo &info) {
310
565
  return Napi::Number::New(
311
566
  info.Env(), static_cast<double>(ch_ ? ch_->readIndex() : 0));
@@ -339,17 +594,83 @@ Napi::Value MarketData::Close(const Napi::CallbackInfo &info) {
339
594
  }
340
595
 
341
596
  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
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
346
630
  if (spi_)
347
- spi_->setArmRegistry(armReg_.get());
631
+ spi_->setArmRegistry(armReg_);
348
632
  }
349
633
  return info.Env().Undefined();
350
634
  }
351
635
 
636
+ // snapshot(instrumentId) -> the latest full depth tick as raw struct bytes (JS
637
+ // decodes with the shared codec, identical to a streamed tick), or null if none.
638
+ Napi::Value MarketData::Snapshot(const Napi::CallbackInfo &info) {
639
+ Napi::Env env = info.Env();
640
+ if (!info[0].IsString())
641
+ return env.Null();
642
+ CThostFtdcDepthMarketDataField f;
643
+ if (!snap_->get(info[0].As<Napi::String>().Utf8Value(), f))
644
+ return env.Null();
645
+ return Napi::Buffer<uint8_t>::Copy(env, reinterpret_cast<uint8_t *>(&f), sizeof(f));
646
+ }
647
+
648
+ // last(instrumentId) -> latest price (0 if none). Synchronous, no event wait.
649
+ Napi::Value MarketData::Last(const Napi::CallbackInfo &info) {
650
+ Napi::Env env = info.Env();
651
+ if (!info[0].IsString())
652
+ return Napi::Number::New(env, 0.0);
653
+ return Napi::Number::New(env, snap_->last(info[0].As<Napi::String>().Utf8Value()));
654
+ }
655
+
656
+ // Hand the LVC (as a shared_ptr) to a Trader so its deviation check reads live
657
+ // prices in C++ (Trader._attachSnapshot). Mirrors the arm-registry sharing: a
658
+ // heap shared_ptr copy with a finalizer, so the cache can't dangle.
659
+ Napi::Value MarketData::SnapshotExternal(const Napi::CallbackInfo &info) {
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; });
665
+ }
666
+
352
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
+ }
353
674
  // Drive the real SPI path (so arm triggers are evaluated too). Optional args
354
675
  // override bid/ask, so tests can inject edge prices - e.g. a DBL_MAX "no-bid"
355
676
  // sentinel (BidPrice1 at limit-down) to verify armed triggers ignore it:
@@ -373,6 +694,116 @@ Napi::Value MarketData::InjectTestTick(const Napi::CallbackInfo &info) {
373
694
  return info.Env().Undefined();
374
695
  }
375
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
+
376
807
  // test-only: spawn a background producer thread that pushes `n` synthetic depth
377
808
  // ticks straight into the real channel (the exact cross-thread SPSC + coalesced
378
809
  // doorbell path), each tagged with its sequence number in the requestId slot so
@@ -381,6 +812,12 @@ Napi::Value MarketData::InjectTestTick(const Napi::CallbackInfo &info) {
381
812
  // doorbell race the claim() seq_cst fence guards.
382
813
  Napi::Value MarketData::BurstTicks(const Napi::CallbackInfo &info) {
383
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
+ }
384
821
  if (closed_ || !ch_)
385
822
  return env.Undefined();
386
823
  if (burst_.joinable())
@@ -388,18 +825,25 @@ Napi::Value MarketData::BurstTicks(const Napi::CallbackInfo &info) {
388
825
  int n = info.Length() >= 1 ? info[0].As<Napi::Number>().Int32Value() : 0;
389
826
  // optional inter-push jitter in microseconds (0 = none) to widen the window.
390
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();
391
830
  EventChannel *ch = ch_;
392
- burst_ = std::thread([ch, n, jitterUs]() {
831
+ burst_ = std::thread([ch, n, jitterUs, injectControl]() {
393
832
  CThostFtdcDepthMarketDataField f;
394
833
  std::memset(&f, 0, sizeof(f));
395
834
  std::snprintf(f.InstrumentID, sizeof(f.InstrumentID), "%s", "rb2510");
396
835
  std::snprintf(f.ExchangeID, sizeof(f.ExchangeID), "%s", "SHFE");
397
836
  f.LastPrice = 3500.5;
398
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
+ }
399
843
  f.Volume = i; // sequence echo in the payload too
400
844
  // requestId field carries the sequence number (JS reads it per record).
401
845
  ch->push(MD_RTN_DEPTH_MARKET_DATA, i, -1, 0, "", SID_DepthMarketData, &f,
402
- (int)sizeof(f));
846
+ (int)sizeof(f), true);
403
847
  if (jitterUs > 0 && (i & 0x3F) == 0)
404
848
  std::this_thread::sleep_for(std::chrono::microseconds(jitterUs));
405
849
  }
@@ -407,6 +851,122 @@ Napi::Value MarketData::BurstTicks(const Napi::CallbackInfo &info) {
407
851
  return env.Undefined();
408
852
  }
409
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
+
410
970
  Napi::Function InitMarketData(Napi::Env env) { return MarketData::Init(env); }
411
971
 
412
972
  } // namespace ctp