
Security News
TC39 Advances 11 Proposals for Math Precision, Binary APIs, and More
TC39 advances 11 JavaScript proposals, with two moving to Stage 4, bringing better math, binary APIs, and more features one step closer to the ECMAScript spec.
bitget-api
Advanced tools
Complete Node.js & JavaScript SDK for Bitget V1-V3 REST APIs & WebSockets, with TypeScript & end-to-end tests.
Updated & performant JavaScript & Node.js SDK for the Bitget V2 REST APIs and WebSockets:
reconnected
event when dropped connection is restored.npm install --save bitget-api
Refer to the examples folder for implementation demos.
Check out my related JavaScript/TypeScript/Node.js projects:
Most methods accept JS objects. These can be populated using parameters specified by Bitget's API documentation, or check the type definition in each class within this repository (see table below for convenient links to each class).
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).
Create API credentials at Bitget:
Each REST API group has a dedicated REST client. To avoid confusion, here are the available REST clients and the corresponding API groups:
Class | Description |
---|---|
RestClientV3 | V3/UTA REST APIs for Bitget's Unified Trading Account |
WebsocketClientV3 | Universal WS client for Bitget's V3/UTA WebSockets |
WebsocketAPIClient | Websocket API Client, for RESTlike order placement via Bitget's V3/UTA WebSocket API |
RestClientV2 | V2 REST APIs |
WebsocketClientV2 | Universal WS client for all Bitget's V2 WebSockets |
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.
All REST APIs are integrated in each dedicated Rest Client class. See the above table for which REST client to use. If you've upgraded to the Unified Trading Account, you should use the V3 REST APIs and WebSockets.
There are several REST API modules as there are some differences in each API group:
RestClientV3
for the latest V3/UTA APIs (Unified Trading Account) - recommended for new projects.RestClientV2
for V2 APIs - use if you haven't upgraded to UTA yet.SpotClient
, FuturesClient
, BrokerClient
) - deprecated, migrate to V2 or V3.More Node.js & JavaScript examples for Bitget's REST APIs & WebSockets can be found in the examples folder on GitHub.
These are only available if you have upgraded to the Unified Trading Account. If not, use the V2 APIs instead.
import { RestClientV3 } from 'bitget-api';
// or if you prefer require:
// const { RestClientV3 } = require('bitget-api');
// note the single quotes, preventing special characters such as $ from being incorrectly passed
const client = new RestClientV3({
apiKey: process.env.API_KEY_COM || 'insert_api_key_here',
apiSecret: process.env.API_SECRET_COM || 'insert_api_secret_here',
apiPass: process.env.API_PASS_COM || 'insert_api_pass_here',
});
(async () => {
try {
console.log(await client.getBalances());
const newOrder = await client.submitNewOrder({
category: 'USDT-FUTURES',
orderType: 'market',
side: 'buy',
qty: '0.001',
symbol: 'BTCUSDT',
});
console.log('Order submitted: ', newOrder);
} catch (e) {
console.error('request failed: ', e);
}
})();
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.
If you found the method you're looking for in the API docs, you can also search for the endpoint in the RestClientV2 class. This class has all V2 endpoints available.
import { RestClientV2 } from 'bitget-api';
// or if you prefer require:
// const { RestClientV2 } = require('bitget-api');
const API_KEY = 'xxx';
const API_SECRET = 'yyy';
const API_PASS = 'zzz';
const client = new RestClientV2({
apiKey: API_KEY,
apiSecret: API_SECRET,
apiPass: API_PASS,
});
// For public-only API calls, simply don't provide a key & secret or set them to undefined
// const client = new RestClientV2();
client
.getSpotAccount()
.then((result) => {
console.log('getSpotAccount result: ', result);
})
.catch((err) => {
console.error('getSpotAccount error: ', err);
});
client
.getSpotCandles({
symbol: 'BTCUSDT',
granularity: '1min',
limit: '1000',
})
.then((result) => {
console.log('getCandles result: ', result);
})
.catch((err) => {
console.error('getCandles error: ', err);
});
All WebSocket functionality is supported via the WebsocketClient. Since there are currently 3 generations of Bitget's API, there are 3 WebsocketClient classes in this Node.js, JavaScript & TypeScript SDK for Bitget.
Use the following guidance to decide which one to use:
All WebSocket clients support:
Higher level examples below, while more thorough examples can be found in the examples folder on GitHub.
The V3 / Unified Trading Account APIs introduce order placement via a persisted WebSocket connection. This Bitget Node.js, JavaScript & TypeScript SDK supports Bitget's full V3 API offering, including the WebSocket API.
There are two approaches to placing orders via the Bitget WebSocket APIs. The recommended route is to use the dedicated WebsocketAPIClient class, included with this SDK.
This integration looks & feels like a REST API client, but uses WebSockets, via the WebsocketClient's sendWSAPIRequest method. It returns promises and has end to end types.
A simple example is below, but for a more thorough example, check the example here: ./examples/V3/ws-api-client-trade.ts
import { WebsocketAPIClient } from 'bitget-api';
// or if you prefer require:
// const { WebsocketAPIClient } = require("bitget-api");
// Make an instance of the WS API Client class with your API keys
const wsClient = new WebsocketAPIClient({
apiKey: API_KEY,
apiSecret: API_SECRET,
apiPass: API_PASS,
// Whether to use the demo trading wss connection
// demoTrading: true,
});
async function start() {
// Start using it like a REST API. All actions are sent via a persisted WebSocket connection.
/**
* Place Order
* https://www.bitget.com/api-doc/uta/websocket/private/Place-Order-Channel#request-parameters
*/
try {
const res = await wsClient.submitNewOrder('spot', {
orderType: 'limit',
price: '100',
qty: '0.1',
side: 'buy',
symbol: 'BTCUSDT',
timeInForce: 'gtc',
});
console.log(new Date(), 'WS API "submitNewOrder()" result: ', res);
} catch (e) {
console.error(new Date(), 'Exception with WS API "submitNewOrder()": ', e);
}
}
start().catch((e) => console.error('Exception in example: '.e));
Use the WebsocketClientV3 to receive data via the V3 WebSockets
import { WebsocketClientV3 } from "bitget-api";
// or if you prefer require:
// const { WebsocketClientV3 } = require("bitget-api");
const API_KEY = "yourAPIKeyHere";
const API_SECRET = "yourAPISecretHere;
const API_PASS = "yourAPIPassHere";
const wsClient = new WebsocketClientV3(
{
// Only necessary if you plan on using private/account websocket topics
apiKey: API_KEY,
apiSecret: API_SECRET,
apiPass: API_PASS,
}
);
// Connect event handlers to process incoming events
wsClient.on('update', (data) => {
console.log('WS raw message received ', data);
// console.log('WS raw message received ', JSON.stringify(data, null, 2));
});
wsClient.on('open', (data) => {
console.log('WS connection opened:', data.wsKey);
});
wsClient.on('response', (data) => {
console.log('WS response: ', JSON.stringify(data, null, 2));
});
wsClient.on('reconnect', ({ wsKey }) => {
console.log('WS automatically reconnecting.... ', wsKey);
});
wsClient.on('reconnected', (data) => {
console.log('WS reconnected ', data?.wsKey);
});
wsClient.on('exception', (data) => {
console.log('WS error', data);
});
/**
* Subscribe to topics as you wish
*/
// You can subscribe to one topic at a time
wsClient.subscribe(
{
topic: 'account',
payload: {
instType: 'UTA', // Note: all account events go on the UTA instType
},
},
WS_KEY_MAP.v3Private, // This parameter points to private or public
);
// Note: all account events go on the UTA instType
const ACCOUNT_INST_TYPE = 'UTA';
const ACCOUNT_WS_KEY = WS_KEY_MAP.v3Private;
// Or multiple at once:
wsClient.subscribe(
[
{
topic: 'account',
payload: {
instType: ACCOUNT_INST_TYPE,
},
},
{
topic: 'position',
payload: {
instType: ACCOUNT_INST_TYPE,
},
},
{
topic: 'fill',
payload: {
instType: ACCOUNT_INST_TYPE,
},
},
{
topic: 'order',
payload: {
instType: ACCOUNT_INST_TYPE,
},
},
],
ACCOUNT_WS_KEY,
);
// Example public events
wsClient.subscribe(
[
{
topic: 'ticker',
payload: {
instType: 'spot',
symbol: 'BTCUSDT',
},
},
{
topic: 'ticker',
payload: {
instType: 'spot',
symbol: 'ETHUSDT',
},
},
{
topic: 'ticker',
payload: {
instType: 'spot',
symbol: 'XRPUSDT',
},
},
{
topic: 'ticker',
payload: {
instType: 'usdt-futures',
symbol: 'BTCUSDT',
},
},
{
topic: 'ticker',
payload: {
instType: 'usdt-futures',
symbol: 'BTCUSDT',
},
},
],
WS_KEY_MAP.v3Public,
);
For more examples, including how to use websockets with Bitget, check the examples and test folders.
If you haven't upgraded to the Unified Trading Account, use the V2 WebSocket client:
import { WebsocketClientV2 } from 'bitget-api';
// or if you prefer require:
// const { WebsocketClientV2 } = require('bitget-api');
const API_KEY = 'xxx';
const API_SECRET = 'yyy';
const API_PASS = 'zzz';
const wsClient = new WebsocketClientV2({
apiKey: API_KEY,
apiSecret: API_SECRET,
apiPass: API_PASS,
// Optional: connect to demo trading environment
// demoTrading: true,
});
// Handle incoming messages
wsClient.on('update', (data) => {
console.log('WS update received: ', data);
});
wsClient.on('open', (data) => {
console.log('WS connection opened: ', data.wsKey);
});
wsClient.on('reconnected', (data) => {
console.log('WS reconnected: ', data?.wsKey);
});
wsClient.on('exception', (data) => {
console.log('WS error: ', data);
});
// Subscribe to public data streams
wsClient.subscribeTopic('SPOT', 'ticker', symbol);
// Subscribe to private data streams (requires authentication)
wsClient.subscribeTopic('SPOT', 'account');
Pass a custom logger which supports the log methods trace
, info
and error
, or override methods from the default logger as desired.
import { WebsocketClientV2, DefaultLogger } from 'bitget-api';
// or if you prefer require:
// const { WebsocketClientV2, DefaultLogger } = require('bitget-api');
// Disable all logging on the trace level (less console logs)
const customLogger = {
...DefaultLogger,
trace: () => {},
};
const ws = new WebsocketClientV2(
{
apiKey: 'API_KEY',
apiSecret: 'API_SECRET',
apiPass: 'API_PASS',
},
customLogger,
);
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 BITGETTRACE
env var to true
.
This is the "modern" way, allowing the package to be directly imported into frontend projects with full typescript support.
npm install crypto-browserify stream-browserify
tsconfig.json
{
"compilerOptions": {
"paths": {
"crypto": [
"./node_modules/crypto-browserify"
],
"stream": [
"./node_modules/stream-browserify"
]
}
(window as any).global = window;
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.
This SDK includes a bundled llms.txt
file in the root of the repository. If you're developing with LLMs, use the included llms.txt
with your LLM - it will significantly improve the LLMs understanding of how to correctly use this SDK.
This file contains AI optimised structure of all the functions in this package, and their parameters for easier use with any learning models or artificial intelligence.
Have my projects helped you? Share the love, there are many ways you can show your thanks:
0xA3Bda8BecaB4DCdA539Dc16F9C54a592553Be06C
Contributions are encouraged, I will review any incoming pull requests. See the issues tab for todo items.
FAQs
Complete Node.js & JavaScript SDK for Bitget V1-V3 REST APIs & WebSockets, with TypeScript & end-to-end tests.
The npm package bitget-api receives a total of 728 weekly downloads. As such, bitget-api popularity was classified as not popular.
We found that bitget-api demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
TC39 advances 11 JavaScript proposals, with two moving to Stage 4, bringing better math, binary APIs, and more features one step closer to the ECMAScript spec.
Research
/Security News
A flawed sandbox in @nestjs/devtools-integration lets attackers run code on your machine via CSRF, leading to full Remote Code Execution (RCE).
Product
Customize license detection with Socket’s new license overlays: gain control, reduce noise, and handle edge cases with precision.