@nemesis-oss/binance-sdk 1.0.0 → 2.0.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/dist/index.cjs CHANGED
@@ -33,12 +33,15 @@ __export(index_exports, {
33
33
  AccountAssetSchema: () => AccountAssetSchema,
34
34
  AccountPositionSchema: () => AccountPositionSchema,
35
35
  AccountSchema: () => AccountSchema,
36
+ AccountSnapshotSchema: () => AccountSnapshotSchema,
36
37
  AggTradeSchema: () => AggTradeSchema,
37
38
  AggTradesResponseSchema: () => AggTradesResponseSchema,
38
39
  AlgoOrderResponseSchema: () => AlgoOrderResponseSchema,
39
40
  AlgoOrderSchema: () => AlgoOrderSchema,
40
41
  AlgoOrdersResponseSchema: () => AlgoOrdersResponseSchema,
42
+ ApiKeyPermissionsSchema: () => ApiKeyPermissionsSchema,
41
43
  ApiTradingStatusSchema: () => ApiTradingStatusSchema,
44
+ AssetDetailSchema: () => AssetDetailSchema,
42
45
  AvgPriceSchema: () => AvgPriceSchema,
43
46
  BalanceSchema: () => BalanceSchema,
44
47
  BalancesResponseSchema: () => BalancesResponseSchema,
@@ -50,13 +53,57 @@ __export(index_exports, {
50
53
  BinanceClient: () => BinanceClient,
51
54
  BinanceError: () => BinanceError,
52
55
  BookTickerSchema: () => BookTickerSchema,
56
+ BorrowRepayParamsSchema: () => BorrowRepayParamsSchema,
57
+ BorrowRepayRecordEntrySchema: () => BorrowRepayRecordEntrySchema,
58
+ BorrowRepayRecordResponseSchema: () => BorrowRepayRecordResponseSchema,
59
+ BorrowRepayResultSchema: () => BorrowRepayResultSchema,
60
+ CoinMAccount: () => CoinMAccount,
61
+ CoinMAccountAssetSchema: () => CoinMAccountAssetSchema,
62
+ CoinMAccountPositionSchema: () => CoinMAccountPositionSchema,
63
+ CoinMAccountSchema: () => CoinMAccountSchema,
64
+ CoinMBalanceResponseSchema: () => CoinMBalanceResponseSchema,
65
+ CoinMBalanceSchema: () => CoinMBalanceSchema,
66
+ CoinMCommissionRateSchema: () => CoinMCommissionRateSchema,
67
+ CoinMCreateOrderParamsSchema: () => CoinMCreateOrderParamsSchema,
68
+ CoinMIncomeHistoryResponseSchema: () => CoinMIncomeHistoryResponseSchema,
69
+ CoinMIncomeSchema: () => CoinMIncomeSchema,
70
+ CoinMLeverageBracketResponseSchema: () => CoinMLeverageBracketResponseSchema,
71
+ CoinMLeverageBracketSchema: () => CoinMLeverageBracketSchema,
72
+ CoinMLeverageChangeSchema: () => CoinMLeverageChangeSchema,
73
+ CoinMMarginTypeChangeSchema: () => CoinMMarginTypeChangeSchema,
74
+ CoinMMarket: () => CoinMMarket,
75
+ CoinMMarketWS: () => CoinMMarketWS,
76
+ CoinMOpenInterestHistEntrySchema: () => CoinMOpenInterestHistEntrySchema,
77
+ CoinMOpenInterestHistSchema: () => CoinMOpenInterestHistSchema,
78
+ CoinMOrderResponseSchema: () => CoinMOrderResponseSchema,
79
+ CoinMOrderSchema: () => CoinMOrderSchema,
80
+ CoinMOrdersResponseSchema: () => CoinMOrdersResponseSchema,
81
+ CoinMPositionMarginChangeSchema: () => CoinMPositionMarginChangeSchema,
82
+ CoinMPositionModeSchema: () => CoinMPositionModeSchema,
83
+ CoinMPositionRiskResponseSchema: () => CoinMPositionRiskResponseSchema,
84
+ CoinMPositionRiskSchema: () => CoinMPositionRiskSchema,
85
+ CoinMTrading: () => CoinMTrading,
86
+ CoinMUserDataStream: () => CoinMUserDataStream,
87
+ CoinMUserTradeSchema: () => CoinMUserTradeSchema,
88
+ CoinMUserTradesResponseSchema: () => CoinMUserTradesResponseSchema,
89
+ CoinMUserWS: () => CoinMUserWS,
53
90
  CommissionRateSchema: () => CommissionRateSchema,
54
91
  CountdownCancelAllSchema: () => CountdownCancelAllSchema,
55
92
  CreateOrderParamsSchema: () => CreateOrderParamsSchema,
93
+ CrossMarginAccountSchema: () => CrossMarginAccountSchema,
94
+ DepositAddressSchema: () => DepositAddressSchema,
95
+ DepositHistoryEntrySchema: () => DepositHistoryEntrySchema,
96
+ DepositHistoryResponseSchema: () => DepositHistoryResponseSchema,
56
97
  DepthSnapshotSchema: () => DepthSnapshotSchema,
98
+ DryRunError: () => DryRunError,
99
+ DustConversionResultSchema: () => DustConversionResultSchema,
100
+ DustLogEntrySchema: () => DustLogEntrySchema,
101
+ DustLogResponseSchema: () => DustLogResponseSchema,
57
102
  ExchangeInfoSchema: () => ExchangeInfoSchema,
58
103
  ExchangeSymbolSchema: () => ExchangeSymbolSchema,
59
104
  FeeBurnStatusSchema: () => FeeBurnStatusSchema,
105
+ FundingAssetSchema: () => FundingAssetSchema,
106
+ FundingAssetsResponseSchema: () => FundingAssetsResponseSchema,
60
107
  FundingRateHistorySchema: () => FundingRateHistorySchema,
61
108
  FundingRateSchema: () => FundingRateSchema,
62
109
  FuturesAccount: () => FuturesAccount,
@@ -69,6 +116,10 @@ __export(index_exports, {
69
116
  HttpClient: () => HttpClient,
70
117
  IncomeHistoryResponseSchema: () => IncomeHistoryResponseSchema,
71
118
  IncomeSchema: () => IncomeSchema,
119
+ IsolatedMarginAccountSchema: () => IsolatedMarginAccountSchema,
120
+ IsolatedMarginAssetSchema: () => IsolatedMarginAssetSchema,
121
+ IsolatedMarginSymbolSchema: () => IsolatedMarginSymbolSchema,
122
+ IsolatedTransferParamsSchema: () => IsolatedTransferParamsSchema,
72
123
  KlineIntervalSchema: () => KlineIntervalSchema,
73
124
  KlineSchema: () => KlineSchema,
74
125
  KlinesResponseSchema: () => KlinesResponseSchema,
@@ -78,8 +129,25 @@ __export(index_exports, {
78
129
  ListenKeySchema: () => ListenKeySchema,
79
130
  LongShortRatioEntrySchema: () => LongShortRatioEntrySchema,
80
131
  LongShortRatioSchema: () => LongShortRatioSchema,
132
+ MarginAccount: () => MarginAccount,
133
+ MarginAssetBalanceSchema: () => MarginAssetBalanceSchema,
134
+ MarginCreateOrderParamsSchema: () => MarginCreateOrderParamsSchema,
135
+ MarginForceLiquidationEntrySchema: () => MarginForceLiquidationEntrySchema,
136
+ MarginForceLiquidationResponseSchema: () => MarginForceLiquidationResponseSchema,
137
+ MarginInterestHistoryEntrySchema: () => MarginInterestHistoryEntrySchema,
138
+ MarginInterestHistoryResponseSchema: () => MarginInterestHistoryResponseSchema,
139
+ MarginOrderResponseSchema: () => MarginOrderResponseSchema,
140
+ MarginOrderSchema: () => MarginOrderSchema,
141
+ MarginOrdersResponseSchema: () => MarginOrdersResponseSchema,
142
+ MarginPriceIndexSchema: () => MarginPriceIndexSchema,
143
+ MarginTradeSchema: () => MarginTradeSchema,
144
+ MarginTradesResponseSchema: () => MarginTradesResponseSchema,
145
+ MarginTrading: () => MarginTrading,
146
+ MarginTransferResultSchema: () => MarginTransferResultSchema,
81
147
  MarginTypeChangeSchema: () => MarginTypeChangeSchema,
82
148
  MarketDataBase: () => MarketDataBase,
149
+ MaxBorrowableSchema: () => MaxBorrowableSchema,
150
+ MaxTransferableSchema: () => MaxTransferableSchema,
83
151
  ModifyOrderParamsSchema: () => ModifyOrderParamsSchema,
84
152
  MultiAssetsMarginSchema: () => MultiAssetsMarginSchema,
85
153
  NetworkError: () => NetworkError,
@@ -93,6 +161,7 @@ __export(index_exports, {
93
161
  OrderSchema: () => OrderSchema,
94
162
  OrdersResponseSchema: () => OrdersResponseSchema,
95
163
  PaperTradingEngine: () => PaperTradingEngine,
164
+ PolicyViolationError: () => PolicyViolationError,
96
165
  PositionMarginChangeSchema: () => PositionMarginChangeSchema,
97
166
  PositionMarginHistoryEntrySchema: () => PositionMarginHistoryEntrySchema,
98
167
  PositionMarginHistorySchema: () => PositionMarginHistorySchema,
@@ -103,6 +172,8 @@ __export(index_exports, {
103
172
  RateLimitError: () => RateLimitError,
104
173
  RateLimitOrderResponseSchema: () => RateLimitOrderResponseSchema,
105
174
  RateLimitOrderSchema: () => RateLimitOrderSchema,
175
+ RateLimitTracker: () => RateLimitTracker,
176
+ Signer: () => Signer,
106
177
  SpotAccount: () => SpotAccount,
107
178
  SpotAccountSchema: () => SpotAccountSchema,
108
179
  SpotBalanceSchema: () => SpotBalanceSchema,
@@ -123,12 +194,42 @@ __export(index_exports, {
123
194
  SpotTrading: () => SpotTrading,
124
195
  SpotUserDataStream: () => SpotUserDataStream,
125
196
  SpotUserWS: () => SpotUserWS,
197
+ SpotWsApi: () => SpotWsApi,
198
+ SubAccount: () => SubAccount,
199
+ SubAccountDepositAddressSchema: () => SubAccountDepositAddressSchema,
200
+ SubAccountDepositHistoryEntrySchema: () => SubAccountDepositHistoryEntrySchema,
201
+ SubAccountDepositHistoryResponseSchema: () => SubAccountDepositHistoryResponseSchema,
202
+ SubAccountEnableResultSchema: () => SubAccountEnableResultSchema,
203
+ SubAccountEntrySchema: () => SubAccountEntrySchema,
204
+ SubAccountFuturesSummarySchema: () => SubAccountFuturesSummarySchema,
205
+ SubAccountListResponseSchema: () => SubAccountListResponseSchema,
206
+ SubAccountMarginAccountSchema: () => SubAccountMarginAccountSchema,
207
+ SubAccountSpotAssetSchema: () => SubAccountSpotAssetSchema,
208
+ SubAccountSpotAssetsResponseSchema: () => SubAccountSpotAssetsResponseSchema,
209
+ SubAccountSpotSummaryEntrySchema: () => SubAccountSpotSummaryEntrySchema,
210
+ SubAccountSpotSummarySchema: () => SubAccountSpotSummarySchema,
211
+ SubAccountStatusResponseSchema: () => SubAccountStatusResponseSchema,
212
+ SubAccountStatusSchema: () => SubAccountStatusSchema,
213
+ SubAccountUniversalTransferEntrySchema: () => SubAccountUniversalTransferEntrySchema,
214
+ SubAccountUniversalTransferHistoryResponseSchema: () => SubAccountUniversalTransferHistoryResponseSchema,
215
+ SubAccountUniversalTransferParamsSchema: () => SubAccountUniversalTransferParamsSchema,
216
+ SubAccountUniversalTransferResultSchema: () => SubAccountUniversalTransferResultSchema,
126
217
  TakerLongShortRatioEntrySchema: () => TakerLongShortRatioEntrySchema,
127
218
  TakerLongShortRatioSchema: () => TakerLongShortRatioSchema,
128
219
  Ticker24hrSchema: () => Ticker24hrSchema,
129
220
  TickerPriceSchema: () => TickerPriceSchema,
221
+ TradeFeeEntrySchema: () => TradeFeeEntrySchema,
222
+ TradeFeeResponseSchema: () => TradeFeeResponseSchema,
130
223
  TradeSchema: () => TradeSchema,
131
224
  TradesResponseSchema: () => TradesResponseSchema,
225
+ TradingPolicy: () => TradingPolicy,
226
+ TransferTypeSchema: () => TransferTypeSchema,
227
+ UniversalTransferHistoryEntrySchema: () => UniversalTransferHistoryEntrySchema,
228
+ UniversalTransferHistoryResponseSchema: () => UniversalTransferHistoryResponseSchema,
229
+ UniversalTransferParamsSchema: () => UniversalTransferParamsSchema,
230
+ UniversalTransferResultSchema: () => UniversalTransferResultSchema,
231
+ UserAssetSchema: () => UserAssetSchema,
232
+ UserAssetsResponseSchema: () => UserAssetsResponseSchema,
132
233
  UserDataAccountUpdateSchema: () => UserDataAccountUpdateSchema,
133
234
  UserDataMarginCallSchema: () => UserDataMarginCallSchema,
134
235
  UserDataOrderTradeUpdateSchema: () => UserDataOrderTradeUpdateSchema,
@@ -136,6 +237,12 @@ __export(index_exports, {
136
237
  UserTradeSchema: () => UserTradeSchema,
137
238
  UserTradesResponseSchema: () => UserTradesResponseSchema,
138
239
  VERSION: () => VERSION,
240
+ VirtualSubAccountResultSchema: () => VirtualSubAccountResultSchema,
241
+ Wallet: () => Wallet,
242
+ WithdrawHistoryEntrySchema: () => WithdrawHistoryEntrySchema,
243
+ WithdrawHistoryResponseSchema: () => WithdrawHistoryResponseSchema,
244
+ WithdrawParamsSchema: () => WithdrawParamsSchema,
245
+ WithdrawResultSchema: () => WithdrawResultSchema,
139
246
  WsAggTradePayloadSchema: () => WsAggTradePayloadSchema,
140
247
  WsApi: () => WsApi,
141
248
  WsApiResponseSchema: () => WsApiResponseSchema,
@@ -182,7 +289,6 @@ __export(index_exports, {
182
289
  module.exports = __toCommonJS(index_exports);
183
290
 
184
291
  // src/client/HttpClient.ts
185
- var import_node_crypto = require("crypto");
186
292
  var import_axios = __toESM(require("axios"), 1);
187
293
  var import_bottleneck = __toESM(require("bottleneck"), 1);
188
294
 
@@ -205,18 +311,33 @@ var BinanceAuthError = class extends BinanceError {
205
311
 
206
312
  // src/errors/BinanceApiError.ts
207
313
  var BinanceApiError = class extends BinanceError {
208
- constructor(message, code, status) {
314
+ constructor(message, code, status, context) {
209
315
  super(message);
210
316
  this.name = "BinanceApiError";
211
317
  this.code = code;
212
318
  this.status = status;
319
+ this.endpoint = context?.endpoint;
320
+ this.method = context?.method;
321
+ this.headers = context?.headers;
322
+ }
323
+ /** -1003 (way too many requests) or HTTP 429/418. */
324
+ isRateLimitError() {
325
+ return this.code === -1003 || this.status === 429 || this.status === 418;
326
+ }
327
+ /** -1021: request timestamp outside recvWindow, usually caused by local clock drift. */
328
+ isTimestampError() {
329
+ return this.code === -1021;
330
+ }
331
+ /** -2010: account has insufficient balance for the requested action. */
332
+ isInsufficientBalance() {
333
+ return this.code === -2010;
213
334
  }
214
335
  };
215
336
 
216
337
  // src/errors/RateLimitError.ts
217
338
  var RateLimitError = class extends BinanceApiError {
218
- constructor(message, code, status, retryAfterMs) {
219
- super(message, code, status);
339
+ constructor(message, code, status, retryAfterMs, context) {
340
+ super(message, code, status, context);
220
341
  this.name = "RateLimitError";
221
342
  this.retryAfterMs = retryAfterMs;
222
343
  }
@@ -231,16 +352,144 @@ var NetworkError = class extends BinanceError {
231
352
  }
232
353
  };
233
354
 
355
+ // src/errors/PolicyViolationError.ts
356
+ var PolicyViolationError = class extends BinanceError {
357
+ constructor(rule, message, method, endpoint, details) {
358
+ super(`Blocked by trading policy (${rule}): ${message} [${method} ${endpoint}]`);
359
+ this.name = "PolicyViolationError";
360
+ this.rule = rule;
361
+ this.method = method;
362
+ this.endpoint = endpoint;
363
+ this.details = details;
364
+ }
365
+ };
366
+
367
+ // src/errors/DryRunError.ts
368
+ var DryRunError = class extends BinanceError {
369
+ constructor(method, endpoint, params = {}) {
370
+ super(`DRY RUN \u2014 request not sent: ${method} ${endpoint} ${JSON.stringify(params)}`);
371
+ this.name = "DryRunError";
372
+ this.method = method;
373
+ this.endpoint = endpoint;
374
+ this.params = params;
375
+ }
376
+ /** Human/LLM-readable description of the suppressed request. */
377
+ describe() {
378
+ return `Would have sent ${this.method} ${this.endpoint} with ${JSON.stringify(this.params)}`;
379
+ }
380
+ };
381
+
382
+ // src/client/RateLimitTracker.ts
383
+ var WEIGHT_HEADER = /^x-mbx-used-weight-(.+)$/i;
384
+ var ORDER_COUNT_HEADER = /^x-mbx-order-count-(.+)$/i;
385
+ var RateLimitTracker = class {
386
+ constructor(options = {}) {
387
+ this.usage = {
388
+ usedWeight: 0,
389
+ usedWeightByInterval: {},
390
+ orderCountByInterval: {},
391
+ lastUpdated: 0
392
+ };
393
+ this.weightLimitPerMinute = options.weightLimitPerMinute ?? 6e3;
394
+ this.safetyMargin = options.safetyMargin ?? 0.8;
395
+ }
396
+ update(headers) {
397
+ if (!headers) return;
398
+ const usedWeightByInterval = {};
399
+ const orderCountByInterval = {};
400
+ for (const [key, value] of Object.entries(headers)) {
401
+ const weightMatch = key.match(WEIGHT_HEADER);
402
+ if (weightMatch?.[1]) {
403
+ usedWeightByInterval[weightMatch[1]] = Number(value);
404
+ continue;
405
+ }
406
+ const orderMatch = key.match(ORDER_COUNT_HEADER);
407
+ if (orderMatch?.[1]) {
408
+ orderCountByInterval[orderMatch[1]] = Number(value);
409
+ }
410
+ }
411
+ if (Object.keys(usedWeightByInterval).length === 0 && Object.keys(orderCountByInterval).length === 0) {
412
+ return;
413
+ }
414
+ this.usage = {
415
+ usedWeight: Math.max(0, ...Object.values(usedWeightByInterval)),
416
+ usedWeightByInterval,
417
+ orderCountByInterval,
418
+ lastUpdated: Date.now()
419
+ };
420
+ }
421
+ getUsage() {
422
+ return this.usage;
423
+ }
424
+ /**
425
+ * Milliseconds a caller should wait before its next request, based on the most recently
426
+ * observed 1-minute weight usage. Returns 0 when usage is stale or under the safety margin.
427
+ */
428
+ getThrottleDelayMs() {
429
+ if (this.safetyMargin >= 1) return 0;
430
+ const oneMinuteWeight = this.usage.usedWeightByInterval["1m"] ?? this.usage.usedWeight;
431
+ if (!oneMinuteWeight) return 0;
432
+ if (Date.now() - this.usage.lastUpdated > 6e4) return 0;
433
+ const threshold = this.weightLimitPerMinute * this.safetyMargin;
434
+ if (oneMinuteWeight < threshold) return 0;
435
+ const msIntoMinute = Date.now() % 6e4;
436
+ return 6e4 - msIntoMinute;
437
+ }
438
+ };
439
+
440
+ // src/client/Signer.ts
441
+ var import_node_crypto = require("crypto");
442
+ var Signer = class {
443
+ constructor(options) {
444
+ this.algorithm = options.algorithm ?? (options.privateKey ? "ED25519" : "HMAC");
445
+ this.apiSecret = options.apiSecret;
446
+ if (options.privateKey) {
447
+ this.privateKey = (0, import_node_crypto.createPrivateKey)(options.privateKey);
448
+ }
449
+ }
450
+ canSign() {
451
+ return this.algorithm === "HMAC" ? Boolean(this.apiSecret) : Boolean(this.privateKey);
452
+ }
453
+ sign(payload) {
454
+ switch (this.algorithm) {
455
+ case "HMAC": {
456
+ if (!this.apiSecret) throw new Error("apiSecret is required for HMAC signing");
457
+ return (0, import_node_crypto.createHmac)("sha256", this.apiSecret).update(payload).digest("hex");
458
+ }
459
+ case "ED25519": {
460
+ if (!this.privateKey) throw new Error("privateKey is required for ED25519 signing");
461
+ return (0, import_node_crypto.sign)(null, Buffer.from(payload), this.privateKey).toString("base64");
462
+ }
463
+ case "RSA": {
464
+ if (!this.privateKey) throw new Error("privateKey is required for RSA signing");
465
+ return (0, import_node_crypto.createSign)("RSA-SHA256").update(payload).sign(this.privateKey, "base64");
466
+ }
467
+ default: {
468
+ const exhaustive = this.algorithm;
469
+ throw new Error(`Unsupported signature algorithm: ${String(exhaustive)}`);
470
+ }
471
+ }
472
+ }
473
+ };
474
+
234
475
  // src/client/HttpClient.ts
235
476
  var RETRYABLE_STATUS = /* @__PURE__ */ new Set([429, 418, 500, 502, 503, 504]);
236
477
  function sleep(ms) {
237
478
  return new Promise((resolve) => setTimeout(resolve, ms));
238
479
  }
480
+ function normalizeHeaders(headers) {
481
+ const result = {};
482
+ if (!headers || typeof headers !== "object") return result;
483
+ for (const [key, value] of Object.entries(headers)) {
484
+ if (value !== void 0 && value !== null) result[key.toLowerCase()] = String(value);
485
+ }
486
+ return result;
487
+ }
239
488
  var HttpClient = class {
240
489
  constructor(options) {
241
490
  this.pendingRequests = 0;
491
+ this.timeOffsetMs = 0;
242
492
  this.apiKey = options.apiKey;
243
- this.apiSecret = options.apiSecret;
244
493
  this.recvWindow = options.recvWindow ?? 5e3;
245
494
  this.timeoutMs = options.timeoutMs ?? 15e3;
246
495
  this.maxRetries = options.maxRetries ?? 3;
@@ -248,7 +497,22 @@ var HttpClient = class {
248
497
  this.retryBaseDelayMs = options.retryBaseDelayMs ?? 1e3;
249
498
  this.retryMaxDelayMs = options.retryMaxDelayMs ?? 3e4;
250
499
  this.retryFactor = options.retryFactor ?? 2;
251
- this.axios = import_axios.default.create({ baseURL: options.baseURL, timeout: this.timeoutMs });
500
+ this.signer = new Signer({
501
+ algorithm: options.signatureAlgorithm,
502
+ apiSecret: options.apiSecret,
503
+ privateKey: options.privateKey
504
+ });
505
+ this.rateLimitTracker = new RateLimitTracker({
506
+ weightLimitPerMinute: options.rateLimitWeightPerMinute,
507
+ safetyMargin: options.rateLimitSafetyMargin
508
+ });
509
+ this.policy = options.policy;
510
+ this.axios = import_axios.default.create({
511
+ baseURL: options.baseURL,
512
+ timeout: this.timeoutMs,
513
+ httpsAgent: options.httpsAgent,
514
+ proxy: options.proxy
515
+ });
252
516
  this.limiter = new import_bottleneck.default({ minTime: this.minTimeMs });
253
517
  }
254
518
  async get(path, params, mode = "public") {
@@ -266,6 +530,10 @@ var HttpClient = class {
266
530
  getRateLimiterStatus() {
267
531
  return { minTimeMs: this.minTimeMs, queueLength: this.pendingRequests };
268
532
  }
533
+ /** Snapshot of the most recently observed `X-MBX-USED-WEIGHT-*` / `X-MBX-ORDER-COUNT-*` response headers. */
534
+ getRateLimitUsage() {
535
+ return this.rateLimitTracker.getUsage();
536
+ }
269
537
  configureRateLimiter(options) {
270
538
  if (options.minTimeMs !== void 0) {
271
539
  this.minTimeMs = options.minTimeMs;
@@ -286,10 +554,28 @@ var HttpClient = class {
286
554
  if (options.maxDelayMs !== void 0) this.retryMaxDelayMs = options.maxDelayMs;
287
555
  if (options.factor !== void 0) this.retryFactor = options.factor;
288
556
  }
557
+ /**
558
+ * Fetches server time from `timePath` (e.g. '/time', '/fapi/v1/time', '/dapi/v1/time') and
559
+ * stores the offset from local time, applied to every signed request's `timestamp` param.
560
+ * Mitigates `-1021` (timestamp outside recvWindow) errors caused by local clock drift.
561
+ */
562
+ async syncTime(timePath = "/time") {
563
+ const res = await this.axios.request({ method: "GET", url: timePath });
564
+ this.timeOffsetMs = res.data.serverTime - Date.now();
565
+ return this.timeOffsetMs;
566
+ }
567
+ getTimeOffsetMs() {
568
+ return this.timeOffsetMs;
569
+ }
289
570
  async request(method, path, params, mode) {
571
+ this.policy?.check(method, path, params ?? {});
290
572
  const url = this.buildUrl(path, params, mode);
291
573
  const config = { method, url, headers: this.buildHeaders(mode) };
292
- return this.limiter.schedule(() => this.requestWithRetry(config, 0));
574
+ return this.limiter.schedule(async () => {
575
+ const throttleMs = this.rateLimitTracker.getThrottleDelayMs();
576
+ if (throttleMs > 0) await sleep(throttleMs);
577
+ return this.requestWithRetry(config, 0, method, path);
578
+ });
293
579
  }
294
580
  buildHeaders(mode) {
295
581
  const headers = {
@@ -301,7 +587,7 @@ var HttpClient = class {
301
587
  }
302
588
  buildUrl(path, params, mode) {
303
589
  if (mode !== "signed") return this.appendQuery(path, params);
304
- const requestData = { ...params, timestamp: Date.now(), recvWindow: this.recvWindow };
590
+ const requestData = { ...params, timestamp: Date.now() + this.timeOffsetMs, recvWindow: this.recvWindow };
305
591
  const queryString = this.buildQueryString(requestData);
306
592
  const signature = this.sign(queryString);
307
593
  return `${path}?${queryString}&signature=${signature}`;
@@ -312,20 +598,25 @@ var HttpClient = class {
312
598
  }
313
599
  buildQueryString(params) {
314
600
  if (!params) return "";
315
- return Object.entries(params).filter(([, val]) => val !== void 0 && val !== null).map(([key, val]) => `${key}=${encodeURIComponent(String(val))}`).join("&");
601
+ return Object.entries(params).filter(([, val]) => val !== void 0 && val !== null).flatMap(
602
+ ([key, val]) => Array.isArray(val) ? val.map((item) => `${key}=${encodeURIComponent(String(item))}`) : [`${key}=${encodeURIComponent(String(val))}`]
603
+ ).join("&");
316
604
  }
317
605
  sign(queryString) {
318
- if (!this.apiSecret) throw new BinanceAuthError("apiSecret");
319
- return (0, import_node_crypto.createHmac)("sha256", this.apiSecret).update(queryString).digest("hex");
606
+ if (!this.signer.canSign()) {
607
+ throw new BinanceAuthError(this.signer.algorithm === "HMAC" ? "apiSecret" : "privateKey");
608
+ }
609
+ return this.signer.sign(queryString);
320
610
  }
321
611
  requireApiKey() {
322
612
  if (!this.apiKey) throw new BinanceAuthError("apiKey");
323
613
  return this.apiKey;
324
614
  }
325
- async requestWithRetry(config, attempt) {
615
+ async requestWithRetry(config, attempt, method, endpoint) {
326
616
  this.pendingRequests += 1;
327
617
  try {
328
618
  const res = await this.axios.request(config);
619
+ this.rateLimitTracker.update(normalizeHeaders(res.headers));
329
620
  return res.data;
330
621
  } catch (err) {
331
622
  if (!import_axios.default.isAxiosError(err)) {
@@ -333,21 +624,36 @@ var HttpClient = class {
333
624
  }
334
625
  const status = err.response?.status;
335
626
  const body = err.response?.data;
627
+ const headers = normalizeHeaders(err.response?.headers);
628
+ this.rateLimitTracker.update(headers);
336
629
  if (attempt < this.maxRetries && this.shouldRetry(err)) {
337
630
  await sleep(this.calculateDelay(attempt));
338
- return this.requestWithRetry(config, attempt + 1);
631
+ return this.requestWithRetry(config, attempt + 1, method, endpoint);
339
632
  }
633
+ const context = { endpoint, method, headers };
340
634
  if (status === 429 || status === 418) {
341
- throw new RateLimitError(body?.msg ?? "Binance rate limit exceeded", body?.code ?? -1, status);
635
+ throw new RateLimitError(
636
+ body?.msg ?? "Binance rate limit exceeded",
637
+ body?.code ?? -1,
638
+ status,
639
+ this.parseRetryAfterMs(headers),
640
+ context
641
+ );
342
642
  }
343
643
  if (status && body) {
344
- throw new BinanceApiError(body.msg ?? "Binance API error", body.code ?? -1, status);
644
+ throw new BinanceApiError(body.msg ?? "Binance API error", body.code ?? -1, status, context);
345
645
  }
346
646
  throw new NetworkError(err.message, err);
347
647
  } finally {
348
648
  this.pendingRequests -= 1;
349
649
  }
350
650
  }
651
+ parseRetryAfterMs(headers) {
652
+ const raw = headers["retry-after"];
653
+ if (!raw) return void 0;
654
+ const seconds = Number(raw);
655
+ return Number.isFinite(seconds) ? seconds * 1e3 : void 0;
656
+ }
351
657
  shouldRetry(err) {
352
658
  if (err.response?.status !== void 0) return RETRYABLE_STATUS.has(err.response.status);
353
659
  return true;
@@ -359,6 +665,92 @@ var HttpClient = class {
359
665
  }
360
666
  };
361
667
 
668
+ // src/client/TradingPolicy.ts
669
+ var WITHDRAW_FRAGMENTS = ["/capital/withdraw/apply"];
670
+ var TRANSFER_FRAGMENTS = [
671
+ "/asset/transfer",
672
+ "/margin/transfer",
673
+ "/margin/isolated/transfer",
674
+ "/universaltransfer",
675
+ "/futures/transfer"
676
+ ];
677
+ var MUTATING_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "DELETE"]);
678
+ function toNumber(value) {
679
+ if (value === void 0 || value === null || value === "") return void 0;
680
+ const num2 = Number(value);
681
+ return Number.isFinite(num2) ? num2 : void 0;
682
+ }
683
+ function includesFragment(path, fragments) {
684
+ const lower = path.toLowerCase();
685
+ return fragments.some((fragment) => lower.includes(fragment.toLowerCase()));
686
+ }
687
+ var TradingPolicy = class {
688
+ constructor(options = {}) {
689
+ this.options = options;
690
+ if (options.allowedSymbols?.length) {
691
+ this.allowedSymbols = new Set(options.allowedSymbols.map((s) => s.toUpperCase()));
692
+ }
693
+ }
694
+ /** Throws {@link PolicyViolationError} or {@link DryRunError} if the request is not permitted. */
695
+ check(method, path, params = {}) {
696
+ if (!MUTATING_METHODS.has(method)) return;
697
+ const deny = (rule, message, details) => {
698
+ throw new PolicyViolationError(rule, message, method, path, details);
699
+ };
700
+ if (this.options.blockedPaths?.length && includesFragment(path, this.options.blockedPaths)) {
701
+ deny("blockedPath", "endpoint is on the blocked-path list");
702
+ }
703
+ if (this.options.readOnly) {
704
+ deny("readOnly", "client is in read-only mode; mutating requests are refused");
705
+ }
706
+ if (includesFragment(path, WITHDRAW_FRAGMENTS) && this.options.allowWithdrawals !== true) {
707
+ deny("withdrawalsBlocked", "withdrawals are disabled; set safety.allowWithdrawals to permit them");
708
+ }
709
+ if (includesFragment(path, TRANSFER_FRAGMENTS) && this.options.allowTransfers === false) {
710
+ deny("transfersBlocked", "account transfers are disabled by policy");
711
+ }
712
+ this.checkSymbol(path, params, deny);
713
+ this.checkNotional(path, params, deny);
714
+ if (this.options.dryRun) {
715
+ throw new DryRunError(method, path, params);
716
+ }
717
+ }
718
+ checkSymbol(path, params, deny) {
719
+ if (!this.allowedSymbols) return;
720
+ const symbol3 = params.symbol;
721
+ if (typeof symbol3 !== "string" || symbol3 === "") return;
722
+ if (!this.allowedSymbols.has(symbol3.toUpperCase())) {
723
+ deny("symbolNotAllowed", `symbol ${symbol3} is not in the allowed list`, {
724
+ symbol: symbol3,
725
+ allowed: [...this.allowedSymbols]
726
+ });
727
+ }
728
+ }
729
+ checkNotional(path, params, deny) {
730
+ const max = this.options.maxNotionalPerOrder;
731
+ if (max === void 0) return;
732
+ if (!path.toLowerCase().includes("order")) return;
733
+ const quantity = toNumber(params.quantity);
734
+ const quoteOrderQty = toNumber(params.quoteOrderQty);
735
+ if (quantity === void 0 && quoteOrderQty === void 0) return;
736
+ const price = toNumber(params.price);
737
+ const notional = quoteOrderQty ?? (price !== void 0 && quantity !== void 0 ? price * quantity : void 0);
738
+ if (notional === void 0) {
739
+ deny(
740
+ "notionalUndeterminable",
741
+ `cannot verify notional against the ${max} cap (no price on this order); supply a price or raise/remove maxNotionalPerOrder`,
742
+ { quantity, maxNotionalPerOrder: max }
743
+ );
744
+ }
745
+ if (notional > max) {
746
+ deny("maxNotionalPerOrder", `order notional ${notional} exceeds the ${max} cap`, {
747
+ notional,
748
+ maxNotionalPerOrder: max
749
+ });
750
+ }
751
+ }
752
+ };
753
+
362
754
  // src/client/endpoints.ts
363
755
  function resolveEnvironment(options) {
364
756
  const env = options?.demo ? "demo" : options?.testnet ? "testnet" : "live";
@@ -369,6 +761,9 @@ function resolveEnvironment(options) {
369
761
  const restSpotHost = options?.apiBase ?? (env === "testnet" ? "https://testnet.binance.vision" : "https://api.binance.com");
370
762
  const wsSpotMarketHost = options?.wsBase ?? (env === "testnet" ? "wss://testnet.binance.vision/stream" : "wss://stream.binance.com:9443/stream");
371
763
  const wsSpotUserHost = options?.wsUserBase ?? (env === "testnet" ? "wss://testnet.binance.vision/ws" : "wss://stream.binance.com:9443/ws");
764
+ const restDapiHost = options?.dapiBase ?? (env === "testnet" || env === "demo" ? "https://testnet.binancefuture.com" : "https://dapi.binance.com");
765
+ const wsSpotApiHost = options?.wsSpotApiBase ?? (env === "testnet" ? "wss://testnet.binance.vision/ws-api/v3" : "wss://ws-api.binance.com:443/ws-api/v3");
766
+ const wsDapiHost = options?.wsDapiBase ?? (env === "testnet" || env === "demo" ? "wss://dstream.binancefuture.com" : "wss://dstream.binance.com");
372
767
  return {
373
768
  env,
374
769
  endpoints: {
@@ -376,11 +771,17 @@ function resolveEnvironment(options) {
376
771
  restFapi: `${restHost}/fapi/v1`,
377
772
  restFuturesData: `${restHost}/futures/data`,
378
773
  restSpot: `${restSpotHost}/api/v3`,
774
+ restApiRoot: restSpotHost,
775
+ restDapiRoot: restDapiHost,
776
+ restDapi: `${restDapiHost}/dapi/v1`,
379
777
  wsMarket: wsMarketHost,
380
778
  wsUser: wsUserHost,
381
779
  wsApi: wsApiHost,
382
780
  wsSpotMarket: wsSpotMarketHost,
383
- wsSpotUser: wsSpotUserHost
781
+ wsSpotUser: wsSpotUserHost,
782
+ wsSpotApi: wsSpotApiHost,
783
+ wsDapiMarket: `${wsDapiHost}/stream`,
784
+ wsDapiUser: `${wsDapiHost}/ws`
384
785
  }
385
786
  };
386
787
  }
@@ -2030,300 +2431,1403 @@ var UserDataStream = class {
2030
2431
  }
2031
2432
  };
2032
2433
 
2033
- // src/ws/BaseWS.ts
2034
- var import_node_events = require("events");
2035
- var import_ws = __toESM(require("ws"), 1);
2036
-
2037
- // src/types/ws.types.ts
2434
+ // src/types/coinm.types.ts
2038
2435
  var import_zod7 = require("zod");
2039
- var WsKlinePayloadSchema = import_zod7.z.object({
2040
- e: import_zod7.z.literal("kline"),
2041
- E: import_zod7.z.number(),
2042
- s: import_zod7.z.string(),
2043
- k: import_zod7.z.object({
2044
- t: import_zod7.z.number(),
2045
- T: import_zod7.z.number(),
2046
- s: import_zod7.z.string(),
2047
- i: import_zod7.z.string(),
2048
- o: import_zod7.z.string().transform(Number),
2049
- c: import_zod7.z.string().transform(Number),
2050
- h: import_zod7.z.string().transform(Number),
2051
- l: import_zod7.z.string().transform(Number),
2052
- v: import_zod7.z.string().transform(Number),
2053
- n: import_zod7.z.number(),
2054
- x: import_zod7.z.boolean(),
2055
- q: import_zod7.z.string().transform(Number),
2056
- V: import_zod7.z.string().transform(Number),
2057
- Q: import_zod7.z.string().transform(Number)
2058
- })
2059
- });
2060
- var WsAggTradePayloadSchema = import_zod7.z.object({
2061
- e: import_zod7.z.literal("aggTrade"),
2062
- E: import_zod7.z.number(),
2063
- s: import_zod7.z.string(),
2064
- a: import_zod7.z.number(),
2065
- p: import_zod7.z.string().transform(Number),
2066
- q: import_zod7.z.string().transform(Number),
2067
- f: import_zod7.z.number(),
2068
- l: import_zod7.z.number(),
2069
- T: import_zod7.z.number(),
2070
- m: import_zod7.z.boolean()
2436
+ var CoinMBalanceSchema = import_zod7.z.object({
2437
+ accountAlias: import_zod7.z.string(),
2438
+ asset: import_zod7.z.string(),
2439
+ balance: import_zod7.z.string().transform(Number),
2440
+ withdrawAvailable: import_zod7.z.string().transform(Number),
2441
+ crossWalletBalance: import_zod7.z.string().transform(Number),
2442
+ crossUnPnl: import_zod7.z.string().transform(Number),
2443
+ availableBalance: import_zod7.z.string().transform(Number),
2444
+ updateTime: import_zod7.z.number()
2071
2445
  });
2072
- var WsTradePayloadSchema = import_zod7.z.object({
2073
- e: import_zod7.z.literal("trade"),
2074
- E: import_zod7.z.number(),
2075
- s: import_zod7.z.string(),
2076
- t: import_zod7.z.number(),
2077
- p: import_zod7.z.string().transform(Number),
2078
- q: import_zod7.z.string().transform(Number),
2079
- T: import_zod7.z.number(),
2080
- m: import_zod7.z.boolean()
2081
- });
2082
- var WsDepthUpdatePayloadSchema = import_zod7.z.object({
2083
- e: import_zod7.z.literal("depthUpdate"),
2084
- E: import_zod7.z.number(),
2085
- s: import_zod7.z.string(),
2086
- U: import_zod7.z.number(),
2087
- u: import_zod7.z.number(),
2088
- T: import_zod7.z.number().optional(),
2089
- pu: import_zod7.z.number().optional(),
2090
- b: import_zod7.z.array(import_zod7.z.tuple([import_zod7.z.string(), import_zod7.z.string()])),
2091
- a: import_zod7.z.array(import_zod7.z.tuple([import_zod7.z.string(), import_zod7.z.string()]))
2446
+ var CoinMBalanceResponseSchema = import_zod7.z.array(CoinMBalanceSchema);
2447
+ var CoinMPositionRiskSchema = import_zod7.z.object({
2448
+ symbol: import_zod7.z.string(),
2449
+ pair: import_zod7.z.string().optional(),
2450
+ positionAmt: import_zod7.z.string().transform(Number),
2451
+ entryPrice: import_zod7.z.string().transform(Number),
2452
+ markPrice: import_zod7.z.string().transform(Number),
2453
+ unRealizedProfit: import_zod7.z.string().transform(Number),
2454
+ liquidationPrice: import_zod7.z.string().transform(Number),
2455
+ leverage: import_zod7.z.string().transform(Number),
2456
+ maxQty: import_zod7.z.string().transform(Number).optional(),
2457
+ marginType: import_zod7.z.enum(["isolated", "cross"]),
2458
+ isolatedMargin: import_zod7.z.string().transform(Number).optional(),
2459
+ isAutoAddMargin: import_zod7.z.union([import_zod7.z.string(), import_zod7.z.boolean()]).optional(),
2460
+ positionSide: import_zod7.z.string(),
2461
+ notionalValue: import_zod7.z.string().transform(Number).optional(),
2462
+ breakEvenPrice: import_zod7.z.string().transform(Number).optional(),
2463
+ updateTime: import_zod7.z.number().optional()
2464
+ }).loose();
2465
+ var CoinMPositionRiskResponseSchema = import_zod7.z.array(CoinMPositionRiskSchema);
2466
+ var CoinMAccountAssetSchema = import_zod7.z.object({
2467
+ asset: import_zod7.z.string(),
2468
+ walletBalance: import_zod7.z.string().transform(Number),
2469
+ unrealizedProfit: import_zod7.z.string().transform(Number),
2470
+ marginBalance: import_zod7.z.string().transform(Number),
2471
+ maintMargin: import_zod7.z.string().transform(Number),
2472
+ initialMargin: import_zod7.z.string().transform(Number),
2473
+ positionInitialMargin: import_zod7.z.string().transform(Number),
2474
+ openOrderInitialMargin: import_zod7.z.string().transform(Number),
2475
+ maxWithdrawAmount: import_zod7.z.string().transform(Number),
2476
+ crossWalletBalance: import_zod7.z.string().transform(Number),
2477
+ crossUnPnl: import_zod7.z.string().transform(Number),
2478
+ availableBalance: import_zod7.z.string().transform(Number),
2479
+ updateTime: import_zod7.z.number()
2480
+ }).loose();
2481
+ var CoinMAccountPositionSchema = import_zod7.z.object({
2482
+ symbol: import_zod7.z.string(),
2483
+ positionAmt: import_zod7.z.string().transform(Number),
2484
+ initialMargin: import_zod7.z.string().transform(Number),
2485
+ maintMargin: import_zod7.z.string().transform(Number),
2486
+ unrealizedProfit: import_zod7.z.string().transform(Number),
2487
+ positionInitialMargin: import_zod7.z.string().transform(Number),
2488
+ openOrderInitialMargin: import_zod7.z.string().transform(Number),
2489
+ leverage: import_zod7.z.string().transform(Number),
2490
+ isolated: import_zod7.z.boolean(),
2491
+ positionSide: import_zod7.z.string(),
2492
+ entryPrice: import_zod7.z.string().transform(Number),
2493
+ maxQty: import_zod7.z.string().transform(Number).optional(),
2494
+ updateTime: import_zod7.z.number().optional()
2495
+ }).loose();
2496
+ var CoinMAccountSchema = import_zod7.z.object({
2497
+ canDeposit: import_zod7.z.boolean(),
2498
+ canTrade: import_zod7.z.boolean(),
2499
+ canWithdraw: import_zod7.z.boolean(),
2500
+ feeTier: import_zod7.z.number(),
2501
+ updateTime: import_zod7.z.number(),
2502
+ assets: import_zod7.z.array(CoinMAccountAssetSchema),
2503
+ positions: import_zod7.z.array(CoinMAccountPositionSchema)
2504
+ }).loose();
2505
+ var CoinMOrderSchema = import_zod7.z.object({
2506
+ orderId: import_zod7.z.number(),
2507
+ symbol: import_zod7.z.string(),
2508
+ pair: import_zod7.z.string().optional(),
2509
+ status: import_zod7.z.string(),
2510
+ clientOrderId: import_zod7.z.string(),
2511
+ price: import_zod7.z.string().transform(Number),
2512
+ avgPrice: import_zod7.z.string().transform(Number),
2513
+ origQty: import_zod7.z.string().transform(Number),
2514
+ executedQty: import_zod7.z.string().transform(Number),
2515
+ cumBase: import_zod7.z.string().transform(Number).optional(),
2516
+ type: import_zod7.z.string(),
2517
+ reduceOnly: import_zod7.z.boolean(),
2518
+ closePosition: import_zod7.z.boolean().optional(),
2519
+ side: import_zod7.z.string(),
2520
+ positionSide: import_zod7.z.string(),
2521
+ stopPrice: import_zod7.z.string().transform(Number).optional(),
2522
+ workingType: import_zod7.z.string().optional(),
2523
+ priceProtect: import_zod7.z.boolean().optional(),
2524
+ origType: import_zod7.z.string().optional(),
2525
+ timeInForce: import_zod7.z.string().optional(),
2526
+ activatePrice: import_zod7.z.string().transform(Number).optional(),
2527
+ priceRate: import_zod7.z.string().transform(Number).optional(),
2528
+ time: import_zod7.z.number(),
2529
+ updateTime: import_zod7.z.number()
2530
+ }).loose();
2531
+ var CoinMOrderResponseSchema = CoinMOrderSchema;
2532
+ var CoinMOrdersResponseSchema = import_zod7.z.array(CoinMOrderSchema);
2533
+ var CoinMCreateOrderParamsSchema = import_zod7.z.object({
2534
+ symbol: import_zod7.z.string(),
2535
+ side: import_zod7.z.enum(["BUY", "SELL"]),
2536
+ positionSide: import_zod7.z.enum(["BOTH", "LONG", "SHORT"]).optional(),
2537
+ type: import_zod7.z.string(),
2538
+ timeInForce: import_zod7.z.enum(["GTC", "IOC", "FOK", "GTX"]).optional(),
2539
+ quantity: import_zod7.z.union([import_zod7.z.string(), import_zod7.z.number()]).optional(),
2540
+ reduceOnly: import_zod7.z.boolean().optional(),
2541
+ price: import_zod7.z.union([import_zod7.z.string(), import_zod7.z.number()]).optional(),
2542
+ newClientOrderId: import_zod7.z.string().optional(),
2543
+ stopPrice: import_zod7.z.union([import_zod7.z.string(), import_zod7.z.number()]).optional(),
2544
+ closePosition: import_zod7.z.boolean().optional(),
2545
+ activationPrice: import_zod7.z.union([import_zod7.z.string(), import_zod7.z.number()]).optional(),
2546
+ callbackRate: import_zod7.z.union([import_zod7.z.string(), import_zod7.z.number()]).optional(),
2547
+ workingType: import_zod7.z.enum(["MARK_PRICE", "CONTRACT_PRICE"]).optional(),
2548
+ priceProtect: import_zod7.z.boolean().optional(),
2549
+ newOrderRespType: import_zod7.z.enum(["ACK", "RESULT"]).optional()
2092
2550
  });
2093
- var WsTicker24hrPayloadSchema = import_zod7.z.object({
2094
- e: import_zod7.z.literal("24hrTicker"),
2095
- E: import_zod7.z.number(),
2096
- s: import_zod7.z.string(),
2097
- p: import_zod7.z.string().transform(Number),
2098
- P: import_zod7.z.string().transform(Number),
2099
- c: import_zod7.z.string().transform(Number),
2100
- o: import_zod7.z.string().transform(Number),
2101
- h: import_zod7.z.string().transform(Number),
2102
- l: import_zod7.z.string().transform(Number),
2103
- v: import_zod7.z.string().transform(Number),
2104
- q: import_zod7.z.string().transform(Number)
2551
+ var CoinMLeverageChangeSchema = import_zod7.z.object({
2552
+ leverage: import_zod7.z.number(),
2553
+ maxQty: import_zod7.z.string().transform(Number),
2554
+ symbol: import_zod7.z.string()
2105
2555
  });
2106
- var WsBookTickerPayloadSchema = import_zod7.z.object({
2107
- u: import_zod7.z.number(),
2108
- s: import_zod7.z.string(),
2109
- b: import_zod7.z.string().transform(Number),
2110
- B: import_zod7.z.string().transform(Number),
2111
- a: import_zod7.z.string().transform(Number),
2112
- A: import_zod7.z.string().transform(Number)
2556
+ var CoinMMarginTypeChangeSchema = import_zod7.z.object({ code: import_zod7.z.number(), msg: import_zod7.z.string() });
2557
+ var CoinMPositionMarginChangeSchema = import_zod7.z.object({
2558
+ amount: import_zod7.z.number(),
2559
+ code: import_zod7.z.number(),
2560
+ msg: import_zod7.z.string(),
2561
+ type: import_zod7.z.number()
2113
2562
  });
2114
- var WsMarkPricePayloadSchema = import_zod7.z.object({
2115
- e: import_zod7.z.literal("markPriceUpdate"),
2116
- E: import_zod7.z.number(),
2117
- s: import_zod7.z.string(),
2118
- p: import_zod7.z.string().transform(Number),
2119
- i: import_zod7.z.string().transform(Number),
2120
- P: import_zod7.z.string().transform(Number),
2121
- r: import_zod7.z.string().transform(Number),
2122
- T: import_zod7.z.number()
2563
+ var CoinMIncomeSchema = import_zod7.z.object({
2564
+ symbol: import_zod7.z.string().optional(),
2565
+ incomeType: import_zod7.z.string(),
2566
+ income: import_zod7.z.string().transform(Number),
2567
+ asset: import_zod7.z.string(),
2568
+ info: import_zod7.z.string().optional(),
2569
+ time: import_zod7.z.number(),
2570
+ tranId: import_zod7.z.number(),
2571
+ tradeId: import_zod7.z.string().optional()
2572
+ }).loose();
2573
+ var CoinMIncomeHistoryResponseSchema = import_zod7.z.array(CoinMIncomeSchema);
2574
+ var CoinMUserTradeSchema = import_zod7.z.object({
2575
+ symbol: import_zod7.z.string(),
2576
+ id: import_zod7.z.number(),
2577
+ orderId: import_zod7.z.number(),
2578
+ pair: import_zod7.z.string().optional(),
2579
+ side: import_zod7.z.string(),
2580
+ price: import_zod7.z.string().transform(Number),
2581
+ qty: import_zod7.z.string().transform(Number),
2582
+ realizedPnl: import_zod7.z.string().transform(Number),
2583
+ marginAsset: import_zod7.z.string().optional(),
2584
+ baseQty: import_zod7.z.string().transform(Number).optional(),
2585
+ commission: import_zod7.z.string().transform(Number),
2586
+ commissionAsset: import_zod7.z.string(),
2587
+ time: import_zod7.z.number(),
2588
+ positionSide: import_zod7.z.string(),
2589
+ buyer: import_zod7.z.boolean(),
2590
+ maker: import_zod7.z.boolean()
2591
+ }).loose();
2592
+ var CoinMUserTradesResponseSchema = import_zod7.z.array(CoinMUserTradeSchema);
2593
+ var CoinMOpenInterestHistEntrySchema = import_zod7.z.object({
2594
+ pair: import_zod7.z.string(),
2595
+ contractType: import_zod7.z.string(),
2596
+ sumOpenInterest: import_zod7.z.string().transform(Number),
2597
+ sumOpenInterestValue: import_zod7.z.string().transform(Number),
2598
+ timestamp: import_zod7.z.number()
2123
2599
  });
2124
- var WsMiniTickerPayloadSchema = import_zod7.z.object({
2125
- e: import_zod7.z.literal("24hrMiniTicker"),
2126
- E: import_zod7.z.number(),
2127
- s: import_zod7.z.string(),
2128
- c: import_zod7.z.string().transform(Number),
2129
- o: import_zod7.z.string().transform(Number),
2130
- h: import_zod7.z.string().transform(Number),
2131
- l: import_zod7.z.string().transform(Number),
2132
- v: import_zod7.z.string().transform(Number),
2133
- q: import_zod7.z.string().transform(Number)
2600
+ var CoinMOpenInterestHistSchema = import_zod7.z.array(CoinMOpenInterestHistEntrySchema);
2601
+ var CoinMPositionModeSchema = import_zod7.z.object({ dualSidePosition: import_zod7.z.boolean() });
2602
+ var CoinMLeverageBracketSchema = import_zod7.z.object({
2603
+ bracket: import_zod7.z.number(),
2604
+ initialLeverage: import_zod7.z.number(),
2605
+ qtyCap: import_zod7.z.number(),
2606
+ qtyFloor: import_zod7.z.number(),
2607
+ maintMarginRatio: import_zod7.z.number(),
2608
+ cum: import_zod7.z.number().optional()
2134
2609
  });
2135
- var WsForceOrderPayloadSchema = import_zod7.z.object({
2136
- e: import_zod7.z.literal("forceOrder"),
2137
- E: import_zod7.z.number(),
2138
- o: import_zod7.z.object({
2139
- s: import_zod7.z.string(),
2140
- S: import_zod7.z.string(),
2141
- o: import_zod7.z.string(),
2142
- f: import_zod7.z.string(),
2143
- q: import_zod7.z.string().transform(Number),
2144
- p: import_zod7.z.string().transform(Number),
2145
- ap: import_zod7.z.string().transform(Number),
2146
- X: import_zod7.z.string(),
2147
- l: import_zod7.z.string().transform(Number),
2148
- z: import_zod7.z.string().transform(Number),
2149
- T: import_zod7.z.number()
2610
+ var CoinMLeverageBracketResponseSchema = import_zod7.z.array(
2611
+ import_zod7.z.object({
2612
+ symbol: import_zod7.z.string().optional(),
2613
+ pair: import_zod7.z.string().optional(),
2614
+ brackets: import_zod7.z.array(CoinMLeverageBracketSchema)
2150
2615
  })
2616
+ );
2617
+ var CoinMCommissionRateSchema = import_zod7.z.object({
2618
+ symbol: import_zod7.z.string(),
2619
+ makerCommissionRate: import_zod7.z.string().transform(Number),
2620
+ takerCommissionRate: import_zod7.z.string().transform(Number)
2151
2621
  });
2152
- var WsCompositeIndexPayloadSchema = import_zod7.z.object({
2153
- e: import_zod7.z.literal("compositeIndex"),
2154
- E: import_zod7.z.number(),
2155
- s: import_zod7.z.string(),
2156
- p: import_zod7.z.string().transform(Number),
2157
- c: import_zod7.z.array(
2158
- import_zod7.z.object({
2159
- b: import_zod7.z.string(),
2160
- q: import_zod7.z.string(),
2161
- w: import_zod7.z.string().transform(Number),
2162
- p: import_zod7.z.string().transform(Number)
2163
- })
2164
- )
2165
- });
2166
- var WsAssetIndexPayloadSchema = import_zod7.z.object({
2167
- e: import_zod7.z.literal("assetIndex"),
2168
- E: import_zod7.z.number(),
2169
- s: import_zod7.z.string(),
2170
- i: import_zod7.z.string().transform(Number),
2171
- b: import_zod7.z.string().transform(Number),
2172
- a: import_zod7.z.string().transform(Number)
2173
- });
2174
- var WsRollingWindowTickerPayloadSchema = import_zod7.z.object({
2175
- e: import_zod7.z.enum(["1hTicker", "4hTicker", "1dTicker", "7dTicker", "30dTicker"]),
2176
- E: import_zod7.z.number(),
2177
- s: import_zod7.z.string(),
2178
- p: import_zod7.z.string().transform(Number),
2179
- P: import_zod7.z.string().transform(Number),
2180
- o: import_zod7.z.string().transform(Number),
2181
- h: import_zod7.z.string().transform(Number),
2182
- l: import_zod7.z.string().transform(Number),
2183
- c: import_zod7.z.string().transform(Number),
2184
- v: import_zod7.z.string().transform(Number),
2185
- q: import_zod7.z.string().transform(Number),
2186
- O: import_zod7.z.number(),
2187
- C: import_zod7.z.number()
2188
- });
2189
- var WsSpotAvgPricePayloadSchema = import_zod7.z.object({
2190
- e: import_zod7.z.literal("avgPrice"),
2191
- E: import_zod7.z.number(),
2192
- s: import_zod7.z.string(),
2193
- i: import_zod7.z.string(),
2194
- w: import_zod7.z.string().transform(Number),
2195
- T: import_zod7.z.number()
2196
- });
2197
- function parseWsPayload(streamName, raw) {
2198
- if (streamName.includes("@kline_")) return WsKlinePayloadSchema.parse(raw);
2199
- if (streamName.includes("@continuousKline_") || streamName.includes("@indexPriceKline_") || streamName.includes("@markPriceKline_")) {
2200
- return WsKlinePayloadSchema.parse(raw);
2201
- }
2202
- if (streamName.includes("@aggTrade")) return WsAggTradePayloadSchema.parse(raw);
2203
- if (streamName.includes("@trade")) return WsTradePayloadSchema.parse(raw);
2204
- if (streamName.includes("@depth")) return WsDepthUpdatePayloadSchema.parse(raw);
2205
- if (streamName.includes("@bookTicker")) return WsBookTickerPayloadSchema.parse(raw);
2206
- if (streamName.includes("@markPrice")) return WsMarkPricePayloadSchema.parse(raw);
2207
- if (streamName.includes("@miniTicker")) return WsMiniTickerPayloadSchema.parse(raw);
2208
- if (streamName.includes("@forceOrder")) return WsForceOrderPayloadSchema.parse(raw);
2209
- if (streamName.includes("@compositeIndex")) return WsCompositeIndexPayloadSchema.parse(raw);
2210
- if (streamName.includes("@assetIndex")) return WsAssetIndexPayloadSchema.parse(raw);
2211
- if (streamName.includes("@avgPrice")) return WsSpotAvgPricePayloadSchema.parse(raw);
2212
- if (streamName.includes("@ticker_")) return WsRollingWindowTickerPayloadSchema.parse(raw);
2213
- if (streamName.includes("@ticker")) return WsTicker24hrPayloadSchema.parse(raw);
2214
- throw new Error(`Unknown WS stream type: ${streamName}`);
2215
- }
2216
2622
 
2217
- // src/ws/BaseWS.ts
2218
- var BaseWS = class extends import_node_events.EventEmitter {
2219
- constructor(options) {
2220
- super();
2221
- this.options = options;
2222
- this.ws = null;
2223
- this.streams = /* @__PURE__ */ new Set();
2224
- this.reconnectAttempt = 0;
2225
- this.closedByUser = false;
2226
- }
2227
- subscribe(streams) {
2228
- streams.forEach((s) => this.streams.add(s));
2229
- if (this.isOpen()) {
2230
- this.send({ method: "SUBSCRIBE", params: streams, id: Date.now() });
2231
- } else {
2232
- this.connect();
2233
- }
2234
- }
2235
- unsubscribe(streams) {
2236
- streams.forEach((s) => this.streams.delete(s));
2237
- if (this.isOpen()) {
2238
- this.send({ method: "UNSUBSCRIBE", params: streams, id: Date.now() });
2239
- }
2240
- }
2241
- close() {
2242
- this.closedByUser = true;
2243
- this.ws?.close();
2623
+ // src/resources/CoinMMarket.ts
2624
+ var CoinMMarket = class extends MarketDataBase {
2625
+ constructor(http) {
2626
+ super(http ?? new HttpClient({ baseURL: "https://dapi.binance.com/dapi/v1" }));
2244
2627
  }
2245
- reconnect() {
2246
- if (this.ws?.readyState === import_ws.default.OPEN) this.ws.close();
2247
- this.reconnectAttempt = 0;
2248
- if (!this.closedByUser) this.connect();
2628
+ async continuousKlines(pair, contractType2, interval, options) {
2629
+ const data = await this.http.get("/continuousKlines", {
2630
+ pair,
2631
+ contractType: contractType2,
2632
+ interval,
2633
+ startTime: options?.startTime,
2634
+ endTime: options?.endTime,
2635
+ limit: options?.limit ?? 500
2636
+ });
2637
+ return KlinesResponseSchema.parse(data);
2249
2638
  }
2250
- resetReconnectAttempts() {
2251
- this.reconnectAttempt = 0;
2639
+ async indexPriceKlines(pair, interval, options) {
2640
+ const data = await this.http.get("/indexPriceKlines", {
2641
+ pair,
2642
+ interval,
2643
+ startTime: options?.startTime,
2644
+ endTime: options?.endTime,
2645
+ limit: options?.limit ?? 500
2646
+ });
2647
+ return KlinesResponseSchema.parse(data);
2252
2648
  }
2253
- isOpen() {
2254
- return this.ws?.readyState === import_ws.default.OPEN;
2649
+ async markPriceKlines(symbol3, interval, options) {
2650
+ const data = await this.http.get("/markPriceKlines", {
2651
+ symbol: symbol3,
2652
+ interval,
2653
+ startTime: options?.startTime,
2654
+ endTime: options?.endTime,
2655
+ limit: options?.limit ?? 500
2656
+ });
2657
+ return KlinesResponseSchema.parse(data);
2255
2658
  }
2256
- send(payload) {
2257
- this.ws?.send(JSON.stringify(payload));
2659
+ async premiumIndex(options) {
2660
+ return PremiumIndexSchema.or(PremiumIndexSchema.array()).parse(
2661
+ await this.http.get("/premiumIndex", options)
2662
+ );
2258
2663
  }
2259
- connect() {
2260
- this.closedByUser = false;
2261
- const url = `${this.options.baseStreamUrl}?streams=${[...this.streams].join("/")}`;
2262
- this.ws = new import_ws.default(url);
2263
- this.ws.on("open", () => {
2264
- this.reconnectAttempt = 0;
2265
- this.emit("open");
2266
- });
2267
- this.ws.on("message", (raw) => {
2268
- this.handleMessage(raw.toString());
2269
- });
2270
- this.ws.on("close", () => {
2271
- this.emit("close");
2272
- if (!this.closedByUser) this.scheduleReconnect();
2273
- });
2274
- this.ws.on("error", (err) => {
2275
- if (this.closedByUser) return;
2276
- this.emit("error", err);
2277
- });
2664
+ async fundingRateHistory(symbol3, options) {
2665
+ return FundingRateHistorySchema.parse(await this.http.get("/fundingRate", { symbol: symbol3, ...options }));
2278
2666
  }
2279
- handleMessage(raw) {
2280
- let parsed;
2281
- try {
2282
- parsed = JSON.parse(raw);
2283
- } catch {
2284
- return;
2285
- }
2286
- if (!parsed.stream || parsed.data === void 0) return;
2287
- try {
2288
- const payload = parseWsPayload(parsed.stream, parsed.data);
2289
- this.emit("message", parsed.stream, payload);
2290
- this.emit(parsed.stream, payload);
2291
- } catch (err) {
2292
- this.emit("error", err);
2293
- }
2667
+ async openInterest(symbol3) {
2668
+ return OpenInterestSchema.parse(await this.http.get("/openInterest", { symbol: symbol3 }));
2294
2669
  }
2295
- scheduleReconnect() {
2296
- const base = this.options.reconnectDelayMs ?? 1e3;
2297
- const max = this.options.maxReconnectDelayMs ?? 3e4;
2298
- const delay = Math.min(base * 2 ** this.reconnectAttempt, max);
2299
- this.reconnectAttempt += 1;
2300
- setTimeout(() => {
2301
- if (!this.closedByUser) this.connect();
2302
- }, delay);
2670
+ async openInterestHist(pair, contractType2, period2, options) {
2671
+ return CoinMOpenInterestHistSchema.parse(
2672
+ await this.http.get("/openInterestHist", { pair, contractType: contractType2, period: period2, ...options })
2673
+ );
2303
2674
  }
2304
2675
  };
2305
2676
 
2306
- // src/ws/FuturesMarketWS.ts
2307
- var FuturesMarketWS = class extends BaseWS {
2308
- constructor(baseStreamUrl = "wss://fstream.binance.com/stream") {
2309
- super({ baseStreamUrl });
2677
+ // src/resources/CoinMAccount.ts
2678
+ var CoinMAccount = class {
2679
+ constructor(http) {
2680
+ this.http = http;
2310
2681
  }
2311
- kline(symbol3, interval) {
2312
- return `${symbol3.toLowerCase()}@kline_${interval}`;
2682
+ async balance() {
2683
+ return CoinMBalanceResponseSchema.parse(await this.http.get("/dapi/v1/balance", void 0, "signed"));
2313
2684
  }
2314
- continuousKline(symbol3, contractType2, interval) {
2315
- return `${symbol3.toLowerCase()}@continuousKline_${contractType2}_${interval}`;
2685
+ async account() {
2686
+ return CoinMAccountSchema.parse(await this.http.get("/dapi/v1/account", void 0, "signed"));
2316
2687
  }
2317
- indexPriceKline(symbol3, interval) {
2318
- return `${symbol3.toLowerCase()}@indexPriceKline_${interval}`;
2688
+ async positionRisk(options) {
2689
+ return CoinMPositionRiskResponseSchema.parse(
2690
+ await this.http.get("/dapi/v1/positionRisk", options, "signed")
2691
+ );
2319
2692
  }
2320
- markPriceKline(symbol3, interval) {
2321
- return `${symbol3.toLowerCase()}@markPriceKline_${interval}`;
2693
+ async incomeHistory(options) {
2694
+ return CoinMIncomeHistoryResponseSchema.parse(await this.http.get("/dapi/v1/income", options, "signed"));
2322
2695
  }
2323
- aggTrade(symbol3) {
2324
- return `${symbol3.toLowerCase()}@aggTrade`;
2696
+ async userTrades(options) {
2697
+ return CoinMUserTradesResponseSchema.parse(
2698
+ await this.http.get("/dapi/v1/userTrades", options, "signed")
2699
+ );
2325
2700
  }
2326
- trade(symbol3) {
2701
+ async leverageBrackets(symbol3) {
2702
+ const params = symbol3 ? { symbol: symbol3 } : void 0;
2703
+ return CoinMLeverageBracketResponseSchema.parse(
2704
+ await this.http.get("/dapi/v1/leverageBracket", params, "signed")
2705
+ );
2706
+ }
2707
+ async commissionRate(symbol3) {
2708
+ return CoinMCommissionRateSchema.parse(
2709
+ await this.http.get("/dapi/v1/commissionRate", { symbol: symbol3 }, "signed")
2710
+ );
2711
+ }
2712
+ async positionMode() {
2713
+ return CoinMPositionModeSchema.parse(
2714
+ await this.http.get("/dapi/v1/positionSide/dual", void 0, "signed")
2715
+ );
2716
+ }
2717
+ async setPositionMode(dualSidePosition) {
2718
+ return this.http.post("/dapi/v1/positionSide/dual", { dualSidePosition }, "signed");
2719
+ }
2720
+ };
2721
+
2722
+ // src/resources/CoinMTrading.ts
2723
+ var CoinMTrading = class {
2724
+ constructor(http) {
2725
+ this.http = http;
2726
+ }
2727
+ async setLeverage(symbol3, leverage) {
2728
+ return CoinMLeverageChangeSchema.parse(
2729
+ await this.http.post("/dapi/v1/leverage", { symbol: symbol3, leverage }, "signed")
2730
+ );
2731
+ }
2732
+ async setMarginType(symbol3, marginType) {
2733
+ return CoinMMarginTypeChangeSchema.parse(
2734
+ await this.http.post("/dapi/v1/marginType", { symbol: symbol3, marginType }, "signed")
2735
+ );
2736
+ }
2737
+ async createOrder(params) {
2738
+ return CoinMOrderResponseSchema.parse(await this.http.post("/dapi/v1/order", params, "signed"));
2739
+ }
2740
+ async createTestOrder(params) {
2741
+ return this.http.post("/dapi/v1/order/test", params, "signed");
2742
+ }
2743
+ async getOrder(symbol3, options) {
2744
+ return CoinMOrderResponseSchema.parse(
2745
+ await this.http.get("/dapi/v1/order", { symbol: symbol3, ...options }, "signed")
2746
+ );
2747
+ }
2748
+ async cancelOrder(symbol3, options) {
2749
+ return CoinMOrderResponseSchema.parse(
2750
+ await this.http.delete("/dapi/v1/order", { symbol: symbol3, ...options }, "signed")
2751
+ );
2752
+ }
2753
+ async cancelAllOpenOrders(symbol3) {
2754
+ return this.http.delete("/dapi/v1/allOpenOrders", { symbol: symbol3 }, "signed");
2755
+ }
2756
+ async getOpenOrders(symbol3) {
2757
+ const params = symbol3 ? { symbol: symbol3 } : void 0;
2758
+ return CoinMOrdersResponseSchema.parse(await this.http.get("/dapi/v1/openOrders", params, "signed"));
2759
+ }
2760
+ async getAllOrders(symbol3, options) {
2761
+ return CoinMOrdersResponseSchema.parse(
2762
+ await this.http.get("/dapi/v1/allOrders", { symbol: symbol3, ...options }, "signed")
2763
+ );
2764
+ }
2765
+ async modifyPositionMargin(symbol3, amount, type) {
2766
+ return CoinMPositionMarginChangeSchema.parse(
2767
+ await this.http.post("/dapi/v1/positionMargin", { symbol: symbol3, amount, type }, "signed")
2768
+ );
2769
+ }
2770
+ };
2771
+
2772
+ // src/resources/CoinMUserDataStream.ts
2773
+ var CoinMUserDataStream = class {
2774
+ constructor(http) {
2775
+ this.http = http;
2776
+ }
2777
+ async createListenKey() {
2778
+ return ListenKeySchema.parse(await this.http.post("/dapi/v1/listenKey", void 0, "apiKey"));
2779
+ }
2780
+ async keepAliveListenKey() {
2781
+ return this.http.put("/dapi/v1/listenKey", void 0, "apiKey");
2782
+ }
2783
+ async closeListenKey() {
2784
+ return this.http.delete("/dapi/v1/listenKey", void 0, "apiKey");
2785
+ }
2786
+ };
2787
+
2788
+ // src/types/margin.types.ts
2789
+ var import_zod8 = require("zod");
2790
+ var MarginAssetBalanceSchema = import_zod8.z.object({
2791
+ asset: import_zod8.z.string(),
2792
+ borrowed: import_zod8.z.string().transform(Number),
2793
+ free: import_zod8.z.string().transform(Number),
2794
+ interest: import_zod8.z.string().transform(Number),
2795
+ locked: import_zod8.z.string().transform(Number),
2796
+ netAsset: import_zod8.z.string().transform(Number)
2797
+ });
2798
+ var CrossMarginAccountSchema = import_zod8.z.object({
2799
+ borrowEnabled: import_zod8.z.boolean(),
2800
+ marginLevel: import_zod8.z.string().transform(Number),
2801
+ totalAssetOfBtc: import_zod8.z.string().transform(Number),
2802
+ totalLiabilityOfBtc: import_zod8.z.string().transform(Number),
2803
+ totalNetAssetOfBtc: import_zod8.z.string().transform(Number),
2804
+ tradeEnabled: import_zod8.z.boolean(),
2805
+ transferEnabled: import_zod8.z.boolean(),
2806
+ accountType: import_zod8.z.string().optional(),
2807
+ userAssets: import_zod8.z.array(MarginAssetBalanceSchema)
2808
+ }).loose();
2809
+ var IsolatedMarginAssetSchema = import_zod8.z.object({
2810
+ asset: import_zod8.z.string(),
2811
+ borrowEnabled: import_zod8.z.boolean(),
2812
+ borrowed: import_zod8.z.string().transform(Number),
2813
+ free: import_zod8.z.string().transform(Number),
2814
+ interest: import_zod8.z.string().transform(Number),
2815
+ locked: import_zod8.z.string().transform(Number),
2816
+ netAsset: import_zod8.z.string().transform(Number),
2817
+ netAssetOfBtc: import_zod8.z.string().transform(Number),
2818
+ repayEnabled: import_zod8.z.boolean(),
2819
+ totalAsset: import_zod8.z.string().transform(Number)
2820
+ }).loose();
2821
+ var IsolatedMarginSymbolSchema = import_zod8.z.object({
2822
+ baseAsset: IsolatedMarginAssetSchema,
2823
+ quoteAsset: IsolatedMarginAssetSchema,
2824
+ symbol: import_zod8.z.string(),
2825
+ isolatedCreated: import_zod8.z.boolean().optional(),
2826
+ enabled: import_zod8.z.boolean(),
2827
+ marginLevel: import_zod8.z.string().transform(Number),
2828
+ marginLevelStatus: import_zod8.z.string().optional(),
2829
+ marginRatio: import_zod8.z.string().transform(Number).optional(),
2830
+ indexPrice: import_zod8.z.string().transform(Number).optional(),
2831
+ liquidatePrice: import_zod8.z.string().transform(Number).optional(),
2832
+ liquidateRate: import_zod8.z.string().transform(Number).optional(),
2833
+ tradeEnabled: import_zod8.z.boolean()
2834
+ }).loose();
2835
+ var IsolatedMarginAccountSchema = import_zod8.z.object({
2836
+ assets: import_zod8.z.array(IsolatedMarginSymbolSchema),
2837
+ totalAssetOfBtc: import_zod8.z.string().transform(Number).optional(),
2838
+ totalLiabilityOfBtc: import_zod8.z.string().transform(Number).optional(),
2839
+ totalNetAssetOfBtc: import_zod8.z.string().transform(Number).optional()
2840
+ });
2841
+ var MaxBorrowableSchema = import_zod8.z.object({
2842
+ amount: import_zod8.z.string().transform(Number),
2843
+ borrowLimit: import_zod8.z.string().transform(Number)
2844
+ });
2845
+ var MaxTransferableSchema = import_zod8.z.object({
2846
+ amount: import_zod8.z.string().transform(Number),
2847
+ fullAmount: import_zod8.z.string().transform(Number).optional()
2848
+ });
2849
+ var BorrowRepayParamsSchema = import_zod8.z.object({
2850
+ asset: import_zod8.z.string(),
2851
+ isIsolated: import_zod8.z.enum(["TRUE", "FALSE"]).optional(),
2852
+ symbol: import_zod8.z.string().optional(),
2853
+ amount: import_zod8.z.union([import_zod8.z.string(), import_zod8.z.number()]),
2854
+ type: import_zod8.z.enum(["BORROW", "REPAY"])
2855
+ });
2856
+ var BorrowRepayResultSchema = import_zod8.z.object({ tranId: import_zod8.z.number() });
2857
+ var BorrowRepayRecordEntrySchema = import_zod8.z.object({
2858
+ isolatedSymbol: import_zod8.z.string().optional(),
2859
+ txId: import_zod8.z.number(),
2860
+ asset: import_zod8.z.string(),
2861
+ principal: import_zod8.z.string().transform(Number),
2862
+ timestamp: import_zod8.z.number(),
2863
+ status: import_zod8.z.string()
2864
+ }).loose();
2865
+ var BorrowRepayRecordResponseSchema = import_zod8.z.object({
2866
+ rows: import_zod8.z.array(BorrowRepayRecordEntrySchema),
2867
+ total: import_zod8.z.number()
2868
+ });
2869
+ var MarginTransferResultSchema = import_zod8.z.object({ tranId: import_zod8.z.number() });
2870
+ var IsolatedTransferParamsSchema = import_zod8.z.object({
2871
+ asset: import_zod8.z.string(),
2872
+ symbol: import_zod8.z.string(),
2873
+ transFrom: import_zod8.z.enum(["SPOT", "ISOLATED_MARGIN"]),
2874
+ transTo: import_zod8.z.enum(["SPOT", "ISOLATED_MARGIN"]),
2875
+ amount: import_zod8.z.union([import_zod8.z.string(), import_zod8.z.number()])
2876
+ });
2877
+ var MarginInterestHistoryEntrySchema = import_zod8.z.object({
2878
+ txId: import_zod8.z.number(),
2879
+ interestAccuredTime: import_zod8.z.number(),
2880
+ asset: import_zod8.z.string(),
2881
+ rawAsset: import_zod8.z.string().optional(),
2882
+ principal: import_zod8.z.string().transform(Number),
2883
+ interest: import_zod8.z.string().transform(Number),
2884
+ interestRate: import_zod8.z.string().transform(Number),
2885
+ type: import_zod8.z.string(),
2886
+ isolatedSymbol: import_zod8.z.string().optional()
2887
+ }).loose();
2888
+ var MarginInterestHistoryResponseSchema = import_zod8.z.object({
2889
+ rows: import_zod8.z.array(MarginInterestHistoryEntrySchema),
2890
+ total: import_zod8.z.number()
2891
+ });
2892
+ var MarginForceLiquidationEntrySchema = import_zod8.z.object({
2893
+ avgPrice: import_zod8.z.string().transform(Number),
2894
+ executedQty: import_zod8.z.string().transform(Number),
2895
+ orderId: import_zod8.z.number(),
2896
+ price: import_zod8.z.string().transform(Number),
2897
+ qty: import_zod8.z.string().transform(Number),
2898
+ side: import_zod8.z.string(),
2899
+ symbol: import_zod8.z.string(),
2900
+ timeInForce: import_zod8.z.string(),
2901
+ isIsolated: import_zod8.z.boolean().optional(),
2902
+ updatedTime: import_zod8.z.number()
2903
+ }).loose();
2904
+ var MarginForceLiquidationResponseSchema = import_zod8.z.object({
2905
+ rows: import_zod8.z.array(MarginForceLiquidationEntrySchema),
2906
+ total: import_zod8.z.number()
2907
+ });
2908
+ var MarginPriceIndexSchema = import_zod8.z.object({
2909
+ calcTime: import_zod8.z.number(),
2910
+ price: import_zod8.z.string().transform(Number),
2911
+ symbol: import_zod8.z.string()
2912
+ });
2913
+ var MarginOrderSchema = import_zod8.z.object({
2914
+ symbol: import_zod8.z.string(),
2915
+ orderId: import_zod8.z.number(),
2916
+ clientOrderId: import_zod8.z.string(),
2917
+ isIsolated: import_zod8.z.boolean().optional(),
2918
+ price: import_zod8.z.string().transform(Number),
2919
+ origQty: import_zod8.z.string().transform(Number),
2920
+ executedQty: import_zod8.z.string().transform(Number),
2921
+ cummulativeQuoteQty: import_zod8.z.string().transform(Number),
2922
+ status: import_zod8.z.string(),
2923
+ timeInForce: import_zod8.z.string().optional(),
2924
+ type: import_zod8.z.string(),
2925
+ side: import_zod8.z.string(),
2926
+ transactTime: import_zod8.z.number().optional(),
2927
+ time: import_zod8.z.number().optional(),
2928
+ updateTime: import_zod8.z.number().optional(),
2929
+ fills: import_zod8.z.array(import_zod8.z.unknown()).optional()
2930
+ }).loose();
2931
+ var MarginOrderResponseSchema = MarginOrderSchema;
2932
+ var MarginOrdersResponseSchema = import_zod8.z.array(MarginOrderSchema);
2933
+ var MarginCreateOrderParamsSchema = import_zod8.z.object({
2934
+ symbol: import_zod8.z.string(),
2935
+ isIsolated: import_zod8.z.enum(["TRUE", "FALSE"]).optional(),
2936
+ side: import_zod8.z.enum(["BUY", "SELL"]),
2937
+ type: import_zod8.z.string(),
2938
+ quantity: import_zod8.z.union([import_zod8.z.string(), import_zod8.z.number()]).optional(),
2939
+ quoteOrderQty: import_zod8.z.union([import_zod8.z.string(), import_zod8.z.number()]).optional(),
2940
+ price: import_zod8.z.union([import_zod8.z.string(), import_zod8.z.number()]).optional(),
2941
+ stopPrice: import_zod8.z.union([import_zod8.z.string(), import_zod8.z.number()]).optional(),
2942
+ newClientOrderId: import_zod8.z.string().optional(),
2943
+ icebergQty: import_zod8.z.union([import_zod8.z.string(), import_zod8.z.number()]).optional(),
2944
+ timeInForce: import_zod8.z.enum(["GTC", "IOC", "FOK"]).optional(),
2945
+ sideEffectType: import_zod8.z.enum(["NO_SIDE_EFFECT", "MARGIN_BUY", "AUTO_REPAY", "AUTO_BORROW_REPAY"]).optional(),
2946
+ newOrderRespType: import_zod8.z.enum(["ACK", "RESULT", "FULL"]).optional(),
2947
+ autoRepayAtCancel: import_zod8.z.boolean().optional()
2948
+ });
2949
+ var MarginTradeSchema = import_zod8.z.object({
2950
+ symbol: import_zod8.z.string(),
2951
+ id: import_zod8.z.number(),
2952
+ orderId: import_zod8.z.number(),
2953
+ price: import_zod8.z.string().transform(Number),
2954
+ qty: import_zod8.z.string().transform(Number),
2955
+ quoteQty: import_zod8.z.string().transform(Number),
2956
+ commission: import_zod8.z.string().transform(Number),
2957
+ commissionAsset: import_zod8.z.string(),
2958
+ time: import_zod8.z.number(),
2959
+ isBuyer: import_zod8.z.boolean(),
2960
+ isMaker: import_zod8.z.boolean(),
2961
+ isBestMatch: import_zod8.z.boolean().optional(),
2962
+ isIsolated: import_zod8.z.boolean().optional()
2963
+ }).loose();
2964
+ var MarginTradesResponseSchema = import_zod8.z.array(MarginTradeSchema);
2965
+
2966
+ // src/resources/Margin.ts
2967
+ var MarginAccount = class {
2968
+ constructor(http) {
2969
+ this.http = http;
2970
+ }
2971
+ async crossAccount() {
2972
+ return CrossMarginAccountSchema.parse(await this.http.get("/sapi/v1/margin/account", void 0, "signed"));
2973
+ }
2974
+ async isolatedAccount(symbols) {
2975
+ const params = symbols?.length ? { symbols: symbols.join(",") } : void 0;
2976
+ return IsolatedMarginAccountSchema.parse(
2977
+ await this.http.get("/sapi/v1/margin/isolated/account", params, "signed")
2978
+ );
2979
+ }
2980
+ async maxBorrowable(asset, isolatedSymbol) {
2981
+ return MaxBorrowableSchema.parse(
2982
+ await this.http.get("/sapi/v1/margin/maxBorrowable", { asset, isolatedSymbol }, "signed")
2983
+ );
2984
+ }
2985
+ async maxTransferable(asset, isolatedSymbol) {
2986
+ return MaxTransferableSchema.parse(
2987
+ await this.http.get("/sapi/v1/margin/maxTransferable", { asset, isolatedSymbol }, "signed")
2988
+ );
2989
+ }
2990
+ async borrowRepay(params) {
2991
+ return BorrowRepayResultSchema.parse(
2992
+ await this.http.post("/sapi/v1/margin/borrow-repay", params, "signed")
2993
+ );
2994
+ }
2995
+ async borrow(asset, amount, options) {
2996
+ return this.borrowRepay({
2997
+ asset,
2998
+ amount,
2999
+ type: "BORROW",
3000
+ isIsolated: options?.isIsolated ? "TRUE" : void 0,
3001
+ symbol: options?.symbol
3002
+ });
3003
+ }
3004
+ async repay(asset, amount, options) {
3005
+ return this.borrowRepay({
3006
+ asset,
3007
+ amount,
3008
+ type: "REPAY",
3009
+ isIsolated: options?.isIsolated ? "TRUE" : void 0,
3010
+ symbol: options?.symbol
3011
+ });
3012
+ }
3013
+ async borrowRepayRecord(type, options) {
3014
+ return BorrowRepayRecordResponseSchema.parse(
3015
+ await this.http.get("/sapi/v1/margin/borrow-repay", { type, ...options }, "signed")
3016
+ );
3017
+ }
3018
+ async transfer(asset, amount, type) {
3019
+ return MarginTransferResultSchema.parse(
3020
+ await this.http.post("/sapi/v1/margin/transfer", { asset, amount, type }, "signed")
3021
+ );
3022
+ }
3023
+ async isolatedTransfer(params) {
3024
+ return MarginTransferResultSchema.parse(
3025
+ await this.http.post("/sapi/v1/margin/isolated/transfer", params, "signed")
3026
+ );
3027
+ }
3028
+ async interestHistory(options) {
3029
+ return MarginInterestHistoryResponseSchema.parse(
3030
+ await this.http.get("/sapi/v1/margin/interestHistory", options, "signed")
3031
+ );
3032
+ }
3033
+ async forceLiquidationRecord(options) {
3034
+ return MarginForceLiquidationResponseSchema.parse(
3035
+ await this.http.get("/sapi/v1/margin/forceLiquidationRec", options, "signed")
3036
+ );
3037
+ }
3038
+ async priceIndex(symbol3) {
3039
+ return MarginPriceIndexSchema.parse(await this.http.get("/sapi/v1/margin/priceIndex", { symbol: symbol3 }));
3040
+ }
3041
+ };
3042
+ var MarginTrading = class {
3043
+ constructor(http) {
3044
+ this.http = http;
3045
+ }
3046
+ async createOrder(params) {
3047
+ return MarginOrderResponseSchema.parse(await this.http.post("/sapi/v1/margin/order", params, "signed"));
3048
+ }
3049
+ async cancelOrder(symbol3, options) {
3050
+ return MarginOrderResponseSchema.parse(
3051
+ await this.http.delete("/sapi/v1/margin/order", { symbol: symbol3, ...options }, "signed")
3052
+ );
3053
+ }
3054
+ async cancelAllOpenOrders(symbol3, isIsolated) {
3055
+ return MarginOrdersResponseSchema.parse(
3056
+ await this.http.delete("/sapi/v1/margin/openOrders", { symbol: symbol3, isIsolated }, "signed")
3057
+ );
3058
+ }
3059
+ async getOrder(symbol3, options) {
3060
+ return MarginOrderResponseSchema.parse(
3061
+ await this.http.get("/sapi/v1/margin/order", { symbol: symbol3, ...options }, "signed")
3062
+ );
3063
+ }
3064
+ async getOpenOrders(options) {
3065
+ return MarginOrdersResponseSchema.parse(await this.http.get("/sapi/v1/margin/openOrders", options, "signed"));
3066
+ }
3067
+ async getAllOrders(symbol3, options) {
3068
+ return MarginOrdersResponseSchema.parse(
3069
+ await this.http.get("/sapi/v1/margin/allOrders", { symbol: symbol3, ...options }, "signed")
3070
+ );
3071
+ }
3072
+ async myTrades(symbol3, options) {
3073
+ return MarginTradesResponseSchema.parse(
3074
+ await this.http.get("/sapi/v1/margin/myTrades", { symbol: symbol3, ...options }, "signed")
3075
+ );
3076
+ }
3077
+ };
3078
+
3079
+ // src/types/wallet.types.ts
3080
+ var import_zod9 = require("zod");
3081
+ var TransferTypeSchema = import_zod9.z.enum([
3082
+ "MAIN_UMFUTURE",
3083
+ "MAIN_CMFUTURE",
3084
+ "MAIN_MARGIN",
3085
+ "MAIN_MINING",
3086
+ "MAIN_FUNDING",
3087
+ "MAIN_OPTION",
3088
+ "UMFUTURE_MAIN",
3089
+ "UMFUTURE_MARGIN",
3090
+ "UMFUTURE_FUNDING",
3091
+ "CMFUTURE_MAIN",
3092
+ "CMFUTURE_MARGIN",
3093
+ "MARGIN_MAIN",
3094
+ "MARGIN_UMFUTURE",
3095
+ "MARGIN_CMFUTURE",
3096
+ "MARGIN_MINING",
3097
+ "MARGIN_FUNDING",
3098
+ "MINING_MAIN",
3099
+ "MINING_UMFUTURE",
3100
+ "MINING_MARGIN",
3101
+ "FUNDING_MAIN",
3102
+ "FUNDING_UMFUTURE",
3103
+ "FUNDING_MARGIN",
3104
+ "FUNDING_CMFUTURE",
3105
+ "OPTION_MAIN",
3106
+ "MAIN_OPTION_MARGIN",
3107
+ "MAIN_PORTFOLIO_MARGIN",
3108
+ "PORTFOLIO_MARGIN_MAIN",
3109
+ "ISOLATEDMARGIN_MARGIN",
3110
+ "MARGIN_ISOLATEDMARGIN",
3111
+ "ISOLATEDMARGIN_ISOLATEDMARGIN"
3112
+ ]);
3113
+ var UniversalTransferParamsSchema = import_zod9.z.object({
3114
+ type: TransferTypeSchema,
3115
+ asset: import_zod9.z.string(),
3116
+ amount: import_zod9.z.union([import_zod9.z.string(), import_zod9.z.number()]),
3117
+ fromSymbol: import_zod9.z.string().optional(),
3118
+ toSymbol: import_zod9.z.string().optional()
3119
+ });
3120
+ var UniversalTransferResultSchema = import_zod9.z.object({ tranId: import_zod9.z.number() });
3121
+ var UniversalTransferHistoryEntrySchema = import_zod9.z.object({
3122
+ asset: import_zod9.z.string(),
3123
+ amount: import_zod9.z.string().transform(Number),
3124
+ type: import_zod9.z.string(),
3125
+ status: import_zod9.z.string(),
3126
+ tranId: import_zod9.z.number(),
3127
+ timestamp: import_zod9.z.number(),
3128
+ fromSymbol: import_zod9.z.string().nullable().optional(),
3129
+ toSymbol: import_zod9.z.string().nullable().optional()
3130
+ }).loose();
3131
+ var UniversalTransferHistoryResponseSchema = import_zod9.z.object({
3132
+ total: import_zod9.z.number(),
3133
+ rows: import_zod9.z.array(UniversalTransferHistoryEntrySchema)
3134
+ });
3135
+ var FundingAssetSchema = import_zod9.z.object({
3136
+ asset: import_zod9.z.string(),
3137
+ free: import_zod9.z.string().transform(Number),
3138
+ locked: import_zod9.z.string().transform(Number),
3139
+ freeze: import_zod9.z.string().transform(Number),
3140
+ withdrawing: import_zod9.z.string().transform(Number),
3141
+ btcValuation: import_zod9.z.string().transform(Number)
3142
+ });
3143
+ var FundingAssetsResponseSchema = import_zod9.z.array(FundingAssetSchema);
3144
+ var UserAssetSchema = import_zod9.z.object({
3145
+ asset: import_zod9.z.string(),
3146
+ free: import_zod9.z.string().transform(Number),
3147
+ locked: import_zod9.z.string().transform(Number),
3148
+ freeze: import_zod9.z.string().transform(Number),
3149
+ withdrawing: import_zod9.z.string().transform(Number),
3150
+ ipoable: import_zod9.z.string().transform(Number),
3151
+ btcValuation: import_zod9.z.string().transform(Number)
3152
+ });
3153
+ var UserAssetsResponseSchema = import_zod9.z.array(UserAssetSchema);
3154
+ var DepositHistoryEntrySchema = import_zod9.z.object({
3155
+ id: import_zod9.z.string(),
3156
+ amount: import_zod9.z.string().transform(Number),
3157
+ coin: import_zod9.z.string(),
3158
+ network: import_zod9.z.string(),
3159
+ status: import_zod9.z.number(),
3160
+ address: import_zod9.z.string(),
3161
+ addressTag: import_zod9.z.string().optional(),
3162
+ txId: import_zod9.z.string(),
3163
+ insertTime: import_zod9.z.number(),
3164
+ transferType: import_zod9.z.number(),
3165
+ confirmTimes: import_zod9.z.string().optional(),
3166
+ unlockConfirm: import_zod9.z.union([import_zod9.z.string(), import_zod9.z.number()]).optional(),
3167
+ walletType: import_zod9.z.number().optional()
3168
+ }).loose();
3169
+ var DepositHistoryResponseSchema = import_zod9.z.array(DepositHistoryEntrySchema);
3170
+ var WithdrawHistoryEntrySchema = import_zod9.z.object({
3171
+ id: import_zod9.z.string(),
3172
+ amount: import_zod9.z.string().transform(Number),
3173
+ transactionFee: import_zod9.z.string().transform(Number),
3174
+ coin: import_zod9.z.string(),
3175
+ status: import_zod9.z.number(),
3176
+ address: import_zod9.z.string(),
3177
+ txId: import_zod9.z.string().optional(),
3178
+ applyTime: import_zod9.z.string(),
3179
+ network: import_zod9.z.string(),
3180
+ transferType: import_zod9.z.number(),
3181
+ withdrawOrderId: import_zod9.z.string().nullable().optional(),
3182
+ info: import_zod9.z.string().optional(),
3183
+ confirmNo: import_zod9.z.number().optional(),
3184
+ walletType: import_zod9.z.number().optional()
3185
+ }).loose();
3186
+ var WithdrawHistoryResponseSchema = import_zod9.z.array(WithdrawHistoryEntrySchema);
3187
+ var WithdrawParamsSchema = import_zod9.z.object({
3188
+ coin: import_zod9.z.string(),
3189
+ address: import_zod9.z.string(),
3190
+ amount: import_zod9.z.union([import_zod9.z.string(), import_zod9.z.number()]),
3191
+ withdrawOrderId: import_zod9.z.string().optional(),
3192
+ network: import_zod9.z.string().optional(),
3193
+ addressTag: import_zod9.z.string().optional(),
3194
+ transactionFeeFlag: import_zod9.z.boolean().optional(),
3195
+ name: import_zod9.z.string().optional(),
3196
+ walletType: import_zod9.z.number().optional()
3197
+ });
3198
+ var WithdrawResultSchema = import_zod9.z.object({ id: import_zod9.z.string() });
3199
+ var DepositAddressSchema = import_zod9.z.object({
3200
+ address: import_zod9.z.string(),
3201
+ coin: import_zod9.z.string(),
3202
+ tag: import_zod9.z.string(),
3203
+ url: import_zod9.z.string().optional()
3204
+ });
3205
+ var ApiKeyPermissionsSchema = import_zod9.z.object({
3206
+ ipRestrict: import_zod9.z.boolean(),
3207
+ createTime: import_zod9.z.number(),
3208
+ enableWithdrawals: import_zod9.z.boolean(),
3209
+ enableInternalTransfer: import_zod9.z.boolean(),
3210
+ enableFutures: import_zod9.z.boolean(),
3211
+ enableMargin: import_zod9.z.boolean(),
3212
+ enableSpotAndMarginTrading: import_zod9.z.boolean(),
3213
+ permitsUniversalTransfer: import_zod9.z.boolean().optional(),
3214
+ enableReading: import_zod9.z.boolean().optional(),
3215
+ tradingAuthorityExpirationTime: import_zod9.z.number().optional()
3216
+ }).loose();
3217
+ var AssetDetailSchema = import_zod9.z.record(
3218
+ import_zod9.z.string(),
3219
+ import_zod9.z.object({
3220
+ minWithdrawAmount: import_zod9.z.string().transform(Number),
3221
+ depositStatus: import_zod9.z.boolean(),
3222
+ withdrawFee: import_zod9.z.number(),
3223
+ withdrawStatus: import_zod9.z.boolean(),
3224
+ depositTip: import_zod9.z.string().optional()
3225
+ }).loose()
3226
+ );
3227
+ var DustLogEntrySchema = import_zod9.z.object({
3228
+ transId: import_zod9.z.number(),
3229
+ serviceChargeAmount: import_zod9.z.string().transform(Number),
3230
+ amount: import_zod9.z.string().transform(Number),
3231
+ operateTime: import_zod9.z.string(),
3232
+ transferedAmount: import_zod9.z.string().transform(Number),
3233
+ fromAsset: import_zod9.z.string()
3234
+ }).loose();
3235
+ var DustLogResponseSchema = import_zod9.z.object({
3236
+ total: import_zod9.z.number(),
3237
+ userAssetDribblets: import_zod9.z.array(
3238
+ import_zod9.z.object({
3239
+ operateTime: import_zod9.z.number(),
3240
+ totalTransferedAmount: import_zod9.z.string().transform(Number),
3241
+ totalServiceChargeAmount: import_zod9.z.string().transform(Number),
3242
+ transId: import_zod9.z.number(),
3243
+ userAssetDribbletDetails: import_zod9.z.array(DustLogEntrySchema)
3244
+ })
3245
+ )
3246
+ });
3247
+ var DustConversionResultSchema = import_zod9.z.object({
3248
+ totalServiceCharge: import_zod9.z.string().transform(Number),
3249
+ totalTransfered: import_zod9.z.string().transform(Number),
3250
+ transferResult: import_zod9.z.array(
3251
+ import_zod9.z.object({
3252
+ amount: import_zod9.z.string().transform(Number),
3253
+ fromAsset: import_zod9.z.string(),
3254
+ operateTime: import_zod9.z.number(),
3255
+ serviceChargeAmount: import_zod9.z.string().transform(Number),
3256
+ tranId: import_zod9.z.number(),
3257
+ transferedAmount: import_zod9.z.string().transform(Number)
3258
+ }).loose()
3259
+ )
3260
+ }).loose();
3261
+ var TradeFeeEntrySchema = import_zod9.z.object({
3262
+ symbol: import_zod9.z.string(),
3263
+ makerCommission: import_zod9.z.string().transform(Number),
3264
+ takerCommission: import_zod9.z.string().transform(Number)
3265
+ });
3266
+ var TradeFeeResponseSchema = import_zod9.z.array(TradeFeeEntrySchema);
3267
+ var AccountSnapshotSchema = import_zod9.z.object({
3268
+ code: import_zod9.z.number(),
3269
+ msg: import_zod9.z.string(),
3270
+ snapshotVos: import_zod9.z.array(
3271
+ import_zod9.z.object({
3272
+ type: import_zod9.z.string(),
3273
+ updateTime: import_zod9.z.number(),
3274
+ data: import_zod9.z.record(import_zod9.z.string(), import_zod9.z.unknown())
3275
+ }).loose()
3276
+ )
3277
+ }).loose();
3278
+
3279
+ // src/resources/Wallet.ts
3280
+ var Wallet = class {
3281
+ constructor(http) {
3282
+ this.http = http;
3283
+ }
3284
+ async universalTransfer(params) {
3285
+ return UniversalTransferResultSchema.parse(
3286
+ await this.http.post("/sapi/v1/asset/transfer", params, "signed")
3287
+ );
3288
+ }
3289
+ async universalTransferHistory(options) {
3290
+ return UniversalTransferHistoryResponseSchema.parse(
3291
+ await this.http.get("/sapi/v1/asset/transfer", options, "signed")
3292
+ );
3293
+ }
3294
+ async fundingWallet(options) {
3295
+ return FundingAssetsResponseSchema.parse(
3296
+ await this.http.post("/sapi/v1/asset/get-funding-asset", options, "signed")
3297
+ );
3298
+ }
3299
+ async userAsset(options) {
3300
+ return UserAssetsResponseSchema.parse(
3301
+ await this.http.post("/sapi/v3/asset/getUserAsset", options, "signed")
3302
+ );
3303
+ }
3304
+ async depositHistory(options) {
3305
+ return DepositHistoryResponseSchema.parse(
3306
+ await this.http.get("/sapi/v1/capital/deposit/hisrec", options, "signed")
3307
+ );
3308
+ }
3309
+ async withdrawHistory(options) {
3310
+ return WithdrawHistoryResponseSchema.parse(
3311
+ await this.http.get("/sapi/v1/capital/withdraw/history", options, "signed")
3312
+ );
3313
+ }
3314
+ async withdraw(params) {
3315
+ return WithdrawResultSchema.parse(
3316
+ await this.http.post("/sapi/v1/capital/withdraw/apply", params, "signed")
3317
+ );
3318
+ }
3319
+ async depositAddress(coin, network) {
3320
+ return DepositAddressSchema.parse(
3321
+ await this.http.get("/sapi/v1/capital/deposit/address", { coin, network }, "signed")
3322
+ );
3323
+ }
3324
+ async accountSnapshot(type, options) {
3325
+ return AccountSnapshotSchema.parse(
3326
+ await this.http.get("/sapi/v1/accountSnapshot", { type, ...options }, "signed")
3327
+ );
3328
+ }
3329
+ async apiKeyPermissions() {
3330
+ return ApiKeyPermissionsSchema.parse(
3331
+ await this.http.get("/sapi/v1/account/apiRestrictions", void 0, "signed")
3332
+ );
3333
+ }
3334
+ async assetDetail(asset) {
3335
+ const params = asset ? { asset } : void 0;
3336
+ return AssetDetailSchema.parse(await this.http.get("/sapi/v1/asset/assetDetail", params, "signed"));
3337
+ }
3338
+ async dustLog(options) {
3339
+ return DustLogResponseSchema.parse(
3340
+ await this.http.get("/sapi/v1/asset/dribblet", options, "signed")
3341
+ );
3342
+ }
3343
+ async convertDustToBnb(assets, accountType) {
3344
+ return DustConversionResultSchema.parse(
3345
+ await this.http.post("/sapi/v1/asset/dust", { asset: assets, accountType }, "signed")
3346
+ );
3347
+ }
3348
+ async tradeFee(symbol3) {
3349
+ const params = symbol3 ? { symbol: symbol3 } : void 0;
3350
+ return TradeFeeResponseSchema.parse(await this.http.get("/sapi/v1/asset/tradeFee", params, "signed"));
3351
+ }
3352
+ };
3353
+
3354
+ // src/types/subaccount.types.ts
3355
+ var import_zod10 = require("zod");
3356
+ var SubAccountEntrySchema = import_zod10.z.object({
3357
+ email: import_zod10.z.string(),
3358
+ isFreeze: import_zod10.z.boolean(),
3359
+ createTime: import_zod10.z.number(),
3360
+ isManagedSubAccount: import_zod10.z.boolean().optional(),
3361
+ isAssetManagementSubAccount: import_zod10.z.boolean().optional(),
3362
+ type: import_zod10.z.string().optional()
3363
+ }).loose();
3364
+ var SubAccountListResponseSchema = import_zod10.z.object({
3365
+ subAccounts: import_zod10.z.array(SubAccountEntrySchema)
3366
+ });
3367
+ var SubAccountStatusSchema = import_zod10.z.object({
3368
+ email: import_zod10.z.string(),
3369
+ isSubUserEnabled: import_zod10.z.boolean(),
3370
+ isUserActive: import_zod10.z.boolean(),
3371
+ insertTime: import_zod10.z.number(),
3372
+ isMarginEnabled: import_zod10.z.boolean(),
3373
+ isFutureEnabled: import_zod10.z.boolean(),
3374
+ mobile: import_zod10.z.number().optional()
3375
+ }).loose();
3376
+ var SubAccountStatusResponseSchema = import_zod10.z.array(SubAccountStatusSchema);
3377
+ var SubAccountSpotAssetSchema = import_zod10.z.object({
3378
+ asset: import_zod10.z.string(),
3379
+ free: import_zod10.z.string().transform(Number),
3380
+ locked: import_zod10.z.string().transform(Number)
3381
+ });
3382
+ var SubAccountSpotAssetsResponseSchema = import_zod10.z.object({
3383
+ balances: import_zod10.z.array(SubAccountSpotAssetSchema)
3384
+ });
3385
+ var SubAccountSpotSummaryEntrySchema = import_zod10.z.object({
3386
+ email: import_zod10.z.string(),
3387
+ totalAsset: import_zod10.z.string().transform(Number)
3388
+ }).loose();
3389
+ var SubAccountSpotSummarySchema = import_zod10.z.object({
3390
+ totalCount: import_zod10.z.number(),
3391
+ masterAccountTotalAsset: import_zod10.z.string().transform(Number),
3392
+ spotSubUserAssetBtcVoList: import_zod10.z.array(SubAccountSpotSummaryEntrySchema)
3393
+ });
3394
+ var SubAccountFuturesSummarySchema = import_zod10.z.object({
3395
+ totalCount: import_zod10.z.number().optional(),
3396
+ totalMarginBalanceOfBTC: import_zod10.z.string().transform(Number).optional(),
3397
+ totalUnrealizedProfitOfBTC: import_zod10.z.string().transform(Number).optional(),
3398
+ totalWalletBalanceOfBTC: import_zod10.z.string().transform(Number).optional(),
3399
+ subAccountList: import_zod10.z.array(import_zod10.z.record(import_zod10.z.string(), import_zod10.z.unknown())).optional()
3400
+ }).loose();
3401
+ var SubAccountMarginAccountSchema = import_zod10.z.object({
3402
+ email: import_zod10.z.string(),
3403
+ marginLevel: import_zod10.z.string().transform(Number),
3404
+ totalAssetOfBtc: import_zod10.z.string().transform(Number),
3405
+ totalLiabilityOfBtc: import_zod10.z.string().transform(Number),
3406
+ totalNetAssetOfBtc: import_zod10.z.string().transform(Number),
3407
+ marginTradeCoeffVo: import_zod10.z.record(import_zod10.z.string(), import_zod10.z.unknown()).optional(),
3408
+ marginUserAssetVoList: import_zod10.z.array(import_zod10.z.record(import_zod10.z.string(), import_zod10.z.unknown())).optional()
3409
+ }).loose();
3410
+ var SubAccountUniversalTransferParamsSchema = import_zod10.z.object({
3411
+ fromEmail: import_zod10.z.string().optional(),
3412
+ toEmail: import_zod10.z.string().optional(),
3413
+ fromAccountType: import_zod10.z.enum(["SPOT", "USDT_FUTURE", "COIN_FUTURE", "MARGIN", "ISOLATED_MARGIN"]),
3414
+ toAccountType: import_zod10.z.enum(["SPOT", "USDT_FUTURE", "COIN_FUTURE", "MARGIN", "ISOLATED_MARGIN"]),
3415
+ symbol: import_zod10.z.string().optional(),
3416
+ asset: import_zod10.z.string(),
3417
+ amount: import_zod10.z.union([import_zod10.z.string(), import_zod10.z.number()]),
3418
+ clientTranId: import_zod10.z.string().optional()
3419
+ });
3420
+ var SubAccountUniversalTransferResultSchema = import_zod10.z.object({
3421
+ tranId: import_zod10.z.number(),
3422
+ clientTranId: import_zod10.z.string().optional()
3423
+ });
3424
+ var SubAccountUniversalTransferEntrySchema = import_zod10.z.object({
3425
+ tranId: import_zod10.z.number(),
3426
+ fromEmail: import_zod10.z.string(),
3427
+ toEmail: import_zod10.z.string(),
3428
+ asset: import_zod10.z.string(),
3429
+ amount: import_zod10.z.string().transform(Number),
3430
+ fromAccountType: import_zod10.z.string(),
3431
+ toAccountType: import_zod10.z.string(),
3432
+ status: import_zod10.z.string(),
3433
+ createTimeStamp: import_zod10.z.number(),
3434
+ clientTranId: import_zod10.z.string().optional()
3435
+ }).loose();
3436
+ var SubAccountUniversalTransferHistoryResponseSchema = import_zod10.z.object({
3437
+ result: import_zod10.z.array(SubAccountUniversalTransferEntrySchema),
3438
+ totalCount: import_zod10.z.number()
3439
+ });
3440
+ var VirtualSubAccountResultSchema = import_zod10.z.object({ email: import_zod10.z.string() });
3441
+ var SubAccountDepositAddressSchema = import_zod10.z.object({
3442
+ address: import_zod10.z.string(),
3443
+ coin: import_zod10.z.string(),
3444
+ tag: import_zod10.z.string(),
3445
+ url: import_zod10.z.string().optional()
3446
+ });
3447
+ var SubAccountDepositHistoryEntrySchema = import_zod10.z.object({
3448
+ id: import_zod10.z.string(),
3449
+ amount: import_zod10.z.string().transform(Number),
3450
+ coin: import_zod10.z.string(),
3451
+ network: import_zod10.z.string(),
3452
+ status: import_zod10.z.number(),
3453
+ address: import_zod10.z.string(),
3454
+ txId: import_zod10.z.string(),
3455
+ insertTime: import_zod10.z.number(),
3456
+ transferType: import_zod10.z.number()
3457
+ }).loose();
3458
+ var SubAccountDepositHistoryResponseSchema = import_zod10.z.array(SubAccountDepositHistoryEntrySchema);
3459
+ var SubAccountEnableResultSchema = import_zod10.z.object({
3460
+ email: import_zod10.z.string(),
3461
+ isFuturesEnabled: import_zod10.z.boolean().optional(),
3462
+ isMarginEnabled: import_zod10.z.boolean().optional()
3463
+ }).loose();
3464
+
3465
+ // src/resources/SubAccount.ts
3466
+ var SubAccount = class {
3467
+ constructor(http) {
3468
+ this.http = http;
3469
+ }
3470
+ async list(options) {
3471
+ const res = await this.http.get("/sapi/v1/sub-account/list", options, "signed");
3472
+ return SubAccountListResponseSchema.parse(res).subAccounts;
3473
+ }
3474
+ async status(email) {
3475
+ const params = email ? { email } : void 0;
3476
+ return SubAccountStatusResponseSchema.parse(
3477
+ await this.http.get("/sapi/v1/sub-account/status", params, "signed")
3478
+ );
3479
+ }
3480
+ async spotAssets(email) {
3481
+ return SubAccountSpotAssetsResponseSchema.parse(
3482
+ await this.http.get("/sapi/v3/sub-account/assets", { email }, "signed")
3483
+ );
3484
+ }
3485
+ async spotSummary(options) {
3486
+ return SubAccountSpotSummarySchema.parse(
3487
+ await this.http.get("/sapi/v1/sub-account/spotSummary", options, "signed")
3488
+ );
3489
+ }
3490
+ async futuresAccountSummary(futuresType) {
3491
+ return SubAccountFuturesSummarySchema.parse(
3492
+ await this.http.get("/sapi/v2/sub-account/futures/accountSummary", { futuresType }, "signed")
3493
+ );
3494
+ }
3495
+ async marginAccount(email) {
3496
+ return SubAccountMarginAccountSchema.parse(
3497
+ await this.http.get("/sapi/v1/sub-account/margin/account", { email }, "signed")
3498
+ );
3499
+ }
3500
+ async universalTransfer(params) {
3501
+ return SubAccountUniversalTransferResultSchema.parse(
3502
+ await this.http.post("/sapi/v1/sub-account/universalTransfer", params, "signed")
3503
+ );
3504
+ }
3505
+ async universalTransferHistory(options) {
3506
+ return SubAccountUniversalTransferHistoryResponseSchema.parse(
3507
+ await this.http.get("/sapi/v1/sub-account/universalTransfer", options, "signed")
3508
+ );
3509
+ }
3510
+ async createVirtualSubAccount(subAccountString) {
3511
+ return VirtualSubAccountResultSchema.parse(
3512
+ await this.http.post("/sapi/v1/sub-account/virtualSubAccount", { subAccountString }, "signed")
3513
+ );
3514
+ }
3515
+ async enableFutures(email) {
3516
+ return SubAccountEnableResultSchema.parse(
3517
+ await this.http.post("/sapi/v1/sub-account/futures/enable", { email }, "signed")
3518
+ );
3519
+ }
3520
+ async enableMargin(email) {
3521
+ return SubAccountEnableResultSchema.parse(
3522
+ await this.http.post("/sapi/v1/sub-account/margin/enable", { email }, "signed")
3523
+ );
3524
+ }
3525
+ async depositAddress(email, coin, network) {
3526
+ return SubAccountDepositAddressSchema.parse(
3527
+ await this.http.get("/sapi/v1/capital/deposit/subAddress", { email, coin, network }, "signed")
3528
+ );
3529
+ }
3530
+ async depositHistory(options) {
3531
+ return SubAccountDepositHistoryResponseSchema.parse(
3532
+ await this.http.get("/sapi/v1/capital/deposit/subHisrec", options, "signed")
3533
+ );
3534
+ }
3535
+ };
3536
+
3537
+ // src/ws/BaseWS.ts
3538
+ var import_node_events = require("events");
3539
+ var import_ws = __toESM(require("ws"), 1);
3540
+
3541
+ // src/types/ws.types.ts
3542
+ var import_zod11 = require("zod");
3543
+ var WsKlinePayloadSchema = import_zod11.z.object({
3544
+ e: import_zod11.z.literal("kline"),
3545
+ E: import_zod11.z.number(),
3546
+ s: import_zod11.z.string(),
3547
+ k: import_zod11.z.object({
3548
+ t: import_zod11.z.number(),
3549
+ T: import_zod11.z.number(),
3550
+ s: import_zod11.z.string(),
3551
+ i: import_zod11.z.string(),
3552
+ o: import_zod11.z.string().transform(Number),
3553
+ c: import_zod11.z.string().transform(Number),
3554
+ h: import_zod11.z.string().transform(Number),
3555
+ l: import_zod11.z.string().transform(Number),
3556
+ v: import_zod11.z.string().transform(Number),
3557
+ n: import_zod11.z.number(),
3558
+ x: import_zod11.z.boolean(),
3559
+ q: import_zod11.z.string().transform(Number),
3560
+ V: import_zod11.z.string().transform(Number),
3561
+ Q: import_zod11.z.string().transform(Number)
3562
+ })
3563
+ });
3564
+ var WsAggTradePayloadSchema = import_zod11.z.object({
3565
+ e: import_zod11.z.literal("aggTrade"),
3566
+ E: import_zod11.z.number(),
3567
+ s: import_zod11.z.string(),
3568
+ a: import_zod11.z.number(),
3569
+ p: import_zod11.z.string().transform(Number),
3570
+ q: import_zod11.z.string().transform(Number),
3571
+ f: import_zod11.z.number(),
3572
+ l: import_zod11.z.number(),
3573
+ T: import_zod11.z.number(),
3574
+ m: import_zod11.z.boolean()
3575
+ });
3576
+ var WsTradePayloadSchema = import_zod11.z.object({
3577
+ e: import_zod11.z.literal("trade"),
3578
+ E: import_zod11.z.number(),
3579
+ s: import_zod11.z.string(),
3580
+ t: import_zod11.z.number(),
3581
+ p: import_zod11.z.string().transform(Number),
3582
+ q: import_zod11.z.string().transform(Number),
3583
+ T: import_zod11.z.number(),
3584
+ m: import_zod11.z.boolean()
3585
+ });
3586
+ var WsDepthUpdatePayloadSchema = import_zod11.z.object({
3587
+ e: import_zod11.z.literal("depthUpdate"),
3588
+ E: import_zod11.z.number(),
3589
+ s: import_zod11.z.string(),
3590
+ U: import_zod11.z.number(),
3591
+ u: import_zod11.z.number(),
3592
+ T: import_zod11.z.number().optional(),
3593
+ pu: import_zod11.z.number().optional(),
3594
+ b: import_zod11.z.array(import_zod11.z.tuple([import_zod11.z.string(), import_zod11.z.string()])),
3595
+ a: import_zod11.z.array(import_zod11.z.tuple([import_zod11.z.string(), import_zod11.z.string()]))
3596
+ });
3597
+ var WsTicker24hrPayloadSchema = import_zod11.z.object({
3598
+ e: import_zod11.z.literal("24hrTicker"),
3599
+ E: import_zod11.z.number(),
3600
+ s: import_zod11.z.string(),
3601
+ p: import_zod11.z.string().transform(Number),
3602
+ P: import_zod11.z.string().transform(Number),
3603
+ c: import_zod11.z.string().transform(Number),
3604
+ o: import_zod11.z.string().transform(Number),
3605
+ h: import_zod11.z.string().transform(Number),
3606
+ l: import_zod11.z.string().transform(Number),
3607
+ v: import_zod11.z.string().transform(Number),
3608
+ q: import_zod11.z.string().transform(Number)
3609
+ });
3610
+ var WsBookTickerPayloadSchema = import_zod11.z.object({
3611
+ u: import_zod11.z.number(),
3612
+ s: import_zod11.z.string(),
3613
+ b: import_zod11.z.string().transform(Number),
3614
+ B: import_zod11.z.string().transform(Number),
3615
+ a: import_zod11.z.string().transform(Number),
3616
+ A: import_zod11.z.string().transform(Number)
3617
+ });
3618
+ var WsMarkPricePayloadSchema = import_zod11.z.object({
3619
+ e: import_zod11.z.literal("markPriceUpdate"),
3620
+ E: import_zod11.z.number(),
3621
+ s: import_zod11.z.string(),
3622
+ p: import_zod11.z.string().transform(Number),
3623
+ i: import_zod11.z.string().transform(Number),
3624
+ P: import_zod11.z.string().transform(Number),
3625
+ r: import_zod11.z.string().transform(Number),
3626
+ T: import_zod11.z.number()
3627
+ });
3628
+ var WsMiniTickerPayloadSchema = import_zod11.z.object({
3629
+ e: import_zod11.z.literal("24hrMiniTicker"),
3630
+ E: import_zod11.z.number(),
3631
+ s: import_zod11.z.string(),
3632
+ c: import_zod11.z.string().transform(Number),
3633
+ o: import_zod11.z.string().transform(Number),
3634
+ h: import_zod11.z.string().transform(Number),
3635
+ l: import_zod11.z.string().transform(Number),
3636
+ v: import_zod11.z.string().transform(Number),
3637
+ q: import_zod11.z.string().transform(Number)
3638
+ });
3639
+ var WsForceOrderPayloadSchema = import_zod11.z.object({
3640
+ e: import_zod11.z.literal("forceOrder"),
3641
+ E: import_zod11.z.number(),
3642
+ o: import_zod11.z.object({
3643
+ s: import_zod11.z.string(),
3644
+ S: import_zod11.z.string(),
3645
+ o: import_zod11.z.string(),
3646
+ f: import_zod11.z.string(),
3647
+ q: import_zod11.z.string().transform(Number),
3648
+ p: import_zod11.z.string().transform(Number),
3649
+ ap: import_zod11.z.string().transform(Number),
3650
+ X: import_zod11.z.string(),
3651
+ l: import_zod11.z.string().transform(Number),
3652
+ z: import_zod11.z.string().transform(Number),
3653
+ T: import_zod11.z.number()
3654
+ })
3655
+ });
3656
+ var WsCompositeIndexPayloadSchema = import_zod11.z.object({
3657
+ e: import_zod11.z.literal("compositeIndex"),
3658
+ E: import_zod11.z.number(),
3659
+ s: import_zod11.z.string(),
3660
+ p: import_zod11.z.string().transform(Number),
3661
+ c: import_zod11.z.array(
3662
+ import_zod11.z.object({
3663
+ b: import_zod11.z.string(),
3664
+ q: import_zod11.z.string(),
3665
+ w: import_zod11.z.string().transform(Number),
3666
+ p: import_zod11.z.string().transform(Number)
3667
+ })
3668
+ )
3669
+ });
3670
+ var WsAssetIndexPayloadSchema = import_zod11.z.object({
3671
+ e: import_zod11.z.literal("assetIndex"),
3672
+ E: import_zod11.z.number(),
3673
+ s: import_zod11.z.string(),
3674
+ i: import_zod11.z.string().transform(Number),
3675
+ b: import_zod11.z.string().transform(Number),
3676
+ a: import_zod11.z.string().transform(Number)
3677
+ });
3678
+ var WsRollingWindowTickerPayloadSchema = import_zod11.z.object({
3679
+ e: import_zod11.z.enum(["1hTicker", "4hTicker", "1dTicker", "7dTicker", "30dTicker"]),
3680
+ E: import_zod11.z.number(),
3681
+ s: import_zod11.z.string(),
3682
+ p: import_zod11.z.string().transform(Number),
3683
+ P: import_zod11.z.string().transform(Number),
3684
+ o: import_zod11.z.string().transform(Number),
3685
+ h: import_zod11.z.string().transform(Number),
3686
+ l: import_zod11.z.string().transform(Number),
3687
+ c: import_zod11.z.string().transform(Number),
3688
+ v: import_zod11.z.string().transform(Number),
3689
+ q: import_zod11.z.string().transform(Number),
3690
+ O: import_zod11.z.number(),
3691
+ C: import_zod11.z.number()
3692
+ });
3693
+ var WsSpotAvgPricePayloadSchema = import_zod11.z.object({
3694
+ e: import_zod11.z.literal("avgPrice"),
3695
+ E: import_zod11.z.number(),
3696
+ s: import_zod11.z.string(),
3697
+ i: import_zod11.z.string(),
3698
+ w: import_zod11.z.string().transform(Number),
3699
+ T: import_zod11.z.number()
3700
+ });
3701
+ function parseWsPayload(streamName, raw) {
3702
+ if (streamName.includes("@kline_")) return WsKlinePayloadSchema.parse(raw);
3703
+ if (streamName.includes("@continuousKline_") || streamName.includes("@indexPriceKline_") || streamName.includes("@markPriceKline_")) {
3704
+ return WsKlinePayloadSchema.parse(raw);
3705
+ }
3706
+ if (streamName.includes("@aggTrade")) return WsAggTradePayloadSchema.parse(raw);
3707
+ if (streamName.includes("@trade")) return WsTradePayloadSchema.parse(raw);
3708
+ if (streamName.includes("@depth")) return WsDepthUpdatePayloadSchema.parse(raw);
3709
+ if (streamName.includes("@bookTicker")) return WsBookTickerPayloadSchema.parse(raw);
3710
+ if (streamName.includes("@markPrice")) return WsMarkPricePayloadSchema.parse(raw);
3711
+ if (streamName.includes("@miniTicker")) return WsMiniTickerPayloadSchema.parse(raw);
3712
+ if (streamName.includes("@forceOrder")) return WsForceOrderPayloadSchema.parse(raw);
3713
+ if (streamName.includes("@compositeIndex")) return WsCompositeIndexPayloadSchema.parse(raw);
3714
+ if (streamName.includes("@assetIndex")) return WsAssetIndexPayloadSchema.parse(raw);
3715
+ if (streamName.includes("@avgPrice")) return WsSpotAvgPricePayloadSchema.parse(raw);
3716
+ if (streamName.includes("@ticker_")) return WsRollingWindowTickerPayloadSchema.parse(raw);
3717
+ if (streamName.includes("@ticker")) return WsTicker24hrPayloadSchema.parse(raw);
3718
+ throw new Error(`Unknown WS stream type: ${streamName}`);
3719
+ }
3720
+
3721
+ // src/ws/BaseWS.ts
3722
+ var BaseWS = class extends import_node_events.EventEmitter {
3723
+ constructor(options) {
3724
+ super();
3725
+ this.options = options;
3726
+ this.ws = null;
3727
+ this.streams = /* @__PURE__ */ new Set();
3728
+ this.reconnectAttempt = 0;
3729
+ this.closedByUser = false;
3730
+ }
3731
+ subscribe(streams) {
3732
+ streams.forEach((s) => this.streams.add(s));
3733
+ if (this.isOpen()) {
3734
+ this.send({ method: "SUBSCRIBE", params: streams, id: Date.now() });
3735
+ } else {
3736
+ this.connect();
3737
+ }
3738
+ }
3739
+ unsubscribe(streams) {
3740
+ streams.forEach((s) => this.streams.delete(s));
3741
+ if (this.isOpen()) {
3742
+ this.send({ method: "UNSUBSCRIBE", params: streams, id: Date.now() });
3743
+ }
3744
+ }
3745
+ close() {
3746
+ this.closedByUser = true;
3747
+ this.ws?.close();
3748
+ }
3749
+ reconnect() {
3750
+ if (this.ws?.readyState === import_ws.default.OPEN) this.ws.close();
3751
+ this.reconnectAttempt = 0;
3752
+ if (!this.closedByUser) this.connect();
3753
+ }
3754
+ resetReconnectAttempts() {
3755
+ this.reconnectAttempt = 0;
3756
+ }
3757
+ isOpen() {
3758
+ return this.ws?.readyState === import_ws.default.OPEN;
3759
+ }
3760
+ send(payload) {
3761
+ this.ws?.send(JSON.stringify(payload));
3762
+ }
3763
+ connect() {
3764
+ this.closedByUser = false;
3765
+ const url = `${this.options.baseStreamUrl}?streams=${[...this.streams].join("/")}`;
3766
+ this.ws = new import_ws.default(url);
3767
+ this.ws.on("open", () => {
3768
+ this.reconnectAttempt = 0;
3769
+ this.emit("open");
3770
+ });
3771
+ this.ws.on("message", (raw) => {
3772
+ this.handleMessage(raw.toString());
3773
+ });
3774
+ this.ws.on("close", () => {
3775
+ this.emit("close");
3776
+ if (!this.closedByUser) this.scheduleReconnect();
3777
+ });
3778
+ this.ws.on("error", (err) => {
3779
+ if (this.closedByUser) return;
3780
+ this.emit("error", err);
3781
+ });
3782
+ }
3783
+ handleMessage(raw) {
3784
+ let parsed;
3785
+ try {
3786
+ parsed = JSON.parse(raw);
3787
+ } catch {
3788
+ return;
3789
+ }
3790
+ if (!parsed.stream || parsed.data === void 0) return;
3791
+ try {
3792
+ const payload = parseWsPayload(parsed.stream, parsed.data);
3793
+ this.emit("message", parsed.stream, payload);
3794
+ this.emit(parsed.stream, payload);
3795
+ } catch (err) {
3796
+ this.emit("error", err);
3797
+ }
3798
+ }
3799
+ scheduleReconnect() {
3800
+ const base = this.options.reconnectDelayMs ?? 1e3;
3801
+ const max = this.options.maxReconnectDelayMs ?? 3e4;
3802
+ const delay = Math.min(base * 2 ** this.reconnectAttempt, max);
3803
+ this.reconnectAttempt += 1;
3804
+ setTimeout(() => {
3805
+ if (!this.closedByUser) this.connect();
3806
+ }, delay);
3807
+ }
3808
+ };
3809
+
3810
+ // src/ws/FuturesMarketWS.ts
3811
+ var FuturesMarketWS = class extends BaseWS {
3812
+ constructor(baseStreamUrl = "wss://fstream.binance.com/stream") {
3813
+ super({ baseStreamUrl });
3814
+ }
3815
+ kline(symbol3, interval) {
3816
+ return `${symbol3.toLowerCase()}@kline_${interval}`;
3817
+ }
3818
+ continuousKline(symbol3, contractType2, interval) {
3819
+ return `${symbol3.toLowerCase()}@continuousKline_${contractType2}_${interval}`;
3820
+ }
3821
+ indexPriceKline(symbol3, interval) {
3822
+ return `${symbol3.toLowerCase()}@indexPriceKline_${interval}`;
3823
+ }
3824
+ markPriceKline(symbol3, interval) {
3825
+ return `${symbol3.toLowerCase()}@markPriceKline_${interval}`;
3826
+ }
3827
+ aggTrade(symbol3) {
3828
+ return `${symbol3.toLowerCase()}@aggTrade`;
3829
+ }
3830
+ trade(symbol3) {
2327
3831
  return `${symbol3.toLowerCase()}@trade`;
2328
3832
  }
2329
3833
  depth(symbol3, level = 20) {
@@ -2469,48 +3973,185 @@ var SpotUserWS = class extends import_node_events2.EventEmitter {
2469
3973
  this.emit("error", err);
2470
3974
  });
2471
3975
  }
2472
- close() {
2473
- this.closedByUser = true;
2474
- this.ws?.close();
3976
+ close() {
3977
+ this.closedByUser = true;
3978
+ this.ws?.close();
3979
+ }
3980
+ reconnect() {
3981
+ if (this.ws?.readyState === import_ws2.default.OPEN) this.ws.close();
3982
+ this.reconnectAttempt = 0;
3983
+ if (!this.closedByUser) this.connect();
3984
+ }
3985
+ resetReconnectAttempts() {
3986
+ this.reconnectAttempt = 0;
3987
+ }
3988
+ handleMessage(raw) {
3989
+ let parsed;
3990
+ try {
3991
+ parsed = JSON.parse(raw);
3992
+ } catch {
3993
+ return;
3994
+ }
3995
+ try {
3996
+ const event = parseSpotUserDataEvent(parsed);
3997
+ this.emit(event.e, event);
3998
+ this.emit("userData", event);
3999
+ } catch (err) {
4000
+ this.emit("error", err);
4001
+ }
4002
+ }
4003
+ scheduleReconnect() {
4004
+ const base = this.options.reconnectDelayMs ?? 1e3;
4005
+ const max = this.options.maxReconnectDelayMs ?? 3e4;
4006
+ const delay = Math.min(base * 2 ** this.reconnectAttempt, max);
4007
+ this.reconnectAttempt += 1;
4008
+ setTimeout(() => {
4009
+ if (!this.closedByUser) this.connect();
4010
+ }, delay);
4011
+ }
4012
+ };
4013
+
4014
+ // src/ws/FuturesUserWS.ts
4015
+ var import_node_events3 = require("events");
4016
+ var import_ws3 = __toESM(require("ws"), 1);
4017
+ var FuturesUserWS = class extends import_node_events3.EventEmitter {
4018
+ constructor(options) {
4019
+ super();
4020
+ this.options = options;
4021
+ this.ws = null;
4022
+ this.reconnectAttempt = 0;
4023
+ this.closedByUser = false;
4024
+ }
4025
+ connect() {
4026
+ const listenKey = this.options.getListenKey();
4027
+ if (!listenKey) {
4028
+ this.emit("error", new Error("No listenKey available for user data stream"));
4029
+ return;
4030
+ }
4031
+ this.closedByUser = false;
4032
+ const url = `${this.options.baseUserUrl}/${listenKey}`;
4033
+ this.ws = new import_ws3.default(url);
4034
+ this.ws.on("open", () => {
4035
+ this.reconnectAttempt = 0;
4036
+ this.emit("open");
4037
+ });
4038
+ this.ws.on("message", (raw) => {
4039
+ this.handleMessage(raw.toString());
4040
+ });
4041
+ this.ws.on("close", () => {
4042
+ this.emit("close");
4043
+ if (!this.closedByUser) this.scheduleReconnect();
4044
+ });
4045
+ this.ws.on("error", (err) => {
4046
+ this.emit("error", err);
4047
+ });
4048
+ }
4049
+ close() {
4050
+ this.closedByUser = true;
4051
+ this.ws?.close();
4052
+ }
4053
+ reconnect() {
4054
+ if (this.ws?.readyState === import_ws3.default.OPEN) this.ws.close();
4055
+ this.reconnectAttempt = 0;
4056
+ if (!this.closedByUser) this.connect();
4057
+ }
4058
+ resetReconnectAttempts() {
4059
+ this.reconnectAttempt = 0;
4060
+ }
4061
+ handleMessage(raw) {
4062
+ let parsed;
4063
+ try {
4064
+ parsed = JSON.parse(raw);
4065
+ } catch {
4066
+ return;
4067
+ }
4068
+ try {
4069
+ const event = parseUserDataEvent(parsed);
4070
+ this.emit(event.e, event);
4071
+ this.emit("userData", event);
4072
+ } catch (err) {
4073
+ this.emit("error", err);
4074
+ }
4075
+ }
4076
+ scheduleReconnect() {
4077
+ const base = this.options.reconnectDelayMs ?? 1e3;
4078
+ const max = this.options.maxReconnectDelayMs ?? 3e4;
4079
+ const delay = Math.min(base * 2 ** this.reconnectAttempt, max);
4080
+ this.reconnectAttempt += 1;
4081
+ setTimeout(() => {
4082
+ if (!this.closedByUser) this.connect();
4083
+ }, delay);
4084
+ }
4085
+ };
4086
+
4087
+ // src/ws/CoinMMarketWS.ts
4088
+ var CoinMMarketWS = class extends BaseWS {
4089
+ constructor(baseStreamUrl = "wss://dstream.binance.com/stream") {
4090
+ super({ baseStreamUrl });
4091
+ }
4092
+ kline(symbol3, interval) {
4093
+ return `${symbol3.toLowerCase()}@kline_${interval}`;
4094
+ }
4095
+ continuousKline(pair, contractType2, interval) {
4096
+ return `${pair.toLowerCase()}_${contractType2}@continuousKline_${interval}`;
4097
+ }
4098
+ indexPriceKline(pair, interval) {
4099
+ return `${pair.toLowerCase()}@indexPriceKline_${interval}`;
4100
+ }
4101
+ markPriceKline(symbol3, interval) {
4102
+ return `${symbol3.toLowerCase()}@markPriceKline_${interval}`;
4103
+ }
4104
+ aggTrade(symbol3) {
4105
+ return `${symbol3.toLowerCase()}@aggTrade`;
4106
+ }
4107
+ trade(symbol3) {
4108
+ return `${symbol3.toLowerCase()}@trade`;
4109
+ }
4110
+ depth(symbol3, level = 20) {
4111
+ return `${symbol3.toLowerCase()}@depth${level}`;
4112
+ }
4113
+ depthDiff(symbol3) {
4114
+ return `${symbol3.toLowerCase()}@depth`;
4115
+ }
4116
+ depthDiffSpeed(symbol3, updateSpeed) {
4117
+ return `${symbol3.toLowerCase()}@depth@${updateSpeed}`;
4118
+ }
4119
+ ticker(symbol3) {
4120
+ return `${symbol3.toLowerCase()}@ticker`;
4121
+ }
4122
+ allMarketTickers() {
4123
+ return "!ticker@arr";
4124
+ }
4125
+ miniTicker(symbol3) {
4126
+ return `${symbol3.toLowerCase()}@miniTicker`;
4127
+ }
4128
+ allMiniTickers() {
4129
+ return "!miniTicker@arr";
4130
+ }
4131
+ bookTicker(symbol3) {
4132
+ return `${symbol3.toLowerCase()}@bookTicker`;
2475
4133
  }
2476
- reconnect() {
2477
- if (this.ws?.readyState === import_ws2.default.OPEN) this.ws.close();
2478
- this.reconnectAttempt = 0;
2479
- if (!this.closedByUser) this.connect();
4134
+ allBookTickers() {
4135
+ return "!bookTicker";
2480
4136
  }
2481
- resetReconnectAttempts() {
2482
- this.reconnectAttempt = 0;
4137
+ markPrice(symbol3, updateSpeed = "3s") {
4138
+ return `${symbol3.toLowerCase()}@markPrice@${updateSpeed}`;
2483
4139
  }
2484
- handleMessage(raw) {
2485
- let parsed;
2486
- try {
2487
- parsed = JSON.parse(raw);
2488
- } catch {
2489
- return;
2490
- }
2491
- try {
2492
- const event = parseSpotUserDataEvent(parsed);
2493
- this.emit(event.e, event);
2494
- this.emit("userData", event);
2495
- } catch (err) {
2496
- this.emit("error", err);
2497
- }
4140
+ markPriceForPair(pair, updateSpeed = "3s") {
4141
+ return `${pair.toLowerCase()}@markPrice@${updateSpeed}`;
2498
4142
  }
2499
- scheduleReconnect() {
2500
- const base = this.options.reconnectDelayMs ?? 1e3;
2501
- const max = this.options.maxReconnectDelayMs ?? 3e4;
2502
- const delay = Math.min(base * 2 ** this.reconnectAttempt, max);
2503
- this.reconnectAttempt += 1;
2504
- setTimeout(() => {
2505
- if (!this.closedByUser) this.connect();
2506
- }, delay);
4143
+ liquidationOrder(symbol3) {
4144
+ return `${symbol3.toLowerCase()}@forceOrder`;
4145
+ }
4146
+ allLiquidationOrders() {
4147
+ return "!forceOrder@arr";
2507
4148
  }
2508
4149
  };
2509
4150
 
2510
- // src/ws/FuturesUserWS.ts
2511
- var import_node_events3 = require("events");
2512
- var import_ws3 = __toESM(require("ws"), 1);
2513
- var FuturesUserWS = class extends import_node_events3.EventEmitter {
4151
+ // src/ws/CoinMUserWS.ts
4152
+ var import_node_events4 = require("events");
4153
+ var import_ws4 = __toESM(require("ws"), 1);
4154
+ var CoinMUserWS = class extends import_node_events4.EventEmitter {
2514
4155
  constructor(options) {
2515
4156
  super();
2516
4157
  this.options = options;
@@ -2521,12 +4162,12 @@ var FuturesUserWS = class extends import_node_events3.EventEmitter {
2521
4162
  connect() {
2522
4163
  const listenKey = this.options.getListenKey();
2523
4164
  if (!listenKey) {
2524
- this.emit("error", new Error("No listenKey available for user data stream"));
4165
+ this.emit("error", new Error("No listenKey available for COIN-M user data stream"));
2525
4166
  return;
2526
4167
  }
2527
4168
  this.closedByUser = false;
2528
4169
  const url = `${this.options.baseUserUrl}/${listenKey}`;
2529
- this.ws = new import_ws3.default(url);
4170
+ this.ws = new import_ws4.default(url);
2530
4171
  this.ws.on("open", () => {
2531
4172
  this.reconnectAttempt = 0;
2532
4173
  this.emit("open");
@@ -2547,7 +4188,7 @@ var FuturesUserWS = class extends import_node_events3.EventEmitter {
2547
4188
  this.ws?.close();
2548
4189
  }
2549
4190
  reconnect() {
2550
- if (this.ws?.readyState === import_ws3.default.OPEN) this.ws.close();
4191
+ if (this.ws?.readyState === import_ws4.default.OPEN) this.ws.close();
2551
4192
  this.reconnectAttempt = 0;
2552
4193
  if (!this.closedByUser) this.connect();
2553
4194
  }
@@ -2582,31 +4223,36 @@ var FuturesUserWS = class extends import_node_events3.EventEmitter {
2582
4223
 
2583
4224
  // src/ws/WsApi.ts
2584
4225
  var import_node_crypto2 = require("crypto");
2585
- var import_ws4 = __toESM(require("ws"), 1);
4226
+ var import_ws5 = __toESM(require("ws"), 1);
2586
4227
  function buildQueryString(data) {
2587
4228
  return Object.entries(data).filter(([, val]) => val !== void 0 && val !== null).map(([key, val]) => `${key}=${encodeURIComponent(String(val))}`).join("&");
2588
4229
  }
2589
4230
  var WsApi = class {
2590
4231
  constructor(options) {
2591
4232
  this.options = options;
4233
+ this.signer = new Signer({
4234
+ algorithm: options.signatureAlgorithm,
4235
+ apiSecret: options.apiSecret,
4236
+ privateKey: options.privateKey
4237
+ });
2592
4238
  }
2593
4239
  async request(method, params = {}, options) {
2594
- const { apiKey, apiSecret } = this.options;
4240
+ const { apiKey } = this.options;
2595
4241
  const signed = options?.signed ?? true;
2596
4242
  const { id = (0, import_node_crypto2.randomUUID)(), ...methodParams } = params;
2597
4243
  const requestParams = { ...methodParams };
2598
4244
  if (signed) {
2599
- if (!apiKey || !apiSecret) {
2600
- throw new Error("API key and secret required for signed WebSocket API requests");
4245
+ if (!apiKey || !this.signer.canSign()) {
4246
+ throw new Error("API key and secret (or privateKey) required for signed WebSocket API requests");
2601
4247
  }
2602
4248
  requestParams.apiKey = apiKey;
2603
4249
  requestParams.timestamp = Date.now();
2604
4250
  requestParams.recvWindow = this.options.recvWindow ?? 5e3;
2605
4251
  const queryString = buildQueryString(requestParams);
2606
- requestParams.signature = (0, import_node_crypto2.createHmac)("sha256", apiSecret).update(queryString).digest("hex");
4252
+ requestParams.signature = this.signer.sign(queryString);
2607
4253
  }
2608
4254
  return new Promise((resolve, reject) => {
2609
- const ws = new import_ws4.default(this.options.baseUrl);
4255
+ const ws = new import_ws5.default(this.options.baseUrl);
2610
4256
  const timeout = setTimeout(() => {
2611
4257
  ws.close();
2612
4258
  reject(new NetworkError(`WebSocket API request timed out: ${method}`));
@@ -2707,6 +4353,174 @@ var WsApi = class {
2707
4353
  }
2708
4354
  };
2709
4355
 
4356
+ // src/ws/SpotWsApi.ts
4357
+ var import_node_crypto3 = require("crypto");
4358
+ var import_ws6 = __toESM(require("ws"), 1);
4359
+ function buildQueryString2(data) {
4360
+ return Object.entries(data).filter(([, val]) => val !== void 0 && val !== null).map(([key, val]) => `${key}=${encodeURIComponent(String(val))}`).join("&");
4361
+ }
4362
+ var SpotWsApi = class {
4363
+ constructor(options) {
4364
+ this.options = options;
4365
+ this.signer = new Signer({
4366
+ algorithm: options.signatureAlgorithm,
4367
+ apiSecret: options.apiSecret,
4368
+ privateKey: options.privateKey
4369
+ });
4370
+ }
4371
+ async request(method, params = {}, options) {
4372
+ const { apiKey } = this.options;
4373
+ const signed = options?.signed ?? true;
4374
+ const { id = (0, import_node_crypto3.randomUUID)(), ...methodParams } = params;
4375
+ const requestParams = { ...methodParams };
4376
+ if (signed) {
4377
+ if (!apiKey || !this.signer.canSign()) {
4378
+ throw new Error("API key and secret (or privateKey) required for signed WebSocket API requests");
4379
+ }
4380
+ requestParams.apiKey = apiKey;
4381
+ requestParams.timestamp = Date.now();
4382
+ requestParams.recvWindow = this.options.recvWindow ?? 5e3;
4383
+ const queryString = buildQueryString2(requestParams);
4384
+ requestParams.signature = this.signer.sign(queryString);
4385
+ }
4386
+ return new Promise((resolve, reject) => {
4387
+ const ws = new import_ws6.default(this.options.baseUrl);
4388
+ const timeout = setTimeout(() => {
4389
+ ws.close();
4390
+ reject(new NetworkError(`WebSocket API request timed out: ${method}`));
4391
+ }, this.options.timeoutMs ?? 15e3);
4392
+ ws.on("open", () => ws.send(JSON.stringify({ id, method, params: requestParams })));
4393
+ ws.on("message", (raw) => {
4394
+ clearTimeout(timeout);
4395
+ ws.close();
4396
+ try {
4397
+ const parsed = JSON.parse(raw.toString());
4398
+ if (parsed.status >= 400) {
4399
+ reject(new Error(parsed.error?.msg ?? `WebSocket API error: ${method}`));
4400
+ } else {
4401
+ resolve(parsed);
4402
+ }
4403
+ } catch (err) {
4404
+ reject(new NetworkError("Invalid WebSocket API JSON payload", err));
4405
+ }
4406
+ });
4407
+ ws.on("error", (err) => {
4408
+ clearTimeout(timeout);
4409
+ reject(new NetworkError(err.message, err));
4410
+ });
4411
+ });
4412
+ }
4413
+ // ---- Trading (signed) ----
4414
+ placeOrder(params) {
4415
+ return this.request("order.place", params);
4416
+ }
4417
+ testOrder(params) {
4418
+ return this.request("order.test", params);
4419
+ }
4420
+ cancelOrder(params) {
4421
+ return this.request("order.cancel", params);
4422
+ }
4423
+ cancelReplaceOrder(params) {
4424
+ return this.request("order.cancelReplace", params);
4425
+ }
4426
+ orderStatus(params) {
4427
+ return this.request("order.status", params);
4428
+ }
4429
+ openOrdersStatus(params = {}) {
4430
+ return this.request("openOrders.status", params);
4431
+ }
4432
+ cancelOpenOrders(params) {
4433
+ return this.request("openOrders.cancelAll", params);
4434
+ }
4435
+ placeOrderList(params) {
4436
+ return this.request("orderList.place", params);
4437
+ }
4438
+ cancelOrderList(params) {
4439
+ return this.request("orderList.cancel", params);
4440
+ }
4441
+ orderListStatus(params) {
4442
+ return this.request("orderList.status", params);
4443
+ }
4444
+ openOrderListsStatus() {
4445
+ return this.request("openOrderLists.status", {});
4446
+ }
4447
+ // ---- Account (signed) ----
4448
+ accountStatus() {
4449
+ return this.request("account.status", {});
4450
+ }
4451
+ accountCommission(params) {
4452
+ return this.request("account.commission", params);
4453
+ }
4454
+ accountRateLimitsOrders() {
4455
+ return this.request("account.rateLimits.orders", {});
4456
+ }
4457
+ allOrders(params) {
4458
+ return this.request("allOrders", params);
4459
+ }
4460
+ allOrderLists(params = {}) {
4461
+ return this.request("allOrderLists", params);
4462
+ }
4463
+ myTrades(params) {
4464
+ return this.request("myTrades", params);
4465
+ }
4466
+ // ---- User data stream (managed listen keys) ----
4467
+ userDataStreamStart() {
4468
+ return this.request("userDataStream.start", {});
4469
+ }
4470
+ userDataStreamPing(listenKey) {
4471
+ return this.request("userDataStream.ping", { listenKey });
4472
+ }
4473
+ userDataStreamStop(listenKey) {
4474
+ return this.request("userDataStream.stop", { listenKey });
4475
+ }
4476
+ // ---- Public market data (no signature required) ----
4477
+ ping() {
4478
+ return this.request("ping", {}, { signed: false });
4479
+ }
4480
+ time() {
4481
+ return this.request("time", {}, { signed: false });
4482
+ }
4483
+ exchangeInfo(params = {}) {
4484
+ return this.request("exchangeInfo", params, { signed: false });
4485
+ }
4486
+ depth(params) {
4487
+ return this.request("depth", params, { signed: false });
4488
+ }
4489
+ recentTrades(params) {
4490
+ return this.request("trades.recent", params, { signed: false });
4491
+ }
4492
+ historicalTrades(params) {
4493
+ return this.request("trades.historical", params, { signed: false });
4494
+ }
4495
+ aggTrades(params) {
4496
+ return this.request("trades.aggregate", params, { signed: false });
4497
+ }
4498
+ klines(params) {
4499
+ return this.request("klines", params, { signed: false });
4500
+ }
4501
+ uiKlines(params) {
4502
+ return this.request("uiKlines", params, { signed: false });
4503
+ }
4504
+ avgPrice(params) {
4505
+ return this.request("avgPrice", params, { signed: false });
4506
+ }
4507
+ ticker24hr(params = {}) {
4508
+ return this.request("ticker.24hr", params, { signed: false });
4509
+ }
4510
+ tickerTradingDay(params) {
4511
+ return this.request("ticker.tradingDay", params, { signed: false });
4512
+ }
4513
+ tickerPrice(params = {}) {
4514
+ return this.request("ticker.price", params, { signed: false });
4515
+ }
4516
+ tickerBook(params = {}) {
4517
+ return this.request("ticker.book", params, { signed: false });
4518
+ }
4519
+ ticker(params) {
4520
+ return this.request("ticker", params, { signed: false });
4521
+ }
4522
+ };
4523
+
2710
4524
  // src/client/BinanceClient.ts
2711
4525
  var BinanceClient = class {
2712
4526
  constructor(options = {}) {
@@ -2714,18 +4528,29 @@ var BinanceClient = class {
2714
4528
  this.keepAliveInterval = null;
2715
4529
  this.spotListenKeyValue = null;
2716
4530
  this.spotKeepAliveInterval = null;
4531
+ this.coinmListenKeyValue = null;
4532
+ this.coinmKeepAliveInterval = null;
2717
4533
  const { endpoints } = resolveEnvironment(options);
4534
+ this.policy = options.safety ? new TradingPolicy(options.safety) : void 0;
2718
4535
  const httpOptions = {
4536
+ policy: this.policy,
2719
4537
  apiKey: options.apiKey,
2720
4538
  apiSecret: options.apiSecret,
4539
+ privateKey: options.privateKey,
4540
+ signatureAlgorithm: options.signatureAlgorithm,
2721
4541
  recvWindow: options.recvWindow ?? 5e3,
2722
4542
  timeoutMs: options.timeoutMs ?? 15e3,
2723
4543
  maxRetries: options.maxRetries ?? 3,
2724
4544
  retryBaseDelayMs: options.retryBaseDelayMs,
2725
- retryMaxDelayMs: options.retryMaxDelayMs
4545
+ retryMaxDelayMs: options.retryMaxDelayMs,
4546
+ rateLimitWeightPerMinute: options.rateLimitWeightPerMinute,
4547
+ rateLimitSafetyMargin: options.rateLimitSafetyMargin,
4548
+ httpsAgent: options.httpsAgent,
4549
+ proxy: options.proxy
2726
4550
  };
2727
4551
  this.authHttp = new HttpClient({ baseURL: endpoints.restRoot, ...httpOptions });
2728
- const spotHttp = new HttpClient({ baseURL: endpoints.restSpot, ...httpOptions });
4552
+ this.spotHttp = new HttpClient({ baseURL: endpoints.restSpot, ...httpOptions });
4553
+ const spotHttp = this.spotHttp;
2729
4554
  this.spot = {
2730
4555
  market: new SpotMarket(spotHttp),
2731
4556
  account: new SpotAccount(spotHttp),
@@ -2735,6 +4560,14 @@ var BinanceClient = class {
2735
4560
  wsUser: new SpotUserWS({
2736
4561
  baseUserUrl: endpoints.wsSpotUser,
2737
4562
  getListenKey: () => this.spotListenKeyValue
4563
+ }),
4564
+ wsApi: new SpotWsApi({
4565
+ baseUrl: endpoints.wsSpotApi,
4566
+ apiKey: options.apiKey,
4567
+ apiSecret: options.apiSecret,
4568
+ privateKey: options.privateKey,
4569
+ signatureAlgorithm: options.signatureAlgorithm,
4570
+ recvWindow: options.recvWindow
2738
4571
  })
2739
4572
  };
2740
4573
  const futuresMarket = new FuturesMarket(
@@ -2764,9 +4597,30 @@ var BinanceClient = class {
2764
4597
  baseUrl: endpoints.wsApi,
2765
4598
  apiKey: options.apiKey,
2766
4599
  apiSecret: options.apiSecret,
4600
+ privateKey: options.privateKey,
4601
+ signatureAlgorithm: options.signatureAlgorithm,
2767
4602
  recvWindow: options.recvWindow
2768
4603
  })
2769
4604
  };
4605
+ this.dapiHttp = new HttpClient({ baseURL: endpoints.restDapiRoot, ...httpOptions });
4606
+ this.coinm = {
4607
+ market: new CoinMMarket(new HttpClient({ baseURL: endpoints.restDapi, ...httpOptions })),
4608
+ account: new CoinMAccount(this.dapiHttp),
4609
+ trading: new CoinMTrading(this.dapiHttp),
4610
+ userStream: new CoinMUserDataStream(this.dapiHttp),
4611
+ ws: new CoinMMarketWS(endpoints.wsDapiMarket),
4612
+ wsUser: new CoinMUserWS({
4613
+ baseUserUrl: endpoints.wsDapiUser,
4614
+ getListenKey: () => this.coinmListenKeyValue
4615
+ })
4616
+ };
4617
+ this.sapiHttp = new HttpClient({ baseURL: endpoints.restApiRoot, ...httpOptions });
4618
+ this.margin = {
4619
+ account: new MarginAccount(this.sapiHttp),
4620
+ trading: new MarginTrading(this.sapiHttp)
4621
+ };
4622
+ this.wallet = new Wallet(this.sapiHttp);
4623
+ this.subaccount = new SubAccount(this.sapiHttp);
2770
4624
  }
2771
4625
  static nowSeconds() {
2772
4626
  return Math.floor(Date.now() / 1e3);
@@ -2783,6 +4637,31 @@ var BinanceClient = class {
2783
4637
  const dir = side3 === "buy" ? 1 : -1;
2784
4638
  return dir === 1 ? entryPrice * (1 - 1 / leverage + mm) : entryPrice * (1 + 1 / leverage - mm);
2785
4639
  }
4640
+ /**
4641
+ * Syncs local time against each REST host's server clock and stores the offset, applied to
4642
+ * every subsequent signed request's `timestamp` param. Call this once after construction to
4643
+ * mitigate `-1021` errors caused by local clock drift.
4644
+ */
4645
+ async syncTime() {
4646
+ await Promise.all([
4647
+ this.authHttp.syncTime("/fapi/v1/time"),
4648
+ this.spotHttp.syncTime("/time"),
4649
+ this.dapiHttp.syncTime("/dapi/v1/time"),
4650
+ this.sapiHttp.syncTime("/api/v3/time")
4651
+ ]);
4652
+ }
4653
+ /**
4654
+ * Snapshot of the most recently observed `X-MBX-USED-WEIGHT-*` / `X-MBX-ORDER-COUNT-*`
4655
+ * response headers, per REST host. Each host tracks its own weight budget independently.
4656
+ */
4657
+ getRateLimitUsage() {
4658
+ return {
4659
+ spot: this.spotHttp.getRateLimitUsage(),
4660
+ futures: this.authHttp.getRateLimitUsage(),
4661
+ coinm: this.dapiHttp.getRateLimitUsage(),
4662
+ sapi: this.sapiHttp.getRateLimitUsage()
4663
+ };
4664
+ }
2786
4665
  async startUserStream() {
2787
4666
  const { listenKey } = await this.futures.userStream.createListenKey();
2788
4667
  this.listenKeyValue = listenKey;
@@ -2819,25 +4698,50 @@ var BinanceClient = class {
2819
4698
  });
2820
4699
  this.spotListenKeyValue = null;
2821
4700
  }
4701
+ async startCoinMUserStream() {
4702
+ const { listenKey } = await this.coinm.userStream.createListenKey();
4703
+ this.coinmListenKeyValue = listenKey;
4704
+ this.coinmKeepAliveInterval = setInterval(() => {
4705
+ this.coinm.userStream.keepAliveListenKey().catch(() => {
4706
+ });
4707
+ }, 30 * 60 * 1e3);
4708
+ this.coinm.wsUser.connect();
4709
+ return listenKey;
4710
+ }
4711
+ closeCoinMUserStream() {
4712
+ if (this.coinmKeepAliveInterval) clearInterval(this.coinmKeepAliveInterval);
4713
+ this.coinmKeepAliveInterval = null;
4714
+ this.coinm.wsUser.close();
4715
+ this.coinm.userStream.closeListenKey().catch(() => {
4716
+ });
4717
+ this.coinmListenKeyValue = null;
4718
+ }
2822
4719
  closeAllWebSockets() {
2823
4720
  this.futures.ws.close();
2824
4721
  this.futures.wsUser.close();
2825
4722
  this.spot.ws.close();
2826
4723
  this.spot.wsUser.close();
4724
+ this.coinm.ws.close();
4725
+ this.coinm.wsUser.close();
2827
4726
  this.closeUserStream();
2828
4727
  this.closeSpotUserStream();
4728
+ this.closeCoinMUserStream();
2829
4729
  }
2830
4730
  reconnectWebSocket(target) {
2831
4731
  if (target === "ws") this.futures.ws.reconnect();
2832
4732
  else if (target === "wsUser") this.futures.wsUser.reconnect();
2833
4733
  else if (target === "spot") this.spot.ws.reconnect();
2834
- else this.spot.wsUser.reconnect();
4734
+ else if (target === "spotUser") this.spot.wsUser.reconnect();
4735
+ else if (target === "coinm") this.coinm.ws.reconnect();
4736
+ else this.coinm.wsUser.reconnect();
2835
4737
  }
2836
4738
  resetReconnectAttempts() {
2837
4739
  this.futures.ws.resetReconnectAttempts();
2838
4740
  this.futures.wsUser.resetReconnectAttempts();
2839
4741
  this.spot.ws.resetReconnectAttempts();
2840
4742
  this.spot.wsUser.resetReconnectAttempts();
4743
+ this.coinm.ws.resetReconnectAttempts();
4744
+ this.coinm.wsUser.resetReconnectAttempts();
2841
4745
  }
2842
4746
  };
2843
4747
 
@@ -3025,15 +4929,15 @@ var PaperTradingEngine = class {
3025
4929
  };
3026
4930
 
3027
4931
  // src/tools/account.tools.ts
3028
- var import_zod9 = require("zod");
4932
+ var import_zod13 = require("zod");
3029
4933
 
3030
4934
  // src/tools/types.ts
3031
- var import_zod8 = require("zod");
4935
+ var import_zod12 = require("zod");
3032
4936
  function normalizeSymbol(value) {
3033
4937
  return String(value ?? "").trim().toUpperCase();
3034
4938
  }
3035
4939
  function toJsonSchema(inputSchema) {
3036
- return import_zod8.z.toJSONSchema(inputSchema, { target: "json" });
4940
+ return import_zod12.z.toJSONSchema(inputSchema, { target: "json" });
3037
4941
  }
3038
4942
  function toOpenAITool(tool) {
3039
4943
  return {
@@ -3068,248 +4972,248 @@ function textResult(data) {
3068
4972
  }
3069
4973
 
3070
4974
  // src/tools/account.tools.ts
3071
- var optionalSymbol = import_zod9.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT").optional();
3072
- var limit = import_zod9.z.number().int().positive().max(1e3).default(100);
3073
- var startTime = import_zod9.z.number().int().positive().optional();
3074
- var endTime = import_zod9.z.number().int().positive().optional();
4975
+ var optionalSymbol = import_zod13.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT").optional();
4976
+ var limit = import_zod13.z.number().int().positive().max(1e3).default(100);
4977
+ var startTime = import_zod13.z.number().int().positive().optional();
4978
+ var endTime = import_zod13.z.number().int().positive().optional();
3075
4979
  function accountTools(client) {
3076
4980
  const a = client.futures.account;
3077
4981
  return [
3078
4982
  {
3079
4983
  name: "futures_balance",
3080
4984
  description: "Get futures account balances (v3): asset, wallet balance, unrealized profit, margin balance, available balance (signed).",
3081
- inputSchema: import_zod9.z.object({}),
4985
+ inputSchema: import_zod13.z.object({}),
3082
4986
  handler: async () => textResult(await a.balanceV3())
3083
4987
  },
3084
4988
  {
3085
4989
  name: "futures_account",
3086
4990
  description: "Get full account information (v3): total wallet/margin balance, unrealized profit, available balance, assets & positions (signed).",
3087
- inputSchema: import_zod9.z.object({}),
4991
+ inputSchema: import_zod13.z.object({}),
3088
4992
  handler: async () => textResult(await a.accountV3())
3089
4993
  },
3090
4994
  {
3091
4995
  name: "futures_balance_v2",
3092
4996
  description: "Get futures account balance (v2 legacy) per asset (signed).",
3093
- inputSchema: import_zod9.z.object({}),
4997
+ inputSchema: import_zod13.z.object({}),
3094
4998
  handler: async () => textResult(await a.balance())
3095
4999
  },
3096
5000
  {
3097
5001
  name: "futures_account_v2",
3098
5002
  description: "Get futures account information (v2 legacy) (signed).",
3099
- inputSchema: import_zod9.z.object({}),
5003
+ inputSchema: import_zod13.z.object({}),
3100
5004
  handler: async () => textResult(await a.account())
3101
5005
  },
3102
5006
  {
3103
5007
  name: "futures_position_risk",
3104
5008
  description: "Get current open positions (v3): symbol, side, size, entry price, mark price, liquidation price, leverage, unrealized PnL, margin (signed).",
3105
- inputSchema: import_zod9.z.object({ symbol: optionalSymbol }),
5009
+ inputSchema: import_zod13.z.object({ symbol: optionalSymbol }),
3106
5010
  handler: async ({ symbol: symbol3 }) => textResult(await a.positionRiskV3(symbol3 ? normalizeSymbol(symbol3) : void 0))
3107
5011
  },
3108
5012
  {
3109
5013
  name: "futures_income_history",
3110
5014
  description: "Get futures income history (realized PnL, funding fees, commissions, transfers, insurance clearing). incomeType examples: TRANSFER, REALIZED_PNL, FUNDING_FEE, COMMISSION, INSURANCE_CLEAR, REFERRAL_KICKBACK (signed).",
3111
- inputSchema: import_zod9.z.object({ symbol: optionalSymbol, incomeType: import_zod9.z.string().optional().describe("e.g. TRANSFER, REALIZED_PNL, FUNDING_FEE, COMMISSION"), startTime, endTime, limit: limit.default(100) }),
5015
+ inputSchema: import_zod13.z.object({ symbol: optionalSymbol, incomeType: import_zod13.z.string().optional().describe("e.g. TRANSFER, REALIZED_PNL, FUNDING_FEE, COMMISSION"), startTime, endTime, limit: limit.default(100) }),
3112
5016
  handler: async ({ symbol: symbol3, incomeType, startTime: startTime5, endTime: endTime5, limit: limit4 }) => textResult(await a.incomeHistory({ symbol: symbol3 ? normalizeSymbol(symbol3) : void 0, incomeType, startTime: startTime5, endTime: endTime5, limit: Number(limit4) }))
3113
5017
  },
3114
5018
  {
3115
5019
  name: "futures_user_trades",
3116
5020
  description: "Get account trade list (filled trades) for a symbol with optional time range (signed).",
3117
- inputSchema: import_zod9.z.object({ symbol: import_zod9.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT"), startTime, endTime, limit: limit.default(100), fromId: import_zod9.z.number().int().positive().optional() }),
5021
+ inputSchema: import_zod13.z.object({ symbol: import_zod13.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT"), startTime, endTime, limit: limit.default(100), fromId: import_zod13.z.number().int().positive().optional() }),
3118
5022
  handler: async ({ symbol: symbol3, startTime: startTime5, endTime: endTime5, limit: limit4, fromId }) => textResult(await a.userTrades({ symbol: normalizeSymbol(symbol3), startTime: startTime5, endTime: endTime5, limit: Number(limit4), fromId }))
3119
5023
  },
3120
5024
  {
3121
5025
  name: "futures_leverage_brackets",
3122
5026
  description: "Get notional and leverage brackets for one symbol or all: tier caps, maintenance margin rate, max leverage (signed).",
3123
- inputSchema: import_zod9.z.object({ symbol: optionalSymbol }),
5027
+ inputSchema: import_zod13.z.object({ symbol: optionalSymbol }),
3124
5028
  handler: async ({ symbol: symbol3 }) => textResult(await a.leverageBrackets(symbol3 ? normalizeSymbol(symbol3) : void 0))
3125
5029
  },
3126
5030
  {
3127
5031
  name: "futures_commission_rate",
3128
5032
  description: "Get user commission rate (taker & maker fee) for a symbol (signed).",
3129
- inputSchema: import_zod9.z.object({ symbol: import_zod9.z.string().min(1).describe("USD-M pair, e.g. ETHUSDT") }),
5033
+ inputSchema: import_zod13.z.object({ symbol: import_zod13.z.string().min(1).describe("USD-M pair, e.g. ETHUSDT") }),
3130
5034
  handler: async ({ symbol: symbol3 }) => textResult(await a.commissionRate(normalizeSymbol(symbol3)))
3131
5035
  },
3132
5036
  {
3133
5037
  name: "futures_multi_assets_mode",
3134
5038
  description: "Get current multi-assets margin mode status (signed).",
3135
- inputSchema: import_zod9.z.object({}),
5039
+ inputSchema: import_zod13.z.object({}),
3136
5040
  handler: async () => textResult(await a.multiAssetsMargin())
3137
5041
  },
3138
5042
  {
3139
5043
  name: "futures_set_multi_assets_mode",
3140
5044
  description: "Enable or disable multi-assets mode (signed; 7-day cooldown between toggles).",
3141
- inputSchema: import_zod9.z.object({ enabled: import_zod9.z.boolean().describe("true to enable, false to disable") }),
5045
+ inputSchema: import_zod13.z.object({ enabled: import_zod13.z.boolean().describe("true to enable, false to disable") }),
3142
5046
  handler: async ({ enabled }) => textResult(await a.setMultiAssetsMargin(enabled))
3143
5047
  },
3144
5048
  {
3145
5049
  name: "futures_fee_burn_status",
3146
5050
  description: "Get BNB fee burn status for futures trades (signed).",
3147
- inputSchema: import_zod9.z.object({}),
5051
+ inputSchema: import_zod13.z.object({}),
3148
5052
  handler: async () => textResult(await a.feeBurnStatus())
3149
5053
  },
3150
5054
  {
3151
5055
  name: "futures_set_fee_burn",
3152
5056
  description: "Toggle BNB fee burn on futures trades (signed).",
3153
- inputSchema: import_zod9.z.object({ enabled: import_zod9.z.boolean().describe("true to enable fee burn") }),
5057
+ inputSchema: import_zod13.z.object({ enabled: import_zod13.z.boolean().describe("true to enable fee burn") }),
3154
5058
  handler: async ({ enabled }) => textResult(await a.setFeeBurnStatus(enabled))
3155
5059
  },
3156
5060
  {
3157
5061
  name: "futures_position_mode",
3158
5062
  description: "Get current position mode: one-way (BOTH) or hedge mode (LONG/SHORT) (signed).",
3159
- inputSchema: import_zod9.z.object({}),
5063
+ inputSchema: import_zod13.z.object({}),
3160
5064
  handler: async () => textResult(await a.positionMode())
3161
5065
  },
3162
5066
  {
3163
5067
  name: "futures_set_position_mode",
3164
5068
  description: "Change position mode: hedgeMode true = dual side (hedge), false = one-way (signed; 30-day cooldown).",
3165
- inputSchema: import_zod9.z.object({ hedgeMode: import_zod9.z.boolean().describe("true = hedge mode, false = one-way") }),
5069
+ inputSchema: import_zod13.z.object({ hedgeMode: import_zod13.z.boolean().describe("true = hedge mode, false = one-way") }),
3166
5070
  handler: async ({ hedgeMode }) => textResult(await a.setPositionMode(hedgeMode))
3167
5071
  },
3168
5072
  {
3169
5073
  name: "futures_api_trading_status",
3170
5074
  description: "Get futures trading quantitative rules indicators and disable intervals (signed).",
3171
- inputSchema: import_zod9.z.object({}),
5075
+ inputSchema: import_zod13.z.object({}),
3172
5076
  handler: async () => textResult(await a.apiTradingStatus())
3173
5077
  },
3174
5078
  {
3175
5079
  name: "futures_position_margin_history",
3176
5080
  description: "Get isolated position margin change history. type: 1 = add margin, 2 = reduce margin (signed).",
3177
- inputSchema: import_zod9.z.object({ symbol: import_zod9.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT"), type: import_zod9.z.enum(["1", "2"]).describe("1 = add margin, 2 = reduce margin"), startTime, endTime, limit: limit.default(50) }),
5081
+ inputSchema: import_zod13.z.object({ symbol: import_zod13.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT"), type: import_zod13.z.enum(["1", "2"]).describe("1 = add margin, 2 = reduce margin"), startTime, endTime, limit: limit.default(50) }),
3178
5082
  handler: async ({ symbol: symbol3, type, startTime: startTime5, endTime: endTime5, limit: limit4 }) => textResult(await a.positionMarginHistory({ symbol: normalizeSymbol(symbol3), type: Number(type), startTime: startTime5, endTime: endTime5, limit: Number(limit4) }))
3179
5083
  },
3180
5084
  {
3181
5085
  name: "futures_rate_limit_order",
3182
5086
  description: "Query the current user order rate limit usage (signed).",
3183
- inputSchema: import_zod9.z.object({}),
5087
+ inputSchema: import_zod13.z.object({}),
3184
5088
  handler: async () => textResult(await a.rateLimitOrder())
3185
5089
  },
3186
5090
  {
3187
5091
  name: "futures_request_order_download",
3188
5092
  description: "Request a futures order-history download (async, 7-day window). Returns a downloadId (signed).",
3189
- inputSchema: import_zod9.z.object({ symbol: optionalSymbol, startTime, endTime }),
5093
+ inputSchema: import_zod13.z.object({ symbol: optionalSymbol, startTime, endTime }),
3190
5094
  handler: async ({ symbol: symbol3, startTime: startTime5, endTime: endTime5 }) => textResult(await a.requestOrderDownload({ symbol: symbol3 ? normalizeSymbol(symbol3) : void 0, startTime: startTime5, endTime: endTime5 }))
3191
5095
  },
3192
5096
  {
3193
5097
  name: "futures_order_download_status",
3194
5098
  description: "Get the futures order-history download link by downloadId (signed).",
3195
- inputSchema: import_zod9.z.object({ downloadId: import_zod9.z.string().min(1) }),
5099
+ inputSchema: import_zod13.z.object({ downloadId: import_zod13.z.string().min(1) }),
3196
5100
  handler: async ({ downloadId }) => textResult(await a.getOrderDownloadStatus(downloadId))
3197
5101
  },
3198
5102
  {
3199
5103
  name: "futures_request_trade_download",
3200
5104
  description: "Request a futures trade-history download (async, 7-day window). Returns a downloadId (signed).",
3201
- inputSchema: import_zod9.z.object({ symbol: optionalSymbol, startTime, endTime }),
5105
+ inputSchema: import_zod13.z.object({ symbol: optionalSymbol, startTime, endTime }),
3202
5106
  handler: async ({ symbol: symbol3, startTime: startTime5, endTime: endTime5 }) => textResult(await a.requestTradeDownload({ symbol: symbol3 ? normalizeSymbol(symbol3) : void 0, startTime: startTime5, endTime: endTime5 }))
3203
5107
  },
3204
5108
  {
3205
5109
  name: "futures_trade_download_status",
3206
5110
  description: "Get the futures trade-history download link by downloadId (signed).",
3207
- inputSchema: import_zod9.z.object({ downloadId: import_zod9.z.string().min(1) }),
5111
+ inputSchema: import_zod13.z.object({ downloadId: import_zod13.z.string().min(1) }),
3208
5112
  handler: async ({ downloadId }) => textResult(await a.getTradeDownloadStatus(downloadId))
3209
5113
  },
3210
5114
  {
3211
5115
  name: "futures_account_config",
3212
5116
  description: "Get futures account configuration: fee tier, trading permissions, dual-side position setting (signed).",
3213
- inputSchema: import_zod9.z.object({}),
5117
+ inputSchema: import_zod13.z.object({}),
3214
5118
  handler: async () => textResult(await a.accountConfig())
3215
5119
  },
3216
5120
  {
3217
5121
  name: "futures_portfolio_margin_account_info",
3218
5122
  description: "Get Portfolio Margin account info for an asset: cross margin balance and liability (signed).",
3219
- inputSchema: import_zod9.z.object({ asset: import_zod9.z.string().min(1).describe("Asset, e.g. USDT") }),
5123
+ inputSchema: import_zod13.z.object({ asset: import_zod13.z.string().min(1).describe("Asset, e.g. USDT") }),
3220
5124
  handler: async ({ asset }) => textResult(await a.pmAccountInfo(asset))
3221
5125
  },
3222
5126
  {
3223
5127
  name: "futures_request_income_download",
3224
5128
  description: "Request a futures income/transaction-history download (async). Returns a downloadId (signed).",
3225
- inputSchema: import_zod9.z.object({ startTime: startTime.unwrap(), endTime: endTime.unwrap() }),
5129
+ inputSchema: import_zod13.z.object({ startTime: startTime.unwrap(), endTime: endTime.unwrap() }),
3226
5130
  handler: async ({ startTime: startTime5, endTime: endTime5 }) => textResult(await a.requestIncomeDownload({ startTime: startTime5, endTime: endTime5 }))
3227
5131
  },
3228
5132
  {
3229
5133
  name: "futures_income_download_status",
3230
5134
  description: "Get the futures income/transaction-history download link by downloadId (signed).",
3231
- inputSchema: import_zod9.z.object({ downloadId: import_zod9.z.string().min(1) }),
5135
+ inputSchema: import_zod13.z.object({ downloadId: import_zod13.z.string().min(1) }),
3232
5136
  handler: async ({ downloadId }) => textResult(await a.getIncomeDownloadStatus(downloadId))
3233
5137
  }
3234
5138
  ];
3235
5139
  }
3236
5140
 
3237
5141
  // src/tools/derived.tools.ts
3238
- var import_zod10 = require("zod");
3239
- var symbol = import_zod10.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT");
5142
+ var import_zod14 = require("zod");
5143
+ var symbol = import_zod14.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT");
3240
5144
  function derivedTools(client) {
3241
5145
  const ops = client.futures.ops;
3242
5146
  return [
3243
5147
  {
3244
5148
  name: "futures_symbol_rules",
3245
5149
  description: "Get the tradeable rules for a symbol in one call: tick size, step size, min/max quantity, market-order lot bounds and minimum notional, flattened out of exchangeInfo filters. Call this before sizing or pricing any order.",
3246
- inputSchema: import_zod10.z.object({ symbol, refresh: import_zod10.z.boolean().default(false).describe("Bypass the 60s cache") }),
5150
+ inputSchema: import_zod14.z.object({ symbol, refresh: import_zod14.z.boolean().default(false).describe("Bypass the 60s cache") }),
3247
5151
  handler: async ({ symbol: s, refresh }) => textResult(await ops.symbolRules(normalizeSymbol(s), { refresh }))
3248
5152
  },
3249
5153
  {
3250
5154
  name: "futures_quantize",
3251
5155
  description: "Round a price to the symbol's tick size and a quantity to its step size, returning exchange-ready strings. Use this instead of rounding numbers yourself \u2014 Binance rejects off-tick prices (-1111).",
3252
- inputSchema: import_zod10.z.object({
5156
+ inputSchema: import_zod14.z.object({
3253
5157
  symbol,
3254
- price: import_zod10.z.number().positive().optional(),
3255
- quantity: import_zod10.z.number().positive().optional(),
3256
- marketOrder: import_zod10.z.boolean().default(false).describe("Use MARKET_LOT_SIZE bounds instead of LOT_SIZE")
5158
+ price: import_zod14.z.number().positive().optional(),
5159
+ quantity: import_zod14.z.number().positive().optional(),
5160
+ marketOrder: import_zod14.z.boolean().default(false).describe("Use MARKET_LOT_SIZE bounds instead of LOT_SIZE")
3257
5161
  }),
3258
5162
  handler: async ({ symbol: s, price, quantity, marketOrder }) => textResult(await ops.quantize(normalizeSymbol(s), { price, quantity, marketOrder }))
3259
5163
  },
3260
5164
  {
3261
5165
  name: "futures_size_position",
3262
5166
  description: "Convert a risk budget into an exchange-ready order quantity. Given a stop price and either riskAmount (quote currency) or riskPct (percent of available balance), returns the quantity rounded down to the symbol step size, plus the notional, required margin and every constraint that failed (min notional, lot bounds, wrong-side stop). Never increases risk to satisfy a minimum \u2014 it reports instead.",
3263
- inputSchema: import_zod10.z.object({
5167
+ inputSchema: import_zod14.z.object({
3264
5168
  symbol,
3265
- side: import_zod10.z.enum(["BUY", "SELL"]),
3266
- stopPrice: import_zod10.z.number().positive().describe("Protective stop price"),
3267
- entryPrice: import_zod10.z.number().positive().optional().describe("Defaults to current mark price"),
3268
- riskAmount: import_zod10.z.number().positive().optional().describe("Quote-currency amount to risk, e.g. 50 USDT"),
3269
- riskPct: import_zod10.z.number().positive().max(100).optional().describe("Percent of available balance to risk (signed call)"),
3270
- leverage: import_zod10.z.number().int().min(1).max(125).optional().describe("Used to report required margin"),
3271
- marketOrder: import_zod10.z.boolean().default(false)
5169
+ side: import_zod14.z.enum(["BUY", "SELL"]),
5170
+ stopPrice: import_zod14.z.number().positive().describe("Protective stop price"),
5171
+ entryPrice: import_zod14.z.number().positive().optional().describe("Defaults to current mark price"),
5172
+ riskAmount: import_zod14.z.number().positive().optional().describe("Quote-currency amount to risk, e.g. 50 USDT"),
5173
+ riskPct: import_zod14.z.number().positive().max(100).optional().describe("Percent of available balance to risk (signed call)"),
5174
+ leverage: import_zod14.z.number().int().min(1).max(125).optional().describe("Used to report required margin"),
5175
+ marketOrder: import_zod14.z.boolean().default(false)
3272
5176
  }),
3273
5177
  handler: async (args) => textResult(await ops.sizePosition({ ...args, symbol: normalizeSymbol(args.symbol) }))
3274
5178
  },
3275
5179
  {
3276
5180
  name: "futures_close_position",
3277
5181
  description: "Flatten an open position with a reduce-only market order. Reads the current position, derives the closing side from its sign, and automatically uses reduceOnly in one-way mode vs positionSide in hedge mode (Binance rejects the wrong one). Set dryRun to preview the order without sending it. Signed, destructive.",
3278
- inputSchema: import_zod10.z.object({
5182
+ inputSchema: import_zod14.z.object({
3279
5183
  symbol,
3280
- positionSide: import_zod10.z.enum(["BOTH", "LONG", "SHORT"]).optional().describe("Required when hedge mode has both sides open"),
3281
- portion: import_zod10.z.number().positive().max(1).default(1).describe("Fraction of the position to close, e.g. 0.5 for half"),
3282
- dryRun: import_zod10.z.boolean().default(false)
5184
+ positionSide: import_zod14.z.enum(["BOTH", "LONG", "SHORT"]).optional().describe("Required when hedge mode has both sides open"),
5185
+ portion: import_zod14.z.number().positive().max(1).default(1).describe("Fraction of the position to close, e.g. 0.5 for half"),
5186
+ dryRun: import_zod14.z.boolean().default(false)
3283
5187
  }),
3284
5188
  handler: async (args) => textResult(await ops.closePosition({ ...args, symbol: normalizeSymbol(args.symbol) }))
3285
5189
  },
3286
5190
  {
3287
5191
  name: "futures_market_snapshot",
3288
5192
  description: "One-call market picture for a symbol: 24h stats, mark/index price with funding, open interest and long/short positioning. Replaces four separate primitive calls; individual feeds degrade to an error field rather than failing the whole snapshot.",
3289
- inputSchema: import_zod10.z.object({
5193
+ inputSchema: import_zod14.z.object({
3290
5194
  symbol,
3291
- period: import_zod10.z.enum(["5m", "15m", "30m", "1h", "2h", "4h", "6h", "12h", "1d"]).default("1h")
5195
+ period: import_zod14.z.enum(["5m", "15m", "30m", "1h", "2h", "4h", "6h", "12h", "1d"]).default("1h")
3292
5196
  }),
3293
5197
  handler: async ({ symbol: s, period: period2 }) => textResult(await ops.marketSnapshot(normalizeSymbol(s), { period: period2 }))
3294
5198
  },
3295
5199
  {
3296
5200
  name: "futures_account_overview",
3297
5201
  description: "One-call account picture: funded balances, open positions only (zero-size entries filtered out), working orders, and totals for unrealized PnL and gross notional. Signed.",
3298
- inputSchema: import_zod10.z.object({}),
5202
+ inputSchema: import_zod14.z.object({}),
3299
5203
  handler: async () => textResult(await ops.accountOverview())
3300
5204
  },
3301
5205
  {
3302
5206
  name: "futures_place_bracket_order",
3303
5207
  description: "Place an entry order together with its protective stop-loss and optional take-profit, with all prices quantized to the symbol tick. Returns each leg separately; if a protective leg fails the response is flagged protectionComplete=false and the entry is NOT auto-cancelled (it may already have filled). Signed, destructive.",
3304
- inputSchema: import_zod10.z.object({
5208
+ inputSchema: import_zod14.z.object({
3305
5209
  symbol,
3306
- side: import_zod10.z.enum(["BUY", "SELL"]),
3307
- quantity: import_zod10.z.union([import_zod10.z.string(), import_zod10.z.number()]),
3308
- entryPrice: import_zod10.z.number().positive().optional().describe("Omit for a MARKET entry"),
3309
- stopLossPrice: import_zod10.z.number().positive(),
3310
- takeProfitPrice: import_zod10.z.number().positive().optional(),
3311
- positionSide: import_zod10.z.enum(["BOTH", "LONG", "SHORT"]).optional(),
3312
- workingType: import_zod10.z.enum(["MARK_PRICE", "CONTRACT_PRICE"]).default("MARK_PRICE")
5210
+ side: import_zod14.z.enum(["BUY", "SELL"]),
5211
+ quantity: import_zod14.z.union([import_zod14.z.string(), import_zod14.z.number()]),
5212
+ entryPrice: import_zod14.z.number().positive().optional().describe("Omit for a MARKET entry"),
5213
+ stopLossPrice: import_zod14.z.number().positive(),
5214
+ takeProfitPrice: import_zod14.z.number().positive().optional(),
5215
+ positionSide: import_zod14.z.enum(["BOTH", "LONG", "SHORT"]).optional(),
5216
+ workingType: import_zod14.z.enum(["MARK_PRICE", "CONTRACT_PRICE"]).default("MARK_PRICE")
3313
5217
  }),
3314
5218
  handler: async (args) => textResult(await ops.placeBracketOrder({ ...args, symbol: normalizeSymbol(args.symbol) }))
3315
5219
  }
@@ -3317,14 +5221,14 @@ function derivedTools(client) {
3317
5221
  }
3318
5222
 
3319
5223
  // src/tools/market-data.tools.ts
3320
- var import_zod11 = require("zod");
5224
+ var import_zod15 = require("zod");
3321
5225
  var u = (s) => s.optional();
3322
- var optSymbol = u(import_zod11.z.string().min(1)).describe("USD-M pair, e.g. BTCUSDT");
3323
- var limitDefault = import_zod11.z.number().int().positive().max(1500).default(100);
3324
- var startTime2 = import_zod11.z.number().int().positive().optional();
3325
- var endTime2 = import_zod11.z.number().int().positive().optional();
3326
- var period = import_zod11.z.enum(["5m", "15m", "30m", "1h", "2h", "4h", "6h", "12h", "1d"]).default("1h");
3327
- var contractType = import_zod11.z.enum(["perpetual", "current_quarter", "next_quarter"]).default("perpetual");
5226
+ var optSymbol = u(import_zod15.z.string().min(1)).describe("USD-M pair, e.g. BTCUSDT");
5227
+ var limitDefault = import_zod15.z.number().int().positive().max(1500).default(100);
5228
+ var startTime2 = import_zod15.z.number().int().positive().optional();
5229
+ var endTime2 = import_zod15.z.number().int().positive().optional();
5230
+ var period = import_zod15.z.enum(["5m", "15m", "30m", "1h", "2h", "4h", "6h", "12h", "1d"]).default("1h");
5231
+ var contractType = import_zod15.z.enum(["perpetual", "current_quarter", "next_quarter"]).default("perpetual");
3328
5232
  function marketDataTools(client) {
3329
5233
  const m = client.futures.market;
3330
5234
  const d = client.futures.data;
@@ -3332,65 +5236,65 @@ function marketDataTools(client) {
3332
5236
  {
3333
5237
  name: "futures_ping",
3334
5238
  description: "Test connectivity to the Binance USD-M futures REST API. Returns empty object {} on success.",
3335
- inputSchema: import_zod11.z.object({}),
5239
+ inputSchema: import_zod15.z.object({}),
3336
5240
  handler: async () => textResult(await m.ping())
3337
5241
  },
3338
5242
  {
3339
5243
  name: "futures_server_time",
3340
5244
  description: "Get the current Binance USD-M futures server time in milliseconds since epoch.",
3341
- inputSchema: import_zod11.z.object({}),
5245
+ inputSchema: import_zod15.z.object({}),
3342
5246
  handler: async () => textResult(await m.serverTime())
3343
5247
  },
3344
5248
  {
3345
5249
  name: "futures_exchange_info",
3346
5250
  description: "Get exchange trading rules and symbol metadata: contract type, status, base/quote assets, price/quantity filters, tick size, step size, notional and leverage brackets, delivery dates.",
3347
- inputSchema: import_zod11.z.object({}),
5251
+ inputSchema: import_zod15.z.object({}),
3348
5252
  handler: async () => textResult(await m.exchangeInfo())
3349
5253
  },
3350
5254
  {
3351
5255
  name: "futures_ticker_price",
3352
5256
  description: "Get latest price for one symbol (v1).",
3353
- inputSchema: import_zod11.z.object({ symbol: import_zod11.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT") }),
5257
+ inputSchema: import_zod15.z.object({ symbol: import_zod15.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT") }),
3354
5258
  handler: async ({ symbol: symbol3 }) => textResult(await m.tickerPrice(normalizeSymbol(symbol3)))
3355
5259
  },
3356
5260
  {
3357
5261
  name: "futures_ticker_price_v2",
3358
5262
  description: "Get latest price for one symbol, or for all symbols when symbol is omitted (v2 endpoint). Use all-symbols mode for market overviews.",
3359
- inputSchema: import_zod11.z.object({ symbol: optSymbol }),
5263
+ inputSchema: import_zod15.z.object({ symbol: optSymbol }),
3360
5264
  handler: async ({ symbol: symbol3 }) => textResult(await m.tickerPriceV2(symbol3 ? normalizeSymbol(symbol3) : void 0))
3361
5265
  },
3362
5266
  {
3363
5267
  name: "futures_ticker_24hr",
3364
5268
  description: "Get 24-hour rolling price change statistics for a symbol: price change %, high, low, volume, quote volume, open interest.",
3365
- inputSchema: import_zod11.z.object({ symbol: import_zod11.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT") }),
5269
+ inputSchema: import_zod15.z.object({ symbol: import_zod15.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT") }),
3366
5270
  handler: async ({ symbol: symbol3 }) => textResult(await m.ticker24hr(normalizeSymbol(symbol3)))
3367
5271
  },
3368
5272
  {
3369
5273
  name: "futures_book_ticker",
3370
5274
  description: "Get best bid/ask (top of book) for a single symbol (v1).",
3371
- inputSchema: import_zod11.z.object({ symbol: import_zod11.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT") }),
5275
+ inputSchema: import_zod15.z.object({ symbol: import_zod15.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT") }),
3372
5276
  handler: async ({ symbol: symbol3 }) => textResult(await m.bookTicker(normalizeSymbol(symbol3)))
3373
5277
  },
3374
5278
  {
3375
5279
  name: "futures_book_ticker_v2",
3376
5280
  description: "Get best bid/ask (top of book) for one symbol, or all symbols when omitted (v2 endpoint).",
3377
- inputSchema: import_zod11.z.object({ symbol: optSymbol }),
5281
+ inputSchema: import_zod15.z.object({ symbol: optSymbol }),
3378
5282
  handler: async ({ symbol: symbol3 }) => textResult(await m.bookTickerV2(symbol3 ? normalizeSymbol(symbol3) : void 0))
3379
5283
  },
3380
5284
  {
3381
5285
  name: "futures_order_book",
3382
5286
  description: "Get order book depth for a symbol. Limits: 5, 10, 20, 50, 100, 500, 1000.",
3383
- inputSchema: import_zod11.z.object({
3384
- symbol: import_zod11.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT"),
3385
- limit: import_zod11.z.enum(["5", "10", "20", "50", "100", "500", "1000"]).default("100")
5287
+ inputSchema: import_zod15.z.object({
5288
+ symbol: import_zod15.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT"),
5289
+ limit: import_zod15.z.enum(["5", "10", "20", "50", "100", "500", "1000"]).default("100")
3386
5290
  }),
3387
5291
  handler: async ({ symbol: symbol3, limit: limit4 }) => textResult(await m.depth(normalizeSymbol(symbol3), Number(limit4)))
3388
5292
  },
3389
5293
  {
3390
5294
  name: "futures_recent_trades",
3391
5295
  description: "Get the most recent executed trades for a symbol (public endpoint).",
3392
- inputSchema: import_zod11.z.object({
3393
- symbol: import_zod11.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT"),
5296
+ inputSchema: import_zod15.z.object({
5297
+ symbol: import_zod15.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT"),
3394
5298
  limit: limitDefault.default(500)
3395
5299
  }),
3396
5300
  handler: async ({ symbol: symbol3, limit: limit4 }) => textResult(await m.trades(normalizeSymbol(symbol3), Number(limit4)))
@@ -3398,30 +5302,30 @@ function marketDataTools(client) {
3398
5302
  {
3399
5303
  name: "futures_historical_trades",
3400
5304
  description: "Get older trades for a symbol by fromId (older than recent).",
3401
- inputSchema: import_zod11.z.object({
3402
- symbol: import_zod11.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT"),
5305
+ inputSchema: import_zod15.z.object({
5306
+ symbol: import_zod15.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT"),
3403
5307
  limit: limitDefault.default(500),
3404
- fromId: import_zod11.z.number().int().positive().optional()
5308
+ fromId: import_zod15.z.number().int().positive().optional()
3405
5309
  }),
3406
5310
  handler: async ({ symbol: symbol3, limit: limit4, fromId }) => textResult(await m.historicalTrades(normalizeSymbol(symbol3), { limit: Number(limit4), fromId }))
3407
5311
  },
3408
5312
  {
3409
5313
  name: "futures_agg_trades",
3410
5314
  description: "Get compressed/aggregate trades for a symbol within an optional time window. Each entry aggregates trades with the same price and side.",
3411
- inputSchema: import_zod11.z.object({ symbol: import_zod11.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT"), limit: limitDefault.default(500), startTime: startTime2, endTime: endTime2 }),
5315
+ inputSchema: import_zod15.z.object({ symbol: import_zod15.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT"), limit: limitDefault.default(500), startTime: startTime2, endTime: endTime2 }),
3412
5316
  handler: async ({ symbol: symbol3, limit: limit4, startTime: startTime5, endTime: endTime5 }) => textResult(await m.aggTrades(normalizeSymbol(symbol3), { limit: Number(limit4), startTime: startTime5, endTime: endTime5 }))
3413
5317
  },
3414
5318
  {
3415
5319
  name: "futures_klines",
3416
5320
  description: "Get candlestick (OHLCV) data for a symbol. Intervals: 1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,1M. Max 1500 per request.",
3417
- inputSchema: import_zod11.z.object({ symbol: import_zod11.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT"), interval: KlineIntervalSchema, limit: limitDefault.default(500), startTime: startTime2, endTime: endTime2 }),
5321
+ inputSchema: import_zod15.z.object({ symbol: import_zod15.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT"), interval: KlineIntervalSchema, limit: limitDefault.default(500), startTime: startTime2, endTime: endTime2 }),
3418
5322
  handler: async ({ symbol: symbol3, interval, limit: limit4, startTime: startTime5, endTime: endTime5 }) => textResult(await m.klines(normalizeSymbol(symbol3), interval, { limit: Number(limit4), startTime: startTime5, endTime: endTime5 }))
3419
5323
  },
3420
5324
  {
3421
5325
  name: "futures_continuous_klines",
3422
5326
  description: "Get klines for a continuous contract (perpetual, current_quarter, next_quarter) identified by base pair (e.g. BTCUSDT).",
3423
- inputSchema: import_zod11.z.object({
3424
- symbol: import_zod11.z.string().min(1).describe("Base pair, e.g. BTCUSDT"),
5327
+ inputSchema: import_zod15.z.object({
5328
+ symbol: import_zod15.z.string().min(1).describe("Base pair, e.g. BTCUSDT"),
3425
5329
  contractType,
3426
5330
  interval: KlineIntervalSchema,
3427
5331
  limit: limitDefault.default(500),
@@ -3433,80 +5337,80 @@ function marketDataTools(client) {
3433
5337
  {
3434
5338
  name: "futures_index_price_klines",
3435
5339
  description: "Get index price candlesticks for a pair (e.g. BTCUSDT index).",
3436
- inputSchema: import_zod11.z.object({ symbol: import_zod11.z.string().min(1).describe("Base pair, e.g. BTCUSDT"), interval: KlineIntervalSchema, limit: limitDefault.default(500), startTime: startTime2, endTime: endTime2 }),
5340
+ inputSchema: import_zod15.z.object({ symbol: import_zod15.z.string().min(1).describe("Base pair, e.g. BTCUSDT"), interval: KlineIntervalSchema, limit: limitDefault.default(500), startTime: startTime2, endTime: endTime2 }),
3437
5341
  handler: async ({ symbol: symbol3, interval, limit: limit4, startTime: startTime5, endTime: endTime5 }) => textResult(await m.indexPriceKlines(normalizeSymbol(symbol3), interval, { limit: Number(limit4), startTime: startTime5, endTime: endTime5 }))
3438
5342
  },
3439
5343
  {
3440
5344
  name: "futures_mark_price_klines",
3441
5345
  description: "Get mark price candlesticks for a symbol.",
3442
- inputSchema: import_zod11.z.object({ symbol: import_zod11.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT"), interval: KlineIntervalSchema, limit: limitDefault.default(500), startTime: startTime2, endTime: endTime2 }),
5346
+ inputSchema: import_zod15.z.object({ symbol: import_zod15.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT"), interval: KlineIntervalSchema, limit: limitDefault.default(500), startTime: startTime2, endTime: endTime2 }),
3443
5347
  handler: async ({ symbol: symbol3, interval, limit: limit4, startTime: startTime5, endTime: endTime5 }) => textResult(await m.markPriceKlines(normalizeSymbol(symbol3), interval, { limit: Number(limit4), startTime: startTime5, endTime: endTime5 }))
3444
5348
  },
3445
5349
  {
3446
5350
  name: "futures_trading_day_ticker",
3447
5351
  description: "Get the trading-day ticker (v1: rolling window stats by symbol, including open, close, high, low, volume, closeTime).",
3448
- inputSchema: import_zod11.z.object({ symbol: import_zod11.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT") }),
5352
+ inputSchema: import_zod15.z.object({ symbol: import_zod15.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT") }),
3449
5353
  handler: async ({ symbol: symbol3 }) => textResult(await m.tradingDayTicker(normalizeSymbol(symbol3)))
3450
5354
  },
3451
5355
  {
3452
5356
  name: "futures_mark_price",
3453
5357
  description: "Get mark price, index price, estimated settle price, last funding rate, next funding time and interest rate for a symbol.",
3454
- inputSchema: import_zod11.z.object({ symbol: import_zod11.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT") }),
5358
+ inputSchema: import_zod15.z.object({ symbol: import_zod15.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT") }),
3455
5359
  handler: async ({ symbol: symbol3 }) => textResult(await d.premiumIndex(normalizeSymbol(symbol3)))
3456
5360
  },
3457
5361
  {
3458
5362
  name: "futures_funding_rate_history",
3459
5363
  description: "Get historical funding rates for a symbol.",
3460
- inputSchema: import_zod11.z.object({ symbol: import_zod11.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT"), limit: limitDefault.default(100), startTime: startTime2, endTime: endTime2 }),
5364
+ inputSchema: import_zod15.z.object({ symbol: import_zod15.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT"), limit: limitDefault.default(100), startTime: startTime2, endTime: endTime2 }),
3461
5365
  handler: async ({ symbol: symbol3, limit: limit4, startTime: startTime5, endTime: endTime5 }) => textResult(await d.fundingRateHistory(normalizeSymbol(symbol3), { limit: Number(limit4), startTime: startTime5, endTime: endTime5 }))
3462
5366
  },
3463
5367
  {
3464
5368
  name: "futures_funding_info",
3465
5369
  description: "Get funding rate configuration for all symbols with adjusted funding cap/floor or interval (e.g. under extreme volatility).",
3466
- inputSchema: import_zod11.z.object({}),
5370
+ inputSchema: import_zod15.z.object({}),
3467
5371
  handler: async () => textResult(await d.fundingInfo())
3468
5372
  },
3469
5373
  {
3470
5374
  name: "futures_open_interest",
3471
5375
  description: "Get the current total open interest for a symbol.",
3472
- inputSchema: import_zod11.z.object({ symbol: import_zod11.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT") }),
5376
+ inputSchema: import_zod15.z.object({ symbol: import_zod15.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT") }),
3473
5377
  handler: async ({ symbol: symbol3 }) => textResult(await d.openInterest(normalizeSymbol(symbol3)))
3474
5378
  },
3475
5379
  {
3476
5380
  name: "futures_open_interest_hist",
3477
5381
  description: "Get historical open interest statistics per period.",
3478
- inputSchema: import_zod11.z.object({ symbol: import_zod11.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT"), period, limit: limitDefault.default(30) }),
5382
+ inputSchema: import_zod15.z.object({ symbol: import_zod15.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT"), period, limit: limitDefault.default(30) }),
3479
5383
  handler: async ({ symbol: symbol3, period: period2, limit: limit4 }) => textResult(await d.openInterestHist(normalizeSymbol(symbol3), period2, Number(limit4)))
3480
5384
  },
3481
5385
  {
3482
5386
  name: "futures_top_long_short_account_ratio",
3483
5387
  description: "Get top trader long/short account ratio (number of accounts) for a symbol.",
3484
- inputSchema: import_zod11.z.object({ symbol: import_zod11.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT"), period, limit: limitDefault.default(30) }),
5388
+ inputSchema: import_zod15.z.object({ symbol: import_zod15.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT"), period, limit: limitDefault.default(30) }),
3485
5389
  handler: async ({ symbol: symbol3, period: period2, limit: limit4 }) => textResult(await d.topLongShortAccountRatio(normalizeSymbol(symbol3), period2, Number(limit4)))
3486
5390
  },
3487
5391
  {
3488
5392
  name: "futures_top_long_short_position_ratio",
3489
5393
  description: "Get top trader long/short position ratio (accounts with net positions) for a symbol.",
3490
- inputSchema: import_zod11.z.object({ symbol: import_zod11.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT"), period, limit: limitDefault.default(30) }),
5394
+ inputSchema: import_zod15.z.object({ symbol: import_zod15.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT"), period, limit: limitDefault.default(30) }),
3491
5395
  handler: async ({ symbol: symbol3, period: period2, limit: limit4 }) => textResult(await d.topLongShortPositionRatio(normalizeSymbol(symbol3), period2, Number(limit4)))
3492
5396
  },
3493
5397
  {
3494
5398
  name: "futures_global_long_short_ratio",
3495
5399
  description: "Get global long/short account ratio for a symbol (all accounts).",
3496
- inputSchema: import_zod11.z.object({ symbol: import_zod11.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT"), period, limit: limitDefault.default(30) }),
5400
+ inputSchema: import_zod15.z.object({ symbol: import_zod15.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT"), period, limit: limitDefault.default(30) }),
3497
5401
  handler: async ({ symbol: symbol3, period: period2, limit: limit4 }) => textResult(await d.globalLongShortAccountRatio(normalizeSymbol(symbol3), period2, Number(limit4)))
3498
5402
  },
3499
5403
  {
3500
5404
  name: "futures_taker_long_short_ratio",
3501
5405
  description: "Get taker buy/sell volume ratio for a symbol.",
3502
- inputSchema: import_zod11.z.object({ symbol: import_zod11.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT"), period, limit: limitDefault.default(30) }),
5406
+ inputSchema: import_zod15.z.object({ symbol: import_zod15.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT"), period, limit: limitDefault.default(30) }),
3503
5407
  handler: async ({ symbol: symbol3, period: period2, limit: limit4 }) => textResult(await d.takerLongShortRatio(normalizeSymbol(symbol3), period2, Number(limit4)))
3504
5408
  },
3505
5409
  {
3506
5410
  name: "futures_basis",
3507
5411
  description: "Get basis data (spot-futures spread, mark price - index price) for a pair and contract type.",
3508
- inputSchema: import_zod11.z.object({
3509
- symbol: import_zod11.z.string().min(1).describe("Base pair, e.g. BTCUSDT"),
5412
+ inputSchema: import_zod15.z.object({
5413
+ symbol: import_zod15.z.string().min(1).describe("Base pair, e.g. BTCUSDT"),
3510
5414
  period,
3511
5415
  limit: limitDefault.default(30),
3512
5416
  startTime: startTime2,
@@ -3517,63 +5421,63 @@ function marketDataTools(client) {
3517
5421
  {
3518
5422
  name: "futures_asset_index",
3519
5423
  description: "Get multi-assets mode asset index (collateral price) for one asset or all assets.",
3520
- inputSchema: import_zod11.z.object({ symbol: optSymbol.describe("Asset index symbol, e.g. ADAUSD") }),
5424
+ inputSchema: import_zod15.z.object({ symbol: optSymbol.describe("Asset index symbol, e.g. ADAUSD") }),
3521
5425
  handler: async ({ symbol: symbol3 }) => textResult(await d.assetIndex(symbol3 ? normalizeSymbol(symbol3) : void 0))
3522
5426
  },
3523
5427
  {
3524
5428
  name: "futures_composite_index_info",
3525
5429
  description: "Get composite index symbol information (e.g. DEFIUSDT) with constituent weights.",
3526
- inputSchema: import_zod11.z.object({ symbol: optSymbol }),
5430
+ inputSchema: import_zod15.z.object({ symbol: optSymbol }),
3527
5431
  handler: async ({ symbol: symbol3 }) => textResult(await d.compositeIndexInfo(symbol3 ? normalizeSymbol(symbol3) : void 0))
3528
5432
  },
3529
5433
  {
3530
5434
  name: "futures_insurance_balance",
3531
5435
  description: "Get insurance fund balance snapshots for a symbol.",
3532
- inputSchema: import_zod11.z.object({ symbol: import_zod11.z.string().min(1).describe("USD-M pair, e.g. BNBUSDT"), limit: limitDefault.default(100), startTime: startTime2, endTime: endTime2 }),
5436
+ inputSchema: import_zod15.z.object({ symbol: import_zod15.z.string().min(1).describe("USD-M pair, e.g. BNBUSDT"), limit: limitDefault.default(100), startTime: startTime2, endTime: endTime2 }),
3533
5437
  handler: async ({ symbol: symbol3, limit: limit4, startTime: startTime5, endTime: endTime5 }) => textResult(await d.insuranceFundBalance({ symbol: normalizeSymbol(symbol3), limit: Number(limit4), startTime: startTime5, endTime: endTime5 }))
3534
5438
  },
3535
5439
  {
3536
5440
  name: "futures_index_price_constituents",
3537
5441
  description: "Get the index price constituents (exchange weights) for a symbol.",
3538
- inputSchema: import_zod11.z.object({ symbol: import_zod11.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT") }),
5442
+ inputSchema: import_zod15.z.object({ symbol: import_zod15.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT") }),
3539
5443
  handler: async ({ symbol: symbol3 }) => textResult(await d.indexPriceConstituents(normalizeSymbol(symbol3)))
3540
5444
  },
3541
5445
  {
3542
5446
  name: "futures_premium_index_klines",
3543
5447
  description: "Get premium index candlesticks for a symbol (mark price premium over index price).",
3544
- inputSchema: import_zod11.z.object({ symbol: import_zod11.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT"), interval: KlineIntervalSchema, limit: limitDefault.default(500), startTime: startTime2, endTime: endTime2 }),
5448
+ inputSchema: import_zod15.z.object({ symbol: import_zod15.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT"), interval: KlineIntervalSchema, limit: limitDefault.default(500), startTime: startTime2, endTime: endTime2 }),
3545
5449
  handler: async ({ symbol: symbol3, interval, limit: limit4, startTime: startTime5, endTime: endTime5 }) => textResult(await m.premiumIndexKlines(normalizeSymbol(symbol3), interval, { limit: Number(limit4), startTime: startTime5, endTime: endTime5 }))
3546
5450
  },
3547
5451
  {
3548
5452
  name: "futures_rpi_depth",
3549
5453
  description: "Get the RPI (Retail Price Improvement) order book depth for a symbol.",
3550
- inputSchema: import_zod11.z.object({ symbol: import_zod11.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT"), limit: import_zod11.z.number().int().positive().default(1e3) }),
5454
+ inputSchema: import_zod15.z.object({ symbol: import_zod15.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT"), limit: import_zod15.z.number().int().positive().default(1e3) }),
3551
5455
  handler: async ({ symbol: symbol3, limit: limit4 }) => textResult(await m.rpiDepth(normalizeSymbol(symbol3), Number(limit4)))
3552
5456
  },
3553
5457
  {
3554
5458
  name: "futures_delivery_price",
3555
5459
  description: "Get historical quarterly contract settlement/delivery prices for a pair.",
3556
- inputSchema: import_zod11.z.object({ symbol: import_zod11.z.string().min(1).describe("Base pair, e.g. BTCUSDT") }),
5460
+ inputSchema: import_zod15.z.object({ symbol: import_zod15.z.string().min(1).describe("Base pair, e.g. BTCUSDT") }),
3557
5461
  handler: async ({ symbol: symbol3 }) => textResult(await d.deliveryPrice(normalizeSymbol(symbol3)))
3558
5462
  },
3559
5463
  {
3560
5464
  name: "futures_symbol_adl_risk",
3561
5465
  description: "Get the auto-deleveraging (ADL) risk level for one symbol or all symbols on the account (signed).",
3562
- inputSchema: import_zod11.z.object({ symbol: optSymbol }),
5466
+ inputSchema: import_zod15.z.object({ symbol: optSymbol }),
3563
5467
  handler: async ({ symbol: symbol3 }) => textResult(await d.symbolAdlRisk(symbol3 ? normalizeSymbol(symbol3) : void 0))
3564
5468
  },
3565
5469
  {
3566
5470
  name: "futures_adl_quantile",
3567
5471
  description: "Get the position ADL (auto-deleveraging) quantile estimation for one symbol or all symbols (signed).",
3568
- inputSchema: import_zod11.z.object({ symbol: optSymbol }),
5472
+ inputSchema: import_zod15.z.object({ symbol: optSymbol }),
3569
5473
  handler: async ({ symbol: symbol3 }) => textResult(await d.adlQuantile(symbol3 ? normalizeSymbol(symbol3) : void 0))
3570
5474
  },
3571
5475
  {
3572
5476
  name: "futures_force_orders",
3573
5477
  description: "Get the user's force-liquidation orders (LIQUIDATION) and ADL orders for a symbol or all symbols (signed).",
3574
- inputSchema: import_zod11.z.object({
5478
+ inputSchema: import_zod15.z.object({
3575
5479
  symbol: optSymbol,
3576
- autoCloseType: import_zod11.z.enum(["LIQUIDATION", "ADL"]).optional(),
5480
+ autoCloseType: import_zod15.z.enum(["LIQUIDATION", "ADL"]).optional(),
3577
5481
  startTime: startTime2,
3578
5482
  endTime: endTime2,
3579
5483
  limit: limitDefault.default(50)
@@ -3593,7 +5497,7 @@ function marketDataTools(client) {
3593
5497
  }
3594
5498
 
3595
5499
  // src/tools/paper.tools.ts
3596
- var import_zod12 = require("zod");
5500
+ var import_zod16 = require("zod");
3597
5501
  function createPaperContext(client, initialState = {}) {
3598
5502
  return {
3599
5503
  client,
@@ -3611,7 +5515,7 @@ function paperTools(ctx) {
3611
5515
  {
3612
5516
  name: "paper_init",
3613
5517
  description: "Initialize paper-trading state (reset balances, positions, history). No API keys required.",
3614
- inputSchema: import_zod12.z.object({ balance: import_zod12.z.number().positive().default(1e4).describe("Starting USDT balance") }),
5518
+ inputSchema: import_zod16.z.object({ balance: import_zod16.z.number().positive().default(1e4).describe("Starting USDT balance") }),
3615
5519
  handler: async ({ balance }) => {
3616
5520
  s.balance = balance;
3617
5521
  s.positions = [];
@@ -3622,17 +5526,17 @@ function paperTools(ctx) {
3622
5526
  {
3623
5527
  name: "paper_balance",
3624
5528
  description: "Get current paper-trading balance and open-position equity (uses live market prices if an open position exists). No API keys required.",
3625
- inputSchema: import_zod12.z.object({}),
5529
+ inputSchema: import_zod16.z.object({}),
3626
5530
  handler: async () => textResult(s)
3627
5531
  },
3628
5532
  {
3629
5533
  name: "paper_open_position",
3630
5534
  description: "Open an in-memory paper position at the live ticker price (or a fixed price). No API keys required.",
3631
- inputSchema: import_zod12.z.object({
3632
- symbol: import_zod12.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT"),
3633
- side: import_zod12.z.enum(["LONG", "SHORT"]),
3634
- quantity: import_zod12.z.number().positive(),
3635
- price: import_zod12.z.number().positive().optional().describe("If omitted, uses live ticker price")
5535
+ inputSchema: import_zod16.z.object({
5536
+ symbol: import_zod16.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT"),
5537
+ side: import_zod16.z.enum(["LONG", "SHORT"]),
5538
+ quantity: import_zod16.z.number().positive(),
5539
+ price: import_zod16.z.number().positive().optional().describe("If omitted, uses live ticker price")
3636
5540
  }),
3637
5541
  handler: async ({ symbol: symbol3, side: side3, quantity, price }) => {
3638
5542
  const sym = normalizeSymbol(symbol3);
@@ -3646,10 +5550,10 @@ function paperTools(ctx) {
3646
5550
  {
3647
5551
  name: "paper_close_position",
3648
5552
  description: "Close a paper position by id (or symbol) and realize PnL at the live/last price.",
3649
- inputSchema: import_zod12.z.object({
3650
- id: import_zod12.z.string().optional().describe("Position id from paper_open_position"),
3651
- symbol: import_zod12.z.string().min(1).optional().describe("Close the position for this symbol"),
3652
- price: import_zod12.z.number().positive().optional().describe("If omitted, uses live ticker price")
5553
+ inputSchema: import_zod16.z.object({
5554
+ id: import_zod16.z.string().optional().describe("Position id from paper_open_position"),
5555
+ symbol: import_zod16.z.string().min(1).optional().describe("Close the position for this symbol"),
5556
+ price: import_zod16.z.number().positive().optional().describe("If omitted, uses live ticker price")
3653
5557
  }),
3654
5558
  handler: async ({ id, symbol: symbol3, price }) => {
3655
5559
  const idx = s.positions.findIndex((p) => id ? p.id === id : normalizeSymbol(p.symbol) === normalizeSymbol(symbol3 ?? ""));
@@ -3667,7 +5571,7 @@ function paperTools(ctx) {
3667
5571
  {
3668
5572
  name: "paper_positions",
3669
5573
  description: "List open paper positions with live unrealized PnL (marked to market).",
3670
- inputSchema: import_zod12.z.object({}),
5574
+ inputSchema: import_zod16.z.object({}),
3671
5575
  handler: async () => {
3672
5576
  const out = await Promise.all(
3673
5577
  s.positions.map(async (p) => {
@@ -3681,39 +5585,39 @@ function paperTools(ctx) {
3681
5585
  {
3682
5586
  name: "paper_history",
3683
5587
  description: "List paper-trading history of open/close events with realized PnL.",
3684
- inputSchema: import_zod12.z.object({}),
5588
+ inputSchema: import_zod16.z.object({}),
3685
5589
  handler: async () => textResult(s.history)
3686
5590
  },
3687
5591
  {
3688
5592
  name: "paper_summary",
3689
5593
  description: "Summarize paper-trading state: balance, open positions, trade count.",
3690
- inputSchema: import_zod12.z.object({}),
5594
+ inputSchema: import_zod16.z.object({}),
3691
5595
  handler: async () => textResult({ balance: s.balance, openPositions: s.positions.length, trades: s.history.length })
3692
5596
  }
3693
5597
  ];
3694
5598
  }
3695
5599
 
3696
5600
  // src/tools/spot.tools.ts
3697
- var import_zod13 = require("zod");
3698
- var spotSymbol = import_zod13.z.string().min(1).describe("Spot pair, e.g. BTCUSDT");
3699
- var optionalSymbol2 = import_zod13.z.string().min(1).describe("Spot pair, e.g. BTCUSDT").optional();
3700
- var limit2 = import_zod13.z.number().int().positive().max(1e3).default(100);
3701
- var startTime3 = import_zod13.z.number().int().positive().optional();
3702
- var endTime3 = import_zod13.z.number().int().positive().optional();
3703
- var side = import_zod13.z.enum(["BUY", "SELL"]);
3704
- var spotOrderParamsSchema = import_zod13.z.object({
5601
+ var import_zod17 = require("zod");
5602
+ var spotSymbol = import_zod17.z.string().min(1).describe("Spot pair, e.g. BTCUSDT");
5603
+ var optionalSymbol2 = import_zod17.z.string().min(1).describe("Spot pair, e.g. BTCUSDT").optional();
5604
+ var limit2 = import_zod17.z.number().int().positive().max(1e3).default(100);
5605
+ var startTime3 = import_zod17.z.number().int().positive().optional();
5606
+ var endTime3 = import_zod17.z.number().int().positive().optional();
5607
+ var side = import_zod17.z.enum(["BUY", "SELL"]);
5608
+ var spotOrderParamsSchema = import_zod17.z.object({
3705
5609
  symbol: spotSymbol,
3706
5610
  side,
3707
- type: import_zod13.z.enum(["LIMIT", "MARKET", "LIMIT_MAKER", "STOP_LOSS", "STOP_LOSS_LIMIT", "TAKE_PROFIT", "TAKE_PROFIT_LIMIT"]),
3708
- quantity: import_zod13.z.union([import_zod13.z.string(), import_zod13.z.number()]).optional().describe("Base-asset quantity; omit if using quoteOrderQty"),
3709
- quoteOrderQty: import_zod13.z.union([import_zod13.z.string(), import_zod13.z.number()]).optional().describe("Quote-asset quantity (e.g. spend 100 USDT on a MARKET order)"),
3710
- price: import_zod13.z.union([import_zod13.z.string(), import_zod13.z.number()]).optional().describe("Required for LIMIT / STOP_LOSS_LIMIT / TAKE_PROFIT_LIMIT"),
3711
- stopPrice: import_zod13.z.union([import_zod13.z.string(), import_zod13.z.number()]).optional().describe("Trigger price for STOP_LOSS / TAKE_PROFIT variants"),
3712
- timeInForce: import_zod13.z.enum(["GTC", "IOC", "FOK"]).optional().describe("Required for LIMIT"),
3713
- newClientOrderId: import_zod13.z.string().optional(),
3714
- newOrderRespType: import_zod13.z.enum(["ACK", "RESULT", "FULL"]).optional(),
3715
- icebergQty: import_zod13.z.union([import_zod13.z.string(), import_zod13.z.number()]).optional(),
3716
- selfTradePreventionMode: import_zod13.z.enum(["NONE", "EXPIRE_TAKER", "EXPIRE_MAKER", "EXPIRE_BOTH"]).optional()
5611
+ type: import_zod17.z.enum(["LIMIT", "MARKET", "LIMIT_MAKER", "STOP_LOSS", "STOP_LOSS_LIMIT", "TAKE_PROFIT", "TAKE_PROFIT_LIMIT"]),
5612
+ quantity: import_zod17.z.union([import_zod17.z.string(), import_zod17.z.number()]).optional().describe("Base-asset quantity; omit if using quoteOrderQty"),
5613
+ quoteOrderQty: import_zod17.z.union([import_zod17.z.string(), import_zod17.z.number()]).optional().describe("Quote-asset quantity (e.g. spend 100 USDT on a MARKET order)"),
5614
+ price: import_zod17.z.union([import_zod17.z.string(), import_zod17.z.number()]).optional().describe("Required for LIMIT / STOP_LOSS_LIMIT / TAKE_PROFIT_LIMIT"),
5615
+ stopPrice: import_zod17.z.union([import_zod17.z.string(), import_zod17.z.number()]).optional().describe("Trigger price for STOP_LOSS / TAKE_PROFIT variants"),
5616
+ timeInForce: import_zod17.z.enum(["GTC", "IOC", "FOK"]).optional().describe("Required for LIMIT"),
5617
+ newClientOrderId: import_zod17.z.string().optional(),
5618
+ newOrderRespType: import_zod17.z.enum(["ACK", "RESULT", "FULL"]).optional(),
5619
+ icebergQty: import_zod17.z.union([import_zod17.z.string(), import_zod17.z.number()]).optional(),
5620
+ selfTradePreventionMode: import_zod17.z.enum(["NONE", "EXPIRE_TAKER", "EXPIRE_MAKER", "EXPIRE_BOTH"]).optional()
3717
5621
  });
3718
5622
  function spotTools(client) {
3719
5623
  const m = client.spot.market;
@@ -3724,128 +5628,128 @@ function spotTools(client) {
3724
5628
  {
3725
5629
  name: "spot_ping",
3726
5630
  description: "Test connectivity to the Binance Spot REST API.",
3727
- inputSchema: import_zod13.z.object({}),
5631
+ inputSchema: import_zod17.z.object({}),
3728
5632
  handler: async () => textResult(await m.ping())
3729
5633
  },
3730
5634
  {
3731
5635
  name: "spot_server_time",
3732
5636
  description: "Get the current Binance Spot server time in ms since epoch.",
3733
- inputSchema: import_zod13.z.object({}),
5637
+ inputSchema: import_zod17.z.object({}),
3734
5638
  handler: async () => textResult(await m.serverTime())
3735
5639
  },
3736
5640
  {
3737
5641
  name: "spot_exchange_info",
3738
5642
  description: "Get Spot exchange trading rules and symbol metadata (status, base/quote assets, filters, permissions).",
3739
- inputSchema: import_zod13.z.object({}),
5643
+ inputSchema: import_zod17.z.object({}),
3740
5644
  handler: async () => textResult(await m.exchangeInfo())
3741
5645
  },
3742
5646
  {
3743
5647
  name: "spot_ticker_price",
3744
5648
  description: "Get the latest price for a Spot symbol.",
3745
- inputSchema: import_zod13.z.object({ symbol: spotSymbol }),
5649
+ inputSchema: import_zod17.z.object({ symbol: spotSymbol }),
3746
5650
  handler: async ({ symbol: symbol3 }) => textResult(await m.tickerPrice(normalizeSymbol(symbol3)))
3747
5651
  },
3748
5652
  {
3749
5653
  name: "spot_ticker_24hr",
3750
5654
  description: "Get 24-hour rolling price change statistics for a Spot symbol.",
3751
- inputSchema: import_zod13.z.object({ symbol: spotSymbol }),
5655
+ inputSchema: import_zod17.z.object({ symbol: spotSymbol }),
3752
5656
  handler: async ({ symbol: symbol3 }) => textResult(await m.ticker24hr(normalizeSymbol(symbol3)))
3753
5657
  },
3754
5658
  {
3755
5659
  name: "spot_book_ticker",
3756
5660
  description: "Get the best bid/ask (top of book) for a Spot symbol.",
3757
- inputSchema: import_zod13.z.object({ symbol: spotSymbol }),
5661
+ inputSchema: import_zod17.z.object({ symbol: spotSymbol }),
3758
5662
  handler: async ({ symbol: symbol3 }) => textResult(await m.bookTicker(normalizeSymbol(symbol3)))
3759
5663
  },
3760
5664
  {
3761
5665
  name: "spot_order_book",
3762
5666
  description: "Get the Spot order book depth for a symbol (limits 5/10/20/50/100/500/1000/5000).",
3763
- inputSchema: import_zod13.z.object({
5667
+ inputSchema: import_zod17.z.object({
3764
5668
  symbol: spotSymbol,
3765
- limit: import_zod13.z.enum(["5", "10", "20", "50", "100", "500", "1000", "5000"]).default("100")
5669
+ limit: import_zod17.z.enum(["5", "10", "20", "50", "100", "500", "1000", "5000"]).default("100")
3766
5670
  }),
3767
5671
  handler: async ({ symbol: symbol3, limit: limit4 }) => textResult(await m.depth(normalizeSymbol(symbol3), Number(limit4)))
3768
5672
  },
3769
5673
  {
3770
5674
  name: "spot_recent_trades",
3771
5675
  description: "Get the most recent executed trades for a Spot symbol.",
3772
- inputSchema: import_zod13.z.object({ symbol: spotSymbol, limit: limit2.default(500) }),
5676
+ inputSchema: import_zod17.z.object({ symbol: spotSymbol, limit: limit2.default(500) }),
3773
5677
  handler: async ({ symbol: symbol3, limit: limit4 }) => textResult(await m.trades(normalizeSymbol(symbol3), Number(limit4)))
3774
5678
  },
3775
5679
  {
3776
5680
  name: "spot_historical_trades",
3777
5681
  description: "Get older Spot trades for a symbol by fromId.",
3778
- inputSchema: import_zod13.z.object({ symbol: spotSymbol, limit: limit2.default(500), fromId: import_zod13.z.number().int().positive().optional() }),
5682
+ inputSchema: import_zod17.z.object({ symbol: spotSymbol, limit: limit2.default(500), fromId: import_zod17.z.number().int().positive().optional() }),
3779
5683
  handler: async ({ symbol: symbol3, limit: limit4, fromId }) => textResult(await m.historicalTrades(normalizeSymbol(symbol3), { limit: Number(limit4), fromId }))
3780
5684
  },
3781
5685
  {
3782
5686
  name: "spot_agg_trades",
3783
5687
  description: "Get compressed/aggregate Spot trades for a symbol within an optional time window.",
3784
- inputSchema: import_zod13.z.object({ symbol: spotSymbol, limit: limit2.default(500), startTime: startTime3, endTime: endTime3 }),
5688
+ inputSchema: import_zod17.z.object({ symbol: spotSymbol, limit: limit2.default(500), startTime: startTime3, endTime: endTime3 }),
3785
5689
  handler: async ({ symbol: symbol3, limit: limit4, startTime: startTime5, endTime: endTime5 }) => textResult(await m.aggTrades(normalizeSymbol(symbol3), { limit: Number(limit4), startTime: startTime5, endTime: endTime5 }))
3786
5690
  },
3787
5691
  {
3788
5692
  name: "spot_klines",
3789
5693
  description: "Get Spot candlesticks (OHLCV). Intervals 1m\u20261M; max 1000 per request.",
3790
- inputSchema: import_zod13.z.object({ symbol: spotSymbol, interval: KlineIntervalSchema, limit: limit2.default(500), startTime: startTime3, endTime: endTime3 }),
5694
+ inputSchema: import_zod17.z.object({ symbol: spotSymbol, interval: KlineIntervalSchema, limit: limit2.default(500), startTime: startTime3, endTime: endTime3 }),
3791
5695
  handler: async ({ symbol: symbol3, interval, limit: limit4, startTime: startTime5, endTime: endTime5 }) => textResult(await m.klines(normalizeSymbol(symbol3), interval, { limit: Number(limit4), startTime: startTime5, endTime: endTime5 }))
3792
5696
  },
3793
5697
  {
3794
5698
  name: "spot_ui_klines",
3795
5699
  description: "Get Spot candlesticks via the optimized uiKlines endpoint (same shape as spot_klines).",
3796
- inputSchema: import_zod13.z.object({ symbol: spotSymbol, interval: KlineIntervalSchema, limit: limit2.default(500), startTime: startTime3, endTime: endTime3 }),
5700
+ inputSchema: import_zod17.z.object({ symbol: spotSymbol, interval: KlineIntervalSchema, limit: limit2.default(500), startTime: startTime3, endTime: endTime3 }),
3797
5701
  handler: async ({ symbol: symbol3, interval, limit: limit4, startTime: startTime5, endTime: endTime5 }) => textResult(await m.uiKlines(normalizeSymbol(symbol3), interval, { limit: Number(limit4), startTime: startTime5, endTime: endTime5 }))
3798
5702
  },
3799
5703
  {
3800
5704
  name: "spot_avg_price",
3801
5705
  description: "Get the current average price (5-minute rolling average) for a Spot symbol.",
3802
- inputSchema: import_zod13.z.object({ symbol: spotSymbol }),
5706
+ inputSchema: import_zod17.z.object({ symbol: spotSymbol }),
3803
5707
  handler: async ({ symbol: symbol3 }) => textResult(await m.avgPrice(normalizeSymbol(symbol3)))
3804
5708
  },
3805
5709
  {
3806
5710
  name: "spot_rolling_window_ticker",
3807
5711
  description: "Get rolling-window price change statistics (1d/7d/30d). Omit symbol for all symbols.",
3808
- inputSchema: import_zod13.z.object({
5712
+ inputSchema: import_zod17.z.object({
3809
5713
  symbol: optionalSymbol2,
3810
- windowSize: import_zod13.z.enum(["1d", "7d", "30d"]).optional()
5714
+ windowSize: import_zod17.z.enum(["1d", "7d", "30d"]).optional()
3811
5715
  }),
3812
5716
  handler: async ({ symbol: symbol3, windowSize }) => textResult(await m.rollingWindowTicker(symbol3 ? normalizeSymbol(symbol3) : void 0, windowSize))
3813
5717
  },
3814
5718
  {
3815
5719
  name: "spot_trading_day_ticker",
3816
5720
  description: "Get the Spot trading-day ticker (open/close/high/low/volume by UTC day). Omit symbol for all symbols.",
3817
- inputSchema: import_zod13.z.object({ symbol: optionalSymbol2, timeZone: import_zod13.z.string().optional(), type: import_zod13.z.enum(["FULL", "MINI"]).optional() }),
5721
+ inputSchema: import_zod17.z.object({ symbol: optionalSymbol2, timeZone: import_zod17.z.string().optional(), type: import_zod17.z.enum(["FULL", "MINI"]).optional() }),
3818
5722
  handler: async ({ symbol: symbol3, timeZone, type }) => textResult(await m.tradingDayTicker(symbol3 ? normalizeSymbol(symbol3) : void 0, { timeZone, type }))
3819
5723
  },
3820
5724
  // ---- Account (signed) ----
3821
5725
  {
3822
5726
  name: "spot_account",
3823
5727
  description: "Get the Spot account: balances (free/locked), commissions, permissions (signed).",
3824
- inputSchema: import_zod13.z.object({}),
5728
+ inputSchema: import_zod17.z.object({}),
3825
5729
  handler: async () => textResult(await a.account())
3826
5730
  },
3827
5731
  {
3828
5732
  name: "spot_my_trades",
3829
5733
  description: "Get the Spot account trade list (filled trades) for a symbol with optional time range (signed).",
3830
- inputSchema: import_zod13.z.object({ symbol: spotSymbol, orderId: import_zod13.z.number().int().positive().optional(), startTime: startTime3, endTime: endTime3, fromId: import_zod13.z.number().int().positive().optional(), limit: limit2.default(500) }),
5734
+ inputSchema: import_zod17.z.object({ symbol: spotSymbol, orderId: import_zod17.z.number().int().positive().optional(), startTime: startTime3, endTime: endTime3, fromId: import_zod17.z.number().int().positive().optional(), limit: limit2.default(500) }),
3831
5735
  handler: async ({ symbol: symbol3, orderId, startTime: startTime5, endTime: endTime5, fromId, limit: limit4 }) => textResult(await a.myTrades(normalizeSymbol(symbol3), { orderId, startTime: startTime5, endTime: endTime5, fromId, limit: Number(limit4) }))
3832
5736
  },
3833
5737
  {
3834
5738
  name: "spot_my_prevented_matches",
3835
5739
  description: "Get Spot orders that were expired by the self-trade-prevention (STP) mechanism (signed).",
3836
- inputSchema: import_zod13.z.object({ symbol: spotSymbol, preventedMatchId: import_zod13.z.number().int().positive().optional(), orderId: import_zod13.z.number().int().positive().optional(), limit: limit2.default(500) }),
5740
+ inputSchema: import_zod17.z.object({ symbol: spotSymbol, preventedMatchId: import_zod17.z.number().int().positive().optional(), orderId: import_zod17.z.number().int().positive().optional(), limit: limit2.default(500) }),
3837
5741
  handler: async ({ symbol: symbol3, preventedMatchId, orderId, limit: limit4 }) => textResult(await a.myPreventedMatches(normalizeSymbol(symbol3), { preventedMatchId, orderId, limit: Number(limit4) }))
3838
5742
  },
3839
5743
  {
3840
5744
  name: "spot_account_commission",
3841
5745
  description: "Get the Spot account commission rates for a symbol (signed).",
3842
- inputSchema: import_zod13.z.object({ symbol: spotSymbol }),
5746
+ inputSchema: import_zod17.z.object({ symbol: spotSymbol }),
3843
5747
  handler: async ({ symbol: symbol3 }) => textResult(await a.accountCommission(normalizeSymbol(symbol3)))
3844
5748
  },
3845
5749
  {
3846
5750
  name: "spot_rate_limit_order",
3847
5751
  description: "Query the current Spot order rate limit usage (signed).",
3848
- inputSchema: import_zod13.z.object({}),
5752
+ inputSchema: import_zod17.z.object({}),
3849
5753
  handler: async () => textResult(await a.rateLimitOrder())
3850
5754
  },
3851
5755
  // ---- Trading (signed) ----
@@ -3864,109 +5768,109 @@ function spotTools(client) {
3864
5768
  {
3865
5769
  name: "spot_get_order",
3866
5770
  description: "Query a specific Spot order by orderId or client order id. Signed.",
3867
- inputSchema: import_zod13.z.object({ symbol: spotSymbol, orderId: import_zod13.z.number().int().positive().optional(), origClientOrderId: import_zod13.z.string().optional() }),
5771
+ inputSchema: import_zod17.z.object({ symbol: spotSymbol, orderId: import_zod17.z.number().int().positive().optional(), origClientOrderId: import_zod17.z.string().optional() }),
3868
5772
  handler: async ({ symbol: symbol3, orderId, origClientOrderId }) => textResult(await t.getOrder(normalizeSymbol(symbol3), { orderId, origClientOrderId }))
3869
5773
  },
3870
5774
  {
3871
5775
  name: "spot_cancel_order",
3872
5776
  description: "Cancel a specific open Spot order by orderId or client order id. Signed.",
3873
- inputSchema: import_zod13.z.object({ symbol: spotSymbol, orderId: import_zod13.z.number().int().positive().optional(), origClientOrderId: import_zod13.z.string().optional(), newClientOrderId: import_zod13.z.string().optional() }),
5777
+ inputSchema: import_zod17.z.object({ symbol: spotSymbol, orderId: import_zod17.z.number().int().positive().optional(), origClientOrderId: import_zod17.z.string().optional(), newClientOrderId: import_zod17.z.string().optional() }),
3874
5778
  handler: async ({ symbol: symbol3, orderId, origClientOrderId, newClientOrderId }) => textResult(await t.cancelOrder(normalizeSymbol(symbol3), { orderId, origClientOrderId, newClientOrderId }))
3875
5779
  },
3876
5780
  {
3877
5781
  name: "spot_open_orders",
3878
5782
  description: "Get all current open Spot orders, for one symbol or all symbols. Signed.",
3879
- inputSchema: import_zod13.z.object({ symbol: optionalSymbol2 }),
5783
+ inputSchema: import_zod17.z.object({ symbol: optionalSymbol2 }),
3880
5784
  handler: async ({ symbol: symbol3 }) => textResult(await t.getOpenOrders(symbol3 ? normalizeSymbol(symbol3) : void 0))
3881
5785
  },
3882
5786
  {
3883
5787
  name: "spot_all_orders",
3884
5788
  description: "Get historical Spot orders for a symbol with optional time range. Signed.",
3885
- inputSchema: import_zod13.z.object({ symbol: spotSymbol, orderId: import_zod13.z.number().int().positive().optional(), startTime: startTime3, endTime: endTime3, limit: limit2 }),
5789
+ inputSchema: import_zod17.z.object({ symbol: spotSymbol, orderId: import_zod17.z.number().int().positive().optional(), startTime: startTime3, endTime: endTime3, limit: limit2 }),
3886
5790
  handler: async ({ symbol: symbol3, orderId, startTime: startTime5, endTime: endTime5, limit: limit4 }) => textResult(await t.getAllOrders(normalizeSymbol(symbol3), { orderId, startTime: startTime5, endTime: endTime5, limit: limit4 }))
3887
5791
  },
3888
5792
  {
3889
5793
  name: "spot_cancel_open_orders",
3890
5794
  description: "Cancel all open Spot orders for a symbol. Signed.",
3891
- inputSchema: import_zod13.z.object({ symbol: spotSymbol }),
5795
+ inputSchema: import_zod17.z.object({ symbol: spotSymbol }),
3892
5796
  handler: async ({ symbol: symbol3 }) => textResult(await t.cancelOpenOrders(normalizeSymbol(symbol3)))
3893
5797
  },
3894
5798
  {
3895
5799
  name: "spot_cancel_replace_order",
3896
5800
  description: "Cancel an existing Spot order and place a new one on the same symbol (cancel-replace). Signed.",
3897
- inputSchema: import_zod13.z.object({
5801
+ inputSchema: import_zod17.z.object({
3898
5802
  symbol: spotSymbol,
3899
5803
  side,
3900
- type: import_zod13.z.enum(["LIMIT", "MARKET", "STOP_LOSS", "STOP_LOSS_LIMIT", "TAKE_PROFIT", "TAKE_PROFIT_LIMIT"]),
3901
- cancelReplaceMode: import_zod13.z.enum(["STOP_ON_FAILURE", "ALLOW_FAILURE"]).default("STOP_ON_FAILURE"),
3902
- cancelOrderId: import_zod13.z.number().int().positive().optional(),
3903
- cancelOrigClientOrderId: import_zod13.z.string().optional(),
3904
- cancelNewClientOrderId: import_zod13.z.string().optional(),
3905
- quantity: import_zod13.z.union([import_zod13.z.string(), import_zod13.z.number()]).optional(),
3906
- price: import_zod13.z.union([import_zod13.z.string(), import_zod13.z.number()]).optional(),
3907
- timeInForce: import_zod13.z.enum(["GTC", "IOC", "FOK"]).optional(),
3908
- newClientOrderId: import_zod13.z.string().optional()
5804
+ type: import_zod17.z.enum(["LIMIT", "MARKET", "STOP_LOSS", "STOP_LOSS_LIMIT", "TAKE_PROFIT", "TAKE_PROFIT_LIMIT"]),
5805
+ cancelReplaceMode: import_zod17.z.enum(["STOP_ON_FAILURE", "ALLOW_FAILURE"]).default("STOP_ON_FAILURE"),
5806
+ cancelOrderId: import_zod17.z.number().int().positive().optional(),
5807
+ cancelOrigClientOrderId: import_zod17.z.string().optional(),
5808
+ cancelNewClientOrderId: import_zod17.z.string().optional(),
5809
+ quantity: import_zod17.z.union([import_zod17.z.string(), import_zod17.z.number()]).optional(),
5810
+ price: import_zod17.z.union([import_zod17.z.string(), import_zod17.z.number()]).optional(),
5811
+ timeInForce: import_zod17.z.enum(["GTC", "IOC", "FOK"]).optional(),
5812
+ newClientOrderId: import_zod17.z.string().optional()
3909
5813
  }),
3910
5814
  handler: async (args) => textResult(await t.cancelReplaceOrder({ ...args, symbol: normalizeSymbol(args.symbol) }))
3911
5815
  },
3912
5816
  {
3913
5817
  name: "spot_new_oco_order",
3914
5818
  description: "Place a new Spot OCO (one-cancels-other) order: a stop-loss limit + a limit-maker take-profit. Signed.",
3915
- inputSchema: import_zod13.z.object({
5819
+ inputSchema: import_zod17.z.object({
3916
5820
  symbol: spotSymbol,
3917
5821
  side,
3918
- quantity: import_zod13.z.union([import_zod13.z.string(), import_zod13.z.number()]).describe("Total base-asset quantity for both legs"),
3919
- price: import_zod13.z.union([import_zod13.z.string(), import_zod13.z.number()]).describe("Limit (take-profit) price"),
3920
- stopPrice: import_zod13.z.union([import_zod13.z.string(), import_zod13.z.number()]).describe("Stop-loss trigger price"),
3921
- stopLimitPrice: import_zod13.z.union([import_zod13.z.string(), import_zod13.z.number()]).optional().describe("Stop-loss limit price (defaults to stopPrice)"),
3922
- stopLimitTimeInForce: import_zod13.z.enum(["GTC", "IOC", "FOK"]).optional(),
3923
- listClientOrderId: import_zod13.z.string().optional(),
3924
- limitClientOrderId: import_zod13.z.string().optional(),
3925
- stopClientOrderId: import_zod13.z.string().optional()
5822
+ quantity: import_zod17.z.union([import_zod17.z.string(), import_zod17.z.number()]).describe("Total base-asset quantity for both legs"),
5823
+ price: import_zod17.z.union([import_zod17.z.string(), import_zod17.z.number()]).describe("Limit (take-profit) price"),
5824
+ stopPrice: import_zod17.z.union([import_zod17.z.string(), import_zod17.z.number()]).describe("Stop-loss trigger price"),
5825
+ stopLimitPrice: import_zod17.z.union([import_zod17.z.string(), import_zod17.z.number()]).optional().describe("Stop-loss limit price (defaults to stopPrice)"),
5826
+ stopLimitTimeInForce: import_zod17.z.enum(["GTC", "IOC", "FOK"]).optional(),
5827
+ listClientOrderId: import_zod17.z.string().optional(),
5828
+ limitClientOrderId: import_zod17.z.string().optional(),
5829
+ stopClientOrderId: import_zod17.z.string().optional()
3926
5830
  }),
3927
5831
  handler: async (args) => textResult(await t.createOCOOrder({ ...args, symbol: normalizeSymbol(args.symbol) }))
3928
5832
  },
3929
5833
  {
3930
5834
  name: "spot_cancel_oco_order",
3931
5835
  description: "Cancel an entire Spot OCO order list by orderListId or listClientOrderId. Signed.",
3932
- inputSchema: import_zod13.z.object({ symbol: spotSymbol, orderListId: import_zod13.z.number().int().positive().optional(), listClientOrderId: import_zod13.z.string().optional(), newClientOrderId: import_zod13.z.string().optional() }),
5836
+ inputSchema: import_zod17.z.object({ symbol: spotSymbol, orderListId: import_zod17.z.number().int().positive().optional(), listClientOrderId: import_zod17.z.string().optional(), newClientOrderId: import_zod17.z.string().optional() }),
3933
5837
  handler: async ({ symbol: symbol3, orderListId, listClientOrderId, newClientOrderId }) => textResult(await t.cancelOCOOrder(normalizeSymbol(symbol3), { orderListId, listClientOrderId, newClientOrderId }))
3934
5838
  },
3935
5839
  {
3936
5840
  name: "spot_get_oco_order",
3937
5841
  description: "Query a Spot OCO order list by orderListId or listClientOrderId. Signed.",
3938
- inputSchema: import_zod13.z.object({ symbol: spotSymbol, orderListId: import_zod13.z.number().int().positive().optional(), origClientOrderId: import_zod13.z.string().optional() }),
5842
+ inputSchema: import_zod17.z.object({ symbol: spotSymbol, orderListId: import_zod17.z.number().int().positive().optional(), origClientOrderId: import_zod17.z.string().optional() }),
3939
5843
  handler: async ({ symbol: symbol3, orderListId, origClientOrderId }) => textResult(await t.getOCOOrder(normalizeSymbol(symbol3), { orderListId, origClientOrderId }))
3940
5844
  },
3941
5845
  {
3942
5846
  name: "spot_open_oco_orders",
3943
5847
  description: "Get all current open Spot OCO order lists. Signed.",
3944
- inputSchema: import_zod13.z.object({}),
5848
+ inputSchema: import_zod17.z.object({}),
3945
5849
  handler: async () => textResult(await t.getOpenOCOOrders())
3946
5850
  },
3947
5851
  {
3948
5852
  name: "spot_all_oco_orders",
3949
5853
  description: "Get historical Spot OCO order lists for a symbol with optional time range. Signed.",
3950
- inputSchema: import_zod13.z.object({ symbol: spotSymbol, fromId: import_zod13.z.number().int().positive().optional(), startTime: startTime3, endTime: endTime3, limit: limit2 }),
5854
+ inputSchema: import_zod17.z.object({ symbol: spotSymbol, fromId: import_zod17.z.number().int().positive().optional(), startTime: startTime3, endTime: endTime3, limit: limit2 }),
3951
5855
  handler: async ({ symbol: symbol3, fromId, startTime: startTime5, endTime: endTime5, limit: limit4 }) => textResult(await t.getAllOCOOrders(normalizeSymbol(symbol3), { fromId, startTime: startTime5, endTime: endTime5, limit: limit4 }))
3952
5856
  },
3953
5857
  {
3954
5858
  name: "spot_cancel_open_oco_orders",
3955
5859
  description: "Cancel all open Spot OCO order lists for a symbol. Signed.",
3956
- inputSchema: import_zod13.z.object({ symbol: spotSymbol }),
5860
+ inputSchema: import_zod17.z.object({ symbol: spotSymbol }),
3957
5861
  handler: async ({ symbol: symbol3 }) => textResult(await t.cancelOpenOCOOrders(normalizeSymbol(symbol3)))
3958
5862
  },
3959
5863
  // ---- User data stream (signed) ----
3960
5864
  {
3961
5865
  name: "spot_ws_start_user_stream",
3962
5866
  description: "Start the Spot user data stream: creates a listenKey, connects the private WebSocket, and begins keep-alive. Emits executionReport, outboundAccountPosition, balanceUpdate, listStatus.",
3963
- inputSchema: import_zod13.z.object({}),
5867
+ inputSchema: import_zod17.z.object({}),
3964
5868
  handler: async () => textResult({ listenKey: await client.startSpotUserStream() })
3965
5869
  },
3966
5870
  {
3967
5871
  name: "spot_ws_stop_user_stream",
3968
5872
  description: "Stop the Spot user data stream: closes the private WebSocket and invalidates the listenKey.",
3969
- inputSchema: import_zod13.z.object({}),
5873
+ inputSchema: import_zod17.z.object({}),
3970
5874
  handler: async () => {
3971
5875
  client.closeSpotUserStream();
3972
5876
  return textResult({ stopped: true });
@@ -3977,33 +5881,33 @@ function spotTools(client) {
3977
5881
  }
3978
5882
 
3979
5883
  // src/tools/trading.tools.ts
3980
- var import_zod14 = require("zod");
3981
- var symbol2 = import_zod14.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT");
3982
- var optionalSymbol3 = import_zod14.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT").optional();
3983
- var limit3 = import_zod14.z.number().int().positive().max(1e3).default(100);
3984
- var startTime4 = import_zod14.z.number().int().positive().optional();
3985
- var endTime4 = import_zod14.z.number().int().positive().optional();
3986
- var side2 = import_zod14.z.enum(["BUY", "SELL"]);
3987
- var positionSide = import_zod14.z.enum(["BOTH", "LONG", "SHORT"]).optional();
3988
- var orderParamsSchema = import_zod14.z.object({
5884
+ var import_zod18 = require("zod");
5885
+ var symbol2 = import_zod18.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT");
5886
+ var optionalSymbol3 = import_zod18.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT").optional();
5887
+ var limit3 = import_zod18.z.number().int().positive().max(1e3).default(100);
5888
+ var startTime4 = import_zod18.z.number().int().positive().optional();
5889
+ var endTime4 = import_zod18.z.number().int().positive().optional();
5890
+ var side2 = import_zod18.z.enum(["BUY", "SELL"]);
5891
+ var positionSide = import_zod18.z.enum(["BOTH", "LONG", "SHORT"]).optional();
5892
+ var orderParamsSchema = import_zod18.z.object({
3989
5893
  symbol: symbol2,
3990
5894
  side: side2,
3991
- type: import_zod14.z.enum(["LIMIT", "MARKET", "STOP", "STOP_MARKET", "TAKE_PROFIT", "TAKE_PROFIT_MARKET", "TRAILING_STOP_MARKET"]),
3992
- quantity: import_zod14.z.union([import_zod14.z.string(), import_zod14.z.number()]).describe("Order quantity in base asset"),
3993
- price: import_zod14.z.union([import_zod14.z.string(), import_zod14.z.number()]).optional().describe("Required for LIMIT and STOP/TAKE_PROFIT (limit-triggered) types"),
3994
- timeInForce: import_zod14.z.enum(["GTC", "IOC", "FOK", "GTX"]).optional(),
3995
- stopPrice: import_zod14.z.union([import_zod14.z.string(), import_zod14.z.number()]).optional().describe("Trigger price for STOP/STOP_MARKET/TAKE_PROFIT/TAKE_PROFIT_MARKET"),
3996
- reduceOnly: import_zod14.z.boolean().optional().describe("true = only reduces the position, never opens"),
5895
+ type: import_zod18.z.enum(["LIMIT", "MARKET", "STOP", "STOP_MARKET", "TAKE_PROFIT", "TAKE_PROFIT_MARKET", "TRAILING_STOP_MARKET"]),
5896
+ quantity: import_zod18.z.union([import_zod18.z.string(), import_zod18.z.number()]).describe("Order quantity in base asset"),
5897
+ price: import_zod18.z.union([import_zod18.z.string(), import_zod18.z.number()]).optional().describe("Required for LIMIT and STOP/TAKE_PROFIT (limit-triggered) types"),
5898
+ timeInForce: import_zod18.z.enum(["GTC", "IOC", "FOK", "GTX"]).optional(),
5899
+ stopPrice: import_zod18.z.union([import_zod18.z.string(), import_zod18.z.number()]).optional().describe("Trigger price for STOP/STOP_MARKET/TAKE_PROFIT/TAKE_PROFIT_MARKET"),
5900
+ reduceOnly: import_zod18.z.boolean().optional().describe("true = only reduces the position, never opens"),
3997
5901
  positionSide,
3998
- newClientOrderId: import_zod14.z.string().optional(),
3999
- closePosition: import_zod14.z.boolean().optional().describe("Close the full position on trigger (mutually exclusive with quantity)"),
4000
- newOrderRespType: import_zod14.z.enum(["ACK", "RESULT"]).optional(),
4001
- priceProtect: import_zod14.z.boolean().optional(),
4002
- workingType: import_zod14.z.enum(["MARK_PRICE", "CONTRACT_PRICE"]).optional().describe("Trigger price basis; default CONTRACT_PRICE"),
4003
- callbackRate: import_zod14.z.union([import_zod14.z.string(), import_zod14.z.number()]).optional().describe("Percent callback for TRAILING_STOP_MARKET, e.g. 0.5"),
4004
- activationPrice: import_zod14.z.union([import_zod14.z.string(), import_zod14.z.number()]).optional().describe("Activation price for TRAILING_STOP_MARKET"),
4005
- selfTradePreventionMode: import_zod14.z.enum(["NONE", "EXPIRE_TAKER", "EXPIRE_MAKER", "EXPIRE_BOTH"]).optional(),
4006
- goodTillDate: import_zod14.z.number().int().optional().describe("Timestamp when a GTD order expires")
5902
+ newClientOrderId: import_zod18.z.string().optional(),
5903
+ closePosition: import_zod18.z.boolean().optional().describe("Close the full position on trigger (mutually exclusive with quantity)"),
5904
+ newOrderRespType: import_zod18.z.enum(["ACK", "RESULT"]).optional(),
5905
+ priceProtect: import_zod18.z.boolean().optional(),
5906
+ workingType: import_zod18.z.enum(["MARK_PRICE", "CONTRACT_PRICE"]).optional().describe("Trigger price basis; default CONTRACT_PRICE"),
5907
+ callbackRate: import_zod18.z.union([import_zod18.z.string(), import_zod18.z.number()]).optional().describe("Percent callback for TRAILING_STOP_MARKET, e.g. 0.5"),
5908
+ activationPrice: import_zod18.z.union([import_zod18.z.string(), import_zod18.z.number()]).optional().describe("Activation price for TRAILING_STOP_MARKET"),
5909
+ selfTradePreventionMode: import_zod18.z.enum(["NONE", "EXPIRE_TAKER", "EXPIRE_MAKER", "EXPIRE_BOTH"]).optional(),
5910
+ goodTillDate: import_zod18.z.number().int().optional().describe("Timestamp when a GTD order expires")
4007
5911
  });
4008
5912
  function tradingTools(client) {
4009
5913
  const t = client.futures.trading;
@@ -4023,66 +5927,66 @@ function tradingTools(client) {
4023
5927
  {
4024
5928
  name: "futures_get_order",
4025
5929
  description: "Query a specific order by orderId or client order id. Signed.",
4026
- inputSchema: import_zod14.z.object({ symbol: symbol2, orderId: import_zod14.z.number().int().positive().optional(), origClientOrderId: import_zod14.z.string().optional() }),
5930
+ inputSchema: import_zod18.z.object({ symbol: symbol2, orderId: import_zod18.z.number().int().positive().optional(), origClientOrderId: import_zod18.z.string().optional() }),
4027
5931
  handler: async ({ symbol: symbol3, orderId, origClientOrderId }) => textResult(await t.getOrder(normalizeSymbol(symbol3), { orderId, origClientOrderId }))
4028
5932
  },
4029
5933
  {
4030
5934
  name: "futures_cancel_order",
4031
5935
  description: "Cancel a specific open order by orderId or client order id. Signed.",
4032
- inputSchema: import_zod14.z.object({ symbol: symbol2, orderId: import_zod14.z.number().int().positive().optional(), origClientOrderId: import_zod14.z.string().optional() }),
5936
+ inputSchema: import_zod18.z.object({ symbol: symbol2, orderId: import_zod18.z.number().int().positive().optional(), origClientOrderId: import_zod18.z.string().optional() }),
4033
5937
  handler: async ({ symbol: symbol3, orderId, origClientOrderId }) => textResult(await t.cancelOrder(normalizeSymbol(symbol3), { orderId, origClientOrderId }))
4034
5938
  },
4035
5939
  {
4036
5940
  name: "futures_get_open_order",
4037
5941
  description: "Query a current open order (must exist in the open order book). Signed.",
4038
- inputSchema: import_zod14.z.object({ symbol: symbol2, orderId: import_zod14.z.number().int().positive().optional(), origClientOrderId: import_zod14.z.string().optional() }),
5942
+ inputSchema: import_zod18.z.object({ symbol: symbol2, orderId: import_zod18.z.number().int().positive().optional(), origClientOrderId: import_zod18.z.string().optional() }),
4039
5943
  handler: async ({ symbol: symbol3, orderId, origClientOrderId }) => textResult(await t.getCurrentOrder(normalizeSymbol(symbol3), { orderId, origClientOrderId }))
4040
5944
  },
4041
5945
  {
4042
5946
  name: "futures_open_orders",
4043
5947
  description: "Get all current open orders, for one symbol or all symbols. Signed.",
4044
- inputSchema: import_zod14.z.object({ symbol: optionalSymbol3 }),
5948
+ inputSchema: import_zod18.z.object({ symbol: optionalSymbol3 }),
4045
5949
  handler: async ({ symbol: symbol3 }) => textResult(await t.getOpenOrders(symbol3 ? normalizeSymbol(symbol3) : void 0))
4046
5950
  },
4047
5951
  {
4048
5952
  name: "futures_all_orders",
4049
5953
  description: "Get historical orders for a symbol with optional time range (last 7 days by default). Signed.",
4050
- inputSchema: import_zod14.z.object({ symbol: symbol2, orderId: import_zod14.z.number().int().positive().optional(), startTime: startTime4, endTime: endTime4, limit: limit3 }),
5954
+ inputSchema: import_zod18.z.object({ symbol: symbol2, orderId: import_zod18.z.number().int().positive().optional(), startTime: startTime4, endTime: endTime4, limit: limit3 }),
4051
5955
  handler: async ({ symbol: symbol3, orderId, startTime: startTime5, endTime: endTime5, limit: limit4 }) => textResult(await t.getAllOrders(normalizeSymbol(symbol3), { orderId, startTime: startTime5, endTime: endTime5, limit: limit4 }))
4052
5956
  },
4053
5957
  {
4054
5958
  name: "futures_cancel_all_orders",
4055
5959
  description: "Cancel all open orders for a symbol. Signed.",
4056
- inputSchema: import_zod14.z.object({ symbol: symbol2 }),
5960
+ inputSchema: import_zod18.z.object({ symbol: symbol2 }),
4057
5961
  handler: async ({ symbol: symbol3 }) => textResult(await t.cancelAllOpenOrders(normalizeSymbol(symbol3)))
4058
5962
  },
4059
5963
  {
4060
5964
  name: "futures_modify_order",
4061
5965
  description: "Modify an open order (price/quantity/stopPrice). Cannot modify when position side is BOTH and closePosition is true. Signed.",
4062
- inputSchema: import_zod14.z.object({
5966
+ inputSchema: import_zod18.z.object({
4063
5967
  symbol: symbol2,
4064
5968
  side: side2,
4065
- quantity: import_zod14.z.union([import_zod14.z.string(), import_zod14.z.number()]),
4066
- price: import_zod14.z.union([import_zod14.z.string(), import_zod14.z.number()]).optional(),
4067
- orderId: import_zod14.z.number().int().positive().optional(),
4068
- origClientOrderId: import_zod14.z.string().optional(),
4069
- stopPrice: import_zod14.z.union([import_zod14.z.string(), import_zod14.z.number()]).optional(),
4070
- timeInForce: import_zod14.z.enum(["GTC", "IOC", "FOK", "GTX"]).optional(),
5969
+ quantity: import_zod18.z.union([import_zod18.z.string(), import_zod18.z.number()]),
5970
+ price: import_zod18.z.union([import_zod18.z.string(), import_zod18.z.number()]).optional(),
5971
+ orderId: import_zod18.z.number().int().positive().optional(),
5972
+ origClientOrderId: import_zod18.z.string().optional(),
5973
+ stopPrice: import_zod18.z.union([import_zod18.z.string(), import_zod18.z.number()]).optional(),
5974
+ timeInForce: import_zod18.z.enum(["GTC", "IOC", "FOK", "GTX"]).optional(),
4071
5975
  positionSide,
4072
- newClientOrderId: import_zod14.z.string().optional()
5976
+ newClientOrderId: import_zod18.z.string().optional()
4073
5977
  }),
4074
5978
  handler: async (args) => textResult(await t.modifyOrder({ ...args, symbol: normalizeSymbol(args.symbol) }))
4075
5979
  },
4076
5980
  {
4077
5981
  name: "futures_order_modify_history",
4078
5982
  description: "Get order modification history for a symbol. Signed.",
4079
- inputSchema: import_zod14.z.object({ symbol: symbol2, startTime: startTime4, endTime: endTime4, limit: limit3 }),
5983
+ inputSchema: import_zod18.z.object({ symbol: symbol2, startTime: startTime4, endTime: endTime4, limit: limit3 }),
4080
5984
  handler: async ({ symbol: symbol3, startTime: startTime5, endTime: endTime5, limit: limit4 }) => textResult(await t.getOrderModifyHistory(normalizeSymbol(symbol3), { startTime: startTime5, endTime: endTime5, limit: limit4 }))
4081
5985
  },
4082
5986
  {
4083
5987
  name: "futures_batch_orders",
4084
5988
  description: "Place up to 5 orders in one request (array of order objects, max 30 per minute per symbol). Signed.",
4085
- inputSchema: import_zod14.z.object({ orders: import_zod14.z.array(orderParamsSchema).min(1).max(5) }),
5989
+ inputSchema: import_zod18.z.object({ orders: import_zod18.z.array(orderParamsSchema).min(1).max(5) }),
4086
5990
  handler: async (args) => {
4087
5991
  const mapped = args.orders.map((o) => ({ ...o, symbol: normalizeSymbol(o.symbol) }));
4088
5992
  return textResult(await t.createBatchOrders(mapped));
@@ -4091,124 +5995,124 @@ function tradingTools(client) {
4091
5995
  {
4092
5996
  name: "futures_cancel_batch_orders",
4093
5997
  description: "Cancel multiple orders at once (up to 10 by orderId list or client order id list). Signed.",
4094
- inputSchema: import_zod14.z.object({
5998
+ inputSchema: import_zod18.z.object({
4095
5999
  symbol: symbol2,
4096
- orderIdList: import_zod14.z.array(import_zod14.z.number().int().positive()).max(10).optional(),
4097
- origClientOrderIdList: import_zod14.z.array(import_zod14.z.string()).max(10).optional()
6000
+ orderIdList: import_zod18.z.array(import_zod18.z.number().int().positive()).max(10).optional(),
6001
+ origClientOrderIdList: import_zod18.z.array(import_zod18.z.string()).max(10).optional()
4098
6002
  }),
4099
6003
  handler: async ({ symbol: symbol3, orderIdList, origClientOrderIdList }) => textResult(await t.cancelBatchOrders(normalizeSymbol(symbol3), { orderIdList, origClientOrderIdList }))
4100
6004
  },
4101
6005
  {
4102
6006
  name: "futures_set_leverage",
4103
6007
  description: "Change initial leverage for a symbol (1-125, within bracket). Signed.",
4104
- inputSchema: import_zod14.z.object({ symbol: symbol2, leverage: import_zod14.z.number().int().min(1).max(125) }),
6008
+ inputSchema: import_zod18.z.object({ symbol: symbol2, leverage: import_zod18.z.number().int().min(1).max(125) }),
4105
6009
  handler: async ({ symbol: symbol3, leverage }) => textResult(await t.setLeverage(normalizeSymbol(symbol3), leverage))
4106
6010
  },
4107
6011
  {
4108
6012
  name: "futures_set_margin_type",
4109
6013
  description: "Change margin type for a symbol: isolated or cross. Only allowed when no open position for the symbol. Signed.",
4110
- inputSchema: import_zod14.z.object({ symbol: symbol2, marginType: import_zod14.z.enum(["isolated", "cross"]) }),
6014
+ inputSchema: import_zod18.z.object({ symbol: symbol2, marginType: import_zod18.z.enum(["isolated", "cross"]) }),
4111
6015
  handler: async ({ symbol: symbol3, marginType }) => textResult(await t.setMarginType(normalizeSymbol(symbol3), marginType))
4112
6016
  },
4113
6017
  {
4114
6018
  name: "futures_modify_position_margin",
4115
6019
  description: "Add or reduce isolated position margin. marginType: 1 = add margin, 2 = reduce margin. Signed.",
4116
- inputSchema: import_zod14.z.object({ symbol: symbol2, amount: import_zod14.z.number().positive(), marginType: import_zod14.z.enum(["1", "2"]).describe("1 = add margin, 2 = reduce margin") }),
6020
+ inputSchema: import_zod18.z.object({ symbol: symbol2, amount: import_zod18.z.number().positive(), marginType: import_zod18.z.enum(["1", "2"]).describe("1 = add margin, 2 = reduce margin") }),
4117
6021
  handler: async ({ symbol: symbol3, amount, marginType }) => textResult(await t.modifyPositionMargin(normalizeSymbol(symbol3), amount, Number(marginType)))
4118
6022
  },
4119
6023
  {
4120
6024
  name: "futures_countdown_cancel_all",
4121
6025
  description: "Auto-cancel all open orders for a symbol after countdownTime ms (0 = cancel the countdown). Emergency circuit breaker. Signed.",
4122
- inputSchema: import_zod14.z.object({ symbol: symbol2, countdownTime: import_zod14.z.number().int().min(100).max(6e4) }),
6026
+ inputSchema: import_zod18.z.object({ symbol: symbol2, countdownTime: import_zod18.z.number().int().min(100).max(6e4) }),
4123
6027
  handler: async ({ symbol: symbol3, countdownTime }) => textResult(await t.setCountdownCancelAll(normalizeSymbol(symbol3), countdownTime))
4124
6028
  },
4125
6029
  {
4126
6030
  name: "futures_new_algo_order",
4127
6031
  description: "Place a conditional algo order (CONDITIONAL or VP). CONDITIONAL supports STOP_MARKET/TAKE_PROFIT_MARKET types with triggerPrice; VP is a volume-participation order with urgency and quantity. Signed.",
4128
- inputSchema: import_zod14.z.object({
4129
- algoType: import_zod14.z.enum(["CONDITIONAL", "VP"]),
6032
+ inputSchema: import_zod18.z.object({
6033
+ algoType: import_zod18.z.enum(["CONDITIONAL", "VP"]),
4130
6034
  symbol: symbol2,
4131
6035
  side: side2,
4132
6036
  positionSide,
4133
- type: import_zod14.z.enum(["STOP_MARKET", "TAKE_PROFIT_MARKET", "LIMIT"]).describe("For CONDITIONAL: STOP_MARKET/TAKE_PROFIT_MARKET. For VP: LIMIT"),
4134
- quantity: import_zod14.z.union([import_zod14.z.string(), import_zod14.z.number()]),
4135
- triggerPrice: import_zod14.z.union([import_zod14.z.string(), import_zod14.z.number()]).optional().describe("Required for CONDITIONAL"),
4136
- price: import_zod14.z.union([import_zod14.z.string(), import_zod14.z.number()]).optional(),
4137
- timeInForce: import_zod14.z.enum(["GTC", "IOC", "FOK", "GTX"]).optional(),
4138
- workingType: import_zod14.z.enum(["MARK_PRICE", "CONTRACT_PRICE"]).optional(),
4139
- priceProtect: import_zod14.z.boolean().optional(),
4140
- reduceOnly: import_zod14.z.boolean().optional(),
4141
- closePosition: import_zod14.z.boolean().optional(),
4142
- urgency: import_zod14.z.enum(["LOW", "MEDIUM", "HIGH"]).optional().describe("Required for VP"),
4143
- clientAlgoId: import_zod14.z.string().optional()
6037
+ type: import_zod18.z.enum(["STOP_MARKET", "TAKE_PROFIT_MARKET", "LIMIT"]).describe("For CONDITIONAL: STOP_MARKET/TAKE_PROFIT_MARKET. For VP: LIMIT"),
6038
+ quantity: import_zod18.z.union([import_zod18.z.string(), import_zod18.z.number()]),
6039
+ triggerPrice: import_zod18.z.union([import_zod18.z.string(), import_zod18.z.number()]).optional().describe("Required for CONDITIONAL"),
6040
+ price: import_zod18.z.union([import_zod18.z.string(), import_zod18.z.number()]).optional(),
6041
+ timeInForce: import_zod18.z.enum(["GTC", "IOC", "FOK", "GTX"]).optional(),
6042
+ workingType: import_zod18.z.enum(["MARK_PRICE", "CONTRACT_PRICE"]).optional(),
6043
+ priceProtect: import_zod18.z.boolean().optional(),
6044
+ reduceOnly: import_zod18.z.boolean().optional(),
6045
+ closePosition: import_zod18.z.boolean().optional(),
6046
+ urgency: import_zod18.z.enum(["LOW", "MEDIUM", "HIGH"]).optional().describe("Required for VP"),
6047
+ clientAlgoId: import_zod18.z.string().optional()
4144
6048
  }),
4145
6049
  handler: async (args) => textResult(await t.createAlgoOrder({ ...args, symbol: normalizeSymbol(args.symbol) }))
4146
6050
  },
4147
6051
  {
4148
6052
  name: "futures_cancel_algo_order",
4149
6053
  description: "Cancel an open algo order by algoId or clientAlgoId. Signed.",
4150
- inputSchema: import_zod14.z.object({ symbol: symbol2, algoId: import_zod14.z.number().int().positive().optional(), clientAlgoId: import_zod14.z.string().optional() }),
6054
+ inputSchema: import_zod18.z.object({ symbol: symbol2, algoId: import_zod18.z.number().int().positive().optional(), clientAlgoId: import_zod18.z.string().optional() }),
4151
6055
  handler: async ({ symbol: symbol3, algoId, clientAlgoId }) => textResult(await t.cancelAlgoOrder(normalizeSymbol(symbol3), { algoId, clientAlgoId }))
4152
6056
  },
4153
6057
  {
4154
6058
  name: "futures_cancel_all_algo_orders",
4155
6059
  description: "Cancel all open algo orders for a symbol. Signed.",
4156
- inputSchema: import_zod14.z.object({ symbol: symbol2 }),
6060
+ inputSchema: import_zod18.z.object({ symbol: symbol2 }),
4157
6061
  handler: async ({ symbol: symbol3 }) => textResult(await t.cancelAllOpenAlgoOrders(normalizeSymbol(symbol3)))
4158
6062
  },
4159
6063
  {
4160
6064
  name: "futures_get_algo_order",
4161
6065
  description: "Query an algo order by algoId or clientAlgoId. Signed.",
4162
- inputSchema: import_zod14.z.object({ symbol: symbol2, algoId: import_zod14.z.number().int().positive().optional(), clientAlgoId: import_zod14.z.string().optional() }),
6066
+ inputSchema: import_zod18.z.object({ symbol: symbol2, algoId: import_zod18.z.number().int().positive().optional(), clientAlgoId: import_zod18.z.string().optional() }),
4163
6067
  handler: async ({ symbol: symbol3, algoId, clientAlgoId }) => textResult(await t.getAlgoOrder(normalizeSymbol(symbol3), { algoId, clientAlgoId }))
4164
6068
  },
4165
6069
  {
4166
6070
  name: "futures_open_algo_orders",
4167
6071
  description: "Get all current open algo orders, optionally filtered by symbol. Signed.",
4168
- inputSchema: import_zod14.z.object({ symbol: optionalSymbol3 }),
6072
+ inputSchema: import_zod18.z.object({ symbol: optionalSymbol3 }),
4169
6073
  handler: async ({ symbol: symbol3 }) => textResult(await t.getOpenAlgoOrders(symbol3 ? normalizeSymbol(symbol3) : void 0))
4170
6074
  },
4171
6075
  {
4172
6076
  name: "futures_all_algo_orders",
4173
6077
  description: "Get historical algo orders for a symbol with optional time range. Signed.",
4174
- inputSchema: import_zod14.z.object({ symbol: symbol2, startTime: startTime4, endTime: endTime4, limit: limit3 }),
6078
+ inputSchema: import_zod18.z.object({ symbol: symbol2, startTime: startTime4, endTime: endTime4, limit: limit3 }),
4175
6079
  handler: async ({ symbol: symbol3, startTime: startTime5, endTime: endTime5, limit: limit4 }) => textResult(await t.getAllAlgoOrders(normalizeSymbol(symbol3), { startTime: startTime5, endTime: endTime5, limit: limit4 }))
4176
6080
  },
4177
6081
  {
4178
6082
  name: "futures_convert_exchange_info",
4179
6083
  description: "List asset pairs eligible for futures Convert, optionally filtered by fromAsset/toAsset.",
4180
- inputSchema: import_zod14.z.object({ fromAsset: import_zod14.z.string().optional(), toAsset: import_zod14.z.string().optional() }),
6084
+ inputSchema: import_zod18.z.object({ fromAsset: import_zod18.z.string().optional(), toAsset: import_zod18.z.string().optional() }),
4181
6085
  handler: async ({ fromAsset, toAsset }) => textResult(await t.convertExchangeInfo({ fromAsset, toAsset }))
4182
6086
  },
4183
6087
  {
4184
6088
  name: "futures_convert_get_quote",
4185
6089
  description: "Request a Convert quote between two assets (quote expires quickly; accept with futures_convert_accept_quote). Signed.",
4186
- inputSchema: import_zod14.z.object({
4187
- fromAsset: import_zod14.z.string().min(1),
4188
- toAsset: import_zod14.z.string().min(1),
4189
- fromAmount: import_zod14.z.number().positive().optional(),
4190
- toAmount: import_zod14.z.number().positive().optional(),
4191
- validTime: import_zod14.z.enum(["10s", "30s", "1m", "2m"]).optional()
6090
+ inputSchema: import_zod18.z.object({
6091
+ fromAsset: import_zod18.z.string().min(1),
6092
+ toAsset: import_zod18.z.string().min(1),
6093
+ fromAmount: import_zod18.z.number().positive().optional(),
6094
+ toAmount: import_zod18.z.number().positive().optional(),
6095
+ validTime: import_zod18.z.enum(["10s", "30s", "1m", "2m"]).optional()
4192
6096
  }),
4193
6097
  handler: async (args) => textResult(await t.convertGetQuote(args))
4194
6098
  },
4195
6099
  {
4196
6100
  name: "futures_convert_accept_quote",
4197
6101
  description: "Accept a previously requested Convert quote by quoteId. Signed.",
4198
- inputSchema: import_zod14.z.object({ quoteId: import_zod14.z.string().min(1) }),
6102
+ inputSchema: import_zod18.z.object({ quoteId: import_zod18.z.string().min(1) }),
4199
6103
  handler: async ({ quoteId }) => textResult(await t.convertAcceptQuote(quoteId))
4200
6104
  },
4201
6105
  {
4202
6106
  name: "futures_convert_order_status",
4203
6107
  description: "Query the status of a Convert order by orderId or quoteId. Signed.",
4204
- inputSchema: import_zod14.z.object({ orderId: import_zod14.z.string().optional(), quoteId: import_zod14.z.string().optional() }),
6108
+ inputSchema: import_zod18.z.object({ orderId: import_zod18.z.string().optional(), quoteId: import_zod18.z.string().optional() }),
4205
6109
  handler: async ({ orderId, quoteId }) => textResult(await t.convertOrderStatus({ orderId, quoteId }))
4206
6110
  }
4207
6111
  ];
4208
6112
  }
4209
6113
 
4210
6114
  // src/tools/ws.tools.ts
4211
- var import_zod15 = require("zod");
6115
+ var import_zod19 = require("zod");
4212
6116
  var buffers = /* @__PURE__ */ new Map();
4213
6117
  var MAX_BUFFER = 500;
4214
6118
  function bufferFor(client) {
@@ -4235,8 +6139,8 @@ function wsTools(client) {
4235
6139
  {
4236
6140
  name: "futures_ws_subscribe",
4237
6141
  description: "Subscribe to real-time market data streams. Topic format: <symbol>@<stream>, e.g. btcusdt@aggTrade, btcusdt@kline_1m, btcusdt@depth20, btcusdt@markPrice@1s, btcusdt@bookTicker, btcusdt@ticker, btcusdt@miniTicker, btcusdt@forceOrder, or all-market topics !ticker@arr, !bookTicker, !markPrice@arr, !forceOrder@arr, !miniTicker@arr. Multiple topics can be passed at once.",
4238
- inputSchema: import_zod15.z.object({
4239
- topics: import_zod15.z.array(import_zod15.z.string().min(1)).min(1).describe('Stream topics, e.g. ["btcusdt@aggTrade", "btcusdt@kline_1m"]')
6142
+ inputSchema: import_zod19.z.object({
6143
+ topics: import_zod19.z.array(import_zod19.z.string().min(1)).min(1).describe('Stream topics, e.g. ["btcusdt@aggTrade", "btcusdt@kline_1m"]')
4240
6144
  }),
4241
6145
  handler: async ({ topics }) => {
4242
6146
  const normalized = topics.map((t) => t.trim().toLowerCase());
@@ -4248,7 +6152,7 @@ function wsTools(client) {
4248
6152
  {
4249
6153
  name: "futures_ws_unsubscribe",
4250
6154
  description: "Unsubscribe from previously subscribed market data streams.",
4251
- inputSchema: import_zod15.z.object({ topics: import_zod15.z.array(import_zod15.z.string().min(1)).min(1) }),
6155
+ inputSchema: import_zod19.z.object({ topics: import_zod19.z.array(import_zod19.z.string().min(1)).min(1) }),
4252
6156
  handler: async ({ topics }) => {
4253
6157
  const normalized = topics.map((t) => t.trim().toLowerCase());
4254
6158
  client.futures.ws.unsubscribe(normalized);
@@ -4259,19 +6163,19 @@ function wsTools(client) {
4259
6163
  {
4260
6164
  name: "futures_ws_subscriptions",
4261
6165
  description: "List the currently subscribed WebSocket market streams for this client.",
4262
- inputSchema: import_zod15.z.object({}),
6166
+ inputSchema: import_zod19.z.object({}),
4263
6167
  handler: async () => textResult({ active: [...buffer.subscriptions] })
4264
6168
  },
4265
6169
  {
4266
6170
  name: "futures_ws_events",
4267
6171
  description: "Read the buffered real-time payloads received since the last read for the subscribed streams (aggregate trades, klines, depth deltas, mark price, book tickers, tickers, force orders). Payloads are parsed; depth deltas must be applied to a snapshot from futures_order_book.",
4268
- inputSchema: import_zod15.z.object({ limit: import_zod15.z.number().int().min(1).max(200).default(50) }),
6172
+ inputSchema: import_zod19.z.object({ limit: import_zod19.z.number().int().min(1).max(200).default(50) }),
4269
6173
  handler: async ({ limit: limit4 }) => textResult(getBufferedWsEvents(client, limit4))
4270
6174
  },
4271
6175
  {
4272
6176
  name: "futures_ws_clear_events",
4273
6177
  description: "Clear the buffered WebSocket events so the next read only returns new payloads.",
4274
- inputSchema: import_zod15.z.object({}),
6178
+ inputSchema: import_zod19.z.object({}),
4275
6179
  handler: async () => {
4276
6180
  clearBufferedWsEvents(client);
4277
6181
  return textResult({ cleared: true });
@@ -4280,13 +6184,13 @@ function wsTools(client) {
4280
6184
  {
4281
6185
  name: "futures_ws_start_user_stream",
4282
6186
  description: "Start the user data stream: creates a listenKey, connects the private WebSocket, and begins a 30-minute keep-alive. Emits private events (ACCOUNT_UPDATE, ORDER_TRADE_UPDATE, MARGIN_CALL, ACCOUNT_CONFIG_UPDATE, listenKeyExpired) that the application can consume from the client.",
4283
- inputSchema: import_zod15.z.object({}),
6187
+ inputSchema: import_zod19.z.object({}),
4284
6188
  handler: async () => textResult({ listenKey: await client.startUserStream() })
4285
6189
  },
4286
6190
  {
4287
6191
  name: "futures_ws_stop_user_stream",
4288
6192
  description: "Stop the user data stream: closes the private WebSocket and invalidates the listenKey.",
4289
- inputSchema: import_zod15.z.object({}),
6193
+ inputSchema: import_zod19.z.object({}),
4290
6194
  handler: async () => {
4291
6195
  client.closeUserStream();
4292
6196
  return textResult({ stopped: true });
@@ -4295,49 +6199,49 @@ function wsTools(client) {
4295
6199
  {
4296
6200
  name: "futures_ws_api_order_status",
4297
6201
  description: "Query an order via the signed WebSocket API (order.status) \u2014 lower-latency alternative to futures_get_order.",
4298
- inputSchema: import_zod15.z.object({
4299
- symbol: import_zod15.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT"),
4300
- orderId: import_zod15.z.number().int().positive().optional(),
4301
- origClientOrderId: import_zod15.z.string().optional()
6202
+ inputSchema: import_zod19.z.object({
6203
+ symbol: import_zod19.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT"),
6204
+ orderId: import_zod19.z.number().int().positive().optional(),
6205
+ origClientOrderId: import_zod19.z.string().optional()
4302
6206
  }),
4303
6207
  handler: async ({ symbol: symbol3, orderId, origClientOrderId }) => textResult(await client.futures.wsApi.orderStatus({ symbol: normalizeSymbol(symbol3), orderId, origClientOrderId }))
4304
6208
  },
4305
6209
  {
4306
6210
  name: "futures_ws_api_account_status",
4307
6211
  description: "Get account info via the signed WebSocket API (account.status).",
4308
- inputSchema: import_zod15.z.object({}),
6212
+ inputSchema: import_zod19.z.object({}),
4309
6213
  handler: async () => textResult(await client.futures.wsApi.accountStatus())
4310
6214
  },
4311
6215
  {
4312
6216
  name: "futures_ws_api_account_position",
4313
6217
  description: "Get current positions via the signed WebSocket API (account.position).",
4314
- inputSchema: import_zod15.z.object({ symbol: import_zod15.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT").optional() }),
6218
+ inputSchema: import_zod19.z.object({ symbol: import_zod19.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT").optional() }),
4315
6219
  handler: async ({ symbol: symbol3 }) => textResult(await client.futures.wsApi.accountPosition(symbol3 ? { symbol: normalizeSymbol(symbol3) } : {}))
4316
6220
  },
4317
6221
  {
4318
6222
  name: "futures_ws_api_user_data_stream_start",
4319
6223
  description: "Create a listenKey via the signed WebSocket API (userDataStream.start) \u2014 no REST call required.",
4320
- inputSchema: import_zod15.z.object({}),
6224
+ inputSchema: import_zod19.z.object({}),
4321
6225
  handler: async () => textResult(await client.futures.wsApi.userDataStreamStart())
4322
6226
  },
4323
6227
  {
4324
6228
  name: "futures_ws_api_user_data_stream_stop",
4325
6229
  description: "Invalidate a listenKey via the signed WebSocket API (userDataStream.stop).",
4326
- inputSchema: import_zod15.z.object({ listenKey: import_zod15.z.string().min(1) }),
6230
+ inputSchema: import_zod19.z.object({ listenKey: import_zod19.z.string().min(1) }),
4327
6231
  handler: async ({ listenKey }) => textResult(await client.futures.wsApi.userDataStreamStop(listenKey))
4328
6232
  },
4329
6233
  {
4330
6234
  name: "futures_ws_api_ticker_price",
4331
6235
  description: "Get latest price via the unsigned WebSocket API (ticker.price); omit symbol for all symbols.",
4332
- inputSchema: import_zod15.z.object({ symbol: import_zod15.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT").optional() }),
6236
+ inputSchema: import_zod19.z.object({ symbol: import_zod19.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT").optional() }),
4333
6237
  handler: async ({ symbol: symbol3 }) => textResult(await client.futures.wsApi.tickerPrice(symbol3 ? { symbol: normalizeSymbol(symbol3) } : {}))
4334
6238
  },
4335
6239
  {
4336
6240
  name: "futures_ws_api_order_book",
4337
6241
  description: "Get order-book depth via the unsigned WebSocket API (depth).",
4338
- inputSchema: import_zod15.z.object({
4339
- symbol: import_zod15.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT"),
4340
- limit: import_zod15.z.enum(["5", "10", "20", "50", "100", "500", "1000"]).optional()
6242
+ inputSchema: import_zod19.z.object({
6243
+ symbol: import_zod19.z.string().min(1).describe("USD-M pair, e.g. BTCUSDT"),
6244
+ limit: import_zod19.z.enum(["5", "10", "20", "50", "100", "500", "1000"]).optional()
4341
6245
  }),
4342
6246
  handler: async ({ symbol: symbol3, limit: limit4 }) => textResult(await client.futures.wsApi.depth({ symbol: normalizeSymbol(symbol3), limit: limit4 }))
4343
6247
  }
@@ -4378,7 +6282,7 @@ function toolkitToFormats(toolkit) {
4378
6282
  // src/mcp/server.ts
4379
6283
  var import_mcp = require("@modelcontextprotocol/sdk/server/mcp.js");
4380
6284
  function createBinanceMcpServer(client) {
4381
- const server = new import_mcp.McpServer({ name: "binance-sdk", version: "3.0.0" });
6285
+ const server = new import_mcp.McpServer({ name: "binance-sdk", version: "2.0.0" });
4382
6286
  const toolkit = createFuturesToolkit(client);
4383
6287
  toolkit.tools.forEach((tool) => {
4384
6288
  server.registerTool(tool.name, { description: tool.description, inputSchema: tool.inputSchema }, async (args) => ({
@@ -4431,18 +6335,21 @@ function registerResources(server, client) {
4431
6335
  }
4432
6336
 
4433
6337
  // src/index.ts
4434
- var VERSION = "2.1.0";
6338
+ var VERSION = "2.0.0";
4435
6339
  // Annotate the CommonJS export names for ESM import in node:
4436
6340
  0 && (module.exports = {
4437
6341
  AccountAssetSchema,
4438
6342
  AccountPositionSchema,
4439
6343
  AccountSchema,
6344
+ AccountSnapshotSchema,
4440
6345
  AggTradeSchema,
4441
6346
  AggTradesResponseSchema,
4442
6347
  AlgoOrderResponseSchema,
4443
6348
  AlgoOrderSchema,
4444
6349
  AlgoOrdersResponseSchema,
6350
+ ApiKeyPermissionsSchema,
4445
6351
  ApiTradingStatusSchema,
6352
+ AssetDetailSchema,
4446
6353
  AvgPriceSchema,
4447
6354
  BalanceSchema,
4448
6355
  BalancesResponseSchema,
@@ -4454,13 +6361,57 @@ var VERSION = "2.1.0";
4454
6361
  BinanceClient,
4455
6362
  BinanceError,
4456
6363
  BookTickerSchema,
6364
+ BorrowRepayParamsSchema,
6365
+ BorrowRepayRecordEntrySchema,
6366
+ BorrowRepayRecordResponseSchema,
6367
+ BorrowRepayResultSchema,
6368
+ CoinMAccount,
6369
+ CoinMAccountAssetSchema,
6370
+ CoinMAccountPositionSchema,
6371
+ CoinMAccountSchema,
6372
+ CoinMBalanceResponseSchema,
6373
+ CoinMBalanceSchema,
6374
+ CoinMCommissionRateSchema,
6375
+ CoinMCreateOrderParamsSchema,
6376
+ CoinMIncomeHistoryResponseSchema,
6377
+ CoinMIncomeSchema,
6378
+ CoinMLeverageBracketResponseSchema,
6379
+ CoinMLeverageBracketSchema,
6380
+ CoinMLeverageChangeSchema,
6381
+ CoinMMarginTypeChangeSchema,
6382
+ CoinMMarket,
6383
+ CoinMMarketWS,
6384
+ CoinMOpenInterestHistEntrySchema,
6385
+ CoinMOpenInterestHistSchema,
6386
+ CoinMOrderResponseSchema,
6387
+ CoinMOrderSchema,
6388
+ CoinMOrdersResponseSchema,
6389
+ CoinMPositionMarginChangeSchema,
6390
+ CoinMPositionModeSchema,
6391
+ CoinMPositionRiskResponseSchema,
6392
+ CoinMPositionRiskSchema,
6393
+ CoinMTrading,
6394
+ CoinMUserDataStream,
6395
+ CoinMUserTradeSchema,
6396
+ CoinMUserTradesResponseSchema,
6397
+ CoinMUserWS,
4457
6398
  CommissionRateSchema,
4458
6399
  CountdownCancelAllSchema,
4459
6400
  CreateOrderParamsSchema,
6401
+ CrossMarginAccountSchema,
6402
+ DepositAddressSchema,
6403
+ DepositHistoryEntrySchema,
6404
+ DepositHistoryResponseSchema,
4460
6405
  DepthSnapshotSchema,
6406
+ DryRunError,
6407
+ DustConversionResultSchema,
6408
+ DustLogEntrySchema,
6409
+ DustLogResponseSchema,
4461
6410
  ExchangeInfoSchema,
4462
6411
  ExchangeSymbolSchema,
4463
6412
  FeeBurnStatusSchema,
6413
+ FundingAssetSchema,
6414
+ FundingAssetsResponseSchema,
4464
6415
  FundingRateHistorySchema,
4465
6416
  FundingRateSchema,
4466
6417
  FuturesAccount,
@@ -4473,6 +6424,10 @@ var VERSION = "2.1.0";
4473
6424
  HttpClient,
4474
6425
  IncomeHistoryResponseSchema,
4475
6426
  IncomeSchema,
6427
+ IsolatedMarginAccountSchema,
6428
+ IsolatedMarginAssetSchema,
6429
+ IsolatedMarginSymbolSchema,
6430
+ IsolatedTransferParamsSchema,
4476
6431
  KlineIntervalSchema,
4477
6432
  KlineSchema,
4478
6433
  KlinesResponseSchema,
@@ -4482,8 +6437,25 @@ var VERSION = "2.1.0";
4482
6437
  ListenKeySchema,
4483
6438
  LongShortRatioEntrySchema,
4484
6439
  LongShortRatioSchema,
6440
+ MarginAccount,
6441
+ MarginAssetBalanceSchema,
6442
+ MarginCreateOrderParamsSchema,
6443
+ MarginForceLiquidationEntrySchema,
6444
+ MarginForceLiquidationResponseSchema,
6445
+ MarginInterestHistoryEntrySchema,
6446
+ MarginInterestHistoryResponseSchema,
6447
+ MarginOrderResponseSchema,
6448
+ MarginOrderSchema,
6449
+ MarginOrdersResponseSchema,
6450
+ MarginPriceIndexSchema,
6451
+ MarginTradeSchema,
6452
+ MarginTradesResponseSchema,
6453
+ MarginTrading,
6454
+ MarginTransferResultSchema,
4485
6455
  MarginTypeChangeSchema,
4486
6456
  MarketDataBase,
6457
+ MaxBorrowableSchema,
6458
+ MaxTransferableSchema,
4487
6459
  ModifyOrderParamsSchema,
4488
6460
  MultiAssetsMarginSchema,
4489
6461
  NetworkError,
@@ -4497,6 +6469,7 @@ var VERSION = "2.1.0";
4497
6469
  OrderSchema,
4498
6470
  OrdersResponseSchema,
4499
6471
  PaperTradingEngine,
6472
+ PolicyViolationError,
4500
6473
  PositionMarginChangeSchema,
4501
6474
  PositionMarginHistoryEntrySchema,
4502
6475
  PositionMarginHistorySchema,
@@ -4507,6 +6480,8 @@ var VERSION = "2.1.0";
4507
6480
  RateLimitError,
4508
6481
  RateLimitOrderResponseSchema,
4509
6482
  RateLimitOrderSchema,
6483
+ RateLimitTracker,
6484
+ Signer,
4510
6485
  SpotAccount,
4511
6486
  SpotAccountSchema,
4512
6487
  SpotBalanceSchema,
@@ -4527,12 +6502,42 @@ var VERSION = "2.1.0";
4527
6502
  SpotTrading,
4528
6503
  SpotUserDataStream,
4529
6504
  SpotUserWS,
6505
+ SpotWsApi,
6506
+ SubAccount,
6507
+ SubAccountDepositAddressSchema,
6508
+ SubAccountDepositHistoryEntrySchema,
6509
+ SubAccountDepositHistoryResponseSchema,
6510
+ SubAccountEnableResultSchema,
6511
+ SubAccountEntrySchema,
6512
+ SubAccountFuturesSummarySchema,
6513
+ SubAccountListResponseSchema,
6514
+ SubAccountMarginAccountSchema,
6515
+ SubAccountSpotAssetSchema,
6516
+ SubAccountSpotAssetsResponseSchema,
6517
+ SubAccountSpotSummaryEntrySchema,
6518
+ SubAccountSpotSummarySchema,
6519
+ SubAccountStatusResponseSchema,
6520
+ SubAccountStatusSchema,
6521
+ SubAccountUniversalTransferEntrySchema,
6522
+ SubAccountUniversalTransferHistoryResponseSchema,
6523
+ SubAccountUniversalTransferParamsSchema,
6524
+ SubAccountUniversalTransferResultSchema,
4530
6525
  TakerLongShortRatioEntrySchema,
4531
6526
  TakerLongShortRatioSchema,
4532
6527
  Ticker24hrSchema,
4533
6528
  TickerPriceSchema,
6529
+ TradeFeeEntrySchema,
6530
+ TradeFeeResponseSchema,
4534
6531
  TradeSchema,
4535
6532
  TradesResponseSchema,
6533
+ TradingPolicy,
6534
+ TransferTypeSchema,
6535
+ UniversalTransferHistoryEntrySchema,
6536
+ UniversalTransferHistoryResponseSchema,
6537
+ UniversalTransferParamsSchema,
6538
+ UniversalTransferResultSchema,
6539
+ UserAssetSchema,
6540
+ UserAssetsResponseSchema,
4536
6541
  UserDataAccountUpdateSchema,
4537
6542
  UserDataMarginCallSchema,
4538
6543
  UserDataOrderTradeUpdateSchema,
@@ -4540,6 +6545,12 @@ var VERSION = "2.1.0";
4540
6545
  UserTradeSchema,
4541
6546
  UserTradesResponseSchema,
4542
6547
  VERSION,
6548
+ VirtualSubAccountResultSchema,
6549
+ Wallet,
6550
+ WithdrawHistoryEntrySchema,
6551
+ WithdrawHistoryResponseSchema,
6552
+ WithdrawParamsSchema,
6553
+ WithdrawResultSchema,
4543
6554
  WsAggTradePayloadSchema,
4544
6555
  WsApi,
4545
6556
  WsApiResponseSchema,