@hitrading/ctp-node 3.0.0 → 4.0.1

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/src/index.ts CHANGED
@@ -9,6 +9,9 @@ export type {
9
9
  RiskLimits,
10
10
  InstrumentPositionLimit,
11
11
  PositionSeed,
12
+ MarginRateSyncOptions,
13
+ TraderSessionIdentity,
14
+ TraderSessionResult,
12
15
  SessionOptions,
13
16
  ArmSpec,
14
17
  ArmHandle,
@@ -1,8 +1,8 @@
1
1
  /*
2
2
  * order_capability.h - the deliberately narrow ordinary-order capability.
3
3
  *
4
- * Local reservation/margin accounting models one single-instrument, immediate
5
- * GFD limit order in the confirmed InvestorID. Every other InputOrder mode is
4
+ * Local reservation/margin accounting models single-instrument GFD, FAK and
5
+ * FOK limit orders in the confirmed InvestorID. Every other InputOrder mode is
6
6
  * rejected before it reaches CTP; accepting it as an "ordinary" order would
7
7
  * silently claim risk coverage for dimensions the ledger does not represent.
8
8
  */
@@ -52,6 +52,10 @@ inline bool decodeOrdinaryOrder(
52
52
  f.CombHedgeFlag[0] == '5' ||
53
53
  f.CombHedgeFlag[0] == '6' ||
54
54
  f.CombHedgeFlag[0] == '7';
55
+ const bool supportedExecutionPolicy =
56
+ (f.TimeCondition == '3' && f.VolumeCondition == '1') ||
57
+ (f.TimeCondition == '1' &&
58
+ (f.VolumeCondition == '1' || f.VolumeCondition == '3'));
55
59
  return !identity.brokerId.empty() && !identity.investorId.empty() &&
56
60
  !identity.orderRef.empty() && !identity.instrumentId.empty() &&
57
61
  (f.Direction == '0' || f.Direction == '1') &&
@@ -60,8 +64,7 @@ inline bool decodeOrdinaryOrder(
60
64
  f.CombHedgeFlag[1] == '\0' && f.OrderPriceType == '2' &&
61
65
  std::isfinite(f.LimitPrice) && f.LimitPrice > 0.0 &&
62
66
  f.LimitPrice < 1e300 && f.VolumeTotalOriginal > 0 &&
63
- f.TimeCondition == '3' && gtdDate.empty() &&
64
- f.VolumeCondition == '1' && f.MinVolume == 1 &&
67
+ supportedExecutionPolicy && gtdDate.empty() && f.MinVolume == 1 &&
65
68
  f.ContingentCondition == '1' && f.StopPrice == 0.0 &&
66
69
  f.ForceCloseReason == '0' && f.IsAutoSuspend == 0 &&
67
70
  businessUnit.empty() && f.RequestID == 0 &&
@@ -1294,7 +1294,7 @@ bool RiskEngine::acceptLoginSession(int requestId, int frontId, int sessionId,
1294
1294
  std::lock_guard<std::mutex> lk(posMutex_);
1295
1295
  if (requestId <= 0 || requestId != pendingSessionRequestId_ ||
1296
1296
  !pendingSessionExpectsLogin_ || brokerId.empty() || userId.empty() ||
1297
- frontId <= 0 || sessionId <= 0 ||
1297
+ frontId <= 0 || sessionId == 0 ||
1298
1298
  (!pendingSessionBrokerId_.empty() &&
1299
1299
  brokerId != pendingSessionBrokerId_) ||
1300
1300
  (!pendingSessionUserId_.empty() && userId != pendingSessionUserId_))
@@ -1329,7 +1329,7 @@ bool RiskEngine::confirmSessionAccount(
1329
1329
  const std::string &investorId) {
1330
1330
  std::lock_guard<RiskSendMutex> send(sendModeMutex_);
1331
1331
  std::lock_guard<std::mutex> lk(posMutex_);
1332
- if (!loginSessionKnown_ || frontId <= 0 || sessionId <= 0 ||
1332
+ if (!loginSessionKnown_ || frontId <= 0 || sessionId == 0 ||
1333
1333
  frontId != myFrontId_ || sessionId != mySessionId_ || brokerId.empty() ||
1334
1334
  investorId.empty() || brokerId != myBrokerId_)
1335
1335
  return false;
@@ -46,6 +46,28 @@ namespace {
46
46
  // the process instead of surfacing a catchable JS RangeError.
47
47
  constexpr uint32_t kMaxInstrumentLimitBatch = 65536;
48
48
 
49
+ bool readInstrumentLimitBatchLength(const Napi::Array &input,
50
+ const char *label, uint32_t &length) {
51
+ Napi::Value lengthValue = input.Get("length");
52
+ if (!lengthValue.IsNumber()) {
53
+ Napi::TypeError::New(input.Env(), std::string(label) +
54
+ " length must be numeric")
55
+ .ThrowAsJavaScriptException();
56
+ return false;
57
+ }
58
+ const double rawLength = lengthValue.As<Napi::Number>().DoubleValue();
59
+ if (!std::isfinite(rawLength) || rawLength < 0.0 ||
60
+ rawLength > static_cast<double>(kMaxInstrumentLimitBatch)) {
61
+ Napi::RangeError::New(
62
+ input.Env(), std::string(label) +
63
+ " batch exceeds the maximum of 65536 instruments")
64
+ .ThrowAsJavaScriptException();
65
+ return false;
66
+ }
67
+ length = static_cast<uint32_t>(rawLength);
68
+ return true;
69
+ }
70
+
49
71
  bool toStringList(const Napi::Value &v, std::vector<std::string> &out,
50
72
  const char *label) {
51
73
  if (v.IsArray()) {
@@ -801,15 +823,12 @@ Napi::Value Trader::SetInstrumentPositionLimits(
801
823
  return env.Undefined();
802
824
  }
803
825
  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();
826
+ uint32_t length = 0;
827
+ if (!readInstrumentLimitBatchLength(input, "position limits", length))
808
828
  return env.Undefined();
809
- }
810
829
  std::vector<InstrumentPositionLimitUpdate> updates;
811
- updates.reserve(input.Length());
812
- for (uint32_t i = 0; i < input.Length(); ++i) {
830
+ updates.reserve(length);
831
+ for (uint32_t i = 0; i < length; ++i) {
813
832
  Napi::Value rowValue = input.Get(i);
814
833
  if (!rowValue.IsObject()) {
815
834
  Napi::TypeError::New(env, "each position limit must be an object")
@@ -854,15 +873,12 @@ Napi::Value Trader::SetInstrumentMarginLimits(
854
873
  return env.Undefined();
855
874
  }
856
875
  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();
876
+ uint32_t length = 0;
877
+ if (!readInstrumentLimitBatchLength(input, "margin limits", length))
861
878
  return env.Undefined();
862
- }
863
879
  std::vector<InstrumentMarginLimitUpdate> updates;
864
- updates.reserve(input.Length());
865
- for (uint32_t i = 0; i < input.Length(); ++i) {
880
+ updates.reserve(length);
881
+ for (uint32_t i = 0; i < length; ++i) {
866
882
  Napi::Value rowValue = input.Get(i);
867
883
  if (!rowValue.IsObject()) {
868
884
  Napi::TypeError::New(env, "each margin limit must be an object")
package/src/trader.ts CHANGED
@@ -72,6 +72,30 @@ export interface PositionSeed {
72
72
  margin: number;
73
73
  }
74
74
 
75
+ /** A bounded margin-rate sync scoped to the hedge flag used by the orders that
76
+ * will consume those schedules in the native risk ledger. */
77
+ export interface MarginRateSyncOptions {
78
+ instrumentIds: string[];
79
+ hedgeFlag: "1" | "2" | "3" | "5" | "6" | "7";
80
+ }
81
+
82
+ /** The request-correlated identity established by a successful trader login. */
83
+ export interface TraderSessionIdentity {
84
+ readonly frontId: number;
85
+ readonly sessionId: number;
86
+ /** MaxOrderRef reported by this login response. The process-wide automatic
87
+ * allocator may retain a higher high-water mark from earlier sends. */
88
+ readonly maxOrderRef: number;
89
+ }
90
+
91
+ export interface TraderSessionResult {
92
+ identity: TraderSessionIdentity;
93
+ multipliers: number;
94
+ marginRates: number;
95
+ positions: number;
96
+ orders: number;
97
+ }
98
+
75
99
  /** Options for the one-call post-connect handshake, {@link Trader.session}. */
76
100
  export interface SessionOptions {
77
101
  brokerId: string;
@@ -89,13 +113,13 @@ export interface SessionOptions {
89
113
  * for environments that don't need it. */
90
114
  confirmSettlement?: boolean;
91
115
  /** Which risk inputs to fetch after login. Multipliers/positions/orders default
92
- * on; margin rates require an explicit contract list. `multipliers` may
93
- * be `true` (all instruments) or a list of symbols. */
116
+ * on; margin rates require an explicit contract list and hedge flag.
117
+ * `multipliers` may be `true` (all instruments) or a list of symbols. */
94
118
  sync?: {
95
119
  multipliers?: boolean | string[];
96
- /** Contracts whose speculation margin schedules should be queried. Omitted
97
- * by default because CTP requires one rate query per contract. */
98
- marginRates?: string[];
120
+ /** Contracts and hedge flag whose margin schedules should be queried.
121
+ * Omitted by default because CTP requires one rate query per contract. */
122
+ marginRates?: MarginRateSyncOptions;
99
123
  positions?: boolean;
100
124
  orders?: boolean;
101
125
  };
@@ -171,6 +195,7 @@ const SESSION_KEYS = new Set([
171
195
  "confirmSettlement", "sync",
172
196
  ]);
173
197
  const SESSION_SYNC_KEYS = new Set(["multipliers", "marginRates", "positions", "orders"]);
198
+ const MARGIN_RATE_SYNC_KEYS = new Set(["instrumentIds", "hedgeFlag"]);
174
199
  const ARM_SPEC_KEYS = new Set(["instrumentId", "side", "triggerPrice", "order"]);
175
200
  const POSITION_LIMIT_KEYS = new Set(["long", "short"]);
176
201
  const POSITION_SEED_KEYS = new Set([
@@ -213,7 +238,8 @@ export class Trader extends TraderBase {
213
238
  }
214
239
  if (eventName !== "rsp-user-login") return;
215
240
  // A matched login response updates the confirmed identity, but only from a
216
- // row carrying the COMPLETE, usable identity (FrontID/SessionID > 0 plus
241
+ // row carrying the COMPLETE, usable identity (FrontID > 0, non-zero signed
242
+ // SessionID, plus
217
243
  // BrokerID/UserID) — the same acceptance condition the generated login
218
244
  // validator enforces before it resolves. A partial/abnormal success row
219
245
  // (e.g. FrontID 0) is rejected downstream, so caching broker/investor from
@@ -241,7 +267,7 @@ export class Trader extends TraderBase {
241
267
  Number.isInteger(r.frontId) &&
242
268
  Number(r.frontId) > 0 &&
243
269
  Number.isInteger(r.sessionId) &&
244
- Number(r.sessionId) > 0
270
+ Number(r.sessionId) !== 0
245
271
  ) {
246
272
  this.broker = r.brokerId;
247
273
  this.investor = r.userId;
@@ -286,12 +312,11 @@ export class Trader extends TraderBase {
286
312
  * login → confirm settlement → sync multipliers / margin rates / orders /
287
313
  * positions. Each
288
314
  * step just wraps the matching req / sync method, so you can hand-roll your
289
- * own flow instead when you need finer control. Returns the row counts from
290
- * the sync steps. Must run on a connected front (queries need the session up).
315
+ * own flow instead when you need finer control. Returns the request-correlated
316
+ * login identity and row counts from the sync steps. Must run on a connected
317
+ * front (queries need the session up).
291
318
  */
292
- async session(opts: SessionOptions): Promise<{
293
- multipliers: number; marginRates: number; positions: number; orders: number;
294
- }> {
319
+ async session(opts: SessionOptions): Promise<TraderSessionResult> {
295
320
  assertObjectKeys(opts, "session options", SESSION_KEYS);
296
321
  const cleanOpts = copyOwnRecord(opts, "session options");
297
322
  const { brokerId, userId, password, appId, authCode } = cleanOpts;
@@ -323,10 +348,29 @@ export class Trader extends TraderBase {
323
348
  cleanSync.multipliers = copyDenseStringArray(
324
349
  multipliers, "session.sync.multipliers"
325
350
  );
326
- if (marginRates !== undefined)
327
- cleanSync.marginRates = copyDenseStringArray(
351
+ if (marginRates !== undefined) {
352
+ assertObjectKeys(
353
+ marginRates, "session.sync.marginRates", MARGIN_RATE_SYNC_KEYS
354
+ );
355
+ const cleanMarginRates = copyOwnRecord(
328
356
  marginRates, "session.sync.marginRates"
329
357
  );
358
+ const instrumentIds = copyDenseStringArray(
359
+ cleanMarginRates.instrumentIds,
360
+ "session.sync.marginRates.instrumentIds",
361
+ false
362
+ );
363
+ const hedgeFlag = cleanMarginRates.hedgeFlag;
364
+ if (typeof hedgeFlag !== "string" || !/^[123567]$/.test(hedgeFlag)) {
365
+ throw new TypeError(
366
+ "session.sync.marginRates.hedgeFlag must be 1, 2, 3, 5, 6 or 7"
367
+ );
368
+ }
369
+ cleanSync.marginRates = {
370
+ instrumentIds,
371
+ hedgeFlag: hedgeFlag as MarginRateSyncOptions["hedgeFlag"],
372
+ };
373
+ }
330
374
  if (positions !== undefined && typeof positions !== "boolean")
331
375
  throw new TypeError("session.sync.positions must be boolean");
332
376
  if (orders !== undefined && typeof orders !== "boolean")
@@ -393,7 +437,7 @@ export class Trader extends TraderBase {
393
437
  RspUserLogin | undefined;
394
438
  this.assertRequestContext(contextToken, "trader session login");
395
439
  if (!login || !Number.isInteger(login.frontId) || login.frontId <= 0 ||
396
- !Number.isInteger(login.sessionId) || login.sessionId <= 0 ||
440
+ !Number.isInteger(login.sessionId) || login.sessionId === 0 ||
397
441
  login.brokerId !== brokerId ||
398
442
  login.userId !== userId) {
399
443
  // FrontID/SessionID are part of the reservation identity. Treating an
@@ -403,6 +447,14 @@ export class Trader extends TraderBase {
403
447
  this.investor = undefined;
404
448
  throw new Error("trader login response has missing or mismatched session identity");
405
449
  }
450
+ const maxOrderRef = typeof login.maxOrderRef === "string"
451
+ ? login.maxOrderRef.trim() : "";
452
+ if (maxOrderRef !== "" && !/^\d{1,12}$/.test(maxOrderRef)) {
453
+ this.broker = undefined;
454
+ this.investor = undefined;
455
+ throw new Error("trader login response has an invalid MaxOrderRef");
456
+ }
457
+ const maxRef = maxOrderRef === "" ? 0 : Number(maxOrderRef);
406
458
  // A successful CTP response may legally end with an empty payload. The
407
459
  // request identity is still authoritative for the synchronization calls
408
460
  // below; never retain a previous session's broker/investor in that case.
@@ -416,11 +468,7 @@ export class Trader extends TraderBase {
416
468
  }
417
469
  this.broker = brokerId;
418
470
  this.investor = investorId;
419
- const maxOrderRef = typeof login.maxOrderRef === "string"
420
- ? login.maxOrderRef.trim() : "";
421
- const maxRef = /^\d{1,12}$/.test(maxOrderRef) ? Number(maxOrderRef) : NaN;
422
- if (Number.isFinite(maxRef) && maxRef > this.orderRefSeq)
423
- this.orderRefSeq = maxRef;
471
+ if (maxRef > this.orderRefSeq) this.orderRefSeq = maxRef;
424
472
  if (cleanOpts.confirmSettlement ?? true) {
425
473
  // idempotent: confirming an already-confirmed statement is fine
426
474
  await this.reqSettlementInfoConfirm({ brokerId, investorId });
@@ -428,13 +476,27 @@ export class Trader extends TraderBase {
428
476
  }
429
477
  const sync = cleanSync;
430
478
  const mul = sync.multipliers ?? true;
431
- const result = { multipliers: 0, marginRates: 0, positions: 0, orders: 0 };
479
+ const result: TraderSessionResult = {
480
+ identity: Object.freeze({
481
+ frontId: login.frontId,
482
+ sessionId: login.sessionId,
483
+ maxOrderRef: maxRef,
484
+ }),
485
+ multipliers: 0,
486
+ marginRates: 0,
487
+ positions: 0,
488
+ orders: 0,
489
+ };
432
490
  if (mul) {
433
491
  result.multipliers = await this.syncMultipliers(Array.isArray(mul) ? mul : undefined);
434
492
  this.assertRequestContext(contextToken, "trader session multiplier sync");
435
493
  }
436
- if (sync.marginRates?.length) {
437
- result.marginRates = await this.syncMarginRates(sync.marginRates);
494
+ const marginRateSync = sync.marginRates;
495
+ if (marginRateSync !== undefined) {
496
+ result.marginRates = await this.syncMarginRates(
497
+ marginRateSync.instrumentIds,
498
+ marginRateSync.hedgeFlag
499
+ );
438
500
  this.assertRequestContext(contextToken, "trader session margin sync");
439
501
  }
440
502
  if (sync.orders ?? true) {
@@ -511,13 +573,16 @@ export class Trader extends TraderBase {
511
573
  const value = <K extends keyof InputOrder>(key: K, fallback: InputOrder[K]) =>
512
574
  clean[key] === undefined ? fallback : clean[key];
513
575
  const empty = (v: unknown) => v === undefined || v === "";
514
- // This binding deliberately models only one immediate, single-instrument
515
- // GFD limit order. Reject every semantic/dimension the native reservation
516
- // ledger does not represent; otherwise an arm could be accepted now and
517
- // retry an impossible template forever after its trigger fires.
576
+ // The reservation ledger models ordinary single-instrument limit orders.
577
+ // Admit only the three execution policies whose live remainder is fully
578
+ // represented by CTP order/trade callbacks: GFD, FAK and FOK.
579
+ const timeCondition = value("timeCondition", "3");
580
+ const volumeCondition = value("volumeCondition", "1");
581
+ const supportedExecutionPolicy =
582
+ (timeCondition === "3" && volumeCondition === "1") ||
583
+ (timeCondition === "1" && (volumeCondition === "1" || volumeCondition === "3"));
518
584
  if (value("orderPriceType", "2") !== "2" ||
519
- value("timeCondition", "3") !== "3" || !empty(clean.gtdDate) ||
520
- value("volumeCondition", "1") !== "1" ||
585
+ !supportedExecutionPolicy || !empty(clean.gtdDate) ||
521
586
  value("minVolume", 1) !== 1 ||
522
587
  value("contingentCondition", "1") !== "1" ||
523
588
  value("stopPrice", 0) !== 0 ||
@@ -530,16 +595,16 @@ export class Trader extends TraderBase {
530
595
  !empty(clean.currencyId) || !empty(clean.clientId) ||
531
596
  value("sessionReqSeq", 0) !== 0) {
532
597
  throw new TypeError(
533
- `${context}: only an immediate single-instrument GFD limit order is supported`
598
+ `${context}: only single-instrument GFD, FAK or FOK limit orders are supported`
534
599
  );
535
600
  }
536
601
  return {
537
602
  ...clean,
538
603
  orderPriceType: "2",
539
604
  combHedgeFlag: clean.combHedgeFlag ?? "1",
540
- timeCondition: "3",
605
+ timeCondition,
541
606
  gtdDate: "",
542
- volumeCondition: "1",
607
+ volumeCondition,
543
608
  minVolume: 1,
544
609
  contingentCondition: "1",
545
610
  stopPrice: 0,