fix linter configuration & jest type dependency

This commit is contained in:
tiagosiebler
2023-02-17 13:51:40 +00:00
parent 7669c037c8
commit 8e54ecbaf5
34 changed files with 1600 additions and 1710 deletions

View File

@@ -1,36 +0,0 @@
module.exports = {
env: {
es6: true,
node: true,
},
extends: ['eslint:recommended'],
parserOptions: {
sourceType: 'module',
ecmaVersion: 9
},
plugins: [],
rules: {
'array-bracket-spacing': ['error', 'never'],
indent: ['warn', 2],
'linebreak-style': ['error', 'unix'],
'lines-between-class-members': ['warn', 'always'],
semi: ['error', 'always'],
'new-cap': 'off',
'no-console': 'off',
'no-debugger': 'off',
'no-mixed-spaces-and-tabs': 2,
'no-use-before-define': [2, 'nofunc'],
'no-unreachable': ['warn'],
'no-unused-vars': ['warn'],
'no-extra-parens': ['off'],
'no-mixed-operators': ['off'],
quotes: [2, 'single', 'avoid-escape'],
'block-scoped-var': 2,
'brace-style': [2, '1tbs', { allowSingleLine: true }],
'computed-property-spacing': [2, 'never'],
'keyword-spacing': 2,
'space-unary-ops': 2,
'max-len': ['warn', { 'code': 140 }]
}
};

86
.eslintrc.json Normal file
View File

@@ -0,0 +1,86 @@
{
"env": {
"es6": true,
"node": true
},
"extends": ["eslint:recommended"],
"parser": "@typescript-eslint/parser",
"root": true,
"plugins": ["@typescript-eslint"],
"overrides": [
{
"files": ["**/*.ts", "**/*.tsx"],
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended"
],
"parserOptions": {
"projecasdft": true,
"project": ["./tsconfig.json", "examples/tsconfig.examples.json"]
},
"rules": {
"@typescript-eslint/await-thenable": "error",
"@typescript-eslint/dot-notation": "off",
"@typescript-eslint/no-unused-vars": "warn",
"@typescript-eslint/no-unused-expressions": "error",
"@typescript-eslint/no-var-requires": "error",
"@typescript-eslint/prefer-namespace-keyword": "error",
"@typescript-eslint/no-explicit-any": "error",
"@typescript-eslint/no-floating-promises": "off",
"@typescript-eslint/no-inferrable-types": "off",
"@typescript-eslint/promise-function-async": "off",
"@typescript-eslint/no-use-before-define": "off",
"@typescript-eslint/no-non-null-assertion": "off",
"@typescript-eslint/ban-types": "off",
"@typescript-eslint/explicit-module-boundary-types": "off",
"no-dupe-class-members": "off",
"no-param-reassign": ["error"],
"array-bracket-spacing": ["error", "never"],
"indent": [
"warn",
2,
{
"SwitchCase": 1
}
],
"linebreak-style": ["error", "unix"],
"lines-between-class-members": ["warn", "always"],
"semi": "off",
"@typescript-eslint/semi": ["error"],
"new-cap": "off",
"no-console": "off",
"no-debugger": "off",
"no-mixed-spaces-and-tabs": 2,
"no-use-before-define": [2, "nofunc"],
"no-unreachable": ["warn"],
"no-unused-vars": ["warn"],
"no-extra-parens": ["off"],
"no-mixed-operators": ["off"],
"quotes": [2, "single", "avoid-escape"],
"block-scoped-var": 2,
"brace-style": [2, "1tbs", { "allowSingleLine": true }],
"computed-property-spacing": [2, "never"],
"keyword-spacing": 2,
"space-unary-ops": 2,
"sort-imports": [
"error",
{
"ignoreCase": false,
"ignoreDeclarationSort": true,
"ignoreMemberSort": false,
"memberSyntaxSortOrder": ["none", "all", "multiple", "single"],
"allowSeparatedGroups": false
}
],
"max-len": ["warn", { "code": 140 }]
}
},
{
"files": ["examples/*.js"],
"extends": ["eslint:recommended"]
}
]
}

View File

@@ -15,8 +15,10 @@ const client = new ContractClient({
(async () => {
try {
/**
* You can make raw HTTP requests without the per-endpoint abstraction,
* The REST ContractClient uses bybit's v3 signature mechanism, so it can be used for raw calls to any v3-supporting endpoints (incl the V5 APIs).
* You can make raw HTTP requests without the per-endpoint abstraction.
*
* The REST ContractClient uses bybit's v3 signature mechanism,
* so it can be used for raw calls to any v3-supporting endpoints (incl the V5 APIs).
* e.g. if an endpoint is missing and you desperately need it (but please raise an issue or PR if you're missing an endpoint)
*/
const rawCall = await client.getPrivate('/v5/order/realtime', {

View File

@@ -0,0 +1,12 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "distExamples",
"allowJs": true
},
"include": [
"**/*.ts",
// if you have a mixed JS/TS codebase, don't forget to include your JS files
"**/*.js"
]
}

2644
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -29,12 +29,14 @@
"ws": "^7.4.0"
},
"devDependencies": {
"@types/jest": "^26.0.23",
"@types/jest": "^27.0.4",
"@types/node": "^14.14.7",
"eslint": "^7.10.0",
"@typescript-eslint/eslint-plugin": "^5.46.0",
"@typescript-eslint/parser": "^5.46.0",
"eslint": "^8.29.0",
"jest": "^27.0.4",
"source-map-loader": "^2.0.0",
"ts-jest": "^27.0.3",
"ts-jest": "^27.0.4",
"ts-loader": "^8.0.11",
"typescript": "^4.0.5",
"webpack": "^5.4.0",

View File

@@ -1,10 +1,11 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import {
AccountCoinBalanceResponseV3,
AccountCoinBalancesRequestV3,
AccountCoinBalancesResponseV3,
APIKeyInfoV3,
APIResponseV3WithTime,
APIResponseWithTime,
AccountCoinBalanceResponseV3,
AccountCoinBalancesRequestV3,
AccountCoinBalancesResponseV3,
AssetInfoRequestV3,
AssetInfoResponseV3,
CoinInfoQueryResponseV3,
@@ -18,8 +19,8 @@ import {
InternalTransferRequestV3,
ModifyAPIKeyRequestV3,
QueryDepositAddressRequestV3,
QueryInternalTransfersRequestV3,
QueryInternalTransferSResponseV3,
QueryInternalTransfersRequestV3,
QuerySubAccountDepositAddressRequestV3,
SingleAccountCoinBalanceRequestV3,
SubAccountTransferRequestV3,

View File

@@ -1,6 +1,7 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import {
AccountAssetInformationRequest,
APIResponseWithTime,
AccountAssetInformationRequest,
DepositRecordsRequest,
EnableUniversalTransferRequest,
InternalTransferRequest,

View File

@@ -1,6 +1,24 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import {
APIResponseWithTime,
APIResponseV3,
APIResponseWithTime,
ContractActiveOrdersRequest,
ContractCancelOrderRequest,
ContractClosedPNLRequest,
ContractHistoricOrder,
ContractHistoricOrdersRequest,
ContractListResult,
ContractModifyOrderRequest,
ContractOrderRequest,
ContractPositionsRequest,
ContractSetAutoAddMarginRequest,
ContractSetMarginSwitchRequest,
ContractSetPositionModeRequest,
ContractSetTPSLRequest,
ContractSymbolTicker,
ContractUserExecutionHistoryRequest,
ContractWalletFundRecordRequest,
PaginatedResult,
UMCandlesRequest,
UMCategory,
UMFundingRateHistoryRequest,
@@ -8,23 +26,6 @@ import {
UMOpenInterestRequest,
UMOptionDeliveryPriceRequest,
UMPublicTradesRequest,
ContractOrderRequest,
ContractHistoricOrdersRequest,
ContractCancelOrderRequest,
ContractModifyOrderRequest,
ContractActiveOrdersRequest,
ContractPositionsRequest,
ContractSetAutoAddMarginRequest,
ContractSetMarginSwitchRequest,
ContractSetPositionModeRequest,
ContractSetTPSLRequest,
ContractUserExecutionHistoryRequest,
ContractClosedPNLRequest,
ContractWalletFundRecordRequest,
PaginatedResult,
ContractHistoricOrder,
ContractSymbolTicker,
ContractListResult,
} from './types';
import { REST_CLIENT_TYPE_ENUM } from './util';
import BaseRestClient from './util/BaseRestClient';

View File

@@ -1,4 +1,6 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import {
APIResponseV3,
APIResponseWithTime,
CopyTradingCancelOrderRequest,
CopyTradingCloseOrderRequest,
@@ -6,7 +8,6 @@ import {
CopyTradingOrderRequest,
CopyTradingTradingStopRequest,
CopyTradingTransferRequest,
APIResponseV3,
} from './types';
import { REST_CLIENT_TYPE_ENUM } from './util';
import BaseRestClient from './util/BaseRestClient';

View File

@@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { REST_CLIENT_TYPE_ENUM } from './util';
import {
APIResponseWithTime,

View File

@@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { REST_CLIENT_TYPE_ENUM } from './util/requestUtils';
import {
APIResponseWithTime,

View File

@@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { REST_CLIENT_TYPE_ENUM } from './util/requestUtils';
import {
APIResponse,
@@ -273,6 +274,7 @@ export class LinearClient extends BaseRestClient {
*/
getPosition(): Promise<APIResponseWithTime<PerpPositionRoot[]>>;
getPosition(
params: Partial<SymbolParam>
): Promise<APIResponseWithTime<PerpPosition[]>>;
@@ -344,7 +346,10 @@ export class LinearClient extends BaseRestClient {
getHistoryTradeRecords(
params: LinearGetHistoryTradeRecordsRequest
): Promise<APIResponseWithTime<any>> {
return this.getPrivate('/private/linear/trade/execution/history-list', params);
return this.getPrivate(
'/private/linear/trade/execution/history-list',
params
);
}
getClosedPnl(

View File

@@ -1,13 +1,63 @@
import {
APIResponseV3,
APIResponseV3WithTime,
AccountCoinBalanceV5,
AccountInfoV5,
AccountMarginModeV5,
AccountOrderV5,
AccountTypeV5,
AllCoinsBalanceV5,
AllowedDepositCoinInfoV5,
AmendOrderParamsV5,
ApiKeyInfoV5,
AssetInfoV5,
BatchAmendOrderParamsV5,
BatchAmendOrderResult,
BatchCancelOrderParamsV5,
BatchCancelOrderResult,
BatchOrderParamsV5,
BatchOrderResult,
BatchOrdersResult,
BorrowHistoryRecordV5,
CancelAllOrdersParamsV5,
CancelOrderParamsV5,
CategoryCursorListV5,
CategoryListV5,
CategorySymbolListV5,
CategoryV5,
ClosedPnLV5,
CoinExchangeRecordV5,
CoinGreeksV5,
CoinInfoV5,
CollateralInfoV5,
CreateSubApiKeyParamsV5,
CreateSubApiKeyResultV5,
CreateSubMemberParamsV5,
CreateSubMemberResultV5,
CursorListV5,
DeliveryRecordV5,
DepositAddressResultV5,
DepositRecordV5,
ExecutionV5,
FeeRateV5,
FundingRateHistoryResponseV5,
GetAccountCoinBalanceParamsV5,
GetAccountOrdersParams,
GetAllCoinsBalanceParamsV5,
GetAllowedDepositCoinInfoParamsV5,
GetAssetInfoParamsV5,
GetBorrowHistoryParamsV5,
GetClosedPnLParamsV5,
GetCoinExchangeRecordParamsV5,
GetDeliveryRecordParamsV5,
GetDepositRecordParamsV5,
GetExecutionListParamsV5,
GetFundingRateHistoryParamsV5,
GetHistoricalVolatilityParamsV5,
GetIndexPriceKlineParamsV5,
GetInstrumentsInfoParamsV5,
GetInsuranceParamsV5,
GetInternalTransferParamsV5,
GetKlineParamsV5,
GetMarkPriceKlineParamsV5,
GetOpenInterestParamsV5,
@@ -16,113 +66,63 @@ import {
GetPremiumIndexPriceKlineParams,
GetPublicTradingHistoryParamsV5,
GetRiskLimitParamsV5,
GetTickersParamsV5,
HistoricalVolatilityV5,
InsuranceResponseV5,
OpenInterestResponseV5,
OrderbookResponseV5,
OrderParamsV5,
CursorListV5,
PublicTradeV5,
RiskLimitV5,
AmendOrderParamsV5,
CancelOrderParamsV5,
GetAccountOrdersParams,
OrderResultV5,
CancelAllOrdersParamsV5,
BatchOrderParamsV5,
BatchAmendOrderParamsV5,
BatchOrderResult,
BatchOrdersResult,
BatchAmendOrderResult,
BatchCancelOrderParamsV5,
BatchCancelOrderResult,
OrderSideV5,
SpotBorrowCheckResult,
APIResponseV3,
PositionInfoParamsV5,
CategoryCursorListV5,
PositionV5,
AccountOrderV5,
OptionDeliveryPriceV5,
CategorySymbolListV5,
OHLCKlineV5,
OHLCVKlineV5,
TickerSpotV5,
TickerOptionV5,
TickerLinearInverseV5,
SetLeverageParamsV5,
SwitchIsolatedMarginParamsV5,
SetTPSLModeParamsV5,
TPSLModeV5,
SwitchPositionModeParamsV5,
SetRiskLimitParamsV5,
SetRiskLimitResultV5,
SetTradingStopParamsV5,
SetAutoAddMarginParamsV5,
GetExecutionListParamsV5,
ExecutionV5,
GetClosedPnLParamsV5,
ClosedPnLV5,
GetWalletBalanceParamsV5,
WalletBalanceV5,
UnifiedAccountUpgradeResultV5,
GetBorrowHistoryParamsV5,
BorrowHistoryRecordV5,
CollateralInfoV5,
CoinGreeksV5,
FeeRateV5,
AccountInfoV5,
GetTransactionLogParamsV5,
TransactionLogV5,
AccountMarginModeV5,
MMPModifyParamsV5,
MMPStateV5,
GetCoinExchangeRecordParamsV5,
CoinExchangeRecordV5,
GetDeliveryRecordParamsV5,
DeliveryRecordV5,
GetSettlementRecordParamsV5,
SettlementRecordV5,
GetAssetInfoParamsV5,
AssetInfoV5,
GetAllCoinsBalanceParamsV5,
AllCoinsBalanceV5,
GetAccountCoinBalanceParamsV5,
AccountCoinBalanceV5,
AccountTypeV5,
GetInternalTransferParamsV5,
InternalTransferRecordV5,
UniversalTransferParamsV5,
GetUniversalTransferRecordsParamsV5,
UniversalTransferRecordV5,
GetAllowedDepositCoinInfoParamsV5,
AllowedDepositCoinInfoV5,
GetDepositRecordParamsV5,
DepositRecordV5,
GetSpotLeveragedTokenOrderHistoryParamsV5,
GetSubAccountDepositRecordParamsV5,
DepositAddressResultV5,
CoinInfoV5,
GetTickersParamsV5,
GetTransactionLogParamsV5,
GetUniversalTransferRecordsParamsV5,
GetWalletBalanceParamsV5,
GetWithdrawalRecordsParamsV5,
WithdrawalRecordV5,
WithdrawParamsV5,
CreateSubMemberParamsV5,
CreateSubMemberResultV5,
CreateSubApiKeyParamsV5,
CreateSubApiKeyResultV5,
SubMemberV5,
ApiKeyInfoV5,
UpdateApiKeyResultV5,
UpdateApiKeyParamsV5,
HistoricalVolatilityV5,
InstrumentInfoResponseV5,
InsuranceResponseV5,
InternalTransferRecordV5,
LeverageTokenInfoV5,
LeveragedTokenMarketResultV5,
MMPModifyParamsV5,
MMPStateV5,
OHLCKlineV5,
OHLCVKlineV5,
OpenInterestResponseV5,
OptionDeliveryPriceV5,
OrderParamsV5,
OrderResultV5,
OrderSideV5,
OrderbookResponseV5,
PositionInfoParamsV5,
PositionV5,
PublicTradeV5,
PurchaseSpotLeveragedTokenParamsV5,
PurchaseSpotLeveragedTokenResultV5,
RedeemSpotLeveragedTokenParamsV5,
RedeemSpotLeveragedTokenResultV5,
GetSpotLeveragedTokenOrderHistoryParamsV5,
RiskLimitV5,
SetAutoAddMarginParamsV5,
SetLeverageParamsV5,
SetRiskLimitParamsV5,
SetRiskLimitResultV5,
SetTPSLModeParamsV5,
SetTradingStopParamsV5,
SettlementRecordV5,
SpotBorrowCheckResult,
SpotLeveragedTokenOrderHistoryV5,
InstrumentInfoResponseV5,
SubMemberV5,
SwitchIsolatedMarginParamsV5,
SwitchPositionModeParamsV5,
TPSLModeV5,
TickerLinearInverseV5,
TickerOptionV5,
TickerSpotV5,
TransactionLogV5,
UnifiedAccountUpgradeResultV5,
UniversalTransferParamsV5,
UniversalTransferRecordV5,
UpdateApiKeyParamsV5,
UpdateApiKeyResultV5,
WalletBalanceV5,
WithdrawParamsV5,
WithdrawalRecordV5,
} from './types';
import { REST_CLIENT_TYPE_ENUM } from './util';
import BaseRestClient from './util/BaseRestClient';
@@ -166,7 +166,7 @@ export class RestClientV5 extends BaseRestClient {
CategorySymbolListV5<OHLCVKlineV5[], 'spot' | 'linear' | 'inverse'>
>
> {
return this.get(`/v5/market/kline`, params);
return this.get('/v5/market/kline', params);
}
/**
@@ -181,7 +181,7 @@ export class RestClientV5 extends BaseRestClient {
CategorySymbolListV5<OHLCKlineV5[], 'linear' | 'inverse'>
>
> {
return this.get(`/v5/market/mark-price-kline`, params);
return this.get('/v5/market/mark-price-kline', params);
}
/**
@@ -196,7 +196,7 @@ export class RestClientV5 extends BaseRestClient {
CategorySymbolListV5<OHLCKlineV5[], 'linear' | 'inverse'>
>
> {
return this.get(`/v5/market/index-price-kline`, params);
return this.get('/v5/market/index-price-kline', params);
}
/**
@@ -209,7 +209,7 @@ export class RestClientV5 extends BaseRestClient {
): Promise<
APIResponseV3WithTime<CategorySymbolListV5<OHLCKlineV5[], 'linear'>>
> {
return this.get(`/v5/market/premium-index-price-kline`, params);
return this.get('/v5/market/premium-index-price-kline', params);
}
/**
@@ -222,7 +222,7 @@ export class RestClientV5 extends BaseRestClient {
getInstrumentsInfo(
params: GetInstrumentsInfoParamsV5
): Promise<APIResponseV3WithTime<InstrumentInfoResponseV5>> {
return this.get(`/v5/market/instruments-info`, params);
return this.get('/v5/market/instruments-info', params);
}
/**
@@ -233,7 +233,7 @@ export class RestClientV5 extends BaseRestClient {
getOrderbook(
params: GetOrderbookParamsV5
): Promise<APIResponseV3WithTime<OrderbookResponseV5>> {
return this.get(`/v5/market/orderbook`, params);
return this.get('/v5/market/orderbook', params);
}
/**
@@ -250,7 +250,7 @@ export class RestClientV5 extends BaseRestClient {
| CategoryListV5<TickerSpotV5[], 'spot'>
>
> {
return this.get(`/v5/market/tickers`, params);
return this.get('/v5/market/tickers', params);
}
/**
@@ -265,7 +265,7 @@ export class RestClientV5 extends BaseRestClient {
CategoryListV5<FundingRateHistoryResponseV5[], 'linear' | 'inverse'>
>
> {
return this.get(`/v5/market/funding/history`, params);
return this.get('/v5/market/funding/history', params);
}
/**
@@ -278,7 +278,7 @@ export class RestClientV5 extends BaseRestClient {
): Promise<
APIResponseV3WithTime<CategoryListV5<PublicTradeV5[], CategoryV5>>
> {
return this.get(`/v5/market/recent-trade`, params);
return this.get('/v5/market/recent-trade', params);
}
/**
@@ -289,7 +289,7 @@ export class RestClientV5 extends BaseRestClient {
getOpenInterest(
params: GetOpenInterestParamsV5
): Promise<APIResponseV3WithTime<OpenInterestResponseV5>> {
return this.get(`/v5/market/open-interest`, params);
return this.get('/v5/market/open-interest', params);
}
/**
@@ -301,7 +301,7 @@ export class RestClientV5 extends BaseRestClient {
): Promise<
APIResponseV3WithTime<CategoryListV5<HistoricalVolatilityV5[], 'option'>>
> {
return this.get(`/v5/market/historical-volatility`, params);
return this.get('/v5/market/historical-volatility', params);
}
/**
@@ -310,7 +310,7 @@ export class RestClientV5 extends BaseRestClient {
getInsurance(
params?: GetInsuranceParamsV5
): Promise<APIResponseV3WithTime<InsuranceResponseV5>> {
return this.get(`/v5/market/insurance`, params);
return this.get('/v5/market/insurance', params);
}
/**
@@ -323,7 +323,7 @@ export class RestClientV5 extends BaseRestClient {
): Promise<
APIResponseV3WithTime<CategoryListV5<RiskLimitV5[], 'inverse' | 'linear'>>
> {
return this.get(`/v5/market/risk-limit`, params);
return this.get('/v5/market/risk-limit', params);
}
/**
@@ -336,7 +336,7 @@ export class RestClientV5 extends BaseRestClient {
): Promise<
APIResponseV3WithTime<CategoryCursorListV5<OptionDeliveryPriceV5[]>>
> {
return this.get(`/v5/market/delivery-price`, params);
return this.get('/v5/market/delivery-price', params);
}
/**
@@ -348,7 +348,7 @@ export class RestClientV5 extends BaseRestClient {
submitOrder(
params: OrderParamsV5
): Promise<APIResponseV3WithTime<OrderResultV5>> {
return this.postPrivate(`/v5/order/create`, params);
return this.postPrivate('/v5/order/create', params);
}
amendOrder(
@@ -386,7 +386,7 @@ export class RestClientV5 extends BaseRestClient {
getHistoricOrders(
params: GetAccountOrdersParams
): Promise<APIResponseV3WithTime<CategoryCursorListV5<AccountOrderV5[]>>> {
return this.getPrivate(`/v5/order/history`, params);
return this.getPrivate('/v5/order/history', params);
}
/**
@@ -573,6 +573,7 @@ export class RestClientV5 extends BaseRestClient {
): Promise<APIResponseV3WithTime<{}>> {
return this.postPrivate('/v5/position/trading-stop', params);
}
/**
* This endpoint allows you to turn on/off auto-add-margin for an isolated margin position.
*
@@ -1175,7 +1176,7 @@ export class RestClientV5 extends BaseRestClient {
getLeveragedTokenMarket(
ltCoin: string
): Promise<APIResponseV3WithTime<LeveragedTokenMarketResultV5>> {
return this.get(`/v5/spot-lever-token/reference`, { ltCoin });
return this.get('/v5/spot-lever-token/reference', { ltCoin });
}
/**

View File

@@ -1,17 +1,16 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import {
APIResponseWithTime,
APIResponseV3,
SpotOrderQueryById,
OrderSide,
OrderTypeSpot,
SpotBalances,
APIResponseWithTime,
KlineInterval,
NewSpotOrderV3,
SpotMyTradesRequest,
SpotLeveragedTokenPRHistoryRequest,
SpotBalances,
SpotCancelOrderBatchRequest,
SpotCrossMarginBorrowingInfoRequest,
SpotCrossMarginRepaymentHistoryRequest,
SpotCancelOrderBatchRequest,
SpotLeveragedTokenPRHistoryRequest,
SpotMyTradesRequest,
SpotOrderQueryById,
} from './types';
import { REST_CLIENT_TYPE_ENUM } from './util';
import BaseRestClient from './util/BaseRestClient';

View File

@@ -1,7 +1,8 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import {
NewSpotOrder,
APIResponse,
KlineInterval,
NewSpotOrder,
OrderSide,
OrderTypeSpot,
SpotBalances,
@@ -87,7 +88,9 @@ export class SpotClient extends BaseRestClient {
}
getLastTradedPrice(): Promise<APIResponse<SpotLastPrice[]>>;
getLastTradedPrice(symbol: string): Promise<APIResponse<SpotLastPrice>>;
getLastTradedPrice(
symbol?: string
): Promise<APIResponse<SpotLastPrice | SpotLastPrice[]>> {

View File

@@ -1,4 +1,4 @@
import { numberInString, OrderSide } from '../shared';
import { OrderSide, numberInString } from '../shared';
export type OrderTypeSpot = 'LIMIT' | 'MARKET' | 'LIMIT_MAKER';
export type OrderTimeInForce = 'GTC' | 'FOK' | 'IOC';

View File

@@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
export interface PaginatedResult<TList = any> {
nextPageCursor: string;
list: TList[];

View File

@@ -1,3 +1,4 @@
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export interface UMPaginatedResult<List = any> {
nextPageCursor: string;
category: string;

View File

@@ -251,6 +251,7 @@ export interface RiskLimitV5 {
riskLimitValue: string;
maintenanceMargin: number;
initialMargin: number;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
section: any;
isLowestRisk: 0 | 1;
maxLeverage: string;

View File

@@ -1,7 +1,7 @@
import {
LeverageTokenStatusV5,
LTOrderStatusV5,
LTOrderTypeV5,
LeverageTokenStatusV5,
} from '../v5-shared';
export interface LeverageTokenInfoV5 {

View File

@@ -71,9 +71,9 @@ export type StopOrderTypeV5 =
/**
* Position index. Used to identify positions in different position modes.
*
* - 0one-way mode position
* - 1Buy side of hedge-mode position
* - 2Sell side of hedge-mode position
* - 0 one-way mode position
* - 1 Buy side of hedge-mode position
* - 2 Sell side of hedge-mode position
*/
export type PositionIdx = 0 | 1 | 2;
@@ -124,15 +124,11 @@ export type PermissionTypeV5 =
/**
* Leveraged token status:
*
* 1LT can be purchased and redeemed
*
* 2LT can be purchased, but not redeemed
*
* 3LT can be redeemed, but not purchased
*
* 4LT cannot be purchased nor redeemed
*
* 5Adjusting position
* - '1' LT can be purchased and redeemed
* - '2' LT can be purchased, but not redeemed
* - '3' LT can be redeemed, but not purchased
* - '4' LT cannot be purchased nor redeemed
* - '5' Adjusting position
*/
export type LeverageTokenStatusV5 = '1' | '2' | '3' | '4' | '5';

View File

@@ -98,6 +98,7 @@ export interface WSClientConfigurableOptions {
pingInterval?: number;
reconnectTimeout?: number;
restOptions?: RestClientOptions;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
requestOptions?: any;
wsUrl?: string;
/** If true, fetch server time before trying to authenticate (disabled by default) */

View File

@@ -1,34 +1,35 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import {
APIResponseWithTime,
APIResponseV3,
UMCategory,
UMCandlesRequest,
UMInstrumentInfoRequest,
UMFundingRateHistoryRequest,
UMOptionDeliveryPriceRequest,
UMPublicTradesRequest,
UMOpenInterestRequest,
UMOrderRequest,
UMModifyOrderRequest,
UMCancelOrderRequest,
UMActiveOrdersRequest,
UMHistoricOrdersRequest,
UMBatchOrder,
UMBatchOrderReplace,
UMBatchOrderCancel,
UMCancelAllOrdersRequest,
UMPositionsRequest,
UMSetTPSLRequest,
UM7DayTradingHistoryRequest,
UMOptionsSettlementHistoryRequest,
UMPerpSettlementHistoryRequest,
UMTransactionLogRequest,
APIResponseWithTime,
InternalTransferRequest,
UMExchangeCoinsRequest,
UM7DayTradingHistoryRequest,
UMActiveOrdersRequest,
UMBatchOrder,
UMBatchOrderCancel,
UMBatchOrderReplace,
UMBorrowHistoryRequest,
UMPaginatedResult,
UMCancelAllOrdersRequest,
UMCancelOrderRequest,
UMCandlesRequest,
UMCategory,
UMExchangeCoinsRequest,
UMFundingRateHistoryRequest,
UMHistoricOrder,
UMHistoricOrdersRequest,
UMInstrumentInfo,
UMInstrumentInfoRequest,
UMModifyOrderRequest,
UMOpenInterestRequest,
UMOptionDeliveryPriceRequest,
UMOptionsSettlementHistoryRequest,
UMOrderRequest,
UMPaginatedResult,
UMPerpSettlementHistoryRequest,
UMPositionsRequest,
UMPublicTradesRequest,
UMSetTPSLRequest,
UMTransactionLogRequest,
} from './types';
import { REST_CLIENT_TYPE_ENUM } from './util';
import BaseRestClient from './util/BaseRestClient';

View File

@@ -1,6 +1,7 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import {
APIResponseWithTime,
APIResponseV3,
APIResponseWithTime,
USDCOptionsActiveOrdersRealtimeRequest,
USDCOptionsActiveOrdersRequest,
USDCOptionsCancelAllOrdersRequest,
@@ -8,8 +9,8 @@ import {
USDCOptionsContractInfoRequest,
USDCOptionsDeliveryHistoryRequest,
USDCOptionsDeliveryPriceRequest,
USDCOptionsHistoricalVolatilityRequest,
USDCOptionsHistoricOrdersRequest,
USDCOptionsHistoricalVolatilityRequest,
USDCOptionsModifyMMPRequest,
USDCOptionsModifyOrderRequest,
USDCOptionsOrderExecutionRequest,
@@ -203,7 +204,11 @@ export class USDCOptionClient extends BaseRestClient {
);
}
/** Query trade history. The endpoint only supports up to 30 days of queried records. An error will be returned if startTime is more than 30 days. */
/**
* Query trade history.
* The endpoint only supports up to 30 days of queried records.
* An error will be returned if startTime is more than 30 days.
*/
getOrderExecutionHistory(
params: USDCOptionsOrderExecutionRequest
): Promise<APIResponseV3<any>> {
@@ -241,7 +246,9 @@ export class USDCOptionClient extends BaseRestClient {
}
/**
* If USDC derivatives account balance is greater than X, you can open PORTFOLIO_MARGIN, and if it is less than Y, it will automatically close PORTFOLIO_MARGIN and change back to REGULAR_MARGIN. X and Y will be adjusted according to operational requirements.
* If USDC derivatives account balance is greater than X, you can open PORTFOLIO_MARGIN,
* and if it is less than Y, it will automatically close PORTFOLIO_MARGIN and change back to REGULAR_MARGIN.
* X and Y will be adjusted according to operational requirements.
* Rest API returns the result of checking prerequisites. You could get the real status of margin mode change by subscribing margin mode.
*/
setMarginMode(

View File

@@ -1,8 +1,9 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import {
APIResponseV3,
APIResponseWithTime,
SymbolLimitParam,
SymbolPeriodLimitParam,
APIResponseV3,
USDCKlineRequest,
USDCLast500TradesRequest,
USDCOpenInterestRequest,
@@ -213,7 +214,9 @@ export class USDCPerpetualClient extends BaseRestClient {
}
/**
* If USDC derivatives account balance is greater than X, you can open PORTFOLIO_MARGIN, and if it is less than Y, it will automatically close PORTFOLIO_MARGIN and change back to REGULAR_MARGIN. X and Y will be adjusted according to operational requirements.
* If USDC derivatives account balance is greater than X, you can open PORTFOLIO_MARGIN,
* and if it is less than Y, it will automatically close PORTFOLIO_MARGIN and change back to REGULAR_MARGIN.
* X and Y will be adjusted according to operational requirements.
* Rest API returns the result of checking prerequisites. You could get the real status of margin mode change by subscribing margin mode.
*/
setMarginMode(

View File

@@ -1,14 +1,15 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import axios, { AxiosRequestConfig, AxiosResponse, Method } from 'axios';
import { signMessage } from './node-support';
import {
RestClientOptions,
serializeParams,
RestClientType,
REST_CLIENT_TYPE_ENUM,
APIID,
REST_CLIENT_TYPE_ENUM,
RestClientOptions,
RestClientType,
getRestBaseUrl,
serializeParams,
} from './requestUtils';
import { signMessage } from './node-support';
// axios.interceptors.request.use((request) => {
// console.log(new Date(), 'Starting Request', JSON.stringify(request, null, 2));
@@ -48,7 +49,7 @@ interface SignedRequestContext {
}
interface SignedRequest<T> {
originalParams: T & SignedRequestContext;
originalParams: (T & SignedRequestContext) | SignedRequestContext;
paramsWithSign?: T & SignedRequestContext & { sign: string };
serializedParams: string;
sign: string;
@@ -65,12 +66,19 @@ type SignMethod = 'keyInBody' | 'usdc';
export default abstract class BaseRestClient {
private timeOffset: number | null = null;
private syncTimePromise: null | Promise<any> = null;
private options: RestClientOptions;
private baseUrl: string;
private globalRequestOptions: AxiosRequestConfig;
private key: string | undefined;
private secret: string | undefined;
private clientType: RestClientType;
/** Function that calls exchange API to query & resolve server time, used by time sync, disabled by default */
@@ -159,13 +167,15 @@ export default abstract class BaseRestClient {
params?: TParams,
isPublicApi?: true
): Promise<UnsignedRequest<TParams>>;
private async prepareSignParams<TParams = any>(
method: Method,
signMethod: SignMethod,
params?: TParams,
isPublicApi?: false | undefined
): Promise<SignedRequest<TParams>>;
private async prepareSignParams<TParams = any>(
private async prepareSignParams<TParams extends SignedRequestContext = any>(
method: Method,
signMethod: SignMethod,
params?: TParams,
@@ -186,7 +196,7 @@ export default abstract class BaseRestClient {
await this.syncTime();
}
return this.signRequest(params, method, signMethod);
return this.signRequest(params || {}, method, signMethod);
}
/** Returns an axios request object. Handles signing process automatically if this is a private API call */
@@ -336,7 +346,7 @@ export default abstract class BaseRestClient {
/**
* @private sign request and set recv window
*/
private async signRequest<T = {}>(
private async signRequest<T extends SignedRequestContext | {} = {}>(
data: T,
method: Method,
signMethod: SignMethod
@@ -409,10 +419,13 @@ export default abstract class BaseRestClient {
encodeValues
);
res.sign = await signMessage(res.serializedParams, this.secret);
// @ts-ignore
res.paramsWithSign = {
...res.originalParams,
sign: res.sign,
};
return res;
}

View File

@@ -16,7 +16,8 @@ type WsTopic = string;
/**
* A "Set" is used to ensure we only subscribe to a topic once (tracking a list of unique topics we're expected to be connected to)
* Note: Accurate duplicate tracking only works for plaintext topics. E.g. JSON objects may not be seen as duplicates if keys are in different orders. If that's needed, check the FTX implementation.
* Note: Accurate duplicate tracking only works for plaintext topics.
* E.g. JSON objects may not be seen as duplicates if keys are in different orders. If that's needed, check the FTX implementation.
*/
type WsTopicList = Set<WsTopic>;
@@ -39,6 +40,7 @@ interface WsStoredState {
export default class WsStore {
private wsState: Record<string, WsStoredState>;
private logger: typeof DefaultLogger;
constructor(logger: typeof DefaultLogger) {
@@ -48,7 +50,9 @@ export default class WsStore {
/** Get WS stored state for key, optionally create if missing */
get(key: WsKey, createIfMissing?: true): WsStoredState;
get(key: WsKey, createIfMissing?: false): WsStoredState | undefined;
get(key: WsKey, createIfMissing?: boolean): WsStoredState | undefined {
if (this.wsState[key]) {
return this.wsState[key];

View File

@@ -3,6 +3,7 @@ export async function signMessage(
secret: string
): Promise<string> {
const encoder = new TextEncoder();
// eslint-disable-next-line no-undef
const key = await window.crypto.subtle.importKey(
'raw',
encoder.encode(secret),
@@ -11,6 +12,7 @@ export async function signMessage(
['sign']
);
// eslint-disable-next-line no-undef
const signature = await window.crypto.subtle.sign(
'HMAC',
key,
@@ -18,8 +20,10 @@ export async function signMessage(
);
return Array.prototype.map
.call(new Uint8Array(signature), (x: any) =>
('00' + x.toString(16)).slice(-2)
.call(
new Uint8Array(signature),
(x: { toString: (arg0: number) => string }) =>
('00' + x.toString(16)).slice(-2)
)
.join('');
}

View File

@@ -1,3 +1,4 @@
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type LogParams = null | any;
export const DefaultLogger = {

View File

@@ -91,6 +91,7 @@ export function getRestBaseUrl(
return exchangeBaseUrls.livenet;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function isWsPong(msg: any): boolean {
if (!msg) {
return false;

View File

@@ -298,7 +298,7 @@ export function getWsKeyForTopic(
: WS_KEY_MAP.contractUSDTPublic;
}
default: {
throw neverGuard(market, `getWsKeyForTopic(): Unhandled market`);
throw neverGuard(market, 'getWsKeyForTopic(): Unhandled market');
}
}
}
@@ -322,7 +322,7 @@ export function getMaxTopicsPerSubscribeEvent(
return 10;
}
default: {
throw neverGuard(market, `getWsKeyForTopic(): Unhandled market`);
throw neverGuard(market, 'getWsKeyForTopic(): Unhandled market');
}
}
}

View File

@@ -1,3 +1,5 @@
/* eslint-disable max-len */
/* eslint-disable @typescript-eslint/no-explicit-any */
import { EventEmitter } from 'events';
import WebSocket from 'isomorphic-ws';
@@ -17,24 +19,24 @@ import {
APIMarket,
KlineInterval,
RESTClient,
WebsocketClientOptions,
WSClientConfigurableOptions,
WebsocketClientOptions,
WsKey,
WsTopic,
} from './types';
import {
serializeParams,
isWsPong,
WsConnectionStateEnum,
DefaultLogger,
PUBLIC_WS_KEYS,
WS_AUTH_ON_CONNECT_KEYS,
WS_KEY_MAP,
DefaultLogger,
WS_BASE_URL_MAP,
getWsKeyForTopic,
neverGuard,
WS_KEY_MAP,
WsConnectionStateEnum,
getMaxTopicsPerSubscribeEvent,
getWsKeyForTopic,
isWsPong,
neverGuard,
serializeParams,
} from './util';
const loggerCategory = { category: 'bybit-ws' };
@@ -78,10 +80,14 @@ export declare interface WebsocketClient {
): boolean;
}
// eslint-disable-next-line no-redeclare
export class WebsocketClient extends EventEmitter {
private logger: typeof DefaultLogger;
private restClient?: RESTClient;
private options: WebsocketClientOptions;
private wsStore: WsStore;
constructor(
@@ -109,6 +115,7 @@ export class WebsocketClient extends EventEmitter {
this.prepareRESTClient();
// add default error handling so this doesn't crash node (if the user didn't set a handler)
// eslint-disable-next-line @typescript-eslint/no-empty-function
this.on('error', () => {});
}
@@ -247,7 +254,7 @@ export class WebsocketClient extends EventEmitter {
default: {
throw neverGuard(
this.options.market,
`prepareRESTClient(): Unhandled market`
'prepareRESTClient(): Unhandled market'
);
}
}
@@ -304,7 +311,7 @@ export class WebsocketClient extends EventEmitter {
return [...this.connectPublic(), this.connectPrivate()];
}
default: {
throw neverGuard(this.options.market, `connectAll(): Unhandled market`);
throw neverGuard(this.options.market, 'connectAll(): Unhandled market');
}
}
}
@@ -345,7 +352,7 @@ export class WebsocketClient extends EventEmitter {
default: {
throw neverGuard(
this.options.market,
`connectPublic(): Unhandled market`
'connectPublic(): Unhandled market'
);
}
}
@@ -382,7 +389,7 @@ export class WebsocketClient extends EventEmitter {
default: {
throw neverGuard(
this.options.market,
`connectPrivate(): Unhandled market`
'connectPrivate(): Unhandled market'
);
}
}
@@ -517,7 +524,7 @@ export class WebsocketClient extends EventEmitter {
'Cannot authenticate websocket, either api or private keys missing.',
{ ...loggerCategory, wsKey }
);
throw new Error(`Cannot auth - missing api or secret in config`);
throw new Error('Cannot auth - missing api or secret in config');
}
this.logger.debug("Getting auth'd request params", {
@@ -660,7 +667,7 @@ export class WebsocketClient extends EventEmitter {
this.logger.silly(
`Subscribing to topics in batches of ${maxTopicsPerEvent}`
);
for (var i = 0; i < topics.length; i += maxTopicsPerEvent) {
for (let i = 0; i < topics.length; i += maxTopicsPerEvent) {
const batch = topics.slice(i, i + maxTopicsPerEvent);
this.logger.silly(`Subscribing to batch of ${batch.length}`);
this.requestSubscribeTopics(wsKey, batch);
@@ -695,7 +702,7 @@ export class WebsocketClient extends EventEmitter {
this.logger.silly(
`Unsubscribing to topics in batches of ${maxTopicsPerEvent}`
);
for (var i = 0; i < topics.length; i += maxTopicsPerEvent) {
for (let i = 0; i < topics.length; i += maxTopicsPerEvent) {
const batch = topics.slice(i, i + maxTopicsPerEvent);
this.logger.silly(`Unsubscribing to batch of ${batch.length}`);
this.requestUnsubscribeTopics(wsKey, batch);
@@ -716,7 +723,7 @@ export class WebsocketClient extends EventEmitter {
public tryWsSend(wsKey: WsKey, wsMessage: string) {
try {
this.logger.silly(`Sending upstream ws message: `, {
this.logger.silly('Sending upstream ws message: ', {
...loggerCategory,
wsMessage,
wsKey,
@@ -734,7 +741,7 @@ export class WebsocketClient extends EventEmitter {
}
ws.send(wsMessage);
} catch (e) {
this.logger.error(`Failed to send WS message`, {
this.logger.error('Failed to send WS message', {
...loggerCategory,
wsMessage,
wsKey,
@@ -782,7 +789,7 @@ export class WebsocketClient extends EventEmitter {
// Some websockets require an auth packet to be sent after opening the connection
if (WS_AUTH_ON_CONNECT_KEYS.includes(wsKey)) {
this.logger.info(`Sending auth request...`);
this.logger.info('Sending auth request...');
await this.sendAuthRequest(wsKey);
}
@@ -955,7 +962,7 @@ export class WebsocketClient extends EventEmitter {
...loggerCategory,
wsKey,
});
throw neverGuard(wsKey, `getWsUrl(): Unhandled wsKey`);
throw neverGuard(wsKey, 'getWsUrl(): Unhandled wsKey');
}
}
}
@@ -1051,7 +1058,7 @@ export class WebsocketClient extends EventEmitter {
case 'merge': {
topic = 'mergedDepth';
if (!dumpScale) {
throw new Error(`Dumpscale must be provided for merged orderbooks`);
throw new Error('Dumpscale must be provided for merged orderbooks');
}
break;
}

View File

@@ -13,14 +13,9 @@
"skipLibCheck": true,
"sourceMap": true,
"esModuleInterop": true,
"lib": ["es2017","dom"],
"lib": ["es2017", "dom"],
"outDir": "lib"
},
"include": ["src/**/*"],
"exclude": [
"node_modules",
"**/node_modules/*",
"coverage",
"doc"
]
"exclude": ["node_modules", "**/node_modules/*", "coverage", "doc"]
}