@medievalrain/binance-ts 0.7.0 → 0.9.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/index.d.ts +472 -1208
  2. package/dist/index.js +131 -732
  3. package/package.json +20 -17
package/dist/index.js CHANGED
@@ -1,505 +1,6 @@
1
- import z$1, { z } from "zod";
2
- import { Client, WebSocket } from "undici";
3
- import * as z4 from "zod/v4/core";
4
1
  import { createHmac } from "node:crypto";
5
2
  import { createEmitter } from "@medievalrain/emitter";
6
3
 
7
- //#region src/rest/futures/schema.ts
8
- const FuturesTestConnectivitySchema = z.object({});
9
- const FuturesCheckServerTimeSchema = z.object({ serverTime: z.number() });
10
- const FuturesExchangeInfoRateLimitSchema = z.object({
11
- interval: z.enum(["MINUTE", "SECOND"]),
12
- intervalNum: z.number(),
13
- limit: z.number(),
14
- rateLimitType: z.enum(["REQUEST_WEIGHT", "ORDERS"])
15
- });
16
- const FuturesExchangeInfoAssetSchema = z.object({
17
- asset: z.string(),
18
- marginAvailable: z.boolean(),
19
- autoAssetExchange: z.string().nullable()
20
- });
21
- const FuturesExchangeInfoFilterSchema = z.discriminatedUnion("filterType", [
22
- z.object({
23
- filterType: z.literal("PRICE_FILTER"),
24
- maxPrice: z.coerce.number(),
25
- minPrice: z.coerce.number(),
26
- tickSize: z.coerce.number()
27
- }),
28
- z.object({
29
- filterType: z.literal("LOT_SIZE"),
30
- maxQty: z.coerce.number(),
31
- minQty: z.coerce.number(),
32
- stepSize: z.coerce.number()
33
- }),
34
- z.object({
35
- filterType: z.literal("MARKET_LOT_SIZE"),
36
- maxQty: z.coerce.number(),
37
- minQty: z.coerce.number(),
38
- stepSize: z.coerce.number()
39
- }),
40
- z.object({
41
- filterType: z.literal("MAX_NUM_ORDERS"),
42
- limit: z.number()
43
- }),
44
- z.object({
45
- filterType: z.literal("MAX_NUM_ALGO_ORDERS"),
46
- limit: z.number()
47
- }),
48
- z.object({
49
- filterType: z.literal("MIN_NOTIONAL"),
50
- notional: z.string()
51
- }),
52
- z.object({
53
- filterType: z.literal("PERCENT_PRICE"),
54
- multiplierUp: z.coerce.number(),
55
- multiplierDown: z.coerce.number().optional(),
56
- multiplierDecimal: z.coerce.number().optional()
57
- }),
58
- z.object({
59
- filterType: z.literal("POSITION_RISK_CONTROL"),
60
- positionControlSide: z.literal("NONE"),
61
- multiplierDown: z.coerce.number().optional(),
62
- multiplierDecimal: z.coerce.number().optional()
63
- })
64
- ]);
65
- const FuturesContractTypeSchema = z.enum([
66
- "PERPETUAL",
67
- "CURRENT_QUARTER",
68
- "NEXT_QUARTER"
69
- ]);
70
- const FuturesUnderlyingTypeSchema = z.enum([
71
- "COIN",
72
- "INDEX",
73
- "PREMARKET"
74
- ]);
75
- const FuturesOrderTypeSchema = z.enum([
76
- "LIMIT",
77
- "MARKET",
78
- "STOP",
79
- "TAKE_PROFIT",
80
- "STOP_MARKET",
81
- "TAKE_PROFIT_MARKET",
82
- "TRAILING_STOP_MARKET"
83
- ]);
84
- const FuturesExchangeInfoSymbolSchema = z.object({
85
- symbol: z.string(),
86
- pair: z.string(),
87
- contractType: FuturesContractTypeSchema,
88
- deliveryDate: z.number(),
89
- onboardDate: z.number(),
90
- status: z.enum([
91
- "TRADING",
92
- "SETTLING",
93
- "PENDING_TRADING"
94
- ]),
95
- maintMarginPercent: z.string(),
96
- requiredMarginPercent: z.string(),
97
- baseAsset: z.string(),
98
- quoteAsset: z.string(),
99
- marginAsset: z.string(),
100
- pricePrecision: z.number(),
101
- quantityPrecision: z.number(),
102
- baseAssetPrecision: z.number(),
103
- quotePrecision: z.number(),
104
- underlyingType: FuturesUnderlyingTypeSchema,
105
- underlyingSubType: z.array(z.string()),
106
- permissionSets: z.array(z.enum(["COPY", "GRID"])),
107
- settlePlan: z.number().optional(),
108
- triggerProtect: z.string(),
109
- filters: z.array(FuturesExchangeInfoFilterSchema),
110
- OrderType: z.array(FuturesOrderTypeSchema).optional(),
111
- timeInForce: z.array(z.string()),
112
- liquidationFee: z.coerce.number(),
113
- marketTakeBound: z.coerce.number()
114
- });
115
- const FuturesExchangeInfoSchema = z.object({
116
- exchangeFilters: z.array(z.unknown()),
117
- rateLimits: z.array(FuturesExchangeInfoRateLimitSchema),
118
- serverTime: z.number(),
119
- assets: z.array(FuturesExchangeInfoAssetSchema),
120
- symbols: z.array(FuturesExchangeInfoSymbolSchema),
121
- timezone: z.string()
122
- });
123
- const FuturesOrderBookSchema = z.object({
124
- lastUpdateId: z.number(),
125
- E: z.number(),
126
- T: z.number(),
127
- bids: z.array(z.tuple([z.coerce.number(), z.coerce.number()])),
128
- asks: z.array(z.tuple([z.coerce.number(), z.coerce.number()]))
129
- });
130
- const FuturesRecentTradesSchema = z.array(z.object({
131
- id: z.number(),
132
- price: z.coerce.number(),
133
- qty: z.coerce.number(),
134
- quoteQty: z.coerce.number(),
135
- time: z.number(),
136
- isBuyerMaker: z.boolean()
137
- }));
138
- const FuturesOldTradesLookupSchema = z.array(z.object({
139
- id: z.number(),
140
- price: z.coerce.number(),
141
- qty: z.coerce.number(),
142
- quoteQty: z.coerce.number(),
143
- time: z.number(),
144
- isBuyerMaker: z.boolean()
145
- }));
146
- const FuturesAggregateTradesSchema = z.array(z.object({
147
- a: z.number(),
148
- p: z.coerce.number(),
149
- q: z.coerce.number(),
150
- f: z.number(),
151
- l: z.number(),
152
- T: z.number(),
153
- m: z.boolean()
154
- }));
155
- const FuturesKlineDataSchema = z.array(z.tuple([
156
- z.number(),
157
- z.coerce.number(),
158
- z.coerce.number(),
159
- z.coerce.number(),
160
- z.coerce.number(),
161
- z.coerce.number(),
162
- z.number(),
163
- z.coerce.number(),
164
- z.number(),
165
- z.coerce.number(),
166
- z.coerce.number(),
167
- z.coerce.number()
168
- ]));
169
- const FuturesMarkPriceSchema = z.object({
170
- symbol: z.string(),
171
- markPrice: z.coerce.number(),
172
- indexPrice: z.coerce.number(),
173
- estimatedSettlePrice: z.coerce.number(),
174
- lastFundingRate: z.coerce.number(),
175
- interestRate: z.coerce.number(),
176
- nextFundingTime: z.number(),
177
- time: z.number()
178
- });
179
- const FuturesFundingRateEntrySchema = z.object({
180
- symbol: z.string(),
181
- fundingRate: z.coerce.number(),
182
- fundingTime: z.number(),
183
- markPrice: z.coerce.number()
184
- });
185
- const FuturesFundingRateSchema = z.array(FuturesFundingRateEntrySchema);
186
- const FuturesFundingInfoEntrySchema = z.object({
187
- symbol: z.string(),
188
- adjustedFundingRateCap: z.coerce.number(),
189
- adjustedFundingRateFloor: z.coerce.number(),
190
- fundingIntervalHours: z.number()
191
- });
192
- const FuturesFundingInfoSchema = z.array(FuturesFundingInfoEntrySchema);
193
- const FuturesTicker24hSchema = z.object({
194
- symbol: z.string(),
195
- priceChange: z.coerce.number(),
196
- priceChangePercent: z.coerce.number(),
197
- weightedAvgPrice: z.coerce.number(),
198
- lastPrice: z.coerce.number(),
199
- lastQty: z.coerce.number(),
200
- openPrice: z.coerce.number(),
201
- highPrice: z.coerce.number(),
202
- lowPrice: z.coerce.number(),
203
- volume: z.coerce.number(),
204
- quoteVolume: z.coerce.number(),
205
- openTime: z.number(),
206
- closeTime: z.number(),
207
- firstId: z.number(),
208
- lastId: z.number(),
209
- count: z.number()
210
- });
211
- const FuturesSymbolPriceSchema = z.object({
212
- symbol: z.string(),
213
- price: z.coerce.number(),
214
- time: z.number()
215
- });
216
- const FuturesBookTickerSchema = z.object({
217
- symbol: z.string(),
218
- bidPrice: z.coerce.number(),
219
- bidQty: z.coerce.number(),
220
- askPrice: z.coerce.number(),
221
- askQty: z.coerce.number(),
222
- time: z.coerce.number()
223
- });
224
- const FuturesDeliveryPriceSchema = z.array(z.object({
225
- deliveryTime: z.coerce.number(),
226
- deliveryPrice: z.coerce.number()
227
- }));
228
- const FuturesOpenInterestSchema = z.object({
229
- openInterest: z.coerce.number(),
230
- symbol: z.string(),
231
- time: z.coerce.number()
232
- });
233
- const FuturesOpenInterestStatsSchema = z.array(z.object({
234
- symbol: z.string(),
235
- sumOpenInterest: z.coerce.number(),
236
- sumOpenInterestValue: z.coerce.number(),
237
- timestamp: z.coerce.number()
238
- }));
239
- const FuturesLongShortRatioSchema = z.array(z.object({
240
- symbol: z.string(),
241
- longShortRatio: z.coerce.number(),
242
- longAccount: z.coerce.number(),
243
- shortAccount: z.coerce.number(),
244
- timestamp: z.coerce.number()
245
- }));
246
- const FuturesTakerBuySellRatioItemSchema = z.object({
247
- buySellRatio: z.coerce.number(),
248
- buyVol: z.coerce.number(),
249
- sellVol: z.coerce.number(),
250
- timestamp: z.coerce.number()
251
- });
252
- const FuturesTakerBuySellRatioSchema = z.array(FuturesTakerBuySellRatioItemSchema);
253
- const FuturesBasisSchema = z.array(z.object({
254
- indexPrice: z.coerce.number(),
255
- contractType: FuturesContractTypeSchema,
256
- basisRate: z.coerce.number(),
257
- futuresPrice: z.coerce.number(),
258
- annualizedBasisRate: z.string().optional(),
259
- basis: z.coerce.number(),
260
- pair: z.string(),
261
- timestamp: z.number()
262
- }));
263
- const FuturesCompositeIndexAssetSchema = z.object({
264
- baseAsset: z.string(),
265
- quoteAsset: z.string(),
266
- weightInQuantity: z.coerce.number(),
267
- weightInPercentage: z.coerce.number()
268
- });
269
- const FuturesCompositeIndexSchema = z.object({
270
- symbol: z.string(),
271
- time: z.coerce.number(),
272
- component: z.string(),
273
- baseAssetList: z.array(FuturesCompositeIndexAssetSchema)
274
- });
275
- const FuturesAssetIndexSchema = z.object({
276
- symbol: z.string(),
277
- time: z.coerce.number(),
278
- index: z.coerce.number(),
279
- bidBuffer: z.coerce.number(),
280
- askBuffer: z.coerce.number(),
281
- bidRate: z.coerce.number(),
282
- askRate: z.coerce.number(),
283
- autoExchangeBidBuffer: z.coerce.number(),
284
- autoExchangeAskBuffer: z.coerce.number(),
285
- autoExchangeBidRate: z.coerce.number(),
286
- autoExchangeAskRate: z.coerce.number()
287
- });
288
- const FuturesIndexPriceConstituentItemSchema = z.object({
289
- exchange: z.string(),
290
- symbol: z.string(),
291
- price: z.coerce.number(),
292
- weight: z.coerce.number()
293
- });
294
- const FuturesIndexPriceConstituentsSchema = z.object({
295
- symbol: z.string(),
296
- time: z.coerce.number(),
297
- constituents: z.array(FuturesIndexPriceConstituentItemSchema)
298
- });
299
- const FuturesInsuranceBalanceAssetSchema = z.object({
300
- asset: z.string(),
301
- marginBalance: z.coerce.number(),
302
- updateTime: z.coerce.number()
303
- });
304
- const FuturesInsuranceBalanceEntrySchema = z.object({
305
- symbols: z.array(z.string()),
306
- assets: z.array(FuturesInsuranceBalanceAssetSchema)
307
- });
308
- const FuturesAccountBalanceSchema = z.array(z.object({
309
- accountAlias: z.string(),
310
- asset: z.string(),
311
- balance: z.coerce.number(),
312
- crossWalletBalance: z.coerce.number(),
313
- crossUnPnl: z.coerce.number(),
314
- availableBalance: z.coerce.number(),
315
- maxWithdrawAmount: z.coerce.number(),
316
- marginAvailable: z.boolean(),
317
- updateTime: z.number()
318
- }));
319
- const FuturesAccountAssetSchema = z.object({
320
- asset: z.string(),
321
- walletBalance: z.coerce.number(),
322
- unrealizedProfit: z.coerce.number(),
323
- marginBalance: z.coerce.number(),
324
- maintMargin: z.coerce.number(),
325
- initialMargin: z.coerce.number(),
326
- positionInitialMargin: z.coerce.number(),
327
- openOrderInitialMargin: z.coerce.number(),
328
- crossWalletBalance: z.coerce.number(),
329
- crossUnPnl: z.coerce.number(),
330
- availableBalance: z.coerce.number(),
331
- maxWithdrawAmount: z.coerce.number(),
332
- updateTime: z.number(),
333
- marginAvailable: z.boolean().optional()
334
- });
335
- const FuturesAccountPositionSchema = z.object({
336
- symbol: z.string(),
337
- positionSide: z.string(),
338
- positionAmt: z.coerce.number(),
339
- unrealizedProfit: z.coerce.number(),
340
- isolatedMargin: z.coerce.number(),
341
- notional: z.coerce.number(),
342
- isolatedWallet: z.coerce.number(),
343
- initialMargin: z.coerce.number(),
344
- maintMargin: z.coerce.number(),
345
- updateTime: z.number()
346
- });
347
- const FuturesAccountInfoSchema = z.object({
348
- totalInitialMargin: z.coerce.number(),
349
- totalMaintMargin: z.coerce.number(),
350
- totalWalletBalance: z.coerce.number(),
351
- totalUnrealizedProfit: z.coerce.number(),
352
- totalMarginBalance: z.coerce.number(),
353
- totalPositionInitialMargin: z.coerce.number(),
354
- totalOpenOrderInitialMargin: z.coerce.number(),
355
- totalCrossWalletBalance: z.coerce.number(),
356
- totalCrossUnPnl: z.coerce.number(),
357
- availableBalance: z.coerce.number(),
358
- maxWithdrawAmount: z.coerce.number(),
359
- assets: z.array(FuturesAccountAssetSchema),
360
- positions: z.array(FuturesAccountPositionSchema)
361
- });
362
- const FuturesCommissionRateSchema = z.object({
363
- symbol: z.string(),
364
- makerCommissionRate: z.coerce.number(),
365
- takerCommissionRate: z.coerce.number()
366
- });
367
- const FuturesAccountConfigSchema = z.object({
368
- feeTier: z.number(),
369
- canTrade: z.boolean(),
370
- canDeposit: z.boolean(),
371
- canWithdraw: z.boolean(),
372
- dualSidePosition: z.boolean(),
373
- multiAssetsMargin: z.boolean(),
374
- tradeGroupId: z.number()
375
- });
376
- const FuturesSymbolConfigSchema = z.array(z.object({
377
- symbol: z.string(),
378
- marginType: z.enum(["ISOLATED", "CROSSED"]),
379
- isAutoAddMargin: z.boolean(),
380
- leverage: z.coerce.number(),
381
- maxNotionalValue: z.coerce.number().or(z.literal("INF")).transform((v) => v === "INF" ? Infinity : Number(v))
382
- }));
383
- const FuturesUserRateLimitSchema = z.array(z.object({
384
- rateLimitType: z.literal("ORDERS"),
385
- interval: z.enum([
386
- "SECOND",
387
- "MINUTE",
388
- "DAY"
389
- ]),
390
- intervalNum: z.number(),
391
- limit: z.number()
392
- }));
393
- const FuturesLeverageBracketEntrySchema = z.object({
394
- bracket: z.number(),
395
- initialLeverage: z.number(),
396
- notionalCap: z.number(),
397
- notionalFloor: z.number(),
398
- maintMarginRatio: z.number(),
399
- cum: z.number()
400
- });
401
- const FuturesLeverageBracketSchema = z.array(z.object({
402
- symbol: z.string(),
403
- notionalCoef: z.number().optional(),
404
- brackets: z.array(FuturesLeverageBracketEntrySchema)
405
- }));
406
- const FuturesPositionModeSchema = z.object({ dualSidePosition: z.boolean() });
407
- const FuturesIncomeTypeSchema = z.enum([
408
- "TRANSFER",
409
- "WELCOME_BONUS",
410
- "REALIZED_PNL",
411
- "FUNDING_FEE",
412
- "COMMISSION",
413
- "INSURANCE_CLEAR",
414
- "REFERRAL_KICKBACK",
415
- "COMMISSION_REBATE",
416
- "API_REBATE",
417
- "CONTEST_REWARD",
418
- "CROSS_COLLATERAL_TRANSFER",
419
- "OPTIONS_PREMIUM_FEE",
420
- "OPTIONS_SETTLE_PROFIT",
421
- "INTERNAL_TRANSFER",
422
- "AUTO_EXCHANGE",
423
- "DELIVERED_SETTELMENT",
424
- "COIN_SWAP_DEPOSIT",
425
- "COIN_SWAP_WITHDRAW",
426
- "POSITION_LIMIT_INCREASE_FEE",
427
- "STRATEGY_UMFUTURES_TRANSFER",
428
- "FEE_RETURN",
429
- "BFUSD_REWARD"
430
- ]);
431
- const FuturesIncomeHistorySchema = z.array(z.object({
432
- symbol: z.string().optional(),
433
- incomeType: FuturesIncomeTypeSchema,
434
- income: z.coerce.number(),
435
- asset: z.string(),
436
- info: z.string(),
437
- time: z.number(),
438
- tranId: z.number(),
439
- tradeId: z.string().optional()
440
- }));
441
- const FuturesOrderSideSchema = z.enum(["BUY", "SELL"]);
442
- const FuturesPositionSideSchema = z.enum([
443
- "BOTH",
444
- "LONG",
445
- "SHORT"
446
- ]);
447
- const FuturesTimeInForceSchema = z.enum([
448
- "GTC",
449
- "IOC",
450
- "FOK",
451
- "GTX",
452
- "GTD"
453
- ]);
454
- const FuturesWorkingTypeSchema = z.enum(["MARK_PRICE", "CONTRACT_PRICE"]);
455
- const FuturesNewOrderRespTypeSchema = z.enum(["ACK", "RESULT"]);
456
- const FuturesPriceMatchSchema = z.enum([
457
- "OPPONENT",
458
- "OPPONENT_5",
459
- "OPPONENT_10",
460
- "OPPONENT_20",
461
- "QUEUE",
462
- "QUEUE_5",
463
- "QUEUE_10",
464
- "QUEUE_20",
465
- "NONE"
466
- ]);
467
- const FuturesSelfTradePreventionSchema = z.enum([
468
- "NONE",
469
- "EXPIRE_TAKER",
470
- "EXPIRE_MAKER",
471
- "EXPIRE_BOTH"
472
- ]);
473
- const FuturesNewOrderSchema = z.object({
474
- clientOrderId: z.string(),
475
- cumQty: z.coerce.number(),
476
- cumQuote: z.coerce.number(),
477
- executedQty: z.coerce.number(),
478
- orderId: z.number(),
479
- avgPrice: z.coerce.number(),
480
- origQty: z.coerce.number(),
481
- price: z.coerce.number(),
482
- reduceOnly: z.boolean(),
483
- side: FuturesOrderSideSchema,
484
- positionSide: FuturesPositionSideSchema,
485
- status: z.string(),
486
- stopPrice: z.coerce.number().optional(),
487
- closePosition: z.boolean().optional(),
488
- symbol: z.string(),
489
- timeInForce: FuturesTimeInForceSchema,
490
- type: FuturesOrderTypeSchema,
491
- origType: FuturesOrderTypeSchema,
492
- activatePrice: z.coerce.number().optional(),
493
- priceRate: z.coerce.number().optional(),
494
- updateTime: z.number(),
495
- workingType: FuturesWorkingTypeSchema,
496
- priceProtect: z.boolean(),
497
- priceMatch: FuturesPriceMatchSchema.optional(),
498
- selfTradePreventionMode: FuturesSelfTradePreventionSchema.optional(),
499
- goodTillDate: z.number().optional()
500
- });
501
-
502
- //#endregion
503
4
  //#region src/shared/api-error.ts
504
5
  var ApiError = class extends Error {
505
6
  endpoint;
@@ -511,21 +12,6 @@ var ApiError = class extends Error {
511
12
  this.endpoint = endpoint;
512
13
  }
513
14
  };
514
- var ValidationError = class extends ApiError {
515
- error;
516
- input;
517
- constructor({ error, input, endpoint }) {
518
- super({
519
- endpoint,
520
- metadata: {
521
- error,
522
- input
523
- }
524
- });
525
- this.error = error;
526
- this.input = input;
527
- }
528
- };
529
15
  var ResponseError = class extends ApiError {
530
16
  code;
531
17
  status;
@@ -563,11 +49,9 @@ var WeightError = class extends ResponseError {
563
49
  parseWeightResponse(message) {
564
50
  const match = message.match(/IP\(([^)]+)\).*?until (\d+)/);
565
51
  if (!match) throw new ErrorMessageParsingError("Can't parse weight data");
566
- const ip = String(match[1]);
567
- const timestamp = Number(match[2]);
568
52
  return {
569
- ip,
570
- timestamp
53
+ ip: String(match[1]),
54
+ timestamp: Number(match[2])
571
55
  };
572
56
  }
573
57
  };
@@ -588,59 +72,73 @@ var MalformedParamError = class extends ResponseError {
588
72
  }
589
73
  };
590
74
 
591
- //#endregion
592
- //#region src/shared/schema.ts
593
- const ErrorResponseSchema = z.object({
594
- code: z.number(),
595
- msg: z.string()
596
- });
597
-
598
75
  //#endregion
599
76
  //#region src/shared/base-rest-client.ts
600
77
  var BaseRestClient = class {
601
- httpCleint;
602
78
  apiKey;
603
79
  apiSecret;
604
- constructor({ baseUrl, apiKey, apiSecret, httpOptions }) {
80
+ baseUrl;
81
+ constructor({ baseUrl, apiKey, apiSecret }) {
605
82
  this.apiKey = apiKey;
606
83
  this.apiSecret = apiSecret;
607
- this.httpCleint = new Client(baseUrl, {
608
- allowH2: true,
609
- connect: {
610
- maxVersion: "TLSv1.2",
611
- ...httpOptions?.connect
612
- },
613
- ...httpOptions
84
+ this.baseUrl = baseUrl;
85
+ }
86
+ marketRequest = async ({ endpoint, params }) => {
87
+ const searchParams = this.toSearchParams(params);
88
+ const url = new URL(endpoint, this.baseUrl);
89
+ url.search = searchParams.toString();
90
+ const response = await fetch(url.toString(), { keepalive: true });
91
+ const json = await response.json();
92
+ if (response.status === 200) return json;
93
+ throw this.parseErrorResponse(endpoint, response.status, json);
94
+ };
95
+ async privateRequest({ endpoint, params, method }) {
96
+ if (!this.apiKey || !this.apiSecret) throw new ApiError({
97
+ endpoint,
98
+ metadata: { cause: "Empty credentials" }
614
99
  });
100
+ const searchParams = this.toSearchParams(params);
101
+ searchParams.append("timestamp", (/* @__PURE__ */ new Date()).getTime().toString());
102
+ const signature = this.sign(searchParams.toString(), this.apiSecret);
103
+ searchParams.append("signature", signature);
104
+ const url = new URL(endpoint, this.baseUrl);
105
+ const requestOptions = {
106
+ keepalive: true,
107
+ headers: { "X-MBX-APIKEY": this.apiKey },
108
+ method
109
+ };
110
+ if (method === "POST") requestOptions.body = searchParams.toString();
111
+ else url.search = searchParams.toString();
112
+ const response = await fetch(url.toString(), requestOptions);
113
+ const json = await response.json();
114
+ if (response.status === 200) return json;
115
+ throw this.parseErrorResponse(endpoint, response.status, json);
116
+ }
117
+ sign(message, secret) {
118
+ return createHmac("sha256", secret).update(message).digest("hex");
615
119
  }
616
120
  toSearchParams(rawParams) {
617
- if (!rawParams) return {};
618
- return Object.entries(rawParams).reduce((acc, [key, value]) => {
619
- if (Array.isArray(value)) {
620
- acc[key] = JSON.stringify(value);
621
- return acc;
622
- }
623
- if (value !== void 0 && value !== null) acc[key] = String(value);
624
- return acc;
625
- }, {});
121
+ const searchParams = new URLSearchParams();
122
+ if (!rawParams) return searchParams;
123
+ for (const [key, value] of Object.entries(rawParams)) {
124
+ if (Array.isArray(value)) searchParams.append(key, JSON.stringify(value));
125
+ if (value !== void 0 && value !== null) searchParams.append(key, String(value));
126
+ }
127
+ return searchParams;
626
128
  }
627
129
  parseErrorResponse(endpoint, statusCode, json) {
628
- const result = ErrorResponseSchema.safeParse(json);
629
- if (result.error) throw new ApiError({
130
+ if (!json.code || !json.msg) throw new ApiError({
630
131
  endpoint,
631
- metadata: {
632
- error: result.error,
633
- json
634
- }
132
+ metadata: { json }
635
133
  });
636
134
  switch (statusCode) {
637
135
  case 418: throw new WeightError({
638
- message: result.data.msg,
136
+ message: json.msg,
639
137
  endpoint
640
138
  });
641
139
  case 400: throw new MalformedParamError({
642
140
  endpoint,
643
- message: result.data.msg
141
+ message: json.msg
644
142
  });
645
143
  default: throw new ApiError({
646
144
  endpoint,
@@ -648,376 +146,275 @@ var BaseRestClient = class {
648
146
  });
649
147
  }
650
148
  }
651
- async parseResponse(schema, response, endpoint) {
652
- const json = await response.body.json();
653
- if (response.statusCode === 200) {
654
- const result = z4.safeParse(schema, json);
655
- if (result.error) throw new ValidationError({
656
- endpoint,
657
- input: json,
658
- error: result.error
659
- });
660
- return result.data;
661
- }
662
- throw this.parseErrorResponse(endpoint, response.statusCode, json);
663
- }
664
- async publicRequest({ endpoint, params, schema }) {
665
- const searchParams = this.toSearchParams(params);
666
- const response = await this.httpCleint.request({
667
- method: "GET",
668
- path: endpoint,
669
- query: searchParams,
670
- headers: { "X-MBX-APIKEY": this.apiKey }
671
- });
672
- return this.parseResponse(schema, response, endpoint);
673
- }
674
- async privateRequest({ endpoint, params, schema, method }) {
675
- if (!this.apiKey || !this.apiSecret) throw new ApiError({
676
- endpoint,
677
- metadata: { cause: "Empty credentials" }
678
- });
679
- const searchParams = this.toSearchParams(params);
680
- searchParams["timestamp"] = (/* @__PURE__ */ new Date()).getTime().toString();
681
- searchParams["signature"] = this.sign(new URLSearchParams(searchParams).toString(), this.apiSecret);
682
- const response = await this.httpCleint.request({
683
- method,
684
- path: endpoint,
685
- query: method !== "POST" ? searchParams : void 0,
686
- body: method === "POST" ? new URLSearchParams(searchParams).toString() : void 0,
687
- headers: { "X-MBX-APIKEY": this.apiKey }
688
- });
689
- return this.parseResponse(schema, response, endpoint);
690
- }
691
- sign(message, secret) {
692
- return createHmac("sha256", secret).update(message).digest("hex");
693
- }
694
149
  };
695
150
 
696
151
  //#endregion
697
152
  //#region src/rest/futures/client.ts
698
153
  var FuturesRestClient = class extends BaseRestClient {
699
- constructor({ baseUrl = "https://fapi.binance.com", apiKey, apiSecret, httpOptions }) {
154
+ constructor({ baseUrl = "https://fapi.binance.com", apiKey, apiSecret }) {
700
155
  super({
701
156
  baseUrl,
702
157
  apiKey,
703
- apiSecret,
704
- httpOptions
158
+ apiSecret
705
159
  });
706
160
  }
707
161
  async testConnectivity() {
708
- return this.publicRequest({
709
- endpoint: "/fapi/v1/ping",
710
- schema: FuturesTestConnectivitySchema
711
- });
162
+ return this.marketRequest({ endpoint: "/fapi/v1/ping" });
712
163
  }
713
164
  async checkServerTime() {
714
- return this.publicRequest({
715
- endpoint: "/fapi/v1/time",
716
- schema: FuturesCheckServerTimeSchema
717
- });
165
+ return this.marketRequest({ endpoint: "/fapi/v1/time" });
718
166
  }
719
167
  async exchangeInformation() {
720
- return this.publicRequest({
721
- endpoint: "/fapi/v1/exchangeInfo",
722
- schema: FuturesExchangeInfoSchema
723
- });
168
+ return this.marketRequest({ endpoint: "/fapi/v1/exchangeInfo" });
724
169
  }
725
170
  async orderBook(params) {
726
- return this.publicRequest({
171
+ return this.marketRequest({
727
172
  params,
728
- endpoint: "/fapi/v1/depth",
729
- schema: FuturesOrderBookSchema
173
+ endpoint: "/fapi/v1/depth"
730
174
  });
731
175
  }
732
176
  async recentTrades(params) {
733
- return this.publicRequest({
177
+ return this.marketRequest({
734
178
  params,
735
- endpoint: "/fapi/v1/trades",
736
- schema: FuturesRecentTradesSchema
179
+ endpoint: "/fapi/v1/trades"
737
180
  });
738
181
  }
739
182
  async oldTradesLookup(params) {
740
183
  return this.privateRequest({
741
184
  method: "GET",
742
185
  params,
743
- endpoint: "/fapi/v1/historicalTrades",
744
- schema: FuturesOldTradesLookupSchema
186
+ endpoint: "/fapi/v1/historicalTrades"
745
187
  });
746
188
  }
747
189
  async aggregateTrades(params) {
748
- return this.publicRequest({
190
+ return this.marketRequest({
749
191
  params,
750
- endpoint: "/fapi/v1/aggTrades",
751
- schema: FuturesAggregateTradesSchema
192
+ endpoint: "/fapi/v1/aggTrades"
752
193
  });
753
194
  }
754
195
  async klineData(params) {
755
- return this.publicRequest({
196
+ return this.marketRequest({
756
197
  params,
757
- endpoint: "/fapi/v1/klines",
758
- schema: FuturesKlineDataSchema
198
+ endpoint: "/fapi/v1/klines"
759
199
  });
760
200
  }
761
201
  async continuousContractKlineData(params) {
762
- return this.publicRequest({
202
+ return this.marketRequest({
763
203
  params,
764
- endpoint: "/fapi/v1/continuousKlines",
765
- schema: FuturesKlineDataSchema
204
+ endpoint: "/fapi/v1/continuousKlines"
766
205
  });
767
206
  }
768
207
  async indexPriceKlineData(params) {
769
- return this.publicRequest({
208
+ return this.marketRequest({
770
209
  params,
771
- endpoint: "/fapi/v1/indexPriceKlines",
772
- schema: FuturesKlineDataSchema
210
+ endpoint: "/fapi/v1/indexPriceKlines"
773
211
  });
774
212
  }
775
213
  async markPriceKlineData(params) {
776
- return this.publicRequest({
214
+ return this.marketRequest({
777
215
  params,
778
- endpoint: "/fapi/v1/markPriceKlines",
779
- schema: FuturesKlineDataSchema
216
+ endpoint: "/fapi/v1/markPriceKlines"
780
217
  });
781
218
  }
782
219
  async premiumIndexKlineData(params) {
783
- return this.publicRequest({
220
+ return this.marketRequest({
784
221
  params,
785
- endpoint: "/fapi/v1/premiumIndexKlines",
786
- schema: FuturesKlineDataSchema
222
+ endpoint: "/fapi/v1/premiumIndexKlines"
787
223
  });
788
224
  }
789
225
  async markPrice(params) {
790
- const isSingle = !!params?.symbol;
791
- return this.publicRequest({
226
+ return this.marketRequest({
792
227
  params,
793
- endpoint: "/fapi/v1/premiumIndex",
794
- schema: isSingle ? FuturesMarkPriceSchema : z$1.array(FuturesMarkPriceSchema)
228
+ endpoint: "/fapi/v1/premiumIndex"
795
229
  });
796
230
  }
797
231
  async fundingRateHistory(params) {
798
- return this.publicRequest({
232
+ return this.marketRequest({
799
233
  params,
800
- endpoint: "/fapi/v1/fundingRate",
801
- schema: FuturesFundingRateSchema
234
+ endpoint: "/fapi/v1/fundingRate"
802
235
  });
803
236
  }
804
237
  async fundingRateInfo() {
805
- return this.publicRequest({
806
- endpoint: "/fapi/v1/fundingInfo",
807
- schema: FuturesFundingInfoSchema
808
- });
238
+ return this.marketRequest({ endpoint: "/fapi/v1/fundingInfo" });
809
239
  }
810
240
  async ticker24h(params) {
811
- return this.publicRequest({
241
+ return this.marketRequest({
812
242
  params,
813
- endpoint: "/fapi/v1/ticker/24hr",
814
- schema: params?.symbol ? FuturesTicker24hSchema : z$1.array(FuturesTicker24hSchema)
243
+ endpoint: "/fapi/v1/ticker/24hr"
815
244
  });
816
245
  }
817
246
  async symbolPriceTicker(params) {
818
- return this.publicRequest({
247
+ return this.marketRequest({
819
248
  params,
820
- endpoint: "/fapi/v2/ticker/price",
821
- schema: params?.symbol ? FuturesSymbolPriceSchema : z$1.array(FuturesSymbolPriceSchema)
249
+ endpoint: "/fapi/v2/ticker/price"
822
250
  });
823
251
  }
824
252
  async bookTicker(params) {
825
- return this.publicRequest({
253
+ return this.marketRequest({
826
254
  params,
827
- endpoint: "/fapi/v1/ticker/bookTicker",
828
- schema: params?.symbol ? FuturesBookTickerSchema : z$1.array(FuturesBookTickerSchema)
255
+ endpoint: "/fapi/v1/ticker/bookTicker"
829
256
  });
830
257
  }
831
258
  async quarterlySettlementPrices(params) {
832
- return this.publicRequest({
259
+ return this.marketRequest({
833
260
  params,
834
- endpoint: "/futures/data/delivery-price",
835
- schema: FuturesDeliveryPriceSchema
261
+ endpoint: "/futures/data/delivery-price"
836
262
  });
837
263
  }
838
264
  async openInterest(params) {
839
- return this.publicRequest({
265
+ return this.marketRequest({
840
266
  params,
841
- endpoint: "/fapi/v1/openInterest",
842
- schema: FuturesOpenInterestSchema
267
+ endpoint: "/fapi/v1/openInterest"
843
268
  });
844
269
  }
845
270
  async openInterestStats(params) {
846
- return this.publicRequest({
271
+ return this.marketRequest({
847
272
  params,
848
- endpoint: "/futures/data/openInterestHist",
849
- schema: FuturesOpenInterestStatsSchema
273
+ endpoint: "/futures/data/openInterestHist"
850
274
  });
851
275
  }
852
276
  async topLongShortPositionRatio(params) {
853
- return this.publicRequest({
277
+ return this.marketRequest({
854
278
  params,
855
- endpoint: "/futures/data/topLongShortPositionRatio",
856
- schema: FuturesLongShortRatioSchema
279
+ endpoint: "/futures/data/topLongShortPositionRatio"
857
280
  });
858
281
  }
859
282
  async topLongShortAccountRatio(params) {
860
- return this.publicRequest({
283
+ return this.marketRequest({
861
284
  params,
862
- endpoint: "/futures/data/topLongShortAccountRatio",
863
- schema: FuturesLongShortRatioSchema
285
+ endpoint: "/futures/data/topLongShortAccountRatio"
864
286
  });
865
287
  }
866
288
  async globalLongShortAccountRatio(params) {
867
- return this.publicRequest({
289
+ return this.marketRequest({
868
290
  params,
869
- endpoint: "/futures/data/globalLongShortAccountRatio",
870
- schema: FuturesLongShortRatioSchema
291
+ endpoint: "/futures/data/globalLongShortAccountRatio"
871
292
  });
872
293
  }
873
294
  async takerBuySellRatio(params) {
874
- return this.publicRequest({
295
+ return this.marketRequest({
875
296
  params,
876
- endpoint: "/futures/data/takerlongshortRatio",
877
- schema: FuturesTakerBuySellRatioSchema
297
+ endpoint: "/futures/data/takerlongshortRatio"
878
298
  });
879
299
  }
880
300
  async basisData(params) {
881
- return this.publicRequest({
301
+ return this.marketRequest({
882
302
  params,
883
- endpoint: "/futures/data/basis",
884
- schema: FuturesBasisSchema
303
+ endpoint: "/futures/data/basis"
885
304
  });
886
305
  }
887
306
  async compositeIndexInfo(params) {
888
- const isSingle = !!params?.symbol;
889
- return await this.publicRequest({
307
+ return await this.marketRequest({
890
308
  params,
891
- endpoint: "/fapi/v1/indexInfo",
892
- schema: isSingle ? FuturesCompositeIndexSchema : z$1.array(FuturesCompositeIndexSchema)
309
+ endpoint: "/fapi/v1/indexInfo"
893
310
  });
894
311
  }
895
312
  async assetIndex(params) {
896
- return await this.publicRequest({
313
+ return await this.marketRequest({
897
314
  params,
898
- endpoint: "/fapi/v1/assetIndex",
899
- schema: params?.symbol ? FuturesAssetIndexSchema : z$1.array(FuturesAssetIndexSchema)
315
+ endpoint: "/fapi/v1/assetIndex"
900
316
  });
901
317
  }
902
318
  async indexPriceConstituents(params) {
903
- return this.publicRequest({
319
+ return this.marketRequest({
904
320
  params,
905
- endpoint: "/fapi/v1/constituents",
906
- schema: FuturesIndexPriceConstituentsSchema
321
+ endpoint: "/fapi/v1/constituents"
907
322
  });
908
323
  }
909
324
  async insuranceBalance(params) {
910
- const isSingle = !!params?.symbol;
911
- return this.publicRequest({
325
+ return this.marketRequest({
912
326
  params,
913
- endpoint: "/fapi/v1/insuranceBalance",
914
- schema: isSingle ? FuturesInsuranceBalanceEntrySchema : z$1.array(FuturesInsuranceBalanceEntrySchema)
327
+ endpoint: "/fapi/v1/insuranceBalance"
915
328
  });
916
329
  }
917
330
  async accountBalance() {
918
331
  return this.privateRequest({
919
332
  method: "GET",
920
- endpoint: "/fapi/v3/balance",
921
- schema: FuturesAccountBalanceSchema
333
+ endpoint: "/fapi/v3/balance"
922
334
  });
923
335
  }
924
336
  async accountInformation() {
925
337
  return this.privateRequest({
926
338
  method: "GET",
927
- endpoint: "/fapi/v3/account",
928
- schema: FuturesAccountInfoSchema
339
+ endpoint: "/fapi/v3/account"
929
340
  });
930
341
  }
931
342
  async userCommissionRate(params) {
932
343
  return this.privateRequest({
933
344
  method: "GET",
934
345
  endpoint: "/fapi/v1/commissionRate",
935
- params,
936
- schema: FuturesCommissionRateSchema
346
+ params
937
347
  });
938
348
  }
939
349
  async accountConfig() {
940
350
  return this.privateRequest({
941
351
  method: "GET",
942
- endpoint: "/fapi/v1/accountConfig",
943
- schema: FuturesAccountConfigSchema
352
+ endpoint: "/fapi/v1/accountConfig"
944
353
  });
945
354
  }
946
355
  async symbolConfig(params) {
947
356
  return this.privateRequest({
948
357
  method: "GET",
949
358
  endpoint: "/fapi/v1/symbolConfig",
950
- params,
951
- schema: FuturesSymbolConfigSchema
359
+ params
952
360
  });
953
361
  }
954
362
  async userRateLimit() {
955
363
  return this.privateRequest({
956
364
  method: "GET",
957
- endpoint: "/fapi/v1/rateLimit/order",
958
- schema: FuturesUserRateLimitSchema
365
+ endpoint: "/fapi/v1/rateLimit/order"
959
366
  });
960
367
  }
961
368
  async leverageBrackets(params) {
962
369
  return this.privateRequest({
963
370
  method: "GET",
964
371
  endpoint: "/fapi/v1/leverageBracket",
965
- params,
966
- schema: FuturesLeverageBracketSchema
372
+ params
967
373
  });
968
374
  }
969
375
  async positionMode() {
970
376
  return this.privateRequest({
971
377
  method: "GET",
972
- endpoint: "/fapi/v1/positionSide/dual",
973
- schema: FuturesPositionModeSchema
378
+ endpoint: "/fapi/v1/positionSide/dual"
974
379
  });
975
380
  }
976
381
  async incomeHistory(params) {
977
382
  return this.privateRequest({
978
383
  method: "GET",
979
384
  endpoint: "/fapi/v1/income",
980
- params,
981
- schema: FuturesIncomeHistorySchema
385
+ params
982
386
  });
983
387
  }
984
388
  async newOrder(params) {
985
389
  return this.privateRequest({
986
390
  method: "POST",
987
391
  endpoint: "/fapi/v1/order",
988
- params,
989
- schema: FuturesNewOrderSchema
392
+ params
393
+ });
394
+ }
395
+ async getListenKey() {
396
+ return this.privateRequest({
397
+ method: "POST",
398
+ endpoint: "/fapi/v1/listenKey"
990
399
  });
991
400
  }
992
401
  };
993
402
 
994
- //#endregion
995
- //#region src/rest/spot/schema.ts
996
- const SpotTestConnectivitySchema = z.object({});
997
- const SpotCheckServerTimeSchema = z.object({ serverTime: z.number() });
998
-
999
403
  //#endregion
1000
404
  //#region src/rest/spot/client.ts
1001
405
  var SpotRestClient = class extends BaseRestClient {
1002
- constructor({ baseUrl = "https://api.binance.com", apiKey, apiSecret, httpOptions }) {
406
+ constructor({ baseUrl = "https://api.binance.com", apiKey, apiSecret }) {
1003
407
  super({
1004
408
  baseUrl,
1005
409
  apiKey,
1006
- apiSecret,
1007
- httpOptions
410
+ apiSecret
1008
411
  });
1009
412
  }
1010
413
  async testConnectivity() {
1011
- return this.publicRequest({
1012
- endpoint: "/api/v3/ping",
1013
- schema: SpotTestConnectivitySchema
1014
- });
414
+ return this.marketRequest({ endpoint: "/api/v3/ping" });
1015
415
  }
1016
416
  async checkServerTime() {
1017
- return this.publicRequest({
1018
- endpoint: "/api/v3/time",
1019
- schema: SpotCheckServerTimeSchema
1020
- });
417
+ return this.marketRequest({ endpoint: "/api/v3/time" });
1021
418
  }
1022
419
  };
1023
420
 
@@ -1064,8 +461,7 @@ const makeSection = (baseUrl) => {
1064
461
  connectionController = new AbortController();
1065
462
  socket.addEventListener("message", parseMessageEvent, { signal: connectionController.signal });
1066
463
  connectionId = 1;
1067
- const toSubscribe = Array.from(subscriptions.entries()).filter(([_, state]) => state !== "PENDING_UNSUBSCRIPTION").map(([key]) => key);
1068
- return subscribe(toSubscribe);
464
+ return subscribe(Array.from(subscriptions.entries()).filter(([_, state]) => state !== "PENDING_UNSUBSCRIPTION").map(([key]) => key));
1069
465
  }
1070
466
  if (socket.readyState === WebSocket.CONNECTING) socket.addEventListener("open", () => resolve(), { once: true });
1071
467
  if (socket.readyState === WebSocket.CLOSING) socket.addEventListener("close", async () => {
@@ -1198,6 +594,9 @@ const symbolConverter = {
1198
594
  partialBookDepth: (symbol, { levels, updateSpeedMs }) => {
1199
595
  if (updateSpeedMs) return `${symbol.toLowerCase()}@depth${levels}@${updateSpeedMs}ms`;
1200
596
  return `${symbol.toLowerCase()}@depth${levels}`;
597
+ },
598
+ aggTrade: (symbol) => {
599
+ return `${symbol.toLowerCase()}@aggTrade`;
1201
600
  }
1202
601
  };
1203
602
  const createFuturesWebsocketClient = (baseUrl = "wss://stream.binance.com:9443/ws") => {
@@ -1205,4 +604,4 @@ const createFuturesWebsocketClient = (baseUrl = "wss://stream.binance.com:9443/w
1205
604
  };
1206
605
 
1207
606
  //#endregion
1208
- export { ApiError, BinanceRestClient, ErrorMessageParsingError, MalformedParamError, ResponseError, ValidationError, WeightError, createFuturesWebsocketClient };
607
+ export { ApiError, BinanceRestClient, ErrorMessageParsingError, MalformedParamError, ResponseError, WeightError, createFuturesWebsocketClient };