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