Merge pull request #223 from tiagosiebler/accountav3

v3.4.0: feat(#219) add support for account asset v3 REST endpoints
This commit is contained in:
Tiago
2023-02-14 10:58:21 +00:00
committed by GitHub
12 changed files with 872 additions and 50 deletions

View File

@@ -1,4 +1,5 @@
# Node.js & Typescript Bybit API SDK
[![Tests](https://circleci.com/gh/tiagosiebler/bybit-api.svg?style=shield)](https://circleci.com/gh/tiagosiebler/bybit-api)
[![npm version](https://img.shields.io/npm/v/bybit-api)][1] [![npm size](https://img.shields.io/bundlephobia/min/bybit-api/latest)][1] [![npm downloads](https://img.shields.io/npm/dt/bybit-api)][1]
[![last commit](https://img.shields.io/github/last-commit/tiagosiebler/bybit-api)][1]
@@ -8,7 +9,8 @@
[1]: https://www.npmjs.com/package/bybit-api
Node.js connector for the Bybit APIs and WebSockets:
Node.js SDK for the Bybit APIs and WebSockets:
- Complete integration with all Bybit APIs.
- TypeScript support (with type declarations for most API requests & responses).
- Over 300 end-to-end tests making real API calls & WebSocket connections, validating any changes before they reach npm.
@@ -16,14 +18,18 @@ Node.js connector for the Bybit APIs and WebSockets:
- Browser support (via webpack bundle - see "Browser Usage" below).
## Installation
`npm install --save bybit-api`
## Issues & Discussion
- Issues? Check the [issues tab](https://github.com/tiagosiebler/bybit-api/issues).
- Discuss & collaborate with other node devs? Join our [Node.js Algo Traders](https://t.me/nodetraders) engineering community on telegram.
## Related projects
Check out my related projects:
- Try my connectors:
- [binance](https://www.npmjs.com/package/binance)
- [bybit-api](https://www.npmjs.com/package/bybit-api)
@@ -36,10 +42,13 @@ Check out my related projects:
- [awesome-crypto-examples](https://github.com/tiagosiebler/awesome-crypto-examples)
## Documentation
Most methods accept JS objects. These can be populated using parameters specified by Bybit's API documentation, or check the type definition in each class within this repository (see table below for convenient links to each class).
- [Bybit API Docs (choose API category from the tabs at the top)](https://bybit-exchange.github.io/docs/futuresV2/inverse/#t-introduction).
## Structure
This connector is fully compatible with both TypeScript and pure JavaScript projects, while the connector is written in TypeScript. A pure JavaScript version can be built using `npm run build`, which is also the version published to [npm](https://www.npmjs.com/package/bybit-api).
The version on npm is the output from the `build` command and can be used in projects without TypeScript (although TypeScript is definitely recommended).
@@ -50,36 +59,44 @@ The version on npm is the output from the `build` command and can be used in pro
- [examples](./examples) - some implementation examples & demonstrations. Contributions are welcome!
---
## REST API Clients
Each REST API group has a dedicated REST client. To avoid confusion, here are the available REST clients and the corresponding API groups:
| Class | Description |
|:------------------------------------------------------------------: |:----------------------------------------------------------------------------------------------------------------------------: |
| [ **V5 API** ] | The new unified V5 APIs (successor to previously fragmented APIs for all API groups). To learn more about the V5 API, please read the [V5 upgrade guideline](https://bybit-exchange.github.io/docs/v5/upgrade-guide). |
| [RestClientV5](src/rest-client-v5.ts) | Coming soon... Unified V5 all-in-one REST client for all [V5 REST APIs](https://bybit-exchange.github.io/docs/v5/intro) |
| [ **Derivatives v3** ] | The Derivatives v3 APIs (successor to the Futures V2 APIs) |
| [UnifiedMarginClient](src/unified-margin-client.ts) | [Derivatives (v3) Unified Margin APIs](https://bybit-exchange.github.io/docs/derivativesV3/unified_margin/#t-introduction) |
| [ContractClient](src/contract-client.ts) | [Derivatives (v3) Contract APIs](https://bybit-exchange.github.io/docs/derivativesV3/contract). |
| [UnifiedMarginClient](src/unified-margin-client.ts) | [Derivatives (v3) Unified Margin APIs](https://bybit-exchange.github.io/docs/derivatives/unified/place-order) |
| [ContractClient](src/contract-client.ts) | [Derivatives (v3) Contract APIs](https://bybit-exchange.github.io/docs/derivatives/contract/place-order). |
| [ **Futures v2** ] | The Futures v2 APIs |
| [InverseClient](src/inverse-client.ts) | [Inverse Perpetual Futures (v2) APIs](https://bybit-exchange.github.io/docs/futuresV2/inverse/) |
| [LinearClient](src/linear-client.ts) | [USDT Perpetual Futures (v2) APIs](https://bybit-exchange.github.io/docs/futuresV2/linear/#t-introduction) |
| [InverseFuturesClient](src/inverse-futures-client.ts) | [Inverse Futures (v2) APIs](https://bybit-exchange.github.io/docs/futuresV2/inverse_futures/#t-introduction) |
| [ **Spot** ] | The spot APIs |
| [SpotClientV3](src/spot-client-v3.ts) | [Spot Market (v3) APIs](https://bybit-exchange.github.io/docs/spot/v3/#t-introduction) |
| [SpotClientV3](src/spot-client-v3.ts) | [Spot Market (v3) APIs](https://bybit-exchange.github.io/docs/spot/public/instrument) |
| [~SpotClient~](src/spot-client.ts) (deprecated, SpotClientV3 recommended)| [Spot Market (v1) APIs](https://bybit-exchange.github.io/docs/spot/v1/#t-introduction) |
| [ **USDC Contract** ] | The USDC Contract APIs |
| [USDCPerpetualClient](src/usdc-perpetual-client.ts) | [USDC Perpetual APIs](https://bybit-exchange.github.io/docs/usdc/option/?console#t-querydeliverylog) |
| [USDCOptionClient](src/usdc-option-client.ts) | [USDC Option APIs](https://bybit-exchange.github.io/docs/usdc/option/#t-introduction) |
| [ **Other** ] | Other standalone API groups |
| [AccountAssetClient](src/account-asset-client.ts) | [Account Asset APIs](https://bybit-exchange.github.io/docs/account_asset/#t-introduction) |
| [CopyTradingClient](src/copy-trading-client.ts) | [Copy Trading APIs](https://bybit-exchange.github.io/docs/copy_trading/#t-introduction) |
| [CopyTradingClient](src/copy-trading-client.ts) | [Copy Trading APIs](https://bybit-exchange.github.io/docs/category/copy-trade) |
| [AccountAssetClientV3](src/account-asset-client-v3.ts) | [Account Asset V3 APIs](https://bybit-exchange.github.io/docs/account-asset/internal-transfer) |
| [~AccountAssetClient~](src/account-asset-client.ts) (deprecated, AccountAssetClientV3 recommended) | [Account Asset V1 APIs](https://bybit-exchange.github.io/docs/account_asset/v1/#t-introduction) |
| [WebsocketClient](src/websocket-client.ts) | All WebSocket Events (Public & Private for all API categories) |
Examples for using each client can be found in:
- the [examples](./examples) folder.
- the [awesome-crypto-examples](https://github.com/tiagosiebler/awesome-crypto-examples) repository.
If you're missing an example, you're welcome to request one. Priority will be given to [github sponsors](https://github.com/sponsors/tiagosiebler).
### Usage
Create API credentials on Bybit's website:
- [Livenet](https://bybit.com/app/user/api-management?affiliate_id=9410&language=en-US&group_id=0&group_type=1)
- [Testnet](https://testnet.bybit.com/app/user/api-management)
@@ -166,6 +183,7 @@ client.getOrderBook({ symbol: 'BTCUSD' })
```
## WebSockets
All API groups can be used via a shared `WebsocketClient`. However, to listen to multiple API groups at once, you will need to make one WebsocketClient instance per API group.
The WebsocketClient can be configured to a specific API group using the market parameter. These are the currently available API groups:
@@ -240,7 +258,7 @@ ws.subscribe(['position', 'execution', 'trade']);
ws.subscribe('kline.BTCUSD.1m');
// Listen to events coming from websockets. This is the primary data source
ws.on('update', data => {
ws.on('update', (data) => {
console.log('update', data);
});
@@ -250,7 +268,7 @@ ws.on('open', ({ wsKey, event }) => {
});
// Optional: Listen to responses to websocket queries (e.g. the response after subscribing to a topic)
ws.on('response', response => {
ws.on('response', (response) => {
console.log('response', response);
});
@@ -260,7 +278,7 @@ ws.on('close', () => {
});
// Optional: Listen to raw error events. Recommended.
ws.on('error', err => {
ws.on('error', (err) => {
console.error('error', err);
});
```
@@ -270,6 +288,7 @@ See [websocket-client.ts](./src/websocket-client.ts) for further information.
---
## Customise Logging
Pass a custom logger which supports the log methods `silly`, `debug`, `notice`, `info`, `warning` and `error`, or override methods from the default logger as desired.
```javascript
@@ -281,14 +300,13 @@ const customLogger = {
silly: () => {},
};
const ws = new WebsocketClient(
{ key: 'xxx', secret: 'yyy' },
customLogger
);
const ws = new WebsocketClient({ key: 'xxx', secret: 'yyy' }, customLogger);
```
## Browser Usage
Build a bundle using webpack:
- `npm install`
- `npm build`
- `npm pack`
@@ -300,23 +318,31 @@ However, note that browser usage will lead to CORS errors due Bybit. See [issue
---
## Contributions & Thanks
### Donations
#### tiagosiebler
If you found this project interesting or useful, create accounts with my referral links:
- [Bybit](https://www.bybit.com/en-US/register?affiliate_id=9410&language=en-US&group_id=0&group_type=1)
- [Binance](https://www.binance.com/en/register?ref=20983262)
Or buy me a coffee using any of these:
- BTC: `1C6GWZL1XW3jrjpPTS863XtZiXL1aTK7Jk`
- ETH (ERC20): `0xd773d8e6a50758e1ada699bb6c4f98bb4abf82da`
#### pixtron
An early generation of this library was started by @pixtron. If this library helps you to trade better on bybit, feel free to donate a coffee to @pixtron:
- BTC `1Fh1158pXXudfM6ZrPJJMR7Y5SgZUz4EdF`
- ETH `0x21aEdeC53ab7593b77C9558942f0c9E78131e8d7`
- LTC `LNdHSVtG6UWsriMYLJR3qLdfVNKwJ6GSLF`
### Contributions & Pull Requests
Contributions are encouraged, I will review any incoming pull requests. See the issues tab for todo items.
## Star History

4
package-lock.json generated
View File

@@ -1,12 +1,12 @@
{
"name": "bybit-api",
"version": "3.3.8",
"version": "3.4.0",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "bybit-api",
"version": "3.3.8",
"version": "3.4.0",
"license": "MIT",
"dependencies": {
"axios": "^0.21.0",

View File

@@ -1,6 +1,6 @@
{
"name": "bybit-api",
"version": "3.3.10",
"version": "3.4.0",
"description": "Complete & robust node.js SDK for Bybit's REST APIs and WebSockets, with TypeScript & integration tests.",
"main": "lib/index.js",
"types": "lib/index.d.ts",

View File

@@ -0,0 +1,309 @@
import {
AccountCoinBalanceResponseV3,
AccountCoinBalancesRequestV3,
AccountCoinBalancesResponseV3,
APIKeyInfoV3,
APIResponseV3WithTime,
APIResponseWithTime,
AssetInfoRequestV3,
AssetInfoResponseV3,
CoinInfoQueryResponseV3,
CreateSubAPIKeyRequestV3,
CreateSubAPIKeyResponseV3,
CreateSubMemberRequestV3,
CreateSubMemberResponseV3,
DepositAddressResponseV3,
DepositRecordQueryRequestV3,
DepositRecordQueryResponseV3,
InternalTransferRequestV3,
ModifyAPIKeyRequestV3,
QueryDepositAddressRequestV3,
QueryInternalTransfersRequestV3,
QueryInternalTransferSResponseV3,
QuerySubAccountDepositAddressRequestV3,
SingleAccountCoinBalanceRequestV3,
SubAccountTransferRequestV3,
SubAccountTransferResponseV3,
SubDepositRecordQueryRequestV3,
SubMemberResponseV3,
SupportedDepositListRequestV3,
SupportedDepositListResponseV3,
TransferCoinListRequestV3,
UniversalTransferCreateResponse,
UniversalTransferListRequestV3,
UniversalTransferListResponseV3,
UniversalTransferRequestV3,
WithdrawCreateRequestV3,
WithdrawRecordQueryRequestV3,
WithdrawRecordsQueryResponseV3,
} from './types';
import { REST_CLIENT_TYPE_ENUM } from './util';
import BaseRestClient from './util/BaseRestClient';
/**
* REST API client for Account Asset V3 APIs
*/
export class AccountAssetClientV3 extends BaseRestClient {
getClientType() {
return REST_CLIENT_TYPE_ENUM.v3;
}
async fetchServerTime(): Promise<number> {
const res = await this.getServerTime();
return Number(res.time);
}
getServerTime(): Promise<
APIResponseV3WithTime<{ timeSecond: string; timeNano: string }>
> {
return this.get('/v3/public/time');
}
/**
*
* Transfer Data Endpoints
*
*/
createInternalTransfer(
params: InternalTransferRequestV3
): Promise<APIResponseWithTime<{ transferId: string }>> {
return this.postPrivate(
'/asset/v3/private/transfer/inter-transfer',
params
);
}
getInternalTransfers(
params: QueryInternalTransfersRequestV3
): Promise<APIResponseWithTime<QueryInternalTransferSResponseV3>> {
return this.getPrivate(
'/asset/v3/private/transfer/inter-transfer/list/query',
params
);
}
createSubAccountTransfer(params: {
transferId: string;
coin: string;
amount: string;
subMemberId: number;
type: 'IN' | 'OUT';
}): Promise<APIResponseWithTime<{ transferId: string }>> {
return this.postPrivate(
'/asset/v3/private/transfer/sub-member-transfer',
params
);
}
getSubAccountTransfers(
params?: SubAccountTransferRequestV3
): Promise<APIResponseWithTime<SubAccountTransferResponseV3>> {
return this.getPrivate(
'/asset/v3/private/transfer/sub-member-transfer/list/query',
params
);
}
getSubAccounts(): Promise<
APIResponseWithTime<{
subMemberIds: string[];
transferableSubMemberIds: string[];
}>
> {
return this.getPrivate('/asset/v3/private/transfer/sub-member/list/query');
}
enableUniversalTransfer(params?: {
subMemberIds?: string;
}): Promise<APIResponseWithTime<any>> {
return this.postPrivate(
'/asset/v3/private/transfer/transfer-sub-member-save',
params
);
}
createUniversalTransfer(
params: UniversalTransferRequestV3
): Promise<APIResponseWithTime<UniversalTransferCreateResponse>> {
return this.postPrivate(
'/asset/v3/private/transfer/universal-transfer',
params
);
}
getUniversalTransfers(
params: UniversalTransferListRequestV3
): Promise<APIResponseWithTime<UniversalTransferListResponseV3>> {
return this.getPrivate(
'/asset/v3/private/transfer/universal-transfer/list/query',
params
);
}
getTransferableCoinList(
params: TransferCoinListRequestV3
): Promise<APIResponseWithTime<{ list: string[] }>> {
return this.getPrivate(
'/asset/v3/private/transfer/transfer-coin/list/query',
params
);
}
getAccountCoinBalance(
params: SingleAccountCoinBalanceRequestV3
): Promise<APIResponseWithTime<AccountCoinBalanceResponseV3>> {
return this.getPrivate(
'/asset/v3/private/transfer/account-coin/balance/query',
params
);
}
getAccountCoinBalances(
params: AccountCoinBalancesRequestV3
): Promise<APIResponseWithTime<AccountCoinBalancesResponseV3>> {
return this.getPrivate(
'/asset/v3/private/transfer/account-coins/balance/query',
params
);
}
getAssetInfo(
params?: AssetInfoRequestV3
): Promise<APIResponseWithTime<AssetInfoResponseV3>> {
return this.getPrivate(
'/asset/v3/private/transfer/asset-info/query',
params
);
}
/**
*
* Wallet & Deposit Endpoints
*
*/
/** Get Deposit Spec */
getSupportedDepositList(
params?: SupportedDepositListRequestV3
): Promise<APIResponseWithTime<SupportedDepositListResponseV3>> {
return this.get(
'/asset/v3/public/deposit/allowed-deposit-list/query',
params
);
}
getDepositRecords(
params?: DepositRecordQueryRequestV3
): Promise<APIResponseWithTime<DepositRecordQueryResponseV3>> {
return this.getPrivate('/asset/v3/private/deposit/record/query', params);
}
getSubDepositRecords(
params: SubDepositRecordQueryRequestV3
): Promise<APIResponseWithTime<DepositRecordQueryResponseV3>> {
return this.getPrivate(
'/asset/v3/private/deposit/sub-member-record/query',
params
);
}
getWithdrawRecords(
params?: WithdrawRecordQueryRequestV3
): Promise<APIResponseWithTime<WithdrawRecordsQueryResponseV3>> {
return this.getPrivate('/asset/v3/private/withdraw/record/query', params);
}
getCoinInformation(
coin?: string
): Promise<APIResponseWithTime<CoinInfoQueryResponseV3>> {
return this.getPrivate('/asset/v3/private/coin-info/query', { coin });
}
submitWithdrawal(
params: WithdrawCreateRequestV3
): Promise<APIResponseWithTime<{ id: string }>> {
return this.postPrivate('/asset/v3/private/withdraw/create', params);
}
cancelWithdrawal(
withdrawalId: number
): Promise<APIResponseWithTime<{ status: 1 | 0 }>> {
return this.postPrivate('/asset/v3/private/withdraw/create', {
withdrawalId,
});
}
getMasterAccountDepositAddress(
params?: QueryDepositAddressRequestV3
): Promise<APIResponseWithTime<DepositAddressResponseV3>> {
return this.getPrivate('/asset/v3/private/deposit/address/query', params);
}
getSubAccountDepositAddress(
params: QuerySubAccountDepositAddressRequestV3
): Promise<APIResponseWithTime<DepositAddressResponseV3>> {
return this.getPrivate(
'/asset/v3/private/deposit/sub-member-address/query',
params
);
}
createSubMember(
params: CreateSubMemberRequestV3
): Promise<APIResponseWithTime<CreateSubMemberResponseV3>> {
return this.postPrivate('/user/v3/private/create-sub-member', params);
}
createSubAPIKey(
params: CreateSubAPIKeyRequestV3
): Promise<APIResponseWithTime<CreateSubAPIKeyResponseV3>> {
return this.postPrivate('/user/v3/private/create-sub-api', params);
}
/**
* Get Sub UID List
*/
getSubMembers(): Promise<APIResponseWithTime<SubMemberResponseV3>> {
return this.postPrivate('/user/v3/private/query-sub-members');
}
/**
* Froze Sub UID
*/
freezeSubMember(
subuid: number,
frozenStatus: 0 | 1
): Promise<APIResponseWithTime<{}>> {
return this.postPrivate('/user/v3/private/frozen-sub-member', {
subuid,
frozen: frozenStatus,
});
}
getAPIKeyInformation(): Promise<APIResponseWithTime<APIKeyInfoV3>> {
return this.getPrivate('/user/v3/private/query-api');
}
modifyMasterAPIKey(
params: ModifyAPIKeyRequestV3
): Promise<APIResponseWithTime<APIKeyInfoV3>> {
return this.postPrivate('/user/v3/private/update-api', params);
}
modifySubAPIKey(
params: ModifyAPIKeyRequestV3
): Promise<APIResponseWithTime<APIKeyInfoV3>> {
return this.postPrivate('/user/v3/private/update-sub-api', params);
}
/** WARNING: BE CAREFUL! The API key used to call this interface will be invalid immediately. */
deleteMasterAPIKey(): Promise<APIResponseWithTime<{}>> {
return this.postPrivate('/user/v3/private/delete-api');
}
/** WARNING: BE CAREFUL! The API key used to call this interface will be invalid immediately. */
deleteSubAPIKey(): Promise<APIResponseWithTime<{}>> {
return this.postPrivate('/user/v3/private/delete-sub-api');
}
}

View File

@@ -1,4 +1,5 @@
export * from './account-asset-client';
export * from './account-asset-client-v3';
export * from './copy-trading-client';
export * from './inverse-client';
export * from './inverse-futures-client';

View File

@@ -19,6 +19,24 @@ export interface InternalTransferRequest {
to_account_type: TransferAccountType;
}
export interface InternalTransferRequestV3 {
transferId: string;
coin: string;
amount: string;
fromAccountType: string;
toAccountType: string;
}
export interface QueryInternalTransfersRequestV3 {
transferId?: string;
coin: string;
status?: string;
startTime?: number;
endTime?: number;
limit?: number;
cursor?: string;
}
export interface SubAccountTransferRequest {
transfer_id: string;
coin: string;
@@ -27,6 +45,16 @@ export interface SubAccountTransferRequest {
type: TransferType;
}
export interface SubAccountTransferRequestV3 {
transferId?: string;
coin?: string;
status?: string;
startTime?: number;
endTime?: number;
limit?: number;
cursor?: string;
}
export interface TransferQueryRequest {
transfer_id?: string;
coin?: string;
@@ -52,7 +80,6 @@ export interface UniversalTransferRequest {
from_account_type: TransferAccountType;
to_account_type: TransferAccountType;
}
export interface SupportedDepositListRequest {
coin?: string;
chain?: string;
@@ -92,3 +119,140 @@ export interface WithdrawalRequest {
chain: string;
tag?: string;
}
export interface UniversalTransferRequestV3 {
transferId: string;
coin: string;
amount: string;
fromMemberId: string;
toMemberId: string;
fromAccountType: TransferAccountType;
toAccountType: TransferAccountType;
}
export interface UniversalTransferListRequestV3 {
transferId?: string;
coin: string;
status?: string;
startTime?: number;
endTime?: number;
limit?: number;
cursor?: string;
}
export interface TransferCoinListRequestV3 {
fromAccountType: TransferAccountType;
toAccountType: TransferAccountType;
}
export interface SingleAccountCoinBalanceRequestV3 {
memberId?: string;
accountType: TransferAccountType;
coin: string;
withBonus?: '0' | '1';
}
export interface AccountCoinBalancesRequestV3 {
memberId?: string;
accountType: TransferAccountType;
coin?: string;
withBonus?: '0' | '1';
}
export interface AssetInfoRequestV3 {
accountType?: TransferAccountType;
coin?: string;
}
export interface SupportedDepositListRequestV3 {
coin?: string;
chain?: string;
cursor?: string;
limit?: number;
}
export interface DepositRecordQueryRequestV3 {
startTime?: number;
endTime?: number;
coin?: string;
cursor?: string;
limit?: number;
}
export interface SubDepositRecordQueryRequestV3 {
subMemberId: number;
startTime?: number;
endTime?: number;
coin?: string;
cursor?: string;
limit?: number;
}
export interface WithdrawRecordQueryRequestV3 {
withdrawID?: number;
startTime?: number;
endTime?: number;
coin?: string;
withdrawType?: string;
cursor?: string;
limit?: number;
}
export interface WithdrawCreateRequestV3 {
coin: string;
chain: string;
address: string;
tag?: string;
amount: string;
timestamp: number;
forceChain?: 0 | 1;
}
export interface QueryDepositAddressRequestV3 {
coin?: string;
chainType?: string;
}
export interface QuerySubAccountDepositAddressRequestV3 {
coin?: string;
chainType?: string;
subMemberId: string;
}
export interface CreateSubMemberRequestV3 {
username: string;
memberType: 1 | 6;
switch?: 0 | 1;
note?: string;
}
export interface CreateSubAPIKeyRequestV3 {
subuid: string;
note?: string;
readOnly: 0 | 1;
ips?: string[];
permissions: {
ContractTrade?: [];
Spot?: string[];
Wallet?: string[];
Options?: string[];
Derivatives?: string[];
Exchange?: string[];
};
}
export interface ModifyAPIKeyRequestV3 {
readOnly: number;
ips?: string[];
permissions: {
ContractTrade?: string[];
Spot?: string[];
Wallet?: string[];
Options?: string[];
Derivatives?: string[];
CopyTrading?: string[];
BlockTrade?: string[];
Exchange?: string[];
NFT?: string[];
};
}

View File

@@ -0,0 +1,236 @@
export interface UniversalTransferCreateResponse {
transferId: string;
}
export interface UniversalTransferListResponseV3 {
list: {
transferId: string;
coin: string;
amount: string;
timestamp: string;
status: string;
fromAccountType: string;
toAccountType: string;
fromMemberId: string;
toMemberId: string;
}[];
nextPageCursor: string;
}
export interface QueryInternalTransferSResponseV3 {
list: {
transferId: string;
coin: string;
amount: string;
fromAccountType: string;
toAccountType: string;
timestamp: string;
status: string;
}[];
nextPageCursor: string;
}
export interface SubAccountTransferResponseV3 {
list: {
transferId: string;
coin: string;
amount: string;
memberId: number;
subMemberId: number;
timestamp: string;
status: string;
type: 'IN' | 'OUT';
}[];
nextPageCursor: string;
}
export interface AccountCoinBalanceResponseV3 {
accountType: string;
bizType: number;
accountId: string;
memberId: string;
balance: {
coin: string;
walletBalance: string;
transferBalance: string;
bonus: string;
};
}
export interface AccountCoinBalancesResponseV3 {
accountType: string;
memberId: string;
balance: {
coin: string;
walletBalance: string;
transferBalance: string;
bonus: string;
}[];
}
export interface AssetInfoResponseV3 {
spot: {
status: 'ACCOUNT_STATUS_NORMAL' | 'ACCOUNT_STATUS_UNSPECIFIED';
assets: {
coin: string;
frozen: string;
free: string;
withdraw: string;
}[];
};
}
interface SupportedDepositV3 {
coin: string;
chain: string;
coinShowName: string;
chainType: string;
blockConfirmNumber: number;
minDepositAmount: string;
}
export interface SupportedDepositListResponseV3 {
configList: SupportedDepositV3[];
nextPageCursor: string;
}
interface DepositRecordV3 {
coin: string;
chain: string;
amount: string;
txID: string;
status: number;
toAddress: string;
tag: string;
depositFee: string;
successAt: string;
confirmations: string;
txIndex: string;
blockHash: string;
}
export interface DepositRecordQueryResponseV3 {
rows: DepositRecordV3[];
nextPageCursor: string;
}
export interface WithdrawRecordsQueryResponseV3 {
rows: {
coin: string;
chain: string;
amount: string;
txID: string;
status: number;
toAddress: string;
tag: string;
withdrawFee: string;
createTime: string;
updateTime: string;
withdrawId: string;
withdrawType: number;
}[];
nextPageCursor: string;
}
export interface CoinInfoV3 {
name: string;
coin: string;
remainAmount: string;
chains: {
chainType: string;
confirmation: string;
withdrawFee: string;
depositMin: string;
withdrawMin: string;
chain: string;
chainDeposit: string;
chainWithdraw: string;
minAccuracy: string;
}[];
}
export interface CoinInfoQueryResponseV3 {
rows: CoinInfoV3[];
}
export interface DepositAddressChainV3 {
chainType: string;
addressDeposit: string;
tagDeposit: string;
chain: string;
}
export interface DepositAddressResponseV3 {
coin: string;
chains: DepositAddressChainV3[];
}
export interface CreateSubMemberResponseV3 {
uid: number;
username: string;
memberType: 1 | 6;
switch: 0 | 1;
note: string;
}
export interface CreateSubAPIKeyResponseV3 {
id: string;
note: string;
apiKey: string;
readOnly: string;
secret: string;
permissions: {
ContractTrade: string[];
Spot: string[];
Wallet: string[];
Options: string[];
Derivatives: string[];
CopyTrading: string[];
BlockTrade: string[];
Exchange: string[];
NFT: string[];
};
}
export interface SubMemberV3 {
uid: string;
username: string;
memberType: 1 | 6;
status: 1 | 2 | 4;
remark: string;
}
export interface SubMemberResponseV3 {
subMembers: SubMemberV3[];
}
export interface APIKeyInfoV3 {
id: string;
note: string;
apiKey: string;
readOnly: string;
secret: string;
permissions: {
ContractTrade: string[];
Spot: string[];
Wallet: string[];
Options: string[];
Derivatives: string[];
CopyTrading: string[];
BlockTrade: string[];
Exchange: string[];
NFT: string[];
};
ips: string[];
type: number;
deadlineDay: number;
expiredAt: string;
createdAt: string;
unified: number;
uta: number;
userID: number;
inviterID: number;
vipLevel: string;
mktMakerLevel: string;
affiliateID: number;
}

View File

@@ -1,3 +1,4 @@
export * from './account-asset';
export * from './contract';
export * from './shared';
export * from './spot';

View File

@@ -65,6 +65,13 @@ export interface APIResponseV3<T> {
result: T;
}
export interface APIResponseV3WithTime<T> {
retCode: number;
retMsg: 'OK' | string;
result: T;
time: number;
}
export interface APIResponseWithTime<T = {}> extends APIResponse<T> {
/** UTC timestamp */
time_now: numberInString;

View File

@@ -15,10 +15,29 @@ import {
// return request;
// });
// axios.interceptors.response.use((response) => {
// console.log(new Date(), 'Response:', JSON.stringify(response, null, 2));
// return response;
// });
if (
typeof process === 'object' &&
typeof process.env === 'object' &&
process.env.BYBITTRACE
) {
axios.interceptors.response.use((response) => {
console.log(new Date(), 'Response:', {
request: {
url: response.config.url,
method: response.config.method,
data: response.config.data,
headers: response.config.headers,
},
response: {
status: response.status,
statusText: response.statusText,
headers: response.headers,
data: response.data,
},
});
return response;
});
}
interface SignedRequestContext {
timestamp?: number;

View File

@@ -0,0 +1,58 @@
import { AccountAssetClientV3 } from '../../src';
import { successResponseObjectV3 } from '../response.util';
// Only some minimal coverage for v3 apis, since v5 apis are already available
describe('Private Account Asset V3 REST API Endpoints', () => {
const API_KEY = process.env.API_KEY_COM;
const API_SECRET = process.env.API_SECRET_COM;
it('should have api credentials to test with', () => {
expect(API_KEY).toStrictEqual(expect.any(String));
expect(API_SECRET).toStrictEqual(expect.any(String));
});
const api = new AccountAssetClientV3({
key: API_KEY,
secret: API_SECRET,
testnet: false,
});
const coin = 'USDT';
it('fetchServerTime()', async () => {
expect(await api.fetchServerTime()).toEqual(expect.any(Number));
});
it('getInternalTransfers()', async () => {
expect(
await api.getInternalTransfers({
coin: coin,
})
).toMatchObject(successResponseObjectV3());
});
it('getSubAccountTransfers()', async () => {
expect(await api.getSubAccountTransfers()).toMatchObject(
successResponseObjectV3()
);
});
it('getSubAccounts()', async () => {
expect(await api.getSubAccounts()).toMatchObject(successResponseObjectV3());
});
it('getUniversalTransfers()', async () => {
expect(await api.getUniversalTransfers({ coin: coin })).toMatchObject(
successResponseObjectV3()
);
});
it('getTransferableCoinList()', async () => {
expect(
await api.getTransferableCoinList({
fromAccountType: 'SPOT',
toAccountType: 'CONTRACT',
})
).toMatchObject(successResponseObjectV3());
});
});

View File

@@ -36,7 +36,8 @@ describe('Private Unified Margin REST API POST Endpoints', () => {
timeInForce: 'GoodTillCancel',
})
).toMatchObject({
retCode: API_ERROR_CODE.ACCOUNT_NOT_UNIFIED,
retCode: expect.any(Number),
// retMsg: '',
});
});