@stxapp/stx-typescript 0.6.3 → 0.7.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.
@@ -185,7 +185,7 @@ var Environments = {
185
185
  name: "ontario-production",
186
186
  region: Region.ONTARIO,
187
187
  env: Environment.PRODUCTION,
188
- host: "stxapp.ca",
188
+ host: "api.on.stxapp.ca",
189
189
  realMoney: true
190
190
  }
191
191
  };
@@ -809,7 +809,7 @@ function credentialsFromSettings(keyId, privateKey, signer) {
809
809
  }
810
810
 
811
811
  // src/version.ts
812
- var VERSION = "0.6.3";
812
+ var VERSION = "0.7.0";
813
813
  var USER_AGENT = `stx-typescript/${VERSION}`;
814
814
  var ASYNC_DISPOSE = Symbol.asyncDispose ?? /* @__PURE__ */ Symbol.for("Symbol.asyncDispose");
815
815
 
@@ -1187,160 +1187,6 @@ function toBatchOrderResult(raw) {
1187
1187
  return { ...obj, order, errors, ok: order !== null && !errors?.length };
1188
1188
  }
1189
1189
 
1190
- // src/legacy-routes.ts
1191
- function isRouteMissing(err) {
1192
- return err instanceof STXNotFoundException && err.statusCode === 404 && typeof err.body === "string";
1193
- }
1194
- var QUIET = { debug() {
1195
- }, info() {
1196
- }, warn() {
1197
- }, error() {
1198
- } };
1199
- var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1200
- async function channelSnapshot(client, join3, event) {
1201
- const me = await client._identity();
1202
- const ws = client.websocket({
1203
- userId: me.user_id,
1204
- reconnect: false,
1205
- channelPingIntervalMs: null,
1206
- joinTimeoutMs: client.timeoutMs,
1207
- logger: QUIET
1208
- });
1209
- try {
1210
- const channel = await join3(ws, me);
1211
- const snapshot = await channel.waitSnapshot(client.timeoutMs);
1212
- return snapshot[event];
1213
- } finally {
1214
- await ws.close();
1215
- }
1216
- }
1217
- async function balanceFromChannel(client) {
1218
- const payload = await channelSnapshot(
1219
- client,
1220
- (ws, me) => ws.balances(me.account_id ? { accountId: me.account_id } : {}),
1221
- "balances"
1222
- );
1223
- if (!payload || typeof payload !== "object") {
1224
- throw new STXException("The balances channel sent no balance", { path: "/api/v1/account/balance" });
1225
- }
1226
- return payload;
1227
- }
1228
- function positionsFilter(marketIds) {
1229
- if (marketIds === void 0 || marketIds === null) return null;
1230
- const list = typeof marketIds === "string" ? [marketIds] : [...marketIds];
1231
- if (list.length === 0) return null;
1232
- const joined = list.join(",");
1233
- if (joined === "") return null;
1234
- const ids2 = joined.split(",").map((s) => s.trim());
1235
- for (const id of ids2) {
1236
- if (!UUID.test(id)) {
1237
- throw new STXValidationException(`${id} is not a valid UUID`, {
1238
- statusCode: 400,
1239
- body: { error: `${id} is not a valid UUID` },
1240
- method: "GET",
1241
- path: "/api/v1/positions"
1242
- });
1243
- }
1244
- }
1245
- return new Set(ids2.map((id) => id.toLowerCase()));
1246
- }
1247
- async function positionsFromChannel(client, query = {}) {
1248
- const filter = positionsFilter(query.marketIds);
1249
- const payload = await channelSnapshot(client, (ws) => ws.positions(), "all_positions");
1250
- const rows = payload && Array.isArray(payload.positions) ? payload.positions : null;
1251
- if (!rows) throw new STXException("The positions channel sent no positions", { path: "/api/v1/positions" });
1252
- return filter ? rows.filter((p) => filter.has(String(p.market_id).toLowerCase())) : rows;
1253
- }
1254
- var MAX_BATCH_ORDERS = 100;
1255
- var ORDER_TYPES = ["limit", "market"];
1256
- var ACTIONS = ["buy", "sell"];
1257
- var EXPIRATIONS = ["good_till_start", "good_till_time"];
1258
- function batchRefusal(message) {
1259
- return new STXValidationException(message, {
1260
- statusCode: 400,
1261
- body: { error: message },
1262
- method: "POST",
1263
- path: "/api/v1/orders/batched"
1264
- });
1265
- }
1266
- function enumError(field, value, allowed, required) {
1267
- if (value === void 0 || value === null) return required ? `${field} is required` : void 0;
1268
- if (typeof value !== "string") return `${field} is invalid`;
1269
- return allowed.includes(value) ? void 0 : `${field} has invalid value: ${value}`;
1270
- }
1271
- function parseDecimal(text) {
1272
- if (/^[+-]?(inf|infinity|nan)$/i.test(text)) return { special: true };
1273
- const m = /^([+-]?)(?:(\d+)\.?(\d*)|\.(\d+))(?:[eE]([+-]?\d+))?$/.exec(text);
1274
- if (!m) return void 0;
1275
- const int = m[2] ?? "";
1276
- const frac = m[3] ?? m[4] ?? "";
1277
- return { special: false, sign: m[1] === "-" ? -1 : 1, digits: int + frac, exp: Number(m[5] ?? 0) - frac.length };
1278
- }
1279
- var scaleOf = (exp) => Math.max(0, -exp);
1280
- function priceError(value) {
1281
- if (value === void 0 || value === null) return void 0;
1282
- const format2 = 'price must be a dollar amount as a string, e.g. "30.00"';
1283
- if (typeof value !== "string") return format2;
1284
- const d = parseDecimal(value);
1285
- if (!d || d.special) return format2;
1286
- if (scaleOf(d.exp) > 7) return "price supports at most 7 decimal places";
1287
- const trailingZeros = /0*$/.exec(d.digits)[0].length;
1288
- const significant = /^0*$/.test(d.digits) ? 0 : scaleOf(d.exp + trailingZeros);
1289
- if (significant > 2) {
1290
- return `price must be a whole number of cents \u2014 at most 2 decimal places, not counting trailing zeros (got ${JSON.stringify(value)})`;
1291
- }
1292
- if (d.sign < 0 || /^0*$/.test(d.digits)) return "price must be greater than 0";
1293
- return void 0;
1294
- }
1295
- function marketIdError(value) {
1296
- if (value === void 0 || value === null) return "market_id is required";
1297
- return typeof value === "string" && UUID.test(value) ? void 0 : "market_id is not a valid UUID";
1298
- }
1299
- function quantityError(value) {
1300
- if (value === void 0 || value === null) return "quantity is required";
1301
- const d = typeof value === "string" ? parseDecimal(value) : void 0;
1302
- return d && !d.special ? void 0 : 'quantity must be a decimal string, e.g. "10" or "10.00"';
1303
- }
1304
- function validateBatch(orders) {
1305
- if (orders.length === 0) throw batchRefusal("orders must not be empty");
1306
- if (orders.length > MAX_BATCH_ORDERS) {
1307
- throw batchRefusal(`orders may contain at most ${MAX_BATCH_ORDERS} orders per batch`);
1308
- }
1309
- for (const order of orders) {
1310
- const { marketId, action, orderType, ...fields } = order;
1311
- const body = orderBody(marketId, action, orderType, fields);
1312
- const message = marketIdError(body.market_id) ?? enumError("order_type", body.order_type, ORDER_TYPES, true) ?? enumError("action", body.action, ACTIONS, true) ?? priceError(body.price) ?? quantityError(body.quantity) ?? enumError("expiration", body.expiration, EXPIRATIONS, false) ?? (body.expiration !== void 0 && body.order_type !== "limit" ? "Order expiration is only supported for limit orders." : void 0);
1313
- if (message) throw batchRefusal(message);
1314
- }
1315
- }
1316
- async function placeOrdersOneByOne(client, orders, opts) {
1317
- validateBatch(orders);
1318
- const packet = opts?.geoLocation !== void 0 ? opts.geoLocation : await resolveGeoLocation(client.geoLocation) ?? null;
1319
- const results = [];
1320
- let placed = 0;
1321
- for (let i = 0; i < orders.length; i++) {
1322
- const { marketId, action, orderType, ...fields } = orders[i];
1323
- try {
1324
- const order = await client.placeOrder(marketId, action, orderType, { ...fields, geoLocation: packet });
1325
- results.push(toBatchOrderResult({ order }));
1326
- placed += 1;
1327
- } catch (err) {
1328
- if (!(err instanceof STXException)) throw err;
1329
- if (err instanceof STXRejectedException && !(err instanceof STXGeoLocationException)) {
1330
- results.push(toBatchOrderResult({ errors: [err.message] }));
1331
- continue;
1332
- }
1333
- if (err instanceof STXServerException || err instanceof STXTransportException) throw err;
1334
- if (placed === 0) throw err;
1335
- results.push(toBatchOrderResult({ errors: [err.message] }));
1336
- if (err instanceof STXValidationException) continue;
1337
- for (let j = i + 1; j < orders.length; j++) results.push(toBatchOrderResult({ errors: [err.message] }));
1338
- break;
1339
- }
1340
- }
1341
- return results;
1342
- }
1343
-
1344
1190
  // src/client.ts
1345
1191
  var NEW_ORDER_FIELDS = {
1346
1192
  marketId: "market_id",
@@ -1417,8 +1263,6 @@ var STX = class _STX {
1417
1263
  onResponse;
1418
1264
  #fetch;
1419
1265
  #me;
1420
- // Exchanges older than v3.3.172: the routes this exchange turned out not to serve.
1421
- #missingRoutes = /* @__PURE__ */ new Set();
1422
1266
  /** Test hook: how retries wait. */
1423
1267
  _sleep = sleep;
1424
1268
  constructor(opts = {}) {
@@ -1610,14 +1454,6 @@ var STX = class _STX {
1610
1454
  this.#me = await this.#one("me_get");
1611
1455
  return this.#me;
1612
1456
  }
1613
- /**
1614
- * @internal The cached `me()` when it has both ids, else a fresh `me()`.
1615
- * Never falls back to `balance()`, so the channel fallbacks can use it.
1616
- */
1617
- async _identity() {
1618
- if (this.#me?.user_id && this.#me.account_id) return this.#me;
1619
- return this.me();
1620
- }
1621
1457
  /**
1622
1458
  * The user id from `me()`, fetched once and cached. If `me()` is not
1623
1459
  * permitted, the id comes from `balance()`, which carries the same
@@ -1750,15 +1586,7 @@ var STX = class _STX {
1750
1586
  */
1751
1587
  async placeOrders(orders, opts) {
1752
1588
  const body = { orders: orders.map(normalizeOrder) };
1753
- if (this.#missingRoutes.has("batch")) return placeOrdersOneByOne(this, orders, opts);
1754
- let raw;
1755
- try {
1756
- raw = await this.#list("orders_batched_post", { body: await this.#geoBody(body, opts) });
1757
- } catch (err) {
1758
- if (!isRouteMissing(err)) throw err;
1759
- this.#missingRoutes.add("batch");
1760
- return placeOrdersOneByOne(this, orders, opts);
1761
- }
1589
+ const raw = await this.#list("orders_batched_post", { body: await this.#geoBody(body, opts) });
1762
1590
  return raw.map(toBatchOrderResult);
1763
1591
  }
1764
1592
  /**
@@ -1843,28 +1671,14 @@ var STX = class _STX {
1843
1671
  * negative when short.
1844
1672
  */
1845
1673
  async positions(query = {}) {
1846
- if (this.#missingRoutes.has("positions")) return positionsFromChannel(this, query);
1847
- try {
1848
- return await this.#list("positions_get", { query: { market_ids: ids(query.marketIds) } });
1849
- } catch (err) {
1850
- if (!isRouteMissing(err)) throw err;
1851
- this.#missingRoutes.add("positions");
1852
- return positionsFromChannel(this, query);
1853
- }
1674
+ return this.#list("positions_get", { query: { market_ids: ids(query.marketIds) } });
1854
1675
  }
1855
1676
  /**
1856
1677
  * `GET /api/v1/account/balance`: balance, liabilities and fee schedule.
1857
1678
  * The same object the `balances` channel pushes.
1858
1679
  */
1859
1680
  async balance() {
1860
- if (this.#missingRoutes.has("balance")) return balanceFromChannel(this);
1861
- try {
1862
- return await this.#one("account_balance_get");
1863
- } catch (err) {
1864
- if (!isRouteMissing(err)) throw err;
1865
- this.#missingRoutes.add("balance");
1866
- return balanceFromChannel(this);
1867
- }
1681
+ return this.#one("account_balance_get");
1868
1682
  }
1869
1683
  static #marketStatsQuery(q) {
1870
1684
  return {
@@ -1881,7 +1695,7 @@ var STX = class _STX {
1881
1695
  }
1882
1696
  /**
1883
1697
  * `GET /api/v1/account/market_stats`: your exposure and P&L per market.
1884
- * Not the public `market_stats` channel, which carries prices.
1698
+ * Not the `market_stats` WebSocket channel, which carries price history.
1885
1699
  */
1886
1700
  accountMarketStats(query = {}) {
1887
1701
  return this.#page("account_market_stats_get", _STX.#marketStatsQuery(query));
@@ -2407,7 +2221,7 @@ var STXWebSocket = class {
2407
2221
  return this.#userId;
2408
2222
  }
2409
2223
  // ------------------------------------------------------------------
2410
- // Public market channels
2224
+ // Market data channels
2411
2225
  // ------------------------------------------------------------------
2412
2226
  /**
2413
2227
  * `orderbook`: the aggregated book, one `book` push per market. Each push
@@ -2957,4 +2771,4 @@ export {
2957
2771
  orderBody,
2958
2772
  STX
2959
2773
  };
2960
- //# sourceMappingURL=chunk-PZUVKPHZ.js.map
2774
+ //# sourceMappingURL=chunk-CDXZOW53.js.map