@hitrading/ctp-node 2.0.0 → 4.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 (79) hide show
  1. package/CHANGELOG.md +82 -0
  2. package/README.md +54 -32
  3. package/README.zh-CN.md +44 -27
  4. package/RELEASING.md +78 -0
  5. package/dist/client.d.ts +36 -15
  6. package/dist/client.d.ts.map +1 -1
  7. package/dist/client.js +234 -62
  8. package/dist/client.js.map +1 -1
  9. package/dist/codec.d.ts.map +1 -1
  10. package/dist/codec.js +84 -19
  11. package/dist/codec.js.map +1 -1
  12. package/dist/generated/structs.gen.d.ts +5461 -5461
  13. package/dist/generated/structs.gen.d.ts.map +1 -1
  14. package/dist/generated/trader.gen.d.ts.map +1 -1
  15. package/dist/generated/trader.gen.js +788 -94
  16. package/dist/generated/trader.gen.js.map +1 -1
  17. package/dist/index.cjs +1909 -417
  18. package/dist/index.d.cts +1 -1
  19. package/dist/index.d.ts +1 -1
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/index.js.map +1 -1
  22. package/dist/market-data.d.ts +41 -24
  23. package/dist/market-data.d.ts.map +1 -1
  24. package/dist/market-data.js +148 -29
  25. package/dist/market-data.js.map +1 -1
  26. package/dist/native-binding.d.ts.map +1 -1
  27. package/dist/native-binding.js +4 -0
  28. package/dist/native-binding.js.map +1 -1
  29. package/dist/trader.d.ts +136 -79
  30. package/dist/trader.d.ts.map +1 -1
  31. package/dist/trader.js +807 -182
  32. package/dist/trader.js.map +1 -1
  33. package/dist/validation.d.ts +27 -0
  34. package/dist/validation.d.ts.map +1 -0
  35. package/dist/validation.js +85 -0
  36. package/dist/validation.js.map +1 -0
  37. package/docs/API.md +1445 -0
  38. package/docs/API.zh-CN.md +1285 -0
  39. package/docs/MIGRATION.md +54 -0
  40. package/docs/assets/validation.svg +27 -0
  41. package/docs/integration.md +60 -0
  42. package/docs/native-hooks.md +281 -0
  43. package/docs/native-hooks.zh-CN.md +205 -0
  44. package/docs/troubleshooting.md +257 -0
  45. package/docs/troubleshooting.zh-CN.md +220 -0
  46. package/package.json +12 -4
  47. package/prebuilds/linux-x64/@hitrading+ctp-node.node +0 -0
  48. package/prebuilds/win32-x64/@hitrading+ctp-node.node +0 -0
  49. package/scripts/bench-decode.mjs +37 -0
  50. package/scripts/bench-fullmarket-offline.mjs +207 -0
  51. package/scripts/stress-fullmarket.mjs +255 -0
  52. package/src/addon.cc +2 -2
  53. package/src/client.ts +255 -65
  54. package/src/codec.ts +86 -19
  55. package/src/generated/structs.gen.ts +5461 -5461
  56. package/src/generated/trader.gen.ts +309 -94
  57. package/src/generated/traderreq.gen.cc +194 -18
  58. package/src/generated/traderreq.gen.h +4 -0
  59. package/src/generated/traderspi.gen.cc +129 -15
  60. package/src/generated/traderspi.gen.h +4 -2
  61. package/src/index.ts +11 -1
  62. package/src/market-data.ts +199 -46
  63. package/src/native/arm.cc +114 -30
  64. package/src/native/arm.h +16 -4
  65. package/src/native/channel.cc +209 -81
  66. package/src/native/channel.h +65 -24
  67. package/src/native/ctp_field.h +23 -0
  68. package/src/native/mdapi.cc +582 -69
  69. package/src/native/mdspi.cc +219 -16
  70. package/src/native/mdspi.h +59 -10
  71. package/src/native/order_capability.h +78 -0
  72. package/src/native/risk.cc +2030 -213
  73. package/src/native/risk.h +431 -78
  74. package/src/native/shared_handle.h +37 -0
  75. package/src/native/snapshot.h +75 -16
  76. package/src/native/traderapi.cc +769 -124
  77. package/src/native-binding.ts +4 -0
  78. package/src/trader.ts +1038 -207
  79. package/src/validation.ts +96 -0
package/docs/API.md ADDED
@@ -0,0 +1,1445 @@
1
+ <!-- LANG-SWITCH -->
2
+ **English** · [简体中文](API.zh-CN.md)
3
+
4
+ # ctp-node API Reference
5
+
6
+ Complete usage documentation for every public TypeScript/JavaScript interface in
7
+ `ctp-node`. For the architecture and native-hook internals see
8
+ [native-hooks.md](native-hooks.md); for the design overview see the
9
+ [README](../README.md).
10
+
11
+ - [Install](#install)
12
+ - [Quick start](#quick-start)
13
+ - [Core concepts](#core-concepts)
14
+ - [`MarketData`](#marketdata) — the market-data (行情) client
15
+ - [`Trader`](#trader) — the trading (交易) client
16
+ - [`CtpClient`](#ctpclient) — shared base (events, close, backpressure)
17
+ - [Types](#types) — `RiskLimits`, `InstrumentPositionLimit`, `SessionOptions`, `ArmSpec`, `ArmHandle`, `CallbackOptions`, `RspInfo`, `MdLoginReq`
18
+ - [Enums & struct types](#enums--struct-types)
19
+ - [Risk controls at a glance](#risk-controls-at-a-glance)
20
+ - [Recipes](#recipes) — strategy skeleton · reconnect handling · combination orders
21
+
22
+ ```ts
23
+ import {
24
+ MarketData, Trader,
25
+ Direction, OffsetFlag, OrderPriceType, // generated enums
26
+ type RiskLimits, type SessionOptions, type DepthMarketData,
27
+ } from "@hitrading/ctp-node";
28
+ ```
29
+
30
+ ---
31
+
32
+ ## Install
33
+
34
+ ```bash
35
+ npm install @hitrading/ctp-node
36
+ ```
37
+
38
+ Supported Node.js release lines are `^22.22.2 || ^24.15.0 || >=26.0.0`, matching
39
+ the bundled node-gyp 13 requirement. Prebuilt binaries ship in the npm package
40
+ for win32-x64 and linux-x64. macOS and other platforms build from source on
41
+ install (a C++ toolchain + Python are required).
42
+
43
+ ---
44
+
45
+ ## Quick start
46
+
47
+ ### Market data
48
+
49
+ ```ts
50
+ import { MarketData } from "@hitrading/ctp-node";
51
+
52
+ const md = new MarketData("./flow/md/", "tcp://182.254.243.31:30012");
53
+
54
+ md.on("front-connected", async () => {
55
+ await md.login({ brokerId: "9999", userId: "your-id", password: "your-pw" });
56
+ md.subscribe(["rb2510", "au2508"]);
57
+ });
58
+
59
+ md.on("rtn-depth-market-data", (tick) => {
60
+ console.log(tick.instrumentId, tick.lastPrice, tick.bidPrice1, tick.askPrice1);
61
+ });
62
+
63
+ // keep the process alive; call md.close() once at shutdown
64
+ ```
65
+
66
+ ### Trading with pre-trade risk
67
+
68
+ ```ts
69
+ import { Trader, Direction, OffsetFlag } from "@hitrading/ctp-node";
70
+
71
+ const td = new Trader("./flow/td/", "tcp://182.254.243.31:30002");
72
+
73
+ td.setRiskLimits({ maxOrderVolume: 10, maxOrdersPerSec: 20 });
74
+ td.setInstrumentPositionLimit("rb2510", 100); // never hold more than 100 lots/side
75
+
76
+ td.on("front-connected", async () => {
77
+ await td.session({
78
+ brokerId: "9999", userId: "your-id", password: "your-pw",
79
+ appId: "your-app", authCode: "your-auth-code",
80
+ });
81
+
82
+ // resolves on submission; the fill arrives via rtn-trade
83
+ await td.reqOrderInsert({
84
+ instrumentId: "rb2510",
85
+ direction: Direction.Buy, // "0"
86
+ combOffsetFlag: OffsetFlag.Open, // "0"
87
+ limitPrice: 3500,
88
+ volumeTotalOriginal: 1,
89
+ }).catch((e) => console.error("order refused:", e.message));
90
+ });
91
+
92
+ td.on("rtn-trade", (t) => console.log("filled", t.instrumentId, t.price, t.volume));
93
+ ```
94
+
95
+ ---
96
+
97
+ ## Core concepts
98
+
99
+ **Hybrid event + promise API.** Streaming pushes (ticks, order/trade returns,
100
+ connection state) are delivered as **EventEmitter** events with kebab-case names
101
+ (`rtn-depth-market-data`, `rtn-order`, …). Request/response calls return a
102
+ **Promise** correlated to the response (`login()`, `reqQry*()`, …).
103
+ Response-event payloads may be `undefined` on an error or an empty final row;
104
+ inspect `options.rspInfo` / `options.isLast` before dereferencing them.
105
+
106
+ **Strict request objects.** Requests/configs must be object literals (or
107
+ null-prototype dictionaries) with explicit own fields. Unknown, inherited,
108
+ misspelled, removed, symbol, and `null` field values are rejected before a
109
+ request reaches CTP; they are never silently encoded as zero. Input arrays must
110
+ be dense and contain explicit own entries; sparse or prototype-provided values
111
+ are rejected.
112
+
113
+ **Create once, reuse for the life of the process.** Construct a `MarketData` /
114
+ `Trader` once and keep it. CTP reconnects on its own — handle a dropped link
115
+ **in place** by re-running your handshake when `front-connected` fires again (it
116
+ fires on the first connect *and* every auto-reconnect). Do **not** destroy and
117
+ recreate the client: repeated Windows create/close cycles have been observed to
118
+ deadlock inside the vendor DLL's `Release()`. Call `close()` once at shutdown (or not at all —
119
+ process exit cleans up). See
120
+ [native-hooks.md → Process lifecycle](native-hooks.md#process-lifecycle-create-once-reuse).
121
+
122
+ **Backpressure.** Each client decodes ticks/returns from a native ring. Market
123
+ data uses bounded keep-newest overflow staging and retains the freshest quote.
124
+ Trader overflow is lossless and ordered: it spills beyond the
125
+ 4096-slot ring instead of dropping callbacks. Sustained Trader overload can use
126
+ unbounded memory, so event handlers still need to remain bounded.
127
+
128
+ **Pre-trade risk runs in C++.** All risk limits (`setRiskLimits`,
129
+ `setInstrumentPositionLimit`, `reduceOnly` / `haltAll`, …) are enforced on the order-send path inside the native addon, before
130
+ the order reaches CTP — no JS round trip. A blocked order makes
131
+ `reqOrderInsert()` reject; the reason is in the error message.
132
+
133
+ ---
134
+
135
+ ## `MarketData`
136
+
137
+ The market-data (行情) client. Subscribes to depth quotes and streams them as
138
+ events.
139
+
140
+ ### `new MarketData(flowPath, fronts)`
141
+
142
+ | Parameter | Type | Meaning |
143
+ |---|---|---|
144
+ | `flowPath` | `string` | Directory CTP uses for its flow files (caches sequence state). Created if missing; use a per-client path, e.g. `"./flow/md/"`. |
145
+ | `fronts` | `string \| string[]` | One or more front addresses, e.g. `"tcp://182.254.243.31:30012"`. Empty/empty-list throws. |
146
+
147
+ Construction connects asynchronously; wire your handlers, then act in the
148
+ `front-connected` handler.
149
+
150
+ ```ts
151
+ // single front
152
+ const md = new MarketData("./flow/md/", "tcp://182.254.243.31:30012");
153
+
154
+ // multiple fronts for failover
155
+ const md2 = new MarketData("./flow/md/", [
156
+ "tcp://182.254.243.31:30012",
157
+ "tcp://182.254.243.31:30011",
158
+ ]);
159
+ ```
160
+
161
+ ### `md.login(req?)` → `Promise<RspUserLogin | undefined>`
162
+
163
+ Log in to the market-data front. Resolves with the login response, or rejects
164
+ with a CTP error (`err.errorId`, `err.errorMsg`).
165
+
166
+ | Field of `req` (`MdLoginReq`, all optional) | Type | Meaning |
167
+ |---|---|---|
168
+ | `brokerId` | `string` | Broker id. |
169
+ | `userId` | `string` | Investor / user id. |
170
+ | `password` | `string` | Password. |
171
+ | `tradingDay` | `string` | Trading day (rarely needed). |
172
+ | `userProductInfo` | `string` | Product info tag. |
173
+
174
+ > SimNow's market-data front accepts an anonymous `login({})`; real fronts
175
+ > require credentials.
176
+ >
177
+ > Await every market-data `login()` / `logout()` before starting another one.
178
+ > Some fronts answer these requests with `requestId = 0`, so the binding
179
+ > deliberately permits only one such transition at a time. If one times out,
180
+ > the native cache/armed-order path remains fail-closed: the first late final
181
+ > response is ignored (or a front transition resets the state) before a new
182
+ > authenticated cache epoch can be established.
183
+
184
+ ```ts
185
+ // with credentials
186
+ md.on("front-connected", async () => {
187
+ const rsp = await md.login({ brokerId: "9999", userId: "id", password: "pw" });
188
+ console.log("logged in, trading day", rsp.tradingDay);
189
+ md.subscribe(["rb2510"]);
190
+ });
191
+
192
+ // anonymous (SimNow MD front)
193
+ await md.login();
194
+
195
+ // handle a bad login
196
+ try {
197
+ await md.login({ brokerId: "9999", userId: "id", password: "wrong" });
198
+ } catch (e) {
199
+ console.error("login failed", e.errorId, e.errorMsg);
200
+ }
201
+ ```
202
+
203
+ ### `md.logout(req?)` → `Promise<UserLogout | undefined>`
204
+
205
+ Log out. `req` may carry `{ brokerId?, userId? }`.
206
+
207
+ As with `login()`, market-data login/logout transitions must not overlap; await
208
+ the returned Promise before starting the next one.
209
+
210
+ ```ts
211
+ await md.logout();
212
+ // or scoped to a specific account
213
+ await md.logout({ brokerId: "9999", userId: "id" });
214
+ ```
215
+
216
+ ### `md.reqQryMulticastInstrument(req?)` → `Promise<MulticastInstrument[]>`
217
+
218
+ Query multicast instruments and resolve all response rows as an array. The
219
+ request may contain `topicId` and `instrumentId`. Calls use the same conservative
220
+ per-client query scheduler as other CTP queries, with at least 1100 ms between
221
+ sends. No caller-side sleep is required.
222
+
223
+ ```ts
224
+ const instruments = await md.reqQryMulticastInstrument({ topicId: 1 });
225
+ ```
226
+
227
+ ### `md.subscribe(instrumentIds)` → `number`
228
+
229
+ Subscribe to depth market data. Returns the CTP send code (`0` = accepted,
230
+ non-zero / `-1` = failed). Quotes arrive as `rtn-depth-market-data` events.
231
+
232
+ | Parameter | Type | Meaning |
233
+ |---|---|---|
234
+ | `instrumentIds` | `string[]` | Instrument ids to subscribe, e.g. `["rb2510", "au2508"]`. |
235
+
236
+ ```ts
237
+ md.on("rsp-sub-market-data", (info) => console.log("subscribed", info.instrumentId));
238
+ md.on("rtn-depth-market-data", (t) => console.log(t.instrumentId, t.lastPrice));
239
+
240
+ const rc = md.subscribe(["rb2510", "au2508"]);
241
+ if (rc !== 0) console.warn("subscribe send failed:", rc);
242
+
243
+ // subscribe more later (e.g. after rolling to a new contract)
244
+ md.subscribe(["rb2601"]);
245
+ ```
246
+
247
+ ### `md.unsubscribe(instrumentIds)` → `number`
248
+
249
+ Unsubscribe from depth market data. Same shape as `subscribe`.
250
+
251
+ ```ts
252
+ md.unsubscribe(["au2508"]); // stop one
253
+ md.unsubscribe(["rb2510", "au2508"]); // stop several
254
+ ```
255
+
256
+ ### `md.subscribeForQuote(instrumentIds)` / `md.unsubscribeForQuote(instrumentIds)` → `number`
257
+
258
+ Subscribe / unsubscribe to quote-request (询价) notifications, delivered as
259
+ `rtn-for-quote` events (used by options market makers).
260
+
261
+ ```ts
262
+ md.on("rtn-for-quote", (q) => console.log("quote requested for", q.instrumentId));
263
+ md.subscribeForQuote(["IO2508-C-3900"]);
264
+ // ...later
265
+ md.unsubscribeForQuote(["IO2508-C-3900"]);
266
+ ```
267
+
268
+ ### `md.snapshot(instrumentId)` → `DepthMarketData | null`
269
+
270
+ The latest full depth tick for an instrument, read **synchronously** from the
271
+ C++ last-value cache. A successful MD login starts a new, empty cache epoch;
272
+ only subsequent ticks in that authenticated epoch update it before reaching JS.
273
+ Connect/disconnect, a new login/logout attempt, successful logout, and close
274
+ invalidate and clear the epoch immediately. Returns `null` outside an active
275
+ epoch, if no tick has been seen for that instrument, or after unsubscribe.
276
+
277
+ | Parameter | Type | Meaning |
278
+ |---|---|---|
279
+ | `instrumentId` | `string` | Instrument id, e.g. `"rb2510"`. |
280
+
281
+ ```ts
282
+ md.subscribe(["rb2510"]);
283
+ // ...later, anywhere in your code — no event handler needed
284
+ const tick = md.snapshot("rb2510");
285
+ if (tick) console.log("mid", (tick.bidPrice1 + tick.askPrice1) / 2, "@", tick.updateTime);
286
+ ```
287
+
288
+ ### `md.last(instrumentId)` → `number`
289
+
290
+ The latest price for an instrument from the same C++ cache, read
291
+ **synchronously**. Returns `0` outside an authenticated cache epoch, if no tick
292
+ has been seen, or after the entry is cleared — see
293
+ [`snapshot`](#mdsnapshotinstrumentid--depthmarketdata--null).
294
+
295
+ ```ts
296
+ const px = md.last("rb2510");
297
+ if (px > 0) console.log("last traded", px);
298
+ ```
299
+
300
+ ### `md.attachArm(trader)` → `void`
301
+
302
+ Route this feed's ticks to a `Trader`'s armed triggers (see
303
+ [`Trader.arm`](#tdarmmd-spec--armhandle)). Usually you call `td.arm(md, …)`,
304
+ which calls this for you. A `MarketData` feeds exactly one **live** `Trader`'s
305
+ triggers; attaching a second live Trader throws. After the old Trader has closed,
306
+ its registry may be replaced without retaining the closed JS object.
307
+
308
+ ```ts
309
+ // explicit (rarely needed — td.arm() does this automatically):
310
+ md.attachArm(td);
311
+
312
+ // a second, different live trader throws:
313
+ md.attachArm(td); // ok
314
+ md.attachArm(otherTd); // throws: already feeds another Trader
315
+ ```
316
+
317
+ ### `md.apiVersion` / `md.tradingDay` → `string` (read-only)
318
+
319
+ The CTP API version string, and the current trading day (`YYYYMMDD`), available
320
+ after connect.
321
+
322
+ ```ts
323
+ console.log("CTP MD API", md.apiVersion); // e.g. "6.7.2"
324
+ md.on("front-connected", () => console.log("trading day", md.tradingDay));
325
+ ```
326
+
327
+ ### `md.droppedRecords` → `number` (getter)
328
+
329
+ Total ticks discarded by keep-newest backpressure. Monitor it to detect a slow
330
+ consumer.
331
+
332
+ ```ts
333
+ setInterval(() => {
334
+ if (md.droppedRecords > 0) console.warn("MD dropped", md.droppedRecords, "ticks");
335
+ }, 5000);
336
+ ```
337
+
338
+ ### `md.close()` → `void`
339
+
340
+ Release the underlying CTP API and free native resources. Idempotent. Call once,
341
+ at shutdown. See [lifecycle](#core-concepts).
342
+
343
+ ```ts
344
+ process.on("SIGINT", () => { md.close(); process.exit(0); });
345
+ ```
346
+
347
+ ### MarketData events
348
+
349
+ Subscribe with `md.on(name, handler)`. Handlers receive `(data, options)` where
350
+ `options` is a [`CallbackOptions`](#callbackoptions). Symbolic names are in the
351
+ `MarketDataEvent` enum; plain strings work too.
352
+
353
+ | Event | `data` type | Fires when |
354
+ |---|---|---|
355
+ | `front-connected` | `undefined` | Connected (first connect and every reconnect). Re-run login/subscribe here. |
356
+ | `front-disconnected` | `number` (reason code) | Connection dropped. In-flight requests reject. |
357
+ | `rsp-user-login` | `RspUserLogin` | Login response. |
358
+ | `rsp-user-logout` | `UserLogout` | Logout response. |
359
+ | `rsp-qry-multicast-instrument` | `MulticastInstrument` | One multicast-instrument query row. |
360
+ | `rsp-sub-market-data` | `SpecificInstrument` | Subscription ack. |
361
+ | `rsp-unsub-market-data` | `SpecificInstrument` | Unsubscription ack. |
362
+ | `rtn-depth-market-data` | `DepthMarketData` | A depth quote tick. |
363
+ | `rtn-for-quote` | `ForQuoteRsp` | A quote-request notification. |
364
+ | `rsp-error` | `undefined` | A CTP error response (`options.rspInfo`). |
365
+ | `error` | `unknown` | A *handler* you registered threw — see [error handling](#the-error-event). |
366
+
367
+ ```ts
368
+ import { MarketDataEvent } from "@hitrading/ctp-node";
369
+
370
+ // symbolic name
371
+ md.on(MarketDataEvent.RtnDepthMarketData, (t) => {
372
+ const mid = (t.bidPrice1 + t.askPrice1) / 2;
373
+ });
374
+
375
+ // reconnect handling
376
+ md.on("front-connected", async () => { await md.login(); md.subscribe(["rb2510"]); });
377
+ md.on("front-disconnected", (reason) => console.warn("MD disconnected, code", reason));
378
+ ```
379
+
380
+ ---
381
+
382
+ ## `Trader`
383
+
384
+ The trading (交易) client: order entry, queries, position/risk tracking, and
385
+ latency-critical armed triggers. Extends [`CtpClient`](#ctpclient); every
386
+ generated `reqXxx` request method is available (see
387
+ [request methods](#generated-request-methods)).
388
+
389
+ ### `new Trader(flowPath, fronts)`
390
+
391
+ Same parameters as [`MarketData`](#new-marketdataflowpath-fronts). The trader
392
+ remembers the credentials from the login response, so `sync*` need no arguments,
393
+ and seeds its auto-`OrderRef` counter past the broker's `maxOrderRef` so refs
394
+ never collide with a prior session.
395
+
396
+ ```ts
397
+ const td = new Trader("./flow/td/", "tcp://182.254.243.31:30002");
398
+ // failover fronts:
399
+ const td2 = new Trader("./flow/td/", ["tcp://182.254.243.31:30002", "tcp://182.254.243.31:30001"]);
400
+ ```
401
+
402
+ ### `td.session(opts)` → `Promise<{ identity, multipliers, marginRates, positions, orders }>`
403
+
404
+ One-call post-connect handshake: **authenticate → login → confirm settlement →
405
+ sync multipliers / optional margin rates / orders / positions**. Call it from the `front-connected`
406
+ handler (and again after a reconnect). Returns the request-correlated
407
+ `identity: { frontId, sessionId, maxOrderRef }` plus row counts from the sync.
408
+ Here `maxOrderRef` is the value reported by that login response; the Trader's
409
+ automatic allocator may retain a higher process-local high-water mark.
410
+ Each step just wraps the matching request/sync method, so you can
411
+ hand-roll the flow when you need finer control.
412
+
413
+ At handshake start, held-position and working-order ledgers are marked
414
+ uncertain, so all opening inserts fail closed across a possible
415
+ reconnect gap. Successful `syncPositions()` and `syncOrders()` each clear only
416
+ their own uncertainty. Disabling either sync leaves that side fail-closed until
417
+ you reconcile it later.
418
+
419
+ A newly created Trader starts in the same fail-closed state, including the small
420
+ window before its first `front-connected` callback.
421
+
422
+ `opts` is a [`SessionOptions`](#sessionoptions):
423
+
424
+ The login response must contain a concrete `frontId` / `sessionId` and the same
425
+ `brokerId` / `userId` that were requested. An empty or mismatched success
426
+ payload is rejected because those fields are part of the local reservation and
427
+ snapshot identity; reusing an old/zero session or reconciling another account
428
+ would make the ledger unsafe.
429
+
430
+ | Field | Type | Meaning |
431
+ |---|---|---|
432
+ | `brokerId` | `string` | Broker id (required). |
433
+ | `userId` | `string` | Investor id (required). |
434
+ | `password` | `string` | Password (required). |
435
+ | `appId` | `string?` | Terminal app id for authentication. SimNow: `"simnow_client_test"`. |
436
+ | `authCode` | `string?` | Terminal auth code. SimNow: 16 zeros. Omit both `appId`/`authCode` to skip authentication. |
437
+ | `confirmSettlement` | `boolean?` | Confirm the settlement statement after login (real accounts must, or orders are rejected). Default `true`. |
438
+ | `sync` | `object?` | `{ multipliers?: boolean \| string[], marginRates?: { instrumentIds: string[], hedgeFlag: "1" \| "2" \| "3" \| "5" \| "6" \| "7" }, positions?: boolean, orders?: boolean }`. Multipliers/positions/orders default on; margin rates require an explicit bounded contract list and hedge flag because CTP needs one query per contract and keeps separate schedules per hedge flag. |
439
+
440
+ ```ts
441
+ // SimNow full handshake
442
+ td.on("front-connected", async () => {
443
+ const counts = await td.session({
444
+ brokerId: "9999", userId: "id", password: "pw",
445
+ appId: "simnow_client_test", authCode: "0000000000000000",
446
+ });
447
+ console.log("synced", counts); // { identity, multipliers, marginRates, positions, orders }
448
+ });
449
+
450
+ // scope the multiplier sync to the symbols you trade (faster cold start)
451
+ await td.session({
452
+ brokerId: "9999", userId: "id", password: "pw",
453
+ sync: {
454
+ multipliers: ["rb2510", "au2508"],
455
+ marginRates: { instrumentIds: ["rb2510", "au2508"], hedgeFlag: "2" },
456
+ positions: true,
457
+ orders: true,
458
+ },
459
+ });
460
+
461
+ // skip the settlement confirm (environments that don't need it)
462
+ await td.session({ brokerId: "9999", userId: "id", password: "pw", confirmSettlement: false });
463
+ ```
464
+
465
+ > The hand-rolled equivalent: `await td.reqAuthenticate(...)` →
466
+ > `await td.reqUserLogin(...)` → `await td.reqSettlementInfoConfirm(...)` →
467
+ > `await td.syncMultipliers()` → `await td.syncMarginRates([...])` → `await td.syncOrders()` →
468
+ > `await td.syncPositions()`.
469
+
470
+ ### `td.reqOrderInsert(req?)` → `Promise<void>`
471
+
472
+ Insert an order through the C++ pre-trade risk gate. **Resolves on submission** —
473
+ CTP sends no success acknowledgement for an accepted order, only `rtn-order` /
474
+ `rtn-trade` (correlate by `orderRef`). It **rejects** only if the send is refused
475
+ (risk gate, rate limit, or a CTP API error code). A blank `orderRef` is assigned
476
+ a unique numeric value automatically.
477
+
478
+ A confirmed login is required. `brokerId` and `investorId` are filled from that
479
+ session; supplying a different value is rejected before encoding, so the local
480
+ position/order snapshots cannot be applied to an order for another account.
481
+
482
+ `req` is a `Partial<InputOrder>`; the fields you almost always set:
483
+
484
+ | Field | Type | Meaning |
485
+ |---|---|---|
486
+ | `instrumentId` | `string` | Contract, e.g. `"rb2510"`. |
487
+ | `direction` | `Direction` (`"0"`/`"1"`) | `Buy` / `Sell`. |
488
+ | `combOffsetFlag` | `string` | Exactly one offset char: `"0"` open, `"1"` close, `"3"` close-today, … Multi-leg flags are rejected. |
489
+ | `limitPrice` | `number` | Limit price; must be `> 0`. Market / any-price orders (`limitPrice: 0`) are **not** supported. |
490
+ | `volumeTotalOriginal` | `number` | Quantity in lots (positive int32). |
491
+ | `orderRef` | `string?` | Leave unset for an auto-assigned unique ref; otherwise 1–12 decimal digits. |
492
+ | `orderPriceType` | `OrderPriceType?` | Optional; if set, must be `"2"` (limit). Defaults to limit. |
493
+
494
+ > **Only single-instrument GFD, FAK and FOK limit orders are accepted.** Use `timeCondition: "3", volumeCondition: "1"` for GFD; `"1", "1"` for FAK; and `"1", "3"` for FOK. `reqOrderInsert` deliberately rejects (with a `TypeError`) anything the native risk-reservation ledger cannot represent: other time/volume-condition combinations, min-volume/conditional/stop/swap/force-close variants, and multi-leg offset/hedge flags.
495
+
496
+ ```ts
497
+ import { Direction, OffsetFlag } from "@hitrading/ctp-node";
498
+
499
+ // 1) limit buy 1 lot to open
500
+ await td.reqOrderInsert({
501
+ instrumentId: "rb2510", direction: Direction.Buy,
502
+ combOffsetFlag: OffsetFlag.Open, limitPrice: 3500, volumeTotalOriginal: 1,
503
+ });
504
+
505
+ // 2) handle a refusal (risk gate / rate limit / CTP error)
506
+ try {
507
+ await td.reqOrderInsert({ instrumentId: "rb2510", direction: "0", combOffsetFlag: "0", limitPrice: 9999, volumeTotalOriginal: 1 });
508
+ } catch (e) {
509
+ console.warn("refused:", e.message); // e.g. "blocked by pre-trade risk: order price deviates too far from reference"
510
+ }
511
+
512
+ // 3) correlate a fill by your own orderRef
513
+ await td.reqOrderInsert({ orderRef: "42001", instrumentId: "rb2510", direction: "0", combOffsetFlag: "0", limitPrice: 3500, volumeTotalOriginal: 2 });
514
+ td.on("rtn-trade", (t) => { if (t.orderRef === "42001") console.log("my order filled", t.volume); });
515
+
516
+ // 4) close-today a short position (sell -> close)
517
+ await td.reqOrderInsert({ instrumentId: "rb2510", direction: Direction.Sell, combOffsetFlag: OffsetFlag.CloseToday, limitPrice: 3490, volumeTotalOriginal: 1 });
518
+ ```
519
+
520
+ ### `td.reqOrderAction(req?)` → `Promise<void>` (cancel)
521
+
522
+ Cancel / modify a working order. Resolves on submission. A Delete action remains
523
+ available in every risk mode. A Modify action can increase exposure, so it is
524
+ treated as an unsupported mutation and is refused unless the Trader is in
525
+ `NORMAL` with every local risk control disabled. Identify the order via
526
+ `orderRef` + `frontId` + `sessionId` (from its `rtn-order`), or by
527
+ `exchangeId` + `orderSysId`.
528
+
529
+ ```ts
530
+ import { ActionFlag } from "@hitrading/ctp-node";
531
+
532
+ let working;
533
+ td.on("rtn-order", (o) => { if (o.orderStatus === "3") working = o; }); // NoTradeQueueing
534
+
535
+ // cancel it
536
+ await td.reqOrderAction({
537
+ instrumentId: working.instrumentId,
538
+ orderRef: working.orderRef, frontId: working.frontId, sessionId: working.sessionId,
539
+ actionFlag: ActionFlag.Delete, // "0"
540
+ });
541
+
542
+ // cancel by exchange order id instead
543
+ await td.reqOrderAction({
544
+ instrumentId: working.instrumentId,
545
+ exchangeId: working.exchangeId, orderSysId: working.orderSysId,
546
+ actionFlag: "0",
547
+ });
548
+ ```
549
+
550
+ ### Query methods — `td.reqQry*` / `td.reqQuery*`
551
+
552
+ Every `reqQry*` resolves with an **array of rows** (multi-row responses are
553
+ accumulated; an empty result resolves `[]`); the two single-response `reqQuery*`
554
+ methods resolve one row. CTP rate-limits queries to roughly one per second.
555
+ Every generated query shares a per-Trader scheduler with at least 1100 ms
556
+ between attempted sends, including concurrent direct calls; it keeps at most one
557
+ query in flight, so callers do not add `setTimeout(1000)`. Request data is
558
+ snapshotted when the method is called, and disconnect/login/logout transitions
559
+ reject queued work from the old context. The scheduler is per client (not
560
+ process-global) and accepts at most 256 active/queued queries. Raw queries are
561
+ paced but not retried. The
562
+ [`sync*`](#tdsyncmultipliersinstrumentids--promisenumber) helpers additionally
563
+ retry transient `-2`/`-3` flow-control failures and required empty cold-start
564
+ data.
565
+
566
+ ```ts
567
+ // current positions
568
+ const positions = await td.reqQryInvestorPosition({ brokerId: "9999", investorId: "id" });
569
+ for (const p of positions) console.log(p.instrumentId, p.posiDirection, p.position);
570
+
571
+ // account funds
572
+ const [account] = await td.reqQryTradingAccount({ brokerId: "9999", investorId: "id" });
573
+ console.log("available", account?.available);
574
+
575
+ // instrument details (multiplier, tick size, …)
576
+ const [rb] = await td.reqQryInstrument({ instrumentId: "rb2510" });
577
+ console.log("multiplier", rb?.volumeMultiple, "tick", rb?.priceTick);
578
+
579
+ // today's orders / trades
580
+ const orders = await td.reqQryOrder({ brokerId: "9999", investorId: "id" });
581
+ const trades = await td.reqQryTrade({ brokerId: "9999", investorId: "id" });
582
+ ```
583
+
584
+ See [request methods](#generated-request-methods) for the full list.
585
+
586
+ ### `td.syncMultipliers(instrumentIds?)` → `Promise<number>`
587
+
588
+ Trigger the instrument query so the C++ risk engine picks up contract multipliers
589
+ (合约乘数) — it sources them **directly** from CTP's `OnRspQryInstrument` response,
590
+ so this no longer calls a JS setter. Needed for multiplier-accurate notional and
591
+ position-margin limits. No argument queries all instruments in one request; pass a
592
+ symbol list to scope it. An explicit empty list is a no-op returning `0`; only an
593
+ omitted argument means "query all". Retries through cold-start flow control.
594
+ Returns the count of contracts whose final callback row has a usable multiplier.
595
+
596
+ Starting an instrument refresh invalidates the old multiplier before the request
597
+ is sent, so a failed/empty refresh cannot leave stale metadata active. If held
598
+ positions exist, run `syncPositions()` afterwards to refresh their authoritative
599
+ `UseMargin`; monetary opening gates remain fail-closed until then.
600
+
601
+ ```ts
602
+ const n = await td.syncMultipliers(); // all instruments
603
+ await td.syncMultipliers(["rb2510", "au2508"]); // just these
604
+ console.log(n, "contracts with a multiplier");
605
+ ```
606
+
607
+ ### `td.syncMarginRates(instrumentIds, hedgeFlag?)` → `Promise<number>`
608
+
609
+ Query investor long/short by-money/by-volume schedules for a bounded contract
610
+ universe (default hedge flag `"1"`, speculation). A second exchange-base query
611
+ is issued only for a relative row; the shared scheduler spaces every query.
612
+ Relative investor schedules are added to their exchange base. Missing metadata
613
+ fails closed.
614
+
615
+ Old investor and exchange schedules are invalidated before the refresh. Run
616
+ `syncPositions()` after refreshing schedules when the account already holds
617
+ positions; the engine will not treat margin estimated under an old schedule as
618
+ authoritative.
619
+
620
+ ### `td.syncPositions()` → `Promise<number>`
621
+
622
+ Seed open-position **margin** from CTP (`reqQryInvestorPosition`, each row's
623
+ `UseMargin`) into the risk engine's position tracker. It always uses the
624
+ confirmed login identity; account overrides are rejected. Returns the number of
625
+ positions seeded. Empty snapshots must be observed twice; applying the snapshot is an
626
+ atomic revision-checked replacement that preserves working reservations. A
627
+ realtime callback during the query causes a retry rather than a clear/reseed gap.
628
+
629
+ ```ts
630
+ const held = await td.syncPositions();
631
+ console.log("seeded", held, "positions, margin =", td.accountMargin);
632
+ ```
633
+
634
+ ### `td.syncOrders()` → `Promise<number>`
635
+
636
+ Rebuild the in-flight reservation from CTP's currently-working orders
637
+ (`reqQryOrder`) — an authoritative resync. Call after login and after any
638
+ reconnect so the position caps account for orders already working at the broker
639
+ (placed before a reconnect, or — since CTP delivers them too — from another
640
+ terminal on the same account). Run `syncMultipliers()` first so the reserved cost
641
+ uses the right multiplier and query margin schedules before monetary caps are
642
+ enabled. Conditional statuses (`a`/`b`/`c`) remain reserved. Applying the
643
+ snapshot is revision-checked against realtime callbacks. Returns the number of
644
+ working open orders re-reserved.
645
+
646
+ If the account has a working multi-leg/unsupported order (including one placed
647
+ by another terminal), its exposure cannot be represented by this single-leg
648
+ ledger. The snapshot is still committed atomically, that order is recorded as
649
+ unsupported, and the method throws. Opening inserts then fail
650
+ closed until a later successful `syncOrders()` confirms the order is gone.
651
+
652
+ `syncOrders()` deliberately marks the held-position side uncertain too. Run
653
+ `syncPositions()` **after it**; reversing the order stays fail-closed instead of
654
+ opening on two broker snapshots that have no transactional common cut.
655
+
656
+ ```ts
657
+ await td.syncMultipliers();
658
+ const working = await td.syncOrders();
659
+ await td.syncPositions();
660
+ console.log("re-reserved", working, "working open orders");
661
+ ```
662
+
663
+ ### Risk configuration
664
+
665
+ #### `td.setRiskLimits(config)` → `this`
666
+
667
+ Publish pre-trade risk limits to the C++ enforcer (takes effect at once). A
668
+ non-finite (`NaN`/`Infinity`) limit is **rejected with a throw** rather than
669
+ silently disabling the control. `config` is a [`RiskLimits`](#risklimits); omit a
670
+ field or pass `0` to disable that control; negative values are rejected. The object replaces the
671
+ whole prior configuration; `maxReferenceAgeMs` is the exception: it must be
672
+ positive and defaults to 3000 ms when omitted. Unknown fields (including removed
673
+ legacy names such as `maxMargin`) are rejected instead of being ignored.
674
+
675
+ ```ts
676
+ // full set
677
+ td.setRiskLimits({
678
+ maxOrderVolume: 10, // ≤ 10 lots per order
679
+ maxPriceDeviation: 0.02, // ≤ 2% from the reference price
680
+ maxNotional: 5_000_000, // ≤ 5M Futures/TAS notional per opening order
681
+ maxOrdersPerSec: 20, // token-bucket rate limit
682
+ orderBurst: 40, // bucket size (default: maxOrdersPerSec)
683
+ maxCloseOrdersPerSec: 10, // optional independent close-order rate
684
+ closeOrderBurst: 20,
685
+ maxAccountMargin: 20_000_000, // ≤ 20M held + reserved account margin
686
+ });
687
+
688
+ // just a couple of controls (the rest stay disabled)
689
+ td.setRiskLimits({ maxOrderVolume: 5, maxOrdersPerSec: 10 });
690
+
691
+ // disable a control by passing 0
692
+ td.setRiskLimits({ maxNotional: 0 });
693
+ ```
694
+
695
+ #### `td.reduceOnly()` / `td.haltAll()` / `td.resume()` → `this`
696
+
697
+ The atomic modes are `NORMAL`, `REDUCE_ONLY`, and `HALT_ALL`. `reduceOnly()`
698
+ blocks normal opens, every advanced mutation, and bank/futures transfers while
699
+ keeping cancellations and single-leg normal closes available. `haltAll()` also
700
+ blocks close inserts, clears all armed triggers, and rejects new `arm()` calls
701
+ until `resume()`. Mode transitions share the
702
+ final vendor-API send barrier, so no forbidden armed order can cross after the
703
+ transition returns. `resume()` restores `NORMAL`.
704
+
705
+ Advanced mutations (complex inserts, offset setting, spread/hedge confirmation)
706
+ cannot be represented by the normal reservation ledger, so they fail closed
707
+ whenever any local risk control is configured. The generator requires every
708
+ future non-query SDK request to be classified; an unreviewed method fails code
709
+ generation instead of defaulting to unguarded.
710
+
711
+ This separation is lifetime-sticky: after CTP accepts any unsupported risk
712
+ mutation in pure binding mode, later enabling a local control makes ordinary
713
+ opening orders fail closed. `syncOrders()` covers normal single-leg orders only
714
+ and therefore cannot certify that quote/exec/comb/parked exposure has gone away.
715
+ Realtime advanced-mutation and funds-transfer returns observed from another
716
+ terminal set the same sticky fail-closed marker; they are not mistaken for
717
+ ordinary-ledger state merely because this process did not originate them.
718
+ Use a Trader instance in one capability mode for its whole lifetime; do not
719
+ switch a protocol-binding session into locally managed trading after advanced
720
+ mutations have been admitted.
721
+
722
+ Bank/futures transfers are subject to the same rule. They change available
723
+ collateral but are not represented by this local ledger, so they are forwarded
724
+ only in `NORMAL` mode when every local risk control is disabled. Authentication
725
+ and transfer authorization remain the caller's responsibility.
726
+
727
+ ```ts
728
+ // stop risk increases but keep closes/cancels working
729
+ process.on("SIGINT", () => td.reduceOnly());
730
+
731
+ // stop both opens and closes (cancellations still work)
732
+ td.haltAll();
733
+
734
+ // re-enable trading once you've assessed the situation
735
+ td.resume();
736
+
737
+ // example: halt if PnL breaches a limit
738
+ td.on("rtn-trade", () => { if (computePnl() < -100000) td.reduceOnly(); });
739
+ ```
740
+
741
+ #### `td.setInstrumentPositionLimit(instrumentId, limit)` / `td.setInstrumentPositionLimits(limits)` → `this`
742
+
743
+ Cap the open position (in lots) per instrument, enforced on every opening order.
744
+ `limit` is an [`InstrumentPositionLimit`](#instrumentpositionlimit): a number caps both sides; `{ long, short }` caps
745
+ each side separately. Within `{ long, short }`, **omitting a side leaves its
746
+ current cap unchanged** (pass `0` to clear; negative values are rejected). Long and short are tracked
747
+ independently. The check counts committed = held + in-flight (working) volume.
748
+
749
+ ```ts
750
+ td.setInstrumentPositionLimit("rb2510", 100); // long ≤ 100 and short ≤ 100
751
+ td.setInstrumentPositionLimit("au2508", { long: 50, short: 10 }); // asymmetric
752
+
753
+ // raise only the long cap, leave short as it was
754
+ td.setInstrumentPositionLimit("au2508", { long: 80 });
755
+ // clear the short cap
756
+ td.setInstrumentPositionLimit("au2508", { short: 0 });
757
+
758
+ // many at once
759
+ td.setInstrumentPositionLimits({ rb2510: 100, ru2510: { long: 100, short: 20 }, au2508: 10 });
760
+ ```
761
+
762
+ #### `td.setInstrumentMarginLimit(instrumentId, limit)` / `td.setInstrumentMarginLimits(limits)` → `this`
763
+
764
+ Cap one instrument's open-position **margin** (price × volume × multiplier ×
765
+ by-money + volume × by-volume, long and short summed).
766
+ Per-instrument and independent of the account-wide
767
+ `setRiskLimits({ maxAccountMargin })`; both apply. Pass `limit = 0` to remove it; negative values are rejected. Until a
768
+ contract multiplier and usable absolute margin schedule are known (fed from CTP
769
+ callbacks after the corresponding queries), capped opening orders fail closed.
770
+ Both by-money and by-volume/per-lot components are included. `IsRelative`
771
+ schedules are added to the matching exchange schedule loaded by
772
+ `syncMarginRates()`; either half missing fails closed.
773
+
774
+ This formula is enabled only for CTP Futures/TAS product classes. Options,
775
+ combinations and spot products require product-specific margin models and fail
776
+ closed while a monetary cap is active.
777
+
778
+ `maxNotional` uses the same Futures/TAS allowlist. Option premium and combination
779
+ price are not treated as futures notional; unknown/unsupported product metadata
780
+ fails closed when the notional guard is enabled.
781
+
782
+ Notional and working-order margin are valued at the greater of the order price
783
+ and a fresh market reference. This prevents a low sell/open limit from
784
+ understating exposure. Attach market data with `trackMarketData()`; missing or
785
+ older-than-`maxReferenceAgeMs` quotes make every enabled monetary gate fail
786
+ closed. Existing working orders are revalued before each monetary admission.
787
+
788
+ ```ts
789
+ td.setInstrumentMarginLimit("au2508", 5_000_000); // ≤ 5M of gold margin
790
+ td.setInstrumentMarginLimits({ ag2508: 2_000_000, au2508: 5_000_000 });
791
+ td.setInstrumentMarginLimit("au2508", 0); // remove the cap
792
+ ```
793
+
794
+ #### `td.trackMarketData(md)` → `this`
795
+
796
+ Provide the live reference price used by price deviation, notional and
797
+ working-order margin checks.
798
+ Wires the `MarketData` feed's C++ snapshot cache straight into this Trader's risk
799
+ engine, so the deviation reference is read **in C++ on the order-send path** — no
800
+ JS round-trip, and it covers armed orders that fire from C++ with no JS in the
801
+ loop. Without a reference, or when its age exceeds `maxReferenceAgeMs` (default
802
+ 3000 ms), every enabled deviation or monetary check fails closed for opening
803
+ orders.
804
+
805
+ ```ts
806
+ td.setRiskLimits({ maxPriceDeviation: 0.02 });
807
+
808
+ // live reference from the feed (read in C++ on every order, incl. armed orders)
809
+ td.trackMarketData(md);
810
+ ```
811
+
812
+ > Contract multipliers (for notional / cost accounting) and per-contract margin
813
+ > rates (for the `maxAccountMargin` cap) are **not** fed from JS: the C++ risk engine
814
+ > sources them directly from CTP's `OnRspQryInstrument` /
815
+ > `OnRspQryInstrumentMarginRate` callbacks. So any `reqQryInstrument` keeps
816
+ > multipliers current (see [`syncMultipliers`](#tdsyncmultipliersinstrumentids--promisenumber)),
817
+ > Prefer `syncMarginRates()` for every contract/hedge flag you trade: it queries
818
+ > both investor and exchange schedules, includes both formula components, and
819
+ > combines `IsRelative` correctly. Missing metadata is never guessed.
820
+
821
+ ### Position-margin tracking
822
+
823
+ #### `td.seedPositions(positions)` → `this`
824
+
825
+ Atomically replace held positions from a **complete** manually reconciled
826
+ snapshot. Each row is `{ instrumentId, side, hedgeFlag, volume, margin }`, where
827
+ `margin` is the actual capital occupied (`InvestorPosition.UseMargin`). An empty
828
+ array is an authoritative flat book. The removed singular `seedPosition()` is
829
+ intentionally not retained: several incremental JS calls would expose a partial
830
+ book to native armed orders between calls.
831
+
832
+ ```ts
833
+ td.seedPositions([
834
+ { instrumentId: "rb2510", side: "long", hedgeFlag: "1", volume: 3, margin: 30_000 },
835
+ { instrumentId: "au2508", side: "short", hedgeFlag: "1", volume: 2, margin: 112_000 },
836
+ ]);
837
+ ```
838
+
839
+ #### `td.seedFromPositions(positions)` → `this`
840
+
841
+ Atomically replace held open-position **margin** from a complete set of
842
+ `reqQryInvestorPosition` rows (each row's `UseMargin`) for **gross-mode**
843
+ accounts (`posiDirection` `"2"` = long, `"3"` = short), retaining each
844
+ supported `HedgeFlag` as a separate cost bucket. Net/unknown directions or
845
+ hedge flags are rejected because guessing would corrupt per-side volume or
846
+ margin accounting; convert those rows explicitly and submit one complete
847
+ `seedPositions()` snapshot.
848
+
849
+ ```ts
850
+ const rows = await td.reqQryInvestorPosition({ brokerId: "9999", investorId: "id" });
851
+ td.seedFromPositions(rows); // complete held snapshot; working reservations remain
852
+ ```
853
+
854
+ #### `td.accountMargin` → `number` (read-only)
855
+
856
+ Current held-position margin tracked by the risk engine. It deliberately excludes
857
+ working-order reservations, although `maxAccountMargin` admits against
858
+ **held + reserved** margin. This property is best-effort observability: when
859
+ metadata is missing or refreshed it may not be an exact admission value; an
860
+ enabled monetary gate still fails closed until an authoritative position sync.
861
+
862
+ ```ts
863
+ console.log("book margin", td.accountMargin);
864
+ td.on("rtn-trade", () => console.log("margin now", td.accountMargin));
865
+ ```
866
+
867
+ #### `td.resetPositions()` → `this`
868
+
869
+ Clear held position margin only. Working-order reservations are deliberately
870
+ preserved. A reset is not proof that the account is flat, so opening inserts
871
+ remain fail-closed until `seedFromPositions()` or `syncPositions()` completes an
872
+ authoritative revision-checked replacement.
873
+
874
+ ```ts
875
+ td.resetPositions(); // clear held rows, keep reservations; block opens
876
+ td.seedFromPositions(freshRows); // atomic complete replacement; reopen the ledger
877
+ ```
878
+
879
+ ### Latency-critical armed triggers
880
+
881
+ #### `td.arm(md, spec)` → `ArmHandle`
882
+
883
+ Arm a trigger evaluated and fired entirely in C++ on the market-data callback
884
+ thread — when `md` sees the condition, the order is sent through this Trader's
885
+ risk gate with **no JS round trip**. It is removed after a successful submission;
886
+ a halt/rate/metadata/send refusal leaves it armed with exponential retry
887
+ backoff (100 ms initially, capped at 5 seconds).
888
+ `haltAll()` is the hard-stop exception: it closes the final send barrier and
889
+ clears every existing arm, so `resume()` cannot fire a historical trigger.
890
+ Front connect/disconnect events and every Trader login/logout request also
891
+ clear all arms: a mandate never crosses an authenticated session boundary.
892
+ Recreate the required triggers only after `session()` has reconciled the new
893
+ session.
894
+ The acknowledgement arrives via the normal `rtn-order` / `rsp-order-insert`
895
+ events (correlate by `orderRef`).
896
+
897
+ The supplied `md` is also attached automatically as this Trader's fresh-price
898
+ source for deviation, notional and working-margin checks.
899
+
900
+ `spec` is an [`ArmSpec`](#armspec): `{ instrumentId, side, triggerPrice, order }`.
901
+ A **buy** fires when `ask ≤ triggerPrice`; a **sell** when `bid ≥ triggerPrice`.
902
+ The `order` is a full `Partial<InputOrder>` and is validated up front (it must
903
+ have `instrumentId`, `direction`, `combOffsetFlag` and
904
+ `volumeTotalOriginal > 0`).
905
+
906
+ Returns an [`ArmHandle`](#armhandle) — call `handle.disarm()` to remove it.
907
+
908
+ ```ts
909
+ import { Direction, OffsetFlag } from "@hitrading/ctp-node";
910
+
911
+ // stop-loss: sell rb2510 the instant the bid reaches 3450
912
+ const stop = td.arm(md, {
913
+ instrumentId: "rb2510",
914
+ side: "sell",
915
+ triggerPrice: 3450,
916
+ order: {
917
+ instrumentId: "rb2510", direction: Direction.Sell,
918
+ combOffsetFlag: OffsetFlag.CloseToday, limitPrice: 3445, volumeTotalOriginal: 1,
919
+ },
920
+ });
921
+
922
+ // breakout entry: buy when the ask reaches 3600
923
+ const entry = td.arm(md, {
924
+ instrumentId: "rb2510", side: "buy", triggerPrice: 3600,
925
+ order: { instrumentId: "rb2510", direction: "0", combOffsetFlag: "0", limitPrice: 3605, volumeTotalOriginal: 2 },
926
+ });
927
+
928
+ // cancel a trigger that hasn't fired
929
+ stop.disarm();
930
+ ```
931
+
932
+ #### `td.armStats` → `{ fired: number; blocked: number }` (read-only)
933
+
934
+ Observability for armed triggers (they fire in C++ with no JS in the loop):
935
+ how many fired and were sent (`fired`) vs were refused by the risk gate / send
936
+ (`blocked`). Poll this after a trigger you expected to fire — a blocked armed
937
+ order is otherwise invisible.
938
+
939
+ ```ts
940
+ const { fired, blocked } = td.armStats;
941
+ console.log(`armed: ${fired} sent, ${blocked} refused`);
942
+ if (blocked > 0) console.warn("an armed order was refused by risk");
943
+ ```
944
+
945
+ ### `td.apiVersion` / `td.tradingDay` → `string` (read-only)
946
+
947
+ The CTP trader API version and current trading day.
948
+
949
+ ```ts
950
+ console.log("CTP TD API", td.apiVersion, "day", td.tradingDay);
951
+ ```
952
+
953
+ ### `td.close()` / `td.droppedRecords`
954
+
955
+ As on [`CtpClient`](#ctpclient). The Trader uses an ordered lossless overflow
956
+ queue after its fixed ring fills; order/trade/query callbacks are not discarded.
957
+
958
+ ```ts
959
+ console.log("trader dropped (should stay 0):", td.droppedRecords);
960
+ process.on("SIGINT", () => td.close());
961
+ ```
962
+
963
+ ### Trader events
964
+
965
+ | Event | `data` type | Fires when |
966
+ |---|---|---|
967
+ | `front-connected` | `undefined` | Connected (first connect and every reconnect). Run `session()` here. |
968
+ | `front-disconnected` | `number` | Connection dropped. In-flight requests reject. |
969
+ | `rsp-user-login` | `RspUserLogin` | Login response. |
970
+ | `rtn-order` | `Order` | Order status update (accepted, queueing, filled, cancelled, …). |
971
+ | `rtn-trade` | `Trade` | A fill. |
972
+ | `err-rtn-order-insert` | `InputOrder` | An order insert was rejected by the exchange (`options.rspInfo`). |
973
+ | `error` | `unknown` | A *handler* you registered threw — see below. |
974
+
975
+ Plus an `rsp-*` event for every request method (e.g. `rsp-qry-investor-position`),
976
+ though you'll usually consume those via the request Promise.
977
+
978
+ ```ts
979
+ td.on("rtn-order", (o, opts) => {
980
+ console.log(o.instrumentId, "status", o.orderStatus, "ref", o.orderRef);
981
+ });
982
+ td.on("rtn-trade", (t) => console.log("FILL", t.instrumentId, t.price, "x", t.volume));
983
+ td.on("err-rtn-order-insert", (input, opts) => {
984
+ console.error("exchange rejected", input.orderRef, opts.rspInfo?.errorMsg);
985
+ });
986
+ ```
987
+
988
+ ---
989
+
990
+ ## `CtpClient`
991
+
992
+ The shared base of `MarketData` and `Trader`. You don't construct it directly,
993
+ but its members are available on both clients.
994
+
995
+ ### `client.on(event, handler)` → `this`
996
+
997
+ Register an event handler (standard `EventEmitter`). Handlers receive
998
+ `(data, options)`; `options` is a [`CallbackOptions`](#callbackoptions). All event
999
+ names are plain strings (the typed overloads on each subclass list the common
1000
+ ones); unknown native events surface as `event:<id>`.
1001
+
1002
+ ```ts
1003
+ md.on("rtn-depth-market-data", (tick, options) => {
1004
+ if (options.rspInfo) console.error("error record", options.rspInfo.errorMsg);
1005
+ else console.log(tick.lastPrice);
1006
+ });
1007
+
1008
+ // one-shot with .once, remove with .off — it's a normal EventEmitter
1009
+ td.once("front-connected", () => console.log("connected for the first time"));
1010
+ ```
1011
+
1012
+ ### `client.droppedRecords` → `number` (getter)
1013
+
1014
+ Total records dropped under backpressure since construction. A steadily climbing
1015
+ value means the market-data consumer can't keep up. Market data drops oldest;
1016
+ Trader callbacks spill losslessly and therefore keep this counter at zero.
1017
+
1018
+ ```ts
1019
+ setInterval(() => console.log("dropped:", md.droppedRecords, td.droppedRecords), 10_000);
1020
+ ```
1021
+
1022
+ ### `client.close()` → `void`
1023
+
1024
+ Release the underlying CTP API and free native resources (the decode ring, SPI,
1025
+ background threads). Idempotent. In-flight request Promises reject with
1026
+ `"client closed"`. Call once, at shutdown.
1027
+
1028
+ ```ts
1029
+ async function shutdown() { td.close(); md.close(); }
1030
+ process.on("SIGTERM", shutdown);
1031
+ ```
1032
+
1033
+ ### The `error` event
1034
+
1035
+ A throw inside one of *your* event handlers can't be allowed to wedge the data
1036
+ plane, so it is caught and re-surfaced asynchronously:
1037
+
1038
+ - if you subscribe to `error`, the exception is delivered there (catchable);
1039
+ - otherwise it is re-thrown on the next tick as an `uncaughtException` — the
1040
+ normal fate of a throwing `EventEmitter` listener, just deferred so the feed
1041
+ stays consistent.
1042
+
1043
+ Either way the ring keeps advancing — a buggy handler never re-delivers or stalls
1044
+ records.
1045
+
1046
+ ```ts
1047
+ md.on("error", (err) => console.error("a market-data handler threw:", err));
1048
+ td.on("error", (err) => console.error("a trader handler threw:", err));
1049
+ ```
1050
+
1051
+ ### Generated request methods
1052
+
1053
+ Every CTP request maps to a camelCase method on `Trader` taking a
1054
+ `Partial<…Field>` and returning a Promise:
1055
+
1056
+ - **`reqQry*`** (queries) → `Promise<unknown[]>` (array of rows; `[]` if empty),
1057
+ serialized through the shared query scheduler.
1058
+ - **Exchange-bound inserts/actions** (`reqOrderInsert`, `reqOrderAction`,
1059
+ `reqExecOrderInsert`, `reqQuoteInsert`, `reqForQuoteInsert`,
1060
+ `reqOptionSelfCloseInsert`, `reqCombActionInsert`, and their `*Action`
1061
+ cancels) → `Promise<void>`, resolving on **submission** (CTP returns no success
1062
+ response; outcomes arrive via `rtn-*` events). They reject if the send is
1063
+ refused.
1064
+ - **All other requests** → `Promise<...>` resolving with the single `OnRsp*`
1065
+ response row.
1066
+
1067
+ ```ts
1068
+ // authenticate / login / confirm manually (what session() automates)
1069
+ await td.reqAuthenticate({ brokerId: "9999", userId: "id", appId: "simnow_client_test", authCode: "0000000000000000" });
1070
+ await td.reqUserLogin({ brokerId: "9999", userId: "id", password: "pw" });
1071
+ await td.reqSettlementInfoConfirm({ brokerId: "9999", investorId: "id" });
1072
+
1073
+ // the settlement statement text
1074
+ const [info] = await td.reqQrySettlementInfo({ brokerId: "9999", investorId: "id" });
1075
+ ```
1076
+
1077
+ Common ones: `reqAuthenticate`, `reqUserLogin`, `reqUserLogout`,
1078
+ `reqSettlementInfoConfirm`, `reqQrySettlementInfo`, `reqQryInstrument`,
1079
+ `reqQryInvestorPosition`, `reqQryInvestorPositionDetail`, `reqQryTradingAccount`,
1080
+ `reqQryOrder`, `reqQryTrade`, `reqOrderInsert`, `reqOrderAction`. (The full set
1081
+ is generated from the CTP headers — 125 request methods.)
1082
+
1083
+ ---
1084
+
1085
+ ## Types
1086
+
1087
+ ### `RiskLimits`
1088
+
1089
+ Pre-trade risk limits for [`setRiskLimits`](#tdsetrisklimitsconfig--this). All fields
1090
+ are optional; **omit or `0` = disabled** for controls. `maxReferenceAgeMs` must
1091
+ be positive and defaults to 3000 ms. `NaN`/`Infinity` throws.
1092
+
1093
+ | Field | Type | Meaning |
1094
+ |---|---|---|
1095
+ | `maxOrderVolume` | `number` | Max lots per single order. |
1096
+ | `maxPriceDeviation` | `number` | Max `\|price − reference\| / reference` ratio (e.g. `0.02` = 2%); missing/stale reference fails closed. |
1097
+ | `maxReferenceAgeMs` | `number` | Maximum quote age for deviation and monetary valuation; default 3000 ms. |
1098
+ | `maxNotional` | `number` | Max notional (`max(order price, fresh reference) × volume × multiplier`) per order; missing/stale reference fails closed. |
1099
+ | `maxOrdersPerSec` | `number` | Max opening-order sends per second (token bucket). |
1100
+ | `orderBurst` | `number` | Token-bucket burst size. Default: `maxOrdersPerSec`. |
1101
+ | `maxCloseOrdersPerSec` | `number` | Independent close-order send rate; disabled by default. |
1102
+ | `closeOrderBurst` | `number` | Close-order bucket size. Default: `maxCloseOrdersPerSec`. |
1103
+ | `maxAccountMargin` | `number` | Cap on total held + reserved account margin. Requires a fresh reference, multiplier and investor schedule; includes by-money/by-volume and combines relative schedules with the exchange base. Missing/stale inputs fail closed. |
1104
+
1105
+ ```ts
1106
+ const conservative: RiskLimits = { maxOrderVolume: 5, maxOrdersPerSec: 10, maxNotional: 2_000_000 };
1107
+ td.setRiskLimits(conservative);
1108
+ ```
1109
+
1110
+ ### `InstrumentPositionLimit`
1111
+
1112
+ `number | { long?: number; short?: number }` — the limit argument to
1113
+ [`setInstrumentPositionLimit`](#tdsetinstrumentpositionlimitinstrumentid-limit--tdsetinstrumentpositionlimitslimits--this).
1114
+ A number caps both sides; `{ long, short }` caps each (omit a side = unchanged,
1115
+ `0` = clear; negative values are rejected).
1116
+
1117
+ ```ts
1118
+ const a: InstrumentPositionLimit = 100; // both sides ≤ 100
1119
+ const b: InstrumentPositionLimit = { long: 50, short: 5 }; // long ≤ 50, short ≤ 5
1120
+ ```
1121
+
1122
+ ### `SessionOptions`
1123
+
1124
+ Options for [`session`](#tdsessionopts--promise-identity-multipliers-marginrates-positions-orders-).
1125
+ See the table there.
1126
+
1127
+ ```ts
1128
+ const opts: SessionOptions = {
1129
+ brokerId: "9999", userId: "id", password: "pw",
1130
+ appId: "simnow_client_test", authCode: "0000000000000000",
1131
+ confirmSettlement: true,
1132
+ sync: { multipliers: ["rb2510"], positions: true, orders: true },
1133
+ };
1134
+ ```
1135
+
1136
+ ### `ArmSpec`
1137
+
1138
+ ```ts
1139
+ interface ArmSpec {
1140
+ instrumentId: string; // contract the trigger watches
1141
+ side: "buy" | "sell"; // buy: fires when ask ≤ trigger; sell: when bid ≥ trigger
1142
+ triggerPrice: number; // must be > 0
1143
+ order: Partial<InputOrder>; // the order to send (needs instrumentId, direction,
1144
+ // combOffsetFlag, volumeTotalOriginal > 0)
1145
+ }
1146
+ ```
1147
+
1148
+ ```ts
1149
+ const spec: ArmSpec = {
1150
+ instrumentId: "rb2510", side: "sell", triggerPrice: 3450,
1151
+ order: { instrumentId: "rb2510", direction: "1", combOffsetFlag: "3", limitPrice: 3445, volumeTotalOriginal: 1 },
1152
+ };
1153
+ const handle = td.arm(md, spec);
1154
+ ```
1155
+
1156
+ ### `ArmHandle`
1157
+
1158
+ ```ts
1159
+ interface ArmHandle {
1160
+ readonly id: number;
1161
+ disarm(): boolean; // remove the trigger; false if it was already gone/fired
1162
+ }
1163
+ ```
1164
+
1165
+ ```ts
1166
+ const handle = td.arm(md, spec);
1167
+ console.log("armed id", handle.id);
1168
+ if (!handle.disarm()) console.log("it had already fired");
1169
+ ```
1170
+
1171
+ ### `CallbackOptions`
1172
+
1173
+ The second argument to every event handler:
1174
+
1175
+ ```ts
1176
+ interface CallbackOptions {
1177
+ requestId?: number; // the request this response correlates to (responses only)
1178
+ isLast?: boolean; // last row of a multi-row response (responses only)
1179
+ rspInfo?: RspInfo; // present when the record carries a CTP error
1180
+ }
1181
+ ```
1182
+
1183
+ ```ts
1184
+ td.on("rsp-qry-investor-position", (row, options) => {
1185
+ if (options.rspInfo) return console.error(options.rspInfo.errorMsg);
1186
+ collect(row);
1187
+ if (options.isLast) finish(); // final row of the multi-row response
1188
+ });
1189
+ ```
1190
+
1191
+ ### `RspInfo`
1192
+
1193
+ ```ts
1194
+ interface RspInfo {
1195
+ errorId: number; // 0 = success
1196
+ errorMsg: string; // human-readable (GB18030-decoded)
1197
+ }
1198
+ ```
1199
+
1200
+ A rejected request Promise's error carries these fields too
1201
+ (`err.errorId` / `err.errorMsg`):
1202
+
1203
+ ```ts
1204
+ try { await td.reqUserLogin({ brokerId: "9999", userId: "id", password: "bad" }); }
1205
+ catch (e) { console.error(`CTP ${e.errorId}: ${e.errorMsg}`); }
1206
+ ```
1207
+
1208
+ ### `MdLoginReq`
1209
+
1210
+ ```ts
1211
+ interface MdLoginReq {
1212
+ brokerId?: string; userId?: string; password?: string;
1213
+ tradingDay?: string; userProductInfo?: string;
1214
+ }
1215
+ ```
1216
+
1217
+ ```ts
1218
+ const req: MdLoginReq = { brokerId: "9999", userId: "id", password: "pw" };
1219
+ await md.login(req);
1220
+ ```
1221
+
1222
+ ---
1223
+
1224
+ ## Enums & struct types
1225
+
1226
+ All CTP enums (values) and struct interfaces (types) are generated from the CTP
1227
+ headers and re-exported from the package root.
1228
+
1229
+ **Enums** are string-valued and usable both as the enum member and the raw code:
1230
+
1231
+ ```ts
1232
+ import { Direction, OffsetFlag, OrderStatus, OrderPriceType, ActionFlag } from "@hitrading/ctp-node";
1233
+
1234
+ Direction.Buy; // "0"
1235
+ Direction.Sell; // "1"
1236
+ OffsetFlag.Open; // "0"
1237
+ OffsetFlag.CloseToday; // "3"
1238
+ OrderStatus.AllTraded; // "0"
1239
+ ActionFlag.Delete; // "0"
1240
+
1241
+ // both forms type-check on a struct field:
1242
+ const a = { direction: Direction.Buy };
1243
+ const b = { direction: "0" } as const;
1244
+ ```
1245
+
1246
+ **Struct types** describe the shape of event payloads and request fields — e.g.
1247
+ `DepthMarketData` (a tick), `Order`, `Trade`, `InputOrder`,
1248
+ `InvestorPosition`, `RspUserLogin`. Import them as types:
1249
+
1250
+ ```ts
1251
+ import type { DepthMarketData, Order, Trade, InputOrder } from "@hitrading/ctp-node";
1252
+
1253
+ md.on("rtn-depth-market-data", (tick: DepthMarketData) => {
1254
+ const mid = (tick.bidPrice1 + tick.askPrice1) / 2;
1255
+ });
1256
+
1257
+ function buildOrder(): Partial<InputOrder> {
1258
+ return { instrumentId: "rb2510", direction: "0", combOffsetFlag: "0", limitPrice: 3500, volumeTotalOriginal: 1 };
1259
+ }
1260
+ ```
1261
+
1262
+ > Field names are camelCase versions of the CTP fields (`LastPrice` →
1263
+ > `lastPrice`, `BidPrice1` → `bidPrice1`). CTP fills unset numeric price fields
1264
+ > with a sentinel (`Number.MAX_VALUE`); guard for it if you read a price that may
1265
+ > not have traded yet (the risk engine already does).
1266
+
1267
+ ---
1268
+
1269
+ ## Risk controls at a glance
1270
+
1271
+ | Control | Set via | Scope | Disabled when |
1272
+ |---|---|---|---|
1273
+ | Risk mode | `reduceOnly()` / `haltAll()` / `resume()` | Opens, or all order inserts; `haltAll()` also clears arms | `resume()` |
1274
+ | Max order volume | `setRiskLimits({ maxOrderVolume })` | Per order | `0` / omitted |
1275
+ | Max price deviation | `setRiskLimits({ maxPriceDeviation })` + reference | Per order | `0` / omitted (missing reference blocks) |
1276
+ | Max notional | `setRiskLimits({ maxNotional })` | Per order | `0` / omitted |
1277
+ | Open rate | `setRiskLimits({ maxOrdersPerSec, orderBurst })` | Per second | `0` / omitted |
1278
+ | Close rate | `setRiskLimits({ maxCloseOrdersPerSec, closeOrderBurst })` | Per second | `0` / omitted |
1279
+ | Max position lots | `setInstrumentPositionLimit(id, …)` | Per instrument, per side | `0` |
1280
+ | Max position margin (per instrument) | `setInstrumentMarginLimit(id, …)` | Per instrument | `0` |
1281
+ | Max position margin (account) | `setRiskLimits({ maxAccountMargin })` | Account | `0` / omitted |
1282
+
1283
+ Position-lot and position-margin caps count **committed = held (filled) +
1284
+ in-flight (working order) volume**, so a burst of opens can't slip past a cap
1285
+ before the fills report. Feed held positions via `syncPositions()` /
1286
+ `seedPositions()` and working orders via `syncOrders()` (especially after a
1287
+ reconnect). Query contract multipliers and both investor/exchange margin schedules before
1288
+ enabling monetary caps; missing metadata blocks capped opens. All caps
1289
+ are enforced in C++ on the send path; a breach
1290
+ makes `reqOrderInsert()` reject with the reason in the message.
1291
+
1292
+ ---
1293
+
1294
+ ## Recipes
1295
+
1296
+ End-to-end patterns that stitch the individual calls above into something
1297
+ runnable.
1298
+
1299
+ ### A complete strategy skeleton
1300
+
1301
+ A minimal but production-shaped skeleton: risk first, handshake on connect,
1302
+ positions tracked from fills (the source of truth), graceful shutdown. Drop your
1303
+ own logic into `signal()`.
1304
+
1305
+ ```ts
1306
+ import {
1307
+ MarketData, Trader, Direction, OffsetFlag, type DepthMarketData, type Trade,
1308
+ } from "@hitrading/ctp-node";
1309
+
1310
+ const CREDS = {
1311
+ brokerId: "9999", userId: "your-id", password: "your-pw",
1312
+ appId: "simnow_client_test", authCode: "0000000000000000",
1313
+ };
1314
+ const SYMBOL = "rb2510";
1315
+
1316
+ const md = new MarketData("./flow/md/", "tcp://182.254.243.31:30012");
1317
+ const td = new Trader("./flow/td/", "tcp://182.254.243.31:30002");
1318
+
1319
+ // 1) Configure risk BEFORE any order can be sent (enforced in C++).
1320
+ td.setRiskLimits({ maxOrderVolume: 5, maxNotional: 2_000_000, maxOrdersPerSec: 10, maxPriceDeviation: 0.02, maxAccountMargin: 5_000_000 });
1321
+ td.setInstrumentPositionLimit(SYMBOL, { long: 10, short: 10 });
1322
+ td.trackMarketData(md); // fresh reference for deviation + monetary gates
1323
+
1324
+ // 2) Never let a buggy handler wedge the feed — log handler throws.
1325
+ md.on("error", (e) => console.error("[md handler]", e));
1326
+ td.on("error", (e) => console.error("[td handler]", e));
1327
+
1328
+ // 3) Handshake on connect AND every reconnect (CTP reconnects on its own).
1329
+ td.on("front-connected", async () => {
1330
+ try { await td.session({ ...CREDS }); console.log("trader ready"); }
1331
+ catch (e: any) { console.error("session failed", e.errorId, e.errorMsg); }
1332
+ });
1333
+ md.on("front-connected", async () => {
1334
+ await md.login(); // SimNow MD front accepts anonymous login
1335
+ md.subscribe([SYMBOL]);
1336
+ });
1337
+
1338
+ // 4) Position is derived from FILLS, never assumed from sends.
1339
+ let position = 0; // net lots (+long / -short)
1340
+ td.on("rtn-trade", (t: Trade) => {
1341
+ position += t.direction === Direction.Buy ? t.volume : -t.volume;
1342
+ console.log("fill", t.price, "x", t.volume, "-> net position", position);
1343
+ });
1344
+
1345
+ // 5) The strategy: turn each tick into a target and trade the difference.
1346
+ md.on("rtn-depth-market-data", async (tick: DepthMarketData) => {
1347
+ if (tick.instrumentId !== SYMBOL) return;
1348
+ const want = signal(tick); // your logic: target net lots, e.g. -1 / 0 / +1
1349
+ const delta = want - position;
1350
+ if (delta === 0) return;
1351
+ const buy = delta > 0;
1352
+ await td.reqOrderInsert({
1353
+ instrumentId: SYMBOL,
1354
+ direction: buy ? Direction.Buy : Direction.Sell,
1355
+ // open if we're growing the position, close if we're shrinking it
1356
+ combOffsetFlag: Math.sign(want) === Math.sign(position) || position === 0 ? OffsetFlag.Open : OffsetFlag.CloseToday,
1357
+ limitPrice: buy ? tick.askPrice1 : tick.bidPrice1, // cross the spread to fill
1358
+ volumeTotalOriginal: Math.abs(delta),
1359
+ }).catch((e) => console.warn("order refused:", e.message));
1360
+ });
1361
+
1362
+ function signal(_tick: DepthMarketData): number { return 0; /* TODO your alpha */ }
1363
+
1364
+ // 6) Graceful shutdown — halt, then close ONCE.
1365
+ for (const sig of ["SIGINT", "SIGTERM"] as const) {
1366
+ process.on(sig, () => { td.haltAll(); td.close(); md.close(); process.exit(0); });
1367
+ }
1368
+ ```
1369
+
1370
+ ### Robust reconnect handling
1371
+
1372
+ CTP reconnects on its own; you re-run the handshake **in place** on every
1373
+ `front-connected` — never `new Trader()` to reconnect (the vendor DLL deadlocks;
1374
+ see [native-hooks.md](native-hooks.md#process-lifecycle-create-once-reuse)).
1375
+
1376
+ ```ts
1377
+ td.on("front-connected", async () => {
1378
+ // session() re-authenticates, re-logs-in, re-confirms, and crucially re-syncs
1379
+ // multipliers/positions/orders — so the risk engine's position caps are rebuilt
1380
+ // to include orders that were working before the drop (and any from another
1381
+ // terminal on the same account). Then re-arm whatever you need.
1382
+ await td.session({ ...CREDS });
1383
+ rearmTriggers();
1384
+ });
1385
+
1386
+ td.on("front-disconnected", (reason) => {
1387
+ console.warn("trader link down (code", reason, ") — CTP will auto-reconnect");
1388
+ // pending request Promises have already rejected; pause new signals until
1389
+ // the next front-connected if your strategy needs a confirmed session.
1390
+ });
1391
+
1392
+ function rearmTriggers() { /* re-create any td.arm(...) triggers here */ }
1393
+ ```
1394
+
1395
+ If you prefer to hand-roll instead of `session()`, the key is to **re-sync orders
1396
+ after a reconnect** so in-flight reservations are rebuilt:
1397
+
1398
+ ```ts
1399
+ td.on("front-connected", async () => {
1400
+ await td.reqUserLogin({ ...CREDS });
1401
+ await td.syncMultipliers(); // before syncOrders, so reserved cost uses the right multiplier
1402
+ await td.syncOrders(); // rebuild reservations; marks positions uncertain
1403
+ await td.syncPositions(); // final held snapshot; preserve reservations
1404
+ });
1405
+ ```
1406
+
1407
+ ### Combination & multi-leg orders
1408
+
1409
+ **Close-today vs close-yesterday.** SHFE/INE distinguish them, so `"close"` isn't
1410
+ enough — pick `CloseToday` (`"3"`) or `CloseYesterday` (`"4"`). To flatten 5 long
1411
+ lots that are 2 opened today + 3 from prior days, send two orders:
1412
+
1413
+ ```ts
1414
+ import { Direction, OffsetFlag } from "@hitrading/ctp-node";
1415
+
1416
+ await td.reqOrderInsert({ instrumentId: "rb2510", direction: Direction.Sell, combOffsetFlag: OffsetFlag.CloseToday, limitPrice: px, volumeTotalOriginal: 2 });
1417
+ await td.reqOrderInsert({ instrumentId: "rb2510", direction: Direction.Sell, combOffsetFlag: OffsetFlag.CloseYesterday, limitPrice: px, volumeTotalOriginal: 3 });
1418
+ ```
1419
+
1420
+ **Multi-leg offset flags are deliberately unsupported.** The local ledger is a
1421
+ single-instrument/single-side ledger and cannot prove per-leg position or margin
1422
+ for values such as `"00"`, `"30"`, or `"03"`. `reqOrderInsert()` and `arm()`
1423
+ therefore require exactly one offset character and reject multi-leg templates
1424
+ before they reach CTP. Use a higher-level gateway with a per-leg ledger if your
1425
+ strategy needs exchange combination instruments.
1426
+
1427
+ Realtime callbacks and `syncOrders()` also detect unsupported working orders
1428
+ placed elsewhere; while any remain, opening inserts fail
1429
+ closed instead of guessing their per-leg exposure.
1430
+
1431
+ **Building/dissolving a combined position** (where the exchange supports it) goes
1432
+ through `reqCombActionInsert` with an `InputCombAction`:
1433
+
1434
+ ```ts
1435
+ await td.reqCombActionInsert({
1436
+ brokerId: "9999", investorId: "your-id",
1437
+ instrumentId: "SPC m2509&m2601", // the combination instrument
1438
+ combDirection: "0", // 0 = build the combination, 1 = split it
1439
+ volume: 1,
1440
+ // ...remaining InputCombAction fields per your exchange
1441
+ });
1442
+ ```
1443
+
1444
+ > `reqCombActionInsert` is also refused whenever local risk is configured or the
1445
+ > mode is not `NORMAL`; it is outside this binding's quantitative-risk allowlist.