@hitrading/ctp-node 2.0.0 → 4.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 +82 -0
  2. package/README.md +54 -32
  3. package/README.zh-CN.md +44 -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 +1909 -417
  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 +136 -79
  30. package/dist/trader.d.ts.map +1 -1
  31. package/dist/trader.js +807 -182
  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 +1445 -0
  38. package/docs/API.zh-CN.md +1285 -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 +11 -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 +78 -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 +769 -124
  77. package/src/native-binding.ts +4 -0
  78. package/src/trader.ts +1038 -207
  79. package/src/validation.ts +96 -0
@@ -14,9 +14,13 @@
14
14
 
15
15
  #include <algorithm>
16
16
  #include <atomic>
17
+ #include <cmath>
17
18
  #include <cstring>
19
+ #include <iterator>
18
20
  #include <memory>
19
21
  #include <string>
22
+ #include <thread>
23
+ #include <utility>
20
24
  #include <vector>
21
25
 
22
26
  #include "../generated/layout.gen.h"
@@ -25,40 +29,130 @@
25
29
  #include "ThostFtdcTraderApi.h"
26
30
  #include "arm.h"
27
31
  #include "channel.h"
32
+ #include "ctp_field.h"
33
+ #include "order_capability.h"
28
34
  #include "risk.h"
35
+ #include "shared_handle.h"
29
36
  #include "snapshot.h"
30
37
 
31
38
  namespace ctp {
32
39
 
33
40
  namespace {
34
41
 
35
- std::vector<std::string> toStringList(const Napi::Value &v) {
36
- std::vector<std::string> out;
42
+ // A per-instrument limit batch never legitimately spans more than the whole CTP
43
+ // instrument universe (a few tens of thousands). Reject anything larger up front
44
+ // so an attacker-controlled Array length cannot amplify into a huge reserve()
45
+ // whose std::bad_alloc would escape the Error-only N-API trampoline and abort
46
+ // the process instead of surfacing a catchable JS RangeError.
47
+ constexpr uint32_t kMaxInstrumentLimitBatch = 65536;
48
+
49
+ bool readInstrumentLimitBatchLength(const Napi::Array &input,
50
+ const char *label, uint32_t &length) {
51
+ Napi::Value lengthValue = input.Get("length");
52
+ if (!lengthValue.IsNumber()) {
53
+ Napi::TypeError::New(input.Env(), std::string(label) +
54
+ " length must be numeric")
55
+ .ThrowAsJavaScriptException();
56
+ return false;
57
+ }
58
+ const double rawLength = lengthValue.As<Napi::Number>().DoubleValue();
59
+ if (!std::isfinite(rawLength) || rawLength < 0.0 ||
60
+ rawLength > static_cast<double>(kMaxInstrumentLimitBatch)) {
61
+ Napi::RangeError::New(
62
+ input.Env(), std::string(label) +
63
+ " batch exceeds the maximum of 65536 instruments")
64
+ .ThrowAsJavaScriptException();
65
+ return false;
66
+ }
67
+ length = static_cast<uint32_t>(rawLength);
68
+ return true;
69
+ }
70
+
71
+ bool toStringList(const Napi::Value &v, std::vector<std::string> &out,
72
+ const char *label) {
37
73
  if (v.IsArray()) {
38
74
  Napi::Array a = v.As<Napi::Array>();
39
- for (uint32_t i = 0; i < a.Length(); ++i)
40
- out.push_back(a.Get(i).As<Napi::String>().Utf8Value());
75
+ for (uint32_t i = 0; i < a.Length(); ++i) {
76
+ Napi::Value item = a.Get(i);
77
+ if (!item.IsString()) {
78
+ Napi::TypeError::New(v.Env(), std::string(label) +
79
+ " must contain only strings")
80
+ .ThrowAsJavaScriptException();
81
+ return false;
82
+ }
83
+ std::string value = item.As<Napi::String>().Utf8Value();
84
+ if (value.find('\0') != std::string::npos) {
85
+ Napi::RangeError::New(v.Env(), std::string(label) +
86
+ " must not contain NUL")
87
+ .ThrowAsJavaScriptException();
88
+ return false;
89
+ }
90
+ out.push_back(std::move(value));
91
+ }
41
92
  } else if (v.IsString()) {
42
- out.push_back(v.As<Napi::String>().Utf8Value());
93
+ std::string value = v.As<Napi::String>().Utf8Value();
94
+ if (value.find('\0') != std::string::npos) {
95
+ Napi::RangeError::New(v.Env(), std::string(label) +
96
+ " must not contain NUL")
97
+ .ThrowAsJavaScriptException();
98
+ return false;
99
+ }
100
+ out.push_back(std::move(value));
101
+ } else {
102
+ Napi::TypeError::New(v.Env(), std::string(label) +
103
+ " must be a string or string array")
104
+ .ThrowAsJavaScriptException();
105
+ return false;
43
106
  }
44
- return out;
107
+ return true;
45
108
  }
46
109
 
47
- int getInt(const Napi::Object &o, const char *k, int d) {
48
- if (o.Has(k)) {
49
- Napi::Value v = o.Get(k);
50
- if (v.IsNumber())
51
- return v.As<Napi::Number>().Int32Value();
110
+ bool getFiniteNumber(const Napi::Object &object, const char *key,
111
+ double defaultValue, double &out) {
112
+ if (!object.Has(key)) {
113
+ out = defaultValue;
114
+ return true;
52
115
  }
53
- return d;
54
- }
55
- double getDbl(const Napi::Object &o, const char *k, double d) {
56
- if (o.Has(k)) {
57
- Napi::Value v = o.Get(k);
58
- if (v.IsNumber())
59
- return v.As<Napi::Number>().DoubleValue();
116
+ Napi::Value value = object.Get(key);
117
+ if (!value.IsNumber() ||
118
+ !std::isfinite(value.As<Napi::Number>().DoubleValue())) {
119
+ Napi::TypeError::New(object.Env(), std::string(key) +
120
+ " must be a finite number")
121
+ .ThrowAsJavaScriptException();
122
+ return false;
60
123
  }
61
- return d;
124
+ out = value.As<Napi::Number>().DoubleValue();
125
+ return true;
126
+ }
127
+
128
+ bool isInt32Number(const Napi::Value &v) {
129
+ if (!v.IsNumber())
130
+ return false;
131
+ const double n = v.As<Napi::Number>().DoubleValue();
132
+ return std::isfinite(n) && std::floor(n) == n && n >= -2147483648.0 &&
133
+ n <= 2147483647.0;
134
+ }
135
+
136
+ bool validRiskLimitKey(const std::string &key) {
137
+ static constexpr const char *keys[] = {
138
+ "maxOrderVolume", "maxPriceDeviation", "maxNotional",
139
+ "maxOrdersPerSec", "orderBurst", "maxCloseOrdersPerSec",
140
+ "closeOrderBurst", "maxAccountMargin", "maxReferenceAgeMs",
141
+ };
142
+ return std::any_of(std::begin(keys), std::end(keys),
143
+ [&](const char *candidate) { return key == candidate; });
144
+ }
145
+
146
+ bool testHooksEnabled(Napi::Env env) {
147
+ Napi::Value process = env.Global().Get("process");
148
+ if (!process.IsObject())
149
+ return false;
150
+ Napi::Value environment = process.As<Napi::Object>().Get("env");
151
+ if (!environment.IsObject())
152
+ return false;
153
+ Napi::Value value =
154
+ environment.As<Napi::Object>().Get("CTP_NODE_TEST_HOOKS");
155
+ return value.IsString() && value.As<Napi::String>().Utf8Value() == "1";
62
156
  }
63
157
 
64
158
  } // namespace
@@ -74,20 +168,28 @@ public:
74
168
 
75
169
  private:
76
170
  void doClose();
171
+ bool detachBufferForClose();
77
172
 
78
173
  Napi::Value GetApiVersion(const Napi::CallbackInfo &info);
79
174
  Napi::Value GetTradingDay(const Napi::CallbackInfo &info);
80
175
  Napi::Value Req(const Napi::CallbackInfo &info);
81
- Napi::Value RiskSet(const Napi::CallbackInfo &info);
82
- Napi::Value RiskHalt(const Napi::CallbackInfo &info);
176
+ Napi::Value SetRiskLimits(const Napi::CallbackInfo &info);
177
+ Napi::Value RiskReduceOnly(const Napi::CallbackInfo &info);
178
+ Napi::Value RiskHaltAll(const Napi::CallbackInfo &info);
83
179
  Napi::Value RiskResume(const Napi::CallbackInfo &info);
84
180
  Napi::Value LastRiskReason(const Napi::CallbackInfo &info);
181
+ Napi::Value TimeoutSessionTransition(const Napi::CallbackInfo &info);
182
+ Napi::Value ConfirmSessionAccount(const Napi::CallbackInfo &info);
183
+ Napi::Value BeginSessionHandshake(const Napi::CallbackInfo &info);
85
184
  Napi::Value AttachSnapshot(const Napi::CallbackInfo &info);
86
- Napi::Value SetMaxPositionVolume(const Napi::CallbackInfo &info);
87
- Napi::Value SetMaxInstrumentCost(const Napi::CallbackInfo &info);
185
+ Napi::Value SetInstrumentPositionLimits(const Napi::CallbackInfo &info);
186
+ Napi::Value SetInstrumentMarginLimits(const Napi::CallbackInfo &info);
88
187
  Napi::Value RebuildReservations(const Napi::CallbackInfo &info);
89
- Napi::Value SeedPosition(const Napi::CallbackInfo &info);
90
- Napi::Value PositionCost(const Napi::CallbackInfo &info);
188
+ Napi::Value RiskRevision(const Napi::CallbackInfo &info);
189
+ Napi::Value MarkPositionLedgerUncertain(const Napi::CallbackInfo &info);
190
+ Napi::Value MarkOrderLedgerUncertain(const Napi::CallbackInfo &info);
191
+ Napi::Value ReplacePositions(const Napi::CallbackInfo &info);
192
+ Napi::Value AccountMargin(const Napi::CallbackInfo &info);
91
193
  Napi::Value ResetPositions(const Napi::CallbackInfo &info);
92
194
  Napi::Value Start(const Napi::CallbackInfo &info);
93
195
  Napi::Value Buffer(const Napi::CallbackInfo &info);
@@ -101,13 +203,21 @@ private:
101
203
  Napi::Value Disarm(const Napi::CallbackInfo &info);
102
204
  Napi::Value ArmFireCount(const Napi::CallbackInfo &info);
103
205
  Napi::Value ArmBlockedCount(const Napi::CallbackInfo &info);
206
+ Napi::Value BurstEvents(const Napi::CallbackInfo &info);
207
+ Napi::Value InjectTestLogin(const Napi::CallbackInfo &info);
208
+ int nextArmRequestId();
104
209
 
105
210
  CThostFtdcTraderApi *api_ = nullptr;
106
211
  TraderSpi *spi_ = nullptr;
107
212
  EventChannel *ch_ = nullptr;
108
213
  RiskEngine risk_;
109
214
  std::shared_ptr<ArmRegistry> arm_ = std::make_shared<ArmRegistry>();
110
- std::atomic<int> armReqId_{1000000};
215
+ // Disjoint from JS CtpClient ids (1..0x3fffffff), preventing an armed-order
216
+ // error response from settling an unrelated pending query by numeric id.
217
+ std::atomic<uint32_t> armReqId_{0x40000000u};
218
+ std::thread burst_; // test-only lossless-channel stress producer
219
+ napi_env env_ = nullptr;
220
+ napi_ref bufferRef_ = nullptr;
111
221
  bool started_ = false;
112
222
  bool closed_ = false;
113
223
  };
@@ -116,19 +226,34 @@ Napi::Function Trader::Init(Napi::Env env) {
116
226
  return DefineClass(
117
227
  env, "Trader",
118
228
  {
119
- InstanceMethod("getApiVersion", &Trader::GetApiVersion),
120
- InstanceMethod("getTradingDay", &Trader::GetTradingDay),
229
+ InstanceMethod("apiVersion", &Trader::GetApiVersion),
230
+ InstanceMethod("tradingDay", &Trader::GetTradingDay),
121
231
  InstanceMethod("_req", &Trader::Req),
122
- InstanceMethod("riskSet", &Trader::RiskSet),
123
- InstanceMethod("riskHalt", &Trader::RiskHalt),
232
+ InstanceMethod("setRiskLimits", &Trader::SetRiskLimits),
233
+ InstanceMethod("riskReduceOnly", &Trader::RiskReduceOnly),
234
+ InstanceMethod("riskHaltAll", &Trader::RiskHaltAll),
124
235
  InstanceMethod("riskResume", &Trader::RiskResume),
125
236
  InstanceMethod("lastRiskReason", &Trader::LastRiskReason),
237
+ InstanceMethod("_timeoutSessionTransition",
238
+ &Trader::TimeoutSessionTransition),
239
+ InstanceMethod("_confirmSessionAccount",
240
+ &Trader::ConfirmSessionAccount),
241
+ InstanceMethod("_beginSessionHandshake",
242
+ &Trader::BeginSessionHandshake),
243
+ InstanceMethod("_injectTestLogin", &Trader::InjectTestLogin),
126
244
  InstanceMethod("_attachSnapshot", &Trader::AttachSnapshot),
127
- InstanceMethod("setMaxPositionVolume", &Trader::SetMaxPositionVolume),
128
- InstanceMethod("setMaxInstrumentCost", &Trader::SetMaxInstrumentCost),
245
+ InstanceMethod("_setInstrumentPositionLimits",
246
+ &Trader::SetInstrumentPositionLimits),
247
+ InstanceMethod("_setInstrumentMarginLimits",
248
+ &Trader::SetInstrumentMarginLimits),
129
249
  InstanceMethod("rebuildReservations", &Trader::RebuildReservations),
130
- InstanceMethod("seedPosition", &Trader::SeedPosition),
131
- InstanceMethod("positionCost", &Trader::PositionCost),
250
+ InstanceMethod("riskRevision", &Trader::RiskRevision),
251
+ InstanceMethod("_markPositionLedgerUncertain",
252
+ &Trader::MarkPositionLedgerUncertain),
253
+ InstanceMethod("_markOrderLedgerUncertain",
254
+ &Trader::MarkOrderLedgerUncertain),
255
+ InstanceMethod("replacePositions", &Trader::ReplacePositions),
256
+ InstanceMethod("accountMargin", &Trader::AccountMargin),
132
257
  InstanceMethod("resetPositions", &Trader::ResetPositions),
133
258
  InstanceMethod("_start", &Trader::Start),
134
259
  InstanceMethod("_buffer", &Trader::Buffer),
@@ -141,11 +266,13 @@ Napi::Function Trader::Init(Napi::Env env) {
141
266
  InstanceMethod("disarm", &Trader::Disarm),
142
267
  InstanceMethod("_armFireCount", &Trader::ArmFireCount),
143
268
  InstanceMethod("_armBlockedCount", &Trader::ArmBlockedCount),
269
+ InstanceMethod("_burstEvents", &Trader::BurstEvents),
144
270
  InstanceMethod("close", &Trader::Close),
145
271
  });
146
272
  }
147
273
 
148
- Trader::Trader(const Napi::CallbackInfo &info) : Napi::ObjectWrap<Trader>(info) {
274
+ Trader::Trader(const Napi::CallbackInfo &info)
275
+ : Napi::ObjectWrap<Trader>(info), env_(info.Env()) {
149
276
  Napi::Env env = info.Env();
150
277
  if (info.Length() < 2 || !info[0].IsString()) {
151
278
  Napi::TypeError::New(env, "Trader(flowPath, fronts)")
@@ -153,12 +280,20 @@ Trader::Trader(const Napi::CallbackInfo &info) : Napi::ObjectWrap<Trader>(info)
153
280
  return;
154
281
  }
155
282
  std::string flowPath = info[0].As<Napi::String>().Utf8Value();
283
+ if (flowPath.find('\0') != std::string::npos) {
284
+ Napi::RangeError::New(env, "Trader flowPath must not contain NUL")
285
+ .ThrowAsJavaScriptException();
286
+ return;
287
+ }
156
288
 
157
289
  // Validate fronts BEFORE allocating anything: RegisterFront("") faults deep
158
290
  // inside the CTP DLL, so drop empty addresses and reject an empty result with
159
291
  // a clean JS error rather than crashing the process.
160
292
  std::vector<std::string> fronts;
161
- for (auto &addr : toStringList(info[1]))
293
+ std::vector<std::string> requestedFronts;
294
+ if (!toStringList(info[1], requestedFronts, "fronts"))
295
+ return;
296
+ for (auto &addr : requestedFronts)
162
297
  if (!addr.empty())
163
298
  fronts.push_back(addr);
164
299
  if (fronts.empty()) {
@@ -174,12 +309,18 @@ Trader::Trader(const Napi::CallbackInfo &info) : Napi::ObjectWrap<Trader>(info)
174
309
  .ThrowAsJavaScriptException();
175
310
  return;
176
311
  }
177
- // Trader uses DropPolicy::Newest (reliable): order/trade returns must never be
178
- // silently discarded under backpressure.
312
+ // Trader uses a lossless staged overflow: order/trade/query returns must never
313
+ // be silently discarded under backpressure.
179
314
  ch_ = new EventChannel(4096, static_cast<size_t>(ctpMaxStructSize()),
180
- DropPolicy::Newest);
181
- spi_ = new TraderSpi(api_, ch_);
182
- spi_->setRisk(&risk_); // fills update the position-cost tracker
315
+ DropPolicy::Lossless);
316
+ spi_ = new TraderSpi(ch_);
317
+ spi_->setRisk(&risk_); // fills update the position-margin tracker
318
+ spi_->setArmRegistry(arm_.get()); // front transitions revoke old mandates
319
+ // Fail closed even before the first OnFrontConnected callback. Opening
320
+ // permission must come only from authoritative position + working-order
321
+ // snapshots, never from a timing window during construction/initial login.
322
+ risk_.markTradeLedgerUncertain();
323
+ risk_.markOrderLedgerUncertain();
183
324
  api_->RegisterSpi(spi_);
184
325
  arm_->setSink(this); // armed triggers fire orders through this Trader
185
326
  api_->SubscribePublicTopic(THOST_TERT_QUICK);
@@ -191,10 +332,41 @@ Trader::Trader(const Napi::CallbackInfo &info) : Napi::ObjectWrap<Trader>(info)
191
332
 
192
333
  Trader::~Trader() { doClose(); }
193
334
 
335
+ bool Trader::detachBufferForClose() {
336
+ if (!bufferRef_)
337
+ return true;
338
+
339
+ // Fail closed on every N-API anomaly: an attached external ArrayBuffer is a
340
+ // reason to retain native backing storage, never a reason to risk a UAF.
341
+ bool safeToFreeRing = false;
342
+ napi_value buffer = nullptr;
343
+ if (env_ &&
344
+ napi_get_reference_value(env_, bufferRef_, &buffer) == napi_ok &&
345
+ buffer != nullptr) {
346
+ bool detached = false;
347
+ if (napi_is_detached_arraybuffer(env_, buffer, &detached) == napi_ok) {
348
+ if (detached) {
349
+ safeToFreeRing = true;
350
+ } else if (napi_detach_arraybuffer(env_, buffer) == napi_ok) {
351
+ detached = false;
352
+ safeToFreeRing =
353
+ napi_is_detached_arraybuffer(env_, buffer, &detached) == napi_ok &&
354
+ detached;
355
+ }
356
+ }
357
+ }
358
+ if (env_)
359
+ napi_delete_reference(env_, bufferRef_);
360
+ bufferRef_ = nullptr;
361
+ return safeToFreeRing;
362
+ }
363
+
194
364
  void Trader::doClose() {
195
365
  if (closed_)
196
366
  return;
197
367
  closed_ = true;
368
+ if (burst_.joinable())
369
+ burst_.join();
198
370
  // Order matters: clearSink() (under the arm lock) guarantees no fireArmed is
199
371
  // running or will start, so the non-atomic api_ below is never read after it
200
372
  // is nulled. Do NOT move the api_ teardown before clearSink().
@@ -203,6 +375,9 @@ void Trader::doClose() {
203
375
  api_->Release();
204
376
  api_ = nullptr;
205
377
  }
378
+ // The ring backs one cached external ArrayBuffer. Detach it before freeing
379
+ // the native storage so retained JS references can never read freed memory.
380
+ const bool safeToFreeRing = detachBufferForClose();
206
381
  // Free the SPI and the ring here, on close(), not in the GC finalizer: the
207
382
  // ring (~maxStructSize * 4096 slots, ~10 MB) is off-heap so V8 feels no GC
208
383
  // pressure from it, and a create/close loop leaks it (measured unreclaimed
@@ -214,7 +389,10 @@ void Trader::doClose() {
214
389
  }
215
390
  if (ch_) {
216
391
  ch_->stop();
217
- delete ch_;
392
+ if (safeToFreeRing)
393
+ delete ch_;
394
+ // A stopped-channel leak is preferable to exposing freed storage through
395
+ // an ArrayBuffer if detachment unexpectedly failed.
218
396
  ch_ = nullptr;
219
397
  }
220
398
  }
@@ -227,53 +405,142 @@ int Trader::fireArmed(const ArmSpec &spec) {
227
405
  std::memset(&f, 0, sizeof(f));
228
406
  std::memcpy(&f, spec.orderTemplate.data(),
229
407
  std::min(spec.orderTemplate.size(), sizeof(f)));
230
- // Deviation check is intentionally skipped (refPrice 0) for armed orders:
231
- // they fire on fast moves where the limit can legitimately differ from the
232
- // last print, and silently blocking the armed order would be worse. Volume,
233
- // notional (multiplier-aware), kill-switch and rate limit still apply.
234
- RiskVerdict v = risk_.check(f.InstrumentID, f.LimitPrice, 0.0,
235
- f.VolumeTotalOriginal);
408
+ OrdinaryOrderIdentity identity;
409
+ if (!decodeOrdinaryOrder(f, identity))
410
+ return CTP_INVALID_ORDER_FIELDS;
411
+ const bool isOpen = f.CombOffsetFlag[0] == '0';
412
+ bool sendAllowed = false;
413
+ auto sendGuard = risk_.acquireOrderSendForAccount(
414
+ isOpen, identity.brokerId, identity.investorId, sendAllowed);
415
+ if (!sendAllowed)
416
+ return CTP_RISK_BLOCKED;
417
+ // Armed orders use the same fail-closed gate as regular orders. In particular,
418
+ // a configured deviation check may not silently skip stale/missing market data.
419
+ RiskVerdict v = risk_.check(identity.instrumentId, f.LimitPrice,
420
+ risk_.refPrice(identity.instrumentId),
421
+ f.VolumeTotalOriginal, isOpen);
236
422
  if (!v.ok)
237
423
  return CTP_RISK_BLOCKED;
424
+ int requestId = 0;
238
425
  // Position caps (incl. in-flight reservation) apply to armed orders too -
239
426
  // safety, not latency-sensitive.
240
- const bool isOpen = (f.CombOffsetFlag[0] == '0');
241
427
  if (isOpen) {
242
- OpenGate g = risk_.tryReserveOpen(f.OrderRef, f.InstrumentID,
428
+ OpenGate g = risk_.tryReserveOpen(identity.orderRef, identity.instrumentId,
243
429
  f.Direction == '0', f.LimitPrice,
244
- f.VolumeTotalOriginal);
430
+ f.VolumeTotalOriginal,
431
+ f.CombHedgeFlag[0]);
245
432
  if (g == OpenGate::VolumeLimit)
246
433
  return CTP_POSITION_VOLUME_LIMIT;
247
434
  if (g == OpenGate::CostLimit)
248
435
  return CTP_POSITION_LIMIT;
436
+ if (g == OpenGate::DuplicateOrderRef)
437
+ return CTP_DUPLICATE_ORDER_REF;
438
+ if (g == OpenGate::MetadataUnavailable)
439
+ return CTP_RISK_METADATA_UNAVAILABLE;
440
+ requestId = nextArmRequestId();
441
+ if (!risk_.bindInsertRequest(requestId, identity.orderRef))
442
+ return CTP_RISK_METADATA_UNAVAILABLE;
249
443
  }
250
- if (!risk_.allowRate()) {
251
- if (isOpen)
252
- risk_.releaseReservation(f.OrderRef);
444
+ if (isOpen && !risk_.allowRate()) {
445
+ risk_.rollbackInsertRequest(requestId, identity.orderRef);
253
446
  return CTP_RATE_LIMITED;
254
447
  }
255
- int sendRc = api->ReqOrderInsert(&f, armReqId_.fetch_add(1));
448
+ if (!isOpen && !risk_.allowCloseRate())
449
+ return CTP_RATE_LIMITED;
450
+ if (requestId == 0)
451
+ requestId = nextArmRequestId();
452
+ int sendRc = api->ReqOrderInsert(&f, requestId);
256
453
  if (sendRc != 0 && isOpen)
257
- risk_.releaseReservation(f.OrderRef); // send failed -> release the reservation
454
+ risk_.rollbackInsertRequest(requestId, identity.orderRef); // not accepted; arm may retry this ref
258
455
  return sendRc;
259
456
  }
260
457
 
458
+ int Trader::nextArmRequestId() {
459
+ uint32_t current = armReqId_.load(std::memory_order_relaxed);
460
+ for (;;) {
461
+ const uint32_t next = current >= 0x7fffffffu ? 0x40000000u : current + 1u;
462
+ if (armReqId_.compare_exchange_weak(current, next,
463
+ std::memory_order_relaxed,
464
+ std::memory_order_relaxed))
465
+ return static_cast<int>(current);
466
+ }
467
+ }
468
+
261
469
  Napi::Value Trader::ArmRegistryExternal(const Napi::CallbackInfo &info) {
262
- auto *sp = new std::shared_ptr<ArmRegistry>(arm_);
263
- return Napi::External<std::shared_ptr<ArmRegistry>>::New(
264
- info.Env(), sp,
265
- [](Napi::Env, std::shared_ptr<ArmRegistry> *p) { delete p; });
470
+ if (closed_ || !api_ || !arm_->hasSink()) {
471
+ Napi::Error::New(info.Env(), "Trader is closed")
472
+ .ThrowAsJavaScriptException();
473
+ return info.Env().Undefined();
474
+ }
475
+ auto *handle = new SharedHandle();
476
+ handle->kind = SharedHandleKind::ArmRegistry;
477
+ handle->arm = arm_;
478
+ return Napi::External<SharedHandle>::New(
479
+ info.Env(), handle, [](Napi::Env, SharedHandle *p) { delete p; });
266
480
  }
267
481
 
268
482
  Napi::Value Trader::Arm(const Napi::CallbackInfo &info) {
269
483
  Napi::Env env = info.Env();
484
+ if (closed_ || !api_ || !arm_->hasSink()) {
485
+ Napi::Error::New(env, "Trader is closed").ThrowAsJavaScriptException();
486
+ return env.Undefined();
487
+ }
488
+ if (info.Length() < 4 || !info[0].IsString() || !info[1].IsString() ||
489
+ !info[2].IsNumber() || !info[3].IsTypedArray()) {
490
+ Napi::TypeError::New(env, "invalid armed-order arguments")
491
+ .ThrowAsJavaScriptException();
492
+ return env.Undefined();
493
+ }
494
+ Napi::TypedArray typed = info[3].As<Napi::TypedArray>();
495
+ if (typed.TypedArrayType() != napi_uint8_array) {
496
+ Napi::TypeError::New(env, "armed order template must be a Uint8Array")
497
+ .ThrowAsJavaScriptException();
498
+ return env.Undefined();
499
+ }
500
+ Napi::Uint8Array bytes = info[3].As<Napi::Uint8Array>();
501
+ if (bytes.ByteLength() != sizeof(CThostFtdcInputOrderField)) {
502
+ Napi::RangeError::New(env, "invalid armed InputOrder byte length")
503
+ .ThrowAsJavaScriptException();
504
+ return env.Undefined();
505
+ }
506
+ CThostFtdcInputOrderField order;
507
+ std::memcpy(&order, bytes.Data(), sizeof(order));
508
+ OrdinaryOrderIdentity identity;
509
+ if (!decodeOrdinaryOrder(order, identity)) {
510
+ Napi::TypeError::New(env, "unsupported armed order template")
511
+ .ThrowAsJavaScriptException();
512
+ return env.Undefined();
513
+ }
270
514
  ArmSpec spec;
271
515
  spec.instrumentId = info[0].As<Napi::String>().Utf8Value();
272
516
  std::string side = info[1].As<Napi::String>().Utf8Value();
273
- spec.side = side.empty() ? '0' : side[0];
517
+ spec.side = side.size() == 1 ? side[0] : '\0';
274
518
  spec.triggerPrice = info[2].As<Napi::Number>().DoubleValue();
275
- Napi::Uint8Array bytes = info[3].As<Napi::Uint8Array>();
519
+ if (spec.instrumentId != identity.instrumentId ||
520
+ (spec.side != '0' && spec.side != '1') || spec.side != order.Direction ||
521
+ !std::isfinite(spec.triggerPrice) || spec.triggerPrice <= 0.0 ||
522
+ spec.triggerPrice >= 1e300) {
523
+ Napi::TypeError::New(env, "armed trigger does not match its order template")
524
+ .ThrowAsJavaScriptException();
525
+ return env.Undefined();
526
+ }
276
527
  spec.orderTemplate.assign(bytes.Data(), bytes.Data() + bytes.ByteLength());
528
+ const bool isOpen = order.CombOffsetFlag[0] == '0';
529
+ bool allowed = false;
530
+ // Gate registration on the risk MODE only: a HaltAll (and, for opens,
531
+ // ReduceOnly) hard-stop must not accept new arms. The account/session scope is
532
+ // deliberately NOT checked here — at the native layer an arm may legitimately
533
+ // be registered before login and fire once the session is confirmed. (The
534
+ // TypeScript arm() wrapper is stricter still: it needs a confirmed login to
535
+ // stamp the order template's broker/investor.) fireArmed() re-applies the full
536
+ // per-account gate at send time, so no armed order can reach CTP in an
537
+ // unconfirmed or foreign account regardless of when it was registered.
538
+ auto sendGuard = risk_.acquireOrderSend(isOpen, allowed);
539
+ if (!allowed) {
540
+ Napi::Error::New(env, "cannot arm while order sending is halted")
541
+ .ThrowAsJavaScriptException();
542
+ return env.Undefined();
543
+ }
277
544
  uint64_t id = arm_->arm(std::move(spec));
278
545
  return Napi::Number::New(env, static_cast<double>(id));
279
546
  }
@@ -293,6 +560,28 @@ Napi::Value Trader::ArmFireCount(const Napi::CallbackInfo &info) {
293
560
  static_cast<double>(arm_->fireCount()));
294
561
  }
295
562
 
563
+ Napi::Value Trader::BurstEvents(const Napi::CallbackInfo &info) {
564
+ if (!testHooksEnabled(info.Env())) {
565
+ Napi::Error::New(info.Env(),
566
+ "test hook disabled; set CTP_NODE_TEST_HOOKS=1 explicitly")
567
+ .ThrowAsJavaScriptException();
568
+ return info.Env().Undefined();
569
+ }
570
+ if (!ch_ || closed_)
571
+ return info.Env().Undefined();
572
+ const int n = info[0].As<Napi::Number>().Int32Value();
573
+ if (n <= 0)
574
+ return info.Env().Undefined();
575
+ if (burst_.joinable())
576
+ burst_.join();
577
+ EventChannel *ch = ch_;
578
+ burst_ = std::thread([ch, n]() {
579
+ for (int i = 0; i < n; ++i)
580
+ ch->push(ET_RtnTrade, i, -1, 0, "", -2, &i, sizeof(i));
581
+ });
582
+ return info.Env().Undefined();
583
+ }
584
+
296
585
  Napi::Value Trader::GetApiVersion(const Napi::CallbackInfo &info) {
297
586
  return Napi::String::New(info.Env(), CThostFtdcTraderApi::GetApiVersion());
298
587
  }
@@ -300,7 +589,7 @@ Napi::Value Trader::GetApiVersion(const Napi::CallbackInfo &info) {
300
589
  Napi::Value Trader::GetTradingDay(const Napi::CallbackInfo &info) {
301
590
  Napi::Env env = info.Env();
302
591
  if (!api_)
303
- return env.Null();
592
+ return Napi::String::New(env, "");
304
593
  const char *d = api_->GetTradingDay();
305
594
  return Napi::String::New(env, d ? d : "");
306
595
  }
@@ -310,6 +599,15 @@ Napi::Value Trader::Req(const Napi::CallbackInfo &info) {
310
599
  if (!api_)
311
600
  return Napi::Number::New(env, -1);
312
601
  int methodId = info[0].As<Napi::Number>().Int32Value();
602
+ if (methodId == M_ReqUserLogin || methodId == M_ReqUserLogout ||
603
+ methodId == M_ReqUserLoginWithCaptcha ||
604
+ methodId == M_ReqUserLoginWithText ||
605
+ methodId == M_ReqUserLoginWithOTP) {
606
+ // A mandate belongs to one authenticated session/account. Clear it before
607
+ // the transition request; traderReq() then invalidates the risk identity
608
+ // before calling CTP. A failed transition stays deliberately disarmed.
609
+ arm_->clear();
610
+ }
313
611
  Napi::Uint8Array bytes = info[1].As<Napi::Uint8Array>();
314
612
  int id = info[2].As<Napi::Number>().Int32Value();
315
613
  int rc = traderReq(api_, methodId, bytes.Data(),
@@ -317,24 +615,72 @@ Napi::Value Trader::Req(const Napi::CallbackInfo &info) {
317
615
  return Napi::Number::New(env, rc);
318
616
  }
319
617
 
320
- Napi::Value Trader::RiskSet(const Napi::CallbackInfo &info) {
321
- if (info[0].IsObject()) {
322
- Napi::Object o = info[0].As<Napi::Object>();
323
- RiskConfig cfg;
324
- cfg.maxOrderVolume = getInt(o, "maxOrderVolume", 0);
325
- cfg.maxPriceDeviation = getDbl(o, "maxPriceDeviation", 0.0);
326
- cfg.maxNotional = getDbl(o, "maxNotional", 0.0);
327
- cfg.maxOrdersPerSec = getDbl(o, "maxOrdersPerSec", 0.0);
328
- cfg.orderBurst = getDbl(o, "orderBurst", 0.0);
329
- cfg.maxPositionCost = getDbl(o, "maxPositionCost", 0.0);
330
- cfg.maxMargin = getDbl(o, "maxMargin", 0.0);
331
- risk_.configure(cfg);
618
+ Napi::Value Trader::SetRiskLimits(const Napi::CallbackInfo &info) {
619
+ Napi::Env env = info.Env();
620
+ if (info.Length() < 1 || !info[0].IsObject() || info[0].IsArray()) {
621
+ Napi::TypeError::New(env, "setRiskLimits requires an object")
622
+ .ThrowAsJavaScriptException();
623
+ return env.Undefined();
624
+ }
625
+ Napi::Object object = info[0].As<Napi::Object>();
626
+ Napi::Array names = object.GetPropertyNames();
627
+ for (uint32_t i = 0; i < names.Length(); ++i) {
628
+ Napi::Value name = names.Get(i);
629
+ if (!name.IsString() ||
630
+ !validRiskLimitKey(name.As<Napi::String>().Utf8Value())) {
631
+ Napi::TypeError::New(env, "setRiskLimits contains an unknown field")
632
+ .ThrowAsJavaScriptException();
633
+ return env.Undefined();
634
+ }
635
+ }
636
+ RiskLimits cfg;
637
+ double maxOrderVolume = 0.0;
638
+ if (!getFiniteNumber(object, "maxOrderVolume", 0.0, maxOrderVolume) ||
639
+ !getFiniteNumber(object, "maxPriceDeviation", 0.0,
640
+ cfg.maxPriceDeviation) ||
641
+ !getFiniteNumber(object, "maxNotional", 0.0, cfg.maxNotional) ||
642
+ !getFiniteNumber(object, "maxOrdersPerSec", 0.0,
643
+ cfg.maxOrdersPerSec) ||
644
+ !getFiniteNumber(object, "orderBurst", 0.0, cfg.orderBurst) ||
645
+ !getFiniteNumber(object, "maxCloseOrdersPerSec", 0.0,
646
+ cfg.maxCloseOrdersPerSec) ||
647
+ !getFiniteNumber(object, "closeOrderBurst", 0.0,
648
+ cfg.closeOrderBurst) ||
649
+ !getFiniteNumber(object, "maxAccountMargin", 0.0,
650
+ cfg.maxAccountMargin) ||
651
+ !getFiniteNumber(object, "maxReferenceAgeMs", 3000.0,
652
+ cfg.maxReferenceAgeMs))
653
+ return env.Undefined();
654
+ if (maxOrderVolume < 0.0 || cfg.maxPriceDeviation < 0.0 ||
655
+ cfg.maxNotional < 0.0 || cfg.maxOrdersPerSec < 0.0 ||
656
+ cfg.orderBurst < 0.0 || cfg.maxCloseOrdersPerSec < 0.0 ||
657
+ cfg.closeOrderBurst < 0.0 || cfg.maxAccountMargin < 0.0 ||
658
+ (maxOrderVolume > 0.0 &&
659
+ (std::floor(maxOrderVolume) != maxOrderVolume ||
660
+ maxOrderVolume > 2147483647.0)) ||
661
+ cfg.maxReferenceAgeMs <= 0.0) {
662
+ Napi::TypeError::New(env, "invalid risk-limit value")
663
+ .ThrowAsJavaScriptException();
664
+ return env.Undefined();
332
665
  }
666
+ cfg.maxOrderVolume = maxOrderVolume > 0.0
667
+ ? static_cast<int>(maxOrderVolume)
668
+ : 0;
669
+ risk_.configure(cfg);
670
+ return env.Undefined();
671
+ }
672
+
673
+ Napi::Value Trader::RiskReduceOnly(const Napi::CallbackInfo &info) {
674
+ risk_.reduceOnly();
333
675
  return info.Env().Undefined();
334
676
  }
335
677
 
336
- Napi::Value Trader::RiskHalt(const Napi::CallbackInfo &info) {
337
- risk_.halt();
678
+ Napi::Value Trader::RiskHaltAll(const Napi::CallbackInfo &info) {
679
+ // First close the final send barrier (and wait for any already-admitted send
680
+ // to return), then discard historical mandates. After this method returns,
681
+ // resume() cannot unexpectedly fire an arm created before the hard stop.
682
+ risk_.haltAll();
683
+ arm_->clear();
338
684
  return info.Env().Undefined();
339
685
  }
340
686
 
@@ -349,74 +695,358 @@ Napi::Value Trader::LastRiskReason(const Napi::CallbackInfo &info) {
349
695
  return Napi::String::New(info.Env(), r ? r : "");
350
696
  }
351
697
 
698
+ Napi::Value Trader::TimeoutSessionTransition(
699
+ const Napi::CallbackInfo &info) {
700
+ if (info.Length() < 1 || !info[0].IsNumber())
701
+ return Napi::Boolean::New(info.Env(), true);
702
+ const double raw = info[0].As<Napi::Number>().DoubleValue();
703
+ if (!std::isfinite(raw) || std::floor(raw) != raw || raw <= 0.0 ||
704
+ raw > 2147483647.0)
705
+ return Napi::Boolean::New(info.Env(), true);
706
+ return Napi::Boolean::New(
707
+ info.Env(),
708
+ risk_.timeoutSessionTransition(static_cast<int>(raw)));
709
+ }
710
+
711
+ Napi::Value Trader::ConfirmSessionAccount(const Napi::CallbackInfo &info) {
712
+ Napi::Env env = info.Env();
713
+ if (info.Length() < 3 || !isInt32Number(info[0]) ||
714
+ !isInt32Number(info[1]) || !info[2].IsTypedArray()) {
715
+ Napi::TypeError::New(
716
+ env, "_confirmSessionAccount requires frontId, sessionId and encoded SettlementInfoConfirm bytes")
717
+ .ThrowAsJavaScriptException();
718
+ return env.Undefined();
719
+ }
720
+ Napi::TypedArray typed = info[2].As<Napi::TypedArray>();
721
+ if (typed.TypedArrayType() != napi_uint8_array) {
722
+ Napi::TypeError::New(
723
+ env, "_confirmSessionAccount bytes must be a Uint8Array")
724
+ .ThrowAsJavaScriptException();
725
+ return env.Undefined();
726
+ }
727
+ Napi::Uint8Array bytes = info[2].As<Napi::Uint8Array>();
728
+ if (bytes.ByteLength() != sizeof(CThostFtdcSettlementInfoConfirmField)) {
729
+ Napi::RangeError::New(
730
+ env, "invalid encoded SettlementInfoConfirm byte length")
731
+ .ThrowAsJavaScriptException();
732
+ return env.Undefined();
733
+ }
734
+ CThostFtdcSettlementInfoConfirmField account;
735
+ std::memcpy(&account, bytes.Data(), sizeof(account));
736
+ std::string brokerId, investorId;
737
+ if (!boundedCtpField(account.BrokerID, brokerId) ||
738
+ !boundedCtpField(account.InvestorID, investorId) || brokerId.empty() ||
739
+ investorId.empty()) {
740
+ Napi::RangeError::New(env, "invalid encoded session account identity")
741
+ .ThrowAsJavaScriptException();
742
+ return env.Undefined();
743
+ }
744
+ const int frontId = info[0].As<Napi::Number>().Int32Value();
745
+ const int sessionId = info[1].As<Napi::Number>().Int32Value();
746
+ return Napi::Boolean::New(
747
+ env, risk_.confirmSessionAccount(frontId, sessionId, brokerId,
748
+ investorId));
749
+ }
750
+
751
+ Napi::Value Trader::BeginSessionHandshake(const Napi::CallbackInfo &info) {
752
+ if (arm_)
753
+ arm_->clear();
754
+ risk_.invalidateSession();
755
+ return info.Env().Undefined();
756
+ }
757
+
758
+ // Test-only: establish a confirmed native session offline. Drives the exact
759
+ // same RiskEngine handshake the live path uses (beginSessionTransition ->
760
+ // acceptLoginSession, as the SPI OnRspUserLogin would, then confirmSessionAccount
761
+ // as the high-level session() does), so an order/arm test can reach a confirmed
762
+ // account without a live front. Gated behind CTP_NODE_TEST_HOOKS like the other
763
+ // injection hooks; returns whether the confirmed session was established.
764
+ Napi::Value Trader::InjectTestLogin(const Napi::CallbackInfo &info) {
765
+ Napi::Env env = info.Env();
766
+ if (!testHooksEnabled(env)) {
767
+ Napi::Error::New(env,
768
+ "test hook disabled; set CTP_NODE_TEST_HOOKS=1 explicitly")
769
+ .ThrowAsJavaScriptException();
770
+ return env.Undefined();
771
+ }
772
+ if (info.Length() < 4 || !isInt32Number(info[0]) || !isInt32Number(info[1]) ||
773
+ !info[2].IsString() || !info[3].IsString()) {
774
+ Napi::TypeError::New(
775
+ env, "_injectTestLogin requires frontId, sessionId, brokerId, investorId")
776
+ .ThrowAsJavaScriptException();
777
+ return env.Undefined();
778
+ }
779
+ const int frontId = info[0].As<Napi::Number>().Int32Value();
780
+ const int sessionId = info[1].As<Napi::Number>().Int32Value();
781
+ const std::string brokerId = info[2].As<Napi::String>().Utf8Value();
782
+ const std::string investorId = info[3].As<Napi::String>().Utf8Value();
783
+ // Drives pendingSessionRequestId_ (the session-transition slot) — a separate
784
+ // structure from the insert/arm request bindings (insertRequests_), so this id
785
+ // need not be unique across those spaces (nextArmRequestId can also return this
786
+ // value). acceptLoginSession clears it immediately, leaving no pending state.
787
+ static constexpr int kTestLoginRequestId = 2147483647;
788
+ risk_.beginSessionTransition(kTestLoginRequestId, true, brokerId, investorId);
789
+ if (!risk_.acceptLoginSession(kTestLoginRequestId, frontId, sessionId,
790
+ brokerId, investorId))
791
+ return Napi::Boolean::New(env, false);
792
+ return Napi::Boolean::New(
793
+ env, risk_.confirmSessionAccount(frontId, sessionId, brokerId, investorId));
794
+ }
795
+
352
796
  // (mdSnapshotExternal) - attach a MarketData's snapshot cache so the deviation
353
797
  // check reads live prices in C++ (no JS round-trip). See Trader.trackMarketData.
354
798
  Napi::Value Trader::AttachSnapshot(const Napi::CallbackInfo &info) {
355
- auto ext = info[0].As<Napi::External<std::shared_ptr<SnapshotCache>>>();
356
- std::shared_ptr<SnapshotCache> *sp = ext.Data();
357
- if (sp && *sp)
358
- risk_.setMdSnapshot(*sp); // SnapshotCache -> const RefPriceSource (upcast)
799
+ if (info.Length() < 1 || !info[0].IsExternal()) {
800
+ Napi::TypeError::New(info.Env(), "invalid MarketData snapshot handle")
801
+ .ThrowAsJavaScriptException();
802
+ return info.Env().Undefined();
803
+ }
804
+ auto ext = info[0].As<Napi::External<SharedHandle>>();
805
+ SharedHandle *handle = ext.Data();
806
+ if (!handle || handle->magic != SharedHandle::kMagic ||
807
+ handle->kind != SharedHandleKind::SnapshotCache || !handle->snapshot) {
808
+ Napi::TypeError::New(info.Env(), "invalid MarketData snapshot handle")
809
+ .ThrowAsJavaScriptException();
810
+ return info.Env().Undefined();
811
+ }
812
+ risk_.setMdSnapshot(handle->snapshot);
359
813
  return info.Env().Undefined();
360
814
  }
361
815
 
362
- // (instrumentId, isLong, maxVolume) - per-side open-position lot cap; 0 = off.
363
- Napi::Value Trader::SetMaxPositionVolume(const Napi::CallbackInfo &info) {
364
- if (info.Length() >= 3 && info[0].IsString() && info[2].IsNumber()) {
365
- risk_.setMaxPositionVolume(info[0].As<Napi::String>().Utf8Value(),
366
- info[1].ToBoolean().Value(),
367
- info[2].As<Napi::Number>().DoubleValue());
816
+ // (Array<{instrumentId, long?, short?}>) - one atomic position-limit batch.
817
+ Napi::Value Trader::SetInstrumentPositionLimits(
818
+ const Napi::CallbackInfo &info) {
819
+ Napi::Env env = info.Env();
820
+ if (info.Length() < 1 || !info[0].IsArray()) {
821
+ Napi::TypeError::New(env, "position limits must be an array")
822
+ .ThrowAsJavaScriptException();
823
+ return env.Undefined();
368
824
  }
369
- return info.Env().Undefined();
825
+ Napi::Array input = info[0].As<Napi::Array>();
826
+ uint32_t length = 0;
827
+ if (!readInstrumentLimitBatchLength(input, "position limits", length))
828
+ return env.Undefined();
829
+ std::vector<InstrumentPositionLimitUpdate> updates;
830
+ updates.reserve(length);
831
+ for (uint32_t i = 0; i < length; ++i) {
832
+ Napi::Value rowValue = input.Get(i);
833
+ if (!rowValue.IsObject()) {
834
+ Napi::TypeError::New(env, "each position limit must be an object")
835
+ .ThrowAsJavaScriptException();
836
+ return env.Undefined();
837
+ }
838
+ Napi::Object row = rowValue.As<Napi::Object>();
839
+ Napi::Value instrument = row.Get("instrumentId");
840
+ Napi::Value longValue = row.Get("long");
841
+ Napi::Value shortValue = row.Get("short");
842
+ if (!instrument.IsString() ||
843
+ (!longValue.IsUndefined() && !longValue.IsNumber()) ||
844
+ (!shortValue.IsUndefined() && !shortValue.IsNumber())) {
845
+ Napi::TypeError::New(env, "invalid position-limit entry")
846
+ .ThrowAsJavaScriptException();
847
+ return env.Undefined();
848
+ }
849
+ InstrumentPositionLimitUpdate update;
850
+ update.instrumentId = instrument.As<Napi::String>().Utf8Value();
851
+ update.updateLong = longValue.IsNumber();
852
+ update.updateShort = shortValue.IsNumber();
853
+ if (update.updateLong)
854
+ update.longLimit = longValue.As<Napi::Number>().DoubleValue();
855
+ if (update.updateShort)
856
+ update.shortLimit = shortValue.As<Napi::Number>().DoubleValue();
857
+ updates.push_back(std::move(update));
858
+ }
859
+ if (!risk_.setInstrumentPositionLimits(updates)) {
860
+ Napi::TypeError::New(env, "invalid position-limit batch")
861
+ .ThrowAsJavaScriptException();
862
+ }
863
+ return env.Undefined();
370
864
  }
371
865
 
372
- // (instrumentId, maxCost) - per-instrument open-position cost cap; 0 = off.
373
- Napi::Value Trader::SetMaxInstrumentCost(const Napi::CallbackInfo &info) {
374
- if (info.Length() >= 2 && info[0].IsString() && info[1].IsNumber()) {
375
- risk_.setMaxInstrumentCost(info[0].As<Napi::String>().Utf8Value(),
376
- info[1].As<Napi::Number>().DoubleValue());
866
+ // (Array<{instrumentId, limit}>) - one atomic scheduled-margin-limit batch.
867
+ Napi::Value Trader::SetInstrumentMarginLimits(
868
+ const Napi::CallbackInfo &info) {
869
+ Napi::Env env = info.Env();
870
+ if (info.Length() < 1 || !info[0].IsArray()) {
871
+ Napi::TypeError::New(env, "margin limits must be an array")
872
+ .ThrowAsJavaScriptException();
873
+ return env.Undefined();
377
874
  }
378
- return info.Env().Undefined();
875
+ Napi::Array input = info[0].As<Napi::Array>();
876
+ uint32_t length = 0;
877
+ if (!readInstrumentLimitBatchLength(input, "margin limits", length))
878
+ return env.Undefined();
879
+ std::vector<InstrumentMarginLimitUpdate> updates;
880
+ updates.reserve(length);
881
+ for (uint32_t i = 0; i < length; ++i) {
882
+ Napi::Value rowValue = input.Get(i);
883
+ if (!rowValue.IsObject()) {
884
+ Napi::TypeError::New(env, "each margin limit must be an object")
885
+ .ThrowAsJavaScriptException();
886
+ return env.Undefined();
887
+ }
888
+ Napi::Object row = rowValue.As<Napi::Object>();
889
+ Napi::Value instrument = row.Get("instrumentId");
890
+ Napi::Value limit = row.Get("limit");
891
+ if (!instrument.IsString() || !limit.IsNumber()) {
892
+ Napi::TypeError::New(env, "invalid margin-limit entry")
893
+ .ThrowAsJavaScriptException();
894
+ return env.Undefined();
895
+ }
896
+ updates.push_back(InstrumentMarginLimitUpdate{
897
+ instrument.As<Napi::String>().Utf8Value(),
898
+ limit.As<Napi::Number>().DoubleValue()});
899
+ }
900
+ if (!risk_.setInstrumentMarginLimits(updates)) {
901
+ Napi::TypeError::New(env, "invalid margin-limit batch")
902
+ .ThrowAsJavaScriptException();
903
+ }
904
+ return env.Undefined();
379
905
  }
380
906
 
381
907
  // (Array<{frontId, sessionId, orderRef, instrumentId, isLong, vol, price}>) -
382
908
  // rebuild in-flight reservations from CTP's working orders (reqQryOrder).
383
909
  Napi::Value Trader::RebuildReservations(const Napi::CallbackInfo &info) {
910
+ Napi::Env env = info.Env();
911
+ if (info.Length() < 2 || !info[0].IsArray() || !info[1].IsNumber()) {
912
+ Napi::TypeError::New(env, "rebuildReservations requires rows and revision")
913
+ .ThrowAsJavaScriptException();
914
+ return Napi::Boolean::New(env, false);
915
+ }
384
916
  std::vector<OpenOrderInfo> orders;
385
- if (info.Length() >= 1 && info[0].IsArray()) {
386
- Napi::Array arr = info[0].As<Napi::Array>();
387
- for (uint32_t i = 0; i < arr.Length(); ++i) {
388
- Napi::Value v = arr.Get(i);
389
- if (!v.IsObject())
390
- continue;
391
- Napi::Object o = v.As<Napi::Object>();
392
- OpenOrderInfo r;
393
- r.frontId = o.Get("frontId").ToNumber().Int32Value();
394
- r.sessionId = o.Get("sessionId").ToNumber().Int32Value();
395
- r.orderRef = o.Get("orderRef").ToString().Utf8Value();
396
- r.instrumentId = o.Get("instrumentId").ToString().Utf8Value();
397
- r.isLong = o.Get("isLong").ToBoolean().Value();
398
- r.vol = o.Get("vol").ToNumber().DoubleValue();
399
- r.price = o.Get("price").ToNumber().DoubleValue();
400
- orders.push_back(std::move(r));
917
+ Napi::Array arr = info[0].As<Napi::Array>();
918
+ for (uint32_t i = 0; i < arr.Length(); ++i) {
919
+ Napi::Value v = arr.Get(i);
920
+ if (!v.IsObject()) {
921
+ Napi::TypeError::New(env, "invalid working-order snapshot row")
922
+ .ThrowAsJavaScriptException();
923
+ return Napi::Boolean::New(env, false);
401
924
  }
925
+ Napi::Object o = v.As<Napi::Object>();
926
+ Napi::Value front = o.Get("frontId");
927
+ Napi::Value session = o.Get("sessionId");
928
+ Napi::Value orderRef = o.Get("orderRef");
929
+ Napi::Value instrument = o.Get("instrumentId");
930
+ Napi::Value isLong = o.Get("isLong");
931
+ Napi::Value volume = o.Get("vol");
932
+ Napi::Value price = o.Get("price");
933
+ Napi::Value hedgeValue = o.Get("hedgeFlag");
934
+ Napi::Value tradedValue = o.Get("traded");
935
+ Napi::Value sysValue = o.Get("orderSysKey");
936
+ Napi::Value supportedValue = o.Get("supportedSingleLeg");
937
+ if (!isInt32Number(front) || !isInt32Number(session) ||
938
+ !orderRef.IsString() ||
939
+ !instrument.IsString() || !isLong.IsBoolean() || !volume.IsNumber() ||
940
+ !price.IsNumber() ||
941
+ !hedgeValue.IsString() ||
942
+ (!tradedValue.IsUndefined() && !tradedValue.IsNumber()) ||
943
+ (!sysValue.IsUndefined() && !sysValue.IsString()) ||
944
+ !supportedValue.IsBoolean()) {
945
+ Napi::TypeError::New(env, "invalid working-order snapshot row")
946
+ .ThrowAsJavaScriptException();
947
+ return Napi::Boolean::New(env, false);
948
+ }
949
+ OpenOrderInfo r;
950
+ r.frontId = front.As<Napi::Number>().Int32Value();
951
+ r.sessionId = session.As<Napi::Number>().Int32Value();
952
+ r.orderRef = orderRef.As<Napi::String>().Utf8Value();
953
+ r.instrumentId = instrument.As<Napi::String>().Utf8Value();
954
+ r.isLong = isLong.As<Napi::Boolean>().Value();
955
+ const std::string hedge = hedgeValue.As<Napi::String>().Utf8Value();
956
+ r.hedgeFlag = hedge.empty() ? '\0' : hedge[0];
957
+ r.vol = volume.As<Napi::Number>().DoubleValue();
958
+ r.price = price.As<Napi::Number>().DoubleValue();
959
+ r.traded = tradedValue.IsNumber()
960
+ ? tradedValue.As<Napi::Number>().DoubleValue()
961
+ : 0.0;
962
+ r.orderSysKey = sysValue.IsString()
963
+ ? sysValue.As<Napi::String>().Utf8Value()
964
+ : std::string();
965
+ r.supportedSingleLeg = supportedValue.As<Napi::Boolean>().Value();
966
+ orders.push_back(std::move(r));
967
+ }
968
+ const double revision = info[1].As<Napi::Number>().DoubleValue();
969
+ if (!std::isfinite(revision) || revision < 0.0 ||
970
+ revision > 9007199254740991.0 || std::floor(revision) != revision) {
971
+ Napi::TypeError::New(env, "invalid risk revision")
972
+ .ThrowAsJavaScriptException();
973
+ return Napi::Boolean::New(env, false);
402
974
  }
403
- risk_.rebuildOpenReservations(orders);
975
+ return Napi::Boolean::New(
976
+ env, risk_.rebuildOpenReservationsIfRevision(
977
+ static_cast<uint64_t>(revision), orders));
978
+ }
979
+
980
+ Napi::Value Trader::RiskRevision(const Napi::CallbackInfo &info) {
981
+ return Napi::Number::New(info.Env(), static_cast<double>(risk_.revision()));
982
+ }
983
+
984
+ Napi::Value Trader::MarkPositionLedgerUncertain(
985
+ const Napi::CallbackInfo &info) {
986
+ risk_.markTradeLedgerUncertain();
404
987
  return info.Env().Undefined();
405
988
  }
406
989
 
407
- // (instrumentId, isLong, volume, openCost) - seed a pre-existing position.
408
- Napi::Value Trader::SeedPosition(const Napi::CallbackInfo &info) {
409
- if (info.Length() >= 4) {
410
- risk_.seedPosition(info[0].As<Napi::String>().Utf8Value(),
411
- info[1].ToBoolean().Value(),
412
- info[2].As<Napi::Number>().DoubleValue(),
413
- info[3].As<Napi::Number>().DoubleValue());
414
- }
990
+ Napi::Value Trader::MarkOrderLedgerUncertain(
991
+ const Napi::CallbackInfo &info) {
992
+ risk_.markOrderLedgerUncertain();
415
993
  return info.Env().Undefined();
416
994
  }
417
995
 
418
- Napi::Value Trader::PositionCost(const Napi::CallbackInfo &info) {
419
- return Napi::Number::New(info.Env(), risk_.currentPositionCost());
996
+ Napi::Value Trader::ReplacePositions(const Napi::CallbackInfo &info) {
997
+ Napi::Env env = info.Env();
998
+ if (info.Length() < 2 || !info[0].IsArray() || !info[1].IsNumber()) {
999
+ Napi::TypeError::New(env, "replacePositions requires rows and revision")
1000
+ .ThrowAsJavaScriptException();
1001
+ return Napi::Boolean::New(env, false);
1002
+ }
1003
+ std::vector<PositionSeed> seeds;
1004
+ Napi::Array arr = info[0].As<Napi::Array>();
1005
+ for (uint32_t i = 0; i < arr.Length(); ++i) {
1006
+ Napi::Value v = arr.Get(i);
1007
+ if (!v.IsObject()) {
1008
+ Napi::TypeError::New(env, "invalid position snapshot row")
1009
+ .ThrowAsJavaScriptException();
1010
+ return Napi::Boolean::New(env, false);
1011
+ }
1012
+ Napi::Object o = v.As<Napi::Object>();
1013
+ Napi::Value instrument = o.Get("instrumentId");
1014
+ Napi::Value isLong = o.Get("isLong");
1015
+ Napi::Value hedge = o.Get("hedgeFlag");
1016
+ Napi::Value volume = o.Get("volume");
1017
+ Napi::Value margin = o.Get("margin");
1018
+ if (!instrument.IsString() || !isLong.IsBoolean() || !hedge.IsString() ||
1019
+ !volume.IsNumber() || !margin.IsNumber()) {
1020
+ Napi::TypeError::New(env, "invalid position snapshot row")
1021
+ .ThrowAsJavaScriptException();
1022
+ return Napi::Boolean::New(env, false);
1023
+ }
1024
+ const std::string hedgeFlag = hedge.As<Napi::String>().Utf8Value();
1025
+ if (hedgeFlag.size() != 1) {
1026
+ Napi::TypeError::New(env, "invalid position snapshot hedgeFlag")
1027
+ .ThrowAsJavaScriptException();
1028
+ return Napi::Boolean::New(env, false);
1029
+ }
1030
+ seeds.push_back(PositionSeed{
1031
+ instrument.As<Napi::String>().Utf8Value(),
1032
+ isLong.As<Napi::Boolean>().Value(),
1033
+ volume.As<Napi::Number>().DoubleValue(),
1034
+ margin.As<Napi::Number>().DoubleValue(), hedgeFlag[0]});
1035
+ }
1036
+ const double revision = info[1].As<Napi::Number>().DoubleValue();
1037
+ if (!std::isfinite(revision) || revision < 0.0 ||
1038
+ revision > 9007199254740991.0 || std::floor(revision) != revision) {
1039
+ Napi::TypeError::New(env, "invalid risk revision")
1040
+ .ThrowAsJavaScriptException();
1041
+ return Napi::Boolean::New(env, false);
1042
+ }
1043
+ return Napi::Boolean::New(
1044
+ env, risk_.replacePositionsIfRevision(static_cast<uint64_t>(revision),
1045
+ seeds));
1046
+ }
1047
+
1048
+ Napi::Value Trader::AccountMargin(const Napi::CallbackInfo &info) {
1049
+ return Napi::Number::New(info.Env(), risk_.accountMargin());
420
1050
  }
421
1051
 
422
1052
  Napi::Value Trader::ResetPositions(const Napi::CallbackInfo &info) {
@@ -442,7 +1072,23 @@ Napi::Value Trader::Start(const Napi::CallbackInfo &info) {
442
1072
  Napi::Value Trader::Buffer(const Napi::CallbackInfo &info) {
443
1073
  if (!ch_)
444
1074
  return info.Env().Undefined();
445
- return Napi::ArrayBuffer::New(info.Env(), ch_->data(), ch_->byteLength());
1075
+ if (bufferRef_) {
1076
+ napi_value cached = nullptr;
1077
+ if (napi_get_reference_value(info.Env(), bufferRef_, &cached) == napi_ok &&
1078
+ cached != nullptr)
1079
+ return Napi::Value(info.Env(), cached);
1080
+ Napi::Error::New(info.Env(), "cached event-channel buffer is unavailable")
1081
+ .ThrowAsJavaScriptException();
1082
+ return info.Env().Undefined();
1083
+ }
1084
+ Napi::ArrayBuffer buffer =
1085
+ Napi::ArrayBuffer::New(info.Env(), ch_->data(), ch_->byteLength());
1086
+ if (napi_create_reference(info.Env(), buffer, 1, &bufferRef_) != napi_ok) {
1087
+ Napi::Error::New(info.Env(), "failed to retain event-channel buffer")
1088
+ .ThrowAsJavaScriptException();
1089
+ return info.Env().Undefined();
1090
+ }
1091
+ return buffer;
446
1092
  }
447
1093
 
448
1094
  Napi::Value Trader::ClaimBatch(const Napi::CallbackInfo &info) {
@@ -467,8 +1113,7 @@ Napi::Value Trader::ChannelInfo(const Napi::CallbackInfo &info) {
467
1113
  o.Set("slotSize", static_cast<double>(live ? ch_->slotSize() : 0));
468
1114
  o.Set("numSlots", static_cast<double>(live ? ch_->numSlots() : 0));
469
1115
  o.Set("headerSize", static_cast<double>(live ? ch_->headerSize() : 0));
470
- // Trader keeps DropPolicy::Newest: an order/trade return must never be silently
471
- // dropped in favour of a newer record.
1116
+ // Trader uses Lossless; this flag is only the MarketData JS drain selector.
472
1117
  o.Set("dropOldest", false);
473
1118
  return o;
474
1119
  }