tiagosiebler / bybit-api Goto Github PK
View Code? Open in Web Editor NEWNode.js SDK for the Bybit APIs and WebSockets, with TypeScript & browser support.
Home Page: https://www.npmjs.com/package/bybit-api
License: MIT License
Node.js SDK for the Bybit APIs and WebSockets, with TypeScript & browser support.
Home Page: https://www.npmjs.com/package/bybit-api
License: MIT License
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 }
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)
})
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));
}
Adapt/expand the one from the binance connector:
https://github.com/tiagosiebler/binance/blob/master/src/util/beautifier.ts
This error will be expected in the upcoming release. Use InverseClient
instead. See #75
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.
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?
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?
Plan effort to transition library to typescript
https://bybit-exchange.github.io/docs/inverse_futures/#t-introduction
Currently testnet only, but worth starting with it.
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 ?
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
These are in no particular order:
linear-client.js
See beppu's post below:
lib/linear-client.js
dedicated to linear contracts, very similar to lib/rest-client.js
.rest-client.js
for automatic handlingrest-clientv2.js
for automatic handlingrest-client
.rest-clientv2.js
. TBC.rest-client
with deprecation warning).inverse-client
vs linear-client
vs rest-clientv2
rest-client
will remain for a while, albeit deprecated.rest-client
(such as endpoints) could be taken from a separate module, to reduce repetition.rest-clientv2
, which works like (3).Bybit changed API for get wallet balance to have optional 'coin' param but current library doesn't support that for now.
Hope to remove assert from following line.
https://github.com/tiagosiebler/bybit-api/blob/master/lib/rest-client.js#L228
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×tamp=1599924773483]"
}
Should be excluded from the npm publish, but would be nice to automatically build it when merging to master
https://github.com/tiagosiebler/bybit-api/blob/master/lib/rest-client.js#L75
Check for others too
https://github.com/tiagosiebler/bybit-api/blob/master/lib/websocket-client.js#L38
Currently initialises REST client without a way to pass that through, meaning the WS might not leverage proxies.
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"
}
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?
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
Some params are optional now:
https://bybit-exchange.github.io/docs/inverse/#2020-11-02
livenet2: 'wss://stream.bytick.com/realtime_public',
Need to swap private/public
https://github.com/tiagosiebler/bybit-api/blob/master/src/websocket-client.ts#L20
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
Reported in telegram. The WebSocket client uses the npm ws
module, which is not browser compatible.
One possibility is a wrapper approach, such as the one suggested in the ws
docs too:
https://github.com/heineiuo/isomorphic-ws
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.
A browser-compatible bundle can be packed:
https://github.com/tiagosiebler/bybit-api#browser-usage
Due to dependencies (and duplicate ones too) that bundle is currently almost 700kb. There should be optimisation room to reduce that, though it needs investigation.
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
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.
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?
Connect to webso and subscribe to the position
When you buy coins at the market price
The signal flies twice..
Is it originally like that? Or is it a bug?
I am using a testnet.
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.
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
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
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);
}
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 ?
This is currently only in testnet but it's worth starting integration:
https://bybit-exchange.github.io/docs/spot/#t-marketdata
I would add this as another "client", similar to inverse-client and linear-client: https://github.com/tiagosiebler/bybit-api/tree/master/src
Same issue here is likely
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.
Request is deprecated for a while now. Need to refactor the library to leverage axios for requests. This will also reduce bundle size significantly.
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 !
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!
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
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
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
Got error when compiling
It seems to be bound to file node-support.js line 13
https://www.npmjs.com/package/crypto
How do you handle this error ?
Please add feature for Switching margin mode (Cross, Isolated)
Testnet's API working perfect, but real API always returns 404
https://bybit-exchange.github.io/docs/inverse/#t-restapi_update_20201231_0
A number of endpoints have received a 1:1 replacement via a new route, bybit recommends using them instead.
https://bybit-exchange.github.io/docs/inverse/#t-a_getrisklimit
Seems these methods were abandoned by bybit, they're in the abandoned section of the api docs, and are returning not-found erros.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.