@medievalrain/binance-ts 0.8.0 → 0.9.7

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 +128 -726
  3. package/package.json +18 -13
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;
@@ -586,59 +72,73 @@ var MalformedParamError = class extends ResponseError {
586
72
  }
587
73
  };
588
74
 
589
- //#endregion
590
- //#region src/shared/schema.ts
591
- const ErrorResponseSchema = z.object({
592
- code: z.number(),
593
- msg: z.string()
594
- });
595
-
596
75
  //#endregion
597
76
  //#region src/shared/base-rest-client.ts
598
77
  var BaseRestClient = class {
599
- httpCleint;
600
78
  apiKey;
601
79
  apiSecret;
602
- constructor({ baseUrl, apiKey, apiSecret, httpOptions }) {
80
+ baseUrl;
81
+ constructor({ baseUrl, apiKey, apiSecret }) {
603
82
  this.apiKey = apiKey;
604
83
  this.apiSecret = apiSecret;
605
- this.httpCleint = new Client(baseUrl, {
606
- allowH2: true,
607
- connect: {
608
- maxVersion: "TLSv1.2",
609
- ...httpOptions?.connect
610
- },
611
- ...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" }
612
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");
613
119
  }
614
120
  toSearchParams(rawParams) {
615
- if (!rawParams) return {};
616
- return Object.entries(rawParams).reduce((acc, [key, value]) => {
617
- if (Array.isArray(value)) {
618
- acc[key] = JSON.stringify(value);
619
- return acc;
620
- }
621
- if (value !== void 0 && value !== null) acc[key] = String(value);
622
- return acc;
623
- }, {});
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;
624
128
  }
625
129
  parseErrorResponse(endpoint, statusCode, json) {
626
- const result = ErrorResponseSchema.safeParse(json);
627
- if (result.error) throw new ApiError({
130
+ if (!json.code || !json.msg) throw new ApiError({
628
131
  endpoint,
629
- metadata: {
630
- error: result.error,
631
- json
632
- }
132
+ metadata: { json }
633
133
  });
634
134
  switch (statusCode) {
635
135
  case 418: throw new WeightError({
636
- message: result.data.msg,
136
+ message: json.msg,
637
137
  endpoint
638
138
  });
639
139
  case 400: throw new MalformedParamError({
640
140
  endpoint,
641
- message: result.data.msg
141
+ message: json.msg
642
142
  });
643
143
  default: throw new ApiError({
644
144
  endpoint,
@@ -646,376 +146,275 @@ var BaseRestClient = class {
646
146
  });
647
147
  }
648
148
  }
649
- async parseResponse(schema, response, endpoint) {
650
- const json = await response.body.json();
651
- if (response.statusCode === 200) {
652
- const result = z4.safeParse(schema, json);
653
- if (result.error) throw new ValidationError({
654
- endpoint,
655
- input: json,
656
- error: result.error
657
- });
658
- return result.data;
659
- }
660
- throw this.parseErrorResponse(endpoint, response.statusCode, json);
661
- }
662
- async publicRequest({ endpoint, params, schema }) {
663
- const searchParams = this.toSearchParams(params);
664
- const response = await this.httpCleint.request({
665
- method: "GET",
666
- path: endpoint,
667
- query: searchParams,
668
- headers: { "X-MBX-APIKEY": this.apiKey }
669
- });
670
- return this.parseResponse(schema, response, endpoint);
671
- }
672
- async privateRequest({ endpoint, params, schema, method }) {
673
- if (!this.apiKey || !this.apiSecret) throw new ApiError({
674
- endpoint,
675
- metadata: { cause: "Empty credentials" }
676
- });
677
- const searchParams = this.toSearchParams(params);
678
- searchParams["timestamp"] = (/* @__PURE__ */ new Date()).getTime().toString();
679
- searchParams["signature"] = this.sign(new URLSearchParams(searchParams).toString(), this.apiSecret);
680
- const response = await this.httpCleint.request({
681
- method,
682
- path: endpoint,
683
- query: method !== "POST" ? searchParams : void 0,
684
- body: method === "POST" ? new URLSearchParams(searchParams).toString() : void 0,
685
- headers: { "X-MBX-APIKEY": this.apiKey }
686
- });
687
- return this.parseResponse(schema, response, endpoint);
688
- }
689
- sign(message, secret) {
690
- return createHmac("sha256", secret).update(message).digest("hex");
691
- }
692
149
  };
693
150
 
694
151
  //#endregion
695
152
  //#region src/rest/futures/client.ts
696
153
  var FuturesRestClient = class extends BaseRestClient {
697
- constructor({ baseUrl = "https://fapi.binance.com", apiKey, apiSecret, httpOptions }) {
154
+ constructor({ baseUrl = "https://fapi.binance.com", apiKey, apiSecret }) {
698
155
  super({
699
156
  baseUrl,
700
157
  apiKey,
701
- apiSecret,
702
- httpOptions
158
+ apiSecret
703
159
  });
704
160
  }
705
161
  async testConnectivity() {
706
- return this.publicRequest({
707
- endpoint: "/fapi/v1/ping",
708
- schema: FuturesTestConnectivitySchema
709
- });
162
+ return this.marketRequest({ endpoint: "/fapi/v1/ping" });
710
163
  }
711
164
  async checkServerTime() {
712
- return this.publicRequest({
713
- endpoint: "/fapi/v1/time",
714
- schema: FuturesCheckServerTimeSchema
715
- });
165
+ return this.marketRequest({ endpoint: "/fapi/v1/time" });
716
166
  }
717
167
  async exchangeInformation() {
718
- return this.publicRequest({
719
- endpoint: "/fapi/v1/exchangeInfo",
720
- schema: FuturesExchangeInfoSchema
721
- });
168
+ return this.marketRequest({ endpoint: "/fapi/v1/exchangeInfo" });
722
169
  }
723
170
  async orderBook(params) {
724
- return this.publicRequest({
171
+ return this.marketRequest({
725
172
  params,
726
- endpoint: "/fapi/v1/depth",
727
- schema: FuturesOrderBookSchema
173
+ endpoint: "/fapi/v1/depth"
728
174
  });
729
175
  }
730
176
  async recentTrades(params) {
731
- return this.publicRequest({
177
+ return this.marketRequest({
732
178
  params,
733
- endpoint: "/fapi/v1/trades",
734
- schema: FuturesRecentTradesSchema
179
+ endpoint: "/fapi/v1/trades"
735
180
  });
736
181
  }
737
182
  async oldTradesLookup(params) {
738
183
  return this.privateRequest({
739
184
  method: "GET",
740
185
  params,
741
- endpoint: "/fapi/v1/historicalTrades",
742
- schema: FuturesOldTradesLookupSchema
186
+ endpoint: "/fapi/v1/historicalTrades"
743
187
  });
744
188
  }
745
189
  async aggregateTrades(params) {
746
- return this.publicRequest({
190
+ return this.marketRequest({
747
191
  params,
748
- endpoint: "/fapi/v1/aggTrades",
749
- schema: FuturesAggregateTradesSchema
192
+ endpoint: "/fapi/v1/aggTrades"
750
193
  });
751
194
  }
752
195
  async klineData(params) {
753
- return this.publicRequest({
196
+ return this.marketRequest({
754
197
  params,
755
- endpoint: "/fapi/v1/klines",
756
- schema: FuturesKlineDataSchema
198
+ endpoint: "/fapi/v1/klines"
757
199
  });
758
200
  }
759
201
  async continuousContractKlineData(params) {
760
- return this.publicRequest({
202
+ return this.marketRequest({
761
203
  params,
762
- endpoint: "/fapi/v1/continuousKlines",
763
- schema: FuturesKlineDataSchema
204
+ endpoint: "/fapi/v1/continuousKlines"
764
205
  });
765
206
  }
766
207
  async indexPriceKlineData(params) {
767
- return this.publicRequest({
208
+ return this.marketRequest({
768
209
  params,
769
- endpoint: "/fapi/v1/indexPriceKlines",
770
- schema: FuturesKlineDataSchema
210
+ endpoint: "/fapi/v1/indexPriceKlines"
771
211
  });
772
212
  }
773
213
  async markPriceKlineData(params) {
774
- return this.publicRequest({
214
+ return this.marketRequest({
775
215
  params,
776
- endpoint: "/fapi/v1/markPriceKlines",
777
- schema: FuturesKlineDataSchema
216
+ endpoint: "/fapi/v1/markPriceKlines"
778
217
  });
779
218
  }
780
219
  async premiumIndexKlineData(params) {
781
- return this.publicRequest({
220
+ return this.marketRequest({
782
221
  params,
783
- endpoint: "/fapi/v1/premiumIndexKlines",
784
- schema: FuturesKlineDataSchema
222
+ endpoint: "/fapi/v1/premiumIndexKlines"
785
223
  });
786
224
  }
787
225
  async markPrice(params) {
788
- const isSingle = !!params?.symbol;
789
- return this.publicRequest({
226
+ return this.marketRequest({
790
227
  params,
791
- endpoint: "/fapi/v1/premiumIndex",
792
- schema: isSingle ? FuturesMarkPriceSchema : z$1.array(FuturesMarkPriceSchema)
228
+ endpoint: "/fapi/v1/premiumIndex"
793
229
  });
794
230
  }
795
231
  async fundingRateHistory(params) {
796
- return this.publicRequest({
232
+ return this.marketRequest({
797
233
  params,
798
- endpoint: "/fapi/v1/fundingRate",
799
- schema: FuturesFundingRateSchema
234
+ endpoint: "/fapi/v1/fundingRate"
800
235
  });
801
236
  }
802
237
  async fundingRateInfo() {
803
- return this.publicRequest({
804
- endpoint: "/fapi/v1/fundingInfo",
805
- schema: FuturesFundingInfoSchema
806
- });
238
+ return this.marketRequest({ endpoint: "/fapi/v1/fundingInfo" });
807
239
  }
808
240
  async ticker24h(params) {
809
- return this.publicRequest({
241
+ return this.marketRequest({
810
242
  params,
811
- endpoint: "/fapi/v1/ticker/24hr",
812
- schema: params?.symbol ? FuturesTicker24hSchema : z$1.array(FuturesTicker24hSchema)
243
+ endpoint: "/fapi/v1/ticker/24hr"
813
244
  });
814
245
  }
815
246
  async symbolPriceTicker(params) {
816
- return this.publicRequest({
247
+ return this.marketRequest({
817
248
  params,
818
- endpoint: "/fapi/v2/ticker/price",
819
- schema: params?.symbol ? FuturesSymbolPriceSchema : z$1.array(FuturesSymbolPriceSchema)
249
+ endpoint: "/fapi/v2/ticker/price"
820
250
  });
821
251
  }
822
252
  async bookTicker(params) {
823
- return this.publicRequest({
253
+ return this.marketRequest({
824
254
  params,
825
- endpoint: "/fapi/v1/ticker/bookTicker",
826
- schema: params?.symbol ? FuturesBookTickerSchema : z$1.array(FuturesBookTickerSchema)
255
+ endpoint: "/fapi/v1/ticker/bookTicker"
827
256
  });
828
257
  }
829
258
  async quarterlySettlementPrices(params) {
830
- return this.publicRequest({
259
+ return this.marketRequest({
831
260
  params,
832
- endpoint: "/futures/data/delivery-price",
833
- schema: FuturesDeliveryPriceSchema
261
+ endpoint: "/futures/data/delivery-price"
834
262
  });
835
263
  }
836
264
  async openInterest(params) {
837
- return this.publicRequest({
265
+ return this.marketRequest({
838
266
  params,
839
- endpoint: "/fapi/v1/openInterest",
840
- schema: FuturesOpenInterestSchema
267
+ endpoint: "/fapi/v1/openInterest"
841
268
  });
842
269
  }
843
270
  async openInterestStats(params) {
844
- return this.publicRequest({
271
+ return this.marketRequest({
845
272
  params,
846
- endpoint: "/futures/data/openInterestHist",
847
- schema: FuturesOpenInterestStatsSchema
273
+ endpoint: "/futures/data/openInterestHist"
848
274
  });
849
275
  }
850
276
  async topLongShortPositionRatio(params) {
851
- return this.publicRequest({
277
+ return this.marketRequest({
852
278
  params,
853
- endpoint: "/futures/data/topLongShortPositionRatio",
854
- schema: FuturesLongShortRatioSchema
279
+ endpoint: "/futures/data/topLongShortPositionRatio"
855
280
  });
856
281
  }
857
282
  async topLongShortAccountRatio(params) {
858
- return this.publicRequest({
283
+ return this.marketRequest({
859
284
  params,
860
- endpoint: "/futures/data/topLongShortAccountRatio",
861
- schema: FuturesLongShortRatioSchema
285
+ endpoint: "/futures/data/topLongShortAccountRatio"
862
286
  });
863
287
  }
864
288
  async globalLongShortAccountRatio(params) {
865
- return this.publicRequest({
289
+ return this.marketRequest({
866
290
  params,
867
- endpoint: "/futures/data/globalLongShortAccountRatio",
868
- schema: FuturesLongShortRatioSchema
291
+ endpoint: "/futures/data/globalLongShortAccountRatio"
869
292
  });
870
293
  }
871
294
  async takerBuySellRatio(params) {
872
- return this.publicRequest({
295
+ return this.marketRequest({
873
296
  params,
874
- endpoint: "/futures/data/takerlongshortRatio",
875
- schema: FuturesTakerBuySellRatioSchema
297
+ endpoint: "/futures/data/takerlongshortRatio"
876
298
  });
877
299
  }
878
300
  async basisData(params) {
879
- return this.publicRequest({
301
+ return this.marketRequest({
880
302
  params,
881
- endpoint: "/futures/data/basis",
882
- schema: FuturesBasisSchema
303
+ endpoint: "/futures/data/basis"
883
304
  });
884
305
  }
885
306
  async compositeIndexInfo(params) {
886
- const isSingle = !!params?.symbol;
887
- return await this.publicRequest({
307
+ return await this.marketRequest({
888
308
  params,
889
- endpoint: "/fapi/v1/indexInfo",
890
- schema: isSingle ? FuturesCompositeIndexSchema : z$1.array(FuturesCompositeIndexSchema)
309
+ endpoint: "/fapi/v1/indexInfo"
891
310
  });
892
311
  }
893
312
  async assetIndex(params) {
894
- return await this.publicRequest({
313
+ return await this.marketRequest({
895
314
  params,
896
- endpoint: "/fapi/v1/assetIndex",
897
- schema: params?.symbol ? FuturesAssetIndexSchema : z$1.array(FuturesAssetIndexSchema)
315
+ endpoint: "/fapi/v1/assetIndex"
898
316
  });
899
317
  }
900
318
  async indexPriceConstituents(params) {
901
- return this.publicRequest({
319
+ return this.marketRequest({
902
320
  params,
903
- endpoint: "/fapi/v1/constituents",
904
- schema: FuturesIndexPriceConstituentsSchema
321
+ endpoint: "/fapi/v1/constituents"
905
322
  });
906
323
  }
907
324
  async insuranceBalance(params) {
908
- const isSingle = !!params?.symbol;
909
- return this.publicRequest({
325
+ return this.marketRequest({
910
326
  params,
911
- endpoint: "/fapi/v1/insuranceBalance",
912
- schema: isSingle ? FuturesInsuranceBalanceEntrySchema : z$1.array(FuturesInsuranceBalanceEntrySchema)
327
+ endpoint: "/fapi/v1/insuranceBalance"
913
328
  });
914
329
  }
915
330
  async accountBalance() {
916
331
  return this.privateRequest({
917
332
  method: "GET",
918
- endpoint: "/fapi/v3/balance",
919
- schema: FuturesAccountBalanceSchema
333
+ endpoint: "/fapi/v3/balance"
920
334
  });
921
335
  }
922
336
  async accountInformation() {
923
337
  return this.privateRequest({
924
338
  method: "GET",
925
- endpoint: "/fapi/v3/account",
926
- schema: FuturesAccountInfoSchema
339
+ endpoint: "/fapi/v3/account"
927
340
  });
928
341
  }
929
342
  async userCommissionRate(params) {
930
343
  return this.privateRequest({
931
344
  method: "GET",
932
345
  endpoint: "/fapi/v1/commissionRate",
933
- params,
934
- schema: FuturesCommissionRateSchema
346
+ params
935
347
  });
936
348
  }
937
349
  async accountConfig() {
938
350
  return this.privateRequest({
939
351
  method: "GET",
940
- endpoint: "/fapi/v1/accountConfig",
941
- schema: FuturesAccountConfigSchema
352
+ endpoint: "/fapi/v1/accountConfig"
942
353
  });
943
354
  }
944
355
  async symbolConfig(params) {
945
356
  return this.privateRequest({
946
357
  method: "GET",
947
358
  endpoint: "/fapi/v1/symbolConfig",
948
- params,
949
- schema: FuturesSymbolConfigSchema
359
+ params
950
360
  });
951
361
  }
952
362
  async userRateLimit() {
953
363
  return this.privateRequest({
954
364
  method: "GET",
955
- endpoint: "/fapi/v1/rateLimit/order",
956
- schema: FuturesUserRateLimitSchema
365
+ endpoint: "/fapi/v1/rateLimit/order"
957
366
  });
958
367
  }
959
368
  async leverageBrackets(params) {
960
369
  return this.privateRequest({
961
370
  method: "GET",
962
371
  endpoint: "/fapi/v1/leverageBracket",
963
- params,
964
- schema: FuturesLeverageBracketSchema
372
+ params
965
373
  });
966
374
  }
967
375
  async positionMode() {
968
376
  return this.privateRequest({
969
377
  method: "GET",
970
- endpoint: "/fapi/v1/positionSide/dual",
971
- schema: FuturesPositionModeSchema
378
+ endpoint: "/fapi/v1/positionSide/dual"
972
379
  });
973
380
  }
974
381
  async incomeHistory(params) {
975
382
  return this.privateRequest({
976
383
  method: "GET",
977
384
  endpoint: "/fapi/v1/income",
978
- params,
979
- schema: FuturesIncomeHistorySchema
385
+ params
980
386
  });
981
387
  }
982
388
  async newOrder(params) {
983
389
  return this.privateRequest({
984
390
  method: "POST",
985
391
  endpoint: "/fapi/v1/order",
986
- params,
987
- schema: FuturesNewOrderSchema
392
+ params
393
+ });
394
+ }
395
+ async getListenKey() {
396
+ return this.privateRequest({
397
+ method: "POST",
398
+ endpoint: "/fapi/v1/listenKey"
988
399
  });
989
400
  }
990
401
  };
991
402
 
992
- //#endregion
993
- //#region src/rest/spot/schema.ts
994
- const SpotTestConnectivitySchema = z.object({});
995
- const SpotCheckServerTimeSchema = z.object({ serverTime: z.number() });
996
-
997
403
  //#endregion
998
404
  //#region src/rest/spot/client.ts
999
405
  var SpotRestClient = class extends BaseRestClient {
1000
- constructor({ baseUrl = "https://api.binance.com", apiKey, apiSecret, httpOptions }) {
406
+ constructor({ baseUrl = "https://api.binance.com", apiKey, apiSecret }) {
1001
407
  super({
1002
408
  baseUrl,
1003
409
  apiKey,
1004
- apiSecret,
1005
- httpOptions
410
+ apiSecret
1006
411
  });
1007
412
  }
1008
413
  async testConnectivity() {
1009
- return this.publicRequest({
1010
- endpoint: "/api/v3/ping",
1011
- schema: SpotTestConnectivitySchema
1012
- });
414
+ return this.marketRequest({ endpoint: "/api/v3/ping" });
1013
415
  }
1014
416
  async checkServerTime() {
1015
- return this.publicRequest({
1016
- endpoint: "/api/v3/time",
1017
- schema: SpotCheckServerTimeSchema
1018
- });
417
+ return this.marketRequest({ endpoint: "/api/v3/time" });
1019
418
  }
1020
419
  };
1021
420
 
@@ -1195,6 +594,9 @@ const symbolConverter = {
1195
594
  partialBookDepth: (symbol, { levels, updateSpeedMs }) => {
1196
595
  if (updateSpeedMs) return `${symbol.toLowerCase()}@depth${levels}@${updateSpeedMs}ms`;
1197
596
  return `${symbol.toLowerCase()}@depth${levels}`;
597
+ },
598
+ aggTrade: (symbol) => {
599
+ return `${symbol.toLowerCase()}@aggTrade`;
1198
600
  }
1199
601
  };
1200
602
  const createFuturesWebsocketClient = (baseUrl = "wss://stream.binance.com:9443/ws") => {
@@ -1202,4 +604,4 @@ const createFuturesWebsocketClient = (baseUrl = "wss://stream.binance.com:9443/w
1202
604
  };
1203
605
 
1204
606
  //#endregion
1205
- export { ApiError, BinanceRestClient, ErrorMessageParsingError, MalformedParamError, ResponseError, ValidationError, WeightError, createFuturesWebsocketClient };
607
+ export { ApiError, BinanceRestClient, ErrorMessageParsingError, MalformedParamError, ResponseError, WeightError, createFuturesWebsocketClient };