@hitrading/ctp-node 2.0.0 → 3.0.0

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