@flexemarkets/fm-sdk 0.13.0 → 0.15.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/dist/client.js CHANGED
@@ -7,11 +7,13 @@ import { randomUUID } from "node:crypto";
7
7
  import { readFileSync, existsSync } from "node:fs";
8
8
  import { homedir } from "node:os";
9
9
  import { join } from "node:path";
10
- import { MARKET_MECHANISM_CALL, MARKET_MECHANISM_CONTINUOUS, orderedSecurities, toOrderType, toSide, unitGrid } from "./types.js";
10
+ import { MARKET_CALL_BOOK_SEALED, MARKET_MECHANISM_CALL, MARKET_MECHANISM_CONTINUOUS, orderedSecurities, toOrderType, toSide, unitGrid } from "./types.js";
11
11
  import { toInstant } from "./timestamps.js";
12
12
  import { Decimals } from "./decimals.js";
13
13
  import { EventListener, NO_SEQ } from "./stomp.js";
14
+ import { OrderStream } from "./order-stream.js";
14
15
  import { DefaultDesk, DeskHandle, } from "./desk.js";
16
+ import { Page } from "./page.js";
15
17
  import { readVersion } from "./version.js";
16
18
  const FM_NETWORK_CLIENT = `fm-sdk-typescript/${readVersion()}`;
17
19
  export const DEFAULT_ENDPOINT = "https://api.flexemarkets.com";
@@ -29,6 +31,8 @@ const REFRESH_TOKEN_PREFIX = "refresh:";
29
31
  const MAX_TRADED_LEGS = 5000;
30
32
  const BCRYPT_RE = /^\$2[abxy]?\$\d{2}\$[./A-Za-z0-9]{53}$/;
31
33
  const JWT_RE = /^[A-Za-z0-9\-_]+\.[A-Za-z0-9\-_]+\.[A-Za-z0-9\-_]+$/;
34
+ /** The `before` in a `Link` header's `rel="next"` target: where a page's older rows start. */
35
+ const NEXT_LINK = /<[^>]*[?&]before=(\d+)[^>]*>\s*;\s*rel="?next"?/;
32
36
  // ---------------------------------------------------------------------------
33
37
  // Errors
34
38
  // ---------------------------------------------------------------------------
@@ -73,6 +77,22 @@ export class ConnectionFailedError extends FlexemarketsError {
73
77
  }
74
78
  export class ConfigurationError extends FlexemarketsError {
75
79
  }
80
+ /**
81
+ * An order was sent and no answer to it can now arrive.
82
+ *
83
+ * Not a refusal: fm-server may well have placed it. Thrown for an order sent
84
+ * over the socket that was still unanswered when its stream closed. Placing it
85
+ * again under a new submission risks holding the position twice; read the
86
+ * book, or the orders, to learn whether it stands. `submissionId` is the id it
87
+ * was sent under, which the order carries if it was placed.
88
+ */
89
+ export class OrderOutcomeUnknownError extends FlexemarketsError {
90
+ submissionId;
91
+ constructor(message, submissionId = null) {
92
+ super(message);
93
+ this.submissionId = submissionId;
94
+ }
95
+ }
76
96
  /**
77
97
  * A response the SDK has no better name for, carrying its status and body.
78
98
  *
@@ -201,6 +221,25 @@ export function parseMarket(data) {
201
221
  callCarry: data.callCarry !== false,
202
222
  priceDecimals: data.priceDecimals ?? Decimals.DEFAULT_PRICE_DECIMALS,
203
223
  unitDecimals: data.unitDecimals ?? Decimals.DEFAULT_UNIT_DECIMALS,
224
+ callBook: data.callBook || MARKET_CALL_BOOK_SEALED,
225
+ };
226
+ }
227
+ export function parseCurrentSession(data) {
228
+ return {
229
+ marketplaceId: data.marketplaceId ?? 0,
230
+ sessionId: data.sessionId ?? 0,
231
+ state: data.state ?? "",
232
+ };
233
+ }
234
+ export function parseCallIndicative(data) {
235
+ return {
236
+ marketplaceId: data.marketplaceId ?? 0,
237
+ marketId: data.marketId ?? 0,
238
+ sessionId: data.sessionId ?? 0,
239
+ price: data.price ?? null,
240
+ volume: data.volume ?? 0,
241
+ seq: data.seq ?? 0,
242
+ at: toInstant(data.at),
204
243
  };
205
244
  }
206
245
  export function parseMarketCall(data) {
@@ -266,6 +305,7 @@ export function parseOrder(data) {
266
305
  lastModifiedDate: toInstant(data.lastModifiedDate),
267
306
  mine: data.mine ?? null,
268
307
  originalSessionId: data.originalSessionId ?? null,
308
+ submissionId: data.submissionId ?? null,
269
309
  };
270
310
  }
271
311
  export function parseParticipantState(data) {
@@ -660,17 +700,25 @@ function checkResponse(response, body) {
660
700
  const status = response.status;
661
701
  if (status >= 200 && status < 300)
662
702
  return;
703
+ throw refused(status, body);
704
+ }
705
+ /**
706
+ * The error for a refusal with this status and failure body. REST reads the
707
+ * status off the response; the socket's ORDER-REJECTED carries it in the body.
708
+ * One mapping, so an order refused either way throws the same thing.
709
+ */
710
+ export function refused(status, body) {
663
711
  if (status === 400)
664
- throw answered(new InvalidArgumentError("Invalid request: " + detail(body)), status, body);
712
+ return answered(new InvalidArgumentError("Invalid request: " + detail(body)), status, body);
665
713
  if (status === 401)
666
- throw answered(new AuthenticationError("Authentication failed: " + detail(body)), status, body);
714
+ return answered(new AuthenticationError("Authentication failed: " + detail(body)), status, body);
667
715
  if (status === 403)
668
- throw answered(new AuthorizationError("Not permitted: " + detail(body)), status, body);
716
+ return answered(new AuthorizationError("Not permitted: " + detail(body)), status, body);
669
717
  if (status === 409)
670
- throw answered(new ConflictError(body), status, body);
718
+ return answered(new ConflictError(body), status, body);
671
719
  if (status >= 500)
672
- throw answered(new ConnectionFailedError(body), status, body);
673
- throw answered(new HttpError(status, body), status, body);
720
+ return answered(new ConnectionFailedError(body), status, body);
721
+ return answered(new HttpError(status, body), status, body);
674
722
  }
675
723
  /** The server's proposed alternative name, when a 409 body carries one. */
676
724
  function suggestedNameIn(body) {
@@ -905,6 +953,13 @@ export class Flexemarkets {
905
953
  * `Snapshot.NO_SEQ` when the header is absent.
906
954
  */
907
955
  async _getSnapshot(url) {
956
+ const { data, headers } = await this._getRead(url);
957
+ const raw = headers.get("x-fm-as-of-seq");
958
+ const asOfSeq = raw === null ? NO_SEQ : Number.parseInt(raw, 10);
959
+ return { data, asOfSeq: Number.isFinite(asOfSeq) ? asOfSeq : NO_SEQ };
960
+ }
961
+ /** GET a body the answer needs a response header beside: a snapshot's sequence, a page's next link. */
962
+ async _getRead(url) {
908
963
  const resp = await this._fetch(url.startsWith("/") ? `${this._baseUrl}${url}` : url, {
909
964
  headers: {
910
965
  ...this._authHeaders(),
@@ -914,9 +969,18 @@ export class Flexemarkets {
914
969
  });
915
970
  const body = await resp.text();
916
971
  checkResponse(resp, body);
917
- const raw = resp.headers.get("x-fm-as-of-seq");
918
- const asOfSeq = raw === null ? NO_SEQ : Number.parseInt(raw, 10);
919
- return { data: readBody(body), asOfSeq: Number.isFinite(asOfSeq) ? asOfSeq : NO_SEQ };
972
+ return { data: readBody(body), headers: resp.headers };
973
+ }
974
+ /**
975
+ * A page of a collection: `url` with `?limit=` and `?before=`, and the
976
+ * `before` of the page after it read from the `Link: <...>; rel="next"` the
977
+ * server sends while older rows remain.
978
+ */
979
+ async _page(url, limit, before, parse) {
980
+ const paged = `${url}${url.includes("?") ? "&" : "?"}limit=${limit}${before === undefined ? "" : `&before=${before}`}`;
981
+ const { data, headers } = await this._getRead(paged);
982
+ const next = NEXT_LINK.exec(headers.get("link") ?? "");
983
+ return new Page(data.map(parse), next === null ? null : Number.parseInt(next[1], 10));
920
984
  }
921
985
  /** PATCH with a JSON body -- the shape every session transition takes. */
922
986
  async _patch(url, json) {
@@ -958,7 +1022,7 @@ export class Flexemarkets {
958
1022
  checkResponse(resp, body);
959
1023
  return body;
960
1024
  }
961
- async _post(url, json) {
1025
+ async _post(url, json, headers = {}) {
962
1026
  const resp = await this._fetch(url.startsWith("/") ? `${this._baseUrl}${url}` : url, {
963
1027
  method: "POST",
964
1028
  headers: {
@@ -966,6 +1030,7 @@ export class Flexemarkets {
966
1030
  "Content-Type": "application/json",
967
1031
  Accept: "application/json",
968
1032
  "User-Agent": FM_NETWORK_CLIENT,
1033
+ ...headers,
969
1034
  },
970
1035
  body: JSON.stringify(json),
971
1036
  });
@@ -1053,13 +1118,21 @@ export class Flexemarkets {
1053
1118
  const data = await this._get(this._v1("/accounts"));
1054
1119
  return data.map(parseAccount);
1055
1120
  }
1121
+ /**
1122
+ * A page of `accounts()`: the newest `limit`, or of those whose id is below
1123
+ * `before` -- a page's `next`. The server answers at most 5,000.
1124
+ */
1125
+ async accountsPage(limit, before) {
1126
+ return this._page(this._v1("/accounts"), limit, before, (a) => parseAccount(a));
1127
+ }
1056
1128
  /** Delete an account. Destructive, and takes its users with it. */
1057
1129
  async deleteAccount(accountId) {
1058
1130
  await this._delete(this._v1(`/accounts/${accountId}`));
1059
1131
  }
1060
1132
  /** Create a user in the caller's account. */
1061
1133
  async createUser(email, password, firstName, lastName, roles = []) {
1062
- const data = await this._post(this._v1("/users"), { email, password, firstName, lastName, roles });
1134
+ const user = { email, password, firstName, lastName, roles };
1135
+ const data = await this._create((key) => this._post(this._v1("/users"), user, key));
1063
1136
  return parsePerson(data);
1064
1137
  }
1065
1138
  /** Delete a user. Destructive. */
@@ -1092,7 +1165,7 @@ export class Flexemarkets {
1092
1165
  * `units` keeps the old default.
1093
1166
  */
1094
1167
  async createMarket(marketplaceId, symbol, name, price, units = unitGrid(), privateMarket = false) {
1095
- return parseMarket(await this._post(`${this._marketplace(marketplaceId)}/markets`, {
1168
+ return parseMarket(await this._create((key) => this._post(`${this._marketplace(marketplaceId)}/markets`, {
1096
1169
  symbol,
1097
1170
  name,
1098
1171
  priceMinimum: price.minimum,
@@ -1102,7 +1175,7 @@ export class Flexemarkets {
1102
1175
  unitMaximum: units.maximum,
1103
1176
  unitTick: units.tick,
1104
1177
  privateMarket,
1105
- }));
1178
+ }, key)));
1106
1179
  }
1107
1180
  /**
1108
1181
  * Add a call-auction market to a marketplace: orders collect, crossed or
@@ -1113,9 +1186,15 @@ export class Flexemarkets {
1113
1186
  * the latter. `carry` is whether what a call leaves unfilled waits for the
1114
1187
  * next one rather than being cancelled. A call market cannot be private, so
1115
1188
  * there is no flag for it here; the server refuses the combination.
1189
+ *
1190
+ * `callBook` is what the book shows during the call:
1191
+ * {@link MARKET_CALL_BOOK_SEALED}, a participant's own orders only, or
1192
+ * {@link MARKET_CALL_BOOK_INDICATIVE}, also the price it would clear at now
1193
+ * and the volume. Left out, the server makes it sealed. Needs fm-server
1194
+ * 4.17; an older one ignores it.
1116
1195
  */
1117
- async createCallMarket(marketplaceId, symbol, name, price, units = unitGrid(), intervalSeconds = null, carry = true) {
1118
- return parseMarket(await this._post(`${this._marketplace(marketplaceId)}/markets`, {
1196
+ async createCallMarket(marketplaceId, symbol, name, price, units = unitGrid(), intervalSeconds = null, carry = true, callBook) {
1197
+ return parseMarket(await this._create((key) => this._post(`${this._marketplace(marketplaceId)}/markets`, {
1119
1198
  symbol,
1120
1199
  name,
1121
1200
  priceMinimum: price.minimum,
@@ -1128,7 +1207,8 @@ export class Flexemarkets {
1128
1207
  mechanism: MARKET_MECHANISM_CALL,
1129
1208
  callIntervalSeconds: intervalSeconds,
1130
1209
  callCarry: carry,
1131
- }));
1210
+ ...(callBook === undefined ? {} : { callBook }),
1211
+ }, key)));
1132
1212
  }
1133
1213
  /**
1134
1214
  * Mint one-time passcodes for the given users.
@@ -1175,11 +1255,30 @@ export class Flexemarkets {
1175
1255
  * header, where 0.3 posted it as a multipart upload to an `/uploads`
1176
1256
  * segment. Bytes, not a string, so the file's own encoding survives.
1177
1257
  */
1178
- async _sendCsv(method, url, filename) {
1179
- return this._sendCsvContent(method, url, readFileSync(filename));
1258
+ /**
1259
+ * Send a create under an `Idempotency-Key`, and once more under the same key
1260
+ * if its answer was lost. A create that lost its connection may or may not
1261
+ * have landed; fm-server 4.17 answers a key it already holds with what it
1262
+ * answered the first time (its IdempotencyFilter), so the resend makes one
1263
+ * marketplace, market or call, never two. Orders do the same with their own
1264
+ * `submissionId`.
1265
+ */
1266
+ async _create(send) {
1267
+ const key = { "Idempotency-Key": randomUUID() };
1268
+ try {
1269
+ return await send(key);
1270
+ }
1271
+ catch (e) {
1272
+ if (!answerLost(e))
1273
+ throw e;
1274
+ return send(key);
1275
+ }
1276
+ }
1277
+ async _sendCsv(method, url, filename, headers = {}) {
1278
+ return this._sendCsvContent(method, url, readFileSync(filename), headers);
1180
1279
  }
1181
1280
  /** CSV as the request body, declared text/csv; see {@link _sendCsv}. */
1182
- async _sendCsvContent(method, url, content) {
1281
+ async _sendCsvContent(method, url, content, headers = {}) {
1183
1282
  const resp = await this._fetch(url, {
1184
1283
  method,
1185
1284
  headers: {
@@ -1187,6 +1286,7 @@ export class Flexemarkets {
1187
1286
  "Content-Type": "text/csv",
1188
1287
  Accept: "application/json",
1189
1288
  "User-Agent": FM_NETWORK_CLIENT,
1289
+ ...headers,
1190
1290
  },
1191
1291
  body: content,
1192
1292
  });
@@ -1214,6 +1314,31 @@ export class Flexemarkets {
1214
1314
  const data = await this._get(this._v1("/marketplaces"));
1215
1315
  return data.map(parseMarketplace);
1216
1316
  }
1317
+ /**
1318
+ * A page of `marketplaces()`: the newest `limit`, or of those whose id is below
1319
+ * `before` -- a page's `next`. The server answers at most 5,000.
1320
+ */
1321
+ async marketplacesPage(limit, before) {
1322
+ return this._page(this._v1("/marketplaces"), limit, before, parseMarketplace);
1323
+ }
1324
+ /**
1325
+ * Each marketplace `marketplaces()` lists that has a session, with that
1326
+ * session: one read where `session()` would be one per marketplace. A
1327
+ * marketplace that has never opened a session is left out.
1328
+ */
1329
+ async currentSessions() {
1330
+ const data = await this._get(this._v1("/marketplaces/current-sessions"));
1331
+ return data.map(parseCurrentSession);
1332
+ }
1333
+ /**
1334
+ * A page of `currentSessions()`, paged by marketplace as `marketplacesPage()`
1335
+ * pages: the current sessions of exactly the marketplaces that page holds. One
1336
+ * with no session is left out, so a page can hold fewer rows than `limit` and
1337
+ * still have a `next`.
1338
+ */
1339
+ async currentSessionsPage(limit, before) {
1340
+ return this._page(this._v1("/marketplaces/current-sessions"), limit, before, parseCurrentSession);
1341
+ }
1217
1342
  async marketplace(marketplaceId) {
1218
1343
  return parseMarketplace(await this._get(this._marketplace(marketplaceId)));
1219
1344
  }
@@ -1222,6 +1347,18 @@ export class Flexemarkets {
1222
1347
  const data = await this._get(`${this._marketplace(marketplaceId)}/markets`);
1223
1348
  return data.map(parseMarket);
1224
1349
  }
1350
+ /**
1351
+ * What an indicative call market's book would clear at now: the price and
1352
+ * volume a call would make, read on subscribe. The stream then delivers
1353
+ * each change as a {@link CallIndicative}; apply those with a higher `seq`
1354
+ * for the same session.
1355
+ *
1356
+ * Only for a market that `showsIndicative()`, while a session is open; the
1357
+ * server refuses a sealed market, a continuous one, or no session.
1358
+ */
1359
+ async indicative(marketplaceId, marketId) {
1360
+ return parseCallIndicative(await this._get(`${this._marketplace(marketplaceId)}/markets/${marketId}/indicative`));
1361
+ }
1225
1362
  /**
1226
1363
  * The token this connection signed in with.
1227
1364
  *
@@ -1263,6 +1400,13 @@ export class Flexemarkets {
1263
1400
  const url = `${this._marketplace(marketplaceId)}/sessions`;
1264
1401
  return (await this._get(url)).map(parseSession);
1265
1402
  }
1403
+ /**
1404
+ * A page of `sessions()`: the newest `limit`, or of those whose id is below
1405
+ * `before` -- a page's `next`. The server answers at most 5,000.
1406
+ */
1407
+ async sessionsPage(marketplaceId, limit, before) {
1408
+ return this._page(`${this._marketplace(marketplaceId)}/sessions`, limit, before, parseSession);
1409
+ }
1266
1410
  async session(marketplaceId) {
1267
1411
  return parseSession(await this._get(`${this._marketplace(marketplaceId)}/sessions/current`));
1268
1412
  }
@@ -1281,6 +1425,38 @@ export class Flexemarkets {
1281
1425
  * on the order; it defaults to the description this client connected with.
1282
1426
  */
1283
1427
  async submitLimit(marketplaceId, marketId, side, units, price, options = {}) {
1428
+ const order = this._limitOrder(marketplaceId, marketId, side, units, price, options);
1429
+ const url = `${this._marketplace(marketplaceId)}/orders`;
1430
+ let data;
1431
+ try {
1432
+ data = await this._post(url, order);
1433
+ }
1434
+ catch (e) {
1435
+ if (!answerLost(e))
1436
+ throw e;
1437
+ data = await this._post(url, order);
1438
+ }
1439
+ return parseOrder(data);
1440
+ }
1441
+ /**
1442
+ * Place a limit order without waiting for the answer.
1443
+ *
1444
+ * The order goes over the marketplace's socket and the {@link PendingOrder}
1445
+ * this resolves to is there at once: the next order can go before this one
1446
+ * is matched, and fm-server still matches them in the order sent. Its
1447
+ * `result()` is the order, or the refusal {@link submitLimit} would have
1448
+ * thrown -- or {@link OrderOutcomeUnknownError} if the socket closed before
1449
+ * the answer came. The socket opens with the first order sent this way and
1450
+ * stays open until {@link close}; at most `MAX_IN_FLIGHT` orders are
1451
+ * unanswered at once, and this waits, in turn, while they are. The arguments
1452
+ * are {@link submitLimit}'s. See docs/SUBMIT-RATE.md.
1453
+ */
1454
+ async sendLimit(marketplaceId, marketId, side, units, price, options = {}) {
1455
+ const order = this._limitOrder(marketplaceId, marketId, side, units, price, options);
1456
+ return (await this._orderStream(marketplaceId)).submit(order);
1457
+ }
1458
+ /** The body of a limit order, named with a fresh submission id. */
1459
+ _limitOrder(marketplaceId, marketId, side, units, price, options) {
1284
1460
  const { ownerTarget, ownerTargetId, clientDescription } = options;
1285
1461
  if (ownerTarget !== undefined && ownerTargetId !== undefined) {
1286
1462
  throw new InvalidArgumentError("Name the counterparty by ownerTarget or ownerTargetId, not both");
@@ -1306,17 +1482,21 @@ export class Flexemarkets {
1306
1482
  // may not have landed; reporting it as refused invited the caller to place
1307
1483
  // it again and double the position.
1308
1484
  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);
1485
+ return order;
1486
+ }
1487
+ /** The marketplace's order socket, opened on first use; one open for concurrent first callers. */
1488
+ _orderStream(marketplaceId) {
1489
+ let stream = this._orderStreams.get(marketplaceId);
1490
+ if (stream === undefined) {
1491
+ stream = OrderStream.open((callback) => this._connectEvents(marketplaceId, callback), marketplaceId, {
1492
+ notSent: (message) => new ConnectionFailedError(message),
1493
+ outcomeUnknown: (message, submissionId) => new OrderOutcomeUnknownError(message, submissionId),
1494
+ });
1495
+ this._orderStreams.set(marketplaceId, stream);
1496
+ // One that could not open is forgotten, so the next order tries again.
1497
+ stream.catch(() => this._orderStreams.delete(marketplaceId));
1318
1498
  }
1319
- return parseOrder(data);
1499
+ return stream;
1320
1500
  }
1321
1501
  /**
1322
1502
  * Cross the book: buy at the highest price this market allows, sell at the
@@ -1427,6 +1607,14 @@ export class Flexemarkets {
1427
1607
  : `${base}?cancelled=false`;
1428
1608
  return (await this._get(url)).map(parseOrder);
1429
1609
  }
1610
+ /**
1611
+ * A page of `orders()` with no filter -- cancellations left out, as there:
1612
+ * the newest `limit`, or of those whose id is below `before` -- a page's
1613
+ * `next`. The server answers at most 5,000.
1614
+ */
1615
+ async ordersPage(marketplaceId, limit, before) {
1616
+ return this._page(`${this._marketplace(marketplaceId)}/orders?cancelled=false`, limit, before, parseOrder);
1617
+ }
1430
1618
  /**
1431
1619
  * One market's traded legs, as many as the server gives in one read
1432
1620
  * ({@link MAX_TRADED_LEGS}), in the server's order.
@@ -1471,6 +1659,13 @@ export class Flexemarkets {
1471
1659
  const url = `${this._marketplace(marketplaceId)}/connections`;
1472
1660
  return (await this._get(url)).map(parseConnection);
1473
1661
  }
1662
+ /**
1663
+ * A page of `connections()`: the newest `limit`, or of those whose id is below
1664
+ * `before` -- a page's `next`. The server answers at most 5,000.
1665
+ */
1666
+ async connectionsPage(marketplaceId, limit, before) {
1667
+ return this._page(`${this._marketplace(marketplaceId)}/connections`, limit, before, parseConnection);
1668
+ }
1474
1669
  // -- management ------------------------------------------------------------
1475
1670
  //
1476
1671
  // Running an experiment, as opposed to trading in one: set the opening
@@ -1497,7 +1692,7 @@ export class Flexemarkets {
1497
1692
  catch (e) {
1498
1693
  throw new InvalidArgumentError(`Marketplace definition is not valid JSON: ${e.message}`);
1499
1694
  }
1500
- return parseMarketplace(await this._post(this._v1("/marketplaces"), parsed));
1695
+ return parseMarketplace(await this._create((key) => this._post(this._v1("/marketplaces"), parsed, key)));
1501
1696
  }
1502
1697
  /** Opens the marketplace's session, returning it in its new state. */
1503
1698
  async openSession(marketplaceId) {
@@ -1525,6 +1720,13 @@ export class Flexemarkets {
1525
1720
  const data = await this._get(this._v1("/users"));
1526
1721
  return data.map((u) => parsePerson(u));
1527
1722
  }
1723
+ /**
1724
+ * A page of `users()`: the newest `limit`, or of those whose id is below
1725
+ * `before` -- a page's `next`. The server answers at most 5,000.
1726
+ */
1727
+ async usersPage(limit, before) {
1728
+ return this._page(this._v1("/users"), limit, before, (u) => parsePerson(u));
1729
+ }
1528
1730
  /** The opening positions of one allocation. */
1529
1731
  async allotments(marketplaceId, allocationId) {
1530
1732
  const url = `${this._marketplace(marketplaceId)}/allocations/${allocationId}/allotments`;
@@ -1544,7 +1746,7 @@ export class Flexemarkets {
1544
1746
  async allocate(marketplaceId, holdings) {
1545
1747
  const url = `${this._marketplace(marketplaceId)}/allocations`;
1546
1748
  const body = holdings.map((h) => holdingToAllotment(marketplaceId, h));
1547
- const data = await this._post(url, body);
1749
+ const data = await this._create((key) => this._post(url, body, key));
1548
1750
  return allotmentsToHoldings(data.map(parseAllotment));
1549
1751
  }
1550
1752
  /**
@@ -1565,7 +1767,7 @@ export class Flexemarkets {
1565
1767
  */
1566
1768
  async uploadHoldings(marketplaceId, filename) {
1567
1769
  const url = `${this._marketplace(marketplaceId)}/allocations`;
1568
- const data = (await this._sendCsv("POST", url, filename));
1770
+ const data = (await this._create((key) => this._sendCsv("POST", url, filename, key)));
1569
1771
  return allotmentsToHoldings(data.map(parseAllotment));
1570
1772
  }
1571
1773
  /**
@@ -1580,7 +1782,7 @@ export class Flexemarkets {
1580
1782
  */
1581
1783
  async uploadHoldingsCsv(marketplaceId, csv) {
1582
1784
  const url = `${this._marketplace(marketplaceId)}/allocations`;
1583
- const data = (await this._sendCsvContent("POST", url, csv));
1785
+ const data = (await this._create((key) => this._sendCsvContent("POST", url, csv, key)));
1584
1786
  return allotmentsToHoldings(data.map(parseAllotment));
1585
1787
  }
1586
1788
  /**
@@ -1620,7 +1822,8 @@ export class Flexemarkets {
1620
1822
  */
1621
1823
  async pushWidgets(marketplaceId, widgets) {
1622
1824
  const url = `${this._marketplace(marketplaceId)}/widgets`;
1623
- const data = await this._post(url, widgets.map(widgetPushJson));
1825
+ const pushes = widgets.map(widgetPushJson);
1826
+ const data = await this._create((key) => this._post(url, pushes, key));
1624
1827
  return data.map(parseWidget);
1625
1828
  }
1626
1829
  /**
@@ -1669,14 +1872,22 @@ export class Flexemarkets {
1669
1872
  * every trade does.
1670
1873
  */
1671
1874
  async clearNow(marketplaceId, marketId) {
1672
- return parseMarketCall(await this._post(`${this._marketplace(marketplaceId)}/markets/${marketId}/calls`, null));
1875
+ // Created where the calls are listed (fm-server 4.17); the market's own route is superseded.
1876
+ return parseMarketCall(await this._create((key) => this._post(`${this._marketplace(marketplaceId)}/calls`, { marketId }, key)));
1673
1877
  }
1674
1878
  /** Every call the marketplace's call markets have made, oldest first; one session's with `sessionId`. */
1675
1879
  async calls(marketplaceId, sessionId) {
1676
- const query = sessionId === undefined ? "" : `?sessionId=${sessionId}`;
1880
+ const query = sessionId === undefined ? "" : `?sessions=${sessionId}`;
1677
1881
  const data = await this._get(`${this._marketplace(marketplaceId)}/calls${query}`);
1678
1882
  return data.map(parseMarketCall);
1679
1883
  }
1884
+ /**
1885
+ * A page of `calls()`: the newest `limit`, or of those whose id is below
1886
+ * `before` -- a page's `next`. The server answers at most 5,000.
1887
+ */
1888
+ async callsPage(marketplaceId, limit, before) {
1889
+ return this._page(`${this._marketplace(marketplaceId)}/calls`, limit, before, parseMarketCall);
1890
+ }
1680
1891
  /**
1681
1892
  * Every robot the marketplace's robot host offers, with whether it is
1682
1893
  * enabled here and how a manager has configured its parameters.
@@ -1715,6 +1926,8 @@ export class Flexemarkets {
1715
1926
  }
1716
1927
  // -- events / WebSocket ----------------------------------------------------
1717
1928
  _sharedViews = new Map();
1929
+ /** The socket each marketplace's sendLimit orders go out on, opened by the first of them. */
1930
+ _orderStreams = new Map();
1718
1931
  _sharedViewPromises = new Map();
1719
1932
  /**
1720
1933
  * Open a stateful Desk on this marketplace. Multiple calls
@@ -1836,7 +2049,7 @@ export class Flexemarkets {
1836
2049
  const wsUrl = server(this._endpoint)
1837
2050
  .replace("https://", "wss://")
1838
2051
  .replace("http://", "ws://") + "/v1/events";
1839
- const events = new EventListener(wsUrl, () => this._bearerToken, marketplaceId, callback, this._clientDescription, parseHolding, parseOrder, (presented) => this._renewToken(presented), history);
2052
+ const events = new EventListener(wsUrl, () => this._bearerToken, marketplaceId, callback, this._clientDescription, parseHolding, parseOrder, (presented) => this._renewToken(presented), history, refused);
1840
2053
  await events.start();
1841
2054
  return events;
1842
2055
  }
@@ -1848,6 +2061,12 @@ export class Flexemarkets {
1848
2061
  }
1849
2062
  // -- lifecycle -------------------------------------------------------------
1850
2063
  close() {
2064
+ // Before the listeners: an order still unanswered is told so, rather than
2065
+ // waiting on a socket that has gone.
2066
+ for (const stream of this._orderStreams.values()) {
2067
+ stream.then((s) => s.close(), () => { });
2068
+ }
2069
+ this._orderStreams.clear();
1851
2070
  if (this._eventListener !== null) {
1852
2071
  this._eventListener.close();
1853
2072
  this._eventListener = null;