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