Skip to content

Repository files navigation

Node.js & Typescript Bitget API SDK

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

SDK Logo

Tip

Upcoming change: As part of the Siebly.io brand, this SDK is now hosted under our Siebly.io GitHub organisation. The migration is seamless and requires no user changes.

Updated & performant JavaScript & Node.js SDK for the Bitget V2 REST APIs and WebSockets.

Take a look at our dedicated Bitget API quickstart guides for major frameworks and JavaScript runtimes.

  • Professional, robust & performant Bitget SDK with extensive production use in live trading environments.
  • Complete integration with all Bitget APIs.
    • Supports V2 REST APIs & WebSockets
    • Supports V3/UTA REST APIs & WebSockets (latest)
    • Supports order placement via V3 WebSocket API
  • Complete TypeScript support (with type declarations for all API requests & responses).
    • Strongly typed requests and responses.
    • Automated end-to-end tests on most API calls, ensuring no breaking changes are released to npm.
  • Actively maintained with a modern, promise-driven interface.
  • Over 100 integration 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 with automatic reconnection handling.
    • Emit reconnected event when dropped connection is restored.
    • Optional beautification of WebSocket events for improved readability.
  • Officially listed Node.js SDK in Bitget API docs.
  • Browser support (via webpack bundle - see "Browser Usage" below).
  • Support all authentication methods supported by Bitget:
    • HMAC
    • RSA
  • Heavy automated end-to-end testing with real API calls.
    • End-to-end testing before any release.
    • Real API calls in e2e tests.
  • Proxy support via axios integration.
  • Active community support & collaboration in telegram: Node.js Algo Traders.
  • QuickStart Guide: https://siebly.io/sdk/bitget/javascript
  • Bitget JavaScript Tutorial: https://siebly.io/sdk/bitget/javascript/tutorial

Table of Contents

Installation

npm install --save bitget-api

Frameworks & Quickstart Guides

Our complete Bitget SDK supports all the major JavaScript runtimes. For maximum convenience, we've included guides to quickly get you started with the most popular runtimes. If you're not sure how to use this SDK with a runtime or framework not listed here, feel free to open an issue on GitHub.

Runtime Details
Backend (trading bots) Using Node.js and JavaScript, Node.js and TypeScript, Bun, or Deno. This is the recommendation for algorithmic trading systems.
Frontend / Web Development Using React with Vite or Vite with plain JavaScript. Display REST and WebSocket prices in the browser.
Next.js App Router Using the Next.js App Router to serve the price from a Route Handler running on Node.js.
Mobile (iOS & Android) Using React Native with Expo for iOS and Android. The example guides you to display the current BTCUSDT price from Bitget and stream updates over WebSockets.
Cloudflare Workers Cloudflare Workers. Return a public price from a Worker, with a separate example for authenticated orders.

Refer to runtime setup for installation commands, project configuration, and public price examples.

Examples

Refer to the examples folder for implementation demos.

Issues & Discussion

  • Issues? Check the issues tab.
  • Discuss & collaborate with other node devs? Join our Node.js Algo Traders engineering community on telegram.
  • Follow our announcement channel for real-time updates on X/Twitter

Related Projects

Check out our JavaScript/TypeScript/Node.js SDKs & Projects:

Documentation

The Bitget SDK documentation covers installation, client setup, public market data, authenticated trading, and WebSocket subscriptions.

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).

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.
  • dist - the webpack bundle of the project for use in browser environments (see guidance on webpack below).
  • examples - some implementation examples & demonstrations. Contributions are welcome!

Usage

Create API credentials at Bitget:

REST API Clients

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.

Getting Started

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:

  1. RestClientV3 for the latest V3/UTA APIs (Unified Trading Account) - recommended for new projects.
  2. RestClientV2 for V2 APIs - use if you haven't upgraded to UTA yet.

More Node.js & JavaScript examples for Bitget's REST APIs & WebSockets can be found in the examples folder on GitHub.

V3 REST APIs

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);
  }
})();

V2 REST APIs

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);
  });

WebSockets

All WebSocket functionality is supported via the WebsocketClient. Since there are currently 2 generations of Bitget's API, there are 2 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:

  • Event driven messaging
  • Smart WebSocket persistence with automatic reconnection
  • Heartbeat mechanisms to detect disconnections
  • Automatic resubscription after reconnection
  • Error handling and connection monitoring
  • Optional data beautification

Higher level examples below, while more thorough examples can be found in the examples folder on GitHub.

V3 Unified Trading Account
Sending orders via WebSockets

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));
Receiving realtime data

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.

V2 WebSockets

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');

Logging

Customise logging

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,
);

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 BITGETTRACE env var to true.

Browser/Frontend Usage

The npm package includes ES module and CommonJS builds. You do not need to build the SDK's standalone Webpack bundle to use it in a frontend project. Choose the setup for your application below.

Vite and React

Use the Vite guide or React guide for a complete public market-data project that imports bitget-api from npm.

Keep the supplied bundler configuration with the example: it provides EventEmitter and replaces the SDK's Node-only HTTPS Agent with a browser guard. Browsers manage connections, so omit keepAlive. These browser examples use public Bitget market data. Keep private keys and API credentials in a secure server-side environment and make authenticated calls there.

Browser REST requests also depend on Bitget's CORS policy. If a request is blocked, call the SDK through your application's server route instead. A development proxy does not solve CORS for a deployed application.

Next.js and server-side requests

The Next.js guide runs the SDK in a Node.js Route Handler and returns the result to the frontend. Use this pattern when requests need credentials or cannot be made directly from the browser.

React Native and Expo

Follow the Expo guide for its Metro configuration and required polyfills, including events, buffer, https-browserify, stream-http and url. Browser bundler configuration is not interchangeable with Metro configuration. The example uses public Bitget market data; keep authenticated operations on your server.

Standalone Webpack bundle

If you need a standalone UMD bundle rather than npm imports in your application, the SDK repository includes a Webpack configuration. From a checkout of this repository:

npm install
npm run build
npm run pack

The configuration writes dist/bitgetapi.js with the bitgetapi global name. This is a separate packaging option, not a required step for the framework guides above. Browser-specific configuration and API access restrictions still apply.

For older browser integrations that require Node crypto and stream polyfills, install crypto-browserify and stream-browserify and configure your bundler to resolve those modules to the polyfills. The previous setup also supplied window.global = window for dependencies that expect a Node-style global. The repository's Webpack configuration disables Node http and https; it does not configure these crypto and stream polyfills automatically.

Use with LLMs & AI

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.


Used By

Repository Users Preview Image


Contributions & Thanks

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

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

Releases

Sponsor this project

Used by

Contributors

Languages