Bybit API gives developers and traders the ability to programmatically perform any actions on the Bybit exchange — place orders, get account balances, retrieve live market data, and manage positions without interacting with the website UI. The official API documentation describes the v5 unified API for Bybit, which combines endpoints in one structure regardless of the product category: spot, linear and inverse perpetuals, options, and the copy trading system. This article reviews the functionality provided by the Bybit API, authentication and rate limits, the most important endpoints for common use cases, and how to get started.
Where to Find the Official Bybit API Documentation
The official Bybit API documentation is located at bybit-exchange.github.io/docs/v5/intro. It includes descriptions of all v5 endpoints, parameter definitions, JSON response examples, and changelog entries.
Bybit hosts its API documentation on GitHub, which makes the history of changes publicly accessible.
The current version is v5, which replaced the previous v3 and category-specific APIs with a unified structure. If you are working from older code or documentation containing endpoints starting with /v2/public or /private/linear, these are legacy endpoints from earlier API versions. It is advisable to use v5 equivalents for any new integration.
Bybit also maintains a separate testnet environment at api-testnet.bybit.com, which uses the same endpoint structure as the production API. The testnet lets you test integrations, place orders, and verify responses without using real funds. Creating a separate testnet account and generating API keys for it is the recommended first step before connecting any trading logic to the live environment.
API Architecture: REST and WebSocket
Bybit's API has two main communication modes: REST (HTTP) and WebSocket. Each serves a different purpose, and most production integrations use both.
REST API
The REST API is request-response based: your application sends an HTTP request to a Bybit endpoint and receives a JSON response. The base URL for the production environment is api.bybit.com. REST endpoints are used for actions that do not require a persistent connection: placing and cancelling orders, querying account balances, retrieving order history, fetching position information, and accessing historical market data such as candlestick (kline) data.
All REST endpoints return JSON with a standard structure including a retCode field (0 means success), a retMsg field ("OK" on success or an error description), and a result object containing the actual response data. Checking the retCode before processing the result is the standard pattern for error handling.
WebSocket API
WebSocket connections establish a persistent, bidirectional channel between your application and Bybit's servers. They are used for real-time data streams: live order book updates, trade executions, ticker price feeds, and private streams for account-level events like order fills and position changes.
Bybit separates WebSocket streams into public and private channels. Public streams — order books, tickers, recent trades, klines — are available without authentication. Private streams — order updates, position changes, wallet balance changes — require authentication using your API key and a signed message sent immediately after the connection is established.
WebSocket endpoints differ by product category. The linear perpetuals public stream uses wss://stream.bybit.com/v5/public/linear and the spot public stream uses wss://stream.bybit.com/v5/public/spot. The private stream for all categories uses wss://stream.bybit.com/v5/private.
Authentication
Public endpoints — market data, instrument information, server time --- require no authentication. Private endpoints — anything involving your account, orders, or positions — require a signed request using your API key and secret.
Generating API Keys
API keys are created in your Bybit account under Account and Security, then API. Each key consists of an API Key (a public identifier) and an API Secret (used for signing, kept private). When creating a key, you set its permissions: read-only for market data and account queries, or read-write for trading. You can also restrict a key to specific IP addresses, which is a recommended security practice for any key used in automated trading.
Signing REST Requests
For authenticated REST requests, you construct a signature string and include it as a request header. The signature is built from a concatenation of the timestamp, the API key, a receive window value, and the raw query string or request body, then signed using HMAC-SHA256 with your API Secret. The request must include four headers: X-BAPI-API-KEY (your API key), X-BAPI-TIMESTAMP (the current Unix timestamp in milliseconds), X-BAPI-RECV-WINDOW (the allowed time window for the request, typically 5000 milliseconds), and X-BAPI-SIGN (the HMAC-SHA256 signature).
The timestamp used must be within the receive window of Bybit's server time. If your system clock is significantly out of sync, requests will be rejected with a timestamp error. Fetching /v5/market/time before your first authenticated request and comparing it to your local clock is a good practice to verify synchronization.
Authenticating WebSocket Private Streams
For private WebSocket streams, authentication is performed immediately after the connection is established by sending an auth message. The message includes your API key, an expiry timestamp, and a signature generated by signing the string "GET/realtime" + expiry using HMAC-SHA256 with your API Secret. If authentication succeeds, the server responds with a confirmation and you can then subscribe to private topics.
Rate Limits
Bybit enforces rate limits per endpoint category and per API key. Exceeding them results in HTTP 429 responses for REST or error messages on WebSocket. Understanding the limit structure is necessary for any integration that makes frequent requests.
Rate limits on Bybit are expressed as requests per second or per minute depending on the endpoint. Order placement and cancellation endpoints have stricter limits than market data endpoints. The exact limits vary by account tier — higher-volume accounts on Bybit's VIP program have increased rate limits. Current limits are published in the official documentation under the Rate Limit section and should be checked there since they are updated periodically.
Bybit's REST responses include headers that show your current rate limit status: X-Bapi-Limit (total limit), X-Bapi-Limit-Status (remaining requests in the current window), and X-Bapi-Limit-Reset-Timestamp (when the window resets). Reading these headers and implementing backoff logic when the remaining limit approaches zero prevents avoidable rate limit errors.
For WebSocket connections, Bybit limits the number of topics you can subscribe to per connection and the number of simultaneous connections per API key. If you need more concurrent subscriptions than a single connection allows, opening multiple WebSocket connections with the same key is the standard approach.
Key REST Endpoints
The v5 API organizes endpoints into several categories. Below are the most commonly used for trading integrations.
Market Data
GET /v5/market/tickers returns the latest price, 24-hour volume, high, low, and other summary data for one or all instruments in a category. Required parameters are category (spot, linear, inverse, or option) and optionally symbol for a specific instrument.
GET /v5/market/orderbook returns the current order book for a symbol up to a specified depth (1, 25, 50, or 200 levels depending on category). This is used for real-time pricing logic or spread calculations when REST polling is preferred over WebSocket streaming.
GET /v5/market/kline returns historical and recent candlestick data for a symbol and interval. Available intervals include 1, 3, 5, 15, 30, 60, 120, 240, 360, 720 (minutes), D (daily), W (weekly), and M (monthly). Results are paginated with a maximum of 1,000 candles per request.
GET /v5/market/instruments-info returns the full specification of trading instruments: minimum order size, maximum order size, tick size (price increment), lot size (quantity increment), and trading status. This is essential for order validation before submission — placing an order with a quantity below the minimum or not aligned to the lot size will be rejected.
Order Management
POST /v5/order/create places a new order. Required parameters include category, symbol, side (Buy or Sell), orderType (Market or Limit), and qty. For limit orders, price is also required. Optional parameters include timeInForce (GTC, IOC, FOK, PostOnly), orderLinkId (a client-assigned order ID for tracking), and reduceOnly (for futures, to ensure the order only reduces an existing position).
POST /v5/order/cancel cancels an open order by orderId or orderLinkId. Both category and symbol are required. Attempting to cancel an already-filled or cancelled order returns a specific error code rather than silently succeeding.
POST /v5/order/cancel-all cancels all open orders for a symbol or category. This is useful for risk management scenarios where you need to clear all pending orders quickly.
POST /v5/order/amend modifies an existing open order's price or quantity without cancelling and re-placing it. This is more efficient than a cancel-replace cycle and reduces the risk of a gap in market coverage during the modification.
GET /v5/order/realtime returns currently open orders. GET /v5/order/history returns completed, cancelled, and rejected orders with pagination. Both require category and can be filtered by symbol.
Account and Position
GET /v5/account/wallet-balance returns your account balance by coin and wallet type (Unified, Contract, or Spot). The account Type parameter specifies which wallet to query. For unified margin accounts, this endpoint also returns total equity and available margin.
GET /v5/position/list returns open positions for a category and optionally a symbol. Response fields include size, side, entry price, leverage, unrealized PnL, and mark price. For risk management logic, this endpoint provides the data needed to calculate current exposure.
POST /v5/position/set-leverage sets the leverage for a symbol in the futures account. Leverage changes apply to the next position opened in that symbol, not to an existing open position.
Key WebSocket Topics
WebSocket subscriptions are managed by sending JSON messages to the connected stream. The subscribe message format is: {"op": "subscribe", "args": ["topic.symbol"]}.
Public Topics
orderbook.{depth}.{symbol} streams order book snapshots and delta updates. The first message after subscribing is a full snapshot; subsequent messages are incremental deltas showing changes to specific price levels. Maintaining a local order book by applying deltas to the initial snapshot is the standard pattern for latency-sensitive applications.
publicTrade.{symbol} streams every individual trade as it executes, including price, quantity, direction, and timestamp. This is useful for building trade flow analysis or detecting large order activity.
tickers.{symbol} streams real-time updates to the instrument's ticker data, including last price, bid, ask, 24-hour volume, and funding rate for perpetuals. The update frequency is approximately 100 milliseconds.
kline.{interval}.{symbol} streams completed and in-progress candlestick data in real time, useful for strategies that react to candle closes.
Private Topics
order streams updates on your orders in real time: when an order is placed, partially filled, fully filled, cancelled, or rejected. This is the primary mechanism for order tracking in a trading bot, replacing the need to poll GET /v5/order/realtime repeatedly.
position streams changes to your open positions: size changes from fills, unrealized PnL updates, and liquidation events. Monitoring this topic alongside the order topic provides a complete real-time picture of account state.
wallet streams balance updates whenever your available balance changes due to a fill, fee deduction, or fund transfer.
Official SDKs and Client Libraries
Bybit maintains official SDKs that handle authentication, request signing, and WebSocket connection management, reducing the boilerplate required to get started. Official SDKs are available for Python, Go, Java, and TypeScript/JavaScript. They are published under the bybit-exchange organization on GitHub.
The Python SDK (pybit) is the most widely used and is installed via pip: pip install pybit. It provides separate classes for HTTP (REST) and WebSocket sessions. Instantiating an HTTP session with your API key and secret automatically handles signing for all authenticated requests. The WebSocket class manages connection lifecycle, reconnection on disconnect, and message routing to user-defined callback functions.
For JavaScript and TypeScript, the bybit-api package is available via npm. It provides typed interfaces for request parameters and responses, which is particularly useful for catching errors at compile time rather than at runtime.
Community-maintained libraries also exist in languages not covered by official SDKs, though these carry more risk of lagging behind API changes or containing bugs. When using an unofficial library, verifying that it targets the v5 API and checking its last update date against recent Bybit changelog entries is advisable.
Common Integration Patterns
Market Making
A market-making bot typically maintains a WebSocket connection to the order book and ticker topics for its target symbol, uses the real-time data to calculate bid and ask prices, and places limit orders on both sides of the spread using POST /v5/order/create. When the market moves, it amends existing orders using POST /v5/order/amend rather than cancelling and re-placing, which reduces latency and API usage. The private order topic provides fill notifications in real time.
Trend Following
A trend-following bot typically polls kline data from GET /v5/market/kline at the close of each candle to recalculate indicators, then places market or limit orders based on signal logic. Position state is maintained locally and verified periodically against GET /v5/position/list. Stop-loss and take-profit levels can be set directly on the order using the stopLoss and takeProfit parameters on POST /v5/order/create for futures orders.
Automated Risk Management
Risk management integrations typically subscribe to the private position and wallet WebSocket topics to monitor real-time exposure and available margin. If a predefined risk threshold is crossed — maximum drawdown, total position size, or available margin below a floor — the bot calls POST /v5/order/cancel-all to clear open orders and then POST /v5/order/create with reduceOnly set to true to flatten positions.
Error Handling and Debugging
Every REST response includes a retCode. A value of 0 means success. Non-zero values are error codes documented in the API reference under Error Codes. The most common errors include 10001 (parameter error — a required field is missing or has an invalid value), 10002 (timestamp error — your clock is out of sync with Bybit's server), 110001 (order does not exist — often from a race condition when cancelling an already-filled order), and 110004 (insufficient balance).
For WebSocket debugging, Bybit requires periodic ping messages to keep the connection alive. The recommended interval is every 20 seconds. If the server does not receive a ping within 30 seconds, it closes the connection. Handling reconnection logic and re-subscribing to topics after a reconnect is a necessary part of any production WebSocket implementation.
Bybit's API changelog, published in the documentation, lists recent endpoint changes, deprecated parameters, and new features. Subscribing to change notifications or periodically reviewing the changelog prevents integrations from breaking silently when the API evolves.
Final Notes
Bybit's v5 API is well-structured and covers the full range of trading operations across spot, linear, inverse, and options markets through a unified interface. The official documentation at bybit-exchange.github.io/docs/v5/intro is the definitive reference; the testnet environment at api-testnet.bybit.com is the right place to validate any integration before connecting to live markets. For most use cases — order management, market data streaming, position tracking --- the combination of REST for actions and WebSocket for real-time state is the practical pattern, and the official Python or TypeScript SDKs significantly reduce the setup overhead for new integrations.