@cexyio/cexy 0.1.0-dev.5 → 0.1.0-dev.6

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/README.md CHANGED
@@ -62,6 +62,9 @@ await cexy.trading.cancelAll({ symbol: "BTC/USDT" }); // { symbol: null } = ever
62
62
  `cancelAll` requires `symbol`: the server treats a missing symbol as "every market", so the SDK makes
63
63
  you say so with `{ symbol: null }`. An unknown symbol throws `NotFoundError`.
64
64
 
65
+ It also cancels stop orders that have not triggered yet (status `pending_trigger`) and releases
66
+ their reservations, so nothing fires into the market after the call.
67
+
65
68
  One call handles at most 500 orders and puts each in exactly one list: `cancelled`, `already_closed`
66
69
  (it filled, was refused or was cancelled elsewhere first; not an error) or `failed`, with the reason in
67
70
  `failures` (`INVALID_STATE` for an order still being placed). `has_more: true` means more orders remain.
@@ -79,6 +82,8 @@ After a call without progress it waits 1, 2, 4, 8, then 15 s, and it stops after
79
82
  request (the loop owns the retries, so it never sends more than `maxRounds` requests): a 429 round waits its
80
83
  Retry-After, which counts against the budget; another retryable error (5xx, network) takes the next backoff
81
84
  step; a wait that would pass the budget ends the loop with `stopped: "time_budget"` and `last_error_code`.
85
+ A wait imposed by the client rate limiter (e.g. `X-RateLimit-Remaining: 0` with a Reset) counts too: if it
86
+ would pass the budget the loop stops without calling, with `last_error_code: "RATE_LIMITED"`.
82
87
  A non-retryable error (e.g. a key without the trade scope) throws `CancelAllInterruptedError` with the error
83
88
  and the partial result. The server allows 30 cancel-all calls per minute per account.
84
89
 
@@ -183,6 +188,22 @@ for await (const order of cexy.trading.iterateOrderHistory({ symbol: "BTC/USDT",
183
188
  // cap the total: cexy.account.iterateLedger({}, { maxItems: 500 })
184
189
  ```
185
190
 
191
+ Each ledger entry's `reference` says what caused it, as a union told apart by `type` (`deposit`,
192
+ `withdrawal`, `order`, `trade`, `transfer`, `adjustment`, `pool`, `futures_transfer`, `system`).
193
+ Newer types the SDK does not know yet arrive unchanged instead of failing; narrow with
194
+ `isLedgerReference`:
195
+
196
+ ```ts
197
+ import { isLedgerReference } from "@cexyio/cexy";
198
+
199
+ for await (const e of cexy.account.iterateLedger({}, { maxItems: 100 })) {
200
+ if (isLedgerReference(e.reference, "trade")) console.log(e.reference.trade_id);
201
+ else if (!isLedgerReference(e.reference)) console.log("new cause type:", e.reference.type);
202
+ }
203
+ ```
204
+
205
+ Ids (`OrderId`, `TradeId`, `UserId`, …) are plain strings; the SDK does not check their format.
206
+
186
207
  ## Rate limits
187
208
 
188
209
  The client has a token-bucket limiter: **100 requests/minute without a key** (the server allows 120/min
package/dist/index.cjs CHANGED
@@ -139,7 +139,8 @@ var KNOWN_CODES = /* @__PURE__ */ new Set([
139
139
  "INTERNAL",
140
140
  "SERVICE_UNAVAILABLE",
141
141
  "UNDER_MAINTENANCE",
142
- "ENGINE_OVERLOADED"
142
+ "ENGINE_OVERLOADED",
143
+ "PRICE_UNAVAILABLE"
143
144
  ]);
144
145
  var CLIENT_ERROR_CODES = { UNEXPECTED_REDIRECT: "UNEXPECTED_REDIRECT" };
145
146
  function isKnownErrorCode(code) {
@@ -545,6 +546,17 @@ var RateLimiter = class {
545
546
  await this.#sleep(Math.min(MAX_BLOCK_MS, Math.ceil((1 - this.#tokens) * msPerToken)), signal);
546
547
  }
547
548
  }
549
+ /**
550
+ * How long `acquire()` would wait right now, in ms (0 when a request may go at once). Lets a
551
+ * caller with a time budget, such as the cancelAll untilDone loop, count the limiter's wait.
552
+ */
553
+ pendingWaitMs() {
554
+ this.#refill();
555
+ const block = this.#blockedUntil - this.#now();
556
+ if (block > 0) return block;
557
+ if (this.#tokens >= 1) return 0;
558
+ return Math.min(MAX_BLOCK_MS, Math.ceil((1 - this.#tokens) * (6e4 / this.#rpm)));
559
+ }
548
560
  /** Adapts to the server's rate-limit headers. Never raises the configured limit. */
549
561
  update(headers) {
550
562
  this.#refill();
@@ -1015,8 +1027,10 @@ var TradingResource = class extends Resource {
1015
1027
  if (progress) idle = 0;
1016
1028
  else waitMs = (CANCEL_BACKOFF_S[Math.min(idle++, CANCEL_BACKOFF_S.length - 1)] ?? 15) * 1e3;
1017
1029
  }
1018
- if (now() - start + waitMs >= budgetMs) {
1030
+ const limiterMs = this.t.config.limiter?.pendingWaitMs() ?? 0;
1031
+ if (now() - start + Math.max(waitMs, limiterMs) >= budgetMs) {
1019
1032
  stopped = "time_budget";
1033
+ if (limiterMs > waitMs) lastErrorCode = "RATE_LIMITED";
1020
1034
  break;
1021
1035
  }
1022
1036
  if (waitMs > 0) await this.t.config.sleep(waitMs, opts?.signal);
@@ -1026,7 +1040,7 @@ var TradingResource = class extends Resource {
1026
1040
  };
1027
1041
 
1028
1042
  // src/version.ts
1029
- var VERSION = "0.1.0-dev.5";
1043
+ var VERSION = "0.1.0-dev.6";
1030
1044
  var USER_AGENT = `cexy-typescript/${VERSION}`;
1031
1045
 
1032
1046
  // src/ws/emitter.ts
@@ -1878,6 +1892,23 @@ function canSetUserAgent() {
1878
1892
  return !(typeof g.window !== "undefined" && typeof g.window.document !== "undefined");
1879
1893
  }
1880
1894
 
1895
+ // src/ledger.ts
1896
+ var KNOWN_LEDGER_REFERENCE_TYPES = /* @__PURE__ */ new Set([
1897
+ "deposit",
1898
+ "withdrawal",
1899
+ "order",
1900
+ "trade",
1901
+ "transfer",
1902
+ "adjustment",
1903
+ "pool",
1904
+ "futures_transfer",
1905
+ "system"
1906
+ ]);
1907
+ function isLedgerReference(ref, type) {
1908
+ if (typeof ref !== "object" || ref === null || typeof ref.type !== "string") return false;
1909
+ return type === void 0 ? KNOWN_LEDGER_REFERENCE_TYPES.has(ref.type) : ref.type === type;
1910
+ }
1911
+
1881
1912
  exports.AccountResource = AccountResource;
1882
1913
  exports.ApiKeyAuthenticator = ApiKeyAuthenticator;
1883
1914
  exports.AssetsResource = AssetsResource;
@@ -1928,6 +1959,7 @@ exports.assertAmountFields = assertAmountFields;
1928
1959
  exports.errorFromResponse = errorFromResponse;
1929
1960
  exports.isAmount = isAmount;
1930
1961
  exports.isKnownErrorCode = isKnownErrorCode;
1962
+ exports.isLedgerReference = isLedgerReference;
1931
1963
  exports.isLocalHost = isLocalHost;
1932
1964
  exports.isRetryable = isRetryable;
1933
1965
  exports.paginate = paginate;
package/dist/index.d.cts CHANGED
@@ -54,6 +54,11 @@ declare class RateLimiter {
54
54
  get state(): RateLimiterState;
55
55
  /** Waits until a request may be sent, then takes a token. */
56
56
  acquire(signal?: AbortSignal): Promise<void>;
57
+ /**
58
+ * How long `acquire()` would wait right now, in ms (0 when a request may go at once). Lets a
59
+ * caller with a time budget, such as the cancelAll untilDone loop, count the limiter's wait.
60
+ */
61
+ pendingWaitMs(): number;
57
62
  /** Adapts to the server's rate-limit headers. Never raises the configured limit. */
58
63
  update(headers: Headers): void;
59
64
  /**
@@ -731,8 +736,10 @@ interface paths {
731
736
  get?: never;
732
737
  put?: never;
733
738
  /**
734
- * Cancels every open order, optionally within one market.
735
- * @description Best-effort: a failure on one order does not stop the rest, and every outcome is reported. A panic-button endpoint that stops at the first problem is worse than useless.
739
+ * Cancels every open order, and every stop order that has not triggered, optionally within
740
+ * @description one market.
741
+ *
742
+ * Best-effort: a failure on one order does not stop the rest, and every outcome is reported. A panic-button endpoint that stops at the first problem is worse than useless. A stop waiting for its trigger (`pending_trigger`) is cancelled too and its reservation released, so nothing fires into the market after the call.
736
743
  *
737
744
  * An order still being placed when the call starts (status `pending`, for as long as its own placement request runs) is waited for, up to 500 ms per call in total: cancelled if it opens, reported in `already_closed` if it fills or is refused, and in `failed` with code `INVALID_STATE` if it is still being placed at the deadline. Orders placed after the call starts are not part of it. At most 500 orders per call; `has_more` says there are others.
738
745
  *
@@ -1117,6 +1124,11 @@ interface components {
1117
1124
  /** @description Network code. */
1118
1125
  network: string;
1119
1126
  };
1127
+ /**
1128
+ * @description Unique identifier of a deposit.
1129
+ * @example 507f1f77bcf86cd799439011
1130
+ */
1131
+ DepositId: string;
1120
1132
  /** @description A deposit. */
1121
1133
  DepositResponse: {
1122
1134
  /** @description Address that received it. */
@@ -1198,7 +1210,7 @@ interface components {
1198
1210
  * Serialized as `SCREAMING_SNAKE_CASE`. Adding a variant is backwards-compatible; renaming or removing one is a breaking API change.
1199
1211
  * @enum {string}
1200
1212
  */
1201
- ErrorCode: "VALIDATION_FAILED" | "MALFORMED_REQUEST" | "INVALID_CURSOR" | "PRECISION_EXCEEDED" | "BELOW_MINIMUM" | "ABOVE_MAXIMUM" | "INVALID_ADDRESS" | "MEMO_REQUIRED" | "UNAUTHENTICATED" | "INVALID_CREDENTIALS" | "TOKEN_EXPIRED" | "SESSION_REVOKED" | "TWO_FACTOR_REQUIRED" | "TWO_FACTOR_INVALID" | "FRESH_TWO_FACTOR_REQUIRED" | "FORBIDDEN" | "API_KEY_NOT_ALLOWED" | "FUTURES_RESTRICTED" | "ACCOUNT_FROZEN" | "ACCOUNT_ON_HOLD" | "EMAIL_NOT_VERIFIED" | "REGION_BLOCKED" | "JURISDICTION_BLOCKED" | "NOT_FOUND" | "METHOD_NOT_ALLOWED" | "ALREADY_EXISTS" | "INVALID_STATE" | "IDEMPOTENCY_KEY_CONFLICT" | "WINDOW_OPEN" | "EVIDENCE_CONTRADICTS" | "AMOUNT_MISMATCH" | "CONCURRENT_MODIFICATION" | "INSUFFICIENT_FUNDS" | "INSUFFICIENT_FEE_FUNDS" | "MARKET_UNAVAILABLE" | "DEPOSIT_DISABLED" | "WITHDRAWAL_DISABLED" | "SELF_TRADE_BLOCKED" | "LIMIT_EXCEEDED" | "RATE_LIMITED" | "INTERNAL" | "SERVICE_UNAVAILABLE" | "UNDER_MAINTENANCE" | "ENGINE_OVERLOADED";
1213
+ ErrorCode: "VALIDATION_FAILED" | "MALFORMED_REQUEST" | "INVALID_CURSOR" | "PRECISION_EXCEEDED" | "BELOW_MINIMUM" | "ABOVE_MAXIMUM" | "INVALID_ADDRESS" | "MEMO_REQUIRED" | "UNAUTHENTICATED" | "INVALID_CREDENTIALS" | "TOKEN_EXPIRED" | "SESSION_REVOKED" | "TWO_FACTOR_REQUIRED" | "TWO_FACTOR_INVALID" | "FRESH_TWO_FACTOR_REQUIRED" | "FORBIDDEN" | "API_KEY_NOT_ALLOWED" | "FUTURES_RESTRICTED" | "ACCOUNT_FROZEN" | "ACCOUNT_ON_HOLD" | "EMAIL_NOT_VERIFIED" | "REGION_BLOCKED" | "JURISDICTION_BLOCKED" | "NOT_FOUND" | "METHOD_NOT_ALLOWED" | "ALREADY_EXISTS" | "INVALID_STATE" | "IDEMPOTENCY_KEY_CONFLICT" | "WINDOW_OPEN" | "EVIDENCE_CONTRADICTS" | "AMOUNT_MISMATCH" | "CONCURRENT_MODIFICATION" | "INSUFFICIENT_FUNDS" | "INSUFFICIENT_FEE_FUNDS" | "MARKET_UNAVAILABLE" | "DEPOSIT_DISABLED" | "WITHDRAWAL_DISABLED" | "SELF_TRADE_BLOCKED" | "LIMIT_EXCEEDED" | "PRICE_UNAVAILABLE" | "RATE_LIMITED" | "INTERNAL" | "SERVICE_UNAVAILABLE" | "UNDER_MAINTENANCE" | "ENGINE_OVERLOADED";
1202
1214
  /** @description The top-level error envelope. */
1203
1215
  ErrorResponse: {
1204
1216
  error: components["schemas"]["ErrorBody"];
@@ -1309,14 +1321,15 @@ interface components {
1309
1321
  /** @description Trade id. */
1310
1322
  trade_id: string;
1311
1323
  };
1324
+ /**
1325
+ * @description Unique identifier of a futures collateral transfer.
1326
+ * @example 507f1f77bcf86cd799439011
1327
+ */
1328
+ FuturesTransferId: string;
1312
1329
  /** @description Adds liquidity to a pool. */
1313
1330
  JoinPoolRequest: {
1314
1331
  base_amount: components["schemas"]["Amount"];
1315
- /**
1316
- * @description How far, in percent, the offered ratio may sit from the pool's own before the request is refused rather than repriced. Defaults to 1%.
1317
- * @example 1
1318
- */
1319
- max_ratio_deviation_percent?: string | null;
1332
+ max_ratio_deviation_percent?: components["schemas"]["Amount"] | null;
1320
1333
  quote_amount: components["schemas"]["Amount"];
1321
1334
  };
1322
1335
  /** @description What a join produced. */
@@ -1330,7 +1343,7 @@ interface components {
1330
1343
  * @description What a ledger entry records.
1331
1344
  * @enum {string}
1332
1345
  */
1333
- LedgerEntryKind: "deposit" | "deposit_reversal" | "withdrawal_debit" | "withdrawal_fee" | "withdrawal_fee_reserve" | "withdrawal_release" | "withdrawal_fee_release" | "order_reserve" | "withdrawal_reserve" | "order_release" | "trade_debit" | "trade_credit" | "trade_fee" | "transfer_out" | "transfer_in" | "adjustment_credit" | "adjustment_debit" | "rebate" | "pool_join" | "pool_exit" | "futures_transfer_reserve" | "futures_transfer_release" | "futures_collateral_sent" | "futures_collateral_returned" | "trade_fee_revenue" | "withdrawal_fee_revenue" | "futures_transfer_fee_revenue" | "futures_hyperliquid_cost" | "futures_transfer_discrepancy" | "exchange_capital";
1346
+ LedgerEntryKind: "deposit" | "deposit_reversal" | "withdrawal_debit" | "withdrawal_fee" | "withdrawal_fee_reserve" | "withdrawal_release" | "withdrawal_fee_release" | "order_reserve" | "withdrawal_reserve" | "order_release" | "trade_debit" | "trade_credit" | "trade_fee" | "transfer_out" | "transfer_in" | "transfer_in_held" | "transfer_release" | "transfer_reversal" | "adjustment_credit" | "adjustment_debit" | "rebate" | "pool_join" | "pool_exit" | "futures_transfer_reserve" | "futures_transfer_release" | "futures_collateral_sent" | "futures_collateral_returned" | "trade_fee_revenue" | "withdrawal_fee_revenue" | "withdrawal_refund" | "withdrawal_fee_revenue_reversal" | "futures_transfer_fee_revenue" | "futures_hyperliquid_cost" | "futures_transfer_discrepancy" | "exchange_capital";
1334
1347
  /** @description One entry from the account's ledger. */
1335
1348
  LedgerEntryResponse: {
1336
1349
  /** @description Asset symbol. */
@@ -1347,14 +1360,55 @@ interface components {
1347
1360
  kind: components["schemas"]["LedgerEntryKind"];
1348
1361
  locked_delta: components["schemas"]["Amount"];
1349
1362
  pending_delta: components["schemas"]["Amount"];
1350
- /** @description What caused the entry. */
1351
- reference: unknown;
1363
+ reference: components["schemas"]["LedgerReference"];
1352
1364
  /**
1353
1365
  * Format: int64
1354
1366
  * @description Position in this account's history for this asset.
1355
1367
  */
1356
1368
  sequence: number;
1357
1369
  };
1370
+ /** @description What caused a ledger entry: one kind of cause per variant, told apart by `type`. */
1371
+ LedgerReference: {
1372
+ deposit_id: components["schemas"]["DepositId"];
1373
+ /** @enum {string} */
1374
+ type: "deposit";
1375
+ } | {
1376
+ /** @enum {string} */
1377
+ type: "withdrawal";
1378
+ withdrawal_id: components["schemas"]["WithdrawalId"];
1379
+ } | {
1380
+ order_id: components["schemas"]["OrderId"];
1381
+ /** @enum {string} */
1382
+ type: "order";
1383
+ } | {
1384
+ order_id: components["schemas"]["OrderId"];
1385
+ trade_id: components["schemas"]["TradeId"];
1386
+ /** @enum {string} */
1387
+ type: "trade";
1388
+ } | {
1389
+ counterparty_user_id: components["schemas"]["UserId"];
1390
+ /** @description Shared reference linking both halves. */
1391
+ transfer_ref: string;
1392
+ /** @enum {string} */
1393
+ type: "transfer";
1394
+ } | {
1395
+ operator_user_id: components["schemas"]["UserId"];
1396
+ /** @enum {string} */
1397
+ type: "adjustment";
1398
+ } | {
1399
+ pool_id: components["schemas"]["PoolId"];
1400
+ /** @enum {string} */
1401
+ type: "pool";
1402
+ } | {
1403
+ futures_transfer_id: components["schemas"]["FuturesTransferId"];
1404
+ /** @enum {string} */
1405
+ type: "futures_transfer";
1406
+ } | {
1407
+ /** @description Short machine-readable cause. */
1408
+ cause: string;
1409
+ /** @enum {string} */
1410
+ type: "system";
1411
+ };
1358
1412
  /**
1359
1413
  * @description Whether a fill added liquidity (maker) or removed it (taker).
1360
1414
  * @enum {string}
@@ -1514,6 +1568,11 @@ interface components {
1514
1568
  */
1515
1569
  timestamp: string;
1516
1570
  };
1571
+ /**
1572
+ * @description Unique identifier of an order.
1573
+ * @example 507f1f77bcf86cd799439011
1574
+ */
1575
+ OrderId: string;
1517
1576
  /** @description An order. */
1518
1577
  OrderResponse: {
1519
1578
  average_price?: components["schemas"]["Amount"] | null;
@@ -1616,6 +1675,11 @@ interface components {
1616
1675
  fills: components["schemas"]["FillResponse"][];
1617
1676
  order: components["schemas"]["OrderResponse"];
1618
1677
  };
1678
+ /**
1679
+ * @description Unique identifier of a liquidity pool.
1680
+ * @example 507f1f77bcf86cd799439011
1681
+ */
1682
+ PoolId: string;
1619
1683
  /**
1620
1684
  * @description A pool as a client sees it.
1621
1685
  *
@@ -1717,6 +1781,11 @@ interface components {
1717
1781
  * @enum {string}
1718
1782
  */
1719
1783
  TimeInForce: "gtc" | "ioc" | "fok" | "post_only";
1784
+ /**
1785
+ * @description Unique identifier of a trade.
1786
+ * @example 507f1f77bcf86cd799439011
1787
+ */
1788
+ TradeId: string;
1720
1789
  /**
1721
1790
  * @description Which way the price must move for a stop to fire.
1722
1791
  *
@@ -1724,6 +1793,11 @@ interface components {
1724
1793
  * @enum {string}
1725
1794
  */
1726
1795
  TriggerDirection: "above" | "below";
1796
+ /**
1797
+ * @description Unique identifier of a user account.
1798
+ * @example 507f1f77bcf86cd799439011
1799
+ */
1800
+ UserId: string;
1727
1801
  /** @description A saved withdrawal address. */
1728
1802
  WithdrawalAddressResponse: {
1729
1803
  /** @description The address. */
@@ -1762,6 +1836,11 @@ interface components {
1762
1836
  reason?: string | null;
1763
1837
  status: components["schemas"]["WithdrawalStatus"];
1764
1838
  };
1839
+ /**
1840
+ * @description Unique identifier of a withdrawal.
1841
+ * @example 507f1f77bcf86cd799439011
1842
+ */
1843
+ WithdrawalId: string;
1765
1844
  /** @description A withdrawal. */
1766
1845
  WithdrawalResponse: {
1767
1846
  /** @description Destination. */
@@ -1818,7 +1897,7 @@ interface components {
1818
1897
  * against the chain.
1819
1898
  * @enum {string}
1820
1899
  */
1821
- WithdrawalStatus: "requested" | "pending_approval" | "approved" | "processing" | "broadcast" | "completed" | "rejected" | "cancelled" | "failed" | "broadcast_unknown";
1900
+ WithdrawalStatus: "requested" | "pending_approval" | "approved" | "processing" | "broadcast" | "completed" | "rejected" | "cancelled" | "failed" | "broadcast_unknown" | "reverted";
1822
1901
  };
1823
1902
  responses: never;
1824
1903
  parameters: never;
@@ -3256,7 +3335,31 @@ type FeeSchedule = S["FeeScheduleResponse"];
3256
3335
  type Fill = S["FillResponse"];
3257
3336
  type JoinPoolRequest = S["JoinPoolRequest"];
3258
3337
  type JoinPoolResult = S["JoinPoolResponse"];
3259
- type LedgerEntry = S["LedgerEntryResponse"];
3338
+ /** A ledger entry. `reference` also accepts cause types this SDK version does not know yet. */
3339
+ type LedgerEntry = Omit<S["LedgerEntryResponse"], "reference"> & {
3340
+ reference: LedgerReference;
3341
+ };
3342
+ /** What caused a ledger entry, as documented: one variant per `type`. */
3343
+ type KnownLedgerReference = S["LedgerReference"];
3344
+ /** The documented `LedgerReference` types. */
3345
+ type LedgerReferenceType = KnownLedgerReference["type"];
3346
+ /**
3347
+ * A cause type this SDK version does not know yet (the server may add new ones). The object is
3348
+ * kept as sent. Use `isLedgerReference()` to narrow to a documented variant.
3349
+ */
3350
+ interface UnknownLedgerReference {
3351
+ type: string;
3352
+ [field: string]: unknown;
3353
+ }
3354
+ /** `LedgerEntry.reference`: a documented variant or an unknown one; never throws on new types. */
3355
+ type LedgerReference = KnownLedgerReference | UnknownLedgerReference;
3356
+ type DepositId = S["DepositId"];
3357
+ type FuturesTransferId = S["FuturesTransferId"];
3358
+ type OrderId = S["OrderId"];
3359
+ type PoolId = S["PoolId"];
3360
+ type TradeId = S["TradeId"];
3361
+ type UserId = S["UserId"];
3362
+ type WithdrawalId = S["WithdrawalId"];
3260
3363
  type LedgerEntryKind = S["LedgerEntryKind"];
3261
3364
  type LiquidityRole = S["LiquidityRole"];
3262
3365
  type MaintenanceState = S["MaintenanceState"];
@@ -3449,6 +3552,8 @@ declare class TradingResource extends Resource {
3449
3552
  cancelOrder(orderId: string, opts?: RequestOptions): Promise<Order>;
3450
3553
  /**
3451
3554
  * Cancels every open order in one market: `cancelAll({ symbol: "BTC/USDT" })`.
3555
+ * This includes stop orders that have not triggered yet (status `pending_trigger`): they are
3556
+ * cancelled and their reservations released, so nothing fires into the market afterwards.
3452
3557
  * To cancel across ALL markets, pass `symbol: null` explicitly: `cancelAll({ symbol: null })`.
3453
3558
  * Omitting `symbol` is an error, so an account-wide cancel never happens by accident
3454
3559
  * (the server itself treats `{}` as every market). An unknown symbol throws `NotFoundError`.
@@ -4050,12 +4155,23 @@ declare function isAmount(value: unknown): value is Amount;
4050
4155
  */
4051
4156
  declare function assertAmountFields(body: Record<string, unknown>, fields: readonly string[], context: string): void;
4052
4157
 
4158
+ /**
4159
+ * Narrows a ledger entry's `reference`:
4160
+ * - `isLedgerReference(ref)`: true for any documented variant;
4161
+ * - `isLedgerReference(ref, "trade")`: true only for that variant, typed accordingly.
4162
+ * Unknown (newer) types return false and keep their raw fields.
4163
+ */
4164
+ declare function isLedgerReference(ref: LedgerReference): ref is KnownLedgerReference;
4165
+ declare function isLedgerReference<T extends LedgerReferenceType>(ref: LedgerReference, type: T): ref is Extract<KnownLedgerReference, {
4166
+ type: T;
4167
+ }>;
4168
+
4053
4169
  /** SDK version, kept in sync with package.json (a test enforces this). */
4054
- declare const VERSION = "0.1.0-dev.5";
4170
+ declare const VERSION = "0.1.0-dev.6";
4055
4171
  /** Default User-Agent product token. */
4056
- declare const USER_AGENT = "cexy-typescript/0.1.0-dev.5";
4172
+ declare const USER_AGENT = "cexy-typescript/0.1.0-dev.6";
4057
4173
 
4058
4174
  /** True for loopback hosts, the only ones where plain-text transport may be allowed. */
4059
4175
  declare function isLocalHost(hostname: string): boolean;
4060
4176
 
4061
- export { AccountResource, type Amount, type ApiKey, ApiKeyAuthenticator, type ApiScope, type Asset, type AssetNetwork, AssetsResource, type AuthRequest, type AuthResult, type AuthenticatedFrame, AuthenticationError, type Authenticator, type Balance, type BalanceUpdatedEvent, type BookLevel, CLIENT_ERROR_CODES, CancelAllInterruptedError, type CancelAllParams, type CancelAllRequest, type CancelAllResult, type CancelAllStopReason, type CancelAllUntilDoneResult, type CancelFailure, type Candle, type CandleInterval, CexyApiError, type CexyApiErrorInit, CexyClient, type CexyClientOptions, CexyConfigError, CexyConnectionError, CexyError, CexyTimeoutError, CexyWebSocket, CexyWebSocketError, type CexyWebSocketEvents, type CexyWebSocketOptions, type CloseInfo, ConflictError, type CursorParams, DEFAULT_BASE_URL, DEFAULT_RPM_ANONYMOUS, DEFAULT_RPM_WITH_KEY, DEFAULT_WS_URL, type Deposit, type DepositAddress, type DepositEvent, type DepositStatus, type ErrorBody, type ErrorCode, type ErrorFrame, type EventMap, type ExchangeConfig, type ExitPoolRequest, type ExitPoolResult, ExportsResource, type FeeSchedule, FeesResource, type FetchLike, type Fill, ForbiddenError, InvalidAmountError, type IterateOptions, type JoinPoolRequest, type JoinPoolResult, JurisdictionBlockedError, KNOWN_EVENT_TYPES, type KnownErrorCode, type LedgerEntry, type LedgerEntryKind, type LiquidityRole, type Listener, LiveOrderBook, type LiveOrderBookEvents, type LiveOrderBookOptions, MAX_SERVER_WAIT_MS, type MaintenanceState, type Market, type MarketStatus, type MarketStatusEvent, MarketsResource, type Network, NetworksResource, NotFoundError, type Notification, type NotificationKind, OPERATIONS, type OperationAuth, type OperationId, type OperationInfo, type OperationScope, type Order, type OrderBook, type OrderBookUpdateData, type OrderBookUpdateEvent, type OrderEvent, type OrderSide, OrderStateUnknownError, type OrderStatus, type OrderType, PRIVATE_CHANNELS, type Page, type PlaceOrderRequest, type PlaceOrderResponse, type PlaceOrderResult, type PongFrame, type Pool, type PoolStatus, PoolsResource, type PublicTrade, type QueryOf, RateLimitError, RateLimiter, type RateLimiterOptions, type RateLimiterState, type ReconnectOptions, type RequestOptions, type ResyncReason, type RetryInfo, SUPPORTED_PROTOCOL_VERSION, ServerError, type ServerTime, type SessionRevokedData, type SessionRevokedEvent, type SnapshotSource, type SortDirection, type SubAccount, type SubscribeResult, type SubscribedFrame, type TickerUpdateEvent, type TimeInForce, type TradeNewEvent, TradingResource, type TriggerDirection, TypedEmitter, USER_AGENT, UnprocessableError, type UnsubscribedFrame, VERSION, ValidationError, WS_BOOK_DEPTH, WalletResource, type WebSocketConstructor, type WebSocketLike, type WelcomeFrame, type Withdrawal, type WithdrawalAddress, type WithdrawalStatus, type WithdrawalUpdatedEvent, type WsEvent, type WsLogger, assertAmountFields, type components, errorFromResponse, isAmount, isKnownErrorCode, isLocalHost, isRetryable, type operations, paginate, type paths };
4177
+ export { AccountResource, type Amount, type ApiKey, ApiKeyAuthenticator, type ApiScope, type Asset, type AssetNetwork, AssetsResource, type AuthRequest, type AuthResult, type AuthenticatedFrame, AuthenticationError, type Authenticator, type Balance, type BalanceUpdatedEvent, type BookLevel, CLIENT_ERROR_CODES, CancelAllInterruptedError, type CancelAllParams, type CancelAllRequest, type CancelAllResult, type CancelAllStopReason, type CancelAllUntilDoneResult, type CancelFailure, type Candle, type CandleInterval, CexyApiError, type CexyApiErrorInit, CexyClient, type CexyClientOptions, CexyConfigError, CexyConnectionError, CexyError, CexyTimeoutError, CexyWebSocket, CexyWebSocketError, type CexyWebSocketEvents, type CexyWebSocketOptions, type CloseInfo, ConflictError, type CursorParams, DEFAULT_BASE_URL, DEFAULT_RPM_ANONYMOUS, DEFAULT_RPM_WITH_KEY, DEFAULT_WS_URL, type Deposit, type DepositAddress, type DepositEvent, type DepositId, type DepositStatus, type ErrorBody, type ErrorCode, type ErrorFrame, type EventMap, type ExchangeConfig, type ExitPoolRequest, type ExitPoolResult, ExportsResource, type FeeSchedule, FeesResource, type FetchLike, type Fill, ForbiddenError, type FuturesTransferId, InvalidAmountError, type IterateOptions, type JoinPoolRequest, type JoinPoolResult, JurisdictionBlockedError, KNOWN_EVENT_TYPES, type KnownErrorCode, type KnownLedgerReference, type LedgerEntry, type LedgerEntryKind, type LedgerReference, type LedgerReferenceType, type LiquidityRole, type Listener, LiveOrderBook, type LiveOrderBookEvents, type LiveOrderBookOptions, MAX_SERVER_WAIT_MS, type MaintenanceState, type Market, type MarketStatus, type MarketStatusEvent, MarketsResource, type Network, NetworksResource, NotFoundError, type Notification, type NotificationKind, OPERATIONS, type OperationAuth, type OperationId, type OperationInfo, type OperationScope, type Order, type OrderBook, type OrderBookUpdateData, type OrderBookUpdateEvent, type OrderEvent, type OrderId, type OrderSide, OrderStateUnknownError, type OrderStatus, type OrderType, PRIVATE_CHANNELS, type Page, type PlaceOrderRequest, type PlaceOrderResponse, type PlaceOrderResult, type PongFrame, type Pool, type PoolId, type PoolStatus, PoolsResource, type PublicTrade, type QueryOf, RateLimitError, RateLimiter, type RateLimiterOptions, type RateLimiterState, type ReconnectOptions, type RequestOptions, type ResyncReason, type RetryInfo, SUPPORTED_PROTOCOL_VERSION, ServerError, type ServerTime, type SessionRevokedData, type SessionRevokedEvent, type SnapshotSource, type SortDirection, type SubAccount, type SubscribeResult, type SubscribedFrame, type TickerUpdateEvent, type TimeInForce, type TradeId, type TradeNewEvent, TradingResource, type TriggerDirection, TypedEmitter, USER_AGENT, type UnknownLedgerReference, UnprocessableError, type UnsubscribedFrame, type UserId, VERSION, ValidationError, WS_BOOK_DEPTH, WalletResource, type WebSocketConstructor, type WebSocketLike, type WelcomeFrame, type Withdrawal, type WithdrawalAddress, type WithdrawalId, type WithdrawalStatus, type WithdrawalUpdatedEvent, type WsEvent, type WsLogger, assertAmountFields, type components, errorFromResponse, isAmount, isKnownErrorCode, isLedgerReference, isLocalHost, isRetryable, type operations, paginate, type paths };
package/dist/index.d.ts CHANGED
@@ -54,6 +54,11 @@ declare class RateLimiter {
54
54
  get state(): RateLimiterState;
55
55
  /** Waits until a request may be sent, then takes a token. */
56
56
  acquire(signal?: AbortSignal): Promise<void>;
57
+ /**
58
+ * How long `acquire()` would wait right now, in ms (0 when a request may go at once). Lets a
59
+ * caller with a time budget, such as the cancelAll untilDone loop, count the limiter's wait.
60
+ */
61
+ pendingWaitMs(): number;
57
62
  /** Adapts to the server's rate-limit headers. Never raises the configured limit. */
58
63
  update(headers: Headers): void;
59
64
  /**
@@ -731,8 +736,10 @@ interface paths {
731
736
  get?: never;
732
737
  put?: never;
733
738
  /**
734
- * Cancels every open order, optionally within one market.
735
- * @description Best-effort: a failure on one order does not stop the rest, and every outcome is reported. A panic-button endpoint that stops at the first problem is worse than useless.
739
+ * Cancels every open order, and every stop order that has not triggered, optionally within
740
+ * @description one market.
741
+ *
742
+ * Best-effort: a failure on one order does not stop the rest, and every outcome is reported. A panic-button endpoint that stops at the first problem is worse than useless. A stop waiting for its trigger (`pending_trigger`) is cancelled too and its reservation released, so nothing fires into the market after the call.
736
743
  *
737
744
  * An order still being placed when the call starts (status `pending`, for as long as its own placement request runs) is waited for, up to 500 ms per call in total: cancelled if it opens, reported in `already_closed` if it fills or is refused, and in `failed` with code `INVALID_STATE` if it is still being placed at the deadline. Orders placed after the call starts are not part of it. At most 500 orders per call; `has_more` says there are others.
738
745
  *
@@ -1117,6 +1124,11 @@ interface components {
1117
1124
  /** @description Network code. */
1118
1125
  network: string;
1119
1126
  };
1127
+ /**
1128
+ * @description Unique identifier of a deposit.
1129
+ * @example 507f1f77bcf86cd799439011
1130
+ */
1131
+ DepositId: string;
1120
1132
  /** @description A deposit. */
1121
1133
  DepositResponse: {
1122
1134
  /** @description Address that received it. */
@@ -1198,7 +1210,7 @@ interface components {
1198
1210
  * Serialized as `SCREAMING_SNAKE_CASE`. Adding a variant is backwards-compatible; renaming or removing one is a breaking API change.
1199
1211
  * @enum {string}
1200
1212
  */
1201
- ErrorCode: "VALIDATION_FAILED" | "MALFORMED_REQUEST" | "INVALID_CURSOR" | "PRECISION_EXCEEDED" | "BELOW_MINIMUM" | "ABOVE_MAXIMUM" | "INVALID_ADDRESS" | "MEMO_REQUIRED" | "UNAUTHENTICATED" | "INVALID_CREDENTIALS" | "TOKEN_EXPIRED" | "SESSION_REVOKED" | "TWO_FACTOR_REQUIRED" | "TWO_FACTOR_INVALID" | "FRESH_TWO_FACTOR_REQUIRED" | "FORBIDDEN" | "API_KEY_NOT_ALLOWED" | "FUTURES_RESTRICTED" | "ACCOUNT_FROZEN" | "ACCOUNT_ON_HOLD" | "EMAIL_NOT_VERIFIED" | "REGION_BLOCKED" | "JURISDICTION_BLOCKED" | "NOT_FOUND" | "METHOD_NOT_ALLOWED" | "ALREADY_EXISTS" | "INVALID_STATE" | "IDEMPOTENCY_KEY_CONFLICT" | "WINDOW_OPEN" | "EVIDENCE_CONTRADICTS" | "AMOUNT_MISMATCH" | "CONCURRENT_MODIFICATION" | "INSUFFICIENT_FUNDS" | "INSUFFICIENT_FEE_FUNDS" | "MARKET_UNAVAILABLE" | "DEPOSIT_DISABLED" | "WITHDRAWAL_DISABLED" | "SELF_TRADE_BLOCKED" | "LIMIT_EXCEEDED" | "RATE_LIMITED" | "INTERNAL" | "SERVICE_UNAVAILABLE" | "UNDER_MAINTENANCE" | "ENGINE_OVERLOADED";
1213
+ ErrorCode: "VALIDATION_FAILED" | "MALFORMED_REQUEST" | "INVALID_CURSOR" | "PRECISION_EXCEEDED" | "BELOW_MINIMUM" | "ABOVE_MAXIMUM" | "INVALID_ADDRESS" | "MEMO_REQUIRED" | "UNAUTHENTICATED" | "INVALID_CREDENTIALS" | "TOKEN_EXPIRED" | "SESSION_REVOKED" | "TWO_FACTOR_REQUIRED" | "TWO_FACTOR_INVALID" | "FRESH_TWO_FACTOR_REQUIRED" | "FORBIDDEN" | "API_KEY_NOT_ALLOWED" | "FUTURES_RESTRICTED" | "ACCOUNT_FROZEN" | "ACCOUNT_ON_HOLD" | "EMAIL_NOT_VERIFIED" | "REGION_BLOCKED" | "JURISDICTION_BLOCKED" | "NOT_FOUND" | "METHOD_NOT_ALLOWED" | "ALREADY_EXISTS" | "INVALID_STATE" | "IDEMPOTENCY_KEY_CONFLICT" | "WINDOW_OPEN" | "EVIDENCE_CONTRADICTS" | "AMOUNT_MISMATCH" | "CONCURRENT_MODIFICATION" | "INSUFFICIENT_FUNDS" | "INSUFFICIENT_FEE_FUNDS" | "MARKET_UNAVAILABLE" | "DEPOSIT_DISABLED" | "WITHDRAWAL_DISABLED" | "SELF_TRADE_BLOCKED" | "LIMIT_EXCEEDED" | "PRICE_UNAVAILABLE" | "RATE_LIMITED" | "INTERNAL" | "SERVICE_UNAVAILABLE" | "UNDER_MAINTENANCE" | "ENGINE_OVERLOADED";
1202
1214
  /** @description The top-level error envelope. */
1203
1215
  ErrorResponse: {
1204
1216
  error: components["schemas"]["ErrorBody"];
@@ -1309,14 +1321,15 @@ interface components {
1309
1321
  /** @description Trade id. */
1310
1322
  trade_id: string;
1311
1323
  };
1324
+ /**
1325
+ * @description Unique identifier of a futures collateral transfer.
1326
+ * @example 507f1f77bcf86cd799439011
1327
+ */
1328
+ FuturesTransferId: string;
1312
1329
  /** @description Adds liquidity to a pool. */
1313
1330
  JoinPoolRequest: {
1314
1331
  base_amount: components["schemas"]["Amount"];
1315
- /**
1316
- * @description How far, in percent, the offered ratio may sit from the pool's own before the request is refused rather than repriced. Defaults to 1%.
1317
- * @example 1
1318
- */
1319
- max_ratio_deviation_percent?: string | null;
1332
+ max_ratio_deviation_percent?: components["schemas"]["Amount"] | null;
1320
1333
  quote_amount: components["schemas"]["Amount"];
1321
1334
  };
1322
1335
  /** @description What a join produced. */
@@ -1330,7 +1343,7 @@ interface components {
1330
1343
  * @description What a ledger entry records.
1331
1344
  * @enum {string}
1332
1345
  */
1333
- LedgerEntryKind: "deposit" | "deposit_reversal" | "withdrawal_debit" | "withdrawal_fee" | "withdrawal_fee_reserve" | "withdrawal_release" | "withdrawal_fee_release" | "order_reserve" | "withdrawal_reserve" | "order_release" | "trade_debit" | "trade_credit" | "trade_fee" | "transfer_out" | "transfer_in" | "adjustment_credit" | "adjustment_debit" | "rebate" | "pool_join" | "pool_exit" | "futures_transfer_reserve" | "futures_transfer_release" | "futures_collateral_sent" | "futures_collateral_returned" | "trade_fee_revenue" | "withdrawal_fee_revenue" | "futures_transfer_fee_revenue" | "futures_hyperliquid_cost" | "futures_transfer_discrepancy" | "exchange_capital";
1346
+ LedgerEntryKind: "deposit" | "deposit_reversal" | "withdrawal_debit" | "withdrawal_fee" | "withdrawal_fee_reserve" | "withdrawal_release" | "withdrawal_fee_release" | "order_reserve" | "withdrawal_reserve" | "order_release" | "trade_debit" | "trade_credit" | "trade_fee" | "transfer_out" | "transfer_in" | "transfer_in_held" | "transfer_release" | "transfer_reversal" | "adjustment_credit" | "adjustment_debit" | "rebate" | "pool_join" | "pool_exit" | "futures_transfer_reserve" | "futures_transfer_release" | "futures_collateral_sent" | "futures_collateral_returned" | "trade_fee_revenue" | "withdrawal_fee_revenue" | "withdrawal_refund" | "withdrawal_fee_revenue_reversal" | "futures_transfer_fee_revenue" | "futures_hyperliquid_cost" | "futures_transfer_discrepancy" | "exchange_capital";
1334
1347
  /** @description One entry from the account's ledger. */
1335
1348
  LedgerEntryResponse: {
1336
1349
  /** @description Asset symbol. */
@@ -1347,14 +1360,55 @@ interface components {
1347
1360
  kind: components["schemas"]["LedgerEntryKind"];
1348
1361
  locked_delta: components["schemas"]["Amount"];
1349
1362
  pending_delta: components["schemas"]["Amount"];
1350
- /** @description What caused the entry. */
1351
- reference: unknown;
1363
+ reference: components["schemas"]["LedgerReference"];
1352
1364
  /**
1353
1365
  * Format: int64
1354
1366
  * @description Position in this account's history for this asset.
1355
1367
  */
1356
1368
  sequence: number;
1357
1369
  };
1370
+ /** @description What caused a ledger entry: one kind of cause per variant, told apart by `type`. */
1371
+ LedgerReference: {
1372
+ deposit_id: components["schemas"]["DepositId"];
1373
+ /** @enum {string} */
1374
+ type: "deposit";
1375
+ } | {
1376
+ /** @enum {string} */
1377
+ type: "withdrawal";
1378
+ withdrawal_id: components["schemas"]["WithdrawalId"];
1379
+ } | {
1380
+ order_id: components["schemas"]["OrderId"];
1381
+ /** @enum {string} */
1382
+ type: "order";
1383
+ } | {
1384
+ order_id: components["schemas"]["OrderId"];
1385
+ trade_id: components["schemas"]["TradeId"];
1386
+ /** @enum {string} */
1387
+ type: "trade";
1388
+ } | {
1389
+ counterparty_user_id: components["schemas"]["UserId"];
1390
+ /** @description Shared reference linking both halves. */
1391
+ transfer_ref: string;
1392
+ /** @enum {string} */
1393
+ type: "transfer";
1394
+ } | {
1395
+ operator_user_id: components["schemas"]["UserId"];
1396
+ /** @enum {string} */
1397
+ type: "adjustment";
1398
+ } | {
1399
+ pool_id: components["schemas"]["PoolId"];
1400
+ /** @enum {string} */
1401
+ type: "pool";
1402
+ } | {
1403
+ futures_transfer_id: components["schemas"]["FuturesTransferId"];
1404
+ /** @enum {string} */
1405
+ type: "futures_transfer";
1406
+ } | {
1407
+ /** @description Short machine-readable cause. */
1408
+ cause: string;
1409
+ /** @enum {string} */
1410
+ type: "system";
1411
+ };
1358
1412
  /**
1359
1413
  * @description Whether a fill added liquidity (maker) or removed it (taker).
1360
1414
  * @enum {string}
@@ -1514,6 +1568,11 @@ interface components {
1514
1568
  */
1515
1569
  timestamp: string;
1516
1570
  };
1571
+ /**
1572
+ * @description Unique identifier of an order.
1573
+ * @example 507f1f77bcf86cd799439011
1574
+ */
1575
+ OrderId: string;
1517
1576
  /** @description An order. */
1518
1577
  OrderResponse: {
1519
1578
  average_price?: components["schemas"]["Amount"] | null;
@@ -1616,6 +1675,11 @@ interface components {
1616
1675
  fills: components["schemas"]["FillResponse"][];
1617
1676
  order: components["schemas"]["OrderResponse"];
1618
1677
  };
1678
+ /**
1679
+ * @description Unique identifier of a liquidity pool.
1680
+ * @example 507f1f77bcf86cd799439011
1681
+ */
1682
+ PoolId: string;
1619
1683
  /**
1620
1684
  * @description A pool as a client sees it.
1621
1685
  *
@@ -1717,6 +1781,11 @@ interface components {
1717
1781
  * @enum {string}
1718
1782
  */
1719
1783
  TimeInForce: "gtc" | "ioc" | "fok" | "post_only";
1784
+ /**
1785
+ * @description Unique identifier of a trade.
1786
+ * @example 507f1f77bcf86cd799439011
1787
+ */
1788
+ TradeId: string;
1720
1789
  /**
1721
1790
  * @description Which way the price must move for a stop to fire.
1722
1791
  *
@@ -1724,6 +1793,11 @@ interface components {
1724
1793
  * @enum {string}
1725
1794
  */
1726
1795
  TriggerDirection: "above" | "below";
1796
+ /**
1797
+ * @description Unique identifier of a user account.
1798
+ * @example 507f1f77bcf86cd799439011
1799
+ */
1800
+ UserId: string;
1727
1801
  /** @description A saved withdrawal address. */
1728
1802
  WithdrawalAddressResponse: {
1729
1803
  /** @description The address. */
@@ -1762,6 +1836,11 @@ interface components {
1762
1836
  reason?: string | null;
1763
1837
  status: components["schemas"]["WithdrawalStatus"];
1764
1838
  };
1839
+ /**
1840
+ * @description Unique identifier of a withdrawal.
1841
+ * @example 507f1f77bcf86cd799439011
1842
+ */
1843
+ WithdrawalId: string;
1765
1844
  /** @description A withdrawal. */
1766
1845
  WithdrawalResponse: {
1767
1846
  /** @description Destination. */
@@ -1818,7 +1897,7 @@ interface components {
1818
1897
  * against the chain.
1819
1898
  * @enum {string}
1820
1899
  */
1821
- WithdrawalStatus: "requested" | "pending_approval" | "approved" | "processing" | "broadcast" | "completed" | "rejected" | "cancelled" | "failed" | "broadcast_unknown";
1900
+ WithdrawalStatus: "requested" | "pending_approval" | "approved" | "processing" | "broadcast" | "completed" | "rejected" | "cancelled" | "failed" | "broadcast_unknown" | "reverted";
1822
1901
  };
1823
1902
  responses: never;
1824
1903
  parameters: never;
@@ -3256,7 +3335,31 @@ type FeeSchedule = S["FeeScheduleResponse"];
3256
3335
  type Fill = S["FillResponse"];
3257
3336
  type JoinPoolRequest = S["JoinPoolRequest"];
3258
3337
  type JoinPoolResult = S["JoinPoolResponse"];
3259
- type LedgerEntry = S["LedgerEntryResponse"];
3338
+ /** A ledger entry. `reference` also accepts cause types this SDK version does not know yet. */
3339
+ type LedgerEntry = Omit<S["LedgerEntryResponse"], "reference"> & {
3340
+ reference: LedgerReference;
3341
+ };
3342
+ /** What caused a ledger entry, as documented: one variant per `type`. */
3343
+ type KnownLedgerReference = S["LedgerReference"];
3344
+ /** The documented `LedgerReference` types. */
3345
+ type LedgerReferenceType = KnownLedgerReference["type"];
3346
+ /**
3347
+ * A cause type this SDK version does not know yet (the server may add new ones). The object is
3348
+ * kept as sent. Use `isLedgerReference()` to narrow to a documented variant.
3349
+ */
3350
+ interface UnknownLedgerReference {
3351
+ type: string;
3352
+ [field: string]: unknown;
3353
+ }
3354
+ /** `LedgerEntry.reference`: a documented variant or an unknown one; never throws on new types. */
3355
+ type LedgerReference = KnownLedgerReference | UnknownLedgerReference;
3356
+ type DepositId = S["DepositId"];
3357
+ type FuturesTransferId = S["FuturesTransferId"];
3358
+ type OrderId = S["OrderId"];
3359
+ type PoolId = S["PoolId"];
3360
+ type TradeId = S["TradeId"];
3361
+ type UserId = S["UserId"];
3362
+ type WithdrawalId = S["WithdrawalId"];
3260
3363
  type LedgerEntryKind = S["LedgerEntryKind"];
3261
3364
  type LiquidityRole = S["LiquidityRole"];
3262
3365
  type MaintenanceState = S["MaintenanceState"];
@@ -3449,6 +3552,8 @@ declare class TradingResource extends Resource {
3449
3552
  cancelOrder(orderId: string, opts?: RequestOptions): Promise<Order>;
3450
3553
  /**
3451
3554
  * Cancels every open order in one market: `cancelAll({ symbol: "BTC/USDT" })`.
3555
+ * This includes stop orders that have not triggered yet (status `pending_trigger`): they are
3556
+ * cancelled and their reservations released, so nothing fires into the market afterwards.
3452
3557
  * To cancel across ALL markets, pass `symbol: null` explicitly: `cancelAll({ symbol: null })`.
3453
3558
  * Omitting `symbol` is an error, so an account-wide cancel never happens by accident
3454
3559
  * (the server itself treats `{}` as every market). An unknown symbol throws `NotFoundError`.
@@ -4050,12 +4155,23 @@ declare function isAmount(value: unknown): value is Amount;
4050
4155
  */
4051
4156
  declare function assertAmountFields(body: Record<string, unknown>, fields: readonly string[], context: string): void;
4052
4157
 
4158
+ /**
4159
+ * Narrows a ledger entry's `reference`:
4160
+ * - `isLedgerReference(ref)`: true for any documented variant;
4161
+ * - `isLedgerReference(ref, "trade")`: true only for that variant, typed accordingly.
4162
+ * Unknown (newer) types return false and keep their raw fields.
4163
+ */
4164
+ declare function isLedgerReference(ref: LedgerReference): ref is KnownLedgerReference;
4165
+ declare function isLedgerReference<T extends LedgerReferenceType>(ref: LedgerReference, type: T): ref is Extract<KnownLedgerReference, {
4166
+ type: T;
4167
+ }>;
4168
+
4053
4169
  /** SDK version, kept in sync with package.json (a test enforces this). */
4054
- declare const VERSION = "0.1.0-dev.5";
4170
+ declare const VERSION = "0.1.0-dev.6";
4055
4171
  /** Default User-Agent product token. */
4056
- declare const USER_AGENT = "cexy-typescript/0.1.0-dev.5";
4172
+ declare const USER_AGENT = "cexy-typescript/0.1.0-dev.6";
4057
4173
 
4058
4174
  /** True for loopback hosts, the only ones where plain-text transport may be allowed. */
4059
4175
  declare function isLocalHost(hostname: string): boolean;
4060
4176
 
4061
- export { AccountResource, type Amount, type ApiKey, ApiKeyAuthenticator, type ApiScope, type Asset, type AssetNetwork, AssetsResource, type AuthRequest, type AuthResult, type AuthenticatedFrame, AuthenticationError, type Authenticator, type Balance, type BalanceUpdatedEvent, type BookLevel, CLIENT_ERROR_CODES, CancelAllInterruptedError, type CancelAllParams, type CancelAllRequest, type CancelAllResult, type CancelAllStopReason, type CancelAllUntilDoneResult, type CancelFailure, type Candle, type CandleInterval, CexyApiError, type CexyApiErrorInit, CexyClient, type CexyClientOptions, CexyConfigError, CexyConnectionError, CexyError, CexyTimeoutError, CexyWebSocket, CexyWebSocketError, type CexyWebSocketEvents, type CexyWebSocketOptions, type CloseInfo, ConflictError, type CursorParams, DEFAULT_BASE_URL, DEFAULT_RPM_ANONYMOUS, DEFAULT_RPM_WITH_KEY, DEFAULT_WS_URL, type Deposit, type DepositAddress, type DepositEvent, type DepositStatus, type ErrorBody, type ErrorCode, type ErrorFrame, type EventMap, type ExchangeConfig, type ExitPoolRequest, type ExitPoolResult, ExportsResource, type FeeSchedule, FeesResource, type FetchLike, type Fill, ForbiddenError, InvalidAmountError, type IterateOptions, type JoinPoolRequest, type JoinPoolResult, JurisdictionBlockedError, KNOWN_EVENT_TYPES, type KnownErrorCode, type LedgerEntry, type LedgerEntryKind, type LiquidityRole, type Listener, LiveOrderBook, type LiveOrderBookEvents, type LiveOrderBookOptions, MAX_SERVER_WAIT_MS, type MaintenanceState, type Market, type MarketStatus, type MarketStatusEvent, MarketsResource, type Network, NetworksResource, NotFoundError, type Notification, type NotificationKind, OPERATIONS, type OperationAuth, type OperationId, type OperationInfo, type OperationScope, type Order, type OrderBook, type OrderBookUpdateData, type OrderBookUpdateEvent, type OrderEvent, type OrderSide, OrderStateUnknownError, type OrderStatus, type OrderType, PRIVATE_CHANNELS, type Page, type PlaceOrderRequest, type PlaceOrderResponse, type PlaceOrderResult, type PongFrame, type Pool, type PoolStatus, PoolsResource, type PublicTrade, type QueryOf, RateLimitError, RateLimiter, type RateLimiterOptions, type RateLimiterState, type ReconnectOptions, type RequestOptions, type ResyncReason, type RetryInfo, SUPPORTED_PROTOCOL_VERSION, ServerError, type ServerTime, type SessionRevokedData, type SessionRevokedEvent, type SnapshotSource, type SortDirection, type SubAccount, type SubscribeResult, type SubscribedFrame, type TickerUpdateEvent, type TimeInForce, type TradeNewEvent, TradingResource, type TriggerDirection, TypedEmitter, USER_AGENT, UnprocessableError, type UnsubscribedFrame, VERSION, ValidationError, WS_BOOK_DEPTH, WalletResource, type WebSocketConstructor, type WebSocketLike, type WelcomeFrame, type Withdrawal, type WithdrawalAddress, type WithdrawalStatus, type WithdrawalUpdatedEvent, type WsEvent, type WsLogger, assertAmountFields, type components, errorFromResponse, isAmount, isKnownErrorCode, isLocalHost, isRetryable, type operations, paginate, type paths };
4177
+ export { AccountResource, type Amount, type ApiKey, ApiKeyAuthenticator, type ApiScope, type Asset, type AssetNetwork, AssetsResource, type AuthRequest, type AuthResult, type AuthenticatedFrame, AuthenticationError, type Authenticator, type Balance, type BalanceUpdatedEvent, type BookLevel, CLIENT_ERROR_CODES, CancelAllInterruptedError, type CancelAllParams, type CancelAllRequest, type CancelAllResult, type CancelAllStopReason, type CancelAllUntilDoneResult, type CancelFailure, type Candle, type CandleInterval, CexyApiError, type CexyApiErrorInit, CexyClient, type CexyClientOptions, CexyConfigError, CexyConnectionError, CexyError, CexyTimeoutError, CexyWebSocket, CexyWebSocketError, type CexyWebSocketEvents, type CexyWebSocketOptions, type CloseInfo, ConflictError, type CursorParams, DEFAULT_BASE_URL, DEFAULT_RPM_ANONYMOUS, DEFAULT_RPM_WITH_KEY, DEFAULT_WS_URL, type Deposit, type DepositAddress, type DepositEvent, type DepositId, type DepositStatus, type ErrorBody, type ErrorCode, type ErrorFrame, type EventMap, type ExchangeConfig, type ExitPoolRequest, type ExitPoolResult, ExportsResource, type FeeSchedule, FeesResource, type FetchLike, type Fill, ForbiddenError, type FuturesTransferId, InvalidAmountError, type IterateOptions, type JoinPoolRequest, type JoinPoolResult, JurisdictionBlockedError, KNOWN_EVENT_TYPES, type KnownErrorCode, type KnownLedgerReference, type LedgerEntry, type LedgerEntryKind, type LedgerReference, type LedgerReferenceType, type LiquidityRole, type Listener, LiveOrderBook, type LiveOrderBookEvents, type LiveOrderBookOptions, MAX_SERVER_WAIT_MS, type MaintenanceState, type Market, type MarketStatus, type MarketStatusEvent, MarketsResource, type Network, NetworksResource, NotFoundError, type Notification, type NotificationKind, OPERATIONS, type OperationAuth, type OperationId, type OperationInfo, type OperationScope, type Order, type OrderBook, type OrderBookUpdateData, type OrderBookUpdateEvent, type OrderEvent, type OrderId, type OrderSide, OrderStateUnknownError, type OrderStatus, type OrderType, PRIVATE_CHANNELS, type Page, type PlaceOrderRequest, type PlaceOrderResponse, type PlaceOrderResult, type PongFrame, type Pool, type PoolId, type PoolStatus, PoolsResource, type PublicTrade, type QueryOf, RateLimitError, RateLimiter, type RateLimiterOptions, type RateLimiterState, type ReconnectOptions, type RequestOptions, type ResyncReason, type RetryInfo, SUPPORTED_PROTOCOL_VERSION, ServerError, type ServerTime, type SessionRevokedData, type SessionRevokedEvent, type SnapshotSource, type SortDirection, type SubAccount, type SubscribeResult, type SubscribedFrame, type TickerUpdateEvent, type TimeInForce, type TradeId, type TradeNewEvent, TradingResource, type TriggerDirection, TypedEmitter, USER_AGENT, type UnknownLedgerReference, UnprocessableError, type UnsubscribedFrame, type UserId, VERSION, ValidationError, WS_BOOK_DEPTH, WalletResource, type WebSocketConstructor, type WebSocketLike, type WelcomeFrame, type Withdrawal, type WithdrawalAddress, type WithdrawalId, type WithdrawalStatus, type WithdrawalUpdatedEvent, type WsEvent, type WsLogger, assertAmountFields, type components, errorFromResponse, isAmount, isKnownErrorCode, isLedgerReference, isLocalHost, isRetryable, type operations, paginate, type paths };
package/dist/index.js CHANGED
@@ -137,7 +137,8 @@ var KNOWN_CODES = /* @__PURE__ */ new Set([
137
137
  "INTERNAL",
138
138
  "SERVICE_UNAVAILABLE",
139
139
  "UNDER_MAINTENANCE",
140
- "ENGINE_OVERLOADED"
140
+ "ENGINE_OVERLOADED",
141
+ "PRICE_UNAVAILABLE"
141
142
  ]);
142
143
  var CLIENT_ERROR_CODES = { UNEXPECTED_REDIRECT: "UNEXPECTED_REDIRECT" };
143
144
  function isKnownErrorCode(code) {
@@ -543,6 +544,17 @@ var RateLimiter = class {
543
544
  await this.#sleep(Math.min(MAX_BLOCK_MS, Math.ceil((1 - this.#tokens) * msPerToken)), signal);
544
545
  }
545
546
  }
547
+ /**
548
+ * How long `acquire()` would wait right now, in ms (0 when a request may go at once). Lets a
549
+ * caller with a time budget, such as the cancelAll untilDone loop, count the limiter's wait.
550
+ */
551
+ pendingWaitMs() {
552
+ this.#refill();
553
+ const block = this.#blockedUntil - this.#now();
554
+ if (block > 0) return block;
555
+ if (this.#tokens >= 1) return 0;
556
+ return Math.min(MAX_BLOCK_MS, Math.ceil((1 - this.#tokens) * (6e4 / this.#rpm)));
557
+ }
546
558
  /** Adapts to the server's rate-limit headers. Never raises the configured limit. */
547
559
  update(headers) {
548
560
  this.#refill();
@@ -1013,8 +1025,10 @@ var TradingResource = class extends Resource {
1013
1025
  if (progress) idle = 0;
1014
1026
  else waitMs = (CANCEL_BACKOFF_S[Math.min(idle++, CANCEL_BACKOFF_S.length - 1)] ?? 15) * 1e3;
1015
1027
  }
1016
- if (now() - start + waitMs >= budgetMs) {
1028
+ const limiterMs = this.t.config.limiter?.pendingWaitMs() ?? 0;
1029
+ if (now() - start + Math.max(waitMs, limiterMs) >= budgetMs) {
1017
1030
  stopped = "time_budget";
1031
+ if (limiterMs > waitMs) lastErrorCode = "RATE_LIMITED";
1018
1032
  break;
1019
1033
  }
1020
1034
  if (waitMs > 0) await this.t.config.sleep(waitMs, opts?.signal);
@@ -1024,7 +1038,7 @@ var TradingResource = class extends Resource {
1024
1038
  };
1025
1039
 
1026
1040
  // src/version.ts
1027
- var VERSION = "0.1.0-dev.5";
1041
+ var VERSION = "0.1.0-dev.6";
1028
1042
  var USER_AGENT = `cexy-typescript/${VERSION}`;
1029
1043
 
1030
1044
  // src/ws/emitter.ts
@@ -1876,4 +1890,21 @@ function canSetUserAgent() {
1876
1890
  return !(typeof g.window !== "undefined" && typeof g.window.document !== "undefined");
1877
1891
  }
1878
1892
 
1879
- export { AccountResource, ApiKeyAuthenticator, AssetsResource, AuthenticationError, CLIENT_ERROR_CODES, CancelAllInterruptedError, CexyApiError, CexyClient, CexyConfigError, CexyConnectionError, CexyError, CexyTimeoutError, CexyWebSocket, CexyWebSocketError, ConflictError, DEFAULT_BASE_URL, DEFAULT_RPM_ANONYMOUS, DEFAULT_RPM_WITH_KEY, DEFAULT_WS_URL, ExportsResource, FeesResource, ForbiddenError, InvalidAmountError, JurisdictionBlockedError, KNOWN_EVENT_TYPES, LiveOrderBook, MAX_SERVER_WAIT_MS, MarketsResource, NetworksResource, NotFoundError, OPERATIONS, OrderStateUnknownError, PRIVATE_CHANNELS, PoolsResource, RateLimitError, RateLimiter, SUPPORTED_PROTOCOL_VERSION, ServerError, TradingResource, TypedEmitter, USER_AGENT, UnprocessableError, VERSION, ValidationError, WS_BOOK_DEPTH, WalletResource, assertAmountFields, errorFromResponse, isAmount, isKnownErrorCode, isLocalHost, isRetryable, paginate };
1893
+ // src/ledger.ts
1894
+ var KNOWN_LEDGER_REFERENCE_TYPES = /* @__PURE__ */ new Set([
1895
+ "deposit",
1896
+ "withdrawal",
1897
+ "order",
1898
+ "trade",
1899
+ "transfer",
1900
+ "adjustment",
1901
+ "pool",
1902
+ "futures_transfer",
1903
+ "system"
1904
+ ]);
1905
+ function isLedgerReference(ref, type) {
1906
+ if (typeof ref !== "object" || ref === null || typeof ref.type !== "string") return false;
1907
+ return type === void 0 ? KNOWN_LEDGER_REFERENCE_TYPES.has(ref.type) : ref.type === type;
1908
+ }
1909
+
1910
+ export { AccountResource, ApiKeyAuthenticator, AssetsResource, AuthenticationError, CLIENT_ERROR_CODES, CancelAllInterruptedError, CexyApiError, CexyClient, CexyConfigError, CexyConnectionError, CexyError, CexyTimeoutError, CexyWebSocket, CexyWebSocketError, ConflictError, DEFAULT_BASE_URL, DEFAULT_RPM_ANONYMOUS, DEFAULT_RPM_WITH_KEY, DEFAULT_WS_URL, ExportsResource, FeesResource, ForbiddenError, InvalidAmountError, JurisdictionBlockedError, KNOWN_EVENT_TYPES, LiveOrderBook, MAX_SERVER_WAIT_MS, MarketsResource, NetworksResource, NotFoundError, OPERATIONS, OrderStateUnknownError, PRIVATE_CHANNELS, PoolsResource, RateLimitError, RateLimiter, SUPPORTED_PROTOCOL_VERSION, ServerError, TradingResource, TypedEmitter, USER_AGENT, UnprocessableError, VERSION, ValidationError, WS_BOOK_DEPTH, WalletResource, assertAmountFields, errorFromResponse, isAmount, isKnownErrorCode, isLedgerReference, isLocalHost, isRetryable, paginate };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cexyio/cexy",
3
- "version": "0.1.0-dev.5",
3
+ "version": "0.1.0-dev.6",
4
4
  "description": "Official TypeScript/JavaScript SDK for the CEXY.io REST and WebSocket API",
5
5
  "license": "MIT",
6
6
  "author": "CEXY.io",