繁體中文
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

2022-05-12

REST API

2022-04-14

WebSocket 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

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

1.The parameters are in json format

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.

Message format for POST requests:

POST 'https://api.bybit.com/option/usdc/openapi/private/v1/place-order'
X-BAPI-API-KEY: your api key
X-BAPI-SIGN: 6c864f0f0d332133b79de911387c6408ae0d189609c485b9a132fd5ec3beb2ee'
X-BAPI-SIGN-TYPE: 2
X-BAPI-TIMESTAMP: 1655197818844
X-BAPI-RECV-WINDOW: 5000
Content-Type: application/json

{
    "side": "Buy",
    "symbol": "BTC-14JUN22-24500-C",
    "orderType": "Market",
    "orderQty": "0.5",
    "orderPrice": "500",
    "orderLinkId": "option10005",
    "reduce_only": false
}
import requests
import json
import time
import hashlib
import hmac

api_key='API-KEY'
secret_key='SECRET-KEY'
time_stamp=str(int(time.time() * 10 ** 3))
recv_window=str(5000)
url = "https://api-testnet.bybit.com/perpetual/usdc/openapi/private/v1/place-order"

payload = json.dumps({"side":"Buy","orderFilter":"Order","orderType":"Limit","orderQty":"5","orderPrice":"40780","timeInForce":"ImmediateOrCancel","symbol":"BTCPERP"})

param_str= str(time_stamp) + api_key + recv_window + payload
hash = hmac.new(bytes(secret_key, "utf-8"), param_str.encode("utf-8"),hashlib.sha256)
signature = hash.hexdigest()

headers = {
  'X-BAPI-API-KEY': api_key,
  'X-BAPI-SIGN': signature,
  'X-BAPI-SIGN-TYPE': '2',
  'X-BAPI-TIMESTAMP': time_stamp,
  'X-BAPI-RECV-WINDOW': recv_window,
  'Content-Type': 'application/json'
}
response = requests.request("POST", url, headers=headers, data=payload)
print(response.text)

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.

OrderBook

Request Example

curl https://api-testnet.bybit.com/perpetual/usdc/openapi/public/v1/order-book?symbol=BTCPERP' \

Response Example

{
  "retCode":0,
    "retMsg":"",
    "result":[
    {
      "price":"56390",
      "size":"0.0130000",
      "side":"Buy"
    },
    {
      "price":"56797.5",
      "size":"1.4430000",
      "side":"Sell"
    }
  ]
}

HTTP Request

GET /perpetual/usdc/openapi/public/v1/order-book

Request Parameters

Parameter Required Type Comment
symbol true string Contract name

Response Parameters

Parameter Type Comment
price string price
size string size
side string Direction, Buy or Sell

Contract Info

Request Example

curl https://api-testnet.bybit.com/perpetual/usdc/openapi/public/v1/symbols

Response Example

{
  "retCode": 0,
    "retMsg": "",
    "result": [
    {
      "symbol": "BTCPERP",
      "status": "ONLINE",
      "baseCoin": "BTC",
      "quoteCoin": "USD",
      "takerFeeRate": "0.00075",
      "makerFeeRate": "-0.00025",
      "minLeverage": "1",
      "maxLeverage": "100",
      "leverageStep": "0.01",
      "minPrice": "0.50",
      "maxPrice": "999999.00",
      "tickSize": "0.50",
      "maxTradingQty": "5.000",
      "minTradingQty": "0.001",
      "qtyStep": "0.001",
      "deliveryFeeRate": "",
      "deliveryTime": "0"
    }
  ]
}

HTTP Request

GET /perpetual/usdc/openapi/public/v1/symbols

Request Parameters

Parameter Required Type Comment
symbol false string Contract name
direction false string

prev: prev page, next: next page.

limit false string Number of data per page; the max. value is 200, and the default value is 200

Response Parameters

Parameter Type Comment
symbol string Contract name
status string Status, can be WAITING_ONLINE, ONLINE, DELIVERING, or OFFLINE
baseCoin string Base currency
quoteCoin string Quote currency
takerFeeRate string Taker fee rate
makerFeeRate string Maker fee rate
minLeverage string Min. leverage
maxLeverage string Max. leverage
leverageStep string Modification to leverage
minPrice string Min. order price
maxPrice string Max. order price
tickSize string Tick size
minTradingQty string Min. order quantity
maxTradingQty string Max. order quantity
qtyStep string Min. order quantity increment
deliveryFeeRate string Delivery fee rate
deliveryTime string Delivery time, unit in milliseconds

Latest Symbol Info

Request Example

curl 'https://api-testnet.bybit.com/perpetual/usdc/openapi/public/v1/tick?symbol=BTCPERP'

Response Example

{
  "retCode": 0,
    "retMsg": "",
    "result": {
    "symbol": "BTCPERP",
      "bid": "56685",
      "bidIv": "",
      "bidSize": "1.954",
      "ask": "56760",
      "askIv": "",
      "askSize": "114.866",
      "lastPrice": "56457.00",
      "openInterest": "1853.80",
      "indexPrice": "56928.09",
      "markPrice": "57216.42",
      "markPriceIv": "",
      "change24h": "-0.053195",
      "high24h": "59629.00",
      "low24h": "56110.50",
      "volume24h": "35.92",
      "turnover24h": "2040176.21",
      "totalVolume": "35.92",
      "totalTurnover": "2040176.21",
      "fundingRate": "0",
      "predictedFundingRate": "0",
      "nextFundingTime": "2021-11-30T16:00:00Z",
      "countdownHour": "6",
      "predictedDeliveryPrice": "",
      "underlyingPrice": "",
      "delta": "",
      "gamma": "",
      "vega": "",
      "theta": ""
  }
}

HTTP Request

GET /perpetual/usdc/openapi/public/v1/tick

Request Parameters

Parameter Required Type Comment
symbol true string Contract name

Response Parameters

Parameter Type Comment
symbol string Contract name
bid string Best bid price
bidIv string Implied volatility for best bid
bidSize string Bid quantity
ask string Best ask price
askIv string Implied volatility for best ask
askSize string Ask quantity
lastPrice string Last traded price
openInterest string Open interest
indexPrice string Index Price
markPrice string Mark Price
markPriceIv string Implied volatility for mark price
change24h string 24-hour change
high24h string 24-hour high
low24h string 24-hour low
volume24h string 24-hour trading volume
turnover24h string 24-hour turnover
totalVolume string Total trading volume
totalTurnover string Total turnover
fundingRate string Funding Rate API
predictedFundingRate string Est. funding rate
nextFundingTime string Next settlement time of capital cost
countdownHour string Countdown of settlement capital cost
predictedDeliveryPrice string Est. delivery price
underlyingPrice string Underlying price
delta string Delta value
gamma string Delta value
vega string Vega value
theta string Theta value

Query Kline

Request Example

curl 'https://api-testnet.bybit.com/perpetual/usdc/openapi/public/v1/kline/list?symbol=BTCPERP&period=1&limit=1&startTime=1

Response Example


{
  "retCode":0,
  "retMsg":"",
  "result":[
  {
    "symbol":"BTCPERP",
    "volume":"0.01",
    "period":"1",
    "openTime":"1636358160",
    "open":"66001.50",
    "high":"66001.50",
    "low":"66001.50",
    "close":"66001.50",
    "turnover":"1188.02"
  }
]
}

HTTP Request

GET /perpetual/usdc/openapi/public/v1/kline/list

Request Parameters

Parameter Required Type Comment
symbol true string Contract name
period true string

Data refresh frequency. Enum: 1 3 5 15 30 60 120 240 360 720 "D" "M" "W"

startTime true number Start time, unit in seconds
limit false number Number of data per page; the max. value is 200, and the default value is 200

Response Parameters

Parameter Type Comment
symbol string Contract name
volume string Trading volume
period string

Data refresh frequency. Enum: 1 3 5 15 30 60 120 240 360 720 "D" "M" "W"

openTime string Start time
open string Open price
high string 24-hour high
low string 24-hour low
close string 24-hour high
turnover string Turnover

Mark Price

Request Example

curl 'https://api-testnet.bybit.com/perpetual/usdc/openapi/public/v1/mark-price-kline?symbol=BTCPERP&period=1&limit=1&startTime=1'

Response Example


{
    "retCode":0,
    "retMsg":"",
    "result":[
        {
            "symbol":"BTCPERP",
            "period":"1",
            "openTime":"1634696220",
            "open":"63884.11",
            "high":"63884.11",
            "low":"63862.49",
            "close":"63866.63"
        }
    ]
}

HTTP Request

GET /perpetual/usdc/openapi/public/v1/mark-price-kline

Request Parameters

Parameter Required Type Comment
symbol true string Contract name
period true string

Data refresh frequency. Enum: 1 3 5 15 30 60 120 240 360 720 "D" "M" "W"

limit false string Number of data per page; the max. value is 200, and the default value is 200
startTime true number Start time, unit in seconds

Response Parameters

Parameter Type Comment
symbol string Contract name
period string

Data refresh frequency. Enum: 1 3 5 15 30 60 120 240 360 720 "D" "M" "W"

openTime number Start time
open string Open price
high string 24-hour high
low string 24-hour low
close string Close price

Index Price

Request Example

curl 'https://api-testnet.bybit.com/perpetual/usdc/openapi/public/v1/index-price-kline?symbol=BTCPERP&period=1&limit=1&startTime=1'

Response Example

{
    "retCode":0,
    "retMsg":"",
    "result":[
        {
            "symbol":"BTCPERP",
            "period":"W",
            "openTime":"1635120000",
            "open":"62033.96",
            "high":"62058.66",
            "low":"60005.97",
            "close":"61359.21"
        }
    ]
}

HTTP Request

GET /perpetual/usdc/openapi/public/v1/index-price-kline

Request Parameters

Parameter Required Type Comment
symbol true string Contract name
period true string

Data refresh frequency. Enum: 1 3 5 15 30 60 120 240 360 720 "D" "M" "W"

limit false string Number of data per page; the max. value is 200, and the default value is 200
startTime true number Start time, unit in seconds

Response Parameters

Parameter Type Comment
symbol string Contract name
period string

Data refresh frequency. Enum: 1 3 5 15 30 60 120 240 360 720 "D" "M" "W"

openTime string Start time
open string Open price
high string 24-hour high
low string 24-hour low
close string Close price

Index Premium

Request Example

curl 'https://api-testnet.bybit.com/perpetual/usdc/openapi/public/v1/premium-index-kline?symbol=BTCPERP&period=1&limit=1&startTime=1'

Response Example


{
    "retCode":0,
    "retMsg":"",
    "result":[
        {
            "symbol":"BTCPERP",
            "period":"1",
            "openTime":"1635648300",
            "open":"0.000066",
            "high":"0.000066",
            "low":"0.000066",
            "close":"0.000066"
        }
    ]
}

HTTP Request

GET /perpetual/usdc/openapi/public/v1/premium-index-kline

Request Parameters

Parameter Required Type Comment
symbol true string Contract name
period true string

Data refresh frequency. Enum: 1 3 5 15 30 60 120 240 360 720 "D" "M" "W"

limit false string Number of data per page; the max. value is 200, and the default value is 200
startTime true number Start time, unit in seconds

Response Parameters

Parameter Type Comment
symbol string Contract name
period string

Data refresh frequency. Enum: 1 3 5 15 30 60 120 240 360 720 "D" "M" "W"

openTime string Start time
open string Open price
high string 24-hour high
low string 24-hour low
close string Close price

Open Interest

Request Example

curl 'https://api-testnet.bybit.com/perpetual/usdc/openapi/public/v1/open-interest?symbol=BTCPERP&period=5min&limit=2'

Response Example


{
  "retCode": 0,
  "retMsg": "",
  "result": [
  {
    "symbol": "BTCPERP",
    "timestamp": "0",
    "openInterest": "11"
  },
  {
    "symbol": "BTCPERP",
    "timestamp": "1637922300",
    "openInterest": "185380200000"
  }
]
}

HTTP Request

GET /perpetual/usdc/openapi/public/v1/open-interest

Request Parameters

Parameter Required Type Comment
symbol true string Contract name
period true string Data refresh frequency. 5min, 15min, 30min, 1h, 4h, 1d
limit false string Number of data per page; the max value 200, and the default value is 50

Response Parameters

Parameter Type Comment
symbol string Contract name
timestamp string Timestamp, unit in milliseconds
openInterest string Open Interest

Large Orders

Request Example


curl 'https://api-testnet.bybit.com/perpetual/usdc/openapi/public/v1/big-deal?symbol=BTCPERP&limit=2'

Response Example


{
  "retCode": 0,
  "retMsg": "",
  "result": [
  {
    "symbol": "BTCPERP",
    "side": "Sell",
    "timestamp": "1638254956",
    "value": "1933941.70000000"
  },
  {
    "symbol": "BTCPERP",
    "side": "Sell",
    "timestamp": "1638254952",
    "value": "504610.00000000"
  }
]
}

HTTP Request

GET /perpetual/usdc/openapi/public/v1/big-deal

Request Parameters

Parameter Required Type Comment
symbol true string Contract name
limit false string Number of data returned; the max. value is 100, and the default value is 500

Response Parameters

Parameter Type Comment
symbol string Contract name
timestamp string Timestamp, unit in milliseconds
side string Direction
value string Order value

Long-Short Ratio

Request Example

curl 'https://api-testnet.bybit.com/perpetual/usdc/openapi/public/v1/account-ratio?symbol=BTCPERP&limit=2&period=1d'

Response Example

 {
  "retCode": 0,
    "retMsg": "",
    "result": [
    {
      "symbol": "BTCPERP",
      "buyRatio": 0.6131,
      "sellRatio": 0.3869,
      "timestamp": "1638230400"
    },
    {
      "symbol": "BTCPERP",
      "buyRatio": 0.5902,
      "sellRatio": 0.4098,
      "timestamp": "1638144000"
    }
  ]
}

HTTP Request

GET /perpetual/usdc/openapi/public/v1/account-ratio

Request Parameters

Parameter Required Type Comment
symbol true string Contract name
period true string Data refresh frequency. 5min, 15min, 30min, 1h, 4h, 1d
limit false string Number of data returned; the max. value is 500, and the default value is 50

Response Parameters

Parameter Type Comment
symbol string Contract name
buyRatio string Long position ratio
sellRatio string Short position ratio
timestamp string Timestamp, unit in milliseconds

Query Last 500 Trades

Request Example

curl 'https://api-testnet.bybit.com/option/usdc/openapi/public/v1/query-trade-latest?symbol=BTCPERP&limit=2&category=PERPETUAL' \

Response Example

{
    "result": {
        "resultTotalSize": 2,
        "dataList": [
            {
                "symbol": "BTCPERP",
                "orderQty": "0.157",
                "orderPrice": "22359.00",
                "time": "1655189065841"
            },
            {
                "symbol": "BTCPERP",
                "orderQty": "0.052",
                "orderPrice": "22340.00",
                "time": "1655189059840"
            }
        ]
    },
    "retCode": 0,
    "retMsg": "Success."
}

Returned records are Taker Buy in default.

HTTP Request

GET /option/usdc/openapi/public/v1/query-trade-latest

Request Parameters

Parameter Required Type Comment
category true string Type. PERPETUAL
symbol false string Contract name
limit false string default 500

Response Parameters

Parameter Type Comment
resultTotalSize number length of dataList
cursor string API pass-through
dataList list Return the result list, refer to the following fields
Parameter Type Comment
symbol string Contract name
orderQty string Order quantity
orderPrice string Order price
time string Timestamp, unit in milliseconds

Account Data Endpoints

The following account data endpoints require authentication.

Order API

Place Order

Request Example

curl https://api-testnet.bybit.com/perpetual/usdc/openapi/private/v1/place-order \
-H "Content-Type: application/json" \
-D '{
    "symbol": "BTCPERP",
    "orderType": "Market",
    "orderFilter": "Order",
    "side": "Sell",
    "orderQty": "0.002",
    "timeInForce": "GoodTillCancel",
    "orderLinkId": "usdcP10001",
    "reduceOnly": false,
    "closeOnTrigger": false,
    "takeProfit": "19600",
    "stopLoss": "23000"
}'

Response Example

{
    "retCode": 0,
    "retMsg": "",
    "result": {
        "orderId": "3710f92a-3f71-42c3-bc3c-253a81c190ef",
        "orderLinkId": "usdcP10001",
        "mmp": false,
        "symbol": "BTCPERP",
        "orderType": "Market",
        "side": "Sell",
        "orderQty": "0.00500000",
        "orderPrice": "20272.50",
        "iv": "0",
        "timeInForce": "ImmediateOrCancel",
        "orderStatus": "Created",
        "createdAt": "1655173222148884",
        "basePrice": "0.00",
        "triggerPrice": "0.00",
        "takeProfit": "19600.00",
        "stopLoss": "23000.00",
        "slTriggerBy": "MarkPrice",
        "tpTriggerBy": "MarkPrice"
    }
}

Place an order using the USDC Derivatives Account.

The request status can be queried in real-time.

The response parameters must be queried through a query or a WebSocket response.

HTTP Request

POST /perpetual/usdc/openapi/private/v1/place-order

Request Parameters

Parameter Required Type Comment
symbol true string Contract name
orderType true string Order Type
orderFilter true string refer to Order Filter
side true string Direction
orderPrice false string Order Price
orderQty true string Order quantity
timeInForce false string Time in force
orderLinkId false string Custom ID used for cross-platform strategy remarks; a max. of 32 characters
reduceOnly false bool Reduce-only
closeOnTrigger false bool Close on trigger, please set it to true for a close order
takeProfit false string Take-profit price (Perpetual)
stopLoss false string Stop-loss price (Perpetual)
tptriggerby false string Price type for take-profit triggering (Perpetual), Default MarkPrice
slTriggerBy false string Price type for stop-loss triggering (Perpetual), Default MarkPrice
basePrice false string When OrderFilter is StopOrder REQUIRED. It will be used to compare with the value of triggerPrice, to decide whether your stop order will be triggered by crossing trigger price from upper side or lower side. Mainly used to identify the expected direction of the current stop order.
triggerPrice false string Trigger price
triggerBy false string Trigger price type. Default MarkPrice
mmp false bool Market maker protection; false not enabled (default) and true means enabled.

Response Parameters

Parameter Type Comment
orderId string Order ID
orderLinkId string Custom ID used for cross-platform strategy remarks; a max. of 32 characters
mmp bool Market maker protection; false not enabled (default) and true means enabled.
symbol string Contract name
orderType string Order Type
side string Direction
orderQty string Order quantity
orderPrice string Order price
iv string Implied volatility
timeInForce string Time in force
orderStatus string Order status
createdAt string Creation time
basePrice string Market price during order placement
triggerPrice string Trigger price
takeProfit string Take-profit price (Perpetual)
stopLoss string Stop-loss price (Perpetual)
slTriggerBy string Price type for stop-loss triggering (Perpetual), Default MarkPrice
tpTriggerBy string Price type for take-profit triggering (Perpetual), Default MarkPrice

Modify Order

Active order parameters (such as quantity, price) and stop order parameters cannot be modified in one request at the same time. Please request modification separately.

curl https://api-testnet.bybit.com/perpetual/usdc/openapi/private/v1/replace-order \
-H "Content-Type: application/json" \
-D '{
{
    "symbol": "BTCPERP",
    "orderFilter": "StopOrder",
    "orderLinkId": "usdcP10002",
    "orderPrice": "20000",
    "orderQty": "0.002",
    "takeProfit": "17000",
    "stopLoss": "23000",
    "tptriggerby": "LastPrice",
    "slTriggerBy": "MarkPrice",
    "triggerPrice": "20900",
    "triggerBy": "MarkPrice"
}'



Response Example

{
    "retCode": 0,
    "retMsg": "",
    "result": {
        "orderId": "3727c054-ef45-4385-a5e6-0fa0b76ad5da",
        "orderLinkId": "usdcP10002",
        "createdAt": "1655177751954588",
        "updatedAt": "0",
        "symbol": "BTCPERP",
        "orderType": "UNKNOWN",
        "side": "None",
        "qty": "0.00200000",
        "price": "20000.00",
        "timeInForce": "UNKNOWN",
        "orderStatus": "UNKNOWN",
        "triggerPrice": "20900.00"
    }
}

HTTP Request

POST /perpetual/usdc/openapi/private/v1/replace-order

Request Parameters

Parameter Required Type Comment
symbol true string Contract name
orderFilter true string refer to Order Filter
orderId false string Order ID
orderLinkId false string Either orderId or orderLinkId is required
orderPrice false string Order price
orderQty false string Order quantity
takeProfit false string Take-profit price (Perpetual)
stopLoss false string Stop-loss price (Perpetual)
tptriggerby false string Price type for take-profit triggering (Perpetual), Default MarkPrice
slTriggerBy false string Price type for stop-loss triggering (Perpetual), Default MarkPrice
triggerPrice false string Trigger price

Response Parameters

Parameter Type Comment
orderId string Order ID
orderLinkId string Custom ID used for cross-platform strategy remarks; a max. of 32 characters
createdAt string Creation time
updatedAt string Update time
symbol string Contract name
orderType string Order Type
side string Direction
qty string Order quantity
price string Order price
timeInForce string Time in force
orderStatus string Order status
triggerPrice string Trigger price

Cancel Order

curl https://api-testnet.bybit.com/perpetual/usdc/openapi/private/v1/cancel-order \
-H "Content-Type: application/json" \
-D '
{
"symbol":"BTCPERP",
"orderLinkId":"",
"orderFilter":"Order",
"orderId":"752cff9a-6941-44d3-a405-bd297b1df4bc"
}
'


Response Example

{
  "retCode": 0,
    "retMsg": "",
    "result": {
    "orderId": "752cff9a-6941-44d3-a405-bd297b1df4bc"
  }
}

HTTP Request

POST /perpetual/usdc/openapi/private/v1/cancel-order

Request Parameters

Parameter Required Type Comment
symbol true string Contract name
orderFilter true string refer to Order Filter
orderId false string Order ID
orderLinkId false string Either orderId or orderLinkId is required

Response Parameters

Parameter Type Comment
orderId string Order ID

Cancel All Active Orders

curl https://api-testnet.bybit.com/perpetual/usdc/openapi/private/v1/cancel-order \
-H "Content-Type: application/json" \
-D '{
    "symbol": "BTCPERP",
    "orderFilter": "Order"
}'



Response Example

{
  "retCode": 0,
    "retMsg": ""
}

This is used to cancel all active orders. The real-time response indicates whether the request is successful, depending on retCode.

HTTP Request

POST /perpetual/usdc/openapi/private/v1/cancel-all

Request Parameters

Parameter Required Type Comment
symbol true string Contract name
orderFilter true string refer to Order Filter

Query Unfilled/Partially Filled Orders

curl https://api-testnet.bybit.com/option/usdc/openapi/private/v1/query-active-orders \
-H "Content-Type: application/json" \
-D '{
    "category": "PERPETUAL",
    "symbol": "BTCPERP"
}'


Response Example

{
  "result": {
    "cursor": "3dd0f4a4-b726-4921-9a23-723e0c0fdbd3%3A1640856463068%2C3dd0f4a4-b726-4921-9a23-723e0c0fdbd3%3A1640856463068",
      "resultTotalSize": 1,
      "dataList": [
      {
        "symbol": "BTCPERP",
        "orderType": "Limit",
        "orderLinkId": "",
        "orderId": "3dd0f4a4-b726-4921-9a23-723e0c0fdbd3",
        "stopOrderType": "UNKNOWN",
        "orderStatus": "New",
        "takeProfit": "0.0000",
        "cumExecValue": "0.0000",
        "createdAt": "1640856463065",
        "orderPnl": "-",
        "price": "38000.0",
        "tpTriggerBy": "UNKNOWN",
        "timeInForce": "GoodTillCancel",
        "basePrice": "",
        "side": "Buy",
        "triggerPrice": "0.0000",
        "cumExecFee": "0.0000",
        "leavesQty": "0.010",
        "slTriggerBy": "UNKNOWN",
        "iv": "",
        "closeOnTrigger": "UNKNOWN",
        "cumExecQty": "",
        "reduceOnly": 0,
        "qty": "0.010",
        "stopLoss": "0.0000",
        "lastExecPrice": "0.0",
        "triggerBy": "UNKNOWN",
        "orderIM": ""
      }
    ]
  },
  "retCode": 0,
    "retMsg": "Success."
}

HTTP Request

POST /option/usdc/openapi/private/v1/query-active-orders

Request Parameters

Parameter Required Type Comment
category true string Type. PERPETUAL
symbol false string Contract name
orderId false string Order ID
orderLinkId false string Custom ID used for cross-platform strategy remarks; a max. of 32 characters
orderFilter false string refer to Order Filter
direction false string

prev: prev page, next: next page.

limit false number Limit for data size per page, max size is 50. Default as showing 20 pieces of data per page
cursor false string API pass-through

Response Parameters

Parameter Type Comment
resultTotalSize number length of dataList
cursor string API pass-through
dataList list Return the result list, refer to the following fields
Parameter Type Comment
symbol string Contract name
orderType string Order Type
orderLinkId string Custom ID used for cross-platform strategy remarks; a max. of 32 characters
orderId string Order ID
stopOrderType string refer to Stop Order Type
orderStatus string Order status
takeProfit string Take-profit price (Perpetual)
cumExecValue string Total order value of filled orders
createdAt string Creation time
orderPnl string The total trade profit and loss for this order
price string Order price
tpTriggerBy string Price type for take-profit triggering (Perpetual), Default MarkPrice
timeInForce string Time in force
basePrice string Market price during order placement
side string Direction
triggerPrice string Trigger price
cumExecFee string Total trading fees
leavesQty string Unfilled quantity
slTriggerBy string Price type for stop-loss triggering (Perpetual), Default MarkPrice
iv string Implied volatility
closeOnTrigger string Close on trigger, please set it to true for a close order
cumExecQty string Total filled quantity
reduceOnly bool Reduce-only
qty string Order quantity
stopLoss string Stop-loss price (Perpetual)
lastExecPrice string Filled price
triggerBy string Trigger price type. Default MarkPrice
orderIM string Initial margin

Query Order History


curl https://api-testnet.bybit.com/option/usdc/openapi/private/v1/query-order-history \
-H "Content-Type: application/json" \
-D '{
    "category": "PERPETUAL",
    "limit":2
}'


Response Example

{
  "result": {
    "cursor": "640034d1-97ec-4382-9983-694898c03ba3%3A1640854950675%2C640034d1-97ec-4382-9983-694898c03ba3%3A1640854950675",
      "resultTotalSize": 1,
      "dataList": [
      {
        "symbol": "BTCPERP",
        "orderType": "Market",
        "orderLinkId": "",
        "orderId": "640034d1-97ec-4382-9983-694898c03ba3",
        "cancelType": "UNKNOWN",
        "stopOrderType": "UNKNOWN",
        "orderStatus": "Filled",
        "takeProfit": "0.0000",
        "createdAt": "1640854950672",
        "orderPnl": "-",
        "price": "49192.5",
        "tpTriggerBy": "UNKNOWN",
        "timeInForce": "ImmediateOrCancel",
        "updatedAt": "1640854950675",
        "basePrice": "",
        "realisedPnl": "0.0000",
        "side": "Buy",
        "triggerPrice": "0.0",
        "cumExecFee": "0.3514",
        "leavesQty": "0.000",
        "cashFlow": "",
        "slTriggerBy": "UNKNOWN",
        "iv": "",
        "closeOnTrigger": "UNKNOWN",
        "cumExecQty": "0.010",
        "reduceOnly": 0,
        "qty": "0.010",
        "stopLoss": "0.0000",
        "triggerBy": "UNKNOWN",
        "orderIM": ""
      }
    ]
  },
  "retCode": 0,
    "retMsg": "Success."
}

HTTP Request

POST /option/usdc/openapi/private/v1/query-order-history

Request Parameters

Parameter Required Type Comment
category true string Type. PERPETUAL
symbol false string Contract name
orderId false string Order ID
orderLinkId false string Custom ID used for cross-platform strategy remarks; a max. of 32 characters
orderStatus false string Order status
orderFilter false string refer to Order Filter
direction false string

prev: prev page, next: next page.

limit false number Limit for data size per page, max size is 50. Default as showing 20 pieces of data per page
cursor false string API pass-through

Response Parameters

Parameter Type Comment
resultTotalSize number length of dataList
cursor string API pass-through
dataList list Return the result list, refer to the following fields
Parameter Type Comment
symbol string Contract name
orderType string Order Type
orderLinkId string Custom ID used for cross-platform strategy remarks; a max. of 32 characters
orderId string Order ID
cancelType string Order cancelation
stopOrderType string refer to Stop Order Type
orderStatus string Order status
takeProfit string Take-profit price (Perpetual)
createdAt string Creation time
orderPnl string The total trade profit and loss for this order
price string Order price
tpTriggerBy string Price type for take-profit triggering (Perpetual), Default MarkPrice
timeInForce string Time in force
updatedAt string Update time
basePrice string Market price during order placement
realisedPnl string Closed P&L
side string Direction
triggerPrice string Trigger price
cumExecFee string Total trading fees
leavesQty string Unfilled quantity
cashFlow string Cash flow
slTriggerBy string Price type for stop-loss triggering (Perpetual), Default MarkPrice
iv string Implied volatility
closeOnTrigger string Close on trigger, please set it to true for a close order
cumExecQty string Total filled quantity
reduceOnly bool Reduce-only
qty string Order quantity
stopLoss string Stop-loss price (Perpetual)
triggerBy string Trigger price type. Default MarkPrice
orderIM string Initial margin

Trade History

Request Example

curl https://api-testnet.bybit.com/option/usdc/openapi/private/v1/execution-list \
-H "Content-Type: application/json" \
-D '{
    "category": "PERPETUAL",
    "limit": 1
}'

Response Example

{
  "result": {
    "cursor": "52%3A1%2C52%3A1",
      "resultTotalSize": 1,
      "dataList": [
      {
        "symbol": "BTCPERP",
        "tradeTime": "1640854950675",
        "orderLinkId": "",
        "side": "Buy",
        "orderId": "640034d1-97ec-4382-9983-694898c03ba3",
        "execPrice": "46851.50",
        "lastLiquidityInd": "TAKER",
        "execValue": "468.5150",
        "execType": "TRADE",
        "execQty": "0.010",
        "execFee": "0.3514",
        "feeRate": "0.000750",
        "tradeId": "22f7e871-e11b-50f0-aa6f-40dc52f57322"
      }
    ]
  },
  "retCode": 0,
    "retMsg": "Success."
}

HTTP Request

POST /option/usdc/openapi/private/v1/execution-list

Request Parameters

Parameter Required Type Comment
category true string Type. PERPETUAL
symbol false string Contract name
orderId false string Order ID
orderLinkId false string Either orderId or orderLinkId is required
startTime false string Start time, unit in milliseconds
direction false string

prev: prev page, next: next page.

limit false string Limit for data size per page, max size is 50. Default as showing 20 pieces of data per page
cursor false string API pass-through

Response Parameters

Parameter Type Comment
resultTotalSize number length of dataList
cursor string API pass-through
dataList list Return the result list, refer to the following fields
Parameter Type Comment
symbol string Contract name
tradeTime number Timestamp, unit in milliseconds
orderLinkId string Custom ID used for cross-platform strategy remarks; a max. of 32 characters
side string Direction
orderId string Order ID
execPrice string Filled price
lastLiquidityInd string Liquidity
execValue string Position value
execType string Execution type
execQty string Positions
execFee string Trading fees
feeRate string Taker or maker fee rate
tradeId string Transaction ID

Account API

The following wallet data endpoints require authentication.

Transaction Log

Request Example

curl https://api-testnet.bybit.com/option/usdc/openapi/private/v1/query-transaction-log \
-H "Content-Type: application/json" \
-D '{
    "type": "TRADE",
    "limit": 1
}'

Response Example

{
  "retCode": 0,
    "retMsg": "Success.",
    "result": {
    "resultTotalSize": 1,
      "cursor": "289037_BTCPERP_1176501331%3A1638341411994%3A9806%2C289037_BTCPERP_1176501331%3A1638341411994%3A9806",
      "dataList": [
      {
        "transactionTime": "1638341411994",
        "symbol": "BTCPERP",
        "type": "TRADE",
        "side": "Buy",
        "tradePrice": "57168.5",
        "funding": "0.0000",
        "qty": "0.020",
        "size": "1.150",
        "fee": "0.8576",
        "cashFlow": "-",
        "change": "-0.8575",
        "walletBalance": "24080.5708",
        "feeRate": "0.0008",
        "orderId": "61f22ac5-6774-46e6-9697-fc3f2621ee09",
        "orderLinkId": "",
        "tradeId": "14c7eb47-15e7-565a-b622-9633d09a5389",
        "info": ""
      }
    ]
  }
}

HTTP Request

POST /option/usdc/openapi/private/v1/query-transaction-log

Request Parameters

Parameter Required Type Comment
type true string refer to Transaction type
startTime false string Start time, unit in milliseconds
endTime false string End time, unit in milliseconds
direction false string

prev: prev page, next: next page.

limit false string Limit for data size per page, max size is 50. Default as showing 20 pieces of data per page
cursor false string API pass-through
category false string Type. OPTION or PERPETUAL

Response Parameters

Parameter Type Comment
resultTotalSize number length of dataList
cursor string API pass-through
dataList list Return the result list, refer to the following fields
Parameter Type Comment
transactionTime string Timestamp, unit in milliseconds
symbol string Contract name
type string Default value is all
side string Direction
tradePrice string Filled price
funding string Funding fees
qty string Order quantity
size string Positions
fee string Trading fees
cashFlow string Cash flow
change string Change
walletBalance string Cash balance
feeRate string Taker or maker fee rate
orderId string Order ID
orderLinkId string Custom ID used for cross-platform strategy remarks; a max. of 32 characters
tradeId string Transaction ID
info string Symbol info of liquidated assets under Portfolio Margin

Wallet Info

For USDC Account.

Request Example

curl https://api-testnet.bybit.com/option/usdc/openapi/private/v1/query-wallet-balance \


Response Example

{
    "result": {
        "walletBalance": "999.6758",
        "accountMM": "0.3728",
        "bonus": "0.0000",
        "accountIM": "6.4519",
        "totalSessionRPL": "-0.2120",
        "equity": "995.2654",
        "totalRPL": "-0.2120",
        "marginBalance": "995.2654",
        "availableBalance": "988.8135",
        "totalSessionUPL": "-4.4104"
    },
    "retCode": 0,
    "retMsg": "Success."
}

HTTP Request

POST /option/usdc/openapi/private/v1/query-wallet-balance

Response Parameters

Parameter Type Comment
walletBalance string Cash balance
accountMM string Maintenance margin
bonus string Bonus
accountIM string Initial margin
totalSessionRPL string Session RPL
equity string Equity
totalRPL string Total RPL
marginBalance string Margin balance
availableBalance string Available balance
totalSessionUPL string Session UPL

Asset Info

Request Example

curl https://api-testnet.bybit.com/option/usdc/openapi/private/v1/query-asset-info \
-H "Content-Type: application/json" \
-D '{"baseCoin":"BTC"}'

Response Example

{
  "retCode":0,
    "retMsg":"OK",
    "result":{
    "resultTotalSize":1,
      "dataList":[
      {
        "baseCoin":"BTC",
        "totalDelta":"-0.1093",
        "totalGamma":"0.00000",
        "totalVega":"1.8799",
        "totalTheta":"-19.2038",
        "totalRPL":"-3773.8879",
        "sessionUPL":"-16.0781",
        "sessionRPL":"-13.0000",
        "im":"28940.8205",
        "mm":"14997.4532"
      }
    ]
  }
}

HTTP Request

POST /option/usdc/openapi/private/v1/query-asset-info

Request Parameters

Parameter Required Type Comment
baseCoin false string Base currency

Response Parameters

Parameter Type Comment
resultTotalSize int length of dataList
dataList list Return the result list, refer to the following fields
Parameter Type Comment
baseCoin string Base currency
totalDelta string Total delta
totalGamma string Total gamma
totalVega string Total vega
totalTheta string Total theta
totalRpl string Total RPL
sessionUpl string Session UPL
sessionRpl string Session RPL
im string Initial margin
mm string Maintenance margin

Query Margin Mode

For USDC ACCOUNT.

Request Example


curl https://api-testnet.bybit.com/option/usdc/openapi/private/v1/query-margin-info \


Response Example

{
  "retCode":0,
    "retMsg":"OK",
    "result":{
    "marginMode":"REGULAR_MARGIN"
  }
}

HTTP Request

POST /option/usdc/openapi/private/v1/query-margin-info

Request Parameters

Parameter Required Type Comment

Response Parameters

Parameter Type Comment
marginMode string Margin mode Margin Mode

Positions API

Query My Positions

Request Example

curl https://api-testnet.bybit.com/option/usdc/openapi/private/v1/query-position \
-H "Content-Type: application/json" \
-D '{
    "category": "PERPETUAL"
}'

Response Example

{
    "result": {
        "cursor": "BTCPERP%3A1655184421732%2CBTCPERP%3A1655184421732",
        "resultTotalSize": 1,
        "dataList": [
            {
                "symbol": "BTCPERP",
                "leverage": "10.00",
                "occClosingFee": "0.0000",
                "liqPrice": "",
                "positionValue": "22.9450",
                "takeProfit": "25000.0",
                "riskId": "10001",
                "trailingStop": "0.0000",
                "unrealisedPnl": "0.0000",
                "createdAt": "1655184421732",
                "markPrice": "22912.41",
                "cumRealisedPnl": "0.0000",
                "positionMM": "0.1302",
                "positionIM": "2.3100",
                "updatedAt": "1655184421732",
                "tpSLMode": "UNKNOWN",
                "side": "Buy",
                "bustPrice": "",
                "deleverageIndicator": 0,
                "entryPrice": "22945.0",
                "size": "0.001",
                "sessionRPL": "-5.3255",
                "positionStatus": "NORMAL",
                "sessionUPL": "-0.0326",
                "stopLoss": "19000.0",
                "orderMargin": "0.0000",
                "sessionAvgPrice": "22945.0"
            }
        ]
    },
    "retCode": 0,
    "retMsg": "Success."
}

HTTP Request

POST /option/usdc/openapi/private/v1/query-position

Request Parameters

Parameter Required Type Comment
category true string Type. PERPETUAL
symbol false string Contract name
cursor false string API pass-through
direction false string

prev: prev page, next: next page.

limit number string Number of data per page; the max. value is 50, and the default value is 20

Response Parameters

Parameter Type Comment
resultTotalSize number length of dataList
cursor string API pass-through
dataList list Return the result list, refer to the following fields
Parameter Type Comment
symbol string Contract name
leverage string Contract name
occClosingFee string Position closing fees
liqPrice string Liquidation price
positionValue string Position value
takeProfit string Take-profit price
riskId string riskId
trailingStop string Trailing stop
unrealisedPnl string unrealised pnl
createdAt string Creation time
markPrice string Mark Price
cumRealisedPnl string Accumulated realised pnl (all-time total)
positionMM string Maintenance margin
positionIM string Initial margin
updatedAt string Update time
tpSLMode string TP/SL settings
side string Direction
bustPrice string Bankruptcy price
deleverageIndicator integer ADL indicators; can be 1,2,3,4,5
entryPrice string Avg. entry price
size string Positions
sessionRPL string Session RPL
positionStatus string Position status; can be normal, liquidating, and auto deleveraging
sessionUPL string Session UPL
stopLoss string Stop-loss price (Perpetual)
orderMargin string Pre-occupied order margin
sessionAvgPrice string Settlement price

Set Leverage

Only for REGULAR_MARGIN.

Request Example


curl https://api-testnet.bybit.com/perpetual/usdc/openapi/private/v1/position/leverage/save \
-H "Content-Type: application/json" \
-d '{
    "symbol": "BTCPERP",
    "leverage": "1"
}'

import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.Positions.Positions_saveLeverage(symbol="BTCUSD", leverage="14").result())

Response Example

{
    "retCode": 0,
    "retMsg": "",
    "extCode": null,
    "extInfo": null,
    "result": {
        "leverage": 1
    }
}

HTTP Request

POST /perpetual/usdc/openapi/private/v1/position/leverage/save

Request Parameters

Parameter Required Type Comment
symbol true string Contract name
leverage true string Must be greater than zero and less than the max. leverage allowed

Response Parameters

Parameter Type Comment
leverage number Leverage

Query Settlement History

Request Example

curl https://api-testnet.bybit.com/option/usdc/openapi/private/v1/session-settlement \
-H "Content-Type: application/json" \
-d '{"symbol":"BTCPERP"}'


Response Example

{
    "retCode": 0,
    "retMsg": "Success.",
    "result": {
        "resultTotalSize": 20,
        "cursor": "4327:0,4286:0",
        "dataList": [
            {
                "time": "1650240000000",
                "symbol": "BTCPERP",
                "side": "Buy",
                "size": "0.001",
                "sessionAvgPrice": "39685.53",
                "markPrice": "39686.28",
                "sessionRpl": "-0.7730"
            }
        ]
    }
}

HTTP Request

POST /option/usdc/openapi/private/v1/session-settlement

Request Parameters

Parameter Required Type Comment
symbol true string Contract name
direction false string

prev: prev page, next: next page.

limit false number Number of data per page; the max. value is 50, and the default value is 20
cursor false string API pass-through

Response Parameters

Parameter Type Comment
resultTotalSize number length of dataList
cursor string API pass-through
dataList list Return the result list, refer to the following fields
Parameter Type Comment
time string Settlement time, unit in milliseconds
symbol string Contract name
side string Direction
size string size
sessionAvgPrice string Settlement price
markPrice string Mark Price
sessionRpl string Session RPL

Risk Limit API

Query Risk Limit

Request Example

curl https://api-testnet.bybit.com/perpetual/usdc/openapi/public/v1/risk-limit/list \
-H "Content-Type: application/json" \
-d '{"symbol":"BTCPERP"}'

Response Example

{
    "retCode": 0,
    "retMsg": "",
    "result": [
        {
            "riskId": "10001",
            "symbol": "BTCPERP",
            "limit": "1000000",
            "startingMargin": "0.0100",
            "maintainMargin": "0.0050",
            "isLowestRisk": true,
            "section": [
                "1",
                "2",
                "3",
                "5",
                "10",
                "25",
                "50",
                "100"
            ],
            "maxLeverage": "100.00"
        }
}

HTTP Request

GET /perpetual/usdc/openapi/public/v1/risk-limit/list

Request Parameters

Parameter Required Type Comment
symbol true string Contract name

Response Parameters

Parameter Type Comment
symbol string Contract name
riskId string Risk ID
limit string Risk Limit
maintainMargin string Maintenance margin
startingMargin string Initial margin
section string Interval
isLowestRisk string Whether it's the lowest risk limit; 0 indicates no and 1 means yes
maxLeverage string Max. leverage

Set Risk Limit

Request Example

curl https://api-testnet.bybit.com/perpetual/usdc/openapi/private/v1/position/set-risk-limit \
-H "Content-Type: application/json" \
-d '{"symbol":"BTCPERP","riskId":2}'


Response Example

{
    "retCode": 0,
    "retMsg": "OK",
    "result": {
        "riskId": 2
  }
}

HTTP Request

POST /perpetual/usdc/openapi/private/v1/position/set-risk-limit

Request Parameters

Parameter Required Type Comment
symbol true string Contract name
riskId true number Risk ID

Response Parameters

Parameter Type Comment
riskId number Risk ID

Funding API

Get the Last Funding Rate

Request Example

curl https://api-testnet.bybit.com/perpetual/usdc/openapi/public/v1/prev-funding-rate?symbol=BTCPERP \


Response Example

{
    "retCode": 0,
    "retMsg": "",
    "result": {
        "symbol": "BTCPERP",
        "fundingRate": "0.00010000",
        "fundingRateTimestamp": "1652313600000"
    }
}

Funding settlement occurs every 8 hours at 00:00 UTC, 08:00 UTC and 16:00 UTC. The current interval's fund fee settlement is based on the previous interval's fund rate. For example, at 16:00, the settlement is based on the fund rate generated at 8:00. The fund rate generated at 16:00 will be used at 0:00 the next day.

HTTP Request

GET /perpetual/usdc/openapi/public/v1/prev-funding-rate

Request Parameters

Parameter Required Type Comment
symbol true string Contract name

Response Parameters

Parameter Type Comment
symbol string Contract name
fundingRate string Funding rate
fundingRateTimestamp string Transaction time

Predicted Funding Rate and My Funding Fee

Request Example

curl https://api-testnet.bybit.com/perpetual/usdc/openapi/private/v1/predicted-funding \
-H "Content-Type: application/json" \
-d '{"symbol":"BTCPERP"}'


Response Example

{
    "result": {
        "predictedFundingRate": "0.00010",
        "predictedFundingFee": "29.0848836700"
    },
    "retCode": 0,
    "retMsg": "success"
}

Get predicted funding rate and my predicted funding fee.

HTTP Request

POST /perpetual/usdc/openapi/private/v1/predicted-funding

Request Parameters

Parameter Required Type Comment
symbol true string Contract name

Response Parameters

Parameter Type Comment
predictedFundingRate string Predicted funding rate
predictedFundingFee string Predicted funding fee

API Data Endpoints

The following API data endpoints do not require authentication.

Server Time

Request Example


curl https://api-testnet.bybit.com/v2/public/time

Response Example

{
    "ret_code": 0,
    "ret_msg": "OK",
    "ext_code": "",
    "ext_info": "",
    "result": {},
    "time_now": "1637635413.927628"
}

Get Bybit server time.

HTTP Request

GET /v2/public/time

Request Parameters

Parameter Required Type Comment

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.

This table shows how there are different IP rate limit counters depending on the API you are using.

IP rate limit API Path
2mins 50/s;
5s 70/s
Inverse Perpetual/v2
Inverse Futures/futures
Linear Perpetual/public, /private
Account Asset/asset
2mins 50/s;
5s 70/s
Spot/spot
2mins 50/s;
5s 70/s
USDC Options/option
USDC Perpetual/perpetual

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
1 requests/second /perpetual/usdc/openapi/private/v1/cancel-all
5 requests/second All other private endpoints

The rate limits for each private endpoint should be considered separately.

WebSocket Data

Authentication

Send auth request for authentication after establishing a connection.

import hmac
import websocket
import threading
import time
import json

def on_message(ws, message):
    print(json.loads(message))

def on_error(ws, error):
    print('we got error')
    print(error)

def on_close(ws):
    print("### about to close please don't close ###")

def send_auth(ws):
    api_key = 'XXXXXXXXXXXXXXX'
    secret = 'XXXXXXXXXXXXXXX'
    expires = int((time.time() + 10) * 1000)
    _val = f'GET/realtime{expires}'
    print(_val)
    signature = str(hmac.new(
        bytes(secret, 'utf-8'),
        bytes(_val, 'utf-8'), digestmod='sha256'
    ).hexdigest())

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

def on_open(ws):
    print('opened')
    send_auth(ws)
    def pingPer(ws):
        while True:
            ws.send(
              json.dumps({
              "op": "ping",
              "args": ["946656000000"]
              })
            )
            time.sleep(25)
    t1 = threading.Thread(target=pingPer, args=(ws,))
    t1.start()
    ws.send(
      json.dumps({
        "op": "subscribe", "id": "{100003}",
        "args": ["user.openapi.perp.order", "user.openapi.perp.position", "user.openapi.perp.trade"]
      })
    )

def connWS():
    ws = websocket.WebSocketApp("wss://stream-testnet.bybit.com/trade/option/usdc/private/v1",
                                on_message=on_message,
                                on_error=on_error,
                                on_close=on_close,
                                on_open=on_open
                                )
    ws.run_forever()

if __name__ == "__main__":
    connWS()

Base endpoints:

How to Send Heartbeat Packet

How to Send

ws.send('{"op":"ping","args":["1535975085152"]}');

Response Example

{"op":"pong","args":["1535975085152"]}

The client needs to periodically send a "ping" to Bybit, and the Bybit server returns a heartbeat "pong" to show that the connection between the client and the server is normal. It is recommended to send at least every 20s. WSS will actively trigger to break the connection without heartbeat "ping" received in 30s.

If the client does not receive the heartbeat feedback normally, it needs to check the network connection status and reconnect to the server.

Disconnection Protection

Based on the heartbeat mechanism, Bybit provides disconnection protection function. If you need to turn it on/off, you can contact your client manager for consultation and application.

The timing starts from the first disconnection. If the Bybit server does not receive the reconnection from the client for more than 3 minutes and resumes the heartbeat "ping", and the client is in the state of "disconnection protection", all the active orders of the client will be canceled all automatically.

If within 3 minutes, the client reconnects and resumes the heartbeat "ping", the timing will be reset and restarted at the next disconnection.

How to Subscribe to Topics

Understanding Websocket Filters

How to subscribe with a filter

Subscribing:

ws.send('{"op":"subscribe","id":"{uuid}","args":["topic1","topic2"]}');

Response:

{"id":"{uuid}","success":true,"conn_id":{conn_id},"data":{"successTopics":["topic1"],"failTopics":["topic2"]},"type":"COMMAND_RESP"}

// Subscribing to the trade data for BTCUSDT

Understanding Websocket Filters unsubscription

Remove WebSocket Topic Subscriptions

ws.send('{"op":"unsubscribe","id":"{uuid}","args":["topic1","topic2"]}')

Response:

{"id":"{uuid}","success":true,"conn_id":{conn_id},"data":{"successTopics":["topic1"],"failTopics":["topic2"]},"type":"COMMAND_RESP"}

Remove All WebSocket Topic Subscriptions

{"op":"unSubAll","id":"{uuid}"}

Response:

{"id":"{uuid}","success":true,"conn_id":{conn_id},"type":"COMMAND_RESP"}

Understanding Subscription Response

Subscription Response


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

Public Topics

orderBookL2

How to Subscribe

  ws.send('{"op": "subscribe", "args": ["orderBook_200.100ms.BTCPERP"]}');

Snapshot Response Example - format of the first response


{
  "topic":"orderBookL2_25.BTCPERP",
  "type":"snapshot",
  "data":{
  "orderBook":[
    {
      "price":"56347.50",
      "symbol":"BTCPERP",
      "id":"563475000",
      "side":"Buy",
      "size":4.512
    },
    {
      "price":"56805.50",
      "symbol":"BTCPERP",
      "id":"568055000",
      "side":"Sell",
      "size":1.035
    }
  ]
},
  "crossSeq":"122458406",
  "timestampE6":"1638426051379488"
}

Delta Response Example - format of the responses following the snapshot response

{
    "topic":"orderBookL2_25.BTCPERP",
    "type":"delta",
    "data":{
        "delete":[
            {
                "price":"56810.00",
                "symbol":"BTCPERP",
                "id":"568100000",
                "side":"Sell"
            }
        ],
        "update":[
            {
                "price":"56758.50",
                "symbol":"BTCPERP",
                "id":"567585000",
                "side":"Buy",
                "size":2.429
            }
        ],
        "insert":[
            {
                "price":"56347.00",
                "symbol":"BTCPERP",
                "id":"563470000",
                "side":"Buy",
                "size":0.485
            }
        ]
    },
    "crossSeq":"122458433",
    "timestampE6":"1638426051822077"
}

Either 25 or 200 orders will be fetched from the bid and ask side of the order book.

After a successful subscription, the first response will be a snapshot data, then provide the delta data

topic format: orderBookL2_25.{symbol} or orderBook_200.100ms.{symbol}

orderBookL2_25.BTCPERP or orderBook_200.100ms.BTCPERP

Response Parameters

Parameter Type Comment
price string Order price
symbol string Contract name
side string Side
size number Position qty

trade

How to Subscribe

  ws.send('{"op": "subscribe", "args": ["trade.BTCPERP"]}');

Snapshot Response Example - format of response


{
  "topic":"trade.BTCPERP",
  "data":[
  {
    "symbol":"BTCPERP",
    "tickDirection":"MinusTick",
    "price":"56689.00",
    "size":0.15,
    "timestamp":"2021-12-02T06:37:25.000Z",
    "tradeTimeMs":"1638427045643",
    "side":"Sell",
    "tradeId":"bac9d230-e553-59c4-a22e-ca2dcca1467e"
  }
]
}

Fetch the transaction data on Bybit in the last 24 hours.

topic format: trade.{symbol}

trade.BTCPERP

Response Parameters

Parameter Type Comment
symbol string Contract name
tickDirection string Direction of price change
price string Transaction price
size string Position qty
timestamp string timestamp
tradeTimeMs string Timestamp, unit in milliseconds
side string Direction of taker
tradeId string Transaction ID

instrumentInfo

How to Subscribe

ws.send('{"op": "subscribe", "args": ["instrument_info.100ms.BTCPERP"]}');

Snapshot Response Example - format of the first response


{
  "topic":"instrument_info.100ms.BTCPERP",
  "type":"snapshot",
  "data":{
  "id":1,
    "symbol":"BTCPERP",
    "lastPriceE4":"566055000",
    "lastPrice":"56605.50",
    "lastTickDirection":"PlusTick",
    "prevPrice24hE4":"570275000",
    "prevPrice24h":"57027.50",
    "price24hPcntE6":"-7399",
    "highPrice24hE4":"592375000",
    "highPrice24h":"59237.50",
    "lowPrice24hE4":"556675000",
    "lowPrice24h":"55667.50",
    "prevPrice1hE4":"569910000",
    "prevPrice1h":"56991.00",
    "price1hPcntE6":"-6764",
    "markPriceE4":"565270100",
    "markPrice":"56527.01",
    "indexPriceE4":"565262500",
    "indexPrice":"56526.25",
    "openInterestE8":"58513199999",
    "totalTurnoverE8":"663673580321250000",
    "turnover24hE8":"38217656797550020",
    "totalVolumeE8":"11089424900000",
    "volume24hE8":"665962700000",
    "fundingRateE6":"100",
    "predictedFundingRateE6":"100",
    "crossSeq":"122534036",
    "createdAt":"1970-01-01T00:00:00.000Z",
    "updatedAt":"2021-12-02T06:43:16.000Z",
    "nextFundingTime":"2021-12-02T08:00:00Z",
    "countDownHour":"2",
    "bid1PriceE4":"565635000",
    "bid1Price":"56563.50",
    "ask1PriceE4":"566055000",
    "ask1Price":"56605.50"
},
  "crossSeq":"122534100",
  "timestampE6":"1638427403846982"
}

Delta Response Example - format of the responses following the snapshot response


{
    "topic":"instrument_info.100ms.BTCPERP",
    "type":"delta",
    "data":{
        "update":[
            {
                "id":1,
                "symbol":"BTCPERP",
                "markPriceE4":"567607800",
                "markPrice":"56760.78",
                "indexPriceE4":"567615500",
                "indexPrice":"56761.55",
                "crossSeq":"122596005",
                "createdAt":"1970-01-01T00:00:00.000Z",
                "updatedAt":"2021-12-02T07:10:41.000Z"
            }
        ]
    },
    "crossSeq":"122596143",
    "timestampE6":"1638429048145806"
}

topic format: instrument_info.100ms.{symbol}

instrument_info.100ms.BTCPERP

Response Parameters

Parameter Type Comment
symbol string Symbol
lastPriceE4 string (Deprecated) Latest transaction price 10^4
lastPrice string Latest transaction price
lastTickDirection string Direction of price change
prevPrice24hE4 string (Deprecated) Price of 24 hours ago * 10^4
prevPrice24h string Price of 24 hours ago
price24hPcntE6 string Percentage change of market price relative to 24 hour ago * 10^6
highPrice24hE4 string (Deprecated) The highest price in the last 24 hours * 10^4
highPrice24h string The highest price in the last 24 hours
lowPrice24hE4 string (Deprecated) Lowest price in the last 24 hours * 10^4
lowPrice24h string Lowest price in the last 24 hours
prevPrice1hE4 string (Deprecated) Hourly market price an hour ago * 10^4
prevPrice1h string Hourly market price an hour ago
price1hPcntE6 string Percentage change of market price relative to 1 hour ago * 10^6
markPriceE4 string (Deprecated) Mark price * 10^4
markPrice string Mark price
indexPriceE4 string (Deprecated) Index_price * 10^4
indexPrice string Index_price
openInterestE8 string Open interest * 10^8. The update is not immediate - slowest update is 1 minute
totalTurnoverE8 string Total turnover * 10^8
turnover24hE8 string Turnover for 24h * 10^8
totalVolumeE8 string Total volume * 10^8
volume24hE8 string Trading volume in the last 24 hours * 10^8
fundingRateE6 string Funding rate * 10^8
predictedFundingRateE6 string Predicted funding rate * 10^6
crossSeq string Cross sequence (internal value)
createdAt string Creation time (when the order_status was Created)
updatedAt string Update time
nextFundingTime string Next settlement time of capital cost
countDownHour string Countdown of settlement capital cost
bid1PriceE4 string (Deprecated) Best bid price * 10^4
bid1Price string Best bid price
ask1PriceE4 string (Deprecated) Best ask price * 10^4
ask1Price string Best ask price

kline

How to Subscribe

ws.send('{"op":"subscribe","args":["candle.1.BTCPERP"]}')

Response Example - format of all responses


{
    "topic":"candle.1.BTCPERP",
    "data":[
        {
            "start":1638429120,
            "end":1638429180,
            "period":"1",
            "open":56823.5,
            "close":56806,
            "high":56855.5,
            "low":56791,
            "volume":2.817,
            "turnover":160070.652,
            "confirm":false,
            "crossSeq":122599728,
            "timestamp":1638429160388749
        }
    ],
    "timestampE6":1638429160388752
}

Currently supported intervals:

Push frequency: 1-60s

Response Parameters

Parameter Type Comment
start string Start time, unit in seconds
end string End time, unit in seconds
open string Open price
close string Close price
high string 24-hour high
low string 24-hour low
volume string 24-hour trading volume
turnover string 24-hour turnover
confirm string Confirmed or not
crossSeq string Cross sequence (internal value)
timestamp string Timestamp, unit in milliseconds

Private Topics

position

How to Subscribe

ws.send(json.dumps({"op": "subscribe", "id": "{100003}","args": ["user.openapi.perp.position"]}));

Snapshot Response Example - format of response

{
    "id":"7b8fdb38-1cfa-40f6-8010-f2ab3eb33df4",
    "topic":"user.openapi.perp.position",
    "creationTime":1646200751865,
    "data":{
        "result":[

        ],
        "version":1,
        "baseLine":1,
        "dataType":"NEW"
    }
}

Delta Response Example - format of the responses following the snapshot response

{
    "id":"9cf9e9a8-2f19-4252-a2b6-1fd733a8bee2",
    "topic":"user.openapi.perp.position",
    "creationTime":1646200779801,
    "data":{
        "result":[
            {
                "symbol":"BTCPERP",
                "positionStatus":"NORMAL",
                "side":"Buy",
                "size":"0.001",
                "entryPrice":"44277",
                "sessionAvgPrice":"44277",
                "markPrice":"44285.75",
                "positionIM":"4.457586975",
                "positionMM":"0.251271975",
                "positionValue":"44.277",
                "liqPrice":"",
                "bustPrice":"",
                "occClosingFee":"",
                "unrealisedPnl":"0.0000",
                "cumRealisedPnl":"0.0000",
                "sessionUPL":"0.00875",
                "sessionRPL":"0",
                "createdAt":1646200779751,
                "updatedAt":1646200779751,
                "tpSLMode":"UNKNOWN",
                "leverage":1000,
                "trailingStop":"",
                "takeProfit":"0",
                "stopLoss":"0",
                "deleverageIndicator":0,
                "riskId":"10001"
            }
        ],
        "version":2,
        "baseLine":1,
        "dataType":"CHANGE"
    }
}

topic:

user.openapi.perp.position

Response Parameters

Parameter Type Comment
symbol string Contract name
positionStatus string Position status; can be normal, liquidating, and auto deleveraging
side string Direction
size string size
entryPrice string Avg. entry price
sessionAvgPrice string Average entry price during session
markPrice string Mark Price
positionIM string Initial margin
positionMM string Maintenance margin
positionValue string Position value
liqPrice string Liquidation price
bustPrice string Bankruptcy price
occClosingFee string Position closing fees
unrealisedPnl string unrealised pnl
cumRealisedPnl string Accumulated realised pnl (all-time total)
sessionUPL string Session UPL
sessionRPL string Session RPL
createdAt string Creation time (when the order_status was Created)
updatedAt string Update time
tpSlMode string TP/SL settings
leverage string Must be greater than zero and less than the max. leverage allowed
trailingStop number Trailing stop
takeProfit string Take-profit price
stopLoss string Stop-loss price (Perpetual)
deleverageIndicator string ADL indicators; can be 1,2,3,4,5
riskId string Risk ID

execution

How to Subscribe

ws.send(json.dumps({"op": "subscribe", "id": "{100003}","args": ["user.openapi.perp.trade"]}))

Snapshot Response Example - format of response

{
    "id":"6ffe5750-d3b6-4de8-b63a-736a59aa8278",
    "topic":"user.openapi.perp.trade",
    "creationTime":1646200779785,
    "data":{
        "result":[
            {
                "orderId":"2a44a4de-8244-4be9-b343-52bdfe135c9e",
                "orderLinkId":"",
                "tradeId":"9ae8aad2-0dae-583f-bff1-89aef6f88cd2",
                "symbol":"BTCPERP",
                "side": "Buy",
                "execPrice":"44277",
                "execQty":"0.001",
                "execFee":"0.03320775",
                "feeRate":"0.00075",
                "tradeTime":1646200779736,
                "lastLiquidityInd":"TAKER",
                "execValue":"44.277",
                "execType":"TRADE"
            }
        ],
        "version":1,
        "baseLine":1
    }
}

topic:

user.openapi.perp.trade

Response Parameters

Parameter Type Comment
orderId string Order ID
orderLinkId string Custom ID used for cross-platform strategy remarks; a max. of 32 characters
tradeId string Transaction ID
symbol string Contract name
side string Direction
execPrice string Filled price
execQty string Filled quantity
execFee string Trading fees
feeRate string Taker or maker fee rate
tradeTime number Timestamp, unit in milliseconds
lastLiquidityInd string Liquidity
execValue string order value of filled orders
execType string Execution type

order

How to Subscribe

ws.send(json.dumps({"op": "subscribe", "id": "{100003}","args": ["user.openapi.perp.order"]}))

Snapshot Response Example - format of response

{
    "id":"c044cbae-8331-4a2e-93c9-5114ab4815cf",
    "topic":"user.openapi.perp.order",
    "creationTime":1646200751861,
    "data":{
        "result":[

        ],
        "version":1,
        "baseLine":1,
        "dataType":"NEW"
    }
}

Delta Response Example - format of the responses following the snapshot response

{
    "id":"aa89ef9f-e77a-4ccd-a35c-b62e2c03c8e0",
    "topic":"user.openapi.perp.order",
    "creationTime":1646200779822,
    "data":{
        "result":[
            {
                "orderId":"2a44a4de-8244-4be9-b343-52bdfe135c9e",
                "orderLinkId":"",
                "createdAt":1646200779733,
                "updatedAt":1646200779736,
                "symbol":"BTCPERP",
                "orderStatus":"Filled",
                "side":"Buy",
                "price":"44283.5",
                "qty":"0.001",
                "cumExecQty":"0.001",
                "leavesQty":"0",
                "orderIM":"0",
                "realisedPnl":"None",
                "orderType":"Limit",
                "reduceOnly":0,
                "timeInForce":"GoodTillCancel",
                "cumExecFee":"0.03320775",
                "orderPnl":"",
                "basePrice":"",
                "cumExecValue":"44.277",
                "closeOnTrigger":"false",
                "triggerBy":"UNKNOWN",
                "takeProfit":"0",
                "stopLoss":"0",
                "tpTriggerBy":"UNKNOWN",
                "slTriggerBy":"UNKNOWN",
                "triggerPrice":"0",
                "stopOrderType":"UNKNOWN",
                "cancelType":"UNKNOWN"
            }
        ],
        "version":2,
        "baseLine":1,
        "dataType":"CHANGE"
    }
}

Subscribe to stay updated on active orders.

topic:

user.openapi.perp.order

Response Parameters

Parameter Type Comment
orderId string Order ID
orderLinkId string Custom ID used for cross-platform strategy remarks; a max. of 32 characters
createdAt string Creation time (when the order_status was Created)
updatedAt string Update time
symbol string Contract name
orderStatus string Order status
side string Direction
price string Order price
qty string size of order.
cumExecQty string Total filled quantity
leavesQty string unfilled size of order
orderIm string Initial margin
realisedPnl string Closed P&L
orderType string refer to Order Type
reduceOnly number Reduce-only
timeInForce string Time in force
cumExecFee string Total trading fees
orderPnl string The total trade profit and loss for this order
basePrice string Market price during order placement
cumExecValue string Total order value of filled orders
closeOnTrigger bool Close on trigger, please set it to true for a close order
triggerBy string Trigger price type
takeProfit string Take-profit price (Perpetual)
stopLoss string Stop-loss price (Perpetual)
tpTriggerBy string Price type for take-profit triggering (Perpetual), default value is last traded price
slTriggerBy string Price type for stop-loss triggering (Perpetual), default value is last traded price
triggerPrice string Trigger price
stopOrderType string refer to Stop Order Type
cancelType string refer to Cancel Type

Enums Definitions

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

Side (side)

Time in force (timeInForce)

Symbol (symbol)

refer to Query Symbol endpoint

Order type (orderTypes)

Currency (currency/coin)

Order status (orderStatus)

Quantity (qty)

Price (price)

Kline interval (interval)

Transaction type (type)

Margin Mode (marginMode)

Order Filter (orderFilter)

LastLiquidityInd (LastLiquidityInd)

Exec Type (execType)

Tick Direction(tickDirection)

It indicates price fluctuation relative to the last trade.

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

0

Success

10001

Error - request failed processed. Please try again.

10002

Request not authorized - an API key is required and should be included in all requests.

10003

Too many requests - please use WebSocket for live updates. Current limit is %s requests per minute.

10004

invalid sign

10005

permission denied for current apikey

10006

System not responding. Request status unknown. Please contact live support.

10007

Response timeout from backend server. Delivery and request status unknown.

10016

System error. Please try again later.

3100102

Contract name cannot be empty.

3100103

Invalid order direction.

3100104

Please enter the order quantity.

3100105

Only Standard and Advanced versions supported.

3100106

Please enter the order price.

3100107

Order type must be price or implied volatility.

3100108

Implied volatility must be greater than zero.

3100109

Invalid order type.

3100110

Invalid time in force.

3100113

Order price cannot be lower than {{key0}}.

3100114

Order price cannot be higher than {{key0}}.

3100115

The min. tick size should be {{key0}}.

3100116

Order quantity below the lower limit.

3100117

Order qty exceeds the upper limit.

3100118

The min. order size increment is {{key0}}.

3100119

Order ID cannot be empty.

3100122

Only modification to implied volatility, order price, or order quantity supported.

3100123

outRequestId cannot be empty.

3100126

Settlement in progress! {{key0}} not available for trades.

3100127

{{key0}} not yet available for trades.

3100128

{{key0}} no longer available for trades.

3100129

Repeated Request

3100136

Order does not exist. (the order does not exist or the order has been completed to the final state (Canceled, Filled))

3100141

Failed to place new order(s)! Position is being liquidated.

3100143

Failed to cancel! The order has already been filled.

3100191

Failed! The order has already been canceled.

3100192

Failed to edit! The order has already been filled.

3100193

Failed to edit! The order has already been canceled.

3100144

Failed to edit!

3100145

Up to {{key0}} active orders supported for Options.

3200300

Insufficient margin balance.

3200304

The number of active orders exceeds the upper limit.

3200200

Insufficient margin balance.

3303001

No corresponding command execution authority.

3303004

Instruction execution exception.

3303005

Repeat signature verification.

3303006

Sign verification failed.

3303007

Single connection execution command frequency overrun.

3303008

The number of websocket connections established by a single uid exceeds the limit.

3400001

Please ensure that there are no positions in your USDC account, including USDC perpetual and options

3400002

Please ensure that there are no active orders in your USDC account, including Limit, Market and Conditional orders

3400005

Set margin mode failed

3400015

System error. Please try again later.

3400045

Set margin mode failed. The error will be triggerd when your account is in the upgrade of unified margin account, then you request set margin mode endpoint in the mean time.

3500001

System error. Please try again later.

3500040

System error. Please try again later.