Pybit
Pybit is the official Python3 connector for Bybit's HTTP and WebSocket APIs, offering a lightweight and efficient way to interact with the Bybit exchange. The library is actively developed, ensuring new Bybit API changes arrive quickly, and is currently at version 5.15.0.
Common errors
-
{"retCode": 10003, "retMsg": "API key is invalid.", "result": {}}cause The API key used is either incorrect, expired, or generated for the wrong environment (testnet key used on mainnet or vice-versa).fixVerify your `api_key` and `api_secret`. Ensure the `testnet` parameter in your `HTTP` or `WebSocket` client matches the environment your keys are from. -
{"retCode": 10006, "retMsg": "Too many visits!", "result": {}}cause Your application is sending requests to the Bybit API faster than the allowed rate limit for that endpoint.fixImplement an exponential backoff strategy with random jitter to space out your API calls, or reduce the frequency of your requests. -
{"retCode": 10001, "retMsg": "Parameter Error: qty precision is 0.001.", "result": {}}cause The quantity or price specified in your order does not conform to the instrument's required precision or step size.fixQuery `get_instruments_info()` for the specific symbol to get `qtyStep` and `minOrderQty`. Always round your order quantities and prices to these exact specifications. -
pybit.exceptions.FailedRequestError: Http status code is not 200. (ErrCode: 404)
cause The requested API endpoint was not found, often due to an incorrect `category` parameter, or an invalid endpoint path if manually specifying.fixDouble-check the `category` parameter (e.g., 'linear', 'spot', 'inverse') and ensure all required parameters for the specific method are correct according to Bybit's V5 API documentation. -
You have breached the ip rate limit. (ErrCode: 403)
cause Your external IP address has exceeded a platform-wide rate limit, possibly in shared hosting environments like PythonAnywhere.fixThis is typically an infrastructure issue. If on shared hosting, contact your provider or consider a dedicated IP/server. If self-hosting, ensure your application adheres to IP-based rate limits.
Warnings
- breaking The `set_limit_price_action()` HTTP endpoint no longer accepts any arguments as of `v5.14.0`.
- deprecated Older Crypto Loan HTTP endpoints were deprecated in `v5.14.0rc0`.
- gotcha API keys generated for Bybit's testnet are incompatible with the mainnet endpoint, and vice-versa. Using mismatched keys will result in an 'Invalid API Key' error (`retCode: 10003`).
- gotcha Bybit API enforces strict precision and step sizes for order quantities and prices. Incorrect values will result in a 'Parameter Error' (`retCode: 10001`).
- gotcha Exceeding Bybit's API rate limits will lead to 'Too many visits!' (`retCode: 10006`).
Install
-
pip install pybit
Imports
- HTTP
from pybit import usdt_perpetual
from pybit.unified_trading import HTTP
- WebSocket
from pybit import usdt_perpetual
from pybit.unified_trading import WebSocket
- AsyncHTTP
from pybit.unified_trading import AsyncHTTP
- AsyncWebSocket
from pybit.unified_trading import AsyncWebSocket
Quickstart
import os
from pybit.unified_trading import HTTP
# It's recommended to store API keys in environment variables
api_key = os.environ.get('BYBIT_API_KEY', 'YOUR_API_KEY')
api_secret = os.environ.get('BYBIT_API_SECRET', 'YOUR_API_SECRET')
# Initialize an authenticated HTTP session for the unified trading API
# Set testnet=True for testing on Bybit's testnet
session = HTTP(
testnet=True, # Change to False for mainnet
api_key=api_key,
api_secret=api_secret,
)
try:
# Example: Get wallet balance (requires authentication)
response = session.get_wallet_balance(accountType="UNIFIED")
print("Authentication successful. Total Equity:", response["result"]["list"][0]["totalEquity"])
# Example: Get market tickers (does not require authentication)
tickers = session.get_tickers(category="linear", symbol="BTCUSDT")
print("BTCUSDT Mark Price:", tickers["result"]["list"][0]["markPrice"])
except Exception as e:
print(f"An error occurred: {e}")
print("Please ensure your API keys are correct and match the testnet/mainnet setting.")