@flexemarkets/fm-sdk 0.14.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.d.ts CHANGED
@@ -3,8 +3,9 @@
3
3
  *
4
4
  * Port of fm.client (Python) / fm.Flexemarkets (Java).
5
5
  */
6
- import type { Account, Allotment, ClientConnection, Holding, ManagerOtpBundle, Market, MarketCall, Marketplace, Order, ParticipantState, Person, Security, Session, TickGrid, Token, Widget, WidgetPush, MarketplaceRobot, RobotParameterConfig, RobotParameterControl } from "./types.js";
6
+ import type { Account, Allotment, CallIndicative, CurrentSession, ClientConnection, Holding, ManagerOtpBundle, Market, MarketCall, Marketplace, Order, ParticipantState, Person, Security, Session, TickGrid, Token, Widget, WidgetPush, MarketplaceRobot, RobotParameterConfig, RobotParameterControl } from "./types.js";
7
7
  import { EventListener, type EventCallback } from "./stomp.js";
8
+ import { type PendingOrder } from "./order-stream.js";
8
9
  import { type Desk, type Subscription } from "./desk.js";
9
10
  import type { Snapshot } from "./snapshot.js";
10
11
  import { Page } from "./page.js";
@@ -47,6 +48,19 @@ export declare class ConnectionFailedError extends FlexemarketsError {
47
48
  }
48
49
  export declare class ConfigurationError extends FlexemarketsError {
49
50
  }
51
+ /**
52
+ * An order was sent and no answer to it can now arrive.
53
+ *
54
+ * Not a refusal: fm-server may well have placed it. Thrown for an order sent
55
+ * over the socket that was still unanswered when its stream closed. Placing it
56
+ * again under a new submission risks holding the position twice; read the
57
+ * book, or the orders, to learn whether it stands. `submissionId` is the id it
58
+ * was sent under, which the order carries if it was placed.
59
+ */
60
+ export declare class OrderOutcomeUnknownError extends FlexemarketsError {
61
+ readonly submissionId: string | null;
62
+ constructor(message: string, submissionId?: string | null);
63
+ }
50
64
  /**
51
65
  * A response the SDK has no better name for, carrying its status and body.
52
66
  *
@@ -100,6 +114,8 @@ export declare function parseAccount(data: JsonObject | null | undefined): Accou
100
114
  export declare function parseToken(data: JsonObject): Token;
101
115
  export declare function parseSecurity(data: JsonObject): Security;
102
116
  export declare function parseMarket(data: JsonObject): Market;
117
+ export declare function parseCurrentSession(data: JsonObject): CurrentSession;
118
+ export declare function parseCallIndicative(data: JsonObject): CallIndicative;
103
119
  export declare function parseMarketCall(data: JsonObject): MarketCall;
104
120
  export declare function parseMarketplace(data: JsonObject): Marketplace;
105
121
  export declare function parseSession(data: JsonObject): Session;
@@ -156,6 +172,12 @@ export declare function loadConfig(): Record<string, string>;
156
172
  * order carried the whole JSON document.
157
173
  */
158
174
  export declare function detail(body: string): string;
175
+ /**
176
+ * The error for a refusal with this status and failure body. REST reads the
177
+ * status off the response; the socket's ORDER-REJECTED carries it in the body.
178
+ * One mapping, so an order refused either way throws the same thing.
179
+ */
180
+ export declare function refused(status: number, body: string): FlexemarketsError;
159
181
  /** How long a request may take, start to finish, before it is given up. */
160
182
  export declare const REQUEST_TIMEOUT_MS = 30000;
161
183
  /** The timeout in force: {@link REQUEST_TIMEOUT_MS}, unless a test has shortened it. */
@@ -315,8 +337,14 @@ export declare class Flexemarkets {
315
337
  * the latter. `carry` is whether what a call leaves unfilled waits for the
316
338
  * next one rather than being cancelled. A call market cannot be private, so
317
339
  * there is no flag for it here; the server refuses the combination.
340
+ *
341
+ * `callBook` is what the book shows during the call:
342
+ * {@link MARKET_CALL_BOOK_SEALED}, a participant's own orders only, or
343
+ * {@link MARKET_CALL_BOOK_INDICATIVE}, also the price it would clear at now
344
+ * and the volume. Left out, the server makes it sealed. Needs fm-server
345
+ * 4.17; an older one ignores it.
318
346
  */
319
- createCallMarket(marketplaceId: number, symbol: string, name: string, price: TickGrid, units?: TickGrid, intervalSeconds?: number | null, carry?: boolean): Promise<Market>;
347
+ createCallMarket(marketplaceId: number, symbol: string, name: string, price: TickGrid, units?: TickGrid, intervalSeconds?: number | null, carry?: boolean, callBook?: string): Promise<Market>;
320
348
  /**
321
349
  * Mint one-time passcodes for the given users.
322
350
  *
@@ -361,8 +389,31 @@ export declare class Flexemarkets {
361
389
  * `before` -- a page's `next`. The server answers at most 5,000.
362
390
  */
363
391
  marketplacesPage(limit: number, before?: number): Promise<Page<Marketplace>>;
392
+ /**
393
+ * Each marketplace `marketplaces()` lists that has a session, with that
394
+ * session: one read where `session()` would be one per marketplace. A
395
+ * marketplace that has never opened a session is left out.
396
+ */
397
+ currentSessions(): Promise<CurrentSession[]>;
398
+ /**
399
+ * A page of `currentSessions()`, paged by marketplace as `marketplacesPage()`
400
+ * pages: the current sessions of exactly the marketplaces that page holds. One
401
+ * with no session is left out, so a page can hold fewer rows than `limit` and
402
+ * still have a `next`.
403
+ */
404
+ currentSessionsPage(limit: number, before?: number): Promise<Page<CurrentSession>>;
364
405
  marketplace(marketplaceId: number): Promise<Marketplace>;
365
406
  markets(marketplaceId: number): Promise<Market[]>;
407
+ /**
408
+ * What an indicative call market's book would clear at now: the price and
409
+ * volume a call would make, read on subscribe. The stream then delivers
410
+ * each change as a {@link CallIndicative}; apply those with a higher `seq`
411
+ * for the same session.
412
+ *
413
+ * Only for a market that `showsIndicative()`, while a session is open; the
414
+ * server refuses a sealed market, a continuous one, or no session.
415
+ */
416
+ indicative(marketplaceId: number, marketId: number): Promise<CallIndicative>;
366
417
  /**
367
418
  * The token this connection signed in with.
368
419
  *
@@ -414,6 +465,28 @@ export declare class Flexemarkets {
414
465
  ownerTargetId?: number;
415
466
  clientDescription?: string;
416
467
  }): Promise<Order>;
468
+ /**
469
+ * Place a limit order without waiting for the answer.
470
+ *
471
+ * The order goes over the marketplace's socket and the {@link PendingOrder}
472
+ * this resolves to is there at once: the next order can go before this one
473
+ * is matched, and fm-server still matches them in the order sent. Its
474
+ * `result()` is the order, or the refusal {@link submitLimit} would have
475
+ * thrown -- or {@link OrderOutcomeUnknownError} if the socket closed before
476
+ * the answer came. The socket opens with the first order sent this way and
477
+ * stays open until {@link close}; at most `MAX_IN_FLIGHT` orders are
478
+ * unanswered at once, and this waits, in turn, while they are. The arguments
479
+ * are {@link submitLimit}'s. See docs/SUBMIT-RATE.md.
480
+ */
481
+ sendLimit(marketplaceId: number, marketId: number, side: string, units: number, price: number, options?: {
482
+ ownerTarget?: string;
483
+ ownerTargetId?: number;
484
+ clientDescription?: string;
485
+ }): Promise<PendingOrder>;
486
+ /** The body of a limit order, named with a fresh submission id. */
487
+ private _limitOrder;
488
+ /** The marketplace's order socket, opened on first use; one open for concurrent first callers. */
489
+ private _orderStream;
417
490
  /**
418
491
  * Cross the book: buy at the highest price this market allows, sell at the
419
492
  * lowest. Immediate or cancel — whatever does not fill is cancelled.
@@ -674,6 +747,8 @@ export declare class Flexemarkets {
674
747
  */
675
748
  configureRobotParameter(marketplaceId: number, robotId: string, paramName: string, value: string, control: RobotParameterControl | null): Promise<RobotParameterConfig>;
676
749
  private readonly _sharedViews;
750
+ /** The socket each marketplace's sendLimit orders go out on, opened by the first of them. */
751
+ private readonly _orderStreams;
677
752
  private readonly _sharedViewPromises;
678
753
  /**
679
754
  * Open a stateful Desk on this marketplace. Multiple calls
package/dist/client.js CHANGED
@@ -7,10 +7,11 @@ 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";
15
16
  import { Page } from "./page.js";
16
17
  import { readVersion } from "./version.js";
@@ -76,6 +77,22 @@ export class ConnectionFailedError extends FlexemarketsError {
76
77
  }
77
78
  export class ConfigurationError extends FlexemarketsError {
78
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
+ }
79
96
  /**
80
97
  * A response the SDK has no better name for, carrying its status and body.
81
98
  *
@@ -204,6 +221,25 @@ export function parseMarket(data) {
204
221
  callCarry: data.callCarry !== false,
205
222
  priceDecimals: data.priceDecimals ?? Decimals.DEFAULT_PRICE_DECIMALS,
206
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),
207
243
  };
208
244
  }
209
245
  export function parseMarketCall(data) {
@@ -269,6 +305,7 @@ export function parseOrder(data) {
269
305
  lastModifiedDate: toInstant(data.lastModifiedDate),
270
306
  mine: data.mine ?? null,
271
307
  originalSessionId: data.originalSessionId ?? null,
308
+ submissionId: data.submissionId ?? null,
272
309
  };
273
310
  }
274
311
  export function parseParticipantState(data) {
@@ -663,17 +700,25 @@ function checkResponse(response, body) {
663
700
  const status = response.status;
664
701
  if (status >= 200 && status < 300)
665
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) {
666
711
  if (status === 400)
667
- throw answered(new InvalidArgumentError("Invalid request: " + detail(body)), status, body);
712
+ return answered(new InvalidArgumentError("Invalid request: " + detail(body)), status, body);
668
713
  if (status === 401)
669
- throw answered(new AuthenticationError("Authentication failed: " + detail(body)), status, body);
714
+ return answered(new AuthenticationError("Authentication failed: " + detail(body)), status, body);
670
715
  if (status === 403)
671
- throw answered(new AuthorizationError("Not permitted: " + detail(body)), status, body);
716
+ return answered(new AuthorizationError("Not permitted: " + detail(body)), status, body);
672
717
  if (status === 409)
673
- throw answered(new ConflictError(body), status, body);
718
+ return answered(new ConflictError(body), status, body);
674
719
  if (status >= 500)
675
- throw answered(new ConnectionFailedError(body), status, body);
676
- 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);
677
722
  }
678
723
  /** The server's proposed alternative name, when a 409 body carries one. */
679
724
  function suggestedNameIn(body) {
@@ -1141,8 +1186,14 @@ export class Flexemarkets {
1141
1186
  * the latter. `carry` is whether what a call leaves unfilled waits for the
1142
1187
  * next one rather than being cancelled. A call market cannot be private, so
1143
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.
1144
1195
  */
1145
- async createCallMarket(marketplaceId, symbol, name, price, units = unitGrid(), intervalSeconds = null, carry = true) {
1196
+ async createCallMarket(marketplaceId, symbol, name, price, units = unitGrid(), intervalSeconds = null, carry = true, callBook) {
1146
1197
  return parseMarket(await this._create((key) => this._post(`${this._marketplace(marketplaceId)}/markets`, {
1147
1198
  symbol,
1148
1199
  name,
@@ -1156,6 +1207,7 @@ export class Flexemarkets {
1156
1207
  mechanism: MARKET_MECHANISM_CALL,
1157
1208
  callIntervalSeconds: intervalSeconds,
1158
1209
  callCarry: carry,
1210
+ ...(callBook === undefined ? {} : { callBook }),
1159
1211
  }, key)));
1160
1212
  }
1161
1213
  /**
@@ -1269,6 +1321,24 @@ export class Flexemarkets {
1269
1321
  async marketplacesPage(limit, before) {
1270
1322
  return this._page(this._v1("/marketplaces"), limit, before, parseMarketplace);
1271
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
+ }
1272
1342
  async marketplace(marketplaceId) {
1273
1343
  return parseMarketplace(await this._get(this._marketplace(marketplaceId)));
1274
1344
  }
@@ -1277,6 +1347,18 @@ export class Flexemarkets {
1277
1347
  const data = await this._get(`${this._marketplace(marketplaceId)}/markets`);
1278
1348
  return data.map(parseMarket);
1279
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
+ }
1280
1362
  /**
1281
1363
  * The token this connection signed in with.
1282
1364
  *
@@ -1343,6 +1425,38 @@ export class Flexemarkets {
1343
1425
  * on the order; it defaults to the description this client connected with.
1344
1426
  */
1345
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) {
1346
1460
  const { ownerTarget, ownerTargetId, clientDescription } = options;
1347
1461
  if (ownerTarget !== undefined && ownerTargetId !== undefined) {
1348
1462
  throw new InvalidArgumentError("Name the counterparty by ownerTarget or ownerTargetId, not both");
@@ -1368,17 +1482,21 @@ export class Flexemarkets {
1368
1482
  // may not have landed; reporting it as refused invited the caller to place
1369
1483
  // it again and double the position.
1370
1484
  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);
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));
1380
1498
  }
1381
- return parseOrder(data);
1499
+ return stream;
1382
1500
  }
1383
1501
  /**
1384
1502
  * Cross the book: buy at the highest price this market allows, sell at the
@@ -1808,6 +1926,8 @@ export class Flexemarkets {
1808
1926
  }
1809
1927
  // -- events / WebSocket ----------------------------------------------------
1810
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();
1811
1931
  _sharedViewPromises = new Map();
1812
1932
  /**
1813
1933
  * Open a stateful Desk on this marketplace. Multiple calls
@@ -1929,7 +2049,7 @@ export class Flexemarkets {
1929
2049
  const wsUrl = server(this._endpoint)
1930
2050
  .replace("https://", "wss://")
1931
2051
  .replace("http://", "ws://") + "/v1/events";
1932
- 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);
1933
2053
  await events.start();
1934
2054
  return events;
1935
2055
  }
@@ -1941,6 +2061,12 @@ export class Flexemarkets {
1941
2061
  }
1942
2062
  // -- lifecycle -------------------------------------------------------------
1943
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();
1944
2070
  if (this._eventListener !== null) {
1945
2071
  this._eventListener.close();
1946
2072
  this._eventListener = null;