kucoin-api 2.3.0 → 2.3.2

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 (33) hide show
  1. package/LICENSE.md +7 -0
  2. package/dist/cjs/FuturesClient.d.ts +38 -10
  3. package/dist/cjs/FuturesClient.js +40 -8
  4. package/dist/cjs/FuturesClient.js.map +1 -1
  5. package/dist/cjs/SpotClient.d.ts +17 -13
  6. package/dist/cjs/SpotClient.js +17 -0
  7. package/dist/cjs/SpotClient.js.map +1 -1
  8. package/dist/cjs/WebsocketAPIClient.js +7 -1
  9. package/dist/cjs/WebsocketAPIClient.js.map +1 -1
  10. package/dist/cjs/lib/BaseWSClient.js +3 -1
  11. package/dist/cjs/lib/BaseWSClient.js.map +1 -1
  12. package/dist/cjs/types/request/futures.types.d.ts +29 -0
  13. package/dist/cjs/types/request/spot-margin-trading.d.ts +6 -0
  14. package/dist/cjs/types/response/futures.types.d.ts +24 -0
  15. package/dist/cjs/types/response/spot-account.d.ts +26 -0
  16. package/dist/cjs/types/response/spot-margin-trading.d.ts +12 -0
  17. package/dist/mjs/FuturesClient.d.ts +38 -10
  18. package/dist/mjs/FuturesClient.js +40 -8
  19. package/dist/mjs/FuturesClient.js.map +1 -1
  20. package/dist/mjs/SpotClient.d.ts +17 -13
  21. package/dist/mjs/SpotClient.js +17 -0
  22. package/dist/mjs/SpotClient.js.map +1 -1
  23. package/dist/mjs/WebsocketAPIClient.js +7 -1
  24. package/dist/mjs/WebsocketAPIClient.js.map +1 -1
  25. package/dist/mjs/lib/BaseWSClient.js +3 -1
  26. package/dist/mjs/lib/BaseWSClient.js.map +1 -1
  27. package/dist/mjs/types/request/futures.types.d.ts +29 -0
  28. package/dist/mjs/types/request/spot-margin-trading.d.ts +6 -0
  29. package/dist/mjs/types/response/futures.types.d.ts +24 -0
  30. package/dist/mjs/types/response/spot-account.d.ts +26 -0
  31. package/dist/mjs/types/response/spot-margin-trading.d.ts +12 -0
  32. package/llms.txt +2145 -1938
  33. package/package.json +1 -1
package/llms.txt CHANGED
@@ -125,6 +125,7 @@ src/
125
125
  .nvmrc
126
126
  .prettierrc
127
127
  jest.config.ts
128
+ LICENSE.md
128
129
  package.json
129
130
  postBuild.sh
130
131
  README.md
@@ -1328,362 +1329,561 @@ File: src/lib/misc-util.ts
1328
1329
  export function neverGuard(x: never, msg: string): Error
1329
1330
 
1330
1331
  ================
1331
- File: src/types/request/spot-misc.ts
1332
+ File: src/types/request/broker.types.ts
1332
1333
  ================
1333
- export interface GetAnnouncementsRequest {
1334
+ export interface GetBrokerInfoRequest {
1335
+ begin: string;
1336
+ end: string;
1337
+ tradeType: '1' | '2';
1338
+ }
1339
+ ⋮----
1340
+ export interface GetBrokerSubAccountsRequest {
1341
+ uid: string;
1334
1342
  currentPage?: number;
1335
1343
  pageSize?: number;
1336
- annType?: string;
1337
- lang?: string;
1338
- startTime?: number;
1339
- endTime?: number;
1340
1344
  }
1341
-
1342
- ================
1343
- File: src/types/request/uta-types.ts
1344
- ================
1345
- /**
1346
- * Unified Trading Account Request Types
1347
- */
1348
1345
  ⋮----
1349
- export interface GetAnnouncementsRequestUTA {
1350
- language?:
1351
- | 'zh_HK'
1352
- | 'ja_JP'
1353
- | 'ko_KR'
1354
- | 'en_US'
1355
- | 'pl_PL'
1356
- | 'es_ES'
1357
- | 'fr_FR'
1358
- | 'ar_AE'
1359
- | 'it_IT'
1360
- | 'id_ID'
1361
- | 'nl_NL'
1362
- | 'pt_PT'
1363
- | 'vi_VN'
1364
- | 'de_DE'
1365
- | 'tr_TR'
1366
- | 'ms_MY'
1367
- | 'ru_RU'
1368
- | 'th_TH'
1369
- | 'hi_IN'
1370
- | 'bn_BD'
1371
- | 'fil_PH'
1372
- | 'ur_PK';
1373
- type?:
1374
- | 'latest-announcements'
1375
- | 'activities'
1376
- | 'product-updates'
1377
- | 'vip'
1378
- | 'maintenance-updates'
1379
- | 'delistings'
1380
- | 'others'
1381
- | 'api-campaigns'
1382
- | 'new-listings'
1383
- | 'futures-announcements';
1384
- pageNumber?: number;
1385
- pageSize?: number;
1386
- startTime?: number;
1387
- endTime?: number;
1346
+ export type BrokerSubAccountPermission = 'general' | 'spot' | 'futures';
1347
+ ⋮----
1348
+ export interface CreateBrokerSubAccountApiRequest {
1349
+ uid: string;
1350
+ passphrase: string;
1351
+ ipWhitelist: string[];
1352
+ permissions: BrokerSubAccountPermission[];
1353
+ label: string;
1388
1354
  }
1389
1355
  ⋮----
1390
- export interface GetCurrencyRequestUTA {
1391
- currency?: string;
1392
- chain?: string;
1356
+ export interface GetBrokerSubAccountApisRequest {
1357
+ uid: string;
1358
+ apiKey?: string;
1393
1359
  }
1394
1360
  ⋮----
1395
- export interface GetSymbolRequestUTA {
1396
- tradeType: 'SPOT' | 'FUTURES' | 'ISOLATED' | 'CROSS';
1397
- symbol?: string;
1361
+ export interface UpdateBrokerSubAccountApiRequest {
1362
+ uid: string;
1363
+ apiKey: string;
1364
+ ipWhitelist: string[];
1365
+ permissions: BrokerSubAccountPermission[];
1366
+ label: string;
1398
1367
  }
1399
1368
  ⋮----
1400
- export interface GetTickerRequestUTA {
1401
- tradeType: 'SPOT' | 'FUTURES';
1402
- symbol?: string;
1369
+ export interface DeleteBrokerSubAccountApiRequest {
1370
+ uid: string;
1371
+ apiKey: string;
1403
1372
  }
1404
1373
  ⋮----
1405
- export interface GetTradesRequestUTA {
1406
- tradeType: 'SPOT' | 'FUTURES';
1407
- symbol: string;
1374
+ export type BrokerTransferDirection = 'OUT' | 'IN';
1375
+ export type BrokerAccountType = 'MAIN' | 'TRADE';
1376
+ ⋮----
1377
+ export interface BrokerTransferRequest {
1378
+ currency: string;
1379
+ amount: string;
1380
+ clientOid: string;
1381
+ direction: BrokerTransferDirection;
1382
+ accountType: BrokerAccountType;
1383
+ specialUid: string;
1384
+ specialAccountType: BrokerAccountType;
1408
1385
  }
1409
1386
  ⋮----
1410
- export interface GetOrderBookRequestUTA {
1411
- tradeType: 'SPOT' | 'FUTURES';
1412
- symbol: string;
1413
- limit: '20' | '50' | '100' | 'FULL';
1387
+ export interface GetBrokerDepositListRequest {
1388
+ currency?: string;
1389
+ status?: 'PROCESSING' | 'SUCCESS' | 'FAILURE';
1390
+ hash?: string;
1391
+ startTimestamp?: number;
1392
+ endTimestamp?: number;
1393
+ limit?: number;
1394
+ }
1395
+
1396
+ ================
1397
+ File: src/types/request/spot-account.ts
1398
+ ================
1399
+ export interface GetBalancesRequest {
1400
+ currency?: string;
1401
+ type?: 'main' | 'trade';
1414
1402
  }
1415
1403
  ⋮----
1416
- export interface GetKlinesRequestUTA {
1417
- tradeType: 'SPOT' | 'FUTURES';
1418
- symbol: string;
1419
- interval:
1420
- | '1min'
1421
- | '3min'
1422
- | '5min'
1423
- | '15min'
1424
- | '30min'
1425
- | '1hour'
1426
- | '2hour'
1427
- | '4hour'
1428
- | '6hour'
1429
- | '8hour'
1430
- | '12hour'
1431
- | '1day'
1432
- | '1week'
1433
- | '1month';
1404
+ export interface GetSpotTransactionsRequest {
1405
+ currency?: string;
1406
+ direction?: 'in' | 'out';
1407
+ bizType?:
1408
+ | 'DEPOSIT'
1409
+ | 'WITHDRAW'
1410
+ | 'TRANSFER'
1411
+ | 'SUB_TRANSFER'
1412
+ | 'TRADE_EXCHANGE'
1413
+ | 'MARGIN_EXCHANGE'
1414
+ | 'KUCOIN_BONUS'
1415
+ | 'BROKER_TRANSFER'
1416
+ | 'REBATE';
1434
1417
  startAt?: number;
1435
1418
  endAt?: number;
1419
+ currentPage?: number;
1420
+ pageSize?: number;
1436
1421
  }
1437
1422
  ⋮----
1438
- export interface GetCurrentFundingRateRequestUTA {
1439
- symbol: string;
1423
+ export interface AccountHFTransactionsRequest {
1424
+ currency?: string;
1425
+ direction?: 'in' | 'out';
1426
+ bizType?:
1427
+ | 'TRANSFER'
1428
+ | 'TRADE_EXCHANGE'
1429
+ | 'RETURNED_FEES'
1430
+ | 'DEDUCTION_FEES'
1431
+ | 'OTHER';
1432
+ lastId?: number;
1433
+ limit?: number;
1434
+ startAt?: number;
1435
+ endAt?: number;
1440
1436
  }
1441
1437
  ⋮----
1442
- export interface GetHistoryFundingRateRequestUTA {
1443
- symbol: string;
1444
- startAt: number;
1445
- endAt: number;
1438
+ export interface AccountHFMarginTransactionsRequest {
1439
+ currency?: string;
1440
+ direction?: 'in' | 'out';
1441
+ bizType?:
1442
+ | 'TRANSFER'
1443
+ | 'MARGIN_EXCHANGE'
1444
+ | 'ISOLATED_EXCHANGE'
1445
+ | 'LIQUIDATION'
1446
+ | 'ASSERT_RETURN';
1447
+ lastId?: number;
1448
+ limit?: number;
1449
+ startAt?: number;
1450
+ endAt?: number;
1446
1451
  }
1447
1452
  ⋮----
1448
- export interface GetServiceStatusRequestUTA {
1449
- tradeType: 'SPOT' | 'FUTURES';
1450
- }
1451
-
1452
- ================
1453
- File: src/types/response/shared.types.ts
1454
- ================
1455
- export interface APISuccessResponse<TData> {
1456
- code: '200000';
1457
- data: TData;
1453
+ export interface CreateSubAccountRequest {
1454
+ password: string;
1455
+ remarks?: string;
1456
+ subName: string;
1457
+ access: string;
1458
1458
  }
1459
1459
  ⋮----
1460
- export interface APIErrorResponse {
1461
- msg: string;
1462
- code: string;
1460
+ export interface CreateSubAccountAPIRequest {
1461
+ subName: string;
1462
+ passphrase: string;
1463
+ remark: string;
1464
+ permission?: string;
1465
+ ipWhitelist?: string;
1466
+ expire?: string;
1463
1467
  }
1464
1468
  ⋮----
1465
- export type APIResponse<TData> = APISuccessResponse<TData> | APIErrorResponse;
1466
- ⋮----
1467
- export interface ServiceStatus {
1468
- msg: string;
1469
- status: 'cancelonly' | 'close' | 'open';
1470
- }
1471
-
1472
- ================
1473
- File: src/types/response/spot-misc.ts
1474
- ================
1475
- export interface Announcement {
1476
- annId: number;
1477
- annTitle: string;
1478
- annType: string[];
1479
- annDesc: string;
1480
- cTime: number;
1481
- language: string;
1482
- annUrl: string;
1469
+ export interface UpdateSubAccountAPIRequest {
1470
+ subName: string;
1471
+ apiKey: string;
1472
+ passphrase: string;
1473
+ permission?: string;
1474
+ ipWhitelist?: string;
1475
+ expire?: string;
1483
1476
  }
1484
1477
  ⋮----
1485
- export interface Announcements {
1486
- totalNum: number;
1487
- currentPage: number;
1488
- pageSize: number;
1489
- totalPage: number;
1490
- items: Announcement[];
1478
+ export interface DeleteSubAccountAPIRequest {
1479
+ apiKey: string;
1480
+ passphrase: string;
1481
+ subName: string;
1491
1482
  }
1492
1483
 
1493
1484
  ================
1494
- File: src/types/response/uta-types.ts
1485
+ File: src/types/request/spot-funding.ts
1495
1486
  ================
1496
1487
  /**
1497
- * Unified Trading Account Response Types
1488
+ *
1489
+ ***********
1490
+ * Funding
1491
+ ***********
1492
+ *
1498
1493
  */
1499
1494
  ⋮----
1500
- export interface AnnouncementItemUTA {
1501
- id: number;
1502
- title: string;
1503
- type: string[];
1504
- description: string;
1505
- releaseTime: number;
1506
- language: string;
1507
- url: string;
1495
+ export interface CreateDepositAddressV3Request {
1496
+ currency: string;
1497
+ chain?: string;
1498
+ to?: 'main' | 'trade';
1499
+ amount?: string;
1508
1500
  }
1509
1501
  ⋮----
1510
- export interface GetAnnouncementsResponseUTA {
1511
- totalNumber: number;
1512
- totalPage: number;
1513
- pageNumber: number;
1514
- pageSize: number;
1515
- list: AnnouncementItemUTA[];
1502
+ export interface GetMarginBalanceRequest {
1503
+ quoteCurrency?: string;
1504
+ queryType?: 'MARGIN' | 'MARGIN_V2' | 'ALL';
1516
1505
  }
1517
1506
  ⋮----
1518
- export interface CurrencyChainUTA {
1519
- chainName: string;
1520
- minWithdrawSize: string | null;
1521
- minDepositSize: string | null;
1522
- withdrawFeeRate: string;
1523
- minWithdrawFee: string;
1524
- isWithdrawEnabled: boolean;
1525
- isDepositEnabled: boolean;
1526
- confirms: number;
1527
- preConfirms: number;
1528
- contractAddress: string;
1529
- withdrawPrecision: number;
1530
- maxWithdrawSize: string | null;
1531
- maxDepositSize: string | null;
1532
- needTag: boolean;
1533
- chainId: string;
1507
+ export interface GetIsolatedMarginBalanceRequest {
1508
+ symbol?: string;
1509
+ quoteCurrency?: string;
1510
+ queryType?: 'ISOLATED' | 'ISOLATED_V2' | 'ALL';
1534
1511
  }
1535
1512
  ⋮----
1536
- export interface GetCurrencyResponseUTA {
1513
+ /**
1514
+ *
1515
+ * Deposit
1516
+ *
1517
+ */
1518
+ ⋮----
1519
+ export interface GetDepositsRequest {
1520
+ currency?: string;
1521
+ startAt?: number;
1522
+ endAt?: number;
1523
+ status?: 'PROCESSING' | 'SUCCESS' | 'FAILURE';
1524
+ currentPage?: number;
1525
+ pageSize?: number;
1526
+ }
1527
+ ⋮----
1528
+ /**
1529
+ *
1530
+ * Withdrawals
1531
+ *
1532
+ */
1533
+ ⋮----
1534
+ export interface GetWithdrawalsRequest {
1535
+ currency?: string;
1536
+ status?: 'PROCESSING' | 'WALLET_PROCESSING' | 'SUCCESS' | 'FAILURE';
1537
+ startAt?: number;
1538
+ endAt?: number;
1539
+ currentPage?: number;
1540
+ pageSize?: number;
1541
+ }
1542
+ ⋮----
1543
+ export interface ApplyWithdrawRequest {
1537
1544
  currency: string;
1538
- name: string;
1539
- fullName: string;
1540
- precision: number;
1541
- confirms: number | null;
1542
- contractAddress: string | null;
1543
- isMarginEnabled: boolean;
1544
- isDebitEnabled: boolean;
1545
- list: CurrencyChainUTA[];
1545
+ address: string;
1546
+ amount: number;
1547
+ memo?: string;
1548
+ isInner?: boolean;
1549
+ remark?: string;
1550
+ chain?: string;
1551
+ feeDeductType?: 'INTERNAL' | 'EXTERNAL';
1546
1552
  }
1547
1553
  ⋮----
1548
- export interface SymbolUTA {
1549
- symbol: string;
1550
- name?: string;
1551
- baseCurrency: string;
1552
- quoteCurrency: string;
1553
- market?: string;
1554
- minBaseOrderSize?: string;
1555
- minQuoteOrderSize?: string;
1556
- maxBaseOrderSize?: string | number;
1557
- maxQuoteOrderSize?: string;
1558
- baseOrderStep?: string;
1559
- quoteOrderStep?: string;
1560
- tickSize?: string | number;
1561
- feeCurrency?: string;
1562
- tradingStatus?: string;
1563
- marginMode?: string;
1564
- priceLimitRatio?: string;
1565
- feeCategory?: number;
1566
- makerFeeCoefficient?: string;
1567
- takerFeeCoefficient?: string;
1568
- st?: boolean;
1569
- settlementCurrency?: string;
1570
- contractType?: string;
1571
- isInverse?: boolean;
1572
- launchTime?: number;
1573
- expiryTime?: number | null;
1574
- settlementTime?: number | null;
1575
- maxPrice?: string | number;
1576
- lotSize?: string | number;
1577
- unitSize?: string | number;
1578
- makerFeeRate?: string | number;
1579
- takerFeeRate?: string | number;
1580
- settlementFeeRate?: string | number | null;
1581
- maxLeverage?: number;
1582
- indexSourceExchanges?: string[];
1583
- k?: string | number;
1584
- m?: string | number;
1585
- f?: string | number;
1586
- mmrLimit?: string | number;
1587
- mmrLevConstant?: string | number;
1588
- alertRiskRatio?: string;
1589
- liquidationRiskRatio?: string;
1590
- baseBorrowEnable?: boolean | string;
1591
- quoteBorrowEnable?: boolean | string;
1592
- baseTransferInEnable?: boolean | string;
1593
- quoteTransferInEnable?: boolean | string;
1554
+ export interface SubmitWithdrawV3Request {
1555
+ currency: string;
1556
+ toAddress: string;
1557
+ amount: number;
1558
+ memo?: string;
1559
+ isInner?: boolean;
1560
+ remark?: string;
1561
+ chain?: string;
1562
+ feeDeductType?: 'INTERNAL' | 'EXTERNAL';
1563
+ withdrawType: 'ADDRESS' | 'UID' | 'MAIL' | 'PHONE';
1594
1564
  }
1595
1565
  ⋮----
1596
- export interface GetSymbolResponseUTA {
1597
- tradeType: string;
1598
- list: SymbolUTA[];
1566
+ /**
1567
+ *
1568
+ * Transfer
1569
+ *
1570
+ */
1571
+ ⋮----
1572
+ export interface GetTransferableRequest {
1573
+ currency: string;
1574
+ type:
1575
+ | 'MAIN'
1576
+ | 'TRADE'
1577
+ | 'TRADE_HF'
1578
+ | 'MARGIN'
1579
+ | 'ISOLATED'
1580
+ | 'OPTION'
1581
+ | 'MARGIN_V2'
1582
+ | 'ISOLATED_V2';
1583
+ tag?: string;
1599
1584
  }
1600
1585
  ⋮----
1601
- export interface TickerUTA {
1602
- symbol: string;
1603
- name?: string;
1604
- bestBidPrice: string;
1605
- bestBidSize: string;
1606
- bestAskPrice: string;
1607
- bestAskSize: string;
1608
- high: string;
1609
- low: string;
1610
- baseVolume: string;
1611
- quoteVolume: string;
1612
- lastPrice: string;
1613
- open: string;
1614
- size: string;
1586
+ export interface FlexTransferRequest {
1587
+ clientOid: string;
1588
+ currency?: string;
1589
+ amount: string;
1590
+ fromUserId?: string;
1591
+ fromAccountType:
1592
+ | 'MAIN'
1593
+ | 'TRADE'
1594
+ | 'CONTRACT'
1595
+ | 'MARGIN'
1596
+ | 'ISOLATED'
1597
+ | 'TRADE_HF'
1598
+ | 'MARGIN_V2'
1599
+ | 'ISOLATED_V2'
1600
+ | 'OPTION';
1601
+ fromAccountTag?: string;
1602
+ type: 'INTERNAL' | 'PARENT_TO_SUB' | 'SUB_TO_PARENT';
1603
+ toUserId?: string;
1604
+ toAccountType:
1605
+ | 'MAIN'
1606
+ | 'TRADE'
1607
+ | 'CONTRACT'
1608
+ | 'MARGIN'
1609
+ | 'ISOLATED'
1610
+ | 'TRADE_HF'
1611
+ | 'MARGIN_V2'
1612
+ | 'ISOLATED_V2'
1613
+ | 'OPTION';
1614
+ toAccountTag?: string;
1615
1615
  }
1616
1616
  ⋮----
1617
- export interface GetTickerResponseUTA {
1618
- tradeType: string;
1619
- ts: number;
1620
- list: TickerUTA[];
1617
+ export interface submitTransferMasterSubRequest {
1618
+ clientOid: string;
1619
+ currency: string;
1620
+ amount: string;
1621
+ direction: 'OUT' | 'IN';
1622
+ accountType?:
1623
+ | 'MAIN'
1624
+ | 'TRADE'
1625
+ | 'TRADE_HF'
1626
+ | 'MARGIN'
1627
+ | 'CONTRACT'
1628
+ | 'OPTION';
1629
+ subAccountType?:
1630
+ | 'MAIN'
1631
+ | 'TRADE'
1632
+ | 'TRADE_HF'
1633
+ | 'MARGIN'
1634
+ | 'CONTRACT'
1635
+ | 'OPTION';
1636
+ subUserId: string;
1621
1637
  }
1622
1638
  ⋮----
1623
- export interface TradeUTA {
1624
- sequence: string;
1625
- tradeId: string;
1626
- price: string;
1627
- size: string;
1628
- side: 'buy' | 'sell';
1629
- ts: number;
1639
+ export interface InnerTransferRequest {
1640
+ clientOid: string;
1641
+ currency: string;
1642
+ from:
1643
+ | 'main'
1644
+ | 'trade'
1645
+ | 'trade_hf'
1646
+ | 'margin'
1647
+ | 'isolated'
1648
+ | 'margin_v2'
1649
+ | 'isolated_v2'
1650
+ | 'contract'
1651
+ | 'option';
1652
+ to:
1653
+ | 'main'
1654
+ | 'trade'
1655
+ | 'trade_hf'
1656
+ | 'margin'
1657
+ | 'isolated'
1658
+ | 'margin_v2'
1659
+ | 'isolated_v2'
1660
+ | 'contract'
1661
+ | 'option';
1662
+ amount: string;
1663
+ fromTag?: string;
1664
+ toTag?: string;
1665
+ }
1666
+
1667
+ ================
1668
+ File: src/types/request/spot-misc.ts
1669
+ ================
1670
+ export interface GetAnnouncementsRequest {
1671
+ currentPage?: number;
1672
+ pageSize?: number;
1673
+ annType?: string;
1674
+ lang?: string;
1675
+ startTime?: number;
1676
+ endTime?: number;
1677
+ }
1678
+
1679
+ ================
1680
+ File: src/types/response/broker.types.ts
1681
+ ================
1682
+ export interface BrokerInfo {
1683
+ accountSize: number;
1684
+ maxAccountSize: number | null;
1685
+ level: number;
1686
+ }
1687
+ ⋮----
1688
+ export interface CreateBrokerSubAccountResponse {
1689
+ accountName: string;
1690
+ uid: string;
1691
+ createdAt: number;
1692
+ level: number;
1693
+ }
1694
+ ⋮----
1695
+ export interface BrokerSubAccount {
1696
+ accountName: string;
1697
+ uid: string;
1698
+ createdAt: number;
1699
+ level: number;
1700
+ }
1701
+ ⋮----
1702
+ export interface GetBrokerSubAccountsResponse {
1703
+ currentPage: number;
1704
+ pageSize: number;
1705
+ totalNum: number;
1706
+ totalPage: number;
1707
+ items: BrokerSubAccount[];
1708
+ }
1709
+ ⋮----
1710
+ export interface CreateBrokerSubAccountApiResponse {
1711
+ uid: string;
1712
+ label: string;
1713
+ apiKey: string;
1714
+ secretKey: string;
1715
+ apiVersion: number;
1716
+ permissions: string[];
1717
+ ipWhitelist: string[];
1718
+ createdAt: number;
1719
+ }
1720
+ ⋮----
1721
+ export interface BrokerSubAccountApi {
1722
+ uid: string;
1723
+ label: string;
1724
+ apiKey: string;
1725
+ apiVersion: number;
1726
+ permissions: ('General' | 'Spot' | 'Futures')[];
1727
+ ipWhitelist: string[];
1728
+ createdAt: number;
1729
+ }
1730
+ ⋮----
1731
+ export type BrokerTransferAccountType =
1732
+ | 'MAIN'
1733
+ | 'TRADE'
1734
+ | 'CONTRACT'
1735
+ | 'MARGIN'
1736
+ | 'ISOLATED';
1737
+ export type BrokerTransferStatus = 'PROCESSING' | 'SUCCESS' | 'FAILURE';
1738
+ ⋮----
1739
+ export interface BrokerTransferHistory {
1740
+ orderId: string;
1741
+ currency: string;
1742
+ amount: string;
1743
+ fromUid: number;
1744
+ fromAccountType: BrokerTransferAccountType;
1745
+ fromAccountTag: string;
1746
+ toUid: number;
1747
+ toAccountType: BrokerTransferAccountType;
1748
+ toAccountTag: string;
1749
+ status: BrokerTransferStatus;
1750
+ reason: string | null;
1751
+ createdAt: number;
1630
1752
  }
1631
1753
  ⋮----
1632
- export interface GetTradesResponseUTA {
1633
- tradeType: string;
1634
- list: TradeUTA[];
1754
+ export interface BrokerDepositRecord {
1755
+ uid: number;
1756
+ hash: string;
1757
+ address: string;
1758
+ memo: string;
1759
+ amount: string;
1760
+ fee: string;
1761
+ currency: string;
1762
+ isInner: boolean;
1763
+ walletTxId: string;
1764
+ status: BrokerTransferStatus;
1765
+ remark: string;
1766
+ chain: string;
1767
+ createdAt: number;
1768
+ updatedAt: number;
1635
1769
  }
1636
1770
  ⋮----
1637
- export interface OrderBookLevelUTA {
1638
- price: string;
1639
- size: string;
1640
- }
1771
+ export type BrokerWithdrawalStatus =
1772
+ | 'PROCESSING'
1773
+ | 'WALLET_PROCESSING'
1774
+ | 'REVIEW'
1775
+ | 'SUCCESS'
1776
+ | 'FAILURE';
1641
1777
  ⋮----
1642
- export interface GetOrderBookResponseUTA {
1643
- tradeType: string;
1644
- symbol: string;
1645
- sequence: string;
1646
- bids: OrderBookLevelUTA[];
1647
- asks: OrderBookLevelUTA[];
1778
+ export interface BrokerWithdrawalRecord {
1779
+ id: string;
1780
+ chain: string;
1781
+ walletTxId: string;
1782
+ uid: number;
1783
+ amount: string;
1784
+ memo: string;
1785
+ fee: string;
1786
+ address: string;
1787
+ remark: string;
1788
+ isInner: boolean;
1789
+ currency: string;
1790
+ status: BrokerWithdrawalStatus;
1791
+ createdAt: number;
1792
+ updatedAt: number;
1793
+ }
1794
+
1795
+ ================
1796
+ File: src/types/response/shared.types.ts
1797
+ ================
1798
+ export interface APISuccessResponse<TData> {
1799
+ code: '200000';
1800
+ data: TData;
1648
1801
  }
1649
1802
  ⋮----
1650
- export interface GetKlinesResponseUTA {
1651
- tradeType: string;
1652
- symbol: string;
1653
- list: string[][]; // [time, open, close, high, low, volume, turnover]
1803
+ export interface APIErrorResponse {
1804
+ msg: string;
1805
+ code: string;
1654
1806
  }
1655
1807
  ⋮----
1656
- list: string[][]; // [time, open, close, high, low, volume, turnover]
1808
+ export type APIResponse<TData> = APISuccessResponse<TData> | APIErrorResponse;
1657
1809
  ⋮----
1658
- export interface GetCurrentFundingRateResponseUTA {
1659
- symbol: string;
1660
- nextFundingRate: number;
1661
- fundingTime: number;
1662
- fundingRateCap: number;
1663
- fundingRateFloor: number;
1810
+ export interface ServiceStatus {
1811
+ msg: string;
1812
+ status: 'cancelonly' | 'close' | 'open';
1813
+ }
1814
+
1815
+ ================
1816
+ File: src/types/response/spot-misc.ts
1817
+ ================
1818
+ export interface Announcement {
1819
+ annId: number;
1820
+ annTitle: string;
1821
+ annType: string[];
1822
+ annDesc: string;
1823
+ cTime: number;
1824
+ language: string;
1825
+ annUrl: string;
1664
1826
  }
1665
1827
  ⋮----
1666
- export interface FundingRateHistoryItemUTA {
1667
- fundingRate: number;
1668
- ts: number;
1828
+ export interface Announcements {
1829
+ totalNum: number;
1830
+ currentPage: number;
1831
+ pageSize: number;
1832
+ totalPage: number;
1833
+ items: Announcement[];
1669
1834
  }
1835
+
1836
+ ================
1837
+ File: src/types/response/spot-vip.ts
1838
+ ================
1839
+ /**
1840
+ *
1841
+ ***********
1842
+ * VIP LENDING
1843
+ ***********
1844
+ *
1845
+ */
1670
1846
  ⋮----
1671
- export interface GetHistoryFundingRateResponseUTA {
1672
- symbol: string;
1673
- list: FundingRateHistoryItemUTA[];
1847
+ export interface DiscountRateConfig {
1848
+ currency: string;
1849
+ usdtLevels: {
1850
+ left: number;
1851
+ right: number;
1852
+ discountRate: string;
1853
+ }[];
1674
1854
  }
1675
1855
  ⋮----
1676
- export interface GetCrossMarginConfigResponseUTA {
1677
- maxLeverage: number;
1678
- alertRiskRatio: string;
1679
- liquidationRiskRatio: string;
1680
- currencyList: string[];
1856
+ export interface OtcLoan {
1857
+ parentUid: string;
1858
+ orders: {
1859
+ orderId: string;
1860
+ currency: string;
1861
+ principal: string;
1862
+ interest: string;
1863
+ }[];
1864
+ ltv: {
1865
+ transferLtv: string;
1866
+ onlyClosePosLtv: string;
1867
+ delayedLiquidationLtv: string;
1868
+ instantLiquidationLtv: string;
1869
+ currentLtv: string;
1870
+ };
1871
+ totalMarginAmount: string;
1872
+ transferMarginAmount: string;
1873
+ margins: {
1874
+ marginCcy: string;
1875
+ marginQty: string;
1876
+ marginFactor: string;
1877
+ }[];
1681
1878
  }
1682
1879
  ⋮----
1683
- export interface GetServiceStatusResponseUTA {
1684
- tradeType: string;
1685
- serverStatus: 'open' | 'close' | 'cancelonly';
1686
- msg: string;
1880
+ export interface OtcLoanAccount {
1881
+ uid: string;
1882
+ marginCcy: string;
1883
+ marginQty: string;
1884
+ marginFactor: string;
1885
+ accountType: 'TRADE' | 'TRADE_HF' | 'CONTRACT';
1886
+ isParent: boolean;
1687
1887
  }
1688
1888
 
1689
1889
  ================
@@ -1703,153 +1903,222 @@ export interface WsConnectionInfo {
1703
1903
  }
1704
1904
 
1705
1905
  ================
1706
- File: src/UnifiedAPIClient.ts
1906
+ File: src/BrokerClient.ts
1707
1907
  ================
1708
- import { AxiosRequestConfig } from 'axios';
1709
- ⋮----
1710
1908
  import { BaseRestClient } from './lib/BaseRestClient.js';
1909
+ import { REST_CLIENT_TYPE_ENUM, RestClientType } from './lib/requestUtils.js';
1711
1910
  import {
1712
- REST_CLIENT_TYPE_ENUM,
1713
- RestClientOptions,
1714
- RestClientType,
1715
- } from './lib/requestUtils.js';
1911
+ BrokerTransferRequest,
1912
+ CreateBrokerSubAccountApiRequest,
1913
+ DeleteBrokerSubAccountApiRequest,
1914
+ GetBrokerDepositListRequest,
1915
+ GetBrokerInfoRequest,
1916
+ GetBrokerSubAccountApisRequest,
1917
+ GetBrokerSubAccountsRequest,
1918
+ UpdateBrokerSubAccountApiRequest,
1919
+ } from './types/request/broker.types.js';
1716
1920
  import {
1717
- GetAnnouncementsRequestUTA,
1718
- GetCurrencyRequestUTA,
1719
- GetCurrentFundingRateRequestUTA,
1720
- GetHistoryFundingRateRequestUTA,
1721
- GetKlinesRequestUTA,
1722
- GetOrderBookRequestUTA,
1723
- GetServiceStatusRequestUTA,
1724
- GetSymbolRequestUTA,
1725
- GetTickerRequestUTA,
1726
- GetTradesRequestUTA,
1727
- } from './types/request/uta-types.js';
1921
+ BrokerDepositRecord,
1922
+ BrokerInfo,
1923
+ BrokerSubAccountApi,
1924
+ BrokerTransferHistory,
1925
+ BrokerWithdrawalRecord,
1926
+ CreateBrokerSubAccountApiResponse,
1927
+ CreateBrokerSubAccountResponse,
1928
+ GetBrokerSubAccountsResponse,
1929
+ } from './types/response/broker.types.js';
1728
1930
  import { APISuccessResponse } from './types/response/shared.types.js';
1729
- import {
1730
- GetAnnouncementsResponseUTA,
1731
- GetCrossMarginConfigResponseUTA,
1732
- GetCurrencyResponseUTA,
1733
- GetCurrentFundingRateResponseUTA,
1734
- GetHistoryFundingRateResponseUTA,
1735
- GetKlinesResponseUTA,
1736
- GetOrderBookResponseUTA,
1737
- GetServiceStatusResponseUTA,
1738
- GetSymbolResponseUTA,
1739
- GetTickerResponseUTA,
1740
- GetTradesResponseUTA,
1741
- } from './types/response/uta-types.js';
1742
1931
  ⋮----
1743
1932
  /**
1744
- * Unified Trading Account Client
1745
1933
  *
1746
- * This client provides access to the Unified Trading Account API endpoints
1747
- * that unify market data access across Spot, Futures, and Margin trading.
1748
1934
  */
1749
- export class UnifiedAPIClient extends BaseRestClient
1750
- ⋮----
1751
- constructor(
1752
- restClientOptions: RestClientOptions = {},
1753
- requestOptions: AxiosRequestConfig = {},
1754
- )
1935
+ export class BrokerClient extends BaseRestClient
1755
1936
  ⋮----
1756
1937
  getClientType(): RestClientType
1757
1938
  ⋮----
1758
1939
  /**
1940
+ * Get Broker Info
1759
1941
  *
1760
- * REST - Unified Trading Account - Market Data
1942
+ * This endpoint supports querying the basic information of the current Broker
1943
+ */
1944
+ getBrokerInfo(
1945
+ params: GetBrokerInfoRequest,
1946
+ ): Promise<APISuccessResponse<BrokerInfo>>
1947
+ ⋮----
1948
+ /**
1949
+ * Add SubAccount
1761
1950
  *
1951
+ * This endpoint supports Broker users to create sub-accounts.
1952
+ * Note that the account name is unique across the exchange.
1953
+ * It is recommended to add a special identifier to prevent name duplication.
1762
1954
  */
1955
+ createSubAccount(params: {
1956
+ accountName: string;
1957
+ }): Promise<APISuccessResponse<CreateBrokerSubAccountResponse>>
1763
1958
  ⋮----
1764
1959
  /**
1765
- * Get Announcements
1766
- * This interface can obtain the latest news announcements, and the default
1767
- * page search is for announcements within a month.
1960
+ * Get SubAccount
1961
+ *
1962
+ * This interface supports querying sub-accounts created by Broker.
1963
+ * Returns paginated results with default page size of 20 (max 100).
1964
+ */
1965
+ getSubAccounts(
1966
+ params: GetBrokerSubAccountsRequest,
1967
+ ): Promise<APISuccessResponse<GetBrokerSubAccountsResponse>>
1968
+ ⋮----
1969
+ /**
1970
+ * Add SubAccount API
1971
+ *
1972
+ * This interface supports the creation of Broker sub-account APIKEY.
1973
+ * Supports up to 20 IPs in the whitelist.
1974
+ * Only General, Spot, and Futures permissions can be set.
1975
+ * Label must be between 4 and 32 characters.
1768
1976
  */
1769
- getAnnouncements(
1770
- params?: GetAnnouncementsRequestUTA,
1771
- ): Promise<APISuccessResponse<GetAnnouncementsResponseUTA>>
1977
+ createSubAccountApi(
1978
+ params: CreateBrokerSubAccountApiRequest,
1979
+ ): Promise<APISuccessResponse<CreateBrokerSubAccountApiResponse>>
1772
1980
  ⋮----
1773
1981
  /**
1774
- * Get Currency
1775
- * Request the currency details of a specified currency via this endpoint.
1982
+ * Get SubAccount API
1983
+ *
1984
+ * This interface supports querying the Broker's sub-account APIKEYs.
1985
+ * Can optionally filter by specific apiKey.
1776
1986
  */
1777
- getCurrency(
1778
- params?: GetCurrencyRequestUTA,
1779
- ): Promise<APISuccessResponse<GetCurrencyResponseUTA>>
1987
+ getSubAccountApis(
1988
+ params: GetBrokerSubAccountApisRequest,
1989
+ ): Promise<APISuccessResponse<BrokerSubAccountApi[]>>
1780
1990
  ⋮----
1781
1991
  /**
1782
- * Get Symbol
1783
- * Request a list of available currency pairs for trading via this endpoint.
1992
+ * Modify SubAccount API
1993
+ *
1994
+ * This interface supports modifying the Broker's sub-account APIKEY.
1995
+ * Supports up to 20 IPs in the whitelist.
1996
+ * Only General, Spot, and Futures permissions can be set.
1997
+ * Label must be between 4 and 32 characters.
1784
1998
  */
1785
- getSymbol(
1786
- params: GetSymbolRequestUTA,
1787
- ): Promise<APISuccessResponse<GetSymbolResponseUTA>>
1999
+ updateSubAccountApi(
2000
+ params: UpdateBrokerSubAccountApiRequest,
2001
+ ): Promise<APISuccessResponse<BrokerSubAccountApi>>
1788
2002
  ⋮----
1789
2003
  /**
1790
- * Get Ticker
1791
- * Request market tickers for the trading pairs in the market (including 24h volume).
2004
+ * Delete SubAccount API
2005
+ *
2006
+ * This interface supports deleting Broker's sub-account APIKEY.
1792
2007
  */
1793
- getTicker(
1794
- params: GetTickerRequestUTA,
1795
- ): Promise<APISuccessResponse<GetTickerResponseUTA>>
2008
+ deleteSubAccountApi(
2009
+ params: DeleteBrokerSubAccountApiRequest,
2010
+ ): Promise<APISuccessResponse<boolean>>
1796
2011
  ⋮----
1797
2012
  /**
1798
- * Get Trades
1799
- * Request via this endpoint to get the latest 100 public trades of the specified symbol.
2013
+ * Transfer
2014
+ *
2015
+ * This endpoint supports fund transfer between Broker account and Broker sub-accounts.
2016
+ * Please be aware that withdrawal from sub-account is not directly supported.
2017
+ * Broker has to transfer funds from broker sub-account to broker account to initiate the withdrawals.
2018
+ *
2019
+ * Direction:
2020
+ * - OUT: Broker account is transferred to Broker sub-account
2021
+ * - IN: Broker sub-account is transferred to Broker account
2022
+ *
2023
+ * Account Types:
2024
+ * - MAIN: Funding account
2025
+ * - TRADE: Spot trading account
1800
2026
  */
1801
- getTrades(
1802
- params: GetTradesRequestUTA,
1803
- ): Promise<APISuccessResponse<GetTradesResponseUTA>>
2027
+ submitTransfer(params: BrokerTransferRequest): Promise<
2028
+ APISuccessResponse<{
2029
+ orderId: string;
2030
+ }>
2031
+ > {
2032
+ return this.postPrivate('api/v1/broker/nd/transfer', params);
1804
2033
  ⋮----
1805
2034
  /**
1806
- * Get OrderBook
1807
- * Query order book depth information (aggregated by price).
2035
+ * Get Transfer History
2036
+ *
2037
+ * This endpoint supports querying transfer records of the broker itself and its created sub-accounts.
2038
+ *
2039
+ * Account Types:
2040
+ * - MAIN: Funding account
2041
+ * - TRADE: Spot trading account
2042
+ * - CONTRACT: Contract account
2043
+ * - MARGIN: Margin account
2044
+ * - ISOLATED: Isolated margin account
2045
+ *
2046
+ * Status:
2047
+ * - PROCESSING: Processing
2048
+ * - SUCCESS: Successful
2049
+ * - FAILURE: Failed
1808
2050
  */
1809
- getOrderBook(
1810
- params: GetOrderBookRequestUTA,
1811
- ): Promise<APISuccessResponse<GetOrderBookResponseUTA>>
2051
+ getTransferHistory(params: {
2052
+ orderId: string;
2053
+ }): Promise<APISuccessResponse<BrokerTransferHistory>>
1812
2054
  ⋮----
1813
2055
  /**
1814
- * Get Klines
1815
- * Get the Kline of the symbol. Data are returned in grouped buckets based on requested type.
2056
+ * Get Deposit List
2057
+ *
2058
+ * This endpoint can obtain the deposit records of each sub-account under the ND Broker.
2059
+ * Default limit is 1000 records (max 1000).
2060
+ * Results are sorted in descending order by default.
2061
+ *
2062
+ * Status:
2063
+ * - PROCESSING: Processing
2064
+ * - SUCCESS: Successful
2065
+ * - FAILURE: Failed
1816
2066
  */
1817
- getKlines(
1818
- params: GetKlinesRequestUTA,
1819
- ): Promise<APISuccessResponse<GetKlinesResponseUTA>>
2067
+ getDeposits(
2068
+ params?: GetBrokerDepositListRequest,
2069
+ ): Promise<APISuccessResponse<BrokerDepositRecord[]>>
1820
2070
  ⋮----
1821
2071
  /**
1822
- * Get Current Funding Rate
1823
- * Get current Futures funding fee rate.
2072
+ * Get Deposit Detail
2073
+ *
2074
+ * This endpoint supports querying the deposit record of sub-accounts created by a Broker
2075
+ * (excluding main account of nd broker).
2076
+ *
2077
+ * Status:
2078
+ * - PROCESSING: Processing
2079
+ * - SUCCESS: Successful
2080
+ * - FAILURE: Failed
1824
2081
  */
1825
- getCurrentFundingRate(
1826
- params: GetCurrentFundingRateRequestUTA,
1827
- ): Promise<APISuccessResponse<GetCurrentFundingRateResponseUTA>>
2082
+ getDeposit(params: {
2083
+ currency: string;
2084
+ hash: string;
2085
+ }): Promise<APISuccessResponse<BrokerDepositRecord>>
1828
2086
  ⋮----
1829
2087
  /**
1830
- * Get History Funding Rate
1831
- * Query the Futures funding rate at each settlement time point within a certain time range.
2088
+ * Get Withdrawal Detail
2089
+ *
2090
+ * This endpoint supports querying the withdrawal records of sub-accounts created by a Broker
2091
+ * (excluding main account of nd broker).
2092
+ *
2093
+ * Status:
2094
+ * - PROCESSING: Processing
2095
+ * - WALLET_PROCESSING: Wallet Processing
2096
+ * - REVIEW: Under Review
2097
+ * - SUCCESS: Successful
2098
+ * - FAILURE: Failed
1832
2099
  */
1833
- getHistoryFundingRate(
1834
- params: GetHistoryFundingRateRequestUTA,
1835
- ): Promise<APISuccessResponse<GetHistoryFundingRateResponseUTA>>
2100
+ getWithdrawal(params: {
2101
+ withdrawalId: string;
2102
+ }): Promise<APISuccessResponse<BrokerWithdrawalRecord>>
1836
2103
  ⋮----
1837
2104
  /**
1838
- * Get Cross Margin Config
1839
- * Request the configure info of the 'spot cross margin' via this endpoint.
2105
+ * Get Broker Rebate
2106
+ *
2107
+ * This interface supports downloading Broker rebate orders.
2108
+ * Returns a URL to download a CSV file containing the rebate data.
2109
+ * The URL is valid for 1 day.
2110
+ * Maximum interval between begin and end dates is 6 months.
1840
2111
  */
1841
- getCrossMarginConfig(): Promise<
1842
- APISuccessResponse<GetCrossMarginConfigResponseUTA>
2112
+ getBrokerRebate(params: {
2113
+ begin: string;
2114
+ end: string;
2115
+ tradeType: '1' | '2';
2116
+ }): Promise<
2117
+ APISuccessResponse<{
2118
+ url: string;
2119
+ }>
1843
2120
  > {
1844
- return this.get('api/ua/v1/market/cross-config');
1845
- ⋮----
1846
- /**
1847
- * Get Service Status
1848
- * Get the service status.
1849
- */
1850
- getServiceStatus(
1851
- params: GetServiceStatusRequestUTA,
1852
- ): Promise<APISuccessResponse<GetServiceStatusResponseUTA>>
2121
+ return this.getPrivate('api/v1/broker/nd/rebase/download', params);
1853
2122
 
1854
2123
  ================
1855
2124
  File: .prettierrc
@@ -2553,200 +2822,47 @@ export interface WsStoredState<TWSTopicSubscribeEvent extends string | object> {
2553
2822
  /**
2554
2823
  * All the topics we are expected to be subscribed to on this connection (and we automatically resubscribe to if the connection drops)
2555
2824
  *
2556
- * A "Set" and a deep-object-match are used to ensure we only subscribe to a topic once (tracking a list of unique topics we're expected to be connected to)
2557
- */
2558
- ⋮----
2559
- /** Whether this connection has completed authentication (only applies to private connections) */
2560
- ⋮----
2561
- /**
2562
- * Whether this connection has completed authentication before for the Websocket API, so it knows to automatically reauth if reconnected
2563
- */
2564
- ⋮----
2565
- /** To reauthenticate on the WS API, which channel do we send to? */
2566
-
2567
- ================
2568
- File: src/lib/webCryptoAPI.ts
2569
- ================
2570
- import { neverGuard } from './misc-util.js';
2571
- ⋮----
2572
- function bufferToB64(buffer: ArrayBuffer): string
2573
- ⋮----
2574
- export type SignEncodeMethod = 'hex' | 'base64';
2575
- export type SignAlgorithm = 'SHA-256' | 'SHA-512';
2576
- ⋮----
2577
- /**
2578
- * Similar to node crypto's `createHash()` function
2579
- */
2580
- export async function hashMessage(
2581
- message: string,
2582
- method: SignEncodeMethod,
2583
- algorithm: SignAlgorithm,
2584
- ): Promise<string>
2585
- ⋮----
2586
- /**
2587
- * Sign a message, with a secret, using the Web Crypto API
2588
- */
2589
- export async function signMessage(
2590
- message: string,
2591
- secret: string,
2592
- method: SignEncodeMethod,
2593
- algorithm: SignAlgorithm,
2594
- ): Promise<string>
2595
- ⋮----
2596
- export function checkWebCryptoAPISupported()
2597
-
2598
- ================
2599
- File: src/types/request/broker.types.ts
2600
- ================
2601
- export interface GetBrokerInfoRequest {
2602
- begin: string;
2603
- end: string;
2604
- tradeType: '1' | '2';
2605
- }
2606
- ⋮----
2607
- export interface GetBrokerSubAccountsRequest {
2608
- uid: string;
2609
- currentPage?: number;
2610
- pageSize?: number;
2611
- }
2612
- ⋮----
2613
- export type BrokerSubAccountPermission = 'general' | 'spot' | 'futures';
2614
- ⋮----
2615
- export interface CreateBrokerSubAccountApiRequest {
2616
- uid: string;
2617
- passphrase: string;
2618
- ipWhitelist: string[];
2619
- permissions: BrokerSubAccountPermission[];
2620
- label: string;
2621
- }
2622
- ⋮----
2623
- export interface GetBrokerSubAccountApisRequest {
2624
- uid: string;
2625
- apiKey?: string;
2626
- }
2627
- ⋮----
2628
- export interface UpdateBrokerSubAccountApiRequest {
2629
- uid: string;
2630
- apiKey: string;
2631
- ipWhitelist: string[];
2632
- permissions: BrokerSubAccountPermission[];
2633
- label: string;
2634
- }
2635
- ⋮----
2636
- export interface DeleteBrokerSubAccountApiRequest {
2637
- uid: string;
2638
- apiKey: string;
2639
- }
2825
+ * A "Set" and a deep-object-match are used to ensure we only subscribe to a topic once (tracking a list of unique topics we're expected to be connected to)
2826
+ */
2640
2827
  ⋮----
2641
- export type BrokerTransferDirection = 'OUT' | 'IN';
2642
- export type BrokerAccountType = 'MAIN' | 'TRADE';
2828
+ /** Whether this connection has completed authentication (only applies to private connections) */
2643
2829
  ⋮----
2644
- export interface BrokerTransferRequest {
2645
- currency: string;
2646
- amount: string;
2647
- clientOid: string;
2648
- direction: BrokerTransferDirection;
2649
- accountType: BrokerAccountType;
2650
- specialUid: string;
2651
- specialAccountType: BrokerAccountType;
2652
- }
2830
+ /**
2831
+ * Whether this connection has completed authentication before for the Websocket API, so it knows to automatically reauth if reconnected
2832
+ */
2653
2833
  ⋮----
2654
- export interface GetBrokerDepositListRequest {
2655
- currency?: string;
2656
- status?: 'PROCESSING' | 'SUCCESS' | 'FAILURE';
2657
- hash?: string;
2658
- startTimestamp?: number;
2659
- endTimestamp?: number;
2660
- limit?: number;
2661
- }
2834
+ /** To reauthenticate on the WS API, which channel do we send to? */
2662
2835
 
2663
2836
  ================
2664
- File: src/types/request/spot-account.ts
2837
+ File: src/lib/webCryptoAPI.ts
2665
2838
  ================
2666
- export interface GetBalancesRequest {
2667
- currency?: string;
2668
- type?: 'main' | 'trade';
2669
- }
2670
- ⋮----
2671
- export interface GetSpotTransactionsRequest {
2672
- currency?: string;
2673
- direction?: 'in' | 'out';
2674
- bizType?:
2675
- | 'DEPOSIT'
2676
- | 'WITHDRAW'
2677
- | 'TRANSFER'
2678
- | 'SUB_TRANSFER'
2679
- | 'TRADE_EXCHANGE'
2680
- | 'MARGIN_EXCHANGE'
2681
- | 'KUCOIN_BONUS'
2682
- | 'BROKER_TRANSFER'
2683
- | 'REBATE';
2684
- startAt?: number;
2685
- endAt?: number;
2686
- currentPage?: number;
2687
- pageSize?: number;
2688
- }
2689
- ⋮----
2690
- export interface AccountHFTransactionsRequest {
2691
- currency?: string;
2692
- direction?: 'in' | 'out';
2693
- bizType?:
2694
- | 'TRANSFER'
2695
- | 'TRADE_EXCHANGE'
2696
- | 'RETURNED_FEES'
2697
- | 'DEDUCTION_FEES'
2698
- | 'OTHER';
2699
- lastId?: number;
2700
- limit?: number;
2701
- startAt?: number;
2702
- endAt?: number;
2703
- }
2839
+ import { neverGuard } from './misc-util.js';
2704
2840
  ⋮----
2705
- export interface AccountHFMarginTransactionsRequest {
2706
- currency?: string;
2707
- direction?: 'in' | 'out';
2708
- bizType?:
2709
- | 'TRANSFER'
2710
- | 'MARGIN_EXCHANGE'
2711
- | 'ISOLATED_EXCHANGE'
2712
- | 'LIQUIDATION'
2713
- | 'ASSERT_RETURN';
2714
- lastId?: number;
2715
- limit?: number;
2716
- startAt?: number;
2717
- endAt?: number;
2718
- }
2841
+ function bufferToB64(buffer: ArrayBuffer): string
2719
2842
  ⋮----
2720
- export interface CreateSubAccountRequest {
2721
- password: string;
2722
- remarks?: string;
2723
- subName: string;
2724
- access: string;
2725
- }
2843
+ export type SignEncodeMethod = 'hex' | 'base64';
2844
+ export type SignAlgorithm = 'SHA-256' | 'SHA-512';
2726
2845
  ⋮----
2727
- export interface CreateSubAccountAPIRequest {
2728
- subName: string;
2729
- passphrase: string;
2730
- remark: string;
2731
- permission?: string;
2732
- ipWhitelist?: string;
2733
- expire?: string;
2734
- }
2846
+ /**
2847
+ * Similar to node crypto's `createHash()` function
2848
+ */
2849
+ export async function hashMessage(
2850
+ message: string,
2851
+ method: SignEncodeMethod,
2852
+ algorithm: SignAlgorithm,
2853
+ ): Promise<string>
2735
2854
  ⋮----
2736
- export interface UpdateSubAccountAPIRequest {
2737
- subName: string;
2738
- apiKey: string;
2739
- passphrase: string;
2740
- permission?: string;
2741
- ipWhitelist?: string;
2742
- expire?: string;
2743
- }
2855
+ /**
2856
+ * Sign a message, with a secret, using the Web Crypto API
2857
+ */
2858
+ export async function signMessage(
2859
+ message: string,
2860
+ secret: string,
2861
+ method: SignEncodeMethod,
2862
+ algorithm: SignAlgorithm,
2863
+ ): Promise<string>
2744
2864
  ⋮----
2745
- export interface DeleteSubAccountAPIRequest {
2746
- apiKey: string;
2747
- passphrase: string;
2748
- subName: string;
2749
- }
2865
+ export function checkWebCryptoAPISupported()
2750
2866
 
2751
2867
  ================
2752
2868
  File: src/types/request/spot-convert.ts
@@ -2877,245 +2993,62 @@ export interface InitiateRedemptionRequest {
2877
2993
  confirmPunishRedeem?: '1';
2878
2994
  }
2879
2995
  ⋮----
2880
- export interface GetEarnRedeemPreviewRequest {
2881
- orderId: string;
2882
- fromAccountType?: 'MAIN' | 'TRADE';
2883
- }
2884
- ⋮----
2885
- export interface GetEarnFixedIncomeHoldAssetsRequest {
2886
- currentPage?: number;
2887
- pageSize?: number;
2888
- productId?: string;
2889
- productCategory?: string;
2890
- currency?: string;
2891
- }
2892
- ⋮----
2893
- /**
2894
- *
2895
- * STRUCTURED EARN - DUAL
2896
- *
2897
- */
2898
- ⋮----
2899
- export interface StructuredProductPurchaseRequest {
2900
- productId: string; // required - Product ID
2901
- investCurrency: string; // required - Investment currency
2902
- investAmount: string; // required - Subscription amount
2903
- accountType: 'MAIN' | 'TRADE'; // required - MAIN (funding account), TRADE (spot trading account)
2904
- }
2905
- ⋮----
2906
- productId: string; // required - Product ID
2907
- investCurrency: string; // required - Investment currency
2908
- investAmount: string; // required - Subscription amount
2909
- accountType: 'MAIN' | 'TRADE'; // required - MAIN (funding account), TRADE (spot trading account)
2910
- ⋮----
2911
- export interface GetDualInvestmentProductsRequest {
2912
- category: 'DUAL_CLASSIC' | 'DUAL_BOOSTER' | 'DUAL_EXTRA'; // required - Product category
2913
- strikeCurrency?: string; // optional - Strike Currency
2914
- investCurrency?: string; // optional - Investment Currency
2915
- side?: 'CALL' | 'PUT'; // optional - Direction
2916
- }
2917
- ⋮----
2918
- category: 'DUAL_CLASSIC' | 'DUAL_BOOSTER' | 'DUAL_EXTRA'; // required - Product category
2919
- strikeCurrency?: string; // optional - Strike Currency
2920
- investCurrency?: string; // optional - Investment Currency
2921
- side?: 'CALL' | 'PUT'; // optional - Direction
2922
- ⋮----
2923
- export interface GetStructuredProductOrdersRequest {
2924
- categories: string; // required - Product categories, multiple categories are supported, e.g. DUAL_CLASSIC, DUAL_BOOSTER, DUAL_EXTRA
2925
- orderId?: string; // optional - Order Id
2926
- investCurrency?: string; // optional - Investment Currency
2927
- currentPage?: number; // optional - Current Page, default: 1
2928
- pageSize?: number; // optional - Page Size >= 10, <= 500, default: 15
2929
- }
2930
- ⋮----
2931
- categories: string; // required - Product categories, multiple categories are supported, e.g. DUAL_CLASSIC, DUAL_BOOSTER, DUAL_EXTRA
2932
- orderId?: string; // optional - Order Id
2933
- investCurrency?: string; // optional - Investment Currency
2934
- currentPage?: number; // optional - Current Page, default: 1
2935
- pageSize?: number; // optional - Page Size >= 10, <= 500, default: 15
2936
-
2937
- ================
2938
- File: src/types/request/spot-funding.ts
2939
- ================
2940
- /**
2941
- *
2942
- ***********
2943
- * Funding
2944
- ***********
2945
- *
2946
- */
2947
- ⋮----
2948
- export interface CreateDepositAddressV3Request {
2949
- currency: string;
2950
- chain?: string;
2951
- to?: 'main' | 'trade';
2952
- amount?: string;
2953
- }
2954
- ⋮----
2955
- export interface GetMarginBalanceRequest {
2956
- quoteCurrency?: string;
2957
- queryType?: 'MARGIN' | 'MARGIN_V2' | 'ALL';
2958
- }
2959
- ⋮----
2960
- export interface GetIsolatedMarginBalanceRequest {
2961
- symbol?: string;
2962
- quoteCurrency?: string;
2963
- queryType?: 'ISOLATED' | 'ISOLATED_V2' | 'ALL';
2964
- }
2965
- ⋮----
2966
- /**
2967
- *
2968
- * Deposit
2969
- *
2970
- */
2971
- ⋮----
2972
- export interface GetDepositsRequest {
2973
- currency?: string;
2974
- startAt?: number;
2975
- endAt?: number;
2976
- status?: 'PROCESSING' | 'SUCCESS' | 'FAILURE';
2977
- currentPage?: number;
2978
- pageSize?: number;
2979
- }
2980
- ⋮----
2981
- /**
2982
- *
2983
- * Withdrawals
2984
- *
2985
- */
2986
- ⋮----
2987
- export interface GetWithdrawalsRequest {
2988
- currency?: string;
2989
- status?: 'PROCESSING' | 'WALLET_PROCESSING' | 'SUCCESS' | 'FAILURE';
2990
- startAt?: number;
2991
- endAt?: number;
2992
- currentPage?: number;
2993
- pageSize?: number;
2994
- }
2995
- ⋮----
2996
- export interface ApplyWithdrawRequest {
2997
- currency: string;
2998
- address: string;
2999
- amount: number;
3000
- memo?: string;
3001
- isInner?: boolean;
3002
- remark?: string;
3003
- chain?: string;
3004
- feeDeductType?: 'INTERNAL' | 'EXTERNAL';
3005
- }
3006
- ⋮----
3007
- export interface SubmitWithdrawV3Request {
3008
- currency: string;
3009
- toAddress: string;
3010
- amount: number;
3011
- memo?: string;
3012
- isInner?: boolean;
3013
- remark?: string;
3014
- chain?: string;
3015
- feeDeductType?: 'INTERNAL' | 'EXTERNAL';
3016
- withdrawType: 'ADDRESS' | 'UID' | 'MAIL' | 'PHONE';
2996
+ export interface GetEarnRedeemPreviewRequest {
2997
+ orderId: string;
2998
+ fromAccountType?: 'MAIN' | 'TRADE';
2999
+ }
3000
+ ⋮----
3001
+ export interface GetEarnFixedIncomeHoldAssetsRequest {
3002
+ currentPage?: number;
3003
+ pageSize?: number;
3004
+ productId?: string;
3005
+ productCategory?: string;
3006
+ currency?: string;
3017
3007
  }
3018
3008
  ⋮----
3019
3009
  /**
3020
3010
  *
3021
- * Transfer
3011
+ * STRUCTURED EARN - DUAL
3022
3012
  *
3023
3013
  */
3024
3014
  ⋮----
3025
- export interface GetTransferableRequest {
3026
- currency: string;
3027
- type:
3028
- | 'MAIN'
3029
- | 'TRADE'
3030
- | 'TRADE_HF'
3031
- | 'MARGIN'
3032
- | 'ISOLATED'
3033
- | 'OPTION'
3034
- | 'MARGIN_V2'
3035
- | 'ISOLATED_V2';
3036
- tag?: string;
3015
+ export interface StructuredProductPurchaseRequest {
3016
+ productId: string; // required - Product ID
3017
+ investCurrency: string; // required - Investment currency
3018
+ investAmount: string; // required - Subscription amount
3019
+ accountType: 'MAIN' | 'TRADE'; // required - MAIN (funding account), TRADE (spot trading account)
3037
3020
  }
3038
3021
  ⋮----
3039
- export interface FlexTransferRequest {
3040
- clientOid: string;
3041
- currency?: string;
3042
- amount: string;
3043
- fromUserId?: string;
3044
- fromAccountType:
3045
- | 'MAIN'
3046
- | 'TRADE'
3047
- | 'CONTRACT'
3048
- | 'MARGIN'
3049
- | 'ISOLATED'
3050
- | 'TRADE_HF'
3051
- | 'MARGIN_V2'
3052
- | 'ISOLATED_V2'
3053
- | 'OPTION';
3054
- fromAccountTag?: string;
3055
- type: 'INTERNAL' | 'PARENT_TO_SUB' | 'SUB_TO_PARENT';
3056
- toUserId?: string;
3057
- toAccountType:
3058
- | 'MAIN'
3059
- | 'TRADE'
3060
- | 'CONTRACT'
3061
- | 'MARGIN'
3062
- | 'ISOLATED'
3063
- | 'TRADE_HF'
3064
- | 'MARGIN_V2'
3065
- | 'ISOLATED_V2'
3066
- | 'OPTION';
3067
- toAccountTag?: string;
3068
- }
3022
+ productId: string; // required - Product ID
3023
+ investCurrency: string; // required - Investment currency
3024
+ investAmount: string; // required - Subscription amount
3025
+ accountType: 'MAIN' | 'TRADE'; // required - MAIN (funding account), TRADE (spot trading account)
3069
3026
  ⋮----
3070
- export interface submitTransferMasterSubRequest {
3071
- clientOid: string;
3072
- currency: string;
3073
- amount: string;
3074
- direction: 'OUT' | 'IN';
3075
- accountType?:
3076
- | 'MAIN'
3077
- | 'TRADE'
3078
- | 'TRADE_HF'
3079
- | 'MARGIN'
3080
- | 'CONTRACT'
3081
- | 'OPTION';
3082
- subAccountType?:
3083
- | 'MAIN'
3084
- | 'TRADE'
3085
- | 'TRADE_HF'
3086
- | 'MARGIN'
3087
- | 'CONTRACT'
3088
- | 'OPTION';
3089
- subUserId: string;
3027
+ export interface GetDualInvestmentProductsRequest {
3028
+ category: 'DUAL_CLASSIC' | 'DUAL_BOOSTER' | 'DUAL_EXTRA'; // required - Product category
3029
+ strikeCurrency?: string; // optional - Strike Currency
3030
+ investCurrency?: string; // optional - Investment Currency
3031
+ side?: 'CALL' | 'PUT'; // optional - Direction
3090
3032
  }
3091
3033
  ⋮----
3092
- export interface InnerTransferRequest {
3093
- clientOid: string;
3094
- currency: string;
3095
- from:
3096
- | 'main'
3097
- | 'trade'
3098
- | 'trade_hf'
3099
- | 'margin'
3100
- | 'isolated'
3101
- | 'margin_v2'
3102
- | 'isolated_v2'
3103
- | 'contract'
3104
- | 'option';
3105
- to:
3106
- | 'main'
3107
- | 'trade'
3108
- | 'trade_hf'
3109
- | 'margin'
3110
- | 'isolated'
3111
- | 'margin_v2'
3112
- | 'isolated_v2'
3113
- | 'contract'
3114
- | 'option';
3115
- amount: string;
3116
- fromTag?: string;
3117
- toTag?: string;
3034
+ category: 'DUAL_CLASSIC' | 'DUAL_BOOSTER' | 'DUAL_EXTRA'; // required - Product category
3035
+ strikeCurrency?: string; // optional - Strike Currency
3036
+ investCurrency?: string; // optional - Investment Currency
3037
+ side?: 'CALL' | 'PUT'; // optional - Direction
3038
+ ⋮----
3039
+ export interface GetStructuredProductOrdersRequest {
3040
+ categories: string; // required - Product categories, multiple categories are supported, e.g. DUAL_CLASSIC, DUAL_BOOSTER, DUAL_EXTRA
3041
+ orderId?: string; // optional - Order Id
3042
+ investCurrency?: string; // optional - Investment Currency
3043
+ currentPage?: number; // optional - Current Page, default: 1
3044
+ pageSize?: number; // optional - Page Size >= 10, <= 500, default: 15
3118
3045
  }
3046
+ ⋮----
3047
+ categories: string; // required - Product categories, multiple categories are supported, e.g. DUAL_CLASSIC, DUAL_BOOSTER, DUAL_EXTRA
3048
+ orderId?: string; // optional - Order Id
3049
+ investCurrency?: string; // optional - Investment Currency
3050
+ currentPage?: number; // optional - Current Page, default: 1
3051
+ pageSize?: number; // optional - Page Size >= 10, <= 500, default: 15
3119
3052
 
3120
3053
  ================
3121
3054
  File: src/types/request/spot-margin-trading.ts
@@ -3478,6 +3411,15 @@ export interface GetMarginOcoOrderDetailByOrderIdRequest {
3478
3411
  }
3479
3412
  ⋮----
3480
3413
  orderId: string; // Order ID
3414
+ ⋮----
3415
+ /**
3416
+ * Get Margin Collateral Ratio
3417
+ */
3418
+ export interface GetMarginCollateralRatioRequest {
3419
+ currencyList?: string; // If not specified, all currencies will be returned. Supports multiple currencies, separated by commas.
3420
+ }
3421
+ ⋮----
3422
+ currencyList?: string; // If not specified, all currencies will be returned. Supports multiple currencies, separated by commas.
3481
3423
 
3482
3424
  ================
3483
3425
  File: src/types/request/spot-trading.ts
@@ -3771,119 +3713,113 @@ export interface GetOCOOrdersRequest {
3771
3713
  }
3772
3714
 
3773
3715
  ================
3774
- File: src/types/response/broker.types.ts
3716
+ File: src/types/request/uta-types.ts
3775
3717
  ================
3776
- export interface BrokerInfo {
3777
- accountSize: number;
3778
- maxAccountSize: number | null;
3779
- level: number;
3718
+ /**
3719
+ * Unified Trading Account Request Types
3720
+ */
3721
+ ⋮----
3722
+ export interface GetAnnouncementsRequestUTA {
3723
+ language?:
3724
+ | 'zh_HK'
3725
+ | 'ja_JP'
3726
+ | 'ko_KR'
3727
+ | 'en_US'
3728
+ | 'pl_PL'
3729
+ | 'es_ES'
3730
+ | 'fr_FR'
3731
+ | 'ar_AE'
3732
+ | 'it_IT'
3733
+ | 'id_ID'
3734
+ | 'nl_NL'
3735
+ | 'pt_PT'
3736
+ | 'vi_VN'
3737
+ | 'de_DE'
3738
+ | 'tr_TR'
3739
+ | 'ms_MY'
3740
+ | 'ru_RU'
3741
+ | 'th_TH'
3742
+ | 'hi_IN'
3743
+ | 'bn_BD'
3744
+ | 'fil_PH'
3745
+ | 'ur_PK';
3746
+ type?:
3747
+ | 'latest-announcements'
3748
+ | 'activities'
3749
+ | 'product-updates'
3750
+ | 'vip'
3751
+ | 'maintenance-updates'
3752
+ | 'delistings'
3753
+ | 'others'
3754
+ | 'api-campaigns'
3755
+ | 'new-listings'
3756
+ | 'futures-announcements';
3757
+ pageNumber?: number;
3758
+ pageSize?: number;
3759
+ startTime?: number;
3760
+ endTime?: number;
3780
3761
  }
3781
3762
  ⋮----
3782
- export interface CreateBrokerSubAccountResponse {
3783
- accountName: string;
3784
- uid: string;
3785
- createdAt: number;
3786
- level: number;
3763
+ export interface GetCurrencyRequestUTA {
3764
+ currency?: string;
3765
+ chain?: string;
3787
3766
  }
3788
3767
  ⋮----
3789
- export interface BrokerSubAccount {
3790
- accountName: string;
3791
- uid: string;
3792
- createdAt: number;
3793
- level: number;
3768
+ export interface GetSymbolRequestUTA {
3769
+ tradeType: 'SPOT' | 'FUTURES' | 'ISOLATED' | 'CROSS';
3770
+ symbol?: string;
3794
3771
  }
3795
3772
  ⋮----
3796
- export interface GetBrokerSubAccountsResponse {
3797
- currentPage: number;
3798
- pageSize: number;
3799
- totalNum: number;
3800
- totalPage: number;
3801
- items: BrokerSubAccount[];
3773
+ export interface GetTickerRequestUTA {
3774
+ tradeType: 'SPOT' | 'FUTURES';
3775
+ symbol?: string;
3802
3776
  }
3803
3777
  ⋮----
3804
- export interface CreateBrokerSubAccountApiResponse {
3805
- uid: string;
3806
- label: string;
3807
- apiKey: string;
3808
- secretKey: string;
3809
- apiVersion: number;
3810
- permissions: string[];
3811
- ipWhitelist: string[];
3812
- createdAt: number;
3778
+ export interface GetTradesRequestUTA {
3779
+ tradeType: 'SPOT' | 'FUTURES';
3780
+ symbol: string;
3813
3781
  }
3814
3782
  ⋮----
3815
- export interface BrokerSubAccountApi {
3816
- uid: string;
3817
- label: string;
3818
- apiKey: string;
3819
- apiVersion: number;
3820
- permissions: ('General' | 'Spot' | 'Futures')[];
3821
- ipWhitelist: string[];
3822
- createdAt: number;
3783
+ export interface GetOrderBookRequestUTA {
3784
+ tradeType: 'SPOT' | 'FUTURES';
3785
+ symbol: string;
3786
+ limit: '20' | '50' | '100' | 'FULL';
3787
+ }
3788
+ ⋮----
3789
+ export interface GetKlinesRequestUTA {
3790
+ tradeType: 'SPOT' | 'FUTURES';
3791
+ symbol: string;
3792
+ interval:
3793
+ | '1min'
3794
+ | '3min'
3795
+ | '5min'
3796
+ | '15min'
3797
+ | '30min'
3798
+ | '1hour'
3799
+ | '2hour'
3800
+ | '4hour'
3801
+ | '6hour'
3802
+ | '8hour'
3803
+ | '12hour'
3804
+ | '1day'
3805
+ | '1week'
3806
+ | '1month';
3807
+ startAt?: number;
3808
+ endAt?: number;
3823
3809
  }
3824
3810
  ⋮----
3825
- export type BrokerTransferAccountType =
3826
- | 'MAIN'
3827
- | 'TRADE'
3828
- | 'CONTRACT'
3829
- | 'MARGIN'
3830
- | 'ISOLATED';
3831
- export type BrokerTransferStatus = 'PROCESSING' | 'SUCCESS' | 'FAILURE';
3832
- ⋮----
3833
- export interface BrokerTransferHistory {
3834
- orderId: string;
3835
- currency: string;
3836
- amount: string;
3837
- fromUid: number;
3838
- fromAccountType: BrokerTransferAccountType;
3839
- fromAccountTag: string;
3840
- toUid: number;
3841
- toAccountType: BrokerTransferAccountType;
3842
- toAccountTag: string;
3843
- status: BrokerTransferStatus;
3844
- reason: string | null;
3845
- createdAt: number;
3811
+ export interface GetCurrentFundingRateRequestUTA {
3812
+ symbol: string;
3846
3813
  }
3847
3814
  ⋮----
3848
- export interface BrokerDepositRecord {
3849
- uid: number;
3850
- hash: string;
3851
- address: string;
3852
- memo: string;
3853
- amount: string;
3854
- fee: string;
3855
- currency: string;
3856
- isInner: boolean;
3857
- walletTxId: string;
3858
- status: BrokerTransferStatus;
3859
- remark: string;
3860
- chain: string;
3861
- createdAt: number;
3862
- updatedAt: number;
3815
+ export interface GetHistoryFundingRateRequestUTA {
3816
+ symbol: string;
3817
+ startAt: number;
3818
+ endAt: number;
3863
3819
  }
3864
3820
  ⋮----
3865
- export type BrokerWithdrawalStatus =
3866
- | 'PROCESSING'
3867
- | 'WALLET_PROCESSING'
3868
- | 'REVIEW'
3869
- | 'SUCCESS'
3870
- | 'FAILURE';
3871
- ⋮----
3872
- export interface BrokerWithdrawalRecord {
3873
- id: string;
3874
- chain: string;
3875
- walletTxId: string;
3876
- uid: number;
3877
- amount: string;
3878
- memo: string;
3879
- fee: string;
3880
- address: string;
3881
- remark: string;
3882
- isInner: boolean;
3883
- currency: string;
3884
- status: BrokerWithdrawalStatus;
3885
- createdAt: number;
3886
- updatedAt: number;
3821
+ export interface GetServiceStatusRequestUTA {
3822
+ tradeType: 'SPOT' | 'FUTURES';
3887
3823
  }
3888
3824
 
3889
3825
  ================
@@ -4109,6 +4045,52 @@ export interface DeleteSubAccountAPI {
4109
4045
  subName: string;
4110
4046
  apiKey: string;
4111
4047
  }
4048
+ ⋮----
4049
+ /**
4050
+ * Get KYC Regions Response
4051
+ */
4052
+ export interface KYCRegion {
4053
+ code: string; // Two-letter country code
4054
+ enName: string; // English name of the region
4055
+ }
4056
+ ⋮----
4057
+ code: string; // Two-letter country code
4058
+ enName: string; // English name of the region
4059
+ ⋮----
4060
+ /**
4061
+ * Get API Key Info Response
4062
+ */
4063
+ export interface ApiKeyInfo {
4064
+ uid: number; // Account UID
4065
+ parentUid?: number; // Master account UID. Returns empty when called by the master account itself
4066
+ region: string; // KYC region of the account, returns the two-letter country code
4067
+ kycStatus: 0 | 1; // KYC status
4068
+ subName?: string; // Sub-account name (not present for the master account)
4069
+ remark: string; // Remarks
4070
+ apiKey: string; // API key
4071
+ apiVersion: number; // API version
4072
+ permission: string; // Permissions
4073
+ ipWhitelist?: string; // IP whitelist (comma-separated list of allowed IPs)
4074
+ isMaster: boolean; // Indicates whether this is the master account
4075
+ createdAt: number; // API key creation timestamp (Unix milliseconds)
4076
+ expiredAt?: number | null; // API key expiration timestamp (Unix milliseconds). Returns null if no expiration is set
4077
+ thirdPartyApp?: string; // Third-party application name. Returns empty string if not associated with any third-party app
4078
+ }
4079
+ ⋮----
4080
+ uid: number; // Account UID
4081
+ parentUid?: number; // Master account UID. Returns empty when called by the master account itself
4082
+ region: string; // KYC region of the account, returns the two-letter country code
4083
+ kycStatus: 0 | 1; // KYC status
4084
+ subName?: string; // Sub-account name (not present for the master account)
4085
+ remark: string; // Remarks
4086
+ apiKey: string; // API key
4087
+ apiVersion: number; // API version
4088
+ permission: string; // Permissions
4089
+ ipWhitelist?: string; // IP whitelist (comma-separated list of allowed IPs)
4090
+ isMaster: boolean; // Indicates whether this is the master account
4091
+ createdAt: number; // API key creation timestamp (Unix milliseconds)
4092
+ expiredAt?: number | null; // API key expiration timestamp (Unix milliseconds). Returns null if no expiration is set
4093
+ thirdPartyApp?: string; // Third-party application name. Returns empty string if not associated with any third-party app
4112
4094
 
4113
4095
  ================
4114
4096
  File: src/types/response/spot-convert.ts
@@ -4440,56 +4422,199 @@ totalPage: number; // Total number of pages
4440
4422
  items: StructuredProductOrder[]; // List of structured product holdings
4441
4423
 
4442
4424
  ================
4443
- File: src/types/response/spot-vip.ts
4425
+ File: src/types/response/uta-types.ts
4444
4426
  ================
4445
4427
  /**
4446
- *
4447
- ***********
4448
- * VIP LENDING
4449
- ***********
4450
- *
4428
+ * Unified Trading Account Response Types
4451
4429
  */
4452
4430
  ⋮----
4453
- export interface DiscountRateConfig {
4454
- currency: string;
4455
- usdtLevels: {
4456
- left: number;
4457
- right: number;
4458
- discountRate: string;
4459
- }[];
4431
+ export interface AnnouncementItemUTA {
4432
+ id: number;
4433
+ title: string;
4434
+ type: string[];
4435
+ description: string;
4436
+ releaseTime: number;
4437
+ language: string;
4438
+ url: string;
4439
+ }
4440
+ ⋮----
4441
+ export interface GetAnnouncementsResponseUTA {
4442
+ totalNumber: number;
4443
+ totalPage: number;
4444
+ pageNumber: number;
4445
+ pageSize: number;
4446
+ list: AnnouncementItemUTA[];
4447
+ }
4448
+ ⋮----
4449
+ export interface CurrencyChainUTA {
4450
+ chainName: string;
4451
+ minWithdrawSize: string | null;
4452
+ minDepositSize: string | null;
4453
+ withdrawFeeRate: string;
4454
+ minWithdrawFee: string;
4455
+ isWithdrawEnabled: boolean;
4456
+ isDepositEnabled: boolean;
4457
+ confirms: number;
4458
+ preConfirms: number;
4459
+ contractAddress: string;
4460
+ withdrawPrecision: number;
4461
+ maxWithdrawSize: string | null;
4462
+ maxDepositSize: string | null;
4463
+ needTag: boolean;
4464
+ chainId: string;
4465
+ }
4466
+ ⋮----
4467
+ export interface GetCurrencyResponseUTA {
4468
+ currency: string;
4469
+ name: string;
4470
+ fullName: string;
4471
+ precision: number;
4472
+ confirms: number | null;
4473
+ contractAddress: string | null;
4474
+ isMarginEnabled: boolean;
4475
+ isDebitEnabled: boolean;
4476
+ list: CurrencyChainUTA[];
4477
+ }
4478
+ ⋮----
4479
+ export interface SymbolUTA {
4480
+ symbol: string;
4481
+ name?: string;
4482
+ baseCurrency: string;
4483
+ quoteCurrency: string;
4484
+ market?: string;
4485
+ minBaseOrderSize?: string;
4486
+ minQuoteOrderSize?: string;
4487
+ maxBaseOrderSize?: string | number;
4488
+ maxQuoteOrderSize?: string;
4489
+ baseOrderStep?: string;
4490
+ quoteOrderStep?: string;
4491
+ tickSize?: string | number;
4492
+ feeCurrency?: string;
4493
+ tradingStatus?: string;
4494
+ marginMode?: string;
4495
+ priceLimitRatio?: string;
4496
+ feeCategory?: number;
4497
+ makerFeeCoefficient?: string;
4498
+ takerFeeCoefficient?: string;
4499
+ st?: boolean;
4500
+ settlementCurrency?: string;
4501
+ contractType?: string;
4502
+ isInverse?: boolean;
4503
+ launchTime?: number;
4504
+ expiryTime?: number | null;
4505
+ settlementTime?: number | null;
4506
+ maxPrice?: string | number;
4507
+ lotSize?: string | number;
4508
+ unitSize?: string | number;
4509
+ makerFeeRate?: string | number;
4510
+ takerFeeRate?: string | number;
4511
+ settlementFeeRate?: string | number | null;
4512
+ maxLeverage?: number;
4513
+ indexSourceExchanges?: string[];
4514
+ k?: string | number;
4515
+ m?: string | number;
4516
+ f?: string | number;
4517
+ mmrLimit?: string | number;
4518
+ mmrLevConstant?: string | number;
4519
+ alertRiskRatio?: string;
4520
+ liquidationRiskRatio?: string;
4521
+ baseBorrowEnable?: boolean | string;
4522
+ quoteBorrowEnable?: boolean | string;
4523
+ baseTransferInEnable?: boolean | string;
4524
+ quoteTransferInEnable?: boolean | string;
4525
+ }
4526
+ ⋮----
4527
+ export interface GetSymbolResponseUTA {
4528
+ tradeType: string;
4529
+ list: SymbolUTA[];
4530
+ }
4531
+ ⋮----
4532
+ export interface TickerUTA {
4533
+ symbol: string;
4534
+ name?: string;
4535
+ bestBidPrice: string;
4536
+ bestBidSize: string;
4537
+ bestAskPrice: string;
4538
+ bestAskSize: string;
4539
+ high: string;
4540
+ low: string;
4541
+ baseVolume: string;
4542
+ quoteVolume: string;
4543
+ lastPrice: string;
4544
+ open: string;
4545
+ size: string;
4546
+ }
4547
+ ⋮----
4548
+ export interface GetTickerResponseUTA {
4549
+ tradeType: string;
4550
+ ts: number;
4551
+ list: TickerUTA[];
4552
+ }
4553
+ ⋮----
4554
+ export interface TradeUTA {
4555
+ sequence: string;
4556
+ tradeId: string;
4557
+ price: string;
4558
+ size: string;
4559
+ side: 'buy' | 'sell';
4560
+ ts: number;
4561
+ }
4562
+ ⋮----
4563
+ export interface GetTradesResponseUTA {
4564
+ tradeType: string;
4565
+ list: TradeUTA[];
4566
+ }
4567
+ ⋮----
4568
+ export interface OrderBookLevelUTA {
4569
+ price: string;
4570
+ size: string;
4571
+ }
4572
+ ⋮----
4573
+ export interface GetOrderBookResponseUTA {
4574
+ tradeType: string;
4575
+ symbol: string;
4576
+ sequence: string;
4577
+ bids: OrderBookLevelUTA[];
4578
+ asks: OrderBookLevelUTA[];
4579
+ }
4580
+ ⋮----
4581
+ export interface GetKlinesResponseUTA {
4582
+ tradeType: string;
4583
+ symbol: string;
4584
+ list: string[][]; // [time, open, close, high, low, volume, turnover]
4585
+ }
4586
+ ⋮----
4587
+ list: string[][]; // [time, open, close, high, low, volume, turnover]
4588
+ ⋮----
4589
+ export interface GetCurrentFundingRateResponseUTA {
4590
+ symbol: string;
4591
+ nextFundingRate: number;
4592
+ fundingTime: number;
4593
+ fundingRateCap: number;
4594
+ fundingRateFloor: number;
4595
+ }
4596
+ ⋮----
4597
+ export interface FundingRateHistoryItemUTA {
4598
+ fundingRate: number;
4599
+ ts: number;
4460
4600
  }
4461
4601
  ⋮----
4462
- export interface OtcLoan {
4463
- parentUid: string;
4464
- orders: {
4465
- orderId: string;
4466
- currency: string;
4467
- principal: string;
4468
- interest: string;
4469
- }[];
4470
- ltv: {
4471
- transferLtv: string;
4472
- onlyClosePosLtv: string;
4473
- delayedLiquidationLtv: string;
4474
- instantLiquidationLtv: string;
4475
- currentLtv: string;
4476
- };
4477
- totalMarginAmount: string;
4478
- transferMarginAmount: string;
4479
- margins: {
4480
- marginCcy: string;
4481
- marginQty: string;
4482
- marginFactor: string;
4483
- }[];
4602
+ export interface GetHistoryFundingRateResponseUTA {
4603
+ symbol: string;
4604
+ list: FundingRateHistoryItemUTA[];
4484
4605
  }
4485
4606
  ⋮----
4486
- export interface OtcLoanAccount {
4487
- uid: string;
4488
- marginCcy: string;
4489
- marginQty: string;
4490
- marginFactor: string;
4491
- accountType: 'TRADE' | 'TRADE_HF' | 'CONTRACT';
4492
- isParent: boolean;
4607
+ export interface GetCrossMarginConfigResponseUTA {
4608
+ maxLeverage: number;
4609
+ alertRiskRatio: string;
4610
+ liquidationRiskRatio: string;
4611
+ currencyList: string[];
4612
+ }
4613
+ ⋮----
4614
+ export interface GetServiceStatusResponseUTA {
4615
+ tradeType: string;
4616
+ serverStatus: 'open' | 'close' | 'cancelonly';
4617
+ msg: string;
4493
4618
  }
4494
4619
 
4495
4620
  ================
@@ -4533,6 +4658,17 @@ File: .nvmrc
4533
4658
  ================
4534
4659
  v22.18.0
4535
4660
 
4661
+ ================
4662
+ File: LICENSE.md
4663
+ ================
4664
+ Copyright 2025 Tiago Siebler
4665
+
4666
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4667
+
4668
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
4669
+
4670
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
4671
+
4536
4672
  ================
4537
4673
  File: tsconfig.json
4538
4674
  ================
@@ -4904,6 +5040,7 @@ export interface CopyTradeOrderRequest {
4904
5040
  closeOrder?: boolean;
4905
5041
  forceHold?: boolean;
4906
5042
  marginMode?: 'ISOLATED' | 'CROSS';
5043
+ positionSide?: 'BOTH' | 'LONG' | 'SHORT';
4907
5044
  price?: string;
4908
5045
  size: number;
4909
5046
  timeInForce?: 'GTC' | 'IOC';
@@ -4921,6 +5058,40 @@ export interface CopyTradeSLTPOrderRequest extends CopyTradeOrderRequest {
4921
5058
  ⋮----
4922
5059
  triggerStopUpPrice?: string; // Take profit price
4923
5060
  triggerStopDownPrice?: string; // Stop loss price
5061
+ ⋮----
5062
+ /**
5063
+ * Switch Margin Mode (Copy Trading)
5064
+ */
5065
+ export interface CopyTradeSwitchMarginModeRequest {
5066
+ symbol: string;
5067
+ marginMode: 'ISOLATED' | 'CROSS';
5068
+ }
5069
+ ⋮----
5070
+ /**
5071
+ * Modify Cross Margin Leverage (Copy Trading)
5072
+ */
5073
+ export interface CopyTradeChangeCrossMarginLeverageRequest {
5074
+ symbol: string;
5075
+ leverage: string;
5076
+ }
5077
+ ⋮----
5078
+ /**
5079
+ * Get Cross Margin Requirement (Copy Trading)
5080
+ */
5081
+ export interface CopyTradeGetCrossMarginRequirementRequest {
5082
+ symbol: string;
5083
+ positionValue: string;
5084
+ leverage?: string;
5085
+ }
5086
+ ⋮----
5087
+ /**
5088
+ * Switch Position Mode (Copy Trading)
5089
+ */
5090
+ export interface CopyTradeSwitchPositionModeRequest {
5091
+ positionMode: '0' | '1'; // 0 = one-way mode, 1 = hedge mode
5092
+ }
5093
+ ⋮----
5094
+ positionMode: '0' | '1'; // 0 = one-way mode, 1 = hedge mode
4924
5095
 
4925
5096
  ================
4926
5097
  File: src/types/request/spot-affiliate.ts
@@ -5738,6 +5909,20 @@ clientOid: string; // Client Order ID
5738
5909
  orderTime: number; // Order placement time (milliseconds)
5739
5910
  status: 'NEW' | 'DONE' | 'TRIGGERED' | 'CANCELLED'; // Order status
5740
5911
  orders: MarginOcoOrderSubOrder[]; // Sub-orders array
5912
+ ⋮----
5913
+ /**
5914
+ * Get Margin Collateral Ratio Response
5915
+ */
5916
+ export interface MarginCollateralRatioItem {
5917
+ lowerLimit: string;
5918
+ upperLimit: string;
5919
+ collateralRatio: string;
5920
+ }
5921
+ ⋮----
5922
+ export interface MarginCollateralRatioData {
5923
+ currencyList: string[];
5924
+ items: MarginCollateralRatioItem[];
5925
+ }
5741
5926
 
5742
5927
  ================
5743
5928
  File: src/types/websockets/ws-general.ts
@@ -5852,222 +6037,153 @@ export type WsMarket = 'spot' | 'futures';
5852
6037
  export type WsEventInternalSrc = 'event' | 'function';
5853
6038
 
5854
6039
  ================
5855
- File: src/BrokerClient.ts
6040
+ File: src/UnifiedAPIClient.ts
5856
6041
  ================
6042
+ import { AxiosRequestConfig } from 'axios';
6043
+ ⋮----
5857
6044
  import { BaseRestClient } from './lib/BaseRestClient.js';
5858
- import { REST_CLIENT_TYPE_ENUM, RestClientType } from './lib/requestUtils.js';
5859
6045
  import {
5860
- BrokerTransferRequest,
5861
- CreateBrokerSubAccountApiRequest,
5862
- DeleteBrokerSubAccountApiRequest,
5863
- GetBrokerDepositListRequest,
5864
- GetBrokerInfoRequest,
5865
- GetBrokerSubAccountApisRequest,
5866
- GetBrokerSubAccountsRequest,
5867
- UpdateBrokerSubAccountApiRequest,
5868
- } from './types/request/broker.types.js';
6046
+ REST_CLIENT_TYPE_ENUM,
6047
+ RestClientOptions,
6048
+ RestClientType,
6049
+ } from './lib/requestUtils.js';
5869
6050
  import {
5870
- BrokerDepositRecord,
5871
- BrokerInfo,
5872
- BrokerSubAccountApi,
5873
- BrokerTransferHistory,
5874
- BrokerWithdrawalRecord,
5875
- CreateBrokerSubAccountApiResponse,
5876
- CreateBrokerSubAccountResponse,
5877
- GetBrokerSubAccountsResponse,
5878
- } from './types/response/broker.types.js';
6051
+ GetAnnouncementsRequestUTA,
6052
+ GetCurrencyRequestUTA,
6053
+ GetCurrentFundingRateRequestUTA,
6054
+ GetHistoryFundingRateRequestUTA,
6055
+ GetKlinesRequestUTA,
6056
+ GetOrderBookRequestUTA,
6057
+ GetServiceStatusRequestUTA,
6058
+ GetSymbolRequestUTA,
6059
+ GetTickerRequestUTA,
6060
+ GetTradesRequestUTA,
6061
+ } from './types/request/uta-types.js';
5879
6062
  import { APISuccessResponse } from './types/response/shared.types.js';
6063
+ import {
6064
+ GetAnnouncementsResponseUTA,
6065
+ GetCrossMarginConfigResponseUTA,
6066
+ GetCurrencyResponseUTA,
6067
+ GetCurrentFundingRateResponseUTA,
6068
+ GetHistoryFundingRateResponseUTA,
6069
+ GetKlinesResponseUTA,
6070
+ GetOrderBookResponseUTA,
6071
+ GetServiceStatusResponseUTA,
6072
+ GetSymbolResponseUTA,
6073
+ GetTickerResponseUTA,
6074
+ GetTradesResponseUTA,
6075
+ } from './types/response/uta-types.js';
5880
6076
  ⋮----
5881
6077
  /**
6078
+ * Unified Trading Account Client
5882
6079
  *
6080
+ * This client provides access to the Unified Trading Account API endpoints
6081
+ * that unify market data access across Spot, Futures, and Margin trading.
5883
6082
  */
5884
- export class BrokerClient extends BaseRestClient
6083
+ export class UnifiedAPIClient extends BaseRestClient
5885
6084
  ⋮----
5886
- getClientType(): RestClientType
6085
+ constructor(
6086
+ restClientOptions: RestClientOptions = {},
6087
+ requestOptions: AxiosRequestConfig = {},
6088
+ )
5887
6089
  ⋮----
5888
- /**
5889
- * Get Broker Info
5890
- *
5891
- * This endpoint supports querying the basic information of the current Broker
5892
- */
5893
- getBrokerInfo(
5894
- params: GetBrokerInfoRequest,
5895
- ): Promise<APISuccessResponse<BrokerInfo>>
6090
+ getClientType(): RestClientType
5896
6091
  ⋮----
5897
6092
  /**
5898
- * Add SubAccount
5899
6093
  *
5900
- * This endpoint supports Broker users to create sub-accounts.
5901
- * Note that the account name is unique across the exchange.
5902
- * It is recommended to add a special identifier to prevent name duplication.
5903
- */
5904
- createSubAccount(params: {
5905
- accountName: string;
5906
- }): Promise<APISuccessResponse<CreateBrokerSubAccountResponse>>
5907
- ⋮----
5908
- /**
5909
- * Get SubAccount
6094
+ * REST - Unified Trading Account - Market Data
5910
6095
  *
5911
- * This interface supports querying sub-accounts created by Broker.
5912
- * Returns paginated results with default page size of 20 (max 100).
5913
6096
  */
5914
- getSubAccounts(
5915
- params: GetBrokerSubAccountsRequest,
5916
- ): Promise<APISuccessResponse<GetBrokerSubAccountsResponse>>
5917
6097
  ⋮----
5918
6098
  /**
5919
- * Add SubAccount API
5920
- *
5921
- * This interface supports the creation of Broker sub-account APIKEY.
5922
- * Supports up to 20 IPs in the whitelist.
5923
- * Only General, Spot, and Futures permissions can be set.
5924
- * Label must be between 4 and 32 characters.
6099
+ * Get Announcements
6100
+ * This interface can obtain the latest news announcements, and the default
6101
+ * page search is for announcements within a month.
5925
6102
  */
5926
- createSubAccountApi(
5927
- params: CreateBrokerSubAccountApiRequest,
5928
- ): Promise<APISuccessResponse<CreateBrokerSubAccountApiResponse>>
6103
+ getAnnouncements(
6104
+ params?: GetAnnouncementsRequestUTA,
6105
+ ): Promise<APISuccessResponse<GetAnnouncementsResponseUTA>>
5929
6106
  ⋮----
5930
6107
  /**
5931
- * Get SubAccount API
5932
- *
5933
- * This interface supports querying the Broker's sub-account APIKEYs.
5934
- * Can optionally filter by specific apiKey.
6108
+ * Get Currency
6109
+ * Request the currency details of a specified currency via this endpoint.
5935
6110
  */
5936
- getSubAccountApis(
5937
- params: GetBrokerSubAccountApisRequest,
5938
- ): Promise<APISuccessResponse<BrokerSubAccountApi[]>>
6111
+ getCurrency(
6112
+ params?: GetCurrencyRequestUTA,
6113
+ ): Promise<APISuccessResponse<GetCurrencyResponseUTA>>
5939
6114
  ⋮----
5940
6115
  /**
5941
- * Modify SubAccount API
5942
- *
5943
- * This interface supports modifying the Broker's sub-account APIKEY.
5944
- * Supports up to 20 IPs in the whitelist.
5945
- * Only General, Spot, and Futures permissions can be set.
5946
- * Label must be between 4 and 32 characters.
6116
+ * Get Symbol
6117
+ * Request a list of available currency pairs for trading via this endpoint.
5947
6118
  */
5948
- updateSubAccountApi(
5949
- params: UpdateBrokerSubAccountApiRequest,
5950
- ): Promise<APISuccessResponse<BrokerSubAccountApi>>
6119
+ getSymbols(
6120
+ params: GetSymbolRequestUTA,
6121
+ ): Promise<APISuccessResponse<GetSymbolResponseUTA>>
5951
6122
  ⋮----
5952
6123
  /**
5953
- * Delete SubAccount API
5954
- *
5955
- * This interface supports deleting Broker's sub-account APIKEY.
6124
+ * Get Ticker
6125
+ * Request market tickers for the trading pairs in the market (including 24h volume).
5956
6126
  */
5957
- deleteSubAccountApi(
5958
- params: DeleteBrokerSubAccountApiRequest,
5959
- ): Promise<APISuccessResponse<boolean>>
6127
+ getTickers(
6128
+ params: GetTickerRequestUTA,
6129
+ ): Promise<APISuccessResponse<GetTickerResponseUTA>>
5960
6130
  ⋮----
5961
6131
  /**
5962
- * Transfer
5963
- *
5964
- * This endpoint supports fund transfer between Broker account and Broker sub-accounts.
5965
- * Please be aware that withdrawal from sub-account is not directly supported.
5966
- * Broker has to transfer funds from broker sub-account to broker account to initiate the withdrawals.
5967
- *
5968
- * Direction:
5969
- * - OUT: Broker account is transferred to Broker sub-account
5970
- * - IN: Broker sub-account is transferred to Broker account
5971
- *
5972
- * Account Types:
5973
- * - MAIN: Funding account
5974
- * - TRADE: Spot trading account
5975
- */
5976
- submitTransfer(params: BrokerTransferRequest): Promise<
5977
- APISuccessResponse<{
5978
- orderId: string;
5979
- }>
5980
- > {
5981
- return this.postPrivate('api/v1/broker/nd/transfer', params);
6132
+ * Get Trades
6133
+ * Request via this endpoint to get the latest 100 public trades of the specified symbol.
6134
+ */
6135
+ getTrades(
6136
+ params: GetTradesRequestUTA,
6137
+ ): Promise<APISuccessResponse<GetTradesResponseUTA>>
5982
6138
  ⋮----
5983
6139
  /**
5984
- * Get Transfer History
5985
- *
5986
- * This endpoint supports querying transfer records of the broker itself and its created sub-accounts.
5987
- *
5988
- * Account Types:
5989
- * - MAIN: Funding account
5990
- * - TRADE: Spot trading account
5991
- * - CONTRACT: Contract account
5992
- * - MARGIN: Margin account
5993
- * - ISOLATED: Isolated margin account
5994
- *
5995
- * Status:
5996
- * - PROCESSING: Processing
5997
- * - SUCCESS: Successful
5998
- * - FAILURE: Failed
6140
+ * Get OrderBook
6141
+ * Query order book depth information (aggregated by price).
5999
6142
  */
6000
- getTransferHistory(params: {
6001
- orderId: string;
6002
- }): Promise<APISuccessResponse<BrokerTransferHistory>>
6143
+ getOrderBook(
6144
+ params: GetOrderBookRequestUTA,
6145
+ ): Promise<APISuccessResponse<GetOrderBookResponseUTA>>
6003
6146
  ⋮----
6004
6147
  /**
6005
- * Get Deposit List
6006
- *
6007
- * This endpoint can obtain the deposit records of each sub-account under the ND Broker.
6008
- * Default limit is 1000 records (max 1000).
6009
- * Results are sorted in descending order by default.
6010
- *
6011
- * Status:
6012
- * - PROCESSING: Processing
6013
- * - SUCCESS: Successful
6014
- * - FAILURE: Failed
6148
+ * Get Klines
6149
+ * Get the Kline of the symbol. Data are returned in grouped buckets based on requested type.
6015
6150
  */
6016
- getDeposits(
6017
- params?: GetBrokerDepositListRequest,
6018
- ): Promise<APISuccessResponse<BrokerDepositRecord[]>>
6151
+ getKlines(
6152
+ params: GetKlinesRequestUTA,
6153
+ ): Promise<APISuccessResponse<GetKlinesResponseUTA>>
6019
6154
  ⋮----
6020
6155
  /**
6021
- * Get Deposit Detail
6022
- *
6023
- * This endpoint supports querying the deposit record of sub-accounts created by a Broker
6024
- * (excluding main account of nd broker).
6025
- *
6026
- * Status:
6027
- * - PROCESSING: Processing
6028
- * - SUCCESS: Successful
6029
- * - FAILURE: Failed
6156
+ * Get Current Funding Rate
6157
+ * Get current Futures funding fee rate.
6030
6158
  */
6031
- getDeposit(params: {
6032
- currency: string;
6033
- hash: string;
6034
- }): Promise<APISuccessResponse<BrokerDepositRecord>>
6159
+ getCurrentFundingRate(
6160
+ params: GetCurrentFundingRateRequestUTA,
6161
+ ): Promise<APISuccessResponse<GetCurrentFundingRateResponseUTA>>
6035
6162
  ⋮----
6036
6163
  /**
6037
- * Get Withdrawal Detail
6038
- *
6039
- * This endpoint supports querying the withdrawal records of sub-accounts created by a Broker
6040
- * (excluding main account of nd broker).
6041
- *
6042
- * Status:
6043
- * - PROCESSING: Processing
6044
- * - WALLET_PROCESSING: Wallet Processing
6045
- * - REVIEW: Under Review
6046
- * - SUCCESS: Successful
6047
- * - FAILURE: Failed
6164
+ * Get History Funding Rate
6165
+ * Query the Futures funding rate at each settlement time point within a certain time range.
6048
6166
  */
6049
- getWithdrawal(params: {
6050
- withdrawalId: string;
6051
- }): Promise<APISuccessResponse<BrokerWithdrawalRecord>>
6167
+ getHistoryFundingRate(
6168
+ params: GetHistoryFundingRateRequestUTA,
6169
+ ): Promise<APISuccessResponse<GetHistoryFundingRateResponseUTA>>
6052
6170
  ⋮----
6053
6171
  /**
6054
- * Get Broker Rebate
6055
- *
6056
- * This interface supports downloading Broker rebate orders.
6057
- * Returns a URL to download a CSV file containing the rebate data.
6058
- * The URL is valid for 1 day.
6059
- * Maximum interval between begin and end dates is 6 months.
6172
+ * Get Cross Margin Config
6173
+ * Request the configure info of the 'spot cross margin' via this endpoint.
6060
6174
  */
6061
- getBrokerRebate(params: {
6062
- begin: string;
6063
- end: string;
6064
- tradeType: '1' | '2';
6065
- }): Promise<
6066
- APISuccessResponse<{
6067
- url: string;
6068
- }>
6175
+ getCrossMarginConfig(): Promise<
6176
+ APISuccessResponse<GetCrossMarginConfigResponseUTA>
6069
6177
  > {
6070
- return this.getPrivate('api/v1/broker/nd/rebase/download', params);
6178
+ return this.get('api/ua/v1/market/cross-config');
6179
+ ⋮----
6180
+ /**
6181
+ * Get Service Status
6182
+ * Get the service status.
6183
+ */
6184
+ getServiceStatus(
6185
+ params: GetServiceStatusRequestUTA,
6186
+ ): Promise<APISuccessResponse<GetServiceStatusResponseUTA>>
6071
6187
 
6072
6188
  ================
6073
6189
  File: .eslintrc.cjs
@@ -7188,66 +7304,239 @@ export interface RestClientOptions {
7188
7304
  */
7189
7305
  keepAliveMsecs?: number;
7190
7306
 
7191
- /**
7192
- * Allows you to provide a custom "signMessage" function, e.g. to use node's much faster createHmac method
7193
- *
7194
- * Look in the examples folder for a demonstration on using node's createHmac instead.
7195
- */
7196
- customSignMessageFn?: (message: string, secret: string) => Promise<string>;
7307
+ /**
7308
+ * Allows you to provide a custom "signMessage" function, e.g. to use node's much faster createHmac method
7309
+ *
7310
+ * Look in the examples folder for a demonstration on using node's createHmac instead.
7311
+ */
7312
+ customSignMessageFn?: (message: string, secret: string) => Promise<string>;
7313
+ }
7314
+ ⋮----
7315
+ /** Your API key */
7316
+ ⋮----
7317
+ /** Your API secret */
7318
+ ⋮----
7319
+ /** Your API passphrase (can be anything) that you set when creating this API key (NOT your account password) */
7320
+ ⋮----
7321
+ /**
7322
+ * Use access token instead of sign, if this is provided.
7323
+ * For guidance refer to: https://github.com/tiagosiebler/kucoin-api/issues/2
7324
+ */
7325
+ ⋮----
7326
+ /** The API key version. Defaults to "2" right now. You can see this in your API management page */
7327
+ ⋮----
7328
+ /** Default: false. If true, we'll throw errors if any params are undefined */
7329
+ ⋮----
7330
+ /**
7331
+ * Optionally override API protocol + domain
7332
+ * e.g baseUrl: 'https://api.kucoin.com'
7333
+ **/
7334
+ ⋮----
7335
+ /** Default: true. whether to try and post-process request exceptions (and throw them). */
7336
+ ⋮----
7337
+ /**
7338
+ * Enable keep alive for REST API requests (via axios).
7339
+ */
7340
+ ⋮----
7341
+ /**
7342
+ * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000.
7343
+ * Only relevant if keepAlive is set to true.
7344
+ * Default: 1000 (defaults comes from https agent)
7345
+ */
7346
+ ⋮----
7347
+ /**
7348
+ * Allows you to provide a custom "signMessage" function, e.g. to use node's much faster createHmac method
7349
+ *
7350
+ * Look in the examples folder for a demonstration on using node's createHmac instead.
7351
+ */
7352
+ ⋮----
7353
+ export function serializeParams<T extends Record<string, any> | undefined = {}>(
7354
+ params: T,
7355
+ strict_validation: boolean | undefined,
7356
+ encodeValues: boolean,
7357
+ prefixWith: string,
7358
+ ): string
7359
+ ⋮----
7360
+ // Only prefix if there's a value
7361
+ ⋮----
7362
+ export function getRestBaseUrl(
7363
+ useTestnet: boolean,
7364
+ restInverseOptions: RestClientOptions,
7365
+ restClientType: RestClientType,
7366
+ ): string
7367
+
7368
+ ================
7369
+ File: src/types/websockets/ws-api.ts
7370
+ ================
7371
+ import { WS_KEY_MAP, WsKey } from '../../lib/websocket/websocket-util.js';
7372
+ import { BatchCancelOrdersRequest, Order } from '../request/futures.types.js';
7373
+ import { SubmitHFMarginOrderRequest } from '../request/spot-margin-trading.js';
7374
+ import {
7375
+ ModifyHFOrderRequest,
7376
+ SubmitHFOrderRequest,
7377
+ } from '../request/spot-trading.js';
7378
+ import {
7379
+ BatchCancelOrderResult,
7380
+ SubmitMultipleOrdersFuturesResponse,
7381
+ } from '../response/futures.types.js';
7382
+ import { MarginSubmitOrderV3Response } from '../response/spot-margin-trading.js';
7383
+ import {
7384
+ SubmitHFOrderSyncResponse,
7385
+ SyncCancelHFOrderResponse,
7386
+ } from '../response/spot-trading.js';
7387
+ ⋮----
7388
+ export type WsOperation =
7389
+ | 'subscribe'
7390
+ | 'unsubscribe'
7391
+ | 'login'
7392
+ | 'access'
7393
+ | 'request'
7394
+ | 'ping';
7395
+ ⋮----
7396
+ export interface WsRequestOperation<TWSTopic extends string> {
7397
+ id: number;
7398
+ type: WsOperation;
7399
+ topic: TWSTopic;
7400
+ privateChannel: boolean;
7401
+ response: boolean;
7402
+ }
7403
+ ⋮----
7404
+ export type Exact<T> = {
7405
+ // This part says: if there's any key that's not in T, it's an error
7406
+ // This conflicts sometimes for some reason...
7407
+ // [K: string]: never;
7408
+ } & {
7409
+ [K in keyof T]: T[K];
7410
+ };
7411
+ ⋮----
7412
+ // This part says: if there's any key that's not in T, it's an error
7413
+ // This conflicts sometimes for some reason...
7414
+ // [K: string]: never;
7415
+ ⋮----
7416
+ /**
7417
+ * WS API commands (for sending requests via WS)
7418
+ */
7419
+ ⋮----
7420
+ export type WsAPIOperation = (typeof WS_API_Operations)[number];
7421
+ ⋮----
7422
+ export interface WsRequestOperationKucoin<
7423
+ TWSTopic extends string,
7424
+ TWSParams extends object = any,
7425
+ > {
7426
+ id: string;
7427
+ op: WsOperation | WsAPIOperation;
7428
+ args?: (TWSTopic | string | number)[] | TWSParams; // Business parameters, same as RestAPI
7429
+ }
7430
+ ⋮----
7431
+ args?: (TWSTopic | string | number)[] | TWSParams; // Business parameters, same as RestAPI
7432
+ ⋮----
7433
+ export interface WSAPIResponse<
7434
+ TResponseData extends object = object,
7435
+ TWSAPIOperation = WsAPIOperation,
7436
+ > {
7437
+ /** Auto-generated */
7438
+ id: string;
7439
+
7440
+ op: TWSAPIOperation;
7441
+
7442
+ msg?: string;
7443
+ code: '200000' | string;
7444
+
7445
+ data: TResponseData;
7446
+ inTime: number; //Gateway in time(ms)
7447
+ outTime: number; //Gateway out time(ms)
7448
+ rateLimit?: { limit: number; reset: number; remaining: number };
7449
+
7450
+ wsKey: WsKey;
7451
+ isWSAPIResponse: boolean;
7452
+
7453
+ request?: any;
7197
7454
  }
7198
7455
  ⋮----
7199
- /** Your API key */
7200
- ⋮----
7201
- /** Your API secret */
7202
- ⋮----
7203
- /** Your API passphrase (can be anything) that you set when creating this API key (NOT your account password) */
7204
- ⋮----
7205
- /**
7206
- * Use access token instead of sign, if this is provided.
7207
- * For guidance refer to: https://github.com/tiagosiebler/kucoin-api/issues/2
7208
- */
7209
- ⋮----
7210
- /** The API key version. Defaults to "2" right now. You can see this in your API management page */
7211
- ⋮----
7212
- /** Default: false. If true, we'll throw errors if any params are undefined */
7456
+ /** Auto-generated */
7213
7457
  ⋮----
7214
- /**
7215
- * Optionally override API protocol + domain
7216
- * e.g baseUrl: 'https://api.kucoin.com'
7217
- **/
7458
+ inTime: number; //Gateway in time(ms)
7459
+ outTime: number; //Gateway out time(ms)
7218
7460
  ⋮----
7219
- /** Default: true. whether to try and post-process request exceptions (and throw them). */
7461
+ export interface WsAPIWsKeyTopicMap {
7462
+ [WS_KEY_MAP.wsApiSpotV1]: WsAPIOperation;
7463
+ [WS_KEY_MAP.wsApiFuturesV1]: WsAPIOperation;
7464
+ }
7220
7465
  ⋮----
7221
- /**
7222
- * Enable keep alive for REST API requests (via axios).
7223
- */
7466
+ export type WSAPICancelOrderRequest = { symbol: string } & (
7467
+ | { orderId: string }
7468
+ | { clientOid: string }
7469
+ );
7224
7470
  ⋮----
7225
- /**
7226
- * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000.
7227
- * Only relevant if keepAlive is set to true.
7228
- * Default: 1000 (defaults comes from https agent)
7229
- */
7471
+ export interface WSAPIOrderResponse {
7472
+ orderId: string;
7473
+ clientOid: string;
7474
+ }
7230
7475
  ⋮----
7231
- /**
7232
- * Allows you to provide a custom "signMessage" function, e.g. to use node's much faster createHmac method
7233
- *
7234
- * Look in the examples folder for a demonstration on using node's createHmac instead.
7235
- */
7476
+ export interface WsAPITopicRequestParamMap {
7477
+ [key: string]: unknown;
7478
+
7479
+ subscribe: never;
7480
+ unsubscribe: never;
7481
+ login: never;
7482
+ access: never;
7483
+ request: never;
7484
+
7485
+ ping: void;
7486
+
7487
+ 'spot.order': SubmitHFOrderRequest;
7488
+ 'margin.order': SubmitHFMarginOrderRequest;
7489
+ 'futures.order': Order;
7490
+ 'spot.cancel': WSAPICancelOrderRequest;
7491
+ 'margin.cancel': WSAPICancelOrderRequest;
7492
+ 'futures.cancel': { orderId: string } | { clientOid: string; symbol: string };
7493
+ 'futures.multi_cancel': BatchCancelOrdersRequest;
7494
+ 'futures.multi_order': Order[];
7495
+ 'spot.sync_order': SubmitHFOrderRequest;
7496
+ 'spot.modify': ModifyHFOrderRequest;
7497
+ 'spot.sync_cancel': WSAPICancelOrderRequest;
7498
+ }
7236
7499
  ⋮----
7237
- export function serializeParams<T extends Record<string, any> | undefined = {}>(
7238
- params: T,
7239
- strict_validation: boolean | undefined,
7240
- encodeValues: boolean,
7241
- prefixWith: string,
7242
- ): string
7500
+ export interface WsAPITopicResponseMap {
7501
+ [key: string]: unknown;
7502
+
7503
+ subscribe: never;
7504
+ unsubscribe: never;
7505
+ login: never;
7506
+ access: never;
7507
+ request: never;
7508
+
7509
+ ping: unknown;
7510
+
7511
+ 'spot.order': WSAPIResponse<WSAPIOrderResponse>;
7512
+ 'margin.order': WSAPIResponse<MarginSubmitOrderV3Response>;
7513
+ 'futures.order': WSAPIResponse<WSAPIOrderResponse>;
7514
+ 'spot.cancel': WSAPIResponse<WSAPIOrderResponse>;
7515
+ 'margin.cancel': WSAPIResponse<WSAPIOrderResponse>;
7516
+ 'futures.cancel': WSAPIResponse<
7517
+ { cancelledOrderIds: string[] } | { clientOid: string }
7518
+ >;
7519
+ 'futures.multi_cancel': WSAPIResponse<BatchCancelOrderResult[]>;
7520
+ 'futures.multi_order': WSAPIResponse<SubmitMultipleOrdersFuturesResponse[]>;
7521
+ 'spot.sync_order': WSAPIResponse<SubmitHFOrderSyncResponse>;
7522
+ 'spot.modify': WSAPIResponse<{
7523
+ newOrderId: string;
7524
+ clientOid: string;
7525
+ }>;
7526
+ 'spot.sync_cancel': WSAPIResponse<SyncCancelHFOrderResponse>;
7527
+ }
7243
7528
  ⋮----
7244
- // Only prefix if there's a value
7529
+ export interface WSAPIAuthenticationRequestFromServer {
7530
+ timestamp: number;
7531
+ sessionId: string;
7532
+ }
7245
7533
  ⋮----
7246
- export function getRestBaseUrl(
7247
- useTestnet: boolean,
7248
- restInverseOptions: RestClientOptions,
7249
- restClientType: RestClientType,
7250
- ): string
7534
+ export interface WSAPIAuthenticationConfirmedFromServer {
7535
+ pingInterval: number;
7536
+ sessionId: string;
7537
+ pingTimeout: number;
7538
+ data: 'welcome';
7539
+ }
7251
7540
 
7252
7541
  ================
7253
7542
  File: src/FuturesClient.ts
@@ -7264,8 +7553,12 @@ import {
7264
7553
  import {
7265
7554
  AccountFillsRequest,
7266
7555
  BatchCancelOrdersRequest,
7556
+ CopyTradeChangeCrossMarginLeverageRequest,
7557
+ CopyTradeGetCrossMarginRequirementRequest,
7267
7558
  CopyTradeOrderRequest,
7268
7559
  CopyTradeSLTPOrderRequest,
7560
+ CopyTradeSwitchMarginModeRequest,
7561
+ CopyTradeSwitchPositionModeRequest,
7269
7562
  GetFundingHistoryRequest,
7270
7563
  GetFundingRatesRequest,
7271
7564
  GetInterestRatesRequest,
@@ -7283,7 +7576,10 @@ import {
7283
7576
  AddMargin,
7284
7577
  BatchCancelOrderResult,
7285
7578
  BatchMarginModeUpdateResponse,
7579
+ CopyTradeCrossMarginRequirement,
7286
7580
  CopyTradePosition,
7581
+ CopyTradeSwitchMarginModeResponse,
7582
+ CopyTradeSwitchPositionModeResponse,
7287
7583
  CrossMarginRequirement,
7288
7584
  CrossMarginRiskLimit,
7289
7585
  FullOrderBookDetail,
@@ -7940,8 +8236,9 @@ hasMore: boolean; // Whether there are more pages
7940
8236
  */
7941
8237
  ⋮----
7942
8238
  /**
7943
- * Add Order
7944
- * Place order to the futures trading system for copy trading
8239
+ * Add Order (Copy Trading)
8240
+ * Place order to the futures trading system for copy trading.
8241
+ * Max leverage is set to 20x, and marginMode supports both ISOLATED and CROSS.
7945
8242
  */
7946
8243
  submitCopyTradeOrder(params: CopyTradeOrderRequest): Promise<
7947
8244
  APISuccessResponse<{
@@ -7952,9 +8249,10 @@ submitCopyTradeOrder(params: CopyTradeOrderRequest): Promise<
7952
8249
  return this.postPrivate('api/v1/copy-trade/futures/orders', params);
7953
8250
  ⋮----
7954
8251
  /**
7955
- * Add Order Test
8252
+ * Add Order Test (Copy Trading)
7956
8253
  * Order test endpoint, the request parameters and return parameters of this endpoint are exactly the same as the order endpoint,
7957
8254
  * and can be used to verify whether the signature is correct and other operations.
8255
+ * Max leverage is set to 20x, and marginMode supports both ISOLATED and CROSS.
7958
8256
  */
7959
8257
  submitCopyTradeOrderTest(params: CopyTradeOrderRequest): Promise<
7960
8258
  APISuccessResponse<{
@@ -7965,8 +8263,9 @@ submitCopyTradeOrderTest(params: CopyTradeOrderRequest): Promise<
7965
8263
  return this.postPrivate('api/v1/copy-trade/futures/orders/test', params);
7966
8264
  ⋮----
7967
8265
  /**
7968
- * Add Take Profit And Stop Loss Order
8266
+ * Add Take Profit And Stop Loss Order (Copy Trading)
7969
8267
  * Place take profit and stop loss order supports both take-profit and stop-loss functions, and other functions are exactly the same as the place order endpoint.
8268
+ * Max leverage is set to 20x, and marginMode supports both ISOLATED and CROSS.
7970
8269
  */
7971
8270
  submitCopyTradeSLTPOrder(params: CopyTradeSLTPOrderRequest): Promise<
7972
8271
  APISuccessResponse<{
@@ -8014,30 +8313,33 @@ getCopyTradeMaxOpenSize(params: {
8014
8313
  );
8015
8314
  ⋮----
8016
8315
  /**
8017
- * Get Max Withdraw Margin
8316
+ * Get Max Withdraw Margin (Copy Trading)
8018
8317
  * This endpoint can query the maximum amount of margin that the current position supports withdrawal.
8019
8318
  */
8020
8319
  getCopyTradeMaxWithdrawMargin(params: {
8021
8320
  symbol: string;
8321
+ positionSide?: 'BOTH' | 'LONG' | 'SHORT';
8022
8322
  }): Promise<APISuccessResponse<string>>
8023
8323
  ⋮----
8024
8324
  /**
8025
- * Add Isolated Margin
8325
+ * Add Isolated Margin (Copy Trading)
8026
8326
  * Add Isolated Margin Manually.
8027
8327
  */
8028
8328
  addCopyTradeIsolatedMargin(params: {
8029
8329
  symbol: string;
8030
8330
  margin: number;
8031
8331
  bizNo: string;
8332
+ positionSide?: 'BOTH' | 'LONG' | 'SHORT';
8032
8333
  }): Promise<APISuccessResponse<CopyTradePosition>>
8033
8334
  ⋮----
8034
8335
  /**
8035
- * Remove Isolated Margin
8336
+ * Remove Isolated Margin (Copy Trading)
8036
8337
  * Remove Isolated Margin Manually.
8037
8338
  */
8038
8339
  removeCopyTradeIsolatedMargin(params: {
8039
8340
  symbol: string;
8040
8341
  withdrawAmount: string;
8342
+ positionSide?: 'BOTH' | 'LONG' | 'SHORT';
8041
8343
  }): Promise<APISuccessResponse<string>>
8042
8344
  ⋮----
8043
8345
  /**
@@ -8051,14 +8353,48 @@ modifyCopyTradeRiskLimitLevel(params: {
8051
8353
  }): Promise<APISuccessResponse<boolean>>
8052
8354
  ⋮----
8053
8355
  /**
8054
- * Modify Isolated Margin Auto-Deposit Status
8356
+ * Modify Isolated Margin Auto-Deposit Status (Copy Trading)
8055
8357
  * This endpoint is only applicable to isolated margin and is no longer recommended. It is recommended to use cross margin instead.
8056
8358
  * @deprecated - It is recommended to use cross margin instead
8057
8359
  */
8058
8360
  updateCopyTradeAutoDepositStatus(params: {
8059
8361
  symbol: string;
8060
8362
  status: boolean;
8363
+ positionSide?: 'BOTH' | 'LONG' | 'SHORT';
8061
8364
  }): Promise<APISuccessResponse<boolean>>
8365
+ ⋮----
8366
+ /**
8367
+ * Switch Margin Mode (Copy Trading)
8368
+ * Modify the margin mode of the current symbol.
8369
+ */
8370
+ switchCopyTradeMarginMode(
8371
+ params: CopyTradeSwitchMarginModeRequest,
8372
+ ): Promise<APISuccessResponse<CopyTradeSwitchMarginModeResponse>>
8373
+ ⋮----
8374
+ /**
8375
+ * Modify Cross Margin Leverage (Copy Trading)
8376
+ * This interface can modify the current symbol's cross-margin leverage multiple.
8377
+ */
8378
+ updateCopyTradeCrossMarginLeverage(
8379
+ params: CopyTradeChangeCrossMarginLeverageRequest,
8380
+ ): Promise<APISuccessResponse<boolean>>
8381
+ ⋮----
8382
+ /**
8383
+ * Get Cross Margin Requirement (Copy Trading)
8384
+ * This endpoint supports querying the cross margin requirements of a symbol by position value.
8385
+ */
8386
+ getCopyTradeCrossMarginRequirement(
8387
+ params: CopyTradeGetCrossMarginRequirementRequest,
8388
+ ): Promise<APISuccessResponse<CopyTradeCrossMarginRequirement[]>>
8389
+ ⋮----
8390
+ /**
8391
+ * Switch Position Mode (Copy Trading)
8392
+ * This interface is used to toggle between one-way mode and hedge mode for the position mode.
8393
+ * Applies to all futures trading pairs.
8394
+ */
8395
+ switchCopyTradePositionMode(
8396
+ params: CopyTradeSwitchPositionModeRequest,
8397
+ ): Promise<APISuccessResponse<CopyTradeSwitchPositionModeResponse>>
8062
8398
  /**
8063
8399
  *
8064
8400
  * REST - Futures - Broker
@@ -8313,39 +8649,131 @@ submitMultipleFuturesOrders(
8313
8649
  wsKey?: WSAPIWsKey,
8314
8650
  ): Promise<WSAPIResponse<SubmitMultipleOrdersFuturesResponse[]>>
8315
8651
  ⋮----
8316
- /**
8317
- * Cancel multiple futures orders
8318
- */
8319
- cancelMultipleFuturesOrders(
8320
- params: BatchCancelOrdersRequest,
8321
- wsKey?: WSAPIWsKey,
8322
- ): Promise<WSAPIResponse<BatchCancelOrderResult[]>>
8652
+ /**
8653
+ * Cancel multiple futures orders
8654
+ */
8655
+ cancelMultipleFuturesOrders(
8656
+ params: BatchCancelOrdersRequest,
8657
+ wsKey?: WSAPIWsKey,
8658
+ ): Promise<WSAPIResponse<BatchCancelOrderResult[]>>
8659
+ ⋮----
8660
+ /**
8661
+ *
8662
+ *
8663
+ *
8664
+ *
8665
+ *
8666
+ *
8667
+ *
8668
+ * Private methods for handling some of the convenience/automation provided by the WS API Client
8669
+ *
8670
+ *
8671
+ *
8672
+ *
8673
+ *
8674
+ *
8675
+ *
8676
+ */
8677
+ ⋮----
8678
+ public connectWSAPI(wsKey: WSAPIWsKey)
8679
+ ⋮----
8680
+ private setupDefaultEventListeners()
8681
+ ⋮----
8682
+ /**
8683
+ * General event handlers for monitoring the WebsocketClient
8684
+ */
8685
+ ⋮----
8686
+ // Blind JSON.stringify can fail on circular references
8687
+ ⋮----
8688
+ // JSON.stringify({ ...data, target: 'WebSocket' }),
8689
+
8690
+ ================
8691
+ File: examples/WebSockets/ws-api-client.ts
8692
+ ================
8693
+ /**
8694
+ * KuCoin WebSocket API Client - Complete Example
8695
+ *
8696
+ * This example demonstrates all available WebSocket API operations:
8697
+ * - Spot trading: submit, modify, cancel, sync operations
8698
+ * - Margin trading: submit and cancel orders
8699
+ * - Futures trading: submit, cancel, batch operations
8700
+ *
8701
+ * Usage:
8702
+ * Make sure to set your API credentials in environment variables:
8703
+ * - API_KEY
8704
+ * - API_SECRET
8705
+ * - API_PASSPHRASE
8706
+ *
8707
+ * or pass them as arguments to the constructor
8708
+ */
8709
+ ⋮----
8710
+ import { DefaultLogger, WebsocketAPIClient } from '../../src/index.js';
8711
+ ⋮----
8712
+ async function main()
8713
+ ⋮----
8714
+ // For a more detailed view of the WebsocketClient, enable the `trace` level by uncommenting the below line:
8715
+ // trace: (...params) => console.log(new Date(), 'trace', ...params),
8716
+ ⋮----
8717
+ passphrase: process.env.API_PASSPHRASE || 'apiPassPhraseHere', // This is NOT your account password
8718
+ ⋮----
8719
+ // If you want your own event handlers instead of the default ones with logs, disable this setting and see the `attachEventHandlers` example below:
8720
+ // attachEventListeners: false
8721
+ ⋮----
8722
+ // Example usage for each WebSocket API operation
8723
+ ⋮----
8724
+ // 1. Submit Spot Order
8725
+ ⋮----
8726
+ price: '20000', // Very low price to avoid accidental execution
8727
+ ⋮----
8728
+ // 2. Submit Sync Spot Order
8729
+ ⋮----
8730
+ price: '1000', // Very high price to avoid accidental execution
8731
+ ⋮----
8732
+ // 3. Modify Spot Order (requires existing order ID)
8733
+ ⋮----
8734
+ orderId: '68cc3476693c1c00072ef1d9', // Replace with actual order ID
8735
+ ⋮----
8736
+ // 4. Cancel Spot Order
8737
+ ⋮----
8738
+ orderId: '68cc34c6693c1c0007301929', // Replace with actual order ID
8739
+ ⋮----
8740
+ // 5. Cancel Sync Spot Order
8741
+ ⋮----
8742
+ orderId: '68cc3530b9870a0007670294', // Replace with actual client order ID
8743
+ ⋮----
8744
+ // 6. Submit Margin Order
8745
+ ⋮----
8746
+ price: '19000', // Very low price to avoid accidental execution
8747
+ ⋮----
8748
+ isIsolated: false, // false for cross margin, true for isolated
8749
+ ⋮----
8750
+ // 7. Cancel Margin Order
8751
+ ⋮----
8752
+ orderId: 'your-margin-order-id-here', // Replace with actual order ID
8753
+ ⋮----
8754
+ // 8. Submit Futures Order
8755
+ ⋮----
8756
+ price: '1000', // Very low price to avoid accidental execution
8757
+ ⋮----
8758
+ positionSide: 'LONG', // needed if trading two-way (hedge) position mode
8759
+ ⋮----
8760
+ // 9. Cancel Futures Order
8761
+ ⋮----
8762
+ orderId: '358196976308797441', // Replace with actual order ID
8323
8763
  ⋮----
8324
- /**
8325
- *
8326
- *
8327
- *
8328
- *
8329
- *
8330
- *
8331
- *
8332
- * Private methods for handling some of the convenience/automation provided by the WS API Client
8333
- *
8334
- *
8335
- *
8336
- *
8337
- *
8338
- *
8339
- *
8340
- */
8764
+ // 10. Submit Multiple Futures Orders
8341
8765
  ⋮----
8342
- public connectWSAPI(wsKey: WSAPIWsKey)
8766
+ price: '1000', // Very low price to avoid accidental execution
8343
8767
  ⋮----
8344
- private setupDefaultEventListeners()
8768
+ positionSide: 'LONG', // Needed if trading hedge/two-way mode. Optional in one-way mode.
8345
8769
  ⋮----
8346
- /**
8347
- * General event handlers for monitoring the WebsocketClient
8348
- */
8770
+ price: '1010', // Very low price to avoid accidental execution
8771
+ ⋮----
8772
+ // 11. Cancel Multiple Futures Orders
8773
+ ⋮----
8774
+ orderIdsList: ['order-id-1', 'order-id-2'], // Replace with actual order IDs
8775
+ ⋮----
8776
+ // Start executing the example workflow
8349
8777
 
8350
8778
  ================
8351
8779
  File: src/types/response/futures.types.ts
@@ -9235,468 +9663,510 @@ export interface CopyTradePosition {
9235
9663
  bankruptPrice: string;
9236
9664
  settleCurrency: string;
9237
9665
  }
9666
+ ⋮----
9667
+ /**
9668
+ * Switch Margin Mode Response (Copy Trading)
9669
+ */
9670
+ export interface CopyTradeSwitchMarginModeResponse {
9671
+ symbol: string;
9672
+ marginMode: 'ISOLATED' | 'CROSS';
9673
+ }
9674
+ ⋮----
9675
+ /**
9676
+ * Get Cross Margin Requirement Response (Copy Trading)
9677
+ */
9678
+ export interface CopyTradeCrossMarginRequirement {
9679
+ imr: string;
9680
+ mmr: string;
9681
+ positionValue: string;
9682
+ price: string;
9683
+ size: number;
9684
+ symbol: string;
9685
+ }
9686
+ ⋮----
9687
+ /**
9688
+ * Switch Position Mode Response (Copy Trading)
9689
+ */
9690
+ export interface CopyTradeSwitchPositionModeResponse {
9691
+ positionMode: '0' | '1'; // 0 = one-way mode, 1 = hedge mode
9692
+ }
9693
+ ⋮----
9694
+ positionMode: '0' | '1'; // 0 = one-way mode, 1 = hedge mode
9238
9695
 
9239
9696
  ================
9240
- File: src/types/websockets/ws-api.ts
9697
+ File: src/lib/BaseRestClient.ts
9241
9698
  ================
9242
- import { WS_KEY_MAP, WsKey } from '../../lib/websocket/websocket-util.js';
9243
- import { BatchCancelOrdersRequest, Order } from '../request/futures.types.js';
9244
- import { SubmitHFMarginOrderRequest } from '../request/spot-margin-trading.js';
9245
- import {
9246
- ModifyHFOrderRequest,
9247
- SubmitHFOrderRequest,
9248
- } from '../request/spot-trading.js';
9699
+ import axios, { AxiosRequestConfig, AxiosResponse, Method } from 'axios';
9700
+ import https from 'https';
9701
+ ⋮----
9702
+ import { neverGuard } from './misc-util.js';
9249
9703
  import {
9250
- BatchCancelOrderResult,
9251
- SubmitMultipleOrdersFuturesResponse,
9252
- } from '../response/futures.types.js';
9253
- import { MarginSubmitOrderV3Response } from '../response/spot-margin-trading.js';
9704
+ APIIDFutures,
9705
+ APIIDFuturesSign,
9706
+ APIIDMain,
9707
+ APIIDMainSign,
9708
+ getRestBaseUrl,
9709
+ REST_CLIENT_TYPE_ENUM,
9710
+ RestClientOptions,
9711
+ RestClientType,
9712
+ serializeParams,
9713
+ } from './requestUtils.js';
9254
9714
  import {
9255
- SubmitHFOrderSyncResponse,
9256
- SyncCancelHFOrderResponse,
9257
- } from '../response/spot-trading.js';
9715
+ checkWebCryptoAPISupported,
9716
+ SignAlgorithm,
9717
+ SignEncodeMethod,
9718
+ signMessage,
9719
+ } from './webCryptoAPI.js';
9258
9720
  ⋮----
9259
- export type WsOperation =
9260
- | 'subscribe'
9261
- | 'unsubscribe'
9262
- | 'login'
9263
- | 'access'
9264
- | 'request'
9265
- | 'ping';
9721
+ export interface SignedRequest<T extends object | undefined = {}> {
9722
+ originalParams: T;
9723
+ paramsWithSign?: T & { sign: string };
9724
+ serializedParams: string;
9725
+ sign: string;
9726
+ queryParamsWithSign: string;
9727
+ timestamp: number;
9728
+ recvWindow: number;
9729
+ }
9266
9730
  ⋮----
9267
- export interface WsRequestOperation<TWSTopic extends string> {
9268
- id: number;
9269
- type: WsOperation;
9270
- topic: TWSTopic;
9271
- privateChannel: boolean;
9272
- response: boolean;
9731
+ interface UnsignedRequest<T extends object | undefined = {}> {
9732
+ originalParams: T;
9733
+ paramsWithSign: T;
9273
9734
  }
9274
9735
  ⋮----
9275
- export type Exact<T> = {
9276
- // This part says: if there's any key that's not in T, it's an error
9277
- // This conflicts sometimes for some reason...
9278
- // [K: string]: never;
9279
- } & {
9280
- [K in keyof T]: T[K];
9281
- };
9736
+ type SignMethod = 'kucoin';
9282
9737
  ⋮----
9283
- // This part says: if there's any key that's not in T, it's an error
9284
- // This conflicts sometimes for some reason...
9285
- // [K: string]: never;
9738
+ // request: {
9739
+ // url: response.config.url,
9740
+ // method: response.config.method,
9741
+ // data: response.config.data,
9742
+ // headers: response.config.headers,
9743
+ // },
9744
+ ⋮----
9745
+ export abstract class BaseRestClient
9746
+ ⋮----
9747
+ /** Defines the client type (affecting how requests & signatures behave) */
9748
+ abstract getClientType(): RestClientType;
9286
9749
  ⋮----
9287
9750
  /**
9288
- * WS API commands (for sending requests via WS)
9289
- */
9751
+ * Create an instance of the REST client. Pass API credentials in the object in the first parameter.
9752
+ * @param {RestClientOptions} [restClientOptions={}] options to configure REST API connectivity
9753
+ * @param {AxiosRequestConfig} [networkOptions={}] HTTP networking options for axios
9754
+ */
9755
+ constructor(
9756
+ restClientOptions: RestClientOptions = {},
9757
+ networkOptions: AxiosRequestConfig = {},
9758
+ )
9290
9759
  ⋮----
9291
- export type WsAPIOperation = (typeof WS_API_Operations)[number];
9760
+ /** Throw errors if any request params are empty */
9292
9761
  ⋮----
9293
- export interface WsRequestOperationKucoin<
9294
- TWSTopic extends string,
9295
- TWSParams extends object = any,
9296
- > {
9297
- id: string;
9298
- op: WsOperation | WsAPIOperation;
9299
- args?: (TWSTopic | string | number)[] | TWSParams; // Business parameters, same as RestAPI
9300
- }
9762
+ /** in ms == 5 minutes by default */
9301
9763
  ⋮----
9302
- args?: (TWSTopic | string | number)[] | TWSParams; // Business parameters, same as RestAPI
9764
+ /** inject custom rquest options based on axios specs - see axios docs for more guidance on AxiosRequestConfig: https://github.com/axios/axios#request-config */
9303
9765
  ⋮----
9304
- export interface WSAPIResponse<
9305
- TResponseData extends object = object,
9306
- TWSAPIOperation = WsAPIOperation,
9307
- > {
9308
- /** Auto-generated */
9309
- id: string;
9310
-
9311
- op: TWSAPIOperation;
9312
-
9313
- msg?: string;
9314
- code: '200000' | string;
9315
-
9316
- data: TResponseData;
9317
- inTime: number; //Gateway in time(ms)
9318
- outTime: number; //Gateway out time(ms)
9319
- rateLimit?: { limit: number; reset: number; remaining: number };
9320
-
9321
- wsKey: WsKey;
9322
- isWSAPIResponse: boolean;
9323
-
9324
- request?: any;
9325
- }
9766
+ // If enabled, configure a https agent with keepAlive enabled
9326
9767
  ⋮----
9327
- /** Auto-generated */
9768
+ // Extract existing https agent parameters, if provided, to prevent the keepAlive flag from overwriting an existing https agent completely
9328
9769
  ⋮----
9329
- inTime: number; //Gateway in time(ms)
9330
- outTime: number; //Gateway out time(ms)
9770
+ // For more advanced configuration, raise an issue on GitHub or use the "networkOptions"
9771
+ // parameter to define a custom httpsAgent with the desired properties
9331
9772
  ⋮----
9332
- export interface WsAPIWsKeyTopicMap {
9333
- [WS_KEY_MAP.wsApiSpotV1]: WsAPIOperation;
9334
- [WS_KEY_MAP.wsApiFuturesV1]: WsAPIOperation;
9335
- }
9773
+ // Check Web Crypto API support when credentials are provided
9336
9774
  ⋮----
9337
- export type WSAPICancelOrderRequest = { symbol: string } & (
9338
- | { orderId: string }
9339
- | { clientOid: string }
9340
- );
9775
+ // Throw if one of the 3 values is missing, but at least one of them is set
9341
9776
  ⋮----
9342
- export interface WSAPIOrderResponse {
9343
- orderId: string;
9344
- clientOid: string;
9345
- }
9777
+ /**
9778
+ * Generates a timestamp for signing API requests.
9779
+ *
9780
+ * This method can be overridden or customized using `customTimestampFn`
9781
+ * to implement a custom timestamp synchronization mechanism.
9782
+ * If no custom function is provided, it defaults to the current system time.
9783
+ */
9784
+ private getSignTimestampMs(): number
9346
9785
  ⋮----
9347
- export interface WsAPITopicRequestParamMap {
9348
- [key: string]: unknown;
9349
-
9350
- subscribe: never;
9351
- unsubscribe: never;
9352
- login: never;
9353
- access: never;
9354
- request: never;
9355
-
9356
- ping: void;
9357
-
9358
- 'spot.order': SubmitHFOrderRequest;
9359
- 'margin.order': SubmitHFMarginOrderRequest;
9360
- 'futures.order': Order;
9361
- 'spot.cancel': WSAPICancelOrderRequest;
9362
- 'margin.cancel': WSAPICancelOrderRequest;
9363
- 'futures.cancel': { orderId: string } | { clientOid: string; symbol: string };
9364
- 'futures.multi_cancel': BatchCancelOrdersRequest;
9365
- 'futures.multi_order': Order[];
9366
- 'spot.sync_order': SubmitHFOrderRequest;
9367
- 'spot.modify': ModifyHFOrderRequest;
9368
- 'spot.sync_cancel': WSAPICancelOrderRequest;
9369
- }
9786
+ private hasValidCredentials()
9787
+ ⋮----
9788
+ setAccessToken(newAccessToken: string)
9789
+ ⋮----
9790
+ hasAccessToken(): boolean
9791
+ ⋮----
9792
+ get(endpoint: string, params?: any)
9793
+ ⋮----
9794
+ post(endpoint: string, params?: any)
9795
+ ⋮----
9796
+ getPrivate(endpoint: string, params?: any)
9797
+ ⋮----
9798
+ postPrivate(endpoint: string, params?: any)
9799
+ ⋮----
9800
+ deletePrivate(endpoint: string, params?: any)
9801
+ ⋮----
9802
+ /**
9803
+ * @private Make a HTTP request to a specific endpoint. Private endpoint API calls are automatically signed.
9804
+ */
9805
+ private async _call(
9806
+ method: Method,
9807
+ endpoint: string,
9808
+ params?: any,
9809
+ isPublicApi?: boolean,
9810
+ ): Promise<any>
9370
9811
  ⋮----
9371
- export interface WsAPITopicResponseMap {
9372
- [key: string]: unknown;
9373
-
9374
- subscribe: never;
9375
- unsubscribe: never;
9376
- login: never;
9377
- access: never;
9378
- request: never;
9379
-
9380
- ping: unknown;
9381
-
9382
- 'spot.order': WSAPIResponse<WSAPIOrderResponse>;
9383
- 'margin.order': WSAPIResponse<MarginSubmitOrderV3Response>;
9384
- 'futures.order': WSAPIResponse<WSAPIOrderResponse>;
9385
- 'spot.cancel': WSAPIResponse<WSAPIOrderResponse>;
9386
- 'margin.cancel': WSAPIResponse<WSAPIOrderResponse>;
9387
- 'futures.cancel': WSAPIResponse<
9388
- { cancelledOrderIds: string[] } | { clientOid: string }
9389
- >;
9390
- 'futures.multi_cancel': WSAPIResponse<BatchCancelOrderResult[]>;
9391
- 'futures.multi_order': WSAPIResponse<SubmitMultipleOrdersFuturesResponse[]>;
9392
- 'spot.sync_order': WSAPIResponse<SubmitHFOrderSyncResponse>;
9393
- 'spot.modify': WSAPIResponse<{
9394
- newOrderId: string;
9395
- clientOid: string;
9396
- }>;
9397
- 'spot.sync_cancel': WSAPIResponse<SyncCancelHFOrderResponse>;
9398
- }
9812
+ // Sanity check to make sure it's only ever prefixed by one forward slash
9399
9813
  ⋮----
9400
- export interface WSAPIAuthenticationRequestFromServer {
9401
- timestamp: number;
9402
- sessionId: string;
9403
- }
9814
+ // Build a request and handle signature process
9815
+ ⋮----
9816
+ // Dispatch request
9817
+ ⋮----
9818
+ // Throw if API returns an error (e.g. insufficient balance)
9404
9819
  ⋮----
9405
- export interface WSAPIAuthenticationConfirmedFromServer {
9406
- pingInterval: number;
9407
- sessionId: string;
9408
- pingTimeout: number;
9409
- data: 'welcome';
9410
- }
9411
-
9412
- ================
9413
- File: examples/WebSockets/ws-api-client.ts
9414
- ================
9415
9820
  /**
9416
- * KuCoin WebSocket API Client - Complete Example
9417
- *
9418
- * This example demonstrates all available WebSocket API operations:
9419
- * - Spot trading: submit, modify, cancel, sync operations
9420
- * - Margin trading: submit and cancel orders
9421
- * - Futures trading: submit, cancel, batch operations
9422
- *
9423
- * Usage:
9424
- * Make sure to set your API credentials in environment variables:
9425
- * - API_KEY
9426
- * - API_SECRET
9427
- * - API_PASSPHRASE
9428
- *
9429
- * or pass them as arguments to the constructor
9430
- */
9821
+ * @private generic handler to parse request exceptions
9822
+ */
9823
+ parseException(e: any, requestParams: any): unknown
9431
9824
  ⋮----
9432
- import { DefaultLogger, WebsocketAPIClient } from '../../src/index.js';
9825
+ // Something happened in setting up the request that triggered an error
9433
9826
  ⋮----
9434
- async function main()
9827
+ // request made but no response received
9435
9828
  ⋮----
9436
- // For a more detailed view of the WebsocketClient, enable the `trace` level by uncommenting the below line:
9437
- // trace: (...params) => console.log(new Date(), 'trace', ...params),
9829
+ // The request was made and the server responded with a status code
9830
+ // that falls out of the range of 2xx
9438
9831
  ⋮----
9439
- passphrase: process.env.API_PASSPHRASE || 'apiPassPhraseHere', // This is NOT your account password
9832
+ // console.error('err: ', response?.data);
9440
9833
  ⋮----
9441
- // If you want your own event handlers instead of the default ones with logs, disable this setting and see the `attachEventHandlers` example below:
9442
- // attachEventListeners: false
9834
+ // Prevent credentials from leaking into error messages
9443
9835
  ⋮----
9444
- // Example usage for each WebSocket API operation
9836
+ private async signMessage(
9837
+ paramsStr: string,
9838
+ secret: string,
9839
+ method: SignEncodeMethod,
9840
+ algorithm: SignAlgorithm,
9841
+ ): Promise<string>
9445
9842
  ⋮----
9446
- // 1. Submit Spot Order
9843
+ /**
9844
+ * @private sign request and set recv window
9845
+ */
9846
+ private async signRequest<T extends object | undefined = {}>(
9847
+ data: T,
9848
+ endpoint: string,
9849
+ method: Method,
9850
+ signMethod: SignMethod,
9851
+ ): Promise<SignedRequest<T>>
9447
9852
  ⋮----
9448
- price: '20000', // Very low price to avoid accidental execution
9853
+ // Only sign when no access token is provided
9449
9854
  ⋮----
9450
- // 2. Submit Sync Spot Order
9855
+ private async prepareSignParams<TParams extends object | undefined>(
9856
+ method: Method,
9857
+ endpoint: string,
9858
+ signMethod: SignMethod,
9859
+ params?: TParams,
9860
+ isPublicApi?: true,
9861
+ ): Promise<UnsignedRequest<TParams>>;
9451
9862
  ⋮----
9452
- price: '1000', // Very high price to avoid accidental execution
9863
+ private async prepareSignParams<TParams extends object | undefined>(
9864
+ method: Method,
9865
+ endpoint: string,
9866
+ signMethod: SignMethod,
9867
+ params?: TParams,
9868
+ isPublicApi?: false | undefined,
9869
+ ): Promise<SignedRequest<TParams>>;
9453
9870
  ⋮----
9454
- // 3. Modify Spot Order (requires existing order ID)
9871
+ private async prepareSignParams<TParams extends object | undefined>(
9872
+ method: Method,
9873
+ endpoint: string,
9874
+ signMethod: SignMethod,
9875
+ params?: TParams,
9876
+ isPublicApi?: boolean,
9877
+ )
9455
9878
  ⋮----
9456
- orderId: '68cc3476693c1c00072ef1d9', // Replace with actual order ID
9879
+ /** Returns an axios request object. Handles signing process automatically if this is a private API call */
9880
+ private async buildRequest(
9881
+ method: Method,
9882
+ endpoint: string,
9883
+ url: string,
9884
+ params?: any,
9885
+ isPublicApi?: boolean,
9886
+ ): Promise<AxiosRequestConfig>
9457
9887
  ⋮----
9458
- // 4. Cancel Spot Order
9888
+ // Support for Authorization header, if provided:
9889
+ // https://github.com/tiagosiebler/kucoin-api/issues/2
9890
+ // Use restClient.setAccessToken(newToken), if you need to store a new access token
9891
+
9892
+ ================
9893
+ File: src/index.ts
9894
+ ================
9895
+
9896
+
9897
+ ================
9898
+ File: src/WebsocketClient.ts
9899
+ ================
9900
+ import { FuturesClient } from './FuturesClient.js';
9901
+ import { SignedRequest } from './lib/BaseRestClient.js';
9902
+ import { BaseWebsocketClient, EmittableEvent } from './lib/BaseWSClient.js';
9903
+ import { neverGuard } from './lib/misc-util.js';
9904
+ import {
9905
+ APIIDFutures,
9906
+ APIIDFuturesSign,
9907
+ APIIDMain,
9908
+ APIIDMainSign,
9909
+ RestClientOptions,
9910
+ serializeParams,
9911
+ } from './lib/requestUtils.js';
9912
+ import {
9913
+ hashMessage,
9914
+ SignAlgorithm,
9915
+ SignEncodeMethod,
9916
+ signMessage,
9917
+ } from './lib/webCryptoAPI.js';
9918
+ import {
9919
+ getPromiseRefForWSAPIRequest,
9920
+ isWSAPIWsKey,
9921
+ WS_KEY_MAP,
9922
+ WsKey,
9923
+ WsTopicRequest,
9924
+ } from './lib/websocket/websocket-util.js';
9925
+ import { WSConnectedResult } from './lib/websocket/WsStore.types.js';
9926
+ import { SpotClient } from './SpotClient.js';
9927
+ import { APISuccessResponse } from './types/response/shared.types.js';
9928
+ import { WsConnectionInfo } from './types/response/ws.js';
9929
+ import {
9930
+ Exact,
9931
+ WSAPIAuthenticationRequestFromServer,
9932
+ WsAPITopicRequestParamMap,
9933
+ WsAPITopicResponseMap,
9934
+ WsAPIWsKeyTopicMap,
9935
+ WsOperation,
9936
+ WsRequestOperation,
9937
+ WsRequestOperationKucoin,
9938
+ } from './types/websockets/ws-api.js';
9939
+ import { MessageEventLike } from './types/websockets/ws-events.js';
9940
+ import { WsMarket } from './types/websockets/ws-general.js';
9459
9941
  ⋮----
9460
- orderId: '68cc34c6693c1c0007301929', // Replace with actual order ID
9942
+ function getRandomInt(max: number)
9461
9943
  ⋮----
9462
- // 5. Cancel Sync Spot Order
9944
+ export interface WSAPIRequestFlags {
9945
+ /** If true, will skip auth requirement for WS API connection */
9946
+ authIsOptional?: boolean | undefined;
9947
+ }
9463
9948
  ⋮----
9464
- orderId: '68cc3530b9870a0007670294', // Replace with actual client order ID
9949
+ /** If true, will skip auth requirement for WS API connection */
9465
9950
  ⋮----
9466
- // 6. Submit Margin Order
9951
+ /** Any WS keys in this list will trigger auth on connect, if credentials are available */
9467
9952
  ⋮----
9468
- price: '19000', // Very low price to avoid accidental execution
9953
+ /** Any WS keys in this list will ALWAYS skip the authentication process, even if credentials are available */
9469
9954
  ⋮----
9470
- isIsolated: false, // false for cross margin, true for isolated
9955
+ /**
9956
+ * WS topics are always a string for this exchange. Some exchanges use complex objects.
9957
+ */
9958
+ type WsTopic = string;
9471
9959
  ⋮----
9472
- // 7. Cancel Margin Order
9960
+ export class WebsocketClient extends BaseWebsocketClient<WsKey>
9473
9961
  ⋮----
9474
- orderId: 'your-margin-order-id-here', // Replace with actual order ID
9962
+ private getRESTClient(wsKey: WsKey): SpotClient | FuturesClient
9475
9963
  ⋮----
9476
- // 8. Submit Futures Order
9964
+ const getClientType = (wsKey: WsKey): 'spot' | 'futures' | null =>
9477
9965
  ⋮----
9478
- price: '1000', // Very low price to avoid accidental execution
9966
+ private getRestClientOptions(): RestClientOptions
9479
9967
  ⋮----
9480
- positionSide: 'LONG', // needed if trading two-way (hedge) position mode
9968
+ private async getWSConnectionInfo(
9969
+ wsKey: WsKey,
9970
+ ): Promise<APISuccessResponse<WsConnectionInfo>>
9481
9971
  ⋮----
9482
- // 9. Cancel Futures Order
9972
+ private async signMessage(
9973
+ paramsStr: string,
9974
+ secret: string,
9975
+ method: SignEncodeMethod,
9976
+ algorithm: SignAlgorithm,
9977
+ ): Promise<string>
9483
9978
  ⋮----
9484
- orderId: '358196976308797441', // Replace with actual order ID
9979
+ /**
9980
+ * Request connection of all dependent (public & private) websockets, instead of waiting for automatic connection by library
9981
+ */
9982
+ public connectAll(): Promise<(WSConnectedResult | undefined)[]>
9983
+ ⋮----
9984
+ /**
9985
+ * Request subscription to one or more topics. Pass topics as either an array of strings, or array of objects (if the topic has parameters).
9986
+ * Objects should be formatted as {topic: string, params: object}.
9987
+ *
9988
+ * - Subscriptions are automatically routed to the correct websocket connection.
9989
+ * - Authentication/connection is automatic.
9990
+ * - Resubscribe after network issues is automatic.
9991
+ *
9992
+ * Call `unsubscribe(topics)` to remove topics
9993
+ */
9994
+ public subscribe(
9995
+ requests:
9996
+ | (WsTopicRequest<WsTopic> | WsTopic)
9997
+ | (WsTopicRequest<WsTopic> | WsTopic)[],
9998
+ wsKey: WsKey,
9999
+ )
10000
+ ⋮----
10001
+ /**
10002
+ * Unsubscribe from one or more topics. Similar to subscribe() but in reverse.
10003
+ *
10004
+ * - Requests are automatically routed to the correct websocket connection.
10005
+ * - These topics will be removed from the topic cache, so they won't be subscribed to again.
10006
+ */
10007
+ public unsubscribe(
10008
+ requests:
10009
+ | (WsTopicRequest<WsTopic> | WsTopic)
10010
+ | (WsTopicRequest<WsTopic> | WsTopic)[],
10011
+ wsKey: WsKey,
10012
+ )
9485
10013
  ⋮----
9486
- // 10. Submit Multiple Futures Orders
10014
+ async sendWSAPIRequest<
10015
+ TWSKey extends keyof WsAPIWsKeyTopicMap,
10016
+ TWSOperation extends WsAPIWsKeyTopicMap[TWSKey],
10017
+ // if this throws a type error, probably forgot to add a new operation to WsAPITopicRequestParamMap
10018
+ TWSParams extends Exact<WsAPITopicRequestParamMap[TWSOperation]>,
10019
+ TWSAPIResponse extends
10020
+ WsAPITopicResponseMap[TWSOperation] = WsAPITopicResponseMap[TWSOperation],
10021
+ >(
10022
+ wsKey: TWSKey,
10023
+ operation: TWSOperation,
10024
+ params: TWSParams & { signRequest?: boolean },
10025
+ requestFlags?: WSAPIRequestFlags,
10026
+ ): Promise<TWSAPIResponse>
9487
10027
  ⋮----
9488
- price: '1000', // Very low price to avoid accidental execution
10028
+ // if this throws a type error, probably forgot to add a new operation to WsAPITopicRequestParamMap
9489
10029
  ⋮----
9490
- positionSide: 'LONG', // Needed if trading hedge/two-way mode. Optional in one-way mode.
10030
+ /**
10031
+ * Base Info:
10032
+ * - https://www.kucoin.com/docs-new/websocket-api/base-info/introduction
10033
+ *
10034
+ * Add/Cancel API info:
10035
+ * - https://www.kucoin.com/docs-new/3470133w0
10036
+ **/
9491
10037
  ⋮----
9492
- price: '1010', // Very low price to avoid accidental execution
10038
+ // this.logger.trace(`sendWSAPIRequest(): assertIsConnected("${wsKey}")...`);
9493
10039
  ⋮----
9494
- // 11. Cancel Multiple Futures Orders
10040
+ // this.logger.trace('sendWSAPIRequest(): assertIsConnected(${wsKey}) ok');
9495
10041
  ⋮----
9496
- orderIdsList: ['order-id-1', 'order-id-2'], // Replace with actual order IDs
10042
+ // Some commands don't require authentication.
9497
10043
  ⋮----
9498
- // Start executing the example workflow
9499
-
9500
- ================
9501
- File: src/lib/BaseRestClient.ts
9502
- ================
9503
- import axios, { AxiosRequestConfig, AxiosResponse, Method } from 'axios';
9504
- import https from 'https';
10044
+ // this.logger.trace(
10045
+ // 'sendWSAPIRequest(): assertIsAuthenticated(${wsKey})...',
10046
+ // );
9505
10047
  ⋮----
9506
- import { neverGuard } from './misc-util.js';
9507
- import {
9508
- APIIDFutures,
9509
- APIIDFuturesSign,
9510
- APIIDMain,
9511
- APIIDMainSign,
9512
- getRestBaseUrl,
9513
- REST_CLIENT_TYPE_ENUM,
9514
- RestClientOptions,
9515
- RestClientType,
9516
- serializeParams,
9517
- } from './requestUtils.js';
9518
- import {
9519
- checkWebCryptoAPISupported,
9520
- SignAlgorithm,
9521
- SignEncodeMethod,
9522
- signMessage,
9523
- } from './webCryptoAPI.js';
10048
+ // this.logger.trace(
10049
+ // 'sendWSAPIRequest(): assertIsAuthenticated(${wsKey}) ok',
10050
+ // );
9524
10051
  ⋮----
9525
- export interface SignedRequest<T extends object | undefined = {}> {
9526
- originalParams: T;
9527
- paramsWithSign?: T & { sign: string };
9528
- serializedParams: string;
9529
- sign: string;
9530
- queryParamsWithSign: string;
9531
- timestamp: number;
9532
- recvWindow: number;
9533
- }
10052
+ // Sign, if needed
9534
10053
  ⋮----
9535
- interface UnsignedRequest<T extends object | undefined = {}> {
9536
- originalParams: T;
9537
- paramsWithSign: T;
9538
- }
10054
+ // Store deferred promise, resolved within the "resolveEmittableEvents" method while parsing incoming events
9539
10055
  ⋮----
9540
- type SignMethod = 'kucoin';
10056
+ // Enrich returned promise with request context for easier debugging
9541
10057
  ⋮----
9542
- // request: {
9543
- // url: response.config.url,
9544
- // method: response.config.method,
9545
- // data: response.config.data,
9546
- // headers: response.config.headers,
9547
- // },
10058
+ // throw e;
9548
10059
  ⋮----
9549
- export abstract class BaseRestClient
10060
+ // Send event.
9550
10061
  ⋮----
9551
- /** Defines the client type (affecting how requests & signatures behave) */
9552
- abstract getClientType(): RestClientType;
10062
+ // Return deferred promise, so caller can await this call
9553
10063
  ⋮----
9554
10064
  /**
9555
- * Create an instance of the REST client. Pass API credentials in the object in the first parameter.
9556
- * @param {RestClientOptions} [restClientOptions={}] options to configure REST API connectivity
9557
- * @param {AxiosRequestConfig} [networkOptions={}] HTTP networking options for axios
10065
+ *
10066
+ * Internal methods
10067
+ *
9558
10068
  */
9559
- constructor(
9560
- restClientOptions: RestClientOptions = {},
9561
- networkOptions: AxiosRequestConfig = {},
9562
- )
9563
- ⋮----
9564
- /** Throw errors if any request params are empty */
9565
10069
  ⋮----
9566
- /** in ms == 5 minutes by default */
9567
- ⋮----
9568
- /** inject custom rquest options based on axios specs - see axios docs for more guidance on AxiosRequestConfig: https://github.com/axios/axios#request-config */
10070
+ private async signWSAPIRequest<TRequestParams extends string = string>(
10071
+ requestEvent: WsRequestOperationKucoin<TRequestParams>,
10072
+ ): Promise<WsRequestOperationKucoin<TRequestParams>>
9569
10073
  ⋮----
9570
- // If enabled, configure a https agent with keepAlive enabled
10074
+ /**
10075
+ * Whatever url this method returns, it's connected to as-is!
10076
+ *
10077
+ * If a token or anything else is needed in the URL, this is a good place to add it.
10078
+ */
10079
+ protected async getWsUrl(wsKey: WsKey): Promise<string>
9571
10080
  ⋮----
9572
- // Extract existing https agent parameters, if provided, to prevent the keepAlive flag from overwriting an existing https agent completely
10081
+ // These WS URLs are dynamically fetched via the REST API, as per API spec
9573
10082
  ⋮----
9574
- // For more advanced configuration, raise an issue on GitHub or use the "networkOptions"
9575
- // parameter to define a custom httpsAgent with the desired properties
10083
+ // WS API URL works differently: https://www.kucoin.com/docs-new/3470133w0
10084
+ // wss://wsapi.kucoin.com/v1/private?apikey=xxx&sign=xxx&passphrase=xxx&timestamp=xxx
9576
10085
  ⋮----
9577
- // Check Web Crypto API support when credentials are provided
10086
+ // ws_url = f"{url}/v1/private?{url_path}&sign={sign_value}&passphrase={passphrase_sign}"
9578
10087
  ⋮----
9579
- // Throw if one of the 3 values is missing, but at least one of them is set
10088
+ // original = f"{apikey}{timestamp}"
9580
10089
  ⋮----
9581
- /**
9582
- * Generates a timestamp for signing API requests.
9583
- *
9584
- * This method can be overridden or customized using `customTimestampFn`
9585
- * to implement a custom timestamp synchronization mechanism.
9586
- * If no custom function is provided, it defaults to the current system time.
9587
- */
9588
- private getSignTimestampMs(): number
10090
+ // console.log('signParams: ', {
10091
+ // paramsStr,
10092
+ // partnerSignParam,
10093
+ // queryString,
10094
+ // finalUrl,
10095
+ // });
9589
10096
  ⋮----
9590
- private hasValidCredentials()
10097
+ protected sendPingEvent(wsKey: WsKey)
9591
10098
  ⋮----
9592
- setAccessToken(newAccessToken: string)
10099
+ protected sendPongEvent(wsKey: WsKey)
9593
10100
  ⋮----
9594
- hasAccessToken(): boolean
10101
+ // Send a protocol layer pong
9595
10102
  ⋮----
9596
- get(endpoint: string, params?: any)
10103
+ // Not really used for kucoin - they don't send pings
10104
+ protected isWsPing(msg: any): boolean
9597
10105
  ⋮----
9598
- post(endpoint: string, params?: any)
10106
+ protected isWsPong(msg: any): boolean
9599
10107
  ⋮----
9600
- getPrivate(endpoint: string, params?: any)
10108
+ // this.logger.info(`Not a pong: `, msg);
9601
10109
  ⋮----
9602
- postPrivate(endpoint: string, params?: any)
10110
+ protected resolveEmittableEvents(
10111
+ wsKey: WsKey,
10112
+ event: MessageEventLike,
10113
+ ): EmittableEvent[]
9603
10114
  ⋮----
9604
- deletePrivate(endpoint: string, params?: any)
10115
+ // parsed: JSON.stringify(parsed, null, 2),
9605
10116
  ⋮----
9606
- /**
9607
- * @private Make a HTTP request to a specific endpoint. Private endpoint API calls are automatically signed.
9608
- */
9609
- private async _call(
9610
- method: Method,
9611
- endpoint: string,
9612
- params?: any,
9613
- isPublicApi?: boolean,
9614
- ): Promise<any>
10117
+ // These are request/reply pattern events (e.g. after subscribing to topics or authenticating)
9615
10118
  ⋮----
9616
- // Sanity check to make sure it's only ever prefixed by one forward slash
10119
+ // Request/reply pattern for authentication success
9617
10120
  ⋮----
9618
- // Build a request and handle signature process
10121
+ // This is the counterpart to getPromiseRefForWSAPIRequest
9619
10122
  ⋮----
9620
- // Dispatch request
10123
+ // WS API Exception
9621
10124
  ⋮----
9622
- // Throw if API returns an error (e.g. insufficient balance)
10125
+ // WS API Success
9623
10126
  ⋮----
9624
10127
  /**
9625
- * @private generic handler to parse request exceptions
10128
+ * Determines if a topic is for a private channel, using a hardcoded list of strings
9626
10129
  */
9627
- parseException(e: any, requestParams: any): unknown
9628
- ⋮----
9629
- // Something happened in setting up the request that triggered an error
10130
+ protected isPrivateTopicRequest(
10131
+ request: WsTopicRequest<string>,
10132
+ wsKey: WsKey,
10133
+ ): boolean
9630
10134
  ⋮----
9631
- // request made but no response received
10135
+ protected getWsKeyForMarket(market: WsMarket, isPrivate: boolean): WsKey
9632
10136
  ⋮----
9633
- // The request was made and the server responded with a status code
9634
- // that falls out of the range of 2xx
10137
+ protected getWsMarketForWsKey(key: WsKey): WsMarket
9635
10138
  ⋮----
9636
- // console.error('err: ', response?.data);
10139
+ protected getPrivateWSKeys(): WsKey[]
9637
10140
  ⋮----
9638
- // Prevent credentials from leaking into error messages
10141
+ /** Force subscription requests to be sent in smaller batches, if a number is returned */
10142
+ protected getMaxTopicsPerSubscribeEvent(wsKey: WsKey): number | null
9639
10143
  ⋮----
9640
- private async signMessage(
9641
- paramsStr: string,
9642
- secret: string,
9643
- method: SignEncodeMethod,
9644
- algorithm: SignAlgorithm,
9645
- ): Promise<string>
10144
+ // Return a number if there's a limit on the number of sub topics per rq
10145
+ // Always 1 at a time for this exchange
9646
10146
  ⋮----
9647
10147
  /**
9648
- * @private sign request and set recv window
10148
+ * Map one or more topics into fully prepared "subscribe request" events (already stringified and ready to send)
9649
10149
  */
9650
- private async signRequest<T extends object | undefined = {}>(
9651
- data: T,
9652
- endpoint: string,
9653
- method: Method,
9654
- signMethod: SignMethod,
9655
- ): Promise<SignedRequest<T>>
9656
- ⋮----
9657
- // Only sign when no access token is provided
10150
+ protected async getWsOperationEventsForTopics(
10151
+ topicRequests: WsTopicRequest<string>[],
10152
+ wsKey: WsKey,
10153
+ operation: WsOperation,
10154
+ ): Promise<string[]>
9658
10155
  ⋮----
9659
- private async prepareSignParams<TParams extends object | undefined>(
9660
- method: Method,
9661
- endpoint: string,
9662
- signMethod: SignMethod,
9663
- params?: TParams,
9664
- isPublicApi?: true,
9665
- ): Promise<UnsignedRequest<TParams>>;
10156
+ // Operations structured in a way that this exchange understands
9666
10157
  ⋮----
9667
- private async prepareSignParams<TParams extends object | undefined>(
9668
- method: Method,
9669
- endpoint: string,
9670
- signMethod: SignMethod,
9671
- params?: TParams,
9672
- isPublicApi?: false | undefined,
9673
- ): Promise<SignedRequest<TParams>>;
10158
+ // Events that are ready to send (usually stringified JSON)
9674
10159
  ⋮----
9675
- private async prepareSignParams<TParams extends object | undefined>(
9676
- method: Method,
9677
- endpoint: string,
9678
- signMethod: SignMethod,
9679
- params?: TParams,
9680
- isPublicApi?: boolean,
9681
- )
10160
+ protected async getWsAuthRequestEvent(
10161
+ wsKey: WsKey,
10162
+ eventToAuth?: WSAPIAuthenticationRequestFromServer,
10163
+ ): Promise<object | string | 'waitForEvent' | void>
9682
10164
  ⋮----
9683
- /** Returns an axios request object. Handles signing process automatically if this is a private API call */
9684
- private async buildRequest(
9685
- method: Method,
9686
- endpoint: string,
9687
- url: string,
9688
- params?: any,
9689
- isPublicApi?: boolean,
9690
- ): Promise<AxiosRequestConfig>
10165
+ // Send anything for WS API
9691
10166
  ⋮----
9692
- // Support for Authorization header, if provided:
9693
- // https://github.com/tiagosiebler/kucoin-api/issues/2
9694
- // Use restClient.setAccessToken(newToken), if you need to store a new access token
9695
-
9696
- ================
9697
- File: src/index.ts
9698
- ================
9699
-
10167
+ // Don't send anything, don't resolve auth promise. Wait for auth handshake from server
10168
+ ⋮----
10169
+ // Don't send anything for all other WS connections, since they auth as part of the connection (not after connect). Returning an empty value here will short-circuit the assertIsAuthenticated workflow.
9700
10170
 
9701
10171
  ================
9702
10172
  File: README.md
@@ -9759,7 +10229,7 @@ Updated & performant JavaScript & Node.js SDK for the Kucoin REST APIs and WebSo
9759
10229
  - [Spot & Margin Trading](#spot--margin-trading)
9760
10230
  - [Futures Trading](#futures-trading)
9761
10231
  - [Broker Operations](#broker-operations)
9762
- - [Unified Trading Account API](#unified-trading-account-api)
10232
+ - [Unified API](#unified-api)
9763
10233
  - [WebSockets](#websockets)
9764
10234
  - [WebSocket Consumers](#websocket-consumers)
9765
10235
  - [Public WebSocket Streams](#public-websocket-streams)
@@ -9894,9 +10364,9 @@ Use the `FuturesClient` for futures trading operations. See [FuturesClient](./sr
9894
10364
 
9895
10365
  Use the `BrokerClient` for broker and sub-account management operations. See [BrokerClient](./src/BrokerClient.ts) for complete API coverage.
9896
10366
 
9897
- ### Unified Trading Account API
10367
+ ### Unified API
9898
10368
 
9899
- The `UnifiedAPIClient` provides access to KuCoin's Unified Trading Account API endpoints, which offer streamlined market data access across Spot, Futures, and Margin trading products.
10369
+ The `UnifiedAPIClient` provides access to KuCoin's Unified API endpoints, which offer streamlined market data access across Spot, Futures, and Margin trading products. It doesn't serve a purpose of a UTA account(Unified trading account) - but it is a new generation of API endpoints generalised for all trading products.
9900
10370
 
9901
10371
  ## WebSockets
9902
10372
 
@@ -10503,6 +10973,8 @@ public async connect(
10503
10973
  throwOnError?: boolean,
10504
10974
  ): Promise<WSConnectedResult | undefined>
10505
10975
  ⋮----
10976
+ // Important: don't check for RECONNECTING here, or this clashes with reconnectWithDelay()!
10977
+ ⋮----
10506
10978
  private connectToWsUrl(url: string, wsKey: TWSKey): WebSocket
10507
10979
  ⋮----
10508
10980
  // Native ws ping/pong frames are not in use for okx
@@ -10528,446 +11000,172 @@ private ping(wsKey: TWSKey)
10528
11000
  private clearTimers(wsKey: TWSKey)
10529
11001
  ⋮----
10530
11002
  // Send a ping at intervals
10531
- private clearPingTimer(wsKey: TWSKey)
10532
- ⋮----
10533
- // Expect a pong within a time limit
10534
- private clearPongTimer(wsKey: TWSKey)
10535
- ⋮----
10536
- // this.logger.trace(`Cleared pong timeout for "${wsKey}"`);
10537
- ⋮----
10538
- // this.logger.trace(`No active pong timer for "${wsKey}"`);
10539
- ⋮----
10540
- /**
10541
- * Simply builds and sends subscribe events for a list of topics for a ws key
10542
- *
10543
- * @private Use the `subscribe(topics)` or `subscribeTopicsForWsKey(topics, wsKey)` method to subscribe to topics. Send WS message to subscribe to topics.
10544
- */
10545
- private async requestSubscribeTopics(
10546
- wsKey: TWSKey,
10547
- topics: WsTopicRequest<string>[],
10548
- )
10549
- ⋮----
10550
- // Automatically splits requests into smaller batches, if needed
10551
- ⋮----
10552
- `Subscribing to ${topics.length} "${wsKey}" topics in ${subscribeWsMessages.length} batches.`, // Events: "${JSON.stringify(topics)}"
10553
- ⋮----
10554
- // this.logger.trace(`Sending batch via message: "${wsMessage}"`);
10555
- ⋮----
10556
- /**
10557
- * Simply builds and sends unsubscribe events for a list of topics for a ws key
10558
- *
10559
- * @private Use the `unsubscribe(topics)` method to unsubscribe from topics. Send WS message to unsubscribe from topics.
10560
- */
10561
- private async requestUnsubscribeTopics(
10562
- wsKey: TWSKey,
10563
- wsTopicRequests: WsTopicRequest<string>[],
10564
- )
10565
- ⋮----
10566
- /**
10567
- * Try sending a string event on a WS connection (identified by the WS Key)
10568
- */
10569
- public tryWsSend(
10570
- wsKey: TWSKey,
10571
- wsMessage: string,
10572
- throwExceptions?: boolean,
10573
- )
10574
- ⋮----
10575
- private async onWsOpen(
10576
- event: WebSocket.Event,
10577
- wsKey: TWSKey,
10578
- url: string,
10579
- ws: WebSocket,
10580
- )
10581
- ⋮----
10582
- // Resolve & cleanup deferred "connection attempt in progress" promise
10583
- ⋮----
10584
- // Remove before continuing, in case there's more requests queued
10585
- ⋮----
10586
- /**
10587
- * Called automatically once a connection is ready.
10588
- * - Some exchanges are ready immediately after the connections open.
10589
- * - Some exchanges send an event to confirm the connection is ready for us.
10590
- *
10591
- * This method is called to act when the connection is ready. Use `requireConnectionReadyConfirmation` to control how this is called.
10592
- */
10593
- private async onWsReadyForEvents(wsKey: TWSKey)
10594
- ⋮----
10595
- // Resolve & cleanup deferred "connection attempt in progress" promise
10596
- ⋮----
10597
- // Remove before resolving, in case there's more requests queued
10598
- ⋮----
10599
- // Some websockets require an auth packet to be sent after opening the connection
10600
- ⋮----
10601
- // Reconnect to topics known before it connected
10602
- ⋮----
10603
- // Request sub to public topics, if any
10604
- ⋮----
10605
- // Request sub to private topics, if auth on connect isn't needed
10606
- ⋮----
10607
- /**
10608
- * Handle subscription to private topics _after_ authentication successfully completes asynchronously.
10609
- *
10610
- * Only used for exchanges that require auth before sending private topic subscription requests
10611
- */
10612
- private onWsAuthenticated(
10613
- wsKey: TWSKey,
10614
- event: { isWSAPI?: boolean; WSAPIAuthChannel?: string },
10615
- )
10616
- ⋮----
10617
- // Resolve & cleanup deferred "auth attempt in progress" promise
10618
- ⋮----
10619
- // Remove before continuing, in case there's more requests queued
10620
- ⋮----
10621
- private onWsPing(
10622
- event: any,
10623
- wsKey: TWSKey,
10624
- ws: WebSocket,
10625
- source: WsEventInternalSrc,
10626
- )
10627
- ⋮----
10628
- private onWsPong(event: any, wsKey: TWSKey, source: WsEventInternalSrc)
10629
- ⋮----
10630
- private onWsMessage(event: unknown, wsKey: TWSKey, ws: WebSocket)
10631
- ⋮----
10632
- // any message can clear the pong timer - wouldn't get a message if the ws wasn't working
10633
- ⋮----
10634
- // console.log(`raw event: `, { data, dataType, emittableEvents });
10635
- ⋮----
10636
- // Other event types are automatically emitted here
10637
- // this.logger.trace(
10638
- // `onWsMessage().emit(${emittable.eventType})`,
10639
- // emittableFinalEvent,
10640
- // );
10641
- ⋮----
10642
- // this.logger.trace(
10643
- // `onWsMessage().emit(${emittable.eventType}).done()`,
10644
- // emittableFinalEvent,
10645
- // );
10646
- ⋮----
10647
- private onWsClose(event: unknown, wsKey: TWSKey)
10648
- ⋮----
10649
- // unintentional close, attempt recovery
10650
- ⋮----
10651
- // clean up any pending promises for this connection
10652
- ⋮----
10653
- // intentional close - clean up
10654
- // clean up any pending promises for this connection
10655
- ⋮----
10656
- // This was an intentional close, delete all state for this connection, as if it never existed:
10657
- ⋮----
10658
- private getWs(wsKey: TWSKey)
10659
- ⋮----
10660
- private setWsState(wsKey: TWSKey, state: WsConnectionStateEnum)
10661
- ⋮----
10662
- /**
10663
- * Promise-driven method to assert that a ws has successfully connected (will await until connection is open)
10664
- */
10665
- protected async assertIsConnected(wsKey: TWSKey): Promise<unknown>
10666
- ⋮----
10667
- // Already in progress? Await shared promise and retry
10668
- ⋮----
10669
- // this.logger.trace('assertIsConnected(): awaiting...');
10670
- ⋮----
10671
- // this.logger.trace('assertIsConnected(): awaiting...connected!');
10672
- ⋮----
10673
- // Start connection, it should automatically store/return a promise.
10674
- // this.logger.trace('assertIsConnected(): connecting...');
10675
- ⋮----
10676
- // this.logger.trace('assertIsConnected(): connecting...newly connected!');
10677
- ⋮----
10678
- /**
10679
- * Promise-driven method to assert that a ws has been successfully authenticated (will await until auth is confirmed)
10680
- */
10681
- public async assertIsAuthenticated(wsKey: TWSKey): Promise<unknown>
10682
- ⋮----
10683
- // this.logger.trace('assertIsAuthenticated(): connecting...');
10684
- ⋮----
10685
- // Already in progress? Await shared promise and retry
10686
- ⋮----
10687
- // this.logger.trace('assertIsAuthenticated(): awaiting...');
10688
- ⋮----
10689
- // this.logger.trace('assertIsAuthenticated(): authenticated!');
10690
- ⋮----
10691
- // this.logger.trace('assertIsAuthenticated(): ok');
10692
- ⋮----
10693
- // Start authentication, it should automatically store/return a promise.
10694
- // this.logger.trace('assertIsAuthenticated(): authenticating...');
10695
- ⋮----
10696
- // this.logger.trace('assertIsAuthenticated(): newly authenticated!');
10697
-
10698
- ================
10699
- File: src/WebsocketClient.ts
10700
- ================
10701
- import { FuturesClient } from './FuturesClient.js';
10702
- import { SignedRequest } from './lib/BaseRestClient.js';
10703
- import { BaseWebsocketClient, EmittableEvent } from './lib/BaseWSClient.js';
10704
- import { neverGuard } from './lib/misc-util.js';
10705
- import {
10706
- APIIDFutures,
10707
- APIIDFuturesSign,
10708
- APIIDMain,
10709
- APIIDMainSign,
10710
- RestClientOptions,
10711
- serializeParams,
10712
- } from './lib/requestUtils.js';
10713
- import {
10714
- hashMessage,
10715
- SignAlgorithm,
10716
- SignEncodeMethod,
10717
- signMessage,
10718
- } from './lib/webCryptoAPI.js';
10719
- import {
10720
- getPromiseRefForWSAPIRequest,
10721
- isWSAPIWsKey,
10722
- WS_KEY_MAP,
10723
- WsKey,
10724
- WsTopicRequest,
10725
- } from './lib/websocket/websocket-util.js';
10726
- import { WSConnectedResult } from './lib/websocket/WsStore.types.js';
10727
- import { SpotClient } from './SpotClient.js';
10728
- import { APISuccessResponse } from './types/response/shared.types.js';
10729
- import { WsConnectionInfo } from './types/response/ws.js';
10730
- import {
10731
- Exact,
10732
- WSAPIAuthenticationRequestFromServer,
10733
- WsAPITopicRequestParamMap,
10734
- WsAPITopicResponseMap,
10735
- WsAPIWsKeyTopicMap,
10736
- WsOperation,
10737
- WsRequestOperation,
10738
- WsRequestOperationKucoin,
10739
- } from './types/websockets/ws-api.js';
10740
- import { MessageEventLike } from './types/websockets/ws-events.js';
10741
- import { WsMarket } from './types/websockets/ws-general.js';
10742
- ⋮----
10743
- function getRandomInt(max: number)
10744
- ⋮----
10745
- export interface WSAPIRequestFlags {
10746
- /** If true, will skip auth requirement for WS API connection */
10747
- authIsOptional?: boolean | undefined;
10748
- }
10749
- ⋮----
10750
- /** If true, will skip auth requirement for WS API connection */
10751
- ⋮----
10752
- /** Any WS keys in this list will trigger auth on connect, if credentials are available */
10753
- ⋮----
10754
- /** Any WS keys in this list will ALWAYS skip the authentication process, even if credentials are available */
10755
- ⋮----
10756
- /**
10757
- * WS topics are always a string for this exchange. Some exchanges use complex objects.
10758
- */
10759
- type WsTopic = string;
10760
- ⋮----
10761
- export class WebsocketClient extends BaseWebsocketClient<WsKey>
10762
- ⋮----
10763
- private getRESTClient(wsKey: WsKey): SpotClient | FuturesClient
10764
- ⋮----
10765
- const getClientType = (wsKey: WsKey): 'spot' | 'futures' | null =>
11003
+ private clearPingTimer(wsKey: TWSKey)
10766
11004
  ⋮----
10767
- private getRestClientOptions(): RestClientOptions
11005
+ // Expect a pong within a time limit
11006
+ private clearPongTimer(wsKey: TWSKey)
10768
11007
  ⋮----
10769
- private async getWSConnectionInfo(
10770
- wsKey: WsKey,
10771
- ): Promise<APISuccessResponse<WsConnectionInfo>>
11008
+ // this.logger.trace(`Cleared pong timeout for "${wsKey}"`);
10772
11009
  ⋮----
10773
- private async signMessage(
10774
- paramsStr: string,
10775
- secret: string,
10776
- method: SignEncodeMethod,
10777
- algorithm: SignAlgorithm,
10778
- ): Promise<string>
11010
+ // this.logger.trace(`No active pong timer for "${wsKey}"`);
10779
11011
  ⋮----
10780
11012
  /**
10781
- * Request connection of all dependent (public & private) websockets, instead of waiting for automatic connection by library
11013
+ * Simply builds and sends subscribe events for a list of topics for a ws key
11014
+ *
11015
+ * @private Use the `subscribe(topics)` or `subscribeTopicsForWsKey(topics, wsKey)` method to subscribe to topics. Send WS message to subscribe to topics.
10782
11016
  */
10783
- public connectAll(): Promise<(WSConnectedResult | undefined)[]>
11017
+ private async requestSubscribeTopics(
11018
+ wsKey: TWSKey,
11019
+ topics: WsTopicRequest<string>[],
11020
+ )
11021
+ ⋮----
11022
+ // Automatically splits requests into smaller batches, if needed
11023
+ ⋮----
11024
+ `Subscribing to ${topics.length} "${wsKey}" topics in ${subscribeWsMessages.length} batches.`, // Events: "${JSON.stringify(topics)}"
11025
+ ⋮----
11026
+ // this.logger.trace(`Sending batch via message: "${wsMessage}"`);
10784
11027
  ⋮----
10785
11028
  /**
10786
- * Request subscription to one or more topics. Pass topics as either an array of strings, or array of objects (if the topic has parameters).
10787
- * Objects should be formatted as {topic: string, params: object}.
10788
- *
10789
- * - Subscriptions are automatically routed to the correct websocket connection.
10790
- * - Authentication/connection is automatic.
10791
- * - Resubscribe after network issues is automatic.
11029
+ * Simply builds and sends unsubscribe events for a list of topics for a ws key
10792
11030
  *
10793
- * Call `unsubscribe(topics)` to remove topics
11031
+ * @private Use the `unsubscribe(topics)` method to unsubscribe from topics. Send WS message to unsubscribe from topics.
10794
11032
  */
10795
- public subscribe(
10796
- requests:
10797
- | (WsTopicRequest<WsTopic> | WsTopic)
10798
- | (WsTopicRequest<WsTopic> | WsTopic)[],
10799
- wsKey: WsKey,
11033
+ private async requestUnsubscribeTopics(
11034
+ wsKey: TWSKey,
11035
+ wsTopicRequests: WsTopicRequest<string>[],
10800
11036
  )
10801
11037
  ⋮----
10802
11038
  /**
10803
- * Unsubscribe from one or more topics. Similar to subscribe() but in reverse.
10804
- *
10805
- * - Requests are automatically routed to the correct websocket connection.
10806
- * - These topics will be removed from the topic cache, so they won't be subscribed to again.
11039
+ * Try sending a string event on a WS connection (identified by the WS Key)
10807
11040
  */
10808
- public unsubscribe(
10809
- requests:
10810
- | (WsTopicRequest<WsTopic> | WsTopic)
10811
- | (WsTopicRequest<WsTopic> | WsTopic)[],
10812
- wsKey: WsKey,
11041
+ public tryWsSend(
11042
+ wsKey: TWSKey,
11043
+ wsMessage: string,
11044
+ throwExceptions?: boolean,
10813
11045
  )
10814
11046
  ⋮----
10815
- async sendWSAPIRequest<
10816
- TWSKey extends keyof WsAPIWsKeyTopicMap,
10817
- TWSOperation extends WsAPIWsKeyTopicMap[TWSKey],
10818
- // if this throws a type error, probably forgot to add a new operation to WsAPITopicRequestParamMap
10819
- TWSParams extends Exact<WsAPITopicRequestParamMap[TWSOperation]>,
10820
- TWSAPIResponse extends
10821
- WsAPITopicResponseMap[TWSOperation] = WsAPITopicResponseMap[TWSOperation],
10822
- >(
11047
+ private async onWsOpen(
11048
+ event: WebSocket.Event,
10823
11049
  wsKey: TWSKey,
10824
- operation: TWSOperation,
10825
- params: TWSParams & { signRequest?: boolean },
10826
- requestFlags?: WSAPIRequestFlags,
10827
- ): Promise<TWSAPIResponse>
10828
- ⋮----
10829
- // if this throws a type error, probably forgot to add a new operation to WsAPITopicRequestParamMap
10830
- ⋮----
10831
- /**
10832
- * Base Info:
10833
- * - https://www.kucoin.com/docs-new/websocket-api/base-info/introduction
10834
- *
10835
- * Add/Cancel API info:
10836
- * - https://www.kucoin.com/docs-new/3470133w0
10837
- **/
10838
- ⋮----
10839
- // this.logger.trace(`sendWSAPIRequest(): assertIsConnected("${wsKey}")...`);
10840
- ⋮----
10841
- // this.logger.trace('sendWSAPIRequest(): assertIsConnected(${wsKey}) ok');
10842
- ⋮----
10843
- // Some commands don't require authentication.
10844
- ⋮----
10845
- // this.logger.trace(
10846
- // 'sendWSAPIRequest(): assertIsAuthenticated(${wsKey})...',
10847
- // );
11050
+ url: string,
11051
+ ws: WebSocket,
11052
+ )
10848
11053
  ⋮----
10849
- // this.logger.trace(
10850
- // 'sendWSAPIRequest(): assertIsAuthenticated(${wsKey}) ok',
10851
- // );
11054
+ // Resolve & cleanup deferred "connection attempt in progress" promise
10852
11055
  ⋮----
10853
- // Sign, if needed
11056
+ // Remove before continuing, in case there's more requests queued
10854
11057
  ⋮----
10855
- // Store deferred promise, resolved within the "resolveEmittableEvents" method while parsing incoming events
11058
+ /**
11059
+ * Called automatically once a connection is ready.
11060
+ * - Some exchanges are ready immediately after the connections open.
11061
+ * - Some exchanges send an event to confirm the connection is ready for us.
11062
+ *
11063
+ * This method is called to act when the connection is ready. Use `requireConnectionReadyConfirmation` to control how this is called.
11064
+ */
11065
+ private async onWsReadyForEvents(wsKey: TWSKey)
10856
11066
  ⋮----
10857
- // Enrich returned promise with request context for easier debugging
11067
+ // Resolve & cleanup deferred "connection attempt in progress" promise
10858
11068
  ⋮----
10859
- // throw e;
11069
+ // Remove before resolving, in case there's more requests queued
10860
11070
  ⋮----
10861
- // Send event.
11071
+ // Some websockets require an auth packet to be sent after opening the connection
10862
11072
  ⋮----
10863
- // Return deferred promise, so caller can await this call
11073
+ // Reconnect to topics known before it connected
10864
11074
  ⋮----
10865
- /**
10866
- *
10867
- * Internal methods
10868
- *
10869
- */
11075
+ // Request sub to public topics, if any
10870
11076
  ⋮----
10871
- private async signWSAPIRequest<TRequestParams extends string = string>(
10872
- requestEvent: WsRequestOperationKucoin<TRequestParams>,
10873
- ): Promise<WsRequestOperationKucoin<TRequestParams>>
11077
+ // Request sub to private topics, if auth on connect isn't needed
10874
11078
  ⋮----
10875
11079
  /**
10876
- * Whatever url this method returns, it's connected to as-is!
11080
+ * Handle subscription to private topics _after_ authentication successfully completes asynchronously.
10877
11081
  *
10878
- * If a token or anything else is needed in the URL, this is a good place to add it.
11082
+ * Only used for exchanges that require auth before sending private topic subscription requests
10879
11083
  */
10880
- protected async getWsUrl(wsKey: WsKey): Promise<string>
10881
- ⋮----
10882
- // These WS URLs are dynamically fetched via the REST API, as per API spec
10883
- ⋮----
10884
- // WS API URL works differently: https://www.kucoin.com/docs-new/3470133w0
10885
- // wss://wsapi.kucoin.com/v1/private?apikey=xxx&sign=xxx&passphrase=xxx&timestamp=xxx
11084
+ private onWsAuthenticated(
11085
+ wsKey: TWSKey,
11086
+ event: { isWSAPI?: boolean; WSAPIAuthChannel?: string },
11087
+ )
10886
11088
  ⋮----
10887
- // ws_url = f"{url}/v1/private?{url_path}&sign={sign_value}&passphrase={passphrase_sign}"
11089
+ // Resolve & cleanup deferred "auth attempt in progress" promise
10888
11090
  ⋮----
10889
- // original = f"{apikey}{timestamp}"
11091
+ // Remove before continuing, in case there's more requests queued
10890
11092
  ⋮----
10891
- // console.log('signParams: ', {
10892
- // paramsStr,
10893
- // partnerSignParam,
10894
- // queryString,
10895
- // finalUrl,
10896
- // });
11093
+ private onWsPing(
11094
+ event: any,
11095
+ wsKey: TWSKey,
11096
+ ws: WebSocket,
11097
+ source: WsEventInternalSrc,
11098
+ )
10897
11099
  ⋮----
10898
- protected sendPingEvent(wsKey: WsKey)
11100
+ private onWsPong(event: any, wsKey: TWSKey, source: WsEventInternalSrc)
10899
11101
  ⋮----
10900
- protected sendPongEvent(wsKey: WsKey)
11102
+ private onWsMessage(event: unknown, wsKey: TWSKey, ws: WebSocket)
10901
11103
  ⋮----
10902
- // Send a protocol layer pong
11104
+ // any message can clear the pong timer - wouldn't get a message if the ws wasn't working
10903
11105
  ⋮----
10904
- // Not really used for kucoin - they don't send pings
10905
- protected isWsPing(msg: any): boolean
11106
+ // console.log(`raw event: `, { data, dataType, emittableEvents });
10906
11107
  ⋮----
10907
- protected isWsPong(msg: any): boolean
11108
+ // Other event types are automatically emitted here
11109
+ // this.logger.trace(
11110
+ // `onWsMessage().emit(${emittable.eventType})`,
11111
+ // emittableFinalEvent,
11112
+ // );
10908
11113
  ⋮----
10909
- // this.logger.info(`Not a pong: `, msg);
11114
+ // this.logger.trace(
11115
+ // `onWsMessage().emit(${emittable.eventType}).done()`,
11116
+ // emittableFinalEvent,
11117
+ // );
10910
11118
  ⋮----
10911
- protected resolveEmittableEvents(
10912
- wsKey: WsKey,
10913
- event: MessageEventLike,
10914
- ): EmittableEvent[]
11119
+ private onWsClose(event: unknown, wsKey: TWSKey)
10915
11120
  ⋮----
10916
- // parsed: JSON.stringify(parsed, null, 2),
11121
+ // unintentional close, attempt recovery
10917
11122
  ⋮----
10918
- // These are request/reply pattern events (e.g. after subscribing to topics or authenticating)
11123
+ // clean up any pending promises for this connection
10919
11124
  ⋮----
10920
- // Request/reply pattern for authentication success
11125
+ // intentional close - clean up
11126
+ // clean up any pending promises for this connection
10921
11127
  ⋮----
10922
- // This is the counterpart to getPromiseRefForWSAPIRequest
11128
+ // This was an intentional close, delete all state for this connection, as if it never existed:
10923
11129
  ⋮----
10924
- // WS API Exception
11130
+ private getWs(wsKey: TWSKey)
10925
11131
  ⋮----
10926
- // WS API Success
11132
+ private setWsState(wsKey: TWSKey, state: WsConnectionStateEnum)
10927
11133
  ⋮----
10928
11134
  /**
10929
- * Determines if a topic is for a private channel, using a hardcoded list of strings
11135
+ * Promise-driven method to assert that a ws has successfully connected (will await until connection is open)
10930
11136
  */
10931
- protected isPrivateTopicRequest(
10932
- request: WsTopicRequest<string>,
10933
- wsKey: WsKey,
10934
- ): boolean
11137
+ protected async assertIsConnected(wsKey: TWSKey): Promise<unknown>
10935
11138
  ⋮----
10936
- protected getWsKeyForMarket(market: WsMarket, isPrivate: boolean): WsKey
11139
+ // Already in progress? Await shared promise and retry
10937
11140
  ⋮----
10938
- protected getWsMarketForWsKey(key: WsKey): WsMarket
11141
+ // this.logger.trace('assertIsConnected(): awaiting...');
10939
11142
  ⋮----
10940
- protected getPrivateWSKeys(): WsKey[]
11143
+ // this.logger.trace('assertIsConnected(): awaiting...connected!');
10941
11144
  ⋮----
10942
- /** Force subscription requests to be sent in smaller batches, if a number is returned */
10943
- protected getMaxTopicsPerSubscribeEvent(wsKey: WsKey): number | null
11145
+ // Start connection, it should automatically store/return a promise.
11146
+ // this.logger.trace('assertIsConnected(): connecting...');
10944
11147
  ⋮----
10945
- // Return a number if there's a limit on the number of sub topics per rq
10946
- // Always 1 at a time for this exchange
11148
+ // this.logger.trace('assertIsConnected(): connecting...newly connected!');
10947
11149
  ⋮----
10948
11150
  /**
10949
- * Map one or more topics into fully prepared "subscribe request" events (already stringified and ready to send)
11151
+ * Promise-driven method to assert that a ws has been successfully authenticated (will await until auth is confirmed)
10950
11152
  */
10951
- protected async getWsOperationEventsForTopics(
10952
- topicRequests: WsTopicRequest<string>[],
10953
- wsKey: WsKey,
10954
- operation: WsOperation,
10955
- ): Promise<string[]>
11153
+ public async assertIsAuthenticated(wsKey: TWSKey): Promise<unknown>
10956
11154
  ⋮----
10957
- // Operations structured in a way that this exchange understands
11155
+ // this.logger.trace('assertIsAuthenticated(): connecting...');
10958
11156
  ⋮----
10959
- // Events that are ready to send (usually stringified JSON)
11157
+ // Already in progress? Await shared promise and retry
10960
11158
  ⋮----
10961
- protected async getWsAuthRequestEvent(
10962
- wsKey: WsKey,
10963
- eventToAuth?: WSAPIAuthenticationRequestFromServer,
10964
- ): Promise<object | string | 'waitForEvent' | void>
11159
+ // this.logger.trace('assertIsAuthenticated(): awaiting...');
10965
11160
  ⋮----
10966
- // Send anything for WS API
11161
+ // this.logger.trace('assertIsAuthenticated(): authenticated!');
10967
11162
  ⋮----
10968
- // Don't send anything, don't resolve auth promise. Wait for auth handshake from server
11163
+ // this.logger.trace('assertIsAuthenticated(): ok');
10969
11164
  ⋮----
10970
- // Don't send anything for all other WS connections, since they auth as part of the connection (not after connect). Returning an empty value here will short-circuit the assertIsAuthenticated workflow.
11165
+ // Start authentication, it should automatically store/return a promise.
11166
+ // this.logger.trace('assertIsAuthenticated(): authenticating...');
11167
+ ⋮----
11168
+ // this.logger.trace('assertIsAuthenticated(): newly authenticated!');
10971
11169
 
10972
11170
  ================
10973
11171
  File: src/SpotClient.ts
@@ -11042,6 +11240,7 @@ import {
11042
11240
  getHFMarginFillsRequest,
11043
11241
  GetLendingRedemptionOrdersV3Request,
11044
11242
  GetLendingSubscriptionOrdersV3Request,
11243
+ GetMarginCollateralRatioRequest,
11045
11244
  GetMarginOcoOrderByClientOidRequest,
11046
11245
  GetMarginOcoOrderDetailByOrderIdRequest,
11047
11246
  GetMarginStopOrderByClientOidRequest,
@@ -11087,10 +11286,12 @@ import {
11087
11286
  import {
11088
11287
  Account,
11089
11288
  AccountHFMarginTransactions,
11289
+ ApiKeyInfo,
11090
11290
  Balances,
11091
11291
  CreateSubAccount,
11092
11292
  CreateSubAPI,
11093
11293
  DeleteSubAccountAPI,
11294
+ KYCRegion,
11094
11295
  SpotAccountSummary,
11095
11296
  SpotAccountTransaction,
11096
11297
  SpotAccountTransactions,
@@ -11156,6 +11357,7 @@ import {
11156
11357
  LendingRedemption,
11157
11358
  MarginActivePairsV3,
11158
11359
  MarginBorrowHistoryV3,
11360
+ MarginCollateralRatioData,
11159
11361
  MarginConfigInfo,
11160
11362
  MarginInterestRecords,
11161
11363
  MarginLevTokenInfo,
@@ -11268,24 +11470,20 @@ getServiceStatus(): Promise<APISuccessResponse<ServiceStatus>>
11268
11470
  */
11269
11471
  getAccountSummary(): Promise<APISuccessResponse<SpotAccountSummary>>
11270
11472
  ⋮----
11473
+ /**
11474
+ * Get KYC Regions
11475
+ *
11476
+ * This endpoint can be used to obtain this user's KYC regions.
11477
+ */
11478
+ getKYCRegions(): Promise<APISuccessResponse<KYCRegion[]>>
11479
+ ⋮----
11271
11480
  /**
11272
11481
  * Get API Key Information
11273
11482
  *
11274
11483
  * Get information about the API key being used. Works for both master and sub user API keys.
11484
+ * Includes KYC region, status, expiration date, and third-party app information.
11275
11485
  */
11276
- getApikeyInfo(): Promise<
11277
- APISuccessResponse<{
11278
- remark: string;
11279
- apiKey: string;
11280
- apiVersion: number;
11281
- permission: string;
11282
- ipWhitelist: string;
11283
- createdAt: number;
11284
- uid: number;
11285
- isMaster: boolean;
11286
- }>
11287
- > {
11288
- return this.getPrivate('api/v1/user/api-key');
11486
+ getApikeyInfo(): Promise<APISuccessResponse<ApiKeyInfo>>
11289
11487
  ⋮----
11290
11488
  /**
11291
11489
  * Get Account Type - Spot
@@ -12291,6 +12489,15 @@ getIsolatedMarginSymbolsConfig(): Promise<
12291
12489
  > {
12292
12490
  return this.getPrivate('api/v1/isolated/symbols');
12293
12491
  ⋮----
12492
+ /**
12493
+ * Get Margin Collateral Ratio
12494
+ *
12495
+ * Request the margin collateral ratio. If currencyList is not specified, all currencies will be returned.
12496
+ */
12497
+ getMarginCollateralRatio(
12498
+ params?: GetMarginCollateralRatioRequest,
12499
+ ): Promise<APISuccessResponse<MarginCollateralRatioData[]>>
12500
+ ⋮----
12294
12501
  /**
12295
12502
  *
12296
12503
  * REST - MARGIN TRADING - Orders
@@ -13358,7 +13565,7 @@ File: package.json
13358
13565
  ================
13359
13566
  {
13360
13567
  "name": "kucoin-api",
13361
- "version": "2.3.0",
13568
+ "version": "2.3.2",
13362
13569
  "description": "Complete & robust Node.js SDK for Kucoin's REST APIs and WebSockets, with TypeScript & strong end to end tests.",
13363
13570
  "scripts": {
13364
13571
  "clean": "rm -rf dist",