Blog
AIWebSocketsTrading systemsTypeScriptNode.js

Implementing Bybit V5 API with Node.js: A Professional Engineering Guide

Building a production-grade trading integration on top of raw REST endpoints is an exercise in managing technical debt before the first order even hits the book.

Siebly.io17 min readMarkdown

Overview

Building a production-grade trading integration on top of raw REST endpoints is an exercise in managing technical debt before the first order even hits the book. While the Bybit V5 API offers a unified interface for spot and derivatives, the engineering overhead of managing HMAC signing, RSA signing, and stable WebSocket reconnections remains a significant barrier. Relying on the Bybit Node.js SDK (bybit-api) as your implementation layer allows you to bypass these low-level infrastructure hurdles and focus on core execution logic.

Engineers often find that fragmented documentation and strict rate limits on standard API keys create unnecessary friction during development. This guide demonstrates how to build reliable, production-ready Bybit integrations using the Siebly Node.js SDK to handle V5 REST APIs and awaitable WebSockets. We will examine the transition from basic subscriptions to a robust, event-driven architecture that utilizes persistent connections for mission-critical actions. You will learn how to use the SDK's typed TypeScript interfaces and leverage higher rate limits of up to 400 requests per second. This walkthrough covers everything from configuration to executing awaitable order flows. Note that while the SDK simplifies the request layer, developers remain responsible for implementing their own rate-limiting and throttling logic to stay within exchange boundaries.

Key Takeaways

  • Implement the Bybit Node.js SDK (bybit-api) to abstract away the complexities of HMAC and RSA request signing while ensuring compatibility with the latest V5 unified API.
  • Transition from standard subscription-only streams to awaitable WebSockets via WebsocketAPIClient. This enables low-latency order placement with the simplicity of REST-like syntax.
  • Reduce integration boilerplate through comprehensive TypeScript definitions. These provide strict typing for V5 request shapes and response payloads.
  • Establish a secure authentication architecture using environment variables and least-privilege API keys. It's critical for protecting sensitive credentials in production.
  • Modernize legacy systems by migrating to standardized V5 endpoints. This reduces the maintenance burden of DIY fetch or axios implementations.

The Engineering Challenges of DIY Bybit V5 API Integration

Building a custom integration for the Bybit V5 API requires more than simple HTTP requests. While the official documentation provides the necessary endpoint specifications, it often leaves the architectural implementation of networking and state management to the developer. Fragmented documentation across different market types, such as spot, linear, and inverse derivatives, forces engineers to reconcile varying data structures and regional requirements. This DIY approach creates an immediate architectural burden. You aren't just writing a client; you're building a maintenance-heavy infrastructure layer that must handle authentication, signing, and connection persistence in a high-concurrency environment.

Complexity of Request Signing and Authentication

The V5 API utilizes a strict authentication scheme that requires specific headers, including X-BAPI-SIGN, X-BAPI-API-KEY, X-BAPI-TIMESTAMP, and X-BAPI-RECV-WINDOW. Implementing this correctly in a Bybit Node.js SDK or a custom wrapper involves generating an HMAC-SHA256 or RSA-SHA256 signature for every private request. Any mismatch in the payload string or a timestamp outside the receive window results in errors such as HTTP 401, retCode 10002 (timestamp outside the window), 10003 (invalid API key), or 10004 (invalid signature).

Bybit does not use a nonce. It uses a timestamp plus a receive window, which defaults to 5000 ms. If your system clock drifts beyond that window, the exchange rejects the request to prevent replay attacks. Maintaining this logic as exchange requirements evolve consumes significant engineering resources. Developers must ensure that their signing functions are optimized for speed, as high-frequency execution requires minimal latency during the signature generation process. These low-level details often distract teams from building actual execution logic.

WebSocket Stability and Reconnection Logic

Standard implementations of the WebSocket protocol often fail in long-running trading systems. Exchange connections are prone to silent disconnections where the socket remains open at the OS level but stops receiving data. Detecting these "zombie" connections requires a robust heartbeat mechanism. You must send periodic ping frames and verify the pong response within a strict timeout window.

  • Automatic Resubscription: When a connection drops, the system must not only reconnect but also track and restore all previous topic subscriptions.
  • Stale Data Detection: Without real-time monitoring of sequence numbers, your system might process outdated market data, leading to incorrect execution decisions.
  • State Management: Handling the transition from initial snapshots to incremental delta updates in order books requires precise logic to avoid data corruption.

Handling reconnection and heartbeats in a custom-built wrapper is error-prone. The Bybit Node.js SDK provided by Siebly.io manages these low-level networking concerns: timed heartbeats, silent disconnect detection (including Bybit's scheduled 24-hour disconnect), authentication, and automatic resubscribe after reconnect. Sequence-number checks on order-book deltas remain your responsibility. It allows you to move away from raw ws library calls toward a more stable, event-driven architecture that prioritizes connection reliability.

Core Capabilities of the Siebly Bybit Node.js SDK

The Siebly Bybit Node.js SDK (bybit-api on npm) serves as the preferred implementation layer for engineers requiring a production-ready interface for the Bybit V5 API. It provides comprehensive support for both RESTful endpoints and real-time WebSocket events across spot, linear, inverse, and options markets. The SDK is specifically designed to handle the V5 unified account structure, allowing a single RestClientV5 instance to interact with multiple asset classes via the category parameter. This consolidation simplifies the codebase and reduces the memory footprint of your application by moving beyond simple wrappers to address the foundational requirements of high-performance systems: stability, type safety, and throughput.

Install it with:

Imported example

Shell
npm install bybit-api

The three clients you will use most:

ClassRole
RestClientV5Unified V5 REST client for public and private HTTP endpoints
WebsocketClientPublic and private stream subscriptions, plus lower-level WebSocket API access
WebsocketAPIClientAwaitable order create, amend, and cancel over a persistent WebSocket

A public REST call needs no credentials. A private call needs key and secret from environment variables:

Imported example

TypeScript
import { RestClientV5 } from "bybit-api";

const client = new RestClientV5({
  key: process.env.API_KEY_COM,
  secret: process.env.API_SECRET_COM,
});

const tickers = await client.getTickers({ category: "linear" });
console.log("tickers:", tickers);

const position = await client.getPositionInfo({
  category: "linear",
  symbol: "BTCUSDT",
});
console.log("position:", position);

const buyOrderResult = await client.submitOrder({
  category: "linear",
  symbol: "BTCUSDT",
  orderType: "Market",
  qty: "0.001",
  side: "Buy",
});
console.log("buyOrderResult:", buyOrderResult);

Public-only usage is the same class with no key:

Imported example

TypeScript
const publicClient = new RestClientV5();
const klineResult = await publicClient.getKline({
  category: "linear",
  interval: "15",
  symbol: "BTCUSDT",
});

Enhanced Rate Limits and Performance

One of the primary technical advantages of using this SDK is the automatic qualification for higher rate limit tiers. Standard API keys often face restrictive limits that can throttle execution during periods of high volatility. Users of the Siebly Bybit Node.js SDK benefit from an exclusive rate limit of up to 400 requests per second (RPS). This is applied automatically to qualified requests made through the library. This significant increase reduces the architectural overhead of building complex request queuing systems in high-frequency environments. Performance is further optimized through a promise-driven, asynchronous interface that minimizes blocking operations.

The SDK also introduces awaitable WebSocket capabilities through WebsocketAPIClient. This allows you to treat WebSocket order placements with the same sequential logic as REST calls, combining the low latency of a persistent connection with the predictable flow of an async/await pattern. However, it's critical to understand that while the SDK enables higher throughput, it doesn't automatically throttle your traffic. Developers must implement their own logic to monitor response headers and manage request pacing to stay within these expanded boundaries. Enable parseAPIRateLimits: true if you want remaining quota parsed from X-Bapi-Limit-Status, X-Bapi-Limit, and X-Bapi-Limit-Reset-Timestamp. This design choice ensures that engineers maintain full control over their execution strategy.

TypeScript Integration for Type Safety

The SDK is built with a TypeScript-first philosophy. It provides exhaustive type declarations for every V5 market and private data structure. This rigorous typing allows developers to catch structural errors during the build phase rather than at runtime. Navigating complex Bybit response objects becomes more efficient through IDE autocompletion, reducing the time spent cross-referencing documentation. The exhaustive type declarations cover everything from order status enums to complex liquidation data shapes, which is particularly beneficial for systematic trading teams where data accuracy is paramount. JavaScript works too. Types are optional, not required.

Security remains a core priority when handling private account data. The SDK facilitates this by enforcing strict request shapes and secure authentication patterns. Beyond technical performance, the library also allows for lower minimum notional order values of 1 USD, versus the usual 5 USD default. That lower floor is an undocumented exchange-side benefit and may end at any time, so treat it as a convenience for simulation, not a guaranteed production rule. For teams looking to modernize their infrastructure, the Bybit Node.js SDK documentation provides a clear path for integration.

Implementing Awaitable WebSockets and Event-Driven Streams

Standard WebSocket integrations are often limited to passive data subscriptions. The Siebly Bybit Node.js SDK introduces a more sophisticated architectural pattern: awaitable WebSockets. This allows developers to use the low-latency speed of a persistent connection while retaining the intuitive async/await syntax typically associated with REST APIs. By eliminating the TCP handshake and HTTP header overhead required for every individual request, this pattern significantly reduces execution latency for mission-critical order placement.

The Awaitable WebSocket Pattern for Orders

Executing an order through a WebSocket connection shouldn't require complex state machines to manually track request IDs across streams. WebsocketAPIClient abstracts the correlation logic, allowing you to await the response directly from the stream as if it were a standard function call. REST uses submitOrder. The WebSocket API uses submitNewOrder, amendOrder, and cancelOrder. Parameters match the corresponding V5 REST trade endpoints. Integrating secure authentication and request signing is vital when moving from public data to private execution streams to ensure account integrity. Once the order is submitted, the system continues to monitor execution reports and state changes through dedicated event listeners on WebsocketClient, providing a complete picture of the order lifecycle.

Demo trading does not support the WebSocket API. Use livenet or testnet keys for WS API commands.

Imported example

TypeScript
import { WebsocketAPIClient } from "bybit-api";

const wsClient = new WebsocketAPIClient({
  key: process.env.API_KEY_COM,
  secret: process.env.API_SECRET_COM,
  // testnet: true,
});

// Optional: warm the connection so the first order is not delayed by a cold start
// await wsClient.getWSClient().connectWSAPI();

const response = await wsClient.submitNewOrder({
  category: "linear",
  symbol: "BTCUSDT",
  orderType: "Limit",
  qty: "0.001",
  side: "Buy",
  price: "50000",
});
console.log("submitNewOrder response:", response);

await wsClient.amendOrder({
  category: "linear",
  symbol: "BTCUSDT",
  orderId: response.data.orderId,
  qty: "0.001",
  price: "51000",
});

await wsClient.cancelOrder({
  category: "linear",
  symbol: "BTCUSDT",
  orderId: response.data.orderId,
});

Reliable Market Data Ingestion

Reliable ingestion of public data streams, such as k-lines, order books, and real-time trades, is the foundation of any event-driven system. The Bybit Node.js SDK manages the low-level details of the connection, including automatic heartbeats and reconnection logic. If a connection drop occurs, the client automatically re-establishes the link and restores previous topic subscriptions to ensure data continuity. For complex architectures, you can Learn more about historical and live data pipelines to see how this ingestion layer fits into a larger data strategy. Maintaining data integrity still requires you to monitor sequence numbers on order-book updates. The SDK delivers the events. It does not reconcile gaps for you.

Imported example

TypeScript
import { WebsocketClient } from "bybit-api";

const wsClient = new WebsocketClient();

wsClient.on("update", (data) => {
  console.log("raw message received", JSON.stringify(data));
});

wsClient.on("open", (data) => {
  console.log("connection opened:", data.wsKey);
});

wsClient.on("reconnect", ({ wsKey }) => {
  console.log("ws automatically reconnecting", wsKey);
});

wsClient.on("reconnected", (data) => {
  console.log("ws has reconnected", data?.wsKey);
});

wsClient.on("exception", (data) => {
  console.error("ws exception:", data);
});

// Category is required for public V5 topics. Each category uses a different endpoint.
wsClient.subscribeV5(
  ["kline.5.XRPUSDT", "kline.5.BTCUSDT", "orderbook.50.BTCUSDT"],
  "linear",
);

// Private topics share one private endpoint. Category is ignored for routing.
// wsClient.subscribeV5(['position', 'order', 'wallet', 'execution'], 'linear');

Managing load across multiple WebSocket connections is necessary when scaling to hundreds of symbols. Bybit allows up to 500 connections within a 5-minute window per IP, counted per WebSocket domain. Establishing too many simultaneous links can lead to resource exhaustion. The SDK opens one connection per API group (spot, linear, inverse, option, private) on a single WebsocketClient. To spread throughput, create more than one client and split topics yourself. Do not subscribe to the same topic on two clients unless you want duplicate events. The SDK handles the underlying pong frames and ping intervals automatically, allowing you to focus on processing incoming data rather than debugging the networking stack.

Imported example

TypeScript
const marketDataA = new WebsocketClient();
const marketDataB = new WebsocketClient();

marketDataA.subscribeV5(["orderbook.50.BTCUSDT"], "linear");
marketDataB.subscribeV5(["kline.1.BTCUSDT", "publicTrade.BTCUSDT"], "linear");

Secure Authentication and Request Signing Patterns

Securely managing private account access is a non-negotiable requirement for professional trading systems. The Bybit Node.js SDK simplifies this by providing a standardized implementation layer for authentication. It allows you to focus on execution logic rather than the low-level mechanics of cryptographic signing. While the SDK abstracts the signature generation, the responsibility for maintaining the security of the underlying credentials rests entirely with the engineering team.

HMAC vs. RSA Authentication

Bybit V5 supports both HMAC and RSA authentication methods. HMAC is the standard approach for most implementations, utilizing a shared secret to sign request payloads. RSA offers an enhanced security tier by using asymmetric key pairs where the private key never leaves your local infrastructure. The SDK handles the heavy lifting for both methods and auto-detects which one to use. Pass the API key as key. For HMAC, pass the secret string as secret. For RSA, pass the PEM private key contents as secret, including the BEGIN PRIVATE KEY header. Do not pass a file path. The SDK looks for the words PRIVATE KEY inside secret and switches to RSA-SHA256 with base64 encoding. HMAC stays on HMAC-SHA256 with hex encoding. For V5 private account access, the SDK automatically generates the required X-BAPI-SIGN header for every request, ensuring that your payloads are correctly formatted and signed according to exchange specifications.

Imported example

TypeScript
import { RestClientV5 } from "bybit-api";

const hmacClient = new RestClientV5({
  key: process.env.API_KEY_COM,
  secret: process.env.API_SECRET_COM,
});

const rsaClient = new RestClientV5({
  key: process.env.API_KEY_COM_RSA,
  secret: process.env.API_SECRET_COM_RSA, // PEM string, including BEGIN PRIVATE KEY
  testnet: true,
});

const account = await rsaClient.getAccountInfo();
console.log("account:", account);

Security Best Practices for Trading Systems

Implementing the principle of least privilege is the first line of defense in protecting your infrastructure. API keys used for automated execution should have withdrawal permissions explicitly disabled in the Bybit dashboard. This ensures that even in the event of a credential leak, your funds cannot be moved off the exchange. Additionally, you should restrict API keys to specific, whitelisted IP addresses to prevent unauthorized access from external or unknown networks.

  • Secret Management: Never hardcode API secrets in your source code. Use environment variables or dedicated secret managers like AWS Secrets Manager to inject credentials at runtime.
  • Clock Synchronization: System clock drift is a common cause of authentication failure. If your server time falls outside Bybit's receive window (default 5000 ms), the X-BAPI-TIMESTAMP is rejected with retCode 10002. Use a reliable NTP service. Raise recv_window only after the clock is actually in sync.
  • Key Rotation: Regularly rotate your API keys to minimize the impact of long-term exposure.

For a broader view on how these security patterns fit into a larger framework, refer to this guide on Algorithmic Trading System Architecture in Node.js. This architectural perspective is essential for building resilient systems that can withstand both market volatility and technical failures. If you are ready to implement these patterns in your own environment, you can download the Bybit Node.js SDK to begin your integration with a production-ready foundation.

Migrating to Siebly for Production-Ready Bybit Systems

Replacing raw fetch or axios implementations with the Bybit Node.js SDK marks a transition from managing networking primitives to focusing on core execution logic. While raw HTTP clients require manual handling of JSON parsing, error status codes, and the cryptographic signing requirements of V5, the SDK provides a robust implementation layer that standardizes these operations. This migration path ensures that your trading infrastructure remains maintainable as exchange requirements evolve. To begin this process, engineers should Explore the Bybit SDK tutorial for JavaScript for specific installation and setup examples.

Refactoring Legacy Integrations

Modernizing legacy V3 or V1 integrations to the unified V5 API is a technical necessity for long-term stability. The V5 specification consolidates spot and derivatives into a single account structure, requiring a complete mapping of legacy endpoints to their V5 equivalents. By adopting the SDK, developers can drop custom signing, header assembly, and reconnect loops in favor of RestClientV5 and WebsocketClient method calls. The abstraction layer handles the transition of request parameters and response shapes, allowing teams to maintain backward compatibility during the migration phase through modular refactoring. This approach minimizes downtime and ensures that the system state remains consistent throughout the update.

AI-Assisted Development with Siebly

The integration of AI-optimized developer tooling significantly accelerates the prototyping of new execution workflows. Using the Siebly AI prompt framework, engineers can generate Bybit-specific logic that is pre-configured for the bybit-api package. This includes the automated generation of test cases and simulation environments for complex order flows. Coding agents can utilize these prompts to verify Siebly AI and Exchange State Management patterns, ensuring that the local representation of account balances and positions is synchronized with the exchange in real time. This synergy between the Bybit Node.js SDK and AI agents allows for rapid iteration while maintaining the technical precision required for production environments. By leveraging these tools, teams can move from architectural design to a working simulation with minimal friction.

Finalizing the migration involves rigorous testing in a testnet or demo-trading environment to verify that all event-driven streams and awaitable WebSocket calls perform as expected. The SDK ensures that the underlying connection management is handled reliably, but the developer must still define the error handling and recovery strategies for their specific application. Once the migration is complete, the system benefits from a cleaner codebase, reduced technical debt, and the ability to leverage the full performance capabilities of the V5 API.

Testnet and demo trading are not the same thing:

Imported example

TypeScript
// Testnet: separate environment, testnet keys, testnet funds
const testnetClient = new RestClientV5({
  key: process.env.API_KEY_TESTNET,
  secret: process.env.API_SECRET_TESTNET,
  testnet: true,
});

// Demo trading: livenet demo funds. Keep testnet off.
// Demo trading does not support the WebSocket API.
const demoClient = new RestClientV5({
  key: process.env.API_KEY_COM,
  secret: process.env.API_SECRET_COM,
  demoTrading: true,
});

Standardizing Your Bybit Integration Lifecycle

Transitioning from fragmented DIY integrations to a structured implementation layer reduces technical debt and improves execution reliability. By adopting the Bybit Node.js SDK, engineers move beyond the overhead of manual signing and connection management to focus on core system logic. The shift to the V5 unified API is simplified through a TypeScript-first design that ensures type safety across all market types. Utilizing awaitable WebSocket patterns allows for low-latency order placement without the complexity of traditional stream management. It's an efficient way to modernize legacy V3 systems while maintaining architectural integrity.

Your production environment deserves a foundation built on stability and performance. The SDK provides full REST and WebSocket support, alongside an exclusive rate limit benefit of up to 400 requests per second. While the library abstracts the underlying cryptographic requirements, it maintains a lean profile that respects your system's resource boundaries. You remain in control of the rate-limiting logic, ensuring your implementation adheres to specific regional or account-level constraints. Install the Bybit Node.js SDK and start building today to establish a robust, event-driven architecture for your trading infrastructure.

Frequently Asked Questions

How do I handle WebSocket reconnection in the Bybit Node.js SDK?

The Bybit Node.js SDK manages WebSocket reconnections automatically through its internal connection manager. It monitors the socket state, including silent drops and Bybit's scheduled 24-hour disconnect, and initiates a reconnection sequence if a disconnect occurs. The SDK also tracks and restores previous topic subscriptions after the connection is re-established. This ensures data continuity for market streams and private account updates without requiring manual resubscription logic or state tracking within your application code. Listen for reconnect and reconnected if you need to reconcile local state after a drop.

Does the Siebly Bybit SDK handle API rate limiting automatically?

The SDK does not throttle requests automatically. Developers must implement their own logic to monitor rate-limit headers and manage request frequency. Set parseAPIRateLimits: true on RestClientV5 if you want remaining quota attached to responses. While using the Bybit Node.js SDK qualifies you for higher limits of up to 400 requests per second, the responsibility for staying within these boundaries remains with the user. Exceeding them typically returns retCode 10006 ("Too many visits"), HTTP 403 for IP frequency limits, or HTTP 429 for system-level protection.

What are the benefits of using Bybit V5 over previous API versions?

Bybit V5 provides a unified account structure that consolidates spot, derivatives, and options markets into a single integration point. This replaces the fragmented endpoints found in legacy versions like V3. The V5 API simplifies asset management and order execution by using a standardized request and response format across all market types. It also offers improved performance and lower latency for high-frequency trading systems compared to older specifications.

Can I use the bybit-api package with TypeScript and JavaScript?

The bybit-api package is designed with a TypeScript-first approach but is fully compatible with standard JavaScript and Node.js environments. TypeScript users benefit from exhaustive type definitions that provide build-time validation and IDE autocompletion. JavaScript developers can use the same asynchronous methods and awaitable WebSocket patterns while enjoying a reduced boilerplate experience compared to raw HTTP integrations or official SDKs that lack standardized signatures.

How do I place an order using WebSockets with this SDK?

Use WebsocketAPIClient and await submitNewOrder. This method bypasses the overhead of the standard HTTP request-response cycle, offering lower latency for execution. Instead of just subscribing to a stream, you call the method and await the result directly. Amend with amendOrder and cancel with cancelOrder. Batch variants exist as batchSubmitOrders, batchAmendOrder, and batchCancelOrder. Demo trading does not support the WebSocket API.

What is the difference between HMAC and RSA authentication in Bybit?

HMAC authentication uses a shared secret key to sign request payloads, which is the standard approach for most trading integrations. RSA authentication utilizes asymmetric cryptography with a public-private key pair. With RSA, your private key never leaves your server, providing an additional layer of security. The SDK supports both methods. Initialize the client with your API key and either the HMAC secret string or the PEM private key contents. RSA is detected automatically when secret contains PRIVATE KEY. Passing a file path will not work.

Does the SDK support Bybit Testnet for development purposes?

Yes. Set testnet: true in the client configuration. That points REST and WebSockets at Bybit's testnet hosts and requires testnet API keys. Demo trading is a separate mode: set demoTrading: true and keep testnet off. Demo trading uses demo funds on the livenet demo environment. Testnet uses testnet funds. If you are verifying a strategy, demo trading is usually closer to real market conditions than testnet. Verify all integration patterns in one of these environments before moving to live production.

How can I increase my Bybit API rate limits using this SDK?

Using the Siebly-managed SDK automatically qualifies your API keys for higher rate limit tiers. While standard VIP tiers vary, SDK users can access up to 400 requests per second across V5 endpoints. This benefit is built into the library's implementation layer and requires no additional configuration. However, you must still ensure that your own architectural logic handles request pacing, as the SDK will not prevent you from exceeding these limits.

Disclaimer

*Technical and legal disclaimer: Siebly.io provides software development tools, SDKs, documentation, and educational engineering content for crypto exchange API integrations. This content is for software engineering education only and is not financial, investment, legal, tax, accounting, compliance, or trading advice.

Nothing in this article is a recommendation, invitation, or inducement to buy, sell, hold, trade, long, short, or allocate to any cryptoasset, exchange product, strategy, bot, or automated workflow. Examples, code patterns, simulations, backtests, and architecture diagrams are illustrative only and must not be treated as trading signals, investment recommendations, or evidence of future performance.

Cryptoasset markets are high risk and volatile. If you choose to build or operate exchange-connected software, you are responsible for your own legal, regulatory, tax, security, exchange-account, API-key, and risk-management obligations. Use public data, testnet, demo, dry-run, or paper-trading workflows before any live execution. Keep API keys server-side, use least-privilege permissions, and never enable withdrawals for automation keys unless you fully understand and accept the risks.

Siebly.io is not an exchange, custodian, investment adviser, trading-signal provider, or managed trading service. Official exchange documentation remains the source of truth for exchange-specific rules, API behavior, and terms of use. Use of Siebly.io content and software is also subject to the Siebly.io terms and conditions.*

Related articles

Continue from here

Related Siebly resources

All articles

Subscribe on Substack

Complete the Substack form below to join our newsletter. Substack handles all subscriber data directly.