Merge pull request #163 from tiagosiebler/lineartypes

remove silly logger from ws by default. Expand spot and linear types
This commit is contained in:
Tiago
2022-08-18 17:23:04 +01:00
committed by GitHub
18 changed files with 182 additions and 39 deletions

View File

@@ -1,6 +1,6 @@
{ {
"name": "bybit-api", "name": "bybit-api",
"version": "2.3.0", "version": "2.3.1",
"description": "Node.js connector for Bybit's REST APIs and WebSockets, with TypeScript & integration tests.", "description": "Node.js connector for Bybit's REST APIs and WebSockets, with TypeScript & integration tests.",
"main": "lib/index.js", "main": "lib/index.js",
"types": "lib/index.d.ts", "types": "lib/index.d.ts",

View File

@@ -40,3 +40,13 @@ export const API_ERROR_CODE = {
SAME_SLTP_MODE_LINEAR: 130150, SAME_SLTP_MODE_LINEAR: 130150,
RISK_ID_NOT_MODIFIED: 134026, RISK_ID_NOT_MODIFIED: 134026,
} as const; } as const;
/**
* Position idx, used to identify positions in different position modes.
* Required if you are under One-Way Mode:
*/
export enum LinearPositionIdx {
OneWayMode = 0,
BuySide = 1,
SellSide = 2,
}

View File

@@ -4,7 +4,6 @@ export * from './linear-client';
export * from './spot-client'; export * from './spot-client';
export * from './websocket-client'; export * from './websocket-client';
export * from './logger'; export * from './logger';
export * from './types/shared'; export * from './types';
export * from './types/spot';
export * from './util/WsStore'; export * from './util/WsStore';
export * from './constants/enum'; export * from './constants/enum';

View File

@@ -9,14 +9,19 @@ import {
APIResponseWithTime, APIResponseWithTime,
AssetExchangeRecordsReq, AssetExchangeRecordsReq,
CoinParam, CoinParam,
LinearOrder,
NewLinearOrder,
PerpPosition,
PerpPositionRoot,
SymbolInfo, SymbolInfo,
SymbolIntervalFromLimitParam, SymbolIntervalFromLimitParam,
SymbolLimitParam, SymbolLimitParam,
SymbolParam, SymbolParam,
SymbolPeriodLimitParam, SymbolPeriodLimitParam,
WalletBalances,
WalletFundRecordsReq, WalletFundRecordsReq,
WithdrawRecordsReq, WithdrawRecordsReq,
} from './types/shared'; } from './types';
import { linearPositionModeEnum, positionTpSlModeEnum } from './constants/enum'; import { linearPositionModeEnum, positionTpSlModeEnum } from './constants/enum';
import BaseRestClient from './util/BaseRestClient'; import BaseRestClient from './util/BaseRestClient';
@@ -150,7 +155,7 @@ export class LinearClient extends BaseRestClient {
getWalletBalance( getWalletBalance(
params?: Partial<CoinParam> params?: Partial<CoinParam>
): Promise<APIResponseWithTime<any>> { ): Promise<APIResponseWithTime<WalletBalances>> {
return this.getPrivate('v2/private/wallet/balance', params); return this.getPrivate('v2/private/wallet/balance', params);
} }
@@ -192,22 +197,9 @@ export class LinearClient extends BaseRestClient {
* *
*/ */
placeActiveOrder(params: { placeActiveOrder(
side: string; params: NewLinearOrder
symbol: string; ): Promise<APIResponseWithTime<LinearOrder | null>> {
order_type: string;
qty: number;
price?: number;
time_in_force: string;
take_profit?: number;
stop_loss?: number;
tp_trigger_by?: string;
sl_trigger_by?: string;
reduce_only: boolean;
close_on_trigger: boolean;
order_link_id?: string;
position_idx?: number;
}): Promise<APIResponseWithTime<any>> {
return this.postPrivate('private/linear/order/create', params); return this.postPrivate('private/linear/order/create', params);
} }
@@ -337,9 +329,14 @@ export class LinearClient extends BaseRestClient {
* Position * Position
*/ */
getPosition(): Promise<APIResponseWithTime<PerpPositionRoot[]>>;
getPosition(
params: Partial<SymbolParam>
): Promise<APIResponseWithTime<PerpPosition[]>>;
getPosition( getPosition(
params?: Partial<SymbolParam> params?: Partial<SymbolParam>
): Promise<APIResponseWithTime<any>> { ): Promise<APIResponseWithTime<PerpPosition[] | PerpPositionRoot[]>> {
return this.getPrivate('private/linear/position/list', params); return this.getPrivate('private/linear/position/list', params);
} }

View File

@@ -2,7 +2,7 @@ export type LogParams = null | any;
export const DefaultLogger = { export const DefaultLogger = {
silly: (...params: LogParams): void => { silly: (...params: LogParams): void => {
console.log(params); // console.log(params);
}, },
debug: (...params: LogParams): void => { debug: (...params: LogParams): void => {
console.log(params); console.log(params);

View File

@@ -1,12 +1,15 @@
import { AxiosRequestConfig } from 'axios'; import { AxiosRequestConfig } from 'axios';
import { APIResponse, KlineInterval } from './types/shared';
import { import {
NewSpotOrder, NewSpotOrder,
APIResponse,
KlineInterval,
OrderSide, OrderSide,
OrderTypeSpot, OrderTypeSpot,
SpotBalances,
SpotLastPrice,
SpotOrderQueryById, SpotOrderQueryById,
SpotSymbolInfo, SpotSymbolInfo,
} from './types/spot'; } from './types';
import BaseRestClient from './util/BaseRestClient'; import BaseRestClient from './util/BaseRestClient';
import { import {
agentSource, agentSource,
@@ -109,7 +112,11 @@ export class SpotClient extends BaseRestClient {
return this.get('/spot/quote/v1/ticker/24hr', { symbol }); return this.get('/spot/quote/v1/ticker/24hr', { symbol });
} }
getLastTradedPrice(symbol?: string): Promise<APIResponse<any>> { getLastTradedPrice(): Promise<APIResponse<SpotLastPrice[]>>;
getLastTradedPrice(symbol: string): Promise<APIResponse<SpotLastPrice>>;
getLastTradedPrice(
symbol?: string
): Promise<APIResponse<SpotLastPrice | SpotLastPrice[]>> {
return this.get('/spot/quote/v1/ticker/price', { symbol }); return this.get('/spot/quote/v1/ticker/price', { symbol });
} }
@@ -192,7 +199,7 @@ export class SpotClient extends BaseRestClient {
* Wallet Data Endpoints * Wallet Data Endpoints
*/ */
getBalances(): Promise<APIResponse<any>> { getBalances(): Promise<APIResponse<SpotBalances>> {
return this.getPrivate('/spot/v1/account'); return this.getPrivate('/spot/v1/account');
} }
} }

4
src/types/index.ts Normal file
View File

@@ -0,0 +1,4 @@
export * from './response';
export * from './request';
export * from './shared';
export * from './spot';

View File

@@ -0,0 +1 @@
export * from './usdt-perp';

View File

@@ -0,0 +1,27 @@
import { LinearPositionIdx } from '../../constants/enum';
import { OrderSide } from '../shared';
export type LinearOrderType = 'Limit' | 'Market';
export type LinearTimeInForce =
| 'GoodTillCancel'
| 'ImmediateOrCancel'
| 'FillOrKill'
| 'PostOnly';
export interface NewLinearOrder {
side: OrderSide;
symbol: string;
order_type: LinearOrderType;
qty: number;
price?: number;
time_in_force: LinearTimeInForce;
take_profit?: number;
stop_loss?: number;
tp_trigger_by?: string;
sl_trigger_by?: string;
reduce_only: boolean;
close_on_trigger: boolean;
order_link_id?: string;
position_idx?: LinearPositionIdx;
}

View File

@@ -0,0 +1,3 @@
export * from './shared';
export * from './spot';
export * from './usdt-perp';

View File

@@ -0,0 +1,19 @@
export interface SymbolWalletBalance {
equity: number;
available_balance: number;
used_margin: number;
order_margin: number;
position_margin: number;
occ_closing_fee: number;
occ_funding_fee: number;
wallet_balance: number;
realised_pnl: number;
unrealised_pnl: number;
cum_realised_pnl: number;
given_cash: number;
service_cash: number;
}
export interface WalletBalances {
[symbol: string]: SymbolWalletBalance | undefined;
}

View File

@@ -0,0 +1,17 @@
export interface SpotBalance {
coin: string;
coinId: string;
coinName: string;
total: string;
free: string;
locked: string;
}
export interface SpotBalances {
balances: SpotBalance[];
}
export interface SpotLastPrice {
symbol: string;
price: string;
}

View File

@@ -0,0 +1,58 @@
export interface PerpPosition {
user_id: number;
symbol: string;
side: string;
size: number;
position_value: number;
entry_price: number;
liq_price: number;
bust_price: number;
leverage: number;
auto_add_margin: number;
is_isolated: boolean;
position_margin: number;
occ_closing_fee: number;
realised_pnl: number;
cum_realised_pnl: number;
free_qty: number;
tp_sl_mode: string;
unrealised_pnl: number;
deleverage_indicator: number;
risk_id: number;
stop_loss: number;
take_profit: number;
trailing_stop: number;
position_idx: number;
mode: string;
}
export interface PerpPositionRoot {
data: PerpPosition;
is_valid: boolean;
}
export interface LinearOrder {
order_id: string;
user_id: number;
symbol: string;
side: string;
order_type: string;
price: number;
qty: number;
time_in_force: string;
order_status: string;
last_exec_price: number;
cum_exec_qty: number;
cum_exec_value: number;
cum_exec_fee: number;
reduce_only: boolean;
close_on_trigger: boolean;
order_link_id: string;
created_time: string;
updated_time: string;
take_profit: number;
stop_loss: number;
tp_trigger_by: string;
sl_trigger_by: string;
position_idx: number;
}

View File

@@ -1,3 +1,7 @@
export type numberInString = string;
export type OrderSide = 'Buy' | 'Sell';
export type KlineInterval = export type KlineInterval =
| '1m' | '1m'
| '3m' | '3m'
@@ -13,8 +17,6 @@ export type KlineInterval =
| '1w' | '1w'
| '1M'; | '1M';
export type numberInString = string;
export interface APIResponse<T> { export interface APIResponse<T> {
ret_code: number; ret_code: number;
ret_msg: 'OK' | string; ret_msg: 'OK' | string;

View File

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

View File

@@ -24,20 +24,20 @@ describe('Private Spot REST API Endpoints', () => {
it('getOrder()', async () => { it('getOrder()', async () => {
// No auth error == test pass // No auth error == test pass
expect(await api.getOrder({ orderId: '123123' })).toMatchObject( expect(await api.getOrder({ orderId: '123123' })).toMatchObject(
errorResponseObject(null, -2013, 'Order does not exist.') errorResponseObject({}, -2013, 'Order does not exist.')
); );
}); });
it('getOpenOrders()', async () => { it('getOpenOrders()', async () => {
expect(await api.getOpenOrders()).toMatchObject(successResponseList('')); expect(await api.getOpenOrders()).toMatchObject(successResponseList());
}); });
it('getPastOrders()', async () => { it('getPastOrders()', async () => {
expect(await api.getPastOrders()).toMatchObject(successResponseList('')); expect(await api.getPastOrders()).toMatchObject(successResponseList());
}); });
it('getMyTrades()', async () => { it('getMyTrades()', async () => {
expect(await api.getMyTrades()).toMatchObject(successResponseList('')); expect(await api.getMyTrades()).toMatchObject(successResponseList());
}); });
it('getBalances()', async () => { it('getBalances()', async () => {
@@ -46,7 +46,7 @@ describe('Private Spot REST API Endpoints', () => {
balances: expect.any(Array), balances: expect.any(Array),
}, },
ret_code: 0, ret_code: 0,
ret_msg: '', ret_msg: 'OK',
}); });
}); });
}); });

View File

@@ -18,7 +18,7 @@ describe('Private Inverse-Futures REST API POST Endpoints', () => {
// These tests are primarily check auth is working by expecting balance or order not found style errors // These tests are primarily check auth is working by expecting balance or order not found style errors
it('submitOrder()', async () => { it.skip('submitOrder()', async () => {
expect( expect(
await api.submitOrder({ await api.submitOrder({
side: 'Buy', side: 'Buy',
@@ -49,6 +49,6 @@ describe('Private Inverse-Futures REST API POST Endpoints', () => {
symbol, symbol,
orderTypes: ['LIMIT', 'LIMIT_MAKER'], orderTypes: ['LIMIT', 'LIMIT_MAKER'],
}) })
).toMatchObject(successResponseObject('')); ).toMatchObject(successResponseObject());
}); });
}); });

View File

@@ -24,7 +24,7 @@ describe('Public Spot REST API Endpoints', () => {
}); });
it('getSymbols()', async () => { it('getSymbols()', async () => {
expect(await api.getSymbols()).toMatchObject(successResponseList('')); expect(await api.getSymbols()).toMatchObject(successResponseList());
}); });
it('getOrderBook()', async () => { it('getOrderBook()', async () => {