@hitrading/ctp-node 1.2.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/CHANGELOG.md +67 -0
  2. package/README.md +52 -31
  3. package/README.zh-CN.md +42 -26
  4. package/RELEASING.md +78 -0
  5. package/binding.gyp +13 -13
  6. package/dist/client.d.ts +40 -15
  7. package/dist/client.d.ts.map +1 -1
  8. package/dist/client.js +241 -62
  9. package/dist/client.js.map +1 -1
  10. package/dist/codec.d.ts.map +1 -1
  11. package/dist/codec.js +84 -19
  12. package/dist/codec.js.map +1 -1
  13. package/dist/generated/structs.gen.d.ts +5461 -5461
  14. package/dist/generated/structs.gen.d.ts.map +1 -1
  15. package/dist/generated/trader.gen.d.ts.map +1 -1
  16. package/dist/generated/trader.gen.js +788 -94
  17. package/dist/generated/trader.gen.js.map +1 -1
  18. package/dist/index.cjs +1896 -420
  19. package/dist/index.d.cts +1 -1
  20. package/dist/index.d.ts +1 -1
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.js.map +1 -1
  23. package/dist/market-data.d.ts +48 -21
  24. package/dist/market-data.d.ts.map +1 -1
  25. package/dist/market-data.js +165 -26
  26. package/dist/market-data.js.map +1 -1
  27. package/dist/native-binding.d.ts.map +1 -1
  28. package/dist/native-binding.js +5 -1
  29. package/dist/native-binding.js.map +1 -1
  30. package/dist/trader.d.ts +127 -79
  31. package/dist/trader.d.ts.map +1 -1
  32. package/dist/trader.js +788 -200
  33. package/dist/trader.js.map +1 -1
  34. package/dist/validation.d.ts +27 -0
  35. package/dist/validation.d.ts.map +1 -0
  36. package/dist/validation.js +85 -0
  37. package/dist/validation.js.map +1 -0
  38. package/docs/API.md +1437 -0
  39. package/docs/API.zh-CN.md +1278 -0
  40. package/docs/MIGRATION.md +54 -0
  41. package/docs/assets/validation.svg +27 -0
  42. package/docs/integration.md +60 -0
  43. package/docs/native-hooks.md +281 -0
  44. package/docs/native-hooks.zh-CN.md +205 -0
  45. package/docs/troubleshooting.md +257 -0
  46. package/docs/troubleshooting.zh-CN.md +220 -0
  47. package/package.json +14 -6
  48. package/prebuilds/linux-x64/@hitrading+ctp-node.node +0 -0
  49. package/prebuilds/win32-x64/@hitrading+ctp-node.node +0 -0
  50. package/scripts/bench-decode.mjs +37 -0
  51. package/scripts/bench-fullmarket-offline.mjs +207 -0
  52. package/scripts/stress-fullmarket.mjs +255 -0
  53. package/src/addon.cc +2 -2
  54. package/src/client.ts +263 -65
  55. package/src/codec.ts +86 -19
  56. package/src/generated/structs.gen.ts +5461 -5461
  57. package/src/generated/trader.gen.ts +309 -94
  58. package/src/generated/traderreq.gen.cc +194 -18
  59. package/src/generated/traderreq.gen.h +4 -0
  60. package/src/generated/traderspi.gen.cc +130 -10
  61. package/src/generated/traderspi.gen.h +4 -2
  62. package/src/index.ts +8 -1
  63. package/src/market-data.ts +219 -43
  64. package/src/native/arm.cc +114 -30
  65. package/src/native/arm.h +16 -4
  66. package/src/native/channel.cc +209 -81
  67. package/src/native/channel.h +65 -24
  68. package/src/native/ctp_field.h +23 -0
  69. package/src/native/mdapi.cc +621 -61
  70. package/src/native/mdspi.cc +221 -14
  71. package/src/native/mdspi.h +62 -9
  72. package/src/native/order_capability.h +75 -0
  73. package/src/native/risk.cc +2051 -205
  74. package/src/native/risk.h +450 -57
  75. package/src/native/shared_handle.h +37 -0
  76. package/src/native/snapshot.h +120 -0
  77. package/src/native/traderapi.cc +749 -170
  78. package/src/native-binding.ts +5 -1
  79. package/src/trader.ts +993 -229
  80. package/src/validation.ts +96 -0
  81. /package/{tradeapi → ctpsdk}/ThostFtdcMdApi.h +0 -0
  82. /package/{tradeapi → ctpsdk}/ThostFtdcTraderApi.h +0 -0
  83. /package/{tradeapi → ctpsdk}/ThostFtdcUserApiDataType.h +0 -0
  84. /package/{tradeapi → ctpsdk}/ThostFtdcUserApiStruct.h +0 -0
  85. /package/{tradeapi → ctpsdk}/error.dtd +0 -0
  86. /package/{tradeapi → ctpsdk}/error.xml +0 -0
  87. /package/{tradeapi → ctpsdk}/linux/thostmduserapi_se.so +0 -0
  88. /package/{tradeapi → ctpsdk}/linux/thosttraderapi_se.so +0 -0
  89. /package/{tradeapi → ctpsdk}/macos/thostmduserapi_se.framework/Versions/A/Headers/ThostFtdcMdApi.h +0 -0
  90. /package/{tradeapi → ctpsdk}/macos/thostmduserapi_se.framework/Versions/A/Headers/ThostFtdcUserApiDataType.h +0 -0
  91. /package/{tradeapi → ctpsdk}/macos/thostmduserapi_se.framework/Versions/A/Headers/ThostFtdcUserApiStruct.h +0 -0
  92. /package/{tradeapi → ctpsdk}/macos/thostmduserapi_se.framework/Versions/A/Resources/Info.plist +0 -0
  93. /package/{tradeapi → ctpsdk}/macos/thostmduserapi_se.framework/Versions/A/_CodeSignature/CodeResources +0 -0
  94. /package/{tradeapi → ctpsdk}/macos/thostmduserapi_se.framework/Versions/A/thostmduserapi_se +0 -0
  95. /package/{tradeapi → ctpsdk}/macos/thosttraderapi_se.framework/Versions/A/Headers/ThostFtdcTraderApi.h +0 -0
  96. /package/{tradeapi → ctpsdk}/macos/thosttraderapi_se.framework/Versions/A/Headers/ThostFtdcUserApiDataType.h +0 -0
  97. /package/{tradeapi → ctpsdk}/macos/thosttraderapi_se.framework/Versions/A/Headers/ThostFtdcUserApiStruct.h +0 -0
  98. /package/{tradeapi → ctpsdk}/macos/thosttraderapi_se.framework/Versions/A/Resources/Info.plist +0 -0
  99. /package/{tradeapi → ctpsdk}/macos/thosttraderapi_se.framework/Versions/A/_CodeSignature/CodeResources +0 -0
  100. /package/{tradeapi → ctpsdk}/macos/thosttraderapi_se.framework/Versions/A/thosttraderapi_se +0 -0
  101. /package/{tradeapi → ctpsdk}/windows/thostmduserapi_se.dll +0 -0
  102. /package/{tradeapi → ctpsdk}/windows/thostmduserapi_se.lib +0 -0
  103. /package/{tradeapi → ctpsdk}/windows/thosttraderapi_se.dll +0 -0
  104. /package/{tradeapi → ctpsdk}/windows/thosttraderapi_se.lib +0 -0
package/src/native/risk.h CHANGED
@@ -13,13 +13,32 @@
13
13
 
14
14
  #include <atomic>
15
15
  #include <chrono>
16
+ #include <cstdint>
17
+ #include <deque>
18
+ #include <map>
19
+ #include <memory>
16
20
  #include <mutex>
17
21
  #include <string>
18
22
  #include <unordered_map>
23
+ #include <unordered_set>
24
+ #include <utility>
19
25
  #include <vector>
20
26
 
21
27
  namespace ctp {
22
28
 
29
+ using RiskSendMutex = std::recursive_mutex;
30
+
31
+ // A read-only source of latest reference prices (the MarketData snapshot cache
32
+ // implements it). Lets the risk engine read live prices for the deviation check
33
+ // in C++; attached via setMdSnapshot with no dependency on the CTP md struct
34
+ // and no JS round-trip. last() returns 0 for an unknown/absent instrument.
35
+ struct RefPriceSource {
36
+ // Atomically pair a price with its age.
37
+ virtual bool quote(const std::string &instrumentId, double &price,
38
+ uint64_t &age) const = 0;
39
+ virtual ~RefPriceSource() = default;
40
+ };
41
+
23
42
  // One working open order, for rebuilding reservations from reqQryOrder.
24
43
  struct OpenOrderInfo {
25
44
  int frontId = 0;
@@ -27,17 +46,54 @@ struct OpenOrderInfo {
27
46
  std::string orderRef;
28
47
  std::string instrumentId;
29
48
  bool isLong = true;
49
+ char hedgeFlag = '1';
30
50
  double vol = 0.0; // working remainder (VolumeTotalOriginal - VolumeTraded)
31
51
  double price = 0.0; // LimitPrice
52
+ double traded = 0.0; // fills already reflected by the authoritative snapshot
53
+ std::string orderSysKey; // ExchangeID|OrderSysID when assigned
54
+ bool supportedSingleLeg = true;
55
+ };
56
+
57
+ struct PositionSeed {
58
+ std::string instrumentId;
59
+ bool isLong = true;
60
+ double volume = 0.0;
61
+ double margin = 0.0;
62
+ char hedgeFlag = '1';
63
+ };
64
+
65
+ // One atomic per-instrument limit update. `updateLong` / `updateShort` allow a
66
+ // caller to leave one side unchanged; a zero limit removes that side's
67
+ // cap. A batch is validated before any entry is committed.
68
+ struct InstrumentPositionLimitUpdate {
69
+ std::string instrumentId;
70
+ bool updateLong = false;
71
+ double longLimit = 0.0;
72
+ bool updateShort = false;
73
+ double shortLimit = 0.0;
74
+ };
75
+
76
+ struct InstrumentMarginLimitUpdate {
77
+ std::string instrumentId;
78
+ double limit = 0.0;
32
79
  };
33
80
 
34
- struct RiskConfig {
81
+ struct RiskLimits {
35
82
  int maxOrderVolume = 0; // per single order; 0 = disabled
36
83
  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
84
+ double maxNotional = 0.0; // price * volume * multiplier; 0 = disabled
85
+ double maxOrdersPerSec = 0.0; // opening-order token-bucket rate; 0 = off
39
86
  double orderBurst = 0.0; // bucket burst; <=0 -> defaults to rate
40
- double maxPositionCost = 0.0; // cap on total open-position cost; 0 = off
87
+ double maxCloseOrdersPerSec = 0.0; // independent reduce-order rate; 0 = off
88
+ double closeOrderBurst = 0.0;
89
+ double maxAccountMargin = 0.0; // cap on total held+reserved margin; 0 = off
90
+ double maxReferenceAgeMs = 3000; // deviation quote freshness; must be > 0
91
+ };
92
+
93
+ enum class RiskMode : uint8_t {
94
+ Normal,
95
+ ReduceOnly,
96
+ HaltAll,
41
97
  };
42
98
 
43
99
  struct RiskVerdict {
@@ -46,16 +102,23 @@ struct RiskVerdict {
46
102
  };
47
103
 
48
104
  // Result of the position gate for an opening order.
49
- enum class OpenGate { Ok, CostLimit, VolumeLimit };
105
+ enum class OpenGate {
106
+ Ok,
107
+ CostLimit,
108
+ VolumeLimit,
109
+ MetadataUnavailable,
110
+ DuplicateOrderRef,
111
+ };
50
112
 
51
113
  // Token-bucket rate limiter. Thread-safe via a tiny mutex; rate<=0 disables.
52
114
  class RateLimiter {
53
115
  public:
54
116
  void configure(double ratePerSec, double burst);
55
117
  bool tryAcquire(); // true = allowed, false = throttled
118
+ bool enabled() const;
56
119
 
57
120
  private:
58
- std::mutex m_;
121
+ mutable std::mutex m_;
59
122
  double rate_ = 0.0;
60
123
  double burst_ = 0.0;
61
124
  double tokens_ = 0.0;
@@ -65,117 +128,447 @@ private:
65
128
 
66
129
  class RiskEngine {
67
130
  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); }
131
+ void configure(const RiskLimits &cfg); // slow path (JS thread)
132
+ void reduceOnly(); // block risk-increasing requests, keep reductions/cancels
133
+ void haltAll(); // block both opening and closing order inserts
134
+ void resume(); // Normal
135
+ RiskMode mode() const { return mode_.load(std::memory_order_acquire); }
72
136
 
73
- // Validation only (no position side effects). refPrice<=0 skips deviation;
74
- // the instrument's multiplier (if set) is applied to the notional check.
137
+ // Validation only (no position side effects). Opening orders fail closed when
138
+ // an enabled deviation/notional rule lacks a usable reference or multiplier.
75
139
  RiskVerdict check(const std::string &instrumentId, double price,
76
- double refPrice, int volume) const;
140
+ double refPrice, int volume, bool isOpen = true) const;
77
141
  // Static reason string of the most recent check() rejection (for diagnostics
78
142
  // / 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); }
143
+ const char *lastBlockReason() const { return lastReason_; }
80
144
 
81
145
  // Rate gate (consumes a token). Call right before sending.
82
146
  bool allowRate() { return limiter_.tryAcquire(); }
147
+ bool allowCloseRate() { return closeLimiter_.tryAcquire(); }
148
+ // RAII lock spanning every gate and the vendor call.
149
+ // `allowed` is evaluated under the same barrier used by configure/mode changes.
150
+ std::unique_lock<RiskSendMutex> acquireOrderSend(bool isOpen, bool &allowed);
151
+ // Ordinary orders additionally bind the final send barrier to the confirmed
152
+ // BrokerID/InvestorID. Session transitions take the same send->position lock
153
+ // order, so a close cannot pass an account check and then be sent in a newly
154
+ // logged-in account (opens were already stopped later by reservation).
155
+ std::unique_lock<RiskSendMutex> acquireOrderSendForAccount(
156
+ bool isOpen, const std::string &brokerId,
157
+ const std::string &investorId, bool &allowed);
83
158
 
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);
159
+ // Attach a live reference-price source (the MarketData snapshot cache) so the
160
+ // maxPriceDeviation check reads current prices in C++ straight from the MD
161
+ // feed, no JS round-trip. Pass nullptr to detach. Without one, refPrice()
162
+ // returns 0 and an enabled deviation rule rejects opening orders.
163
+ void setMdSnapshot(std::shared_ptr<const RefPriceSource> source);
164
+ // Reference price for the deviation check: the attached MD snapshot's last
165
+ // price, or 0 if none/unknown.
87
166
  double refPrice(const std::string &instrumentId) const;
88
167
 
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);
168
+ // Max total open-position MARGIN (sum open price*volume*multiplier*rate).
169
+ // Updated by fills (onTrade) on the trader callback thread; authoritative
170
+ // pre-existing positions enter through replacePositionsIfRevision(). Set the
171
+ // contract multiplier AND margin rate for accuracy.
172
+ // Instrument metadata from reqQryInstrument. Only futures/TAS carry the futures
173
+ // by-money + by-volume margin formula; other product classes (e.g. options)
174
+ // fail closed for BOTH margin reservations AND the maxNotional cap, because a
175
+ // futures notional formula would misrepresent, say, an option premium. The
176
+ // multiplier is still recorded for every class.
177
+ void setInstrument(const std::string &instrumentId, double multiplier,
178
+ char productClass);
179
+ // Called immediately before the corresponding CTP metadata query is sent.
180
+ // Old values must not remain usable while a refresh is in flight or when the
181
+ // refresh comes back empty/invalid.
182
+ void invalidateInstrument(const std::string &instrumentId);
183
+ // Per-instrument margin rate (fraction of notional, e.g. 0.10 = 10%), fed
184
+ // directly from CTP's OnRspQryInstrumentMarginRate inside C++ (no JS round-
185
+ // trip). New futures orders use the published schedule; an authoritative
186
+ // position sync uses CTP `UseMargin`. This is a conservative local margin
187
+ // ledger, not a universal replica of every exchange/broker calculation.
188
+ // Unset/invalid schedules make enabled monetary caps fail closed.
189
+ void setMarginSchedule(const std::string &instrumentId, char hedgeFlag,
190
+ double longByMoney, double longByVolume,
191
+ double shortByMoney, double shortByVolume,
192
+ bool isRelative);
193
+ void setExchangeMarginSchedule(const std::string &instrumentId,
194
+ char hedgeFlag, double longByMoney,
195
+ double longByVolume, double shortByMoney,
196
+ double shortByVolume);
197
+ void invalidateMarginSchedules(const std::string &instrumentId,
198
+ char hedgeFlag);
199
+ void invalidateExchangeMarginSchedule(const std::string &instrumentId,
200
+ char hedgeFlag);
201
+ // Session/account-bound query pipeline. Only the newest request id in the
202
+ // current authenticated account may publish a schedule; late rows from a
203
+ // timed-out or previous-account query are ignored.
204
+ void beginMarginScheduleQuery(int requestId, bool exchange,
205
+ const std::string &instrumentId,
206
+ char hedgeFlag,
207
+ const std::string &brokerId,
208
+ const std::string &investorId);
209
+ void applyInvestorMarginSchedule(
210
+ int requestId, const std::string &brokerId,
211
+ const std::string &investorId, const std::string &investUnitId,
212
+ const std::string &instrumentId, char hedgeFlag,
213
+ double longByMoney, double longByVolume,
214
+ double shortByMoney, double shortByVolume, bool isRelative);
215
+ void applyExchangeMarginSchedule(
216
+ int requestId, const std::string &brokerId,
217
+ const std::string &instrumentId, char hedgeFlag,
218
+ double longByMoney, double longByVolume,
219
+ double shortByMoney, double shortByVolume);
220
+ void finishMarginScheduleQuery(int requestId, bool success);
221
+ // Generated SPI uses a stable exchange/trading-day TradeID key. Returns without
222
+ // side effects when the same trade is replayed.
223
+ void onTrade(const std::string &tradeKey, const std::string &orderRef,
224
+ const std::string &orderSysKey,
225
+ const std::string &instrumentId, bool isBuy, bool isOpen,
226
+ char hedgeFlag, double price, double volume,
227
+ const std::string &brokerId = "",
228
+ const std::string &investorId = "");
229
+ void markTradeLedgerUncertain();
230
+ void markOrderLedgerUncertain();
95
231
  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);
232
+ bool replacePositionsIfRevision(uint64_t expected,
233
+ const std::vector<PositionSeed> &positions);
234
+ double accountMargin() const;
235
+ // Apply a complete batch under the final send barrier. This prevents an order
236
+ // from observing a half-updated pair of long/short limits or a partially
237
+ // committed multi-instrument batch. Returns false without changing anything
238
+ // when any entry is malformed.
239
+ bool setInstrumentPositionLimits(
240
+ const std::vector<InstrumentPositionLimitUpdate> &updates);
241
+ // Per-instrument cap on scheduled open margin (by-money + by-volume, both
242
+ // sides summed). 0/unset = no cap. Complements maxAccountMargin.
243
+ bool setInstrumentMarginLimits(
244
+ const std::vector<InstrumentMarginLimitUpdate> &updates);
245
+
246
+ // Our login identity, set on rsp-user-login. A front transition invalidates
247
+ // it and both ledgers; opening inserts remain fail-closed until a concrete
248
+ // login response supplies the new identity. Reservations are keyed by
249
+ // (front, session, orderRef) so orders from THIS session never collide with
250
+ // another terminal's orders on the same account.
251
+ void invalidateSession();
252
+ // Correlate login/logout responses with the most recent explicit request.
253
+ // Trader request ids are echoed reliably, unlike MD id-0 responses. A newer
254
+ // transition supersedes the old id so its delayed success cannot restore an
255
+ // obsolete native session identity.
256
+ void beginSessionTransition(int requestId, bool expectsLogin,
257
+ const std::string &brokerId = "",
258
+ const std::string &investorId = "");
259
+ bool acceptLoginSession(int requestId, int frontId, int sessionId,
260
+ const std::string &brokerId,
261
+ const std::string &userId);
262
+ // RspUserLogin identifies the operator UserID, not necessarily the trading
263
+ // InvestorID. The high-level session handshake explicitly confirms the
264
+ // account used by orders/positions before native risk state becomes usable.
265
+ bool confirmSessionAccount(int frontId, int sessionId,
266
+ const std::string &brokerId,
267
+ const std::string &investorId);
268
+ bool acceptsOrderAccount(const std::string &brokerId,
269
+ const std::string &investorId) const;
270
+ void finishSessionTransition(int requestId);
271
+ // JS idle-timeout linearization. True means this exact request was still
272
+ // pending and is now revoked; false means its final native callback already
273
+ // won and the queued lossless response should settle the Promise.
274
+ bool timeoutSessionTransition(int requestId);
275
+ void setSession(int frontId, int sessionId,
276
+ const std::string &brokerId = "",
277
+ const std::string &investorId = "");
110
278
 
111
279
  // Atomically check ALL position caps (per-side volume, per-instrument cost,
112
280
  // global cost) against committed = held + in-flight reserved, and, if the
113
281
  // order passes and any cap applies, reserve it (under our own session key) so
114
282
  // 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.
283
+ // blocked, or Ok (reserved). Pair every Ok with bindInsertRequest before the
284
+ // vendor call; callbacks reconcile via onOrderUpdate/rejectInsert*, while a
285
+ // local/immediate send failure uses rollbackInsertRequest.
118
286
  OpenGate tryReserveOpen(const std::string &orderRef, const std::string &instrumentId,
119
- bool isLong, double price, double volume);
287
+ bool isLong, double price, double volume,
288
+ char hedgeFlag = '1');
120
289
  // Reconcile an open order's reservation to its current working remainder
121
290
  // (volTotal - volTraded while queueing; 0 once terminal). Fed from OnRtnOrder,
122
291
  // which carries the originating session - so this also tracks (and releases)
123
292
  // orders placed by another terminal on the same account.
124
293
  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);
294
+ const std::string &instrumentId, bool isOpen, bool isLong,
295
+ char hedgeFlag, char status, double limitPrice,
296
+ double volTotal, double volTraded,
297
+ const std::string &orderSysKey = "",
298
+ const std::string &brokerId = "",
299
+ const std::string &investorId = "");
300
+ // A live multi-leg/otherwise unsupported working order cannot be represented
301
+ // by the single-instrument ledger. Track its identity and fail closed for
302
+ // all opening inserts until it becomes terminal or an
303
+ // authoritative order snapshot confirms it is gone.
304
+ void onUnsupportedOrderUpdate(int frontId, int sessionId,
305
+ const std::string &orderRef, char status,
306
+ const std::string &orderSysKey = "",
307
+ const std::string &brokerId = "",
308
+ const std::string &investorId = "");
309
+ // Bind a successful reservation to the exact CTP request id before the
310
+ // vendor call. The binding captures an internal generation token as well as
311
+ // (front, session, OrderRef), so a delayed response can never release a newer
312
+ // reservation after either session or OrderRef reuse. Returns false and
313
+ // atomically rolls back the still-unbound reservation when the request id is
314
+ // invalid/already live.
315
+ bool bindInsertRequest(int requestId, const std::string &orderRef);
316
+ // OnRspOrderInsert carries requestId and can therefore reject only the exact
317
+ // bound reservation. Unknown, mismatched, or contradictory callbacks fail
318
+ // closed instead of guessing the current session.
319
+ void rejectInsertByRequest(int requestId, const std::string &orderRef,
320
+ const std::string &brokerId = "",
321
+ const std::string &investorId = "");
322
+ // OnErrRtnOrderInsert has no requestId/front/session. It must never release by
323
+ // OrderRef alone; a matching live reservation makes the order ledger
324
+ // uncertain until an authoritative order snapshot reconciles it.
325
+ void rejectInsertUnscoped(const std::string &orderRef,
326
+ const std::string &brokerId = "",
327
+ const std::string &investorId = "");
328
+ // Undo the exact binding + reservation when CTP did not accept the request
329
+ // (rate-limit or an immediate nonzero ReqOrderInsert return). The same
330
+ // OrderRef then remains safe to retry.
331
+ void rollbackInsertRequest(int requestId, const std::string &orderRef);
130
332
  // Rebuild all in-flight reservations from CTP's working orders (reqQryOrder).
131
333
  // Authoritative resync for (re)connect; clears prior reservations first.
132
334
  void rebuildOpenReservations(const std::vector<OpenOrderInfo> &orders);
335
+ bool rebuildOpenReservationsIfRevision(uint64_t expected,
336
+ const std::vector<OpenOrderInfo> &orders);
337
+
338
+ uint64_t revision() const { return revision_.load(std::memory_order_acquire); }
339
+ // Mutations not representable by the normal InputOrder ledger (complex
340
+ // inserts, hedge/offset confirmations, etc.) may pass only when no local risk
341
+ // control is configured; otherwise they fail closed.
342
+ bool allowUnsupportedRiskRequest() const;
343
+ // Once CTP accepts such a mutation, a later transition from protocol-binding
344
+ // mode into locally risk-managed mode cannot assume the single-leg ledger is
345
+ // complete. This history is intentionally sticky for the Trader lifetime.
346
+ // The taint is unconditional (not account-scoped): CTP's private stream only
347
+ // delivers the confirmed investor's realtime returns, so every such broadcast
348
+ // is our own, and account text is not uniformly present anyway (bank-transfer
349
+ // returns carry no InvestorID).
350
+ void recordUnsupportedRiskMutation();
133
351
 
134
352
  private:
135
- std::atomic<bool> halted_{false};
353
+ std::atomic<RiskMode> mode_{RiskMode::Normal};
354
+ // Public N-API calls are validated, but direct/native callers must fail
355
+ // closed too. A valid complete configure() call clears this state.
356
+ std::atomic<bool> invalidConfig_{false};
357
+ // Recursive so a vendor implementation that invokes an SPI callback inline
358
+ // from ReqOrderInsert cannot deadlock when that callback updates the ledger.
359
+ mutable RiskSendMutex sendModeMutex_;
136
360
  std::atomic<int> maxOrderVolume_{0};
137
361
  std::atomic<double> maxPriceDeviation_{0.0};
138
362
  std::atomic<double> maxNotional_{0.0};
139
- std::atomic<double> maxPositionCost_{0.0};
363
+ std::atomic<double> maxAccountMargin_{0.0};
364
+ std::atomic<double> maxReferenceAgeMs_{3000.0};
140
365
  RateLimiter limiter_;
366
+ RateLimiter closeLimiter_;
367
+ // Live reference-price source (the MarketData snapshot cache), read by
368
+ // refPrice() for the deviation check. Guarded by refMutex_.
141
369
  mutable std::mutex refMutex_;
142
- std::unordered_map<std::string, double> refPrices_;
370
+ std::shared_ptr<const RefPriceSource> mdSnap_;
143
371
 
144
372
  struct Pos {
373
+ struct HeldBucket {
374
+ double vol = 0.0, cost = 0.0;
375
+ bool costKnown = true;
376
+ };
145
377
  double longVol = 0, longCost = 0, shortVol = 0, shortCost = 0; // filled
378
+ bool longCostKnown = true, shortCostKnown = true;
379
+ std::unordered_map<char, HeldBucket> longHeld, shortHeld;
146
380
  double longPendVol = 0, longPendCost = 0, shortPendVol = 0, shortPendCost = 0; // in-flight reserved
381
+ size_t longPendUnknown = 0, shortPendUnknown = 0;
147
382
  };
148
383
  mutable std::mutex posMutex_;
149
384
  std::unordered_map<std::string, Pos> positions_;
150
385
  int myFrontId_ = 0, mySessionId_ = 0; // our session, for reservation keys
386
+ std::string myBrokerId_, myInvestorId_, myLoginUserId_;
387
+ // Standalone RiskEngine unit users can seed a session directly. Once a real
388
+ // front lifecycle is observed, however, a fresh login identity is mandatory.
389
+ bool sessionIdentityRequired_ = false;
390
+ bool sessionIdentityKnown_ = false;
391
+ int pendingSessionRequestId_ = 0;
392
+ bool pendingSessionExpectsLogin_ = false;
393
+ std::string pendingSessionBrokerId_, pendingSessionUserId_;
394
+ bool loginSessionKnown_ = false;
151
395
  // In-flight open-order reservations, keyed by (front:session:orderRef) so a
152
396
  // fill/cancel/reject releases exactly what each order reserved (its working
153
397
  // remainder), and our orders never collide with another terminal's.
154
398
  struct Reservation {
399
+ std::string orderRef;
400
+ std::string orderSysKey;
155
401
  std::string instrumentId;
156
402
  bool isLong = true;
157
- double vol = 0.0, cost = 0.0;
403
+ char hedgeFlag = '1';
404
+ double vol = 0.0, cost = 0.0, price = 0.0;
405
+ bool costKnown = false;
406
+ int insertRequestId = 0;
407
+ uint64_t insertBindingToken = 0;
158
408
  };
159
409
  std::unordered_map<std::string, Reservation> reservations_;
410
+ enum class InsertRequestState : uint8_t {
411
+ Pending,
412
+ Observed,
413
+ Rejected,
414
+ };
415
+ struct InsertRequestBinding {
416
+ std::string reservationKey;
417
+ std::string orderRef;
418
+ uint64_t token = 0;
419
+ InsertRequestState state = InsertRequestState::Pending;
420
+ };
421
+ // Exact insert-response correlation is intentionally retained after the
422
+ // first callback, so duplicate/contradictory late responses cannot target a
423
+ // newer reservation. The FIFO is bounded; an eventual callback for an
424
+ // evicted id is treated as unknown and therefore fails closed.
425
+ std::unordered_map<int, InsertRequestBinding> insertRequests_;
426
+ std::deque<std::pair<int, uint64_t>> insertRequestOrder_;
427
+ uint64_t nextInsertBindingToken_ = 1;
428
+ static constexpr size_t kMaxInsertRequestBindings = 65536;
429
+ struct OrderState {
430
+ bool terminal = false;
431
+ double remaining = 0.0;
432
+ double reportedTraded = 0.0;
433
+ double appliedTraded = 0.0;
434
+ // Exchange/day/instrument/OrderSysID fingerprint. It distinguishes a known
435
+ // stale replay from a genuinely new order after front/session/ref reuse.
436
+ std::string orderSysKey;
437
+ };
438
+ // Tombstones make terminal state monotonic: an old non-terminal replay can no
439
+ // longer resurrect a completed order. Exact tombstones are retained in a
440
+ // bounded FIFO; evicting an exceptionally old tombstone can only recreate a
441
+ // conservative pending reservation if that old callback is replayed.
442
+ std::unordered_map<std::string, OrderState> orderStates_;
443
+ std::unordered_set<std::string> unsupportedWorkingOrders_;
444
+ bool orderLedgerUncertain_ = false;
445
+ std::deque<std::string> terminalOrderKeys_;
446
+ std::unordered_set<std::string> terminalOrderKeySet_;
447
+ static constexpr size_t kMaxTerminalOrderTombstones = 65536;
448
+ std::unordered_map<std::string, std::unordered_set<std::string>>
449
+ reservationKeysByRef_;
450
+ std::unordered_map<std::string, std::string> reservationKeyBySys_;
451
+ struct UnmatchedFill {
452
+ std::string orderRef;
453
+ double volume = 0.0;
454
+ };
455
+ // A trade from another terminal may precede its first OnRtnOrder. Remember
456
+ // the already-applied quantity by exchange order id so the later Order row
457
+ // cannot recreate it as pending exposure.
458
+ std::unordered_map<std::string, UnmatchedFill> unmatchedFillsBySys_;
459
+ static constexpr size_t kMaxUnmatchedFills = 65536;
460
+ struct SeenTrade {
461
+ std::string orderRef;
462
+ std::string orderSysKey;
463
+ std::string instrumentId;
464
+ bool isBuy = false;
465
+ bool isOpen = false;
466
+ char hedgeFlag = '\0';
467
+ double price = 0.0;
468
+ double volume = 0.0;
469
+ };
470
+ std::unordered_map<std::string, SeenTrade> seenTrades_;
471
+ std::map<std::string, std::vector<std::string>> tradeKeysByDay_;
472
+ // Once a day's exact keys have been compacted, ignore callbacks from that
473
+ // retired day. Otherwise one very late replay would be treated as new and,
474
+ // worse, rotate a recent day out of the bounded exact-key window.
475
+ // All trading days <= this YYYYMMDD cutoff have had their exact keys
476
+ // compacted. A monotonic cutoff is bounded, unlike retaining one string per
477
+ // historical day forever.
478
+ std::string retiredThroughTradeDay_;
479
+ static constexpr size_t kRetainedTradeDays = 3;
480
+ // Exact dedupe must also be bounded inside one exceptionally busy/malformed
481
+ // day. Older days are retired first. Exhausting one active day makes position
482
+ // accounting fail closed until a later trading day plus authoritative sync.
483
+ static constexpr size_t kMaxSeenTrades = 65536;
484
+ std::string tradeDedupeExhaustedDay_;
485
+ // A callback from a compacted day is ambiguous: it may be a duplicate or a
486
+ // first-seen late fill. Never guess and under-count; opening inserts
487
+ // fail closed until an authoritative position replacement clears this flag.
488
+ bool ledgerUncertain_ = false;
489
+ bool unsupportedRiskMutationUsed_ = false;
490
+ std::atomic<uint64_t> revision_{0};
160
491
  static std::string resvKey(int frontId, int sessionId, const std::string &orderRef);
492
+ void rememberTerminalOrderLocked(const std::string &key);
493
+ void forgetTerminalOrderLocked(const std::string &key);
494
+ void pruneEvictedTerminalOrderLocked(const std::string &key);
161
495
  // Contract multipliers are static metadata kept separate from position state
162
- // so resetPositions() (which syncPositions calls) does not wipe them.
496
+ // so held-position replacement/reset does not wipe them.
163
497
  std::unordered_map<std::string, double> multipliers_;
498
+ std::unordered_map<std::string, bool> futuresMarginFormula_;
499
+ // Per-instrument margin rates (fraction of notional), same lifetime as
500
+ // multipliers_ (static metadata; survives resetPositions). Missing schedules
501
+ // fail closed whenever a monetary cap needs them.
502
+ struct MarginSchedule {
503
+ double longByMoney = 0.0, longByVolume = 0.0;
504
+ double shortByMoney = 0.0, shortByVolume = 0.0;
505
+ bool isRelative = false;
506
+ };
507
+ std::unordered_map<std::string, MarginSchedule> marginRates_;
508
+ std::unordered_map<std::string, MarginSchedule> exchangeMarginRates_;
509
+ enum class MarginQueryKind : uint8_t { None, Investor, Exchange };
510
+ int activeMarginQueryRequestId_ = 0;
511
+ MarginQueryKind activeMarginQueryKind_ = MarginQueryKind::None;
512
+ bool activeMarginQueryAuthorized_ = false;
513
+ std::string activeMarginQueryInstrument_;
514
+ char activeMarginQueryHedgeFlag_ = '\0';
515
+ std::unordered_map<std::string, MarginSchedule> stagedMarginRates_;
164
516
  // Per-instrument, per-side lot caps (config metadata; like multipliers,
165
517
  // survives resets). 0 on a side = that side is uncapped.
166
518
  struct VolCap {
167
519
  double longMax = 0.0, shortMax = 0.0;
168
520
  };
169
521
  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_.
522
+ // Per-instrument scheduled-margin caps (config metadata; survives resets).
523
+ std::unordered_map<std::string, double> maxInstrumentMargin_;
524
+ // Best-effort lookup used only when no monetary cap is active. Capped paths
525
+ // separately require multiplierKnownLocked(). Caller holds posMutex_.
173
526
  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;
527
+ enum class AccountScope : uint8_t { Current, Foreign, Ambiguous };
528
+ AccountScope accountScopeLocked(const std::string &brokerId,
529
+ const std::string &investorId) const;
530
+ void clearAccountMarginMetadataLocked();
531
+ void clearAccountLedgerLocked();
532
+ void setMarginScheduleLocked(const std::string &instrumentId,
533
+ char hedgeFlag, double longByMoney,
534
+ double longByVolume, double shortByMoney,
535
+ double shortByVolume, bool isRelative);
536
+ void setExchangeMarginScheduleLocked(const std::string &instrumentId,
537
+ char hedgeFlag, double longByMoney,
538
+ double longByVolume,
539
+ double shortByMoney,
540
+ double shortByVolume);
541
+ bool multiplierKnownLocked(const std::string &instrumentId) const;
542
+ static std::string marginKey(const std::string &instrumentId, char hedgeFlag);
543
+ bool marginCostLocked(const std::string &instrumentId, bool isLong,
544
+ char hedgeFlag, double price, double volume,
545
+ double &cost) const;
546
+ bool hasCostCapLocked(const std::string &instrumentId) const;
547
+ bool localControlsEnabledLocked() const;
548
+ void refreshReservationCostsLocked(const std::string &instrumentId);
549
+ void refreshAllReservationCostsLocked();
550
+ void invalidateHeldCostsLocked(const std::string &instrumentId);
551
+ void recomputeHeldSideLocked(Pos &position, bool isLong);
552
+ void updateReservationExposureLocked(Reservation &r, double desiredVol,
553
+ double price);
554
+ void indexReservationLocked(const std::string &key);
555
+ void unindexReservationLocked(const std::string &key,
556
+ const Reservation &r);
557
+ // Returns true on an internal ownership conflict (ledger was made uncertain).
558
+ bool observeInsertRequestLocked(const std::string &key,
559
+ const Reservation &reservation);
560
+ std::string reservationKeyForTradeLocked(
561
+ const std::string &orderSysKey) const;
562
+ void clearPendingLocked();
563
+ static bool validOpenOrderSnapshot(
564
+ const std::vector<OpenOrderInfo> &orders);
565
+ bool rebuildOpenReservationsLocked(const std::vector<OpenOrderInfo> &orders);
176
566
  // Record + return a check() rejection (stores the reason for lastBlockReason).
177
567
  RiskVerdict block(const char *reason) const;
178
- mutable std::atomic<const char *> lastReason_{nullptr};
568
+ // Per-calling-thread diagnostic: an armed-order rejection on the MD callback
569
+ // thread cannot overwrite the reason a simultaneous JS-thread send is about
570
+ // to read and surface.
571
+ inline static thread_local const char *lastReason_ = nullptr;
179
572
  };
180
573
 
181
574
  } // namespace ctp
@@ -0,0 +1,37 @@
1
+ /*
2
+ * shared_handle.h - runtime-tagged N-API handles for cross-client shared state.
3
+ *
4
+ * Napi::External<T> does not preserve T at runtime. Both sides therefore use
5
+ * this one concrete payload and verify its magic/kind before touching either
6
+ * shared_ptr. This prevents an arm-registry External from being interpreted as
7
+ * a SnapshotCache External (or vice versa), which would otherwise be native
8
+ * type confusion rather than a recoverable JavaScript TypeError.
9
+ */
10
+ #ifndef CTP_NATIVE_SHARED_HANDLE_H
11
+ #define CTP_NATIVE_SHARED_HANDLE_H
12
+
13
+ #include <cstdint>
14
+ #include <memory>
15
+
16
+ namespace ctp {
17
+
18
+ class ArmRegistry;
19
+ class SnapshotCache;
20
+
21
+ enum class SharedHandleKind : uint32_t {
22
+ ArmRegistry = 1,
23
+ SnapshotCache = 2,
24
+ };
25
+
26
+ struct SharedHandle {
27
+ static constexpr uint64_t kMagic = UINT64_C(0x4354504E4F444548); // CTPNODEH
28
+
29
+ uint64_t magic = kMagic;
30
+ SharedHandleKind kind = SharedHandleKind::ArmRegistry;
31
+ std::shared_ptr<ArmRegistry> arm;
32
+ std::shared_ptr<SnapshotCache> snapshot;
33
+ };
34
+
35
+ } // namespace ctp
36
+
37
+ #endif /* CTP_NATIVE_SHARED_HANDLE_H */