@hitrading/ctp-node 1.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 (102) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +208 -0
  3. package/README.zh-CN.md +185 -0
  4. package/binding.gyp +90 -0
  5. package/dist/client.d.ts +115 -0
  6. package/dist/client.d.ts.map +1 -0
  7. package/dist/client.js +466 -0
  8. package/dist/client.js.map +1 -0
  9. package/dist/codec.d.ts +29 -0
  10. package/dist/codec.d.ts.map +1 -0
  11. package/dist/codec.js +131 -0
  12. package/dist/codec.js.map +1 -0
  13. package/dist/generated/enums.gen.d.ts +2257 -0
  14. package/dist/generated/enums.gen.d.ts.map +1 -0
  15. package/dist/generated/enums.gen.js +2576 -0
  16. package/dist/generated/enums.gen.js.map +1 -0
  17. package/dist/generated/structs.gen.d.ts +11041 -0
  18. package/dist/generated/structs.gen.d.ts.map +1 -0
  19. package/dist/generated/structs.gen.js +939 -0
  20. package/dist/generated/structs.gen.js.map +1 -0
  21. package/dist/generated/trader.gen.d.ts +273 -0
  22. package/dist/generated/trader.gen.d.ts.map +1 -0
  23. package/dist/generated/trader.gen.js +653 -0
  24. package/dist/generated/trader.gen.js.map +1 -0
  25. package/dist/index.d.ts +9 -0
  26. package/dist/index.d.ts.map +1 -0
  27. package/dist/index.js +9 -0
  28. package/dist/index.js.map +1 -0
  29. package/dist/market-data.d.ts +66 -0
  30. package/dist/market-data.d.ts.map +1 -0
  31. package/dist/market-data.js +105 -0
  32. package/dist/market-data.js.map +1 -0
  33. package/dist/native-binding.d.ts +2 -0
  34. package/dist/native-binding.d.ts.map +1 -0
  35. package/dist/native-binding.js +22 -0
  36. package/dist/native-binding.js.map +1 -0
  37. package/dist/trader.d.ts +234 -0
  38. package/dist/trader.d.ts.map +1 -0
  39. package/dist/trader.js +388 -0
  40. package/dist/trader.js.map +1 -0
  41. package/package.json +69 -0
  42. package/prebuilds/linux-x64/@hitrading+ctp-node.node +0 -0
  43. package/prebuilds/linux-x64/thostmduserapi_se.so +0 -0
  44. package/prebuilds/linux-x64/thosttraderapi_se.so +0 -0
  45. package/prebuilds/win32-x64/@hitrading+ctp-node.node +0 -0
  46. package/prebuilds/win32-x64/thostmduserapi_se.dll +0 -0
  47. package/prebuilds/win32-x64/thosttraderapi_se.dll +0 -0
  48. package/src/addon.cc +171 -0
  49. package/src/client.ts +539 -0
  50. package/src/codec.ts +160 -0
  51. package/src/generated/enums.gen.ts +2576 -0
  52. package/src/generated/layout.gen.cc +5771 -0
  53. package/src/generated/layout.gen.h +8 -0
  54. package/src/generated/structids.gen.h +470 -0
  55. package/src/generated/structs.gen.ts +12437 -0
  56. package/src/generated/trader.gen.ts +656 -0
  57. package/src/generated/traderreq.gen.cc +706 -0
  58. package/src/generated/traderreq.gen.h +127 -0
  59. package/src/generated/traderspi.gen.cc +636 -0
  60. package/src/generated/traderspi.gen.h +334 -0
  61. package/src/index.ts +14 -0
  62. package/src/market-data.ts +145 -0
  63. package/src/native/arm.cc +77 -0
  64. package/src/native/arm.h +71 -0
  65. package/src/native/channel.cc +175 -0
  66. package/src/native/channel.h +117 -0
  67. package/src/native/gbk.cc +54 -0
  68. package/src/native/gbk.h +17 -0
  69. package/src/native/mdapi.cc +412 -0
  70. package/src/native/mdapi.h +14 -0
  71. package/src/native/mdspi.cc +103 -0
  72. package/src/native/mdspi.h +81 -0
  73. package/src/native/risk.cc +461 -0
  74. package/src/native/risk.h +183 -0
  75. package/src/native/traderapi.cc +533 -0
  76. package/src/native/traderapi.h +14 -0
  77. package/src/native-binding.ts +25 -0
  78. package/src/trader.ts +522 -0
  79. package/tradeapi/ThostFtdcMdApi.h +168 -0
  80. package/tradeapi/ThostFtdcTraderApi.h +914 -0
  81. package/tradeapi/ThostFtdcUserApiDataType.h +7068 -0
  82. package/tradeapi/ThostFtdcUserApiStruct.h +12386 -0
  83. package/tradeapi/error.dtd +9 -0
  84. package/tradeapi/error.xml +284 -0
  85. package/tradeapi/linux/thostmduserapi_se.so +0 -0
  86. package/tradeapi/linux/thosttraderapi_se.so +0 -0
  87. package/tradeapi/macos/thostmduserapi_se.framework/Versions/A/Headers/ThostFtdcMdApi.h +168 -0
  88. package/tradeapi/macos/thostmduserapi_se.framework/Versions/A/Headers/ThostFtdcUserApiDataType.h +7068 -0
  89. package/tradeapi/macos/thostmduserapi_se.framework/Versions/A/Headers/ThostFtdcUserApiStruct.h +12386 -0
  90. package/tradeapi/macos/thostmduserapi_se.framework/Versions/A/Resources/Info.plist +46 -0
  91. package/tradeapi/macos/thostmduserapi_se.framework/Versions/A/_CodeSignature/CodeResources +149 -0
  92. package/tradeapi/macos/thostmduserapi_se.framework/Versions/A/thostmduserapi_se +0 -0
  93. package/tradeapi/macos/thosttraderapi_se.framework/Versions/A/Headers/ThostFtdcTraderApi.h +914 -0
  94. package/tradeapi/macos/thosttraderapi_se.framework/Versions/A/Headers/ThostFtdcUserApiDataType.h +7068 -0
  95. package/tradeapi/macos/thosttraderapi_se.framework/Versions/A/Headers/ThostFtdcUserApiStruct.h +12386 -0
  96. package/tradeapi/macos/thosttraderapi_se.framework/Versions/A/Resources/Info.plist +46 -0
  97. package/tradeapi/macos/thosttraderapi_se.framework/Versions/A/_CodeSignature/CodeResources +149 -0
  98. package/tradeapi/macos/thosttraderapi_se.framework/Versions/A/thosttraderapi_se +0 -0
  99. package/tradeapi/windows/thostmduserapi_se.dll +0 -0
  100. package/tradeapi/windows/thostmduserapi_se.lib +0 -0
  101. package/tradeapi/windows/thosttraderapi_se.dll +0 -0
  102. package/tradeapi/windows/thosttraderapi_se.lib +0 -0
package/src/trader.ts ADDED
@@ -0,0 +1,522 @@
1
+ /*
2
+ * trader.ts - the Trader client (交易).
3
+ *
4
+ * Inherits every generated reqXxx() (typed input, Promise output) from
5
+ * TraderBase, and adds pre-trade risk controls (enforced in C++ on the order
6
+ * path) plus typed streaming events.
7
+ */
8
+
9
+ import { native } from "./native-binding.js";
10
+ import { TraderBase, TRADER_EVENTS, TraderEvent } from "./generated/trader.gen.js";
11
+ import { STRUCT_ID } from "./generated/structs.gen.js";
12
+ import type { CallbackOptions } from "./client.js";
13
+ import type { Order, Trade, InputOrder, RspUserLogin } from "./generated/structs.gen.js";
14
+ import type { MarketData } from "./market-data.js";
15
+
16
+ const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
17
+
18
+ /** Pre-trade risk limits, enforced in C++ before each order is sent. */
19
+ export interface RiskConfig {
20
+ /** Max volume per single order. Omit/0 = disabled. */
21
+ maxOrderVolume?: number;
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. */
25
+ maxPriceDeviation?: number;
26
+ /** Max notional (price × volume) per order. Omit/0 = disabled. */
27
+ maxNotional?: number;
28
+ /** Max order sends per second (token bucket). Omit/0 = disabled. */
29
+ maxOrdersPerSec?: number;
30
+ /** Token-bucket burst; defaults to maxOrdersPerSec. */
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(). */
35
+ maxPositionCost?: number;
36
+ }
37
+
38
+ /** A per-instrument lot cap: a single number caps both sides at that value;
39
+ * `{ long, short }` caps each side separately (omit a side to leave it open). */
40
+ export type LotCap = number | { long?: number; short?: number };
41
+
42
+ /** Options for the one-call post-connect handshake, {@link Trader.session}. */
43
+ export interface SessionOptions {
44
+ brokerId: string;
45
+ userId: string;
46
+ password: string;
47
+ /** Terminal authentication (real accounts require it; SimNow uses
48
+ * appId "simnow_client_test" / authCode of 16 zeros). Omit both to skip. */
49
+ appId?: string;
50
+ authCode?: string;
51
+ /** Confirm the settlement statement after login — real accounts must do this
52
+ * before trading (brokers reject orders otherwise). Default true; set false
53
+ * for environments that don't need it. */
54
+ confirmSettlement?: boolean;
55
+ /** Which risk inputs to fetch after login (default: all). `multipliers` may
56
+ * be `true` (all instruments) or a list of symbols. */
57
+ sync?: { multipliers?: boolean | string[]; positions?: boolean; orders?: boolean };
58
+ }
59
+
60
+ /** A latency-critical armed order: evaluated and fired in C++ on the market-data
61
+ * callback thread the instant its trigger hits — JS is never in the hot path. */
62
+ export interface ArmSpec {
63
+ instrumentId: string;
64
+ /** Buy fires when ask ≤ triggerPrice; sell when bid ≥ triggerPrice. */
65
+ side: "buy" | "sell";
66
+ triggerPrice: number;
67
+ /** The order to send when triggered (a full InputOrder; set an OrderRef to
68
+ * correlate the resulting rtn-order). */
69
+ order: Partial<InputOrder>;
70
+ }
71
+
72
+ export interface ArmHandle {
73
+ readonly id: number;
74
+ /** Remove the trigger. Returns false if it was already gone. */
75
+ disarm(): boolean;
76
+ }
77
+
78
+ /** Reject a non-finite risk/cap limit. A NaN/Inf would make every `value > limit`
79
+ * comparison in C++ false, silently DISABLING the control and leaving the caller
80
+ * believing a cap is active — a risk control must never fail open by accident.
81
+ * Finite values (including 0/negative, which legitimately mean "disabled") pass. */
82
+ function assertFiniteLimit(name: string, v: number | undefined): void {
83
+ if (v !== undefined && !Number.isFinite(v)) {
84
+ throw new TypeError(`${name} must be a finite number (got ${v})`);
85
+ }
86
+ }
87
+
88
+ export class Trader extends TraderBase {
89
+ private broker?: string;
90
+ private investor?: string;
91
+ private orderRefSeq = 0;
92
+
93
+ constructor(flowPath: string, fronts: string | string[]) {
94
+ super(new native.Trader(flowPath, fronts), native.__layoutData(), TRADER_EVENTS);
95
+ // Remember credentials from the login response so sync* needs no args, and
96
+ // seed the order-ref counter past the broker's max so auto-assigned refs
97
+ // never collide with a prior session's (CTP rejects duplicate refs).
98
+ this.on("rsp-user-login", (d: unknown) => {
99
+ const r = d as
100
+ | { brokerId?: string; userId?: string; maxOrderRef?: string; frontId?: number; sessionId?: number }
101
+ | undefined;
102
+ if (r) {
103
+ this.broker = r.brokerId;
104
+ this.investor = r.userId;
105
+ const mx = r.maxOrderRef ? parseInt(r.maxOrderRef, 10) : NaN;
106
+ 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
+ }
112
+ }
113
+ });
114
+ this.start();
115
+ }
116
+
117
+ getApiVersion(): string {
118
+ return this.native.getApiVersion();
119
+ }
120
+ getTradingDay(): string {
121
+ return this.native.getTradingDay();
122
+ }
123
+
124
+ /**
125
+ * One-call post-connect handshake. Call it from the `front-connected` handler
126
+ * (and again after a reconnect): authenticate (if appId/authCode given) →
127
+ * login → confirm settlement → sync multipliers / positions / orders. Each
128
+ * step just wraps the matching req / sync method, so you can hand-roll your
129
+ * own flow instead when you need finer control. Returns the row counts from
130
+ * the sync steps. Must run on a connected front (queries need the session up).
131
+ */
132
+ async session(opts: SessionOptions): Promise<{ multipliers: number; positions: number; orders: number }> {
133
+ const { brokerId, userId, password, appId, authCode } = opts;
134
+ if (appId !== undefined && authCode !== undefined) {
135
+ await this.reqAuthenticate({ brokerId, userId, appId, authCode });
136
+ }
137
+ await this.reqUserLogin({ brokerId, userId, password });
138
+ if (opts.confirmSettlement ?? true) {
139
+ // idempotent: confirming an already-confirmed statement is fine
140
+ await this.reqSettlementInfoConfirm({ brokerId, investorId: userId });
141
+ }
142
+ const sync = opts.sync ?? {};
143
+ const mul = sync.multipliers ?? true;
144
+ const result = { multipliers: 0, positions: 0, orders: 0 };
145
+ if (mul) result.multipliers = await this.syncMultipliers(Array.isArray(mul) ? mul : undefined);
146
+ if (sync.positions ?? true) result.positions = await this.syncPositions();
147
+ if (sync.orders ?? true) result.orders = await this.syncOrders();
148
+ return result;
149
+ }
150
+
151
+ /** Assign a unique numeric OrderRef when the caller left it blank. CTP treats
152
+ * OrderRef as a per-session sequence and rejects a duplicate or non-numeric
153
+ * ref with "不允许重复报单", so an unset ref would otherwise collide. */
154
+ private withAutoOrderRef(order: Partial<InputOrder>): Partial<InputOrder> {
155
+ if (order.orderRef === undefined || order.orderRef === "") {
156
+ return { ...order, orderRef: String(++this.orderRefSeq) };
157
+ }
158
+ return order;
159
+ }
160
+
161
+ /**
162
+ * Insert an order through the C++ pre-trade risk gate. Resolves on submission:
163
+ * CTP sends no success acknowledgement for an accepted order - only
164
+ * OnRtnOrder / OnRtnTrade (surfaced as the rtn-order / rtn-trade events;
165
+ * correlate by orderRef). It rejects only if the send itself is refused (risk
166
+ * gate, rate limit, or a CTP API error code). A blank orderRef is assigned a
167
+ * unique numeric value automatically.
168
+ */
169
+ reqOrderInsert(req: Partial<InputOrder> = {}): Promise<void> {
170
+ return super.reqOrderInsert(this.withAutoOrderRef(req));
171
+ }
172
+
173
+ /** Publish pre-trade risk limits to the C++ enforcer (takes effect at once). */
174
+ riskSet(config: RiskConfig): this {
175
+ // A non-finite limit would silently disable that control (see
176
+ // assertFiniteLimit) — reject it rather than run unprotected.
177
+ assertFiniteLimit("riskSet.maxOrderVolume", config.maxOrderVolume);
178
+ assertFiniteLimit("riskSet.maxPriceDeviation", config.maxPriceDeviation);
179
+ assertFiniteLimit("riskSet.maxNotional", config.maxNotional);
180
+ assertFiniteLimit("riskSet.maxOrdersPerSec", config.maxOrdersPerSec);
181
+ assertFiniteLimit("riskSet.orderBurst", config.orderBurst);
182
+ assertFiniteLimit("riskSet.maxPositionCost", config.maxPositionCost);
183
+ this.native.riskSet(config);
184
+ return this;
185
+ }
186
+ /** Kill-switch: C++ immediately blocks every order-opening send that reaches
187
+ * the exchange at once — regular, exec, quote, for-quote, option-self-close
188
+ * and comb-action inserts. Cancels and other *actions* are deliberately left
189
+ * open so you can still pull working orders while halted; parked/staged orders
190
+ * (not sent to the exchange immediately) are likewise not gated. Takes effect
191
+ * at once; reverse with {@link resume}. */
192
+ halt(): this {
193
+ this.native.riskHalt();
194
+ return this;
195
+ }
196
+ /** Release the kill-switch (see {@link halt}). */
197
+ resume(): this {
198
+ this.native.riskResume();
199
+ return this;
200
+ }
201
+
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. */
210
+ trackMarketData(md: MarketData): this {
211
+ md.on("rtn-depth-market-data", (t) =>
212
+ this.native.setRefPrice(t.instrumentId, t.lastPrice)
213
+ );
214
+ return this;
215
+ }
216
+
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
+ }
222
+
223
+ /**
224
+ * Cap the open position (in lots) for one instrument, enforced in C++ on
225
+ * every opening order. Pass a number to cap both sides at once, or
226
+ * `{ long, short }` to cap each side separately. Within `{ long, short }`,
227
+ * **omitting a side leaves that side's current cap unchanged** (on a re-call it
228
+ * is NOT reset to uncapped), and passing `<= 0` for a side removes its cap.
229
+ * Long and short are always tracked independently.
230
+ *
231
+ * The check is fill-based (counts confirmed position, like maxPositionCost),
232
+ * so rapid bursts of opens can momentarily overshoot before the fills land —
233
+ * size the cap with that in mind.
234
+ *
235
+ * td.setMaxPosition("rb2610", 100); // long<=100 and short<=100
236
+ * td.setMaxPosition("ru2610", { long: 100, short: 20 });
237
+ */
238
+ setMaxPosition(instrumentId: string, max: LotCap): this {
239
+ if (typeof max === "number") {
240
+ assertFiniteLimit("setMaxPosition", max);
241
+ this.native.setMaxPositionVolume(instrumentId, true, max);
242
+ this.native.setMaxPositionVolume(instrumentId, false, max);
243
+ } else {
244
+ assertFiniteLimit("setMaxPosition.long", max.long);
245
+ assertFiniteLimit("setMaxPosition.short", max.short);
246
+ if (max.long !== undefined) this.native.setMaxPositionVolume(instrumentId, true, max.long);
247
+ if (max.short !== undefined) this.native.setMaxPositionVolume(instrumentId, false, max.short);
248
+ }
249
+ return this;
250
+ }
251
+
252
+ /** Cap several instruments at once, e.g.
253
+ * `{ rb2610: 100, ru2610: { long: 100, short: 20 } }`. */
254
+ setMaxPositions(limits: Record<string, LotCap>): this {
255
+ for (const id of Object.keys(limits)) this.setMaxPosition(id, limits[id]);
256
+ return this;
257
+ }
258
+
259
+ /**
260
+ * Cap one instrument's open-position cost (Σ open price × volume × multiplier,
261
+ * long and short summed - a gross capital/concentration limit), enforced in
262
+ * C++ on every opening order. This is per-instrument and independent of the
263
+ * account-wide cap set via riskSet({ maxPositionCost }); both apply. Pass
264
+ * `maxCost <= 0` to remove it. Fill-based, same caveat as maxPositionCost.
265
+ */
266
+ setMaxPositionCost(instrumentId: string, maxCost: number): this {
267
+ assertFiniteLimit("setMaxPositionCost", maxCost);
268
+ this.native.setMaxInstrumentCost(instrumentId, maxCost);
269
+ return this;
270
+ }
271
+
272
+ /** Cap several instruments' open-position cost at once, e.g.
273
+ * `{ ag2608: 2_000_000, au2608: 5_000_000 }`. */
274
+ setMaxPositionCosts(limits: Record<string, number>): this {
275
+ for (const id of Object.keys(limits)) {
276
+ assertFiniteLimit(`setMaxPositionCosts.${id}`, limits[id]);
277
+ this.native.setMaxInstrumentCost(id, limits[id]);
278
+ }
279
+ return this;
280
+ }
281
+
282
+ /** Seed a pre-existing position's open cost (for the maxPositionCost cap). */
283
+ seedPosition(
284
+ instrumentId: string,
285
+ side: "long" | "short",
286
+ volume: number,
287
+ openCost: number
288
+ ): this {
289
+ this.native.seedPosition(instrumentId, side === "long", volume, openCost);
290
+ return this;
291
+ }
292
+
293
+ /** Seed open-position cost from reqQryInvestorPosition() rows for GROSS-mode
294
+ * 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. */
299
+ seedFromPositions(
300
+ positions: ReadonlyArray<{
301
+ instrumentId: string;
302
+ posiDirection: string;
303
+ position: number;
304
+ openCost: number;
305
+ }>
306
+ ): this {
307
+ // Aggregate by instrument+side (CTP may return several rows per instrument).
308
+ const agg = new Map<string, { id: string; long: boolean; vol: number; cost: number }>();
309
+ for (const p of positions) {
310
+ if (!(p.position > 0)) continue;
311
+ const long = p.posiDirection === "2";
312
+ const key = `${p.instrumentId}|${long}`;
313
+ const e = agg.get(key) ?? { id: p.instrumentId, long, vol: 0, cost: 0 };
314
+ e.vol += p.position;
315
+ e.cost += p.openCost;
316
+ agg.set(key, e);
317
+ }
318
+ for (const e of agg.values()) this.seedPosition(e.id, e.long ? "long" : "short", e.vol, e.cost);
319
+ return this;
320
+ }
321
+
322
+ /** Current total open-position cost tracked by the C++ risk engine. */
323
+ positionCost(): number {
324
+ return this.native.positionCost();
325
+ }
326
+
327
+ /** Clear all tracked position cost. */
328
+ resetPositions(): this {
329
+ this.native.resetPositions();
330
+ return this;
331
+ }
332
+
333
+ /**
334
+ * Run a CTP query with flow-control retries. CTP rate-limits queries (~1/sec)
335
+ * and one issued too soon after login can be rejected or come back empty
336
+ * before the account is ready. With `requireNonEmpty`, an empty result is
337
+ * treated as not-ready-yet and retried (for data that must exist, e.g. an
338
+ * instrument); otherwise empty is returned as-is (e.g. a genuinely flat
339
+ * position book, so a flat account doesn't waste the full retry budget).
340
+ */
341
+ private async queryWithRetry<T>(
342
+ query: () => Promise<T[]>,
343
+ requireNonEmpty: boolean,
344
+ attempts = 5
345
+ ): Promise<T[]> {
346
+ let lastErr: unknown;
347
+ for (let i = 0; i < attempts; i++) {
348
+ if (i > 0) await sleep(1100); // respect the ~1/sec query limit
349
+ try {
350
+ const rows = await query();
351
+ if (!requireNonEmpty || rows.length > 0) return rows;
352
+ } catch (e) {
353
+ lastErr = e; // flow-control rejection - back off and retry
354
+ }
355
+ }
356
+ if (lastErr) throw lastErr;
357
+ return [];
358
+ }
359
+
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. */
363
+ async syncMultipliers(instrumentIds?: string[]): Promise<number> {
364
+ let count = 0;
365
+ const apply = (rows: unknown[]) => {
366
+ 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
+ }
371
+ }
372
+ };
373
+ if (instrumentIds && instrumentIds.length) {
374
+ for (let i = 0; i < instrumentIds.length; i++) {
375
+ apply(await this.queryWithRetry(() => this.reqQryInstrument({ instrumentId: instrumentIds[i] }), true));
376
+ if (i < instrumentIds.length - 1) await sleep(1100); // query flow control
377
+ }
378
+ } else {
379
+ apply(await this.queryWithRetry(() => this.reqQryInstrument({}), true));
380
+ }
381
+ return count;
382
+ }
383
+
384
+ /** Seed open-position cost from CTP (reqQryInvestorPosition). Uses the
385
+ * logged-in account unless brokerId/investorId are supplied. */
386
+ async syncPositions(opts?: { brokerId?: string; investorId?: string }): Promise<number> {
387
+ const brokerId = opts?.brokerId ?? this.broker;
388
+ const investorId = opts?.investorId ?? this.investor;
389
+ const rows = (await this.queryWithRetry(
390
+ () => this.reqQryInvestorPosition({ brokerId, investorId }),
391
+ false
392
+ )) as Array<{
393
+ instrumentId: string;
394
+ posiDirection: string;
395
+ position: number;
396
+ openCost: number;
397
+ }>;
398
+ this.resetPositions();
399
+ this.seedFromPositions(rows);
400
+ return rows.filter((r) => r.position > 0).length;
401
+ }
402
+
403
+ /**
404
+ * Rebuild the in-flight reservation from CTP's currently-working orders
405
+ * (reqQryOrder) - an authoritative resync. Call it after login and after any
406
+ * reconnect so the position caps account for orders already working at the
407
+ * broker: ones placed before a reconnect, or - since CTP delivers them too -
408
+ * orders placed from another terminal on the same account. Returns the number
409
+ * of working open orders re-reserved. Run syncMultipliers() first so the
410
+ * reserved cost uses the right contract multiplier.
411
+ */
412
+ async syncOrders(opts?: { brokerId?: string; investorId?: string }): Promise<number> {
413
+ const brokerId = opts?.brokerId ?? this.broker;
414
+ const investorId = opts?.investorId ?? this.investor;
415
+ const rows = (await this.queryWithRetry(
416
+ () => this.reqQryOrder({ brokerId, investorId }),
417
+ false
418
+ )) as Array<{
419
+ frontId: number;
420
+ sessionId: number;
421
+ orderRef: string;
422
+ instrumentId: string;
423
+ combOffsetFlag: string;
424
+ direction: string;
425
+ orderStatus: string;
426
+ limitPrice: number;
427
+ volumeTotalOriginal: number;
428
+ volumeTraded: number;
429
+ }>;
430
+ // working = queueing (PartTradedQueueing '1' / NoTradeQueueing '3'); open only
431
+ const working = rows
432
+ .filter((o) => (o.orderStatus === "1" || o.orderStatus === "3") && o.combOffsetFlag?.[0] === "0")
433
+ .map((o) => ({
434
+ frontId: o.frontId,
435
+ sessionId: o.sessionId,
436
+ orderRef: o.orderRef,
437
+ instrumentId: o.instrumentId,
438
+ isLong: o.direction === "0",
439
+ vol: o.volumeTotalOriginal - o.volumeTraded,
440
+ price: o.limitPrice,
441
+ }));
442
+ this.native.rebuildReservations(working);
443
+ return working.length;
444
+ }
445
+
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
+ /**
459
+ * Arm a latency-critical trigger: when `md` sees the condition, the order is
460
+ * sent from C++ on the callback thread (through this Trader's risk gate),
461
+ * with no JS round trip. One-shot. The acknowledgement arrives via the normal
462
+ * rtn-order / rsp-order-insert events (correlate by the order's orderRef).
463
+ */
464
+ arm(md: MarketData, spec: ArmSpec): ArmHandle {
465
+ // Validate up front: the order fires from C++ with no JS in the loop, so a
466
+ // malformed template would silently misfire (e.g. a missing combOffsetFlag
467
+ // defaults to a "close" and skips the position reservation).
468
+ if (!spec.instrumentId || !(spec.triggerPrice > 0)) {
469
+ throw new Error("arm: spec.instrumentId and a positive triggerPrice are required");
470
+ }
471
+ const order = this.withAutoOrderRef(spec.order);
472
+ if (!order.instrumentId || order.direction === undefined || !order.combOffsetFlag ||
473
+ !(Number(order.volumeTotalOriginal) > 0)) {
474
+ throw new Error("arm: spec.order needs instrumentId, direction, combOffsetFlag and volumeTotalOriginal > 0");
475
+ }
476
+ md.attachArm(this);
477
+ const bytes = this.encode(STRUCT_ID.InputOrder, order as Record<string, unknown>);
478
+ const id: number = this.native.arm(
479
+ spec.instrumentId,
480
+ spec.side === "buy" ? "0" : "1",
481
+ spec.triggerPrice,
482
+ bytes
483
+ );
484
+ return { id, disarm: () => this.native.disarm(id) as boolean };
485
+ }
486
+
487
+ /** Observability for armed triggers (they fire in C++ with no JS in the loop):
488
+ * how many fired and were sent vs were refused by the risk gate / send.
489
+ * A blocked armed order is otherwise invisible, so poll this after a trigger
490
+ * you expected to fire. */
491
+ armStats(): { fired: number; blocked: number } {
492
+ return { fired: this.native._armFireCount(), blocked: this.native._armBlockedCount() };
493
+ }
494
+
495
+ /** @internal used by MarketData.attachArm to share the arm registry. */
496
+ _armRegistry(): unknown {
497
+ return this.native._armRegistry();
498
+ }
499
+
500
+ /** @internal test-only: how many times armed triggers have fired (sent). */
501
+ _armFireCount(): number {
502
+ return this.native._armFireCount();
503
+ }
504
+ /** @internal test-only: how many armed triggers were blocked on fire. */
505
+ _armBlockedCount(): number {
506
+ return this.native._armBlockedCount();
507
+ }
508
+
509
+ // Typed streaming events (the common ones; any event name still works).
510
+ on(event: "rtn-order", cb: (data: Order, opts: CallbackOptions) => void): this;
511
+ on(event: "rtn-trade", cb: (data: Trade, opts: CallbackOptions) => void): this;
512
+ on(event: "front-connected", cb: (data: undefined, opts: CallbackOptions) => void): this;
513
+ on(event: "front-disconnected", cb: (reason: number, opts: CallbackOptions) => void): this;
514
+ on(event: "rsp-user-login", cb: (data: RspUserLogin, opts: CallbackOptions) => void): this;
515
+ on(event: "err-rtn-order-insert", cb: (data: InputOrder, opts: CallbackOptions) => void): this;
516
+ on(event: string, cb: (...args: never[]) => void): this;
517
+ on(event: string, cb: (...args: never[]) => void): this {
518
+ return super.on(event, cb as (...args: unknown[]) => void);
519
+ }
520
+ }
521
+
522
+ export { TraderEvent };
@@ -0,0 +1,168 @@
1
+ /////////////////////////////////////////////////////////////////////////
2
+ ///@system 新一代交易所系统
3
+ ///@company 上海期货信息技术有限公司
4
+ ///@file ThostFtdcMdApi.h
5
+ ///@brief 定义了客户端接口
6
+ ///@history
7
+ ///20060106 赵鸿昊 创建该文件
8
+ /////////////////////////////////////////////////////////////////////////
9
+
10
+ #if !defined(THOST_FTDCMDAPI_H)
11
+ #define THOST_FTDCMDAPI_H
12
+
13
+ #if _MSC_VER > 1000
14
+ #pragma once
15
+ #endif // _MSC_VER > 1000
16
+
17
+ #include "ThostFtdcUserApiStruct.h"
18
+
19
+ #if defined(ISLIB) && defined(WIN32)
20
+ #ifdef LIB_MD_API_EXPORT
21
+ #define MD_API_EXPORT __declspec(dllexport)
22
+ #else
23
+ #define MD_API_EXPORT __declspec(dllimport)
24
+ #endif
25
+ #else
26
+ #define MD_API_EXPORT
27
+ #endif
28
+
29
+ class CThostFtdcMdSpi
30
+ {
31
+ public:
32
+ ///当客户端与交易后台建立起通信连接时(还未登录前),该方法被调用。
33
+ virtual void OnFrontConnected(){};
34
+
35
+ ///当客户端与交易后台通信连接断开时,该方法被调用。当发生这个情况后,API会自动重新连接,客户端可不做处理。
36
+ ///@param nReason 错误原因
37
+ /// 0x1001 网络读失败
38
+ /// 0x1002 网络写失败
39
+ /// 0x2001 接收心跳超时
40
+ /// 0x2002 发送心跳失败
41
+ /// 0x2003 收到错误报文
42
+ virtual void OnFrontDisconnected(int nReason){};
43
+
44
+ ///心跳超时警告。当长时间未收到报文时,该方法被调用。
45
+ ///@param nTimeLapse 距离上次接收报文的时间
46
+ virtual void OnHeartBeatWarning(int nTimeLapse){};
47
+
48
+
49
+ ///登录请求响应
50
+ virtual void OnRspUserLogin(CThostFtdcRspUserLoginField *pRspUserLogin, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {};
51
+
52
+ ///登出请求响应
53
+ virtual void OnRspUserLogout(CThostFtdcUserLogoutField *pUserLogout, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {};
54
+
55
+ ///请求查询组播合约响应
56
+ virtual void OnRspQryMulticastInstrument(CThostFtdcMulticastInstrumentField *pMulticastInstrument, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {};
57
+
58
+ ///错误应答
59
+ virtual void OnRspError(CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {};
60
+
61
+ ///订阅行情应答
62
+ virtual void OnRspSubMarketData(CThostFtdcSpecificInstrumentField *pSpecificInstrument, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {};
63
+
64
+ ///取消订阅行情应答
65
+ virtual void OnRspUnSubMarketData(CThostFtdcSpecificInstrumentField *pSpecificInstrument, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {};
66
+
67
+ ///订阅询价应答
68
+ virtual void OnRspSubForQuoteRsp(CThostFtdcSpecificInstrumentField *pSpecificInstrument, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {};
69
+
70
+ ///取消订阅询价应答
71
+ virtual void OnRspUnSubForQuoteRsp(CThostFtdcSpecificInstrumentField *pSpecificInstrument, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {};
72
+
73
+ ///深度行情通知
74
+ virtual void OnRtnDepthMarketData(CThostFtdcDepthMarketDataField *pDepthMarketData) {};
75
+
76
+ ///询价通知
77
+ virtual void OnRtnForQuoteRsp(CThostFtdcForQuoteRspField *pForQuoteRsp) {};
78
+ };
79
+
80
+ class MD_API_EXPORT CThostFtdcMdApi
81
+ {
82
+ public:
83
+ ///创建MdApi
84
+ ///@param pszFlowPath 存贮订阅信息文件的目录,默认为当前目录
85
+ ///@return 创建出的UserApi
86
+ ///modify for udp marketdata
87
+ static CThostFtdcMdApi *CreateFtdcMdApi(const char *pszFlowPath = "", const bool bIsUsingUdp=false, const bool bIsMulticast=false);
88
+
89
+ ///获取API的版本信息
90
+ ///@retrun 获取到的版本号
91
+ static const char *GetApiVersion();
92
+
93
+ ///删除接口对象本身
94
+ ///@remark 不再使用本接口对象时,调用该函数删除接口对象
95
+ virtual void Release() = 0;
96
+
97
+ ///初始化
98
+ ///@remark 初始化运行环境,只有调用后,接口才开始工作
99
+ virtual void Init() = 0;
100
+
101
+ ///等待接口线程结束运行
102
+ ///@return 线程退出代码
103
+ virtual int Join() = 0;
104
+
105
+ ///获取当前交易日
106
+ ///@retrun 获取到的交易日
107
+ ///@remark 只有登录成功后,才能得到正确的交易日
108
+ virtual const char *GetTradingDay() = 0;
109
+
110
+ ///注册前置机网络地址
111
+ ///@param pszFrontAddress:前置机网络地址。
112
+ ///@remark 网络地址的格式为:“protocol://ipaddress:port”,如:”tcp://127.0.0.1:17001”。
113
+ ///@remark “tcp”代表传输协议,“127.0.0.1”代表服务器地址。”17001”代表服务器端口号。
114
+ virtual void RegisterFront(char *pszFrontAddress) = 0;
115
+
116
+ ///注册名字服务器网络地址
117
+ ///@param pszNsAddress:名字服务器网络地址。
118
+ ///@remark 网络地址的格式为:“protocol://ipaddress:port”,如:”tcp://127.0.0.1:12001”。
119
+ ///@remark “tcp”代表传输协议,“127.0.0.1”代表服务器地址。”12001”代表服务器端口号。
120
+ ///@remark RegisterNameServer优先于RegisterFront
121
+ virtual void RegisterNameServer(char *pszNsAddress) = 0;
122
+
123
+ ///注册名字服务器用户信息
124
+ ///@param pFensUserInfo:用户信息。
125
+ virtual void RegisterFensUserInfo(CThostFtdcFensUserInfoField * pFensUserInfo) = 0;
126
+
127
+ ///注册回调接口
128
+ ///@param pSpi 派生自回调接口类的实例
129
+ virtual void RegisterSpi(CThostFtdcMdSpi *pSpi) = 0;
130
+
131
+ ///订阅行情。
132
+ ///@param ppInstrumentID 合约ID
133
+ ///@param nCount 要订阅/退订行情的合约个数
134
+ ///@remark
135
+ virtual int SubscribeMarketData(char *ppInstrumentID[], int nCount) = 0;
136
+
137
+ ///退订行情。
138
+ ///@param ppInstrumentID 合约ID
139
+ ///@param nCount 要订阅/退订行情的合约个数
140
+ ///@remark
141
+ virtual int UnSubscribeMarketData(char *ppInstrumentID[], int nCount) = 0;
142
+
143
+ ///订阅询价。
144
+ ///@param ppInstrumentID 合约ID
145
+ ///@param nCount 要订阅/退订行情的合约个数
146
+ ///@remark
147
+ virtual int SubscribeForQuoteRsp(char *ppInstrumentID[], int nCount) = 0;
148
+
149
+ ///退订询价。
150
+ ///@param ppInstrumentID 合约ID
151
+ ///@param nCount 要订阅/退订行情的合约个数
152
+ ///@remark
153
+ virtual int UnSubscribeForQuoteRsp(char *ppInstrumentID[], int nCount) = 0;
154
+
155
+ ///用户登录请求
156
+ virtual int ReqUserLogin(CThostFtdcReqUserLoginField *pReqUserLoginField, int nRequestID) = 0;
157
+
158
+
159
+ ///登出请求
160
+ virtual int ReqUserLogout(CThostFtdcUserLogoutField *pUserLogout, int nRequestID) = 0;
161
+
162
+ ///请求查询组播合约
163
+ virtual int ReqQryMulticastInstrument(CThostFtdcQryMulticastInstrumentField *pQryMulticastInstrument, int nRequestID) = 0;
164
+ protected:
165
+ ~CThostFtdcMdApi(){};
166
+ };
167
+
168
+ #endif