@stxapp/stx-typescript 0.10.0 → 0.12.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/CHANGELOG.md CHANGED
@@ -1,5 +1,26 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.12.0 (2026-11-18)
4
+
5
+ Breaking for anyone reading `orders.post_only` or `orders.fill_or_kill` from `capabilities()`:
6
+
7
+ - Post-only and fill-or-kill orders are sent straight to the exchange, which accepts or rejects them. The client no longer asks `GET /api_version` first. Where a mode is not enabled, the exchange rejects the order and the call throws `STXNotAvailableException` (`feature` `orders.post_only` or `orders.fill_or_kill`), as before. An exchange on a release from before fill modes places the order as a normal limit order. See https://docs.stxapp.io/concepts/order-types/
8
+ - `capabilities()` no longer reports `orders.post_only` or `orders.fill_or_kill`.
9
+
10
+ ## 0.11.0 (2026-11-17)
11
+
12
+ Post-only and fill-or-kill orders:
13
+
14
+ - `placeOrder()` and each `placeOrders()` order take `fillMode`: `"normal"` (the default), `"post_only"` or `"fill_or_kill"`, for limit orders. See https://docs.stxapp.io/sdks/typescript/trading/
15
+ - Before sending a post-only or fill-or-kill order, the client asks the exchange once (`GET /api_version`, cached on the client) whether it offers that mode. When it does not, the call throws `STXNotAvailableException` (`feature` `orders.post_only` or `orders.fill_or_kill`, with `apiVersion`) and sends nothing, so an exchange that does not know the mode never places a normal order instead. `capabilities()` reports both features.
16
+ - A post-only order that would have matched throws `STXPostOnlyWouldMatchException` (`reason` `auto_matching` with the cancelled `order`, or `match_with_self`). A fill mode on a combination market throws `STXFillModeNotAllowedException`. Both extend `STXRejectedException`.
17
+ - `Order` has `fill_mode`, `Market` has `rules_version` and `market_rules_pdf_url`, and `accountMarketStats()` takes `unsettledOnly`.
18
+
19
+ Blocked requests:
20
+
21
+ - A request blocked before it reaches the exchange throws `STXBlockedException` (a 403 `STXForbiddenException`) with `reason` and `reference` (the request id from the `x-amz-cf-id` response header, to quote to STX support), or its subclasses `STXRestrictedJurisdictionException` and `STXUnusualNetworkException`. A 403 that carries no reason says that requests need a `User-Agent` header. Blocked requests are never retried.
22
+ - A 429 from the same place is `STXRateLimitException` with `reference` as well as `retryAfter`. `Retry-After` given as an HTTP date is read too, and when it asks for longer than `RetryPolicy.maxBackoffMs` the exception is thrown at once instead of retrying early.
23
+
3
24
  ## 0.10.0 (2026-11-11)
4
25
 
5
26
  Breaking for anyone passing a geolocation option or using the location check: API key requests are now located from your connection, so the SDK no longer sends or reads geolocation data and no longer has its own location check.
package/README.md CHANGED
@@ -72,6 +72,8 @@ Every field is described in the [API reference](https://docs.stxapp.io/sdks/type
72
72
 
73
73
  </details>
74
74
 
75
+ `placeOrder(marketId, "buy", "limit", { price, quantity, fillMode: "post_only" })` places a limit order that only rests on the book, and `fillMode: "fill_or_kill"` one that fills in full or not at all. Where the exchange has not enabled a fill mode, it rejects the order and the call throws `STXNotAvailableException`. See [Trading](https://docs.stxapp.io/sdks/typescript/trading/).
76
+
75
77
  ## For apps: STX accounts and markets
76
78
 
77
79
  An app registered with STX can bring its members' STX accounts in, and can act as itself. This runs on your server; the client secret and the tokens never go to a browser or a mobile app. OAuth is on in US demo today; on an exchange without it these calls throw `STXNotAvailableException`, and `await stx.capabilities()` says which features an exchange has. There are two ways to bring a member's STX account in.
@@ -43,15 +43,46 @@ var STXTermsRequiredException = class extends STXForbiddenException {
43
43
  };
44
44
  var STXIPNotAllowedException = class extends STXForbiddenException {
45
45
  };
46
+ var STXBlockedException = class extends STXForbiddenException {
47
+
48
+
49
+ constructor(message, opts = {}) {
50
+ super(message, opts);
51
+ this.reason = _nullishCoalesce(opts.reason, () => ( "blocked"));
52
+ this.reference = opts.reference;
53
+ }
54
+ };
55
+ var STXRestrictedJurisdictionException = class extends STXBlockedException {
56
+ };
57
+ var STXUnusualNetworkException = class extends STXBlockedException {
58
+ };
46
59
  var STXNotFoundException = class extends STXAPIException {
47
60
  };
48
61
  var STXRejectedException = class extends STXAPIException {
49
62
  };
63
+ var STXFillModeNotAllowedException = class extends STXRejectedException {
64
+
65
+ constructor(message, opts) {
66
+ super(message, opts);
67
+ this.fillMode = opts.fillMode;
68
+ }
69
+ };
70
+ var STXPostOnlyWouldMatchException = class extends STXRejectedException {
71
+
72
+
73
+ constructor(message, opts) {
74
+ super(message, opts);
75
+ this.reason = opts.reason;
76
+ this.order = opts.order;
77
+ }
78
+ };
50
79
  var STXRateLimitException = class extends STXAPIException {
51
80
 
81
+
52
82
  constructor(message, opts = {}) {
53
83
  super(message, opts);
54
84
  this.retryAfter = opts.retryAfter;
85
+ this.reference = opts.reference;
55
86
  }
56
87
  };
57
88
  var STXServerException = class extends STXAPIException {
@@ -92,21 +123,27 @@ var FEATURE_PHRASES = {
92
123
  event_players: "Event players are",
93
124
  leaderboard: "The leaderboard is",
94
125
  loyalty: "The loyalty program is",
95
- combos: "Combos are"
126
+ combos: "Combos are",
127
+ "orders.post_only": "Post-only orders are",
128
+ "orders.fill_or_kill": "Fill-or-kill orders are"
96
129
  };
97
- function notAvailableMessage(feature, host) {
130
+ function notAvailableMessage(feature, host, apiVersion) {
98
131
  const phrase = feature.startsWith("scope:") ? `The ${feature.slice("scope:".length)} scope is` : _nullishCoalesce(FEATURE_PHRASES[feature], () => ( `${feature} is`));
99
- return `${phrase} not available on ${host} yet.`;
132
+ const where = apiVersion ? `${host} (version ${apiVersion})` : host;
133
+ return `${phrase} not available on ${where} yet.`;
100
134
  }
101
135
  var STXNotAvailableException = class _STXNotAvailableException extends STXAPIException {
102
136
  /** The feature id, e.g. `"combos"`. */
103
137
 
104
138
  /** The exchange host that lacks it, e.g. `"demo.stxapp.ca"`. */
105
139
 
140
+ /** The exchange build, e.g. `"3.4.24"`, when known. */
141
+
106
142
  constructor(feature, host, opts = {}) {
107
- super(_nullishCoalesce(opts.message, () => ( notAvailableMessage(feature, host))), opts);
143
+ super(_nullishCoalesce(opts.message, () => ( notAvailableMessage(feature, host, opts.apiVersion))), opts);
108
144
  this.feature = feature;
109
145
  this.host = host;
146
+ this.apiVersion = _nullishCoalesce(opts.apiVersion, () => ( void 0));
110
147
  markNotAvailable(this);
111
148
  }
112
149
  // `this` is the class on the right of `instanceof`: a subclass keeps the
@@ -172,6 +209,18 @@ function errorForStatus(statusCode, body, opts) {
172
209
  message = `HTTP ${statusCode}`;
173
210
  }
174
211
  const base = { statusCode, body, method: opts.method, path: opts.path };
212
+ const edge = edgeBlock(statusCode, body, opts.stxError, opts.cfId);
213
+ if (edge) {
214
+ if (statusCode === 429) {
215
+ return new STXRateLimitException(edge.message, {
216
+ ...base,
217
+ retryAfter: parseRetryAfter(opts.retryAfter),
218
+ reference: edge.reference
219
+ });
220
+ }
221
+ const cls = edge.reason === "restricted_jurisdiction" ? STXRestrictedJurisdictionException : edge.reason === "unusual_network" ? STXUnusualNetworkException : STXBlockedException;
222
+ return new cls(edge.message, { ...base, reason: edge.reason, reference: edge.reference });
223
+ }
175
224
  switch (statusCode) {
176
225
  case 400:
177
226
  return new STXValidationException(message, base);
@@ -206,10 +255,36 @@ function errorForStatus(statusCode, body, opts) {
206
255
  return statusCode >= 500 ? new STXServerException(message, base) : new STXAPIException(message, base);
207
256
  }
208
257
  }
258
+ var NO_USER_AGENT_HINT = "Request blocked (HTTP 403) before it reached the exchange. Every request needs a User-Agent header; if you replaced or removed the SDK's, set one that names your application. If it persists, contact STX support.";
259
+ var EDGE_REASONS = {
260
+ 403: ["restricted_jurisdiction", "unusual_network"],
261
+ 429: ["rate_limited"]
262
+ };
263
+ var REFERENCE_PLACEHOLDER = "x-amz-cf-id response header";
264
+ function edgeBlock(status, body, stxError, cfId) {
265
+ const reasons = EDGE_REASONS[status];
266
+ if (!reasons || stxError) return void 0;
267
+ let reference = cfId || void 0;
268
+ if (body && typeof body === "object") {
269
+ const fields = body;
270
+ if (typeof fields.error !== "string" || !reasons.includes(fields.error)) return void 0;
271
+ if (reference === void 0 && typeof fields.reference === "string" && fields.reference) {
272
+ reference = fields.reference === REFERENCE_PLACEHOLDER ? void 0 : fields.reference;
273
+ }
274
+ return {
275
+ reason: fields.error,
276
+ message: typeof fields.message === "string" && fields.message ? fields.message : fields.error,
277
+ reference
278
+ };
279
+ }
280
+ return status === 403 ? { reason: "blocked", message: NO_USER_AGENT_HINT, reference } : void 0;
281
+ }
209
282
  function parseRetryAfter(value) {
210
283
  if (value === null || value === void 0 || value.trim() === "") return void 0;
211
284
  const n = Number(value);
212
- return Number.isFinite(n) ? Math.max(0, n) : void 0;
285
+ if (Number.isFinite(n)) return Math.max(0, n);
286
+ const at = Date.parse(value);
287
+ return Number.isNaN(at) ? void 0 : Math.max(0, (at - Date.now()) / 1e3);
213
288
  }
214
289
  function bearerError(header) {
215
290
  if (!header || !/^\s*Bearer\b/i.test(header)) return void 0;
@@ -326,7 +401,7 @@ async function discoverCapabilities(probes) {
326
401
  swallow(probes.signedGet("/api/v1/portfolio/loyalty?limit=1")),
327
402
  swallow(probes.joinReason(`rfq:${NOBODY}`))
328
403
  ]);
329
- const apiVersion = _optionalChain([json, 'call', _5 => _5(version), 'optionalAccess', _6 => _6.api_version]);
404
+ const apiVersion = _optionalChain([version, 'optionalAccess', _5 => _5.status]) === 200 ? _optionalChain([json, 'call', _6 => _6(version), 'optionalAccess', _7 => _7.api_version]) : null;
330
405
  const meta = oauthMetadataFrom(discovery);
331
406
  const scopes = meta ? strings(meta.scopes_supported) : [];
332
407
  const grants = meta ? strings(meta.grant_types_supported) : [];
@@ -481,7 +556,7 @@ var OPERATIONS = {
481
556
  account_market_stats_get: {
482
557
  method: "GET",
483
558
  path: "/api/v1/account/market_stats",
484
- query: ["market_ids", "event_ids", "exclude_zero_settlements", "from_time", "to_time", "sports", "competitions", "limit", "cursor"],
559
+ query: ["market_ids", "event_ids", "exclude_zero_settlements", "unsettled_only", "from_time", "to_time", "sports", "competitions", "limit", "cursor"],
485
560
  pathParams: [],
486
561
  hasBody: false,
487
562
  responseKey: "market_stats",
@@ -917,6 +992,9 @@ var RetryPolicy = class {
917
992
  shouldRetry(exc, attempt, idempotent) {
918
993
  if (attempt >= this.maxAttempts) return false;
919
994
  if (!this.retryableExceptions.some((cls) => exc instanceof cls)) return false;
995
+ if (exc instanceof STXRateLimitException && exc.retryAfter !== void 0 && exc.retryAfter * 1e3 > this.maxBackoffMs) {
996
+ return false;
997
+ }
920
998
  return idempotent || exc instanceof STXRateLimitException;
921
999
  }
922
1000
  /** Milliseconds to wait after attempt `attempt` (1-based) failed. */
@@ -1004,7 +1082,7 @@ function readProfile(profileName, path) {
1004
1082
  }
1005
1083
  function processEnv() {
1006
1084
  const p = globalThis.process;
1007
- return _nullishCoalesce(_optionalChain([p, 'optionalAccess', _7 => _7.env]), () => ( {}));
1085
+ return _nullishCoalesce(_optionalChain([p, 'optionalAccess', _8 => _8.env]), () => ( {}));
1008
1086
  }
1009
1087
  function resolveSettings(input = {}) {
1010
1088
  const environ = _nullishCoalesce(input.environ, () => ( processEnv()));
@@ -1178,7 +1256,7 @@ function credentialsFromSettings(keyId, privateKey, signer) {
1178
1256
  }
1179
1257
 
1180
1258
  // src/version.ts
1181
- var VERSION = "0.10.0";
1259
+ var VERSION = "0.12.0";
1182
1260
  var USER_AGENT = `stx-typescript/${VERSION}`;
1183
1261
  var ASYNC_DISPOSE = _nullishCoalesce(Symbol.asyncDispose, () => ( /* @__PURE__ */ Symbol.for("Symbol.asyncDispose")));
1184
1262
 
@@ -1310,7 +1388,7 @@ var AccountView = (_class3 = class {
1310
1388
  case "all_orders":
1311
1389
  this.seeds.orders = (_nullishCoalesce(this.seeds.orders, () => ( 0))) + 1;
1312
1390
  this.#orders.clear();
1313
- for (const o of _nullishCoalesce(_optionalChain([payload, 'optionalAccess', _8 => _8.orders]), () => ( []))) this.#upsertOrder(o);
1391
+ for (const o of _nullishCoalesce(_optionalChain([payload, 'optionalAccess', _9 => _9.orders]), () => ( []))) this.#upsertOrder(o);
1314
1392
  return change("orders", true);
1315
1393
  case "new_open_order":
1316
1394
  this.#upsertOrder(payload);
@@ -1318,7 +1396,7 @@ var AccountView = (_class3 = class {
1318
1396
  case "all_trades":
1319
1397
  this.seeds.fills = (_nullishCoalesce(this.seeds.fills, () => ( 0))) + 1;
1320
1398
  this.#fills.clear();
1321
- for (const t of _nullishCoalesce(_optionalChain([payload, 'optionalAccess', _9 => _9.trades]), () => ( []))) this.#upsertFill(t);
1399
+ for (const t of _nullishCoalesce(_optionalChain([payload, 'optionalAccess', _10 => _10.trades]), () => ( []))) this.#upsertFill(t);
1322
1400
  return change("fills", true);
1323
1401
  case "trade":
1324
1402
  this.#upsertFill(payload);
@@ -1326,22 +1404,22 @@ var AccountView = (_class3 = class {
1326
1404
  case "all_positions":
1327
1405
  this.seeds.positions = (_nullishCoalesce(this.seeds.positions, () => ( 0))) + 1;
1328
1406
  this.#positions.clear();
1329
- for (const p of _nullishCoalesce(_optionalChain([payload, 'optionalAccess', _10 => _10.positions]), () => ( []))) this.#upsertPosition(p);
1407
+ for (const p of _nullishCoalesce(_optionalChain([payload, 'optionalAccess', _11 => _11.positions]), () => ( []))) this.#upsertPosition(p);
1330
1408
  return change("positions", true);
1331
1409
  case "updated_positions":
1332
- for (const p of _nullishCoalesce(_optionalChain([payload, 'optionalAccess', _11 => _11.positions]), () => ( []))) this.#upsertPosition(p);
1410
+ for (const p of _nullishCoalesce(_optionalChain([payload, 'optionalAccess', _12 => _12.positions]), () => ( []))) this.#upsertPosition(p);
1333
1411
  return change("positions", false);
1334
1412
  default:
1335
1413
  return void 0;
1336
1414
  }
1337
1415
  }
1338
1416
  #upsertOrder(order) {
1339
- if (!_optionalChain([order, 'optionalAccess', _12 => _12.id])) return;
1417
+ if (!_optionalChain([order, 'optionalAccess', _13 => _13.id])) return;
1340
1418
  if (TERMINAL_ORDER_STATUSES.has(String(order.status))) this.#orders.delete(order.id);
1341
1419
  else this.#orders.set(order.id, order);
1342
1420
  }
1343
1421
  #upsertFill(fill) {
1344
- if (!_optionalChain([fill, 'optionalAccess', _13 => _13.id])) return;
1422
+ if (!_optionalChain([fill, 'optionalAccess', _14 => _14.id])) return;
1345
1423
  this.#fills.delete(fill.id);
1346
1424
  this.#fills.set(fill.id, fill);
1347
1425
  if (this.#fills.size > this.#maxFills) {
@@ -1350,7 +1428,7 @@ var AccountView = (_class3 = class {
1350
1428
  }
1351
1429
  }
1352
1430
  #upsertPosition(position) {
1353
- const key = _nullishCoalesce(_optionalChain([position, 'optionalAccess', _14 => _14.market_id]), () => ( _optionalChain([position, 'optionalAccess', _15 => _15.id])));
1431
+ const key = _nullishCoalesce(_optionalChain([position, 'optionalAccess', _15 => _15.market_id]), () => ( _optionalChain([position, 'optionalAccess', _16 => _16.id])));
1354
1432
  if (!key) return;
1355
1433
  if (!this.#keepFlat && isZero(position.position)) this.#positions.delete(key);
1356
1434
  else this.#positions.set(key, position);
@@ -1789,7 +1867,7 @@ function buildRequest(operationId, args = {}) {
1789
1867
  const op = OPERATIONS[operationId];
1790
1868
  let path = op.path;
1791
1869
  for (const name of op.pathParams) {
1792
- const value = _optionalChain([args, 'access', _16 => _16.pathParams, 'optionalAccess', _17 => _17[name]]);
1870
+ const value = _optionalChain([args, 'access', _17 => _17.pathParams, 'optionalAccess', _18 => _18[name]]);
1793
1871
  if (!value) throw new TypeError(`${name} is required`);
1794
1872
  path = path.replace(`{${name}}`, quote(String(value)));
1795
1873
  }
@@ -1828,7 +1906,9 @@ function decodeResponse(request, status, text, headers = {}) {
1828
1906
  method: request.method,
1829
1907
  path: request.path,
1830
1908
  retryAfter: headers.retryAfter,
1831
- wwwAuthenticate: headers.wwwAuthenticate
1909
+ wwwAuthenticate: headers.wwwAuthenticate,
1910
+ stxError: headers.stxError,
1911
+ cfId: headers.cfId
1832
1912
  });
1833
1913
  }
1834
1914
  function splitPage(operationId, body) {
@@ -1843,10 +1923,14 @@ function toBatchOrderResult(raw) {
1843
1923
  const obj = raw && typeof raw === "object" ? raw : {};
1844
1924
  const order = _nullishCoalesce(obj.order, () => ( null));
1845
1925
  const errors = Array.isArray(obj.errors) ? obj.errors : null;
1846
- return { ...obj, order, errors, ok: order !== null && !_optionalChain([errors, 'optionalAccess', _18 => _18.length]) };
1926
+ return { ...obj, order, errors, ok: order !== null && !_optionalChain([errors, 'optionalAccess', _19 => _19.length]) };
1847
1927
  }
1848
1928
 
1849
1929
  // src/client.ts
1930
+ var FILL_MODES = ["normal", "post_only", "fill_or_kill"];
1931
+ var NOT_ENABLED = /fill_mode (post_only|fill_or_kill) is not enabled|The (post_only|fill_or_kill) fill mode is not enabled/;
1932
+ var NOT_ACCEPTED = /does not accept the (post_only|fill_or_kill) fill mode/;
1933
+ var MATCH_WITH_SELF = "would match with your other order";
1850
1934
  var NEW_ORDER_FIELDS = {
1851
1935
  marketId: "market_id",
1852
1936
  action: "action",
@@ -1857,7 +1941,8 @@ var NEW_ORDER_FIELDS = {
1857
1941
  expiration: "expiration",
1858
1942
  expirationTime: "expiration_time",
1859
1943
  cancelOnDisconnect: "cancel_on_disconnect",
1860
- deviceId: "device_id"
1944
+ deviceId: "device_id",
1945
+ fillMode: "fill_mode"
1861
1946
  };
1862
1947
  function amount(name, value, required) {
1863
1948
  if (value === void 0 || value === null) {
@@ -1872,6 +1957,13 @@ function amount(name, value, required) {
1872
1957
  return value;
1873
1958
  }
1874
1959
  function orderBody(marketId, action, orderType, opts) {
1960
+ const mode = opts.fillMode;
1961
+ if (mode !== void 0 && mode !== null && !FILL_MODES.includes(mode)) {
1962
+ throw new TypeError(`fillMode must be one of ${JSON.stringify(FILL_MODES)}, got ${JSON.stringify(mode)}`);
1963
+ }
1964
+ if ((mode === "post_only" || mode === "fill_or_kill") && orderType !== "limit") {
1965
+ throw new TypeError(`fillMode "${mode}" is for limit orders only`);
1966
+ }
1875
1967
  const body = {
1876
1968
  market_id: marketId,
1877
1969
  action,
@@ -1884,7 +1976,8 @@ function orderBody(marketId, action, orderType, opts) {
1884
1976
  expiration: opts.expiration,
1885
1977
  expiration_time: opts.expirationTime,
1886
1978
  cancel_on_disconnect: opts.cancelOnDisconnect,
1887
- device_id: opts.deviceId
1979
+ device_id: opts.deviceId,
1980
+ fill_mode: mode === "normal" ? void 0 : mode
1888
1981
  };
1889
1982
  for (const [k, v] of Object.entries(optional)) if (v !== void 0 && v !== null) body[k] = v;
1890
1983
  return body;
@@ -1985,7 +2078,7 @@ var STX = (_class4 = class _STX {
1985
2078
  this.#fetch = fetchImpl;
1986
2079
  }
1987
2080
  toString() {
1988
- return `STX(baseUrl=${JSON.stringify(this.baseUrl)}, keyId=${JSON.stringify(_nullishCoalesce(_optionalChain([this, 'access', _19 => _19.credentials, 'optionalAccess', _20 => _20.keyId]), () => ( null)))})`;
2081
+ return `STX(baseUrl=${JSON.stringify(this.baseUrl)}, keyId=${JSON.stringify(_nullishCoalesce(_optionalChain([this, 'access', _20 => _20.credentials, 'optionalAccess', _21 => _21.keyId]), () => ( null)))})`;
1989
2082
  }
1990
2083
  /** The exchange host, e.g. `"demo.stxapp.io"`: the name `STXNotAvailableException` and `capabilities()` report. */
1991
2084
  get host() {
@@ -1996,7 +2089,7 @@ var STX = (_class4 = class _STX {
1996
2089
  // ------------------------------------------------------------------
1997
2090
  /**
1998
2091
  * Which features this exchange has, from what it publishes: its OAuth
1999
- * discovery document, `/api_version`, a signed GET of the routes that not
2092
+ * discovery document, a signed GET of the routes that not
2000
2093
  * every exchange has yet, and a join of a combos topic nobody owns. Nothing
2001
2094
  * is created or changed. Checked once per client and cached; pass
2002
2095
  * `{ refresh: true }` to check again.
@@ -2038,6 +2131,20 @@ var STX = (_class4 = class _STX {
2038
2131
  clearTimeout(timer);
2039
2132
  }
2040
2133
  }
2134
+ // A typed error for the exchange's refusals of a fill mode, else undefined.
2135
+ #fillModeError(err, mode) {
2136
+ if (!(err instanceof STXValidationException || err instanceof STXRejectedException)) return void 0;
2137
+ const base = { statusCode: err.statusCode, body: err.body, method: err.method, path: err.path, cause: err };
2138
+ const off = NOT_ENABLED.exec(err.message);
2139
+ if (off) return new STXNotAvailableException(`orders.${_nullishCoalesce(off[1], () => ( off[2]))}`, this.host, base);
2140
+ if (!(err instanceof STXRejectedException)) return void 0;
2141
+ const notAccepted = NOT_ACCEPTED.exec(err.message);
2142
+ if (notAccepted) return new STXFillModeNotAllowedException(err.message, { ...base, fillMode: notAccepted[1] });
2143
+ if (mode === "post_only" && err.message.includes(MATCH_WITH_SELF)) {
2144
+ return new STXPostOnlyWouldMatchException(err.message, { ...base, reason: "match_with_self" });
2145
+ }
2146
+ return void 0;
2147
+ }
2041
2148
  async #joinReason(topic) {
2042
2149
  if (!this.auth) return null;
2043
2150
  const ws = this.websocket({ reconnect: false, joinTimeoutMs: 8e3 });
@@ -2088,7 +2195,7 @@ var STX = (_class4 = class _STX {
2088
2195
  status,
2089
2196
  attempt,
2090
2197
  durationMs: Date.now() - started,
2091
- authKind: _optionalChain([this, 'access', _21 => _21.auth, 'optionalAccess', _22 => _22.kind]),
2198
+ authKind: _optionalChain([this, 'access', _22 => _22.auth, 'optionalAccess', _23 => _23.kind]),
2092
2199
  requestBody: request.body,
2093
2200
  responseBody
2094
2201
  });
@@ -2120,7 +2227,7 @@ var STX = (_class4 = class _STX {
2120
2227
  });
2121
2228
  }
2122
2229
  throw new STXTransportException(
2123
- `${request.method} ${request.path} failed: ${_nullishCoalesce(_optionalChain([err, 'optionalAccess', _23 => _23.message]), () => ( String(err)))}`,
2230
+ `${request.method} ${request.path} failed: ${_nullishCoalesce(_optionalChain([err, 'optionalAccess', _24 => _24.message]), () => ( String(err)))}`,
2124
2231
  { method: request.method, path: request.path, cause: err }
2125
2232
  );
2126
2233
  } finally {
@@ -2129,7 +2236,9 @@ var STX = (_class4 = class _STX {
2129
2236
  this.#report(request, response.status, attempt, started, text);
2130
2237
  return decodeResponse(request, response.status, text, {
2131
2238
  retryAfter: response.headers.get("Retry-After"),
2132
- wwwAuthenticate: response.headers.get("WWW-Authenticate")
2239
+ wwwAuthenticate: response.headers.get("WWW-Authenticate"),
2240
+ stxError: response.headers.get("x-stx-error"),
2241
+ cfId: response.headers.get("x-amz-cf-id")
2133
2242
  });
2134
2243
  }
2135
2244
  async #send(request) {
@@ -2142,7 +2251,7 @@ var STX = (_class4 = class _STX {
2142
2251
  return await this.#sendOnce(request, sent);
2143
2252
  } catch (err) {
2144
2253
  if (!(err instanceof STXException)) throw err;
2145
- if (err.statusCode === 401 && !reauthenticated && _optionalChain([this, 'access', _24 => _24.auth, 'optionalAccess', _25 => _25.onUnauthorized])) {
2254
+ if (err.statusCode === 401 && !reauthenticated && _optionalChain([this, 'access', _25 => _25.auth, 'optionalAccess', _26 => _26.onUnauthorized])) {
2146
2255
  reauthenticated = true;
2147
2256
  if (await this.auth.onUnauthorized()) continue;
2148
2257
  }
@@ -2157,7 +2266,7 @@ var STX = (_class4 = class _STX {
2157
2266
  return await this.#send(buildRequest(operationId, args));
2158
2267
  } catch (err) {
2159
2268
  const feature = GATED_OPERATIONS[operationId];
2160
- const off = feature !== void 0 && err instanceof STXNotFoundException && SWITCHED_OFF[feature] !== void 0 && _optionalChain([err, 'access', _26 => _26.body, 'optionalAccess', _27 => _27.error]) === SWITCHED_OFF[feature];
2269
+ const off = feature !== void 0 && err instanceof STXNotFoundException && SWITCHED_OFF[feature] !== void 0 && _optionalChain([err, 'access', _27 => _27.body, 'optionalAccess', _28 => _28.error]) === SWITCHED_OFF[feature];
2161
2270
  if (feature && (isMissingRoute(err) || off)) {
2162
2271
  throw new STXNotAvailableException(feature, this.host, {
2163
2272
  statusCode: err.statusCode,
@@ -2210,7 +2319,7 @@ var STX = (_class4 = class _STX {
2210
2319
  * `user_id`.
2211
2320
  */
2212
2321
  async userId() {
2213
- if (_optionalChain([this, 'access', _28 => _28.#me, 'optionalAccess', _29 => _29.user_id])) return this.#me.user_id;
2322
+ if (_optionalChain([this, 'access', _29 => _29.#me, 'optionalAccess', _30 => _30.user_id])) return this.#me.user_id;
2214
2323
  try {
2215
2324
  await this.me();
2216
2325
  } catch (err) {
@@ -2221,7 +2330,7 @@ var STX = (_class4 = class _STX {
2221
2330
  if (!balance.user_id) throw err;
2222
2331
  this.#me = { ..._nullishCoalesce(this.#me, () => ( {})), user_id: balance.user_id };
2223
2332
  }
2224
- if (!_optionalChain([this, 'access', _30 => _30.#me, 'optionalAccess', _31 => _31.user_id])) throw new STXException("GET /api/v1/me returned no user_id");
2333
+ if (!_optionalChain([this, 'access', _31 => _31.#me, 'optionalAccess', _32 => _32.user_id])) throw new STXException("GET /api/v1/me returned no user_id");
2225
2334
  return this.#me.user_id;
2226
2335
  }
2227
2336
  // ------------------------------------------------------------------
@@ -2388,6 +2497,18 @@ var STX = (_class4 = class _STX {
2388
2497
  * are decimal strings, e.g. `{ price: "0.58", quantity: "100" }`. Numbers are
2389
2498
  * refused client-side.
2390
2499
  *
2500
+ * `fillMode` (limit orders only) is `"normal"` (the default), `"post_only"`
2501
+ * or `"fill_or_kill"`. A post-only order that would match on arrival is not
2502
+ * placed: this throws `STXPostOnlyWouldMatchException`. A fill-or-kill order
2503
+ * comes back `accepted` (or `delayed` in play); follow it on the `orders`
2504
+ * channel or with `order()` to see it `filled` or `cancelled`.
2505
+ *
2506
+ * The exchange decides whether it takes either mode. Where a mode is not
2507
+ * enabled it rejects the order and this throws `STXNotAvailableException`
2508
+ * (`orders.post_only`, `orders.fill_or_kill`). An exchange on a release from
2509
+ * before fill modes places the order as a normal limit order. A combination
2510
+ * market throws `STXFillModeNotAllowedException`.
2511
+ *
2391
2512
  * The exchange validates the order: a bad price step or a fractional
2392
2513
  * quantity throws `STXValidationException` (400) or `STXRejectedException`
2393
2514
  * (422) with the API's message. An order from outside the region is also
@@ -2398,16 +2519,41 @@ var STX = (_class4 = class _STX {
2398
2519
  */
2399
2520
  async placeOrder(marketId, action, orderType, opts) {
2400
2521
  const body = orderBody(marketId, action, orderType, _nullishCoalesce(opts, () => ( {})));
2401
- return this.#one("orders_post", { body });
2522
+ const mode = body.fill_mode;
2523
+ if (mode === void 0) return this.#one("orders_post", { body });
2524
+ let order;
2525
+ try {
2526
+ order = await this.#one("orders_post", { body });
2527
+ } catch (err) {
2528
+ throw _nullishCoalesce(this.#fillModeError(err, mode), () => ( err));
2529
+ }
2530
+ if (mode === "post_only" && order.status === "cancelled" && order.cancellation_reason === "auto_matching") {
2531
+ throw new STXPostOnlyWouldMatchException(
2532
+ "The post-only order would have matched on arrival, so it was cancelled.",
2533
+ { reason: "auto_matching", order, statusCode: 200, method: "POST", path: OPERATIONS.orders_post.path }
2534
+ );
2535
+ }
2536
+ return order;
2402
2537
  }
2403
2538
  /**
2404
2539
  * `POST /api/v1/orders/batched`: place several orders in one call. Returns
2405
2540
  * one result per order, in order; a rejected order has `errors` instead of
2406
- * `order` and does not stop the others.
2541
+ * `order` and does not stop the others. A post-only order that would have
2542
+ * matched comes back as its order, `cancelled` with `cancellation_reason`
2543
+ * `auto_matching`.
2544
+ *
2545
+ * When the exchange rejects the call because a `fillMode` is not enabled
2546
+ * there, this throws `STXNotAvailableException`, as `placeOrder()` does.
2407
2547
  */
2408
2548
  async placeOrders(orders) {
2409
2549
  const body = { orders: orders.map(normalizeOrder) };
2410
- const raw = await this.#list("orders_batched_post", { body });
2550
+ const modes = body.orders.map((o) => o.fill_mode).filter((m) => typeof m === "string");
2551
+ let raw;
2552
+ try {
2553
+ raw = await this.#list("orders_batched_post", { body });
2554
+ } catch (err) {
2555
+ throw _nullishCoalesce((modes.length ? this.#fillModeError(err, void 0) : void 0), () => ( err));
2556
+ }
2411
2557
  return raw.map(toBatchOrderResult);
2412
2558
  }
2413
2559
  /**
@@ -2466,6 +2612,7 @@ var STX = (_class4 = class _STX {
2466
2612
  market_ids: ids(q.marketIds),
2467
2613
  event_ids: ids(q.eventIds),
2468
2614
  exclude_zero_settlements: q.excludeZeroSettlements,
2615
+ unsettled_only: q.unsettledOnly,
2469
2616
  from_time: q.fromTime,
2470
2617
  to_time: q.toTime,
2471
2618
  sports: ids(q.sports),
@@ -2898,7 +3045,7 @@ var Channel = (_class5 = class {
2898
3045
  _startPinger() {
2899
3046
  this._stopPinger();
2900
3047
  let interval = this.pingIntervalMs;
2901
- const granted = _optionalChain([this, 'access', _32 => _32.reply, 'optionalAccess', _33 => _33.ping_timeout]);
3048
+ const granted = _optionalChain([this, 'access', _33 => _33.reply, 'optionalAccess', _34 => _34.ping_timeout]);
2902
3049
  if (typeof granted === "number" && this.joinPayload.cancel_on_disconnect) {
2903
3050
  const cod = granted / 3;
2904
3051
  interval = interval === null ? cod : Math.min(interval, cod);
@@ -2912,7 +3059,7 @@ var Channel = (_class5 = class {
2912
3059
  (err) => this.#ws.logger.warn(`${this.topic} ping failed: ${err.message}`)
2913
3060
  );
2914
3061
  }, every);
2915
- _optionalChain([this, 'access', _34 => _34.#pingTimer, 'access', _35 => _35.unref, 'optionalCall', _36 => _36()]);
3062
+ _optionalChain([this, 'access', _35 => _35.#pingTimer, 'access', _36 => _36.unref, 'optionalCall', _37 => _37()]);
2916
3063
  }
2917
3064
  }
2918
3065
  /** @internal */
@@ -3124,7 +3271,7 @@ var STXWebSocket = (_class6 = class {
3124
3271
  */
3125
3272
  async marketUpdates(opts = {}) {
3126
3273
  const channel = await this.join("market_updates", {}, opts.onMessage);
3127
- if (_optionalChain([opts, 'access', _37 => _37.watch, 'optionalAccess', _38 => _38.length])) await channel.watch(opts.watch);
3274
+ if (_optionalChain([opts, 'access', _38 => _38.watch, 'optionalAccess', _39 => _39.length])) await channel.watch(opts.watch);
3128
3275
  return channel;
3129
3276
  }
3130
3277
  /**
@@ -3373,12 +3520,12 @@ var STXWebSocket = (_class6 = class {
3373
3520
  if (!(err instanceof STXTransportException)) return false;
3374
3521
  if (err.statusCode !== 401 && err.statusCode !== 403) return false;
3375
3522
  const auth = this.rest.auth;
3376
- if (!_optionalChain([auth, 'optionalAccess', _39 => _39.onUnauthorized])) return false;
3523
+ if (!_optionalChain([auth, 'optionalAccess', _40 => _40.onUnauthorized])) return false;
3377
3524
  return auth.onUnauthorized();
3378
3525
  }
3379
3526
  async #open(reconnect = false) {
3380
3527
  const headers = { "User-Agent": USER_AGENT };
3381
- if (_optionalChain([this, 'access', _40 => _40.rest, 'access', _41 => _41.auth, 'optionalAccess', _42 => _42.websocketHeaders])) Object.assign(headers, await this.rest.auth.websocketHeaders({ reconnect }));
3528
+ if (_optionalChain([this, 'access', _41 => _41.rest, 'access', _42 => _42.auth, 'optionalAccess', _43 => _43.websocketHeaders])) Object.assign(headers, await this.rest.auth.websocketHeaders({ reconnect }));
3382
3529
  const conn = new (0, _ws2.default)(this.url, {
3383
3530
  headers,
3384
3531
  rejectUnauthorized: this.rest.verifyTls,
@@ -3394,7 +3541,7 @@ var STXWebSocket = (_class6 = class {
3394
3541
  conn.on("error", () => {
3395
3542
  });
3396
3543
  conn.terminate();
3397
- const reason = _optionalChain([res, 'access', _43 => _43.headers, 'optionalAccess', _44 => _44["x-stx-error"]]);
3544
+ const reason = _optionalChain([res, 'access', _44 => _44.headers, 'optionalAccess', _45 => _45["x-stx-error"]]);
3398
3545
  reject(
3399
3546
  new STXTransportException(
3400
3547
  `Could not open ${this.url}: HTTP ${res.statusCode}${reason ? ` (${String(reason)})` : ""}`,
@@ -3509,7 +3656,7 @@ var STXWebSocket = (_class6 = class {
3509
3656
  if (!channel.joined) {
3510
3657
  channel._endedJoin = { joinRef: String(joinRef), event };
3511
3658
  const pending = this.#pending.get(String(joinRef));
3512
- if (_optionalChain([pending, 'optionalAccess', _45 => _45.event]) === "phx_join") pending.reject(joinInterrupted(channel, event));
3659
+ if (_optionalChain([pending, 'optionalAccess', _46 => _46.event]) === "phx_join") pending.reject(joinInterrupted(channel, event));
3513
3660
  if (event === "phx_close" && channel.name === "market") this.#finishMarket(channel);
3514
3661
  return;
3515
3662
  }
@@ -3562,7 +3709,7 @@ var STXWebSocket = (_class6 = class {
3562
3709
  } catch (err) {
3563
3710
  this.logger.error(`rejoin ${channel.topic} failed: ${err.message}`);
3564
3711
  const reply = err instanceof STXChannelException ? err.reply : void 0;
3565
- if (_optionalChain([reply, 'optionalAccess', _46 => _46.reason]) === "unauthorized" || _optionalChain([reply, 'optionalAccess', _47 => _47.reason]) === COMBOS_UNAVAILABLE_REASON && COMBO_CHANNELS.has(channel.name)) {
3712
+ if (_optionalChain([reply, 'optionalAccess', _47 => _47.reason]) === "unauthorized" || _optionalChain([reply, 'optionalAccess', _48 => _48.reason]) === COMBOS_UNAVAILABLE_REASON && COMBO_CHANNELS.has(channel.name)) {
3566
3713
  channel._close();
3567
3714
  return;
3568
3715
  }
@@ -3576,7 +3723,7 @@ var STXWebSocket = (_class6 = class {
3576
3723
  if (!this.connected) return;
3577
3724
  if (this.#pendingHeartbeat !== null) {
3578
3725
  this.logger.warn("heartbeat unanswered; reconnecting");
3579
- _optionalChain([this, 'access', _48 => _48.#conn, 'optionalAccess', _49 => _49.terminate, 'call', _50 => _50()]);
3726
+ _optionalChain([this, 'access', _49 => _49.#conn, 'optionalAccess', _50 => _50.terminate, 'call', _51 => _51()]);
3580
3727
  return;
3581
3728
  }
3582
3729
  const ref = this.#nextRef();
@@ -3584,7 +3731,7 @@ var STXWebSocket = (_class6 = class {
3584
3731
  try {
3585
3732
  this.#send([null, ref, PHOENIX_TOPIC, "heartbeat", {}]);
3586
3733
  } catch (e13) {
3587
- _optionalChain([this, 'access', _51 => _51.#conn, 'optionalAccess', _52 => _52.terminate, 'call', _53 => _53()]);
3734
+ _optionalChain([this, 'access', _52 => _52.#conn, 'optionalAccess', _53 => _53.terminate, 'call', _54 => _54()]);
3588
3735
  }
3589
3736
  }, this.heartbeatIntervalMs);
3590
3737
  }
@@ -3671,7 +3818,7 @@ var STXWebSocket = (_class6 = class {
3671
3818
  this.error = err;
3672
3819
  this.#shutdownAfterDrop();
3673
3820
  try {
3674
- _optionalChain([this, 'access', _54 => _54.onAuthError, 'optionalCall', _55 => _55(err)]);
3821
+ _optionalChain([this, 'access', _55 => _55.onAuthError, 'optionalCall', _56 => _56(err)]);
3675
3822
  } catch (hookErr) {
3676
3823
  this.logger.error("onAuthError threw", hookErr);
3677
3824
  }
@@ -3772,5 +3919,10 @@ function dropUndefined(payload) {
3772
3919
 
3773
3920
 
3774
3921
 
3775
- exports.STXException = STXException; exports.STXConfigException = STXConfigException; exports.STXAPIException = STXAPIException; exports.STXValidationException = STXValidationException; exports.STXAuthenticationException = STXAuthenticationException; exports.STXForbiddenException = STXForbiddenException; exports.STXInvalidTokenException = STXInvalidTokenException; exports.STXInsufficientScopeException = STXInsufficientScopeException; exports.STXTermsRequiredException = STXTermsRequiredException; exports.STXIPNotAllowedException = STXIPNotAllowedException; exports.STXNotFoundException = STXNotFoundException; exports.STXRejectedException = STXRejectedException; exports.STXRateLimitException = STXRateLimitException; exports.STXServerException = STXServerException; exports.STXTransportException = STXTransportException; exports.STXChannelException = STXChannelException; exports.STXTimeoutException = STXTimeoutException; exports.notAvailableMessage = notAvailableMessage; exports.STXNotAvailableException = STXNotAvailableException; exports.STXCombosUnavailableException = STXCombosUnavailableException; exports.isEdgeBlock = isEdgeBlock; exports.STXComboRefusedException = STXComboRefusedException; exports.STXComboPriceMovedException = STXComboPriceMovedException; exports.errorForStatus = errorForStatus; exports.FEATURES = FEATURES; exports.Capabilities = Capabilities; exports.Region = Region; exports.Environment = Environment; exports.Environments = Environments; exports.HOSTS = HOSTS; exports.environmentNamed = environmentNamed; exports.resolveHost = resolveHost; exports.baseUrlFor = baseUrlFor; exports.socketUrlFor = socketUrlFor; exports.OPERATIONS = OPERATIONS; exports.Stats = Stats; exports.MAX_MARKETS_PER_REQUEST = MAX_MARKETS_PER_REQUEST; exports.isValidLine = isValidLine; exports.Page = Page; exports.RetryPolicy = RetryPolicy; exports.NO_RETRY = NO_RETRY; exports.resolveSettings = resolveSettings; exports.KEY_HEADER = KEY_HEADER; exports.TIMESTAMP_HEADER = TIMESTAMP_HEADER; exports.SIGNATURE_HEADER = SIGNATURE_HEADER; exports.buildMessage = buildMessage; exports.requestPath = requestPath; exports.handshakePath = handshakePath; exports.loadPrivateKey = loadPrivateKey; exports.signerFromPrivateKey = signerFromPrivateKey; exports.ApiKeyCredentials = ApiKeyCredentials; exports.VERSION = VERSION; exports.USER_AGENT = USER_AGENT; exports.TERMINAL_ORDER_STATUSES = TERMINAL_ORDER_STATUSES; exports.AccountView = AccountView; exports.ComboPlayer = ComboPlayer; exports.ComboMaker = ComboMaker; exports.centsToDollars = centsToDollars; exports.toDollarString = toDollarString; exports.toQuantity = toQuantity; exports.convertMarketPayload = convertMarketPayload; exports.convertMarketsFrame = convertMarketsFrame; exports.convertBook = convertBook; exports.convertMarketChannelPayload = convertMarketChannelPayload; exports.SNAPSHOT_EVENTS = SNAPSHOT_EVENTS; exports.ChannelMessage = ChannelMessage; exports.ReconnectPolicy = ReconnectPolicy; exports.Channel = Channel; exports.STXWebSocket = STXWebSocket; exports.orderBody = orderBody; exports.STX = STX;
3776
- //# sourceMappingURL=chunk-42OCIF3G.cjs.map
3922
+
3923
+
3924
+
3925
+
3926
+
3927
+ exports.STXException = STXException; exports.STXConfigException = STXConfigException; exports.STXAPIException = STXAPIException; exports.STXValidationException = STXValidationException; exports.STXAuthenticationException = STXAuthenticationException; exports.STXForbiddenException = STXForbiddenException; exports.STXInvalidTokenException = STXInvalidTokenException; exports.STXInsufficientScopeException = STXInsufficientScopeException; exports.STXTermsRequiredException = STXTermsRequiredException; exports.STXIPNotAllowedException = STXIPNotAllowedException; exports.STXBlockedException = STXBlockedException; exports.STXRestrictedJurisdictionException = STXRestrictedJurisdictionException; exports.STXUnusualNetworkException = STXUnusualNetworkException; exports.STXNotFoundException = STXNotFoundException; exports.STXRejectedException = STXRejectedException; exports.STXFillModeNotAllowedException = STXFillModeNotAllowedException; exports.STXPostOnlyWouldMatchException = STXPostOnlyWouldMatchException; exports.STXRateLimitException = STXRateLimitException; exports.STXServerException = STXServerException; exports.STXTransportException = STXTransportException; exports.STXChannelException = STXChannelException; exports.STXTimeoutException = STXTimeoutException; exports.notAvailableMessage = notAvailableMessage; exports.STXNotAvailableException = STXNotAvailableException; exports.STXCombosUnavailableException = STXCombosUnavailableException; exports.isEdgeBlock = isEdgeBlock; exports.STXComboRefusedException = STXComboRefusedException; exports.STXComboPriceMovedException = STXComboPriceMovedException; exports.errorForStatus = errorForStatus; exports.FEATURES = FEATURES; exports.Capabilities = Capabilities; exports.Region = Region; exports.Environment = Environment; exports.Environments = Environments; exports.HOSTS = HOSTS; exports.environmentNamed = environmentNamed; exports.resolveHost = resolveHost; exports.baseUrlFor = baseUrlFor; exports.socketUrlFor = socketUrlFor; exports.OPERATIONS = OPERATIONS; exports.Stats = Stats; exports.MAX_MARKETS_PER_REQUEST = MAX_MARKETS_PER_REQUEST; exports.isValidLine = isValidLine; exports.Page = Page; exports.RetryPolicy = RetryPolicy; exports.NO_RETRY = NO_RETRY; exports.resolveSettings = resolveSettings; exports.KEY_HEADER = KEY_HEADER; exports.TIMESTAMP_HEADER = TIMESTAMP_HEADER; exports.SIGNATURE_HEADER = SIGNATURE_HEADER; exports.buildMessage = buildMessage; exports.requestPath = requestPath; exports.handshakePath = handshakePath; exports.loadPrivateKey = loadPrivateKey; exports.signerFromPrivateKey = signerFromPrivateKey; exports.ApiKeyCredentials = ApiKeyCredentials; exports.VERSION = VERSION; exports.USER_AGENT = USER_AGENT; exports.TERMINAL_ORDER_STATUSES = TERMINAL_ORDER_STATUSES; exports.AccountView = AccountView; exports.ComboPlayer = ComboPlayer; exports.ComboMaker = ComboMaker; exports.centsToDollars = centsToDollars; exports.toDollarString = toDollarString; exports.toQuantity = toQuantity; exports.convertMarketPayload = convertMarketPayload; exports.convertMarketsFrame = convertMarketsFrame; exports.convertBook = convertBook; exports.convertMarketChannelPayload = convertMarketChannelPayload; exports.SNAPSHOT_EVENTS = SNAPSHOT_EVENTS; exports.ChannelMessage = ChannelMessage; exports.ReconnectPolicy = ReconnectPolicy; exports.Channel = Channel; exports.STXWebSocket = STXWebSocket; exports.orderBody = orderBody; exports.STX = STX;
3928
+ //# sourceMappingURL=chunk-B3JQFXMJ.cjs.map