Algo Trading on Bybit — Getting Started with the API

Last updated: 21 mars 2026

Introduction

Bybit is one of the three largest derivatives exchanges in the world by volume, and one of the most capable platforms available for algorithmic traders on a centralised exchange. Its REST and WebSocket API is well-documented, actively maintained, and backed by an official Python SDK — pybit — that covers all major operations from order placement to account management.

For traders who want the depth and execution quality of a top-tier CEX combined with programmatic access, Bybit offers a mature API environment with full perpetuals support, a live testnet, and native TradingView charting on the interface side.


Contains affiliate links. Learn more →
Bybit exchange — perpetual futures trading interface for algorithmic traders
Perpetual trading on Bybit — Open account →

Why Bybit for Algo Trading

  • Official Python SDKpybit is maintained by the Bybit team, covers REST and WebSocket with clean abstractions
  • Full perpetuals API — all order types supported: limit, market, conditional (stop/TP/SL), reduce-only
  • WebSocket for live data — public streams for tickers, order book and trades; private streams for fills, positions and wallet updates
  • Testnet available — a dedicated testnet environment lets you validate your strategy before going live with real capital
  • Deep liquidity — among the tightest spreads available on BTC/ETH perpetuals, important for strategies sensitive to fill quality
  • High rate limits — Bybit’s API is permissive for most systematic strategies at standard tier

What You Need to Get Started

  • A Bybit account (requires KYC — government ID and liveness check)
  • An API key with trading permissions — generated in account settings
  • Python 3.9+ with pybit installed
  • USDT deposited as collateral on Bybit

Step 1 — Generate an API Key

  1. Log in at bybit.com and go to Account → API Management
  2. Click Create New Key
  3. Choose System-generated API Keys
  4. Set permissions: enable Read and Trade — do not enable withdrawal permissions for trading bots
  5. Copy the API Key and API Secret — the secret is shown only once
  6. Store credentials in a .env file
# .env
BYBIT_API_KEY=your_api_key
BYBIT_API_SECRET=your_api_secret

Step 2 — Install the Python SDK

pip install pybit

The pybit package is the official Bybit SDK, available on PyPI and maintained at github.com/bybit-exchange/pybit.


Step 3 — Connect and Fetch Market Data

import os
from dotenv import load_dotenv
from pybit.unified_trading import HTTP

load_dotenv()

# Public client — no auth needed for market data
session = HTTP(testnet=False)

# Fetch ticker for BTCUSDT perpetual
ticker = session.get_tickers(category="linear", symbol="BTCUSDT")
btc_price = float(ticker["result"]["list"][0]["lastPrice"])
print(f"BTC last price: {btc_price:.2f}")

# Fetch order book (top 25 levels)
orderbook = session.get_orderbook(category="linear", symbol="BTCUSDT", limit=25)
best_bid = orderbook["result"]["b"][0][0]
best_ask = orderbook["result"]["a"][0][0]
print(f"Best bid: {best_bid}  Best ask: {best_ask}")

Step 4 — Place an Order

# Authenticated session
auth_session = HTTP(
    testnet=False,
    api_key=os.getenv("BYBIT_API_KEY"),
    api_secret=os.getenv("BYBIT_API_SECRET"),
)

# Fetch current price
ticker = auth_session.get_tickers(category="linear", symbol="BTCUSDT")
btc_price = float(ticker["result"]["list"][0]["lastPrice"])

# Place a limit buy order
limit_price = round(btc_price * 0.99, 1)  # 1% below market

order = auth_session.place_order(
    category="linear",
    symbol="BTCUSDT",
    side="Buy",
    orderType="Limit",
    qty="0.001",          # size in BTC
    price=str(limit_price),
    timeInForce="GTC",    # Good Till Cancelled
    reduceOnly=False,
    closeOnTrigger=False,
)
print(f"Order ID: {order['result']['orderId']}")

Step 5 — Stream Real-Time Data via WebSocket

pybit includes a built-in WebSocket manager — no manual connection handling required.

from pybit.unified_trading import WebSocket
import time

def handle_ticker(msg):
    data = msg["data"]
    print(f"BTC: {data['lastPrice']}  OI: {data['openInterest']}  Funding: {data['fundingRate']}")

# Public WebSocket — market data
ws = WebSocket(
    testnet=False,
    channel_type="linear",
)
ws.ticker_stream(symbol="BTCUSDT", callback=handle_ticker)

time.sleep(30)  # Stream for 30 seconds

Available public WebSocket streams:ticker — latest price, volume, funding rate, open interest – orderbook — order book depth (1, 50, 200 or 500 levels) – publicTrade — real-time trade feed

Private WebSocket streams (require authentication): – order — order updates and fills – position — position changes – wallet — balance and margin updates


Step 6 — Fetch Historical Candles

import time

def fetch_candles(symbol: str, interval: str, days: int) -> list:
    """
    Fetch OHLCV candles from Bybit.
    interval: "1", "3", "5", "15", "30", "60", "120", "240", "D"
    """
    end_ms   = int(time.time() * 1000)
    start_ms = end_ms - days * 24 * 60 * 60 * 1000

    result = session.get_kline(
        category="linear",
        symbol=symbol,
        interval=interval,
        start=start_ms,
        end=end_ms,
        limit=1000,
    )
    return result["result"]["list"]

candles = fetch_candles("BTCUSDT", "60", days=7)  # 1H candles, 7 days
print(f"Fetched {len(candles)} candles")
for c in candles[-3:]:
    # Format: [startTime, open, high, low, close, volume, turnover]
    print(f"  O:{c[1]}  H:{c[2]}  L:{c[3]}  C:{c[4]}  V:{c[5]}")

Testing on Testnet

Bybit provides a full testnet environment — create a separate account at testnet.bybit.com, generate testnet API keys there, and set testnet=True in the SDK:

session = HTTP(
    testnet=True,
    api_key="your_testnet_api_key",
    api_secret="your_testnet_api_secret",
)

The testnet mirrors mainnet API structure exactly — all endpoints and order types are identical. Fund your testnet account using the built-in faucet.


Bybit API Quick Reference

ActionTypeSDK Call
Get ticker / latest priceREST (public)session.get_tickers(category, symbol)
Get order bookREST (public)session.get_orderbook(category, symbol, limit)
Get candlesREST (public)session.get_kline(category, symbol, interval, start, end)
Get account infoREST (private)session.get_wallet_balance(accountType)
Get positionsREST (private)session.get_positions(category, symbol)
Place orderREST (private)session.place_order(category, symbol, side, orderType, qty, …)
Cancel orderREST (private)session.cancel_order(category, symbol, orderId)
Stream tickerWebSocket publicws.ticker_stream(symbol, callback)
Stream order bookWebSocket publicws.orderbook_stream(depth, symbol, callback)
Stream fills / ordersWebSocket privatews_private.order_stream(callback)

Key Takeaways

  • Bybit’s official Python SDK (pybit) handles authentication, REST and WebSocket — install with pip install pybit
  • Authentication uses API Key + Secret (HMAC-SHA256) — enable Trade permissions only, never withdrawal permissions on a bot key
  • Use category="linear" for USDT-margined perpetuals throughout — this is the standard for most algo strategies
  • A full testnet is available at testnet.bybit.com — always validate your strategy there before going live
  • WebSocket streams via pybit require no manual connection management — pass a callback function and the SDK handles the rest

Useful Links


For a general introduction to algo trading concepts and strategy design, see our Algorithmic Trading guide. For building a full data pipeline with TimescaleDB and WebSocket feeds, see our Build Your Own Trading Application page.

TradFiDefi

Advanced market analysis at the intersection of traditional finance and blockchain technology.

Explore
About
Connect
Follow on X Read on Substack
Cookie settings | Affiliate disclosure
Rulla till toppen
Curated Resources
Affiliate disclosure ↗
Exchanges
Hyperliquid Decentralised

The leading on-chain perpetual exchange. No KYC, deep liquidity, native token incentives.

Open account →
Bybit Centralised

Broad market access, strong derivatives offering and competitive fees for active traders.

Open account →
Apex Protocol Decentralised

ZK-rollup perpetuals with cross-margin portfolio system and multi-chain deposit support.

Open account →
Lighter Decentralised

Fully on-chain verifiable order book. Zero trading fees and up to 252 API keys per account.

Open account →
Wallets
Ledger Hardware

The market-leading hardware wallet. Cold storage for long-term holdings with broad asset support.

View devices →
Trezor Hardware

Open-source hardware wallet with a strong security track record. Good alternative to Ledger.

View devices →
Tangem Hardware

Card-format hardware wallet. No seed phrase by design — a different security model worth understanding.

View devices →
Services
Glassnode On-Chain Data

The gold standard for Bitcoin and Ethereum on-chain analytics. MVRV, SOPR, LTH supply and more.

Explore platform →
TradingView Charting

The industry standard for crypto charting. Cross-asset coverage, custom indicators and alerts.

Start charting →
CoinGlass Derivatives Data

Open interest, funding rates and liquidation maps across all major exchanges in one dashboard.

Explore platform →