โ† ะะฐะทะฐะด

Bybit API v5 โ€” Technical Research Summary

Compiled from Bybit official documentation (bybit-exchange.github.io/docs/v5/). Verify URLs and rate limits against live docs before production use.


1. Overview

Bybit V5 API โ€” unified API, consolidates all previous endpoints (V2 Spot, V3 USDT Perpetual, V3 Inverse) into a single interface. Parameter category selects product type: spot, linear, inverse, option.


2. Authentication

API Key Setup

  1. Bybit Account โ†’ API Management โ†’ Create New Key
  2. Key types: System-Generated (HMAC) or Self-Generated (RSA)
  3. Set permissions: Read-Only, Trade, Wallet Transfer
  4. IP Whitelist โ€” strongly recommended for production

Request Signing (HMAC-SHA256)

Headers required:

Header Value
X-BAPI-API-KEY Your API key
X-BAPI-SIGN HMAC-SHA256 signature
X-BAPI-SIGN-TYPE 2
X-BAPI-TIMESTAMP Current timestamp in ms
X-BAPI-RECV-WINDOW Recv window (default 5000ms)

Signature formula:

param_str = timestamp + api_key + recv_window + payload
signature = HMAC-SHA256(api_secret, param_str)

3. Base URLs

Mainnet

Type URL
REST https://api.bybit.com
REST (backup) https://api.bytick.com
WS Public (Linear) wss://stream.bybit.com/v5/public/linear
WS Public (Spot) wss://stream.bybit.com/v5/public/spot
WS Public (Inverse) wss://stream.bybit.com/v5/public/inverse
WS Public (Option) wss://stream.bybit.com/v5/public/option
WS Private wss://stream.bybit.com/v5/private

Testnet

Type URL
REST https://api-testnet.bybit.com
WS Public (Linear) wss://stream-testnet.bybit.com/v5/public/linear
WS Private wss://stream-testnet.bybit.com/v5/private
Web UI https://testnet.bybit.com

Testnet setup: Register at testnet.bybit.com (separate account), create API key there, get free testnet USDT from faucet. All endpoints identical to mainnet.


4. REST Endpoints

4.1 Market Data (Public, no auth)

GET /v5/market/tickers?category=linear&symbol=BTCUSDT
GET /v5/market/kline?category=linear&symbol=BTCUSDT&interval=15&limit=200
GET /v5/market/orderbook?category=linear&symbol=BTCUSDT&limit=50
GET /v5/market/recent-trade?category=linear&symbol=BTCUSDT&limit=60
GET /v5/market/instruments-info?category=linear&symbol=BTCUSDT
GET /v5/market/funding/history?category=linear&symbol=BTCUSDT
GET /v5/market/risk-limit?category=linear&symbol=BTCUSDT

Kline intervals: 1, 3, 5, 15, 30, 60, 120, 240, 360, 720, D, W, M

4.2 Place Order

POST /v5/order/create
{
  "category": "linear",
  "symbol": "BTCUSDT",
  "side": "Buy",
  "orderType": "Limit",
  "qty": "0.01",
  "price": "60000",
  "timeInForce": "GTC",
  "positionIdx": 0,
  "takeProfit": "65000",
  "stopLoss": "58000",
  "tpTriggerBy": "LastPrice",
  "slTriggerBy": "LastPrice",
  "tpslMode": "Full",
  "tpOrderType": "Market",
  "slOrderType": "Market"
}

Key parameters:

4.3 Manage Orders

POST /v5/order/amend          โ€” modify price/qty/SL/TP
POST /v5/order/cancel         โ€” cancel single
POST /v5/order/cancel-all     โ€” cancel all
GET  /v5/order/realtime       โ€” open orders
GET  /v5/order/history        โ€” order history

4.4 Positions

GET  /v5/position/list                    โ€” open positions
POST /v5/position/set-leverage            โ€” set leverage (1-100x)
POST /v5/position/switch-isolated         โ€” cross/isolated margin
POST /v5/position/set-trading-stop        โ€” modify TP/SL/trailing stop
POST /v5/position/switch-mode             โ€” one-way <-> hedge mode

4.5 Account & Wallet

GET  /v5/account/wallet-balance?accountType=UNIFIED
GET  /v5/account/fee-rate?category=linear&symbol=BTCUSDT
POST /v5/asset/transfer/inter-transfer    โ€” between accounts

5. WebSocket Streams

Connection & Heartbeat

Public Streams (no auth)

{
  "op": "subscribe",
  "args": [
    "orderbook.50.BTCUSDT",
    "publicTrade.BTCUSDT",
    "kline.15.BTCUSDT",
    "tickers.BTCUSDT"
  ]
}
Topic Format Description
Orderbook orderbook.{depth}.{symbol} Depths: 1, 50, 200, 500
Trades publicTrade.{symbol} Real-time trades
Kline kline.{interval}.{symbol} Candlestick updates
Tickers tickers.{symbol} 24h snapshot
Liquidation liquidation.{symbol} Liquidation events

Private Streams (auth required)

Auth message:

{
  "op": "auth",
  "args": ["API_KEY", EXPIRES_TIMESTAMP, "HMAC_SIGNATURE"]
}

Signature: HMAC-SHA256(secret, "GET/realtime" + expires)

Topics: position, execution, order, wallet


6. Rate Limits

Endpoint Type Rate Limit
Market data (public) 120 req/s per IP
Order create 10 req/s per symbol per account
Order amend 10 req/s per symbol per account
Order cancel 10 req/s per symbol per account
Batch orders 10 req/s (up to 20 orders per batch)
Position endpoints 10 req/s
Account/Wallet 10 req/s

Rate limit headers: X-Bapi-Limit, X-Bapi-Limit-Status, X-Bapi-Limit-Reset-Timestamp


7. Python SDK โ€” pybit

Installation

pip install pybit

REST Example

from pybit.unified_trading import HTTP

session = HTTP(
    testnet=True,
    api_key="YOUR_API_KEY",
    api_secret="YOUR_API_SECRET",
)

# Market data (no auth)
tickers = session.get_tickers(category="linear", symbol="BTCUSDT")
klines = session.get_kline(category="linear", symbol="BTCUSDT", interval=15, limit=200)
orderbook = session.get_orderbook(category="linear", symbol="BTCUSDT", limit=25)

# Account
balance = session.get_wallet_balance(accountType="UNIFIED")
positions = session.get_positions(category="linear", symbol="BTCUSDT")

# Place order with TP/SL
order = session.place_order(
    category="linear",
    symbol="BTCUSDT",
    side="Buy",
    orderType="Market",
    qty="0.01",
    takeProfit="65000",
    stopLoss="58000",
    tpTriggerBy="LastPrice",
    slTriggerBy="LastPrice",
)

# Set leverage
session.set_leverage(category="linear", symbol="BTCUSDT", buyLeverage="10", sellLeverage="10")

WebSocket Example

from pybit.unified_trading import WebSocket
from time import sleep

ws_public = WebSocket(testnet=True, channel_type="linear")

def handle_orderbook(msg):
    print(f"Orderbook: {msg}")

ws_public.orderbook_stream(depth=50, symbol="BTCUSDT", callback=handle_orderbook)
ws_public.trade_stream(symbol="BTCUSDT", callback=lambda m: print(m))
ws_public.kline_stream(interval=5, symbol="BTCUSDT", callback=lambda m: print(m))

# Private WS
ws_private = WebSocket(testnet=True, channel_type="private", api_key="KEY", api_secret="SECRET")
ws_private.position_stream(callback=lambda m: print(m))
ws_private.order_stream(callback=lambda m: print(m))

while True:
    sleep(1)

8. Node.js SDK โ€” bybit-api

npm install bybit-api
const { RestClientV5, WebsocketClient } = require('bybit-api');

const client = new RestClientV5({
  testnet: true,
  key: 'YOUR_API_KEY',
  secret: 'YOUR_API_SECRET',
});

// Place order
const order = await client.submitOrder({
  category: 'linear',
  symbol: 'BTCUSDT',
  side: 'Buy',
  orderType: 'Market',
  qty: '0.01',
  takeProfit: '65000',
  stopLoss: '58000',
});

// WebSocket
const wsClient = new WebsocketClient({ market: 'v5', testnet: true });
wsClient.on('update', (data) => console.log('WS:', data));
wsClient.subscribeV5(['orderbook.50.BTCUSDT', 'publicTrade.BTCUSDT'], 'linear');

npm package: bybit-api by Tiago Siebler (TypeScript, well-maintained).


9. Risk Management Features

Feature Description
TP/SL on order Set at order time, triggers market/limit close
Trailing Stop Dynamic SL via trailingStop param
Partial TP/SL tpslMode: "Partial" for portion of position
Leverage Control set-leverage (1x-100x per symbol)
Risk Limit Max position size tiers
Reduce Only Prevents accidental position increase
Hedge Mode Separate long/short simultaneously
Cross vs Isolated Margin Per-position margin mode

Position Sizing Helper

def calculate_position_size(balance, risk_pct, entry, stop_loss):
    risk_amount = balance * risk_pct
    distance = abs(entry - stop_loss)
    return round(risk_amount / distance, 4)

# $10k balance, 1% risk, entry $60k, SL $59k -> 0.1 BTC

10. Response Format

{
  "retCode": 0,
  "retMsg": "OK",
  "result": { "list": [...] },
  "retExtInfo": {},
  "time": 1234567890123
}

retCode: 0 = success. Common errors: 10001 (param error), 10003 (invalid key), 110007 (insufficient balance).


11. Quick Start Checklist

  1. Register on testnet.bybit.com
  2. Create API key with Trade permission
  3. Install SDK: pip install pybit or npm install bybit-api
  4. Set testnet=True, test market data (no auth needed)
  5. Place a test order on testnet
  6. Set up WebSocket for real-time data
  7. Implement position sizing and SL/TP logic
  8. When ready: switch to mainnet, enable IP whitelist, start with minimal size

Key Links