@flexemarkets/fm-sdk 0.11.0 → 0.13.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/README.md +2 -2
- package/dist/client.d.ts +67 -3
- package/dist/client.js +172 -26
- package/dist/client.js.map +1 -1
- package/dist/decimals.d.ts +52 -0
- package/dist/decimals.js +86 -0
- package/dist/decimals.js.map +1 -0
- package/dist/first-robot.d.ts +1 -1
- package/dist/first-robot.js +1 -1
- package/dist/first-robot.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/order-utils.js +2 -0
- package/dist/order-utils.js.map +1 -1
- package/dist/stomp.d.ts +21 -3
- package/dist/stomp.js +70 -3
- package/dist/stomp.js.map +1 -1
- package/dist/ticker.js +10 -7
- package/dist/ticker.js.map +1 -1
- package/dist/types.d.ts +42 -2
- package/dist/types.js +20 -3
- package/dist/types.js.map +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -118,8 +118,8 @@ fm-ticker OPEN
|
|
|
118
118
|
|
|
119
119
|
Symbol Bid Ask Spread Last trades
|
|
120
120
|
------ ------ ------ ------ -----------
|
|
121
|
-
AAPL
|
|
122
|
-
IBM
|
|
121
|
+
AAPL 9.50 10.50 1.00 9.50 10.00
|
|
122
|
+
IBM 4.00 5.00 1.00 4.50
|
|
123
123
|
```
|
|
124
124
|
|
|
125
125
|
The display refreshes on each order book update. Press `Ctrl-C` to stop.
|
package/dist/client.d.ts
CHANGED
|
@@ -8,7 +8,19 @@ import { EventListener, type EventCallback } from "./stomp.js";
|
|
|
8
8
|
import { type Desk, type Subscription } from "./desk.js";
|
|
9
9
|
import type { Snapshot } from "./snapshot.js";
|
|
10
10
|
export declare const DEFAULT_ENDPOINT = "https://api.flexemarkets.com";
|
|
11
|
+
/**
|
|
12
|
+
* Base of every Flexemarkets error.
|
|
13
|
+
*
|
|
14
|
+
* An error that is the server's answer carries it: `statusCode`, the `body` as
|
|
15
|
+
* sent, and `reason`, the body's `error` -- `SESSION_CLOSED`, `ORDER_INVALID`,
|
|
16
|
+
* `ACCOUNT_TOKEN_EXPIRED` -- which is what a caller branches on, where the
|
|
17
|
+
* message is for people. All three are null for an error the SDK raised
|
|
18
|
+
* itself, and `reason` is null when the body named no error.
|
|
19
|
+
*/
|
|
11
20
|
export declare class FlexemarketsError extends Error {
|
|
21
|
+
statusCode: number | null;
|
|
22
|
+
reason: string | null;
|
|
23
|
+
body: string | null;
|
|
12
24
|
}
|
|
13
25
|
export declare class AuthenticationError extends FlexemarketsError {
|
|
14
26
|
}
|
|
@@ -143,6 +155,12 @@ export declare function loadConfig(): Record<string, string>;
|
|
|
143
155
|
* order carried the whole JSON document.
|
|
144
156
|
*/
|
|
145
157
|
export declare function detail(body: string): string;
|
|
158
|
+
/** How long a request may take, start to finish, before it is given up. */
|
|
159
|
+
export declare const REQUEST_TIMEOUT_MS = 30000;
|
|
160
|
+
/** The timeout in force: {@link REQUEST_TIMEOUT_MS}, unless a test has shortened it. */
|
|
161
|
+
export declare const requestTimeout: {
|
|
162
|
+
ms: number;
|
|
163
|
+
};
|
|
146
164
|
export declare class Flexemarkets {
|
|
147
165
|
private readonly _clientDescription;
|
|
148
166
|
private readonly _endpoint;
|
|
@@ -304,6 +322,8 @@ export declare class Flexemarkets {
|
|
|
304
322
|
* segment. Bytes, not a string, so the file's own encoding survives.
|
|
305
323
|
*/
|
|
306
324
|
private _sendCsv;
|
|
325
|
+
/** CSV as the request body, declared text/csv; see {@link _sendCsv}. */
|
|
326
|
+
private _sendCsvContent;
|
|
307
327
|
/**
|
|
308
328
|
* A V1 route. 0.4 addresses every route from the server rather than through
|
|
309
329
|
* the HAL root's links: the path is knowable without fetching anything
|
|
@@ -343,7 +363,24 @@ export declare class Flexemarkets {
|
|
|
343
363
|
*/
|
|
344
364
|
sessions(marketplaceId: number): Promise<Session[]>;
|
|
345
365
|
session(marketplaceId: number): Promise<Session>;
|
|
346
|
-
|
|
366
|
+
/**
|
|
367
|
+
* Place a limit order.
|
|
368
|
+
*
|
|
369
|
+
* A private market matches an order only with one aimed back at its owner, so
|
|
370
|
+
* an order there names its counterparty: by `ownerTargetId` when the caller
|
|
371
|
+
* knows it, or by `ownerTarget`, the allotment name. The id is the
|
|
372
|
+
* unambiguous one, but only a manager can learn ids -- a participant's
|
|
373
|
+
* `identifiers()` are names -- so a participant has the name and nothing
|
|
374
|
+
* else. Name one or the other, not both.
|
|
375
|
+
*
|
|
376
|
+
* `clientDescription` is this order's own reference, as the server keeps it
|
|
377
|
+
* on the order; it defaults to the description this client connected with.
|
|
378
|
+
*/
|
|
379
|
+
submitLimit(marketplaceId: number, marketId: number, side: string, units: number, price: number, options?: {
|
|
380
|
+
ownerTarget?: string;
|
|
381
|
+
ownerTargetId?: number;
|
|
382
|
+
clientDescription?: string;
|
|
383
|
+
}): Promise<Order>;
|
|
347
384
|
/**
|
|
348
385
|
* Cross the book: buy at the highest price this market allows, sell at the
|
|
349
386
|
* lowest. Immediate or cancel — whatever does not fill is cancelled.
|
|
@@ -484,6 +521,17 @@ export declare class Flexemarkets {
|
|
|
484
521
|
* the same terms as {@link allocate}.
|
|
485
522
|
*/
|
|
486
523
|
uploadHoldings(marketplaceId: number, filename: string): Promise<Holding[]>;
|
|
524
|
+
/**
|
|
525
|
+
* Stage an allocation from holdings CSV text, as {@link uploadHoldings} does
|
|
526
|
+
* from a file.
|
|
527
|
+
*
|
|
528
|
+
* For a program that builds the CSV rather than reading one -- an admin
|
|
529
|
+
* robot writing back the holdings it downloaded and changed -- which
|
|
530
|
+
* otherwise writes a file only to have it read again. The text is sent as it
|
|
531
|
+
* is; a `# holdings -- begin` / `-- end` frame around it is accepted, as in a
|
|
532
|
+
* downloaded file.
|
|
533
|
+
*/
|
|
534
|
+
uploadHoldingsCsv(marketplaceId: number, csv: string): Promise<Holding[]>;
|
|
487
535
|
/**
|
|
488
536
|
* Load per-participant private state from a CSV, returning what was stored.
|
|
489
537
|
*
|
|
@@ -531,6 +579,10 @@ export declare class Flexemarkets {
|
|
|
531
579
|
/**
|
|
532
580
|
* Every widget pushed to the marketplace and still standing, for every
|
|
533
581
|
* participant -- what a manager reads to check on a robot.
|
|
582
|
+
*
|
|
583
|
+
* The answer is the frame every widgets read answers, `{marketplaceId,
|
|
584
|
+
* snapshot, widgets, removed}`; a bare list, which `widgets/all` answered
|
|
585
|
+
* and 0.4.0 to 0.11.0 expected here, is read too.
|
|
534
586
|
*/
|
|
535
587
|
allWidgets(marketplaceId: number): Promise<Widget[]>;
|
|
536
588
|
/**
|
|
@@ -607,15 +659,27 @@ export declare class Flexemarkets {
|
|
|
607
659
|
* Returns an unsubscribe function rather than an object with `close()`,
|
|
608
660
|
* matching what Desk's `on*` handlers already return here. Java
|
|
609
661
|
* returns a `Subscription`; both names describe the same lifetime.
|
|
662
|
+
*
|
|
663
|
+
* With `history`, the first orders update is every order of the current
|
|
664
|
+
* session as this caller may see it -- cancelled and split ones included, a
|
|
665
|
+
* counterparty's private order named from the caller's side -- stamped with
|
|
666
|
+
* the `seq` it was read at, and each reconnect delivers it again. That is
|
|
667
|
+
* fm-server's original subscribe, and the only whole history a participant
|
|
668
|
+
* can read: the REST history is a manager's. Without it the first update is
|
|
669
|
+
* empty and the book comes from `activeOrders`. A history is one frame, so on
|
|
670
|
+
* a session with a very long one it is a large frame -- fm-server's V1
|
|
671
|
+
* subscribe exists to avoid exactly that.
|
|
610
672
|
*/
|
|
611
|
-
subscribe(marketplaceId: number, callback: EventCallback
|
|
673
|
+
subscribe(marketplaceId: number, callback: EventCallback, options?: {
|
|
674
|
+
history?: boolean;
|
|
675
|
+
}): Promise<Subscription>;
|
|
612
676
|
/**
|
|
613
677
|
* Package-private helper used by {@link DefaultDesk} (Phase 2d)
|
|
614
678
|
* to own its own EventListener subscription rather than clobbering
|
|
615
679
|
* the singleton {@link #_eventListener}. Lets multiple
|
|
616
680
|
* desk(marketplaceId) calls coexist within one Flexemarkets.
|
|
617
681
|
*/
|
|
618
|
-
_connectEvents(marketplaceId: number, callback: EventCallback): Promise<EventListener>;
|
|
682
|
+
_connectEvents(marketplaceId: number, callback: EventCallback, history?: boolean): Promise<EventListener>;
|
|
619
683
|
/** Reconnect the WebSocket after a transport error. */
|
|
620
684
|
reconnect(): Promise<void>;
|
|
621
685
|
close(): void;
|
package/dist/client.js
CHANGED
|
@@ -3,11 +3,13 @@
|
|
|
3
3
|
*
|
|
4
4
|
* Port of fm.client (Python) / fm.Flexemarkets (Java).
|
|
5
5
|
*/
|
|
6
|
+
import { randomUUID } from "node:crypto";
|
|
6
7
|
import { readFileSync, existsSync } from "node:fs";
|
|
7
8
|
import { homedir } from "node:os";
|
|
8
9
|
import { join } from "node:path";
|
|
9
10
|
import { MARKET_MECHANISM_CALL, MARKET_MECHANISM_CONTINUOUS, orderedSecurities, toOrderType, toSide, unitGrid } from "./types.js";
|
|
10
11
|
import { toInstant } from "./timestamps.js";
|
|
12
|
+
import { Decimals } from "./decimals.js";
|
|
11
13
|
import { EventListener, NO_SEQ } from "./stomp.js";
|
|
12
14
|
import { DefaultDesk, DeskHandle, } from "./desk.js";
|
|
13
15
|
import { readVersion } from "./version.js";
|
|
@@ -30,7 +32,19 @@ const JWT_RE = /^[A-Za-z0-9\-_]+\.[A-Za-z0-9\-_]+\.[A-Za-z0-9\-_]+$/;
|
|
|
30
32
|
// ---------------------------------------------------------------------------
|
|
31
33
|
// Errors
|
|
32
34
|
// ---------------------------------------------------------------------------
|
|
35
|
+
/**
|
|
36
|
+
* Base of every Flexemarkets error.
|
|
37
|
+
*
|
|
38
|
+
* An error that is the server's answer carries it: `statusCode`, the `body` as
|
|
39
|
+
* sent, and `reason`, the body's `error` -- `SESSION_CLOSED`, `ORDER_INVALID`,
|
|
40
|
+
* `ACCOUNT_TOKEN_EXPIRED` -- which is what a caller branches on, where the
|
|
41
|
+
* message is for people. All three are null for an error the SDK raised
|
|
42
|
+
* itself, and `reason` is null when the body named no error.
|
|
43
|
+
*/
|
|
33
44
|
export class FlexemarketsError extends Error {
|
|
45
|
+
statusCode = null;
|
|
46
|
+
reason = null;
|
|
47
|
+
body = null;
|
|
34
48
|
}
|
|
35
49
|
export class AuthenticationError extends FlexemarketsError {
|
|
36
50
|
}
|
|
@@ -165,6 +179,7 @@ export function parseSecurity(data) {
|
|
|
165
179
|
shortUnits: data.shortUnits ?? data.initialShortUnits ?? 0,
|
|
166
180
|
canBuy: data.canBuy ?? false,
|
|
167
181
|
canSell: data.canSell ?? false,
|
|
182
|
+
initialUnits: data.initialUnits ?? null,
|
|
168
183
|
};
|
|
169
184
|
}
|
|
170
185
|
export function parseMarket(data) {
|
|
@@ -184,6 +199,8 @@ export function parseMarket(data) {
|
|
|
184
199
|
mechanism: data.mechanism || MARKET_MECHANISM_CONTINUOUS,
|
|
185
200
|
callIntervalSeconds: data.callIntervalSeconds ?? null,
|
|
186
201
|
callCarry: data.callCarry !== false,
|
|
202
|
+
priceDecimals: data.priceDecimals ?? Decimals.DEFAULT_PRICE_DECIMALS,
|
|
203
|
+
unitDecimals: data.unitDecimals ?? Decimals.DEFAULT_UNIT_DECIMALS,
|
|
187
204
|
};
|
|
188
205
|
}
|
|
189
206
|
export function parseMarketCall(data) {
|
|
@@ -209,6 +226,7 @@ export function parseMarketplace(data) {
|
|
|
209
226
|
name: data.name ?? null,
|
|
210
227
|
description: data.description ?? null,
|
|
211
228
|
markets: (data.markets ?? []).map(parseMarket),
|
|
229
|
+
cashDecimals: data.cashDecimals ?? Decimals.DEFAULT_CASH_DECIMALS,
|
|
212
230
|
};
|
|
213
231
|
}
|
|
214
232
|
export function parseSession(data) {
|
|
@@ -222,6 +240,8 @@ export function parseSession(data) {
|
|
|
222
240
|
description: data.description ?? null,
|
|
223
241
|
openDate: toInstant(data.openDate),
|
|
224
242
|
closeDate: toInstant(data.closeDate),
|
|
243
|
+
createdDate: toInstant(data.createdDate),
|
|
244
|
+
lastModifiedDate: toInstant(data.lastModifiedDate),
|
|
225
245
|
};
|
|
226
246
|
}
|
|
227
247
|
export function parseOrder(data) {
|
|
@@ -244,6 +264,8 @@ export function parseOrder(data) {
|
|
|
244
264
|
ownerTargetId: data.ownerTargetId ?? null,
|
|
245
265
|
createdDate: toInstant(data.createdDate),
|
|
246
266
|
lastModifiedDate: toInstant(data.lastModifiedDate),
|
|
267
|
+
mine: data.mine ?? null,
|
|
268
|
+
originalSessionId: data.originalSessionId ?? null,
|
|
247
269
|
};
|
|
248
270
|
}
|
|
249
271
|
export function parseParticipantState(data) {
|
|
@@ -404,6 +426,8 @@ function allotmentsToHoldings(allotments) {
|
|
|
404
426
|
cash,
|
|
405
427
|
availableCash: cash,
|
|
406
428
|
securities: a.assets?.securities ?? [],
|
|
429
|
+
// As in Java and Python: a holding built from an allotment does not carry the opening value.
|
|
430
|
+
initialCash: null,
|
|
407
431
|
};
|
|
408
432
|
});
|
|
409
433
|
}
|
|
@@ -418,6 +442,7 @@ export function parseHolding(data) {
|
|
|
418
442
|
cash: data.cash ?? 0,
|
|
419
443
|
availableCash: data.availableCash ?? 0,
|
|
420
444
|
securities: orderedSecurities(securitiesRaw.map(parseSecurity)),
|
|
445
|
+
initialCash: data.initialCash ?? null,
|
|
421
446
|
};
|
|
422
447
|
}
|
|
423
448
|
export function parseConnection(data) {
|
|
@@ -606,21 +631,46 @@ function readBody(body) {
|
|
|
606
631
|
throw new ApiError("Failed to parse the response body");
|
|
607
632
|
}
|
|
608
633
|
}
|
|
634
|
+
/** The `error` a failure body names, or null when it names none. */
|
|
635
|
+
function reasonIn(body) {
|
|
636
|
+
try {
|
|
637
|
+
const parsed = JSON.parse(body);
|
|
638
|
+
const error = typeof parsed === "object" && parsed !== null ? parsed.error : null;
|
|
639
|
+
return typeof error === "string" && error !== "" ? error : null;
|
|
640
|
+
}
|
|
641
|
+
catch {
|
|
642
|
+
return null;
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
/** `error`, carrying the answer it came from. */
|
|
646
|
+
function answered(error, statusCode, body) {
|
|
647
|
+
error.statusCode = statusCode;
|
|
648
|
+
error.body = body;
|
|
649
|
+
error.reason = reasonIn(body);
|
|
650
|
+
return error;
|
|
651
|
+
}
|
|
652
|
+
/** `error`, carrying the answer `from` carried. */
|
|
653
|
+
function answeredAs(error, from) {
|
|
654
|
+
error.statusCode = from.statusCode;
|
|
655
|
+
error.body = from.body;
|
|
656
|
+
error.reason = from.reason;
|
|
657
|
+
return error;
|
|
658
|
+
}
|
|
609
659
|
function checkResponse(response, body) {
|
|
610
660
|
const status = response.status;
|
|
611
661
|
if (status >= 200 && status < 300)
|
|
612
662
|
return;
|
|
613
663
|
if (status === 400)
|
|
614
|
-
throw new InvalidArgumentError("Invalid request: " + detail(body));
|
|
664
|
+
throw answered(new InvalidArgumentError("Invalid request: " + detail(body)), status, body);
|
|
615
665
|
if (status === 401)
|
|
616
|
-
throw new AuthenticationError("Authentication failed: " + detail(body));
|
|
666
|
+
throw answered(new AuthenticationError("Authentication failed: " + detail(body)), status, body);
|
|
617
667
|
if (status === 403)
|
|
618
|
-
throw new AuthorizationError("Not permitted: " + detail(body));
|
|
668
|
+
throw answered(new AuthorizationError("Not permitted: " + detail(body)), status, body);
|
|
619
669
|
if (status === 409)
|
|
620
|
-
throw new ConflictError(body);
|
|
670
|
+
throw answered(new ConflictError(body), status, body);
|
|
621
671
|
if (status >= 500)
|
|
622
|
-
throw new ConnectionFailedError(body);
|
|
623
|
-
throw new HttpError(status, body);
|
|
672
|
+
throw answered(new ConnectionFailedError(body), status, body);
|
|
673
|
+
throw answered(new HttpError(status, body), status, body);
|
|
624
674
|
}
|
|
625
675
|
/** The server's proposed alternative name, when a 409 body carries one. */
|
|
626
676
|
function suggestedNameIn(body) {
|
|
@@ -647,6 +697,29 @@ async function tokenExpired(resp) {
|
|
|
647
697
|
return false;
|
|
648
698
|
}
|
|
649
699
|
}
|
|
700
|
+
/**
|
|
701
|
+
* Whether a request failed with no answer from the server: the connection
|
|
702
|
+
* refused, reset or closed before or while the response came, which fetch
|
|
703
|
+
* says with a TypeError of these two messages and nothing more specific, or
|
|
704
|
+
* no answer within {@link REQUEST_TIMEOUT_MS}.
|
|
705
|
+
*/
|
|
706
|
+
function answerLost(e) {
|
|
707
|
+
return (e instanceof TypeError && (e.message === "fetch failed" || e.message === "terminated"))
|
|
708
|
+
|| (e instanceof Error && e.name === "TimeoutError");
|
|
709
|
+
}
|
|
710
|
+
/** How long a request may take, start to finish, before it is given up. */
|
|
711
|
+
export const REQUEST_TIMEOUT_MS = 30_000;
|
|
712
|
+
/** The timeout in force: {@link REQUEST_TIMEOUT_MS}, unless a test has shortened it. */
|
|
713
|
+
export const requestTimeout = { ms: REQUEST_TIMEOUT_MS };
|
|
714
|
+
/**
|
|
715
|
+
* fetch, given up after {@link REQUEST_TIMEOUT_MS} unless the caller passed a
|
|
716
|
+
* signal of its own. fetch has no timeout: a request whose answer never came
|
|
717
|
+
* waited for ever, where the Python and Java SDKs give up at 30 s -- and a
|
|
718
|
+
* robot stalled on one order stopped trading without a word.
|
|
719
|
+
*/
|
|
720
|
+
function fetchWithin(url, init) {
|
|
721
|
+
return fetch(url, { ...init, signal: init.signal ?? AbortSignal.timeout(requestTimeout.ms) });
|
|
722
|
+
}
|
|
650
723
|
export class Flexemarkets {
|
|
651
724
|
_clientDescription;
|
|
652
725
|
_endpoint;
|
|
@@ -755,7 +828,7 @@ export class Flexemarkets {
|
|
|
755
828
|
if (timing !== null)
|
|
756
829
|
headers.set("Client-Timing", timing);
|
|
757
830
|
const started = process.hrtime.bigint();
|
|
758
|
-
const resp = await
|
|
831
|
+
const resp = await fetchWithin(url, { ...init, headers });
|
|
759
832
|
const rtt = process.hrtime.bigint() - started;
|
|
760
833
|
const served = /st=(\d+)/.exec(resp.headers.get("Server-Timing") ?? "");
|
|
761
834
|
this._lastTiming = served
|
|
@@ -935,8 +1008,8 @@ export class Flexemarkets {
|
|
|
935
1008
|
// back out of a generic conflict.
|
|
936
1009
|
if (e instanceof ConflictError) {
|
|
937
1010
|
const suggested = suggestedNameIn(e.message);
|
|
938
|
-
throw new AccountNameConflictError(`Account name '${accountName}' is taken` +
|
|
939
|
-
(suggested === null ? "" : `; server suggests '${suggested}'`), accountName, suggested);
|
|
1011
|
+
throw answeredAs(new AccountNameConflictError(`Account name '${accountName}' is taken` +
|
|
1012
|
+
(suggested === null ? "" : `; server suggests '${suggested}'`), accountName, suggested), e);
|
|
940
1013
|
}
|
|
941
1014
|
throw e;
|
|
942
1015
|
}
|
|
@@ -999,7 +1072,7 @@ export class Flexemarkets {
|
|
|
999
1072
|
// it, so the server refuses and the caller has to decide what happens to
|
|
1000
1073
|
// the data first.
|
|
1001
1074
|
if (e instanceof ConflictError) {
|
|
1002
|
-
throw new PersonHasMarketplaceDataError(`User ${userId} has marketplace data and cannot be deleted.`, userId);
|
|
1075
|
+
throw answeredAs(new PersonHasMarketplaceDataError(`User ${userId} has marketplace data and cannot be deleted.`, userId), e);
|
|
1003
1076
|
}
|
|
1004
1077
|
throw e;
|
|
1005
1078
|
}
|
|
@@ -1065,7 +1138,7 @@ export class Flexemarkets {
|
|
|
1065
1138
|
*/
|
|
1066
1139
|
async managerOtpBundle(userIds) {
|
|
1067
1140
|
// Unversioned: fm-server has no V1 route for passcodes.
|
|
1068
|
-
const url =
|
|
1141
|
+
const url = this._v1("/otp/manager");
|
|
1069
1142
|
const data = await this._post(url, { userIds });
|
|
1070
1143
|
return {
|
|
1071
1144
|
expiresAt: toInstant(data.expiresAt),
|
|
@@ -1103,6 +1176,10 @@ export class Flexemarkets {
|
|
|
1103
1176
|
* segment. Bytes, not a string, so the file's own encoding survives.
|
|
1104
1177
|
*/
|
|
1105
1178
|
async _sendCsv(method, url, filename) {
|
|
1179
|
+
return this._sendCsvContent(method, url, readFileSync(filename));
|
|
1180
|
+
}
|
|
1181
|
+
/** CSV as the request body, declared text/csv; see {@link _sendCsv}. */
|
|
1182
|
+
async _sendCsvContent(method, url, content) {
|
|
1106
1183
|
const resp = await this._fetch(url, {
|
|
1107
1184
|
method,
|
|
1108
1185
|
headers: {
|
|
@@ -1111,7 +1188,7 @@ export class Flexemarkets {
|
|
|
1111
1188
|
Accept: "application/json",
|
|
1112
1189
|
"User-Agent": FM_NETWORK_CLIENT,
|
|
1113
1190
|
},
|
|
1114
|
-
body:
|
|
1191
|
+
body: content,
|
|
1115
1192
|
});
|
|
1116
1193
|
const body = await resp.text();
|
|
1117
1194
|
checkResponse(resp, body);
|
|
@@ -1190,16 +1267,55 @@ export class Flexemarkets {
|
|
|
1190
1267
|
return parseSession(await this._get(`${this._marketplace(marketplaceId)}/sessions/current`));
|
|
1191
1268
|
}
|
|
1192
1269
|
// -- orders ----------------------------------------------------------------
|
|
1193
|
-
|
|
1194
|
-
|
|
1270
|
+
/**
|
|
1271
|
+
* Place a limit order.
|
|
1272
|
+
*
|
|
1273
|
+
* A private market matches an order only with one aimed back at its owner, so
|
|
1274
|
+
* an order there names its counterparty: by `ownerTargetId` when the caller
|
|
1275
|
+
* knows it, or by `ownerTarget`, the allotment name. The id is the
|
|
1276
|
+
* unambiguous one, but only a manager can learn ids -- a participant's
|
|
1277
|
+
* `identifiers()` are names -- so a participant has the name and nothing
|
|
1278
|
+
* else. Name one or the other, not both.
|
|
1279
|
+
*
|
|
1280
|
+
* `clientDescription` is this order's own reference, as the server keeps it
|
|
1281
|
+
* on the order; it defaults to the description this client connected with.
|
|
1282
|
+
*/
|
|
1283
|
+
async submitLimit(marketplaceId, marketId, side, units, price, options = {}) {
|
|
1284
|
+
const { ownerTarget, ownerTargetId, clientDescription } = options;
|
|
1285
|
+
if (ownerTarget !== undefined && ownerTargetId !== undefined) {
|
|
1286
|
+
throw new InvalidArgumentError("Name the counterparty by ownerTarget or ownerTargetId, not both");
|
|
1287
|
+
}
|
|
1288
|
+
const order = {
|
|
1195
1289
|
marketplaceId,
|
|
1196
1290
|
marketId,
|
|
1197
1291
|
type: "LIMIT",
|
|
1198
1292
|
side,
|
|
1199
1293
|
units,
|
|
1200
1294
|
price,
|
|
1201
|
-
clientDescription: this._clientDescription,
|
|
1202
|
-
}
|
|
1295
|
+
clientDescription: clientDescription || this._clientDescription,
|
|
1296
|
+
};
|
|
1297
|
+
// Left out rather than sent as null: a target of null is a private order
|
|
1298
|
+
// aimed at nobody, which the server refuses.
|
|
1299
|
+
if (ownerTarget !== undefined)
|
|
1300
|
+
order.ownerTarget = ownerTarget;
|
|
1301
|
+
if (ownerTargetId !== undefined)
|
|
1302
|
+
order.ownerTargetId = ownerTargetId;
|
|
1303
|
+
// Named, so an order whose answer was lost can be sent again without
|
|
1304
|
+
// trading twice: fm-server answers a submission it already holds with the
|
|
1305
|
+
// order it made, not a second one. A send that lost its connection may or
|
|
1306
|
+
// may not have landed; reporting it as refused invited the caller to place
|
|
1307
|
+
// it again and double the position.
|
|
1308
|
+
order.submissionId = randomUUID();
|
|
1309
|
+
const url = `${this._marketplace(marketplaceId)}/orders`;
|
|
1310
|
+
let data;
|
|
1311
|
+
try {
|
|
1312
|
+
data = await this._post(url, order);
|
|
1313
|
+
}
|
|
1314
|
+
catch (e) {
|
|
1315
|
+
if (!answerLost(e))
|
|
1316
|
+
throw e;
|
|
1317
|
+
data = await this._post(url, order);
|
|
1318
|
+
}
|
|
1203
1319
|
return parseOrder(data);
|
|
1204
1320
|
}
|
|
1205
1321
|
/**
|
|
@@ -1452,6 +1568,21 @@ export class Flexemarkets {
|
|
|
1452
1568
|
const data = (await this._sendCsv("POST", url, filename));
|
|
1453
1569
|
return allotmentsToHoldings(data.map(parseAllotment));
|
|
1454
1570
|
}
|
|
1571
|
+
/**
|
|
1572
|
+
* Stage an allocation from holdings CSV text, as {@link uploadHoldings} does
|
|
1573
|
+
* from a file.
|
|
1574
|
+
*
|
|
1575
|
+
* For a program that builds the CSV rather than reading one -- an admin
|
|
1576
|
+
* robot writing back the holdings it downloaded and changed -- which
|
|
1577
|
+
* otherwise writes a file only to have it read again. The text is sent as it
|
|
1578
|
+
* is; a `# holdings -- begin` / `-- end` frame around it is accepted, as in a
|
|
1579
|
+
* downloaded file.
|
|
1580
|
+
*/
|
|
1581
|
+
async uploadHoldingsCsv(marketplaceId, csv) {
|
|
1582
|
+
const url = `${this._marketplace(marketplaceId)}/allocations`;
|
|
1583
|
+
const data = (await this._sendCsvContent("POST", url, csv));
|
|
1584
|
+
return allotmentsToHoldings(data.map(parseAllotment));
|
|
1585
|
+
}
|
|
1455
1586
|
/**
|
|
1456
1587
|
* Load per-participant private state from a CSV, returning what was stored.
|
|
1457
1588
|
*
|
|
@@ -1519,10 +1650,15 @@ export class Flexemarkets {
|
|
|
1519
1650
|
/**
|
|
1520
1651
|
* Every widget pushed to the marketplace and still standing, for every
|
|
1521
1652
|
* participant -- what a manager reads to check on a robot.
|
|
1653
|
+
*
|
|
1654
|
+
* The answer is the frame every widgets read answers, `{marketplaceId,
|
|
1655
|
+
* snapshot, widgets, removed}`; a bare list, which `widgets/all` answered
|
|
1656
|
+
* and 0.4.0 to 0.11.0 expected here, is read too.
|
|
1522
1657
|
*/
|
|
1523
1658
|
async allWidgets(marketplaceId) {
|
|
1524
1659
|
const data = await this._get(`${this._marketplace(marketplaceId)}/widgets?participant=all`);
|
|
1525
|
-
|
|
1660
|
+
const widgets = Array.isArray(data) ? data : (data.widgets ?? []);
|
|
1661
|
+
return widgets.map(parseWidget);
|
|
1526
1662
|
}
|
|
1527
1663
|
/**
|
|
1528
1664
|
* Clear a call-auction market now: every crossing order trades at one
|
|
@@ -1673,9 +1809,19 @@ export class Flexemarkets {
|
|
|
1673
1809
|
* Returns an unsubscribe function rather than an object with `close()`,
|
|
1674
1810
|
* matching what Desk's `on*` handlers already return here. Java
|
|
1675
1811
|
* returns a `Subscription`; both names describe the same lifetime.
|
|
1812
|
+
*
|
|
1813
|
+
* With `history`, the first orders update is every order of the current
|
|
1814
|
+
* session as this caller may see it -- cancelled and split ones included, a
|
|
1815
|
+
* counterparty's private order named from the caller's side -- stamped with
|
|
1816
|
+
* the `seq` it was read at, and each reconnect delivers it again. That is
|
|
1817
|
+
* fm-server's original subscribe, and the only whole history a participant
|
|
1818
|
+
* can read: the REST history is a manager's. Without it the first update is
|
|
1819
|
+
* empty and the book comes from `activeOrders`. A history is one frame, so on
|
|
1820
|
+
* a session with a very long one it is a large frame -- fm-server's V1
|
|
1821
|
+
* subscribe exists to avoid exactly that.
|
|
1676
1822
|
*/
|
|
1677
|
-
async subscribe(marketplaceId, callback) {
|
|
1678
|
-
const listener = await this._connectEvents(marketplaceId, callback);
|
|
1823
|
+
async subscribe(marketplaceId, callback, options = {}) {
|
|
1824
|
+
const listener = await this._connectEvents(marketplaceId, callback, options.history ?? false);
|
|
1679
1825
|
return () => {
|
|
1680
1826
|
void listener.close();
|
|
1681
1827
|
};
|
|
@@ -1686,11 +1832,11 @@ export class Flexemarkets {
|
|
|
1686
1832
|
* the singleton {@link #_eventListener}. Lets multiple
|
|
1687
1833
|
* desk(marketplaceId) calls coexist within one Flexemarkets.
|
|
1688
1834
|
*/
|
|
1689
|
-
async _connectEvents(marketplaceId, callback) {
|
|
1835
|
+
async _connectEvents(marketplaceId, callback, history = false) {
|
|
1690
1836
|
const wsUrl = server(this._endpoint)
|
|
1691
1837
|
.replace("https://", "wss://")
|
|
1692
|
-
.replace("http://", "ws://") + "/events";
|
|
1693
|
-
const events = new EventListener(wsUrl, () => this._bearerToken, marketplaceId, callback, this._clientDescription, parseHolding, parseOrder, (presented) => this._renewToken(presented));
|
|
1838
|
+
.replace("http://", "ws://") + "/v1/events";
|
|
1839
|
+
const events = new EventListener(wsUrl, () => this._bearerToken, marketplaceId, callback, this._clientDescription, parseHolding, parseOrder, (presented) => this._renewToken(presented), history);
|
|
1694
1840
|
await events.start();
|
|
1695
1841
|
return events;
|
|
1696
1842
|
}
|
|
@@ -1731,7 +1877,7 @@ export class Flexemarkets {
|
|
|
1731
1877
|
* stops working after hours while the robot runs on.
|
|
1732
1878
|
*/
|
|
1733
1879
|
async function renewWithRefreshToken(baseUrl, config) {
|
|
1734
|
-
const resp = await
|
|
1880
|
+
const resp = await fetchWithin(`${baseUrl}/v1/tokens/renew`, {
|
|
1735
1881
|
method: "POST",
|
|
1736
1882
|
headers: {
|
|
1737
1883
|
"Content-Type": "application/json",
|
|
@@ -1765,7 +1911,7 @@ async function signIn(baseUrl, config, clientDescription) {
|
|
|
1765
1911
|
// Python one never had it, so token auth returned 400 in both from the day
|
|
1766
1912
|
// it was written.
|
|
1767
1913
|
// POST, as minting a token is (fm-server 4.6).
|
|
1768
|
-
const resp = await
|
|
1914
|
+
const resp = await fetchWithin(`${baseUrl}/v1/tokens/refresh`, {
|
|
1769
1915
|
method: "POST",
|
|
1770
1916
|
headers: {
|
|
1771
1917
|
Authorization: `Bearer ${tok}`,
|
|
@@ -1786,8 +1932,8 @@ async function signIn(baseUrl, config, clientDescription) {
|
|
|
1786
1932
|
throw new ConfigurationError("Missing 'email' in configuration.");
|
|
1787
1933
|
if (!password)
|
|
1788
1934
|
throw new ConfigurationError("Missing 'password' in configuration.");
|
|
1789
|
-
const authUrl = `${baseUrl}/tokens`;
|
|
1790
|
-
const resp = await
|
|
1935
|
+
const authUrl = `${baseUrl}/v1/tokens`;
|
|
1936
|
+
const resp = await fetchWithin(authUrl, {
|
|
1791
1937
|
method: "POST",
|
|
1792
1938
|
headers: {
|
|
1793
1939
|
"Content-Type": "application/json",
|