@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.
- package/CHANGELOG.md +67 -0
- package/README.md +52 -31
- package/README.zh-CN.md +42 -26
- package/RELEASING.md +78 -0
- package/binding.gyp +13 -13
- package/dist/client.d.ts +40 -15
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +241 -62
- package/dist/client.js.map +1 -1
- package/dist/codec.d.ts.map +1 -1
- package/dist/codec.js +84 -19
- package/dist/codec.js.map +1 -1
- package/dist/generated/structs.gen.d.ts +5461 -5461
- package/dist/generated/structs.gen.d.ts.map +1 -1
- package/dist/generated/trader.gen.d.ts.map +1 -1
- package/dist/generated/trader.gen.js +788 -94
- package/dist/generated/trader.gen.js.map +1 -1
- package/dist/index.cjs +1896 -420
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/market-data.d.ts +48 -21
- package/dist/market-data.d.ts.map +1 -1
- package/dist/market-data.js +165 -26
- package/dist/market-data.js.map +1 -1
- package/dist/native-binding.d.ts.map +1 -1
- package/dist/native-binding.js +5 -1
- package/dist/native-binding.js.map +1 -1
- package/dist/trader.d.ts +127 -79
- package/dist/trader.d.ts.map +1 -1
- package/dist/trader.js +788 -200
- package/dist/trader.js.map +1 -1
- package/dist/validation.d.ts +27 -0
- package/dist/validation.d.ts.map +1 -0
- package/dist/validation.js +85 -0
- package/dist/validation.js.map +1 -0
- package/docs/API.md +1437 -0
- package/docs/API.zh-CN.md +1278 -0
- package/docs/MIGRATION.md +54 -0
- package/docs/assets/validation.svg +27 -0
- package/docs/integration.md +60 -0
- package/docs/native-hooks.md +281 -0
- package/docs/native-hooks.zh-CN.md +205 -0
- package/docs/troubleshooting.md +257 -0
- package/docs/troubleshooting.zh-CN.md +220 -0
- package/package.json +14 -6
- package/prebuilds/linux-x64/@hitrading+ctp-node.node +0 -0
- package/prebuilds/win32-x64/@hitrading+ctp-node.node +0 -0
- package/scripts/bench-decode.mjs +37 -0
- package/scripts/bench-fullmarket-offline.mjs +207 -0
- package/scripts/stress-fullmarket.mjs +255 -0
- package/src/addon.cc +2 -2
- package/src/client.ts +263 -65
- package/src/codec.ts +86 -19
- package/src/generated/structs.gen.ts +5461 -5461
- package/src/generated/trader.gen.ts +309 -94
- package/src/generated/traderreq.gen.cc +194 -18
- package/src/generated/traderreq.gen.h +4 -0
- package/src/generated/traderspi.gen.cc +130 -10
- package/src/generated/traderspi.gen.h +4 -2
- package/src/index.ts +8 -1
- package/src/market-data.ts +219 -43
- package/src/native/arm.cc +114 -30
- package/src/native/arm.h +16 -4
- package/src/native/channel.cc +209 -81
- package/src/native/channel.h +65 -24
- package/src/native/ctp_field.h +23 -0
- package/src/native/mdapi.cc +621 -61
- package/src/native/mdspi.cc +221 -14
- package/src/native/mdspi.h +62 -9
- package/src/native/order_capability.h +75 -0
- package/src/native/risk.cc +2051 -205
- package/src/native/risk.h +450 -57
- package/src/native/shared_handle.h +37 -0
- package/src/native/snapshot.h +120 -0
- package/src/native/traderapi.cc +749 -170
- package/src/native-binding.ts +5 -1
- package/src/trader.ts +993 -229
- package/src/validation.ts +96 -0
- /package/{tradeapi → ctpsdk}/ThostFtdcMdApi.h +0 -0
- /package/{tradeapi → ctpsdk}/ThostFtdcTraderApi.h +0 -0
- /package/{tradeapi → ctpsdk}/ThostFtdcUserApiDataType.h +0 -0
- /package/{tradeapi → ctpsdk}/ThostFtdcUserApiStruct.h +0 -0
- /package/{tradeapi → ctpsdk}/error.dtd +0 -0
- /package/{tradeapi → ctpsdk}/error.xml +0 -0
- /package/{tradeapi → ctpsdk}/linux/thostmduserapi_se.so +0 -0
- /package/{tradeapi → ctpsdk}/linux/thosttraderapi_se.so +0 -0
- /package/{tradeapi → ctpsdk}/macos/thostmduserapi_se.framework/Versions/A/Headers/ThostFtdcMdApi.h +0 -0
- /package/{tradeapi → ctpsdk}/macos/thostmduserapi_se.framework/Versions/A/Headers/ThostFtdcUserApiDataType.h +0 -0
- /package/{tradeapi → ctpsdk}/macos/thostmduserapi_se.framework/Versions/A/Headers/ThostFtdcUserApiStruct.h +0 -0
- /package/{tradeapi → ctpsdk}/macos/thostmduserapi_se.framework/Versions/A/Resources/Info.plist +0 -0
- /package/{tradeapi → ctpsdk}/macos/thostmduserapi_se.framework/Versions/A/_CodeSignature/CodeResources +0 -0
- /package/{tradeapi → ctpsdk}/macos/thostmduserapi_se.framework/Versions/A/thostmduserapi_se +0 -0
- /package/{tradeapi → ctpsdk}/macos/thosttraderapi_se.framework/Versions/A/Headers/ThostFtdcTraderApi.h +0 -0
- /package/{tradeapi → ctpsdk}/macos/thosttraderapi_se.framework/Versions/A/Headers/ThostFtdcUserApiDataType.h +0 -0
- /package/{tradeapi → ctpsdk}/macos/thosttraderapi_se.framework/Versions/A/Headers/ThostFtdcUserApiStruct.h +0 -0
- /package/{tradeapi → ctpsdk}/macos/thosttraderapi_se.framework/Versions/A/Resources/Info.plist +0 -0
- /package/{tradeapi → ctpsdk}/macos/thosttraderapi_se.framework/Versions/A/_CodeSignature/CodeResources +0 -0
- /package/{tradeapi → ctpsdk}/macos/thosttraderapi_se.framework/Versions/A/thosttraderapi_se +0 -0
- /package/{tradeapi → ctpsdk}/windows/thostmduserapi_se.dll +0 -0
- /package/{tradeapi → ctpsdk}/windows/thostmduserapi_se.lib +0 -0
- /package/{tradeapi → ctpsdk}/windows/thosttraderapi_se.dll +0 -0
- /package/{tradeapi → ctpsdk}/windows/thosttraderapi_se.lib +0 -0
package/src/native/risk.cc
CHANGED
|
@@ -15,18 +15,64 @@ namespace ctp {
|
|
|
15
15
|
// trade) IS finite, so it slips past isfinite alone; 1e300 is far above any real
|
|
16
16
|
// value and far below DBL_MAX. Centralized so EVERY double entering the math
|
|
17
17
|
// rejects the sentinel uniformly: a split policy is exactly what let DBL_MAX
|
|
18
|
-
// poison
|
|
19
|
-
// 11/14). A sentinel/Inf multiplier or fill makes cost Inf and a later
|
|
18
|
+
// poison instrument metadata/onTrade after the reference-price path was guarded
|
|
19
|
+
// (rounds 11/14). A sentinel/Inf multiplier or fill makes cost Inf and a later
|
|
20
20
|
// proportional close-release Inf-Inf = NaN, and NaN > cap is false -> the cost
|
|
21
21
|
// cap is silently voided. Reject at the door instead.
|
|
22
22
|
static inline bool sanePositive(double x) {
|
|
23
23
|
return std::isfinite(x) && x > 0.0 && x < 1e300;
|
|
24
24
|
}
|
|
25
25
|
|
|
26
|
-
|
|
26
|
+
static inline bool saneLots(double x) {
|
|
27
|
+
return std::isfinite(x) && x > 0.0 && x <= 2147483647.0 &&
|
|
28
|
+
std::floor(x) == x;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
static inline bool saneNonNegativeLots(double x) {
|
|
32
|
+
return x == 0.0 || saneLots(x);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
static inline bool validHedgeFlag(char flag) {
|
|
36
|
+
return flag == '1' || flag == '2' || flag == '3' || flag == '5' ||
|
|
37
|
+
flag == '6' || flag == '7';
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
static inline bool terminalOrderStatus(char status) {
|
|
41
|
+
return status == '0' || status == '2' || status == '4' || status == '5';
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
static inline bool validTradingDay(const std::string &day) {
|
|
45
|
+
if (day.size() != 8)
|
|
46
|
+
return false;
|
|
47
|
+
for (char c : day)
|
|
48
|
+
if (c < '0' || c > '9')
|
|
49
|
+
return false;
|
|
50
|
+
const int year = std::stoi(day.substr(0, 4));
|
|
51
|
+
const int month = std::stoi(day.substr(4, 2));
|
|
52
|
+
const int date = std::stoi(day.substr(6, 2));
|
|
53
|
+
if (year == 0 || month < 1 || month > 12)
|
|
54
|
+
return false;
|
|
55
|
+
static constexpr int daysByMonth[] = {
|
|
56
|
+
0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
|
|
57
|
+
int maxDate = daysByMonth[month];
|
|
58
|
+
const bool leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
|
|
59
|
+
if (month == 2 && leap)
|
|
60
|
+
++maxDate;
|
|
61
|
+
return date >= 1 && date <= maxDate;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
static inline double positiveLimitOrDisabled(double x) {
|
|
65
|
+
// Exactly zero disables a limit. Negative/NaN/Inf is never a valid limit:
|
|
66
|
+
// make it fail closed for native callers that bypass the TS guards.
|
|
67
|
+
if (!std::isfinite(x) || x < 0.0)
|
|
68
|
+
return std::numeric_limits<double>::min();
|
|
69
|
+
return x > 0.0 ? x : 0.0;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// Keep an accumulated open-margin running sum finite. Each fill's margin passes the
|
|
27
73
|
// per-fill backstop, but a long chain of huge (test-hook / absurd-seed) fills can
|
|
28
74
|
// still overflow the SUM to +Inf, and a later proportional close (Inf - Inf)
|
|
29
|
-
// would yield NaN, silently voiding the
|
|
75
|
+
// would yield NaN, silently voiding the margin cap (NaN > cap is false). Pin an
|
|
30
76
|
// overflowed sum to the largest finite double: it stays above EVERY finite
|
|
31
77
|
// configured cap (so it keeps blocking - +Inf would block too but breaks the
|
|
32
78
|
// proportional close) while keeping that close arithmetic finite. Unreachable
|
|
@@ -36,23 +82,23 @@ static inline void clampFiniteCost(double &cost) {
|
|
|
36
82
|
cost = std::numeric_limits<double>::max();
|
|
37
83
|
}
|
|
38
84
|
|
|
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
85
|
void RateLimiter::configure(double ratePerSec, double burst) {
|
|
53
86
|
std::lock_guard<std::mutex> lk(m_);
|
|
54
|
-
|
|
55
|
-
|
|
87
|
+
if (!std::isfinite(ratePerSec) || !std::isfinite(burst) ||
|
|
88
|
+
ratePerSec < 0.0 || burst < 0.0) {
|
|
89
|
+
rate_ = std::numeric_limits<double>::min();
|
|
90
|
+
burst_ = 1.0;
|
|
91
|
+
tokens_ = 0.0; // malformed native config fails closed
|
|
92
|
+
last_ = std::chrono::steady_clock::now();
|
|
93
|
+
initialized_ = true;
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
rate_ = positiveLimitOrDisabled(ratePerSec);
|
|
97
|
+
burst_ = positiveLimitOrDisabled(burst);
|
|
98
|
+
if (burst_ <= 0.0)
|
|
99
|
+
burst_ = rate_; // default burst = 1s worth of tokens
|
|
100
|
+
if (rate_ > 0.0)
|
|
101
|
+
burst_ = std::max(1.0, burst_); // a bucket below one token can never fire
|
|
56
102
|
tokens_ = burst_;
|
|
57
103
|
last_ = std::chrono::steady_clock::now();
|
|
58
104
|
initialized_ = true;
|
|
@@ -81,48 +127,448 @@ bool RateLimiter::tryAcquire() {
|
|
|
81
127
|
return false;
|
|
82
128
|
}
|
|
83
129
|
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
130
|
+
bool RateLimiter::enabled() const {
|
|
131
|
+
std::lock_guard<std::mutex> lk(m_);
|
|
132
|
+
return rate_ > 0.0;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
void RiskEngine::configure(const RiskLimits &cfg) {
|
|
136
|
+
std::lock_guard<RiskSendMutex> sendBarrier(sendModeMutex_);
|
|
137
|
+
const bool invalid =
|
|
138
|
+
cfg.maxOrderVolume < 0 || !std::isfinite(cfg.maxPriceDeviation) ||
|
|
139
|
+
cfg.maxPriceDeviation < 0.0 || !std::isfinite(cfg.maxNotional) ||
|
|
140
|
+
cfg.maxNotional < 0.0 || !std::isfinite(cfg.maxOrdersPerSec) ||
|
|
141
|
+
cfg.maxOrdersPerSec < 0.0 || !std::isfinite(cfg.orderBurst) ||
|
|
142
|
+
cfg.orderBurst < 0.0 || !std::isfinite(cfg.maxCloseOrdersPerSec) ||
|
|
143
|
+
cfg.maxCloseOrdersPerSec < 0.0 || !std::isfinite(cfg.closeOrderBurst) ||
|
|
144
|
+
cfg.closeOrderBurst < 0.0 || !std::isfinite(cfg.maxAccountMargin) ||
|
|
145
|
+
cfg.maxAccountMargin < 0.0 || !std::isfinite(cfg.maxReferenceAgeMs) ||
|
|
146
|
+
cfg.maxReferenceAgeMs <= 0.0;
|
|
147
|
+
invalidConfig_.store(invalid, std::memory_order_release);
|
|
148
|
+
maxOrderVolume_.store(cfg.maxOrderVolume > 0 ? cfg.maxOrderVolume : 0,
|
|
149
|
+
std::memory_order_relaxed);
|
|
150
|
+
maxPriceDeviation_.store(positiveLimitOrDisabled(cfg.maxPriceDeviation),
|
|
151
|
+
std::memory_order_relaxed);
|
|
152
|
+
maxNotional_.store(positiveLimitOrDisabled(cfg.maxNotional),
|
|
153
|
+
std::memory_order_relaxed);
|
|
154
|
+
maxAccountMargin_.store(positiveLimitOrDisabled(cfg.maxAccountMargin),
|
|
155
|
+
std::memory_order_relaxed);
|
|
156
|
+
maxReferenceAgeMs_.store(invalid ? 0.0 : cfg.maxReferenceAgeMs,
|
|
157
|
+
std::memory_order_relaxed);
|
|
89
158
|
limiter_.configure(cfg.maxOrdersPerSec, cfg.orderBurst);
|
|
159
|
+
closeLimiter_.configure(cfg.maxCloseOrdersPerSec, cfg.closeOrderBurst);
|
|
90
160
|
}
|
|
91
161
|
|
|
92
|
-
void RiskEngine::
|
|
93
|
-
|
|
162
|
+
void RiskEngine::reduceOnly() {
|
|
163
|
+
std::lock_guard<RiskSendMutex> lk(sendModeMutex_);
|
|
164
|
+
mode_.store(RiskMode::ReduceOnly, std::memory_order_release);
|
|
165
|
+
}
|
|
166
|
+
void RiskEngine::haltAll() {
|
|
167
|
+
std::lock_guard<RiskSendMutex> lk(sendModeMutex_);
|
|
168
|
+
mode_.store(RiskMode::HaltAll, std::memory_order_release);
|
|
169
|
+
}
|
|
170
|
+
void RiskEngine::resume() {
|
|
171
|
+
std::lock_guard<RiskSendMutex> lk(sendModeMutex_);
|
|
172
|
+
mode_.store(RiskMode::Normal, std::memory_order_release);
|
|
173
|
+
}
|
|
94
174
|
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
if (!
|
|
102
|
-
|
|
175
|
+
std::unique_lock<RiskSendMutex> RiskEngine::acquireOrderSend(bool isOpen,
|
|
176
|
+
bool &allowed) {
|
|
177
|
+
std::unique_lock<RiskSendMutex> lock(sendModeMutex_);
|
|
178
|
+
const RiskMode current = mode_.load(std::memory_order_acquire);
|
|
179
|
+
allowed = current != RiskMode::HaltAll &&
|
|
180
|
+
!(current == RiskMode::ReduceOnly && isOpen);
|
|
181
|
+
if (!allowed)
|
|
182
|
+
lastReason_ = current == RiskMode::HaltAll
|
|
183
|
+
? "all order inserts halted"
|
|
184
|
+
: "opening orders blocked in reduce-only mode";
|
|
185
|
+
return lock;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
std::unique_lock<RiskSendMutex> RiskEngine::acquireOrderSendForAccount(
|
|
189
|
+
bool isOpen, const std::string &brokerId,
|
|
190
|
+
const std::string &investorId, bool &allowed) {
|
|
191
|
+
std::unique_lock<RiskSendMutex> lock(sendModeMutex_);
|
|
192
|
+
const RiskMode current = mode_.load(std::memory_order_acquire);
|
|
193
|
+
allowed = current != RiskMode::HaltAll &&
|
|
194
|
+
!(current == RiskMode::ReduceOnly && isOpen);
|
|
195
|
+
if (allowed) {
|
|
196
|
+
std::lock_guard<std::mutex> account(posMutex_);
|
|
197
|
+
allowed = accountScopeLocked(brokerId, investorId) == AccountScope::Current;
|
|
198
|
+
if (!allowed)
|
|
199
|
+
lastReason_ = "order account does not match confirmed session";
|
|
200
|
+
} else {
|
|
201
|
+
lastReason_ = current == RiskMode::HaltAll
|
|
202
|
+
? "all order inserts halted"
|
|
203
|
+
: "opening orders blocked in reduce-only mode";
|
|
204
|
+
}
|
|
205
|
+
return lock;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
void RiskEngine::setMdSnapshot(std::shared_ptr<const RefPriceSource> source) {
|
|
103
209
|
std::lock_guard<std::mutex> lk(refMutex_);
|
|
104
|
-
|
|
210
|
+
mdSnap_ = std::move(source);
|
|
105
211
|
}
|
|
106
212
|
|
|
107
213
|
double RiskEngine::refPrice(const std::string &instrumentId) const {
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
214
|
+
// Read the deviation reference from the live MD snapshot (in C++). Copy the
|
|
215
|
+
// shared_ptr under our lock, then query outside it (the cache has its own
|
|
216
|
+
// mutex); no nested locking, and a concurrent detach can't free it mid-read.
|
|
217
|
+
// A non-finite / DBL_MAX "unset" last price is rejected here (not in the cache)
|
|
218
|
+
// so a sentinel reference can't make |price-ref|/ref == 1.0 and falsely block
|
|
219
|
+
// every order. An enabled deviation guard fails closed on a 0 reference.
|
|
220
|
+
std::shared_ptr<const RefPriceSource> snap;
|
|
221
|
+
{
|
|
222
|
+
std::lock_guard<std::mutex> lk(refMutex_);
|
|
223
|
+
snap = mdSnap_;
|
|
224
|
+
}
|
|
225
|
+
if (!snap)
|
|
226
|
+
return 0.0;
|
|
227
|
+
double px = 0.0;
|
|
228
|
+
uint64_t age = 0;
|
|
229
|
+
if (!snap->quote(instrumentId, px, age))
|
|
230
|
+
return 0.0;
|
|
231
|
+
if (!sanePositive(px))
|
|
232
|
+
return 0.0;
|
|
233
|
+
const double maxAge = maxReferenceAgeMs_.load(std::memory_order_relaxed);
|
|
234
|
+
if (maxAge >= static_cast<double>(std::numeric_limits<uint64_t>::max()))
|
|
235
|
+
return px;
|
|
236
|
+
return age <= static_cast<uint64_t>(maxAge) ? px : 0.0;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
void RiskEngine::setInstrument(const std::string &instrumentId, double mult,
|
|
240
|
+
char productClass) {
|
|
241
|
+
if (instrumentId.empty())
|
|
242
|
+
return;
|
|
243
|
+
// Metadata changes can increase the computed exposure of a just-reserved
|
|
244
|
+
// order. Serialize the refresh with the same final barrier as cap changes so
|
|
245
|
+
// no order is sent using a half-old margin model.
|
|
246
|
+
std::lock_guard<RiskSendMutex> send(sendModeMutex_);
|
|
247
|
+
std::lock_guard<std::mutex> lk(posMutex_);
|
|
248
|
+
if (!sanePositive(mult)) {
|
|
249
|
+
multipliers_.erase(instrumentId);
|
|
250
|
+
futuresMarginFormula_.erase(instrumentId);
|
|
251
|
+
invalidateHeldCostsLocked(instrumentId);
|
|
252
|
+
refreshReservationCostsLocked(instrumentId);
|
|
253
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
multipliers_[instrumentId] = mult;
|
|
257
|
+
// Futures and TAS use the futures margin schedule represented here. Options,
|
|
258
|
+
// combinations and spot products require product-specific fields/formulas.
|
|
259
|
+
futuresMarginFormula_[instrumentId] =
|
|
260
|
+
productClass == '1' || productClass == '7';
|
|
261
|
+
invalidateHeldCostsLocked(instrumentId);
|
|
262
|
+
refreshReservationCostsLocked(instrumentId);
|
|
263
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
void RiskEngine::invalidateInstrument(const std::string &instrumentId) {
|
|
267
|
+
std::lock_guard<RiskSendMutex> send(sendModeMutex_);
|
|
268
|
+
std::lock_guard<std::mutex> lk(posMutex_);
|
|
269
|
+
if (instrumentId.empty()) {
|
|
270
|
+
multipliers_.clear();
|
|
271
|
+
futuresMarginFormula_.clear();
|
|
272
|
+
invalidateHeldCostsLocked("");
|
|
273
|
+
refreshAllReservationCostsLocked();
|
|
274
|
+
} else {
|
|
275
|
+
multipliers_.erase(instrumentId);
|
|
276
|
+
futuresMarginFormula_.erase(instrumentId);
|
|
277
|
+
invalidateHeldCostsLocked(instrumentId);
|
|
278
|
+
refreshReservationCostsLocked(instrumentId);
|
|
279
|
+
}
|
|
280
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
111
281
|
}
|
|
112
282
|
|
|
113
|
-
void RiskEngine::
|
|
283
|
+
void RiskEngine::setMarginScheduleLocked(
|
|
284
|
+
const std::string &instrumentId, char hedgeFlag, double longByMoney,
|
|
285
|
+
double longByVolume, double shortByMoney, double shortByVolume,
|
|
286
|
+
bool isRelative) {
|
|
287
|
+
auto valid = [](double x) {
|
|
288
|
+
return std::isfinite(x) && x >= 0.0 && x < 1e300;
|
|
289
|
+
};
|
|
290
|
+
if (instrumentId.empty() || !validHedgeFlag(hedgeFlag))
|
|
291
|
+
return;
|
|
292
|
+
const std::string key = marginKey(instrumentId, hedgeFlag);
|
|
293
|
+
const bool usable = valid(longByMoney) && valid(longByVolume) &&
|
|
294
|
+
valid(shortByMoney) && valid(shortByVolume) &&
|
|
295
|
+
(isRelative ||
|
|
296
|
+
((longByMoney > 0.0 || longByVolume > 0.0) &&
|
|
297
|
+
(shortByMoney > 0.0 || shortByVolume > 0.0)));
|
|
298
|
+
if (usable)
|
|
299
|
+
marginRates_[key] = MarginSchedule{longByMoney, longByVolume, shortByMoney,
|
|
300
|
+
shortByVolume, isRelative};
|
|
301
|
+
else
|
|
302
|
+
marginRates_.erase(key);
|
|
303
|
+
invalidateHeldCostsLocked(instrumentId);
|
|
304
|
+
refreshReservationCostsLocked(instrumentId);
|
|
305
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
void RiskEngine::setMarginSchedule(const std::string &instrumentId,
|
|
309
|
+
char hedgeFlag, double longByMoney,
|
|
310
|
+
double longByVolume, double shortByMoney,
|
|
311
|
+
double shortByVolume, bool isRelative) {
|
|
312
|
+
std::lock_guard<RiskSendMutex> send(sendModeMutex_);
|
|
114
313
|
std::lock_guard<std::mutex> lk(posMutex_);
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
314
|
+
setMarginScheduleLocked(instrumentId, hedgeFlag, longByMoney, longByVolume,
|
|
315
|
+
shortByMoney, shortByVolume, isRelative);
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
void RiskEngine::setExchangeMarginScheduleLocked(
|
|
319
|
+
const std::string &instrumentId, char hedgeFlag, double longByMoney,
|
|
320
|
+
double longByVolume, double shortByMoney, double shortByVolume) {
|
|
321
|
+
auto valid = [](double x) {
|
|
322
|
+
return std::isfinite(x) && x >= 0.0 && x < 1e300;
|
|
323
|
+
};
|
|
324
|
+
if (instrumentId.empty() || !validHedgeFlag(hedgeFlag))
|
|
325
|
+
return;
|
|
326
|
+
const std::string key = marginKey(instrumentId, hedgeFlag);
|
|
327
|
+
const bool usable = valid(longByMoney) && valid(longByVolume) &&
|
|
328
|
+
valid(shortByMoney) && valid(shortByVolume) &&
|
|
329
|
+
(longByMoney > 0.0 || longByVolume > 0.0) &&
|
|
330
|
+
(shortByMoney > 0.0 || shortByVolume > 0.0);
|
|
331
|
+
if (usable)
|
|
332
|
+
exchangeMarginRates_[key] = MarginSchedule{
|
|
333
|
+
longByMoney, longByVolume, shortByMoney, shortByVolume, false};
|
|
334
|
+
else
|
|
335
|
+
exchangeMarginRates_.erase(key);
|
|
336
|
+
invalidateHeldCostsLocked(instrumentId);
|
|
337
|
+
refreshReservationCostsLocked(instrumentId);
|
|
338
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
119
339
|
}
|
|
120
340
|
|
|
121
|
-
void RiskEngine::
|
|
122
|
-
|
|
341
|
+
void RiskEngine::setExchangeMarginSchedule(
|
|
342
|
+
const std::string &instrumentId, char hedgeFlag, double longByMoney,
|
|
343
|
+
double longByVolume, double shortByMoney, double shortByVolume) {
|
|
344
|
+
std::lock_guard<RiskSendMutex> send(sendModeMutex_);
|
|
123
345
|
std::lock_guard<std::mutex> lk(posMutex_);
|
|
124
|
-
|
|
125
|
-
|
|
346
|
+
setExchangeMarginScheduleLocked(instrumentId, hedgeFlag, longByMoney,
|
|
347
|
+
longByVolume, shortByMoney, shortByVolume);
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
void RiskEngine::invalidateMarginSchedules(const std::string &instrumentId,
|
|
351
|
+
char hedgeFlag) {
|
|
352
|
+
std::lock_guard<RiskSendMutex> send(sendModeMutex_);
|
|
353
|
+
std::lock_guard<std::mutex> lk(posMutex_);
|
|
354
|
+
if (instrumentId.empty()) {
|
|
355
|
+
marginRates_.clear();
|
|
356
|
+
exchangeMarginRates_.clear();
|
|
357
|
+
invalidateHeldCostsLocked("");
|
|
358
|
+
refreshAllReservationCostsLocked();
|
|
359
|
+
} else {
|
|
360
|
+
const std::string key = marginKey(instrumentId, hedgeFlag);
|
|
361
|
+
marginRates_.erase(key);
|
|
362
|
+
exchangeMarginRates_.erase(key);
|
|
363
|
+
invalidateHeldCostsLocked(instrumentId);
|
|
364
|
+
refreshReservationCostsLocked(instrumentId);
|
|
365
|
+
}
|
|
366
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
void RiskEngine::invalidateExchangeMarginSchedule(
|
|
370
|
+
const std::string &instrumentId, char hedgeFlag) {
|
|
371
|
+
std::lock_guard<RiskSendMutex> send(sendModeMutex_);
|
|
372
|
+
std::lock_guard<std::mutex> lk(posMutex_);
|
|
373
|
+
if (instrumentId.empty()) {
|
|
374
|
+
exchangeMarginRates_.clear();
|
|
375
|
+
invalidateHeldCostsLocked("");
|
|
376
|
+
refreshAllReservationCostsLocked();
|
|
377
|
+
} else {
|
|
378
|
+
exchangeMarginRates_.erase(marginKey(instrumentId, hedgeFlag));
|
|
379
|
+
invalidateHeldCostsLocked(instrumentId);
|
|
380
|
+
refreshReservationCostsLocked(instrumentId);
|
|
381
|
+
}
|
|
382
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
void RiskEngine::beginMarginScheduleQuery(
|
|
386
|
+
int requestId, bool exchange, const std::string &instrumentId,
|
|
387
|
+
char hedgeFlag, const std::string &brokerId,
|
|
388
|
+
const std::string &investorId) {
|
|
389
|
+
std::lock_guard<RiskSendMutex> send(sendModeMutex_);
|
|
390
|
+
std::lock_guard<std::mutex> lk(posMutex_);
|
|
391
|
+
activeMarginQueryRequestId_ = requestId > 0 ? requestId : 0;
|
|
392
|
+
activeMarginQueryKind_ = requestId > 0
|
|
393
|
+
? (exchange ? MarginQueryKind::Exchange
|
|
394
|
+
: MarginQueryKind::Investor)
|
|
395
|
+
: MarginQueryKind::None;
|
|
396
|
+
activeMarginQueryInstrument_ = instrumentId;
|
|
397
|
+
activeMarginQueryHedgeFlag_ = hedgeFlag;
|
|
398
|
+
stagedMarginRates_.clear();
|
|
399
|
+
const bool brokerMatches = brokerId.empty() ||
|
|
400
|
+
(!myBrokerId_.empty() && brokerId == myBrokerId_);
|
|
401
|
+
const bool investorMatches = exchange || investorId.empty() ||
|
|
402
|
+
(!myInvestorId_.empty() &&
|
|
403
|
+
investorId == myInvestorId_);
|
|
404
|
+
activeMarginQueryAuthorized_ = requestId > 0 && sessionIdentityKnown_ &&
|
|
405
|
+
brokerMatches && investorMatches &&
|
|
406
|
+
(hedgeFlag == '\0' ||
|
|
407
|
+
validHedgeFlag(hedgeFlag));
|
|
408
|
+
if (!activeMarginQueryAuthorized_)
|
|
409
|
+
return;
|
|
410
|
+
auto eraseInstrument = [&](auto &rates) {
|
|
411
|
+
if (instrumentId.empty()) {
|
|
412
|
+
rates.clear();
|
|
413
|
+
return;
|
|
414
|
+
}
|
|
415
|
+
if (hedgeFlag != '\0') {
|
|
416
|
+
rates.erase(marginKey(instrumentId, hedgeFlag));
|
|
417
|
+
return;
|
|
418
|
+
}
|
|
419
|
+
const std::string prefix = instrumentId + "|";
|
|
420
|
+
for (auto it = rates.begin(); it != rates.end();) {
|
|
421
|
+
if (it->first.rfind(prefix, 0) == 0)
|
|
422
|
+
it = rates.erase(it);
|
|
423
|
+
else
|
|
424
|
+
++it;
|
|
425
|
+
}
|
|
426
|
+
};
|
|
427
|
+
if (instrumentId.empty()) {
|
|
428
|
+
if (exchange) {
|
|
429
|
+
exchangeMarginRates_.clear();
|
|
430
|
+
} else {
|
|
431
|
+
marginRates_.clear();
|
|
432
|
+
exchangeMarginRates_.clear();
|
|
433
|
+
}
|
|
434
|
+
invalidateHeldCostsLocked("");
|
|
435
|
+
refreshAllReservationCostsLocked();
|
|
436
|
+
} else {
|
|
437
|
+
if (exchange) {
|
|
438
|
+
eraseInstrument(exchangeMarginRates_);
|
|
439
|
+
} else {
|
|
440
|
+
eraseInstrument(marginRates_);
|
|
441
|
+
// A new relative investor row may not combine with an exchange base from
|
|
442
|
+
// an older refresh generation.
|
|
443
|
+
eraseInstrument(exchangeMarginRates_);
|
|
444
|
+
}
|
|
445
|
+
invalidateHeldCostsLocked(instrumentId);
|
|
446
|
+
refreshReservationCostsLocked(instrumentId);
|
|
447
|
+
}
|
|
448
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
void RiskEngine::applyInvestorMarginSchedule(
|
|
452
|
+
int requestId, const std::string &brokerId,
|
|
453
|
+
const std::string &investorId, const std::string &investUnitId,
|
|
454
|
+
const std::string &instrumentId, char hedgeFlag, double longByMoney,
|
|
455
|
+
double longByVolume, double shortByMoney, double shortByVolume,
|
|
456
|
+
bool isRelative) {
|
|
457
|
+
std::lock_guard<RiskSendMutex> send(sendModeMutex_);
|
|
458
|
+
std::lock_guard<std::mutex> lk(posMutex_);
|
|
459
|
+
if (requestId <= 0 || requestId != activeMarginQueryRequestId_ ||
|
|
460
|
+
activeMarginQueryKind_ != MarginQueryKind::Investor ||
|
|
461
|
+
!activeMarginQueryAuthorized_ || !sessionIdentityKnown_ ||
|
|
462
|
+
accountScopeLocked(brokerId, investorId) != AccountScope::Current ||
|
|
463
|
+
!investUnitId.empty() ||
|
|
464
|
+
(!activeMarginQueryInstrument_.empty() &&
|
|
465
|
+
instrumentId != activeMarginQueryInstrument_) ||
|
|
466
|
+
(activeMarginQueryHedgeFlag_ != '\0' &&
|
|
467
|
+
hedgeFlag != activeMarginQueryHedgeFlag_))
|
|
468
|
+
return;
|
|
469
|
+
const auto valid = [](double value) {
|
|
470
|
+
return std::isfinite(value) && value >= 0.0 && value < 1e300;
|
|
471
|
+
};
|
|
472
|
+
const bool usable = validHedgeFlag(hedgeFlag) && !instrumentId.empty() &&
|
|
473
|
+
valid(longByMoney) && valid(longByVolume) &&
|
|
474
|
+
valid(shortByMoney) && valid(shortByVolume) &&
|
|
475
|
+
(isRelative ||
|
|
476
|
+
((longByMoney > 0.0 || longByVolume > 0.0) &&
|
|
477
|
+
(shortByMoney > 0.0 || shortByVolume > 0.0)));
|
|
478
|
+
const std::string key = marginKey(instrumentId, hedgeFlag);
|
|
479
|
+
if (usable)
|
|
480
|
+
stagedMarginRates_[key] = MarginSchedule{
|
|
481
|
+
longByMoney, longByVolume, shortByMoney, shortByVolume, isRelative};
|
|
482
|
+
else
|
|
483
|
+
stagedMarginRates_.erase(key);
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
void RiskEngine::applyExchangeMarginSchedule(
|
|
487
|
+
int requestId, const std::string &brokerId,
|
|
488
|
+
const std::string &instrumentId, char hedgeFlag, double longByMoney,
|
|
489
|
+
double longByVolume, double shortByMoney, double shortByVolume) {
|
|
490
|
+
std::lock_guard<RiskSendMutex> send(sendModeMutex_);
|
|
491
|
+
std::lock_guard<std::mutex> lk(posMutex_);
|
|
492
|
+
if (requestId <= 0 || requestId != activeMarginQueryRequestId_ ||
|
|
493
|
+
activeMarginQueryKind_ != MarginQueryKind::Exchange ||
|
|
494
|
+
!activeMarginQueryAuthorized_ || !sessionIdentityKnown_ ||
|
|
495
|
+
myBrokerId_.empty() || brokerId != myBrokerId_ ||
|
|
496
|
+
(!activeMarginQueryInstrument_.empty() &&
|
|
497
|
+
instrumentId != activeMarginQueryInstrument_) ||
|
|
498
|
+
(activeMarginQueryHedgeFlag_ != '\0' &&
|
|
499
|
+
hedgeFlag != activeMarginQueryHedgeFlag_))
|
|
500
|
+
return;
|
|
501
|
+
const auto valid = [](double value) {
|
|
502
|
+
return std::isfinite(value) && value >= 0.0 && value < 1e300;
|
|
503
|
+
};
|
|
504
|
+
const bool usable = validHedgeFlag(hedgeFlag) && !instrumentId.empty() &&
|
|
505
|
+
valid(longByMoney) && valid(longByVolume) &&
|
|
506
|
+
valid(shortByMoney) && valid(shortByVolume) &&
|
|
507
|
+
(longByMoney > 0.0 || longByVolume > 0.0) &&
|
|
508
|
+
(shortByMoney > 0.0 || shortByVolume > 0.0);
|
|
509
|
+
const std::string key = marginKey(instrumentId, hedgeFlag);
|
|
510
|
+
if (usable)
|
|
511
|
+
stagedMarginRates_[key] = MarginSchedule{
|
|
512
|
+
longByMoney, longByVolume, shortByMoney, shortByVolume, false};
|
|
513
|
+
else
|
|
514
|
+
stagedMarginRates_.erase(key);
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
void RiskEngine::finishMarginScheduleQuery(int requestId, bool success) {
|
|
518
|
+
std::lock_guard<RiskSendMutex> send(sendModeMutex_);
|
|
519
|
+
std::lock_guard<std::mutex> lk(posMutex_);
|
|
520
|
+
if (requestId <= 0 || requestId != activeMarginQueryRequestId_)
|
|
521
|
+
return;
|
|
522
|
+
if (success && activeMarginQueryAuthorized_) {
|
|
523
|
+
auto &target = activeMarginQueryKind_ == MarginQueryKind::Exchange
|
|
524
|
+
? exchangeMarginRates_
|
|
525
|
+
: marginRates_;
|
|
526
|
+
for (const auto &entry : stagedMarginRates_)
|
|
527
|
+
target[entry.first] = entry.second;
|
|
528
|
+
invalidateHeldCostsLocked(activeMarginQueryInstrument_);
|
|
529
|
+
if (activeMarginQueryInstrument_.empty())
|
|
530
|
+
refreshAllReservationCostsLocked();
|
|
531
|
+
else
|
|
532
|
+
refreshReservationCostsLocked(activeMarginQueryInstrument_);
|
|
533
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
534
|
+
}
|
|
535
|
+
activeMarginQueryRequestId_ = 0;
|
|
536
|
+
activeMarginQueryKind_ = MarginQueryKind::None;
|
|
537
|
+
activeMarginQueryAuthorized_ = false;
|
|
538
|
+
activeMarginQueryInstrument_.clear();
|
|
539
|
+
activeMarginQueryHedgeFlag_ = '\0';
|
|
540
|
+
stagedMarginRates_.clear();
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
bool RiskEngine::setInstrumentPositionLimits(
|
|
544
|
+
const std::vector<InstrumentPositionLimitUpdate> &updates) {
|
|
545
|
+
for (const auto &u : updates) {
|
|
546
|
+
const auto validLimit = [](double value) {
|
|
547
|
+
return std::isfinite(value) && value >= 0.0 &&
|
|
548
|
+
(value == 0.0 || (std::floor(value) == value &&
|
|
549
|
+
value <= 2147483647.0));
|
|
550
|
+
};
|
|
551
|
+
if (u.instrumentId.empty() || (!u.updateLong && !u.updateShort) ||
|
|
552
|
+
(u.updateLong && !validLimit(u.longLimit)) ||
|
|
553
|
+
(u.updateShort && !validLimit(u.shortLimit)))
|
|
554
|
+
return false;
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
// A tightening call must not return while an order that violates a new cap
|
|
558
|
+
// is between its last local check and the vendor API call. The whole batch is
|
|
559
|
+
// committed under the same barrier, so callers never expose a partial config.
|
|
560
|
+
std::lock_guard<RiskSendMutex> send(sendModeMutex_);
|
|
561
|
+
std::lock_guard<std::mutex> lk(posMutex_);
|
|
562
|
+
for (const auto &u : updates) {
|
|
563
|
+
VolCap &cap = maxPositionVol_[u.instrumentId];
|
|
564
|
+
if (u.updateLong)
|
|
565
|
+
cap.longMax = positiveLimitOrDisabled(u.longLimit);
|
|
566
|
+
if (u.updateShort)
|
|
567
|
+
cap.shortMax = positiveLimitOrDisabled(u.shortLimit);
|
|
568
|
+
if (cap.longMax <= 0.0 && cap.shortMax <= 0.0)
|
|
569
|
+
maxPositionVol_.erase(u.instrumentId);
|
|
570
|
+
}
|
|
571
|
+
return true;
|
|
126
572
|
}
|
|
127
573
|
|
|
128
574
|
double RiskEngine::multiplierLocked(const std::string &instrumentId) const {
|
|
@@ -130,98 +576,851 @@ double RiskEngine::multiplierLocked(const std::string &instrumentId) const {
|
|
|
130
576
|
return it != multipliers_.end() ? it->second : 1.0;
|
|
131
577
|
}
|
|
132
578
|
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
579
|
+
bool RiskEngine::multiplierKnownLocked(const std::string &instrumentId) const {
|
|
580
|
+
return multipliers_.find(instrumentId) != multipliers_.end();
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
std::string RiskEngine::marginKey(const std::string &instrumentId,
|
|
584
|
+
char hedgeFlag) {
|
|
585
|
+
return instrumentId + "|" + std::string(1, hedgeFlag ? hedgeFlag : '1');
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
bool RiskEngine::marginCostLocked(const std::string &instrumentId, bool isLong,
|
|
589
|
+
char hedgeFlag, double price, double volume,
|
|
590
|
+
double &cost) const {
|
|
591
|
+
if (!sanePositive(price) || !sanePositive(volume) ||
|
|
592
|
+
!validHedgeFlag(hedgeFlag) || !multiplierKnownLocked(instrumentId))
|
|
593
|
+
return false;
|
|
594
|
+
auto supported = futuresMarginFormula_.find(instrumentId);
|
|
595
|
+
if (supported == futuresMarginFormula_.end() || !supported->second)
|
|
596
|
+
return false;
|
|
597
|
+
auto it = marginRates_.find(marginKey(instrumentId, hedgeFlag));
|
|
598
|
+
if (it == marginRates_.end())
|
|
599
|
+
return false;
|
|
600
|
+
const MarginSchedule &m = it->second;
|
|
601
|
+
double money = isLong ? m.longByMoney : m.shortByMoney;
|
|
602
|
+
double byVolume = isLong ? m.longByVolume : m.shortByVolume;
|
|
603
|
+
if (m.isRelative) {
|
|
604
|
+
auto base = exchangeMarginRates_.find(marginKey(instrumentId, hedgeFlag));
|
|
605
|
+
if (base == exchangeMarginRates_.end())
|
|
606
|
+
return false;
|
|
607
|
+
money += isLong ? base->second.longByMoney : base->second.shortByMoney;
|
|
608
|
+
byVolume += isLong ? base->second.longByVolume
|
|
609
|
+
: base->second.shortByVolume;
|
|
610
|
+
}
|
|
611
|
+
cost = price * volume * multiplierLocked(instrumentId) * money +
|
|
612
|
+
volume * byVolume;
|
|
613
|
+
return std::isfinite(cost) && cost >= 0.0;
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
bool RiskEngine::hasCostCapLocked(const std::string &instrumentId) const {
|
|
617
|
+
if (maxAccountMargin_.load(std::memory_order_relaxed) > 0.0)
|
|
618
|
+
return true;
|
|
619
|
+
auto it = maxInstrumentMargin_.find(instrumentId);
|
|
620
|
+
return it != maxInstrumentMargin_.end() && it->second > 0.0;
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
bool RiskEngine::localControlsEnabledLocked() const {
|
|
624
|
+
if (invalidConfig_.load(std::memory_order_acquire) ||
|
|
625
|
+
maxOrderVolume_.load(std::memory_order_relaxed) > 0 ||
|
|
626
|
+
maxPriceDeviation_.load(std::memory_order_relaxed) > 0.0 ||
|
|
627
|
+
maxNotional_.load(std::memory_order_relaxed) > 0.0 ||
|
|
628
|
+
maxAccountMargin_.load(std::memory_order_relaxed) > 0.0 ||
|
|
629
|
+
limiter_.enabled() || closeLimiter_.enabled())
|
|
630
|
+
return true;
|
|
631
|
+
for (const auto &kv : maxInstrumentMargin_)
|
|
632
|
+
if (kv.second > 0.0)
|
|
633
|
+
return true;
|
|
634
|
+
for (const auto &kv : maxPositionVol_)
|
|
635
|
+
if (kv.second.longMax > 0.0 || kv.second.shortMax > 0.0)
|
|
636
|
+
return true;
|
|
637
|
+
return false;
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
void RiskEngine::refreshReservationCostsLocked(
|
|
641
|
+
const std::string &instrumentId) {
|
|
642
|
+
for (auto &kv : reservations_) {
|
|
643
|
+
Reservation &r = kv.second;
|
|
644
|
+
if (r.instrumentId != instrumentId || r.vol <= 0.0)
|
|
645
|
+
continue;
|
|
646
|
+
updateReservationExposureLocked(r, r.vol, r.price);
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
void RiskEngine::refreshAllReservationCostsLocked() {
|
|
651
|
+
for (auto &kv : reservations_) {
|
|
652
|
+
Reservation &reservation = kv.second;
|
|
653
|
+
if (reservation.vol > 0.0)
|
|
654
|
+
updateReservationExposureLocked(reservation, reservation.vol,
|
|
655
|
+
reservation.price);
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
void RiskEngine::invalidateHeldCostsLocked(
|
|
660
|
+
const std::string &instrumentId) {
|
|
661
|
+
auto mark = [](Pos &position) {
|
|
662
|
+
for (auto &bucket : position.longHeld)
|
|
663
|
+
if (bucket.second.vol > 0.0)
|
|
664
|
+
bucket.second.costKnown = false;
|
|
665
|
+
for (auto &bucket : position.shortHeld)
|
|
666
|
+
if (bucket.second.vol > 0.0)
|
|
667
|
+
bucket.second.costKnown = false;
|
|
668
|
+
if (position.longVol > 0.0)
|
|
669
|
+
position.longCostKnown = false;
|
|
670
|
+
if (position.shortVol > 0.0)
|
|
671
|
+
position.shortCostKnown = false;
|
|
672
|
+
};
|
|
673
|
+
if (instrumentId.empty()) {
|
|
674
|
+
for (auto &entry : positions_)
|
|
675
|
+
mark(entry.second);
|
|
138
676
|
return;
|
|
139
|
-
|
|
140
|
-
|
|
677
|
+
}
|
|
678
|
+
auto position = positions_.find(instrumentId);
|
|
679
|
+
if (position != positions_.end())
|
|
680
|
+
mark(position->second);
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
void RiskEngine::recomputeHeldSideLocked(Pos &position, bool isLong) {
|
|
684
|
+
auto &held = isLong ? position.longHeld : position.shortHeld;
|
|
685
|
+
double volume = 0.0;
|
|
686
|
+
double cost = 0.0;
|
|
687
|
+
bool known = true;
|
|
688
|
+
for (auto it = held.begin(); it != held.end();) {
|
|
689
|
+
Pos::HeldBucket &bucket = it->second;
|
|
690
|
+
if (bucket.vol <= 0.0) {
|
|
691
|
+
it = held.erase(it);
|
|
692
|
+
continue;
|
|
693
|
+
}
|
|
694
|
+
volume += bucket.vol;
|
|
695
|
+
cost += bucket.cost;
|
|
696
|
+
clampFiniteCost(volume);
|
|
697
|
+
clampFiniteCost(cost);
|
|
698
|
+
known = known && bucket.costKnown;
|
|
699
|
+
++it;
|
|
700
|
+
}
|
|
141
701
|
if (isLong) {
|
|
142
|
-
|
|
143
|
-
|
|
702
|
+
position.longVol = volume;
|
|
703
|
+
position.longCost = cost;
|
|
704
|
+
position.longCostKnown = known;
|
|
144
705
|
} else {
|
|
145
|
-
|
|
146
|
-
|
|
706
|
+
position.shortVol = volume;
|
|
707
|
+
position.shortCost = cost;
|
|
708
|
+
position.shortCostKnown = known;
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
static inline void replaceCostContribution(double &total, double oldCost,
|
|
713
|
+
double newCost) {
|
|
714
|
+
// Once a defensive overflow pins a total at max, subtraction is ambiguous;
|
|
715
|
+
// keep it pinned (fail closed) until the next authoritative rebuild.
|
|
716
|
+
if (total == std::numeric_limits<double>::max() && oldCost > 0.0)
|
|
717
|
+
return;
|
|
718
|
+
total = std::max(0.0, total - oldCost);
|
|
719
|
+
total += newCost;
|
|
720
|
+
clampFiniteCost(total);
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
void RiskEngine::updateReservationExposureLocked(Reservation &r,
|
|
724
|
+
double desiredVol,
|
|
725
|
+
double price) {
|
|
726
|
+
desiredVol = std::max(0.0, desiredVol);
|
|
727
|
+
double desiredCost = 0.0;
|
|
728
|
+
bool desiredKnown = true;
|
|
729
|
+
// A release (desiredVol == 0) needs no reference; only a live open is valued,
|
|
730
|
+
// so avoid the refPrice()/marginCost lookup on the frequent fill/cancel/reject
|
|
731
|
+
// release path. Margin at a caller-supplied sell limit can be arbitrarily below
|
|
732
|
+
// the price at which it immediately executes, so value every live open at the
|
|
733
|
+
// greater of its order price and a fresh market reference. Missing/stale
|
|
734
|
+
// references make the reservation unknown, so an enabled monetary gate fails
|
|
735
|
+
// closed.
|
|
736
|
+
if (desiredVol > 0.0) {
|
|
737
|
+
const double reference = refPrice(r.instrumentId);
|
|
738
|
+
const bool priceKnown = sanePositive(price) && sanePositive(reference);
|
|
739
|
+
const double valuationPrice = priceKnown ? std::max(price, reference) : 0.0;
|
|
740
|
+
desiredKnown = priceKnown &&
|
|
741
|
+
marginCostLocked(r.instrumentId, r.isLong, r.hedgeFlag, valuationPrice,
|
|
742
|
+
desiredVol, desiredCost);
|
|
743
|
+
}
|
|
744
|
+
Pos &p = positions_[r.instrumentId];
|
|
745
|
+
double &pendingVol = r.isLong ? p.longPendVol : p.shortPendVol;
|
|
746
|
+
double &pendingCost = r.isLong ? p.longPendCost : p.shortPendCost;
|
|
747
|
+
size_t &unknown = r.isLong ? p.longPendUnknown : p.shortPendUnknown;
|
|
748
|
+
pendingVol = std::max(0.0, pendingVol - r.vol);
|
|
749
|
+
pendingVol += desiredVol;
|
|
750
|
+
clampFiniteCost(pendingVol);
|
|
751
|
+
replaceCostContribution(pendingCost, r.cost,
|
|
752
|
+
desiredKnown ? desiredCost : 0.0);
|
|
753
|
+
if (!r.costKnown && desiredKnown && unknown > 0)
|
|
754
|
+
--unknown;
|
|
755
|
+
else if (r.costKnown && !desiredKnown)
|
|
756
|
+
++unknown;
|
|
757
|
+
r.vol = desiredVol;
|
|
758
|
+
r.cost = desiredKnown ? desiredCost : 0.0;
|
|
759
|
+
r.price = price;
|
|
760
|
+
r.costKnown = desiredKnown;
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
void RiskEngine::indexReservationLocked(const std::string &key) {
|
|
764
|
+
auto it = reservations_.find(key);
|
|
765
|
+
if (it == reservations_.end())
|
|
766
|
+
return;
|
|
767
|
+
reservationKeysByRef_[it->second.orderRef].insert(key);
|
|
768
|
+
if (!it->second.orderSysKey.empty())
|
|
769
|
+
reservationKeyBySys_[it->second.orderSysKey] = key;
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
void RiskEngine::unindexReservationLocked(const std::string &key,
|
|
773
|
+
const Reservation &r) {
|
|
774
|
+
auto refs = reservationKeysByRef_.find(r.orderRef);
|
|
775
|
+
if (refs != reservationKeysByRef_.end()) {
|
|
776
|
+
refs->second.erase(key);
|
|
777
|
+
if (refs->second.empty())
|
|
778
|
+
reservationKeysByRef_.erase(refs);
|
|
779
|
+
}
|
|
780
|
+
if (!r.orderSysKey.empty()) {
|
|
781
|
+
auto sys = reservationKeyBySys_.find(r.orderSysKey);
|
|
782
|
+
if (sys != reservationKeyBySys_.end() && sys->second == key)
|
|
783
|
+
reservationKeyBySys_.erase(sys);
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
bool RiskEngine::observeInsertRequestLocked(
|
|
788
|
+
const std::string &key, const Reservation &reservation) {
|
|
789
|
+
if (reservation.insertRequestId == 0 ||
|
|
790
|
+
reservation.insertBindingToken == 0)
|
|
791
|
+
return false; // snapshot/external-terminal order, not one of our inserts
|
|
792
|
+
auto binding = insertRequests_.find(reservation.insertRequestId);
|
|
793
|
+
if (binding == insertRequests_.end() ||
|
|
794
|
+
binding->second.reservationKey != key ||
|
|
795
|
+
binding->second.orderRef != reservation.orderRef ||
|
|
796
|
+
binding->second.token != reservation.insertBindingToken) {
|
|
797
|
+
// Internal ownership metadata must be one-to-one. Retain the reservation
|
|
798
|
+
// and require an authoritative snapshot rather than make a release unsafe.
|
|
799
|
+
orderLedgerUncertain_ = true;
|
|
800
|
+
return true;
|
|
147
801
|
}
|
|
802
|
+
if (binding->second.state == InsertRequestState::Pending)
|
|
803
|
+
binding->second.state = InsertRequestState::Observed;
|
|
804
|
+
return false;
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
std::string RiskEngine::reservationKeyForTradeLocked(
|
|
808
|
+
const std::string &orderSysKey) const {
|
|
809
|
+
if (!orderSysKey.empty()) {
|
|
810
|
+
auto sys = reservationKeyBySys_.find(orderSysKey);
|
|
811
|
+
if (sys != reservationKeyBySys_.end())
|
|
812
|
+
return sys->second;
|
|
813
|
+
// A concrete but unknown exchange order id identifies some other order.
|
|
814
|
+
// Falling back to OrderRef here can collide across front/session and release
|
|
815
|
+
// this terminal's unrelated same-ref reservation.
|
|
816
|
+
return {};
|
|
817
|
+
}
|
|
818
|
+
// OrderRef is only unique inside a front/session, neither of which exists on
|
|
819
|
+
// Trade. Without an exchange id, even one currently-live matching ref can
|
|
820
|
+
// belong to another terminal; never release by ref alone.
|
|
821
|
+
return {};
|
|
148
822
|
}
|
|
149
823
|
|
|
150
824
|
void RiskEngine::resetPositions() {
|
|
825
|
+
std::lock_guard<RiskSendMutex> send(sendModeMutex_);
|
|
151
826
|
std::lock_guard<std::mutex> lk(posMutex_);
|
|
152
|
-
|
|
153
|
-
|
|
827
|
+
// Public "reset positions" resets HELD state only. Working-order reservations
|
|
828
|
+
// are a separate source of committed exposure and must survive a position
|
|
829
|
+
// resync; clearing them created a fail-open window until syncOrders completed.
|
|
830
|
+
for (auto it = positions_.begin(); it != positions_.end();) {
|
|
831
|
+
Pos &p = it->second;
|
|
832
|
+
p.longVol = p.longCost = p.shortVol = p.shortCost = 0.0;
|
|
833
|
+
p.longCostKnown = p.shortCostKnown = true;
|
|
834
|
+
p.longHeld.clear();
|
|
835
|
+
p.shortHeld.clear();
|
|
836
|
+
if (p.longPendVol == 0.0 && p.shortPendVol == 0.0)
|
|
837
|
+
it = positions_.erase(it);
|
|
838
|
+
else
|
|
839
|
+
++it;
|
|
840
|
+
}
|
|
841
|
+
// A reset is not an authoritative flat-account snapshot. Keep all opening
|
|
842
|
+
// inserts fail-closed until seedFromPositions()/syncPositions() supplies one;
|
|
843
|
+
// otherwise an armed order can fire in the clear-then-seed window.
|
|
844
|
+
ledgerUncertain_ = true;
|
|
845
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
154
846
|
}
|
|
155
847
|
|
|
156
|
-
|
|
157
|
-
|
|
848
|
+
bool RiskEngine::replacePositionsIfRevision(
|
|
849
|
+
uint64_t expected, const std::vector<PositionSeed> &seeds) {
|
|
850
|
+
std::lock_guard<RiskSendMutex> send(sendModeMutex_);
|
|
851
|
+
std::lock_guard<std::mutex> lk(posMutex_);
|
|
852
|
+
if (revision_.load(std::memory_order_relaxed) != expected)
|
|
853
|
+
return false;
|
|
854
|
+
// Reject the whole snapshot before touching live state. Silently skipping a
|
|
855
|
+
// malformed row after clearing held positions would turn bad input into an
|
|
856
|
+
// authoritative flat book and fail open.
|
|
857
|
+
for (const auto &s : seeds)
|
|
858
|
+
if (s.instrumentId.empty() || !saneNonNegativeLots(s.volume) ||
|
|
859
|
+
!std::isfinite(s.margin) || s.margin < 0.0 ||
|
|
860
|
+
!validHedgeFlag(s.hedgeFlag))
|
|
861
|
+
return false;
|
|
862
|
+
// Preserve pending exposure/reservation identity while replacing held state.
|
|
863
|
+
for (auto &kv : positions_)
|
|
864
|
+
kv.second.longVol = kv.second.longCost = kv.second.shortVol =
|
|
865
|
+
kv.second.shortCost = 0.0;
|
|
866
|
+
for (auto &kv : positions_) {
|
|
867
|
+
kv.second.longCostKnown = kv.second.shortCostKnown = true;
|
|
868
|
+
kv.second.longHeld.clear();
|
|
869
|
+
kv.second.shortHeld.clear();
|
|
870
|
+
}
|
|
871
|
+
for (const auto &s : seeds) {
|
|
872
|
+
Pos &p = positions_[s.instrumentId];
|
|
873
|
+
auto &held = s.isLong ? p.longHeld : p.shortHeld;
|
|
874
|
+
Pos::HeldBucket &bucket = held[s.hedgeFlag];
|
|
875
|
+
bucket.vol += s.volume;
|
|
876
|
+
bucket.cost += s.margin;
|
|
877
|
+
clampFiniteCost(bucket.vol);
|
|
878
|
+
clampFiniteCost(bucket.cost);
|
|
879
|
+
bucket.costKnown = bucket.costKnown &&
|
|
880
|
+
(s.volume <= 0.0 || s.margin > 0.0);
|
|
881
|
+
}
|
|
882
|
+
for (auto &entry : positions_) {
|
|
883
|
+
Pos &position = entry.second;
|
|
884
|
+
recomputeHeldSideLocked(position, true);
|
|
885
|
+
recomputeHeldSideLocked(position, false);
|
|
886
|
+
}
|
|
887
|
+
// A complete snapshot also proves that instruments absent from it have no
|
|
888
|
+
// held position. Do not retain one empty map entry per instrument ever seen
|
|
889
|
+
// over a long-lived process; working-order entries remain because their
|
|
890
|
+
// pending exposure is still authoritative.
|
|
891
|
+
for (auto it = positions_.begin(); it != positions_.end();) {
|
|
892
|
+
const Pos &position = it->second;
|
|
893
|
+
if (position.longVol <= 0.0 && position.shortVol <= 0.0 &&
|
|
894
|
+
position.longPendVol <= 0.0 && position.shortPendVol <= 0.0)
|
|
895
|
+
it = positions_.erase(it);
|
|
896
|
+
else
|
|
897
|
+
++it;
|
|
898
|
+
}
|
|
899
|
+
// A same-day exact-dedupe overflow cannot be repaired by a position snapshot:
|
|
900
|
+
// subsequent callbacks from that day are still indistinguishable from old
|
|
901
|
+
// duplicates. Resume only after the stream advances to a later trading day.
|
|
902
|
+
ledgerUncertain_ = !tradeDedupeExhaustedDay_.empty();
|
|
903
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
904
|
+
return true;
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
void RiskEngine::onTrade(const std::string &tradeKey,
|
|
908
|
+
const std::string &orderRef,
|
|
909
|
+
const std::string &orderSysKey,
|
|
910
|
+
const std::string &instrumentId, bool isBuy,
|
|
911
|
+
bool isOpen, char hedgeFlag, double price,
|
|
912
|
+
double volume, const std::string &brokerId,
|
|
913
|
+
const std::string &investorId) {
|
|
158
914
|
// Real CTP fills are always positive, finite, and far below the sentinel band;
|
|
159
915
|
// ignore malformed data rather than let it corrupt the tracked cost (a NaN
|
|
160
|
-
// would silently void the
|
|
161
|
-
// sanePositive
|
|
162
|
-
|
|
163
|
-
return;
|
|
916
|
+
// would silently void the margin cap, +Inf/DBL_MAX would jam or void it). See
|
|
917
|
+
// sanePositive: the same sentinel rejection as instrument metadata / refPrice.
|
|
918
|
+
std::lock_guard<RiskSendMutex> send(sendModeMutex_);
|
|
164
919
|
std::lock_guard<std::mutex> lk(posMutex_);
|
|
165
|
-
const
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
if (
|
|
920
|
+
const AccountScope account = accountScopeLocked(brokerId, investorId);
|
|
921
|
+
if (account == AccountScope::Foreign)
|
|
922
|
+
return; // delayed broadcast from another logged-out account
|
|
923
|
+
if (account == AccountScope::Ambiguous) {
|
|
924
|
+
ledgerUncertain_ = true;
|
|
925
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
169
926
|
return;
|
|
170
|
-
|
|
927
|
+
}
|
|
928
|
+
if (!sanePositive(price) || !saneLots(volume) ||
|
|
929
|
+
!validHedgeFlag(hedgeFlag)) {
|
|
930
|
+
// A malformed callback may still represent a real fill. Ignoring it would
|
|
931
|
+
// under-count exposure, so require an authoritative position reconciliation.
|
|
932
|
+
ledgerUncertain_ = true;
|
|
933
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
934
|
+
return;
|
|
935
|
+
}
|
|
936
|
+
if (instrumentId.empty()) {
|
|
937
|
+
ledgerUncertain_ = true;
|
|
938
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
939
|
+
return;
|
|
940
|
+
}
|
|
941
|
+
if (tradeKey.empty()) {
|
|
942
|
+
// Without a stable exchange/day identifier we cannot distinguish a replay
|
|
943
|
+
// from a new fill. Applying it could double-count; ignoring it could
|
|
944
|
+
// under-count. Preserve safety by making all position-dependent opening
|
|
945
|
+
// gates fail closed until an authoritative position snapshot arrives.
|
|
946
|
+
ledgerUncertain_ = true;
|
|
947
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
948
|
+
return;
|
|
949
|
+
}
|
|
950
|
+
std::string tradeDay;
|
|
951
|
+
const size_t sep = tradeKey.find('|');
|
|
952
|
+
tradeDay = tradeKey.substr(0, sep);
|
|
953
|
+
if (!validTradingDay(tradeDay)) {
|
|
954
|
+
ledgerUncertain_ = true;
|
|
955
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
956
|
+
return;
|
|
957
|
+
}
|
|
958
|
+
if (!retiredThroughTradeDay_.empty() &&
|
|
959
|
+
tradeDay <= retiredThroughTradeDay_) {
|
|
960
|
+
// Exact ids from this day were intentionally compacted. Silently treating
|
|
961
|
+
// every later callback as a duplicate can miss a real first-seen fill.
|
|
962
|
+
// Preserve bounded memory and safety by requiring a fresh authoritative
|
|
963
|
+
// position sync before any position-dependent opening gate can pass.
|
|
964
|
+
ledgerUncertain_ = true;
|
|
965
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
966
|
+
return;
|
|
967
|
+
}
|
|
968
|
+
const SeenTrade fingerprint{orderRef, orderSysKey, instrumentId, isBuy,
|
|
969
|
+
isOpen, hedgeFlag, price, volume};
|
|
970
|
+
auto seen = seenTrades_.find(tradeKey);
|
|
971
|
+
if (seen != seenTrades_.end()) {
|
|
972
|
+
const SeenTrade &old = seen->second;
|
|
973
|
+
if (old.orderRef == fingerprint.orderRef &&
|
|
974
|
+
old.orderSysKey == fingerprint.orderSysKey &&
|
|
975
|
+
old.instrumentId == fingerprint.instrumentId &&
|
|
976
|
+
old.isBuy == fingerprint.isBuy && old.isOpen == fingerprint.isOpen &&
|
|
977
|
+
old.hedgeFlag == fingerprint.hedgeFlag &&
|
|
978
|
+
old.price == fingerprint.price && old.volume == fingerprint.volume)
|
|
979
|
+
return; // byte-level semantic duplicate
|
|
980
|
+
// Reusing the same exchange/day trade id for different economics is
|
|
981
|
+
// ambiguous: applying can double-count, ignoring can under-count.
|
|
982
|
+
ledgerUncertain_ = true;
|
|
983
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
984
|
+
return;
|
|
985
|
+
}
|
|
986
|
+
|
|
987
|
+
if (!tradeDedupeExhaustedDay_.empty()) {
|
|
988
|
+
if (tradeDay <= tradeDedupeExhaustedDay_) {
|
|
989
|
+
ledgerUncertain_ = true;
|
|
990
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
991
|
+
return;
|
|
992
|
+
}
|
|
993
|
+
// The stream has advanced beyond the exhausted day. Retire every exact key
|
|
994
|
+
// from the old epoch and begin a fresh bounded window, but keep the position
|
|
995
|
+
// ledger uncertain until replacePositionsIfRevision() reconciles fills that
|
|
996
|
+
// were deliberately not guessed while exhausted.
|
|
997
|
+
if (tradeDedupeExhaustedDay_ > retiredThroughTradeDay_)
|
|
998
|
+
retiredThroughTradeDay_ = tradeDedupeExhaustedDay_;
|
|
999
|
+
seenTrades_.clear();
|
|
1000
|
+
tradeKeysByDay_.clear();
|
|
1001
|
+
tradeDedupeExhaustedDay_.clear();
|
|
1002
|
+
}
|
|
1003
|
+
|
|
1004
|
+
// Prefer retiring a complete older day to exhausting the current one. Exact
|
|
1005
|
+
// keys from a retired day are intentionally not guessed if replayed later.
|
|
1006
|
+
while (seenTrades_.size() >= kMaxSeenTrades &&
|
|
1007
|
+
!tradeKeysByDay_.empty() &&
|
|
1008
|
+
tradeKeysByDay_.begin()->first < tradeDay) {
|
|
1009
|
+
const std::string expired = tradeKeysByDay_.begin()->first;
|
|
1010
|
+
if (expired > retiredThroughTradeDay_)
|
|
1011
|
+
retiredThroughTradeDay_ = expired;
|
|
1012
|
+
for (const auto &key : tradeKeysByDay_.begin()->second)
|
|
1013
|
+
seenTrades_.erase(key);
|
|
1014
|
+
tradeKeysByDay_.erase(tradeKeysByDay_.begin());
|
|
1015
|
+
}
|
|
1016
|
+
if (seenTrades_.size() >= kMaxSeenTrades) {
|
|
1017
|
+
tradeDedupeExhaustedDay_ = tradeDay;
|
|
1018
|
+
if (!tradeKeysByDay_.empty() &&
|
|
1019
|
+
tradeKeysByDay_.rbegin()->first > tradeDedupeExhaustedDay_)
|
|
1020
|
+
tradeDedupeExhaustedDay_ = tradeKeysByDay_.rbegin()->first;
|
|
1021
|
+
ledgerUncertain_ = true;
|
|
1022
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
1023
|
+
return;
|
|
1024
|
+
}
|
|
1025
|
+
seenTrades_.emplace(tradeKey, fingerprint);
|
|
1026
|
+
|
|
1027
|
+
// Transfer this fill's exposure from pending to held under the same ledger
|
|
1028
|
+
// lock. If OnRtnOrder reported VolumeTraded first, its reservation deliberately
|
|
1029
|
+
// included the not-yet-delivered trade; this closes that gap atomically.
|
|
171
1030
|
if (isOpen) {
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
1031
|
+
const std::string reservationKey =
|
|
1032
|
+
reservationKeyForTradeLocked(orderSysKey);
|
|
1033
|
+
auto rit = reservations_.find(reservationKey);
|
|
1034
|
+
if (rit != reservations_.end()) {
|
|
1035
|
+
const Reservation &matched = rit->second;
|
|
1036
|
+
if (matched.instrumentId != instrumentId || matched.isLong != isBuy ||
|
|
1037
|
+
matched.hedgeFlag != hedgeFlag) {
|
|
1038
|
+
// The identity index and the economic fields disagree. Apply the fill
|
|
1039
|
+
// to held exposure below, but never release the conflicting working
|
|
1040
|
+
// order until both ledgers have been authoritatively reconciled.
|
|
1041
|
+
orderLedgerUncertain_ = true;
|
|
1042
|
+
ledgerUncertain_ = true;
|
|
1043
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
1044
|
+
rit = reservations_.end();
|
|
1045
|
+
}
|
|
1046
|
+
}
|
|
1047
|
+
if (rit != reservations_.end()) {
|
|
1048
|
+
auto state = orderStates_.find(reservationKey);
|
|
1049
|
+
if (state != orderStates_.end()) {
|
|
1050
|
+
state->second.appliedTraded += volume;
|
|
1051
|
+
clampFiniteCost(state->second.appliedTraded);
|
|
1052
|
+
}
|
|
1053
|
+
Reservation &reservation = rit->second;
|
|
1054
|
+
updateReservationExposureLocked(
|
|
1055
|
+
reservation, std::max(0.0, reservation.vol - volume),
|
|
1056
|
+
reservation.price);
|
|
1057
|
+
if (reservation.vol <= 0.0) {
|
|
1058
|
+
Reservation done = reservation;
|
|
1059
|
+
unindexReservationLocked(reservationKey, done);
|
|
1060
|
+
reservations_.erase(rit);
|
|
1061
|
+
pruneEvictedTerminalOrderLocked(reservationKey);
|
|
1062
|
+
}
|
|
1063
|
+
} else if (!orderSysKey.empty()) {
|
|
1064
|
+
// External-terminal ordering can be Trade -> Order. Without this marker,
|
|
1065
|
+
// the later terminal Order's VolumeTraded would be counted again as an
|
|
1066
|
+
// undelivered fill reservation, leaving a permanent ghost commitment.
|
|
1067
|
+
// If an extreme stream never supplies matching Order callbacks, bound the
|
|
1068
|
+
// optimization map. Dropping these hints can only over-count a later stale
|
|
1069
|
+
// Order as pending; it cannot under-count actual held exposure.
|
|
1070
|
+
if (unmatchedFillsBySys_.size() >= kMaxUnmatchedFills &&
|
|
1071
|
+
unmatchedFillsBySys_.count(orderSysKey) == 0)
|
|
1072
|
+
unmatchedFillsBySys_.clear();
|
|
1073
|
+
UnmatchedFill &fill = unmatchedFillsBySys_[orderSysKey];
|
|
1074
|
+
if (fill.orderRef.empty() || fill.orderRef == orderRef) {
|
|
1075
|
+
fill.orderRef = orderRef;
|
|
1076
|
+
fill.volume += volume;
|
|
1077
|
+
clampFiniteCost(fill.volume);
|
|
1078
|
+
} else {
|
|
1079
|
+
// One exchange order id cannot belong to two OrderRefs. The fills are
|
|
1080
|
+
// still applied to held exposure, but no reservation may be reconciled
|
|
1081
|
+
// through this ambiguous identity until an authoritative order sync.
|
|
1082
|
+
orderLedgerUncertain_ = true;
|
|
1083
|
+
}
|
|
1084
|
+
} else if (!orderRef.empty() && reservationKeysByRef_.count(orderRef) != 0) {
|
|
1085
|
+
// We applied the fill to held exposure, but cannot safely choose which
|
|
1086
|
+
// front/session reservation to release. Keep it and require order sync.
|
|
1087
|
+
orderLedgerUncertain_ = true;
|
|
1088
|
+
}
|
|
1089
|
+
}
|
|
1090
|
+
|
|
1091
|
+
double cost = 0.0;
|
|
1092
|
+
const bool costKnown =
|
|
1093
|
+
!isOpen || marginCostLocked(instrumentId, isBuy, hedgeFlag, price,
|
|
1094
|
+
volume, cost);
|
|
1095
|
+
if (isOpen && !costKnown) {
|
|
1096
|
+
if (hasCostCapLocked(instrumentId)) {
|
|
1097
|
+
// A fill already happened but its metadata is incomplete. Pin the held
|
|
1098
|
+
// ledger above every finite cap rather than under-count and fail open.
|
|
1099
|
+
cost = std::numeric_limits<double>::max() / 4.0;
|
|
176
1100
|
} else {
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
1101
|
+
// No monetary cap is active: retain a best-effort observable cost while
|
|
1102
|
+
// still making future capped opens fail closed at reservation time.
|
|
1103
|
+
cost = price * volume * multiplierLocked(instrumentId);
|
|
1104
|
+
if (!std::isfinite(cost))
|
|
1105
|
+
cost = std::numeric_limits<double>::max() / 4.0;
|
|
1106
|
+
}
|
|
1107
|
+
}
|
|
1108
|
+
Pos &p = positions_[instrumentId];
|
|
1109
|
+
if (isOpen) {
|
|
1110
|
+
auto &held = isBuy ? p.longHeld : p.shortHeld;
|
|
1111
|
+
Pos::HeldBucket &bucket = held[hedgeFlag];
|
|
1112
|
+
bucket.costKnown = bucket.vol <= 0.0
|
|
1113
|
+
? costKnown
|
|
1114
|
+
: bucket.costKnown && costKnown;
|
|
1115
|
+
bucket.vol += volume;
|
|
1116
|
+
bucket.cost += cost;
|
|
1117
|
+
clampFiniteCost(bucket.vol);
|
|
1118
|
+
clampFiniteCost(bucket.cost);
|
|
1119
|
+
recomputeHeldSideLocked(p, isBuy);
|
|
1120
|
+
} else {
|
|
1121
|
+
// A close releases only the matching hedge bucket. Averaging speculation
|
|
1122
|
+
// and hedge margin together can release too much low-margin exposure and
|
|
1123
|
+
// understate the higher-margin remainder.
|
|
1124
|
+
const bool closingLong = !isBuy;
|
|
1125
|
+
auto &held = closingLong ? p.longHeld : p.shortHeld;
|
|
1126
|
+
auto bucketIt = held.find(hedgeFlag);
|
|
1127
|
+
if (bucketIt == held.end() || volume > bucketIt->second.vol) {
|
|
1128
|
+
ledgerUncertain_ = true;
|
|
180
1129
|
}
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
1130
|
+
if (bucketIt != held.end()) {
|
|
1131
|
+
Pos::HeldBucket &bucket = bucketIt->second;
|
|
1132
|
+
const double v = std::min(volume, bucket.vol);
|
|
1133
|
+
const double rel = bucket.vol > 0.0
|
|
1134
|
+
? bucket.cost * (v / bucket.vol)
|
|
1135
|
+
: 0.0;
|
|
1136
|
+
bucket.cost = std::max(0.0, bucket.cost - rel);
|
|
1137
|
+
bucket.vol = std::max(0.0, bucket.vol - v);
|
|
1138
|
+
if (bucket.vol <= 0.0)
|
|
1139
|
+
held.erase(bucketIt);
|
|
1140
|
+
}
|
|
1141
|
+
recomputeHeldSideLocked(p, closingLong);
|
|
1142
|
+
// A position query and the private realtime stream have no common sequence
|
|
1143
|
+
// watermark. This close may already be reflected by the latest snapshot;
|
|
1144
|
+
// never let a possible double-release reopen a cap. A fresh authoritative
|
|
1145
|
+
// position sync is required before the next opening order.
|
|
1146
|
+
ledgerUncertain_ = true;
|
|
1147
|
+
}
|
|
1148
|
+
auto dit = tradeKeysByDay_.find(tradeDay);
|
|
1149
|
+
if (dit == tradeKeysByDay_.end())
|
|
1150
|
+
dit = tradeKeysByDay_.emplace(tradeDay, std::vector<std::string>{}).first;
|
|
1151
|
+
dit->second.push_back(tradeKey);
|
|
1152
|
+
// TradingDay is YYYYMMDD, so lexical order is chronological. A first-seen
|
|
1153
|
+
// late old-day fill is applied once and immediately compacted; it cannot
|
|
1154
|
+
// rotate a recent exact-key day out of the retention window.
|
|
1155
|
+
while (tradeKeysByDay_.size() > kRetainedTradeDays) {
|
|
1156
|
+
const std::string expired = tradeKeysByDay_.begin()->first;
|
|
1157
|
+
if (expired > retiredThroughTradeDay_)
|
|
1158
|
+
retiredThroughTradeDay_ = expired;
|
|
1159
|
+
for (const auto &key : tradeKeysByDay_.begin()->second)
|
|
1160
|
+
seenTrades_.erase(key);
|
|
1161
|
+
tradeKeysByDay_.erase(tradeKeysByDay_.begin());
|
|
191
1162
|
}
|
|
1163
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
1164
|
+
}
|
|
1165
|
+
|
|
1166
|
+
void RiskEngine::markTradeLedgerUncertain() {
|
|
1167
|
+
std::lock_guard<RiskSendMutex> send(sendModeMutex_);
|
|
1168
|
+
std::lock_guard<std::mutex> lk(posMutex_);
|
|
1169
|
+
ledgerUncertain_ = true;
|
|
1170
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
1171
|
+
}
|
|
1172
|
+
|
|
1173
|
+
void RiskEngine::markOrderLedgerUncertain() {
|
|
1174
|
+
std::lock_guard<RiskSendMutex> send(sendModeMutex_);
|
|
1175
|
+
std::lock_guard<std::mutex> lk(posMutex_);
|
|
1176
|
+
orderLedgerUncertain_ = true;
|
|
1177
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
192
1178
|
}
|
|
193
1179
|
|
|
194
|
-
double RiskEngine::
|
|
1180
|
+
double RiskEngine::accountMargin() const {
|
|
195
1181
|
std::lock_guard<std::mutex> lk(posMutex_);
|
|
196
1182
|
double total = 0.0;
|
|
197
|
-
for (const auto &kv : positions_)
|
|
1183
|
+
for (const auto &kv : positions_) {
|
|
198
1184
|
total += kv.second.longCost + kv.second.shortCost;
|
|
1185
|
+
clampFiniteCost(total);
|
|
1186
|
+
}
|
|
199
1187
|
return total;
|
|
200
1188
|
}
|
|
201
1189
|
|
|
202
|
-
|
|
203
|
-
|
|
1190
|
+
bool RiskEngine::setInstrumentMarginLimits(
|
|
1191
|
+
const std::vector<InstrumentMarginLimitUpdate> &updates) {
|
|
1192
|
+
for (const auto &u : updates)
|
|
1193
|
+
if (u.instrumentId.empty() || !std::isfinite(u.limit) || u.limit < 0.0)
|
|
1194
|
+
return false;
|
|
1195
|
+
std::lock_guard<RiskSendMutex> send(sendModeMutex_);
|
|
204
1196
|
std::lock_guard<std::mutex> lk(posMutex_);
|
|
205
|
-
|
|
1197
|
+
for (const auto &u : updates) {
|
|
1198
|
+
const double limit = positiveLimitOrDisabled(u.limit);
|
|
1199
|
+
if (limit > 0.0)
|
|
1200
|
+
maxInstrumentMargin_[u.instrumentId] = limit;
|
|
1201
|
+
else
|
|
1202
|
+
maxInstrumentMargin_.erase(u.instrumentId);
|
|
1203
|
+
}
|
|
1204
|
+
return true;
|
|
206
1205
|
}
|
|
207
1206
|
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
if (
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
1207
|
+
RiskEngine::AccountScope RiskEngine::accountScopeLocked(
|
|
1208
|
+
const std::string &brokerId, const std::string &investorId) const {
|
|
1209
|
+
if (!sessionIdentityKnown_)
|
|
1210
|
+
return AccountScope::Ambiguous;
|
|
1211
|
+
// Standalone C++ users may install a numeric session without account text.
|
|
1212
|
+
// Real Trader sessions always carry both strings and therefore take the
|
|
1213
|
+
// strict branch below.
|
|
1214
|
+
if (myBrokerId_.empty() && myInvestorId_.empty())
|
|
1215
|
+
return AccountScope::Current;
|
|
1216
|
+
if (brokerId.empty() || investorId.empty())
|
|
1217
|
+
return AccountScope::Ambiguous;
|
|
1218
|
+
return brokerId == myBrokerId_ && investorId == myInvestorId_
|
|
1219
|
+
? AccountScope::Current
|
|
1220
|
+
: AccountScope::Foreign;
|
|
1221
|
+
}
|
|
1222
|
+
|
|
1223
|
+
void RiskEngine::clearAccountMarginMetadataLocked() {
|
|
1224
|
+
marginRates_.clear();
|
|
1225
|
+
exchangeMarginRates_.clear();
|
|
1226
|
+
activeMarginQueryRequestId_ = 0;
|
|
1227
|
+
activeMarginQueryKind_ = MarginQueryKind::None;
|
|
1228
|
+
activeMarginQueryAuthorized_ = false;
|
|
1229
|
+
activeMarginQueryInstrument_.clear();
|
|
1230
|
+
activeMarginQueryHedgeFlag_ = '\0';
|
|
1231
|
+
stagedMarginRates_.clear();
|
|
1232
|
+
invalidateHeldCostsLocked("");
|
|
1233
|
+
refreshAllReservationCostsLocked();
|
|
219
1234
|
}
|
|
220
1235
|
|
|
221
|
-
void RiskEngine::
|
|
1236
|
+
void RiskEngine::clearAccountLedgerLocked() {
|
|
1237
|
+
positions_.clear();
|
|
1238
|
+
reservations_.clear();
|
|
1239
|
+
insertRequests_.clear();
|
|
1240
|
+
insertRequestOrder_.clear();
|
|
1241
|
+
orderStates_.clear();
|
|
1242
|
+
unsupportedWorkingOrders_.clear();
|
|
1243
|
+
terminalOrderKeys_.clear();
|
|
1244
|
+
terminalOrderKeySet_.clear();
|
|
1245
|
+
reservationKeysByRef_.clear();
|
|
1246
|
+
reservationKeyBySys_.clear();
|
|
1247
|
+
unmatchedFillsBySys_.clear();
|
|
1248
|
+
seenTrades_.clear();
|
|
1249
|
+
tradeKeysByDay_.clear();
|
|
1250
|
+
retiredThroughTradeDay_.clear();
|
|
1251
|
+
tradeDedupeExhaustedDay_.clear();
|
|
1252
|
+
unsupportedRiskMutationUsed_ = false;
|
|
1253
|
+
clearAccountMarginMetadataLocked();
|
|
1254
|
+
}
|
|
1255
|
+
|
|
1256
|
+
void RiskEngine::invalidateSession() {
|
|
1257
|
+
std::lock_guard<RiskSendMutex> send(sendModeMutex_);
|
|
1258
|
+
std::lock_guard<std::mutex> lk(posMutex_);
|
|
1259
|
+
sessionIdentityRequired_ = true;
|
|
1260
|
+
sessionIdentityKnown_ = false;
|
|
1261
|
+
loginSessionKnown_ = false;
|
|
1262
|
+
pendingSessionRequestId_ = 0;
|
|
1263
|
+
pendingSessionExpectsLogin_ = false;
|
|
1264
|
+
pendingSessionBrokerId_.clear();
|
|
1265
|
+
pendingSessionUserId_.clear();
|
|
1266
|
+
clearAccountMarginMetadataLocked();
|
|
1267
|
+
ledgerUncertain_ = true;
|
|
1268
|
+
orderLedgerUncertain_ = true;
|
|
1269
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
1270
|
+
}
|
|
1271
|
+
|
|
1272
|
+
void RiskEngine::beginSessionTransition(int requestId, bool expectsLogin,
|
|
1273
|
+
const std::string &brokerId,
|
|
1274
|
+
const std::string &userId) {
|
|
1275
|
+
std::lock_guard<RiskSendMutex> send(sendModeMutex_);
|
|
1276
|
+
std::lock_guard<std::mutex> lk(posMutex_);
|
|
1277
|
+
sessionIdentityRequired_ = true;
|
|
1278
|
+
sessionIdentityKnown_ = false;
|
|
1279
|
+
loginSessionKnown_ = false;
|
|
1280
|
+
pendingSessionRequestId_ = requestId > 0 ? requestId : 0;
|
|
1281
|
+
pendingSessionExpectsLogin_ = expectsLogin && requestId > 0;
|
|
1282
|
+
pendingSessionBrokerId_ = brokerId;
|
|
1283
|
+
pendingSessionUserId_ = userId;
|
|
1284
|
+
clearAccountMarginMetadataLocked();
|
|
1285
|
+
ledgerUncertain_ = true;
|
|
1286
|
+
orderLedgerUncertain_ = true;
|
|
1287
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
1288
|
+
}
|
|
1289
|
+
|
|
1290
|
+
bool RiskEngine::acceptLoginSession(int requestId, int frontId, int sessionId,
|
|
1291
|
+
const std::string &brokerId,
|
|
1292
|
+
const std::string &userId) {
|
|
1293
|
+
std::lock_guard<RiskSendMutex> send(sendModeMutex_);
|
|
222
1294
|
std::lock_guard<std::mutex> lk(posMutex_);
|
|
1295
|
+
if (requestId <= 0 || requestId != pendingSessionRequestId_ ||
|
|
1296
|
+
!pendingSessionExpectsLogin_ || brokerId.empty() || userId.empty() ||
|
|
1297
|
+
frontId <= 0 || sessionId <= 0 ||
|
|
1298
|
+
(!pendingSessionBrokerId_.empty() &&
|
|
1299
|
+
brokerId != pendingSessionBrokerId_) ||
|
|
1300
|
+
(!pendingSessionUserId_.empty() && userId != pendingSessionUserId_))
|
|
1301
|
+
return false;
|
|
1302
|
+
const bool accountChanged =
|
|
1303
|
+
!myBrokerId_.empty() && brokerId != myBrokerId_;
|
|
1304
|
+
const bool changed = accountChanged || frontId != myFrontId_ ||
|
|
1305
|
+
sessionId != mySessionId_;
|
|
1306
|
+
if (accountChanged)
|
|
1307
|
+
clearAccountLedgerLocked();
|
|
223
1308
|
myFrontId_ = frontId;
|
|
224
1309
|
mySessionId_ = sessionId;
|
|
1310
|
+
myBrokerId_ = brokerId;
|
|
1311
|
+
myLoginUserId_ = userId;
|
|
1312
|
+
sessionIdentityRequired_ = true;
|
|
1313
|
+
sessionIdentityKnown_ = false;
|
|
1314
|
+
loginSessionKnown_ = true;
|
|
1315
|
+
pendingSessionRequestId_ = 0;
|
|
1316
|
+
pendingSessionExpectsLogin_ = false;
|
|
1317
|
+
pendingSessionBrokerId_.clear();
|
|
1318
|
+
pendingSessionUserId_.clear();
|
|
1319
|
+
if (changed) {
|
|
1320
|
+
ledgerUncertain_ = true;
|
|
1321
|
+
orderLedgerUncertain_ = true;
|
|
1322
|
+
}
|
|
1323
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
1324
|
+
return true;
|
|
1325
|
+
}
|
|
1326
|
+
|
|
1327
|
+
bool RiskEngine::confirmSessionAccount(
|
|
1328
|
+
int frontId, int sessionId, const std::string &brokerId,
|
|
1329
|
+
const std::string &investorId) {
|
|
1330
|
+
std::lock_guard<RiskSendMutex> send(sendModeMutex_);
|
|
1331
|
+
std::lock_guard<std::mutex> lk(posMutex_);
|
|
1332
|
+
if (!loginSessionKnown_ || frontId <= 0 || sessionId <= 0 ||
|
|
1333
|
+
frontId != myFrontId_ || sessionId != mySessionId_ || brokerId.empty() ||
|
|
1334
|
+
investorId.empty() || brokerId != myBrokerId_)
|
|
1335
|
+
return false;
|
|
1336
|
+
const bool accountChanged =
|
|
1337
|
+
!myInvestorId_.empty() && investorId != myInvestorId_;
|
|
1338
|
+
if (accountChanged)
|
|
1339
|
+
clearAccountLedgerLocked();
|
|
1340
|
+
myInvestorId_ = investorId;
|
|
1341
|
+
sessionIdentityRequired_ = true;
|
|
1342
|
+
sessionIdentityKnown_ = true;
|
|
1343
|
+
ledgerUncertain_ = true;
|
|
1344
|
+
orderLedgerUncertain_ = true;
|
|
1345
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
1346
|
+
return true;
|
|
1347
|
+
}
|
|
1348
|
+
|
|
1349
|
+
bool RiskEngine::acceptsOrderAccount(const std::string &brokerId,
|
|
1350
|
+
const std::string &investorId) const {
|
|
1351
|
+
std::lock_guard<std::mutex> lk(posMutex_);
|
|
1352
|
+
return accountScopeLocked(brokerId, investorId) == AccountScope::Current;
|
|
1353
|
+
}
|
|
1354
|
+
|
|
1355
|
+
void RiskEngine::finishSessionTransition(int requestId) {
|
|
1356
|
+
std::lock_guard<RiskSendMutex> send(sendModeMutex_);
|
|
1357
|
+
std::lock_guard<std::mutex> lk(posMutex_);
|
|
1358
|
+
if (requestId <= 0 || requestId != pendingSessionRequestId_)
|
|
1359
|
+
return;
|
|
1360
|
+
pendingSessionRequestId_ = 0;
|
|
1361
|
+
pendingSessionExpectsLogin_ = false;
|
|
1362
|
+
pendingSessionBrokerId_.clear();
|
|
1363
|
+
pendingSessionUserId_.clear();
|
|
1364
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
1365
|
+
}
|
|
1366
|
+
|
|
1367
|
+
bool RiskEngine::timeoutSessionTransition(int requestId) {
|
|
1368
|
+
std::lock_guard<RiskSendMutex> send(sendModeMutex_);
|
|
1369
|
+
std::lock_guard<std::mutex> lk(posMutex_);
|
|
1370
|
+
if (requestId <= 0 || requestId != pendingSessionRequestId_)
|
|
1371
|
+
return false;
|
|
1372
|
+
pendingSessionRequestId_ = 0;
|
|
1373
|
+
pendingSessionExpectsLogin_ = false;
|
|
1374
|
+
pendingSessionBrokerId_.clear();
|
|
1375
|
+
pendingSessionUserId_.clear();
|
|
1376
|
+
sessionIdentityKnown_ = false;
|
|
1377
|
+
loginSessionKnown_ = false;
|
|
1378
|
+
ledgerUncertain_ = true;
|
|
1379
|
+
orderLedgerUncertain_ = true;
|
|
1380
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
1381
|
+
return true;
|
|
1382
|
+
}
|
|
1383
|
+
|
|
1384
|
+
void RiskEngine::setSession(int frontId, int sessionId,
|
|
1385
|
+
const std::string &brokerId,
|
|
1386
|
+
const std::string &investorId) {
|
|
1387
|
+
std::lock_guard<RiskSendMutex> send(sendModeMutex_);
|
|
1388
|
+
std::lock_guard<std::mutex> lk(posMutex_);
|
|
1389
|
+
const bool concreteIdentity = !sessionIdentityRequired_ ||
|
|
1390
|
+
(!brokerId.empty() && !investorId.empty());
|
|
1391
|
+
const bool changed = sessionIdentityKnown_ &&
|
|
1392
|
+
(frontId != myFrontId_ || sessionId != mySessionId_ ||
|
|
1393
|
+
(!brokerId.empty() && !myBrokerId_.empty() && brokerId != myBrokerId_) ||
|
|
1394
|
+
(!investorId.empty() && !myInvestorId_.empty() &&
|
|
1395
|
+
investorId != myInvestorId_));
|
|
1396
|
+
const bool accountChanged = sessionIdentityKnown_ &&
|
|
1397
|
+
((!brokerId.empty() && !myBrokerId_.empty() &&
|
|
1398
|
+
brokerId != myBrokerId_) ||
|
|
1399
|
+
(!investorId.empty() && !myInvestorId_.empty() &&
|
|
1400
|
+
investorId != myInvestorId_));
|
|
1401
|
+
if (accountChanged)
|
|
1402
|
+
clearAccountLedgerLocked();
|
|
1403
|
+
myFrontId_ = frontId;
|
|
1404
|
+
mySessionId_ = sessionId;
|
|
1405
|
+
myBrokerId_ = brokerId;
|
|
1406
|
+
myInvestorId_ = investorId;
|
|
1407
|
+
myLoginUserId_ = investorId;
|
|
1408
|
+
sessionIdentityRequired_ = true;
|
|
1409
|
+
sessionIdentityKnown_ = concreteIdentity;
|
|
1410
|
+
loginSessionKnown_ = concreteIdentity;
|
|
1411
|
+
pendingSessionRequestId_ = 0;
|
|
1412
|
+
pendingSessionExpectsLogin_ = false;
|
|
1413
|
+
pendingSessionBrokerId_.clear();
|
|
1414
|
+
pendingSessionUserId_.clear();
|
|
1415
|
+
if (changed || !concreteIdentity) {
|
|
1416
|
+
// A relogin can switch sessions/accounts without a disconnect callback.
|
|
1417
|
+
// Never carry the old account's held/working certainty into the new one.
|
|
1418
|
+
ledgerUncertain_ = true;
|
|
1419
|
+
orderLedgerUncertain_ = true;
|
|
1420
|
+
}
|
|
1421
|
+
if (changed || !concreteIdentity)
|
|
1422
|
+
clearAccountMarginMetadataLocked();
|
|
1423
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
225
1424
|
}
|
|
226
1425
|
|
|
227
1426
|
std::string RiskEngine::resvKey(int frontId, int sessionId,
|
|
@@ -229,24 +1428,92 @@ std::string RiskEngine::resvKey(int frontId, int sessionId,
|
|
|
229
1428
|
return std::to_string(frontId) + ":" + std::to_string(sessionId) + ":" + orderRef;
|
|
230
1429
|
}
|
|
231
1430
|
|
|
1431
|
+
void RiskEngine::rememberTerminalOrderLocked(const std::string &key) {
|
|
1432
|
+
if (!terminalOrderKeySet_.insert(key).second)
|
|
1433
|
+
return;
|
|
1434
|
+
terminalOrderKeys_.push_back(key);
|
|
1435
|
+
while (terminalOrderKeys_.size() > kMaxTerminalOrderTombstones) {
|
|
1436
|
+
std::string expired = std::move(terminalOrderKeys_.front());
|
|
1437
|
+
terminalOrderKeys_.pop_front();
|
|
1438
|
+
terminalOrderKeySet_.erase(expired);
|
|
1439
|
+
auto state = orderStates_.find(expired);
|
|
1440
|
+
if (state != orderStates_.end() && state->second.terminal &&
|
|
1441
|
+
reservations_.count(expired) == 0)
|
|
1442
|
+
orderStates_.erase(state);
|
|
1443
|
+
}
|
|
1444
|
+
}
|
|
1445
|
+
|
|
1446
|
+
void RiskEngine::forgetTerminalOrderLocked(const std::string &key) {
|
|
1447
|
+
if (terminalOrderKeySet_.erase(key) == 0)
|
|
1448
|
+
return;
|
|
1449
|
+
terminalOrderKeys_.erase(
|
|
1450
|
+
std::remove(terminalOrderKeys_.begin(), terminalOrderKeys_.end(), key),
|
|
1451
|
+
terminalOrderKeys_.end());
|
|
1452
|
+
}
|
|
1453
|
+
|
|
1454
|
+
void RiskEngine::pruneEvictedTerminalOrderLocked(const std::string &key) {
|
|
1455
|
+
if (terminalOrderKeySet_.count(key) != 0 || reservations_.count(key) != 0)
|
|
1456
|
+
return;
|
|
1457
|
+
auto state = orderStates_.find(key);
|
|
1458
|
+
if (state != orderStates_.end() && state->second.terminal)
|
|
1459
|
+
orderStates_.erase(state);
|
|
1460
|
+
}
|
|
1461
|
+
|
|
232
1462
|
OpenGate RiskEngine::tryReserveOpen(const std::string &orderRef,
|
|
233
1463
|
const std::string &instrumentId, bool isLong,
|
|
234
|
-
double price, double volume
|
|
235
|
-
|
|
1464
|
+
double price, double volume,
|
|
1465
|
+
char hedgeFlag) {
|
|
1466
|
+
const double globalCap = maxAccountMargin_.load(std::memory_order_relaxed);
|
|
236
1467
|
std::lock_guard<std::mutex> lk(posMutex_);
|
|
237
|
-
const
|
|
1468
|
+
const std::string key = resvKey(myFrontId_, mySessionId_, orderRef);
|
|
1469
|
+
// OrderRef is an idempotency key within a front/session. Never overwrite an
|
|
1470
|
+
// existing reservation/state: doing so loses the original ledger entry and
|
|
1471
|
+
// leaves a phantom pending amount after the duplicate is rejected.
|
|
1472
|
+
if (orderRef.empty() || reservations_.find(key) != reservations_.end() ||
|
|
1473
|
+
orderStates_.find(key) != orderStates_.end())
|
|
1474
|
+
return OpenGate::DuplicateOrderRef;
|
|
1475
|
+
if (sessionIdentityRequired_ && !sessionIdentityKnown_)
|
|
1476
|
+
return OpenGate::MetadataUnavailable;
|
|
1477
|
+
if (instrumentId.empty() || !saneLots(volume) || !validHedgeFlag(hedgeFlag) ||
|
|
1478
|
+
!std::isfinite(price) || price < 0.0)
|
|
1479
|
+
return OpenGate::MetadataUnavailable;
|
|
1480
|
+
|
|
1481
|
+
auto vit = maxPositionVol_.find(instrumentId);
|
|
1482
|
+
auto cit = maxInstrumentMargin_.find(instrumentId);
|
|
1483
|
+
if (ledgerUncertain_ || orderLedgerUncertain_ ||
|
|
1484
|
+
!unsupportedWorkingOrders_.empty())
|
|
1485
|
+
return OpenGate::MetadataUnavailable;
|
|
1486
|
+
if (invalidConfig_.load(std::memory_order_acquire))
|
|
1487
|
+
return OpenGate::MetadataUnavailable;
|
|
1488
|
+
if (unsupportedRiskMutationUsed_ && localControlsEnabledLocked())
|
|
1489
|
+
return OpenGate::MetadataUnavailable;
|
|
1490
|
+
|
|
1491
|
+
// Revalue every existing working order before comparing a monetary cap. A
|
|
1492
|
+
// once-fresh reference cannot remain authoritative for a long-lived order as
|
|
1493
|
+
// the market moves; a stale/missing current quote turns it unknown.
|
|
1494
|
+
if (globalCap > 0.0)
|
|
1495
|
+
refreshAllReservationCostsLocked();
|
|
1496
|
+
else if (cit != maxInstrumentMargin_.end() && cit->second > 0.0)
|
|
1497
|
+
refreshReservationCostsLocked(instrumentId);
|
|
1498
|
+
|
|
1499
|
+
const double reference = refPrice(instrumentId);
|
|
1500
|
+
const bool priceKnown = sanePositive(price) && sanePositive(reference);
|
|
1501
|
+
const double valuationPrice = priceKnown ? std::max(price, reference) : 0.0;
|
|
1502
|
+
double addCost = 0.0;
|
|
1503
|
+
const bool costKnown = priceKnown &&
|
|
1504
|
+
marginCostLocked(instrumentId, isLong, hedgeFlag, valuationPrice, volume,
|
|
1505
|
+
addCost);
|
|
1506
|
+
// Revaluation may insert a missing positions_ entry and rehash the map, so
|
|
1507
|
+
// take this pointer only after all refreshes are complete.
|
|
238
1508
|
const Pos *p = nullptr;
|
|
239
1509
|
auto pit = positions_.find(instrumentId);
|
|
240
1510
|
if (pit != positions_.end())
|
|
241
1511
|
p = &pit->second;
|
|
242
|
-
bool capped = false;
|
|
243
1512
|
|
|
244
1513
|
// 1) per-side volume cap (committed = held + reserved on this side)
|
|
245
|
-
auto vit = maxPositionVol_.find(instrumentId);
|
|
246
1514
|
if (vit != maxPositionVol_.end()) {
|
|
247
1515
|
const double cap = isLong ? vit->second.longMax : vit->second.shortMax;
|
|
248
1516
|
if (cap > 0.0) {
|
|
249
|
-
capped = true;
|
|
250
1517
|
double committed = 0.0;
|
|
251
1518
|
if (p)
|
|
252
1519
|
committed = isLong ? p->longVol + p->longPendVol
|
|
@@ -256,141 +1523,642 @@ OpenGate RiskEngine::tryReserveOpen(const std::string &orderRef,
|
|
|
256
1523
|
}
|
|
257
1524
|
}
|
|
258
1525
|
|
|
259
|
-
// 2) per-instrument
|
|
260
|
-
|
|
261
|
-
if (cit != maxInstrumentCost_.end() && cit->second > 0.0) {
|
|
262
|
-
capped = true;
|
|
1526
|
+
// 2) per-instrument margin cap (both sides, held + reserved)
|
|
1527
|
+
if (cit != maxInstrumentMargin_.end() && cit->second > 0.0) {
|
|
263
1528
|
double instrCost = 0.0;
|
|
264
1529
|
if (p)
|
|
265
1530
|
instrCost = p->longCost + p->longPendCost + p->shortCost + p->shortPendCost;
|
|
266
|
-
if (instrCost
|
|
1531
|
+
if (instrCost >= cit->second)
|
|
1532
|
+
return OpenGate::CostLimit;
|
|
1533
|
+
if ((p && ((p->longVol > 0.0 && !p->longCostKnown) ||
|
|
1534
|
+
(p->shortVol > 0.0 && !p->shortCostKnown) ||
|
|
1535
|
+
p->longPendUnknown > 0 || p->shortPendUnknown > 0)) ||
|
|
1536
|
+
!costKnown)
|
|
1537
|
+
return OpenGate::MetadataUnavailable;
|
|
1538
|
+
if (addCost > cit->second - instrCost)
|
|
267
1539
|
return OpenGate::CostLimit;
|
|
268
1540
|
}
|
|
269
1541
|
|
|
270
|
-
// 3)
|
|
1542
|
+
// 3) account-wide margin cap (whole book, held + reserved)
|
|
271
1543
|
if (globalCap > 0.0) {
|
|
272
|
-
capped = true;
|
|
273
1544
|
double total = 0.0;
|
|
274
1545
|
for (const auto &kv : positions_)
|
|
275
1546
|
total += kv.second.longCost + kv.second.longPendCost +
|
|
276
1547
|
kv.second.shortCost + kv.second.shortPendCost;
|
|
277
|
-
if (total
|
|
1548
|
+
if (total >= globalCap)
|
|
1549
|
+
return OpenGate::CostLimit;
|
|
1550
|
+
for (const auto &kv : positions_)
|
|
1551
|
+
if ((kv.second.longVol > 0.0 && !kv.second.longCostKnown) ||
|
|
1552
|
+
(kv.second.shortVol > 0.0 && !kv.second.shortCostKnown) ||
|
|
1553
|
+
kv.second.longPendUnknown > 0 || kv.second.shortPendUnknown > 0)
|
|
1554
|
+
return OpenGate::MetadataUnavailable;
|
|
1555
|
+
if (!costKnown)
|
|
1556
|
+
return OpenGate::MetadataUnavailable;
|
|
1557
|
+
if (addCost > globalCap - total)
|
|
278
1558
|
return OpenGate::CostLimit;
|
|
279
1559
|
}
|
|
280
1560
|
|
|
281
|
-
//
|
|
282
|
-
//
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
pp.
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
1561
|
+
// Track every accepted open, even when no cap is currently active. A cap
|
|
1562
|
+
// enabled later must still see already-working orders.
|
|
1563
|
+
Pos &pp = positions_[instrumentId];
|
|
1564
|
+
if (isLong) {
|
|
1565
|
+
pp.longPendVol += volume;
|
|
1566
|
+
pp.longPendCost += costKnown ? addCost : 0.0;
|
|
1567
|
+
clampFiniteCost(pp.longPendVol);
|
|
1568
|
+
clampFiniteCost(pp.longPendCost);
|
|
1569
|
+
if (!costKnown)
|
|
1570
|
+
++pp.longPendUnknown;
|
|
1571
|
+
} else {
|
|
1572
|
+
pp.shortPendVol += volume;
|
|
1573
|
+
pp.shortPendCost += costKnown ? addCost : 0.0;
|
|
1574
|
+
clampFiniteCost(pp.shortPendVol);
|
|
1575
|
+
clampFiniteCost(pp.shortPendCost);
|
|
1576
|
+
if (!costKnown)
|
|
1577
|
+
++pp.shortPendUnknown;
|
|
294
1578
|
}
|
|
1579
|
+
reservations_[key] = Reservation{orderRef, "", instrumentId, isLong,
|
|
1580
|
+
hedgeFlag, volume,
|
|
1581
|
+
costKnown ? addCost : 0.0, price, costKnown};
|
|
1582
|
+
indexReservationLocked(key);
|
|
1583
|
+
orderStates_[key] = OrderState{false, volume, 0.0, 0.0, ""};
|
|
1584
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
295
1585
|
return OpenGate::Ok;
|
|
296
1586
|
}
|
|
297
1587
|
|
|
298
1588
|
void RiskEngine::onOrderUpdate(int frontId, int sessionId,
|
|
299
1589
|
const std::string &orderRef,
|
|
300
1590
|
const std::string &instrumentId, bool isOpen,
|
|
301
|
-
bool isLong, char
|
|
302
|
-
double
|
|
1591
|
+
bool isLong, char hedgeFlag, char status,
|
|
1592
|
+
double limitPrice, double volTotal,
|
|
1593
|
+
double volTraded,
|
|
1594
|
+
const std::string &orderSysKey,
|
|
1595
|
+
const std::string &brokerId,
|
|
1596
|
+
const std::string &investorId) {
|
|
303
1597
|
if (!isOpen)
|
|
304
1598
|
return; // only opening orders reserve
|
|
1599
|
+
std::lock_guard<RiskSendMutex> send(sendModeMutex_);
|
|
305
1600
|
std::lock_guard<std::mutex> lk(posMutex_);
|
|
1601
|
+
const AccountScope account = accountScopeLocked(brokerId, investorId);
|
|
1602
|
+
if (account == AccountScope::Foreign)
|
|
1603
|
+
return;
|
|
1604
|
+
if (account == AccountScope::Ambiguous) {
|
|
1605
|
+
orderLedgerUncertain_ = true;
|
|
1606
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
1607
|
+
return;
|
|
1608
|
+
}
|
|
1609
|
+
if (orderRef.empty() || instrumentId.empty() || !validHedgeFlag(hedgeFlag) ||
|
|
1610
|
+
(limitPrice != 0.0 && !sanePositive(limitPrice)) ||
|
|
1611
|
+
!saneNonNegativeLots(volTotal) ||
|
|
1612
|
+
!saneNonNegativeLots(volTraded)) {
|
|
1613
|
+
// For an opening order from this or another terminal, silently dropping a
|
|
1614
|
+
// malformed update can omit working exposure. Preserve safety until the
|
|
1615
|
+
// authoritative working-order snapshot is rebuilt.
|
|
1616
|
+
orderLedgerUncertain_ = true;
|
|
1617
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
1618
|
+
return;
|
|
1619
|
+
}
|
|
306
1620
|
const std::string key = resvKey(frontId, sessionId, orderRef);
|
|
1621
|
+
if (!orderSysKey.empty()) {
|
|
1622
|
+
auto indexed = reservationKeyBySys_.find(orderSysKey);
|
|
1623
|
+
if (indexed != reservationKeyBySys_.end() && indexed->second != key) {
|
|
1624
|
+
// Exchange order identity must be one-to-one. Overwriting this index
|
|
1625
|
+
// could make a later Trade release the wrong terminal/session order.
|
|
1626
|
+
orderLedgerUncertain_ = true;
|
|
1627
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
1628
|
+
return;
|
|
1629
|
+
}
|
|
1630
|
+
}
|
|
307
1631
|
// The order still holds live working volume UNLESS it has reached a terminal
|
|
308
1632
|
// state. Release only on a definitively-done status: AllTraded '0',
|
|
309
1633
|
// PartTradedNotQueueing '2', NoTradeNotQueueing '4', Canceled '5'. Everything
|
|
310
|
-
// else
|
|
1634
|
+
// else: queueing ('1'/'3') and the transient pre-trade states a conditional
|
|
311
1635
|
// order can report before '3' (Unknown 'a', NotTouched 'b', Touched 'c'), plus
|
|
312
|
-
// any status CTP might add later
|
|
1636
|
+
// any status CTP might add later keeps the reservation. Releasing on a
|
|
313
1637
|
// transient status that merely precedes '3' would briefly drop the cap for
|
|
314
1638
|
// this order's volume (a burst could then slip past). Conservative by design:
|
|
315
1639
|
// hold the reservation until the order is provably finished.
|
|
316
|
-
const bool terminal =
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
1640
|
+
const bool terminal = terminalOrderStatus(status);
|
|
1641
|
+
if (volTraded > volTotal) {
|
|
1642
|
+
// The malformed row may describe fills and/or working exposure larger than
|
|
1643
|
+
// the original order. Retaining one old reservation is not a complete bound.
|
|
1644
|
+
orderLedgerUncertain_ = true;
|
|
1645
|
+
ledgerUncertain_ = true;
|
|
1646
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
1647
|
+
return;
|
|
1648
|
+
}
|
|
1649
|
+
const double working = terminal ? 0.0 : volTotal - volTraded;
|
|
323
1650
|
|
|
324
1651
|
auto rit = reservations_.find(key);
|
|
1652
|
+
if (rit != reservations_.end()) {
|
|
1653
|
+
const Reservation &r = rit->second;
|
|
1654
|
+
if (r.instrumentId != instrumentId || r.isLong != isLong ||
|
|
1655
|
+
r.hedgeFlag != hedgeFlag ||
|
|
1656
|
+
(!r.orderSysKey.empty() && !orderSysKey.empty() &&
|
|
1657
|
+
r.orderSysKey != orderSysKey)) {
|
|
1658
|
+
// Retaining the old reservation alone is not enough: the conflicting
|
|
1659
|
+
// callback may describe a larger or different live order. Require a full
|
|
1660
|
+
// order reconciliation before any further opening insert.
|
|
1661
|
+
orderLedgerUncertain_ = true;
|
|
1662
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
1663
|
+
return;
|
|
1664
|
+
}
|
|
1665
|
+
}
|
|
1666
|
+
|
|
1667
|
+
auto sit = orderStates_.find(key);
|
|
1668
|
+
if (sit != orderStates_.end()) {
|
|
1669
|
+
OrderState &s = sit->second;
|
|
1670
|
+
if (s.terminal) {
|
|
1671
|
+
if (terminal) {
|
|
1672
|
+
// Only a matching concrete exchange identity proves this is a replay.
|
|
1673
|
+
// A terminal callback with a different/missing fingerprint may be a
|
|
1674
|
+
// newly completed order after front/session/ref reuse; ignoring it can
|
|
1675
|
+
// omit its not-yet-delivered fill reservation.
|
|
1676
|
+
if (!s.orderSysKey.empty() && !orderSysKey.empty() &&
|
|
1677
|
+
s.orderSysKey == orderSysKey)
|
|
1678
|
+
return;
|
|
1679
|
+
orderLedgerUncertain_ = true;
|
|
1680
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
1681
|
+
return;
|
|
1682
|
+
}
|
|
1683
|
+
// A concrete matching exchange id proves this is a stale replay of the
|
|
1684
|
+
// terminal order. A different/missing fingerprint is ambiguous: front,
|
|
1685
|
+
// session and OrderRef can be reused after a long-lived client's front
|
|
1686
|
+
// reconnect, so silently ignoring it could omit a genuinely new order.
|
|
1687
|
+
if (!s.orderSysKey.empty() && !orderSysKey.empty() &&
|
|
1688
|
+
s.orderSysKey == orderSysKey)
|
|
1689
|
+
return;
|
|
1690
|
+
orderLedgerUncertain_ = true;
|
|
1691
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
1692
|
+
return;
|
|
1693
|
+
}
|
|
1694
|
+
if (!s.orderSysKey.empty() && !orderSysKey.empty() &&
|
|
1695
|
+
s.orderSysKey != orderSysKey) {
|
|
1696
|
+
orderLedgerUncertain_ = true;
|
|
1697
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
1698
|
+
return;
|
|
1699
|
+
}
|
|
1700
|
+
if (!terminal) {
|
|
1701
|
+
// Working remainder and traded volume should be monotonic for an ordinary
|
|
1702
|
+
// order. A Modify action can legitimately increase the remainder, while
|
|
1703
|
+
// an out-of-order replay can appear identical. Do not guess: retain the
|
|
1704
|
+
// conservative prior exposure and block opens until syncOrders().
|
|
1705
|
+
if (volTraded < s.reportedTraded || working > s.remaining) {
|
|
1706
|
+
orderLedgerUncertain_ = true;
|
|
1707
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
1708
|
+
return;
|
|
1709
|
+
}
|
|
1710
|
+
}
|
|
1711
|
+
s.terminal = terminal;
|
|
1712
|
+
s.remaining = working;
|
|
1713
|
+
s.reportedTraded = std::max(s.reportedTraded, volTraded);
|
|
1714
|
+
if (s.orderSysKey.empty() && !orderSysKey.empty())
|
|
1715
|
+
s.orderSysKey = orderSysKey;
|
|
1716
|
+
} else {
|
|
1717
|
+
sit = orderStates_
|
|
1718
|
+
.emplace(key, OrderState{terminal, working, volTraded, 0.0,
|
|
1719
|
+
orderSysKey})
|
|
1720
|
+
.first;
|
|
1721
|
+
}
|
|
1722
|
+
OrderState &state = sit->second;
|
|
1723
|
+
if (terminal)
|
|
1724
|
+
rememberTerminalOrderLocked(key);
|
|
1725
|
+
if (!orderSysKey.empty()) {
|
|
1726
|
+
auto unmatched = unmatchedFillsBySys_.find(orderSysKey);
|
|
1727
|
+
if (unmatched != unmatchedFillsBySys_.end()) {
|
|
1728
|
+
if (!unmatched->second.orderRef.empty() &&
|
|
1729
|
+
unmatched->second.orderRef != orderRef) {
|
|
1730
|
+
orderLedgerUncertain_ = true;
|
|
1731
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
1732
|
+
return;
|
|
1733
|
+
}
|
|
1734
|
+
state.appliedTraded += unmatched->second.volume;
|
|
1735
|
+
clampFiniteCost(state.appliedTraded);
|
|
1736
|
+
unmatchedFillsBySys_.erase(unmatched);
|
|
1737
|
+
}
|
|
1738
|
+
}
|
|
1739
|
+
if (rit != reservations_.end() &&
|
|
1740
|
+
observeInsertRequestLocked(key, rit->second)) {
|
|
1741
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
1742
|
+
return;
|
|
1743
|
+
}
|
|
1744
|
+
double desiredVol =
|
|
1745
|
+
working + std::max(0.0, state.reportedTraded - state.appliedTraded);
|
|
1746
|
+
clampFiniteCost(desiredVol);
|
|
1747
|
+
|
|
325
1748
|
if (rit == reservations_.end()) {
|
|
326
|
-
//
|
|
327
|
-
//
|
|
328
|
-
if (desiredVol <= 0.0
|
|
1749
|
+
// Track every working or not-yet-delivered fill, including orders sent
|
|
1750
|
+
// before a cap existed and orders placed by another terminal.
|
|
1751
|
+
if (desiredVol <= 0.0) {
|
|
1752
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
329
1753
|
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
1754
|
}
|
|
338
|
-
reservations_[key] = Reservation{
|
|
1755
|
+
reservations_[key] = Reservation{orderRef, orderSysKey, instrumentId,
|
|
1756
|
+
isLong, hedgeFlag, 0.0, 0.0, limitPrice,
|
|
1757
|
+
true};
|
|
1758
|
+
indexReservationLocked(key);
|
|
1759
|
+
updateReservationExposureLocked(reservations_[key], desiredVol,
|
|
1760
|
+
limitPrice);
|
|
1761
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
339
1762
|
return;
|
|
340
1763
|
}
|
|
341
1764
|
|
|
342
|
-
// Reconcile
|
|
1765
|
+
// Reconcile to working remainder + fills reported by Order but not yet applied
|
|
1766
|
+
// by Trade. This makes either callback ordering conservative and gap-free.
|
|
343
1767
|
Reservation &r = rit->second;
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
1768
|
+
if (r.orderSysKey.empty() && !orderSysKey.empty()) {
|
|
1769
|
+
r.orderSysKey = orderSysKey;
|
|
1770
|
+
reservationKeyBySys_[orderSysKey] = key;
|
|
1771
|
+
}
|
|
1772
|
+
updateReservationExposureLocked(r, desiredVol, limitPrice);
|
|
1773
|
+
if (desiredVol <= 0.0) {
|
|
1774
|
+
Reservation done = r;
|
|
1775
|
+
unindexReservationLocked(key, done);
|
|
1776
|
+
reservations_.erase(rit);
|
|
1777
|
+
}
|
|
1778
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
1779
|
+
}
|
|
1780
|
+
|
|
1781
|
+
void RiskEngine::onUnsupportedOrderUpdate(int frontId, int sessionId,
|
|
1782
|
+
const std::string &orderRef,
|
|
1783
|
+
char status,
|
|
1784
|
+
const std::string &orderSysKey,
|
|
1785
|
+
const std::string &brokerId,
|
|
1786
|
+
const std::string &investorId) {
|
|
1787
|
+
std::lock_guard<RiskSendMutex> send(sendModeMutex_);
|
|
1788
|
+
std::lock_guard<std::mutex> lk(posMutex_);
|
|
1789
|
+
const AccountScope account = accountScopeLocked(brokerId, investorId);
|
|
1790
|
+
if (account == AccountScope::Foreign)
|
|
1791
|
+
return;
|
|
1792
|
+
if (account == AccountScope::Ambiguous) {
|
|
1793
|
+
orderLedgerUncertain_ = true;
|
|
1794
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
1795
|
+
return;
|
|
1796
|
+
}
|
|
1797
|
+
if (orderRef.empty()) {
|
|
1798
|
+
orderLedgerUncertain_ = true;
|
|
1799
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
1800
|
+
return;
|
|
1801
|
+
}
|
|
1802
|
+
const std::string key = resvKey(frontId, sessionId, orderRef);
|
|
1803
|
+
auto boundReservation = reservations_.find(key);
|
|
1804
|
+
if (boundReservation != reservations_.end() &&
|
|
1805
|
+
observeInsertRequestLocked(key, boundReservation->second)) {
|
|
1806
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
1807
|
+
return;
|
|
1808
|
+
}
|
|
1809
|
+
bool changed = false;
|
|
1810
|
+
auto state = orderStates_.find(key);
|
|
1811
|
+
if (state != orderStates_.end()) {
|
|
1812
|
+
if (state->second.terminal && terminalOrderStatus(status)) {
|
|
1813
|
+
if (!state->second.orderSysKey.empty() && !orderSysKey.empty() &&
|
|
1814
|
+
state->second.orderSysKey == orderSysKey)
|
|
1815
|
+
return; // proven replay of the same terminal order
|
|
1816
|
+
orderLedgerUncertain_ = true;
|
|
1817
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
1818
|
+
return;
|
|
1819
|
+
}
|
|
1820
|
+
const std::string &knownSys = state->second.orderSysKey;
|
|
1821
|
+
if (!knownSys.empty() && !orderSysKey.empty() && knownSys != orderSysKey) {
|
|
1822
|
+
orderLedgerUncertain_ = true;
|
|
1823
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
1824
|
+
return;
|
|
1825
|
+
}
|
|
1826
|
+
if (state->second.terminal && !terminalOrderStatus(status)) {
|
|
1827
|
+
if (!knownSys.empty() && !orderSysKey.empty() && knownSys == orderSysKey)
|
|
1828
|
+
return; // known stale replay
|
|
1829
|
+
orderLedgerUncertain_ = true;
|
|
1830
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
1831
|
+
return;
|
|
1832
|
+
}
|
|
1833
|
+
}
|
|
1834
|
+
if (terminalOrderStatus(status)) {
|
|
1835
|
+
auto reservation = reservations_.find(key);
|
|
1836
|
+
if (reservation != reservations_.end()) {
|
|
1837
|
+
updateReservationExposureLocked(reservation->second, 0.0,
|
|
1838
|
+
reservation->second.price);
|
|
1839
|
+
Reservation done = reservation->second;
|
|
1840
|
+
unindexReservationLocked(key, done);
|
|
1841
|
+
reservations_.erase(reservation);
|
|
1842
|
+
changed = true;
|
|
1843
|
+
}
|
|
1844
|
+
changed = unsupportedWorkingOrders_.erase(key) != 0 || changed;
|
|
1845
|
+
if (state == orderStates_.end()) {
|
|
1846
|
+
orderStates_[key] = OrderState{true, 0.0, 0.0, 0.0, orderSysKey};
|
|
1847
|
+
changed = true;
|
|
1848
|
+
} else if (!state->second.terminal) {
|
|
1849
|
+
state->second.terminal = true;
|
|
1850
|
+
state->second.remaining = 0.0;
|
|
1851
|
+
if (state->second.orderSysKey.empty() && !orderSysKey.empty())
|
|
1852
|
+
state->second.orderSysKey = orderSysKey;
|
|
1853
|
+
changed = true;
|
|
1854
|
+
}
|
|
1855
|
+
rememberTerminalOrderLocked(key);
|
|
350
1856
|
} else {
|
|
351
|
-
|
|
352
|
-
|
|
1857
|
+
if (state == orderStates_.end())
|
|
1858
|
+
orderStates_[key] = OrderState{false, 0.0, 0.0, 0.0, orderSysKey};
|
|
1859
|
+
else if (state->second.orderSysKey.empty() && !orderSysKey.empty())
|
|
1860
|
+
state->second.orderSysKey = orderSysKey;
|
|
1861
|
+
changed = unsupportedWorkingOrders_.insert(key).second || changed;
|
|
1862
|
+
}
|
|
1863
|
+
if (changed)
|
|
1864
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
1865
|
+
}
|
|
1866
|
+
|
|
1867
|
+
bool RiskEngine::bindInsertRequest(int requestId,
|
|
1868
|
+
const std::string &orderRef) {
|
|
1869
|
+
std::lock_guard<RiskSendMutex> send(sendModeMutex_);
|
|
1870
|
+
std::lock_guard<std::mutex> lk(posMutex_);
|
|
1871
|
+
const std::string key = resvKey(myFrontId_, mySessionId_, orderRef);
|
|
1872
|
+
auto rit = reservations_.find(key);
|
|
1873
|
+
const bool bindable = requestId > 0 && !orderRef.empty() &&
|
|
1874
|
+
rit != reservations_.end() && rit->second.orderRef == orderRef &&
|
|
1875
|
+
rit->second.insertBindingToken == 0 &&
|
|
1876
|
+
insertRequests_.find(requestId) == insertRequests_.end();
|
|
1877
|
+
if (!bindable) {
|
|
1878
|
+
// The request has not reached CTP yet. Roll back only the exact unbound
|
|
1879
|
+
// reservation just created by this admission attempt; never disturb a
|
|
1880
|
+
// reservation already owned by another request.
|
|
1881
|
+
if (rit != reservations_.end() && rit->second.orderRef == orderRef &&
|
|
1882
|
+
rit->second.insertBindingToken == 0) {
|
|
1883
|
+
updateReservationExposureLocked(rit->second, 0.0, rit->second.price);
|
|
1884
|
+
Reservation undone = rit->second;
|
|
1885
|
+
unindexReservationLocked(key, undone);
|
|
1886
|
+
reservations_.erase(rit);
|
|
1887
|
+
auto state = orderStates_.find(key);
|
|
1888
|
+
if (state != orderStates_.end() && !state->second.terminal)
|
|
1889
|
+
orderStates_.erase(state);
|
|
1890
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
1891
|
+
}
|
|
1892
|
+
return false;
|
|
1893
|
+
}
|
|
1894
|
+
|
|
1895
|
+
uint64_t token = nextInsertBindingToken_++;
|
|
1896
|
+
if (token == 0) { // practically unreachable wrap; zero is the unbound marker
|
|
1897
|
+
token = nextInsertBindingToken_++;
|
|
1898
|
+
if (token == 0)
|
|
1899
|
+
token = 1;
|
|
353
1900
|
}
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
1901
|
+
rit->second.insertRequestId = requestId;
|
|
1902
|
+
rit->second.insertBindingToken = token;
|
|
1903
|
+
insertRequests_.emplace(
|
|
1904
|
+
requestId, InsertRequestBinding{key, orderRef, token,
|
|
1905
|
+
InsertRequestState::Pending});
|
|
1906
|
+
insertRequestOrder_.emplace_back(requestId, token);
|
|
1907
|
+
while (insertRequestOrder_.size() > kMaxInsertRequestBindings) {
|
|
1908
|
+
const auto expired = insertRequestOrder_.front();
|
|
1909
|
+
insertRequestOrder_.pop_front();
|
|
1910
|
+
auto old = insertRequests_.find(expired.first);
|
|
1911
|
+
if (old != insertRequests_.end() && old->second.token == expired.second)
|
|
1912
|
+
insertRequests_.erase(old);
|
|
359
1913
|
}
|
|
1914
|
+
return true;
|
|
360
1915
|
}
|
|
361
1916
|
|
|
362
|
-
void RiskEngine::
|
|
1917
|
+
void RiskEngine::rejectInsertByRequest(int requestId,
|
|
1918
|
+
const std::string &orderRef,
|
|
1919
|
+
const std::string &brokerId,
|
|
1920
|
+
const std::string &investorId) {
|
|
1921
|
+
std::lock_guard<RiskSendMutex> send(sendModeMutex_);
|
|
363
1922
|
std::lock_guard<std::mutex> lk(posMutex_);
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
if (rit == reservations_.end())
|
|
1923
|
+
const AccountScope account = accountScopeLocked(brokerId, investorId);
|
|
1924
|
+
if (account == AccountScope::Foreign)
|
|
367
1925
|
return;
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
1926
|
+
if (account == AccountScope::Ambiguous) {
|
|
1927
|
+
orderLedgerUncertain_ = true;
|
|
1928
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
1929
|
+
return;
|
|
1930
|
+
}
|
|
1931
|
+
auto binding = insertRequests_.find(requestId);
|
|
1932
|
+
if (binding == insertRequests_.end() ||
|
|
1933
|
+
(!orderRef.empty() && binding->second.orderRef != orderRef)) {
|
|
1934
|
+
// The response cannot be attributed to one exact generation. It may be an
|
|
1935
|
+
// evicted/very-late response; guessing the current session would fail open.
|
|
1936
|
+
orderLedgerUncertain_ = true;
|
|
1937
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
1938
|
+
return;
|
|
1939
|
+
}
|
|
1940
|
+
InsertRequestBinding &bound = binding->second;
|
|
1941
|
+
const std::string &boundOrderRef = bound.orderRef;
|
|
1942
|
+
if (bound.state == InsertRequestState::Rejected)
|
|
1943
|
+
return; // idempotent duplicate rejection
|
|
1944
|
+
|
|
1945
|
+
auto reservation = reservations_.find(bound.reservationKey);
|
|
1946
|
+
const bool ownsReservation = reservation != reservations_.end() &&
|
|
1947
|
+
reservation->second.orderRef == boundOrderRef &&
|
|
1948
|
+
reservation->second.insertRequestId == requestId &&
|
|
1949
|
+
reservation->second.insertBindingToken == bound.token;
|
|
1950
|
+
auto state = orderStates_.find(bound.reservationKey);
|
|
1951
|
+
const bool hasLiveState = state != orderStates_.end() &&
|
|
1952
|
+
!state->second.terminal;
|
|
1953
|
+
|
|
1954
|
+
if (bound.state == InsertRequestState::Pending && ownsReservation) {
|
|
1955
|
+
updateReservationExposureLocked(reservation->second, 0.0,
|
|
1956
|
+
reservation->second.price);
|
|
1957
|
+
Reservation rejected = reservation->second;
|
|
1958
|
+
unindexReservationLocked(bound.reservationKey, rejected);
|
|
1959
|
+
reservations_.erase(reservation);
|
|
1960
|
+
OrderState &terminal = orderStates_[bound.reservationKey];
|
|
1961
|
+
terminal.terminal = true;
|
|
1962
|
+
terminal.remaining = 0.0;
|
|
1963
|
+
if (terminal.orderSysKey.empty() && !rejected.orderSysKey.empty())
|
|
1964
|
+
terminal.orderSysKey = rejected.orderSysKey;
|
|
1965
|
+
rememberTerminalOrderLocked(bound.reservationKey);
|
|
1966
|
+
bound.state = InsertRequestState::Rejected;
|
|
1967
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
1968
|
+
return;
|
|
1969
|
+
}
|
|
1970
|
+
|
|
1971
|
+
if (ownsReservation || hasLiveState ||
|
|
1972
|
+
(reservation != reservations_.end() &&
|
|
1973
|
+
reservation->second.orderRef == boundOrderRef)) {
|
|
1974
|
+
// An OnRtnOrder already proved this generation live, or the same key has
|
|
1975
|
+
// since been reused/rebuilt with different ownership. Never delete it.
|
|
1976
|
+
orderLedgerUncertain_ = true;
|
|
1977
|
+
bound.state = InsertRequestState::Rejected;
|
|
1978
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
1979
|
+
return;
|
|
1980
|
+
}
|
|
1981
|
+
|
|
1982
|
+
// An authoritative snapshot or terminal OnRtnOrder has already removed this
|
|
1983
|
+
// generation. Remember the rejection so a replay stays idempotent.
|
|
1984
|
+
bound.state = InsertRequestState::Rejected;
|
|
1985
|
+
}
|
|
1986
|
+
|
|
1987
|
+
void RiskEngine::rejectInsertUnscoped(const std::string &orderRef,
|
|
1988
|
+
const std::string &brokerId,
|
|
1989
|
+
const std::string &investorId) {
|
|
1990
|
+
std::lock_guard<RiskSendMutex> send(sendModeMutex_);
|
|
1991
|
+
std::lock_guard<std::mutex> lk(posMutex_);
|
|
1992
|
+
const AccountScope account = accountScopeLocked(brokerId, investorId);
|
|
1993
|
+
if (account == AccountScope::Foreign)
|
|
1994
|
+
return;
|
|
1995
|
+
if (account == AccountScope::Ambiguous) {
|
|
1996
|
+
orderLedgerUncertain_ = true;
|
|
1997
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
1998
|
+
return;
|
|
1999
|
+
}
|
|
2000
|
+
bool live = false;
|
|
2001
|
+
if (!orderRef.empty()) {
|
|
2002
|
+
auto refs = reservationKeysByRef_.find(orderRef);
|
|
2003
|
+
live = refs != reservationKeysByRef_.end() && !refs->second.empty();
|
|
373
2004
|
} else {
|
|
374
|
-
|
|
375
|
-
|
|
2005
|
+
live = !reservations_.empty();
|
|
2006
|
+
}
|
|
2007
|
+
if (!live) {
|
|
2008
|
+
for (const auto &entry : insertRequests_) {
|
|
2009
|
+
const InsertRequestBinding &binding = entry.second;
|
|
2010
|
+
if (binding.state == InsertRequestState::Rejected ||
|
|
2011
|
+
(!orderRef.empty() && binding.orderRef != orderRef))
|
|
2012
|
+
continue;
|
|
2013
|
+
auto reservation = reservations_.find(binding.reservationKey);
|
|
2014
|
+
auto state = orderStates_.find(binding.reservationKey);
|
|
2015
|
+
if ((reservation != reservations_.end() &&
|
|
2016
|
+
reservation->second.insertBindingToken == binding.token) ||
|
|
2017
|
+
(state != orderStates_.end() && !state->second.terminal)) {
|
|
2018
|
+
live = true;
|
|
2019
|
+
break;
|
|
2020
|
+
}
|
|
2021
|
+
}
|
|
376
2022
|
}
|
|
377
|
-
|
|
2023
|
+
if (!live)
|
|
2024
|
+
return;
|
|
2025
|
+
// OnErrRtnOrderInsert supplies neither request id nor session. Retaining the
|
|
2026
|
+
// reservation can over-block, but releasing by a reused ref can under-count.
|
|
2027
|
+
orderLedgerUncertain_ = true;
|
|
2028
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
378
2029
|
}
|
|
379
2030
|
|
|
380
|
-
void RiskEngine::
|
|
2031
|
+
void RiskEngine::rollbackInsertRequest(int requestId,
|
|
2032
|
+
const std::string &orderRef) {
|
|
2033
|
+
std::lock_guard<RiskSendMutex> send(sendModeMutex_);
|
|
381
2034
|
std::lock_guard<std::mutex> lk(posMutex_);
|
|
2035
|
+
auto binding = insertRequests_.find(requestId);
|
|
2036
|
+
if (binding == insertRequests_.end() || orderRef.empty() ||
|
|
2037
|
+
binding->second.orderRef != orderRef) {
|
|
2038
|
+
orderLedgerUncertain_ = true;
|
|
2039
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
2040
|
+
return;
|
|
2041
|
+
}
|
|
2042
|
+
const InsertRequestBinding bound = binding->second;
|
|
2043
|
+
auto reservation = reservations_.find(bound.reservationKey);
|
|
2044
|
+
const bool ownsReservation = reservation != reservations_.end() &&
|
|
2045
|
+
reservation->second.insertRequestId == requestId &&
|
|
2046
|
+
reservation->second.insertBindingToken == bound.token;
|
|
2047
|
+
if (bound.state != InsertRequestState::Pending || !ownsReservation) {
|
|
2048
|
+
// A callback occurred inline despite a local/nonzero return, or ownership
|
|
2049
|
+
// changed unexpectedly. Preserve exposure and reconcile instead of erasing.
|
|
2050
|
+
if (bound.state != InsertRequestState::Rejected) {
|
|
2051
|
+
orderLedgerUncertain_ = true;
|
|
2052
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
2053
|
+
}
|
|
2054
|
+
return;
|
|
2055
|
+
}
|
|
2056
|
+
updateReservationExposureLocked(reservation->second, 0.0,
|
|
2057
|
+
reservation->second.price);
|
|
2058
|
+
Reservation undone = reservation->second;
|
|
2059
|
+
unindexReservationLocked(bound.reservationKey, undone);
|
|
2060
|
+
reservations_.erase(reservation);
|
|
2061
|
+
auto state = orderStates_.find(bound.reservationKey);
|
|
2062
|
+
if (state != orderStates_.end() && !state->second.terminal)
|
|
2063
|
+
orderStates_.erase(state);
|
|
2064
|
+
insertRequests_.erase(binding);
|
|
2065
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
2066
|
+
}
|
|
2067
|
+
|
|
2068
|
+
void RiskEngine::clearPendingLocked() {
|
|
382
2069
|
// Authoritative resync: drop all reservations and the in-flight portion of
|
|
383
2070
|
// every position, then re-reserve from the live working orders. Held (filled)
|
|
384
2071
|
// position is untouched - that's reconciled by syncPositions.
|
|
385
2072
|
for (auto &kv : positions_) {
|
|
386
2073
|
kv.second.longPendVol = kv.second.longPendCost = 0.0;
|
|
387
2074
|
kv.second.shortPendVol = kv.second.shortPendCost = 0.0;
|
|
2075
|
+
kv.second.longPendUnknown = kv.second.shortPendUnknown = 0;
|
|
388
2076
|
}
|
|
389
2077
|
reservations_.clear();
|
|
2078
|
+
reservationKeysByRef_.clear();
|
|
2079
|
+
reservationKeyBySys_.clear();
|
|
2080
|
+
unsupportedWorkingOrders_.clear();
|
|
2081
|
+
orderLedgerUncertain_ = false;
|
|
2082
|
+
// The authoritative order snapshot carries VolumeTraded for every working
|
|
2083
|
+
// row and rebuilds appliedTraded from it, so pre-snapshot Trade->Order hints
|
|
2084
|
+
// are no longer needed.
|
|
2085
|
+
unmatchedFillsBySys_.clear();
|
|
2086
|
+
for (auto it = orderStates_.begin(); it != orderStates_.end();) {
|
|
2087
|
+
if (!it->second.terminal || terminalOrderKeySet_.count(it->first) == 0)
|
|
2088
|
+
it = orderStates_.erase(it);
|
|
2089
|
+
else
|
|
2090
|
+
++it;
|
|
2091
|
+
}
|
|
2092
|
+
}
|
|
2093
|
+
|
|
2094
|
+
bool RiskEngine::validOpenOrderSnapshot(
|
|
2095
|
+
const std::vector<OpenOrderInfo> &orders) {
|
|
2096
|
+
std::unordered_map<std::string, const OpenOrderInfo *> byKey;
|
|
2097
|
+
std::unordered_map<std::string, std::string> bySys;
|
|
2098
|
+
for (const auto &o : orders) {
|
|
2099
|
+
if (o.orderRef.empty() || o.instrumentId.empty() ||
|
|
2100
|
+
(o.supportedSingleLeg && !validHedgeFlag(o.hedgeFlag)) ||
|
|
2101
|
+
!saneNonNegativeLots(o.vol) || !saneNonNegativeLots(o.traded) ||
|
|
2102
|
+
(o.price != 0.0 && !sanePositive(o.price)))
|
|
2103
|
+
return false;
|
|
2104
|
+
const std::string key = resvKey(o.frontId, o.sessionId, o.orderRef);
|
|
2105
|
+
auto [duplicate, inserted] = byKey.emplace(key, &o);
|
|
2106
|
+
if (!inserted) {
|
|
2107
|
+
const OpenOrderInfo &old = *duplicate->second;
|
|
2108
|
+
if (old.instrumentId != o.instrumentId || old.isLong != o.isLong ||
|
|
2109
|
+
old.hedgeFlag != o.hedgeFlag || old.vol != o.vol ||
|
|
2110
|
+
old.price != o.price || old.traded != o.traded ||
|
|
2111
|
+
old.orderSysKey != o.orderSysKey ||
|
|
2112
|
+
old.supportedSingleLeg != o.supportedSingleLeg)
|
|
2113
|
+
return false;
|
|
2114
|
+
}
|
|
2115
|
+
if (!o.orderSysKey.empty()) {
|
|
2116
|
+
auto [sys, sysInserted] = bySys.emplace(o.orderSysKey, key);
|
|
2117
|
+
if (!sysInserted && sys->second != key)
|
|
2118
|
+
return false;
|
|
2119
|
+
}
|
|
2120
|
+
}
|
|
2121
|
+
return true;
|
|
2122
|
+
}
|
|
2123
|
+
|
|
2124
|
+
bool RiskEngine::rebuildOpenReservationsLocked(
|
|
2125
|
+
const std::vector<OpenOrderInfo> &orders) {
|
|
2126
|
+
// Decide every terminal-key collision before clearing live reservations. A
|
|
2127
|
+
// matching concrete sys id proves the query row is a stale replay and can be
|
|
2128
|
+
// skipped. A different concrete id proves key reuse and may supersede the
|
|
2129
|
+
// tombstone. Without both fingerprints the snapshot is ambiguous and must
|
|
2130
|
+
// leave the current ledger intact and fail closed.
|
|
2131
|
+
for (const auto &o : orders) {
|
|
2132
|
+
const std::string key = resvKey(o.frontId, o.sessionId, o.orderRef);
|
|
2133
|
+
auto tomb = orderStates_.find(key);
|
|
2134
|
+
if (tomb != orderStates_.end() && tomb->second.terminal &&
|
|
2135
|
+
(tomb->second.orderSysKey.empty() || o.orderSysKey.empty())) {
|
|
2136
|
+
orderLedgerUncertain_ = true;
|
|
2137
|
+
return false;
|
|
2138
|
+
}
|
|
2139
|
+
}
|
|
2140
|
+
clearPendingLocked();
|
|
390
2141
|
for (const auto &o : orders) {
|
|
391
|
-
if (o.vol <= 0.0)
|
|
392
|
-
continue;
|
|
393
2142
|
const std::string key = resvKey(o.frontId, o.sessionId, o.orderRef);
|
|
2143
|
+
auto tomb = orderStates_.find(key);
|
|
2144
|
+
if (tomb != orderStates_.end() && tomb->second.terminal) {
|
|
2145
|
+
if (tomb->second.orderSysKey == o.orderSysKey)
|
|
2146
|
+
continue; // stale working replay of this exact terminal order
|
|
2147
|
+
// This snapshot was revision-checked against every realtime callback and
|
|
2148
|
+
// is authoritative for currently working orders. A live row with a reused
|
|
2149
|
+
// front/session/ref and a different concrete exchange id therefore
|
|
2150
|
+
// supersedes an older terminal tombstone.
|
|
2151
|
+
forgetTerminalOrderLocked(key);
|
|
2152
|
+
orderStates_.erase(tomb);
|
|
2153
|
+
}
|
|
2154
|
+
if (!o.supportedSingleLeg) {
|
|
2155
|
+
unsupportedWorkingOrders_.insert(key);
|
|
2156
|
+
orderStates_[key] = OrderState{false, 0.0, 0.0, 0.0,
|
|
2157
|
+
o.orderSysKey};
|
|
2158
|
+
continue;
|
|
2159
|
+
}
|
|
2160
|
+
if (o.vol <= 0.0)
|
|
2161
|
+
continue; // a zero working remainder contributes no exposure
|
|
394
2162
|
// Dedupe by key: reqQryOrder can return the same working order more than once
|
|
395
2163
|
// (paged / duplicate rows). Each (front:session:ref) must reserve exactly
|
|
396
2164
|
// once; a duplicate would inflate the pending counters while reservations_
|
|
@@ -398,64 +2166,142 @@ void RiskEngine::rebuildOpenReservations(const std::vector<OpenOrderInfo> &order
|
|
|
398
2166
|
// entry to release it - it would over-block opens until the next full resync.
|
|
399
2167
|
if (reservations_.count(key))
|
|
400
2168
|
continue;
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
2169
|
+
reservations_[key] = Reservation{o.orderRef, o.orderSysKey, o.instrumentId,
|
|
2170
|
+
o.isLong, o.hedgeFlag, 0.0, 0.0, o.price,
|
|
2171
|
+
true};
|
|
2172
|
+
indexReservationLocked(key);
|
|
2173
|
+
// Use the same conservative valuation as realtime order updates: max of a
|
|
2174
|
+
// positive limit and a fresh reference, with missing/stale price or margin
|
|
2175
|
+
// metadata represented as unknown so monetary gates fail closed.
|
|
2176
|
+
updateReservationExposureLocked(reservations_[key], o.vol, o.price);
|
|
2177
|
+
orderStates_[key] =
|
|
2178
|
+
OrderState{false, o.vol, o.traded, o.traded, o.orderSysKey};
|
|
2179
|
+
}
|
|
2180
|
+
return true;
|
|
2181
|
+
}
|
|
2182
|
+
|
|
2183
|
+
void RiskEngine::rebuildOpenReservations(
|
|
2184
|
+
const std::vector<OpenOrderInfo> &orders) {
|
|
2185
|
+
if (!validOpenOrderSnapshot(orders)) {
|
|
2186
|
+
markOrderLedgerUncertain();
|
|
2187
|
+
return;
|
|
2188
|
+
}
|
|
2189
|
+
std::lock_guard<RiskSendMutex> send(sendModeMutex_);
|
|
2190
|
+
std::lock_guard<std::mutex> lk(posMutex_);
|
|
2191
|
+
(void)rebuildOpenReservationsLocked(orders);
|
|
2192
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
2193
|
+
}
|
|
2194
|
+
|
|
2195
|
+
bool RiskEngine::rebuildOpenReservationsIfRevision(
|
|
2196
|
+
uint64_t expected, const std::vector<OpenOrderInfo> &orders) {
|
|
2197
|
+
if (!validOpenOrderSnapshot(orders)) {
|
|
2198
|
+
markOrderLedgerUncertain();
|
|
2199
|
+
return false;
|
|
411
2200
|
}
|
|
2201
|
+
std::lock_guard<RiskSendMutex> send(sendModeMutex_);
|
|
2202
|
+
std::lock_guard<std::mutex> lk(posMutex_);
|
|
2203
|
+
if (revision_.load(std::memory_order_relaxed) != expected)
|
|
2204
|
+
return false;
|
|
2205
|
+
if (!rebuildOpenReservationsLocked(orders)) {
|
|
2206
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
2207
|
+
return false;
|
|
2208
|
+
}
|
|
2209
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
2210
|
+
return true;
|
|
412
2211
|
}
|
|
413
2212
|
|
|
414
2213
|
RiskVerdict RiskEngine::block(const char *reason) const {
|
|
415
|
-
lastReason_
|
|
2214
|
+
lastReason_ = reason;
|
|
416
2215
|
return {false, reason};
|
|
417
2216
|
}
|
|
418
2217
|
|
|
419
2218
|
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
|
-
|
|
2219
|
+
double refPrice, int volume, bool isOpen) const {
|
|
424
2220
|
if (volume <= 0)
|
|
425
2221
|
return block("order volume must be positive");
|
|
426
2222
|
|
|
427
2223
|
// Reject a non-finite limit price (NaN/Inf) here, at the validation point, so
|
|
428
2224
|
// it can't reach tryReserveOpen and poison the reserved cost. A market/any-
|
|
429
2225
|
// price order legitimately has price 0 (finite), so isfinite allows it.
|
|
430
|
-
if (!std::isfinite(price))
|
|
431
|
-
return block("order price
|
|
2226
|
+
if (!std::isfinite(price) || price < 0.0)
|
|
2227
|
+
return block("order price must be finite and non-negative");
|
|
2228
|
+
|
|
2229
|
+
const RiskMode currentMode = mode_.load(std::memory_order_acquire);
|
|
2230
|
+
if (currentMode == RiskMode::HaltAll)
|
|
2231
|
+
return block("all order inserts halted");
|
|
2232
|
+
|
|
2233
|
+
// Closing orders reduce risk and remain available in ReduceOnly mode and
|
|
2234
|
+
// during metadata outages. Only basic structural validation applies to them.
|
|
2235
|
+
if (!isOpen) {
|
|
2236
|
+
lastReason_ = nullptr;
|
|
2237
|
+
return {true, nullptr};
|
|
2238
|
+
}
|
|
2239
|
+
|
|
2240
|
+
if (invalidConfig_.load(std::memory_order_acquire))
|
|
2241
|
+
return block("risk configuration is invalid");
|
|
2242
|
+
|
|
2243
|
+
if (currentMode == RiskMode::ReduceOnly)
|
|
2244
|
+
return block("opening orders blocked in reduce-only mode");
|
|
432
2245
|
|
|
433
2246
|
const int maxVol = maxOrderVolume_.load(std::memory_order_relaxed);
|
|
434
2247
|
if (maxVol > 0 && volume > maxVol)
|
|
435
2248
|
return block("order volume exceeds maxOrderVolume");
|
|
436
2249
|
|
|
437
2250
|
const double dev = maxPriceDeviation_.load(std::memory_order_relaxed);
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
2251
|
+
if (dev > 0.0) {
|
|
2252
|
+
if (!sanePositive(refPrice))
|
|
2253
|
+
return block("reference price unavailable or stale");
|
|
2254
|
+
if (!sanePositive(price))
|
|
2255
|
+
return block("order price unavailable for deviation check");
|
|
441
2256
|
const double diff = std::fabs(price - refPrice) / refPrice;
|
|
442
2257
|
if (diff > dev)
|
|
443
2258
|
return block("order price deviates too far from reference");
|
|
444
2259
|
}
|
|
445
2260
|
|
|
446
2261
|
const double maxNotional = maxNotional_.load(std::memory_order_relaxed);
|
|
447
|
-
if (maxNotional > 0.0
|
|
2262
|
+
if (maxNotional > 0.0) {
|
|
2263
|
+
if (!sanePositive(refPrice))
|
|
2264
|
+
return block("reference price unavailable or stale for maxNotional");
|
|
2265
|
+
if (!sanePositive(price))
|
|
2266
|
+
return block("order price unavailable for maxNotional");
|
|
448
2267
|
double mult;
|
|
449
2268
|
{
|
|
450
2269
|
std::lock_guard<std::mutex> lk(posMutex_); // only when notional is capped
|
|
2270
|
+
if (!multiplierKnownLocked(instrumentId))
|
|
2271
|
+
return block("instrument multiplier unavailable");
|
|
2272
|
+
auto supported = futuresMarginFormula_.find(instrumentId);
|
|
2273
|
+
if (supported == futuresMarginFormula_.end() || !supported->second)
|
|
2274
|
+
return block("instrument product class unsupported for maxNotional");
|
|
451
2275
|
mult = multiplierLocked(instrumentId);
|
|
452
2276
|
}
|
|
453
|
-
const double
|
|
2277
|
+
const double valuationPrice = std::max(price, refPrice);
|
|
2278
|
+
const double notional = valuationPrice * static_cast<double>(volume) * mult;
|
|
454
2279
|
if (notional > maxNotional)
|
|
455
2280
|
return block("order notional exceeds maxNotional");
|
|
456
2281
|
}
|
|
457
2282
|
|
|
2283
|
+
lastReason_ = nullptr;
|
|
458
2284
|
return {true, nullptr};
|
|
459
2285
|
}
|
|
460
2286
|
|
|
2287
|
+
bool RiskEngine::allowUnsupportedRiskRequest() const {
|
|
2288
|
+
if (mode_.load(std::memory_order_acquire) != RiskMode::Normal)
|
|
2289
|
+
return false;
|
|
2290
|
+
std::lock_guard<std::mutex> lk(posMutex_);
|
|
2291
|
+
if ((sessionIdentityRequired_ && !sessionIdentityKnown_) ||
|
|
2292
|
+
ledgerUncertain_ || orderLedgerUncertain_ ||
|
|
2293
|
+
!unsupportedWorkingOrders_.empty() || localControlsEnabledLocked())
|
|
2294
|
+
return false;
|
|
2295
|
+
return true;
|
|
2296
|
+
}
|
|
2297
|
+
|
|
2298
|
+
void RiskEngine::recordUnsupportedRiskMutation() {
|
|
2299
|
+
std::lock_guard<RiskSendMutex> send(sendModeMutex_);
|
|
2300
|
+
std::lock_guard<std::mutex> lk(posMutex_);
|
|
2301
|
+
if (!unsupportedRiskMutationUsed_) {
|
|
2302
|
+
unsupportedRiskMutationUsed_ = true;
|
|
2303
|
+
revision_.fetch_add(1, std::memory_order_release);
|
|
2304
|
+
}
|
|
2305
|
+
}
|
|
2306
|
+
|
|
461
2307
|
} // namespace ctp
|