@flexemarkets/fm-sdk 0.12.0 → 0.14.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 +117 -3
- package/dist/client.js +272 -38
- 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 +2 -0
- package/dist/index.js +3 -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/page.d.ts +41 -0
- package/dist/page.js +56 -0
- package/dist/page.js.map +1 -0
- package/dist/stomp.d.ts +18 -1
- package/dist/stomp.js +50 -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/dist/client.js
CHANGED
|
@@ -3,13 +3,16 @@
|
|
|
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";
|
|
15
|
+
import { Page } from "./page.js";
|
|
13
16
|
import { readVersion } from "./version.js";
|
|
14
17
|
const FM_NETWORK_CLIENT = `fm-sdk-typescript/${readVersion()}`;
|
|
15
18
|
export const DEFAULT_ENDPOINT = "https://api.flexemarkets.com";
|
|
@@ -27,10 +30,24 @@ const REFRESH_TOKEN_PREFIX = "refresh:";
|
|
|
27
30
|
const MAX_TRADED_LEGS = 5000;
|
|
28
31
|
const BCRYPT_RE = /^\$2[abxy]?\$\d{2}\$[./A-Za-z0-9]{53}$/;
|
|
29
32
|
const JWT_RE = /^[A-Za-z0-9\-_]+\.[A-Za-z0-9\-_]+\.[A-Za-z0-9\-_]+$/;
|
|
33
|
+
/** The `before` in a `Link` header's `rel="next"` target: where a page's older rows start. */
|
|
34
|
+
const NEXT_LINK = /<[^>]*[?&]before=(\d+)[^>]*>\s*;\s*rel="?next"?/;
|
|
30
35
|
// ---------------------------------------------------------------------------
|
|
31
36
|
// Errors
|
|
32
37
|
// ---------------------------------------------------------------------------
|
|
38
|
+
/**
|
|
39
|
+
* Base of every Flexemarkets error.
|
|
40
|
+
*
|
|
41
|
+
* An error that is the server's answer carries it: `statusCode`, the `body` as
|
|
42
|
+
* sent, and `reason`, the body's `error` -- `SESSION_CLOSED`, `ORDER_INVALID`,
|
|
43
|
+
* `ACCOUNT_TOKEN_EXPIRED` -- which is what a caller branches on, where the
|
|
44
|
+
* message is for people. All three are null for an error the SDK raised
|
|
45
|
+
* itself, and `reason` is null when the body named no error.
|
|
46
|
+
*/
|
|
33
47
|
export class FlexemarketsError extends Error {
|
|
48
|
+
statusCode = null;
|
|
49
|
+
reason = null;
|
|
50
|
+
body = null;
|
|
34
51
|
}
|
|
35
52
|
export class AuthenticationError extends FlexemarketsError {
|
|
36
53
|
}
|
|
@@ -165,6 +182,7 @@ export function parseSecurity(data) {
|
|
|
165
182
|
shortUnits: data.shortUnits ?? data.initialShortUnits ?? 0,
|
|
166
183
|
canBuy: data.canBuy ?? false,
|
|
167
184
|
canSell: data.canSell ?? false,
|
|
185
|
+
initialUnits: data.initialUnits ?? null,
|
|
168
186
|
};
|
|
169
187
|
}
|
|
170
188
|
export function parseMarket(data) {
|
|
@@ -184,6 +202,8 @@ export function parseMarket(data) {
|
|
|
184
202
|
mechanism: data.mechanism || MARKET_MECHANISM_CONTINUOUS,
|
|
185
203
|
callIntervalSeconds: data.callIntervalSeconds ?? null,
|
|
186
204
|
callCarry: data.callCarry !== false,
|
|
205
|
+
priceDecimals: data.priceDecimals ?? Decimals.DEFAULT_PRICE_DECIMALS,
|
|
206
|
+
unitDecimals: data.unitDecimals ?? Decimals.DEFAULT_UNIT_DECIMALS,
|
|
187
207
|
};
|
|
188
208
|
}
|
|
189
209
|
export function parseMarketCall(data) {
|
|
@@ -209,6 +229,7 @@ export function parseMarketplace(data) {
|
|
|
209
229
|
name: data.name ?? null,
|
|
210
230
|
description: data.description ?? null,
|
|
211
231
|
markets: (data.markets ?? []).map(parseMarket),
|
|
232
|
+
cashDecimals: data.cashDecimals ?? Decimals.DEFAULT_CASH_DECIMALS,
|
|
212
233
|
};
|
|
213
234
|
}
|
|
214
235
|
export function parseSession(data) {
|
|
@@ -222,6 +243,8 @@ export function parseSession(data) {
|
|
|
222
243
|
description: data.description ?? null,
|
|
223
244
|
openDate: toInstant(data.openDate),
|
|
224
245
|
closeDate: toInstant(data.closeDate),
|
|
246
|
+
createdDate: toInstant(data.createdDate),
|
|
247
|
+
lastModifiedDate: toInstant(data.lastModifiedDate),
|
|
225
248
|
};
|
|
226
249
|
}
|
|
227
250
|
export function parseOrder(data) {
|
|
@@ -244,6 +267,8 @@ export function parseOrder(data) {
|
|
|
244
267
|
ownerTargetId: data.ownerTargetId ?? null,
|
|
245
268
|
createdDate: toInstant(data.createdDate),
|
|
246
269
|
lastModifiedDate: toInstant(data.lastModifiedDate),
|
|
270
|
+
mine: data.mine ?? null,
|
|
271
|
+
originalSessionId: data.originalSessionId ?? null,
|
|
247
272
|
};
|
|
248
273
|
}
|
|
249
274
|
export function parseParticipantState(data) {
|
|
@@ -404,6 +429,8 @@ function allotmentsToHoldings(allotments) {
|
|
|
404
429
|
cash,
|
|
405
430
|
availableCash: cash,
|
|
406
431
|
securities: a.assets?.securities ?? [],
|
|
432
|
+
// As in Java and Python: a holding built from an allotment does not carry the opening value.
|
|
433
|
+
initialCash: null,
|
|
407
434
|
};
|
|
408
435
|
});
|
|
409
436
|
}
|
|
@@ -418,6 +445,7 @@ export function parseHolding(data) {
|
|
|
418
445
|
cash: data.cash ?? 0,
|
|
419
446
|
availableCash: data.availableCash ?? 0,
|
|
420
447
|
securities: orderedSecurities(securitiesRaw.map(parseSecurity)),
|
|
448
|
+
initialCash: data.initialCash ?? null,
|
|
421
449
|
};
|
|
422
450
|
}
|
|
423
451
|
export function parseConnection(data) {
|
|
@@ -606,21 +634,46 @@ function readBody(body) {
|
|
|
606
634
|
throw new ApiError("Failed to parse the response body");
|
|
607
635
|
}
|
|
608
636
|
}
|
|
637
|
+
/** The `error` a failure body names, or null when it names none. */
|
|
638
|
+
function reasonIn(body) {
|
|
639
|
+
try {
|
|
640
|
+
const parsed = JSON.parse(body);
|
|
641
|
+
const error = typeof parsed === "object" && parsed !== null ? parsed.error : null;
|
|
642
|
+
return typeof error === "string" && error !== "" ? error : null;
|
|
643
|
+
}
|
|
644
|
+
catch {
|
|
645
|
+
return null;
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
/** `error`, carrying the answer it came from. */
|
|
649
|
+
function answered(error, statusCode, body) {
|
|
650
|
+
error.statusCode = statusCode;
|
|
651
|
+
error.body = body;
|
|
652
|
+
error.reason = reasonIn(body);
|
|
653
|
+
return error;
|
|
654
|
+
}
|
|
655
|
+
/** `error`, carrying the answer `from` carried. */
|
|
656
|
+
function answeredAs(error, from) {
|
|
657
|
+
error.statusCode = from.statusCode;
|
|
658
|
+
error.body = from.body;
|
|
659
|
+
error.reason = from.reason;
|
|
660
|
+
return error;
|
|
661
|
+
}
|
|
609
662
|
function checkResponse(response, body) {
|
|
610
663
|
const status = response.status;
|
|
611
664
|
if (status >= 200 && status < 300)
|
|
612
665
|
return;
|
|
613
666
|
if (status === 400)
|
|
614
|
-
throw new InvalidArgumentError("Invalid request: " + detail(body));
|
|
667
|
+
throw answered(new InvalidArgumentError("Invalid request: " + detail(body)), status, body);
|
|
615
668
|
if (status === 401)
|
|
616
|
-
throw new AuthenticationError("Authentication failed: " + detail(body));
|
|
669
|
+
throw answered(new AuthenticationError("Authentication failed: " + detail(body)), status, body);
|
|
617
670
|
if (status === 403)
|
|
618
|
-
throw new AuthorizationError("Not permitted: " + detail(body));
|
|
671
|
+
throw answered(new AuthorizationError("Not permitted: " + detail(body)), status, body);
|
|
619
672
|
if (status === 409)
|
|
620
|
-
throw new ConflictError(body);
|
|
673
|
+
throw answered(new ConflictError(body), status, body);
|
|
621
674
|
if (status >= 500)
|
|
622
|
-
throw new ConnectionFailedError(body);
|
|
623
|
-
throw new HttpError(status, body);
|
|
675
|
+
throw answered(new ConnectionFailedError(body), status, body);
|
|
676
|
+
throw answered(new HttpError(status, body), status, body);
|
|
624
677
|
}
|
|
625
678
|
/** The server's proposed alternative name, when a 409 body carries one. */
|
|
626
679
|
function suggestedNameIn(body) {
|
|
@@ -647,6 +700,29 @@ async function tokenExpired(resp) {
|
|
|
647
700
|
return false;
|
|
648
701
|
}
|
|
649
702
|
}
|
|
703
|
+
/**
|
|
704
|
+
* Whether a request failed with no answer from the server: the connection
|
|
705
|
+
* refused, reset or closed before or while the response came, which fetch
|
|
706
|
+
* says with a TypeError of these two messages and nothing more specific, or
|
|
707
|
+
* no answer within {@link REQUEST_TIMEOUT_MS}.
|
|
708
|
+
*/
|
|
709
|
+
function answerLost(e) {
|
|
710
|
+
return (e instanceof TypeError && (e.message === "fetch failed" || e.message === "terminated"))
|
|
711
|
+
|| (e instanceof Error && e.name === "TimeoutError");
|
|
712
|
+
}
|
|
713
|
+
/** How long a request may take, start to finish, before it is given up. */
|
|
714
|
+
export const REQUEST_TIMEOUT_MS = 30_000;
|
|
715
|
+
/** The timeout in force: {@link REQUEST_TIMEOUT_MS}, unless a test has shortened it. */
|
|
716
|
+
export const requestTimeout = { ms: REQUEST_TIMEOUT_MS };
|
|
717
|
+
/**
|
|
718
|
+
* fetch, given up after {@link REQUEST_TIMEOUT_MS} unless the caller passed a
|
|
719
|
+
* signal of its own. fetch has no timeout: a request whose answer never came
|
|
720
|
+
* waited for ever, where the Python and Java SDKs give up at 30 s -- and a
|
|
721
|
+
* robot stalled on one order stopped trading without a word.
|
|
722
|
+
*/
|
|
723
|
+
function fetchWithin(url, init) {
|
|
724
|
+
return fetch(url, { ...init, signal: init.signal ?? AbortSignal.timeout(requestTimeout.ms) });
|
|
725
|
+
}
|
|
650
726
|
export class Flexemarkets {
|
|
651
727
|
_clientDescription;
|
|
652
728
|
_endpoint;
|
|
@@ -755,7 +831,7 @@ export class Flexemarkets {
|
|
|
755
831
|
if (timing !== null)
|
|
756
832
|
headers.set("Client-Timing", timing);
|
|
757
833
|
const started = process.hrtime.bigint();
|
|
758
|
-
const resp = await
|
|
834
|
+
const resp = await fetchWithin(url, { ...init, headers });
|
|
759
835
|
const rtt = process.hrtime.bigint() - started;
|
|
760
836
|
const served = /st=(\d+)/.exec(resp.headers.get("Server-Timing") ?? "");
|
|
761
837
|
this._lastTiming = served
|
|
@@ -832,6 +908,13 @@ export class Flexemarkets {
|
|
|
832
908
|
* `Snapshot.NO_SEQ` when the header is absent.
|
|
833
909
|
*/
|
|
834
910
|
async _getSnapshot(url) {
|
|
911
|
+
const { data, headers } = await this._getRead(url);
|
|
912
|
+
const raw = headers.get("x-fm-as-of-seq");
|
|
913
|
+
const asOfSeq = raw === null ? NO_SEQ : Number.parseInt(raw, 10);
|
|
914
|
+
return { data, asOfSeq: Number.isFinite(asOfSeq) ? asOfSeq : NO_SEQ };
|
|
915
|
+
}
|
|
916
|
+
/** GET a body the answer needs a response header beside: a snapshot's sequence, a page's next link. */
|
|
917
|
+
async _getRead(url) {
|
|
835
918
|
const resp = await this._fetch(url.startsWith("/") ? `${this._baseUrl}${url}` : url, {
|
|
836
919
|
headers: {
|
|
837
920
|
...this._authHeaders(),
|
|
@@ -841,9 +924,18 @@ export class Flexemarkets {
|
|
|
841
924
|
});
|
|
842
925
|
const body = await resp.text();
|
|
843
926
|
checkResponse(resp, body);
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
927
|
+
return { data: readBody(body), headers: resp.headers };
|
|
928
|
+
}
|
|
929
|
+
/**
|
|
930
|
+
* A page of a collection: `url` with `?limit=` and `?before=`, and the
|
|
931
|
+
* `before` of the page after it read from the `Link: <...>; rel="next"` the
|
|
932
|
+
* server sends while older rows remain.
|
|
933
|
+
*/
|
|
934
|
+
async _page(url, limit, before, parse) {
|
|
935
|
+
const paged = `${url}${url.includes("?") ? "&" : "?"}limit=${limit}${before === undefined ? "" : `&before=${before}`}`;
|
|
936
|
+
const { data, headers } = await this._getRead(paged);
|
|
937
|
+
const next = NEXT_LINK.exec(headers.get("link") ?? "");
|
|
938
|
+
return new Page(data.map(parse), next === null ? null : Number.parseInt(next[1], 10));
|
|
847
939
|
}
|
|
848
940
|
/** PATCH with a JSON body -- the shape every session transition takes. */
|
|
849
941
|
async _patch(url, json) {
|
|
@@ -885,7 +977,7 @@ export class Flexemarkets {
|
|
|
885
977
|
checkResponse(resp, body);
|
|
886
978
|
return body;
|
|
887
979
|
}
|
|
888
|
-
async _post(url, json) {
|
|
980
|
+
async _post(url, json, headers = {}) {
|
|
889
981
|
const resp = await this._fetch(url.startsWith("/") ? `${this._baseUrl}${url}` : url, {
|
|
890
982
|
method: "POST",
|
|
891
983
|
headers: {
|
|
@@ -893,6 +985,7 @@ export class Flexemarkets {
|
|
|
893
985
|
"Content-Type": "application/json",
|
|
894
986
|
Accept: "application/json",
|
|
895
987
|
"User-Agent": FM_NETWORK_CLIENT,
|
|
988
|
+
...headers,
|
|
896
989
|
},
|
|
897
990
|
body: JSON.stringify(json),
|
|
898
991
|
});
|
|
@@ -935,8 +1028,8 @@ export class Flexemarkets {
|
|
|
935
1028
|
// back out of a generic conflict.
|
|
936
1029
|
if (e instanceof ConflictError) {
|
|
937
1030
|
const suggested = suggestedNameIn(e.message);
|
|
938
|
-
throw new AccountNameConflictError(`Account name '${accountName}' is taken` +
|
|
939
|
-
(suggested === null ? "" : `; server suggests '${suggested}'`), accountName, suggested);
|
|
1031
|
+
throw answeredAs(new AccountNameConflictError(`Account name '${accountName}' is taken` +
|
|
1032
|
+
(suggested === null ? "" : `; server suggests '${suggested}'`), accountName, suggested), e);
|
|
940
1033
|
}
|
|
941
1034
|
throw e;
|
|
942
1035
|
}
|
|
@@ -980,13 +1073,21 @@ export class Flexemarkets {
|
|
|
980
1073
|
const data = await this._get(this._v1("/accounts"));
|
|
981
1074
|
return data.map(parseAccount);
|
|
982
1075
|
}
|
|
1076
|
+
/**
|
|
1077
|
+
* A page of `accounts()`: the newest `limit`, or of those whose id is below
|
|
1078
|
+
* `before` -- a page's `next`. The server answers at most 5,000.
|
|
1079
|
+
*/
|
|
1080
|
+
async accountsPage(limit, before) {
|
|
1081
|
+
return this._page(this._v1("/accounts"), limit, before, (a) => parseAccount(a));
|
|
1082
|
+
}
|
|
983
1083
|
/** Delete an account. Destructive, and takes its users with it. */
|
|
984
1084
|
async deleteAccount(accountId) {
|
|
985
1085
|
await this._delete(this._v1(`/accounts/${accountId}`));
|
|
986
1086
|
}
|
|
987
1087
|
/** Create a user in the caller's account. */
|
|
988
1088
|
async createUser(email, password, firstName, lastName, roles = []) {
|
|
989
|
-
const
|
|
1089
|
+
const user = { email, password, firstName, lastName, roles };
|
|
1090
|
+
const data = await this._create((key) => this._post(this._v1("/users"), user, key));
|
|
990
1091
|
return parsePerson(data);
|
|
991
1092
|
}
|
|
992
1093
|
/** Delete a user. Destructive. */
|
|
@@ -999,7 +1100,7 @@ export class Flexemarkets {
|
|
|
999
1100
|
// it, so the server refuses and the caller has to decide what happens to
|
|
1000
1101
|
// the data first.
|
|
1001
1102
|
if (e instanceof ConflictError) {
|
|
1002
|
-
throw new PersonHasMarketplaceDataError(`User ${userId} has marketplace data and cannot be deleted.`, userId);
|
|
1103
|
+
throw answeredAs(new PersonHasMarketplaceDataError(`User ${userId} has marketplace data and cannot be deleted.`, userId), e);
|
|
1003
1104
|
}
|
|
1004
1105
|
throw e;
|
|
1005
1106
|
}
|
|
@@ -1019,7 +1120,7 @@ export class Flexemarkets {
|
|
|
1019
1120
|
* `units` keeps the old default.
|
|
1020
1121
|
*/
|
|
1021
1122
|
async createMarket(marketplaceId, symbol, name, price, units = unitGrid(), privateMarket = false) {
|
|
1022
|
-
return parseMarket(await this._post(`${this._marketplace(marketplaceId)}/markets`, {
|
|
1123
|
+
return parseMarket(await this._create((key) => this._post(`${this._marketplace(marketplaceId)}/markets`, {
|
|
1023
1124
|
symbol,
|
|
1024
1125
|
name,
|
|
1025
1126
|
priceMinimum: price.minimum,
|
|
@@ -1029,7 +1130,7 @@ export class Flexemarkets {
|
|
|
1029
1130
|
unitMaximum: units.maximum,
|
|
1030
1131
|
unitTick: units.tick,
|
|
1031
1132
|
privateMarket,
|
|
1032
|
-
}));
|
|
1133
|
+
}, key)));
|
|
1033
1134
|
}
|
|
1034
1135
|
/**
|
|
1035
1136
|
* Add a call-auction market to a marketplace: orders collect, crossed or
|
|
@@ -1042,7 +1143,7 @@ export class Flexemarkets {
|
|
|
1042
1143
|
* there is no flag for it here; the server refuses the combination.
|
|
1043
1144
|
*/
|
|
1044
1145
|
async createCallMarket(marketplaceId, symbol, name, price, units = unitGrid(), intervalSeconds = null, carry = true) {
|
|
1045
|
-
return parseMarket(await this._post(`${this._marketplace(marketplaceId)}/markets`, {
|
|
1146
|
+
return parseMarket(await this._create((key) => this._post(`${this._marketplace(marketplaceId)}/markets`, {
|
|
1046
1147
|
symbol,
|
|
1047
1148
|
name,
|
|
1048
1149
|
priceMinimum: price.minimum,
|
|
@@ -1055,7 +1156,7 @@ export class Flexemarkets {
|
|
|
1055
1156
|
mechanism: MARKET_MECHANISM_CALL,
|
|
1056
1157
|
callIntervalSeconds: intervalSeconds,
|
|
1057
1158
|
callCarry: carry,
|
|
1058
|
-
}));
|
|
1159
|
+
}, key)));
|
|
1059
1160
|
}
|
|
1060
1161
|
/**
|
|
1061
1162
|
* Mint one-time passcodes for the given users.
|
|
@@ -1102,7 +1203,30 @@ export class Flexemarkets {
|
|
|
1102
1203
|
* header, where 0.3 posted it as a multipart upload to an `/uploads`
|
|
1103
1204
|
* segment. Bytes, not a string, so the file's own encoding survives.
|
|
1104
1205
|
*/
|
|
1105
|
-
|
|
1206
|
+
/**
|
|
1207
|
+
* Send a create under an `Idempotency-Key`, and once more under the same key
|
|
1208
|
+
* if its answer was lost. A create that lost its connection may or may not
|
|
1209
|
+
* have landed; fm-server 4.17 answers a key it already holds with what it
|
|
1210
|
+
* answered the first time (its IdempotencyFilter), so the resend makes one
|
|
1211
|
+
* marketplace, market or call, never two. Orders do the same with their own
|
|
1212
|
+
* `submissionId`.
|
|
1213
|
+
*/
|
|
1214
|
+
async _create(send) {
|
|
1215
|
+
const key = { "Idempotency-Key": randomUUID() };
|
|
1216
|
+
try {
|
|
1217
|
+
return await send(key);
|
|
1218
|
+
}
|
|
1219
|
+
catch (e) {
|
|
1220
|
+
if (!answerLost(e))
|
|
1221
|
+
throw e;
|
|
1222
|
+
return send(key);
|
|
1223
|
+
}
|
|
1224
|
+
}
|
|
1225
|
+
async _sendCsv(method, url, filename, headers = {}) {
|
|
1226
|
+
return this._sendCsvContent(method, url, readFileSync(filename), headers);
|
|
1227
|
+
}
|
|
1228
|
+
/** CSV as the request body, declared text/csv; see {@link _sendCsv}. */
|
|
1229
|
+
async _sendCsvContent(method, url, content, headers = {}) {
|
|
1106
1230
|
const resp = await this._fetch(url, {
|
|
1107
1231
|
method,
|
|
1108
1232
|
headers: {
|
|
@@ -1110,8 +1234,9 @@ export class Flexemarkets {
|
|
|
1110
1234
|
"Content-Type": "text/csv",
|
|
1111
1235
|
Accept: "application/json",
|
|
1112
1236
|
"User-Agent": FM_NETWORK_CLIENT,
|
|
1237
|
+
...headers,
|
|
1113
1238
|
},
|
|
1114
|
-
body:
|
|
1239
|
+
body: content,
|
|
1115
1240
|
});
|
|
1116
1241
|
const body = await resp.text();
|
|
1117
1242
|
checkResponse(resp, body);
|
|
@@ -1137,6 +1262,13 @@ export class Flexemarkets {
|
|
|
1137
1262
|
const data = await this._get(this._v1("/marketplaces"));
|
|
1138
1263
|
return data.map(parseMarketplace);
|
|
1139
1264
|
}
|
|
1265
|
+
/**
|
|
1266
|
+
* A page of `marketplaces()`: the newest `limit`, or of those whose id is below
|
|
1267
|
+
* `before` -- a page's `next`. The server answers at most 5,000.
|
|
1268
|
+
*/
|
|
1269
|
+
async marketplacesPage(limit, before) {
|
|
1270
|
+
return this._page(this._v1("/marketplaces"), limit, before, parseMarketplace);
|
|
1271
|
+
}
|
|
1140
1272
|
async marketplace(marketplaceId) {
|
|
1141
1273
|
return parseMarketplace(await this._get(this._marketplace(marketplaceId)));
|
|
1142
1274
|
}
|
|
@@ -1186,20 +1318,66 @@ export class Flexemarkets {
|
|
|
1186
1318
|
const url = `${this._marketplace(marketplaceId)}/sessions`;
|
|
1187
1319
|
return (await this._get(url)).map(parseSession);
|
|
1188
1320
|
}
|
|
1321
|
+
/**
|
|
1322
|
+
* A page of `sessions()`: the newest `limit`, or of those whose id is below
|
|
1323
|
+
* `before` -- a page's `next`. The server answers at most 5,000.
|
|
1324
|
+
*/
|
|
1325
|
+
async sessionsPage(marketplaceId, limit, before) {
|
|
1326
|
+
return this._page(`${this._marketplace(marketplaceId)}/sessions`, limit, before, parseSession);
|
|
1327
|
+
}
|
|
1189
1328
|
async session(marketplaceId) {
|
|
1190
1329
|
return parseSession(await this._get(`${this._marketplace(marketplaceId)}/sessions/current`));
|
|
1191
1330
|
}
|
|
1192
1331
|
// -- orders ----------------------------------------------------------------
|
|
1193
|
-
|
|
1194
|
-
|
|
1332
|
+
/**
|
|
1333
|
+
* Place a limit order.
|
|
1334
|
+
*
|
|
1335
|
+
* A private market matches an order only with one aimed back at its owner, so
|
|
1336
|
+
* an order there names its counterparty: by `ownerTargetId` when the caller
|
|
1337
|
+
* knows it, or by `ownerTarget`, the allotment name. The id is the
|
|
1338
|
+
* unambiguous one, but only a manager can learn ids -- a participant's
|
|
1339
|
+
* `identifiers()` are names -- so a participant has the name and nothing
|
|
1340
|
+
* else. Name one or the other, not both.
|
|
1341
|
+
*
|
|
1342
|
+
* `clientDescription` is this order's own reference, as the server keeps it
|
|
1343
|
+
* on the order; it defaults to the description this client connected with.
|
|
1344
|
+
*/
|
|
1345
|
+
async submitLimit(marketplaceId, marketId, side, units, price, options = {}) {
|
|
1346
|
+
const { ownerTarget, ownerTargetId, clientDescription } = options;
|
|
1347
|
+
if (ownerTarget !== undefined && ownerTargetId !== undefined) {
|
|
1348
|
+
throw new InvalidArgumentError("Name the counterparty by ownerTarget or ownerTargetId, not both");
|
|
1349
|
+
}
|
|
1350
|
+
const order = {
|
|
1195
1351
|
marketplaceId,
|
|
1196
1352
|
marketId,
|
|
1197
1353
|
type: "LIMIT",
|
|
1198
1354
|
side,
|
|
1199
1355
|
units,
|
|
1200
1356
|
price,
|
|
1201
|
-
clientDescription: this._clientDescription,
|
|
1202
|
-
}
|
|
1357
|
+
clientDescription: clientDescription || this._clientDescription,
|
|
1358
|
+
};
|
|
1359
|
+
// Left out rather than sent as null: a target of null is a private order
|
|
1360
|
+
// aimed at nobody, which the server refuses.
|
|
1361
|
+
if (ownerTarget !== undefined)
|
|
1362
|
+
order.ownerTarget = ownerTarget;
|
|
1363
|
+
if (ownerTargetId !== undefined)
|
|
1364
|
+
order.ownerTargetId = ownerTargetId;
|
|
1365
|
+
// Named, so an order whose answer was lost can be sent again without
|
|
1366
|
+
// trading twice: fm-server answers a submission it already holds with the
|
|
1367
|
+
// order it made, not a second one. A send that lost its connection may or
|
|
1368
|
+
// may not have landed; reporting it as refused invited the caller to place
|
|
1369
|
+
// it again and double the position.
|
|
1370
|
+
order.submissionId = randomUUID();
|
|
1371
|
+
const url = `${this._marketplace(marketplaceId)}/orders`;
|
|
1372
|
+
let data;
|
|
1373
|
+
try {
|
|
1374
|
+
data = await this._post(url, order);
|
|
1375
|
+
}
|
|
1376
|
+
catch (e) {
|
|
1377
|
+
if (!answerLost(e))
|
|
1378
|
+
throw e;
|
|
1379
|
+
data = await this._post(url, order);
|
|
1380
|
+
}
|
|
1203
1381
|
return parseOrder(data);
|
|
1204
1382
|
}
|
|
1205
1383
|
/**
|
|
@@ -1311,6 +1489,14 @@ export class Flexemarkets {
|
|
|
1311
1489
|
: `${base}?cancelled=false`;
|
|
1312
1490
|
return (await this._get(url)).map(parseOrder);
|
|
1313
1491
|
}
|
|
1492
|
+
/**
|
|
1493
|
+
* A page of `orders()` with no filter -- cancellations left out, as there:
|
|
1494
|
+
* the newest `limit`, or of those whose id is below `before` -- a page's
|
|
1495
|
+
* `next`. The server answers at most 5,000.
|
|
1496
|
+
*/
|
|
1497
|
+
async ordersPage(marketplaceId, limit, before) {
|
|
1498
|
+
return this._page(`${this._marketplace(marketplaceId)}/orders?cancelled=false`, limit, before, parseOrder);
|
|
1499
|
+
}
|
|
1314
1500
|
/**
|
|
1315
1501
|
* One market's traded legs, as many as the server gives in one read
|
|
1316
1502
|
* ({@link MAX_TRADED_LEGS}), in the server's order.
|
|
@@ -1355,6 +1541,13 @@ export class Flexemarkets {
|
|
|
1355
1541
|
const url = `${this._marketplace(marketplaceId)}/connections`;
|
|
1356
1542
|
return (await this._get(url)).map(parseConnection);
|
|
1357
1543
|
}
|
|
1544
|
+
/**
|
|
1545
|
+
* A page of `connections()`: the newest `limit`, or of those whose id is below
|
|
1546
|
+
* `before` -- a page's `next`. The server answers at most 5,000.
|
|
1547
|
+
*/
|
|
1548
|
+
async connectionsPage(marketplaceId, limit, before) {
|
|
1549
|
+
return this._page(`${this._marketplace(marketplaceId)}/connections`, limit, before, parseConnection);
|
|
1550
|
+
}
|
|
1358
1551
|
// -- management ------------------------------------------------------------
|
|
1359
1552
|
//
|
|
1360
1553
|
// Running an experiment, as opposed to trading in one: set the opening
|
|
@@ -1381,7 +1574,7 @@ export class Flexemarkets {
|
|
|
1381
1574
|
catch (e) {
|
|
1382
1575
|
throw new InvalidArgumentError(`Marketplace definition is not valid JSON: ${e.message}`);
|
|
1383
1576
|
}
|
|
1384
|
-
return parseMarketplace(await this._post(this._v1("/marketplaces"), parsed));
|
|
1577
|
+
return parseMarketplace(await this._create((key) => this._post(this._v1("/marketplaces"), parsed, key)));
|
|
1385
1578
|
}
|
|
1386
1579
|
/** Opens the marketplace's session, returning it in its new state. */
|
|
1387
1580
|
async openSession(marketplaceId) {
|
|
@@ -1409,6 +1602,13 @@ export class Flexemarkets {
|
|
|
1409
1602
|
const data = await this._get(this._v1("/users"));
|
|
1410
1603
|
return data.map((u) => parsePerson(u));
|
|
1411
1604
|
}
|
|
1605
|
+
/**
|
|
1606
|
+
* A page of `users()`: the newest `limit`, or of those whose id is below
|
|
1607
|
+
* `before` -- a page's `next`. The server answers at most 5,000.
|
|
1608
|
+
*/
|
|
1609
|
+
async usersPage(limit, before) {
|
|
1610
|
+
return this._page(this._v1("/users"), limit, before, (u) => parsePerson(u));
|
|
1611
|
+
}
|
|
1412
1612
|
/** The opening positions of one allocation. */
|
|
1413
1613
|
async allotments(marketplaceId, allocationId) {
|
|
1414
1614
|
const url = `${this._marketplace(marketplaceId)}/allocations/${allocationId}/allotments`;
|
|
@@ -1428,7 +1628,7 @@ export class Flexemarkets {
|
|
|
1428
1628
|
async allocate(marketplaceId, holdings) {
|
|
1429
1629
|
const url = `${this._marketplace(marketplaceId)}/allocations`;
|
|
1430
1630
|
const body = holdings.map((h) => holdingToAllotment(marketplaceId, h));
|
|
1431
|
-
const data = await this._post(url, body);
|
|
1631
|
+
const data = await this._create((key) => this._post(url, body, key));
|
|
1432
1632
|
return allotmentsToHoldings(data.map(parseAllotment));
|
|
1433
1633
|
}
|
|
1434
1634
|
/**
|
|
@@ -1449,7 +1649,22 @@ export class Flexemarkets {
|
|
|
1449
1649
|
*/
|
|
1450
1650
|
async uploadHoldings(marketplaceId, filename) {
|
|
1451
1651
|
const url = `${this._marketplace(marketplaceId)}/allocations`;
|
|
1452
|
-
const data = (await this._sendCsv("POST", url, filename));
|
|
1652
|
+
const data = (await this._create((key) => this._sendCsv("POST", url, filename, key)));
|
|
1653
|
+
return allotmentsToHoldings(data.map(parseAllotment));
|
|
1654
|
+
}
|
|
1655
|
+
/**
|
|
1656
|
+
* Stage an allocation from holdings CSV text, as {@link uploadHoldings} does
|
|
1657
|
+
* from a file.
|
|
1658
|
+
*
|
|
1659
|
+
* For a program that builds the CSV rather than reading one -- an admin
|
|
1660
|
+
* robot writing back the holdings it downloaded and changed -- which
|
|
1661
|
+
* otherwise writes a file only to have it read again. The text is sent as it
|
|
1662
|
+
* is; a `# holdings -- begin` / `-- end` frame around it is accepted, as in a
|
|
1663
|
+
* downloaded file.
|
|
1664
|
+
*/
|
|
1665
|
+
async uploadHoldingsCsv(marketplaceId, csv) {
|
|
1666
|
+
const url = `${this._marketplace(marketplaceId)}/allocations`;
|
|
1667
|
+
const data = (await this._create((key) => this._sendCsvContent("POST", url, csv, key)));
|
|
1453
1668
|
return allotmentsToHoldings(data.map(parseAllotment));
|
|
1454
1669
|
}
|
|
1455
1670
|
/**
|
|
@@ -1489,7 +1704,8 @@ export class Flexemarkets {
|
|
|
1489
1704
|
*/
|
|
1490
1705
|
async pushWidgets(marketplaceId, widgets) {
|
|
1491
1706
|
const url = `${this._marketplace(marketplaceId)}/widgets`;
|
|
1492
|
-
const
|
|
1707
|
+
const pushes = widgets.map(widgetPushJson);
|
|
1708
|
+
const data = await this._create((key) => this._post(url, pushes, key));
|
|
1493
1709
|
return data.map(parseWidget);
|
|
1494
1710
|
}
|
|
1495
1711
|
/**
|
|
@@ -1538,14 +1754,22 @@ export class Flexemarkets {
|
|
|
1538
1754
|
* every trade does.
|
|
1539
1755
|
*/
|
|
1540
1756
|
async clearNow(marketplaceId, marketId) {
|
|
1541
|
-
|
|
1757
|
+
// Created where the calls are listed (fm-server 4.17); the market's own route is superseded.
|
|
1758
|
+
return parseMarketCall(await this._create((key) => this._post(`${this._marketplace(marketplaceId)}/calls`, { marketId }, key)));
|
|
1542
1759
|
}
|
|
1543
1760
|
/** Every call the marketplace's call markets have made, oldest first; one session's with `sessionId`. */
|
|
1544
1761
|
async calls(marketplaceId, sessionId) {
|
|
1545
|
-
const query = sessionId === undefined ? "" : `?
|
|
1762
|
+
const query = sessionId === undefined ? "" : `?sessions=${sessionId}`;
|
|
1546
1763
|
const data = await this._get(`${this._marketplace(marketplaceId)}/calls${query}`);
|
|
1547
1764
|
return data.map(parseMarketCall);
|
|
1548
1765
|
}
|
|
1766
|
+
/**
|
|
1767
|
+
* A page of `calls()`: the newest `limit`, or of those whose id is below
|
|
1768
|
+
* `before` -- a page's `next`. The server answers at most 5,000.
|
|
1769
|
+
*/
|
|
1770
|
+
async callsPage(marketplaceId, limit, before) {
|
|
1771
|
+
return this._page(`${this._marketplace(marketplaceId)}/calls`, limit, before, parseMarketCall);
|
|
1772
|
+
}
|
|
1549
1773
|
/**
|
|
1550
1774
|
* Every robot the marketplace's robot host offers, with whether it is
|
|
1551
1775
|
* enabled here and how a manager has configured its parameters.
|
|
@@ -1678,9 +1902,19 @@ export class Flexemarkets {
|
|
|
1678
1902
|
* Returns an unsubscribe function rather than an object with `close()`,
|
|
1679
1903
|
* matching what Desk's `on*` handlers already return here. Java
|
|
1680
1904
|
* returns a `Subscription`; both names describe the same lifetime.
|
|
1905
|
+
*
|
|
1906
|
+
* With `history`, the first orders update is every order of the current
|
|
1907
|
+
* session as this caller may see it -- cancelled and split ones included, a
|
|
1908
|
+
* counterparty's private order named from the caller's side -- stamped with
|
|
1909
|
+
* the `seq` it was read at, and each reconnect delivers it again. That is
|
|
1910
|
+
* fm-server's original subscribe, and the only whole history a participant
|
|
1911
|
+
* can read: the REST history is a manager's. Without it the first update is
|
|
1912
|
+
* empty and the book comes from `activeOrders`. A history is one frame, so on
|
|
1913
|
+
* a session with a very long one it is a large frame -- fm-server's V1
|
|
1914
|
+
* subscribe exists to avoid exactly that.
|
|
1681
1915
|
*/
|
|
1682
|
-
async subscribe(marketplaceId, callback) {
|
|
1683
|
-
const listener = await this._connectEvents(marketplaceId, callback);
|
|
1916
|
+
async subscribe(marketplaceId, callback, options = {}) {
|
|
1917
|
+
const listener = await this._connectEvents(marketplaceId, callback, options.history ?? false);
|
|
1684
1918
|
return () => {
|
|
1685
1919
|
void listener.close();
|
|
1686
1920
|
};
|
|
@@ -1691,11 +1925,11 @@ export class Flexemarkets {
|
|
|
1691
1925
|
* the singleton {@link #_eventListener}. Lets multiple
|
|
1692
1926
|
* desk(marketplaceId) calls coexist within one Flexemarkets.
|
|
1693
1927
|
*/
|
|
1694
|
-
async _connectEvents(marketplaceId, callback) {
|
|
1928
|
+
async _connectEvents(marketplaceId, callback, history = false) {
|
|
1695
1929
|
const wsUrl = server(this._endpoint)
|
|
1696
1930
|
.replace("https://", "wss://")
|
|
1697
1931
|
.replace("http://", "ws://") + "/v1/events";
|
|
1698
|
-
const events = new EventListener(wsUrl, () => this._bearerToken, marketplaceId, callback, this._clientDescription, parseHolding, parseOrder, (presented) => this._renewToken(presented));
|
|
1932
|
+
const events = new EventListener(wsUrl, () => this._bearerToken, marketplaceId, callback, this._clientDescription, parseHolding, parseOrder, (presented) => this._renewToken(presented), history);
|
|
1699
1933
|
await events.start();
|
|
1700
1934
|
return events;
|
|
1701
1935
|
}
|
|
@@ -1736,7 +1970,7 @@ export class Flexemarkets {
|
|
|
1736
1970
|
* stops working after hours while the robot runs on.
|
|
1737
1971
|
*/
|
|
1738
1972
|
async function renewWithRefreshToken(baseUrl, config) {
|
|
1739
|
-
const resp = await
|
|
1973
|
+
const resp = await fetchWithin(`${baseUrl}/v1/tokens/renew`, {
|
|
1740
1974
|
method: "POST",
|
|
1741
1975
|
headers: {
|
|
1742
1976
|
"Content-Type": "application/json",
|
|
@@ -1770,7 +2004,7 @@ async function signIn(baseUrl, config, clientDescription) {
|
|
|
1770
2004
|
// Python one never had it, so token auth returned 400 in both from the day
|
|
1771
2005
|
// it was written.
|
|
1772
2006
|
// POST, as minting a token is (fm-server 4.6).
|
|
1773
|
-
const resp = await
|
|
2007
|
+
const resp = await fetchWithin(`${baseUrl}/v1/tokens/refresh`, {
|
|
1774
2008
|
method: "POST",
|
|
1775
2009
|
headers: {
|
|
1776
2010
|
Authorization: `Bearer ${tok}`,
|
|
@@ -1792,7 +2026,7 @@ async function signIn(baseUrl, config, clientDescription) {
|
|
|
1792
2026
|
if (!password)
|
|
1793
2027
|
throw new ConfigurationError("Missing 'password' in configuration.");
|
|
1794
2028
|
const authUrl = `${baseUrl}/v1/tokens`;
|
|
1795
|
-
const resp = await
|
|
2029
|
+
const resp = await fetchWithin(authUrl, {
|
|
1796
2030
|
method: "POST",
|
|
1797
2031
|
headers: {
|
|
1798
2032
|
"Content-Type": "application/json",
|