@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/traderapi.cc
CHANGED
|
@@ -14,9 +14,13 @@
|
|
|
14
14
|
|
|
15
15
|
#include <algorithm>
|
|
16
16
|
#include <atomic>
|
|
17
|
+
#include <cmath>
|
|
17
18
|
#include <cstring>
|
|
19
|
+
#include <iterator>
|
|
18
20
|
#include <memory>
|
|
19
21
|
#include <string>
|
|
22
|
+
#include <thread>
|
|
23
|
+
#include <utility>
|
|
20
24
|
#include <vector>
|
|
21
25
|
|
|
22
26
|
#include "../generated/layout.gen.h"
|
|
@@ -25,39 +29,108 @@
|
|
|
25
29
|
#include "ThostFtdcTraderApi.h"
|
|
26
30
|
#include "arm.h"
|
|
27
31
|
#include "channel.h"
|
|
32
|
+
#include "ctp_field.h"
|
|
33
|
+
#include "order_capability.h"
|
|
28
34
|
#include "risk.h"
|
|
35
|
+
#include "shared_handle.h"
|
|
36
|
+
#include "snapshot.h"
|
|
29
37
|
|
|
30
38
|
namespace ctp {
|
|
31
39
|
|
|
32
40
|
namespace {
|
|
33
41
|
|
|
34
|
-
|
|
35
|
-
|
|
42
|
+
// A per-instrument limit batch never legitimately spans more than the whole CTP
|
|
43
|
+
// instrument universe (a few tens of thousands). Reject anything larger up front
|
|
44
|
+
// so an attacker-controlled Array length cannot amplify into a huge reserve()
|
|
45
|
+
// whose std::bad_alloc would escape the Error-only N-API trampoline and abort
|
|
46
|
+
// the process instead of surfacing a catchable JS RangeError.
|
|
47
|
+
constexpr uint32_t kMaxInstrumentLimitBatch = 65536;
|
|
48
|
+
|
|
49
|
+
bool toStringList(const Napi::Value &v, std::vector<std::string> &out,
|
|
50
|
+
const char *label) {
|
|
36
51
|
if (v.IsArray()) {
|
|
37
52
|
Napi::Array a = v.As<Napi::Array>();
|
|
38
|
-
for (uint32_t i = 0; i < a.Length(); ++i)
|
|
39
|
-
|
|
53
|
+
for (uint32_t i = 0; i < a.Length(); ++i) {
|
|
54
|
+
Napi::Value item = a.Get(i);
|
|
55
|
+
if (!item.IsString()) {
|
|
56
|
+
Napi::TypeError::New(v.Env(), std::string(label) +
|
|
57
|
+
" must contain only strings")
|
|
58
|
+
.ThrowAsJavaScriptException();
|
|
59
|
+
return false;
|
|
60
|
+
}
|
|
61
|
+
std::string value = item.As<Napi::String>().Utf8Value();
|
|
62
|
+
if (value.find('\0') != std::string::npos) {
|
|
63
|
+
Napi::RangeError::New(v.Env(), std::string(label) +
|
|
64
|
+
" must not contain NUL")
|
|
65
|
+
.ThrowAsJavaScriptException();
|
|
66
|
+
return false;
|
|
67
|
+
}
|
|
68
|
+
out.push_back(std::move(value));
|
|
69
|
+
}
|
|
40
70
|
} else if (v.IsString()) {
|
|
41
|
-
|
|
71
|
+
std::string value = v.As<Napi::String>().Utf8Value();
|
|
72
|
+
if (value.find('\0') != std::string::npos) {
|
|
73
|
+
Napi::RangeError::New(v.Env(), std::string(label) +
|
|
74
|
+
" must not contain NUL")
|
|
75
|
+
.ThrowAsJavaScriptException();
|
|
76
|
+
return false;
|
|
77
|
+
}
|
|
78
|
+
out.push_back(std::move(value));
|
|
79
|
+
} else {
|
|
80
|
+
Napi::TypeError::New(v.Env(), std::string(label) +
|
|
81
|
+
" must be a string or string array")
|
|
82
|
+
.ThrowAsJavaScriptException();
|
|
83
|
+
return false;
|
|
42
84
|
}
|
|
43
|
-
return
|
|
85
|
+
return true;
|
|
44
86
|
}
|
|
45
87
|
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
88
|
+
bool getFiniteNumber(const Napi::Object &object, const char *key,
|
|
89
|
+
double defaultValue, double &out) {
|
|
90
|
+
if (!object.Has(key)) {
|
|
91
|
+
out = defaultValue;
|
|
92
|
+
return true;
|
|
51
93
|
}
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
94
|
+
Napi::Value value = object.Get(key);
|
|
95
|
+
if (!value.IsNumber() ||
|
|
96
|
+
!std::isfinite(value.As<Napi::Number>().DoubleValue())) {
|
|
97
|
+
Napi::TypeError::New(object.Env(), std::string(key) +
|
|
98
|
+
" must be a finite number")
|
|
99
|
+
.ThrowAsJavaScriptException();
|
|
100
|
+
return false;
|
|
59
101
|
}
|
|
60
|
-
|
|
102
|
+
out = value.As<Napi::Number>().DoubleValue();
|
|
103
|
+
return true;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
bool isInt32Number(const Napi::Value &v) {
|
|
107
|
+
if (!v.IsNumber())
|
|
108
|
+
return false;
|
|
109
|
+
const double n = v.As<Napi::Number>().DoubleValue();
|
|
110
|
+
return std::isfinite(n) && std::floor(n) == n && n >= -2147483648.0 &&
|
|
111
|
+
n <= 2147483647.0;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
bool validRiskLimitKey(const std::string &key) {
|
|
115
|
+
static constexpr const char *keys[] = {
|
|
116
|
+
"maxOrderVolume", "maxPriceDeviation", "maxNotional",
|
|
117
|
+
"maxOrdersPerSec", "orderBurst", "maxCloseOrdersPerSec",
|
|
118
|
+
"closeOrderBurst", "maxAccountMargin", "maxReferenceAgeMs",
|
|
119
|
+
};
|
|
120
|
+
return std::any_of(std::begin(keys), std::end(keys),
|
|
121
|
+
[&](const char *candidate) { return key == candidate; });
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
bool testHooksEnabled(Napi::Env env) {
|
|
125
|
+
Napi::Value process = env.Global().Get("process");
|
|
126
|
+
if (!process.IsObject())
|
|
127
|
+
return false;
|
|
128
|
+
Napi::Value environment = process.As<Napi::Object>().Get("env");
|
|
129
|
+
if (!environment.IsObject())
|
|
130
|
+
return false;
|
|
131
|
+
Napi::Value value =
|
|
132
|
+
environment.As<Napi::Object>().Get("CTP_NODE_TEST_HOOKS");
|
|
133
|
+
return value.IsString() && value.As<Napi::String>().Utf8Value() == "1";
|
|
61
134
|
}
|
|
62
135
|
|
|
63
136
|
} // namespace
|
|
@@ -73,25 +146,29 @@ public:
|
|
|
73
146
|
|
|
74
147
|
private:
|
|
75
148
|
void doClose();
|
|
149
|
+
bool detachBufferForClose();
|
|
76
150
|
|
|
77
151
|
Napi::Value GetApiVersion(const Napi::CallbackInfo &info);
|
|
78
152
|
Napi::Value GetTradingDay(const Napi::CallbackInfo &info);
|
|
79
153
|
Napi::Value Req(const Napi::CallbackInfo &info);
|
|
80
|
-
Napi::Value
|
|
81
|
-
Napi::Value
|
|
154
|
+
Napi::Value SetRiskLimits(const Napi::CallbackInfo &info);
|
|
155
|
+
Napi::Value RiskReduceOnly(const Napi::CallbackInfo &info);
|
|
156
|
+
Napi::Value RiskHaltAll(const Napi::CallbackInfo &info);
|
|
82
157
|
Napi::Value RiskResume(const Napi::CallbackInfo &info);
|
|
83
158
|
Napi::Value LastRiskReason(const Napi::CallbackInfo &info);
|
|
84
|
-
Napi::Value
|
|
85
|
-
Napi::Value
|
|
86
|
-
Napi::Value
|
|
87
|
-
Napi::Value
|
|
88
|
-
Napi::Value
|
|
159
|
+
Napi::Value TimeoutSessionTransition(const Napi::CallbackInfo &info);
|
|
160
|
+
Napi::Value ConfirmSessionAccount(const Napi::CallbackInfo &info);
|
|
161
|
+
Napi::Value BeginSessionHandshake(const Napi::CallbackInfo &info);
|
|
162
|
+
Napi::Value AttachSnapshot(const Napi::CallbackInfo &info);
|
|
163
|
+
Napi::Value SetInstrumentPositionLimits(const Napi::CallbackInfo &info);
|
|
164
|
+
Napi::Value SetInstrumentMarginLimits(const Napi::CallbackInfo &info);
|
|
89
165
|
Napi::Value RebuildReservations(const Napi::CallbackInfo &info);
|
|
90
|
-
Napi::Value
|
|
91
|
-
Napi::Value
|
|
166
|
+
Napi::Value RiskRevision(const Napi::CallbackInfo &info);
|
|
167
|
+
Napi::Value MarkPositionLedgerUncertain(const Napi::CallbackInfo &info);
|
|
168
|
+
Napi::Value MarkOrderLedgerUncertain(const Napi::CallbackInfo &info);
|
|
169
|
+
Napi::Value ReplacePositions(const Napi::CallbackInfo &info);
|
|
170
|
+
Napi::Value AccountMargin(const Napi::CallbackInfo &info);
|
|
92
171
|
Napi::Value ResetPositions(const Napi::CallbackInfo &info);
|
|
93
|
-
Napi::Value ApplyTestTrade(const Napi::CallbackInfo &info);
|
|
94
|
-
Napi::Value ApplyTestOrder(const Napi::CallbackInfo &info);
|
|
95
172
|
Napi::Value Start(const Napi::CallbackInfo &info);
|
|
96
173
|
Napi::Value Buffer(const Napi::CallbackInfo &info);
|
|
97
174
|
Napi::Value ClaimBatch(const Napi::CallbackInfo &info);
|
|
@@ -104,13 +181,21 @@ private:
|
|
|
104
181
|
Napi::Value Disarm(const Napi::CallbackInfo &info);
|
|
105
182
|
Napi::Value ArmFireCount(const Napi::CallbackInfo &info);
|
|
106
183
|
Napi::Value ArmBlockedCount(const Napi::CallbackInfo &info);
|
|
184
|
+
Napi::Value BurstEvents(const Napi::CallbackInfo &info);
|
|
185
|
+
Napi::Value InjectTestLogin(const Napi::CallbackInfo &info);
|
|
186
|
+
int nextArmRequestId();
|
|
107
187
|
|
|
108
188
|
CThostFtdcTraderApi *api_ = nullptr;
|
|
109
189
|
TraderSpi *spi_ = nullptr;
|
|
110
190
|
EventChannel *ch_ = nullptr;
|
|
111
191
|
RiskEngine risk_;
|
|
112
192
|
std::shared_ptr<ArmRegistry> arm_ = std::make_shared<ArmRegistry>();
|
|
113
|
-
|
|
193
|
+
// Disjoint from JS CtpClient ids (1..0x3fffffff), preventing an armed-order
|
|
194
|
+
// error response from settling an unrelated pending query by numeric id.
|
|
195
|
+
std::atomic<uint32_t> armReqId_{0x40000000u};
|
|
196
|
+
std::thread burst_; // test-only lossless-channel stress producer
|
|
197
|
+
napi_env env_ = nullptr;
|
|
198
|
+
napi_ref bufferRef_ = nullptr;
|
|
114
199
|
bool started_ = false;
|
|
115
200
|
bool closed_ = false;
|
|
116
201
|
};
|
|
@@ -119,24 +204,35 @@ Napi::Function Trader::Init(Napi::Env env) {
|
|
|
119
204
|
return DefineClass(
|
|
120
205
|
env, "Trader",
|
|
121
206
|
{
|
|
122
|
-
InstanceMethod("
|
|
123
|
-
InstanceMethod("
|
|
207
|
+
InstanceMethod("apiVersion", &Trader::GetApiVersion),
|
|
208
|
+
InstanceMethod("tradingDay", &Trader::GetTradingDay),
|
|
124
209
|
InstanceMethod("_req", &Trader::Req),
|
|
125
|
-
InstanceMethod("
|
|
126
|
-
InstanceMethod("
|
|
210
|
+
InstanceMethod("setRiskLimits", &Trader::SetRiskLimits),
|
|
211
|
+
InstanceMethod("riskReduceOnly", &Trader::RiskReduceOnly),
|
|
212
|
+
InstanceMethod("riskHaltAll", &Trader::RiskHaltAll),
|
|
127
213
|
InstanceMethod("riskResume", &Trader::RiskResume),
|
|
128
214
|
InstanceMethod("lastRiskReason", &Trader::LastRiskReason),
|
|
129
|
-
InstanceMethod("
|
|
130
|
-
|
|
131
|
-
InstanceMethod("
|
|
132
|
-
|
|
133
|
-
InstanceMethod("
|
|
215
|
+
InstanceMethod("_timeoutSessionTransition",
|
|
216
|
+
&Trader::TimeoutSessionTransition),
|
|
217
|
+
InstanceMethod("_confirmSessionAccount",
|
|
218
|
+
&Trader::ConfirmSessionAccount),
|
|
219
|
+
InstanceMethod("_beginSessionHandshake",
|
|
220
|
+
&Trader::BeginSessionHandshake),
|
|
221
|
+
InstanceMethod("_injectTestLogin", &Trader::InjectTestLogin),
|
|
222
|
+
InstanceMethod("_attachSnapshot", &Trader::AttachSnapshot),
|
|
223
|
+
InstanceMethod("_setInstrumentPositionLimits",
|
|
224
|
+
&Trader::SetInstrumentPositionLimits),
|
|
225
|
+
InstanceMethod("_setInstrumentMarginLimits",
|
|
226
|
+
&Trader::SetInstrumentMarginLimits),
|
|
134
227
|
InstanceMethod("rebuildReservations", &Trader::RebuildReservations),
|
|
135
|
-
InstanceMethod("
|
|
136
|
-
InstanceMethod("
|
|
228
|
+
InstanceMethod("riskRevision", &Trader::RiskRevision),
|
|
229
|
+
InstanceMethod("_markPositionLedgerUncertain",
|
|
230
|
+
&Trader::MarkPositionLedgerUncertain),
|
|
231
|
+
InstanceMethod("_markOrderLedgerUncertain",
|
|
232
|
+
&Trader::MarkOrderLedgerUncertain),
|
|
233
|
+
InstanceMethod("replacePositions", &Trader::ReplacePositions),
|
|
234
|
+
InstanceMethod("accountMargin", &Trader::AccountMargin),
|
|
137
235
|
InstanceMethod("resetPositions", &Trader::ResetPositions),
|
|
138
|
-
InstanceMethod("_applyTestTrade", &Trader::ApplyTestTrade),
|
|
139
|
-
InstanceMethod("_applyTestOrder", &Trader::ApplyTestOrder),
|
|
140
236
|
InstanceMethod("_start", &Trader::Start),
|
|
141
237
|
InstanceMethod("_buffer", &Trader::Buffer),
|
|
142
238
|
InstanceMethod("_claim", &Trader::ClaimBatch),
|
|
@@ -148,11 +244,13 @@ Napi::Function Trader::Init(Napi::Env env) {
|
|
|
148
244
|
InstanceMethod("disarm", &Trader::Disarm),
|
|
149
245
|
InstanceMethod("_armFireCount", &Trader::ArmFireCount),
|
|
150
246
|
InstanceMethod("_armBlockedCount", &Trader::ArmBlockedCount),
|
|
247
|
+
InstanceMethod("_burstEvents", &Trader::BurstEvents),
|
|
151
248
|
InstanceMethod("close", &Trader::Close),
|
|
152
249
|
});
|
|
153
250
|
}
|
|
154
251
|
|
|
155
|
-
Trader::Trader(const Napi::CallbackInfo &info)
|
|
252
|
+
Trader::Trader(const Napi::CallbackInfo &info)
|
|
253
|
+
: Napi::ObjectWrap<Trader>(info), env_(info.Env()) {
|
|
156
254
|
Napi::Env env = info.Env();
|
|
157
255
|
if (info.Length() < 2 || !info[0].IsString()) {
|
|
158
256
|
Napi::TypeError::New(env, "Trader(flowPath, fronts)")
|
|
@@ -160,12 +258,20 @@ Trader::Trader(const Napi::CallbackInfo &info) : Napi::ObjectWrap<Trader>(info)
|
|
|
160
258
|
return;
|
|
161
259
|
}
|
|
162
260
|
std::string flowPath = info[0].As<Napi::String>().Utf8Value();
|
|
261
|
+
if (flowPath.find('\0') != std::string::npos) {
|
|
262
|
+
Napi::RangeError::New(env, "Trader flowPath must not contain NUL")
|
|
263
|
+
.ThrowAsJavaScriptException();
|
|
264
|
+
return;
|
|
265
|
+
}
|
|
163
266
|
|
|
164
267
|
// Validate fronts BEFORE allocating anything: RegisterFront("") faults deep
|
|
165
268
|
// inside the CTP DLL, so drop empty addresses and reject an empty result with
|
|
166
269
|
// a clean JS error rather than crashing the process.
|
|
167
270
|
std::vector<std::string> fronts;
|
|
168
|
-
|
|
271
|
+
std::vector<std::string> requestedFronts;
|
|
272
|
+
if (!toStringList(info[1], requestedFronts, "fronts"))
|
|
273
|
+
return;
|
|
274
|
+
for (auto &addr : requestedFronts)
|
|
169
275
|
if (!addr.empty())
|
|
170
276
|
fronts.push_back(addr);
|
|
171
277
|
if (fronts.empty()) {
|
|
@@ -181,12 +287,18 @@ Trader::Trader(const Napi::CallbackInfo &info) : Napi::ObjectWrap<Trader>(info)
|
|
|
181
287
|
.ThrowAsJavaScriptException();
|
|
182
288
|
return;
|
|
183
289
|
}
|
|
184
|
-
// Trader uses
|
|
185
|
-
// silently discarded under backpressure.
|
|
290
|
+
// Trader uses a lossless staged overflow: order/trade/query returns must never
|
|
291
|
+
// be silently discarded under backpressure.
|
|
186
292
|
ch_ = new EventChannel(4096, static_cast<size_t>(ctpMaxStructSize()),
|
|
187
|
-
|
|
188
|
-
spi_ = new TraderSpi(
|
|
189
|
-
spi_->setRisk(&risk_); // fills update the position-
|
|
293
|
+
DropPolicy::Lossless);
|
|
294
|
+
spi_ = new TraderSpi(ch_);
|
|
295
|
+
spi_->setRisk(&risk_); // fills update the position-margin tracker
|
|
296
|
+
spi_->setArmRegistry(arm_.get()); // front transitions revoke old mandates
|
|
297
|
+
// Fail closed even before the first OnFrontConnected callback. Opening
|
|
298
|
+
// permission must come only from authoritative position + working-order
|
|
299
|
+
// snapshots, never from a timing window during construction/initial login.
|
|
300
|
+
risk_.markTradeLedgerUncertain();
|
|
301
|
+
risk_.markOrderLedgerUncertain();
|
|
190
302
|
api_->RegisterSpi(spi_);
|
|
191
303
|
arm_->setSink(this); // armed triggers fire orders through this Trader
|
|
192
304
|
api_->SubscribePublicTopic(THOST_TERT_QUICK);
|
|
@@ -198,10 +310,41 @@ Trader::Trader(const Napi::CallbackInfo &info) : Napi::ObjectWrap<Trader>(info)
|
|
|
198
310
|
|
|
199
311
|
Trader::~Trader() { doClose(); }
|
|
200
312
|
|
|
313
|
+
bool Trader::detachBufferForClose() {
|
|
314
|
+
if (!bufferRef_)
|
|
315
|
+
return true;
|
|
316
|
+
|
|
317
|
+
// Fail closed on every N-API anomaly: an attached external ArrayBuffer is a
|
|
318
|
+
// reason to retain native backing storage, never a reason to risk a UAF.
|
|
319
|
+
bool safeToFreeRing = false;
|
|
320
|
+
napi_value buffer = nullptr;
|
|
321
|
+
if (env_ &&
|
|
322
|
+
napi_get_reference_value(env_, bufferRef_, &buffer) == napi_ok &&
|
|
323
|
+
buffer != nullptr) {
|
|
324
|
+
bool detached = false;
|
|
325
|
+
if (napi_is_detached_arraybuffer(env_, buffer, &detached) == napi_ok) {
|
|
326
|
+
if (detached) {
|
|
327
|
+
safeToFreeRing = true;
|
|
328
|
+
} else if (napi_detach_arraybuffer(env_, buffer) == napi_ok) {
|
|
329
|
+
detached = false;
|
|
330
|
+
safeToFreeRing =
|
|
331
|
+
napi_is_detached_arraybuffer(env_, buffer, &detached) == napi_ok &&
|
|
332
|
+
detached;
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
if (env_)
|
|
337
|
+
napi_delete_reference(env_, bufferRef_);
|
|
338
|
+
bufferRef_ = nullptr;
|
|
339
|
+
return safeToFreeRing;
|
|
340
|
+
}
|
|
341
|
+
|
|
201
342
|
void Trader::doClose() {
|
|
202
343
|
if (closed_)
|
|
203
344
|
return;
|
|
204
345
|
closed_ = true;
|
|
346
|
+
if (burst_.joinable())
|
|
347
|
+
burst_.join();
|
|
205
348
|
// Order matters: clearSink() (under the arm lock) guarantees no fireArmed is
|
|
206
349
|
// running or will start, so the non-atomic api_ below is never read after it
|
|
207
350
|
// is nulled. Do NOT move the api_ teardown before clearSink().
|
|
@@ -210,6 +353,9 @@ void Trader::doClose() {
|
|
|
210
353
|
api_->Release();
|
|
211
354
|
api_ = nullptr;
|
|
212
355
|
}
|
|
356
|
+
// The ring backs one cached external ArrayBuffer. Detach it before freeing
|
|
357
|
+
// the native storage so retained JS references can never read freed memory.
|
|
358
|
+
const bool safeToFreeRing = detachBufferForClose();
|
|
213
359
|
// Free the SPI and the ring here, on close(), not in the GC finalizer: the
|
|
214
360
|
// ring (~maxStructSize * 4096 slots, ~10 MB) is off-heap so V8 feels no GC
|
|
215
361
|
// pressure from it, and a create/close loop leaks it (measured unreclaimed
|
|
@@ -221,7 +367,10 @@ void Trader::doClose() {
|
|
|
221
367
|
}
|
|
222
368
|
if (ch_) {
|
|
223
369
|
ch_->stop();
|
|
224
|
-
|
|
370
|
+
if (safeToFreeRing)
|
|
371
|
+
delete ch_;
|
|
372
|
+
// A stopped-channel leak is preferable to exposing freed storage through
|
|
373
|
+
// an ArrayBuffer if detachment unexpectedly failed.
|
|
225
374
|
ch_ = nullptr;
|
|
226
375
|
}
|
|
227
376
|
}
|
|
@@ -234,53 +383,142 @@ int Trader::fireArmed(const ArmSpec &spec) {
|
|
|
234
383
|
std::memset(&f, 0, sizeof(f));
|
|
235
384
|
std::memcpy(&f, spec.orderTemplate.data(),
|
|
236
385
|
std::min(spec.orderTemplate.size(), sizeof(f)));
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
386
|
+
OrdinaryOrderIdentity identity;
|
|
387
|
+
if (!decodeOrdinaryOrder(f, identity))
|
|
388
|
+
return CTP_INVALID_ORDER_FIELDS;
|
|
389
|
+
const bool isOpen = f.CombOffsetFlag[0] == '0';
|
|
390
|
+
bool sendAllowed = false;
|
|
391
|
+
auto sendGuard = risk_.acquireOrderSendForAccount(
|
|
392
|
+
isOpen, identity.brokerId, identity.investorId, sendAllowed);
|
|
393
|
+
if (!sendAllowed)
|
|
394
|
+
return CTP_RISK_BLOCKED;
|
|
395
|
+
// Armed orders use the same fail-closed gate as regular orders. In particular,
|
|
396
|
+
// a configured deviation check may not silently skip stale/missing market data.
|
|
397
|
+
RiskVerdict v = risk_.check(identity.instrumentId, f.LimitPrice,
|
|
398
|
+
risk_.refPrice(identity.instrumentId),
|
|
399
|
+
f.VolumeTotalOriginal, isOpen);
|
|
243
400
|
if (!v.ok)
|
|
244
401
|
return CTP_RISK_BLOCKED;
|
|
402
|
+
int requestId = 0;
|
|
245
403
|
// Position caps (incl. in-flight reservation) apply to armed orders too -
|
|
246
404
|
// safety, not latency-sensitive.
|
|
247
|
-
const bool isOpen = (f.CombOffsetFlag[0] == '0');
|
|
248
405
|
if (isOpen) {
|
|
249
|
-
OpenGate g = risk_.tryReserveOpen(
|
|
406
|
+
OpenGate g = risk_.tryReserveOpen(identity.orderRef, identity.instrumentId,
|
|
250
407
|
f.Direction == '0', f.LimitPrice,
|
|
251
|
-
f.VolumeTotalOriginal
|
|
408
|
+
f.VolumeTotalOriginal,
|
|
409
|
+
f.CombHedgeFlag[0]);
|
|
252
410
|
if (g == OpenGate::VolumeLimit)
|
|
253
411
|
return CTP_POSITION_VOLUME_LIMIT;
|
|
254
412
|
if (g == OpenGate::CostLimit)
|
|
255
413
|
return CTP_POSITION_LIMIT;
|
|
414
|
+
if (g == OpenGate::DuplicateOrderRef)
|
|
415
|
+
return CTP_DUPLICATE_ORDER_REF;
|
|
416
|
+
if (g == OpenGate::MetadataUnavailable)
|
|
417
|
+
return CTP_RISK_METADATA_UNAVAILABLE;
|
|
418
|
+
requestId = nextArmRequestId();
|
|
419
|
+
if (!risk_.bindInsertRequest(requestId, identity.orderRef))
|
|
420
|
+
return CTP_RISK_METADATA_UNAVAILABLE;
|
|
256
421
|
}
|
|
257
|
-
if (!risk_.allowRate()) {
|
|
258
|
-
|
|
259
|
-
risk_.releaseReservation(f.OrderRef);
|
|
422
|
+
if (isOpen && !risk_.allowRate()) {
|
|
423
|
+
risk_.rollbackInsertRequest(requestId, identity.orderRef);
|
|
260
424
|
return CTP_RATE_LIMITED;
|
|
261
425
|
}
|
|
262
|
-
|
|
426
|
+
if (!isOpen && !risk_.allowCloseRate())
|
|
427
|
+
return CTP_RATE_LIMITED;
|
|
428
|
+
if (requestId == 0)
|
|
429
|
+
requestId = nextArmRequestId();
|
|
430
|
+
int sendRc = api->ReqOrderInsert(&f, requestId);
|
|
263
431
|
if (sendRc != 0 && isOpen)
|
|
264
|
-
risk_.
|
|
432
|
+
risk_.rollbackInsertRequest(requestId, identity.orderRef); // not accepted; arm may retry this ref
|
|
265
433
|
return sendRc;
|
|
266
434
|
}
|
|
267
435
|
|
|
436
|
+
int Trader::nextArmRequestId() {
|
|
437
|
+
uint32_t current = armReqId_.load(std::memory_order_relaxed);
|
|
438
|
+
for (;;) {
|
|
439
|
+
const uint32_t next = current >= 0x7fffffffu ? 0x40000000u : current + 1u;
|
|
440
|
+
if (armReqId_.compare_exchange_weak(current, next,
|
|
441
|
+
std::memory_order_relaxed,
|
|
442
|
+
std::memory_order_relaxed))
|
|
443
|
+
return static_cast<int>(current);
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
|
|
268
447
|
Napi::Value Trader::ArmRegistryExternal(const Napi::CallbackInfo &info) {
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
448
|
+
if (closed_ || !api_ || !arm_->hasSink()) {
|
|
449
|
+
Napi::Error::New(info.Env(), "Trader is closed")
|
|
450
|
+
.ThrowAsJavaScriptException();
|
|
451
|
+
return info.Env().Undefined();
|
|
452
|
+
}
|
|
453
|
+
auto *handle = new SharedHandle();
|
|
454
|
+
handle->kind = SharedHandleKind::ArmRegistry;
|
|
455
|
+
handle->arm = arm_;
|
|
456
|
+
return Napi::External<SharedHandle>::New(
|
|
457
|
+
info.Env(), handle, [](Napi::Env, SharedHandle *p) { delete p; });
|
|
273
458
|
}
|
|
274
459
|
|
|
275
460
|
Napi::Value Trader::Arm(const Napi::CallbackInfo &info) {
|
|
276
461
|
Napi::Env env = info.Env();
|
|
462
|
+
if (closed_ || !api_ || !arm_->hasSink()) {
|
|
463
|
+
Napi::Error::New(env, "Trader is closed").ThrowAsJavaScriptException();
|
|
464
|
+
return env.Undefined();
|
|
465
|
+
}
|
|
466
|
+
if (info.Length() < 4 || !info[0].IsString() || !info[1].IsString() ||
|
|
467
|
+
!info[2].IsNumber() || !info[3].IsTypedArray()) {
|
|
468
|
+
Napi::TypeError::New(env, "invalid armed-order arguments")
|
|
469
|
+
.ThrowAsJavaScriptException();
|
|
470
|
+
return env.Undefined();
|
|
471
|
+
}
|
|
472
|
+
Napi::TypedArray typed = info[3].As<Napi::TypedArray>();
|
|
473
|
+
if (typed.TypedArrayType() != napi_uint8_array) {
|
|
474
|
+
Napi::TypeError::New(env, "armed order template must be a Uint8Array")
|
|
475
|
+
.ThrowAsJavaScriptException();
|
|
476
|
+
return env.Undefined();
|
|
477
|
+
}
|
|
478
|
+
Napi::Uint8Array bytes = info[3].As<Napi::Uint8Array>();
|
|
479
|
+
if (bytes.ByteLength() != sizeof(CThostFtdcInputOrderField)) {
|
|
480
|
+
Napi::RangeError::New(env, "invalid armed InputOrder byte length")
|
|
481
|
+
.ThrowAsJavaScriptException();
|
|
482
|
+
return env.Undefined();
|
|
483
|
+
}
|
|
484
|
+
CThostFtdcInputOrderField order;
|
|
485
|
+
std::memcpy(&order, bytes.Data(), sizeof(order));
|
|
486
|
+
OrdinaryOrderIdentity identity;
|
|
487
|
+
if (!decodeOrdinaryOrder(order, identity)) {
|
|
488
|
+
Napi::TypeError::New(env, "unsupported armed order template")
|
|
489
|
+
.ThrowAsJavaScriptException();
|
|
490
|
+
return env.Undefined();
|
|
491
|
+
}
|
|
277
492
|
ArmSpec spec;
|
|
278
493
|
spec.instrumentId = info[0].As<Napi::String>().Utf8Value();
|
|
279
494
|
std::string side = info[1].As<Napi::String>().Utf8Value();
|
|
280
|
-
spec.side = side.
|
|
495
|
+
spec.side = side.size() == 1 ? side[0] : '\0';
|
|
281
496
|
spec.triggerPrice = info[2].As<Napi::Number>().DoubleValue();
|
|
282
|
-
|
|
497
|
+
if (spec.instrumentId != identity.instrumentId ||
|
|
498
|
+
(spec.side != '0' && spec.side != '1') || spec.side != order.Direction ||
|
|
499
|
+
!std::isfinite(spec.triggerPrice) || spec.triggerPrice <= 0.0 ||
|
|
500
|
+
spec.triggerPrice >= 1e300) {
|
|
501
|
+
Napi::TypeError::New(env, "armed trigger does not match its order template")
|
|
502
|
+
.ThrowAsJavaScriptException();
|
|
503
|
+
return env.Undefined();
|
|
504
|
+
}
|
|
283
505
|
spec.orderTemplate.assign(bytes.Data(), bytes.Data() + bytes.ByteLength());
|
|
506
|
+
const bool isOpen = order.CombOffsetFlag[0] == '0';
|
|
507
|
+
bool allowed = false;
|
|
508
|
+
// Gate registration on the risk MODE only: a HaltAll (and, for opens,
|
|
509
|
+
// ReduceOnly) hard-stop must not accept new arms. The account/session scope is
|
|
510
|
+
// deliberately NOT checked here — at the native layer an arm may legitimately
|
|
511
|
+
// be registered before login and fire once the session is confirmed. (The
|
|
512
|
+
// TypeScript arm() wrapper is stricter still: it needs a confirmed login to
|
|
513
|
+
// stamp the order template's broker/investor.) fireArmed() re-applies the full
|
|
514
|
+
// per-account gate at send time, so no armed order can reach CTP in an
|
|
515
|
+
// unconfirmed or foreign account regardless of when it was registered.
|
|
516
|
+
auto sendGuard = risk_.acquireOrderSend(isOpen, allowed);
|
|
517
|
+
if (!allowed) {
|
|
518
|
+
Napi::Error::New(env, "cannot arm while order sending is halted")
|
|
519
|
+
.ThrowAsJavaScriptException();
|
|
520
|
+
return env.Undefined();
|
|
521
|
+
}
|
|
284
522
|
uint64_t id = arm_->arm(std::move(spec));
|
|
285
523
|
return Napi::Number::New(env, static_cast<double>(id));
|
|
286
524
|
}
|
|
@@ -300,6 +538,28 @@ Napi::Value Trader::ArmFireCount(const Napi::CallbackInfo &info) {
|
|
|
300
538
|
static_cast<double>(arm_->fireCount()));
|
|
301
539
|
}
|
|
302
540
|
|
|
541
|
+
Napi::Value Trader::BurstEvents(const Napi::CallbackInfo &info) {
|
|
542
|
+
if (!testHooksEnabled(info.Env())) {
|
|
543
|
+
Napi::Error::New(info.Env(),
|
|
544
|
+
"test hook disabled; set CTP_NODE_TEST_HOOKS=1 explicitly")
|
|
545
|
+
.ThrowAsJavaScriptException();
|
|
546
|
+
return info.Env().Undefined();
|
|
547
|
+
}
|
|
548
|
+
if (!ch_ || closed_)
|
|
549
|
+
return info.Env().Undefined();
|
|
550
|
+
const int n = info[0].As<Napi::Number>().Int32Value();
|
|
551
|
+
if (n <= 0)
|
|
552
|
+
return info.Env().Undefined();
|
|
553
|
+
if (burst_.joinable())
|
|
554
|
+
burst_.join();
|
|
555
|
+
EventChannel *ch = ch_;
|
|
556
|
+
burst_ = std::thread([ch, n]() {
|
|
557
|
+
for (int i = 0; i < n; ++i)
|
|
558
|
+
ch->push(ET_RtnTrade, i, -1, 0, "", -2, &i, sizeof(i));
|
|
559
|
+
});
|
|
560
|
+
return info.Env().Undefined();
|
|
561
|
+
}
|
|
562
|
+
|
|
303
563
|
Napi::Value Trader::GetApiVersion(const Napi::CallbackInfo &info) {
|
|
304
564
|
return Napi::String::New(info.Env(), CThostFtdcTraderApi::GetApiVersion());
|
|
305
565
|
}
|
|
@@ -307,7 +567,7 @@ Napi::Value Trader::GetApiVersion(const Napi::CallbackInfo &info) {
|
|
|
307
567
|
Napi::Value Trader::GetTradingDay(const Napi::CallbackInfo &info) {
|
|
308
568
|
Napi::Env env = info.Env();
|
|
309
569
|
if (!api_)
|
|
310
|
-
return env
|
|
570
|
+
return Napi::String::New(env, "");
|
|
311
571
|
const char *d = api_->GetTradingDay();
|
|
312
572
|
return Napi::String::New(env, d ? d : "");
|
|
313
573
|
}
|
|
@@ -317,6 +577,15 @@ Napi::Value Trader::Req(const Napi::CallbackInfo &info) {
|
|
|
317
577
|
if (!api_)
|
|
318
578
|
return Napi::Number::New(env, -1);
|
|
319
579
|
int methodId = info[0].As<Napi::Number>().Int32Value();
|
|
580
|
+
if (methodId == M_ReqUserLogin || methodId == M_ReqUserLogout ||
|
|
581
|
+
methodId == M_ReqUserLoginWithCaptcha ||
|
|
582
|
+
methodId == M_ReqUserLoginWithText ||
|
|
583
|
+
methodId == M_ReqUserLoginWithOTP) {
|
|
584
|
+
// A mandate belongs to one authenticated session/account. Clear it before
|
|
585
|
+
// the transition request; traderReq() then invalidates the risk identity
|
|
586
|
+
// before calling CTP. A failed transition stays deliberately disarmed.
|
|
587
|
+
arm_->clear();
|
|
588
|
+
}
|
|
320
589
|
Napi::Uint8Array bytes = info[1].As<Napi::Uint8Array>();
|
|
321
590
|
int id = info[2].As<Napi::Number>().Int32Value();
|
|
322
591
|
int rc = traderReq(api_, methodId, bytes.Data(),
|
|
@@ -324,23 +593,72 @@ Napi::Value Trader::Req(const Napi::CallbackInfo &info) {
|
|
|
324
593
|
return Napi::Number::New(env, rc);
|
|
325
594
|
}
|
|
326
595
|
|
|
327
|
-
Napi::Value Trader::
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
596
|
+
Napi::Value Trader::SetRiskLimits(const Napi::CallbackInfo &info) {
|
|
597
|
+
Napi::Env env = info.Env();
|
|
598
|
+
if (info.Length() < 1 || !info[0].IsObject() || info[0].IsArray()) {
|
|
599
|
+
Napi::TypeError::New(env, "setRiskLimits requires an object")
|
|
600
|
+
.ThrowAsJavaScriptException();
|
|
601
|
+
return env.Undefined();
|
|
602
|
+
}
|
|
603
|
+
Napi::Object object = info[0].As<Napi::Object>();
|
|
604
|
+
Napi::Array names = object.GetPropertyNames();
|
|
605
|
+
for (uint32_t i = 0; i < names.Length(); ++i) {
|
|
606
|
+
Napi::Value name = names.Get(i);
|
|
607
|
+
if (!name.IsString() ||
|
|
608
|
+
!validRiskLimitKey(name.As<Napi::String>().Utf8Value())) {
|
|
609
|
+
Napi::TypeError::New(env, "setRiskLimits contains an unknown field")
|
|
610
|
+
.ThrowAsJavaScriptException();
|
|
611
|
+
return env.Undefined();
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
RiskLimits cfg;
|
|
615
|
+
double maxOrderVolume = 0.0;
|
|
616
|
+
if (!getFiniteNumber(object, "maxOrderVolume", 0.0, maxOrderVolume) ||
|
|
617
|
+
!getFiniteNumber(object, "maxPriceDeviation", 0.0,
|
|
618
|
+
cfg.maxPriceDeviation) ||
|
|
619
|
+
!getFiniteNumber(object, "maxNotional", 0.0, cfg.maxNotional) ||
|
|
620
|
+
!getFiniteNumber(object, "maxOrdersPerSec", 0.0,
|
|
621
|
+
cfg.maxOrdersPerSec) ||
|
|
622
|
+
!getFiniteNumber(object, "orderBurst", 0.0, cfg.orderBurst) ||
|
|
623
|
+
!getFiniteNumber(object, "maxCloseOrdersPerSec", 0.0,
|
|
624
|
+
cfg.maxCloseOrdersPerSec) ||
|
|
625
|
+
!getFiniteNumber(object, "closeOrderBurst", 0.0,
|
|
626
|
+
cfg.closeOrderBurst) ||
|
|
627
|
+
!getFiniteNumber(object, "maxAccountMargin", 0.0,
|
|
628
|
+
cfg.maxAccountMargin) ||
|
|
629
|
+
!getFiniteNumber(object, "maxReferenceAgeMs", 3000.0,
|
|
630
|
+
cfg.maxReferenceAgeMs))
|
|
631
|
+
return env.Undefined();
|
|
632
|
+
if (maxOrderVolume < 0.0 || cfg.maxPriceDeviation < 0.0 ||
|
|
633
|
+
cfg.maxNotional < 0.0 || cfg.maxOrdersPerSec < 0.0 ||
|
|
634
|
+
cfg.orderBurst < 0.0 || cfg.maxCloseOrdersPerSec < 0.0 ||
|
|
635
|
+
cfg.closeOrderBurst < 0.0 || cfg.maxAccountMargin < 0.0 ||
|
|
636
|
+
(maxOrderVolume > 0.0 &&
|
|
637
|
+
(std::floor(maxOrderVolume) != maxOrderVolume ||
|
|
638
|
+
maxOrderVolume > 2147483647.0)) ||
|
|
639
|
+
cfg.maxReferenceAgeMs <= 0.0) {
|
|
640
|
+
Napi::TypeError::New(env, "invalid risk-limit value")
|
|
641
|
+
.ThrowAsJavaScriptException();
|
|
642
|
+
return env.Undefined();
|
|
338
643
|
}
|
|
644
|
+
cfg.maxOrderVolume = maxOrderVolume > 0.0
|
|
645
|
+
? static_cast<int>(maxOrderVolume)
|
|
646
|
+
: 0;
|
|
647
|
+
risk_.configure(cfg);
|
|
648
|
+
return env.Undefined();
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
Napi::Value Trader::RiskReduceOnly(const Napi::CallbackInfo &info) {
|
|
652
|
+
risk_.reduceOnly();
|
|
339
653
|
return info.Env().Undefined();
|
|
340
654
|
}
|
|
341
655
|
|
|
342
|
-
Napi::Value Trader::
|
|
343
|
-
|
|
656
|
+
Napi::Value Trader::RiskHaltAll(const Napi::CallbackInfo &info) {
|
|
657
|
+
// First close the final send barrier (and wait for any already-admitted send
|
|
658
|
+
// to return), then discard historical mandates. After this method returns,
|
|
659
|
+
// resume() cannot unexpectedly fire an arm created before the hard stop.
|
|
660
|
+
risk_.haltAll();
|
|
661
|
+
arm_->clear();
|
|
344
662
|
return info.Env().Undefined();
|
|
345
663
|
}
|
|
346
664
|
|
|
@@ -355,122 +673,368 @@ Napi::Value Trader::LastRiskReason(const Napi::CallbackInfo &info) {
|
|
|
355
673
|
return Napi::String::New(info.Env(), r ? r : "");
|
|
356
674
|
}
|
|
357
675
|
|
|
358
|
-
Napi::Value Trader::
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
676
|
+
Napi::Value Trader::TimeoutSessionTransition(
|
|
677
|
+
const Napi::CallbackInfo &info) {
|
|
678
|
+
if (info.Length() < 1 || !info[0].IsNumber())
|
|
679
|
+
return Napi::Boolean::New(info.Env(), true);
|
|
680
|
+
const double raw = info[0].As<Napi::Number>().DoubleValue();
|
|
681
|
+
if (!std::isfinite(raw) || std::floor(raw) != raw || raw <= 0.0 ||
|
|
682
|
+
raw > 2147483647.0)
|
|
683
|
+
return Napi::Boolean::New(info.Env(), true);
|
|
684
|
+
return Napi::Boolean::New(
|
|
685
|
+
info.Env(),
|
|
686
|
+
risk_.timeoutSessionTransition(static_cast<int>(raw)));
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
Napi::Value Trader::ConfirmSessionAccount(const Napi::CallbackInfo &info) {
|
|
690
|
+
Napi::Env env = info.Env();
|
|
691
|
+
if (info.Length() < 3 || !isInt32Number(info[0]) ||
|
|
692
|
+
!isInt32Number(info[1]) || !info[2].IsTypedArray()) {
|
|
693
|
+
Napi::TypeError::New(
|
|
694
|
+
env, "_confirmSessionAccount requires frontId, sessionId and encoded SettlementInfoConfirm bytes")
|
|
695
|
+
.ThrowAsJavaScriptException();
|
|
696
|
+
return env.Undefined();
|
|
362
697
|
}
|
|
698
|
+
Napi::TypedArray typed = info[2].As<Napi::TypedArray>();
|
|
699
|
+
if (typed.TypedArrayType() != napi_uint8_array) {
|
|
700
|
+
Napi::TypeError::New(
|
|
701
|
+
env, "_confirmSessionAccount bytes must be a Uint8Array")
|
|
702
|
+
.ThrowAsJavaScriptException();
|
|
703
|
+
return env.Undefined();
|
|
704
|
+
}
|
|
705
|
+
Napi::Uint8Array bytes = info[2].As<Napi::Uint8Array>();
|
|
706
|
+
if (bytes.ByteLength() != sizeof(CThostFtdcSettlementInfoConfirmField)) {
|
|
707
|
+
Napi::RangeError::New(
|
|
708
|
+
env, "invalid encoded SettlementInfoConfirm byte length")
|
|
709
|
+
.ThrowAsJavaScriptException();
|
|
710
|
+
return env.Undefined();
|
|
711
|
+
}
|
|
712
|
+
CThostFtdcSettlementInfoConfirmField account;
|
|
713
|
+
std::memcpy(&account, bytes.Data(), sizeof(account));
|
|
714
|
+
std::string brokerId, investorId;
|
|
715
|
+
if (!boundedCtpField(account.BrokerID, brokerId) ||
|
|
716
|
+
!boundedCtpField(account.InvestorID, investorId) || brokerId.empty() ||
|
|
717
|
+
investorId.empty()) {
|
|
718
|
+
Napi::RangeError::New(env, "invalid encoded session account identity")
|
|
719
|
+
.ThrowAsJavaScriptException();
|
|
720
|
+
return env.Undefined();
|
|
721
|
+
}
|
|
722
|
+
const int frontId = info[0].As<Napi::Number>().Int32Value();
|
|
723
|
+
const int sessionId = info[1].As<Napi::Number>().Int32Value();
|
|
724
|
+
return Napi::Boolean::New(
|
|
725
|
+
env, risk_.confirmSessionAccount(frontId, sessionId, brokerId,
|
|
726
|
+
investorId));
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
Napi::Value Trader::BeginSessionHandshake(const Napi::CallbackInfo &info) {
|
|
730
|
+
if (arm_)
|
|
731
|
+
arm_->clear();
|
|
732
|
+
risk_.invalidateSession();
|
|
363
733
|
return info.Env().Undefined();
|
|
364
734
|
}
|
|
365
735
|
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
736
|
+
// Test-only: establish a confirmed native session offline. Drives the exact
|
|
737
|
+
// same RiskEngine handshake the live path uses (beginSessionTransition ->
|
|
738
|
+
// acceptLoginSession, as the SPI OnRspUserLogin would, then confirmSessionAccount
|
|
739
|
+
// as the high-level session() does), so an order/arm test can reach a confirmed
|
|
740
|
+
// account without a live front. Gated behind CTP_NODE_TEST_HOOKS like the other
|
|
741
|
+
// injection hooks; returns whether the confirmed session was established.
|
|
742
|
+
Napi::Value Trader::InjectTestLogin(const Napi::CallbackInfo &info) {
|
|
743
|
+
Napi::Env env = info.Env();
|
|
744
|
+
if (!testHooksEnabled(env)) {
|
|
745
|
+
Napi::Error::New(env,
|
|
746
|
+
"test hook disabled; set CTP_NODE_TEST_HOOKS=1 explicitly")
|
|
747
|
+
.ThrowAsJavaScriptException();
|
|
748
|
+
return env.Undefined();
|
|
370
749
|
}
|
|
371
|
-
|
|
750
|
+
if (info.Length() < 4 || !isInt32Number(info[0]) || !isInt32Number(info[1]) ||
|
|
751
|
+
!info[2].IsString() || !info[3].IsString()) {
|
|
752
|
+
Napi::TypeError::New(
|
|
753
|
+
env, "_injectTestLogin requires frontId, sessionId, brokerId, investorId")
|
|
754
|
+
.ThrowAsJavaScriptException();
|
|
755
|
+
return env.Undefined();
|
|
756
|
+
}
|
|
757
|
+
const int frontId = info[0].As<Napi::Number>().Int32Value();
|
|
758
|
+
const int sessionId = info[1].As<Napi::Number>().Int32Value();
|
|
759
|
+
const std::string brokerId = info[2].As<Napi::String>().Utf8Value();
|
|
760
|
+
const std::string investorId = info[3].As<Napi::String>().Utf8Value();
|
|
761
|
+
// Drives pendingSessionRequestId_ (the session-transition slot) — a separate
|
|
762
|
+
// structure from the insert/arm request bindings (insertRequests_), so this id
|
|
763
|
+
// need not be unique across those spaces (nextArmRequestId can also return this
|
|
764
|
+
// value). acceptLoginSession clears it immediately, leaving no pending state.
|
|
765
|
+
static constexpr int kTestLoginRequestId = 2147483647;
|
|
766
|
+
risk_.beginSessionTransition(kTestLoginRequestId, true, brokerId, investorId);
|
|
767
|
+
if (!risk_.acceptLoginSession(kTestLoginRequestId, frontId, sessionId,
|
|
768
|
+
brokerId, investorId))
|
|
769
|
+
return Napi::Boolean::New(env, false);
|
|
770
|
+
return Napi::Boolean::New(
|
|
771
|
+
env, risk_.confirmSessionAccount(frontId, sessionId, brokerId, investorId));
|
|
372
772
|
}
|
|
373
773
|
|
|
374
|
-
// (
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
774
|
+
// (mdSnapshotExternal) - attach a MarketData's snapshot cache so the deviation
|
|
775
|
+
// check reads live prices in C++ (no JS round-trip). See Trader.trackMarketData.
|
|
776
|
+
Napi::Value Trader::AttachSnapshot(const Napi::CallbackInfo &info) {
|
|
777
|
+
if (info.Length() < 1 || !info[0].IsExternal()) {
|
|
778
|
+
Napi::TypeError::New(info.Env(), "invalid MarketData snapshot handle")
|
|
779
|
+
.ThrowAsJavaScriptException();
|
|
780
|
+
return info.Env().Undefined();
|
|
781
|
+
}
|
|
782
|
+
auto ext = info[0].As<Napi::External<SharedHandle>>();
|
|
783
|
+
SharedHandle *handle = ext.Data();
|
|
784
|
+
if (!handle || handle->magic != SharedHandle::kMagic ||
|
|
785
|
+
handle->kind != SharedHandleKind::SnapshotCache || !handle->snapshot) {
|
|
786
|
+
Napi::TypeError::New(info.Env(), "invalid MarketData snapshot handle")
|
|
787
|
+
.ThrowAsJavaScriptException();
|
|
788
|
+
return info.Env().Undefined();
|
|
380
789
|
}
|
|
790
|
+
risk_.setMdSnapshot(handle->snapshot);
|
|
381
791
|
return info.Env().Undefined();
|
|
382
792
|
}
|
|
383
793
|
|
|
384
|
-
// (instrumentId,
|
|
385
|
-
Napi::Value Trader::
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
794
|
+
// (Array<{instrumentId, long?, short?}>) - one atomic position-limit batch.
|
|
795
|
+
Napi::Value Trader::SetInstrumentPositionLimits(
|
|
796
|
+
const Napi::CallbackInfo &info) {
|
|
797
|
+
Napi::Env env = info.Env();
|
|
798
|
+
if (info.Length() < 1 || !info[0].IsArray()) {
|
|
799
|
+
Napi::TypeError::New(env, "position limits must be an array")
|
|
800
|
+
.ThrowAsJavaScriptException();
|
|
801
|
+
return env.Undefined();
|
|
389
802
|
}
|
|
390
|
-
|
|
803
|
+
Napi::Array input = info[0].As<Napi::Array>();
|
|
804
|
+
if (input.Length() > kMaxInstrumentLimitBatch) {
|
|
805
|
+
Napi::RangeError::New(
|
|
806
|
+
env, "position limits batch exceeds the maximum of 65536 instruments")
|
|
807
|
+
.ThrowAsJavaScriptException();
|
|
808
|
+
return env.Undefined();
|
|
809
|
+
}
|
|
810
|
+
std::vector<InstrumentPositionLimitUpdate> updates;
|
|
811
|
+
updates.reserve(input.Length());
|
|
812
|
+
for (uint32_t i = 0; i < input.Length(); ++i) {
|
|
813
|
+
Napi::Value rowValue = input.Get(i);
|
|
814
|
+
if (!rowValue.IsObject()) {
|
|
815
|
+
Napi::TypeError::New(env, "each position limit must be an object")
|
|
816
|
+
.ThrowAsJavaScriptException();
|
|
817
|
+
return env.Undefined();
|
|
818
|
+
}
|
|
819
|
+
Napi::Object row = rowValue.As<Napi::Object>();
|
|
820
|
+
Napi::Value instrument = row.Get("instrumentId");
|
|
821
|
+
Napi::Value longValue = row.Get("long");
|
|
822
|
+
Napi::Value shortValue = row.Get("short");
|
|
823
|
+
if (!instrument.IsString() ||
|
|
824
|
+
(!longValue.IsUndefined() && !longValue.IsNumber()) ||
|
|
825
|
+
(!shortValue.IsUndefined() && !shortValue.IsNumber())) {
|
|
826
|
+
Napi::TypeError::New(env, "invalid position-limit entry")
|
|
827
|
+
.ThrowAsJavaScriptException();
|
|
828
|
+
return env.Undefined();
|
|
829
|
+
}
|
|
830
|
+
InstrumentPositionLimitUpdate update;
|
|
831
|
+
update.instrumentId = instrument.As<Napi::String>().Utf8Value();
|
|
832
|
+
update.updateLong = longValue.IsNumber();
|
|
833
|
+
update.updateShort = shortValue.IsNumber();
|
|
834
|
+
if (update.updateLong)
|
|
835
|
+
update.longLimit = longValue.As<Napi::Number>().DoubleValue();
|
|
836
|
+
if (update.updateShort)
|
|
837
|
+
update.shortLimit = shortValue.As<Napi::Number>().DoubleValue();
|
|
838
|
+
updates.push_back(std::move(update));
|
|
839
|
+
}
|
|
840
|
+
if (!risk_.setInstrumentPositionLimits(updates)) {
|
|
841
|
+
Napi::TypeError::New(env, "invalid position-limit batch")
|
|
842
|
+
.ThrowAsJavaScriptException();
|
|
843
|
+
}
|
|
844
|
+
return env.Undefined();
|
|
391
845
|
}
|
|
392
846
|
|
|
393
|
-
// (
|
|
394
|
-
Napi::Value Trader::
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
847
|
+
// (Array<{instrumentId, limit}>) - one atomic scheduled-margin-limit batch.
|
|
848
|
+
Napi::Value Trader::SetInstrumentMarginLimits(
|
|
849
|
+
const Napi::CallbackInfo &info) {
|
|
850
|
+
Napi::Env env = info.Env();
|
|
851
|
+
if (info.Length() < 1 || !info[0].IsArray()) {
|
|
852
|
+
Napi::TypeError::New(env, "margin limits must be an array")
|
|
853
|
+
.ThrowAsJavaScriptException();
|
|
854
|
+
return env.Undefined();
|
|
398
855
|
}
|
|
399
|
-
|
|
856
|
+
Napi::Array input = info[0].As<Napi::Array>();
|
|
857
|
+
if (input.Length() > kMaxInstrumentLimitBatch) {
|
|
858
|
+
Napi::RangeError::New(
|
|
859
|
+
env, "margin limits batch exceeds the maximum of 65536 instruments")
|
|
860
|
+
.ThrowAsJavaScriptException();
|
|
861
|
+
return env.Undefined();
|
|
862
|
+
}
|
|
863
|
+
std::vector<InstrumentMarginLimitUpdate> updates;
|
|
864
|
+
updates.reserve(input.Length());
|
|
865
|
+
for (uint32_t i = 0; i < input.Length(); ++i) {
|
|
866
|
+
Napi::Value rowValue = input.Get(i);
|
|
867
|
+
if (!rowValue.IsObject()) {
|
|
868
|
+
Napi::TypeError::New(env, "each margin limit must be an object")
|
|
869
|
+
.ThrowAsJavaScriptException();
|
|
870
|
+
return env.Undefined();
|
|
871
|
+
}
|
|
872
|
+
Napi::Object row = rowValue.As<Napi::Object>();
|
|
873
|
+
Napi::Value instrument = row.Get("instrumentId");
|
|
874
|
+
Napi::Value limit = row.Get("limit");
|
|
875
|
+
if (!instrument.IsString() || !limit.IsNumber()) {
|
|
876
|
+
Napi::TypeError::New(env, "invalid margin-limit entry")
|
|
877
|
+
.ThrowAsJavaScriptException();
|
|
878
|
+
return env.Undefined();
|
|
879
|
+
}
|
|
880
|
+
updates.push_back(InstrumentMarginLimitUpdate{
|
|
881
|
+
instrument.As<Napi::String>().Utf8Value(),
|
|
882
|
+
limit.As<Napi::Number>().DoubleValue()});
|
|
883
|
+
}
|
|
884
|
+
if (!risk_.setInstrumentMarginLimits(updates)) {
|
|
885
|
+
Napi::TypeError::New(env, "invalid margin-limit batch")
|
|
886
|
+
.ThrowAsJavaScriptException();
|
|
887
|
+
}
|
|
888
|
+
return env.Undefined();
|
|
400
889
|
}
|
|
401
890
|
|
|
402
891
|
// (Array<{frontId, sessionId, orderRef, instrumentId, isLong, vol, price}>) -
|
|
403
892
|
// rebuild in-flight reservations from CTP's working orders (reqQryOrder).
|
|
404
893
|
Napi::Value Trader::RebuildReservations(const Napi::CallbackInfo &info) {
|
|
894
|
+
Napi::Env env = info.Env();
|
|
895
|
+
if (info.Length() < 2 || !info[0].IsArray() || !info[1].IsNumber()) {
|
|
896
|
+
Napi::TypeError::New(env, "rebuildReservations requires rows and revision")
|
|
897
|
+
.ThrowAsJavaScriptException();
|
|
898
|
+
return Napi::Boolean::New(env, false);
|
|
899
|
+
}
|
|
405
900
|
std::vector<OpenOrderInfo> orders;
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
901
|
+
Napi::Array arr = info[0].As<Napi::Array>();
|
|
902
|
+
for (uint32_t i = 0; i < arr.Length(); ++i) {
|
|
903
|
+
Napi::Value v = arr.Get(i);
|
|
904
|
+
if (!v.IsObject()) {
|
|
905
|
+
Napi::TypeError::New(env, "invalid working-order snapshot row")
|
|
906
|
+
.ThrowAsJavaScriptException();
|
|
907
|
+
return Napi::Boolean::New(env, false);
|
|
908
|
+
}
|
|
909
|
+
Napi::Object o = v.As<Napi::Object>();
|
|
910
|
+
Napi::Value front = o.Get("frontId");
|
|
911
|
+
Napi::Value session = o.Get("sessionId");
|
|
912
|
+
Napi::Value orderRef = o.Get("orderRef");
|
|
913
|
+
Napi::Value instrument = o.Get("instrumentId");
|
|
914
|
+
Napi::Value isLong = o.Get("isLong");
|
|
915
|
+
Napi::Value volume = o.Get("vol");
|
|
916
|
+
Napi::Value price = o.Get("price");
|
|
917
|
+
Napi::Value hedgeValue = o.Get("hedgeFlag");
|
|
918
|
+
Napi::Value tradedValue = o.Get("traded");
|
|
919
|
+
Napi::Value sysValue = o.Get("orderSysKey");
|
|
920
|
+
Napi::Value supportedValue = o.Get("supportedSingleLeg");
|
|
921
|
+
if (!isInt32Number(front) || !isInt32Number(session) ||
|
|
922
|
+
!orderRef.IsString() ||
|
|
923
|
+
!instrument.IsString() || !isLong.IsBoolean() || !volume.IsNumber() ||
|
|
924
|
+
!price.IsNumber() ||
|
|
925
|
+
!hedgeValue.IsString() ||
|
|
926
|
+
(!tradedValue.IsUndefined() && !tradedValue.IsNumber()) ||
|
|
927
|
+
(!sysValue.IsUndefined() && !sysValue.IsString()) ||
|
|
928
|
+
!supportedValue.IsBoolean()) {
|
|
929
|
+
Napi::TypeError::New(env, "invalid working-order snapshot row")
|
|
930
|
+
.ThrowAsJavaScriptException();
|
|
931
|
+
return Napi::Boolean::New(env, false);
|
|
422
932
|
}
|
|
933
|
+
OpenOrderInfo r;
|
|
934
|
+
r.frontId = front.As<Napi::Number>().Int32Value();
|
|
935
|
+
r.sessionId = session.As<Napi::Number>().Int32Value();
|
|
936
|
+
r.orderRef = orderRef.As<Napi::String>().Utf8Value();
|
|
937
|
+
r.instrumentId = instrument.As<Napi::String>().Utf8Value();
|
|
938
|
+
r.isLong = isLong.As<Napi::Boolean>().Value();
|
|
939
|
+
const std::string hedge = hedgeValue.As<Napi::String>().Utf8Value();
|
|
940
|
+
r.hedgeFlag = hedge.empty() ? '\0' : hedge[0];
|
|
941
|
+
r.vol = volume.As<Napi::Number>().DoubleValue();
|
|
942
|
+
r.price = price.As<Napi::Number>().DoubleValue();
|
|
943
|
+
r.traded = tradedValue.IsNumber()
|
|
944
|
+
? tradedValue.As<Napi::Number>().DoubleValue()
|
|
945
|
+
: 0.0;
|
|
946
|
+
r.orderSysKey = sysValue.IsString()
|
|
947
|
+
? sysValue.As<Napi::String>().Utf8Value()
|
|
948
|
+
: std::string();
|
|
949
|
+
r.supportedSingleLeg = supportedValue.As<Napi::Boolean>().Value();
|
|
950
|
+
orders.push_back(std::move(r));
|
|
423
951
|
}
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
Napi::
|
|
430
|
-
if (info.Length() >= 4) {
|
|
431
|
-
risk_.seedPosition(info[0].As<Napi::String>().Utf8Value(),
|
|
432
|
-
info[1].ToBoolean().Value(),
|
|
433
|
-
info[2].As<Napi::Number>().DoubleValue(),
|
|
434
|
-
info[3].As<Napi::Number>().DoubleValue());
|
|
952
|
+
const double revision = info[1].As<Napi::Number>().DoubleValue();
|
|
953
|
+
if (!std::isfinite(revision) || revision < 0.0 ||
|
|
954
|
+
revision > 9007199254740991.0 || std::floor(revision) != revision) {
|
|
955
|
+
Napi::TypeError::New(env, "invalid risk revision")
|
|
956
|
+
.ThrowAsJavaScriptException();
|
|
957
|
+
return Napi::Boolean::New(env, false);
|
|
435
958
|
}
|
|
436
|
-
return
|
|
959
|
+
return Napi::Boolean::New(
|
|
960
|
+
env, risk_.rebuildOpenReservationsIfRevision(
|
|
961
|
+
static_cast<uint64_t>(revision), orders));
|
|
437
962
|
}
|
|
438
963
|
|
|
439
|
-
Napi::Value Trader::
|
|
440
|
-
return Napi::Number::New(info.Env(), risk_.
|
|
964
|
+
Napi::Value Trader::RiskRevision(const Napi::CallbackInfo &info) {
|
|
965
|
+
return Napi::Number::New(info.Env(), static_cast<double>(risk_.revision()));
|
|
441
966
|
}
|
|
442
967
|
|
|
443
|
-
Napi::Value Trader::
|
|
444
|
-
|
|
968
|
+
Napi::Value Trader::MarkPositionLedgerUncertain(
|
|
969
|
+
const Napi::CallbackInfo &info) {
|
|
970
|
+
risk_.markTradeLedgerUncertain();
|
|
445
971
|
return info.Env().Undefined();
|
|
446
972
|
}
|
|
447
973
|
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
risk_.onTrade(info[0].As<Napi::String>().Utf8Value(),
|
|
452
|
-
info[1].ToBoolean().Value(), info[2].ToBoolean().Value(),
|
|
453
|
-
info[3].As<Napi::Number>().DoubleValue(),
|
|
454
|
-
info[4].As<Napi::Number>().DoubleValue());
|
|
455
|
-
}
|
|
974
|
+
Napi::Value Trader::MarkOrderLedgerUncertain(
|
|
975
|
+
const Napi::CallbackInfo &info) {
|
|
976
|
+
risk_.markOrderLedgerUncertain();
|
|
456
977
|
return info.Env().Undefined();
|
|
457
978
|
}
|
|
458
979
|
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
980
|
+
Napi::Value Trader::ReplacePositions(const Napi::CallbackInfo &info) {
|
|
981
|
+
Napi::Env env = info.Env();
|
|
982
|
+
if (info.Length() < 2 || !info[0].IsArray() || !info[1].IsNumber()) {
|
|
983
|
+
Napi::TypeError::New(env, "replacePositions requires rows and revision")
|
|
984
|
+
.ThrowAsJavaScriptException();
|
|
985
|
+
return Napi::Boolean::New(env, false);
|
|
986
|
+
}
|
|
987
|
+
std::vector<PositionSeed> seeds;
|
|
988
|
+
Napi::Array arr = info[0].As<Napi::Array>();
|
|
989
|
+
for (uint32_t i = 0; i < arr.Length(); ++i) {
|
|
990
|
+
Napi::Value v = arr.Get(i);
|
|
991
|
+
if (!v.IsObject()) {
|
|
992
|
+
Napi::TypeError::New(env, "invalid position snapshot row")
|
|
993
|
+
.ThrowAsJavaScriptException();
|
|
994
|
+
return Napi::Boolean::New(env, false);
|
|
995
|
+
}
|
|
996
|
+
Napi::Object o = v.As<Napi::Object>();
|
|
997
|
+
Napi::Value instrument = o.Get("instrumentId");
|
|
998
|
+
Napi::Value isLong = o.Get("isLong");
|
|
999
|
+
Napi::Value hedge = o.Get("hedgeFlag");
|
|
1000
|
+
Napi::Value volume = o.Get("volume");
|
|
1001
|
+
Napi::Value margin = o.Get("margin");
|
|
1002
|
+
if (!instrument.IsString() || !isLong.IsBoolean() || !hedge.IsString() ||
|
|
1003
|
+
!volume.IsNumber() || !margin.IsNumber()) {
|
|
1004
|
+
Napi::TypeError::New(env, "invalid position snapshot row")
|
|
1005
|
+
.ThrowAsJavaScriptException();
|
|
1006
|
+
return Napi::Boolean::New(env, false);
|
|
1007
|
+
}
|
|
1008
|
+
const std::string hedgeFlag = hedge.As<Napi::String>().Utf8Value();
|
|
1009
|
+
if (hedgeFlag.size() != 1) {
|
|
1010
|
+
Napi::TypeError::New(env, "invalid position snapshot hedgeFlag")
|
|
1011
|
+
.ThrowAsJavaScriptException();
|
|
1012
|
+
return Napi::Boolean::New(env, false);
|
|
1013
|
+
}
|
|
1014
|
+
seeds.push_back(PositionSeed{
|
|
1015
|
+
instrument.As<Napi::String>().Utf8Value(),
|
|
1016
|
+
isLong.As<Napi::Boolean>().Value(),
|
|
1017
|
+
volume.As<Napi::Number>().DoubleValue(),
|
|
1018
|
+
margin.As<Napi::Number>().DoubleValue(), hedgeFlag[0]});
|
|
1019
|
+
}
|
|
1020
|
+
const double revision = info[1].As<Napi::Number>().DoubleValue();
|
|
1021
|
+
if (!std::isfinite(revision) || revision < 0.0 ||
|
|
1022
|
+
revision > 9007199254740991.0 || std::floor(revision) != revision) {
|
|
1023
|
+
Napi::TypeError::New(env, "invalid risk revision")
|
|
1024
|
+
.ThrowAsJavaScriptException();
|
|
1025
|
+
return Napi::Boolean::New(env, false);
|
|
473
1026
|
}
|
|
1027
|
+
return Napi::Boolean::New(
|
|
1028
|
+
env, risk_.replacePositionsIfRevision(static_cast<uint64_t>(revision),
|
|
1029
|
+
seeds));
|
|
1030
|
+
}
|
|
1031
|
+
|
|
1032
|
+
Napi::Value Trader::AccountMargin(const Napi::CallbackInfo &info) {
|
|
1033
|
+
return Napi::Number::New(info.Env(), risk_.accountMargin());
|
|
1034
|
+
}
|
|
1035
|
+
|
|
1036
|
+
Napi::Value Trader::ResetPositions(const Napi::CallbackInfo &info) {
|
|
1037
|
+
risk_.resetPositions();
|
|
474
1038
|
return info.Env().Undefined();
|
|
475
1039
|
}
|
|
476
1040
|
|
|
@@ -492,7 +1056,23 @@ Napi::Value Trader::Start(const Napi::CallbackInfo &info) {
|
|
|
492
1056
|
Napi::Value Trader::Buffer(const Napi::CallbackInfo &info) {
|
|
493
1057
|
if (!ch_)
|
|
494
1058
|
return info.Env().Undefined();
|
|
495
|
-
|
|
1059
|
+
if (bufferRef_) {
|
|
1060
|
+
napi_value cached = nullptr;
|
|
1061
|
+
if (napi_get_reference_value(info.Env(), bufferRef_, &cached) == napi_ok &&
|
|
1062
|
+
cached != nullptr)
|
|
1063
|
+
return Napi::Value(info.Env(), cached);
|
|
1064
|
+
Napi::Error::New(info.Env(), "cached event-channel buffer is unavailable")
|
|
1065
|
+
.ThrowAsJavaScriptException();
|
|
1066
|
+
return info.Env().Undefined();
|
|
1067
|
+
}
|
|
1068
|
+
Napi::ArrayBuffer buffer =
|
|
1069
|
+
Napi::ArrayBuffer::New(info.Env(), ch_->data(), ch_->byteLength());
|
|
1070
|
+
if (napi_create_reference(info.Env(), buffer, 1, &bufferRef_) != napi_ok) {
|
|
1071
|
+
Napi::Error::New(info.Env(), "failed to retain event-channel buffer")
|
|
1072
|
+
.ThrowAsJavaScriptException();
|
|
1073
|
+
return info.Env().Undefined();
|
|
1074
|
+
}
|
|
1075
|
+
return buffer;
|
|
496
1076
|
}
|
|
497
1077
|
|
|
498
1078
|
Napi::Value Trader::ClaimBatch(const Napi::CallbackInfo &info) {
|
|
@@ -517,8 +1097,7 @@ Napi::Value Trader::ChannelInfo(const Napi::CallbackInfo &info) {
|
|
|
517
1097
|
o.Set("slotSize", static_cast<double>(live ? ch_->slotSize() : 0));
|
|
518
1098
|
o.Set("numSlots", static_cast<double>(live ? ch_->numSlots() : 0));
|
|
519
1099
|
o.Set("headerSize", static_cast<double>(live ? ch_->headerSize() : 0));
|
|
520
|
-
// Trader
|
|
521
|
-
// dropped in favour of a newer record.
|
|
1100
|
+
// Trader uses Lossless; this flag is only the MarketData JS drain selector.
|
|
522
1101
|
o.Set("dropOldest", false);
|
|
523
1102
|
return o;
|
|
524
1103
|
}
|