Git Product home page Git Product logo

bybit-api's Introduction

Node.js & JavaScript SDK for Bybit REST API & WebSockets

Build & Test npm version npm size npm downloads last commit CodeFactor Telegram

SDK Logo

Node.js & JavaScript SDK for the Bybit REST APIs and WebSockets:

  • Complete integration with all Bybit REST APIs & WebSockets.
  • Actively maintained with a modern, promise-driven interface.
  • TypeScript support (with type declarations for most API requests & responses).
  • Over 450 end-to-end tests making real API calls & WebSocket connections, validating any changes before they reach npm.
  • Robust WebSocket integration with configurable connection heartbeats & automatic reconnect then resubscribe workflows.
    • Event driven messaging.
    • Smart websocket persistence
      • Automatically handle silent websocket disconnections through timed heartbeats, including the scheduled 24hr disconnect.
      • Automatically handle listenKey persistence and expiration/refresh.
      • Emit reconnected event when dropped connection is restored.
  • Proxy support via axios integration.
  • Active community support & collaboration in telegram: Node.js Algo Traders.

Installation

npm install --save bybit-api

Issues & Discussion

Related projects

Check out my related JavaScript/TypeScript/Node.js projects:

Documentation

Most methods accept JS objects. These can be populated using parameters specified by Bybit's API documentation, or check the type definition in each class within the github repository (see table below for convenient links to each class).

Structure

This connector is fully compatible with both TypeScript and pure JavaScript projects, while the connector is written in TypeScript. A pure JavaScript version can be built using npm run build, which is also the version published to npm.

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 - the whole connector written in TypeScript
  • lib - the JavaScript version of the project (built from TypeScript). This should not be edited directly, as it will be overwritten with each release.
  • examples - examples & demonstrations. Contributions are welcome!

REST API Clients

Bybit has several API groups (originally one per product). Each generation is labelled with the version number (e.g. v1/v2/v3/v5). New projects & developments should use the newest available API generation (e.g. use the V5 APIs instead of V3).

Refer to the V5 interface mapping page for more information on which V5 endpoints can be used instead of previous V3 endpoints.

Here are the available REST clients and the corresponding API groups described in the documentation:

Class Description
[ V5 API ] The new unified V5 APIs (successor to previously fragmented APIs for all API groups). To learn more about the V5 API, please read the V5 upgrade guideline.
RestClientV5 Unified V5 all-in-one REST client for all V5 REST APIs
WebsocketClient All WebSocket Events (Public & Private for all API categories)
[ Derivatives v3 ] The Derivatives v3 APIs (successor to the Futures V2 APIs)
UnifiedMarginClient Derivatives (v3) Unified Margin APIs
ContractClient Derivatives (v3) Contract APIs.
[ Other ] Other standalone API groups
CopyTradingClient Copy Trading APIs
AccountAssetClientV3 Account Asset V3 APIs

Deprecated/Obsolete APIs

The following API clients are for previous generation REST APIs and will be removed in the next major release. Some have already stopped working (because bybit stopped supporting them). You should use the V5 APIs for all new development.

Click me to see the list of APIs
Class Description
[ Futures v2 ] The Futures v2 APIs
InverseClient Inverse Perpetual Futures (v2) APIs
LinearClient USDT Perpetual Futures (v2) APIs
InverseFuturesClient Inverse Futures (v2) APIs
[ Spot ] The spot APIs
SpotClientV3 Spot Market (v3) APIs
SpotClient (deprecated, SpotClientV3 recommended) Spot Market (v1) APIs
[ USDC Contract ] The USDC Contract APIs
USDCPerpetualClient USDC Perpetual APIs
USDCOptionClient USDC Option APIs
AccountAssetClient (deprecated, AccountAssetClientV3 recommended) Account Asset V1 APIs

Examples for using each client can be found in:

If you're missing an example, you're welcome to request one. Priority will be given to github sponsors.

Usage

Create API credentials on Bybit's website:

All REST clients have can be used in a similar way. However, method names, parameters and responses may vary depending on the API category you're using!

Not sure which function to call or which parameters to use? Click the class name in the table above to look at all the function names (they are in the same order as the official API docs), and check the API docs for a list of endpoints/parameters/responses.

The following is a minimal example for using the REST clients included with this SDK. For more detailed examples, refer to the examples folder in the repository on GitHub:

const {
  InverseClient,
  LinearClient,
  InverseFuturesClient,
  SpotClientV3,
  UnifiedMarginClient,
  USDCOptionClient,
  USDCPerpetualClient,
  AccountAssetClient,
  CopyTradingClient,
  RestClientV5,
} = require('bybit-api');

const restClientOptions = {
  /** 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;

  /** Default: false. If true, we'll throw errors if any params are undefined */
  strict_param_validation?: boolean;

  /**
   * Optionally override API protocol + domain
   * e.g baseUrl: 'https://api.bytick.com'
   **/
  baseUrl?: string;

  /** Default: true. whether to try and post-process request exceptions. */
  parse_exceptions?: boolean;

  /** Default: false. Enable to parse/include per-API/endpoint rate limits in responses. */
  parseAPIRateLimits?: boolean;

  /** Default: false. Enable to throw error if rate limit parser fails */
  throwOnFailedRateLimitParse?: boolean;
};

const API_KEY = 'xxx';
const API_SECRET = 'yyy';
const useTestnet = false;

const client = new RestClientV5({
  key: API_KEY,
  secret: API_SECRET,
  testnet: useTestnet,
  // Optional: enable to try parsing rate limit values from responses
  // parseAPIRateLimits: true
},
  // requestLibraryOptions
);

// For public-only API calls, simply don't provide a key & secret or set them to undefined
// const client = new RestClientV5({});

client.getAccountInfo()
  .then(result => {
    console.log("getAccountInfo result: ", result);
  })
  .catch(err => {
    console.error("getAccountInfo error: ", err);
  });

client.getOrderbook({ category: 'linear', symbol: 'BTCUSD' })
  .then(result => {
    console.log("getOrderBook result: ", result);
  })
  .catch(err => {
    console.error("getOrderBook error: ", err);
  });

WebSockets

All API groups can be used via a shared WebsocketClient. However, to listen to multiple API groups at once, you will need to make one WebsocketClient instance per API group.

The WebsocketClient can be configured to a specific API group using the market parameter. These are the currently available API groups:

API Category Market Description
V5 Subscriptions market: 'v5' The v5 websocket topics for all categories under one market. Use the subscribeV5 method when subscribing to v5 topics.

Older Websocket APIs

The following API groups are still available in the WebsocketClient but are deprecated and may no longer work. They will be removed in the next major release:

Click me to see the table
API Category Market Description
Unified Margin - Options market: 'unifiedOption' The derivatives v3 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 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 category.
Futures v2 - USDT Perps market: 'linear' The USDT/linear v2 perps category.
Futures v2 - Inverse Futures market: 'inverse' The inverse futures v2 category uses the same market as inverse perps.
Spot v3 market: 'spotv3' The spot v3 category.
Spot v1 market: 'spot' The older spot v1 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 category. Use the linear market to listen to all copy trading topics.
USDC Perps market: 'usdcPerp The USDC perps category.
USDC Options market: 'usdcOption' The USDC options category.
Contract v3 USDT market: 'contractUSDT' The Contract V3 category (USDT perps)
Contract v3 Inverse market: 'contractInverse' The Contract V3 category (inverse perps)

WebSocket Examples

Here's a minimal example for using the websocket client. For more complete examples, look into the ws-* examples in the examples folder in the repo on GitHub.

const { WebsocketClient } = require('bybit-api');

const API_KEY = 'xxx';
const PRIVATE_KEY = 'yyy';

const wsConfig = {
  key: API_KEY,
  secret: PRIVATE_KEY,

  /*
    The following parameters are optional:
  */

  // Connects to livenet by default. Set testnet to true to use the testnet environment.
  // testnet: true

  // If you can, use the v5 market (the newest generation of Bybit's websockets)
  market: 'v5',

  // how long to wait (in ms) before deciding the connection should be terminated & reconnected
  // pongTimeout: 1000,

  // how often to check (in ms) that WS connection is still alive
  // pingInterval: 10000,

  // how long to wait before attempting to reconnect (in ms) after connection is closed
  // reconnectTimeout: 500,

  // recv window size for authenticated websocket requests (higher latency connections (VPN) can cause authentication to fail if the recv window is too small)
  // recvWindow: 5000,

  // config options sent to RestClient (used for time sync). See RestClient docs.
  // restOptions: { },

  // config for axios used for HTTP requests. E.g for proxy support
  // requestOptions: { }

  // override which URL to use for websocket connections
  // wsUrl: 'wss://stream.bytick.com/realtime'
};

const ws = new WebsocketClient(wsConfig);

// (before v5) subscribe to multiple topics at once
ws.subscribe(['position', 'execution', 'trade']);

// (before v5) and/or subscribe to individual topics on demand
ws.subscribe('kline.BTCUSD.1m');

// (v5) subscribe to multiple topics at once
ws.subscribeV5(['orderbook.50.BTCUSDT', 'orderbook.50.ETHUSDT'], 'linear');

// (v5) and/or subscribe to individual topics on demand
ws.subscribeV5('position', 'linear');
ws.subscribeV5('publicTrade.BTC', 'option');

// Listen to events coming from websockets. This is the primary data source
ws.on('update', (data) => {
  console.log('update', data);
});

// Optional: Listen to websocket connection open event (automatic after subscribing to one or more topics)
ws.on('open', ({ wsKey, event }) => {
  console.log('connection open for websocket with ID: ' + wsKey);
});

// Optional: Listen to responses to websocket queries (e.g. the response after subscribing to a topic)
ws.on('response', (response) => {
  console.log('response', response);
});

// Optional: Listen to connection close event. Unexpected connection closes are automatically reconnected.
ws.on('close', () => {
  console.log('connection closed');
});

// Optional: Listen to raw error events. Recommended.
ws.on('error', (err) => {
  console.error('error', err);
});

See websocket-client.ts for further information.


Logging

Customise logging

Pass a custom logger (or mutate the imported DefaultLogger class) which supports the log methods silly, debug, notice, info, warning and error, or override methods from the default logger as desired, as in the example below:

const { WebsocketClient, DefaultLogger } = require('bybit-api');

// Disable all logging on the silly level
const customLogger = {
  ...DefaultLogger,
  silly: () => {},
};

const ws = new WebsocketClient({ key: 'xxx', secret: 'yyy' }, customLogger);

Debug HTTP requests

In rare situations, you may want to see the raw HTTP requets being built as well as the API response. These can be enabled by setting the BYBITTRACE env var to true.

Browser Usage

Import

This is the "modern" way, allowing the package to be directly imported into frontend projects with full typescript support.

  1. Install these dependencies
    npm install crypto-browserify stream-browserify
  2. Add this to your tsconfig.json
    {
      "compilerOptions": {
        "paths": {
          "crypto": [
            "./node_modules/crypto-browserify"
          ],
          "stream": [
            "./node_modules/stream-browserify"
          ]
    }
  3. Declare this in the global context of your application (ex: in polyfills for angular)
    (window as any).global = window;

Webpack

This is the "old" way of using this package on webpages. This will build a minified js bundle that can be pulled in using a script tag on a website.

Build a bundle using webpack:

  • npm install
  • npm build
  • npm pack

The bundle can be found in dist/. Altough usage should be largely consistent, smaller differences will exist. Documentation is still TODO - contributions welcome.


Contributions & Thanks

Donations

tiagosiebler

Have my projects helped you? Share the love, there are many ways you can show your thanks:

  • Star & share my projects.
  • Are my projects useful? Sponsor me on Github and support my effort to maintain & improve them: https://github.com/sponsors/tiagosiebler
  • Have an interesting project? Get in touch & invite me to it.
  • Or buy me all the coffee:
    • ETH(ERC20): 0xA3Bda8BecaB4DCdA539Dc16F9C54a592553Be06C

For more ways to give thanks & support my efforts, visit Contributions & Thanks!

pixtron

An early generation of this library was started by @pixtron. If this library helps you to trade better on bybit, feel free to donate a coffee to @pixtron:

  • BTC 1Fh1158pXXudfM6ZrPJJMR7Y5SgZUz4EdF
  • ETH 0x21aEdeC53ab7593b77C9558942f0c9E78131e8d7
  • LTC LNdHSVtG6UWsriMYLJR3qLdfVNKwJ6GSLF

Contributions & Pull Requests

Contributions are encouraged, I will review any incoming pull requests. See the issues tab for todo items.

Star History

Star History Chart

bybit-api's People

Contributors

battlefieldduck avatar beppu avatar blake41 avatar caius-citiriga-zupit avatar caiuscitiriga avatar code-factor avatar crashdebug avatar dependabot-preview[bot] avatar dependabot[bot] avatar ericcrosson avatar jj-cro avatar justmankus avatar karimsan avatar keith30xi avatar mlake avatar mnjongen avatar peepo5 avatar pixtron avatar pranaypratyush avatar qbkjovfnek avatar t0chk avatar thijmau avatar tiagosiebler avatar tindtily avatar twxia avatar will2022 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

bybit-api's Issues

Verify all possible parameters are sent in POST body, keeping querystring usage minimal

Pretty sure order ID etc shouldn't be in query string, but instead as post body.

{
  "ret_code": 10004,
  "ext_code": "",
  "result": null,
  "ext_info": null,
  "time_now": "1599924774.101266",
  "message": "error sign! origin_string[api_key=xxxxxxxxxx&order_id=5e9b4517-860d-4c60-b797-825afed28ff2&p_r_price=10369.5&p_r_qty=&recv_window=15000&symbol=BTCUSD&timestamp=1599924773483]"
}

Struggling with linear WS: handler not found

Hello!

I'm trying to connect to WS for Kline data but I'm getting this error all the time.

I just followed the "examples" folder but it doesn't work for me.

This is an screenshot of the error log

image

Anyone can help me?

Bybit WSOT | World Series of Trading | Official Team

Hello everyone, hope you're enjoying my connectors. For this year's Bybit WSOT I have made a node algo trader squad.

Join the team through this link:
https://bybit.com/en-US/wsot2022/squad-race/?team_id=248&ref=MZNZO1

Join our highly professional node.js algorithmic trader engineering community on telegram, mingle with colleagues, institutions and key exchange contacts:
https://t.me/nodetraders

The competition starts in a little over 16 days from this post. Good luck!

bybit-share

Verify recv_window logic

server_time - recv_window <= timestamp < server_time + 1000; server_time stands for Bybit server time, you can get it from Server Time endpoint

{
  "ret_code": 10002,
  "ret_msg": "invalid request, please check your timestamp and recv_window param. req_timestamp: 1595314750121 server_timestamp: 1595314742549 recv_window: 15000",
  "ext_code": "",
  "ext_info": "",
  "result": null,
  "time_now": "1595314742.549034",
  "message": "invalid request, please check your timestamp and recv_window param. req_timestamp: 1595314750121 server_timestamp: 1595314742549 recv_window: 15000"
}

we need to add function for linear-client.ts

image

It exsits ' private/linear/tpsl/switch-mode' function.

But there no function '/private/linear/position/switch-mode' for Position Mode Switch

==>

setSwitchMode(params) {
return this.requestWrapper.post('private/linear/tpsl/switch-mode', params);
}

setPositionSwitchMode(params) {
return this.requestWrapper.post('private/linear/position/switch-mode', params);
}

Support linear contracts

Explore plans to support linear contracts for bybit. The linear APIs may have differences to the inverse APIs, but there should be reusable logic:
https://bybit-exchange.github.io/docs/linear/#t-introduction

Proposals

These are in no particular order:

1. Introduce dedicated linear-client.js

See beppu's post below:

  • Separate lib/linear-client.js dedicated to linear contracts, very similar to lib/rest-client.js.
  • No impact on existing implementation.
  • Requires implementation responsibility on which client to use. Likely to see user error (USDT not working with rest-client).

2. Expand existing rest-client.js for automatic handling

  • Instead of a new "opt-in" module, automatically detect which API to use depending on function params.
  • (!) High risk to accidentally affect existing integrations (bugs & upgrade pain).
  • Less likely to see user errors (user doesn't need to worry that linear uses diff APIs).

3. Introduce new rest-clientv2.js for automatic handling

  • Successor to rest-client.
  • Name could be more intuitive than rest-clientv2.js. TBC.
  • No impact on existing implementation (for some time still support rest-client with deprecation warning).
  • Less likely to see user errors, as with 2.

4. inverse-client vs linear-client vs rest-clientv2

  • These are as similar as possible.
  • rest-client will remain for a while, albeit deprecated.
  • Shared parameters from the current rest-client (such as endpoints) could be taken from a separate module, to reduce repetition.
  • Implementations could use either the specific client like (1) or the general rest-clientv2, which works like (3).

recv_window timing issue after updating to 2.2.0 2.1.10

After updating to 2.2.0 I receive a timing issue and am unable to authenticate.
Reverting back to 2.1.10 makes this problem go away.

On 2.2.0 when doing a getApiKeyInfo:

getApiKeyInfo {
  ret_code: 10002,
  ret_msg: 'invalid request, please check your timestamp and recv_window param. req_timestamp: 1653737893 server_timestamp: 1653737454742 recv_window: 5000',
  ext_code: '',
  ext_info: '',
  result: null,
  time_now: '1653737454.742912'
}

I can prevent this error by passing restOptions: { disable_time_sync: true }
I think the websocket connection suffers from the same core issue and gives an auth error:

Websocket error due to 401 authorization failure. { category: 'bybit-ws', wsKey: 'linearPrivate' }

It looks like the server timestamp is in milliseconds and the local timestamp in seconds, could this be the problem ?

Bulky LIMIT ORDERS

does this api offers placing bulky limit order, I want to place 5 limit orders at once and 1 buy order through a POST endpoint, but am getting params error on some of the orders, and some orders are placed, my endpoint only receive one set of data only the price changes each time, when testing my endpoint locally all orders are submitted without issues but on the server i get params error

params error!

i try to place order, but get error:

{ ret_code: 10001, ret_msg: 'params error!', ext_code: '', ext_info: '', result: null, time_now: '1647448210.677814' }

what did i do wrong?
my code

const { InverseFuturesClient } = require('bybit-api');
const API_KEY = '---';
const PRIVATE_KEY = '---';
const useLivenet = false;
const client = new InverseFuturesClient(
  API_KEY,
  PRIVATE_KEY,
  useLivenet,
);
run();
async function run(){
     const marketQty = parseInt(1);
     const params = {
      side: 'Sell',
      symbol: "SOLUSDT",
      order_type: 'Market',
      qty: marketQty,
      time_in_force: 'GoodTillCancel',
    }
    console.log(await client.placeActiveOrder(params));
}

Unhandled promise at websocket client

webcocket-client.js: 7
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }

missing .catch, which is being a reason of throwing error

Code Error -2015 on valid API KEY

Hi !

I started to play and when I try to get my Spot Balance by using my API Key and Secret (and I know that they're valid as I used in parallel the same key for python and also works on another library JS), I always get the following error :

Error :

getBalances result: {
ret_code: -2015,
ret_msg: 'Invalid API-key, IP, or permissions for action.',
ext_code: null,
ext_info: null,
result: null
}

My Code :
`const { SpotClient } = require("bybit-api");

const API_KEY = "myKey"; // Of course I change with the correct one
const PRIVATE_KEY = "myPrivateKey"; // Of course I change with the correct one
const useLivenet = false;

const client = new SpotClient(
API_KEY,
PRIVATE_KEY,
useLivenet
);

client
.getBalances()
.then((result) => {
console.log("getBalances result: ", result);
})
.catch((err) => {
console.error("getBalances error: ", err);
});
`

The error is the same with Inverse, InverseFutures, etc. The test with another lib ('ccxt') is working well on the same machine
Any ideas ?

Thanks a lot for your work !

Get "Missing required parameter 'symbol'" when calling spot submit order

My code as below, I am pretty sure I have all the required params in place.
let newOrder = await client.submitOrder({ symbol: "BTCUSDT", qty: 1000, side: "Buy", type: "LIMIT", timeInForce: "IOC", price: 2.22, });

The response return from bybit api
{ ret_code: -1004, ret_msg: "Missing required parameter 'symbol'", ext_code: null, ext_info: null, result: null }

Improve param types for API calls

While many param types are best left as generics (e.g symbols), there's plenty that would be useful to have clearer types. Dakota already started with a ton of type declarations in #22.

Example:
https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client.ts#L157

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;
    close_on_trigger?: boolean;
    order_link_id?: string;
  })

order_type could be a more specific union type instead of just string:

type OrderType = 'Limit' | 'Market';
...

placeActiveOrder(orderRequest: {
  ...
  order_type: OrderType;
})

Would be great to get these implemented, even if gradually in smaller PRs.

Introduce CI Tests

This library has no test coverage, which can pose problems in the future. It's important to start that asap. What route should we take? Unit tests? Request mocking? Integration tests?

Question: Why is command line still open after closing websocket connection?

Question: Why is command line still open after closing websocket connection?

const wsConfig = {
    key: userExchange.apiKey,
    secret: userExchange.privateKey,
};

const ws = new WebsocketClient(wsConfig)
ws.subscribe('kline.BTCUSD.1s');

ws.on('open',({wsKey, event}) => {
    wsKey = wsKey;
    console.log('connection open for websocket with ID: ' + wsKey);
})

ws.on('update', data => {
    console.log('update', data);
});

ws.on('close', () => {
    console.log('connection closed');
  });

setTimeout(() => {
    console.log('closing', 'inverse')
    ws.close('inverse');
}, 3000)

Command line is still open? - https://prnt.sc/23uyvmd

Bybit API & CORS

Apologies if this is a stupid question. I'm trying to run the bybit-api module in my browser. I'm using a CORS extension in chrome to allow CORS request from any origin but keep getting a CORS issue when I try and use the bybit-api library. I can make requests directly myself when I hit the actual bybit api manually with an axios get request in a JS script so I'm not sure why axios in bybit-api is not being allowed to make CORS requests

Margin Switch

Please add feature for Switching margin mode (Cross, Isolated)
Testnet's API working perfect, but real API always returns 404

Security

My apologies if this question is inappropriate or misplaced but I was wondering how, other than reading every line of code throughout the entire project, one can determine that this npm package is safe to use?

What I mean is, since you have to provide you API_KEY and API_SECRET to interact with your bybit account, could this package not include some code somewhere that would send my private API information to someone, allowing them to interact with my bybit account?

This seems to be a pretty cool package and I am trying it out as I'm writing this and it works great :D! But as one should be, I am cautious when dealing with my private API informations from bybit

How do I calculate qty in USDT Perpetual with leverage

First of all, amazing library.

I'm creating a conditional order but don't know how do I calculate quantity. Is it based on leveraged amount or original?

for example

I have balance of 50 USDT and want to use 100% per trade with following conditions.

BTC at price 44,089.50 with 50x leverage.
SHIB at price 0.030810 with 50x leverage.

How do I calculate the qty parameter?

No wallet methods?

Hello!

Thanks a lot for the package, it's really useful!

I was wondering, there is no method to fetch the wallet balance (nor any methods related to the wallet), is that on purpose?

getClosedPnl

Using getClosedPnl it throws an 404.

Looking at the code on linear-client its set as:

return this.requestWrapper.get('private/linear/tpsl/switch-mode', params);

changing to

return this.requestWrapper.get('/private/linear/trade/closed-pnl/list', params);

It works.

Its a bug or I am getting something wrong?

SpotClient.getServerTime returns undefined

Hi, thanks for the package! I noticed that SpotClient.getServerTime returns undefined. I think in spot-client.js

            const result = yield this.get('/spot/v1/time');
            return result.serverTime;

the line
return result.serverTime;
should be replaced with
return result.result.serverTime;
because the endpoint https://api.bybit.com/spot/v1/time returns an object like this one

{
   "ret_code":0,
   "ret_msg":"",
   "ext_code":null,
   "ext_info":null,
   "result":{
      "serverTime":1651155074458
   }
}

Seems like an easy PR, but I can't do it right now, so I'll post instead

When is public/time called & other shenanigans

Hi there,
I run a scaled app with many clients across a small group of IPs.
For a long while now i have had intermittent issues with bybit banning my IPs. I have worked with their support on this issue over the course of nearly a year. It only seems to happen once in a while, and when it does its really hard to get it to calm down or stop forcing us to abandon an IP for a new one and obviously this looks terrible on my end.

All the issues stem from api access behavior. Specifically repetitive calls to /public/time
I have confirmed with bybit that i never hit any of their rate limits, and they are solely upset with me over these repetitive calls which can reach up to 3.8 million calls in a few hours.

I use ccxt and Ive gone up and down with the developer over there trying to figure out why public/time would being called. There was actually at first an option I had on to sync time, which caused the endpoint to be called preceeding any call ccxt made to bybit. I have since turned this option off, and confirmed multiple times locally and on the production environment that the option is off. Where i did used to see evidence of ccxt calling that endpoint, I no longer do.

It just occurred to me today that I use this library for bybit websockets. Its the only websocket implementation i have right now, and its the only thing else that connects to bybit. I also strictly use this for websockets only. So I was wondering if perhaps this library calls public/time?

I have equipped xray trace logging just for this specific issue and I have found evidence that even today it is still calling public/time.
On a server which is not banned, during normal service it doesnt seem to call it very often.
On a server which is banned, its calling it constantly.

I also read in another thread here that someone else had an issue with sync time and that setting it to a really high timeframe (7 days for him) fixed the problem of it dropping. I also noticed in your reply you said the drops seem to happen at a certain time during the night. Im -5 UTC so idk if my night is the same as your night- but i have also noticed that if it does break once every few months it happens literally hours after i go to bed, like 3 or 4 am. Im a night owl and many times i just miss it. For a while i thought i was cursed lol.

Long story short I wanted to know when public/time is called and what can be done about limiting calls. I know theres a reconnection timeout - normally i would want it to reconnect fast if it just dropped like it sometimes does - but if it dropped and then had a public/time fail or something - i would want it to cool off or something.

Is there a way i can console out the public/time calls this library makes?

I do run multiple sockets, one or two per client, and then two for public calls as well.
While we are on the subject, is there a limit i should be worried about here? I do load balance the wallets across servers but not with respect to any websocket worries at the moment.

Sorry for the long message, hope this provides enough information.

Using sync_interval_ms causes, rather than prevents, time drift

First off, thanks for this great API implementation :)

I have a script which is long-running which occasionally makes API requests to ByBit.

I noticed that after a while, all API requests start failing with the standard "check your revcwindow/timestamp" error. It reports that my time and the server time is a few seconds off.

I found the sync_interval_ms param, so I tried lowering this value so it would sync every minute. I saw some interesting behaviour: the API requests started failing much earlier... roughly a minute after my script started.

So it seems like the 'time sync' actually caused the API errors to start happening. To test this further, I've set sync_interval_ms to a very high value, like ~100 hours, and now have had my script running for a couple of days without issue.

Sorry if this is a bit light on detail - happy to send through anything else that'll help with debugging.

Cheers

Getting params error from inverse-futures-client getPosition method

Hi. Thank you for your hard work on this project!
There's one problem when I use getPosition method from inverse-futures-client.ts file.
I'm getting params error when I pass the symbol property like below.
Could you please tell me what should be fixed here?

const { InverseFuturesClient } = require('bybit-api');
const client = new InverseFuturesClient(API_KEY, PRIVATE_KEY, true);

client.getPosition({ symbol: 'BTCUSD' }).then(res => {
  // getting an error ret_msg: "params error!"
});

Thank you.

Unsubscribing from subscribePublicSpotV1Kline

Is there a way to unsubscribe from subscribePublicSpotV1Kline. I have tried to make use of unsubscribe() with a topic like kline_1m like you would expect with other subscriptions (e.g. linear subscriptions) but not having any luck.

Not sure of the proper way to do this.

Thanks

Api responses not typed

Would be awesome to have the API responses typed properly as well instead of Promise<any>.
Many other things can also see typing improvements, especially arguments.

Process remains running after REST API call finished

is there any option i need to pass? it seems like the console is still running even after the excution

const client = new LinearClient(
API_KEY,
PRIVATE_KEY,
useLivenet,
);

client.getSymbols().then(res => {
const symbol = "BTCUSDT";
const data = _.find(res.result, r => r.name == symbol)
console.log('data', data)
})

error requestWrapper.js

i'm using testnet, I run my program, after a moment i have this error:

(node:11650) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'options' of undefined
at parseException (/home/ubuntu/bybit/node_modules/bybit-api/lib/util/requestWrapper.js:83:18)
at runMicrotasks ()
at processTicksAndRejections (internal/process/task_queues.js:93:5)
(node:11650) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 66984)

i create my object restClient like this:

new RestClient(process.env.API_KEY, process.env.PRIVATE_KEY, IS_LIVE_NET, REST_OPTION);

Someone would have any idea ?

Invalid sign for some api keys on getApiKeyInfo()

Hello, I am getting invalid sign on some api keys(not all) when retrieving api key info.

      async validateBybitAccount(bybitAPIKey: string, bybitAPISecret: string) {
        const client = new InverseClient(bybitAPIKey, bybitAPISecret, true);
    
        const data = await client.getApiKeyInfo();
    
        if (data.ret_code == 10003)
          throw new BadRequestException(ErrorCodes.InvalidAPIOrSecret);
    
        if (data.ret_code == 10004)
          this.logger.error(`error with no result for ${bybitAPIKey}`);
    
        if (data.result[0].inviter_id !== 0)
          throw new BadRequestException(ErrorCodes.InvalidUID);
      }
    }

I can provide you with an api key.

fails with an error code of 10004 invalid sign.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.