繁體中文
NAV
console python

Group And Resources

Bybit API and WebSocket documentation provides guidance to help you access Bybit's endpoints, their expected outputs, and common errors.

For further assistance or feedback, please join the API Telegram chat! API discussion group on Telegram.

Group And Bybit API Resources

Changelog

2021-07-12

REST API

2021-06-17

REST API

2021-05-27

REST API

Authentication

All requests made to private endpoints must be authenticated. Requests made to public endpoints do not require additional authentication.

Parameters for Authenticated Endpoints

The following parameters must be used for authentication:

We also provide recvWindow (unit in millisecond and default value is 5,000) to specify how long an HTTP request is valid. It is also used to prevent replay attacks.

A smaller recvWindow is more secure, but your request may fail if the transmission time is greater than your recvWindow.

Please make sure that your timestamp is in sync with our server time. You can use the Server Time endpoint.

Create A Request

An example for balance query

param_str = "api_key=B2Rou0PLPpGqcU0Vu2&timestamp=1542434791747"
param_str = "api_key=B2Rou0PLPpGqcU0Vu2&timestamp=1542434791747"

# api_key=B2Rou0PLPpGqcU0Vu2&
# leverage=100&
# symbol=BTCUSDH21&
# timestamp=1542434791747

Note how the parameters are ordered in alphabetical order, with api_key first followed by timestamp.

1. Concatenate all the public parameters in the query string format. The parameters must be ordered in alphabetical order. This will be used to generate the sign.

2. Use the HMAC_SHA256 algorithm to sign the query string in step 1, and convert it to a hex string to obtain the sign parameter.

Different requests need different message formats. Message format for GET requests:

GET /spot/v1/order?api_key=q1ksyOX2T0G2SkK8nu&recvWindow=10000&timestamp=1623208423972&sign=b452640c21a2c9eaec30d24a9bce1a9660d1fb9d07ccc0d623a2a4fca0940095 HTTP/1.1
Host: api-testnet.bybit.com

Message format for POST requests:

POST /spot/v1/order HTTP/1.1
Host: api-testnet.bybit.com
Content-Type: application/x-www-form-urlencoded

api_key:q1ksyOX2T0G2SkK8nu
qty:100
recvWindow:10000
side:BUY
symbol:BTCUSDT
timestamp:1623208423972
type:MARKET
sign:b452640c21a2c9eaec30d24a9bce1a9660d1fb9d07ccc0d623a2a4fca0940095

3. Append the sign parameter to the end of the parameters string, and send the HTTP request. Note that the message format for GET and POST requests is different. Please refer to the examples.

Market Data Endpoints

The following market data endpoints do not require authentication.

Query Symbol

Request Example

Response Example

{
    "ret_code": 0,
    "ret_msg": "",
    "ext_code": null,
    "ext_info": null,
    "result": [
        {
            "name": "BTCUSDT",
            "alias": "BTCUSDT",
            "baseCurrency": "BTC",
            "quoteCurrency": "USDT",
            "basePrecision": "0.000001",
            "quotePrecision": "0.01",
            "minTradeQuantity": "0.0001",
            "minTradeAmount": "10",
            "minPricePrecision": "0.01",
            "maxTradeQuantity": "2",
            "maxTradeAmount": "200",
            "category": 1
        },
        {
            "name": "ETHUSDT",
            "alias": "ETHUSDT",
            "baseCurrency": "ETH",
            "quoteCurrency": "USDT",
            "basePrecision": "0.0001",
            "quotePrecision": "0.01",
            "minTradeQuantity": "0.0001",
            "minTradeAmount": "10",
            "minPricePrecision": "0.01",
            "maxTradeQuantity": "2",
            "maxTradeAmount": "200",
            "category": 1
        }
    ]
}

HTTP Request

GET /spot/v1/symbols

Request Parameters

Parameter Required Type Comment

Response Parameters

Parameter Type Comment
name string Name of the trading pair
alias string Alias
baseCurrency string Base currency
quoteCurrency string Quote currency
basePrecision string Decimal precision (base currency)
quotePrecision string Decimal precision (quote currency)
minTradeQuantity string Min. order qty
minTradeAmount string Min. order value
minPricePrecision string Min. number of decimal places
maxTradeQuantity string Max. order qty
maxTradeAmount string Max. order value
category int Category

Order Book

Request Example

Response Example

{
    "ret_code": 0,
    "ret_msg": null,
    "result": {
        "time": 1620886105740,
        "bids": [
            [
                "50005.12",
                "403.0416"
            ]
        ],
        "asks": [
            [
                "50006.34",
                "0.2297"
            ]
        ]
    },
    "ext_code": null,
    "ext_info": null
}

HTTP Request

GET /spot/quote/v1/depth

Request Parameters

Parameter Required Type Comment
symbol true string Name of the trading pair
limit false integer Default value is 100

Response Parameters

Parameter Type Comment
time long Current time, unit in millisecond
bids string Bid price and quantity, with best bid prices ranked from top to bottom
asks string Ask price and quantity, with best ask prices ranked from top to bottom

Merged Order Book

Request Example

Response Example

{
    "ret_code": 0,
    "ret_msg": null,
    "result": {
        "time": 1620891567679,
        "bids": [
            [
                "50008",
                "1.8501"
            ]
        ],
        "asks": [
            [
                "70000",
                "1"
            ]
        ]
    },
    "ext_code": null,
    "ext_info": null
}

HTTP Request

GET /spot/quote/v1/depth/merged

Request Parameters

Parameter Required Type Comment
symbol true string Name of the trading pair
scale false int Precision of the merged orderbook, 1 means 1 digit
limit false integer Default value is 100

Response Parameters

Parameter Type Comment
time long Current time, unit in millisecond
bids string Bid price and quantity, with best bid prices ranked from top to bottom
asks string Ask price and quantity, with best ask prices ranked from top to bottom

Public Trading Records

Request Example

Response Example

{
    "ret_code": 0,
    "ret_msg": null,
    "result": [
        {
            "price": "50005.12",
            "time": 1620822657672,
            "qty": "0.0001",
            "isBuyerMaker": true
        },
        {
            "price": "50008.34",
            "time": 1620891050659,
            "qty": "0.0001",
            "isBuyerMaker": true
        },
        {
            "price": "50008.34",
            "time": 1620891093266,
            "qty": "0.0001",
            "isBuyerMaker": true
        }
    ],
    "ext_code": null,
    "ext_info": null
}

HTTP Request

GET /spot/quote/v1/trades

Request Parameters

Parameter Required Type Comment
symbol true string Name of the trading pair
limit false integer Default value is 1000, max 10,000

Response Parameters

Parameter Type Comment
price float Order price
time long Current timestamp, unit in millisecond
qty float Order quantity
isBuyerMaker bool True indicates buy order, false indicates sell order

Query Kline

Request Example

Response Example

{
    "ret_code": 0,
    "ret_msg": null,
    "result": [
        [
            1620917160000,
            "50008",
            "50008",
            "50008",
            "50008",
            "0",
            0,
            "0",
            0,
            "0",
            "0"
        ]
    ],
    "ext_code": null,
    "ext_info": null
}

HTTP Request

GET /spot/quote/v1/kline

Request Parameters

Parameter Required Type Comment
symbol true string Name of the trading pair
interval true string Chart interval
limit false integer Default value is 1000, max 10,000
startTime false number Start time, unit in millisecond
endTime false number End time, unit in millisecond

Response Parameters

Parameter Type Comment
startTime long Start time, unit in millisecond
open float Open price
high float High price
low float Low price
close float Close price
volume float Trading volume
endTime long End time, unit in millisecond
quoteAssetVolume float Quote asset volume
trades integer Number of trades
takerBaseVolume float Taker buy volume in base asset
takerQuoteVolume float Taker buy volume in quote asset

Latest Information for Symbol

Request Example

Response Example

{
    "ret_code": 0,
    "ret_msg": null,
    "result": {
        "time": 1620918180046,
        "symbol": "ETHUSDT",
        "bestBidPrice": "50005.12",
        "bestAskPrice": "50008",
        "volume": "26.7308",
        "quoteVolume": "1337500.362672",
        "lastPrice": "50008",
        "highPrice": "70000",
        "lowPrice": "50005.12",
        "openPrice": "50005.12"
    },
    "ext_code": null,
    "ext_info": null
}

HTTP Request

GET /spot/quote/v1/ticker/24hr

Request Parameters

Parameter Required Type Comment
symbol false string Name of the trading pair

Response Parameters

Parameter Type Comment
time long Current timestamp, unit in millisecond
symbol string Name of the trading pair
bestBidPrice float Best bid price
bestAskPrice float Best ask price
lastPrice float Last traded price
openPrice float Open price
highPrice float High price
lowPrice float Low price
volume float Trading volume
quoteVolume float Trading quote volume

Last Traded Price

Request Example

Response Example

{
    "ret_code": 0,
    "ret_msg": null,
    "result": {
        "symbol": "ETHUSDT",
        "price": "50008"
    },
    "ext_code": null,
    "ext_info": null
}

HTTP Request

GET /spot/quote/v1/ticker/price

Request Parameters

Parameter Required Type Comment
symbol false string Name of the trading pair

Response Parameters

Parameter Type Comment
symbol string Name of the trading pair
price float Last traded price

Best Bid/Ask Price

Request Example

Response Example

{
    "ret_code": 0,
    "ret_msg": null,
    "result": {
        "symbol": "ETHUSDT",
        "bidPrice": "50005.12",
        "bidQty": "394",
        "askPrice": "50008",
        "askQty": "0.8001",
        "time": 1620919281808
    },
    "ext_code": null,
    "ext_info": null
}

HTTP Request

GET /spot/quote/v1/ticker/book_ticker

Request Parameters

Parameter Required Type Comment
symbol false string Name of the trading pair

Response Parameters

Parameter Type Comment
symbol string Name of the trading pair
bidPrice float Best bid price
bidQty float Bid quantity
askPrice float Best ask price
askQty float Ask quantity
time long Millisecond timestamp

Account Data Endpoints

The following account data endpoints require authentication.

Place Active Order

Request Example

curl https://api.bybit.com/spot/v1/order \
-H "Content-Type: application/x-www-form-urlencoded" \
-d 'api_key={api_key}&side=Buy&symbol=ETHUSDT&type=MARKET&qty=10&timeInForce=GTC&timestamp={timestamp}&sign={signature}'


Response Example

{
    "ret_code": 0,
    "ret_msg": "",
    "ext_code": null,
    "ext_info": null,
    "result": {
        "accountId": "1",
        "symbol": "ETHUSDT",
        "symbolName": "ETHUSDT",
        "orderLinkId": "162073788655749",
        "orderId": "889208273689997824",
        "transactTime": "1620737886573",
        "price": "20000",
        "origQty": "10",
        "executedQty": "0",
        "status": "NEW",
        "timeInForce": "GTC",
        "type": "LIMIT",
        "side": "BUY"
    }
}

HTTP Request

POST /spot/v1/order

Request Parameters

Parameter Required Type Comment
symbol true string Name of the trading pair
qty true number Order quantity (for market orders: when side is Buy, this is in the quote currency. Otherwise, qty is in the base currency. For example, on BTCUSDT a Buy order is in USDT, otherwise it's in BTC. For limit orders, the qty is always in the base currency.)
side true string Order direction
type true string Order type
timeInForce false string Time in force
price false number Order price. When the type field is MARKET, the price field is optional. When the type field is LIMIT or LIMIT_MAKER, the price field is required
orderLinkId false string User-generated order ID

Response Parameters

Parameter Type Comment
orderId integer Order ID
orderLinkId string User-generated order ID
symbol string Name of the trading pair
transactTime int Timestamp
price float Last traded price
origQty float Order quantity
type string Order type
side string Order direction
status string Order status
timeInForce string Time in force
accountId long Account ID
symbolName string Symbol name
executedQty string Please ignore

Get Active Order

Request Example

Response Example

{
    "ret_code": 0,
    "ret_msg": "",
    "ext_code": null,
    "ext_info": null,
    "result": {
        "accountId": "1054",
        "exchangeId": "301",
        "symbol": "ETHUSDT",
        "symbolName": "ETHUSDT",
        "orderLinkId": "162081160171552",
        "orderId": "889826641228952064",
        "price": "20000",
        "origQty": "10",
        "executedQty": "0",
        "cummulativeQuoteQty": "0",
        "avgPrice": "0",
        "status": "NEW",
        "timeInForce": "GTC",
        "type": "LIMIT",
        "side": "BUY",
        "stopPrice": "0.0",
        "icebergQty": "0.0",
        "time": "1620811601728",
        "updateTime": "1620811601743",
        "isWorking": true
    }
}

Get Active Order

HTTP Request

GET /spot/v1/order

Request Parameters

Parameter Required Type Comment
orderId false string Order ID
orderLinkId false string User-generated order ID

Response Parameters

Parameter Type Comment
accountId long Account ID
exchangeId long Order ID
symbol string Name of the trading pair
symbolName string Name of the trading pair
orderLinkId string User-generated order ID
orderId long Order ID
price float Order price
origQty float Order quantity
executedQty float Please ignore
cummulativeQuoteQty float Total order quantity
avgPrice float Average filled price
status string Order status
timeInForce string Time in force
type string Order type
side string Order direction
stopPrice float Stop price
icebergQty float Please ignore
time long Order creation time
updateTime long Last time order was updated
isWorking boolean Working or not (true/false)

Cancel Active Order

Request Example


Response Example

{
    "ret_code": 0,
    "ret_msg": "",
    "ext_code": null,
    "ext_info": null,
    "result": {
        "accountId": "10054",
        "symbol": "ETHUSDT",
        "orderLinkId": "162081160171552",
        "orderId": "889826641228952064",
        "transactTime": "1620811601728",
        "price": "20000",
        "origQty": "10",
        "executedQty": "0",
        "status": "CANCELED",
        "timeInForce": "GTC",
        "type": "LIMIT",
        "side": "BUY"
    }
}

HTTP Request

DELETE /spot/v1/order

Request Parameters

Parameter Required Type Comment
orderId false string Order ID
orderLinkId false string User-generated order ID

Response Parameters

Parameter Type Comment
orderId integer Order ID
orderLinkId string User-generated order ID
symbol string Name of the trading pair
status string Order status
accountId long Account ID
transactTime long Timestamp
price float Order price
origQty float Order quantity
executedQty float Please ignore
timeInForce string Time in force
type string Order type
side string Order direction

Fast Cancel Active Order

Request Example


Response Example

{
    "ret_code": 0,
    "ret_msg": "",
    "ext_code": null,
    "ext_info": null,
    "result": {
        "accountId": "10054",
        "symbol": "ETHUSDT",
        "orderLinkId": "162081160171552",
        "orderId": "889826641228952064",
        "transactTime": "1620811601728",
        "price": "20000",
        "origQty": "10",
        "executedQty": "0",
        "status": "CANCELED",
        "timeInForce": "GTC",
        "type": "LIMIT",
        "side": "BUY"
    }
}

HTTP Request

DELETE /spot/v1/order/fast

Request Parameters

Parameter Required Type Comment
orderId false string Order ID
orderLinkId false string User-generated order ID
symbolId true string Name of the trading pair

Response Parameters

Parameter Type Comment
orderId integer Order ID
orderLinkId string User-generated order ID
symbol string Name of the trading pair
status string Order status
accountId long Account ID
transactTime long Timestamp
price float Order price
origQty float Order quantity
executedQty float Please ignore
timeInForce string Time in force
type string Order type
side string Order direction

Batch Cancel Active Order

Request Example



Response Example

{
    "ret_code": 0,
    "ret_msg": "",
    "ext_code": null,
    "ext_info": null,
    "result": {
        "success": true
    }
}

HTTP Request

DELETE /spot/order/batch-cancel

Request Parameters

Parameter Required Type Comment
symbol true string Name of the trading pair
side false string Order direction
orderTypes false string Order type. Use comma splicing to indicate multiple order types, eg LIMIT,LIMIT_MAKER. Default: LIMIT

Response Parameters

Parameter Type Comment
success boolean Success or not (true/false)

Batch Fast Cancel Active Order

Request Example



Response Example

{
    "ret_code": 0,
    "ret_msg": "",
    "ext_code": null,
    "ext_info": null,
    "result": {
        "success": true
    }
}

HTTP Request

DELETE /spot/order/batch-fast-cancel

Request Parameters

Parameter Required Type Comment
symbol true string Name of the trading pair
side false string Order direction
orderTypes fasle string Order type. Use comma splicing to indicate multiple order types, eg LIMIT,LIMIT_MAKER. Default: LIMIT

Response Parameters

Parameter Type Comment
success boolean Success or not (true/false)

Batch Cancel Active Order By IDs

Request Example



Response Example

{
    "ret_code": 0,
    "ret_msg": "",
    "ext_code": null,
    "ext_info": null,
    "result": [
        {
          "orderId": "889208273689997824",
          "code": "1139"
        }
    ]
}

HTTP Request

DELETE /spot/order/batch-cancel-by-ids

Request Parameters

Parameter Required Type Comment
orderIds true string order ID, use comma splicing to indicate multiple orderIds, no more than 100 ids.

Response Parameters

Parameter Type Comment
orderId integer Order ID
code integer Errors

Open Orders

Request Example

Response Example

{
    "ret_code": 0,
    "ret_msg": "",
    "ext_code": null,
    "ext_info": null,
    "result": [
        {
            "accountId": "10054",
            "exchangeId": "301",
            "symbol": "ETHUSDT",
            "symbolName": "ETHUSDT",
            "orderLinkId": "162080709527252",
            "orderId": "889788838461927936",
            "price": "20000",
            "origQty": "10",
            "executedQty": "0",
            "cummulativeQuoteQty": "0",
            "avgPrice": "0",
            "status": "NEW",
            "timeInForce": "GTC",
            "type": "LIMIT",
            "side": "BUY",
            "stopPrice": "0.0",
            "icebergQty": "0.0",
            "time": "1620807095287",
            "updateTime": "1620807095307",
            "isWorking": true
        },
        {
            "accountId": "10054",
            "exchangeId": "301",
            "symbol": "ETHUSDT",
            "symbolName": "ETHUSDT",
            "orderLinkId": "162063873503148",
            "orderId": "888376530389004800",
            "price": "20000",
            "origQty": "10",
            "executedQty": "0",
            "cummulativeQuoteQty": "0",
            "avgPrice": "0",
            "status": "NEW",
            "timeInForce": "GTC",
            "type": "LIMIT",
            "side": "BUY",
            "stopPrice": "0.0",
            "icebergQty": "0.0",
            "time": "1620638735044",
            "updateTime": "1620638735062",
            "isWorking": true
        }
    ]
}

HTTP Request

GET /spot/v1/open-orders

Request Parameters

Parameter Required Type Comment
symbol false string Name of the trading pair
orderId false string Order ID
limit false integer Default value is 500, max 500

Response Parameters

Parameter Type Comment
accountId long Account ID
exchangeId long Order ID
symbol string Name of the trading pair
symbolName string Name of the trading pair
orderLinkId string User-generated order ID
orderId long Order ID
price float Order price
origQty float Order quantity
executedQty float Please ignore
cummulativeQuoteQty float Total order quantity
avgPrice float Average filled price
status string Order status
timeInForce string Time in force
type string Order type
side string Order direction
stopPrice float Stop price
icebergQty float Please ignore
time long Order creation time
updateTime long Last time order was updated
isWorking boolean Working or not (true/false)

Order History

Request Example


Response Example

{
    "ret_code": 0,
    "ret_msg": "",
    "ext_code": null,
    "ext_info": null,
    "result": [
        {
            "accountId": "10054",
            "exchangeId": "301",
            "symbol": "ETHUSDT",
            "symbolName": "ETHUSDT",
            "orderLinkId": "1620615771764",
            "orderId": "888183901021893120",
            "price": "5000",
            "origQty": "1",
            "executedQty": "0",
            "cummulativeQuoteQty": "0",
            "avgPrice": "0",
            "status": "CANCELED",
            "timeInForce": "GTC",
            "type": "LIMIT",
            "side": "BUY",
            "stopPrice": "0.0",
            "icebergQty": "0.0",
            "time": "1620615771836",
            "updateTime": "1620617056334",
            "isWorking": true
        }
    ]
}

HTTP Request

GET /spot/v1/history-orders

Request Parameters

Parameter Required Type Comment
symbol false string Name of the trading pair
orderId false string Order ID
limit false integer Default value is 500, max 500

Response Parameters

Parameter Type Comment
accountId long Account ID
exchangeId long Order ID
symbol string Name of the trading pair
symbolName string Name of the trading pair
orderLinkId string User-generated order ID
orderId long Order ID
price float Last traded price
origQty float Order quantity
executedQty float Please ignore
cummulativeQuoteQty float Total order quantity
avgPrice float Average filled price
status string Order status
timeInForce string Time in force
type string Order type
side string Order direction
stopPrice float Stop price
icebergQty float Please ignore
time long Order creation time
updateTime long Last time order was updated
isWorking boolean Working or not (true/false)

Trade History

Request Example

Response Example

{
    "ret_code": 0,
    "ret_msg": "",
    "ext_code": null,
    "ext_info": null,
    "result": [
       {
            "id": "931975237315196160",
            "symbol": "BTCUSDT",
            "symbolName": "BTCUSDT",
            "orderId": "931975236946097408",
            "matchOrderId": "931975113180558592",
            "price": "20000.00001",
            "qty": "0.01",
            "commission": "0.02000000001",
            "commissionAsset": "USDT",
            "time": "1625836105890",
            "isBuyer": false,
            "isMaker": false,
            "fee": {
                "feeTokenId": "USDT",
                "feeTokenName": "USDT",
                "fee": "0.02000000001"
            },
            "feeTokenId": "USDT",
            "feeAmount": "0.02000000001",
            "makerRebate": "0"
       }
    ]
}

HTTP Request

GET /spot/v1/myTrades

Request Parameters

Parameter Required Type Comment
symbol false string Name of the trading pair
limit false integer Default value is 500, max 500
fromId false integer Query begins with the trade ID
toId false integer Query ends with the trade ID

Response Parameters

Parameter Type Comment
symbol string Name of the trading pair
id int Trade ID
orderId integer Order ID
price float Last traded price
qty float Order quantity
commission float Trading fee
commissionAsset float Asset type in which the fee is paid
time long Order creation time
isBuyer float True indicates buyer, false indicates seller
isMaker float True indicates maker, false indicates taker
symbolName string Symbol name
matchOrderId long Order ID of the opponent
fee object Trading fee
feeTokenId string Fee Token ID
feeAmount float Trading fee
makerRebate float Marker rebate

fee object

Parameter Type Comment
feeTokenId long Fee Token ID
feeTokenName string Fee token name
fee float Trading fee

Wallet Data Endpoints

The following wallet data endpoints require authentication.

Get Wallet Balance

Request Example

Response Example

{
    "ret_code": 0,
    "ret_msg": "",
    "ext_code": null,
    "ext_info": null,
    "result": {
        "balances": [
            {
                "coin": "USDT",
                "coinId": "USDT",
                "coinName": "USDT",
                "total": "10",
                "free": "10",
                "locked": "0"
            }
        ]
    }
}

HTTP Request

GET /spot/v1/account

Response Parameters

Parameter Type Comment
balances object Account balances

balances object

Parameter Type Comment
coin string Asset
coinId string Asset
coinName string Asset
total string Total equity
free float Available balance
locked float Reserved for orders

API Data Endpoints

The following API data endpoints do not require authentication.

Server Time

Request Example

curl https://api.bybit.com/spot/v1/time

Response Example

{
    "ret_code": 0,
    "ret_msg": "",
    "ext_code": null,
    "ext_info": null,
    "result": {
        "serverTime": 1625799317787
    }
}

Get Bybit server time.

HTTP Request

GET /spot/v1/time

Request Parameters

Parameter Required Type Comment

API Rate Limits

IP Rate Limit

The IP limits are shared across all endpoints: futures, spot, and account asset.

Bybit has different IP frequency limits for GET and POST method:

Rate Limits For All Private Endpoints

For all endpoints that need authentication, the rate limit is 20 per second for each endpoint.

WebSocket Data

Authentication

Apply for authentication when establishing a connection.

# based on: https://github.com/verata-veritatis/pybit/blob/master/pybit/__init__.py

import hmac
import json
import time
import websocket

api_key = ""
api_secret = ""

# Generate expires.
expires = int((time.time() + 1) * 1000)

# Generate signature.
signature = str(hmac.new(
    bytes(api_secret, "utf-8"),
    bytes(f"GET/realtime{expires}", "utf-8"), digestmod="sha256"
).hexdigest())

ws = websocket.WebSocketApp(
    url=url,
    ...
)

# Authenticate with API.
ws.send(
    json.dumps({
        "op": "auth",
        "args": [api_key, expires, signature]
    })
)

Base endpoints:

There are two methods of authentication, as shown in the code panel to the right.

How to Send Heartbeat Packet

How to Send

ws.send(JSON.stringify({"ping": 1535975085052}));

Response Example

{"pong": 1535975085152}

How to Subscribe to Topics

Understanding Websocket Filters

How to subscribe with a filter

After establishing the connection, you can subscribe to a new topic by sending a JSON request. The request formats are as follows:

ws.send('{"symbol":"BTCUSDT","topic":"trade","event":"sub","params":{"binary":false}}');

Multiple assets supported, separated by ',' (Not applicable for V2).

ws.send('{"symbol":"BTCUSDT,ETHUSDT","topic":"trade","event":"sub","params":{"binary":false}}');

// Subscribing to the trade data for BTCUSDT
ws.send('{"symbol":"BTCUSDT","topic":"trade","event":"sub","params":{"binary":false}}');

support many symbol, separate with ','.

// Example: Subscribing to the trade data for BTCUSDT and ETHUSDT
ws.send('{"symbol":"BTCUSDT,ETHUSDT","topic":"trade","event":"sub","params":{"binary":false}}');

Understanding Websocket Filters unsubscription

After successful subscription, you can unsubscribe by sending a JSON request. The request formats are as follows:

ws.send('{"symbol":"BTCUSDT","topic":"trade","event":"cancel","params":{"binary":false}}');

Understanding Subscription Response

Subscription Response

{
  "topic":"trade",
  "event":"sub",
  "symbol":"BTCUSDT",
  "params":{
    "binary":"false"
  },
  "code":"0",
  "msg":"Success"
}

Once you subscribe successfully, you'd receive result information. You can determine whether the subscription is successful based on the response.

Public Topics

trade

How to Subscribe

{
    "topic": "trade",
    "event": "sub",
    "symbol": "BTCUSDT",
    "params": {
        "binary": false
    }
}

Response Example - format of all responses

{
    "symbol":"BTCUSDT",
    "symbolName":"BTCUSDT",
    "topic":"trade",
    "params":{
        "realtimeInterval":"24h",
        "binary":"false"
    },
    "data":[
        {
            "v":"929681067596857345",
            "t":1625562619577,
            "p":"34924.15",
            "q":"0.00027",
            "m":true
        }
    ],
    "f": true,
    "sendTime": 1626249138535,
    "shared": false
}

This topic pushes raw data for each trade.

After a successful subscription message, the first data message (as indicated by "f": true) consists of the last 60 trades. After this payload ("f": false), messages are pushed at frequency of 300ms.

Variable v is a trade ID which is unique across the platform.

Push data at a frequence of 300ms. Message received with a maximum delay of 400ms.

Response Parameters

Parameter Type Comment
v string Transaction ID
t string Timestamp
p string Price
q boolean Quantity
m boolean True indicates buy order, false indicates sell order
f boolean First message for this topic since subscription

realtimes

How to Subscribe

{
    "topic": "realtimes",
    "event": "sub",
    "symbol": "BTCUSDT",
    "params": {
        "binary": false
    }
}

Response Example - format of all responses

{
  "symbol": "BTCUSDT",
  "symbolName": "BTCUSDT",
  "topic": "realtimes",
  "data": [{
    "t": "1565592599015",
    "s": "BTCUSDT",
    "sn": "BTCUSDT",
    "c": "12750.63",
    "h": "12800.96",
    "l": "12740.78",
    "o": "12780.23",
    "v": "73013.575",
    "qv": "15726612.498168",
    "m": "-0.0401",
    "e": 301
    }],
  "f": false,
  "sendTime": 1626252046034,
  "shared": false
}

The 24-hr statistics of a trading pair.

Push data at a frequence of 300ms. Message received with a maximum delay of 400ms.

Response Parameters

Parameter Type Comment
t number Timestamp
s string Trading pair
sn string Trading pair
c string Close price
h string High price
l string Low price
o string Open price
v string Trading volume
qv string Trading quote volume
m string Change
e number Exchange ID
f boolean First message for this topic since subscription

kline

How to Subscribe

{
    "topic": "kline_1m",
    "event": "sub",
    "symbol": "BTCUSDT",
    "params": {
        "binary": false
    }
}

Response Example - format of all responses

{
  "symbol": "BTCUSDT",
  "symbolName": "BTCUSDT",
  "topic": "kline",
  "params": {
    "realtimeInterval": "24h",
    "klineType": "15m",
    "binary": "false"
  },
  "data": [{
    "t": 1565595900000,
    "s": "BTCUSDT",
    "sn": "BTCUSDT",
    "c": "11436.14",
    "h": "11437",
    "l": "11381.89",
    "o": "11381.89",
    "v": "16.3306"
  }],
  "f": true,
  "sendTime": 1626252389284,
  "shared": false
}

Kline data.

To subscribe to different intervals, alter append your desired interval to the topic name. For 1 minute klines, set the topic as kline_1m, for 1 hour klines use kline_1h, etc. Available intervals are listed here.

Push data at a frequence of 300ms. Message received with a maximum delay of 400ms.

Response Parameters

Parameter Type Comment
t number Starting time
s string Trading pair
sn string Trading pair
c string Close price
h string High price
l string Low price
o string Open price
v string Trading volume
f boolean First message for this topic since subscription

depth

How to Subscribe

{
    "topic": "depth",
    "event": "sub",
    "symbol": "BTCUSDT",
    "params": {
        "binary": false
    }
}

Response Example - format of all responses

{
  "symbol": "BTCUSDT",
  "symbolName": "BTCUSDT",
  "topic": "depth",
  "params": {
    "realtimeInterval": "24h",
    "binary": "false"
  },
  "data": [{
    "e": 301,
    "s": "BTCUSDT",
    "t": 1565600357643,
    "v": "112801745_18",
    "b": [
      ["11371.49", "0.0014"],
      ["11371.12", "0.2"],
      ["11369.97", "0.3523"],
      ["11369.96", "0.5"],
      ["11369.95", "0.0934"],
      ["11369.94", "1.6809"],
      ["11369.6", "0.0047"],
      ["11369.17", "0.3"],
      ["11369.16", "0.2"],
      ["11369.04", "1.3203"],
    ]
    "a": [
      ["11375.41", "0.0053"],
      ["11375.42", "0.0043"],
      ["11375.48", "0.0052"],
      ["11375.58", "0.0541"],
      ["11375.7", "0.0386"],
      ["11375.71", "2"],
      ["11377", "2.0691"],
      ["11377.01", "0.0167"],
      ["11377.12", "1.5"],
      ["11377.61", "0.3"]
    ],
    "o": 0
  }],
  "f": true,
  "sendTime": 1626253839401,
  "shared": false
}

This topic pushes all order book data.

Push data at a frequence of 300ms. Message received with a maximum delay of 650ms.

Response Parameters

Parameter Type Comment
e number Exchange ID
t number Timestamp
s string Trading pair
v string Version
b array Bid prices & quantities in descending order (best price first)
a array Ask prices & quantities in ascending order (best price first)
f boolean First message for this topic since subscription
o number Please ignore

mergedDepth

How to Subscribe

{
    "topic": "mergedDepth",
    "event": "sub",
    "symbol": "BTCUSDT",
    "params": {
        "binary": false,
        "dumpScale": 1
    }
}

Response Example - format of all responses

{
  "symbol":"ETHUSDT",
  "symbolName":"ETHUSDT",
  "topic":"mergedDepth",
  "params":{"
    realtimeInterval":"24h",
    "dumpScale":"1",
    "binary":"false"
    },
  "data":[{
    "e":301,
    "s":"ETHUSDT",
    "t":1622541360174,
    "v":"10544_1",
    "b":[
          ["12001","1"],
          ["12000","0.8"],
          ["10000","1"],
          ["4988","0.5"],
          ["4987","0.8"],
          ["4986","1"],
          ["4985","0.9"],
          ["4984","1.1"],
          ["4983","1.3"],
          ["4982","0.5"],
          ["100000","0.94"]
        ],
    "a": [
          ["12001","1"],
          ["12000","0.8"],
          ["10000","1"],
          ["4988","0.5"],
          ["4987","0.8"],
          ["4986","1"],
          ["4985","0.9"],
          ["4984","1.1"],
          ["4983","1.3"],
          ["4982","0.5"],
          ["100000","0.94"]
    ],
    "o":0
    }],
    "f":false,
    "sendTime":1622541360301,
    "shared":false
}

dumpScale must be specified for this endpoint. It refers to the number of decimal places

Push data at a frequence of 300ms. Message received with a maximum delay of 650ms.

Response Parameters

Parameter Type Comment
t number Timestamp
s string Trading pair
v string Version
b array Bid prices & quantities in descending order (best price first)
a array Ask prices & quantities in ascending order (best price first)
f boolean First message for this topic since subscription

diffDepth

How to Subscribe

{
    "topic": "diffDepth",
    "event": "sub",
    "symbol": "BTCUSDT",
    "params": {
        "binary": false
    }
}

Response Example - format of all responses

{
  "symbol": "BTCUSDT",
  "symbolName": "BTCUSDT",
  "topic": "diffDepth",
  "params": {
    "realtimeInterval": "24h",
    "binary": "false"
  },
  "data": [{
    "e": 301,
    "s": "BTCUSDT",
    "t": 1565600357643,
    "v": "112801745_18",
    "b": [
      ["11371.49", "0.0014"],
      ["11371.12", "0.2"],
      ["11369.97", "0.3523"],
      ["11369.96", "0.5"],
      ["11369.95", "0.0934"],
      ["11369.94", "1.6809"],
      ["11369.6", "0.0047"],
      ["11369.17", "0.3"],
      ["11369.16", "0.2"],
      ["11369.04", "1.3203"],
    "a": [
      ["11375.41", "0.0053"],
      ["11375.42", "0.0043"],
      ["11375.48", "0.0052"],
      ["11375.58", "0.0541"],
      ["11375.7", "0.0386"],
      ["11375.71", "2"],
      ["11377", "2.0691"],
      ["11377.01", "0.0167"],
      ["11377.12", "1.5"],
      ["11377.61", "0.3"]
    ],
    "o": 0
  }],
  "f": true,
  "sendTime": 1626253839401,
  "shared": false
}

Changes (if any) in the bid–ask spread of the order book will be pushed. The first message pushes a depth of 200 per side. The following messages act as delta messages, which represent updates to the order book relative to the last response.

In Order Book Streams (Float Depth), the quantity returned may not be equal to the actual bid-ask quantity corresponding to the price. If the quantity=0, it indicates that the price has already changed. If the quantity>0, it refers to the updated bid-ask quantity corresponding to the price.

Assume the response includes the following:

  > ["0.00181860", "155.92000000"]// price, quantity

If the next payload is:

  > ["0.00181860", "12.3"]

This means that the quantity corresponding to this price has been updated.

If the next payload is:

  > ["0.00181860", "0"]

This means that the price has already changed.

Push data at a frequence of 300ms. Message received with a maximum delay of 650ms.

Response Parameters

Parameter Type Comment
e number Exchange ID
t number Timestamp
s string Trading pair
v string Version
b array Bid prices & quantities in descending order (best price first)
a array Ask prices & quantities in ascending order (best price first)
f boolean First message for this topic since subscription
o number Please ignore

Public Topics V2

depth

How to Subscribe

{
    "topic": "depth",
    "event": "sub",
    "params": {
        "symbol": "BTCUSDT",
        "binary": false
    }
}

Snapshot Response Example - format of the first response

{
  "topic": "depth",
  "params": {
    "symbol": "BTCUSDT",
    "binary": "false",
    "symbolName": "BTCUSDT"
  },
  "data": {
    "s": "BTCUSDT",
    "t": 1582001376853,
    "v": "13850022_2",
    "b": [
      [
        "9780.79",
        "0.01"
      ],
      [
        "9780.5",
        "0.1"
      ],
      [
        "9780.4",
        "0.517813"
      ], ...
    "a": [
      [
        "9781.21",
        "0.042842"
      ],
      [
        "9782",
        "0.3"
      ],
      [
        "9782.1",
        "0.226"
      ], ...
    ]
  }
}

Market depth data for a trading pair:

Push data at a frequence of 250ms. Message received with a maximum delay of 300ms.

Response Parameters

Parameter Type Comment
symbol string Trading pair
symbolName string Trading pair
binary string Compressed or not. Defaults to false
t number Timestamp
s string Trading pair
v string Version
b string Best bid price, quantity
a string Best ask price, quantity

kline

How to Subscribe

{
    "topic": "kline",
    "event": "sub",
    "params": {
        "symbol": "BTCUSDT",
        "klineType": "1m",
        "binary": false
    }
}

Response Example - format of all responses

{
  "topic": "kline",
  "params": {
    "symbol": "BTCUSDT",
    "binary": "false",
    "klineType": "1m",
    "symbolName": "BTCUSDT"
  },
  "data": {
    "t": 1582001880000,
    "s": "BTCUSDT",
    "sn": "BTCUSDT",
    "c": "9799.4",
    "h": "9801.4",
    "l": "9798.91",
    "o": "9799.4",
    "v": "15.917433"
  }
}

Kline data pushed at a frequency of every second.

The topic name is kline. To subscribe to different intervals, pass your desired interval with the klineType parameter. Available intervals are listed here.

Pushes data near in realtime.

Response Parameters

Parameter Type Comment
symbol string Trading pair
binary string Compressed or not. Defaults to false
klineType string Interval
symbolName string Trading pair
t number Starting time
s string Trading pair
sn string Trading pair
c string Close price
h string High price
l string Low price
o string Open price
v string Trading volume

trade

How to Subscribe

{
    "topic": "trade",
    "params": {
        "symbol": "BTCUSDT",
        "binary": false
    },
    "event": "sub"
}

Response Example - format of all responses

{
  "topic": "trade",
  "params": {
    "symbol": "BTCUSDT",
    "binary": "false",
    "symbolName": "BTCUSDT"
  },
  "data": {
    "v": "564265886622695424",
    "t": 1582001735462,
    "p": "9787.5",
    "q": "0.195009",
    "m": true
  }
}

The Trade Streams push raw trade information; each trade has a unique buyer and seller.

After successful handshake and connected to server, the server will return the latest 60 trades. After this payload, the following will be real-time trades.

Variable "v" acts as an tradeId. This variable is shared across different symbols; however, each ID is unique. For example, suppose in the last 5 seconds 3 trades happened in ETHUSDT, BTCUSDT, and BHTBTC. Their version (which is "v") will be consecutive: 112, 113, 114.

Pushes data near in realtime.

Response Parameters

Parameter Type Comment
symbol string Trading pair
binary string Compressed or not. Defaults to false
symbolName string Trading pair
v string Transaction ID
t number Timestamp
p string Price
q string Quantity
m boolean True indicates buy order, false indicates sell order

bookTicker

How to Subscribe

{
    "topic": "bookTicker",
    "event": "sub",
    "params": {
        "symbol": "BTCUSDT",
        "binary": false
    }
}

Response Example - format of all responses

{
  "topic": "bookTicker",
  "params": {
    "symbol": "BTCUSDT",
    "binary": "false",
    "symbolName": "BTCUSDT"
  },
  "data": {
    "symbol": "BTCUSDT",
    "bidPrice": "9797.79",
    "bidQty": "0.177976",
    "askPrice": "9799",
    "askQty": "0.65",
    "time": 1582001830346
  }
}

Best bid price and best ask price

Push data at a frequence of 250ms. Message received with a maximum delay of 300ms.

Response Parameters

Parameter Type Comment
symbol string Trading pair
binary string Compressed or not. Defaults to false
symbolName string Trading pair
bidPrice string Best bid price
bidQty string Bid quantity
askPrice string Best ask price
askQty boolean Ask quantity
time member Timestamp

realtimes

How to Subscribe

{
    "topic": "realtimes",
    "event": "sub",
    "params": {
        "symbol": "BTCUSDT",
        "binary": false
    }
}

Response Example - format of all responses

{
  "topic": "realtimes",
  "params": {
    "symbol": "BTCUSDT",
    "binary": "false",
    "symbolName": "BTCUSDT"
  },
  "data": {
    "t": 1582001616500,
    "s": "BTCUSDT",
    "o": "9736.5",
    "h": "9830.19",
    "l": "9455.71",
    "c": "9796.75",
    "v": "77211.561764",
    "qv": "740412516.91255711",
    "m": "0.0062"
  }
}

The 24-hr statistics of a trading pair pushed at a frequency of ???

Pushes data near in realtime.

Response Parameters

Parameter Type Comment
symbol string Trading pair
binary string Compressed or not. Defaults to false
symbolName string Trading pair
t number Timestamp
s string Trading pair
c string Close price
h string High price
l string Low price
o string Open price
v string Trading volume
qv string Trading quote volume
m string Change

Private Topics

Sending the authentication message automatically subscribes you to all 3 private topics.

outboundAccountInfo

Sending the authentication message automatically subscribes you to all 3 private topics.

Response Example - format of all responses

[
    {
        "e":"outboundAccountInfo",
        "E":"1629969654753",
        "T":True,
        "W":True,
        "D":True,
        "B":[
            {
                "a":"BTC",
                "f":"10000000097.1982823144",
                "l":"0"
            }
        ]
    }
]

Pushes data about your account.

Pushes data in realtime.

Response Parameters

Parameter Type Comment
e string Event type
E string Timestamp
T boolean Allow trade
W boolean Allow withdraw
D boolean Allow deposit
B list Wallet balance change
a string Name of the trading pair
f string Available balance
l string Reserved for orders

executionReport

Sending the authentication message automatically subscribes you to all 3 private topics.

Response Example - format of all responses

[
  {
    "e": "executionReport",      
    "E": "1499405658658",            
    "s": "ETHBTC",                 
    "c": "1000087761",               
    "S": "BUY",                    
    "o": "LIMIT",                  
    "f": "GTC",                    
    "q": "1.00000000",             
    "p": "0.10264410",             
    "X": "NEW",                    
    "i": "4293153",     
    "M": "0",             
    "l": "0.00000000",             
    "z": "0.00000000",             
    "L": "0.00000000",             
    "n": "0",                      
    "N": "BTC",                     
    "u": true,                     
    "w": true,                     
    "m": false,                    
    "O": "1499405658657",            
    "Z": "473.199",
    "A": "0",
    "C": false,
    "v": "0"              
  }
]

Pushes data about your orders. Z divided by z equals the average filled price.

Pushes data in realtime.

Response Parameters

Parameter Type Comment
e string Event type
E string Event time
s string Trading pair
c string User-generated order ID
S string BUY indicates buy order, SELL indicates sell order
o string Order type
f string Time in force
q string Quantity
p string Price
X string Order status
i string Order ID
M string Order ID of the opponent
l string Last filled quantity
z string Total filled quantity
L string Last traded price
n string Trading fee
N string Asset type in which fee is paid
u boolean Is normal
w boolean Is working
m boolean Is LIMIT_MAKER
O string Order creation time
Z string Total filled value
A string Account ID
C boolean Is close
v string leverage

ticketInfo

Sending the authentication message automatically subscribes you to all 3 private topics.

Response Example - format of all responses

[
  {
    "e":"ticketInfo",
    "E":"1621912542359",
    "s":"BTCUSDT",
    "q":"0.001639",
    "t":"1621912542314",
    "p":"61000.0",
    "T":"899062000267837441",
    "o":"899048013515737344",
    "c":"1621910874883",
    "O":"899062000118679808",
    "a":"10043",
    "A":"10024"
  }
]

Pushes data about your trades (fills). When an order is filled, you will receive two messages: one from ticketInfo, and one from executionReport

Pushes data in realtime.

Response Parameters

Parameter Type Comment
e string Event type
E string Event time
s string Trading pair
q string Quantity
t string Timestamp
p string Price
T string Transaction ID
o string Order ID
c string User-generated order ID
O string Order ID of the opponent
a string Account ID
A string Account ID

Enums Definitions

The following lists enumerator names for the request and response parameters of each endpoint.

Side (side)

TimeInForce (timeInForce)

Symbol (symbol)

You can get all symbols with the Query Symbol endpoint.

Order type (type/orderTypes)

Currency (currency/coin)

The transfer API also includes:

Order status (status)

Quantity (qty)

Price (price)

Time in force (time_in_force)

Kline interval (interval)

Errors

The Bybit API uses the following HTTP codes and error codes:

HTTP Code Meaning
200 Request is valid
403 Access denied
404 Request path not found
Error Code Meaning
1000 An unknown error occurred while processing the request
1001 Request failed to be processed. Please try again.
1002 Request not authorized. An API key is required and should be included in all requests.
1003 Too many requests. Please use WebSocket for live updates. Current limit is %s requests per minute.
1006 System not responding. Request status unknown. Please contact live support.
1007 Response timeout from backend server. Delivery and request status unknown.
1014 Trading pairs not supported.
1015 Too many new orders. Please lower request frequency.
1016 Service not available.
1020 Request not supported.
1021 Timestamp for the request is outside of the recvWindow. The timestamp of this request is 1000 milliseconds ahead of the server time. Please check local time and server time.
1022 Invalid request signature.
1100 Parameter characters not supported.
1101 Too many parameters sent for this endpoint.
1102 Required parameter not sent. Parameter was empty/null or format was incorrect.
1103 Unknown parameter sent.
1104 Not all parameters sent were read.
1105 Empty parameter.
1106 Parameter was sent when no longer required.
1111 Order price exceeded upper limit.
1112 Trading pair does not exist.
1114 TimeInForce parameter sent when not required.
1115 Invalid timeInForce.
1116 Invalid orderType.
1117 Invalid direction.
1118 User-generated order ID was empty.
1119 User-generated order ID was empty.
1120 Invalid interval.
1121 Invalid symbol.
1125 listenKey does not exist.
1127 Query intervals too large.
1128 Invalid parameter combination.
1130 Invalid parameter sent.
1131 Insufficient balance
1132 Order price exceeded upper limit.
1133 Order price exceeded lower limit.
1134 Order price has too many decimals.
1135 Order quantity exceeded upper limit.
1136 Order quantity exceeded lower limit.
1137 Order quantity has too many decimals.
1138 Order price exceeded limits.
1139 Order has been filled.
1140 Order value exceeded lower limit.
1140 Order value exceeded lower limit.
1141 Duplicate clientOrderId.
1142 Order has been canceled.
1143 Order not found.
1144 Order being cancelled. Operation not supported.
1145 Order cannot be canceled.
1146 Order creation timeout.
1147 Order cancellation timeout.
1190 Cancel order has been finished.
1191 Can not cancel order, please try again later.
2010 New order rejected.
2011 Cancelation rejected.
2013 Order does not exist.
2014 Invalid API key format.
2015 Invalid API key or IP.
2016 Trading window not open yet for current pair.