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.
API Resources and Support Channels
Help Center - Learn more about exchange mechanisms here!
pybit - Official Python SDK
bybit-api - Community NodeJS SDK
QuickStartWithPostman - Postman API Collection
API Discussion Group - get English help here!
API Discussion Group (Chinese) - get Chinese help here!
Bybit API Announcement - subscribe for changes to the API!
Bybit Open API Survey - The survey should take no more than 5 minutes to complete.
Changelog
2023-01-16
WebSocket API
realtimes [update]
- Add new response field
xp
, it means USD index price, which can be an empty string.
- Add new response field
realtimes [update]
- Add new response field
xp
, it means USD index price, which can be an empty string.
- Add new response field
2022-12-16
WebSocket API
- trade [update]
- websocket v2 public stream has new response field
type
- websocket v2 public stream has new response field
2022-09-16
REST API
- Order History [update]
- Update the rule of
limit
andstartTime
endTime
.
- Update the rule of
2022-08-26
WebSocket API
- executionReport [new]
- Add new response field
t
(tradeId)
- Add new response field
2022-08-09
WebSocket API
- stop_executionReport [new]
- Add private topic for TP/SL order
2022-07-08
WebSocket API
- Authentication [update]
- Add notice that an IP can connect to a maximum of 50 private spot websocket connections simultaneously
2022-06-17
REST API
- All Asset Infos (V2 WebSocket) [new]
- Add LT All Asset Infos Query
2022-06-10
WebSocket API
- ticketInfo (V2 WebSocket) [update]
- Add
S
field which indicates the trade side
- Add
2022-06-08
WebSocket API
- depth (V2 WebSocket) [update]
- Increase the push frequency from every 250ms (max. 300ms) to every 100ms
2022-06-01
WebSocket API
- Trade History [update]
- Add new response param
ExecutionTime
and Update response paramtime
- Add new response param
2022-05-20
REST API
- Cross Margin Trading Endpoints [new]
- Add Cross Margin Trading Endpoints
2022-05-13
REST API
- Query Symbol [update]
- Add new response param
innovation
- Add new response param
2022-04-20
REST API
- Leveraged Token Endpoints [new]
- Add Leveraged Token Endpoints
WebSocket API
- lt [new]
- Add lt public Topics
2022-04-14
REST API
- Query Symbol [update]
- MaxTradeQty and MaxTradeAmount are ignored when placing LIMIT_MAKER orders
2022-04-13
REST API
- Get Active Order [new]
- Add response parameter
locked
- Add response parameter
2022-03-24
REST API
- Trade History [new]
- Add request parameters
fromTicketId
,toTicketId
,orderId
- Add request parameters
- Trade History [abandoned]
- Deprecate request parameters
fromId
,toId
- Deprecate request parameters
2022-03-14
WebSocket API
- ticketInfo [update]
- Add
m
(is maker) to theticketInfo
topic
- Add
2021-07-12
REST API
- Optimize the input and output parameters of some interfaces
2021-06-17
REST API
- New add get symbols API. Parameter name for order_link_id updated to orderLinkId
2021-05-27
REST API
- New add spot open-api document
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:
- api_key
- timestamp - UTC timestamp in milliseconds
- sign - a signature derived from the request's parameters
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=XXXXXXXXXXX×tamp=1542434791747"
param_str = "api_key=XXXXXXXXXXX×tamp=1542434791747"
# api_key=XXXXXXXXXXX&
# 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×tamp=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.
Common Response Parameters
{
"ret_code": 0,
"ret_msg": "",
"result": {
},
"ext_info": null,
"ext_code": null
}
{
"ret_code": -2013,
"ret_msg": "Order does not exist",
"result": {},
"ext_info": null,
"ext_code": "",
"time_now": "1671023220.302404"
}
{
"ret_code": 0,
"ret_msg": "success",
"result": [
],
"ext_info": null,
"ext_code": "",
"time_now": "1671023511.680118"
}
Response Parameters
Parameter | Type | Comment |
---|---|---|
ret_code | integer | Success/Error code |
ret_msg | string | Success/Error msg. Can be success ,"" ,OK for success msg |
result | array/Object | It might be array[] ,object{} depend on business data |
ext_info | Object | Value is null |
ext_code | string | For market data, it returns null . Others return "" |
time_now | string | Current timestamp |
Market Data Endpoints
The following market data endpoints do not require authentication.
Query Symbol
Request Example
from pybit import spot
session_unauth = spot.HTTP(
endpoint="https://api-testnet.bybit.com"
)
print(session_unauth.query_symbol())
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,
"innovation": false,
"showStatus": true
},
{
"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,
"innovation": false,
"showStatus": true
}
]
}
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 (Not valid for market buy orders) |
minTradeAmount | string | Min. order value (Only valid for market buy orders) |
minPricePrecision | string | Min. number of decimal places |
maxTradeQuantity | string | Max. order qty (It is ignored when you place an order with order type LIMIT_MAKER) |
maxTradeAmount | string | Max. order value (It is ignored when you place an order with order type LIMIT_MAKER) |
category | int | Category |
innovation | boolean | True indicates that the price of this currency is relatively volatile |
showStatus | boolean | True indicates that the symbol open for trading |
Order Book
Request Example
from pybit import spot
session_unauth = spot.HTTP(
endpoint="https://api-testnet.bybit.com"
)
print(session_unauth.orderbook(symbol="BTCUSDT"))
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. Max value is 200 |
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
from pybit import spot
session_unauth = spot.HTTP(
endpoint="https://api-testnet.bybit.com"
)
print(session_unauth.merged_orderbook(symbol="BTCUSDT"))
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. Max value is 200 |
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
from pybit import spot
session_unauth = spot.HTTP(
endpoint="https://api-testnet.bybit.com"
)
print(session_unauth.public_trading_records(symbol="BTCUSDT"))
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 60, max 60 |
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
from pybit import spot
session_unauth = spot.HTTP(
endpoint="https://api-testnet.bybit.com"
)
print(session_unauth.query_kline(
symbol="BTCUSDT",
interval="1m"
))
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 1000 |
startTime | false | long | Start time, unit in millisecond |
endTime | false | long | 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
from pybit import spot
session_unauth = spot.HTTP(
endpoint="https://api-testnet.bybit.com"
)
print(session_unauth.latest_information_for_symbol(
symbol="BTCUSDT"
))
Response Example
{
"ret_code": 0,
"ret_msg": null,
"result": {
"time": 1620918180046,
"symbol": "BTCUSDT",
"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
from pybit import spot
session_unauth = spot.HTTP(
endpoint="https://api-testnet.bybit.com"
)
print(session_unauth.last_traded_price(
symbol="BTCUSDT"
))
Response Example
{
"ret_code": 0,
"ret_msg": null,
"result": {
"symbol": "BTCUSDT",
"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
from pybit import spot
session_unauth = spot.HTTP(
endpoint="https://api-testnet.bybit.com"
)
print(session_unauth.best_bid_ask_price(
symbol="BTCUSDT"
))
Response Example
{
"ret_code": 0,
"ret_msg": null,
"result": {
"symbol": "BTCUSDT",
"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-testnet.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×tamp={timestamp}&sign={signature}'
from pybit import spot
session_auth = spot.HTTP(
endpoint="https://api-testnet.bybit.com",
api_key="your api key",
api_secret="your api secret"
)
print(session_auth.place_active_order(
symbol="ETHUSDT",
side="Buy",
type="MARKET",
qty=10,
timeInForce="GTC"
))
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 | Order Creation Time |
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
from pybit import spot
session_auth = spot.HTTP(
endpoint="https://api-testnet.bybit.com",
api_key="your api key",
api_secret="your api secret"
)
print(session_auth.get_active_order(
orderId="889826641228952064"
))
Response Example
{
"ret_code": 0,
"ret_msg": "",
"ext_code": null,
"ext_info": null,
"result": {
"accountId": "533287",
"exchangeId": "301",
"symbol": "DOGEUSDT",
"symbolName": "DOGEUSDT",
"orderLinkId": "spotDOGE0003",
"orderId": "1180228509291857152",
"price": "0",
"origQty": "15",
"executedQty": "25.4",
"cummulativeQuoteQty": "14.9606",
"avgPrice": "0.589",
"status": "CANCELED",
"timeInForce": "GTC",
"type": "MARKET",
"side": "BUY",
"stopPrice": "0.0",
"icebergQty": "0.0",
"time": "1655430202103",
"updateTime": "1655430202331",
"isWorking": true,
"locked": "0"
}
}
Get Active Order
HTTP Request
GET
/spot/v1/order
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
orderId | false | string | Order ID. Required if not passing orderLinkId |
orderLinkId | false | string | Unique user-set order ID. Required if not passing orderId |
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 | Executed quantity |
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 created time in the match engine |
updateTime | long | Last time order was updated |
isWorking | boolean | Working or not (true/false) |
locked | float | Reserved for order (if it's 0, it means that the funds corresponding to the order have been settled) |
Cancel Active Order
Request Example
from pybit import spot
session_auth = spot.HTTP(
endpoint="https://api-testnet.bybit.com",
api_key="your api key",
api_secret="your api secret"
)
print(session_auth.cancel_active_order(
orderId="889826641228952064"
))
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. Required if not passing orderLinkId |
orderLinkId | false | string | Unique user-set order ID. Required if not passing orderId |
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 | Order Creation Time |
price | float | Order price |
origQty | float | Order quantity |
executedQty | float | Executed quantity |
timeInForce | string | Time in force |
type | string | Order type |
side | string | Order direction |
Fast Cancel Active Order
Request Example
from pybit import spot
session_auth = spot.HTTP(
endpoint="https://api-testnet.bybit.com",
api_key="your api key",
api_secret="your api secret"
)
print(session_auth.fast_cancel_active_order(
symbolId="ETHUSDT",
orderId="889826641228952064"
))
Response Example
{
"ret_code": 0,
"ret_msg": "",
"ext_code": null,
"ext_info": null,
"result": {
"isCancelled": true
}
}
HTTP Request
DELETE
/spot/v1/order/fast
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
symbolId | true | string | Name of the trading pair |
orderId | false | string | Order ID. Required if not passing orderLinkId |
orderLinkId | false | string | Unique user-set order ID. Required if not passing orderId |
Response Parameters
Parameter | Type | Comment |
---|---|---|
isCancelled | bool | Success or not (true/false) |
Batch Cancel Active Order
Request Example
from pybit import spot
session_auth = spot.HTTP(
endpoint="https://api-testnet.bybit.com",
api_key="your api key",
api_secret="your api secret"
)
print(session_auth.batch_cancel_active_order(
symbol="ETHUSDT",
orderTypes="LIMIT,LIMIT_MAKER"
))
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 commas 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
from pybit import spot
session_auth = spot.HTTP(
endpoint="https://api-testnet.bybit.com",
api_key="your api key",
api_secret="your api secret"
)
print(session_auth.batch_fast_cancel_active_order(
symbol="ETHUSDT",
orderTypes="LIMIT,LIMIT_MAKER"
))
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 commas 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
from pybit import spot
session_auth = spot.HTTP(
endpoint="https://api-testnet.bybit.com",
api_key="your api key",
api_secret="your api secret"
)
print(session_auth.batch_cancel_active_order_by_ids(
orderIds="889208273689997824,889826641228952064"
))
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 commas to indicate multiple orderIds. Maximum of 100 ids. |
Response Parameters
Parameter | Type | Comment |
---|---|---|
orderId | integer | Order ID |
code | integer | Errors |
Open Orders
Request Example
from pybit import spot
session_auth = spot.HTTP(
endpoint="https://api-testnet.bybit.com",
api_key="your api key",
api_secret="your api secret"
)
print(session_auth.query_active_order(
symbol="ETHUSDT"
))
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 | Specify orderId to return all the orders that orderId of which are smaller than this particular one for pagination purpose |
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 | Executed quantity |
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 created time in the match engine |
updateTime | long | Last time order was updated |
isWorking | boolean | Working or not (true/false) |
Order History
Request Example
from pybit import spot
session_auth = spot.HTTP(
endpoint="https://api-testnet.bybit.com",
api_key="your api key",
api_secret="your api secret"
)
print(session_auth.get_active_order(
symbol="ETHUSDT"
))
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 | Specify orderId to return all the orders that orderId of which are smaller than this particular one for pagination purpose |
limit | false | integer | Default value is 100, max 500 |
startTime | false | long | Start time, unit in millisecond |
endTime | false | long | End time, unit in millisecond |
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 | Executed quantity |
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 created time in the match engine |
updateTime | long | Last time order was updated |
isWorking | boolean | Working or not (true/false) |
Trade History
Request Example
from pybit import spot
session_auth = spot.HTTP(
endpoint="https://api-testnet.bybit.com",
api_key="your api key",
api_secret="your api secret"
)
print(session_auth.user_trade_records(
symbol="BTCUSDT"
))
Response Example
{
"ret_code": 0,
"ret_msg": "",
"ext_code": null,
"ext_info": null,
"result": [
{
"id": "1178938734438029312",
"symbol": "BTC3SUSDT",
"symbolName": "BTC3SUSDT",
"orderId": "1178938734052153344",
"ticketId": "2120000000000690997",
"matchOrderId": "1178936255335987114",
"price": "38.8404",
"qty": "1",
"commission": "0.001",
"commissionAsset": "BTC3S",
"time": "1655276448918",
"isBuyer": true,
"isMaker": false,
"fee": {
"feeTokenId": "BTC3S",
"feeTokenName": "BTC3S",
"fee": "0.001"
},
"feeTokenId": "BTC3S",
"feeAmount": "0.001",
"makerRebate": "0",
"executionTime": "1655276448956"
}
]
}
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 50, max 50 |
fromTicketId | false | integer | Query greater than the trade ID. (fromTicketId < trade ID) |
toTicketId | false | integer | Query smaller than the trade ID. (trade ID < toTicketId) |
orderId | false | integer | Order ID |
startTime | false | long | Start time, unit in millisecond |
endTime | false | long | End time, unit in millisecond |
Response Parameters
Parameter | Type | Comment |
---|---|---|
symbol | string | Name of the trading pair |
id | int | Irrelevant for API usage. This field reflects the "Transaction ID" from the Trade History section of the website |
orderId | integer | Order ID |
ticketId | integer | Trade 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 | string | Order created time in the match engine |
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 trader |
fee | object | Trading fee (for a single fill) |
feeTokenId | string | Fee Token ID |
feeAmount | float | Trading fee (for a single fill) |
makerRebate | float | Maker rebate |
executionTime | string | Order execution time |
fee object
Parameter | Type | Comment |
---|---|---|
feeTokenId | long | Fee Token ID |
feeTokenName | string | Fee token name |
fee | float | Trading fee (for a single fill) |
Wallet Data Endpoints
The following wallet data endpoints require authentication.
Get Wallet Balance
Request Example
from pybit import spot
session_auth = spot.HTTP(
endpoint="https://api-testnet.bybit.com",
api_key="your api key",
api_secret="your api secret"
)
print(session_auth.get_wallet_balance())
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
Request Parameters
Parameter | Required | Type | Comment |
---|
Response Parameters
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-testnet.bybit.com/spot/v1/time
from pybit import spot
session_unauth = spot.HTTP(
endpoint="https://api-testnet.bybit.com"
)
print(session_unauth.server_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 |
---|
Leveraged Token Endpoints
All Asset Infos
Request Example
curl https://api-testnet.bybit.com/spot/lt/v1/infos?ltCode=BTC3S \
Response Example
{
"ret_code": 0,
"ret_msg": "",
"ext_code": null,
"ext_info": null,
"result": [
{
"ltCode": "BTC3S",
"ltName": "3X Short",
"maxPurchase": "1000000",
"minPurchase": "10",
"maxPurchaseDaily": "200000",
"maxRedeem": "1000",
"minRedeem": "100",
"maxRedeemDaily": "5000",
"purchaseFeeRate": "0.01",
"redeemFeeRate": "0.01",
"status": "1",
"fundFee": "-263.9050275",
"fundFeeTime": "1655452800000",
"manageFeeRate": "0.0001",
"manageFeeTime": "1655481787000",
"value": "549750319.6491748121231980105",
"total": "5000000",
"netValue": "39.350964984796264668"
}
]
}
HTTP Request
GET
/spot/lt/v1/infos
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
ltCode | false | string | Abbreviation of the LT. |
Response Parameters
Parameter | Type | Comment |
---|---|---|
ltCode | string | Abbreviation of the LT |
ltName | string | Full name of the LT |
maxPurchase | string | Max. purchase amount per transaction |
minPurchase | string | Min. purchase amount per transaction |
maxPurchaseDaily | string | Max. purchase amount per day |
maxRedeem | string | Max. redemption amount per transaction |
minRedeem | string | Min. redemption amount per transaction |
maxRedeemDaily | string | Max. redemption amount per day |
purchaseFeeRate | string | Purchase fees |
redeemFeeRate | string | Redemption fees |
status | string | Whether the LT can be purchased or redeemed; 1. LT can be purchased and redeemed; 2. LT can be purchased, but not redeemed; 3. LT can be redeemed, but not purchased; 4. LT cannot be purchased nor redeemed |
fundFee | string | Funding fees charged daily to users who hold LT |
fundFeeTime | long | Timestamps when funding fees are charged |
manageFeeRate | string | Management fees |
manageFeeTime | long | Timestamps when management fees are charged |
value | string | Internal used parameter, please ignore |
total | string | Application uplimit |
netValue | string | Net asset value |
Asset Info
Request Example
curl https://api-testnet.bybit.com/spot/lt/v1/info \
-H "Content-Type: application/x-www-form-urlencoded" \
-d 'api_key={api_key}<Code={ltCode}×tamp=1637669364000'
Response Example
{
"ret_code": 0,
"ret_msg": null,
"result": {
"ltCode": "BTC3L",
"ltName": "3X Long",
"maxPurchase": "300024.12345678",
"minPurchase": "0.12345678",
"maxPurchaseDaily": "500000.12345678",
"maxRedeem": "1000.12345678",
"minRedeem": "1.12345678",
"maxRedeemDaily": "1000002.12345678",
"purchaseFeeRate": "0.12345678",
"redeemFeeRate": "0.12345678",
"status": "1",
"fundFee": "0.12345678",
"fundFeeTime": 1620917160000,
"manageFeeRate": "-0.12345678",
"manageFeeTime": 1620917160000,
"value": "1212432.12345678",
"total": "200000000.12345678",
"netValue": "10.12345678"
},
"ext_code": null,
"ext_info": null
}
HTTP Request
GET
/spot/lt/v1/info
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
ltCode | true | string | Abbreviation of the LT. |
Response Parameters
Parameter | Type | Comment |
---|---|---|
ltCode | string | Abbreviation of the LT |
ltName | string | Full name of the LT |
maxPurchase | string | Max. purchase amount per transaction |
minPurchase | string | Min. purchase amount per transaction |
maxPurchaseDaily | string | Max. purchase amount per day |
maxRedeem | string | Max. redemption amount per transaction |
minRedeem | string | Min. redemption amount per transaction |
maxRedeemDaily | string | Max. redemption amount per day |
purchaseFeeRate | string | Purchase fees |
redeemFeeRate | string | Redemption fees |
status | string | Whether the LT can be purchased or redeemed; 1. LT can be purchased and redeemed; 2. LT can be purchased, but not redeemed; 3. LT can be redeemed, but not purchased; 4. LT cannot be purchased nor redeemed |
fundFee | string | Funding fees charged daily to users who hold LT |
fundFeeTime | long | Timestamps when funding fees are charged |
manageFeeRate | string | Management fees |
manageFeeTime | long | Timestamps when management fees are charged |
value | string | Internal used parameter, please ignore |
total | string | Application uplimit |
netValue | string | Net asset value |
Market Info
Request Example
Response Example
{
"ret_code": 0,
"ret_msg": "",
"ext_code": null,
"ext_info": null,
"result": {
"ltCode": "BTC3L",
"nav": "8.348543196938590649",
"navTime": "1650259325443",
"basket": "14.063000000262307568",
"leverage": "3.451925561403627643",
"circulation": "18969.901970158967556311"
}
}
HTTP Request
GET
/spot/lt/v1/reference
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
ltCode | true | string | Abbreviation of the LT. |
Response Parameters
Parameter | Type | Comment |
---|---|---|
ltCode | string | Abbreviation of the LT |
nav | string | Net asset value |
navTime | string | Update time for net asset value (in milliseconds and UTC time zone) |
basket | string | Total position value = basket value * total circulation |
leverage | string | Real Leverage calculated by last traded price. |
circulation | string | Circulating supply in the secondary market |
Purchase
Request Example
curl https://api-testnet.bybit.com/spot/lt/v1/purchase \
-H "Content-Type: application/x-www-form-urlencoded" \
-d 'api_key={api_key}<Code={ltCode}<Amount={ltAmount}&serialNo={serialNo}×tamp=1637669364000'
Response Example
{
"ret_code": 0,
"ret_msg": null,
"result": {
"ltCode": "BTC3L",
"orderStatus": "1",
"orderQuantity": "12",
"orderAmount": "123.12345678",
"amount": "123.12345678",
"timestamp": 1620917160000,
"id": 1,
"valueCoin": "USDT",
"serialNo": "0a65e75f165543103539010011"
},
"ext_code": null,
"ext_info": null
}
HTTP Request
POST
/spot/lt/v1/purchase
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
ltCode | true | string | Abbreviation of the LT. |
ltAmount | true | number | Purchase amount |
timestamp | true | number | Timestamp |
serialNo | false | string | Serial number |
Response Parameters
Parameter | Type | Comment |
---|---|---|
ltCode | string | Abbreviation of the LT |
orderStatus | string | Order status; 1. Completed; 2. In progress; 3. Failed |
orderQuantity | string | Order quantity of the LT |
orderAmount | string | Order value of the LT |
amount | string | Actual purchase value of the LT |
timestamp | long | Timestamp |
id | long | Transaction ID |
valueCoin | string | Quote asset |
serialNo | string | Serial number |
Redeem
Request Example
curl https://api-testnet.bybit.com/spot/lt/v1/redeem \
-H "Content-Type: application/x-www-form-urlencoded" \
-d 'api_key={api_key}<Code={ltCode}<Quantity={ltQuantity}&serialNo={serialNo}×tamp=1637669364000'
Response Example
{
"ret_code": 0,
"ret_msg": null,
"result": {
"ltCode": "BTC3L",
"orderStatus": "1",
"quantity": "12",
"orderQuantity": "123.12345678",
"orderAmount": "123.12345678",
"timestamp": 1620917160000,
"id": 1,
"valueCoin": "USDT",
"serialNo": "0a65e75f165543122947310021"
},
"ext_code": null,
"ext_info": null
}
HTTP Request
POST
/spot/lt/v1/redeem
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
ltCode | true | string | Abbreviation of the LT. |
ltQuantity | true | number | Redeem quantity |
timestamp | true | number | Timestamp |
serialNo | false | string | Serial number |
Response Parameters
Parameter | Type | Comment |
---|---|---|
ltCode | string | Abbreviation of the LT |
orderStatus | string | Order status; 1. Completed; 2. In progress; 3. Failed |
quantity | string | Quantity |
orderQuantity | string | Order quantity of the LT |
orderAmount | string | Order value of the LT |
timestamp | long | Timestamp |
id | long | Transaction ID |
valueCoin | string | Quote asset |
serialNo | string | Serial number |
Purchase/Redemption History
Request Example
Response Example
{
"ret_code": 0,
"ret_msg": "",
"ext_code": null,
"ext_info": null,
"result": [
{
"ltCode": "BTC3L",
"orderId": "1049",
"orderType": 1,
"orderTime": "1650253091000",
"excTime": "1650253107000",
"orderStatus": "1",
"fee": "0",
"amount": "9.44245991",
"value": "85.50095708",
"valueCoin": "USDT",
"serialNo": "0a65e240165025309566610041"
}
]
}
HTTP Request
GET
/spot/lt/v1/record
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
ltCode | false | string | Abbreviation of the LT. |
orderId | false | long | Order ID |
timestamp | true | long | Timestamp |
startTime | false | long | Start time |
endTime | false | long | End time |
limit | false | int | Limit for data size per page, max size is 500. Default as showing 100 pieces of data per page |
orderType | false | int | Order type; 1. Purchase; 2. Redemption |
serialNo | false | string | Serial number |
Response Parameters
Parameter | Type | Comment |
---|---|---|
ltCode | string | Abbreviation of the LT |
orderId | string | Order ID |
orderType | int | Order type; 1. Purchase; 2. Redemption |
orderTime | string | Order time |
excTime | string | Last update time of the order status |
orderStatus | string | Order status; 1. Completed; 2. In progress; 3. Failed |
fee | string | Trading fees |
amount | string | Order quantity of the LT |
value | string | Filled value |
valueCoin | string | Quote asset |
serialNo | string | Serial number |
Cross Margin Trading Endpoints
Borrow Margin Loan
Request Example
Response Example
{
"ret_code": 0,
"ret_msg": "",
"ext_code": null,
"ext_info": null,
"result": 438
}
HTTP Request
POST
/spot/v1/cross-margin/loan
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
currency | true | string | currency |
qty | true | string | Amount To Borrow |
Response Parameters
Parameter | Type | Comment |
---|---|---|
result | integer | Loan order id |
Repay Margin Loan
Request Example
Response Example
{
"ret_code": 0,
"ret_msg": "",
"ext_code": null,
"ext_info": null,
"result": 307
}
HTTP Request
POST
/spot/v1/cross-margin/repay
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
currency | true | string | currency |
qty | true | string | Repayment Amount |
Response Parameters
Parameter | Type | Comment |
---|---|---|
result | number | Loan order id |
Query Borrowing Info
Request Example
Response Example
{
"ret_code": 0,
"ret_msg": "",
"ext_code": null,
"ext_info": null,
"result": [
{
"id": "0",
"accountId": "290120",
"currency": "USDT",
"loanAmount": "500",
"loanBalance": "0.005",
"interestAmount": "0.005",
"interestBalance": "0",
"createdTime": "1650946211000",
"type": 2,
"status": 1
}
]
}
HTTP Request
GET
/spot/v1/cross-margin/order
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
startTime | false | long | Start time, unit in millisecond |
endTime | false | long | End time, unit in millisecond |
currency | false | string | currency |
status | false | int | translation missing: en.spotCrossMarginOrderStatus |
limit | false | int | Default is 500; Maximum is 500 |
Response Parameters
Parameter | Type | Comment |
---|---|---|
id | long | Borrowing Id |
accountId | string | Account ID |
currency | string | currency |
loanAmount | string | Principal Amount |
loanBalance | string | Outstanding Principal |
interestAmount | string | Total Interest |
interestBalance | string | Outstanding Interest |
createdTime | long | Timestamp (Borrowing), unit in millisecond |
type | int | Order Type (1. Manual 2. Auto) |
status | int | translation missing: en.spotCrossMarginOrderStatus |
Query Account Info
Request Example
Response Example
{
"ret_code": 0,
"ret_msg": "",
"ext_code": null,
"ext_info": null,
"result": {
"status": "1",
"riskRate": "0",
"acctBalanceSum": "17.544271415503388734",
"debtBalanceSum": "0.000000125952475464",
"loanAccountList": [
{
"tokenId": "BTC",
"total": "9.02798765888",
"locked": "0",
"loan": "0",
"interest": "0",
"free": "9.02798765888"
},
{
"tokenId": "XRP",
"total": "5074.35554",
"locked": "0",
"loan": "0",
"interest": "0",
"free": "5074.35554"
},
{
"tokenId": "ETH",
"total": "73.52299564",
"locked": "0",
"loan": "0",
"interest": "0",
"free": "73.52299564"
},
{
"tokenId": "USDT",
"total": "116360.2045351043476",
"locked": "0",
"loan": "0.005",
"interest": "0.0001",
"free": "116360.2045351043476"
},
{
"tokenId": "BIT",
"total": "6.78291",
"locked": "0",
"loan": "0",
"interest": "0",
"free": "6.78291"
}
]
}
}
HTTP Request
GET
/spot/v1/cross-margin/accounts/balance
Request Parameters
Parameter | Required | Type | Comment |
---|
Response Parameters
Parameter | Type | Comment |
---|---|---|
status | string | Status (1. Normal 2. Withdrawal/Transfer Restricted 3. Liquidation Alert Triggered 4. Liquidated 5. Negative Equity) |
riskRate | string | Risk Rate |
acctBalanceSum | string | Total Equity (BTC) |
debtBalanceSum | string | Total Liability (BTC) |
loanAccountList | List | Object |
tokenId | string | Token Id |
total | string | Total |
free | string | Available |
locked | string | Locked |
loan | string | Total Liability |
interest | string | Interest Left |
Query Interest & Quota
Request Example
Response Example
{
"ret_code": 0,
"ret_msg": "",
"ext_code": null,
"ext_info": null,
"result": {
"currency": "USDT",
"interestRate": "0.00011",
"maxLoanAmount": "15000",
"loanAbleAmount": "1414762.97401717124312"
}
}
HTTP Request
GET
/spot/v1/cross-margin/loan-info
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
currency | true | string | currency |
Response Parameters
Parameter | Type | Comment |
---|---|---|
currency | string | currency |
interestRate | string | Daily Interest Rate |
maxLoanAmount | int | Please ignore |
loanAbleAmount | string | Available Amount to Borrow |
Query Repayment History
Request Example
Response Example
{
"ret_code": 0,
"ret_msg": "",
"ext_code": null,
"ext_info": null,
"result": [
{
"repayMarginOrderId": "1142655714041531904",
"repayId": "307",
"accountId": "290120",
"currency": "USDT",
"repaidAmount": "500",
"repayTime": "1650951176000",
"transactIds": [
{
"transactId": "438",
"repaidSerialNumber": "1142614062270779136",
"repaidAmount": "500",
"repaidPrincipal": "499.995",
"repaidInterest": "0.005"
}
]
}
]
}
HTTP Request
GET
/spot/v1/cross-margin/repay/history
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
startTime | false | long | Start time, unit in millisecond |
endTime | false | long | End time, unit in millisecond |
currency | false | string | currency |
limit | false | int | Default is 500; Maximum is 500 |
Response Parameters
Parameter | Type | Comment |
---|---|---|
repayMarginOrderId | string | Repay Margin Order Id |
repayId | string | Repay Id |
repayTime | string | Timestamp, unit in millisecond |
accountId | string | Account ID |
currency | string | currency |
repaidAmount | string | Total Amount Repaid |
transactIds | List | Object |
repaidSerialNumber | string | Repayment No. (Borrowing Order) |
transactId | string | Transaction ID (Borrowing) |
repaidAmount | string | Total Amount Repaid |
repaidPrincipal | string | Total Principal Repaid |
repaidInterest | string | Total Interest Repaid |
Rate Limits
IP Rate Limit
Bybit has different IP frequency limits depending on the request method. We do not recommend running your application at the very edge of these limits in case abnormal network activity results in an unexpected violation.
-
GET
,POST
&DELETE
methods (shared):- 120 requests per second for 5 consecutive seconds
All traffic to api.bybit.com or api.bytick.com share this limit regardless of if it accesses Spot, Derivatives or Options.
After violating the limit your IP will be banned for a set period of time (usually 30 minutes). Continually violating the limit will result in a permanent ban. We cannot undo permanent bans or shorten temporary bans.
API Rate Limit
Rate Limits For All Private Endpoints
Limit | Path |
---|---|
5 requests/second | Cross Margin Trading Endpoints |
20 requests/second | All other private endpoints |
The rate limits for each private endpoint should be considered separately.
WebSocket Data
Authentication
Apply for authentication when establishing a connection.
Note: if you're using pybit or another high-level library, you can ignore this code - as authentication is handled for you.
# based on: https://github.com/bybit-exchange/pybit/blob/master/pybit/_http_manager.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:
- Testnet:
- Public Topics: wss://stream-testnet.bybit.com/spot/quote/ws/v1
- Public Topics v2: wss://stream-testnet.bybit.com/spot/quote/ws/v2
- Private Topics: wss://stream-testnet.bybit.com/spot/ws
- Mainnet:
- Public Topics: wss://stream.bybit.com/spot/quote/ws/v1
- Public Topics v2: wss://stream.bybit.com/spot/quote/ws/v2
- Private Topics: wss://stream.bybit.com/spot/ws
Authentication examples are shown in the code block.
An IP can connect to a maximum of 50 private spot websocket connections simultaneously.
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
// 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}}');
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}}');
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
}
}
from time import sleep
from pybit import spot
ws_spot = spot.WebSocket(
test=True,
ping_interval=30, # the default is 30
ping_timeout=10, # the default is 10
domain="bybit" # the default is "bybit"
)
def handle_message(msg):
print(msg)
# To subscribe to multiple symbols,
# pass a list: ["BTCUSDT", "ETHUSDT"]
ws_spot.trade_v1_stream(
handle_message, ["BTCUSDT", "ETHUSDT"]
)
while True:
sleep(1)
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
}
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
), only new trades are pushed.
Variable v
is a trade ID which is unique across the platform.
Pushes data at a frequency of 300ms. Message received with a maximum delay of 400ms.
Response Parameters
Parameter | Type | Comment |
---|---|---|
symbol | string | Trading pair |
symbolName | string | Trading pair |
topic | string | Topic name |
binary | string | Compressed or not. Defaults to false |
v | string | Trade ID |
t | string | Timestamp (trading time in the match box) |
p | string | Price |
q | boolean | Quantity |
m | boolean | True indicates buy side is taker, false indicates sell side is taker |
f | boolean | First message for this topic since subscription |
sendTime | string | Timestamp of data sent |
realtimes
How to Subscribe
{
"topic": "realtimes",
"event": "sub",
"symbol": "BTCUSDT",
"params": {
"binary": false
}
}
from time import sleep
from pybit import spot
ws_spot = spot.WebSocket(
test=True,
ping_interval=30, # the default is 30
ping_timeout=10, # the default is 10
domain="bybit" # the default is "bybit"
)
def handle_message(msg):
print(msg)
# To subscribe to multiple symbols,
# pass a list: ["BTCUSDT", "ETHUSDT"]
ws_spot.realtimes_v1_stream(
handle_message, ["BTCUSDT", "ETHUSDT"]
)
while True:
sleep(1)
Response Example - format of all responses
{
"symbol": "BTCUSDT",
"symbolName": "BTCUSDT",
"topic": "realtimes",
"params": {
"realtimeInterval": "24h",
"binary": "false"
},
"data": [
{
"c": "21082.22",
"e": 301,
"h": "21426.99",
"l": "20575",
"m": "0.0190",
"o": "20689.11",
"qv": "141768159.45007801",
"s": "BTCUSDT",
"sn": "BTCUSDT",
"t": 1673852936684,
"v": "6772.990042",
"xp": "21092.15001144"
}
],
"f": true,
"sendTime": 1673852937236
}
The 24-hr statistics of a trading pair.
Pushes data at a frequency of 300ms. Message received with a maximum delay of 400ms.
Response Parameters
Parameter | Type | Comment |
---|---|---|
symbol | string | Trading pair |
symbolName | string | Trading pair |
topic | string | Topic name |
t | number | Timestamp (trading time in the match box) |
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 |
xp | string | USD index price. It can be "" |
sendTime | string | Timestamp of data sent |
kline
How to Subscribe
{
"topic": "kline_1m",
"event": "sub",
"symbol": "BTCUSDT",
"params": {
"binary": false
}
}
from time import sleep
from pybit import spot
ws_spot = spot.WebSocket(
test=True,
ping_interval=30, # the default is 30
ping_timeout=10, # the default is 10
domain="bybit" # the default is "bybit"
)
def handle_message(msg):
print(msg)
# To subscribe to multiple symbols,
# pass a list: ["BTCUSDT", "ETHUSDT"]
# pass an inverval
ws_spot.kline_v1_stream(
handle_message, ["BTCUSDT", "ETHUSDT"], "1h"
)
while True:
sleep(1)
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
}
This topic pushes kline data.
To subscribe to different intervals, 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.
Pushes data at a frequency of 300ms. Message received with a maximum delay of 400ms.
Response Parameters
Parameter | Type | Comment |
---|---|---|
symbol | string | Trading pair |
symbolName | string | Trading pair |
topic | string | Topic name |
klineType | string | Interval |
binary | string | Compressed or not. Defaults to false |
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 |
sendTime | string | Timestamp of data sent |
depth
How to Subscribe
{
"topic": "depth",
"event": "sub",
"symbol": "BTCUSDT",
"params": {
"binary": false
}
}
from time import sleep
from pybit import spot
ws_spot = spot.WebSocket(
test=True,
ping_interval=30, # the default is 30
ping_timeout=10, # the default is 10
domain="bybit" # the default is "bybit"
)
def handle_message(msg):
print(msg)
# To subscribe to multiple symbols,
# pass a list: ["BTCUSDT", "ETHUSDT"]
ws_spot.depth_v1_stream(
handle_message, "ETHUSDT"
)
while True:
sleep(1)
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
}
This topic pushes order book data.
- Snapshot depth: 200 per side.
- Events which trigger a message push to this topic:
- Order enters order book
- Order leaves order book
- Order quantity changes
- Order filled
Pushes data at a frequency of 300ms. Message received with a maximum delay of 650ms.
Response Parameters
Parameter | Type | Comment |
---|---|---|
symbol | string | Trading pair |
symbolName | string | Trading pair |
topic | string | Topic name |
binary | string | Compressed or not. Defaults to false |
e | number | Exchange ID |
t | number | timestamp(ms). The time that system generates the data. |
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 |
sendTime | string | Timestamp of data sent |
mergedDepth
How to Subscribe
{
"topic": "mergedDepth",
"event": "sub",
"symbol": "BTCUSDT",
"params": {
"binary": false,
"dumpScale": 1
}
}
from time import sleep
from pybit import spot
ws_spot = spot.WebSocket(
test=True,
ping_interval=30, # the default is 30
ping_timeout=10, # the default is 10
domain="bybit" # the default is "bybit"
)
def handle_message(msg):
print(msg)
# To subscribe to multiple symbols,
# pass a list: ["BTCUSDT", "ETHUSDT"]
# pass dumpScale
ws_spot.merged_depth_v1_stream(
handle_message, "ETHUSDT", 1
)
while True:
sleep(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
}
This topic pushes aggregated order book data.
dumpScale
must be specified for this endpoint. It refers to the number of decimal places, eg 1
for 50000.5
or 0
for 50000
.
Pushes a depth of 40 items per side, regardless of the dumpScale
.
Pushes data at a frequency of 300ms. Message received with a maximum delay of 650ms.
Response Parameters
Parameter | Type | Comment |
---|---|---|
symbol | string | Trading pair |
symbolName | string | Trading pair |
topic | string | Topic name |
dumpScale | string | Dump scale |
binary | string | Compressed or not. Defaults to false |
e | number | Exchange ID |
t | number | timestamp(ms). The time that system generates the data. |
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 |
sendTime | string | Timestamp of data sent |
diffDepth
How to Subscribe
{
"topic": "diffDepth",
"event": "sub",
"symbol": "BTCUSDT",
"params": {
"binary": false
}
}
from time import sleep
from pybit import spot
ws_spot = spot.WebSocket(
test=True,
ping_interval=30, # the default is 30
ping_timeout=10, # the default is 10
domain="bybit" # the default is "bybit"
)
def handle_message(msg):
print(msg)
# To subscribe to multiple symbols,
# pass a list: ["BTCUSDT", "ETHUSDT"]
ws_spot.diff_depth_v1_stream(
handle_message, "ETHUSDT"
)
while True:
sleep(1)
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
}
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.
For a Python example of the logic to maintain a local order book with this topic, see here.
If the quantity=0, it indicates that there are no longer any orders at this price level. If the quantity>0, the quantity for this price has changed.
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 (there are no orders on this side at this price level).
Pushes data at a frequency of 300ms. Message received with a maximum delay of 650ms.
Response Parameters
Parameter | Type | Comment |
---|---|---|
symbol | string | Trading pair |
symbolName | string | Trading pair |
topic | string | Topic name |
binary | string | Compressed or not. Defaults to false |
e | number | Exchange ID |
t | number | timestamp(ms). The time that system generates the data. |
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 |
sendTime | string | Timestamp of data sent |
lt
How to Subscribe
{
"topic": "lt",
"symbol": "BTC3LUSDTNAV",
"event": "sub",
"params": {
"binary": false
}
}
Response Example - format of all responses
{
"symbol":"BTC3LUSDTNAV",
"symbolName":"BTC3LUSDTNAV",
"topic":"lt",
"params":{
"realtimeInterval":"24h",
"binary":"false"
},
"data":[
{
"t":1650272320201,
"s":"BTC3LUSDTNAV",
"nav":"8.36157024279442973500",
"b":"0.000741332244224795",
"l":"3.448586744632192167",
"loan":"-20.474030060817421380",
"ti":"18969.901970158967556311",
"n":"14.063000000262307568"
}
],
"f":"True",
"sendTime":1650272320374
}
Leveraged Token Net Value Push. Pushes data at a frequency of 300ms. Message received with a maximum delay of 400ms.
Response Parameters
Parameter | Type | Comment |
---|---|---|
symbol | string | Trading pair |
symbolName | string | Trading pair |
topic | string | Topic name |
binary | string | Compressed or not. Defaults to false |
t | number | Timestamp |
s | string | Please make sure to add "NAV" as a suffix to the name of the pair you're querying |
nav | string | Net asset value |
b | string | Basket value |
l | string | Real Leverage calculated by last traded price. |
loan | string | Basket loan |
ti | string | Circulating supply in the secondary market |
n | string | Total position value = basket value * total circulation |
sendTime | string | Timestamp of data sent |
Public Topics V2
depth
How to Subscribe
{
"topic": "depth",
"event": "sub",
"params": {
"symbol": "BTCUSDT",
"binary": false
}
}
from time import sleep
from pybit import spot
ws_spot = spot.WebSocket(
test=True,
ping_interval=30, # the default is 30
ping_timeout=10, # the default is 10
domain="bybit" # the default is "bybit"
)
def handle_message(msg):
print(msg)
# v2 does not support to subscribe mutiple symbols
ws_spot.depth_v2_stream(
handle_message, "ETHUSDT"
)
while True:
sleep(1)
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:
- Snapshot depth: 40 each for asks and bids.
- Events trigger order book version change:
- order enters order book
- order leaves order book
- order quantity changes
- order filled
Pushes data at a frequency of 100ms.
Response Parameters
Parameter | Type | Comment |
---|---|---|
topic | string | Topic name |
symbol | string | Trading pair |
symbolName | string | Trading pair |
binary | string | Compressed or not. Defaults to false |
t | number | timestamp(ms). The time that system generates the data. |
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
}
}
from time import sleep
from pybit import spot
ws_spot = spot.WebSocket(
test=True,
ping_interval=30, # the default is 30
ping_timeout=10, # the default is 10
domain="bybit" # the default is "bybit"
)
def handle_message(msg):
print(msg)
# v2 does not support to subscribe mutiple symbols
# pass an interval
ws_spot.kline_v2_stream(
handle_message, "ETHUSDT", "1h"
)
while True:
sleep(1)
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"
}
}
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 real-time.
Response Parameters
Parameter | Type | Comment |
---|---|---|
topic | string | Topic name |
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"
}
from time import sleep
from pybit import spot
ws_spot = spot.WebSocket(
test=True,
ping_interval=30, # the default is 30
ping_timeout=10, # the default is 10
domain="bybit" # the default is "bybit"
)
def handle_message(msg):
print(msg)
# v2 does not support to subscribe mutiple symbols
ws_spot.trade_v2_stream(
handle_message, "ETHUSDT"
)
while True:
sleep(1)
Response Example - format of all responses
{
"params": {
"binary": "false",
"symbol": "BTCUSDT",
"symbolName": "BTCUSDT"
},
"topic": "trade",
"data": {
"v": "2290000000033122060",
"t": 1671154635003,
"p": "17387.19",
"q": "0.025",
"m": false,
"type": "0"
}
}
This topic pushes raw trade information; each trade has a unique buyer and seller.
Variable "v" acts as a 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 tradeId (which is "v") will be consecutive: 112, 113, 114.
Pushes data near real-time.
Response Parameters
Parameter | Type | Comment |
---|---|---|
topic | string | Topic name |
symbol | string | Trading pair |
binary | string | Compressed or not. Defaults to false |
symbolName | string | Trading pair |
v | string | Trade ID |
t | number | Timestamp (trading time in the match box) |
p | string | Price |
q | string | Quantity |
m | boolean | True indicates buy side is taker, false indicates sell side is taker |
type | string | Trade type. 0 :Spot trade. 1 :Paradigm block trade |
bookTicker
How to Subscribe
{
"topic": "bookTicker",
"event": "sub",
"params": {
"symbol": "BTCUSDT",
"binary": false
}
}
from time import sleep
from pybit import spot
ws_spot = spot.WebSocket(
test=True,
ping_interval=30, # the default is 30
ping_timeout=10, # the default is 10
domain="bybit" # the default is "bybit"
)
def handle_message(msg):
print(msg)
# v2 does not support to subscribe mutiple symbols
ws_spot.book_ticker_v2_stream(
handle_message, "ETHUSDT"
)
while True:
sleep(1)
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
Pushes data at a frequency of 100ms.
Response Parameters
Parameter | Type | Comment |
---|---|---|
topic | string | Topic name |
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(ms). The time that system generates the data. |
realtimes
How to Subscribe
{
"topic": "realtimes",
"event": "sub",
"params": {
"symbol": "BTCUSDT",
"binary": false
}
}
from time import sleep
from pybit import spot
ws_spot = spot.WebSocket(
test=True,
ping_interval=30, # the default is 30
ping_timeout=10, # the default is 10
domain="bybit" # the default is "bybit"
)
def handle_message(msg):
print(msg)
# v2 does not support to subscribe mutiple symbols
ws_spot.realtimes_v2_stream(
handle_message, "ETHUSDT"
)
while True:
sleep(1)
Response Example - format of all responses
{
"params": {
"binary": "false",
"symbol": "BTCUSDT",
"symbolName": "BTCUSDT"
},
"topic": "realtimes",
"data": {
"t": 1673853086475,
"s": "BTCUSDT",
"c": "21095.97",
"h": "21426.99",
"l": "20575",
"o": "20694.57",
"v": "6779.79813",
"qv": "141913713.70049255",
"m": "0.0194",
"xp": "21103.14018642"
}
}
The 24-hr statistics of a trading pair.
Pushes data near real-time.
Response Parameters
Parameter | Type | Comment |
---|---|---|
topic | string | Topic name |
symbol | string | Trading pair |
binary | string | Compressed or not. Defaults to false |
symbolName | string | Trading pair |
t | number | Timestamp (trading time in the match box) |
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 |
xp | string | USD index price. It can be "" |
Private Topics
Sending the authentication message automatically subscribes you to all 4 private topics.
outboundAccountInfo
Sending the authentication message automatically subscribes you to all 4 private topics.
from time import sleep
from pybit import spot
ws_spot = spot.WebSocket(
test=True,
api_key="your api key",
api_secret="your api secret",
ping_interval=30, # the default is 30
ping_timeout=10, # the default is 10
domain="bybit" # the default is "bybit"
)
def handle_message(msg):
print(msg)
ws_spot.outbound_account_info_stream(
handle_message
)
while True:
sleep(1)
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 real-time.
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 | coin name |
f | string | Available balance |
l | string | Reserved for orders |
executionReport
Sending the authentication message automatically subscribes you to all 4 private topics.
from time import sleep
from pybit import spot
ws_spot = spot.WebSocket(
test=True,
api_key="your api key",
api_secret="your api secret",
ping_interval=30, # the default is 30
ping_timeout=10, # the default is 10
domain="bybit" # the default is "bybit"
)
def handle_message(msg):
print(msg)
ws_spot.execution_report_stream(
handle_message
)
while True:
sleep(1)
Response Example - format of all responses
{
"e": "executionReport",
"E": "1661505745347",
"s": "BITUSDT",
"c": "1661505744705",
"S": "BUY",
"o": "MARKET_OF_QUOTE",
"f": "GTC",
"q": "20",
"p": "0",
"X": "CANCELED",
"i": "1231193858535151104",
"M": "1231190924099373824",
"l": "14.16",
"z": "14.16",
"L": "1.4121",
"n": "0.01416",
"N": "BIT",
"u": true,
"w": true,
"m": true,
"O": "1661505745176",
"Z": "19.995336",
"A": "0",
"C": false,
"v": "0",
"d": "NO_LIQ",
"t": "2120000000001252630"
}
Pushes data about your orders. Z
divided by z
equals the average filled price.
Pushes data in real-time.
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, LIMIT/MARKET_OF_QUOTE/MARKET_OF_BASE |
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 trader |
l | string | Last filled quantity |
z | string | Total filled quantity |
L | string | Last traded price |
n | string | Trading fee (for a single fill) |
N | string | Asset type in which fee is paid |
u | boolean | Is normal trade. False if self-trade. |
w | boolean | Is working. false |
m | boolean | Is LIMIT_MAKER |
O | string | Order creation time |
Z | string | Total filled value |
A | string | Account ID of the opponent trader |
C | boolean | Is close |
v | string | leverage |
d | string | NO_LIQ indicates that it is not a liquidation order. IOC indicates that it is a liquidation order. |
t | string | Trade ID |
stop_executionReport
Sending the authentication message automatically subscribes you to all 4 private topics.
Response Example - format of all responses
[
{
"e": "stop_executionReport",
"E": "1660031832249",
"s": "BTCUSDT",
"c": "1660031262869",
"S": "BUY",
"o": "MARKET_OF_QUOTE",
"f": "GTC",
"q": "0",
"p": "0",
"X": "ORDER_CANCELED",
"i": "1218825007084354304",
"T": "1660031263181",
"t": "0",
"C": "1660031832223",
"qp": "23668.86",
"eo": "1218825007084354305",
"ti": "4add1fe84e577026",
"si": "bc86964648a3c395"
}
]
Pushes data about your TP/SL orders. It will be triggered as long as tp/sl order status is changed.
Pushes data in real-time
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, LIMIT/MARKET_OF_QUOTE/MARKET_OF_BASE |
f | string | Time in force |
q | string | Quantity |
p | string | Price |
X | string | TP/SL order status |
i | string | Order ID |
T | string | Order created time |
t | string | Order triggered time. The field is filled only when order status is ORDER_FILLED and ORDER_FAILED |
C | string | Order updated time. It is updated when order status is changed. |
qp | string | The market price when place the order |
eo | string | The new order id after the tp/sl order is triggered. |
ti | string | Please ignore |
si | string | Please ignore |
ticketInfo
Sending the authentication message automatically subscribes you to all 4 private topics.
from time import sleep
from pybit import spot
ws_spot = spot.WebSocket(
test=True,
api_key="your api key",
api_secret="your api secret",
ping_interval=30, # the default is 30
ping_timeout=10, # the default is 10
domain="bybit" # the default is "bybit"
)
def handle_message(msg):
print(msg)
ws_spot.ticket_info_stream(
handle_message
)
while True:
sleep(1)
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",
"m":true,
"S":"BUY"
}
]
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 real-time.
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 | Trade ID |
o | string | Order ID |
c | string | User-generated order ID |
O | string | Order ID of the opponent trader |
a | string | Account ID |
A | string | Account ID of the opponent trader |
m | boolean | Is MAKER. true=maker, false=taker |
S | string | BUY or SELL |
Archive Data
Historical Market Data
You can get Bybit's historical market data here.
Historical funding rates are not available through the API. However, you can obtain a CSV of this data by using the "Export" button here.
Enums Definitions
The following lists enumerator names for the request and response parameters of each endpoint.
Side (side
)
Buy
Sell
Time in force (timeInForce
)
GTC
- Good Till CanceledFOK
- Fill or KillIOC
- Immediate or Cancel
Symbol (symbol
)
BTCUSDT
ETHUSDT
- ...
You can get all symbols with the Query Symbol endpoint.
Order type (type
/orderTypes
)
LIMIT
MARKET
LIMIT_MAKER
Currency (currency
/coin
)
BTC
ETH
EOS
XRP
USDT
The transfer API also includes:
DOT
DOGE
LTC
XLM
USD
Cross Margin Trading Endpoints support below currency:
BTC
ETH
XRP
SOL
LTC
EOS
LINK
XLM
USDC
USDT
Order status (status
)
NEW
PARTIALLY_FILLED
FILLED
CANCELED
PENDING_CANCEL
PENDING_NEW
REJECTED
The below status for tp/sl order only
ORDER_NEW
UntriggeredORDER_CANCELED
ORDER_FILLED
TriggeredORDER_FAILED
fail to trigger
Quantity (qty
)
- The maximum qty for an order (
max_trading_qty
) can be queried with the Query Symbol endpoint. - Must be a positive integer
- Must conform to the symbol's
qty_step
. For example, for the inverse perpetual BTCUSD market: 40
- allowed30.5
- not allowed
Price (price
)
- Must be an integral multiple of
minPricePrecision
- Information about current trading pair (e.g.
minPricePrecision
) can be queried with the Query Symbol endpoint.
Time in force (
time_in_force
)GTC
IOC
FOK
Kline interval (
interval
)1m
- 1 minute3m
- 3 minutes5m
- 5 minutes15m
- 15 minutes30m
- 30 minutes1h
- 1 hour2h
- 2 hours4h
- 4 hours6h
- 6 hours12h
- 12 hours1d
- 1 day1w
- 1 week1M
- 1 month
LT status (
status
)1
- ETP can be purchased and redeemed2
- ETP can be purchased, but not redeemed3
- ETP can be redeemed, but not purchased4
- ETP cannot be purchased nor redeemed
LT order status (
orderStatus
)1
- Completed2
- In progress3
- Failed
LT order type (
orderType
)1
- Purchase2
- Redemption
TP/Sl order status (
status
)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 -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.
-1004
Missing required parameter
symbol
. Content-Type has been configured to application/json; params in JSON format.-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.
-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
Signature for this request is not valid. Check the content-type and try without content-type. If symbol is set to BTC/USDT instead of BTCUSDT this error can ocur. The slash would not be urlencoded before the signature, but it would be after, resulting in mismatching param str.
-1032
Parameter format error
-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
An unknown parameter was sent. For POST request - No content-type specified, should change to application/x-www-form-urlencoded or make sure the query string is in the full request URL. For DELETE request, make sure your parameters are in query string format and the query string is in the full request URL. For GET request - Don't set Content-Type to "application/json". "Spot" permission not enabled when creating the API key.
-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.
-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.
-1201
This coin does not exist
-1202
Too many requests in this time frame
-1203
Your Spot Account with Institutional Lending triggers an alert or liquidation
-1204
You're not a user of the Innovation Zone
-1205
You've failed to check the Risk Alert for Leveraged Tokens
-1206
Your Spot Account for Margin Trading is being liquidated
-1207
This feature is not supported
-1208
The purchase amount of each order exceeds the estimated maximum purchase amount
-1209
The sell quantity per order exceeds the estimated maximum sell quantity
-1210
The reserved quota for Spot Margin Trading does not meet the LTV ratio requirement
-1211
Users with Spot Margin Trading are not allowed to perform Block Trades
-1212
Users with Institutional Lending are not allowed to perform Block Trades
-1213
Users with Leverage Tokens are not allowed to perform Block Trades
-1214
System Error
-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.
-6001
Query user repay history error
-6002
Query user account info error
-6003
Query user loan history error
-6004
Query order history start time exceeds end time
-6005
Failed to borrow
-6006
Repayment Failed
-6007
User not found
-6008
You haven't enabled Cross Margin Trading yet. To do so, please head to the PC trading site
-6009
You haven't enabled Cross Margin Trading yet. To do so, please head to the PC trading site or the Bybit app
-6010
Failed to locate the coins to borrow
-6011
Cross Margin Trading not yet supported by the selected coin
-6012
Pair not available
-6013
Cross Margin Trading not yet supported by the selected pair
-6014
Repeated repayment requests
-6015
Insufficient available balance
-6016
No repayment required
-6017
Repayment amount has exceeded the total liability
-6018
Settlement in progress
-6019
Liquidation in progress
-6020
Failed to locate repayment history
-6021
Repeated borrowing requests
-6022
Coins to borrow not generally available yet
-6023
Pair to borrow not generally available yet
-6024
Invalid user status
-6025
Amount to borrow cannot be lower than the min. amount to borrow (per transaction)
-6026
Amount to borrow cannot be larger than the max. amount to borrow (per transaction)
-6027
Amount to borrow cannot be higher than the max. amount to borrow per user
-6028
Amount to borrow has exceeded Bybit's max. amount to borrow
-6029
Amount to borrow has exceeded the user's estimated max. amount to borrow
-6030
Query user loan info error
-6031
Loan precision has exceeded the maximum precision
-6032
Number of decimals has exceeded the maximum precision
-4000
The serialNum is already in use.
-4001
Daily purchase limit has been exceeded. Please try again later.
-4002
There's a large number of purchase orders. Please try again later.
-4003
Insufficient available balance. Please make a deposit and try again.
-4004
Daily redemption limit has been exceeded. Please try again later.
-4005
There's a large number of redemption orders. Please try again later.
-4006
Insufficient available balance. Please make a deposit and try again.
-4007
Order not found.
-4008
Purchase period hasn't started yet.
-4009
Purchase amount has exceeded the upper limit.
-4010
You must enable Leveraged Tokens first to start trading. To do so, please head to the PC trading site.
-4012
Redemption period hasn't started yet.
-4013
Redemption amount has exceeded the upper limit.
-4014
Purchase of the LT has been temporarily suspended.
-4015
Redemption of the LT has been temporarily suspended.
-4016
Invalid format. Please check the length and numeric precision.
-4110
Failed to place order: Exceed the maximum position limit of leveraged tokens, the current available limit is XXXX USDT.
10008
uta banned. UTA account cannot request this endpoint, you need to check your account.
10024
Compliance rules triggered. Please complete KYC.
10029
The requested symbol is invalid, which are not in the symbol whitelist.
- Information about current trading pair (e.g.