Getting started overview
Integrating with the Bybit API allows developers to automate trading strategies, retrieve real-time market data, and manage account operations programmatically. The process begins with setting up a Bybit account and securing API credentials, followed by constructing and authenticating API requests. Bybit offers various API endpoints for different product types, including Spot, USDT Perpetuals, and Inverse Perpetuals, each with specific request formats and authentication requirements. Understanding the distinctions between these interfaces is important for successful integration.
Before making your first API call, it is recommended to review the official Bybit API documentation to identify the specific endpoints and parameters relevant to your intended operations. Bybit supports RESTful API access, and provides SDKs in multiple programming languages to streamline the development process.
Here is a quick reference table outlining the initial steps:
| Step | What to do | Where to go |
|---|---|---|
| 1. Account Creation | Register for a Bybit account. | Bybit Homepage |
| 2. Identity Verification (KYC) | Complete Level 1 or Level 2 Identity Verification. | Bybit Account Security Settings |
| 3. API Key Generation | Create new API keys and set permissions. | Bybit API Management Page |
| 4. Environment Setup | Install necessary SDKs or libraries. | Local development environment |
| 5. First API Request | Send a public or private API call. | Bybit API Endpoints (e.g., /v5/market/time) |
Create an account and get keys
To interact with the Bybit API, you must first create an account and generate API credentials. This process involves several security and verification steps.
-
Register for a Bybit Account: Navigate to the Bybit homepage and complete the registration process using your email or mobile number. New accounts typically require email or SMS verification.
-
Complete Identity Verification (KYC): Bybit requires users to complete identity verification (Know Your Customer) to access certain features and higher withdrawal limits. This usually involves submitting identification documents. You can initiate this process from your account's Identity Verification page. Bybit offers Level 1 and Level 2 verification, with varying requirements and benefits.
-
Enable Two-Factor Authentication (2FA): For enhanced security, it is recommended to enable 2FA using Google Authenticator or SMS verification. This is accessible within your account's Security Settings.
-
Generate API Keys: Once your account is set up and secured, you can generate API keys. Go to your API Management page. Click "Create New Key" and configure its permissions. You will receive an API Key and an API Secret. The API Secret is only displayed once, so ensure you save it securely. When setting permissions, consider the principle of least privilege, granting only the necessary access for your application (e.g., read-only for market data, trade access for order placement).
- API Key: A unique identifier for your application.
- API Secret: A cryptographic key used to sign private requests, ensuring their authenticity.
- Permissions: Define what actions your API key can perform (e.g., read market data, place orders, access wallet).
-
IP Whitelisting (Optional but Recommended): For additional security, you can whitelist specific IP addresses that are allowed to access your API keys. This restricts access to only trusted environments, reducing the risk of unauthorized use if your keys are compromised. This setting is available during API key creation or modification on the API Management page.
Your first request
After obtaining your API Key and Secret, you can make your first API request. This example demonstrates a public endpoint call to retrieve the server time, which does not require authentication, and a private endpoint call to check account balance, which does require authentication.
Public Endpoint Example: Get Server Time
A public endpoint does not require signing with your API Secret. This example uses the /v5/market/time endpoint to get the current server time.
Endpoint: https://api.bybit.com/v5/market/time
Method: GET
Python Example (using requests library):
import requests
url = "https://api.bybit.com/v5/market/time"
response = requests.get(url)
if response.status_code == 200:
print("Server Time:", response.json())
else:
print("Error:", response.status_code, response.text)
This script makes a GET request to the Bybit server time endpoint and prints the JSON response, which includes the current timestamp.
Private Endpoint Example: Get Wallet Balance
Private endpoints require authentication using your API Key and a cryptographically signed payload. The signature is generated using HMAC-SHA256 with your API Secret. This example retrieves your wallet balance using the /v5/account/wallet-balance endpoint.
Endpoint: https://api.bybit.com/v5/account/wallet-balance
Method: GET
Python Example (using requests and hmac libraries):
import requests
import hmac
import hashlib
import time
import json
API_KEY = "YOUR_API_KEY"
API_SECRET = "YOUR_API_SECRET"
def generate_signature(payload, api_secret):
# Bybit requires a specific format for signing private requests
# For GET requests, the payload is typically the query string
# For POST requests, it's the JSON body concatenated without spaces
# This example assumes a GET request with no body, only query parameters
# The parameters must be sorted alphabetically
# For /v5/account/wallet-balance, the category parameter is required
params = {
"category": "spot", # or "linear", "inverse", etc.
"timestamp": str(int(time.time() * 1000)),
"api_key": API_KEY
}
# Sort parameters alphabetically by key
sorted_params = sorted(params.items())
query_string = "&".join([f"{k}={v}" for k, v in sorted_params])
# Construct the message to be signed (timestamp + API_KEY + recv_window + query_string)
# recv_window is often default to 5000ms, but explicitly including it is safer
# For Bybit V5, the signature string format is: timestamp + api_key + recv_window + query_string
# The Bybit V5 documentation specifies `recv_window` as part of the signature string
recv_window = "5000" # default recv_window
sign_string = params["timestamp"] + API_KEY + recv_window + query_string
hex_signature = hmac.new(bytes(api_secret, "utf-8"), bytes(sign_string, "utf-8"), hashlib.sha256).hexdigest()
return hex_signature, params
# Generate signature and parameters
signature, params = generate_signature(None, API_SECRET) # Payload is None for GET request body
# Construct the final URL with query parameters
base_url = "https://api.bybit.com/v5/account/wallet-balance"
query_string = "&".join([f"{k}={v}" for k, v in params.items()])
full_url = f"{base_url}?{query_string}"
headers = {
"X-BAPI-API-KEY": API_KEY,
"X-BAPI-SIGN": signature,
"X-BAPI-TIMESTAMP": params["timestamp"],
"X-BAPI-RECV-WINDOW": "5000" # Must match the recv_window used in signature generation
}
response = requests.get(full_url, headers=headers)
if response.status_code == 200:
print("Wallet Balance:", response.json())
else:
print("Error:", response.status_code, response.text)
try:
print("API Error Details:", response.json())
except json.JSONDecodeError:
print("Non-JSON error response.")
Replace "YOUR_API_KEY" and "YOUR_API_SECRET" with your actual credentials. This script demonstrates how to construct the signature, append required headers, and send a GET request to a private endpoint. The category parameter is essential for the wallet-balance endpoint, specifying which product's balance to retrieve (e.g., spot, linear, inverse).
Developers should be aware of the specific signature requirements for Bybit's API, which can vary slightly between API versions (e.g., V3 vs. V5) and request methods (GET vs. POST). The Bybit V5 Authentication guide provides detailed instructions on signature generation.
Common next steps
After successfully making your first API calls, consider these common next steps to further integrate with Bybit:
-
Explore Other Endpoints: Review the Bybit API reference for endpoints related to placing orders, managing positions, retrieving historical data, and accessing more detailed account information. Different product types (Spot, Derivatives) have distinct sets of endpoints.
-
Implement WebSockets: For real-time market data and user updates (e.g., order fills, balance changes), Bybit offers WebSocket APIs. Implementing WebSockets provides lower latency data streams compared to polling REST endpoints. Consult the Bybit WebSocket documentation for connection details and subscription channels.
-
Utilize SDKs: While direct HTTP requests are demonstrated, Bybit provides official and community-maintained SDKs for Python, Java, Node.js, and Go. These SDKs abstract away the complexities of signature generation and request formatting, simplifying development.
-
Error Handling and Rate Limits: Implement robust error handling in your application to gracefully manage API responses, especially for rate limit errors (HTTP 429) or invalid parameters. The Bybit API FAQ on rate limits provides details on current restrictions.
-
Security Best Practices: Always store your API Secret securely (e.g., environment variables, secret management services) and never hardcode it directly into your application's source code. Regularly review and rotate your API keys. Consider using OAuth 2.0 if building applications for multiple users, though Bybit's API primarily uses API key authentication for direct integrations.
-
Testing with Testnet: Before deploying strategies to the live market, test your code thoroughly on Bybit's Testnet environment. This allows you to simulate trading and API interactions without risking real funds. The Testnet API endpoint is typically
https://api-testnet.bybit.com.
Troubleshooting the first call
Encountering issues during your initial API calls is common. Here are some troubleshooting tips for Bybit API integration:
-
Check API Key and Secret: Ensure your API Key and API Secret are copied correctly without leading or trailing spaces. The API Secret is only shown once upon creation.
-
Verify Permissions: Confirm that the API key you are using has the necessary permissions for the endpoint you are calling (e.g., "Read Data" for public endpoints, "Trade" for placing orders, "Withdraw" for withdrawals). You can review and modify API key permissions on the API Management page.
-
Signature Mismatch (Error 10001, 10003): This is a frequent issue for private endpoints. Double-check the signature generation process:
- Timestamp: Ensure the
X-BAPI-TIMESTAMPheader is a Unix timestamp in milliseconds and is within the allowedrecv_window(default 5000ms) of the server's time. Your local clock might be out of sync. - Parameter Order: For query strings or JSON bodies, parameters must be sorted alphabetically by key before concatenation for signing.
recv_window: TheX-BAPI-RECV-WINDOWheader and therecv_windowvalue used in the signature string must match.- Concatenation: Ensure the string constructed for signing (
timestamp + api_key + recv_window + query_stringfor GET, ortimestamp + api_key + recv_window + bodyfor POST) is precisely as specified in the Bybit V5 Authentication guide. No extra spaces or characters. - HMAC Algorithm: Confirm you are using HMAC-SHA256.
- Timestamp: Ensure the
-
Invalid IP Address (Error 10005): If you have enabled IP whitelisting, ensure the IP address from which your API call originates is added to the allowed list in your API key settings. If your IP address changes frequently, consider disabling this feature, but be aware of the security implications.
-
Rate Limit Exceeded (HTTP 429): If you receive a 429 status code, you have sent too many requests within a short period. Implement exponential backoff or ensure your application adheres to the Bybit API rate limits. Check the
Retry-Afterheader if provided. -
Incorrect Endpoint or Version: Ensure you are using the correct base URL (e.g.,
api.bybit.comfor live,api-testnet.bybit.comfor testnet) and the correct API version prefix (e.g.,/v5/). Endpoints can vary between versions and product types (Spot vs. Derivatives). -
Check Response Details: Bybit API error responses often include a
retCodeandretMsgfield that provide specific details about the error. Parse these fields to understand the cause. -
Consult Official Documentation: The Bybit API documentation is the authoritative source for endpoint specifics, error codes, and authentication procedures. Refer to it for the most up-to-date information.