@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.
- package/CHANGELOG.md +82 -0
- package/README.md +54 -32
- package/README.zh-CN.md +44 -27
- package/RELEASING.md +78 -0
- package/dist/client.d.ts +36 -15
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +234 -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 +1909 -417
- 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 +41 -24
- package/dist/market-data.d.ts.map +1 -1
- package/dist/market-data.js +148 -29
- package/dist/market-data.js.map +1 -1
- package/dist/native-binding.d.ts.map +1 -1
- package/dist/native-binding.js +4 -0
- package/dist/native-binding.js.map +1 -1
- package/dist/trader.d.ts +136 -79
- package/dist/trader.d.ts.map +1 -1
- package/dist/trader.js +807 -182
- 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 +1445 -0
- package/docs/API.zh-CN.md +1285 -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 +12 -4
- 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 +255 -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 +129 -15
- package/src/generated/traderspi.gen.h +4 -2
- package/src/index.ts +11 -1
- package/src/market-data.ts +199 -46
- 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 +582 -69
- package/src/native/mdspi.cc +219 -16
- package/src/native/mdspi.h +59 -10
- package/src/native/order_capability.h +78 -0
- package/src/native/risk.cc +2030 -213
- package/src/native/risk.h +431 -78
- package/src/native/shared_handle.h +37 -0
- package/src/native/snapshot.h +75 -16
- package/src/native/traderapi.cc +769 -124
- package/src/native-binding.ts +4 -0
- package/src/trader.ts +1038 -207
- package/src/validation.ts +96 -0
package/src/trader.ts
CHANGED
|
@@ -12,46 +12,97 @@ import { STRUCT_ID } from "./generated/structs.gen.js";
|
|
|
12
12
|
import type { CallbackOptions } from "./client.js";
|
|
13
13
|
import type { Order, Trade, InputOrder, RspUserLogin } from "./generated/structs.gen.js";
|
|
14
14
|
import type { MarketData } from "./market-data.js";
|
|
15
|
+
import {
|
|
16
|
+
assertPlainRecord,
|
|
17
|
+
copyDenseStringArray,
|
|
18
|
+
copyOwnFronts,
|
|
19
|
+
copyOwnRecord,
|
|
20
|
+
ownStringKeys,
|
|
21
|
+
} from "./validation.js";
|
|
15
22
|
|
|
16
23
|
const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
|
|
17
24
|
|
|
18
25
|
/** Pre-trade risk limits, enforced in C++ before each order is sent. */
|
|
19
|
-
export interface
|
|
26
|
+
export interface RiskLimits {
|
|
20
27
|
/** Max volume per single order. Omit/0 = disabled. */
|
|
21
28
|
maxOrderVolume?: number;
|
|
22
29
|
/** Reject if order price deviates from the reference by > this ratio (e.g.
|
|
23
30
|
* 0.02 = 2%). Feed the reference via trackMarketData(md) (the MD snapshot is
|
|
24
|
-
* read in C++);
|
|
31
|
+
* read in C++); missing or stale data rejects opening orders. */
|
|
25
32
|
maxPriceDeviation?: number;
|
|
26
|
-
/** Max notional (price × volume) per order.
|
|
33
|
+
/** Max futures notional (price × volume × multiplier) per opening order.
|
|
34
|
+
* Unknown/unsupported product metadata fails closed. Omit/0 = disabled. */
|
|
27
35
|
maxNotional?: number;
|
|
28
|
-
/** Max order sends per second (token bucket). Omit/0 = disabled. */
|
|
36
|
+
/** Max opening-order sends per second (token bucket). Omit/0 = disabled. */
|
|
29
37
|
maxOrdersPerSec?: number;
|
|
30
38
|
/** Token-bucket burst; defaults to maxOrdersPerSec. */
|
|
31
39
|
orderBurst?: number;
|
|
32
|
-
/**
|
|
33
|
-
*
|
|
34
|
-
|
|
35
|
-
|
|
40
|
+
/** Independent rate for risk-reducing close inserts. Disabled by default so
|
|
41
|
+
* emergency exits are not throttled by the opening-order bucket. */
|
|
42
|
+
maxCloseOrdersPerSec?: number;
|
|
43
|
+
/** Close-order token-bucket burst; defaults to maxCloseOrdersPerSec. */
|
|
44
|
+
closeOrderBurst?: number;
|
|
45
|
+
/** Maximum age of the market-data reference used by the deviation guard.
|
|
46
|
+
* Default 3000 ms. Missing or older data fails closed when the guard is on. */
|
|
47
|
+
maxReferenceAgeMs?: number;
|
|
36
48
|
/** Cap on total open-position MARGIN (Σ open price × volume × multiplier ×
|
|
37
|
-
*
|
|
49
|
+
* absolute by-money/by-volume margin schedule) — a zero-lag hard cap enforced in
|
|
38
50
|
* C++ on every opening order (regular AND armed). 0/undefined = disabled.
|
|
39
51
|
* Margin rates are fed automatically from CTP's OnRspQryInstrumentMarginRate
|
|
40
52
|
* inside C++ (populate them by calling reqQryInstrumentMarginRate); until a
|
|
41
|
-
*
|
|
53
|
+
* multiplier or usable absolute schedule is missing, opening orders fail
|
|
54
|
+
* closed. Both by-money and per-lot components are included; relative
|
|
55
|
+
* investor schedules are combined with their exchange base schedule.
|
|
42
56
|
* Multipliers / existing positions are picked up via syncMultipliers() /
|
|
43
57
|
* syncPositions(). */
|
|
44
|
-
|
|
58
|
+
maxAccountMargin?: number;
|
|
45
59
|
}
|
|
46
60
|
|
|
47
61
|
/** A per-instrument lot cap: a single number caps both sides at that value;
|
|
48
62
|
* `{ long, short }` caps each side separately (omit a side to leave it open). */
|
|
49
|
-
export type
|
|
63
|
+
export type InstrumentPositionLimit =
|
|
64
|
+
number | { long?: number; short?: number };
|
|
65
|
+
|
|
66
|
+
/** One bucket in a complete manually reconciled held-position snapshot. */
|
|
67
|
+
export interface PositionSeed {
|
|
68
|
+
instrumentId: string;
|
|
69
|
+
side: "long" | "short";
|
|
70
|
+
hedgeFlag: "1" | "2" | "3" | "5" | "6" | "7";
|
|
71
|
+
volume: number;
|
|
72
|
+
margin: number;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** A bounded margin-rate sync scoped to the hedge flag used by the orders that
|
|
76
|
+
* will consume those schedules in the native risk ledger. */
|
|
77
|
+
export interface MarginRateSyncOptions {
|
|
78
|
+
instrumentIds: string[];
|
|
79
|
+
hedgeFlag: "1" | "2" | "3" | "5" | "6" | "7";
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** The request-correlated identity established by a successful trader login. */
|
|
83
|
+
export interface TraderSessionIdentity {
|
|
84
|
+
readonly frontId: number;
|
|
85
|
+
readonly sessionId: number;
|
|
86
|
+
/** MaxOrderRef reported by this login response. The process-wide automatic
|
|
87
|
+
* allocator may retain a higher high-water mark from earlier sends. */
|
|
88
|
+
readonly maxOrderRef: number;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export interface TraderSessionResult {
|
|
92
|
+
identity: TraderSessionIdentity;
|
|
93
|
+
multipliers: number;
|
|
94
|
+
marginRates: number;
|
|
95
|
+
positions: number;
|
|
96
|
+
orders: number;
|
|
97
|
+
}
|
|
50
98
|
|
|
51
99
|
/** Options for the one-call post-connect handshake, {@link Trader.session}. */
|
|
52
100
|
export interface SessionOptions {
|
|
53
101
|
brokerId: string;
|
|
54
102
|
userId: string;
|
|
103
|
+
/** Trading account. Defaults to userId for ordinary retail accounts; set it
|
|
104
|
+
* explicitly when the login operator UserID differs from InvestorID. */
|
|
105
|
+
investorId?: string;
|
|
55
106
|
password: string;
|
|
56
107
|
/** Terminal authentication (real accounts require it; SimNow uses
|
|
57
108
|
* appId "simnow_client_test" / authCode of 16 zeros). Omit both to skip. */
|
|
@@ -61,9 +112,17 @@ export interface SessionOptions {
|
|
|
61
112
|
* before trading (brokers reject orders otherwise). Default true; set false
|
|
62
113
|
* for environments that don't need it. */
|
|
63
114
|
confirmSettlement?: boolean;
|
|
64
|
-
/** Which risk inputs to fetch after login
|
|
65
|
-
*
|
|
66
|
-
|
|
115
|
+
/** Which risk inputs to fetch after login. Multipliers/positions/orders default
|
|
116
|
+
* on; margin rates require an explicit contract list and hedge flag.
|
|
117
|
+
* `multipliers` may be `true` (all instruments) or a list of symbols. */
|
|
118
|
+
sync?: {
|
|
119
|
+
multipliers?: boolean | string[];
|
|
120
|
+
/** Contracts and hedge flag whose margin schedules should be queried.
|
|
121
|
+
* Omitted by default because CTP requires one rate query per contract. */
|
|
122
|
+
marginRates?: MarginRateSyncOptions;
|
|
123
|
+
positions?: boolean;
|
|
124
|
+
orders?: boolean;
|
|
125
|
+
};
|
|
67
126
|
}
|
|
68
127
|
|
|
69
128
|
/** A latency-critical armed order: evaluated and fired in C++ on the market-data
|
|
@@ -84,75 +143,369 @@ export interface ArmHandle {
|
|
|
84
143
|
disarm(): boolean;
|
|
85
144
|
}
|
|
86
145
|
|
|
87
|
-
/** Reject a non-finite risk/cap limit.
|
|
88
|
-
*
|
|
89
|
-
*
|
|
90
|
-
* Finite values (including 0/negative, which legitimately mean "disabled") pass. */
|
|
146
|
+
/** Reject a non-finite or negative risk/cap limit. NaN/Inf can void ordinary
|
|
147
|
+
* comparisons, while a mistyped negative must not silently disable a control.
|
|
148
|
+
* Exactly zero is the explicit disabled/clear value. */
|
|
91
149
|
function assertFiniteLimit(name: string, v: number | undefined): void {
|
|
92
|
-
if (v !== undefined && !Number.isFinite(v)) {
|
|
93
|
-
throw new TypeError(`${name} must be a finite number (got ${v})`);
|
|
150
|
+
if (v !== undefined && (!Number.isFinite(v) || v < 0)) {
|
|
151
|
+
throw new TypeError(`${name} must be a non-negative finite number (got ${v})`);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function assertPositiveInt32OrDisabled(name: string, v: number | undefined): void {
|
|
156
|
+
assertFiniteLimit(name, v);
|
|
157
|
+
if (v !== undefined && v > 0 && (!Number.isInteger(v) || v > 0x7fffffff)) {
|
|
158
|
+
throw new TypeError(`${name} must be an integer in 1..2147483647 (got ${v})`);
|
|
94
159
|
}
|
|
95
160
|
}
|
|
96
161
|
|
|
162
|
+
function assertLotLimit(name: string, v: number | undefined): void {
|
|
163
|
+
assertFiniteLimit(name, v);
|
|
164
|
+
if (v !== undefined && v > 0 &&
|
|
165
|
+
(!Number.isInteger(v) || v > 0x7fffffff)) {
|
|
166
|
+
throw new TypeError(`${name} must be an integer in 1..2147483647 lots`);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function assertInstrumentId(
|
|
171
|
+
name: string,
|
|
172
|
+
instrumentId: unknown
|
|
173
|
+
): asserts instrumentId is string {
|
|
174
|
+
if (typeof instrumentId !== "string" || !instrumentId || instrumentId.includes("\0"))
|
|
175
|
+
throw new TypeError(`${name}: instrumentId must be non-empty and contain no NUL`);
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const RISK_LIMIT_KEYS = new Set<keyof RiskLimits>([
|
|
179
|
+
"maxOrderVolume", "maxPriceDeviation", "maxNotional",
|
|
180
|
+
"maxOrdersPerSec", "orderBurst", "maxCloseOrdersPerSec",
|
|
181
|
+
"closeOrderBurst", "maxReferenceAgeMs", "maxAccountMargin",
|
|
182
|
+
]);
|
|
183
|
+
|
|
184
|
+
function assertObjectKeys(
|
|
185
|
+
value: unknown,
|
|
186
|
+
label: string,
|
|
187
|
+
allowed: ReadonlySet<string>
|
|
188
|
+
): asserts value is Record<string, unknown> {
|
|
189
|
+
for (const key of ownStringKeys(value, label))
|
|
190
|
+
if (!allowed.has(key)) throw new TypeError(`${label}: unknown field ${key}`);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
const SESSION_KEYS = new Set([
|
|
194
|
+
"brokerId", "userId", "investorId", "password", "appId", "authCode",
|
|
195
|
+
"confirmSettlement", "sync",
|
|
196
|
+
]);
|
|
197
|
+
const SESSION_SYNC_KEYS = new Set(["multipliers", "marginRates", "positions", "orders"]);
|
|
198
|
+
const MARGIN_RATE_SYNC_KEYS = new Set(["instrumentIds", "hedgeFlag"]);
|
|
199
|
+
const ARM_SPEC_KEYS = new Set(["instrumentId", "side", "triggerPrice", "order"]);
|
|
200
|
+
const POSITION_LIMIT_KEYS = new Set(["long", "short"]);
|
|
201
|
+
const POSITION_SEED_KEYS = new Set([
|
|
202
|
+
"instrumentId", "side", "hedgeFlag", "volume", "margin",
|
|
203
|
+
]);
|
|
204
|
+
|
|
97
205
|
export class Trader extends TraderBase {
|
|
98
206
|
private broker?: string;
|
|
99
207
|
private investor?: string;
|
|
100
208
|
private orderRefSeq = 0;
|
|
101
209
|
|
|
102
210
|
constructor(flowPath: string, fronts: string | string[]) {
|
|
103
|
-
super(
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
const mx = r.maxOrderRef ? parseInt(r.maxOrderRef, 10) : NaN;
|
|
115
|
-
if (Number.isFinite(mx) && mx > this.orderRefSeq) this.orderRefSeq = mx;
|
|
116
|
-
// (The login session FrontID/SessionID — used as reservation keys so our
|
|
117
|
-
// orders never collide with another terminal's on the same account — is
|
|
118
|
-
// published into the risk engine directly in C++ from OnRspUserLogin; no
|
|
119
|
-
// JS relay needed.)
|
|
120
|
-
}
|
|
121
|
-
});
|
|
211
|
+
super(
|
|
212
|
+
new native.Trader(flowPath, copyOwnFronts(fronts, "Trader fronts")),
|
|
213
|
+
native.__layoutData(),
|
|
214
|
+
TRADER_EVENTS
|
|
215
|
+
);
|
|
216
|
+
const clearConfirmedIdentity = () => {
|
|
217
|
+
this.broker = undefined;
|
|
218
|
+
this.investor = undefined;
|
|
219
|
+
};
|
|
220
|
+
this.on("front-connected", clearConfirmedIdentity);
|
|
221
|
+
this.on("front-disconnected", clearConfirmedIdentity);
|
|
122
222
|
this.start();
|
|
123
223
|
}
|
|
124
224
|
|
|
125
|
-
|
|
126
|
-
|
|
225
|
+
/** A raw login Promise may resolve only with a structurally usable session.
|
|
226
|
+
* Account confirmation itself happens in session(), after request-vs-response
|
|
227
|
+
* identity validation; merely observing a protocol event never grants order
|
|
228
|
+
* authority. */
|
|
229
|
+
protected override onRequestResolved(
|
|
230
|
+
eventName: string | undefined,
|
|
231
|
+
value: unknown,
|
|
232
|
+
_options: CallbackOptions
|
|
233
|
+
): void {
|
|
234
|
+
if (eventName === "rsp-user-logout") {
|
|
235
|
+
this.broker = undefined;
|
|
236
|
+
this.investor = undefined;
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
239
|
+
if (eventName !== "rsp-user-login") return;
|
|
240
|
+
// A matched login response updates the confirmed identity, but only from a
|
|
241
|
+
// row carrying the COMPLETE, usable identity (FrontID/SessionID > 0 plus
|
|
242
|
+
// BrokerID/UserID) — the same acceptance condition the generated login
|
|
243
|
+
// validator enforces before it resolves. A partial/abnormal success row
|
|
244
|
+
// (e.g. FrontID 0) is rejected downstream, so caching broker/investor from
|
|
245
|
+
// it would strand a stale identity after the login promise rejects, breaking
|
|
246
|
+
// the invariant "broker/investor set ⟺ a confirmed login". We still never
|
|
247
|
+
// throw here (that would reject an otherwise successful login); the
|
|
248
|
+
// authoritative account-match + reservation-key validation lives in
|
|
249
|
+
// session() / _confirmSessionAccount, and direct callers stay fail-closed
|
|
250
|
+
// natively via acceptsOrderAccount.
|
|
251
|
+
const r = value as
|
|
252
|
+
| {
|
|
253
|
+
brokerId?: string;
|
|
254
|
+
userId?: string;
|
|
255
|
+
frontId?: unknown;
|
|
256
|
+
sessionId?: unknown;
|
|
257
|
+
maxOrderRef?: string;
|
|
258
|
+
}
|
|
259
|
+
| undefined;
|
|
260
|
+
if (!r) return;
|
|
261
|
+
if (
|
|
262
|
+
typeof r.brokerId === "string" &&
|
|
263
|
+
r.brokerId &&
|
|
264
|
+
typeof r.userId === "string" &&
|
|
265
|
+
r.userId &&
|
|
266
|
+
Number.isInteger(r.frontId) &&
|
|
267
|
+
Number(r.frontId) > 0 &&
|
|
268
|
+
Number.isInteger(r.sessionId) &&
|
|
269
|
+
Number(r.sessionId) > 0
|
|
270
|
+
) {
|
|
271
|
+
this.broker = r.brokerId;
|
|
272
|
+
this.investor = r.userId;
|
|
273
|
+
}
|
|
274
|
+
const maxOrderRef =
|
|
275
|
+
typeof r.maxOrderRef === "string" ? r.maxOrderRef.trim() : "";
|
|
276
|
+
if (/^\d{1,12}$/.test(maxOrderRef)) {
|
|
277
|
+
const maxRef = Number(maxOrderRef);
|
|
278
|
+
if (Number.isFinite(maxRef) && maxRef > this.orderRefSeq)
|
|
279
|
+
this.orderRefSeq = maxRef;
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/** Generated login/logout methods call this only after their request has
|
|
284
|
+
* encoded successfully. Revoke the confirmed JS account at that same atomic
|
|
285
|
+
* transition boundary, so a concurrent sync helper cannot start with the old
|
|
286
|
+
* identity while native risk state is already fail-closed for the new session. */
|
|
287
|
+
protected override beginRequestContextTransition(reason: string): void {
|
|
288
|
+
this.broker = undefined;
|
|
289
|
+
this.investor = undefined;
|
|
290
|
+
super.beginRequestContextTransition(reason);
|
|
127
291
|
}
|
|
128
|
-
|
|
129
|
-
|
|
292
|
+
|
|
293
|
+
protected override shouldTimeoutRequest(
|
|
294
|
+
requestId: number,
|
|
295
|
+
sessionTransition: boolean
|
|
296
|
+
): boolean {
|
|
297
|
+
if (!sessionTransition) return true;
|
|
298
|
+
return this.native._timeoutSessionTransition(requestId) as boolean;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
get apiVersion(): string {
|
|
302
|
+
return this.native.apiVersion();
|
|
303
|
+
}
|
|
304
|
+
get tradingDay(): string {
|
|
305
|
+
return this.native.tradingDay();
|
|
130
306
|
}
|
|
131
307
|
|
|
132
308
|
/**
|
|
133
309
|
* One-call post-connect handshake. Call it from the `front-connected` handler
|
|
134
310
|
* (and again after a reconnect): authenticate (if appId/authCode given) →
|
|
135
|
-
* login → confirm settlement → sync multipliers /
|
|
311
|
+
* login → confirm settlement → sync multipliers / margin rates / orders /
|
|
312
|
+
* positions. Each
|
|
136
313
|
* step just wraps the matching req / sync method, so you can hand-roll your
|
|
137
|
-
* own flow instead when you need finer control. Returns the
|
|
138
|
-
* the sync steps. Must run on a connected
|
|
314
|
+
* own flow instead when you need finer control. Returns the request-correlated
|
|
315
|
+
* login identity and row counts from the sync steps. Must run on a connected
|
|
316
|
+
* front (queries need the session up).
|
|
139
317
|
*/
|
|
140
|
-
async session(opts: SessionOptions): Promise<
|
|
141
|
-
|
|
318
|
+
async session(opts: SessionOptions): Promise<TraderSessionResult> {
|
|
319
|
+
assertObjectKeys(opts, "session options", SESSION_KEYS);
|
|
320
|
+
const cleanOpts = copyOwnRecord(opts, "session options");
|
|
321
|
+
const { brokerId, userId, password, appId, authCode } = cleanOpts;
|
|
322
|
+
const investorId = cleanOpts.investorId ?? userId;
|
|
323
|
+
if (typeof brokerId !== "string" || !brokerId ||
|
|
324
|
+
brokerId.includes("\0") || typeof userId !== "string" || !userId ||
|
|
325
|
+
userId.includes("\0") || typeof password !== "string" || !password ||
|
|
326
|
+
password.includes("\0")) {
|
|
327
|
+
throw new TypeError("session requires brokerId, userId and password");
|
|
328
|
+
}
|
|
329
|
+
if (typeof investorId !== "string" || !investorId ||
|
|
330
|
+
investorId.includes("\0"))
|
|
331
|
+
throw new TypeError("session investorId must be a non-empty string");
|
|
332
|
+
if (cleanOpts.confirmSettlement !== undefined && typeof cleanOpts.confirmSettlement !== "boolean")
|
|
333
|
+
throw new TypeError("session.confirmSettlement must be boolean");
|
|
334
|
+
if ((appId === undefined) !== (authCode === undefined)) {
|
|
335
|
+
throw new TypeError("session appId and authCode must be supplied together");
|
|
336
|
+
}
|
|
337
|
+
if (appId !== undefined && (typeof appId !== "string" || !appId ||
|
|
338
|
+
appId.includes("\0") || typeof authCode !== "string" || !authCode ||
|
|
339
|
+
authCode.includes("\0")))
|
|
340
|
+
throw new TypeError("session appId and authCode must be non-empty strings");
|
|
341
|
+
let cleanSync: NonNullable<SessionOptions["sync"]> = {};
|
|
342
|
+
if (cleanOpts.sync !== undefined) {
|
|
343
|
+
assertObjectKeys(cleanOpts.sync, "session.sync", SESSION_SYNC_KEYS);
|
|
344
|
+
cleanSync = copyOwnRecord(cleanOpts.sync, "session.sync");
|
|
345
|
+
const { multipliers, marginRates, positions, orders } = cleanSync;
|
|
346
|
+
if (multipliers !== undefined && typeof multipliers !== "boolean")
|
|
347
|
+
cleanSync.multipliers = copyDenseStringArray(
|
|
348
|
+
multipliers, "session.sync.multipliers"
|
|
349
|
+
);
|
|
350
|
+
if (marginRates !== undefined) {
|
|
351
|
+
assertObjectKeys(
|
|
352
|
+
marginRates, "session.sync.marginRates", MARGIN_RATE_SYNC_KEYS
|
|
353
|
+
);
|
|
354
|
+
const cleanMarginRates = copyOwnRecord(
|
|
355
|
+
marginRates, "session.sync.marginRates"
|
|
356
|
+
);
|
|
357
|
+
const instrumentIds = copyDenseStringArray(
|
|
358
|
+
cleanMarginRates.instrumentIds,
|
|
359
|
+
"session.sync.marginRates.instrumentIds",
|
|
360
|
+
false
|
|
361
|
+
);
|
|
362
|
+
const hedgeFlag = cleanMarginRates.hedgeFlag;
|
|
363
|
+
if (typeof hedgeFlag !== "string" || !/^[123567]$/.test(hedgeFlag)) {
|
|
364
|
+
throw new TypeError(
|
|
365
|
+
"session.sync.marginRates.hedgeFlag must be 1, 2, 3, 5, 6 or 7"
|
|
366
|
+
);
|
|
367
|
+
}
|
|
368
|
+
cleanSync.marginRates = {
|
|
369
|
+
instrumentIds,
|
|
370
|
+
hedgeFlag: hedgeFlag as MarginRateSyncOptions["hedgeFlag"],
|
|
371
|
+
};
|
|
372
|
+
}
|
|
373
|
+
if (positions !== undefined && typeof positions !== "boolean")
|
|
374
|
+
throw new TypeError("session.sync.positions must be boolean");
|
|
375
|
+
if (orders !== undefined && typeof orders !== "boolean")
|
|
376
|
+
throw new TypeError("session.sync.orders must be boolean");
|
|
377
|
+
}
|
|
378
|
+
// Validate the exact CTP wire capacities before revoking a healthy prior
|
|
379
|
+
// context. A malformed/oversized handshake must be side-effect free.
|
|
380
|
+
if (appId !== undefined && authCode !== undefined)
|
|
381
|
+
this.encode(STRUCT_ID.ReqAuthenticate,
|
|
382
|
+
{ brokerId, userId, appId, authCode });
|
|
383
|
+
this.encode(STRUCT_ID.ReqUserLogin, { brokerId, userId, password });
|
|
384
|
+
// Encode unconditionally: InvestorID is part of the native account
|
|
385
|
+
// confirmation even when this environment skips settlement confirmation.
|
|
386
|
+
// Passing these exact CTP bytes also avoids re-encoding GB18030 identities
|
|
387
|
+
// through N-API's UTF-8 string conversion.
|
|
388
|
+
const encodedAccount = this.encode(STRUCT_ID.SettlementInfoConfirm,
|
|
389
|
+
{ brokerId, investorId });
|
|
390
|
+
// Revoke native mandates/session authority at the start of the whole
|
|
391
|
+
// handshake, including the authentication phase. A failed auth must not
|
|
392
|
+
// leave an old close arm capable of firing under a superseded account.
|
|
393
|
+
this.native._beginSessionHandshake();
|
|
394
|
+
// No query created under the previous login may cross this handshake. Do
|
|
395
|
+
// this only after all synchronous option validation has succeeded.
|
|
396
|
+
this.invalidateRequestContext("trader session started");
|
|
397
|
+
let contextToken = this.requestContextToken();
|
|
398
|
+
// The cached JS identity is confirmed-session state, not merely the last
|
|
399
|
+
// attempted credentials. Revoke it before auth/login so a failed handshake
|
|
400
|
+
// cannot drive a later snapshot query with stale account fields.
|
|
401
|
+
this.broker = undefined;
|
|
402
|
+
this.investor = undefined;
|
|
403
|
+
// A reconnect may have an event gap. Keep all opening inserts
|
|
404
|
+
// fail-closed throughout the handshake until both authoritative snapshots
|
|
405
|
+
// have independently committed.
|
|
406
|
+
this.native._markPositionLedgerUncertain();
|
|
407
|
+
this.native._markOrderLedgerUncertain();
|
|
142
408
|
if (appId !== undefined && authCode !== undefined) {
|
|
143
409
|
await this.reqAuthenticate({ brokerId, userId, appId, authCode });
|
|
410
|
+
this.assertRequestContext(contextToken, "trader session authentication");
|
|
411
|
+
}
|
|
412
|
+
// The generated login method deliberately begins exactly one new request
|
|
413
|
+
// context. A test double may omit that transition; either form is safe. By
|
|
414
|
+
// retaining the pre-call epoch unless the explicit-transition counter also
|
|
415
|
+
// advanced once, an inline front-disconnected callback cannot masquerade as
|
|
416
|
+
// the expected login transition.
|
|
417
|
+
const beforeLoginContext = this.requestContextToken();
|
|
418
|
+
const beforeLoginTransition = this.requestTransitionToken();
|
|
419
|
+
const loginRequest = this.reqUserLogin({ brokerId, userId, password });
|
|
420
|
+
const afterLoginContext = this.requestContextToken();
|
|
421
|
+
const afterLoginTransition = this.requestTransitionToken();
|
|
422
|
+
if (afterLoginTransition === beforeLoginTransition + 1 &&
|
|
423
|
+
afterLoginContext === beforeLoginContext + 1) {
|
|
424
|
+
contextToken = afterLoginContext;
|
|
425
|
+
} else if (afterLoginTransition === beforeLoginTransition) {
|
|
426
|
+
// Test doubles normally do not implement the generated transition. Keep
|
|
427
|
+
// the old epoch so any synchronous front event is detected after await.
|
|
428
|
+
contextToken = beforeLoginContext;
|
|
429
|
+
} else {
|
|
430
|
+
// Settle the request before surfacing the invariant violation so a
|
|
431
|
+
// synchronously rejected test double cannot become an unhandled promise.
|
|
432
|
+
try { await loginRequest; } catch { /* reported as transition failure */ }
|
|
433
|
+
throw new Error("trader session login crossed multiple context transitions");
|
|
144
434
|
}
|
|
145
|
-
|
|
146
|
-
|
|
435
|
+
const login = await loginRequest as
|
|
436
|
+
RspUserLogin | undefined;
|
|
437
|
+
this.assertRequestContext(contextToken, "trader session login");
|
|
438
|
+
if (!login || !Number.isInteger(login.frontId) || login.frontId <= 0 ||
|
|
439
|
+
!Number.isInteger(login.sessionId) || login.sessionId <= 0 ||
|
|
440
|
+
login.brokerId !== brokerId ||
|
|
441
|
+
login.userId !== userId) {
|
|
442
|
+
// FrontID/SessionID are part of the reservation identity. Treating an
|
|
443
|
+
// empty success response as ready would reuse an old/zero native session
|
|
444
|
+
// key and create ghost reservations when the first OnRtnOrder arrives.
|
|
445
|
+
this.broker = undefined;
|
|
446
|
+
this.investor = undefined;
|
|
447
|
+
throw new Error("trader login response has missing or mismatched session identity");
|
|
448
|
+
}
|
|
449
|
+
const maxOrderRef = typeof login.maxOrderRef === "string"
|
|
450
|
+
? login.maxOrderRef.trim() : "";
|
|
451
|
+
if (maxOrderRef !== "" && !/^\d{1,12}$/.test(maxOrderRef)) {
|
|
452
|
+
this.broker = undefined;
|
|
453
|
+
this.investor = undefined;
|
|
454
|
+
throw new Error("trader login response has an invalid MaxOrderRef");
|
|
455
|
+
}
|
|
456
|
+
const maxRef = maxOrderRef === "" ? 0 : Number(maxOrderRef);
|
|
457
|
+
// A successful CTP response may legally end with an empty payload. The
|
|
458
|
+
// request identity is still authoritative for the synchronization calls
|
|
459
|
+
// below; never retain a previous session's broker/investor in that case.
|
|
460
|
+
const confirmed = this.native._confirmSessionAccount(
|
|
461
|
+
login.frontId, login.sessionId, encodedAccount
|
|
462
|
+
) as boolean;
|
|
463
|
+
if (!confirmed) {
|
|
464
|
+
this.broker = undefined;
|
|
465
|
+
this.investor = undefined;
|
|
466
|
+
throw new Error("native Trader session/account confirmation failed");
|
|
467
|
+
}
|
|
468
|
+
this.broker = brokerId;
|
|
469
|
+
this.investor = investorId;
|
|
470
|
+
if (maxRef > this.orderRefSeq) this.orderRefSeq = maxRef;
|
|
471
|
+
if (cleanOpts.confirmSettlement ?? true) {
|
|
147
472
|
// idempotent: confirming an already-confirmed statement is fine
|
|
148
|
-
await this.reqSettlementInfoConfirm({ brokerId, investorId
|
|
473
|
+
await this.reqSettlementInfoConfirm({ brokerId, investorId });
|
|
474
|
+
this.assertRequestContext(contextToken, "trader session settlement confirmation");
|
|
149
475
|
}
|
|
150
|
-
const sync =
|
|
476
|
+
const sync = cleanSync;
|
|
151
477
|
const mul = sync.multipliers ?? true;
|
|
152
|
-
const result = {
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
478
|
+
const result: TraderSessionResult = {
|
|
479
|
+
identity: Object.freeze({
|
|
480
|
+
frontId: login.frontId,
|
|
481
|
+
sessionId: login.sessionId,
|
|
482
|
+
maxOrderRef: maxRef,
|
|
483
|
+
}),
|
|
484
|
+
multipliers: 0,
|
|
485
|
+
marginRates: 0,
|
|
486
|
+
positions: 0,
|
|
487
|
+
orders: 0,
|
|
488
|
+
};
|
|
489
|
+
if (mul) {
|
|
490
|
+
result.multipliers = await this.syncMultipliers(Array.isArray(mul) ? mul : undefined);
|
|
491
|
+
this.assertRequestContext(contextToken, "trader session multiplier sync");
|
|
492
|
+
}
|
|
493
|
+
const marginRateSync = sync.marginRates;
|
|
494
|
+
if (marginRateSync !== undefined) {
|
|
495
|
+
result.marginRates = await this.syncMarginRates(
|
|
496
|
+
marginRateSync.instrumentIds,
|
|
497
|
+
marginRateSync.hedgeFlag
|
|
498
|
+
);
|
|
499
|
+
this.assertRequestContext(contextToken, "trader session margin sync");
|
|
500
|
+
}
|
|
501
|
+
if (sync.orders ?? true) {
|
|
502
|
+
result.orders = await this.syncOrders();
|
|
503
|
+
this.assertRequestContext(contextToken, "trader session order sync");
|
|
504
|
+
}
|
|
505
|
+
if (sync.positions ?? true) {
|
|
506
|
+
result.positions = await this.syncPositions();
|
|
507
|
+
this.assertRequestContext(contextToken, "trader session position sync");
|
|
508
|
+
}
|
|
156
509
|
return result;
|
|
157
510
|
}
|
|
158
511
|
|
|
@@ -161,11 +514,116 @@ export class Trader extends TraderBase {
|
|
|
161
514
|
* ref with "不允许重复报单", so an unset ref would otherwise collide. */
|
|
162
515
|
private withAutoOrderRef(order: Partial<InputOrder>): Partial<InputOrder> {
|
|
163
516
|
if (order.orderRef === undefined || order.orderRef === "") {
|
|
164
|
-
|
|
517
|
+
if (this.orderRefSeq >= 999_999_999_999) {
|
|
518
|
+
throw new RangeError("OrderRef space exhausted for this process/session");
|
|
519
|
+
}
|
|
520
|
+
return { ...order, orderRef: String(this.orderRefSeq + 1) };
|
|
521
|
+
}
|
|
522
|
+
if (typeof order.orderRef !== "string" || !/^\d{1,12}$/.test(order.orderRef)) {
|
|
523
|
+
throw new TypeError("orderRef must contain 1..12 decimal digits");
|
|
524
|
+
}
|
|
525
|
+
const explicit = Number(order.orderRef);
|
|
526
|
+
if (explicit <= this.orderRefSeq) {
|
|
527
|
+
throw new RangeError(
|
|
528
|
+
`explicit orderRef must be greater than the current high-water mark ${this.orderRefSeq}`
|
|
529
|
+
);
|
|
165
530
|
}
|
|
166
531
|
return order;
|
|
167
532
|
}
|
|
168
533
|
|
|
534
|
+
private commitOrderRef(order: Partial<InputOrder>): void {
|
|
535
|
+
this.orderRefSeq = Number(order.orderRef);
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
private validateOrder(order: Partial<InputOrder>, context: string): Partial<InputOrder> {
|
|
539
|
+
const clean = copyOwnRecord(order, context);
|
|
540
|
+
if (!this.broker || !this.investor) {
|
|
541
|
+
throw new Error(`${context}: a confirmed Trader login is required`);
|
|
542
|
+
}
|
|
543
|
+
if (typeof clean.instrumentId !== "string" || !clean.instrumentId ||
|
|
544
|
+
clean.instrumentId.includes("\0") ||
|
|
545
|
+
(clean.direction !== "0" && clean.direction !== "1")) {
|
|
546
|
+
throw new TypeError(`${context}: instrumentId and direction ("0"/"1") are required`);
|
|
547
|
+
}
|
|
548
|
+
if (typeof clean.combOffsetFlag !== "string" ||
|
|
549
|
+
!/^[0-6]$/.test(clean.combOffsetFlag)) {
|
|
550
|
+
throw new TypeError(`${context}: combOffsetFlag must be one CTP offset digit 0..6; multi-leg orders are unsupported`);
|
|
551
|
+
}
|
|
552
|
+
if (clean.combHedgeFlag !== undefined &&
|
|
553
|
+
(typeof clean.combHedgeFlag !== "string" ||
|
|
554
|
+
!/^[123567]$/.test(clean.combHedgeFlag))) {
|
|
555
|
+
throw new TypeError(`${context}: combHedgeFlag must be one CTP hedge digit (1, 2, 3, 5, 6 or 7)`);
|
|
556
|
+
}
|
|
557
|
+
if (!Number.isInteger(clean.volumeTotalOriginal) ||
|
|
558
|
+
!(Number(clean.volumeTotalOriginal) > 0) ||
|
|
559
|
+
Number(clean.volumeTotalOriginal) > 0x7fffffff) {
|
|
560
|
+
throw new TypeError(`${context}: volumeTotalOriginal must be a positive int32`);
|
|
561
|
+
}
|
|
562
|
+
if (!Number.isFinite(clean.limitPrice) || !(Number(clean.limitPrice) > 0) ||
|
|
563
|
+
Number(clean.limitPrice) >= 1e300) {
|
|
564
|
+
throw new TypeError(`${context}: limitPrice must be a positive finite price`);
|
|
565
|
+
}
|
|
566
|
+
if (clean.brokerId !== undefined && clean.brokerId !== this.broker) {
|
|
567
|
+
throw new TypeError(`${context}: brokerId must match the confirmed login`);
|
|
568
|
+
}
|
|
569
|
+
if (clean.investorId !== undefined && clean.investorId !== this.investor) {
|
|
570
|
+
throw new TypeError(`${context}: investorId must match the confirmed login`);
|
|
571
|
+
}
|
|
572
|
+
const value = <K extends keyof InputOrder>(key: K, fallback: InputOrder[K]) =>
|
|
573
|
+
clean[key] === undefined ? fallback : clean[key];
|
|
574
|
+
const empty = (v: unknown) => v === undefined || v === "";
|
|
575
|
+
// The reservation ledger models ordinary single-instrument limit orders.
|
|
576
|
+
// Admit only the three execution policies whose live remainder is fully
|
|
577
|
+
// represented by CTP order/trade callbacks: GFD, FAK and FOK.
|
|
578
|
+
const timeCondition = value("timeCondition", "3");
|
|
579
|
+
const volumeCondition = value("volumeCondition", "1");
|
|
580
|
+
const supportedExecutionPolicy =
|
|
581
|
+
(timeCondition === "3" && volumeCondition === "1") ||
|
|
582
|
+
(timeCondition === "1" && (volumeCondition === "1" || volumeCondition === "3"));
|
|
583
|
+
if (value("orderPriceType", "2") !== "2" ||
|
|
584
|
+
!supportedExecutionPolicy || !empty(clean.gtdDate) ||
|
|
585
|
+
value("minVolume", 1) !== 1 ||
|
|
586
|
+
value("contingentCondition", "1") !== "1" ||
|
|
587
|
+
value("stopPrice", 0) !== 0 ||
|
|
588
|
+
value("forceCloseReason", "0") !== "0" ||
|
|
589
|
+
value("isAutoSuspend", 0) !== 0 ||
|
|
590
|
+
!empty(clean.businessUnit) || value("requestId", 0) !== 0 ||
|
|
591
|
+
value("userForceClose", 0) !== 0 ||
|
|
592
|
+
value("isSwapOrder", 0) !== 0 || !empty(clean.exchangeId) ||
|
|
593
|
+
!empty(clean.investUnitId) || !empty(clean.accountId) ||
|
|
594
|
+
!empty(clean.currencyId) || !empty(clean.clientId) ||
|
|
595
|
+
value("sessionReqSeq", 0) !== 0) {
|
|
596
|
+
throw new TypeError(
|
|
597
|
+
`${context}: only single-instrument GFD, FAK or FOK limit orders are supported`
|
|
598
|
+
);
|
|
599
|
+
}
|
|
600
|
+
return {
|
|
601
|
+
...clean,
|
|
602
|
+
orderPriceType: "2",
|
|
603
|
+
combHedgeFlag: clean.combHedgeFlag ?? "1",
|
|
604
|
+
timeCondition,
|
|
605
|
+
gtdDate: "",
|
|
606
|
+
volumeCondition,
|
|
607
|
+
minVolume: 1,
|
|
608
|
+
contingentCondition: "1",
|
|
609
|
+
stopPrice: 0,
|
|
610
|
+
forceCloseReason: "0",
|
|
611
|
+
isAutoSuspend: 0,
|
|
612
|
+
businessUnit: "",
|
|
613
|
+
requestId: 0,
|
|
614
|
+
userForceClose: 0,
|
|
615
|
+
isSwapOrder: 0,
|
|
616
|
+
exchangeId: "",
|
|
617
|
+
investUnitId: "",
|
|
618
|
+
accountId: "",
|
|
619
|
+
currencyId: "",
|
|
620
|
+
clientId: "",
|
|
621
|
+
sessionReqSeq: 0,
|
|
622
|
+
brokerId: this.broker,
|
|
623
|
+
investorId: this.investor,
|
|
624
|
+
};
|
|
625
|
+
}
|
|
626
|
+
|
|
169
627
|
/**
|
|
170
628
|
* Insert an order through the C++ pre-trade risk gate. Resolves on submission:
|
|
171
629
|
* CTP sends no success acknowledgement for an accepted order - only
|
|
@@ -175,34 +633,55 @@ export class Trader extends TraderBase {
|
|
|
175
633
|
* unique numeric value automatically.
|
|
176
634
|
*/
|
|
177
635
|
reqOrderInsert(req: Partial<InputOrder> = {}): Promise<void> {
|
|
178
|
-
|
|
636
|
+
const order = this.withAutoOrderRef(this.validateOrder(req, "reqOrderInsert"));
|
|
637
|
+
// Preflight field capacities before consuming the OrderRef high-water mark.
|
|
638
|
+
// TraderBase encodes the same object again when it submits.
|
|
639
|
+
this.encode(STRUCT_ID.InputOrder, order as Record<string, unknown>);
|
|
640
|
+
const result = super.reqOrderInsert(order);
|
|
641
|
+
this.commitOrderRef(order);
|
|
642
|
+
return result;
|
|
179
643
|
}
|
|
180
644
|
|
|
181
645
|
/** Publish pre-trade risk limits to the C++ enforcer (takes effect at once). */
|
|
182
|
-
|
|
646
|
+
setRiskLimits(config: RiskLimits): this {
|
|
647
|
+
const clean = copyOwnRecord(config, "setRiskLimits");
|
|
648
|
+
for (const key of ownStringKeys(clean, "setRiskLimits")) {
|
|
649
|
+
if (!RISK_LIMIT_KEYS.has(key as keyof RiskLimits))
|
|
650
|
+
throw new TypeError(`setRiskLimits: unknown field ${key}`);
|
|
651
|
+
}
|
|
183
652
|
// A non-finite limit would silently disable that control (see
|
|
184
653
|
// assertFiniteLimit) — reject it rather than run unprotected.
|
|
185
|
-
|
|
186
|
-
assertFiniteLimit("
|
|
187
|
-
assertFiniteLimit("
|
|
188
|
-
assertFiniteLimit("
|
|
189
|
-
assertFiniteLimit("
|
|
190
|
-
assertFiniteLimit("
|
|
191
|
-
assertFiniteLimit("
|
|
192
|
-
|
|
654
|
+
assertPositiveInt32OrDisabled("setRiskLimits.maxOrderVolume", clean.maxOrderVolume);
|
|
655
|
+
assertFiniteLimit("setRiskLimits.maxPriceDeviation", clean.maxPriceDeviation);
|
|
656
|
+
assertFiniteLimit("setRiskLimits.maxNotional", clean.maxNotional);
|
|
657
|
+
assertFiniteLimit("setRiskLimits.maxOrdersPerSec", clean.maxOrdersPerSec);
|
|
658
|
+
assertFiniteLimit("setRiskLimits.orderBurst", clean.orderBurst);
|
|
659
|
+
assertFiniteLimit("setRiskLimits.maxCloseOrdersPerSec", clean.maxCloseOrdersPerSec);
|
|
660
|
+
assertFiniteLimit("setRiskLimits.closeOrderBurst", clean.closeOrderBurst);
|
|
661
|
+
assertFiniteLimit("setRiskLimits.maxAccountMargin", clean.maxAccountMargin);
|
|
662
|
+
assertFiniteLimit("setRiskLimits.maxReferenceAgeMs", clean.maxReferenceAgeMs);
|
|
663
|
+
if (clean.maxReferenceAgeMs !== undefined && !(clean.maxReferenceAgeMs > 0)) {
|
|
664
|
+
throw new TypeError("setRiskLimits.maxReferenceAgeMs must be > 0");
|
|
665
|
+
}
|
|
666
|
+
this.native.setRiskLimits(clean);
|
|
667
|
+
return this;
|
|
668
|
+
}
|
|
669
|
+
/** Enter REDUCE_ONLY atomically at the final vendor-API send barrier. Armed
|
|
670
|
+
* opens remain registered but cannot send until resume(). */
|
|
671
|
+
reduceOnly(): this {
|
|
672
|
+
this.native.riskReduceOnly();
|
|
193
673
|
return this;
|
|
194
674
|
}
|
|
195
|
-
/**
|
|
196
|
-
*
|
|
197
|
-
*
|
|
198
|
-
*
|
|
199
|
-
*
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
this.native.riskHalt();
|
|
675
|
+
/** Enter HALT_ALL atomically: both opening and closing order inserts, advanced
|
|
676
|
+
* mutations and bank/futures transfers are refused, and all existing armed
|
|
677
|
+
* triggers are cleared. New arm() calls are rejected until resume().
|
|
678
|
+
* Cancellation actions remain available so working
|
|
679
|
+
* exchange orders can still be withdrawn. */
|
|
680
|
+
haltAll(): this {
|
|
681
|
+
this.native.riskHaltAll();
|
|
203
682
|
return this;
|
|
204
683
|
}
|
|
205
|
-
/**
|
|
684
|
+
/** Return to NORMAL mode after reduceOnly() or haltAll(). */
|
|
206
685
|
resume(): this {
|
|
207
686
|
this.native.riskResume();
|
|
208
687
|
return this;
|
|
@@ -212,129 +691,240 @@ export class Trader extends TraderBase {
|
|
|
212
691
|
* Wires the feed's C++ snapshot cache straight into this Trader's risk engine,
|
|
213
692
|
* so the deviation check reads current prices in C++ on the order path (no JS
|
|
214
693
|
* round-trip, and it also covers armed orders that fire with no JS in the loop).
|
|
215
|
-
* Without
|
|
694
|
+
* Without a fresh reference, an enabled deviation check fails closed. */
|
|
216
695
|
trackMarketData(md: MarketData): this {
|
|
217
696
|
this.native._attachSnapshot(md._snapshotExternal());
|
|
218
697
|
return this;
|
|
219
698
|
}
|
|
220
699
|
|
|
221
700
|
// Contract multipliers (for cost accounting) and margin rates (for the
|
|
222
|
-
//
|
|
701
|
+
// maxAccountMargin cap) are NOT fed from JS: the C++ risk engine sources them directly
|
|
223
702
|
// from CTP's OnRspQryInstrument / OnRspQryInstrumentMarginRate callbacks (see
|
|
224
703
|
// scripts/codegen/generate-trader.mjs). So any reqQryInstrument keeps
|
|
225
704
|
// multipliers current, and querying reqQryInstrumentMarginRate for the
|
|
226
|
-
//
|
|
227
|
-
//
|
|
705
|
+
// syncMarginRates() loads investor plus exchange-base schedules. Missing
|
|
706
|
+
// metadata fails closed; IsRelative is combined with the matching base.
|
|
228
707
|
|
|
229
708
|
/**
|
|
230
709
|
* Cap the open position (in lots) for one instrument, enforced in C++ on
|
|
231
710
|
* every opening order. Pass a number to cap both sides at once, or
|
|
232
711
|
* `{ long, short }` to cap each side separately. Within `{ long, short }`,
|
|
233
712
|
* **omitting a side leaves that side's current cap unchanged** (on a re-call it
|
|
234
|
-
* is NOT reset to uncapped), and passing
|
|
713
|
+
* is NOT reset to uncapped), and passing `0` for a side removes its cap.
|
|
235
714
|
* Long and short are always tracked independently.
|
|
236
715
|
*
|
|
237
|
-
*
|
|
238
|
-
* so rapid bursts of opens can momentarily overshoot before the fills land —
|
|
239
|
-
* size the cap with that in mind.
|
|
716
|
+
* Held positions and in-flight working opens are counted atomically.
|
|
240
717
|
*
|
|
241
|
-
* td.
|
|
242
|
-
* td.
|
|
718
|
+
* td.setInstrumentPositionLimit("rb2610", 100);
|
|
719
|
+
* td.setInstrumentPositionLimit("ru2610", { long: 100, short: 20 });
|
|
243
720
|
*/
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
assertFiniteLimit("setMaxPosition.short", max.short);
|
|
252
|
-
if (max.long !== undefined) this.native.setMaxPositionVolume(instrumentId, true, max.long);
|
|
253
|
-
if (max.short !== undefined) this.native.setMaxPositionVolume(instrumentId, false, max.short);
|
|
254
|
-
}
|
|
721
|
+
setInstrumentPositionLimit(
|
|
722
|
+
instrumentId: string,
|
|
723
|
+
limit: InstrumentPositionLimit
|
|
724
|
+
): this {
|
|
725
|
+
assertInstrumentId("setInstrumentPositionLimit", instrumentId);
|
|
726
|
+
const row = this.normalizePositionLimit(instrumentId, limit);
|
|
727
|
+
this.native._setInstrumentPositionLimits([row]);
|
|
255
728
|
return this;
|
|
256
729
|
}
|
|
257
730
|
|
|
258
731
|
/** Cap several instruments at once, e.g.
|
|
259
732
|
* `{ rb2610: 100, ru2610: { long: 100, short: 20 } }`. */
|
|
260
|
-
|
|
261
|
-
|
|
733
|
+
setInstrumentPositionLimits(
|
|
734
|
+
limits: Record<string, InstrumentPositionLimit>
|
|
735
|
+
): this {
|
|
736
|
+
const rows = ownStringKeys(limits, "setInstrumentPositionLimits").map((instrumentId) => {
|
|
737
|
+
const limit = limits[instrumentId];
|
|
738
|
+
assertInstrumentId("setInstrumentPositionLimits", instrumentId);
|
|
739
|
+
return this.normalizePositionLimit(instrumentId, limit);
|
|
740
|
+
});
|
|
741
|
+
this.native._setInstrumentPositionLimits(rows);
|
|
262
742
|
return this;
|
|
263
743
|
}
|
|
264
744
|
|
|
745
|
+
private normalizePositionLimit(
|
|
746
|
+
instrumentId: string,
|
|
747
|
+
limit: InstrumentPositionLimit
|
|
748
|
+
): { instrumentId: string; long?: number; short?: number } {
|
|
749
|
+
if (typeof limit === "number") {
|
|
750
|
+
assertLotLimit("setInstrumentPositionLimit", limit);
|
|
751
|
+
return copyOwnRecord(
|
|
752
|
+
{ instrumentId, long: limit, short: limit },
|
|
753
|
+
"setInstrumentPositionLimit"
|
|
754
|
+
);
|
|
755
|
+
}
|
|
756
|
+
assertPlainRecord(limit, "setInstrumentPositionLimit");
|
|
757
|
+
const clean = copyOwnRecord(limit, "setInstrumentPositionLimit");
|
|
758
|
+
if (clean.long === undefined && clean.short === undefined) {
|
|
759
|
+
throw new TypeError("setInstrumentPositionLimit requires a number or at least one of long/short");
|
|
760
|
+
}
|
|
761
|
+
for (const key of ownStringKeys(clean, "setInstrumentPositionLimit")) {
|
|
762
|
+
if (!POSITION_LIMIT_KEYS.has(key))
|
|
763
|
+
throw new TypeError(`setInstrumentPositionLimit: unknown field ${key}`);
|
|
764
|
+
}
|
|
765
|
+
assertLotLimit("setInstrumentPositionLimit.long", clean.long);
|
|
766
|
+
assertLotLimit("setInstrumentPositionLimit.short", clean.short);
|
|
767
|
+
return copyOwnRecord(
|
|
768
|
+
{ instrumentId, long: clean.long, short: clean.short },
|
|
769
|
+
"setInstrumentPositionLimit"
|
|
770
|
+
);
|
|
771
|
+
}
|
|
772
|
+
|
|
265
773
|
/**
|
|
266
|
-
* Cap one instrument's open
|
|
267
|
-
* long and short summed
|
|
268
|
-
*
|
|
269
|
-
*
|
|
270
|
-
* `maxCost <= 0` to remove it. Fill-based, same caveat as maxPositionCost.
|
|
774
|
+
* Cap one instrument's scheduled open margin (CTP by-money + by-volume,
|
|
775
|
+
* long and short summed), enforced in C++ on every opening order. This is
|
|
776
|
+
* independent of the account-wide maxAccountMargin cap; both apply. Pass
|
|
777
|
+
* `limit = 0` to remove it. Held and in-flight exposure both count.
|
|
271
778
|
*/
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
779
|
+
setInstrumentMarginLimit(instrumentId: string, limit: number): this {
|
|
780
|
+
assertInstrumentId("setInstrumentMarginLimit", instrumentId);
|
|
781
|
+
assertFiniteLimit("setInstrumentMarginLimit", limit);
|
|
782
|
+
this.native._setInstrumentMarginLimits([{ instrumentId, limit }]);
|
|
275
783
|
return this;
|
|
276
784
|
}
|
|
277
785
|
|
|
278
|
-
/** Cap several instruments' open
|
|
786
|
+
/** Cap several instruments' scheduled open margin at once, e.g.
|
|
279
787
|
* `{ ag2608: 2_000_000, au2608: 5_000_000 }`. */
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
788
|
+
setInstrumentMarginLimits(limits: Record<string, number>): this {
|
|
789
|
+
const rows = ownStringKeys(limits, "setInstrumentMarginLimits").map((instrumentId) => {
|
|
790
|
+
const limit = limits[instrumentId];
|
|
791
|
+
assertInstrumentId("setInstrumentMarginLimits", instrumentId);
|
|
792
|
+
assertFiniteLimit(`setInstrumentMarginLimits.${instrumentId}`, limit);
|
|
793
|
+
return { instrumentId, limit };
|
|
794
|
+
});
|
|
795
|
+
this.native._setInstrumentMarginLimits(rows);
|
|
285
796
|
return this;
|
|
286
797
|
}
|
|
287
798
|
|
|
288
|
-
/**
|
|
289
|
-
*
|
|
290
|
-
*
|
|
291
|
-
*
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
799
|
+
/** Atomically replace held positions from a complete manually reconciled
|
|
800
|
+
* snapshot. `margin` is CTP InvestorPosition.UseMargin. An empty array is an
|
|
801
|
+
* authoritative flat book. Partial/incremental seeding is intentionally not
|
|
802
|
+
* exposed because armed orders can run between JS calls. */
|
|
803
|
+
seedPositions(positions: ReadonlyArray<PositionSeed>): this {
|
|
804
|
+
if (!Array.isArray(positions))
|
|
805
|
+
throw new TypeError("seedPositions requires a complete position array");
|
|
806
|
+
const seeds: Array<{
|
|
807
|
+
instrumentId: string; isLong: boolean; hedgeFlag: string;
|
|
808
|
+
volume: number; margin: number;
|
|
809
|
+
}> = [];
|
|
810
|
+
const positionCount = positions.length;
|
|
811
|
+
for (let i = 0; i < positionCount; i++) {
|
|
812
|
+
if (!Object.prototype.hasOwnProperty.call(positions, i))
|
|
813
|
+
throw new TypeError(`seedPositions row ${i} must be an explicit array entry`);
|
|
814
|
+
const row = copyOwnRecord(positions[i], `seedPositions row ${i}`);
|
|
815
|
+
for (const key of ownStringKeys(row, `seedPositions row ${i}`))
|
|
816
|
+
if (!POSITION_SEED_KEYS.has(key))
|
|
817
|
+
throw new TypeError(`seedPositions row ${i}: unknown field ${key}`);
|
|
818
|
+
assertInstrumentId("seedPositions", row.instrumentId);
|
|
819
|
+
if ((row.side !== "long" && row.side !== "short") ||
|
|
820
|
+
typeof row.hedgeFlag !== "string" ||
|
|
821
|
+
!/^[123567]$/.test(row.hedgeFlag) ||
|
|
822
|
+
!Number.isInteger(row.volume) || row.volume < 0 ||
|
|
823
|
+
!Number.isFinite(row.margin) || row.margin < 0) {
|
|
824
|
+
throw new TypeError(
|
|
825
|
+
"seedPositions requires long/short, one hedgeFlag digit, a non-negative integer volume and non-negative finite margin"
|
|
826
|
+
);
|
|
827
|
+
}
|
|
828
|
+
seeds.push({
|
|
829
|
+
instrumentId: row.instrumentId,
|
|
830
|
+
isLong: row.side === "long",
|
|
831
|
+
hedgeFlag: row.hedgeFlag,
|
|
832
|
+
volume: row.volume,
|
|
833
|
+
margin: row.margin,
|
|
834
|
+
});
|
|
835
|
+
}
|
|
836
|
+
return this.replacePositionSeeds(seeds);
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
private replacePositionSeeds(
|
|
840
|
+
seeds: Array<{
|
|
841
|
+
instrumentId: string; isLong: boolean; hedgeFlag: string;
|
|
842
|
+
volume: number; margin: number;
|
|
843
|
+
}>
|
|
298
844
|
): this {
|
|
299
|
-
|
|
300
|
-
|
|
845
|
+
for (let attempt = 0; attempt < 5; attempt++) {
|
|
846
|
+
const revision: number = this.native.riskRevision();
|
|
847
|
+
if (this.native.replacePositions(seeds, revision) as boolean)
|
|
848
|
+
return this;
|
|
849
|
+
}
|
|
850
|
+
throw new Error("position snapshot could not stabilize; live state kept unchanged");
|
|
301
851
|
}
|
|
302
852
|
|
|
303
|
-
/**
|
|
304
|
-
*
|
|
305
|
-
*
|
|
306
|
-
* sum both sides so the bucket doesn't matter for them, but a per-side *volume*
|
|
307
|
-
* cap on a net-mode instrument would track the wrong side — for net-mode
|
|
308
|
-
* accounts, seed those via seedPosition() with the side you intend. */
|
|
853
|
+
/** Atomically replace held position margin from complete gross-mode query rows
|
|
854
|
+
* (`posiDirection` '2' long, '3' short). Net/unknown direction is rejected
|
|
855
|
+
* because guessing a side corrupts per-side volume caps. */
|
|
309
856
|
seedFromPositions(
|
|
310
857
|
positions: ReadonlyArray<{
|
|
311
858
|
instrumentId: string;
|
|
312
859
|
posiDirection: string;
|
|
860
|
+
hedgeFlag: string;
|
|
313
861
|
position: number;
|
|
314
862
|
useMargin: number;
|
|
315
863
|
}>
|
|
316
864
|
): this {
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
865
|
+
const seeds = this.aggregatePositions(positions);
|
|
866
|
+
// Native callbacks can mutate the ledger concurrently even though this JS
|
|
867
|
+
// method is synchronous. Retry a revision-checked replacement rather than
|
|
868
|
+
// expose a clear-then-seed gap or overwrite a callback that raced us.
|
|
869
|
+
return this.replacePositionSeeds(seeds);
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
private aggregatePositions(
|
|
873
|
+
positions: ReadonlyArray<{
|
|
874
|
+
instrumentId: string;
|
|
875
|
+
posiDirection: string;
|
|
876
|
+
hedgeFlag: string;
|
|
877
|
+
position: number;
|
|
878
|
+
useMargin: number;
|
|
879
|
+
}>
|
|
880
|
+
): Array<{ instrumentId: string; isLong: boolean; hedgeFlag: string; volume: number; margin: number }> {
|
|
881
|
+
// Aggregate by instrument+side+hedge flag (CTP may return several rows per
|
|
882
|
+
// bucket, e.g. today/history). Different hedge flags can have different
|
|
883
|
+
// margin schedules and must never be averaged together on close.
|
|
884
|
+
if (!Array.isArray(positions))
|
|
885
|
+
throw new TypeError("position snapshot must be an array");
|
|
886
|
+
const agg = new Map<string, { instrumentId: string; isLong: boolean; hedgeFlag: string; volume: number; margin: number }>();
|
|
887
|
+
const positionCount = positions.length;
|
|
888
|
+
for (let i = 0; i < positionCount; i++) {
|
|
889
|
+
if (!Object.prototype.hasOwnProperty.call(positions, i))
|
|
890
|
+
throw new TypeError(`position snapshot row ${i} must be an explicit array entry`);
|
|
891
|
+
const p = positions[i];
|
|
892
|
+
const plain = p !== null && typeof p === "object" && !Array.isArray(p) &&
|
|
893
|
+
(Object.getPrototypeOf(p) === Object.prototype || Object.getPrototypeOf(p) === null);
|
|
894
|
+
const row = plain ? copyOwnRecord(p, "position snapshot row") : undefined;
|
|
895
|
+
if (!row || typeof row.instrumentId !== "string" || !row.instrumentId ||
|
|
896
|
+
row.instrumentId.includes("\0") ||
|
|
897
|
+
!Number.isInteger(row.position) || row.position < 0 ||
|
|
898
|
+
!Number.isFinite(row.useMargin) || row.useMargin < 0 ||
|
|
899
|
+
(row.posiDirection !== "2" && row.posiDirection !== "3") ||
|
|
900
|
+
typeof row.hedgeFlag !== "string" ||
|
|
901
|
+
!/^[123567]$/.test(row.hedgeFlag)) {
|
|
902
|
+
throw new TypeError(`invalid position snapshot for ${row?.instrumentId || "<unknown>"}`);
|
|
903
|
+
}
|
|
904
|
+
if (!(row.position > 0)) continue;
|
|
905
|
+
const isLong = row.posiDirection === "2";
|
|
906
|
+
const key = `${row.instrumentId}|${isLong}|${row.hedgeFlag}`;
|
|
907
|
+
const e = agg.get(key) ?? { instrumentId: row.instrumentId, isLong, hedgeFlag: row.hedgeFlag, volume: 0, margin: 0 };
|
|
908
|
+
const volume = e.volume + row.position;
|
|
909
|
+
const margin = e.margin + row.useMargin;
|
|
910
|
+
if (!Number.isSafeInteger(volume) || !Number.isFinite(margin)) {
|
|
911
|
+
throw new RangeError(`position snapshot overflow for ${row.instrumentId}`);
|
|
912
|
+
}
|
|
913
|
+
e.volume = volume;
|
|
914
|
+
e.margin = margin; // real margin occupied (the unit the cap tracks)
|
|
326
915
|
agg.set(key, e);
|
|
327
916
|
}
|
|
328
|
-
|
|
329
|
-
return this;
|
|
917
|
+
return [...agg.values()];
|
|
330
918
|
}
|
|
331
919
|
|
|
332
|
-
/** Current total open-position
|
|
333
|
-
|
|
334
|
-
return this.native.
|
|
920
|
+
/** Current total open-position margin tracked by the C++ risk engine. */
|
|
921
|
+
get accountMargin(): number {
|
|
922
|
+
return this.native.accountMargin();
|
|
335
923
|
}
|
|
336
924
|
|
|
337
|
-
/** Clear
|
|
925
|
+
/** Clear held position state only and mark it uncertain. Working-order
|
|
926
|
+
* reservations are preserved; openings remain blocked until a complete
|
|
927
|
+
* seedFromPositions() or syncPositions() succeeds. */
|
|
338
928
|
resetPositions(): this {
|
|
339
929
|
this.native.resetPositions();
|
|
340
930
|
return this;
|
|
@@ -351,20 +941,47 @@ export class Trader extends TraderBase {
|
|
|
351
941
|
private async queryWithRetry<T>(
|
|
352
942
|
query: () => Promise<T[]>,
|
|
353
943
|
requireNonEmpty: boolean,
|
|
944
|
+
contextToken: number,
|
|
354
945
|
attempts = 5
|
|
355
946
|
): Promise<T[]> {
|
|
356
947
|
let lastErr: unknown;
|
|
357
948
|
for (let i = 0; i < attempts; i++) {
|
|
358
|
-
if (i > 0) await sleep(1100); // respect the ~1/sec query limit
|
|
359
949
|
try {
|
|
950
|
+
this.assertRequestContext(contextToken, "query synchronization");
|
|
951
|
+
// Every generated ReqQry* / ReqQuery* goes through queryRequest(), whose
|
|
952
|
+
// shared scheduler enforces the interval. Do not sleep here as well or
|
|
953
|
+
// retries are needlessly spaced twice.
|
|
360
954
|
const rows = await query();
|
|
955
|
+
this.assertRequestContext(contextToken, "query synchronization");
|
|
361
956
|
if (!requireNonEmpty || rows.length > 0) return rows;
|
|
362
957
|
} catch (e) {
|
|
363
|
-
|
|
958
|
+
this.assertRequestContext(contextToken, "query synchronization");
|
|
959
|
+
// Native send codes -2/-3 are the CTP transient flow-control cases.
|
|
960
|
+
// Do not turn a permanent validation/business/disconnect failure into
|
|
961
|
+
// five delayed copies of the same request.
|
|
962
|
+
const code = (e as { ctpReturnCode?: unknown })?.ctpReturnCode;
|
|
963
|
+
if (code !== -2 && code !== -3) throw e;
|
|
964
|
+
lastErr = e;
|
|
364
965
|
}
|
|
365
966
|
}
|
|
366
967
|
if (lastErr) throw lastErr;
|
|
367
|
-
|
|
968
|
+
if (requireNonEmpty)
|
|
969
|
+
throw new Error(`CTP query returned no rows after ${attempts} attempts`);
|
|
970
|
+
/* c8 ignore next -- fixed positive attempts make this an internal invariant */
|
|
971
|
+
throw new Error("query retry invariant violated");
|
|
972
|
+
}
|
|
973
|
+
|
|
974
|
+
/** Empty position/order snapshots are ambiguous immediately after login. Require
|
|
975
|
+
* the same empty result twice, one query interval apart, before treating it as
|
|
976
|
+
* authoritative. */
|
|
977
|
+
private async authoritativeQuery<T>(
|
|
978
|
+
query: () => Promise<T[]>,
|
|
979
|
+
contextToken: number
|
|
980
|
+
): Promise<T[]> {
|
|
981
|
+
const first = await this.queryWithRetry(query, false, contextToken);
|
|
982
|
+
if (first.length > 0) return first;
|
|
983
|
+
// The scheduler spaces this confirmation request from the first one.
|
|
984
|
+
return this.queryWithRetry(query, false, contextToken);
|
|
368
985
|
}
|
|
369
986
|
|
|
370
987
|
/** Query instruments so the C++ risk engine picks up their multipliers (it
|
|
@@ -372,41 +989,167 @@ export class Trader extends TraderBase {
|
|
|
372
989
|
* all instruments (one request); otherwise the given symbols. Retries through
|
|
373
990
|
* cold-start flow control. Returns the count of contracts with a multiplier. */
|
|
374
991
|
async syncMultipliers(instrumentIds?: string[]): Promise<number> {
|
|
992
|
+
const contextToken = this.requestContextToken();
|
|
993
|
+
if (instrumentIds !== undefined) {
|
|
994
|
+
instrumentIds = copyDenseStringArray(
|
|
995
|
+
instrumentIds, "syncMultipliers instrumentIds"
|
|
996
|
+
);
|
|
997
|
+
if (instrumentIds.length === 0)
|
|
998
|
+
return 0; // explicit empty universe; only omitted means "query all"
|
|
999
|
+
}
|
|
375
1000
|
let count = 0;
|
|
376
1001
|
const apply = (rows: unknown[]) => {
|
|
377
|
-
|
|
378
|
-
|
|
1002
|
+
const finalByInstrument = new Map<string, { instrumentId: string; volumeMultiple: number }>();
|
|
1003
|
+
for (const r of rows as Array<{ instrumentId: string; volumeMultiple: number }>)
|
|
1004
|
+
finalByInstrument.set(r.instrumentId, r);
|
|
1005
|
+
for (const r of finalByInstrument.values()) {
|
|
1006
|
+
if (r.instrumentId && Number.isFinite(r.volumeMultiple) &&
|
|
1007
|
+
r.volumeMultiple > 0 && r.volumeMultiple < 1e300) count++;
|
|
379
1008
|
}
|
|
380
1009
|
};
|
|
381
|
-
if (instrumentIds
|
|
382
|
-
for (
|
|
383
|
-
apply(await this.queryWithRetry(() =>
|
|
384
|
-
|
|
1010
|
+
if (instrumentIds) {
|
|
1011
|
+
for (const instrumentId of new Set(instrumentIds)) {
|
|
1012
|
+
apply(await this.queryWithRetry(async () =>
|
|
1013
|
+
((await this.reqQryInstrument({ instrumentId })) as Array<{
|
|
1014
|
+
instrumentId: string; volumeMultiple: number;
|
|
1015
|
+
}>).filter((row) => row.instrumentId === instrumentId), true, contextToken));
|
|
385
1016
|
}
|
|
386
1017
|
} else {
|
|
387
|
-
apply(await this.queryWithRetry(
|
|
1018
|
+
apply(await this.queryWithRetry(
|
|
1019
|
+
() => this.reqQryInstrument({}), true, contextToken
|
|
1020
|
+
));
|
|
388
1021
|
}
|
|
389
1022
|
return count;
|
|
390
1023
|
}
|
|
391
1024
|
|
|
392
|
-
/**
|
|
393
|
-
*
|
|
394
|
-
*
|
|
395
|
-
async
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
))
|
|
1025
|
+
/** Query investor margin schedules for a bounded universe. The exchange-base
|
|
1026
|
+
* query is issued only when the investor row is relative; the shared query
|
|
1027
|
+
* scheduler enforces spacing. Returns the number of usable schedules. */
|
|
1028
|
+
async syncMarginRates(
|
|
1029
|
+
instrumentIds: string[],
|
|
1030
|
+
hedgeFlag: "1" | "2" | "3" | "5" | "6" | "7" = "1"
|
|
1031
|
+
): Promise<number> {
|
|
1032
|
+
const contextToken = this.requestContextToken();
|
|
1033
|
+
instrumentIds = copyDenseStringArray(instrumentIds, "syncMarginRates", false);
|
|
1034
|
+
if (typeof hedgeFlag !== "string" || !/^[123567]$/.test(hedgeFlag)) {
|
|
1035
|
+
throw new TypeError("syncMarginRates hedgeFlag must be 1, 2, 3, 5, 6 or 7");
|
|
1036
|
+
}
|
|
1037
|
+
const brokerId = this.broker;
|
|
1038
|
+
const investorId = this.investor;
|
|
1039
|
+
if (!brokerId || !investorId) {
|
|
1040
|
+
throw new Error("syncMarginRates requires a successful trader login first");
|
|
1041
|
+
}
|
|
1042
|
+
let count = 0;
|
|
1043
|
+
for (const instrumentId of new Set(instrumentIds)) {
|
|
1044
|
+
type InvestorMarginRow = {
|
|
1045
|
+
instrumentId: string;
|
|
1046
|
+
hedgeFlag: string;
|
|
1047
|
+
isRelative: number;
|
|
1048
|
+
longMarginRatioByMoney: number;
|
|
1049
|
+
longMarginRatioByVolume: number;
|
|
1050
|
+
shortMarginRatioByMoney: number;
|
|
1051
|
+
shortMarginRatioByVolume: number;
|
|
1052
|
+
};
|
|
1053
|
+
const investorRows = await this.queryWithRetry(async () =>
|
|
1054
|
+
((await this.reqQryInstrumentMarginRate({
|
|
1055
|
+
brokerId,
|
|
1056
|
+
investorId,
|
|
1057
|
+
instrumentId,
|
|
1058
|
+
hedgeFlag,
|
|
1059
|
+
})) as InvestorMarginRow[]).filter(
|
|
1060
|
+
(row) => row.instrumentId === instrumentId && row.hedgeFlag === hedgeFlag
|
|
1061
|
+
), true, contextToken);
|
|
1062
|
+
// The native map is keyed by instrument+hedge and processes callbacks in
|
|
1063
|
+
// order, so its final state is the final row, not "any usable row".
|
|
1064
|
+
const investor = investorRows.at(-1)!;
|
|
1065
|
+
const relative = investor.isRelative !== 0;
|
|
1066
|
+
type ExchangeMarginRow = {
|
|
1067
|
+
instrumentId: string;
|
|
1068
|
+
hedgeFlag: string;
|
|
1069
|
+
longMarginRatioByMoney: number;
|
|
1070
|
+
longMarginRatioByVolume: number;
|
|
1071
|
+
shortMarginRatioByMoney: number;
|
|
1072
|
+
shortMarginRatioByVolume: number;
|
|
1073
|
+
};
|
|
1074
|
+
const baseRows = relative
|
|
1075
|
+
? await this.queryWithRetry(async () =>
|
|
1076
|
+
((await this.reqQryExchangeMarginRate({
|
|
1077
|
+
brokerId,
|
|
1078
|
+
instrumentId,
|
|
1079
|
+
hedgeFlag,
|
|
1080
|
+
})) as ExchangeMarginRow[]).filter(
|
|
1081
|
+
(row) => row.instrumentId === instrumentId && row.hedgeFlag === hedgeFlag
|
|
1082
|
+
), true, contextToken)
|
|
1083
|
+
: [];
|
|
1084
|
+
const base = baseRows.at(-1);
|
|
1085
|
+
const component = (value: number) =>
|
|
1086
|
+
Number.isFinite(value) && value >= 0 && value < 1e300;
|
|
1087
|
+
const scheduleUsable = (row: {
|
|
1088
|
+
longMarginRatioByMoney: number;
|
|
1089
|
+
longMarginRatioByVolume: number;
|
|
1090
|
+
shortMarginRatioByMoney: number;
|
|
1091
|
+
shortMarginRatioByVolume: number;
|
|
1092
|
+
} | undefined) => !!row &&
|
|
1093
|
+
component(row.longMarginRatioByMoney) &&
|
|
1094
|
+
component(row.longMarginRatioByVolume) &&
|
|
1095
|
+
component(row.shortMarginRatioByMoney) &&
|
|
1096
|
+
component(row.shortMarginRatioByVolume) &&
|
|
1097
|
+
(row.longMarginRatioByMoney > 0 || row.longMarginRatioByVolume > 0) &&
|
|
1098
|
+
(row.shortMarginRatioByMoney > 0 || row.shortMarginRatioByVolume > 0);
|
|
1099
|
+
const investorComponentsValid =
|
|
1100
|
+
component(investor.longMarginRatioByMoney) &&
|
|
1101
|
+
component(investor.longMarginRatioByVolume) &&
|
|
1102
|
+
component(investor.shortMarginRatioByMoney) &&
|
|
1103
|
+
component(investor.shortMarginRatioByVolume);
|
|
1104
|
+
if (investorComponentsValid &&
|
|
1105
|
+
(relative ? scheduleUsable(base) : scheduleUsable(investor)))
|
|
1106
|
+
count++;
|
|
1107
|
+
}
|
|
1108
|
+
return count;
|
|
1109
|
+
}
|
|
1110
|
+
|
|
1111
|
+
/** Replace held position margin from CTP (`reqQryInvestorPosition`). The
|
|
1112
|
+
* replacement is revision-checked: if an order/trade callback races the
|
|
1113
|
+
* snapshot it retries without clearing live state or reservations. */
|
|
1114
|
+
async syncPositions(): Promise<number> {
|
|
1115
|
+
const contextToken = this.requestContextToken();
|
|
1116
|
+
if (arguments.length !== 0)
|
|
1117
|
+
throw new TypeError("syncPositions does not accept account overrides");
|
|
1118
|
+
const brokerId = this.broker;
|
|
1119
|
+
const investorId = this.investor;
|
|
1120
|
+
if (typeof brokerId !== "string" || !brokerId || brokerId.includes("\0") ||
|
|
1121
|
+
typeof investorId !== "string" || !investorId || investorId.includes("\0"))
|
|
1122
|
+
throw new Error("syncPositions requires a successful trader login");
|
|
1123
|
+
this.native._markPositionLedgerUncertain();
|
|
1124
|
+
type PositionRow = {
|
|
1125
|
+
brokerId: string;
|
|
1126
|
+
investorId: string;
|
|
402
1127
|
instrumentId: string;
|
|
403
1128
|
posiDirection: string;
|
|
404
1129
|
position: number;
|
|
405
1130
|
useMargin: number;
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
1131
|
+
hedgeFlag: string;
|
|
1132
|
+
};
|
|
1133
|
+
for (let attempt = 0; attempt < 5; attempt++) {
|
|
1134
|
+
this.assertRequestContext(contextToken, "position synchronization");
|
|
1135
|
+
const revision: number = this.native.riskRevision();
|
|
1136
|
+
const rows = await this.authoritativeQuery(async () => {
|
|
1137
|
+
const result = (await this.reqQryInvestorPosition({ brokerId, investorId })) as
|
|
1138
|
+
PositionRow[];
|
|
1139
|
+
if (result.some((row) => row.brokerId !== brokerId ||
|
|
1140
|
+
row.investorId !== investorId)) {
|
|
1141
|
+
throw new Error("position snapshot contains a mismatched account identity");
|
|
1142
|
+
}
|
|
1143
|
+
return result;
|
|
1144
|
+
}, contextToken);
|
|
1145
|
+
const seeds = this.aggregatePositions(rows);
|
|
1146
|
+
this.assertRequestContext(contextToken, "position synchronization");
|
|
1147
|
+
if (this.native.replacePositions(seeds, revision) as boolean)
|
|
1148
|
+
return rows.filter((r) => r.position > 0).length;
|
|
1149
|
+
if (attempt < 4)
|
|
1150
|
+
await sleep(100); // live order/trade changed during the snapshot; retry
|
|
1151
|
+
}
|
|
1152
|
+
throw new Error("position snapshot could not stabilize; live state kept unchanged");
|
|
410
1153
|
}
|
|
411
1154
|
|
|
412
1155
|
/**
|
|
@@ -418,38 +1161,112 @@ export class Trader extends TraderBase {
|
|
|
418
1161
|
* of working open orders re-reserved. Run syncMultipliers() first so the
|
|
419
1162
|
* reserved cost uses the right contract multiplier.
|
|
420
1163
|
*/
|
|
421
|
-
async syncOrders(
|
|
422
|
-
const
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
)
|
|
1164
|
+
async syncOrders(): Promise<number> {
|
|
1165
|
+
const contextToken = this.requestContextToken();
|
|
1166
|
+
if (arguments.length !== 0)
|
|
1167
|
+
throw new TypeError("syncOrders does not accept account overrides");
|
|
1168
|
+
const brokerId = this.broker;
|
|
1169
|
+
const investorId = this.investor;
|
|
1170
|
+
if (typeof brokerId !== "string" || !brokerId || brokerId.includes("\0") ||
|
|
1171
|
+
typeof investorId !== "string" || !investorId || investorId.includes("\0"))
|
|
1172
|
+
throw new Error("syncOrders requires a successful trader login");
|
|
1173
|
+
// Order snapshots must precede the final held-position snapshot. Mark both
|
|
1174
|
+
// sides uncertain so calling syncPositions()->syncOrders() in the unsafe
|
|
1175
|
+
// order cannot reopen trading; a later syncPositions() is required.
|
|
1176
|
+
this.native._markPositionLedgerUncertain();
|
|
1177
|
+
this.native._markOrderLedgerUncertain();
|
|
1178
|
+
type OrderRow = {
|
|
1179
|
+
brokerId: string;
|
|
1180
|
+
investorId: string;
|
|
428
1181
|
frontId: number;
|
|
429
1182
|
sessionId: number;
|
|
430
1183
|
orderRef: string;
|
|
1184
|
+
tradingDay: string;
|
|
1185
|
+
exchangeId: string;
|
|
1186
|
+
orderSysId: string;
|
|
431
1187
|
instrumentId: string;
|
|
432
1188
|
combOffsetFlag: string;
|
|
433
1189
|
direction: string;
|
|
1190
|
+
combHedgeFlag: string;
|
|
434
1191
|
orderStatus: string;
|
|
435
1192
|
limitPrice: number;
|
|
436
1193
|
volumeTotalOriginal: number;
|
|
437
1194
|
volumeTraded: number;
|
|
438
|
-
}
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
.
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
})
|
|
451
|
-
|
|
452
|
-
|
|
1195
|
+
};
|
|
1196
|
+
for (let attempt = 0; attempt < 5; attempt++) {
|
|
1197
|
+
this.assertRequestContext(contextToken, "order synchronization");
|
|
1198
|
+
const revision: number = this.native.riskRevision();
|
|
1199
|
+
const rows = await this.authoritativeQuery(async () => {
|
|
1200
|
+
const result = (await this.reqQryOrder({ brokerId, investorId })) as
|
|
1201
|
+
OrderRow[];
|
|
1202
|
+
if (result.some((row) => row.brokerId !== brokerId ||
|
|
1203
|
+
row.investorId !== investorId)) {
|
|
1204
|
+
throw new Error("order snapshot contains a mismatched account identity");
|
|
1205
|
+
}
|
|
1206
|
+
return result;
|
|
1207
|
+
}, contextToken);
|
|
1208
|
+
// Every status except the four definitive terminals is still live. This
|
|
1209
|
+
// includes conditional Unknown/NotTouched/Touched ('a'/'b'/'c').
|
|
1210
|
+
const terminal = new Set(["0", "2", "4", "5"]);
|
|
1211
|
+
const active = rows.filter((o) => !terminal.has(o.orderStatus));
|
|
1212
|
+
for (const o of active) {
|
|
1213
|
+
const vol = o.volumeTotalOriginal - o.volumeTraded;
|
|
1214
|
+
if (!Number.isInteger(o.frontId) || !Number.isInteger(o.sessionId) ||
|
|
1215
|
+
!o.orderRef || !o.instrumentId ||
|
|
1216
|
+
(o.direction !== "0" && o.direction !== "1") ||
|
|
1217
|
+
typeof o.combOffsetFlag !== "string" ||
|
|
1218
|
+
typeof o.combHedgeFlag !== "string" ||
|
|
1219
|
+
!Number.isInteger(o.volumeTotalOriginal) ||
|
|
1220
|
+
!Number.isInteger(o.volumeTraded) || o.volumeTraded < 0 ||
|
|
1221
|
+
o.volumeTraded > o.volumeTotalOriginal ||
|
|
1222
|
+
!Number.isInteger(vol) || vol < 0 ||
|
|
1223
|
+
!Number.isFinite(o.limitPrice) || o.limitPrice < 0 ||
|
|
1224
|
+
(o.orderSysId && !o.exchangeId) ||
|
|
1225
|
+
(/^[0-6]$/.test(o.combOffsetFlag) &&
|
|
1226
|
+
!/^[123567]$/.test(o.combHedgeFlag))) {
|
|
1227
|
+
throw new TypeError(`invalid working-order snapshot for ${o.orderRef || "<unknown>"}`);
|
|
1228
|
+
}
|
|
1229
|
+
}
|
|
1230
|
+
const working = active.flatMap((o) => {
|
|
1231
|
+
const vol = o.volumeTotalOriginal - o.volumeTraded;
|
|
1232
|
+
const supportedSingleLeg = /^[0-6]$/.test(o.combOffsetFlag);
|
|
1233
|
+
if (supportedSingleLeg && o.combOffsetFlag !== "0")
|
|
1234
|
+
return []; // a representable close order adds no opening exposure
|
|
1235
|
+
return [{
|
|
1236
|
+
frontId: o.frontId,
|
|
1237
|
+
sessionId: o.sessionId,
|
|
1238
|
+
orderRef: o.orderRef,
|
|
1239
|
+
instrumentId: o.instrumentId,
|
|
1240
|
+
isLong: o.direction === "0",
|
|
1241
|
+
hedgeFlag: o.combHedgeFlag?.[0] || "1",
|
|
1242
|
+
vol,
|
|
1243
|
+
price: o.limitPrice,
|
|
1244
|
+
traded: o.volumeTraded,
|
|
1245
|
+
// Must be byte-identical to the native realtime key built in
|
|
1246
|
+
// traderspi.gen.cc (OnRtnOrder/OnRtnTrade):
|
|
1247
|
+
// day|broker|investor|exchange|instrument|orderSysId. broker/investor
|
|
1248
|
+
// are the confirmed session identity (validated == every row above),
|
|
1249
|
+
// so a reservation rebuilt on resync correlates with the subsequent
|
|
1250
|
+
// realtime order/trade callbacks instead of being stranded uncertain.
|
|
1251
|
+
orderSysKey: o.tradingDay && o.exchangeId && o.orderSysId
|
|
1252
|
+
? `${o.tradingDay}|${brokerId}|${investorId}|${o.exchangeId}|${o.instrumentId}|${o.orderSysId}`
|
|
1253
|
+
: "",
|
|
1254
|
+
supportedSingleLeg,
|
|
1255
|
+
}];
|
|
1256
|
+
});
|
|
1257
|
+
this.assertRequestContext(contextToken, "order synchronization");
|
|
1258
|
+
if (this.native.rebuildReservations(working, revision) as boolean) {
|
|
1259
|
+
const unsupported = working.filter((o) => !o.supportedSingleLeg);
|
|
1260
|
+
if (unsupported.length > 0) {
|
|
1261
|
+
throw new Error(
|
|
1262
|
+
`unsupported working order ${unsupported[0].orderRef}; opening inserts are fail-closed`
|
|
1263
|
+
);
|
|
1264
|
+
}
|
|
1265
|
+
return working.length;
|
|
1266
|
+
}
|
|
1267
|
+
if (attempt < 4) await sleep(100);
|
|
1268
|
+
}
|
|
1269
|
+
throw new Error("order snapshot could not stabilize; live state kept unchanged");
|
|
453
1270
|
}
|
|
454
1271
|
|
|
455
1272
|
/**
|
|
@@ -460,24 +1277,38 @@ export class Trader extends TraderBase {
|
|
|
460
1277
|
*/
|
|
461
1278
|
arm(md: MarketData, spec: ArmSpec): ArmHandle {
|
|
462
1279
|
// Validate up front: the order fires from C++ with no JS in the loop, so a
|
|
463
|
-
// malformed template
|
|
464
|
-
|
|
465
|
-
|
|
1280
|
+
// malformed template cannot reach the callback-thread send path.
|
|
1281
|
+
const cleanSpec = copyOwnRecord(spec, "arm spec");
|
|
1282
|
+
assertObjectKeys(cleanSpec, "arm spec", ARM_SPEC_KEYS);
|
|
1283
|
+
if (!cleanSpec.instrumentId || cleanSpec.instrumentId.includes("\0") ||
|
|
1284
|
+
!Number.isFinite(cleanSpec.triggerPrice) || !(cleanSpec.triggerPrice > 0) ||
|
|
1285
|
+
cleanSpec.triggerPrice >= 1e300) {
|
|
466
1286
|
throw new Error("arm: spec.instrumentId and a positive triggerPrice are required");
|
|
467
1287
|
}
|
|
468
|
-
const
|
|
469
|
-
if (
|
|
470
|
-
|
|
471
|
-
throw new Error("arm: spec.order needs instrumentId, direction, combOffsetFlag and volumeTotalOriginal > 0");
|
|
1288
|
+
const validatedOrder = this.validateOrder(cleanSpec.order, "arm.order");
|
|
1289
|
+
if (cleanSpec.side !== "buy" && cleanSpec.side !== "sell") {
|
|
1290
|
+
throw new Error("arm: spec.side must be buy or sell");
|
|
472
1291
|
}
|
|
473
|
-
|
|
1292
|
+
if (validatedOrder.instrumentId !== cleanSpec.instrumentId) {
|
|
1293
|
+
throw new Error("arm: spec.instrumentId must match spec.order.instrumentId");
|
|
1294
|
+
}
|
|
1295
|
+
if ((cleanSpec.side === "buy") !== (validatedOrder.direction === "0")) {
|
|
1296
|
+
throw new Error("arm: spec.side must match spec.order.direction");
|
|
1297
|
+
}
|
|
1298
|
+
const order = this.withAutoOrderRef(validatedOrder);
|
|
474
1299
|
const bytes = this.encode(STRUCT_ID.InputOrder, order as Record<string, unknown>);
|
|
1300
|
+
md.attachArm(this);
|
|
1301
|
+
// The triggering feed is also the authoritative fresh-price source for
|
|
1302
|
+
// deviation/notional/margin checks. Without this wiring an armed order can
|
|
1303
|
+
// see the trigger tick yet fail every monetary gate as "no reference".
|
|
1304
|
+
this.trackMarketData(md);
|
|
475
1305
|
const id: number = this.native.arm(
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
1306
|
+
cleanSpec.instrumentId,
|
|
1307
|
+
cleanSpec.side === "buy" ? "0" : "1",
|
|
1308
|
+
cleanSpec.triggerPrice,
|
|
479
1309
|
bytes
|
|
480
1310
|
);
|
|
1311
|
+
this.commitOrderRef(order);
|
|
481
1312
|
return { id, disarm: () => this.native.disarm(id) as boolean };
|
|
482
1313
|
}
|
|
483
1314
|
|
|
@@ -485,7 +1316,7 @@ export class Trader extends TraderBase {
|
|
|
485
1316
|
* how many fired and were sent vs were refused by the risk gate / send.
|
|
486
1317
|
* A blocked armed order is otherwise invisible, so poll this after a trigger
|
|
487
1318
|
* you expected to fire. */
|
|
488
|
-
armStats(): { fired: number; blocked: number } {
|
|
1319
|
+
get armStats(): { fired: number; blocked: number } {
|
|
489
1320
|
return { fired: this.native._armFireCount(), blocked: this.native._armBlockedCount() };
|
|
490
1321
|
}
|
|
491
1322
|
|
|
@@ -508,8 +1339,8 @@ export class Trader extends TraderBase {
|
|
|
508
1339
|
on(event: "rtn-trade", cb: (data: Trade, opts: CallbackOptions) => void): this;
|
|
509
1340
|
on(event: "front-connected", cb: (data: undefined, opts: CallbackOptions) => void): this;
|
|
510
1341
|
on(event: "front-disconnected", cb: (reason: number, opts: CallbackOptions) => void): this;
|
|
511
|
-
on(event: "rsp-user-login", cb: (data: RspUserLogin, opts: CallbackOptions) => void): this;
|
|
512
|
-
on(event: "err-rtn-order-insert", cb: (data: InputOrder, opts: CallbackOptions) => void): this;
|
|
1342
|
+
on(event: "rsp-user-login", cb: (data: RspUserLogin | undefined, opts: CallbackOptions) => void): this;
|
|
1343
|
+
on(event: "err-rtn-order-insert", cb: (data: InputOrder | undefined, opts: CallbackOptions) => void): this;
|
|
513
1344
|
on(event: string, cb: (...args: never[]) => void): this;
|
|
514
1345
|
on(event: string, cb: (...args: never[]) => void): this {
|
|
515
1346
|
return super.on(event, cb as (...args: unknown[]) => void);
|