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