@stxapp/stx-typescript 0.8.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,10 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.8.1 (2026-10-12)
4
+
5
+ - Combos (preview: available on US demo; may change before general availability). `ws.comboPlayer()` requests quotes on a combination, cashes one out, accepts, cancels and reads a request; `ws.comboMaker()` receives requests, quotes and withdraws quotes. Events and replies are typed (`ComboPlayerEvent`, `ComboMakerEvent` and the reply types), with `waitFor()`, `next()` and `for await`.
6
+ - `STXCombosUnavailableException` when an environment does not offer combos, `STXComboRefusedException` with the exchange's reason in `code` (and `detail` for `player_refused`), and `STXComboPriceMovedException` with the live best quote.
7
+
3
8
  ## 0.8.0 (2026-10-06)
4
9
 
5
10
  - Create player-prop markets as an app with the `markets.write` scope: `eventPlayers()`, `statsFor()` and `createMarkets()`, with `Stats` constants by sport and an opt-in `validate` check. Lines must be positive and end in `.5`; up to 25 markets per call.
@@ -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") {
@@ -961,7 +981,7 @@ function credentialsFromSettings(keyId, privateKey, signer) {
961
981
  }
962
982
 
963
983
  // src/version.ts
964
- var VERSION = "0.8.0";
984
+ var VERSION = "0.8.1";
965
985
  var USER_AGENT = `stx-typescript/${VERSION}`;
966
986
  var ASYNC_DISPOSE = Symbol.asyncDispose ?? /* @__PURE__ */ Symbol.for("Symbol.asyncDispose");
967
987
 
@@ -1148,6 +1168,293 @@ var AccountView = class {
1148
1168
  }
1149
1169
  };
1150
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
+
1151
1458
  // src/money.ts
1152
1459
  var PRICE_FIELDS = ["price", "last_traded_price", "max_price"];
1153
1460
  var QUANTITY_FIELDS = ["total_volume", "volume_24h", "open_interest"];
@@ -2102,6 +2409,8 @@ var Channel = class {
2102
2409
  joinRef = null;
2103
2410
  joined = false;
2104
2411
  closed = false;
2412
+ /** @internal Runs before every (re)join, e.g. to refresh a geolocation packet in `joinPayload`. */
2413
+ _beforeJoin;
2105
2414
  #ws;
2106
2415
  #queue;
2107
2416
  #snapshotWaiters = [];
@@ -2557,6 +2866,63 @@ var STXWebSocket = class {
2557
2866
  return this.#joinAccount("user_info", {}, opts.onMessage);
2558
2867
  }
2559
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
+ // ------------------------------------------------------------------
2560
2926
  // Generic join
2561
2927
  // ------------------------------------------------------------------
2562
2928
  /**
@@ -2594,6 +2960,7 @@ var STXWebSocket = class {
2594
2960
  const ref = this.#nextRef();
2595
2961
  channel.joinRef = ref;
2596
2962
  channel._resetForRejoin();
2963
+ if (channel._beforeJoin) await channel._beforeJoin();
2597
2964
  const reply = await this._request(channel.topic, "phx_join", channel.joinPayload, ref, void 0, ref);
2598
2965
  channel.reply = reply && typeof reply === "object" && !Array.isArray(reply) ? reply : { response: reply };
2599
2966
  if (channel.name === "market") channel.reply = convertMarketChannelPayload(channel.reply);
@@ -2800,7 +3167,7 @@ var STXWebSocket = class {
2800
3167
  } catch (err) {
2801
3168
  this.logger.error(`rejoin ${channel.topic} failed: ${err.message}`);
2802
3169
  const reply = err instanceof STXChannelException ? err.reply : void 0;
2803
- if (reply?.reason === "unauthorized") {
3170
+ if (reply?.reason === "unauthorized" || reply?.reason === COMBOS_UNAVAILABLE_REASON && COMBO_CHANNELS.has(channel.name)) {
2804
3171
  channel._close();
2805
3172
  return;
2806
3173
  }
@@ -2941,6 +3308,9 @@ export {
2941
3308
  STXTransportException,
2942
3309
  STXChannelException,
2943
3310
  STXTimeoutException,
3311
+ STXCombosUnavailableException,
3312
+ STXComboRefusedException,
3313
+ STXComboPriceMovedException,
2944
3314
  errorForStatus,
2945
3315
  Environments,
2946
3316
  HOSTS,
@@ -2969,6 +3339,8 @@ export {
2969
3339
  USER_AGENT,
2970
3340
  TERMINAL_ORDER_STATUSES,
2971
3341
  AccountView,
3342
+ ComboPlayer,
3343
+ ComboMaker,
2972
3344
  centsToDollars,
2973
3345
  toDollarString,
2974
3346
  toQuantity,
@@ -2984,4 +3356,4 @@ export {
2984
3356
  orderBody,
2985
3357
  STX
2986
3358
  };
2987
- //# sourceMappingURL=chunk-H7XZDE2U.js.map
3359
+ //# sourceMappingURL=chunk-GLUTQFBV.js.map