@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
@@ -3,6 +3,7 @@
3
3
  */
4
4
 
5
5
  #include "mdspi.h"
6
+ #include "ctp_field.h"
6
7
 
7
8
  #include <cstdio>
8
9
 
@@ -15,11 +16,129 @@ static const char *emsg(CThostFtdcRspInfoField *e) {
15
16
  return (e && e->ErrorID) ? e->ErrorMsg : "";
16
17
  }
17
18
 
19
+ void MdSpi::invalidateSessionLocked() {
20
+ tradingDay_.clear();
21
+ pendingSessionRequestId_ = 0;
22
+ sessionState_ = SessionState::Inactive;
23
+ subscriptions_.clear();
24
+ SnapshotCache *sc = snap_.load(std::memory_order_acquire);
25
+ if (sc)
26
+ sc->invalidate();
27
+ }
28
+
29
+ void MdSpi::noteSubscriptionRequest(
30
+ const std::vector<std::string> &instrumentIds, bool subscribe) {
31
+ std::lock_guard<std::mutex> sessionLock(sessionMutex_);
32
+ uint64_t generation = nextSubscriptionGeneration_++;
33
+ if (generation == 0)
34
+ generation = nextSubscriptionGeneration_++;
35
+ for (const std::string &instrumentId : instrumentIds) {
36
+ SubscriptionState &state = subscriptions_[instrumentId];
37
+ state.latestGeneration = generation;
38
+ state.desired = subscribe;
39
+ auto &queue = subscribe ? state.subscribeGenerations
40
+ : state.unsubscribeGenerations;
41
+ queue.push_back(generation);
42
+ }
43
+ }
44
+
45
+ bool MdSpi::subscriptionAllowsLocked(
46
+ const std::string &instrumentId) const {
47
+ auto it = subscriptions_.find(instrumentId);
48
+ return it == subscriptions_.end() || it->second.desired;
49
+ }
50
+
51
+ void MdSpi::finishSubscriptionLocked(const std::string &instrumentId,
52
+ bool subscribe, bool success) {
53
+ auto state = subscriptions_.find(instrumentId);
54
+ if (state == subscriptions_.end())
55
+ return;
56
+ auto &queue = subscribe ? state->second.subscribeGenerations
57
+ : state->second.unsubscribeGenerations;
58
+ if (queue.empty())
59
+ return;
60
+ const uint64_t generation = queue.front();
61
+ queue.pop_front();
62
+ if (generation != state->second.latestGeneration)
63
+ return; // a newer opposite/same-kind request owns the final intent
64
+ state->second.desired = success ? subscribe : !subscribe;
65
+ SnapshotCache *sc = snap_.load(std::memory_order_acquire);
66
+ if (!state->second.desired && sc)
67
+ sc->erase(instrumentId);
68
+ }
69
+
70
+ void MdSpi::invalidateSession() {
71
+ std::lock_guard<std::mutex> sessionLock(sessionMutex_);
72
+ invalidateSessionLocked();
73
+ }
74
+
75
+ bool MdSpi::beginLogin(int requestId) {
76
+ std::lock_guard<std::mutex> sessionLock(sessionMutex_);
77
+ if (requestId <= 0 || sessionState_ == SessionState::LoginPending ||
78
+ sessionState_ == SessionState::LogoutPending ||
79
+ sessionState_ == SessionState::Ambiguous)
80
+ return false;
81
+ invalidateSessionLocked();
82
+ sessionState_ = SessionState::LoginPending;
83
+ pendingSessionRequestId_ = requestId;
84
+ return true;
85
+ }
86
+
87
+ bool MdSpi::beginLogout(int requestId) {
88
+ std::lock_guard<std::mutex> sessionLock(sessionMutex_);
89
+ if (requestId <= 0 || sessionState_ == SessionState::LoginPending ||
90
+ sessionState_ == SessionState::LogoutPending ||
91
+ sessionState_ == SessionState::Ambiguous)
92
+ return false;
93
+ invalidateSessionLocked();
94
+ sessionState_ = SessionState::LogoutPending;
95
+ pendingSessionRequestId_ = requestId;
96
+ return true;
97
+ }
98
+
99
+ void MdSpi::abandonSessionTransition() {
100
+ std::lock_guard<std::mutex> sessionLock(sessionMutex_);
101
+ if (sessionState_ != SessionState::LoginPending &&
102
+ sessionState_ != SessionState::LogoutPending)
103
+ return;
104
+ tradingDay_.clear();
105
+ pendingSessionRequestId_ = 0;
106
+ sessionState_ = SessionState::Ambiguous;
107
+ SnapshotCache *sc = snap_.load(std::memory_order_acquire);
108
+ if (sc)
109
+ sc->invalidate();
110
+ }
111
+
112
+ bool MdSpi::timeoutSessionTransition(int requestId) {
113
+ std::lock_guard<std::mutex> sessionLock(sessionMutex_);
114
+ const bool pending = sessionState_ == SessionState::LoginPending ||
115
+ sessionState_ == SessionState::LogoutPending;
116
+ if (!pending)
117
+ return false; // final callback/front transition already won the mutex
118
+ if (requestId <= 0 || requestId != pendingSessionRequestId_)
119
+ return true; // not this native transition; do not mutate somebody else's
120
+ tradingDay_.clear();
121
+ pendingSessionRequestId_ = 0;
122
+ sessionState_ = SessionState::Ambiguous;
123
+ SnapshotCache *sc = snap_.load(std::memory_order_acquire);
124
+ if (sc)
125
+ sc->invalidate();
126
+ return true;
127
+ }
128
+
129
+ bool MdSpi::responseMatchesLocked(SessionState pendingState,
130
+ int requestId) const {
131
+ return sessionState_ == pendingState &&
132
+ (requestId == pendingSessionRequestId_ || requestId == 0);
133
+ }
134
+
18
135
  void MdSpi::OnFrontConnected() {
136
+ invalidateSession(); // connected is not authenticated; await successful login
19
137
  ch_->push(MD_FRONT_CONNECTED, 0, -1, 0, "", -1, nullptr, 0);
20
138
  }
21
139
 
22
140
  void MdSpi::OnFrontDisconnected(int nReason) {
141
+ invalidateSession();
23
142
  int r = nReason;
24
143
  ch_->push(MD_FRONT_DISCONNECTED, 0, -1, 0, "", -2, &r, sizeof(r));
25
144
  }
@@ -31,12 +150,52 @@ void MdSpi::OnHeartBeatWarning(int nTimeLapse) {
31
150
 
32
151
  void MdSpi::OnRspUserLogin(CThostFtdcRspUserLoginField *p,
33
152
  CThostFtdcRspInfoField *e, int id, bool last) {
153
+ // Login responses are normally a single final row. Require the final success
154
+ // carrying session data before exposing quotes; an empty/error final response
155
+ // leaves the cache fail-closed.
156
+ if (last) {
157
+ std::lock_guard<std::mutex> sessionLock(sessionMutex_);
158
+ if (responseMatchesLocked(SessionState::LoginPending, id)) {
159
+ pendingSessionRequestId_ = 0;
160
+ std::string tradingDay;
161
+ // An MD login carries no FrontID/SessionID (those are the trade front's
162
+ // order-routing identity and are commonly 0 on the market-data channel). A
163
+ // successful final login row with a well-formed TradingDay is the correct
164
+ // activation signal; requiring a trade session id here left the snapshot
165
+ // cache permanently inactive on real MD logins.
166
+ if (p && eid(e) == 0 && boundedCtpField(p->TradingDay, tradingDay)) {
167
+ tradingDay_ = std::move(tradingDay);
168
+ sessionState_ = SessionState::Authenticated;
169
+ SnapshotCache *sc = snap_.load(std::memory_order_acquire);
170
+ if (sc)
171
+ sc->activate();
172
+ } else {
173
+ invalidateSessionLocked();
174
+ }
175
+ } else if (sessionState_ == SessionState::Ambiguous) {
176
+ // The timed-out request is the only possible outstanding transition.
177
+ // Its final callback resolves the ambiguity, but is never allowed to
178
+ // authenticate after the JS caller has already abandoned that epoch.
179
+ invalidateSessionLocked();
180
+ }
181
+ }
34
182
  ch_->push(MD_RSP_USER_LOGIN, id, last ? 1 : 0, eid(e), emsg(e),
35
183
  p ? SID_RspUserLogin : -1, p, p ? (int)sizeof(*p) : 0);
36
184
  }
37
185
 
38
186
  void MdSpi::OnRspUserLogout(CThostFtdcUserLogoutField *p,
39
187
  CThostFtdcRspInfoField *e, int id, bool last) {
188
+ if (last) {
189
+ std::lock_guard<std::mutex> sessionLock(sessionMutex_);
190
+ if (eid(e) == 0) {
191
+ // A successful logout is always conservative, even if it was initiated
192
+ // outside this wrapper or is a late callback from an older request.
193
+ invalidateSessionLocked();
194
+ } else if (responseMatchesLocked(SessionState::LogoutPending, id) ||
195
+ sessionState_ == SessionState::Ambiguous) {
196
+ invalidateSessionLocked();
197
+ }
198
+ }
40
199
  ch_->push(MD_RSP_USER_LOGOUT, id, last ? 1 : 0, eid(e), emsg(e),
41
200
  p ? SID_UserLogout : -1, p, p ? (int)sizeof(*p) : 0);
42
201
  }
@@ -49,17 +208,37 @@ void MdSpi::OnRspQryMulticastInstrument(CThostFtdcMulticastInstrumentField *p,
49
208
  }
50
209
 
51
210
  void MdSpi::OnRspError(CThostFtdcRspInfoField *e, int id, bool last) {
211
+ if (id > 0 && eid(e) != 0) {
212
+ std::lock_guard<std::mutex> sessionLock(sessionMutex_);
213
+ if (responseMatchesLocked(SessionState::LoginPending, id) ||
214
+ responseMatchesLocked(SessionState::LogoutPending, id))
215
+ invalidateSessionLocked();
216
+ }
52
217
  ch_->push(MD_RSP_ERROR, id, last ? 1 : 0, eid(e), emsg(e), -1, nullptr, 0);
53
218
  }
54
219
 
55
220
  void MdSpi::OnRspSubMarketData(CThostFtdcSpecificInstrumentField *p,
56
221
  CThostFtdcRspInfoField *e, int id, bool last) {
222
+ if (p) {
223
+ std::string instrumentId;
224
+ if (boundedCtpField(p->InstrumentID, instrumentId)) {
225
+ std::lock_guard<std::mutex> sessionLock(sessionMutex_);
226
+ finishSubscriptionLocked(instrumentId, true, eid(e) == 0);
227
+ }
228
+ }
57
229
  ch_->push(MD_RSP_SUB_MARKET_DATA, id, last ? 1 : 0, eid(e), emsg(e),
58
230
  p ? SID_SpecificInstrument : -1, p, p ? (int)sizeof(*p) : 0);
59
231
  }
60
232
 
61
233
  void MdSpi::OnRspUnSubMarketData(CThostFtdcSpecificInstrumentField *p,
62
234
  CThostFtdcRspInfoField *e, int id, bool last) {
235
+ if (p) {
236
+ std::string instrumentId;
237
+ if (boundedCtpField(p->InstrumentID, instrumentId)) {
238
+ std::lock_guard<std::mutex> sessionLock(sessionMutex_);
239
+ finishSubscriptionLocked(instrumentId, false, eid(e) == 0);
240
+ }
241
+ }
63
242
  ch_->push(MD_RSP_UNSUB_MARKET_DATA, id, last ? 1 : 0, eid(e), emsg(e),
64
243
  p ? SID_SpecificInstrument : -1, p, p ? (int)sizeof(*p) : 0);
65
244
  }
@@ -77,22 +256,50 @@ void MdSpi::OnRspUnSubForQuoteRsp(CThostFtdcSpecificInstrumentField *p,
77
256
  }
78
257
 
79
258
  void MdSpi::OnRtnDepthMarketData(CThostFtdcDepthMarketDataField *p) {
80
- // Load the api once: a concurrent close() (clearApi) must not let us deref a
81
- // freed api between the null-check and the call.
82
- CThostFtdcMdApi *api = api_.load(std::memory_order_relaxed);
83
- if (p && api) {
84
- const char *td = api->GetTradingDay();
85
- if (td)
86
- std::snprintf(p->TradingDay, sizeof(p->TradingDay), "%s", td);
87
- }
88
- // Evaluate armed triggers first (lowest tick-to-order latency), then publish.
259
+ // Update the latest-tick cache, evaluate armed triggers (lowest tick-to-order
260
+ // latency), then publish to the ring.
89
261
  if (p) {
90
- ArmRegistry *ar = armReg_.load(std::memory_order_relaxed);
91
- if (ar)
92
- ar->onTick(p->InstrumentID, p->BidPrice1, p->AskPrice1);
262
+ // The callback buffer belongs to the vendor API. Fill missing TradingDay on
263
+ // our own copy rather than mutating memory the provider may reuse.
264
+ CThostFtdcDepthMarketDataField tick = *p;
265
+ std::string instrumentId;
266
+ std::string tickTradingDay;
267
+ const bool fieldsValid = boundedCtpField(tick.InstrumentID, instrumentId) &&
268
+ !instrumentId.empty() &&
269
+ boundedCtpField(tick.TradingDay, tickTradingDay);
270
+ {
271
+ // Linearize the complete cache-update -> arm-evaluation operation against
272
+ // lifecycle invalidation. SnapshotCache's own mutex is released before
273
+ // onTick because armed risk checks may read the same snapshot source.
274
+ std::lock_guard<std::mutex> sessionLock(sessionMutex_);
275
+ if (fieldsValid && tickTradingDay.empty()) {
276
+ if (!tradingDay_.empty())
277
+ std::snprintf(tick.TradingDay, sizeof(tick.TradingDay), "%s",
278
+ tradingDay_.c_str());
279
+ }
280
+ SnapshotCache *sc = snap_.load(std::memory_order_acquire);
281
+ const bool accepted = fieldsValid &&
282
+ subscriptionAllowsLocked(instrumentId) && sc &&
283
+ sc->update(instrumentId, tick);
284
+ // The cache's authenticated epoch is also the mandate clock. A callback
285
+ // racing after disconnect/logout (or arriving before login) remains
286
+ // visible as a protocol event, but must never fire an armed order.
287
+ if (accepted) {
288
+ std::shared_ptr<ArmRegistry> ar;
289
+ {
290
+ std::lock_guard<std::mutex> lk(armRegistryMutex_);
291
+ ar = armReg_;
292
+ }
293
+ if (ar)
294
+ ar->onTick(instrumentId.c_str(), tick.BidPrice1, tick.AskPrice1);
295
+ }
296
+ }
297
+ ch_->push(MD_RTN_DEPTH_MARKET_DATA, 0, -1, 0, "", SID_DepthMarketData,
298
+ &tick, (int)sizeof(tick), true);
299
+ return;
93
300
  }
94
- ch_->push(MD_RTN_DEPTH_MARKET_DATA, 0, -1, 0, "", SID_DepthMarketData, p,
95
- p ? (int)sizeof(*p) : 0);
301
+ ch_->push(MD_RTN_DEPTH_MARKET_DATA, 0, -1, 0, "", SID_DepthMarketData,
302
+ nullptr, 0, true);
96
303
  }
97
304
 
98
305
  void MdSpi::OnRtnForQuoteRsp(CThostFtdcForQuoteRspField *p) {
@@ -11,7 +11,14 @@
11
11
  #include "ThostFtdcMdApi.h"
12
12
  #include "arm.h"
13
13
  #include "channel.h"
14
+ #include "snapshot.h"
14
15
  #include <atomic>
16
+ #include <deque>
17
+ #include <memory>
18
+ #include <mutex>
19
+ #include <string>
20
+ #include <unordered_map>
21
+ #include <vector>
15
22
 
16
23
  namespace ctp {
17
24
 
@@ -34,16 +41,32 @@ enum {
34
41
 
35
42
  class MdSpi : public CThostFtdcMdSpi {
36
43
  public:
37
- MdSpi(CThostFtdcMdApi *api, EventChannel *channel) : api_(api), ch_(channel) {}
44
+ explicit MdSpi(EventChannel *channel) : ch_(channel) {}
38
45
  ~MdSpi() {}
39
46
 
40
47
  // Feed depth ticks to a Trader's arm registry (or nullptr to detach).
41
- void setArmRegistry(ArmRegistry *r) { armReg_.store(r, std::memory_order_relaxed); }
42
-
43
- // Detach the api pointer before the owning MarketData releases it, so a
44
- // late/teardown callback (or the test tick hook) can't dereference a freed
45
- // api. Published atomically: OnRtnDepthMarketData reads it lock-free.
46
- void clearApi() { api_.store(nullptr, std::memory_order_relaxed); }
48
+ void setArmRegistry(std::shared_ptr<ArmRegistry> r) {
49
+ std::lock_guard<std::mutex> lk(armRegistryMutex_);
50
+ armReg_ = std::move(r);
51
+ }
52
+ // Latest-tick cache (LVC) updated on every depth tick (or nullptr to detach).
53
+ void setSnapshotCache(SnapshotCache *c) { snap_.store(c, std::memory_order_release); }
54
+ // Session-transition state is native because SimNow may echo requestId=0.
55
+ // Only one login/logout may be outstanding; a JS timeout poisons transitions
56
+ // until the next front callback so a late id-0 login cannot authenticate a
57
+ // newer attempt.
58
+ bool beginLogin(int requestId);
59
+ bool beginLogout(int requestId);
60
+ // Called by the JS idle timer. Returns true only when the timer won the
61
+ // native state race and poisoned the still-pending transition. If false, a
62
+ // final callback already changed state and its lossless row must be awaited.
63
+ bool timeoutSessionTransition(int requestId);
64
+ void abandonSessionTransition();
65
+ // End the current authenticated MD epoch and reset transition ambiguity.
66
+ // Reserved for concrete front transitions / close and immediate send failure.
67
+ void invalidateSession();
68
+ void noteSubscriptionRequest(const std::vector<std::string> &instrumentIds,
69
+ bool subscribe);
47
70
 
48
71
  void OnFrontConnected() override;
49
72
  void OnFrontDisconnected(int nReason) override;
@@ -71,9 +94,39 @@ public:
71
94
  void OnRtnForQuoteRsp(CThostFtdcForQuoteRspField *p) override;
72
95
 
73
96
  private:
74
- std::atomic<CThostFtdcMdApi *> api_;
97
+ enum class SessionState : uint8_t {
98
+ Inactive,
99
+ LoginPending,
100
+ Authenticated,
101
+ LogoutPending,
102
+ Ambiguous,
103
+ };
104
+ void invalidateSessionLocked(); // sessionMutex_ held
105
+ bool responseMatchesLocked(SessionState pendingState, int requestId) const;
75
106
  EventChannel *ch_;
76
- std::atomic<ArmRegistry *> armReg_{nullptr};
107
+ // Copy shared ownership before evaluating a tick. This makes replacing or
108
+ // detaching a registry safe even when a callback already started.
109
+ std::mutex armRegistryMutex_;
110
+ std::shared_ptr<ArmRegistry> armReg_;
111
+ std::atomic<SnapshotCache *> snap_{nullptr};
112
+ // Linearizes login/disconnect/logout against tick-to-arm evaluation. Once an
113
+ // invalidation callback returns, no earlier accepted tick can still fire.
114
+ std::mutex sessionMutex_;
115
+ // Protected by sessionMutex_.
116
+ SessionState sessionState_ = SessionState::Inactive;
117
+ int pendingSessionRequestId_ = 0;
118
+ std::string tradingDay_;
119
+ struct SubscriptionState {
120
+ uint64_t latestGeneration = 0;
121
+ bool desired = true;
122
+ std::deque<uint64_t> subscribeGenerations;
123
+ std::deque<uint64_t> unsubscribeGenerations;
124
+ };
125
+ uint64_t nextSubscriptionGeneration_ = 1;
126
+ std::unordered_map<std::string, SubscriptionState> subscriptions_;
127
+ bool subscriptionAllowsLocked(const std::string &instrumentId) const;
128
+ void finishSubscriptionLocked(const std::string &instrumentId,
129
+ bool subscribe, bool success);
77
130
  };
78
131
 
79
132
  } // namespace ctp
@@ -0,0 +1,75 @@
1
+ /*
2
+ * order_capability.h - the deliberately narrow ordinary-order capability.
3
+ *
4
+ * Local reservation/margin accounting models one single-instrument, immediate
5
+ * GFD limit order in the confirmed InvestorID. Every other InputOrder mode is
6
+ * rejected before it reaches CTP; accepting it as an "ordinary" order would
7
+ * silently claim risk coverage for dimensions the ledger does not represent.
8
+ */
9
+ #ifndef CTP_NATIVE_ORDER_CAPABILITY_H
10
+ #define CTP_NATIVE_ORDER_CAPABILITY_H
11
+
12
+ #include "ThostFtdcUserApiStruct.h"
13
+ #include "ctp_field.h"
14
+
15
+ #include <cmath>
16
+ #include <cstddef>
17
+ #include <string>
18
+
19
+ namespace ctp {
20
+
21
+ struct OrdinaryOrderIdentity {
22
+ std::string brokerId;
23
+ std::string investorId;
24
+ std::string orderRef;
25
+ std::string instrumentId;
26
+ };
27
+
28
+ inline bool decodeOrdinaryOrder(
29
+ const CThostFtdcInputOrderField &f, OrdinaryOrderIdentity &identity) {
30
+ std::string userId, gtdDate, businessUnit, exchangeId, investUnitId;
31
+ std::string accountId, currencyId, clientId, macAddress, ipAddress, memo;
32
+ if (!boundedCtpField(f.BrokerID, identity.brokerId) ||
33
+ !boundedCtpField(f.InvestorID, identity.investorId) ||
34
+ !boundedCtpField(f.OrderRef, identity.orderRef) ||
35
+ !boundedCtpField(f.UserID, userId) ||
36
+ !boundedCtpField(f.GTDDate, gtdDate) ||
37
+ !boundedCtpField(f.BusinessUnit, businessUnit) ||
38
+ !boundedCtpField(f.ExchangeID, exchangeId) ||
39
+ !boundedCtpField(f.InvestUnitID, investUnitId) ||
40
+ !boundedCtpField(f.AccountID, accountId) ||
41
+ !boundedCtpField(f.CurrencyID, currencyId) ||
42
+ !boundedCtpField(f.ClientID, clientId) ||
43
+ !boundedCtpField(f.MacAddress, macAddress) ||
44
+ !boundedCtpField(f.InstrumentID, identity.instrumentId) ||
45
+ !boundedCtpField(f.IPAddress, ipAddress) ||
46
+ !boundedCtpField(f.OrderMemo, memo))
47
+ return false;
48
+
49
+ const bool validHedge = f.CombHedgeFlag[0] == '1' ||
50
+ f.CombHedgeFlag[0] == '2' ||
51
+ f.CombHedgeFlag[0] == '3' ||
52
+ f.CombHedgeFlag[0] == '5' ||
53
+ f.CombHedgeFlag[0] == '6' ||
54
+ f.CombHedgeFlag[0] == '7';
55
+ return !identity.brokerId.empty() && !identity.investorId.empty() &&
56
+ !identity.orderRef.empty() && !identity.instrumentId.empty() &&
57
+ (f.Direction == '0' || f.Direction == '1') &&
58
+ f.CombOffsetFlag[0] >= '0' && f.CombOffsetFlag[0] <= '6' &&
59
+ f.CombOffsetFlag[1] == '\0' && validHedge &&
60
+ f.CombHedgeFlag[1] == '\0' && f.OrderPriceType == '2' &&
61
+ std::isfinite(f.LimitPrice) && f.LimitPrice > 0.0 &&
62
+ f.LimitPrice < 1e300 && f.VolumeTotalOriginal > 0 &&
63
+ f.TimeCondition == '3' && gtdDate.empty() &&
64
+ f.VolumeCondition == '1' && f.MinVolume == 1 &&
65
+ f.ContingentCondition == '1' && f.StopPrice == 0.0 &&
66
+ f.ForceCloseReason == '0' && f.IsAutoSuspend == 0 &&
67
+ businessUnit.empty() && f.RequestID == 0 &&
68
+ f.UserForceClose == 0 && f.IsSwapOrder == 0 &&
69
+ exchangeId.empty() && investUnitId.empty() && accountId.empty() &&
70
+ currencyId.empty() && clientId.empty() && f.SessionReqSeq == 0;
71
+ }
72
+
73
+ } // namespace ctp
74
+
75
+ #endif /* CTP_NATIVE_ORDER_CAPABILITY_H */