@hitrading/ctp-node 1.2.0 → 2.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 (57) hide show
  1. package/README.md +10 -4
  2. package/README.zh-CN.md +10 -4
  3. package/binding.gyp +13 -13
  4. package/dist/client.d.ts +4 -0
  5. package/dist/client.d.ts.map +1 -1
  6. package/dist/client.js +7 -0
  7. package/dist/client.js.map +1 -1
  8. package/dist/index.cjs +60 -44
  9. package/dist/market-data.d.ts +10 -0
  10. package/dist/market-data.d.ts.map +1 -1
  11. package/dist/market-data.js +20 -0
  12. package/dist/market-data.js.map +1 -1
  13. package/dist/native-binding.js +1 -1
  14. package/dist/native-binding.js.map +1 -1
  15. package/dist/trader.d.ts +38 -30
  16. package/dist/trader.d.ts.map +1 -1
  17. package/dist/trader.js +39 -45
  18. package/dist/trader.js.map +1 -1
  19. package/package.json +3 -3
  20. package/prebuilds/linux-x64/@hitrading+ctp-node.node +0 -0
  21. package/prebuilds/win32-x64/@hitrading+ctp-node.node +0 -0
  22. package/src/client.ts +8 -0
  23. package/src/generated/traderspi.gen.cc +6 -0
  24. package/src/market-data.ts +23 -0
  25. package/src/native/mdapi.cc +49 -2
  26. package/src/native/mdspi.cc +5 -1
  27. package/src/native/mdspi.h +4 -0
  28. package/src/native/risk.cc +50 -21
  29. package/src/native/risk.h +48 -8
  30. package/src/native/snapshot.h +61 -0
  31. package/src/native/traderapi.cc +11 -61
  32. package/src/native-binding.ts +1 -1
  33. package/src/trader.ts +55 -58
  34. /package/{tradeapi → ctpsdk}/ThostFtdcMdApi.h +0 -0
  35. /package/{tradeapi → ctpsdk}/ThostFtdcTraderApi.h +0 -0
  36. /package/{tradeapi → ctpsdk}/ThostFtdcUserApiDataType.h +0 -0
  37. /package/{tradeapi → ctpsdk}/ThostFtdcUserApiStruct.h +0 -0
  38. /package/{tradeapi → ctpsdk}/error.dtd +0 -0
  39. /package/{tradeapi → ctpsdk}/error.xml +0 -0
  40. /package/{tradeapi → ctpsdk}/linux/thostmduserapi_se.so +0 -0
  41. /package/{tradeapi → ctpsdk}/linux/thosttraderapi_se.so +0 -0
  42. /package/{tradeapi → ctpsdk}/macos/thostmduserapi_se.framework/Versions/A/Headers/ThostFtdcMdApi.h +0 -0
  43. /package/{tradeapi → ctpsdk}/macos/thostmduserapi_se.framework/Versions/A/Headers/ThostFtdcUserApiDataType.h +0 -0
  44. /package/{tradeapi → ctpsdk}/macos/thostmduserapi_se.framework/Versions/A/Headers/ThostFtdcUserApiStruct.h +0 -0
  45. /package/{tradeapi → ctpsdk}/macos/thostmduserapi_se.framework/Versions/A/Resources/Info.plist +0 -0
  46. /package/{tradeapi → ctpsdk}/macos/thostmduserapi_se.framework/Versions/A/_CodeSignature/CodeResources +0 -0
  47. /package/{tradeapi → ctpsdk}/macos/thostmduserapi_se.framework/Versions/A/thostmduserapi_se +0 -0
  48. /package/{tradeapi → ctpsdk}/macos/thosttraderapi_se.framework/Versions/A/Headers/ThostFtdcTraderApi.h +0 -0
  49. /package/{tradeapi → ctpsdk}/macos/thosttraderapi_se.framework/Versions/A/Headers/ThostFtdcUserApiDataType.h +0 -0
  50. /package/{tradeapi → ctpsdk}/macos/thosttraderapi_se.framework/Versions/A/Headers/ThostFtdcUserApiStruct.h +0 -0
  51. /package/{tradeapi → ctpsdk}/macos/thosttraderapi_se.framework/Versions/A/Resources/Info.plist +0 -0
  52. /package/{tradeapi → ctpsdk}/macos/thosttraderapi_se.framework/Versions/A/_CodeSignature/CodeResources +0 -0
  53. /package/{tradeapi → ctpsdk}/macos/thosttraderapi_se.framework/Versions/A/thosttraderapi_se +0 -0
  54. /package/{tradeapi → ctpsdk}/windows/thostmduserapi_se.dll +0 -0
  55. /package/{tradeapi → ctpsdk}/windows/thostmduserapi_se.lib +0 -0
  56. /package/{tradeapi → ctpsdk}/windows/thosttraderapi_se.dll +0 -0
  57. /package/{tradeapi → ctpsdk}/windows/thosttraderapi_se.lib +0 -0
@@ -15,8 +15,8 @@ namespace ctp {
15
15
  // trade) IS finite, so it slips past isfinite alone; 1e300 is far above any real
16
16
  // value and far below DBL_MAX. Centralized so EVERY double entering the math
17
17
  // rejects the sentinel uniformly: a split policy is exactly what let DBL_MAX
18
- // poison setMultiplier/onTrade after setRefPrice was already guarded (rounds
19
- // 11/14). A sentinel/Inf multiplier or fill makes cost Inf and a later
18
+ // poison setMultiplier/onTrade after the reference-price path was already guarded
19
+ // (rounds 11/14). A sentinel/Inf multiplier or fill makes cost Inf and a later
20
20
  // proportional close-release Inf-Inf = NaN, and NaN > cap is false -> the cost
21
21
  // cap is silently voided. Reject at the door instead.
22
22
  static inline bool sanePositive(double x) {
@@ -85,29 +85,37 @@ void RiskEngine::configure(const RiskConfig &cfg) {
85
85
  maxOrderVolume_.store(cfg.maxOrderVolume, std::memory_order_relaxed);
86
86
  maxPriceDeviation_.store(cfg.maxPriceDeviation, std::memory_order_relaxed);
87
87
  maxNotional_.store(cfg.maxNotional, std::memory_order_relaxed);
88
- maxPositionCost_.store(cfg.maxPositionCost, std::memory_order_relaxed);
88
+ // maxMargin is the canonical margin-based global cap; maxPositionCost is the
89
+ // deprecated alias. Prefer maxMargin when set.
90
+ maxPositionCost_.store(cfg.maxMargin > 0.0 ? cfg.maxMargin : cfg.maxPositionCost,
91
+ std::memory_order_relaxed);
89
92
  limiter_.configure(cfg.maxOrdersPerSec, cfg.orderBurst);
90
93
  }
91
94
 
92
95
  void RiskEngine::halt() { halted_.store(true, std::memory_order_relaxed); }
93
96
  void RiskEngine::resume() { halted_.store(false, std::memory_order_relaxed); }
94
97
 
95
- void RiskEngine::setRefPrice(const std::string &instrumentId, double price) {
96
- // Reject the CTP DBL_MAX "unset" sentinel (and non-finite/non-positive) — see
97
- // sanePositive. A sentinel reference would make |price - ref| / ref == 1.0 for
98
- // ANY real limit price, falsely blocking every deviation-checked order on the
99
- // instrument; instead the reference stays unset until a real price arrives and
100
- // the deviation check skips (its refPrice > 0 guard).
101
- if (!sanePositive(price))
102
- return;
98
+ void RiskEngine::setMdSnapshot(std::shared_ptr<const RefPriceSource> source) {
103
99
  std::lock_guard<std::mutex> lk(refMutex_);
104
- refPrices_[instrumentId] = price;
100
+ mdSnap_ = std::move(source);
105
101
  }
106
102
 
107
103
  double RiskEngine::refPrice(const std::string &instrumentId) const {
108
- std::lock_guard<std::mutex> lk(refMutex_);
109
- auto it = refPrices_.find(instrumentId);
110
- return it != refPrices_.end() ? it->second : 0.0;
104
+ // Read the deviation reference from the live MD snapshot (in C++). Copy the
105
+ // shared_ptr under our lock, then query outside it (the cache has its own
106
+ // mutex) — no nested locking, and a concurrent detach can't free it mid-read.
107
+ // A non-finite / DBL_MAX "unset" last price is rejected here (not in the cache)
108
+ // so a sentinel reference can't make |price-ref|/ref == 1.0 and falsely block
109
+ // every order — the deviation check skips on a 0 reference.
110
+ std::shared_ptr<const RefPriceSource> snap;
111
+ {
112
+ std::lock_guard<std::mutex> lk(refMutex_);
113
+ snap = mdSnap_;
114
+ }
115
+ if (!snap)
116
+ return 0.0;
117
+ const double px = snap->last(instrumentId);
118
+ return sanePositive(px) ? px : 0.0;
111
119
  }
112
120
 
113
121
  void RiskEngine::setMultiplier(const std::string &instrumentId, double mult) {
@@ -118,6 +126,16 @@ void RiskEngine::setMultiplier(const std::string &instrumentId, double mult) {
118
126
  multipliers_[instrumentId] = sanePositive(mult) ? mult : 1.0;
119
127
  }
120
128
 
129
+ void RiskEngine::setMarginRate(const std::string &instrumentId, double rate) {
130
+ std::lock_guard<std::mutex> lk(posMutex_);
131
+ // Store only a usable rate (finite, positive, sub-sentinel). A 0/invalid rate
132
+ // (e.g. an all-by-volume contract reporting 0 by-money, or a malformed field)
133
+ // is ignored so the conservative default keeps applying — zeroing the margin
134
+ // would silently void the cap for that instrument.
135
+ if (sanePositive(rate))
136
+ marginRate_[instrumentId] = rate;
137
+ }
138
+
121
139
  void RiskEngine::setMaxPositionVolume(const std::string &instrumentId,
122
140
  bool isLong, double maxVolume) {
123
141
  std::lock_guard<std::mutex> lk(posMutex_);
@@ -130,6 +148,17 @@ double RiskEngine::multiplierLocked(const std::string &instrumentId) const {
130
148
  return it != multipliers_.end() ? it->second : 1.0;
131
149
  }
132
150
 
151
+ double RiskEngine::marginRateLocked(const std::string &instrumentId) const {
152
+ auto it = marginRate_.find(instrumentId);
153
+ return it != marginRate_.end() ? it->second : kDefaultMarginRate;
154
+ }
155
+
156
+ double RiskEngine::costFactorLocked(const std::string &instrumentId) const {
157
+ // The tracked open "cost" is MARGIN, so every cost computation scales the
158
+ // notional factor (multiplier) by the instrument's margin rate.
159
+ return multiplierLocked(instrumentId) * marginRateLocked(instrumentId);
160
+ }
161
+
133
162
  void RiskEngine::seedPosition(const std::string &instrumentId, bool isLong,
134
163
  double volume, double cost) {
135
164
  // Reject non-finite/negative seeds so a bad value can't poison positionCost
@@ -158,11 +187,11 @@ void RiskEngine::onTrade(const std::string &instrumentId, bool isBuy,
158
187
  // Real CTP fills are always positive, finite, and far below the sentinel band;
159
188
  // ignore malformed data rather than let it corrupt the tracked cost (a NaN
160
189
  // would silently void the cost cap, +Inf/DBL_MAX would jam or void it). See
161
- // sanePositive — same uniform sentinel rejection as setRefPrice/setMultiplier.
190
+ // sanePositive — same uniform sentinel rejection as setMultiplier / refPrice.
162
191
  if (!sanePositive(price) || !sanePositive(volume))
163
192
  return;
164
193
  std::lock_guard<std::mutex> lk(posMutex_);
165
- const double cost = price * volume * multiplierLocked(instrumentId);
194
+ const double cost = price * volume * costFactorLocked(instrumentId);
166
195
  // Per-fill backstop: even with sanePositive inputs the PRODUCT could be
167
196
  // non-finite (e.g. 1e299 * 1e299); never let a non-finite single-fill cost in.
168
197
  if (!std::isfinite(cost))
@@ -234,7 +263,7 @@ OpenGate RiskEngine::tryReserveOpen(const std::string &orderRef,
234
263
  double price, double volume) {
235
264
  const double globalCap = maxPositionCost_.load(std::memory_order_relaxed);
236
265
  std::lock_guard<std::mutex> lk(posMutex_);
237
- const double addCost = volume * costPrice(price) * multiplierLocked(instrumentId);
266
+ const double addCost = volume * costPrice(price) * costFactorLocked(instrumentId);
238
267
  const Pos *p = nullptr;
239
268
  auto pit = positions_.find(instrumentId);
240
269
  if (pit != positions_.end())
@@ -318,8 +347,8 @@ void RiskEngine::onOrderUpdate(int frontId, int sessionId,
318
347
  double desiredVol = terminal ? 0.0 : volTotal - volTraded;
319
348
  if (desiredVol < 0.0)
320
349
  desiredVol = 0.0;
321
- const double mult = multiplierLocked(instrumentId);
322
- const double desiredCost = desiredVol * costPrice(limitPrice) * mult;
350
+ const double factor = costFactorLocked(instrumentId);
351
+ const double desiredCost = desiredVol * costPrice(limitPrice) * factor;
323
352
 
324
353
  auto rit = reservations_.find(key);
325
354
  if (rit == reservations_.end()) {
@@ -398,7 +427,7 @@ void RiskEngine::rebuildOpenReservations(const std::vector<OpenOrderInfo> &order
398
427
  // entry to release it - it would over-block opens until the next full resync.
399
428
  if (reservations_.count(key))
400
429
  continue;
401
- const double cost = o.vol * costPrice(o.price) * multiplierLocked(o.instrumentId);
430
+ const double cost = o.vol * costPrice(o.price) * costFactorLocked(o.instrumentId);
402
431
  Pos &pp = positions_[o.instrumentId];
403
432
  if (o.isLong) {
404
433
  pp.longPendVol += o.vol;
package/src/native/risk.h CHANGED
@@ -13,6 +13,7 @@
13
13
 
14
14
  #include <atomic>
15
15
  #include <chrono>
16
+ #include <memory>
16
17
  #include <mutex>
17
18
  #include <string>
18
19
  #include <unordered_map>
@@ -20,6 +21,15 @@
20
21
 
21
22
  namespace ctp {
22
23
 
24
+ // A read-only source of latest reference prices (the MarketData snapshot cache
25
+ // implements it). Lets the risk engine read live prices for the deviation check
26
+ // in C++ — attached via setMdSnapshot — with no dependency on the CTP md struct
27
+ // and no JS round-trip. last() returns 0 for an unknown/absent instrument.
28
+ struct RefPriceSource {
29
+ virtual double last(const std::string &instrumentId) const = 0;
30
+ virtual ~RefPriceSource() = default;
31
+ };
32
+
23
33
  // One working open order, for rebuilding reservations from reqQryOrder.
24
34
  struct OpenOrderInfo {
25
35
  int frontId = 0;
@@ -37,7 +47,10 @@ struct RiskConfig {
37
47
  double maxNotional = 0.0; // price * volume; 0 = disabled
38
48
  double maxOrdersPerSec = 0.0; // token-bucket rate; 0 = disabled
39
49
  double orderBurst = 0.0; // bucket burst; <=0 -> defaults to rate
40
- double maxPositionCost = 0.0; // cap on total open-position cost; 0 = off
50
+ double maxPositionCost = 0.0; // DEPRECATED alias for maxMargin; 0 = off
51
+ double maxMargin = 0.0; // cap on total open-position MARGIN
52
+ // (Σ price*vol*mult*marginRate); 0 = off.
53
+ // Takes precedence over maxPositionCost.
41
54
  };
42
55
 
43
56
  struct RiskVerdict {
@@ -81,15 +94,27 @@ public:
81
94
  // Rate gate (consumes a token). Call right before sending.
82
95
  bool allowRate() { return limiter_.tryAcquire(); }
83
96
 
84
- // Per-instrument reference price for the maxPriceDeviation check. Fed from
85
- // market data (cold-ish path); 0 = unknown -> deviation check skipped.
86
- void setRefPrice(const std::string &instrumentId, double price);
97
+ // Attach a live reference-price source (the MarketData snapshot cache) so the
98
+ // maxPriceDeviation check reads current prices in C++ — straight from the MD
99
+ // feed, no JS round-trip. Pass nullptr to detach. Without one, refPrice()
100
+ // returns 0 and the deviation check is skipped.
101
+ void setMdSnapshot(std::shared_ptr<const RefPriceSource> source);
102
+ // Reference price for the deviation check: the attached MD snapshot's last
103
+ // price, or 0 if none/unknown.
87
104
  double refPrice(const std::string &instrumentId) const;
88
105
 
89
- // Max total open-position cost (sum of open price*volume*multiplier). Updated
90
- // by fills (onTrade) on the trader callback thread; seed pre-existing
91
- // positions with seedPosition. Set the contract multiplier for accuracy.
106
+ // Max total open-position MARGIN (Σ open price*volume*multiplier*marginRate).
107
+ // Updated by fills (onTrade) on the trader callback thread; seed pre-existing
108
+ // positions with seedPosition. Set the contract multiplier AND margin rate for
109
+ // accuracy.
92
110
  void setMultiplier(const std::string &instrumentId, double multiplier);
111
+ // Per-instrument margin rate (fraction of notional, e.g. 0.10 = 10%), fed
112
+ // directly from CTP's OnRspQryInstrumentMarginRate inside C++ (no JS round-
113
+ // trip). Makes the tracked open "cost" real MARGIN, so the global cap
114
+ // (configure().maxMargin) and the per-instrument cost cap are margin limits.
115
+ // Unset/invalid -> a conservative default (kDefaultMarginRate) applies, so the
116
+ // cap over-estimates (stays safe) until the real rate arrives.
117
+ void setMarginRate(const std::string &instrumentId, double rate);
93
118
  void seedPosition(const std::string &instrumentId, bool isLong, double volume, double cost);
94
119
  void onTrade(const std::string &instrumentId, bool isBuy, bool isOpen, double price, double volume);
95
120
  void resetPositions();
@@ -138,8 +163,10 @@ private:
138
163
  std::atomic<double> maxNotional_{0.0};
139
164
  std::atomic<double> maxPositionCost_{0.0};
140
165
  RateLimiter limiter_;
166
+ // Live reference-price source (the MarketData snapshot cache), read by
167
+ // refPrice() for the deviation check. Guarded by refMutex_.
141
168
  mutable std::mutex refMutex_;
142
- std::unordered_map<std::string, double> refPrices_;
169
+ std::shared_ptr<const RefPriceSource> mdSnap_;
143
170
 
144
171
  struct Pos {
145
172
  double longVol = 0, longCost = 0, shortVol = 0, shortCost = 0; // filled
@@ -161,6 +188,14 @@ private:
161
188
  // Contract multipliers are static metadata kept separate from position state
162
189
  // so resetPositions() (which syncPositions calls) does not wipe them.
163
190
  std::unordered_map<std::string, double> multipliers_;
191
+ // Per-instrument margin rates (fraction of notional), same lifetime as
192
+ // multipliers_ (static metadata; survives resetPositions). Unset -> default.
193
+ std::unordered_map<std::string, double> marginRate_;
194
+ // Fallback when an instrument's rate is unset: full notional (1.0). Maximally
195
+ // conservative (margin <= notional always), so an un-fetched contract can only
196
+ // OVER-count its margin — the cap never under-blocks — and the cost cap stays
197
+ // back-compatible (no rate set == the previous notional behavior).
198
+ static constexpr double kDefaultMarginRate = 1.0;
164
199
  // Per-instrument, per-side lot caps (config metadata; like multipliers,
165
200
  // survives resets). 0 on a side = that side is uncapped.
166
201
  struct VolCap {
@@ -171,6 +206,11 @@ private:
171
206
  std::unordered_map<std::string, double> maxInstrumentCost_;
172
207
  // Look up an instrument's multiplier (1.0 if unset). Caller holds posMutex_.
173
208
  double multiplierLocked(const std::string &instrumentId) const;
209
+ // Margin rate (kDefaultMarginRate if unset). Caller holds posMutex_.
210
+ double marginRateLocked(const std::string &instrumentId) const;
211
+ // Factor converting price*volume into tracked MARGIN: multiplier * marginRate.
212
+ // Used for all open-position cost accounting. Caller holds posMutex_.
213
+ double costFactorLocked(const std::string &instrumentId) const;
174
214
  // Whether any position cap applies to this instrument/side. Holds posMutex_.
175
215
  bool hasCapLocked(const std::string &instrumentId, bool isLong) const;
176
216
  // Record + return a check() rejection (stores the reason for lastBlockReason).
@@ -0,0 +1,61 @@
1
+ /*
2
+ * snapshot.h - last-value cache (LVC): the latest full depth tick per instrument.
3
+ *
4
+ * Written on the CTP MD callback thread (update), read on the JS thread
5
+ * (get/last) and the Trader's order thread (last, via RefPriceSource, for the
6
+ * deviation reference). One mutex; entries are full DepthMarketDataField copies.
7
+ * Cleared on unsubscribe (erase) and close (clear). This is the in-C++ market-
8
+ * data cache, so latest prices reach the risk engine without round-tripping
9
+ * through JS, and JS can read a synchronous snapshot without waiting for a tick.
10
+ */
11
+ #ifndef CTP_NATIVE_SNAPSHOT_H
12
+ #define CTP_NATIVE_SNAPSHOT_H
13
+
14
+ #include "ThostFtdcUserApiStruct.h"
15
+ #include "risk.h" // RefPriceSource
16
+ #include <mutex>
17
+ #include <string>
18
+ #include <unordered_map>
19
+
20
+ namespace ctp {
21
+
22
+ class SnapshotCache : public RefPriceSource {
23
+ public:
24
+ // MD callback thread: copy the whole latest tick in, keyed by instrument id.
25
+ void update(const CThostFtdcDepthMarketDataField &t) {
26
+ std::lock_guard<std::mutex> lk(m_);
27
+ map_[t.InstrumentID] = t;
28
+ }
29
+ // Reader (JS thread): copy the latest tick out. False if none cached.
30
+ bool get(const std::string &id, CThostFtdcDepthMarketDataField &out) const {
31
+ std::lock_guard<std::mutex> lk(m_);
32
+ auto it = map_.find(id);
33
+ if (it == map_.end())
34
+ return false;
35
+ out = it->second;
36
+ return true;
37
+ }
38
+ // RefPriceSource: latest price, or 0 if absent. Validity (the DBL_MAX "unset"
39
+ // sentinel etc.) is filtered by the risk engine's refPrice(), not here.
40
+ double last(const std::string &id) const override {
41
+ std::lock_guard<std::mutex> lk(m_);
42
+ auto it = map_.find(id);
43
+ return it != map_.end() ? it->second.LastPrice : 0.0;
44
+ }
45
+ void erase(const std::string &id) { // unsubscribe
46
+ std::lock_guard<std::mutex> lk(m_);
47
+ map_.erase(id);
48
+ }
49
+ void clear() { // close
50
+ std::lock_guard<std::mutex> lk(m_);
51
+ map_.clear();
52
+ }
53
+
54
+ private:
55
+ mutable std::mutex m_;
56
+ std::unordered_map<std::string, CThostFtdcDepthMarketDataField> map_;
57
+ };
58
+
59
+ } // namespace ctp
60
+
61
+ #endif /* CTP_NATIVE_SNAPSHOT_H */
@@ -26,6 +26,7 @@
26
26
  #include "arm.h"
27
27
  #include "channel.h"
28
28
  #include "risk.h"
29
+ #include "snapshot.h"
29
30
 
30
31
  namespace ctp {
31
32
 
@@ -81,17 +82,13 @@ private:
81
82
  Napi::Value RiskHalt(const Napi::CallbackInfo &info);
82
83
  Napi::Value RiskResume(const Napi::CallbackInfo &info);
83
84
  Napi::Value LastRiskReason(const Napi::CallbackInfo &info);
84
- Napi::Value SetRefPrice(const Napi::CallbackInfo &info);
85
- Napi::Value SetMultiplier(const Napi::CallbackInfo &info);
85
+ Napi::Value AttachSnapshot(const Napi::CallbackInfo &info);
86
86
  Napi::Value SetMaxPositionVolume(const Napi::CallbackInfo &info);
87
87
  Napi::Value SetMaxInstrumentCost(const Napi::CallbackInfo &info);
88
- Napi::Value SetSession(const Napi::CallbackInfo &info);
89
88
  Napi::Value RebuildReservations(const Napi::CallbackInfo &info);
90
89
  Napi::Value SeedPosition(const Napi::CallbackInfo &info);
91
90
  Napi::Value PositionCost(const Napi::CallbackInfo &info);
92
91
  Napi::Value ResetPositions(const Napi::CallbackInfo &info);
93
- Napi::Value ApplyTestTrade(const Napi::CallbackInfo &info);
94
- Napi::Value ApplyTestOrder(const Napi::CallbackInfo &info);
95
92
  Napi::Value Start(const Napi::CallbackInfo &info);
96
93
  Napi::Value Buffer(const Napi::CallbackInfo &info);
97
94
  Napi::Value ClaimBatch(const Napi::CallbackInfo &info);
@@ -126,17 +123,13 @@ Napi::Function Trader::Init(Napi::Env env) {
126
123
  InstanceMethod("riskHalt", &Trader::RiskHalt),
127
124
  InstanceMethod("riskResume", &Trader::RiskResume),
128
125
  InstanceMethod("lastRiskReason", &Trader::LastRiskReason),
129
- InstanceMethod("setRefPrice", &Trader::SetRefPrice),
130
- InstanceMethod("setMultiplier", &Trader::SetMultiplier),
126
+ InstanceMethod("_attachSnapshot", &Trader::AttachSnapshot),
131
127
  InstanceMethod("setMaxPositionVolume", &Trader::SetMaxPositionVolume),
132
128
  InstanceMethod("setMaxInstrumentCost", &Trader::SetMaxInstrumentCost),
133
- InstanceMethod("setSession", &Trader::SetSession),
134
129
  InstanceMethod("rebuildReservations", &Trader::RebuildReservations),
135
130
  InstanceMethod("seedPosition", &Trader::SeedPosition),
136
131
  InstanceMethod("positionCost", &Trader::PositionCost),
137
132
  InstanceMethod("resetPositions", &Trader::ResetPositions),
138
- InstanceMethod("_applyTestTrade", &Trader::ApplyTestTrade),
139
- InstanceMethod("_applyTestOrder", &Trader::ApplyTestOrder),
140
133
  InstanceMethod("_start", &Trader::Start),
141
134
  InstanceMethod("_buffer", &Trader::Buffer),
142
135
  InstanceMethod("_claim", &Trader::ClaimBatch),
@@ -334,6 +327,7 @@ Napi::Value Trader::RiskSet(const Napi::CallbackInfo &info) {
334
327
  cfg.maxOrdersPerSec = getDbl(o, "maxOrdersPerSec", 0.0);
335
328
  cfg.orderBurst = getDbl(o, "orderBurst", 0.0);
336
329
  cfg.maxPositionCost = getDbl(o, "maxPositionCost", 0.0);
330
+ cfg.maxMargin = getDbl(o, "maxMargin", 0.0);
337
331
  risk_.configure(cfg);
338
332
  }
339
333
  return info.Env().Undefined();
@@ -355,19 +349,13 @@ Napi::Value Trader::LastRiskReason(const Napi::CallbackInfo &info) {
355
349
  return Napi::String::New(info.Env(), r ? r : "");
356
350
  }
357
351
 
358
- Napi::Value Trader::SetRefPrice(const Napi::CallbackInfo &info) {
359
- if (info.Length() >= 2 && info[0].IsString() && info[1].IsNumber()) {
360
- risk_.setRefPrice(info[0].As<Napi::String>().Utf8Value(),
361
- info[1].As<Napi::Number>().DoubleValue());
362
- }
363
- return info.Env().Undefined();
364
- }
365
-
366
- Napi::Value Trader::SetMultiplier(const Napi::CallbackInfo &info) {
367
- if (info.Length() >= 2 && info[0].IsString() && info[1].IsNumber()) {
368
- risk_.setMultiplier(info[0].As<Napi::String>().Utf8Value(),
369
- info[1].As<Napi::Number>().DoubleValue());
370
- }
352
+ // (mdSnapshotExternal) - attach a MarketData's snapshot cache so the deviation
353
+ // check reads live prices in C++ (no JS round-trip). See Trader.trackMarketData.
354
+ 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)
371
359
  return info.Env().Undefined();
372
360
  }
373
361
 
@@ -390,15 +378,6 @@ Napi::Value Trader::SetMaxInstrumentCost(const Napi::CallbackInfo &info) {
390
378
  return info.Env().Undefined();
391
379
  }
392
380
 
393
- // (frontId, sessionId) - our login session, for reservation keys.
394
- Napi::Value Trader::SetSession(const Napi::CallbackInfo &info) {
395
- if (info.Length() >= 2 && info[0].IsNumber() && info[1].IsNumber()) {
396
- risk_.setSession(info[0].As<Napi::Number>().Int32Value(),
397
- info[1].As<Napi::Number>().Int32Value());
398
- }
399
- return info.Env().Undefined();
400
- }
401
-
402
381
  // (Array<{frontId, sessionId, orderRef, instrumentId, isLong, vol, price}>) -
403
382
  // rebuild in-flight reservations from CTP's working orders (reqQryOrder).
404
383
  Napi::Value Trader::RebuildReservations(const Napi::CallbackInfo &info) {
@@ -445,35 +424,6 @@ Napi::Value Trader::ResetPositions(const Napi::CallbackInfo &info) {
445
424
  return info.Env().Undefined();
446
425
  }
447
426
 
448
- // test-only: (instrumentId, isBuy, isOpen, price, volume)
449
- Napi::Value Trader::ApplyTestTrade(const Napi::CallbackInfo &info) {
450
- if (info.Length() >= 5) {
451
- risk_.onTrade(info[0].As<Napi::String>().Utf8Value(),
452
- info[1].ToBoolean().Value(), info[2].ToBoolean().Value(),
453
- info[3].As<Napi::Number>().DoubleValue(),
454
- info[4].As<Napi::Number>().DoubleValue());
455
- }
456
- return info.Env().Undefined();
457
- }
458
-
459
- // (frontId, sessionId, orderRef, instrumentId, isOpen, isLong, status,
460
- // limitPrice, volTotal, volTraded) - drive the reservation tracker (OnRtnOrder).
461
- Napi::Value Trader::ApplyTestOrder(const Napi::CallbackInfo &info) {
462
- if (info.Length() >= 10) {
463
- std::string status = info[6].As<Napi::String>().Utf8Value();
464
- risk_.onOrderUpdate(info[0].As<Napi::Number>().Int32Value(),
465
- info[1].As<Napi::Number>().Int32Value(),
466
- info[2].As<Napi::String>().Utf8Value(),
467
- info[3].As<Napi::String>().Utf8Value(),
468
- info[4].ToBoolean().Value(), info[5].ToBoolean().Value(),
469
- status.empty() ? ' ' : status[0],
470
- info[7].As<Napi::Number>().DoubleValue(),
471
- info[8].As<Napi::Number>().DoubleValue(),
472
- info[9].As<Napi::Number>().DoubleValue());
473
- }
474
- return info.Env().Undefined();
475
- }
476
-
477
427
  Napi::Value Trader::Start(const Napi::CallbackInfo &info) {
478
428
  Napi::Env env = info.Env();
479
429
  if (started_ || !api_)
@@ -15,7 +15,7 @@ const pkgRoot = join(dirname(fileURLToPath(import.meta.url)), "..");
15
15
  // so it is found regardless of where the .node lives (build/ or prebuilds/).
16
16
  // Linux/macOS resolve their .so/.framework via the rpath baked at build time.
17
17
  if (process.platform === "win32") {
18
- process.env.PATH = `${join(pkgRoot, "tradeapi", "windows")};${process.env.PATH ?? ""}`;
18
+ process.env.PATH = `${join(pkgRoot, "ctpsdk", "windows")};${process.env.PATH ?? ""}`;
19
19
  }
20
20
 
21
21
  // eslint-disable-next-line @typescript-eslint/no-explicit-any