@hitrading/ctp-node 1.1.0 → 2.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.
Files changed (86) hide show
  1. package/README.md +12 -5
  2. package/README.zh-CN.md +12 -5
  3. package/binding.gyp +13 -13
  4. package/{tradeapi/macos/thostmduserapi_se.framework/Versions/A/Headers → ctpsdk}/ThostFtdcMdApi.h +2 -1
  5. package/{tradeapi/macos/thosttraderapi_se.framework/Versions/A/Headers → ctpsdk}/ThostFtdcTraderApi.h +133 -6
  6. package/{tradeapi/macos/thostmduserapi_se.framework/Versions/A/Headers → ctpsdk}/ThostFtdcUserApiDataType.h +199 -3
  7. package/{tradeapi/macos/thosttraderapi_se.framework/Versions/A/Headers → ctpsdk}/ThostFtdcUserApiStruct.h +1574 -12
  8. package/{tradeapi → ctpsdk}/error.xml +56 -11
  9. package/ctpsdk/linux/thostmduserapi_se.so +0 -0
  10. package/{tradeapi → ctpsdk}/linux/thosttraderapi_se.so +0 -0
  11. package/{tradeapi → ctpsdk/macos/thostmduserapi_se.framework/Versions/A/Headers}/ThostFtdcMdApi.h +1 -1
  12. package/{tradeapi → ctpsdk/macos/thostmduserapi_se.framework/Versions/A/Headers}/ThostFtdcUserApiDataType.h +35 -2
  13. package/{tradeapi → ctpsdk/macos/thostmduserapi_se.framework/Versions/A/Headers}/ThostFtdcUserApiStruct.h +121 -11
  14. package/{tradeapi → ctpsdk}/macos/thostmduserapi_se.framework/Versions/A/Resources/Info.plist +46 -46
  15. package/{tradeapi → ctpsdk}/macos/thostmduserapi_se.framework/Versions/A/_CodeSignature/CodeResources +149 -149
  16. package/{tradeapi → ctpsdk}/macos/thostmduserapi_se.framework/Versions/A/thostmduserapi_se +0 -0
  17. package/{tradeapi → ctpsdk/macos/thosttraderapi_se.framework/Versions/A/Headers}/ThostFtdcTraderApi.h +14 -2
  18. package/{tradeapi → ctpsdk}/macos/thosttraderapi_se.framework/Versions/A/Headers/ThostFtdcUserApiDataType.h +2123 -2090
  19. package/{tradeapi/macos/thostmduserapi_se.framework → ctpsdk/macos/thosttraderapi_se.framework}/Versions/A/Headers/ThostFtdcUserApiStruct.h +5596 -5486
  20. package/{tradeapi → ctpsdk}/macos/thosttraderapi_se.framework/Versions/A/Resources/Info.plist +46 -46
  21. package/{tradeapi → ctpsdk}/macos/thosttraderapi_se.framework/Versions/A/_CodeSignature/CodeResources +149 -149
  22. package/{tradeapi → ctpsdk}/macos/thosttraderapi_se.framework/Versions/A/thosttraderapi_se +0 -0
  23. package/ctpsdk/windows/thostmduserapi_se.dll +0 -0
  24. package/ctpsdk/windows/thostmduserapi_se.lib +0 -0
  25. package/ctpsdk/windows/thosttraderapi_se.dll +0 -0
  26. package/ctpsdk/windows/thosttraderapi_se.lib +0 -0
  27. package/dist/client.d.ts +4 -0
  28. package/dist/client.d.ts.map +1 -1
  29. package/dist/client.js +7 -0
  30. package/dist/client.js.map +1 -1
  31. package/dist/generated/enums.gen.d.ts +76 -6
  32. package/dist/generated/enums.gen.d.ts.map +1 -1
  33. package/dist/generated/enums.gen.js +78 -0
  34. package/dist/generated/enums.gen.js.map +1 -1
  35. package/dist/generated/structs.gen.d.ts +6271 -4816
  36. package/dist/generated/structs.gen.d.ts.map +1 -1
  37. package/dist/generated/structs.gen.js +131 -25
  38. package/dist/generated/structs.gen.js.map +1 -1
  39. package/dist/generated/trader.gen.d.ts +39 -1
  40. package/dist/generated/trader.gen.d.ts.map +1 -1
  41. package/dist/generated/trader.gen.js +315 -225
  42. package/dist/generated/trader.gen.js.map +1 -1
  43. package/dist/index.cjs +594 -296
  44. package/dist/market-data.d.ts +10 -0
  45. package/dist/market-data.d.ts.map +1 -1
  46. package/dist/market-data.js +20 -0
  47. package/dist/market-data.js.map +1 -1
  48. package/dist/native-binding.js +1 -1
  49. package/dist/native-binding.js.map +1 -1
  50. package/dist/trader.d.ts +38 -30
  51. package/dist/trader.d.ts.map +1 -1
  52. package/dist/trader.js +39 -45
  53. package/dist/trader.js.map +1 -1
  54. package/package.json +7 -3
  55. package/prebuilds/linux-x64/@hitrading+ctp-node.node +0 -0
  56. package/prebuilds/linux-x64/thostmduserapi_se.so +0 -0
  57. package/prebuilds/linux-x64/thosttraderapi_se.so +0 -0
  58. package/prebuilds/win32-x64/@hitrading+ctp-node.node +0 -0
  59. package/prebuilds/win32-x64/thostmduserapi_se.dll +0 -0
  60. package/prebuilds/win32-x64/thosttraderapi_se.dll +0 -0
  61. package/src/client.ts +8 -0
  62. package/src/generated/enums.gen.ts +78 -0
  63. package/src/generated/layout.gen.cc +794 -40
  64. package/src/generated/structids.gen.h +54 -1
  65. package/src/generated/structs.gen.ts +6455 -4841
  66. package/src/generated/trader.gen.ts +315 -225
  67. package/src/generated/traderreq.gen.cc +84 -0
  68. package/src/generated/traderreq.gen.h +89 -75
  69. package/src/generated/traderspi.gen.cc +102 -0
  70. package/src/generated/traderspi.gen.h +198 -150
  71. package/src/market-data.ts +23 -0
  72. package/src/native/mdapi.cc +49 -2
  73. package/src/native/mdspi.cc +5 -1
  74. package/src/native/mdspi.h +4 -0
  75. package/src/native/risk.cc +50 -21
  76. package/src/native/risk.h +48 -8
  77. package/src/native/snapshot.h +61 -0
  78. package/src/native/traderapi.cc +11 -61
  79. package/src/native-binding.ts +1 -1
  80. package/src/trader.ts +55 -58
  81. package/tradeapi/linux/thostmduserapi_se.so +0 -0
  82. package/tradeapi/windows/thostmduserapi_se.dll +0 -0
  83. package/tradeapi/windows/thostmduserapi_se.lib +0 -0
  84. package/tradeapi/windows/thosttraderapi_se.dll +0 -0
  85. package/tradeapi/windows/thosttraderapi_se.lib +0 -0
  86. /package/{tradeapi → ctpsdk}/error.dtd +0 -0
package/src/trader.ts CHANGED
@@ -20,8 +20,8 @@ export interface RiskConfig {
20
20
  /** Max volume per single order. Omit/0 = disabled. */
21
21
  maxOrderVolume?: number;
22
22
  /** Reject if order price deviates from the reference by > this ratio (e.g.
23
- * 0.02 = 2%). Feed the reference via trackMarketData() or setRefPrice();
24
- * with no reference the check is skipped. */
23
+ * 0.02 = 2%). Feed the reference via trackMarketData(md) (the MD snapshot is
24
+ * read in C++); with no reference the check is skipped. */
25
25
  maxPriceDeviation?: number;
26
26
  /** Max notional (price × volume) per order. Omit/0 = disabled. */
27
27
  maxNotional?: number;
@@ -29,10 +29,19 @@ export interface RiskConfig {
29
29
  maxOrdersPerSec?: number;
30
30
  /** Token-bucket burst; defaults to maxOrdersPerSec. */
31
31
  orderBurst?: number;
32
- /** Cap on total open-position cost (Σ open price × volume × multiplier).
33
- * 0/undefined = disabled. Multipliers and existing positions are picked up
34
- * automatically via syncMultipliers() / syncPositions(). */
32
+ /** @deprecated Use {@link maxMargin}. Back-compat alias; now also margin-based
33
+ * (the tracked open cost is real margin once margin rates are known).
34
+ * maxMargin takes precedence when both are set. */
35
35
  maxPositionCost?: number;
36
+ /** Cap on total open-position MARGIN (Σ open price × volume × multiplier ×
37
+ * marginRate) — the real capital occupied, a zero-lag hard cap enforced in
38
+ * C++ on every opening order (regular AND armed). 0/undefined = disabled.
39
+ * Margin rates are fed automatically from CTP's OnRspQryInstrumentMarginRate
40
+ * inside C++ (populate them by calling reqQryInstrumentMarginRate); until a
41
+ * contract's rate is known it counts at full notional (conservative).
42
+ * Multipliers / existing positions are picked up via syncMultipliers() /
43
+ * syncPositions(). */
44
+ maxMargin?: number;
36
45
  }
37
46
 
38
47
  /** A per-instrument lot cap: a single number caps both sides at that value;
@@ -104,11 +113,10 @@ export class Trader extends TraderBase {
104
113
  this.investor = r.userId;
105
114
  const mx = r.maxOrderRef ? parseInt(r.maxOrderRef, 10) : NaN;
106
115
  if (Number.isFinite(mx) && mx > this.orderRefSeq) this.orderRefSeq = mx;
107
- // Publish our session so reservations key by (front, session, ref) and
108
- // never collide with another terminal's orders on the same account.
109
- if (typeof r.frontId === "number" && typeof r.sessionId === "number") {
110
- this.native.setSession(r.frontId, r.sessionId);
111
- }
116
+ // (The login session FrontID/SessionID — used as reservation keys so our
117
+ // orders never collide with another terminal's on the same account — is
118
+ // published into the risk engine directly in C++ from OnRspUserLogin; no
119
+ // JS relay needed.)
112
120
  }
113
121
  });
114
122
  this.start();
@@ -180,6 +188,7 @@ export class Trader extends TraderBase {
180
188
  assertFiniteLimit("riskSet.maxOrdersPerSec", config.maxOrdersPerSec);
181
189
  assertFiniteLimit("riskSet.orderBurst", config.orderBurst);
182
190
  assertFiniteLimit("riskSet.maxPositionCost", config.maxPositionCost);
191
+ assertFiniteLimit("riskSet.maxMargin", config.maxMargin);
183
192
  this.native.riskSet(config);
184
193
  return this;
185
194
  }
@@ -199,26 +208,23 @@ export class Trader extends TraderBase {
199
208
  return this;
200
209
  }
201
210
 
202
- /** Set the reference price for an instrument (used by maxPriceDeviation). */
203
- setRefPrice(instrumentId: string, price: number): this {
204
- this.native.setRefPrice(instrumentId, price);
205
- return this;
206
- }
207
-
208
- /** Auto-feed last prices from a MarketData feed so the maxPriceDeviation
209
- * check has a live reference. */
211
+ /** Use a MarketData feed as the live reference for the maxPriceDeviation check.
212
+ * Wires the feed's C++ snapshot cache straight into this Trader's risk engine,
213
+ * so the deviation check reads current prices in C++ on the order path (no JS
214
+ * round-trip, and it also covers armed orders that fire with no JS in the loop).
215
+ * Without this, no reference is set and the deviation check is skipped. */
210
216
  trackMarketData(md: MarketData): this {
211
- md.on("rtn-depth-market-data", (t) =>
212
- this.native.setRefPrice(t.instrumentId, t.lastPrice)
213
- );
217
+ this.native._attachSnapshot(md._snapshotExternal());
214
218
  return this;
215
219
  }
216
220
 
217
- /** Set a contract's multiplier (合约乘数) for position-cost accounting. */
218
- setMultiplier(instrumentId: string, multiplier: number): this {
219
- this.native.setMultiplier(instrumentId, multiplier);
220
- return this;
221
- }
221
+ // Contract multipliers (for cost accounting) and margin rates (for the
222
+ // maxMargin cap) are NOT fed from JS: the C++ risk engine sources them directly
223
+ // from CTP's OnRspQryInstrument / OnRspQryInstrumentMarginRate callbacks (see
224
+ // scripts/codegen/generate-trader.mjs). So any reqQryInstrument keeps
225
+ // multipliers current, and querying reqQryInstrumentMarginRate for the
226
+ // contracts you trade keeps the margin cap exact — no JS round-trip, and the
227
+ // checks also cover armed orders that fire from C++ with no JS in the loop.
222
228
 
223
229
  /**
224
230
  * Cap the open position (in lots) for one instrument, enforced in C++ on
@@ -279,29 +285,33 @@ export class Trader extends TraderBase {
279
285
  return this;
280
286
  }
281
287
 
282
- /** Seed a pre-existing position's open cost (for the maxPositionCost cap). */
288
+ /** Seed a pre-existing position into the margin/cost cap. `margin` is the real
289
+ * capital occupied (CTP InvestorPosition.UseMargin) — the unit the maxMargin
290
+ * cap tracks. A deliberate resync op (overwrites the held side), so it stays a
291
+ * JS-driven call, unlike the passive multiplier / margin-rate feeds (sourced in
292
+ * C++). */
283
293
  seedPosition(
284
294
  instrumentId: string,
285
295
  side: "long" | "short",
286
296
  volume: number,
287
- openCost: number
297
+ margin: number
288
298
  ): this {
289
- this.native.seedPosition(instrumentId, side === "long", volume, openCost);
299
+ this.native.seedPosition(instrumentId, side === "long", volume, margin);
290
300
  return this;
291
301
  }
292
302
 
293
- /** Seed open-position cost from reqQryInvestorPosition() rows for GROSS-mode
303
+ /** Seed open-position MARGIN from reqQryInvestorPosition() rows for GROSS-mode
294
304
  * accounts (posiDirection '2' = long, '3' = short; any other value, incl. net
295
- * '1', is bucketed as short). Cost caps sum both sides so the bucket doesn't
296
- * matter for them, but a per-side *volume* cap on a net-mode instrument would
297
- * track the wrong side — for net-mode accounts, seed those via seedPosition()
298
- * with the side you intend. */
305
+ * '1', is bucketed as short). Uses each row's real UseMargin. Cost/margin caps
306
+ * sum both sides so the bucket doesn't matter for them, but a per-side *volume*
307
+ * cap on a net-mode instrument would track the wrong side — for net-mode
308
+ * accounts, seed those via seedPosition() with the side you intend. */
299
309
  seedFromPositions(
300
310
  positions: ReadonlyArray<{
301
311
  instrumentId: string;
302
312
  posiDirection: string;
303
313
  position: number;
304
- openCost: number;
314
+ useMargin: number;
305
315
  }>
306
316
  ): this {
307
317
  // Aggregate by instrument+side (CTP may return several rows per instrument).
@@ -312,7 +322,7 @@ export class Trader extends TraderBase {
312
322
  const key = `${p.instrumentId}|${long}`;
313
323
  const e = agg.get(key) ?? { id: p.instrumentId, long, vol: 0, cost: 0 };
314
324
  e.vol += p.position;
315
- e.cost += p.openCost;
325
+ e.cost += p.useMargin; // real margin occupied (the unit the cap tracks)
316
326
  agg.set(key, e);
317
327
  }
318
328
  for (const e of agg.values()) this.seedPosition(e.id, e.long ? "long" : "short", e.vol, e.cost);
@@ -357,17 +367,15 @@ export class Trader extends TraderBase {
357
367
  return [];
358
368
  }
359
369
 
360
- /** Fetch contract multipliers from CTP and apply them. No args queries all
361
- * instruments (one request); otherwise queries the given symbols. Retries
362
- * through cold-start flow control so the multiplier is reliably applied. */
370
+ /** Query instruments so the C++ risk engine picks up their multipliers (it
371
+ * sources them directly from OnRspQryInstrument — no JS feed). No args queries
372
+ * all instruments (one request); otherwise the given symbols. Retries through
373
+ * cold-start flow control. Returns the count of contracts with a multiplier. */
363
374
  async syncMultipliers(instrumentIds?: string[]): Promise<number> {
364
375
  let count = 0;
365
376
  const apply = (rows: unknown[]) => {
366
377
  for (const r of rows as Array<{ instrumentId: string; volumeMultiple: number }>) {
367
- if (r.volumeMultiple > 0) {
368
- this.setMultiplier(r.instrumentId, r.volumeMultiple);
369
- count++;
370
- }
378
+ if (r.volumeMultiple > 0) count++;
371
379
  }
372
380
  };
373
381
  if (instrumentIds && instrumentIds.length) {
@@ -381,8 +389,9 @@ export class Trader extends TraderBase {
381
389
  return count;
382
390
  }
383
391
 
384
- /** Seed open-position cost from CTP (reqQryInvestorPosition). Uses the
385
- * logged-in account unless brokerId/investorId are supplied. */
392
+ /** Seed open-position MARGIN from CTP (reqQryInvestorPosition) into the cap.
393
+ * Uses the logged-in account unless brokerId/investorId are supplied. A
394
+ * deliberate resync (resets the held book first), so it stays JS-driven. */
386
395
  async syncPositions(opts?: { brokerId?: string; investorId?: string }): Promise<number> {
387
396
  const brokerId = opts?.brokerId ?? this.broker;
388
397
  const investorId = opts?.investorId ?? this.investor;
@@ -393,7 +402,7 @@ export class Trader extends TraderBase {
393
402
  instrumentId: string;
394
403
  posiDirection: string;
395
404
  position: number;
396
- openCost: number;
405
+ useMargin: number;
397
406
  }>;
398
407
  this.resetPositions();
399
408
  this.seedFromPositions(rows);
@@ -443,18 +452,6 @@ export class Trader extends TraderBase {
443
452
  return working.length;
444
453
  }
445
454
 
446
- /** @internal test-only: feed a synthetic fill into the position-cost tracker. */
447
- _applyTestTrade(instrumentId: string, isBuy: boolean, isOpen: boolean, price: number, volume: number): void {
448
- this.native._applyTestTrade(instrumentId, isBuy, isOpen, price, volume);
449
- }
450
-
451
- /** @internal test-only: drive the in-flight reservation tracker (OnRtnOrder).
452
- * status: '1'/'3' = working (queueing), others (e.g. '0' filled, '5'
453
- * cancelled) = terminal. */
454
- _applyTestOrder(frontId: number, sessionId: number, orderRef: string, instrumentId: string, isOpen: boolean, isLong: boolean, status: string, limitPrice: number, volTotal: number, volTraded: number): void {
455
- this.native._applyTestOrder(frontId, sessionId, orderRef, instrumentId, isOpen, isLong, status, limitPrice, volTotal, volTraded);
456
- }
457
-
458
455
  /**
459
456
  * Arm a latency-critical trigger: when `md` sees the condition, the order is
460
457
  * sent from C++ on the callback thread (through this Trader's risk gate),
Binary file
File without changes