@stxapp/stx-typescript 0.7.0 → 0.8.1

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.
@@ -114,6 +114,26 @@ var STXChannelException = class extends STXException {
114
114
  };
115
115
  var STXTimeoutException = class extends STXChannelException {
116
116
  };
117
+ var STXCombosUnavailableException = class extends STXChannelException {
118
+ };
119
+ var STXComboRefusedException = class extends STXChannelException {
120
+ command;
121
+ code;
122
+ detail;
123
+ constructor(message, opts) {
124
+ super(message, opts);
125
+ this.command = opts.command;
126
+ this.code = opts.code;
127
+ this.detail = opts.detail;
128
+ }
129
+ };
130
+ var STXComboPriceMovedException = class extends STXComboRefusedException {
131
+ best;
132
+ constructor(message, opts) {
133
+ super(message, opts);
134
+ this.best = opts.best;
135
+ }
136
+ };
117
137
  function errorForStatus(statusCode, body, opts) {
118
138
  let message;
119
139
  if (body && typeof body === "object" && typeof body.error === "string") {
@@ -299,6 +319,17 @@ var OPERATIONS = {
299
319
  isList: true,
300
320
  paginated: true
301
321
  },
322
+ events__id_players_get: {
323
+ method: "GET",
324
+ path: "/api/v1/events/{event_id}/players",
325
+ query: [],
326
+ pathParams: ["event_id"],
327
+ hasBody: false,
328
+ responseKey: "",
329
+ model: "",
330
+ isList: false,
331
+ paginated: false
332
+ },
302
333
  fills_get: {
303
334
  method: "GET",
304
335
  path: "/api/v1/fills",
@@ -310,6 +341,28 @@ var OPERATIONS = {
310
341
  isList: true,
311
342
  paginated: true
312
343
  },
344
+ leaderboard_get: {
345
+ method: "GET",
346
+ path: "/api/v1/leaderboard",
347
+ query: ["period", "category", "metric", "limit"],
348
+ pathParams: [],
349
+ hasBody: false,
350
+ responseKey: "",
351
+ model: "",
352
+ isList: false,
353
+ paginated: false
354
+ },
355
+ leaderboard_me_get: {
356
+ method: "GET",
357
+ path: "/api/v1/leaderboard/me",
358
+ query: ["period", "category"],
359
+ pathParams: [],
360
+ hasBody: false,
361
+ responseKey: "",
362
+ model: "",
363
+ isList: false,
364
+ paginated: false
365
+ },
313
366
  markets_get: {
314
367
  method: "GET",
315
368
  path: "/api/v1/markets",
@@ -321,6 +374,17 @@ var OPERATIONS = {
321
374
  isList: true,
322
375
  paginated: true
323
376
  },
377
+ markets_post: {
378
+ method: "POST",
379
+ path: "/api/v1/markets",
380
+ query: [],
381
+ pathParams: [],
382
+ hasBody: true,
383
+ responseKey: "",
384
+ model: "",
385
+ isList: false,
386
+ paginated: false
387
+ },
324
388
  me_get: {
325
389
  method: "GET",
326
390
  path: "/api/v1/me",
@@ -332,6 +396,17 @@ var OPERATIONS = {
332
396
  isList: false,
333
397
  paginated: false
334
398
  },
399
+ me_profile_patch: {
400
+ method: "PATCH",
401
+ path: "/api/v1/me/profile",
402
+ query: [],
403
+ pathParams: [],
404
+ hasBody: true,
405
+ responseKey: "me",
406
+ model: "Me",
407
+ isList: false,
408
+ paginated: false
409
+ },
335
410
  orders_get: {
336
411
  method: "GET",
337
412
  path: "/api/v1/orders",
@@ -359,7 +434,7 @@ var OPERATIONS = {
359
434
  path: "/api/v1/orders/all",
360
435
  query: [],
361
436
  pathParams: [],
362
- hasBody: false,
437
+ hasBody: true,
363
438
  responseKey: "cancellations",
364
439
  model: "Cancellation",
365
440
  isList: true,
@@ -392,7 +467,7 @@ var OPERATIONS = {
392
467
  path: "/api/v1/orders/{order_id}",
393
468
  query: [],
394
469
  pathParams: ["order_id"],
395
- hasBody: false,
470
+ hasBody: true,
396
471
  responseKey: "",
397
472
  model: "",
398
473
  isList: false,
@@ -499,6 +574,103 @@ var OPERATIONS = {
499
574
  }
500
575
  };
501
576
 
577
+ // src/markets.ts
578
+ var Stats = {
579
+ Baseball: {
580
+ BASES: "BASES",
581
+ BK: "BK",
582
+ DOUBLES: "DOUBLES",
583
+ HITS: "HITS",
584
+ HIT_RUN_RBI: "HIT_RUN_RBI",
585
+ HOMERUN: "HOMERUN",
586
+ PERA: "PERA",
587
+ PHITA: "PHITA",
588
+ PK: "PK",
589
+ POUTS: "POUTS",
590
+ PRUNSALOWED: "PRUNSALOWED",
591
+ PWALKSA: "PWALKSA",
592
+ RBI: "RBI",
593
+ RUNS: "RUNS",
594
+ SINGLES: "SINGLES",
595
+ STOLENBASES: "STOLENBASES",
596
+ TRIPLES: "TRIPLES",
597
+ WALKS: "WALKS"
598
+ },
599
+ Basketball: {
600
+ ASSISTS: "ASSISTS",
601
+ BLOCKS: "BLOCKS",
602
+ POINTS: "POINTS",
603
+ POINTS_ASSISTS: "POINTS_ASSISTS",
604
+ POINTS_REBOUNDS: "POINTS_REBOUNDS",
605
+ POINTS_REBOUNDS_ASSISTS: "POINTS_REBOUNDS_ASSISTS",
606
+ REBOUNDS: "REBOUNDS",
607
+ REBOUNDS_ASSISTS: "REBOUNDS_ASSISTS",
608
+ STEALS: "STEALS",
609
+ STEALS_BLOCKS: "STEALS_BLOCKS",
610
+ THREE_POINTS: "THREE_POINTS",
611
+ TURNOVERS: "TURNOVERS"
612
+ },
613
+ Football: {
614
+ DEF_INTERCEPT: "DEF_INTERCEPT",
615
+ DEF_TD: "DEF_TD",
616
+ FG_MADE: "FG_MADE",
617
+ INTERCEPT: "INTERCEPT",
618
+ PASS_ATT: "PASS_ATT",
619
+ PASS_CMP: "PASS_CMP",
620
+ PASS_RUSH_YDS: "PASS_RUSH_YDS",
621
+ PASS_SACKS: "PASS_SACKS",
622
+ PASS_TD: "PASS_TD",
623
+ PASS_YDS: "PASS_YDS",
624
+ REC: "REC",
625
+ RECV_LONG: "RECV_LONG",
626
+ RECV_TD: "RECV_TD",
627
+ RECV_YDS: "RECV_YDS",
628
+ RUSH_ATT: "RUSH_ATT",
629
+ RUSH_LONG: "RUSH_LONG",
630
+ RUSH_REC_YDS: "RUSH_REC_YDS",
631
+ RUSH_TD: "RUSH_TD",
632
+ RUSH_YDS: "RUSH_YDS",
633
+ SACKS: "SACKS",
634
+ TACKLES_ASSIST: "TACKLES_ASSIST",
635
+ TACKLES_SOLO: "TACKLES_SOLO",
636
+ TACKLES_TOTAL: "TACKLES_TOTAL",
637
+ TD_SCORE: "TD_SCORE"
638
+ },
639
+ Hockey: {
640
+ ASSISTS: "ASSISTS",
641
+ GOALS: "GOALS",
642
+ GOAL_AG: "GOAL_AG",
643
+ GOAL_SO: "GOAL_SO",
644
+ POINTS: "POINTS",
645
+ SAVES: "SAVES"
646
+ }
647
+ };
648
+ var MAX_MARKETS_PER_REQUEST = 25;
649
+ function isValidLine(line) {
650
+ return typeof line === "number" && Number.isFinite(line) && line > 0 && line * 2 % 2 === 1;
651
+ }
652
+ function marketEntry(m) {
653
+ return {
654
+ stat_detail: { player_id: m.playerId, stat: m.stat, prop_type: m.propType ?? "ou", line: m.line }
655
+ };
656
+ }
657
+ function toCreateMarketResult(raw) {
658
+ const market = raw.market ?? raw.stat_detail ?? {};
659
+ return { ...raw, market };
660
+ }
661
+ function rejected(m, reason) {
662
+ const market = marketEntry(m).stat_detail;
663
+ return { status: "rejected", reason, market };
664
+ }
665
+ function checkMarket(m, players) {
666
+ if (!isValidLine(m.line)) return { reason: "invalid_line" };
667
+ const stat = players.stats.find((s) => String(s.stat).toUpperCase() === String(m.stat).toUpperCase());
668
+ if (!stat) return { reason: "unsupported_stat" };
669
+ const ids2 = new Set(players.teams.flatMap((t) => t.players.map((p) => p.player_id)));
670
+ if (!ids2.has(m.playerId)) return { reason: "unknown_player" };
671
+ return { market: { ...m, stat: stat.stat } };
672
+ }
673
+
502
674
  // src/paging.ts
503
675
  var Page = class {
504
676
  items;
@@ -809,7 +981,7 @@ function credentialsFromSettings(keyId, privateKey, signer) {
809
981
  }
810
982
 
811
983
  // src/version.ts
812
- var VERSION = "0.7.0";
984
+ var VERSION = "0.8.1";
813
985
  var USER_AGENT = `stx-typescript/${VERSION}`;
814
986
  var ASYNC_DISPOSE = Symbol.asyncDispose ?? /* @__PURE__ */ Symbol.for("Symbol.asyncDispose");
815
987
 
@@ -996,6 +1168,293 @@ var AccountView = class {
996
1168
  }
997
1169
  };
998
1170
 
1171
+ // src/combos.ts
1172
+ var COMBO_PLAYER_CHANNEL = "rfq";
1173
+ var COMBO_MAKER_CHANNEL = "combo_quote";
1174
+ var UNAVAILABLE_REASON = "unmatched topic";
1175
+ var ACCEPT_TIMEOUT_MS = 35e3;
1176
+ var HISTORY_SIZE = 1e3;
1177
+ var PLAYER_EVENTS = /* @__PURE__ */ new Set(["best_quote", "placed", "negotiation_closed"]);
1178
+ var MAKER_EVENTS = /* @__PURE__ */ new Set([
1179
+ "rfq_opened",
1180
+ "rfq_closed",
1181
+ "quote_accepted",
1182
+ "placed",
1183
+ "negotiation_closed"
1184
+ ]);
1185
+ function comboRefusal(command, topic, response) {
1186
+ const reply = response && typeof response === "object" ? response : {};
1187
+ const reason = typeof reply.reason === "string" ? reply.reason : void 0;
1188
+ if (reason === UNAVAILABLE_REASON) {
1189
+ return new STXCombosUnavailableException("Combos are not available on this environment.", {
1190
+ topic,
1191
+ reply: response
1192
+ });
1193
+ }
1194
+ if (reason === void 0) {
1195
+ return new STXComboRefusedException(`${command} on ${topic} failed: ${JSON.stringify(response)}`, {
1196
+ topic,
1197
+ reply: response,
1198
+ command,
1199
+ code: ""
1200
+ });
1201
+ }
1202
+ let code = reason;
1203
+ let detail;
1204
+ if (reason.startsWith("player_refused:")) {
1205
+ code = "player_refused";
1206
+ detail = reason.slice("player_refused:".length);
1207
+ }
1208
+ const message = `${command} on ${topic} refused: ${reason}`;
1209
+ if (code === "price_moved") {
1210
+ return new STXComboPriceMovedException(message, {
1211
+ topic,
1212
+ reply: response,
1213
+ command,
1214
+ code,
1215
+ best: {
1216
+ quote_id: reply.quote_id ?? null,
1217
+ amount: reply.amount ?? null,
1218
+ expires_at: reply.expires_at ?? null
1219
+ }
1220
+ });
1221
+ }
1222
+ return new STXComboRefusedException(message, { topic, reply: response, command, code, detail });
1223
+ }
1224
+ function comboJoinError(err) {
1225
+ if (err instanceof STXChannelException && !(err instanceof STXCombosUnavailableException) && err.reply !== void 0) {
1226
+ if (err.constructor !== STXChannelException) return err;
1227
+ return comboRefusal("phx_join", err.topic, err.reply);
1228
+ }
1229
+ return err;
1230
+ }
1231
+ async function comboJoinPayload(geo) {
1232
+ const packet = await resolveGeoLocation(geo);
1233
+ return packet === void 0 ? {} : { geo_location: packet };
1234
+ }
1235
+ function money(name, value) {
1236
+ if (typeof value !== "string") {
1237
+ throw new TypeError(`${name} must be a decimal string such as "250.00", got ${typeof value}`);
1238
+ }
1239
+ return value;
1240
+ }
1241
+ var ComboSession = class {
1242
+ /** The underlying channel. Its `reply` is the latest join reply. */
1243
+ channel;
1244
+ #onEvent;
1245
+ #history = [];
1246
+ #waiters = [];
1247
+ #events;
1248
+ /** @internal */
1249
+ constructor(channel, events, onEvent) {
1250
+ this.channel = channel;
1251
+ this.#events = events;
1252
+ this.#onEvent = onEvent;
1253
+ }
1254
+ /** Your account's pseudonym for counterparties, from the join reply. */
1255
+ get externalId() {
1256
+ return this.channel.reply.external_id ?? "";
1257
+ }
1258
+ /** When the geolocation packet this join used expires (ISO 8601), or null. Rejoin before it. */
1259
+ get nextGeolocationAt() {
1260
+ return this.channel.reply.next_geolocation_at ?? null;
1261
+ }
1262
+ /** @internal */
1263
+ _typed(msg) {
1264
+ if (!this.#events.has(msg.event) || !msg.payload || typeof msg.payload !== "object") return void 0;
1265
+ return { event: msg.event, payload: msg.payload };
1266
+ }
1267
+ /** @internal Called for every message on the channel, before it is queued. */
1268
+ async _receive(msg) {
1269
+ const event = this._typed(msg);
1270
+ if (!event) return;
1271
+ this.#history.push(event);
1272
+ if (this.#history.length > HISTORY_SIZE) this.#history.shift();
1273
+ for (const w of [...this.#waiters]) {
1274
+ if (w.match(event)) {
1275
+ this.#waiters = this.#waiters.filter((x) => x !== w);
1276
+ w.resolve(event);
1277
+ }
1278
+ }
1279
+ if (this.#onEvent) await this.#onEvent(event);
1280
+ }
1281
+ /** The events received so far (the latest 1000), oldest first. */
1282
+ get events() {
1283
+ return [...this.#history];
1284
+ }
1285
+ /**
1286
+ * The next event, in arrival order. Rejects with `STXTimeoutException` when
1287
+ * none arrives within `timeoutMs`, and with `STXChannelException` once the
1288
+ * channel is closed. Use either this or `for await`, not both.
1289
+ */
1290
+ async next(timeoutMs) {
1291
+ for (; ; ) {
1292
+ const event = this._typed(await this.channel.next(timeoutMs));
1293
+ if (event) return event;
1294
+ }
1295
+ }
1296
+ async *[Symbol.asyncIterator]() {
1297
+ for await (const msg of this.channel) {
1298
+ const event = this._typed(msg);
1299
+ if (event) yield event;
1300
+ }
1301
+ }
1302
+ /**
1303
+ * Resolve with the first event named `event` (or one of several) for
1304
+ * `rfqId`, looking first at events already received. Unlike `next()`, it
1305
+ * takes nothing from the queue. Rejects with `STXTimeoutException` after
1306
+ * `timeoutMs` (default 10000).
1307
+ *
1308
+ * @param event An event name, or several.
1309
+ * @param opts.rfqId Only events for this request.
1310
+ * @param opts.quoteId Only events for this quote (maker events).
1311
+ * @param opts.timeoutMs Milliseconds to wait. Default 10000.
1312
+ */
1313
+ waitFor(event, opts = {}) {
1314
+ const names = typeof event === "string" ? [event] : event;
1315
+ const match = (e) => names.includes(e.event) && (opts.rfqId === void 0 || e.payload.rfq_id === opts.rfqId) && (opts.quoteId === void 0 || e.payload.quote_id === opts.quoteId);
1316
+ const seen = this.#history.find(match);
1317
+ if (seen) return Promise.resolve(seen);
1318
+ const timeoutMs = opts.timeoutMs ?? 1e4;
1319
+ return new Promise((resolve, reject) => {
1320
+ const waiter = {
1321
+ match,
1322
+ resolve: (e) => {
1323
+ clearTimeout(timer);
1324
+ resolve(e);
1325
+ }
1326
+ };
1327
+ const timer = setTimeout(() => {
1328
+ this.#waiters = this.#waiters.filter((w) => w !== waiter);
1329
+ reject(
1330
+ new STXTimeoutException(`No ${names.join(" or ")} on ${this.channel.topic} within ${timeoutMs} ms`, {
1331
+ topic: this.channel.topic
1332
+ })
1333
+ );
1334
+ }, timeoutMs);
1335
+ this.#waiters.push(waiter);
1336
+ });
1337
+ }
1338
+ /** Leave the topic. Requests opened and quotes placed on this channel end, as on any close. */
1339
+ leave() {
1340
+ return this.channel.leave();
1341
+ }
1342
+ /** @internal Send a command and map a refusal to the combo exceptions. */
1343
+ async _command(command, payload, timeoutMs) {
1344
+ try {
1345
+ return await this.channel.push(command, payload, timeoutMs);
1346
+ } catch (err) {
1347
+ if (err instanceof STXChannelException && err.constructor === STXChannelException && err.reply !== void 0) {
1348
+ throw comboRefusal(command, this.channel.topic, err.reply);
1349
+ }
1350
+ throw err;
1351
+ }
1352
+ }
1353
+ };
1354
+ var ComboPlayer = class extends ComboSession {
1355
+ /** @internal */
1356
+ constructor(channel, onEvent) {
1357
+ super(channel, PLAYER_EVENTS, onEvent);
1358
+ }
1359
+ /**
1360
+ * `request_quote`: ask makers to quote on these legs for a stake. `amount`
1361
+ * is the stake as a decimal string in whole cents, e.g. `"250.00"`. Makers
1362
+ * quote what you win; quotes arrive as `best_quote` events.
1363
+ *
1364
+ * @param legs Two or more `open` markets and the outcome the combination needs of each.
1365
+ * @param amount The stake in dollars, e.g. `"250.00"`.
1366
+ */
1367
+ requestQuote(legs, amount2) {
1368
+ return this._command("request_quote", {
1369
+ legs: legs.map((leg) => ({ market_id: leg.marketId, outcome: leg.outcome })),
1370
+ amount: money("amount", amount2)
1371
+ });
1372
+ }
1373
+ /**
1374
+ * `cash_out`: ask makers to quote for what you hold of a combination, by the
1375
+ * `market_id` from `placed`. The exchange sets the size.
1376
+ *
1377
+ * @param marketId The combination's market id.
1378
+ */
1379
+ cashOut(marketId) {
1380
+ return this._command("cash_out", { market_id: marketId });
1381
+ }
1382
+ /**
1383
+ * `accept`: bind the request at `amount` or more, normally the amount
1384
+ * `best_quote` showed. The best live quote binds whoever made it, so the
1385
+ * placement can be better than `amount`. Waits up to 35 s.
1386
+ *
1387
+ * Throws `STXComboPriceMovedException` (with the live `best`) when nothing
1388
+ * at least as good is live; the request stays open and you can accept again.
1389
+ * The reply says what was placed; fills arrive on `fills`.
1390
+ *
1391
+ * @param rfqId The request.
1392
+ * @param quoteId The quote you saw, normally from `best_quote`.
1393
+ * @param amount The least amount you take, e.g. `"1750.00"`.
1394
+ */
1395
+ accept(rfqId, quoteId, amount2) {
1396
+ return this._command(
1397
+ "accept",
1398
+ { rfq_id: rfqId, quote_id: quoteId, amount: money("amount", amount2) },
1399
+ ACCEPT_TIMEOUT_MS
1400
+ );
1401
+ }
1402
+ /**
1403
+ * `cancel`: end the request and drop every quote on it.
1404
+ *
1405
+ * @param rfqId The request.
1406
+ */
1407
+ cancel(rfqId) {
1408
+ return this._command("cancel", { rfq_id: rfqId });
1409
+ }
1410
+ /**
1411
+ * `snapshot`: the request now, with the live best quote. Not delayed like `best_quote` events.
1412
+ *
1413
+ * @param rfqId The request.
1414
+ */
1415
+ snapshot(rfqId) {
1416
+ return this._command("snapshot", { rfq_id: rfqId });
1417
+ }
1418
+ };
1419
+ var ComboMaker = class extends ComboSession {
1420
+ /** @internal */
1421
+ constructor(channel, onEvent) {
1422
+ super(channel, MAKER_EVENTS, onEvent);
1423
+ }
1424
+ /**
1425
+ * `quote`: offer `amount` on a request. On a buy it is what the player wins;
1426
+ * on a cash out, what you pay for the whole size. Price it against the
1427
+ * request's `max_price` and `tick_size`. `expiresInMs` (a positive integer)
1428
+ * counts from receipt; the quote ends no later than its request.
1429
+ * `clientOrderId` (at most 255 bytes) is copied onto your order if it binds.
1430
+ *
1431
+ * @param rfqId The request, from `rfq_opened`.
1432
+ * @param amount In dollars, e.g. `"1750.00"`.
1433
+ * @param expiresInMs How long the quote stands, in milliseconds.
1434
+ * @param opts.clientOrderId Copied onto your order if the quote binds.
1435
+ */
1436
+ quote(rfqId, amount2, expiresInMs, opts = {}) {
1437
+ const payload = {
1438
+ rfq_id: rfqId,
1439
+ amount: money("amount", amount2),
1440
+ expires_in_ms: expiresInMs
1441
+ };
1442
+ if (opts.clientOrderId !== void 0) payload.client_order_id = opts.clientOrderId;
1443
+ return this._command("quote", payload);
1444
+ }
1445
+ /**
1446
+ * `withdraw_quote`: remove one of your quotes.
1447
+ *
1448
+ * @param rfqId The request.
1449
+ * @param quoteId Your quote, from the `quote()` reply.
1450
+ */
1451
+ withdrawQuote(rfqId, quoteId) {
1452
+ return this._command("withdraw_quote", { rfq_id: rfqId, quote_id: quoteId });
1453
+ }
1454
+ };
1455
+ var COMBO_CHANNELS = /* @__PURE__ */ new Set([COMBO_PLAYER_CHANNEL, COMBO_MAKER_CHANNEL]);
1456
+ var COMBOS_UNAVAILABLE_REASON = UNAVAILABLE_REASON;
1457
+
999
1458
  // src/money.ts
1000
1459
  var PRICE_FIELDS = ["price", "last_traded_price", "max_price"];
1001
1460
  var QUANTITY_FIELDS = ["total_volume", "volume_24h", "open_interest"];
@@ -1140,7 +1599,8 @@ function buildRequest(operationId, args = {}) {
1140
1599
  if (unknown.length) throw new TypeError(`${operationId} does not take ${unknown.sort().join(", ")}`);
1141
1600
  const qs = encodeQuery(query);
1142
1601
  if (qs) path = `${path}?${qs}`;
1143
- const body = op.hasBody || args.body !== void 0 ? JSON.stringify(args.body ?? {}) : void 0;
1602
+ const declared = op.hasBody && op.method !== "DELETE";
1603
+ const body = declared || args.body !== void 0 ? JSON.stringify(args.body ?? {}) : void 0;
1144
1604
  return {
1145
1605
  operationId,
1146
1606
  method: op.method,
@@ -1533,6 +1993,63 @@ var STX = class _STX {
1533
1993
  return this.#iterate("events_get", _STX.#eventsQuery({ ...query, cursor: void 0 }));
1534
1994
  }
1535
1995
  // ------------------------------------------------------------------
1996
+ // Creating markets
1997
+ // ------------------------------------------------------------------
1998
+ /**
1999
+ * `GET /api/v1/events/{event_id}/players`: the event's team rosters and the
2000
+ * stats a market on it can use. `teams` is empty until the rosters are
2001
+ * published. Needs an OAuth app token with `events`, or an API key.
2002
+ */
2003
+ eventPlayers(eventId) {
2004
+ return this.#one("events__id_players_get", { pathParams: { event_id: eventId } });
2005
+ }
2006
+ /** The stats `event` accepts for new markets. */
2007
+ async statsFor(event) {
2008
+ const eventId = typeof event === "string" ? event : event.event_id;
2009
+ if (!eventId) throw new TypeError("statsFor needs an event id");
2010
+ return (await this.eventPlayers(eventId)).stats;
2011
+ }
2012
+ /**
2013
+ * `POST /api/v1/markets`: create player-prop markets on a scheduled event,
2014
+ * up to `MAX_MARKETS_PER_REQUEST` per call. Needs an OAuth app token with
2015
+ * `markets.write`, which STX grants, from the client's IP allow-list.
2016
+ *
2017
+ * Returns one result per market, in order: `created` or `exists` (both with
2018
+ * `market_id`), or `rejected` with a `reason`. A rejected market is a
2019
+ * result, not an error, and resending is safe: a market that is already
2020
+ * listed comes back `exists`. A refused request throws (`403` without
2021
+ * `markets.write`, `404` unknown event, `422` event not open).
2022
+ *
2023
+ * Each `line` must be a positive number ending in `.5`, e.g. `18.5`. More
2024
+ * than `MAX_MARKETS_PER_REQUEST` markets throws `TypeError` before any
2025
+ * request. `validate` also needs the `events` scope.
2026
+ */
2027
+ async createMarkets(eventId, markets, opts = {}) {
2028
+ if (markets.length < 1 || markets.length > MAX_MARKETS_PER_REQUEST) {
2029
+ throw new TypeError(`createMarkets takes 1 to ${MAX_MARKETS_PER_REQUEST} markets; got ${markets.length}`);
2030
+ }
2031
+ const results = new Array(markets.length);
2032
+ let send = markets.map((m, i) => ({ m, i }));
2033
+ if (opts.validate) {
2034
+ const players = await this.eventPlayers(eventId);
2035
+ send = send.flatMap(({ m, i }) => {
2036
+ const checked = checkMarket(m, players);
2037
+ if ("market" in checked) return [{ m: checked.market, i }];
2038
+ results[i] = rejected(m, checked.reason);
2039
+ return [];
2040
+ });
2041
+ }
2042
+ if (send.length) {
2043
+ const body = { event_id: eventId, markets: send.map(({ m }) => marketEntry(m)) };
2044
+ const raw = await this.#one("markets_post", { body });
2045
+ (raw.markets ?? []).forEach((r, k) => {
2046
+ const slot = send[k];
2047
+ if (slot) results[slot.i] = toCreateMarketResult(r);
2048
+ });
2049
+ }
2050
+ return results.map((r, i) => r ?? rejected(markets[i], "not_created"));
2051
+ }
2052
+ // ------------------------------------------------------------------
1536
2053
  // Orders
1537
2054
  // ------------------------------------------------------------------
1538
2055
  static #ordersQuery(q) {
@@ -1892,6 +2409,8 @@ var Channel = class {
1892
2409
  joinRef = null;
1893
2410
  joined = false;
1894
2411
  closed = false;
2412
+ /** @internal Runs before every (re)join, e.g. to refresh a geolocation packet in `joinPayload`. */
2413
+ _beforeJoin;
1895
2414
  #ws;
1896
2415
  #queue;
1897
2416
  #snapshotWaiters = [];
@@ -2347,6 +2866,63 @@ var STXWebSocket = class {
2347
2866
  return this.#joinAccount("user_info", {}, opts.onMessage);
2348
2867
  }
2349
2868
  // ------------------------------------------------------------------
2869
+ // Combos (preview)
2870
+ // ------------------------------------------------------------------
2871
+ /**
2872
+ * Join `rfq:{user_id}` and return a `ComboPlayer`: request quotes on a
2873
+ * combination, cash one out, accept, cancel and read a request.
2874
+ *
2875
+ * Preview: available on US demo; may change before general availability.
2876
+ * Where combos are not available, rejects with
2877
+ * `STXCombosUnavailableException`. Other join refusals (a read-only key, an
2878
+ * account that may not trade) reject with `STXComboRefusedException`.
2879
+ */
2880
+ async comboPlayer(opts = {}) {
2881
+ let player;
2882
+ const early = [];
2883
+ const channel = await this.#joinCombo(COMBO_PLAYER_CHANNEL, opts, async (msg) => {
2884
+ if (player) await player._receive(msg);
2885
+ else early.push(msg);
2886
+ });
2887
+ player = new ComboPlayer(channel, opts.onEvent);
2888
+ for (const msg of early) await player._receive(msg);
2889
+ return player;
2890
+ }
2891
+ /**
2892
+ * Join `combo_quote:{user_id}` and return a `ComboMaker`: receive every
2893
+ * request opened from now on (`rfq_opened`), quote and withdraw quotes.
2894
+ *
2895
+ * Preview: available on US demo; may change before general availability.
2896
+ * Where combos are not available, rejects with
2897
+ * `STXCombosUnavailableException`.
2898
+ */
2899
+ async comboMaker(opts = {}) {
2900
+ let maker;
2901
+ const early = [];
2902
+ const channel = await this.#joinCombo(COMBO_MAKER_CHANNEL, opts, async (msg) => {
2903
+ if (maker) await maker._receive(msg);
2904
+ else early.push(msg);
2905
+ });
2906
+ maker = new ComboMaker(channel, opts.onEvent);
2907
+ for (const msg of early) await maker._receive(msg);
2908
+ return maker;
2909
+ }
2910
+ async #joinCombo(name, opts, onMessage) {
2911
+ let channel;
2912
+ try {
2913
+ channel = await this.#joinAccount(name, await comboJoinPayload(opts.geoLocation), onMessage);
2914
+ } catch (err) {
2915
+ throw comboJoinError(err);
2916
+ }
2917
+ if (typeof opts.geoLocation === "function") {
2918
+ const geo = opts.geoLocation;
2919
+ channel._beforeJoin = async () => {
2920
+ channel.joinPayload = await comboJoinPayload(geo);
2921
+ };
2922
+ }
2923
+ return channel;
2924
+ }
2925
+ // ------------------------------------------------------------------
2350
2926
  // Generic join
2351
2927
  // ------------------------------------------------------------------
2352
2928
  /**
@@ -2384,6 +2960,7 @@ var STXWebSocket = class {
2384
2960
  const ref = this.#nextRef();
2385
2961
  channel.joinRef = ref;
2386
2962
  channel._resetForRejoin();
2963
+ if (channel._beforeJoin) await channel._beforeJoin();
2387
2964
  const reply = await this._request(channel.topic, "phx_join", channel.joinPayload, ref, void 0, ref);
2388
2965
  channel.reply = reply && typeof reply === "object" && !Array.isArray(reply) ? reply : { response: reply };
2389
2966
  if (channel.name === "market") channel.reply = convertMarketChannelPayload(channel.reply);
@@ -2590,7 +3167,7 @@ var STXWebSocket = class {
2590
3167
  } catch (err) {
2591
3168
  this.logger.error(`rejoin ${channel.topic} failed: ${err.message}`);
2592
3169
  const reply = err instanceof STXChannelException ? err.reply : void 0;
2593
- if (reply?.reason === "unauthorized") {
3170
+ if (reply?.reason === "unauthorized" || reply?.reason === COMBOS_UNAVAILABLE_REASON && COMBO_CHANNELS.has(channel.name)) {
2594
3171
  channel._close();
2595
3172
  return;
2596
3173
  }
@@ -2731,6 +3308,9 @@ export {
2731
3308
  STXTransportException,
2732
3309
  STXChannelException,
2733
3310
  STXTimeoutException,
3311
+ STXCombosUnavailableException,
3312
+ STXComboRefusedException,
3313
+ STXComboPriceMovedException,
2734
3314
  errorForStatus,
2735
3315
  Environments,
2736
3316
  HOSTS,
@@ -2739,6 +3319,9 @@ export {
2739
3319
  baseUrlFor,
2740
3320
  socketUrlFor,
2741
3321
  OPERATIONS,
3322
+ Stats,
3323
+ MAX_MARKETS_PER_REQUEST,
3324
+ isValidLine,
2742
3325
  Page,
2743
3326
  RetryPolicy,
2744
3327
  NO_RETRY,
@@ -2756,6 +3339,8 @@ export {
2756
3339
  USER_AGENT,
2757
3340
  TERMINAL_ORDER_STATUSES,
2758
3341
  AccountView,
3342
+ ComboPlayer,
3343
+ ComboMaker,
2759
3344
  centsToDollars,
2760
3345
  toDollarString,
2761
3346
  toQuantity,
@@ -2771,4 +3356,4 @@ export {
2771
3356
  orderBody,
2772
3357
  STX
2773
3358
  };
2774
- //# sourceMappingURL=chunk-CDXZOW53.js.map
3359
+ //# sourceMappingURL=chunk-GLUTQFBV.js.map