Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

bybit-api

Package Overview
Dependencies
Maintainers
1
Versions
126
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

bybit-api - npm Package Compare versions

Comparing version 2.4.0-beta.2 to 3.0.1

lib/types/request/inverse.d.ts

144

lib/inverse-client.d.ts

@@ -1,2 +0,2 @@

import { APIResponseWithTime, AssetExchangeRecordsReq, CoinParam, SymbolInfo, SymbolIntervalFromLimitParam, SymbolLimitParam, SymbolParam, SymbolPeriodLimitParam, WalletFundRecordsReq, WithdrawRecordsReq } from './types';
import { APIResponseWithTime, AssetExchangeRecordsReq, CoinParam, InverseActiveConditionalOrderRequest, InverseActiveOrdersRequest, InverseCancelConditionalOrderRequest, InverseCancelOrderRequest, InverseChangePositionMarginRequest, InverseConditionalOrderRequest, InverseGetClosedPnlRequest, InverseGetOrderRequest, InverseGetTradeRecordsRequest, InverseOrderRequest, InverseReplaceConditionalOrderRequest, InverseReplaceOrderRequest, InverseSetLeverageRequest, InverseSetMarginTypeRequest, InverseSetSlTpPositionModeRequest, InverseSetTradingStopRequest, SymbolInfo, SymbolIntervalFromLimitParam, SymbolLimitParam, SymbolParam, SymbolPeriodLimitParam, WalletFundRecordsReq, WithdrawRecordsReq } from './types';
import BaseRestClient from './util/BaseRestClient';

@@ -63,89 +63,18 @@ /**

*/
placeActiveOrder(orderRequest: {
side: string;
symbol: string;
order_type: string;
qty: number;
price?: number;
time_in_force: string;
take_profit?: number;
stop_loss?: number;
reduce_only?: boolean;
tp_trigger_by?: 'LastPrice' | 'MarkPrice' | 'IndexPrice';
sl_trigger_by?: 'LastPrice' | 'MarkPrice' | 'IndexPrice';
close_on_trigger?: boolean;
order_link_id?: string;
}): Promise<APIResponseWithTime<any>>;
getActiveOrderList(params: {
symbol: string;
order_status?: string;
direction?: string;
limit?: number;
cursor?: string;
}): Promise<APIResponseWithTime<any>>;
cancelActiveOrder(params: {
symbol: string;
order_id?: string;
order_link_id?: string;
}): Promise<APIResponseWithTime<any>>;
placeActiveOrder(orderRequest: InverseOrderRequest): Promise<APIResponseWithTime<any>>;
getActiveOrderList(params: InverseActiveOrdersRequest): Promise<APIResponseWithTime<any>>;
cancelActiveOrder(params: InverseCancelOrderRequest): Promise<APIResponseWithTime<any>>;
cancelAllActiveOrders(params: SymbolParam): Promise<APIResponseWithTime<any>>;
replaceActiveOrder(params: {
order_id?: string;
order_link_id?: string;
symbol: string;
p_r_qty?: number;
p_r_price?: string;
take_profit?: number;
stop_loss?: number;
tp_trigger_by?: string;
sl_trigger_by?: string;
}): Promise<APIResponseWithTime<any>>;
queryActiveOrder(params: {
order_id?: string;
order_link_id?: string;
symbol: string;
}): Promise<APIResponseWithTime<any>>;
replaceActiveOrder(params: InverseReplaceOrderRequest): Promise<APIResponseWithTime<any>>;
queryActiveOrder(params: InverseGetOrderRequest): Promise<APIResponseWithTime<any>>;
/**
* Conditional orders
*/
placeConditionalOrder(params: {
side: string;
symbol: string;
order_type: string;
qty: string;
price?: string;
base_price: string;
stop_px: string;
time_in_force: string;
trigger_by?: string;
close_on_trigger?: boolean;
order_link_id?: string;
}): Promise<APIResponseWithTime<any>>;
placeConditionalOrder(params: InverseConditionalOrderRequest): Promise<APIResponseWithTime<any>>;
/** get conditional order list. This may see delays, use queryConditionalOrder() for real-time queries */
getConditionalOrder(params: {
symbol: string;
stop_order_status?: string;
direction?: string;
limit?: number;
cursor?: string;
}): Promise<APIResponseWithTime<any>>;
cancelConditionalOrder(params: {
symbol: string;
stop_order_id?: string;
order_link_id?: string;
}): Promise<APIResponseWithTime<any>>;
getConditionalOrder(params: InverseActiveConditionalOrderRequest): Promise<APIResponseWithTime<any>>;
cancelConditionalOrder(params: InverseCancelConditionalOrderRequest): Promise<APIResponseWithTime<any>>;
cancelAllConditionalOrders(params: SymbolParam): Promise<APIResponseWithTime<any>>;
replaceConditionalOrder(params: {
stop_order_id?: string;
order_link_id?: string;
symbol: string;
p_r_qty?: number;
p_r_price?: string;
p_r_trigger_price?: string;
}): Promise<APIResponseWithTime<any>>;
queryConditionalOrder(params: {
symbol: string;
stop_order_id?: string;
order_link_id?: string;
}): Promise<APIResponseWithTime<any>>;
replaceConditionalOrder(params: InverseReplaceConditionalOrderRequest): Promise<APIResponseWithTime<any>>;
queryConditionalOrder(params: InverseGetOrderRequest): Promise<APIResponseWithTime<any>>;
/**

@@ -155,46 +84,9 @@ * Position

getPosition(params?: Partial<SymbolParam>): Promise<APIResponseWithTime<any>>;
changePositionMargin(params: {
symbol: string;
margin: string;
}): Promise<APIResponseWithTime<any>>;
setTradingStop(params: {
symbol: string;
take_profit?: number;
stop_loss?: number;
trailing_stop?: number;
tp_trigger_by?: string;
sl_trigger_by?: string;
new_trailing_active?: number;
}): Promise<APIResponseWithTime<any>>;
setUserLeverage(params: {
symbol: string;
leverage: number;
leverage_only?: boolean;
}): Promise<APIResponseWithTime<any>>;
getTradeRecords(params: {
order_id?: string;
symbol: string;
start_time?: number;
page?: number;
limit?: number;
order?: string;
}): Promise<APIResponseWithTime<any>>;
getClosedPnl(params: {
symbol: string;
start_time?: number;
end_time?: number;
exec_type?: string;
page?: number;
limit?: number;
}): Promise<APIResponseWithTime<any>>;
setSlTpPositionMode(params: {
symbol: string;
tp_sl_mode: 'Full' | 'Partial';
}): Promise<APIResponseWithTime<any>>;
setMarginType(params: {
symbol: string;
is_isolated: boolean;
buy_leverage: number;
sell_leverage: number;
}): Promise<APIResponseWithTime<any>>;
changePositionMargin(params: InverseChangePositionMarginRequest): Promise<APIResponseWithTime<any>>;
setTradingStop(params: InverseSetTradingStopRequest): Promise<APIResponseWithTime<any>>;
setUserLeverage(params: InverseSetLeverageRequest): Promise<APIResponseWithTime<any>>;
getTradeRecords(params: InverseGetTradeRecordsRequest): Promise<APIResponseWithTime<any>>;
getClosedPnl(params: InverseGetClosedPnlRequest): Promise<APIResponseWithTime<any>>;
setSlTpPositionMode(params: InverseSetSlTpPositionModeRequest): Promise<APIResponseWithTime<any>>;
setMarginType(params: InverseSetMarginTypeRequest): Promise<APIResponseWithTime<any>>;
/**

@@ -201,0 +93,0 @@ * Funding

@@ -1,3 +0,2 @@

import { APIResponse, APIResponseWithTime, AssetExchangeRecordsReq, CoinParam, LinearOrder, NewLinearOrder, PerpPosition, PerpPositionRoot, SymbolInfo, SymbolIntervalFromLimitParam, SymbolLimitParam, SymbolParam, SymbolPeriodLimitParam, WalletBalances, WalletFundRecordsReq, WithdrawRecordsReq } from './types';
import { linearPositionModeEnum, positionTpSlModeEnum } from './constants/enum';
import { APIResponse, APIResponseWithTime, AssetExchangeRecordsReq, CoinParam, LinearCancelConditionalOrderRequest, LinearCancelOrderRequest, LinearConditionalOrderRequest, LinearGetClosedPnlRequest, LinearGetConditionalOrderRequest, LinearGetOrderRequest, LinearGetOrdersRequest, LinearGetTradeRecordsRequest, LinearOrder, LinearQueryConditionalOrderRequest, LinearReplaceConditionalOrderRequest, LinearReplaceOrderRequest, LinearSetAddReduceMarginRequest, LinearSetAutoAddMarginRequest, LinearSetMarginSwitchRequest, LinearSetPositionModeRequest, LinearSetPositionTpSlModeRequest, LinearSetRiskLimitRequest, LinearSetTradingStopRequest, LinearSetUserLeverageRequest, NewLinearOrder, PerpPosition, PerpPositionRoot, SymbolInfo, SymbolIntervalFromLimitParam, SymbolLimitParam, SymbolParam, SymbolPeriodLimitParam, WalletBalances, WalletFundRecordsReq, WithdrawRecordsReq } from './types';
import BaseRestClient from './util/BaseRestClient';

@@ -63,86 +62,16 @@ /**

placeActiveOrder(params: NewLinearOrder): Promise<APIResponseWithTime<LinearOrder | null>>;
getActiveOrderList(params: {
order_id?: string;
order_link_id?: string;
symbol: string;
order?: string;
page?: number;
limit?: number;
order_status?: string;
}): Promise<APIResponseWithTime<any>>;
cancelActiveOrder(params: {
symbol: string;
order_id?: string;
order_link_id?: string;
}): Promise<APIResponseWithTime<any>>;
getActiveOrderList(params: LinearGetOrdersRequest): Promise<APIResponseWithTime<any>>;
cancelActiveOrder(params: LinearCancelOrderRequest): Promise<APIResponseWithTime<any>>;
cancelAllActiveOrders(params: SymbolParam): Promise<APIResponseWithTime<any>>;
replaceActiveOrder(params: {
order_id?: string;
order_link_id?: string;
symbol: string;
p_r_qty?: number;
p_r_price?: number;
take_profit?: number;
stop_loss?: number;
tp_trigger_by?: string;
sl_trigger_by?: string;
}): Promise<APIResponseWithTime<any>>;
queryActiveOrder(params: {
order_id?: string;
order_link_id?: string;
symbol: string;
}): Promise<APIResponseWithTime<any>>;
replaceActiveOrder(params: LinearReplaceOrderRequest): Promise<APIResponseWithTime<any>>;
queryActiveOrder(params: LinearGetOrderRequest): Promise<APIResponseWithTime<any>>;
/**
* Conditional orders
*/
placeConditionalOrder(params: {
side: string;
symbol: string;
order_type: string;
qty: number;
price?: number;
base_price: number;
stop_px: number;
time_in_force: string;
trigger_by?: string;
close_on_trigger?: boolean;
order_link_id?: string;
reduce_only: boolean;
take_profit?: number;
stop_loss?: number;
tp_trigger_by?: string;
sl_trigger_by?: string;
}): Promise<APIResponseWithTime<any>>;
getConditionalOrder(params: {
stop_order_id?: string;
order_link_id?: string;
symbol: string;
stop_order_status?: string;
order?: string;
page?: number;
limit?: number;
}): Promise<APIResponseWithTime<any>>;
cancelConditionalOrder(params: {
symbol: string;
stop_order_id?: string;
order_link_id?: string;
}): Promise<APIResponseWithTime<any>>;
placeConditionalOrder(params: LinearConditionalOrderRequest): Promise<APIResponseWithTime<any>>;
getConditionalOrder(params: LinearGetConditionalOrderRequest): Promise<APIResponseWithTime<any>>;
cancelConditionalOrder(params: LinearCancelConditionalOrderRequest): Promise<APIResponseWithTime<any>>;
cancelAllConditionalOrders(params: SymbolParam): Promise<APIResponseWithTime<any>>;
replaceConditionalOrder(params: {
stop_order_id?: string;
order_link_id?: string;
symbol: string;
p_r_qty?: number;
p_r_price?: number;
p_r_trigger_price?: number;
take_profit?: number;
stop_loss?: number;
tp_trigger_by?: string;
sl_trigger_by?: string;
}): Promise<APIResponseWithTime<any>>;
queryConditionalOrder(params: {
symbol: string;
stop_order_id?: string;
order_link_id?: string;
}): Promise<APIResponseWithTime<any>>;
replaceConditionalOrder(params: LinearReplaceConditionalOrderRequest): Promise<APIResponseWithTime<any>>;
queryConditionalOrder(params: LinearQueryConditionalOrderRequest): Promise<APIResponseWithTime<any>>;
/**

@@ -153,20 +82,8 @@ * Position

getPosition(params: Partial<SymbolParam>): Promise<APIResponseWithTime<PerpPosition[]>>;
setAutoAddMargin(params?: {
symbol: string;
side: string;
auto_add_margin: boolean;
}): Promise<APIResponseWithTime<any>>;
setMarginSwitch(params?: {
symbol: string;
is_isolated: boolean;
buy_leverage: number;
sell_leverage: number;
}): Promise<APIResponseWithTime<any>>;
setAutoAddMargin(params?: LinearSetAutoAddMarginRequest): Promise<APIResponseWithTime<any>>;
setMarginSwitch(params?: LinearSetMarginSwitchRequest): Promise<APIResponseWithTime<any>>;
/**
* Switch between one-way vs hedge mode. Use `linearPositionModeEnum` for the mode parameter.
*/
setPositionMode(params: {
symbol: string;
mode: typeof linearPositionModeEnum[keyof typeof linearPositionModeEnum];
}): Promise<APIResponseWithTime<any>>;
setPositionMode(params: LinearSetPositionModeRequest): Promise<APIResponseWithTime<any>>;
/**

@@ -176,43 +93,8 @@ * Switch TP/SL mode between full or partial. When set to Partial, TP/SL orders may have a quantity less than the position size.

*/
setPositionTpSlMode(params: {
symbol: string;
tp_sl_mode: typeof positionTpSlModeEnum[keyof typeof positionTpSlModeEnum];
}): Promise<APIResponseWithTime<any>>;
setAddReduceMargin(params?: {
symbol: string;
side: string;
margin: number;
}): Promise<APIResponseWithTime<any>>;
setUserLeverage(params: {
symbol: string;
buy_leverage: number;
sell_leverage: number;
}): Promise<APIResponseWithTime<any>>;
setTradingStop(params: {
symbol: string;
side: string;
take_profit?: number;
stop_loss?: number;
trailing_stop?: number;
tp_trigger_by?: string;
sl_trigger_by?: string;
sl_size?: number;
tp_size?: number;
}): Promise<APIResponseWithTime<any>>;
getTradeRecords(params: {
symbol: string;
start_time?: number;
end_time?: number;
exec_type?: string;
page?: number;
limit?: number;
}): Promise<APIResponseWithTime<any>>;
getClosedPnl(params: {
symbol: string;
start_time?: number;
end_time?: number;
exec_type?: string;
page?: number;
limit?: number;
}): Promise<APIResponseWithTime<any>>;
setPositionTpSlMode(params: LinearSetPositionTpSlModeRequest): Promise<APIResponseWithTime<any>>;
setAddReduceMargin(params?: LinearSetAddReduceMarginRequest): Promise<APIResponseWithTime<any>>;
setUserLeverage(params: LinearSetUserLeverageRequest): Promise<APIResponseWithTime<any>>;
setTradingStop(params: LinearSetTradingStopRequest): Promise<APIResponseWithTime<any>>;
getTradeRecords(params: LinearGetTradeRecordsRequest): Promise<APIResponseWithTime<any>>;
getClosedPnl(params: LinearGetClosedPnlRequest): Promise<APIResponseWithTime<any>>;
/**

@@ -222,7 +104,3 @@ * Risk Limit

getRiskLimitList(params: SymbolParam): Promise<APIResponseWithTime<any>>;
setRiskLimit(params: {
symbol: string;
side: string;
risk_id: number;
}): Promise<APIResponseWithTime<any>>;
setRiskLimit(params: LinearSetRiskLimitRequest): Promise<APIResponseWithTime<any>>;
/**

@@ -229,0 +107,0 @@ * Funding

@@ -1,2 +0,2 @@

import { APIResponseWithTime, APIResponseV3, SpotOrderQueryById, OrderSide, OrderTypeSpot, SpotBalances, KlineInterval, NewSpotOrderV3, SpotMyTradesRequest, SpotLeveragedTokenPRHistoryRequest, SpotCrossMarginBorrowingInfoRequest, SpotCrossMarginRepaymentHistoryRequest } from './types';
import { APIResponseWithTime, APIResponseV3, SpotOrderQueryById, SpotBalances, KlineInterval, NewSpotOrderV3, SpotMyTradesRequest, SpotLeveragedTokenPRHistoryRequest, SpotCrossMarginBorrowingInfoRequest, SpotCrossMarginRepaymentHistoryRequest, SpotCancelOrderBatchRequest } from './types';
import BaseRestClient from './util/BaseRestClient';

@@ -43,7 +43,3 @@ /**

/** Batch cancel orders */
cancelOrderBatch(params: {
symbol: string;
side?: OrderSide;
orderTypes: OrderTypeSpot[];
}): Promise<APIResponseV3<any>>;
cancelOrderBatch(params: SpotCancelOrderBatchRequest): Promise<APIResponseV3<any>>;
/** Batch cancel up to 100 orders by ID */

@@ -50,0 +46,0 @@ cancelOrderBatchIDs(orderIds: string[]): Promise<APIResponseV3<any>>;

@@ -84,3 +84,3 @@ "use strict";

submitOrder(params) {
return this.postPrivate('/spot/v1/order', Object.assign(Object.assign({}, params), { agentSource: requestUtils_1.agentSource }));
return this.postPrivate('/spot/v1/order', params);
}

@@ -87,0 +87,0 @@ getOrder(params) {

export * from './account-asset';
export * from './copy-trading';
export * from './linear';
export * from './inverse';
export * from './spot';
export * from './usdt-perp';
export * from './usdc-perp';

@@ -6,0 +7,0 @@ export * from './usdc-options';

@@ -15,4 +15,5 @@ "use strict";

__exportStar(require("./copy-trading"), exports);
__exportStar(require("./linear"), exports);
__exportStar(require("./inverse"), exports);
__exportStar(require("./spot"), exports);
__exportStar(require("./usdt-perp"), exports);
__exportStar(require("./usdc-perp"), exports);

@@ -19,0 +20,0 @@ __exportStar(require("./usdc-options"), exports);

@@ -24,2 +24,7 @@ import { numberInString, OrderSide } from '../shared';

}
export interface SpotCancelOrderBatchRequest {
symbol: string;
side?: OrderSide;
orderTypes: OrderTypeSpot[];
}
export interface SpotOrderQueryById {

@@ -26,0 +31,0 @@ orderId?: string;

@@ -5,5 +5,6 @@ import { InverseClient } from '../inverse-client';

import { SpotClientV3 } from '../spot-client-v3';
import { UnifiedMarginClient } from '../unified-margin-client';
import { USDCOptionClient } from '../usdc-option-client';
import { USDCPerpetualClient } from '../usdc-perpetual-client';
export declare type RESTClient = InverseClient | LinearClient | SpotClient | SpotClientV3 | USDCOptionClient | USDCPerpetualClient;
export declare type RESTClient = InverseClient | LinearClient | SpotClient | SpotClientV3 | USDCOptionClient | USDCPerpetualClient | UnifiedMarginClient;
export declare type numberInString = string;

@@ -10,0 +11,0 @@ export declare type OrderSide = 'Buy' | 'Sell';

import { RestClientOptions, WS_KEY_MAP } from '../util';
/** For spot markets, spotV3 is recommended */
export declare type APIMarket = 'inverse' | 'linear' | 'spot' | 'spotv3' | 'usdcOption' | 'usdcPerp';
export declare type APIMarket = 'inverse' | 'linear' | 'spot' | 'spotv3' | 'usdcOption' | 'usdcPerp' | 'unifiedPerp' | 'unifiedOption';
export declare type WsPublicInverseTopic = 'orderBookL2_25' | 'orderBookL2_200' | 'trade' | 'insurance' | 'instrument_info' | 'klineV2';

@@ -5,0 +5,0 @@ export declare type WsPublicUSDTPerpTopic = 'orderBookL2_25' | 'orderBookL2_200' | 'trade' | 'insurance' | 'instrument_info' | 'kline';

@@ -17,15 +17,11 @@ import { AxiosRequestConfig } from 'axios';

/**
* Create an instance of the REST client
* @param {string} key - your API key
* @param {string} secret - your API secret
* @param {boolean} [useLivenet=false]
* Create an instance of the REST client. Pass API credentials in the object in the first parameter.
* @param {RestClientOptions} [restClientOptions={}] options to configure REST API connectivity
* @param {AxiosRequestConfig} [requestOptions={}] HTTP networking options for axios
* @param {AxiosRequestConfig} [networkOptions={}] HTTP networking options for axios
*/
constructor(key?: string | undefined, secret?: string | undefined, useLivenet?: boolean, options?: RestClientOptions, requestOptions?: AxiosRequestConfig);
constructor(restOptions?: RestClientOptions, networkOptions?: AxiosRequestConfig);
private isSpotClient;
private isUSDCClient;
get(endpoint: string, params?: any): Promise<any>;
getPrivate(endpoint: string, params?: any): Promise<any>;
post(endpoint: string, params?: any): Promise<any>;
getPrivate(endpoint: string, params?: any): Promise<any>;
postPrivate(endpoint: string, params?: any): Promise<any>;

@@ -32,0 +28,0 @@ deletePrivate(endpoint: string, params?: any): Promise<any>;

@@ -20,11 +20,7 @@ "use strict";

/**
* Create an instance of the REST client
* @param {string} key - your API key
* @param {string} secret - your API secret
* @param {boolean} [useLivenet=false]
* Create an instance of the REST client. Pass API credentials in the object in the first parameter.
* @param {RestClientOptions} [restClientOptions={}] options to configure REST API connectivity
* @param {AxiosRequestConfig} [requestOptions={}] HTTP networking options for axios
* @param {AxiosRequestConfig} [networkOptions={}] HTTP networking options for axios
*/
constructor(key, secret, useLivenet = false, options = {}, requestOptions = {}) {
const baseUrl = requestUtils_1.getRestBaseUrl(useLivenet, options);
constructor(restOptions = {}, networkOptions = {}) {
this.timeOffset = null;

@@ -39,11 +35,13 @@ this.syncTimePromise = null;

/** How often to sync time drift with bybit servers (if time sync is enabled) */
sync_interval_ms: 3600000 }, options);
sync_interval_ms: 3600000 }, restOptions);
this.globalRequestOptions = Object.assign(Object.assign({
// in ms == 5 minutes by default
timeout: 1000 * 60 * 5 }, requestOptions), { headers: {
'x-referer': requestUtils_1.agentSource,
timeout: 1000 * 60 * 5 }, networkOptions), { headers: {
'x-referer': requestUtils_1.APIID,
} });
this.baseUrl = baseUrl;
if (key && !secret) {
throw new Error('API Key & Secret are both required for private enpoints');
this.baseUrl = requestUtils_1.getRestBaseUrl(!!this.options.testnet, restOptions);
this.key = this.options.key;
this.secret = this.options.secret;
if (this.key && !this.secret) {
throw new Error('API Key & Secret are both required for private endpoints');
}

@@ -54,4 +52,2 @@ if (this.options.enable_time_sync) {

}
this.key = key;
this.secret = secret;
}

@@ -61,14 +57,11 @@ isSpotClient() {

}
isUSDCClient() {
return this.clientType === requestUtils_1.REST_CLIENT_TYPE_ENUM.v3;
}
get(endpoint, params) {
return this._call('GET', endpoint, params, true);
}
getPrivate(endpoint, params) {
return this._call('GET', endpoint, params, false);
}
post(endpoint, params) {
return this._call('POST', endpoint, params, true);
}
getPrivate(endpoint, params) {
return this._call('GET', endpoint, params, false);
}
postPrivate(endpoint, params) {

@@ -109,4 +102,4 @@ return this._call('POST', endpoint, params, false);

}
// USDC Options uses a different way of authenticating requests (headers instead of params)
if (this.isUSDCClient()) {
// USDC endpoints, unified margin and a few others use a different way of authenticating requests (headers instead of params)
if (this.clientType === requestUtils_1.REST_CLIENT_TYPE_ENUM.v3) {
if (!options.headers) {

@@ -113,0 +106,0 @@ options.headers = {};

export interface RestClientOptions {
/** Your API key */
key?: string;
/** Your API secret */
secret?: string;
/** Set to `true` to connect to testnet. Uses the live environment by default. */
testnet?: boolean;
/** Override the max size of the request window (in ms) */
recv_window?: number;
/** @deprecated Time sync is now disabled by default. To re-enable it, use enable_time_sync instead. */
disable_time_sync?: boolean;
/** Disabled by default. This can help on machines with consistent latency problems. */

@@ -21,5 +25,5 @@ enable_time_sync?: boolean;

export declare function serializeParams(params?: object, strict_validation?: boolean): string;
export declare function getRestBaseUrl(useLivenet: boolean, restInverseOptions: RestClientOptions): string;
export declare function getRestBaseUrl(useTestnet: boolean, restInverseOptions: RestClientOptions): string;
export declare function isWsPong(msg: any): boolean;
export declare const agentSource = "bybitapinode";
export declare const APIID = "bybitapinode";
/**

@@ -26,0 +30,0 @@ * Used to switch how authentication/requests work under the hood (primarily for SPOT since it's different there)

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.REST_CLIENT_TYPE_ENUM = exports.agentSource = exports.isWsPong = exports.getRestBaseUrl = exports.serializeParams = void 0;
exports.REST_CLIENT_TYPE_ENUM = exports.APIID = exports.isWsPong = exports.getRestBaseUrl = exports.serializeParams = void 0;
function serializeParams(params = {}, strict_validation = false) {

@@ -17,3 +17,3 @@ return Object.keys(params)

exports.serializeParams = serializeParams;
function getRestBaseUrl(useLivenet, restInverseOptions) {
function getRestBaseUrl(useTestnet, restInverseOptions) {
const exchangeBaseUrls = {

@@ -26,6 +26,6 @@ livenet: 'https://api.bybit.com',

}
if (useLivenet === true) {
return exchangeBaseUrls.livenet;
if (useTestnet) {
return exchangeBaseUrls.testnet;
}
return exchangeBaseUrls.testnet;
return exchangeBaseUrls.livenet;
}

@@ -43,2 +43,5 @@ exports.getRestBaseUrl = getRestBaseUrl;

}
if (msg['ret_msg'] === 'pong') {
return true;
}
return (msg.request &&

@@ -50,3 +53,3 @@ msg.request.op === 'ping' &&

exports.isWsPong = isWsPong;
exports.agentSource = 'bybitapinode';
exports.APIID = 'bybitapinode';
/**

@@ -53,0 +56,0 @@ * Used to switch how authentication/requests work under the hood (primarily for SPOT since it's different there)

@@ -9,3 +9,3 @@ import { APIMarket, WsKey } from '../types';

declare type PublicPrivateNetwork = 'public' | 'private';
export declare const WS_BASE_URL_MAP: Record<APIMarket, Record<PublicPrivateNetwork, NetworkMapV3>>;
export declare const WS_BASE_URL_MAP: Record<APIMarket | 'unifiedPerpUSDT' | 'unifiedPerpUSDC', Record<PublicPrivateNetwork, NetworkMapV3>>;
export declare const WS_KEY_MAP: {

@@ -23,2 +23,6 @@ readonly inverse: "inverse";

readonly usdcPerpPublic: "usdcPerpPublic";
readonly unifiedPrivate: "unifiedPrivate";
readonly unifiedOptionPublic: "unifiedOptionPublic";
readonly unifiedPerpUSDTPublic: "unifiedPerpUSDTPublic";
readonly unifiedPerpUSDCPublic: "unifiedPerpUSDCPublic";
};

@@ -25,0 +29,0 @@ export declare const WS_AUTH_ON_CONNECT_KEYS: WsKey[];

@@ -73,2 +73,42 @@ "use strict";

},
unifiedOption: {
public: {
livenet: 'wss://stream.bybit.com/option/usdc/public/v3',
testnet: 'wss://stream-testnet.bybit.com/option/usdc/public/v3',
},
private: {
livenet: 'wss://stream.bybit.com/unified/private/v3',
testnet: 'wss://stream-testnet.bybit.com/unified/private/v3',
},
},
unifiedPerp: {
public: {
livenet: 'useBaseSpecificEndpoint',
testnet: 'useBaseSpecificEndpoint',
},
private: {
livenet: 'wss://stream.bybit.com/unified/private/v3',
testnet: 'wss://stream-testnet.bybit.com/unified/private/v3',
},
},
unifiedPerpUSDT: {
public: {
livenet: 'wss://stream.bybit.com/contract/usdt/public/v3',
testnet: 'wss://stream-testnet.bybit.com/contract/usdt/public/v3',
},
private: {
livenet: 'useUnifiedEndpoint',
testnet: 'useUnifiedEndpoint',
},
},
unifiedPerpUSDC: {
public: {
livenet: 'wss://stream.bybit.com/contract/usdc/public/v3',
testnet: 'wss://stream-testnet.bybit.com/contract/usdc/public/v3',
},
private: {
livenet: 'useUnifiedEndpoint',
testnet: 'useUnifiedEndpoint',
},
},
};

@@ -87,2 +127,6 @@ exports.WS_KEY_MAP = {

usdcPerpPublic: 'usdcPerpPublic',
unifiedPrivate: 'unifiedPrivate',
unifiedOptionPublic: 'unifiedOptionPublic',
unifiedPerpUSDTPublic: 'unifiedPerpUSDTPublic',
unifiedPerpUSDCPublic: 'unifiedPerpUSDCPublic',
};

@@ -100,2 +144,5 @@ exports.WS_AUTH_ON_CONNECT_KEYS = [

exports.WS_KEY_MAP.usdcPerpPublic,
exports.WS_KEY_MAP.unifiedOptionPublic,
exports.WS_KEY_MAP.unifiedPerpUSDTPublic,
exports.WS_KEY_MAP.unifiedPerpUSDCPublic,
];

@@ -166,2 +213,20 @@ /** Used to automatically determine if a sub request should be to the public or private ws (when there's two) */

}
case 'unifiedOption': {
return isPrivateTopic
? exports.WS_KEY_MAP.unifiedPrivate
: exports.WS_KEY_MAP.unifiedOptionPublic;
}
case 'unifiedPerp': {
if (isPrivateTopic) {
return exports.WS_KEY_MAP.unifiedPrivate;
}
const upperTopic = topic.toUpperCase();
if (upperTopic.indexOf('USDT') !== -1) {
return exports.WS_KEY_MAP.unifiedPerpUSDTPublic;
}
if (upperTopic.indexOf('USDC') !== -1) {
return exports.WS_KEY_MAP.unifiedPerpUSDCPublic;
}
throw new Error(`Failed to determine wskey for unified perps topic: "${topic}`);
}
default: {

@@ -168,0 +233,0 @@ throw neverGuard(market, `getWsKeyForTopic(): Unhandled market`);

@@ -15,3 +15,3 @@ import WebSocket from 'isomorphic-ws';

* 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)
* TODO: do any WS topics allow parameters? If so, we need a way to track those (see 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.
*/

@@ -18,0 +18,0 @@ declare type WsTopicList = Set<WsTopic>;

@@ -6,4 +6,5 @@ /// <reference types="node" />

import { DefaultLogger } from './util';
export declare type WsClientEvent = 'open' | 'update' | 'close' | 'errorEvent' | 'reconnect' | 'reconnected' | 'response';
export declare type WsClientEvent = 'open' | 'update' | 'close' | 'error' | 'reconnect' | 'reconnected' | 'response';
interface WebsocketClientEvents {
/** Connection opened. If this connection was previously opened and reconnected, expect the reconnected event instead */
open: (evt: {

@@ -13,2 +14,3 @@ wsKey: WsKey;

}) => void;
/** Reconnecting a dropped connection */
reconnect: (evt: {

@@ -18,2 +20,3 @@ wsKey: WsKey;

}) => void;
/** Successfully reconnected a connection that dropped */
reconnected: (evt: {

@@ -23,2 +26,3 @@ wsKey: WsKey;

}) => void;
/** Connection closed */
close: (evt: {

@@ -28,5 +32,8 @@ wsKey: WsKey;

}) => void;
/** Received reply to websocket command (e.g. after subscribing to topics) */
response: (response: any) => void;
/** Received data for topic */
update: (response: any) => void;
errorEvent: (response: any) => void;
/** Exception from ws client OR custom listeners */
error: (response: any) => void;
}

@@ -50,4 +57,4 @@ export declare interface WebsocketClient {

isTestnet(): boolean;
close(wsKey: WsKey): void;
closeAll(): void;
close(wsKey: WsKey, force?: boolean): void;
closeAll(force?: boolean): void;
/**

@@ -57,3 +64,3 @@ * Request connection of all dependent (public & private) websockets, instead of waiting for automatic connection by library

connectAll(): Promise<WebSocket | undefined>[];
connectPublic(): Promise<WebSocket | undefined>;
connectPublic(): Promise<WebSocket | undefined>[];
connectPrivate(): Promise<WebSocket | undefined>;

@@ -60,0 +67,0 @@ private connect;

@@ -27,2 +27,3 @@ "use strict";

const usdc_perpetual_client_1 = require("./usdc-perpetual-client");
const unified_margin_client_1 = require("./unified-margin-client");
const loggerCategory = { category: 'bybit-ws' };

@@ -35,2 +36,3 @@ class WebsocketClient extends events_1.EventEmitter {

this.options = Object.assign({ testnet: false, pongTimeout: 1000, pingInterval: 10000, reconnectTimeout: 500, fetchTimeOffsetBeforeAuth: false }, options);
this.options.restOptions = Object.assign(Object.assign({}, this.options.restOptions), { testnet: this.options.testnet });
this.prepareRESTClient();

@@ -46,11 +48,11 @@ }

case 'inverse': {
this.restClient = new inverse_client_1.InverseClient(undefined, undefined, !this.isTestnet(), this.options.restOptions, this.options.requestOptions);
this.restClient = new inverse_client_1.InverseClient(this.options.restOptions, this.options.requestOptions);
break;
}
case 'linear': {
this.restClient = new linear_client_1.LinearClient(undefined, undefined, !this.isTestnet(), this.options.restOptions, this.options.requestOptions);
this.restClient = new linear_client_1.LinearClient(this.options.restOptions, this.options.requestOptions);
break;
}
case 'spot': {
this.restClient = new spot_client_1.SpotClient(undefined, undefined, !this.isTestnet(), this.options.restOptions, this.options.requestOptions);
this.restClient = new spot_client_1.SpotClient(this.options.restOptions, this.options.requestOptions);
this.connectPublic();

@@ -60,13 +62,18 @@ break;

case 'spotv3': {
this.restClient = new spot_client_v3_1.SpotClientV3(undefined, undefined, !this.isTestnet(), this.options.restOptions, this.options.requestOptions);
this.restClient = new spot_client_v3_1.SpotClientV3(this.options.restOptions, this.options.requestOptions);
break;
}
case 'usdcOption': {
this.restClient = new usdc_option_client_1.USDCOptionClient(undefined, undefined, !this.isTestnet(), this.options.restOptions, this.options.requestOptions);
this.restClient = new usdc_option_client_1.USDCOptionClient(this.options.restOptions, this.options.requestOptions);
break;
}
case 'usdcPerp': {
this.restClient = new usdc_perpetual_client_1.USDCPerpetualClient(undefined, undefined, !this.isTestnet(), this.options.restOptions, this.options.requestOptions);
this.restClient = new usdc_perpetual_client_1.USDCPerpetualClient(this.options.restOptions, this.options.requestOptions);
break;
}
case 'unifiedOption':
case 'unifiedPerp': {
this.restClient = new unified_margin_client_1.UnifiedMarginClient(this.options.restOptions, this.options.requestOptions);
break;
}
default: {

@@ -80,13 +87,16 @@ throw util_1.neverGuard(this.options.market, `prepareRESTClient(): Unhandled market`);

}
close(wsKey) {
var _a;
close(wsKey, force) {
this.logger.info('Closing connection', Object.assign(Object.assign({}, loggerCategory), { wsKey }));
this.setWsState(wsKey, util_1.WsConnectionStateEnum.CLOSING);
this.clearTimers(wsKey);
(_a = this.getWs(wsKey)) === null || _a === void 0 ? void 0 : _a.close();
const ws = this.getWs(wsKey);
ws === null || ws === void 0 ? void 0 : ws.close();
if (force) {
ws === null || ws === void 0 ? void 0 : ws.terminate();
}
}
closeAll() {
closeAll(force) {
const keys = this.wsStore.getKeys();
keys.forEach((key) => {
this.close(key);
this.close(key, force);
});

@@ -101,3 +111,3 @@ }

// only one for inverse
return [this.connectPublic()];
return [...this.connectPublic()];
}

@@ -109,4 +119,6 @@ // these all have separate public & private ws endpoints

case 'usdcOption':
case 'usdcPerp': {
return [this.connectPublic(), this.connectPrivate()];
case 'usdcPerp':
case 'unifiedPerp':
case 'unifiedOption': {
return [...this.connectPublic(), this.connectPrivate()];
}

@@ -121,19 +133,28 @@ default: {

case 'inverse': {
return this.connect(util_1.WS_KEY_MAP.inverse);
return [this.connect(util_1.WS_KEY_MAP.inverse)];
}
case 'linear': {
return this.connect(util_1.WS_KEY_MAP.linearPublic);
return [this.connect(util_1.WS_KEY_MAP.linearPublic)];
}
case 'spot': {
return this.connect(util_1.WS_KEY_MAP.spotPublic);
return [this.connect(util_1.WS_KEY_MAP.spotPublic)];
}
case 'spotv3': {
return this.connect(util_1.WS_KEY_MAP.spotV3Public);
return [this.connect(util_1.WS_KEY_MAP.spotV3Public)];
}
case 'usdcOption': {
return this.connect(util_1.WS_KEY_MAP.usdcOptionPublic);
return [this.connect(util_1.WS_KEY_MAP.usdcOptionPublic)];
}
case 'usdcPerp': {
return this.connect(util_1.WS_KEY_MAP.usdcPerpPublic);
return [this.connect(util_1.WS_KEY_MAP.usdcPerpPublic)];
}
case 'unifiedOption': {
return [this.connect(util_1.WS_KEY_MAP.unifiedOptionPublic)];
}
case 'unifiedPerp': {
return [
this.connect(util_1.WS_KEY_MAP.unifiedPerpUSDTPublic),
this.connect(util_1.WS_KEY_MAP.unifiedPerpUSDCPublic),
];
}
default: {

@@ -164,2 +185,6 @@ throw util_1.neverGuard(this.options.market, `connectPublic(): Unhandled market`);

}
case 'unifiedPerp':
case 'unifiedOption': {
return this.connect(util_1.WS_KEY_MAP.unifiedPrivate);
}
default: {

@@ -199,3 +224,3 @@ throw util_1.neverGuard(this.options.market, `connectPrivate(): Unhandled market`);

this.logger.error(`${context} due to unexpected error: `, error);
this.emit('errorEvent', error);
this.emit('error', error);
return;

@@ -208,6 +233,6 @@ }

default:
this.logger.error(`{context} due to unexpected response error: ${error.msg}`, Object.assign(Object.assign({}, loggerCategory), { wsKey }));
this.logger.error(`${context} due to unexpected response error: "${(error === null || error === void 0 ? void 0 : error.msg) || (error === null || error === void 0 ? void 0 : error.message) || error}"`, Object.assign(Object.assign({}, loggerCategory), { wsKey, error }));
break;
}
this.emit('errorEvent', error);
this.emit('error', error);
}

@@ -286,2 +311,5 @@ /**

ping(wsKey) {
if (this.wsStore.get(wsKey, true).activePongTimer) {
return;
}
this.clearPongTimer(wsKey);

@@ -293,3 +321,4 @@ this.logger.silly('Sending ping', Object.assign(Object.assign({}, loggerCategory), { wsKey }));

this.logger.info('Pong timeout - closing socket to reconnect', Object.assign(Object.assign({}, loggerCategory), { wsKey }));
(_a = this.getWs(wsKey)) === null || _a === void 0 ? void 0 : _a.close();
(_a = this.getWs(wsKey)) === null || _a === void 0 ? void 0 : _a.terminate();
delete this.wsStore.get(wsKey, true).activePongTimer;
}, this.options.pongTimeout);

@@ -405,3 +434,3 @@ }

const msg = JSON.parse((event && event.data) || event);
this.logger.silly('Received event', Object.assign(Object.assign({}, this.logger), { wsKey, msg: JSON.stringify(msg, null, 2) }));
this.logger.silly('Received event', Object.assign(Object.assign({}, loggerCategory), { wsKey, msg: JSON.stringify(msg) }));
// TODO: cleanme

@@ -413,3 +442,3 @@ if (msg['success'] || (msg === null || msg === void 0 ? void 0 : msg.pong) || util_1.isWsPong(msg)) {

else {
this.emit('response', msg);
this.emit('response', Object.assign(Object.assign({}, msg), { wsKey }));
}

@@ -419,6 +448,6 @@ return;

if (msg['finalFragment']) {
return this.emit('response', msg);
return this.emit('response', Object.assign(Object.assign({}, msg), { wsKey }));
}
if (msg === null || msg === void 0 ? void 0 : msg.topic) {
return this.emit('update', msg);
return this.emit('update', Object.assign(Object.assign({}, msg), { wsKey }));
}

@@ -432,3 +461,3 @@ if (

(msg === null || msg === void 0 ? void 0 : msg.success) === false) {
return this.emit('errorEvent', msg);
return this.emit('error', Object.assign(Object.assign({}, msg), { wsKey }));
}

@@ -445,5 +474,2 @@ this.logger.warning('Unhandled/unrecognised ws event message', Object.assign(Object.assign({}, loggerCategory), { message: msg, event,

this.parseWsError('Websocket error', error, wsKey);
if (this.wsStore.isConnectionState(wsKey, util_1.WsConnectionStateEnum.CONNECTED)) {
this.emit('errorEvent', error);
}
}

@@ -507,2 +533,14 @@ onWsClose(event, wsKey) {

}
case util_1.WS_KEY_MAP.unifiedOptionPublic: {
return util_1.WS_BASE_URL_MAP.unifiedOption.public[networkKey];
}
case util_1.WS_KEY_MAP.unifiedPerpUSDTPublic: {
return util_1.WS_BASE_URL_MAP.unifiedPerpUSDT.public[networkKey];
}
case util_1.WS_KEY_MAP.unifiedPerpUSDCPublic: {
return util_1.WS_BASE_URL_MAP.unifiedPerpUSDC.public[networkKey];
}
case util_1.WS_KEY_MAP.unifiedPrivate: {
return util_1.WS_BASE_URL_MAP.unifiedPerp.private[networkKey];
}
default: {

@@ -529,3 +567,5 @@ this.logger.error('getWsUrl(): Unhandled wsKey: ', Object.assign(Object.assign({}, loggerCategory), { wsKey }));

if (this.wsStore.isConnectionState(wsKey, util_1.WsConnectionStateEnum.CONNECTED)) {
return this.requestSubscribeTopics(wsKey, topics);
return this.requestSubscribeTopics(wsKey, [
...this.wsStore.getTopics(wsKey),
]);
}

@@ -550,3 +590,5 @@ // start connection process if it hasn't yet begun. Topics are automatically subscribed to on-connect

if (this.wsStore.isConnectionState(wsKey, util_1.WsConnectionStateEnum.CONNECTED)) {
this.requestUnsubscribeTopics(wsKey, topics);
this.requestUnsubscribeTopics(wsKey, [
...this.wsStore.getTopics(wsKey),
]);
}

@@ -553,0 +595,0 @@ });

{
"name": "bybit-api",
"version": "2.4.0-beta.2",
"description": "Node.js connector for Bybit's REST APIs and WebSockets, with TypeScript & integration tests.",
"version": "3.0.1",
"description": "Complete & robust node.js SDK for Bybit's REST APIs and WebSockets, with TypeScript & integration tests.",
"main": "lib/index.js",

@@ -6,0 +6,0 @@ "types": "lib/index.d.ts",

@@ -1,2 +0,2 @@

# bybit-api
# Node.js & Typescript Bybit API SDK
[![Tests](https://circleci.com/gh/tiagosiebler/bybit-api.svg?style=shield)](https://circleci.com/gh/tiagosiebler/bybit-api)

@@ -42,9 +42,9 @@ [![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]

## Structure
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).
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).
This connector is fully compatible with both TypeScript and pure JavaScript projects. The version on npm is the output from the `build` command and can be used in projects without TypeScript (although TypeScript is definitely recommended).
The version on npm is the output from the `build` command and can be used in projects without TypeScript (although TypeScript is definitely recommended).
- [src](./src) - the whole connector written in TypeScript
- [lib](./lib) - the JavaScript version of the project (built from TypeScript). This should not be edited directly, as it will be overwritten with each release.
- [dist](./dist) - the web-packed bundle of the project for use in browser environments.
- [dist](./dist) - the webpack bundle of the project for use in browser environments (see guidance on webpack below).
- [examples](./examples) - some implementation examples & demonstrations. Contributions are welcome!

@@ -61,4 +61,4 @@

| [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) |
| [UnifiedMarginClient](src/unified-margin-client.ts) | [Derivatives (v3) unified margin APIs](https://bybit-exchange.github.io/docs/derivativesV3/unified_margin/#t-introduction) |
| [USDCOptionClient](src/usdc-option-client.ts) | [USDC Option APIs](https://bybit-exchange.github.io/docs/usdc/option/#t-introduction) |
| [SpotClientV3](src/spot-client-v3.ts) | [Spot Market (v3) APIs](https://bybit-exchange.github.io/docs/spot/v3/#t-introduction) |

@@ -85,3 +85,3 @@ | [~SpotClient~](src/spot-client.ts) (deprecated, v3 client recommended)| [Spot Market (v1) APIs](https://bybit-exchange.github.io/docs/spot/v1/#t-introduction) |

```javascript
```typescript
const {

@@ -92,27 +92,39 @@ InverseClient,

SpotClient,
SpotClient3,
SpotClientV3,
UnifiedMarginClient,
USDCOptionClient,
USDCPerpetualClient,
AccountAssetClient,
CopyTradingClient,
AccountAssetClient,
} = require('bybit-api');
const restClientOptions = {
// override the max size of the request window (in ms)
/** Your API key. Optional, if you plan on making private api calls */
key?: string;
/** Your API secret. Optional, if you plan on making private api calls */
secret?: string;
/** Set to `true` to connect to testnet. Uses the live environment by default. */
testnet?: boolean;
/** Override the max size of the request window (in ms) */
recv_window?: number;
// how often to sync time drift with bybit servers
sync_interval_ms?: number;
// Default: false. Disable above sync mechanism if true.
/** Disabled by default. This can help on machines with consistent latency problems. */
enable_time_sync?: boolean;
// Default: false. If true, we'll throw errors if any params are undefined
/** How often to sync time drift with bybit servers */
sync_interval_ms?: number | string;
/** Default: false. If true, we'll throw errors if any params are undefined */
strict_param_validation?: boolean;
// Optionally override API protocol + domain
// e.g 'https://api.bytick.com'
/**
* Optionally override API protocol + domain
* e.g baseUrl: 'https://api.bytick.com'
**/
baseUrl?: string;
// Default: true. whether to try and post-process request exceptions.
/** Default: true. whether to try and post-process request exceptions. */
parse_exceptions?: boolean;

@@ -122,16 +134,16 @@ };

const API_KEY = 'xxx';
const PRIVATE_KEY = 'yyy';
const useLivenet = false;
const API_SECRET = 'yyy';
const useTestnet = false;
const client = new InverseClient(
API_KEY,
PRIVATE_KEY,
// optional, uses testnet by default. Set to 'true' to use livenet.
useLivenet,
// restClientOptions,
const client = new InverseClient({
key: API_KEY,
secret: API_SECRET,
testnet: useTestnet
},
// requestLibraryOptions
);
// For public-only API calls, simply don't provide a key & secret or set them to undefined
// const client = new InverseClient({});
client.getApiKeyInfo()

@@ -155,3 +167,3 @@ .then(result => {

## WebSockets
All API groups can be used via a shared `WebsocketClient`. However, make sure to make one instance of the WebsocketClient per API group (spot vs inverse vs linear vs linearfutures etc):
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.

@@ -161,3 +173,4 @@ The WebsocketClient can be configured to a specific API group using the market parameter. These are the currently available API groups:

|:----------------------------: |:-------------------: |-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Unified Margin | TBC | The [derivatives v3](https://bybit-exchange.github.io/docs/derivativesV3/unified_margin/#t-websocket) category for unified margin. |
| Unified Margin - Options | `market: 'unifiedOption'`| The [derivatives v3](https://bybit-exchange.github.io/docs/derivativesV3/unified_margin/#t-websocket) category for unified margin. Note: public topics only support options topics. If you need USDC/USDT perps, use `unifiedPerp` instead. |
| Unified Margin - Perps | `market: 'unifiedPerp'` | The [derivatives v3](https://bybit-exchange.github.io/docs/derivativesV3/unified_margin/#t-websocket) category for unified margin. Note: public topics only support USDT/USDC perpetual topics - use `unifiedOption` if you need public options topics. |
| Futures v2 - Inverse Perps | `market: 'inverse'` | The [inverse v2 perps](https://bybit-exchange.github.io/docs/futuresV2/inverse/#t-websocket) category. |

@@ -168,5 +181,5 @@ | Futures v2 - USDT Perps | `market: 'linear'` | The [USDT/linear v2 perps](https://bybit-exchange.github.io/docs/futuresV2/linear/#t-websocket) category. |

| Spot v1 | `market: 'spot'` | The older [spot v1](https://bybit-exchange.github.io/docs/spot/v1/#t-websocket) category. Use the `spotv3` market if possible, as the v1 category does not have automatic re-subscribe if reconnected. |
| Copy Trading | `market: 'linear'` | The [copy trading](https://bybit-exchange.github.io/docs/copy_trading/#t-websocket) category. Use the linear market to listen to all copy trading topics. |
| USDC Perps | TBC | The [USDC perps](https://bybit-exchange.github.io/docs/usdc/perpetual/#t-websocket) category. |
| USDC Options | TBC | The [USDC options](https://bybit-exchange.github.io/docs/usdc/option/#t-websocket) category. |
| Copy Trading | `market: 'linear'` | The [copy trading](https://bybit-exchange.github.io/docs/copy_trading/#t-websocket) category. Use the linear market to listen to all copy trading topics. |
| USDC Perps | `market: 'usdcPerp` | The [USDC perps](https://bybit-exchange.github.io/docs/usdc/perpetual/#t-websocket) category. |
| USDC Options | `market: 'usdcOption'`| The [USDC options](https://bybit-exchange.github.io/docs/usdc/option/#t-websocket) category. |

@@ -187,11 +200,15 @@ ```javascript

// defaults to false == testnet. Set to true for livenet.
// livenet: true
// defaults to true == livenet
// testnet: false
// NOTE: to listen to multiple markets (spot vs inverse vs linear vs linearfutures) at once, make one WebsocketClient instance per market
// defaults to inverse:
// market: 'inverse'
// market: 'linear'
// market: 'spot'
market: 'linear',
// market: 'inverse',
// market: 'spot',
// market: 'spotv3',
// market: 'usdcOption',
// market: 'usdcPerp',
// market: 'unifiedPerp',
// market: 'unifiedOption',

@@ -245,6 +262,5 @@ // how long to wait (in ms) before deciding the connection should be terminated & reconnected

// Optional: Listen to raw error events.
// Note: responses to invalid topics are currently only sent in the "response" event.
// Optional: Listen to raw error events. Recommended.
ws.on('error', err => {
console.error('ERR', err);
console.error('error', err);
});

@@ -264,7 +280,10 @@ ```

// Disable all logging on the silly level
DefaultLogger.silly = () => {};
const customLogger = {
...DefaultLogger,
silly: () => {},
};
const ws = new WebsocketClient(
{ key: 'xxx', secret: 'yyy' },
DefaultLogger
customLogger
);

@@ -271,0 +290,0 @@ ```

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc