@hitrading/ctp-node 4.0.0 → 4.1.0-rc.2
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 +21 -0
- package/dist/generated/trader.gen.js +4 -4
- package/dist/generated/trader.gen.js.map +1 -1
- package/dist/index.cjs +96 -24
- package/dist/index.d.cts +2 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/product-rates.d.ts +17 -0
- package/dist/product-rates.d.ts.map +1 -0
- package/dist/product-rates.js +23 -0
- package/dist/product-rates.js.map +1 -0
- package/dist/trader.d.ts +6 -0
- package/dist/trader.d.ts.map +1 -1
- package/dist/trader.js +77 -31
- package/dist/trader.js.map +1 -1
- package/docs/API.md +2 -0
- package/docs/API.zh-CN.md +2 -0
- package/package.json +2 -2
- package/prebuilds/linux-x64/@hitrading+ctp-node.node +0 -0
- package/prebuilds/win32-x64/@hitrading+ctp-node.node +0 -0
- package/src/generated/trader.gen.ts +4 -4
- package/src/generated/traderspi.gen.cc +3 -3
- package/src/index.ts +2 -0
- package/src/native/risk.cc +54 -15
- package/src/native/risk.h +4 -1
- package/src/product-rates.ts +35 -0
- package/src/trader.ts +53 -12
package/src/native/risk.cc
CHANGED
|
@@ -237,7 +237,7 @@ double RiskEngine::refPrice(const std::string &instrumentId) const {
|
|
|
237
237
|
}
|
|
238
238
|
|
|
239
239
|
void RiskEngine::setInstrument(const std::string &instrumentId, double mult,
|
|
240
|
-
char productClass) {
|
|
240
|
+
char productClass, const std::string &productId) {
|
|
241
241
|
if (instrumentId.empty())
|
|
242
242
|
return;
|
|
243
243
|
// Metadata changes can increase the computed exposure of a just-reserved
|
|
@@ -248,12 +248,15 @@ void RiskEngine::setInstrument(const std::string &instrumentId, double mult,
|
|
|
248
248
|
if (!sanePositive(mult)) {
|
|
249
249
|
multipliers_.erase(instrumentId);
|
|
250
250
|
futuresMarginFormula_.erase(instrumentId);
|
|
251
|
+
instrumentProducts_.erase(instrumentId);
|
|
251
252
|
invalidateHeldCostsLocked(instrumentId);
|
|
252
253
|
refreshReservationCostsLocked(instrumentId);
|
|
253
254
|
revision_.fetch_add(1, std::memory_order_release);
|
|
254
255
|
return;
|
|
255
256
|
}
|
|
256
257
|
multipliers_[instrumentId] = mult;
|
|
258
|
+
if (productId.empty()) instrumentProducts_.erase(instrumentId);
|
|
259
|
+
else instrumentProducts_[instrumentId] = productId;
|
|
257
260
|
// Futures and TAS use the futures margin schedule represented here. Options,
|
|
258
261
|
// combinations and spot products require product-specific fields/formulas.
|
|
259
262
|
futuresMarginFormula_[instrumentId] =
|
|
@@ -269,11 +272,13 @@ void RiskEngine::invalidateInstrument(const std::string &instrumentId) {
|
|
|
269
272
|
if (instrumentId.empty()) {
|
|
270
273
|
multipliers_.clear();
|
|
271
274
|
futuresMarginFormula_.clear();
|
|
275
|
+
instrumentProducts_.clear();
|
|
272
276
|
invalidateHeldCostsLocked("");
|
|
273
277
|
refreshAllReservationCostsLocked();
|
|
274
278
|
} else {
|
|
275
279
|
multipliers_.erase(instrumentId);
|
|
276
280
|
futuresMarginFormula_.erase(instrumentId);
|
|
281
|
+
instrumentProducts_.erase(instrumentId);
|
|
277
282
|
invalidateHeldCostsLocked(instrumentId);
|
|
278
283
|
refreshReservationCostsLocked(instrumentId);
|
|
279
284
|
}
|
|
@@ -396,6 +401,12 @@ void RiskEngine::beginMarginScheduleQuery(
|
|
|
396
401
|
activeMarginQueryInstrument_ = instrumentId;
|
|
397
402
|
activeMarginQueryHedgeFlag_ = hedgeFlag;
|
|
398
403
|
stagedMarginRates_.clear();
|
|
404
|
+
activeMarginQueryMembers_.clear();
|
|
405
|
+
invalidStagedMarginKeys_.clear();
|
|
406
|
+
if (!instrumentId.empty() && !multipliers_.count(instrumentId)) {
|
|
407
|
+
for (const auto &entry : instrumentProducts_)
|
|
408
|
+
if (entry.second == instrumentId) activeMarginQueryMembers_.insert(entry.first);
|
|
409
|
+
}
|
|
399
410
|
const bool brokerMatches = brokerId.empty() ||
|
|
400
411
|
(!myBrokerId_.empty() && brokerId == myBrokerId_);
|
|
401
412
|
const bool investorMatches = exchange || investorId.empty() ||
|
|
@@ -412,13 +423,11 @@ void RiskEngine::beginMarginScheduleQuery(
|
|
|
412
423
|
rates.clear();
|
|
413
424
|
return;
|
|
414
425
|
}
|
|
415
|
-
if (hedgeFlag != '\0') {
|
|
416
|
-
rates.erase(marginKey(instrumentId, hedgeFlag));
|
|
417
|
-
return;
|
|
418
|
-
}
|
|
419
|
-
const std::string prefix = instrumentId + "|";
|
|
420
426
|
for (auto it = rates.begin(); it != rates.end();) {
|
|
421
|
-
|
|
427
|
+
const auto split = it->first.rfind('|');
|
|
428
|
+
const auto id = it->first.substr(0, split);
|
|
429
|
+
if ((id == instrumentId || activeMarginQueryMembers_.count(id)) &&
|
|
430
|
+
(hedgeFlag == '\0' || it->first == marginKey(id, hedgeFlag)))
|
|
422
431
|
it = rates.erase(it);
|
|
423
432
|
else
|
|
424
433
|
++it;
|
|
@@ -444,6 +453,10 @@ void RiskEngine::beginMarginScheduleQuery(
|
|
|
444
453
|
}
|
|
445
454
|
invalidateHeldCostsLocked(instrumentId);
|
|
446
455
|
refreshReservationCostsLocked(instrumentId);
|
|
456
|
+
for (const auto &member : activeMarginQueryMembers_) {
|
|
457
|
+
invalidateHeldCostsLocked(member);
|
|
458
|
+
refreshReservationCostsLocked(member);
|
|
459
|
+
}
|
|
447
460
|
}
|
|
448
461
|
revision_.fetch_add(1, std::memory_order_release);
|
|
449
462
|
}
|
|
@@ -462,7 +475,8 @@ void RiskEngine::applyInvestorMarginSchedule(
|
|
|
462
475
|
accountScopeLocked(brokerId, investorId) != AccountScope::Current ||
|
|
463
476
|
!investUnitId.empty() ||
|
|
464
477
|
(!activeMarginQueryInstrument_.empty() &&
|
|
465
|
-
instrumentId != activeMarginQueryInstrument_
|
|
478
|
+
instrumentId != activeMarginQueryInstrument_ &&
|
|
479
|
+
!activeMarginQueryMembers_.count(instrumentId)) ||
|
|
466
480
|
(activeMarginQueryHedgeFlag_ != '\0' &&
|
|
467
481
|
hedgeFlag != activeMarginQueryHedgeFlag_))
|
|
468
482
|
return;
|
|
@@ -476,11 +490,14 @@ void RiskEngine::applyInvestorMarginSchedule(
|
|
|
476
490
|
((longByMoney > 0.0 || longByVolume > 0.0) &&
|
|
477
491
|
(shortByMoney > 0.0 || shortByVolume > 0.0)));
|
|
478
492
|
const std::string key = marginKey(instrumentId, hedgeFlag);
|
|
479
|
-
if (usable)
|
|
493
|
+
if (usable) {
|
|
494
|
+
invalidStagedMarginKeys_.erase(key);
|
|
480
495
|
stagedMarginRates_[key] = MarginSchedule{
|
|
481
496
|
longByMoney, longByVolume, shortByMoney, shortByVolume, isRelative};
|
|
482
|
-
else
|
|
497
|
+
} else {
|
|
498
|
+
invalidStagedMarginKeys_.insert(key);
|
|
483
499
|
stagedMarginRates_.erase(key);
|
|
500
|
+
}
|
|
484
501
|
}
|
|
485
502
|
|
|
486
503
|
void RiskEngine::applyExchangeMarginSchedule(
|
|
@@ -494,7 +511,8 @@ void RiskEngine::applyExchangeMarginSchedule(
|
|
|
494
511
|
!activeMarginQueryAuthorized_ || !sessionIdentityKnown_ ||
|
|
495
512
|
myBrokerId_.empty() || brokerId != myBrokerId_ ||
|
|
496
513
|
(!activeMarginQueryInstrument_.empty() &&
|
|
497
|
-
instrumentId != activeMarginQueryInstrument_
|
|
514
|
+
instrumentId != activeMarginQueryInstrument_ &&
|
|
515
|
+
!activeMarginQueryMembers_.count(instrumentId)) ||
|
|
498
516
|
(activeMarginQueryHedgeFlag_ != '\0' &&
|
|
499
517
|
hedgeFlag != activeMarginQueryHedgeFlag_))
|
|
500
518
|
return;
|
|
@@ -507,11 +525,14 @@ void RiskEngine::applyExchangeMarginSchedule(
|
|
|
507
525
|
(longByMoney > 0.0 || longByVolume > 0.0) &&
|
|
508
526
|
(shortByMoney > 0.0 || shortByVolume > 0.0);
|
|
509
527
|
const std::string key = marginKey(instrumentId, hedgeFlag);
|
|
510
|
-
if (usable)
|
|
528
|
+
if (usable) {
|
|
529
|
+
invalidStagedMarginKeys_.erase(key);
|
|
511
530
|
stagedMarginRates_[key] = MarginSchedule{
|
|
512
531
|
longByMoney, longByVolume, shortByMoney, shortByVolume, false};
|
|
513
|
-
else
|
|
532
|
+
} else {
|
|
533
|
+
invalidStagedMarginKeys_.insert(key);
|
|
514
534
|
stagedMarginRates_.erase(key);
|
|
535
|
+
}
|
|
515
536
|
}
|
|
516
537
|
|
|
517
538
|
void RiskEngine::finishMarginScheduleQuery(int requestId, bool success) {
|
|
@@ -525,6 +546,20 @@ void RiskEngine::finishMarginScheduleQuery(int requestId, bool success) {
|
|
|
525
546
|
: marginRates_;
|
|
526
547
|
for (const auto &entry : stagedMarginRates_)
|
|
527
548
|
target[entry.first] = entry.second;
|
|
549
|
+
// Expand only after the complete, successful response. A malformed explicit
|
|
550
|
+
// contract override must never inherit the product schedule.
|
|
551
|
+
for (const auto &member : activeMarginQueryMembers_) {
|
|
552
|
+
for (const char hedge : {'1', '2', '3', '5', '6', '7'}) {
|
|
553
|
+
const auto key = marginKey(member, hedge);
|
|
554
|
+
if (invalidStagedMarginKeys_.count(key)) continue;
|
|
555
|
+
auto row = stagedMarginRates_.find(key);
|
|
556
|
+
if (row == stagedMarginRates_.end())
|
|
557
|
+
row = stagedMarginRates_.find(marginKey(activeMarginQueryInstrument_, hedge));
|
|
558
|
+
if (row != stagedMarginRates_.end()) target[key] = row->second;
|
|
559
|
+
}
|
|
560
|
+
invalidateHeldCostsLocked(member);
|
|
561
|
+
refreshReservationCostsLocked(member);
|
|
562
|
+
}
|
|
528
563
|
invalidateHeldCostsLocked(activeMarginQueryInstrument_);
|
|
529
564
|
if (activeMarginQueryInstrument_.empty())
|
|
530
565
|
refreshAllReservationCostsLocked();
|
|
@@ -538,6 +573,8 @@ void RiskEngine::finishMarginScheduleQuery(int requestId, bool success) {
|
|
|
538
573
|
activeMarginQueryInstrument_.clear();
|
|
539
574
|
activeMarginQueryHedgeFlag_ = '\0';
|
|
540
575
|
stagedMarginRates_.clear();
|
|
576
|
+
activeMarginQueryMembers_.clear();
|
|
577
|
+
invalidStagedMarginKeys_.clear();
|
|
541
578
|
}
|
|
542
579
|
|
|
543
580
|
bool RiskEngine::setInstrumentPositionLimits(
|
|
@@ -1221,6 +1258,8 @@ RiskEngine::AccountScope RiskEngine::accountScopeLocked(
|
|
|
1221
1258
|
}
|
|
1222
1259
|
|
|
1223
1260
|
void RiskEngine::clearAccountMarginMetadataLocked() {
|
|
1261
|
+
activeMarginQueryMembers_.clear();
|
|
1262
|
+
invalidStagedMarginKeys_.clear();
|
|
1224
1263
|
marginRates_.clear();
|
|
1225
1264
|
exchangeMarginRates_.clear();
|
|
1226
1265
|
activeMarginQueryRequestId_ = 0;
|
|
@@ -1294,7 +1333,7 @@ bool RiskEngine::acceptLoginSession(int requestId, int frontId, int sessionId,
|
|
|
1294
1333
|
std::lock_guard<std::mutex> lk(posMutex_);
|
|
1295
1334
|
if (requestId <= 0 || requestId != pendingSessionRequestId_ ||
|
|
1296
1335
|
!pendingSessionExpectsLogin_ || brokerId.empty() || userId.empty() ||
|
|
1297
|
-
frontId <= 0 || sessionId
|
|
1336
|
+
frontId <= 0 || sessionId == 0 ||
|
|
1298
1337
|
(!pendingSessionBrokerId_.empty() &&
|
|
1299
1338
|
brokerId != pendingSessionBrokerId_) ||
|
|
1300
1339
|
(!pendingSessionUserId_.empty() && userId != pendingSessionUserId_))
|
|
@@ -1329,7 +1368,7 @@ bool RiskEngine::confirmSessionAccount(
|
|
|
1329
1368
|
const std::string &investorId) {
|
|
1330
1369
|
std::lock_guard<RiskSendMutex> send(sendModeMutex_);
|
|
1331
1370
|
std::lock_guard<std::mutex> lk(posMutex_);
|
|
1332
|
-
if (!loginSessionKnown_ || frontId <= 0 || sessionId
|
|
1371
|
+
if (!loginSessionKnown_ || frontId <= 0 || sessionId == 0 ||
|
|
1333
1372
|
frontId != myFrontId_ || sessionId != mySessionId_ || brokerId.empty() ||
|
|
1334
1373
|
investorId.empty() || brokerId != myBrokerId_)
|
|
1335
1374
|
return false;
|
package/src/native/risk.h
CHANGED
|
@@ -175,7 +175,7 @@ public:
|
|
|
175
175
|
// futures notional formula would misrepresent, say, an option premium. The
|
|
176
176
|
// multiplier is still recorded for every class.
|
|
177
177
|
void setInstrument(const std::string &instrumentId, double multiplier,
|
|
178
|
-
char productClass);
|
|
178
|
+
char productClass, const std::string &productId);
|
|
179
179
|
// Called immediately before the corresponding CTP metadata query is sent.
|
|
180
180
|
// Old values must not remain usable while a refresh is in flight or when the
|
|
181
181
|
// refresh comes back empty/invalid.
|
|
@@ -496,6 +496,7 @@ private:
|
|
|
496
496
|
// so held-position replacement/reset does not wipe them.
|
|
497
497
|
std::unordered_map<std::string, double> multipliers_;
|
|
498
498
|
std::unordered_map<std::string, bool> futuresMarginFormula_;
|
|
499
|
+
std::unordered_map<std::string, std::string> instrumentProducts_;
|
|
499
500
|
// Per-instrument margin rates (fraction of notional), same lifetime as
|
|
500
501
|
// multipliers_ (static metadata; survives resetPositions). Missing schedules
|
|
501
502
|
// fail closed whenever a monetary cap needs them.
|
|
@@ -513,6 +514,8 @@ private:
|
|
|
513
514
|
std::string activeMarginQueryInstrument_;
|
|
514
515
|
char activeMarginQueryHedgeFlag_ = '\0';
|
|
515
516
|
std::unordered_map<std::string, MarginSchedule> stagedMarginRates_;
|
|
517
|
+
std::unordered_set<std::string> activeMarginQueryMembers_;
|
|
518
|
+
std::unordered_set<std::string> invalidStagedMarginKeys_;
|
|
516
519
|
// Per-instrument, per-side lot caps (config metadata; like multipliers,
|
|
517
520
|
// survives resets). 0 on a side = that side is uncapped.
|
|
518
521
|
struct VolCap {
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/** CTP product schedules are inherited only through the current instrument
|
|
2
|
+
* catalog. An explicit contract row (even an invalid one) always wins. */
|
|
3
|
+
export interface CtpProductInstrument { instrumentId: string; productId: string; }
|
|
4
|
+
export interface CtpResolvedMarginRate {
|
|
5
|
+
instrumentId: string;
|
|
6
|
+
hedgeFlag: '1' | '2' | '3' | '5' | '6' | '7';
|
|
7
|
+
longMarginRatioByMoney: number;
|
|
8
|
+
longMarginRatioByVolume: number;
|
|
9
|
+
shortMarginRatioByMoney: number;
|
|
10
|
+
shortMarginRatioByVolume: number;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function groupCtpInstrumentsByProduct(
|
|
14
|
+
instrumentIds: readonly string[], catalog: readonly CtpProductInstrument[]
|
|
15
|
+
): Map<string, string[]> {
|
|
16
|
+
const products = new Map(catalog.map(row => [row.instrumentId, row.productId]));
|
|
17
|
+
const groups = new Map<string, string[]>();
|
|
18
|
+
for (const instrumentId of new Set(instrumentIds)) {
|
|
19
|
+
const productId = products.get(instrumentId);
|
|
20
|
+
if (typeof productId !== 'string' || !productId.trim() || productId.includes('\0'))
|
|
21
|
+
throw new Error(`CTP product identity is missing: ${instrumentId}`);
|
|
22
|
+
const members = groups.get(productId);
|
|
23
|
+
if (members) members.push(instrumentId);
|
|
24
|
+
else groups.set(productId, [instrumentId]);
|
|
25
|
+
}
|
|
26
|
+
return groups;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function selectCtpProductRate<T>(
|
|
30
|
+
rows: ReadonlyMap<string, T>, instrumentId: string, productId: string
|
|
31
|
+
): T {
|
|
32
|
+
if (rows.has(instrumentId)) return rows.get(instrumentId)!;
|
|
33
|
+
if (rows.has(productId)) return rows.get(productId)!;
|
|
34
|
+
throw new Error(`CTP product/contract rate is missing: ${productId}/${instrumentId}`);
|
|
35
|
+
}
|
package/src/trader.ts
CHANGED
|
@@ -7,10 +7,12 @@
|
|
|
7
7
|
*/
|
|
8
8
|
|
|
9
9
|
import { native } from "./native-binding.js";
|
|
10
|
+
import { groupCtpInstrumentsByProduct, selectCtpProductRate } from "./product-rates.js";
|
|
11
|
+
import type { CtpResolvedMarginRate } from "./product-rates.js";
|
|
10
12
|
import { TraderBase, TRADER_EVENTS, TraderEvent } from "./generated/trader.gen.js";
|
|
11
13
|
import { STRUCT_ID } from "./generated/structs.gen.js";
|
|
12
14
|
import type { CallbackOptions } from "./client.js";
|
|
13
|
-
import type { Order, Trade, InputOrder, RspUserLogin } from "./generated/structs.gen.js";
|
|
15
|
+
import type { Order, Trade, InputOrder, RspUserLogin, Instrument } from "./generated/structs.gen.js";
|
|
14
16
|
import type { MarketData } from "./market-data.js";
|
|
15
17
|
import {
|
|
16
18
|
assertPlainRecord,
|
|
@@ -203,6 +205,8 @@ const POSITION_SEED_KEYS = new Set([
|
|
|
203
205
|
]);
|
|
204
206
|
|
|
205
207
|
export class Trader extends TraderBase {
|
|
208
|
+
private readonly resolvedMarginRates = new Map<string, CtpResolvedMarginRate>();
|
|
209
|
+
private resolvedMarginContext = 0;
|
|
206
210
|
private broker?: string;
|
|
207
211
|
private investor?: string;
|
|
208
212
|
private orderRefSeq = 0;
|
|
@@ -214,6 +218,7 @@ export class Trader extends TraderBase {
|
|
|
214
218
|
TRADER_EVENTS
|
|
215
219
|
);
|
|
216
220
|
const clearConfirmedIdentity = () => {
|
|
221
|
+
this.resolvedMarginRates.clear();
|
|
217
222
|
this.broker = undefined;
|
|
218
223
|
this.investor = undefined;
|
|
219
224
|
};
|
|
@@ -238,7 +243,8 @@ export class Trader extends TraderBase {
|
|
|
238
243
|
}
|
|
239
244
|
if (eventName !== "rsp-user-login") return;
|
|
240
245
|
// A matched login response updates the confirmed identity, but only from a
|
|
241
|
-
// row carrying the COMPLETE, usable identity (FrontID
|
|
246
|
+
// row carrying the COMPLETE, usable identity (FrontID > 0, non-zero signed
|
|
247
|
+
// SessionID, plus
|
|
242
248
|
// BrokerID/UserID) — the same acceptance condition the generated login
|
|
243
249
|
// validator enforces before it resolves. A partial/abnormal success row
|
|
244
250
|
// (e.g. FrontID 0) is rejected downstream, so caching broker/investor from
|
|
@@ -266,7 +272,7 @@ export class Trader extends TraderBase {
|
|
|
266
272
|
Number.isInteger(r.frontId) &&
|
|
267
273
|
Number(r.frontId) > 0 &&
|
|
268
274
|
Number.isInteger(r.sessionId) &&
|
|
269
|
-
Number(r.sessionId)
|
|
275
|
+
Number(r.sessionId) !== 0
|
|
270
276
|
) {
|
|
271
277
|
this.broker = r.brokerId;
|
|
272
278
|
this.investor = r.userId;
|
|
@@ -285,6 +291,7 @@ export class Trader extends TraderBase {
|
|
|
285
291
|
* transition boundary, so a concurrent sync helper cannot start with the old
|
|
286
292
|
* identity while native risk state is already fail-closed for the new session. */
|
|
287
293
|
protected override beginRequestContextTransition(reason: string): void {
|
|
294
|
+
this.resolvedMarginRates.clear();
|
|
288
295
|
this.broker = undefined;
|
|
289
296
|
this.investor = undefined;
|
|
290
297
|
super.beginRequestContextTransition(reason);
|
|
@@ -436,7 +443,7 @@ export class Trader extends TraderBase {
|
|
|
436
443
|
RspUserLogin | undefined;
|
|
437
444
|
this.assertRequestContext(contextToken, "trader session login");
|
|
438
445
|
if (!login || !Number.isInteger(login.frontId) || login.frontId <= 0 ||
|
|
439
|
-
!Number.isInteger(login.sessionId) || login.sessionId
|
|
446
|
+
!Number.isInteger(login.sessionId) || login.sessionId === 0 ||
|
|
440
447
|
login.brokerId !== brokerId ||
|
|
441
448
|
login.userId !== userId) {
|
|
442
449
|
// FrontID/SessionID are part of the reservation identity. Treating an
|
|
@@ -1039,8 +1046,17 @@ export class Trader extends TraderBase {
|
|
|
1039
1046
|
if (!brokerId || !investorId) {
|
|
1040
1047
|
throw new Error("syncMarginRates requires a successful trader login first");
|
|
1041
1048
|
}
|
|
1049
|
+
for (const id of instrumentIds) this.resolvedMarginRates.delete(`${id}|${hedgeFlag}`);
|
|
1050
|
+
const completed: CtpResolvedMarginRate[] = [];
|
|
1051
|
+
// A fresh catalog supplies authoritative ProductID membership to JS and C++.
|
|
1052
|
+
// It is one request, independent of the number of traded months.
|
|
1053
|
+
const catalog = await this.queryWithRetry(() => this.reqQryInstrument({}), true, contextToken) as Instrument[];
|
|
1054
|
+
const productByInstrument = new Map(catalog.map(row => [row.instrumentId, row.productId]));
|
|
1055
|
+
const groups = groupCtpInstrumentsByProduct(instrumentIds, catalog);
|
|
1042
1056
|
let count = 0;
|
|
1043
|
-
for (const
|
|
1057
|
+
for (const [productId, members] of groups) {
|
|
1058
|
+
for (const [contractId, currentProduct] of productByInstrument)
|
|
1059
|
+
if (currentProduct === productId) this.resolvedMarginRates.delete(`${contractId}|${hedgeFlag}`);
|
|
1044
1060
|
type InvestorMarginRow = {
|
|
1045
1061
|
instrumentId: string;
|
|
1046
1062
|
hedgeFlag: string;
|
|
@@ -1054,15 +1070,18 @@ export class Trader extends TraderBase {
|
|
|
1054
1070
|
((await this.reqQryInstrumentMarginRate({
|
|
1055
1071
|
brokerId,
|
|
1056
1072
|
investorId,
|
|
1057
|
-
instrumentId,
|
|
1073
|
+
instrumentId: productId,
|
|
1058
1074
|
hedgeFlag,
|
|
1059
1075
|
})) as InvestorMarginRow[]).filter(
|
|
1060
|
-
(row) => row.
|
|
1076
|
+
(row) => row.hedgeFlag === hedgeFlag && (row.instrumentId === productId ||
|
|
1077
|
+
productByInstrument.get(row.instrumentId) === productId)
|
|
1061
1078
|
), true, contextToken);
|
|
1062
1079
|
// The native map is keyed by instrument+hedge and processes callbacks in
|
|
1063
1080
|
// order, so its final state is the final row, not "any usable row".
|
|
1064
|
-
const
|
|
1065
|
-
const
|
|
1081
|
+
const rates = new Map(investorRows.map(row => [row.instrumentId, row]));
|
|
1082
|
+
for (const instrumentId of members) {
|
|
1083
|
+
const investor = selectCtpProductRate(rates, instrumentId, productId);
|
|
1084
|
+
const relative = investor.isRelative === 1;
|
|
1066
1085
|
type ExchangeMarginRow = {
|
|
1067
1086
|
instrumentId: string;
|
|
1068
1087
|
hedgeFlag: string;
|
|
@@ -1101,13 +1120,35 @@ export class Trader extends TraderBase {
|
|
|
1101
1120
|
component(investor.longMarginRatioByVolume) &&
|
|
1102
1121
|
component(investor.shortMarginRatioByMoney) &&
|
|
1103
1122
|
component(investor.shortMarginRatioByVolume);
|
|
1104
|
-
if (investorComponentsValid &&
|
|
1105
|
-
(relative ? scheduleUsable(base) : scheduleUsable(investor)))
|
|
1106
|
-
|
|
1123
|
+
if ((investor.isRelative === 0 || investor.isRelative === 1) && investorComponentsValid &&
|
|
1124
|
+
(relative ? scheduleUsable(base) : scheduleUsable(investor))) {
|
|
1125
|
+
const value: CtpResolvedMarginRate = { instrumentId, hedgeFlag,
|
|
1126
|
+
longMarginRatioByMoney: investor.longMarginRatioByMoney + (base?.longMarginRatioByMoney ?? 0),
|
|
1127
|
+
longMarginRatioByVolume: investor.longMarginRatioByVolume + (base?.longMarginRatioByVolume ?? 0),
|
|
1128
|
+
shortMarginRatioByMoney: investor.shortMarginRatioByMoney + (base?.shortMarginRatioByMoney ?? 0),
|
|
1129
|
+
shortMarginRatioByVolume: investor.shortMarginRatioByVolume + (base?.shortMarginRatioByVolume ?? 0) };
|
|
1130
|
+
if (scheduleUsable(value)) { completed.push(value); count++; }
|
|
1131
|
+
}
|
|
1132
|
+
}
|
|
1133
|
+
}
|
|
1134
|
+
if (count === new Set(instrumentIds).size) {
|
|
1135
|
+
this.resolvedMarginContext = contextToken;
|
|
1136
|
+
for (const rate of completed) this.resolvedMarginRates.set(`${rate.instrumentId}|${hedgeFlag}`, rate);
|
|
1107
1137
|
}
|
|
1108
1138
|
return count;
|
|
1109
1139
|
}
|
|
1110
1140
|
|
|
1141
|
+
/** Only completed synchronization results from the current authenticated
|
|
1142
|
+
* session; failed/incomplete refreshes never expose previous schedules. */
|
|
1143
|
+
readMarginRates(instrumentIds: readonly string[], hedgeFlag: CtpResolvedMarginRate['hedgeFlag']): CtpResolvedMarginRate[] {
|
|
1144
|
+
this.assertRequestContext(this.resolvedMarginContext, 'margin snapshot');
|
|
1145
|
+
return instrumentIds.map(instrumentId => {
|
|
1146
|
+
const rate = this.resolvedMarginRates.get(`${instrumentId}|${hedgeFlag}`);
|
|
1147
|
+
if (!rate) throw new Error(`CTP synchronized margin rate is missing: ${instrumentId}/${hedgeFlag}`);
|
|
1148
|
+
return { ...rate };
|
|
1149
|
+
});
|
|
1150
|
+
}
|
|
1151
|
+
|
|
1111
1152
|
/** Replace held position margin from CTP (`reqQryInvestorPosition`). The
|
|
1112
1153
|
* replacement is revision-checked: if an order/trade callback races the
|
|
1113
1154
|
* snapshot it retries without clearing live state or reservations. */
|