@hitrading/ctp-node 1.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 (102) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +208 -0
  3. package/README.zh-CN.md +185 -0
  4. package/binding.gyp +90 -0
  5. package/dist/client.d.ts +115 -0
  6. package/dist/client.d.ts.map +1 -0
  7. package/dist/client.js +466 -0
  8. package/dist/client.js.map +1 -0
  9. package/dist/codec.d.ts +29 -0
  10. package/dist/codec.d.ts.map +1 -0
  11. package/dist/codec.js +131 -0
  12. package/dist/codec.js.map +1 -0
  13. package/dist/generated/enums.gen.d.ts +2257 -0
  14. package/dist/generated/enums.gen.d.ts.map +1 -0
  15. package/dist/generated/enums.gen.js +2576 -0
  16. package/dist/generated/enums.gen.js.map +1 -0
  17. package/dist/generated/structs.gen.d.ts +11041 -0
  18. package/dist/generated/structs.gen.d.ts.map +1 -0
  19. package/dist/generated/structs.gen.js +939 -0
  20. package/dist/generated/structs.gen.js.map +1 -0
  21. package/dist/generated/trader.gen.d.ts +273 -0
  22. package/dist/generated/trader.gen.d.ts.map +1 -0
  23. package/dist/generated/trader.gen.js +653 -0
  24. package/dist/generated/trader.gen.js.map +1 -0
  25. package/dist/index.d.ts +9 -0
  26. package/dist/index.d.ts.map +1 -0
  27. package/dist/index.js +9 -0
  28. package/dist/index.js.map +1 -0
  29. package/dist/market-data.d.ts +66 -0
  30. package/dist/market-data.d.ts.map +1 -0
  31. package/dist/market-data.js +105 -0
  32. package/dist/market-data.js.map +1 -0
  33. package/dist/native-binding.d.ts +2 -0
  34. package/dist/native-binding.d.ts.map +1 -0
  35. package/dist/native-binding.js +22 -0
  36. package/dist/native-binding.js.map +1 -0
  37. package/dist/trader.d.ts +234 -0
  38. package/dist/trader.d.ts.map +1 -0
  39. package/dist/trader.js +388 -0
  40. package/dist/trader.js.map +1 -0
  41. package/package.json +69 -0
  42. package/prebuilds/linux-x64/@hitrading+ctp-node.node +0 -0
  43. package/prebuilds/linux-x64/thostmduserapi_se.so +0 -0
  44. package/prebuilds/linux-x64/thosttraderapi_se.so +0 -0
  45. package/prebuilds/win32-x64/@hitrading+ctp-node.node +0 -0
  46. package/prebuilds/win32-x64/thostmduserapi_se.dll +0 -0
  47. package/prebuilds/win32-x64/thosttraderapi_se.dll +0 -0
  48. package/src/addon.cc +171 -0
  49. package/src/client.ts +539 -0
  50. package/src/codec.ts +160 -0
  51. package/src/generated/enums.gen.ts +2576 -0
  52. package/src/generated/layout.gen.cc +5771 -0
  53. package/src/generated/layout.gen.h +8 -0
  54. package/src/generated/structids.gen.h +470 -0
  55. package/src/generated/structs.gen.ts +12437 -0
  56. package/src/generated/trader.gen.ts +656 -0
  57. package/src/generated/traderreq.gen.cc +706 -0
  58. package/src/generated/traderreq.gen.h +127 -0
  59. package/src/generated/traderspi.gen.cc +636 -0
  60. package/src/generated/traderspi.gen.h +334 -0
  61. package/src/index.ts +14 -0
  62. package/src/market-data.ts +145 -0
  63. package/src/native/arm.cc +77 -0
  64. package/src/native/arm.h +71 -0
  65. package/src/native/channel.cc +175 -0
  66. package/src/native/channel.h +117 -0
  67. package/src/native/gbk.cc +54 -0
  68. package/src/native/gbk.h +17 -0
  69. package/src/native/mdapi.cc +412 -0
  70. package/src/native/mdapi.h +14 -0
  71. package/src/native/mdspi.cc +103 -0
  72. package/src/native/mdspi.h +81 -0
  73. package/src/native/risk.cc +461 -0
  74. package/src/native/risk.h +183 -0
  75. package/src/native/traderapi.cc +533 -0
  76. package/src/native/traderapi.h +14 -0
  77. package/src/native-binding.ts +25 -0
  78. package/src/trader.ts +522 -0
  79. package/tradeapi/ThostFtdcMdApi.h +168 -0
  80. package/tradeapi/ThostFtdcTraderApi.h +914 -0
  81. package/tradeapi/ThostFtdcUserApiDataType.h +7068 -0
  82. package/tradeapi/ThostFtdcUserApiStruct.h +12386 -0
  83. package/tradeapi/error.dtd +9 -0
  84. package/tradeapi/error.xml +284 -0
  85. package/tradeapi/linux/thostmduserapi_se.so +0 -0
  86. package/tradeapi/linux/thosttraderapi_se.so +0 -0
  87. package/tradeapi/macos/thostmduserapi_se.framework/Versions/A/Headers/ThostFtdcMdApi.h +168 -0
  88. package/tradeapi/macos/thostmduserapi_se.framework/Versions/A/Headers/ThostFtdcUserApiDataType.h +7068 -0
  89. package/tradeapi/macos/thostmduserapi_se.framework/Versions/A/Headers/ThostFtdcUserApiStruct.h +12386 -0
  90. package/tradeapi/macos/thostmduserapi_se.framework/Versions/A/Resources/Info.plist +46 -0
  91. package/tradeapi/macos/thostmduserapi_se.framework/Versions/A/_CodeSignature/CodeResources +149 -0
  92. package/tradeapi/macos/thostmduserapi_se.framework/Versions/A/thostmduserapi_se +0 -0
  93. package/tradeapi/macos/thosttraderapi_se.framework/Versions/A/Headers/ThostFtdcTraderApi.h +914 -0
  94. package/tradeapi/macos/thosttraderapi_se.framework/Versions/A/Headers/ThostFtdcUserApiDataType.h +7068 -0
  95. package/tradeapi/macos/thosttraderapi_se.framework/Versions/A/Headers/ThostFtdcUserApiStruct.h +12386 -0
  96. package/tradeapi/macos/thosttraderapi_se.framework/Versions/A/Resources/Info.plist +46 -0
  97. package/tradeapi/macos/thosttraderapi_se.framework/Versions/A/_CodeSignature/CodeResources +149 -0
  98. package/tradeapi/macos/thosttraderapi_se.framework/Versions/A/thosttraderapi_se +0 -0
  99. package/tradeapi/windows/thostmduserapi_se.dll +0 -0
  100. package/tradeapi/windows/thostmduserapi_se.lib +0 -0
  101. package/tradeapi/windows/thosttraderapi_se.dll +0 -0
  102. package/tradeapi/windows/thosttraderapi_se.lib +0 -0
@@ -0,0 +1,461 @@
1
+ /*
2
+ * risk.cc - see risk.h
3
+ */
4
+
5
+ #include "risk.h"
6
+ #include <algorithm>
7
+ #include <cmath>
8
+ #include <limits>
9
+
10
+ namespace ctp {
11
+
12
+ // A price / multiplier / fill quantity is usable in the cost & notional math only
13
+ // if it is finite, strictly positive, and below the CTP "unset" sentinel band.
14
+ // DBL_MAX (~1.8e308, what CTP puts in untouched price fields before the first
15
+ // trade) IS finite, so it slips past isfinite alone; 1e300 is far above any real
16
+ // value and far below DBL_MAX. Centralized so EVERY double entering the math
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
20
+ // proportional close-release Inf-Inf = NaN, and NaN > cap is false -> the cost
21
+ // cap is silently voided. Reject at the door instead.
22
+ static inline bool sanePositive(double x) {
23
+ return std::isfinite(x) && x > 0.0 && x < 1e300;
24
+ }
25
+
26
+ // Keep an accumulated open-cost running sum finite. Each fill's cost passes the
27
+ // per-fill backstop, but a long chain of huge (test-hook / absurd-seed) fills can
28
+ // still overflow the SUM to +Inf, and a later proportional close (Inf - Inf)
29
+ // would yield NaN, silently voiding the cost cap (NaN > cap is false). Pin an
30
+ // overflowed sum to the largest finite double: it stays above EVERY finite
31
+ // configured cap (so it keeps blocking - +Inf would block too but breaks the
32
+ // proportional close) while keeping that close arithmetic finite. Unreachable
33
+ // from the live feed (real fills are tiny); defense-in-depth matching sanePositive.
34
+ static inline void clampFiniteCost(double &cost) {
35
+ if (!std::isfinite(cost))
36
+ cost = std::numeric_limits<double>::max();
37
+ }
38
+
39
+ // Price for RESERVATION cost math. The held-cost path (onTrade) guards its price
40
+ // via sanePositive, but the in-flight RESERVATION cost (tryReserveOpen /
41
+ // onOrderUpdate / rebuildOpenReservations) is fed limit prices straight from the
42
+ // order / CTP. A non-finite or DBL_MAX-sentinel price would reserve an Inf cost,
43
+ // and when that order goes terminal the reconcile (Inf - Inf) yields NaN, which
44
+ // silently voids EVERY cost cap book-wide (NaN > cap is false). Treat a
45
+ // non-usable price as 0 cost: the order's volume is still capped, the cost
46
+ // reservation is simply skipped, and no Inf/NaN can enter the ledger. A market
47
+ // order's legitimate 0 price already maps to 0 here, unchanged.
48
+ static inline double costPrice(double price) {
49
+ return sanePositive(price) ? price : 0.0;
50
+ }
51
+
52
+ void RateLimiter::configure(double ratePerSec, double burst) {
53
+ std::lock_guard<std::mutex> lk(m_);
54
+ rate_ = ratePerSec > 0.0 ? ratePerSec : 0.0;
55
+ burst_ = burst > 0.0 ? burst : rate_; // default burst = 1s worth of tokens
56
+ tokens_ = burst_;
57
+ last_ = std::chrono::steady_clock::now();
58
+ initialized_ = true;
59
+ }
60
+
61
+ bool RateLimiter::tryAcquire() {
62
+ std::lock_guard<std::mutex> lk(m_);
63
+ if (rate_ <= 0.0)
64
+ return true; // disabled
65
+
66
+ const auto now = std::chrono::steady_clock::now();
67
+ if (!initialized_) {
68
+ last_ = now;
69
+ tokens_ = burst_;
70
+ initialized_ = true;
71
+ }
72
+
73
+ const double elapsed = std::chrono::duration<double>(now - last_).count();
74
+ last_ = now;
75
+ tokens_ = std::min(burst_, tokens_ + elapsed * rate_);
76
+
77
+ if (tokens_ >= 1.0) {
78
+ tokens_ -= 1.0;
79
+ return true;
80
+ }
81
+ return false;
82
+ }
83
+
84
+ void RiskEngine::configure(const RiskConfig &cfg) {
85
+ maxOrderVolume_.store(cfg.maxOrderVolume, std::memory_order_relaxed);
86
+ maxPriceDeviation_.store(cfg.maxPriceDeviation, std::memory_order_relaxed);
87
+ maxNotional_.store(cfg.maxNotional, std::memory_order_relaxed);
88
+ maxPositionCost_.store(cfg.maxPositionCost, std::memory_order_relaxed);
89
+ limiter_.configure(cfg.maxOrdersPerSec, cfg.orderBurst);
90
+ }
91
+
92
+ void RiskEngine::halt() { halted_.store(true, std::memory_order_relaxed); }
93
+ void RiskEngine::resume() { halted_.store(false, std::memory_order_relaxed); }
94
+
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;
103
+ std::lock_guard<std::mutex> lk(refMutex_);
104
+ refPrices_[instrumentId] = price;
105
+ }
106
+
107
+ 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;
111
+ }
112
+
113
+ void RiskEngine::setMultiplier(const std::string &instrumentId, double mult) {
114
+ std::lock_guard<std::mutex> lk(posMutex_);
115
+ // A usable (finite, positive, sub-sentinel) multiplier is taken as-is; anything
116
+ // else (<=0, NaN, +Inf, or a DBL_MAX-class value) falls back to 1.0 — see
117
+ // sanePositive for why the sentinel band matters.
118
+ multipliers_[instrumentId] = sanePositive(mult) ? mult : 1.0;
119
+ }
120
+
121
+ void RiskEngine::setMaxPositionVolume(const std::string &instrumentId,
122
+ bool isLong, double maxVolume) {
123
+ std::lock_guard<std::mutex> lk(posMutex_);
124
+ VolCap &c = maxPositionVol_[instrumentId];
125
+ (isLong ? c.longMax : c.shortMax) = maxVolume > 0.0 ? maxVolume : 0.0; // 0=off
126
+ }
127
+
128
+ double RiskEngine::multiplierLocked(const std::string &instrumentId) const {
129
+ auto it = multipliers_.find(instrumentId);
130
+ return it != multipliers_.end() ? it->second : 1.0;
131
+ }
132
+
133
+ void RiskEngine::seedPosition(const std::string &instrumentId, bool isLong,
134
+ double volume, double cost) {
135
+ // Reject non-finite/negative seeds so a bad value can't poison positionCost
136
+ // (a NaN would silently disable the cost cap, since NaN > cap is false).
137
+ if (!std::isfinite(volume) || !std::isfinite(cost) || volume < 0.0 || cost < 0.0)
138
+ return;
139
+ std::lock_guard<std::mutex> lk(posMutex_);
140
+ Pos &p = positions_[instrumentId];
141
+ if (isLong) {
142
+ p.longVol = volume;
143
+ p.longCost = cost;
144
+ } else {
145
+ p.shortVol = volume;
146
+ p.shortCost = cost;
147
+ }
148
+ }
149
+
150
+ void RiskEngine::resetPositions() {
151
+ std::lock_guard<std::mutex> lk(posMutex_);
152
+ positions_.clear(); // clears held AND in-flight pending (both live in Pos)
153
+ reservations_.clear();
154
+ }
155
+
156
+ void RiskEngine::onTrade(const std::string &instrumentId, bool isBuy,
157
+ bool isOpen, double price, double volume) {
158
+ // Real CTP fills are always positive, finite, and far below the sentinel band;
159
+ // ignore malformed data rather than let it corrupt the tracked cost (a NaN
160
+ // would silently void the cost cap, +Inf/DBL_MAX would jam or void it). See
161
+ // sanePositive — same uniform sentinel rejection as setRefPrice/setMultiplier.
162
+ if (!sanePositive(price) || !sanePositive(volume))
163
+ return;
164
+ std::lock_guard<std::mutex> lk(posMutex_);
165
+ const double cost = price * volume * multiplierLocked(instrumentId);
166
+ // Per-fill backstop: even with sanePositive inputs the PRODUCT could be
167
+ // non-finite (e.g. 1e299 * 1e299); never let a non-finite single-fill cost in.
168
+ if (!std::isfinite(cost))
169
+ return;
170
+ Pos &p = positions_[instrumentId];
171
+ if (isOpen) {
172
+ if (isBuy) {
173
+ p.longVol += volume;
174
+ p.longCost += cost;
175
+ clampFiniteCost(p.longCost);
176
+ } else {
177
+ p.shortVol += volume;
178
+ p.shortCost += cost;
179
+ clampFiniteCost(p.shortCost);
180
+ }
181
+ } else if (isBuy) { // closing a short: release its open cost proportionally
182
+ const double v = std::min(volume, p.shortVol);
183
+ const double rel = p.shortVol > 0.0 ? p.shortCost * (v / p.shortVol) : 0.0;
184
+ p.shortCost -= rel;
185
+ p.shortVol -= v;
186
+ } else { // closing a long
187
+ const double v = std::min(volume, p.longVol);
188
+ const double rel = p.longVol > 0.0 ? p.longCost * (v / p.longVol) : 0.0;
189
+ p.longCost -= rel;
190
+ p.longVol -= v;
191
+ }
192
+ }
193
+
194
+ double RiskEngine::currentPositionCost() const {
195
+ std::lock_guard<std::mutex> lk(posMutex_);
196
+ double total = 0.0;
197
+ for (const auto &kv : positions_)
198
+ total += kv.second.longCost + kv.second.shortCost;
199
+ return total;
200
+ }
201
+
202
+ void RiskEngine::setMaxInstrumentCost(const std::string &instrumentId,
203
+ double maxCost) {
204
+ std::lock_guard<std::mutex> lk(posMutex_);
205
+ maxInstrumentCost_[instrumentId] = maxCost > 0.0 ? maxCost : 0.0; // 0 = off
206
+ }
207
+
208
+ bool RiskEngine::hasCapLocked(const std::string &instrumentId, bool isLong) const {
209
+ if (maxPositionCost_.load(std::memory_order_relaxed) > 0.0)
210
+ return true;
211
+ auto cit = maxInstrumentCost_.find(instrumentId);
212
+ if (cit != maxInstrumentCost_.end() && cit->second > 0.0)
213
+ return true;
214
+ auto vit = maxPositionVol_.find(instrumentId);
215
+ if (vit != maxPositionVol_.end() &&
216
+ (isLong ? vit->second.longMax : vit->second.shortMax) > 0.0)
217
+ return true;
218
+ return false;
219
+ }
220
+
221
+ void RiskEngine::setSession(int frontId, int sessionId) {
222
+ std::lock_guard<std::mutex> lk(posMutex_);
223
+ myFrontId_ = frontId;
224
+ mySessionId_ = sessionId;
225
+ }
226
+
227
+ std::string RiskEngine::resvKey(int frontId, int sessionId,
228
+ const std::string &orderRef) {
229
+ return std::to_string(frontId) + ":" + std::to_string(sessionId) + ":" + orderRef;
230
+ }
231
+
232
+ OpenGate RiskEngine::tryReserveOpen(const std::string &orderRef,
233
+ const std::string &instrumentId, bool isLong,
234
+ double price, double volume) {
235
+ const double globalCap = maxPositionCost_.load(std::memory_order_relaxed);
236
+ std::lock_guard<std::mutex> lk(posMutex_);
237
+ const double addCost = volume * costPrice(price) * multiplierLocked(instrumentId);
238
+ const Pos *p = nullptr;
239
+ auto pit = positions_.find(instrumentId);
240
+ if (pit != positions_.end())
241
+ p = &pit->second;
242
+ bool capped = false;
243
+
244
+ // 1) per-side volume cap (committed = held + reserved on this side)
245
+ auto vit = maxPositionVol_.find(instrumentId);
246
+ if (vit != maxPositionVol_.end()) {
247
+ const double cap = isLong ? vit->second.longMax : vit->second.shortMax;
248
+ if (cap > 0.0) {
249
+ capped = true;
250
+ double committed = 0.0;
251
+ if (p)
252
+ committed = isLong ? p->longVol + p->longPendVol
253
+ : p->shortVol + p->shortPendVol;
254
+ if (committed + volume > cap)
255
+ return OpenGate::VolumeLimit;
256
+ }
257
+ }
258
+
259
+ // 2) per-instrument cost cap (both sides, held + reserved)
260
+ auto cit = maxInstrumentCost_.find(instrumentId);
261
+ if (cit != maxInstrumentCost_.end() && cit->second > 0.0) {
262
+ capped = true;
263
+ double instrCost = 0.0;
264
+ if (p)
265
+ instrCost = p->longCost + p->longPendCost + p->shortCost + p->shortPendCost;
266
+ if (instrCost + addCost > cit->second)
267
+ return OpenGate::CostLimit;
268
+ }
269
+
270
+ // 3) global cost cap (whole book, held + reserved)
271
+ if (globalCap > 0.0) {
272
+ capped = true;
273
+ double total = 0.0;
274
+ for (const auto &kv : positions_)
275
+ total += kv.second.longCost + kv.second.longPendCost +
276
+ kv.second.shortCost + kv.second.shortPendCost;
277
+ if (total + addCost > globalCap)
278
+ return OpenGate::CostLimit;
279
+ }
280
+
281
+ // Passed every active cap -> reserve (only if a cap is in force; otherwise
282
+ // there is nothing to enforce and tracking would just be overhead).
283
+ if (capped) {
284
+ Pos &pp = positions_[instrumentId];
285
+ if (isLong) {
286
+ pp.longPendVol += volume;
287
+ pp.longPendCost += addCost;
288
+ } else {
289
+ pp.shortPendVol += volume;
290
+ pp.shortPendCost += addCost;
291
+ }
292
+ reservations_[resvKey(myFrontId_, mySessionId_, orderRef)] =
293
+ Reservation{instrumentId, isLong, volume, addCost};
294
+ }
295
+ return OpenGate::Ok;
296
+ }
297
+
298
+ void RiskEngine::onOrderUpdate(int frontId, int sessionId,
299
+ const std::string &orderRef,
300
+ const std::string &instrumentId, bool isOpen,
301
+ bool isLong, char status, double limitPrice,
302
+ double volTotal, double volTraded) {
303
+ if (!isOpen)
304
+ return; // only opening orders reserve
305
+ std::lock_guard<std::mutex> lk(posMutex_);
306
+ const std::string key = resvKey(frontId, sessionId, orderRef);
307
+ // The order still holds live working volume UNLESS it has reached a terminal
308
+ // state. Release only on a definitively-done status: AllTraded '0',
309
+ // PartTradedNotQueueing '2', NoTradeNotQueueing '4', Canceled '5'. Everything
310
+ // else — queueing ('1'/'3') and the transient pre-trade states a conditional
311
+ // order can report before '3' (Unknown 'a', NotTouched 'b', Touched 'c'), plus
312
+ // any status CTP might add later — keeps the reservation. Releasing on a
313
+ // transient status that merely precedes '3' would briefly drop the cap for
314
+ // this order's volume (a burst could then slip past). Conservative by design:
315
+ // hold the reservation until the order is provably finished.
316
+ const bool terminal =
317
+ (status == '0' || status == '2' || status == '4' || status == '5');
318
+ double desiredVol = terminal ? 0.0 : volTotal - volTraded;
319
+ if (desiredVol < 0.0)
320
+ desiredVol = 0.0;
321
+ const double mult = multiplierLocked(instrumentId);
322
+ const double desiredCost = desiredVol * costPrice(limitPrice) * mult;
323
+
324
+ auto rit = reservations_.find(key);
325
+ if (rit == reservations_.end()) {
326
+ // Untracked order (sent before a cap existed, or placed by another terminal
327
+ // on this account): start tracking only if a cap applies and it's working.
328
+ if (desiredVol <= 0.0 || !hasCapLocked(instrumentId, isLong))
329
+ return;
330
+ Pos &pp = positions_[instrumentId];
331
+ if (isLong) {
332
+ pp.longPendVol += desiredVol;
333
+ pp.longPendCost += desiredCost;
334
+ } else {
335
+ pp.shortPendVol += desiredVol;
336
+ pp.shortPendCost += desiredCost;
337
+ }
338
+ reservations_[key] = Reservation{instrumentId, isLong, desiredVol, desiredCost};
339
+ return;
340
+ }
341
+
342
+ // Reconcile the existing reservation to the order's current working remainder.
343
+ Reservation &r = rit->second;
344
+ const double dVol = desiredVol - r.vol;
345
+ const double dCost = desiredCost - r.cost;
346
+ Pos &pp = positions_[r.instrumentId];
347
+ if (r.isLong) {
348
+ pp.longPendVol += dVol;
349
+ pp.longPendCost += dCost;
350
+ } else {
351
+ pp.shortPendVol += dVol;
352
+ pp.shortPendCost += dCost;
353
+ }
354
+ if (desiredVol <= 0.0)
355
+ reservations_.erase(rit); // terminal: fully released
356
+ else {
357
+ r.vol = desiredVol;
358
+ r.cost = desiredCost;
359
+ }
360
+ }
361
+
362
+ void RiskEngine::releaseReservation(const std::string &orderRef) {
363
+ std::lock_guard<std::mutex> lk(posMutex_);
364
+ // Only ever called for OUR own orders (failed send / front rejection).
365
+ auto rit = reservations_.find(resvKey(myFrontId_, mySessionId_, orderRef));
366
+ if (rit == reservations_.end())
367
+ return;
368
+ Reservation &r = rit->second;
369
+ Pos &pp = positions_[r.instrumentId];
370
+ if (r.isLong) {
371
+ pp.longPendVol -= r.vol;
372
+ pp.longPendCost -= r.cost;
373
+ } else {
374
+ pp.shortPendVol -= r.vol;
375
+ pp.shortPendCost -= r.cost;
376
+ }
377
+ reservations_.erase(rit);
378
+ }
379
+
380
+ void RiskEngine::rebuildOpenReservations(const std::vector<OpenOrderInfo> &orders) {
381
+ std::lock_guard<std::mutex> lk(posMutex_);
382
+ // Authoritative resync: drop all reservations and the in-flight portion of
383
+ // every position, then re-reserve from the live working orders. Held (filled)
384
+ // position is untouched - that's reconciled by syncPositions.
385
+ for (auto &kv : positions_) {
386
+ kv.second.longPendVol = kv.second.longPendCost = 0.0;
387
+ kv.second.shortPendVol = kv.second.shortPendCost = 0.0;
388
+ }
389
+ reservations_.clear();
390
+ for (const auto &o : orders) {
391
+ if (o.vol <= 0.0)
392
+ continue;
393
+ const std::string key = resvKey(o.frontId, o.sessionId, o.orderRef);
394
+ // Dedupe by key: reqQryOrder can return the same working order more than once
395
+ // (paged / duplicate rows). Each (front:session:ref) must reserve exactly
396
+ // once; a duplicate would inflate the pending counters while reservations_
397
+ // collapses to a single entry, leaving a phantom reservation with no map
398
+ // entry to release it - it would over-block opens until the next full resync.
399
+ if (reservations_.count(key))
400
+ continue;
401
+ const double cost = o.vol * costPrice(o.price) * multiplierLocked(o.instrumentId);
402
+ Pos &pp = positions_[o.instrumentId];
403
+ if (o.isLong) {
404
+ pp.longPendVol += o.vol;
405
+ pp.longPendCost += cost;
406
+ } else {
407
+ pp.shortPendVol += o.vol;
408
+ pp.shortPendCost += cost;
409
+ }
410
+ reservations_[key] = Reservation{o.instrumentId, o.isLong, o.vol, cost};
411
+ }
412
+ }
413
+
414
+ RiskVerdict RiskEngine::block(const char *reason) const {
415
+ lastReason_.store(reason, std::memory_order_relaxed);
416
+ return {false, reason};
417
+ }
418
+
419
+ RiskVerdict RiskEngine::check(const std::string &instrumentId, double price,
420
+ double refPrice, int volume) const {
421
+ if (halted_.load(std::memory_order_relaxed))
422
+ return block("trading halted (kill-switch)");
423
+
424
+ if (volume <= 0)
425
+ return block("order volume must be positive");
426
+
427
+ // Reject a non-finite limit price (NaN/Inf) here, at the validation point, so
428
+ // it can't reach tryReserveOpen and poison the reserved cost. A market/any-
429
+ // price order legitimately has price 0 (finite), so isfinite allows it.
430
+ if (!std::isfinite(price))
431
+ return block("order price is not finite");
432
+
433
+ const int maxVol = maxOrderVolume_.load(std::memory_order_relaxed);
434
+ if (maxVol > 0 && volume > maxVol)
435
+ return block("order volume exceeds maxOrderVolume");
436
+
437
+ const double dev = maxPriceDeviation_.load(std::memory_order_relaxed);
438
+ // price > 0 guard: a market/any-price order has LimitPrice 0, which must NOT
439
+ // be measured against the reference (|0-ref|/ref = 1.0 would always trip).
440
+ if (dev > 0.0 && refPrice > 0.0 && price > 0.0) {
441
+ const double diff = std::fabs(price - refPrice) / refPrice;
442
+ if (diff > dev)
443
+ return block("order price deviates too far from reference");
444
+ }
445
+
446
+ const double maxNotional = maxNotional_.load(std::memory_order_relaxed);
447
+ if (maxNotional > 0.0 && price > 0.0) {
448
+ double mult;
449
+ {
450
+ std::lock_guard<std::mutex> lk(posMutex_); // only when notional is capped
451
+ mult = multiplierLocked(instrumentId);
452
+ }
453
+ const double notional = price * static_cast<double>(volume) * mult;
454
+ if (notional > maxNotional)
455
+ return block("order notional exceeds maxNotional");
456
+ }
457
+
458
+ return {true, nullptr};
459
+ }
460
+
461
+ } // namespace ctp
@@ -0,0 +1,183 @@
1
+ /*
2
+ * risk.h - pre-trade risk enforcement + rate limiting, sunk into C++.
3
+ *
4
+ * These run on the HOT path (right before an order is sent - which may be the
5
+ * JS thread today, or the CTP callback thread once armed triggers fire). They
6
+ * must be deterministic and never blocked by a JS GC pause, so config is held
7
+ * in atomics, published from the slow path (JS) and read lock-free on the hot
8
+ * path. JS sets the rules; C++ enforces them on every order.
9
+ */
10
+
11
+ #ifndef CTP_NATIVE_RISK_H
12
+ #define CTP_NATIVE_RISK_H
13
+
14
+ #include <atomic>
15
+ #include <chrono>
16
+ #include <mutex>
17
+ #include <string>
18
+ #include <unordered_map>
19
+ #include <vector>
20
+
21
+ namespace ctp {
22
+
23
+ // One working open order, for rebuilding reservations from reqQryOrder.
24
+ struct OpenOrderInfo {
25
+ int frontId = 0;
26
+ int sessionId = 0;
27
+ std::string orderRef;
28
+ std::string instrumentId;
29
+ bool isLong = true;
30
+ double vol = 0.0; // working remainder (VolumeTotalOriginal - VolumeTraded)
31
+ double price = 0.0; // LimitPrice
32
+ };
33
+
34
+ struct RiskConfig {
35
+ int maxOrderVolume = 0; // per single order; 0 = disabled
36
+ double maxPriceDeviation = 0.0; // |px-ref|/ref ratio; 0 = disabled
37
+ double maxNotional = 0.0; // price * volume; 0 = disabled
38
+ double maxOrdersPerSec = 0.0; // token-bucket rate; 0 = disabled
39
+ double orderBurst = 0.0; // bucket burst; <=0 -> defaults to rate
40
+ double maxPositionCost = 0.0; // cap on total open-position cost; 0 = off
41
+ };
42
+
43
+ struct RiskVerdict {
44
+ bool ok = true;
45
+ const char *reason = nullptr; // static string; null when ok
46
+ };
47
+
48
+ // Result of the position gate for an opening order.
49
+ enum class OpenGate { Ok, CostLimit, VolumeLimit };
50
+
51
+ // Token-bucket rate limiter. Thread-safe via a tiny mutex; rate<=0 disables.
52
+ class RateLimiter {
53
+ public:
54
+ void configure(double ratePerSec, double burst);
55
+ bool tryAcquire(); // true = allowed, false = throttled
56
+
57
+ private:
58
+ std::mutex m_;
59
+ double rate_ = 0.0;
60
+ double burst_ = 0.0;
61
+ double tokens_ = 0.0;
62
+ std::chrono::steady_clock::time_point last_{};
63
+ bool initialized_ = false;
64
+ };
65
+
66
+ class RiskEngine {
67
+ public:
68
+ void configure(const RiskConfig &cfg); // slow path (JS thread)
69
+ void halt(); // kill-switch on
70
+ void resume(); // kill-switch off
71
+ bool isHalted() const { return halted_.load(std::memory_order_relaxed); }
72
+
73
+ // Validation only (no position side effects). refPrice<=0 skips deviation;
74
+ // the instrument's multiplier (if set) is applied to the notional check.
75
+ RiskVerdict check(const std::string &instrumentId, double price,
76
+ double refPrice, int volume) const;
77
+ // Static reason string of the most recent check() rejection (for diagnostics
78
+ // / JS-side logging); null if none. Cheap, set only on the reject path.
79
+ const char *lastBlockReason() const { return lastReason_.load(std::memory_order_relaxed); }
80
+
81
+ // Rate gate (consumes a token). Call right before sending.
82
+ bool allowRate() { return limiter_.tryAcquire(); }
83
+
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);
87
+ double refPrice(const std::string &instrumentId) const;
88
+
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.
92
+ void setMultiplier(const std::string &instrumentId, double multiplier);
93
+ void seedPosition(const std::string &instrumentId, bool isLong, double volume, double cost);
94
+ void onTrade(const std::string &instrumentId, bool isBuy, bool isOpen, double price, double volume);
95
+ void resetPositions();
96
+ double currentPositionCost() const;
97
+ // Per-instrument cap on open-position cost (Σ price*volume*multiplier, both
98
+ // sides summed - a gross capital/concentration limit). 0/unset = no cap.
99
+ // Complements the global maxPositionCost.
100
+ void setMaxInstrumentCost(const std::string &instrumentId, double maxCost);
101
+ // Per-instrument, per-side cap on open position volume (lots). Long and short
102
+ // capped independently; 0/unset = that side unlimited.
103
+ void setMaxPositionVolume(const std::string &instrumentId, bool isLong, double maxVolume);
104
+
105
+ // Our login session (FrontID, SessionID), set on rsp-user-login. Reservations
106
+ // are keyed by (front, session, orderRef) so orders from THIS session never
107
+ // collide with another terminal's orders on the same account (which CTP also
108
+ // delivers to us, and which auto-seed the same orderRef numbers).
109
+ void setSession(int frontId, int sessionId);
110
+
111
+ // Atomically check ALL position caps (per-side volume, per-instrument cost,
112
+ // global cost) against committed = held + in-flight reserved, and, if the
113
+ // order passes and any cap applies, reserve it (under our own session key) so
114
+ // a burst of opens can't slip past before fills arrive. Returns the cap that
115
+ // blocked, or Ok (reserved). Pair every Ok with an eventual release: a fill/
116
+ // cancel/reject reconciles via onOrderUpdate / releaseReservation, and a
117
+ // failed send (api rc != 0) must call releaseReservation - no lifecycle event.
118
+ OpenGate tryReserveOpen(const std::string &orderRef, const std::string &instrumentId,
119
+ bool isLong, double price, double volume);
120
+ // Reconcile an open order's reservation to its current working remainder
121
+ // (volTotal - volTraded while queueing; 0 once terminal). Fed from OnRtnOrder,
122
+ // which carries the originating session - so this also tracks (and releases)
123
+ // orders placed by another terminal on the same account.
124
+ void onOrderUpdate(int frontId, int sessionId, const std::string &orderRef,
125
+ const std::string &instrumentId, bool isOpen, bool isLong,
126
+ char status, double limitPrice, double volTotal, double volTraded);
127
+ // Drop one of OUR orders' reservations outright (front/insert rejection, or
128
+ // failed send - neither yields an OnRtnOrder).
129
+ void releaseReservation(const std::string &orderRef);
130
+ // Rebuild all in-flight reservations from CTP's working orders (reqQryOrder).
131
+ // Authoritative resync for (re)connect; clears prior reservations first.
132
+ void rebuildOpenReservations(const std::vector<OpenOrderInfo> &orders);
133
+
134
+ private:
135
+ std::atomic<bool> halted_{false};
136
+ std::atomic<int> maxOrderVolume_{0};
137
+ std::atomic<double> maxPriceDeviation_{0.0};
138
+ std::atomic<double> maxNotional_{0.0};
139
+ std::atomic<double> maxPositionCost_{0.0};
140
+ RateLimiter limiter_;
141
+ mutable std::mutex refMutex_;
142
+ std::unordered_map<std::string, double> refPrices_;
143
+
144
+ struct Pos {
145
+ double longVol = 0, longCost = 0, shortVol = 0, shortCost = 0; // filled
146
+ double longPendVol = 0, longPendCost = 0, shortPendVol = 0, shortPendCost = 0; // in-flight reserved
147
+ };
148
+ mutable std::mutex posMutex_;
149
+ std::unordered_map<std::string, Pos> positions_;
150
+ int myFrontId_ = 0, mySessionId_ = 0; // our session, for reservation keys
151
+ // In-flight open-order reservations, keyed by (front:session:orderRef) so a
152
+ // fill/cancel/reject releases exactly what each order reserved (its working
153
+ // remainder), and our orders never collide with another terminal's.
154
+ struct Reservation {
155
+ std::string instrumentId;
156
+ bool isLong = true;
157
+ double vol = 0.0, cost = 0.0;
158
+ };
159
+ std::unordered_map<std::string, Reservation> reservations_;
160
+ static std::string resvKey(int frontId, int sessionId, const std::string &orderRef);
161
+ // Contract multipliers are static metadata kept separate from position state
162
+ // so resetPositions() (which syncPositions calls) does not wipe them.
163
+ std::unordered_map<std::string, double> multipliers_;
164
+ // Per-instrument, per-side lot caps (config metadata; like multipliers,
165
+ // survives resets). 0 on a side = that side is uncapped.
166
+ struct VolCap {
167
+ double longMax = 0.0, shortMax = 0.0;
168
+ };
169
+ std::unordered_map<std::string, VolCap> maxPositionVol_;
170
+ // Per-instrument open-cost caps (config metadata; survives resets). 0 = off.
171
+ std::unordered_map<std::string, double> maxInstrumentCost_;
172
+ // Look up an instrument's multiplier (1.0 if unset). Caller holds posMutex_.
173
+ double multiplierLocked(const std::string &instrumentId) const;
174
+ // Whether any position cap applies to this instrument/side. Holds posMutex_.
175
+ bool hasCapLocked(const std::string &instrumentId, bool isLong) const;
176
+ // Record + return a check() rejection (stores the reason for lastBlockReason).
177
+ RiskVerdict block(const char *reason) const;
178
+ mutable std::atomic<const char *> lastReason_{nullptr};
179
+ };
180
+
181
+ } // namespace ctp
182
+
183
+ #endif /* CTP_NATIVE_RISK_H */