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

WebSocket API

2022-06-16

REST API

2022-06-02

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.

An example how to place an order(see python):

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/option/usdc/openapi/private/v1/place-order"

payload = json.dumps({"outRequestId":"8c7af60012","symbol":"BTC-17DEC21-40000-C","orderType":"Limit","side":"Buy",
                      "orderQty":"0.01","orderPrice":"308","iv":"72","timeInForce":"GoodTillCancel","orderLinkId":"c3d5cb801a",
                      "reduceOnly":True,"placeMode":1,"placeType":1})

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)

Market Data Endpoints

The following market data endpoints do not require authentication.

OrderBook

Request Example


curl 'https://api-testnet.bybit.com/option/usdc/openapi/public/v1/order-book?symbol=BTC-3DEC21-62000-P'

Response Example

{
  "retCode": 0,
    "retMsg": "SUCCESS",
    "result": [
    {
      "price": "5000.00000000",
      "size": "2.0000",
      "side": "Buy"
    },
    {
      "price": "1.50000000",
      "size": "0.0200",
      "side": "Buy"
    },
    {
      "price": "5900.00000000",
      "size": "0.9000",
      "side": "Sell"
    }
  ]
}

Query order book info. Each side has a depth of 25 orders.

HTTP Request

GET /option/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.

Contract Info

Request Example

curl 'https://api-testnet.bybit.com/option/usdc/openapi/public/v1/symbols?symbol=BTC-30SEP22-400000-C&status=ONLINE'

Response Example

{
    "retCode": 0,
    "retMsg": "success",
    "result": {
        "resultTotalSize": 1,
        "cursor": "",
        "dataList": [
            {
                "symbol": "BTC-30SEP22-400000-C",
                "status": "ONLINE",
                "baseCoin": "BTC",
                "quoteCoin": "USD",
                "settleCoin": "USDC",
                "takerFee": "0.0003",
                "makerFee": "0.0003",
                "minLeverage": "",
                "maxLeverage": "",
                "leverageStep": "",
                "minOrderPrice": "5",
                "maxOrderPrice": "10000000",
                "minOrderSize": "0.01",
                "maxOrderSize": "200",
                "tickSize": "5",
                "minOrderSizeIncrement": "0.01",
                "basicDeliveryFeeRate": "0.00015",
                "deliveryTime": "1664524800000"
            }
        ]
    }
}

Query for all if blank.

HTTP Request

GET /option/usdc/openapi/public/v1/symbols

Request Parameters

Parameter Required Type Comment
symbol false string Contract name
status false string Status, can be WAITING_ONLINE, ONLINE, DELIVERING, or OFFLINE
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
cursor false string API pass-through

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
settleCoin string Settle Coin
takerFee string Taker fee
makerFee string Maker fee
minLeverage string Min. leverage
maxLeverage string Max. leverage
leverageStep string Modification to leverage
minOrderPrice string Min. order price
maxOrderPrice string Max. order price
minOrderSize string Min. order quantity
maxOrderSize string Max. order quantity
tickSize string Tick size
minOrderSizeIncrement string Min. order size increment
basicDeliveryFeeRate string Basic Delivery Fee Rate
deliveryTime string Delivery time, unit in milliseconds
cursor string API pass-through

Latest Symbol Info

Request Example

curl 'https://api-testnet.bybit.com/option/usdc/openapi/public/v1/tick?symbol=BTC-28JAN22-250000-C'

Response Example

{
  "retCode": 0,
    "retMsg": "SUCCESS",
    "result": {
    "symbol": "BTC-28JAN22-250000-C",
      "bid": "0",
      "bidIv": "0",
      "bidSize": "0",
      "ask": "0",
      "askIv": "0",
      "askSize": "0",
      "lastPrice": "0",
      "openInterest": "0",
      "indexPrice": "56171.79000000",
      "markPrice": "12.72021285",
      "markPriceIv": "1.1701",
      "change24h": "0",
      "high24h": "0",
      "low24h": "0",
      "volume24h": "0",
      "turnover24h": "0",
      "totalVolume": "0",
      "totalTurnover": "0",
      "predictedDeliveryPrice": "0",
      "underlyingPrice": "57039.61000000",
      "delta": "0.00184380",
      "gamma": "0.00000022",
      "vega": "1.35132531",
      "theta": "-1.33819821"
  }
}

HTTP Request

GET /option/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
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

Delivery Price

Request Example

curl 'https://api-testnet.bybit.com/option/usdc/openapi/public/v1/delivery-price?symbol=BTC-3NOV21-58000-C'

Response Example

{
  "retCode": 0,
    "retMsg": "success",
    "result": {
    "resultTotalSize": 1,
      "cursor": "",
      "dataList": [
      {
        "symbol": "BTC-3NOV21-58000-C",
        "deliveryPrice": "63149.218777910",
        "deliveryTime": "1635926400000"
      }
    ]
  }
}

HTTP Request

GET /option/usdc/openapi/public/v1/delivery-price

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 50
cursor false string API pass-through

Response Parameters

Parameter Type Comment
symbol string Contract name
deliveryPrice string Delivery price
deliveryTime string Delivery time, unit in milliseconds
cursor string API pass-through

Query Last 500 Trades

Request Example

curl 'https://api-testnet.bybit.com/option/usdc/openapi/public/v1/query-trade-latest?category=OPTION&limit=1'

Response Example

{
    "result": {
        "resultTotalSize": 1,
        "dataList": [
            {
                "symbol": "BTC-14JUN22-24500-C",
                "orderQty": "0.300",
                "orderPrice": "1540.00",
                "time": "1655088048651"
            }
        ]
    },
    "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. OPTION or PERPETUAL
symbol false string Contract name
optionType false string Call or put, required for Options
limit false string default 500

Response Parameters

Parameter Type Comment
resultTotalSize number length of dataList
dataList list Return the result list, refer to the following fields
Parameter Type Comment
symbol string Contract name
orderPrice string Order price
orderQty string Order quantity
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/option/usdc/openapi/private/v1/place-order \
-H "Content-Type: application/json" \
-D '{"symbol":"BTC-26NOV21-58000-P","orderType":"Limit","side":"Buy","orderQty":"1","orderPrice":"1","timeInForce":"GoodTillCancel"}'

Response Example

{
    "retCode": 0,
    "retMsg": "OK",
    "result": {
        "orderId": "8c65df91-91fc-461d-9b14-786379ef138c",
        "orderLinkId": "AAAAA41133",
        "symbol": "BTC-13MAY22-40000-C",
        "orderType": "Limit",
        "side": "Buy",
        "orderQty": "0.01",
        "orderPrice": "5"
    },
    "retExtMap": {}
}

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 /option/usdc/openapi/private/v1/place-order

Request Parameters

Parameter Required Type Comment
symbol true string Contract name
orderType true string refer to Order type (Market is only supported currently for IOC(ImmediateOrCancel)orders)
side true string Direction
orderPrice false string Order price. For option, if iv has value, the final order price will be calculated by Implied volatility. If orderType is Market, orderPrice is not required.
orderQty true string Order quantity
iv false string Implied volatility. If orderType is Market, iv is not required, otherwise the order will fail.
timeInForce false string Time in force
orderLinkId true string Custom ID used for cross-platform strategy remarks; a max. of 32 characters
reduceOnly false bool Reduce-only
mmp false string 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
symbol string Contract name
orderPrice string Order price
orderQty string Order quantity
orderType string Order type
side string Direction

Place Batch Orders

Each request supports a max. of four orders. The reduceOnly parameter should be separate and unique for each order in the request.

curl https://api-testnet.bybit.com/option/usdc/openapi/private/v1/batch-place-orders \
-H "Content-Type: application/json" \
-D '{"orderRequest":[{"symbol":"BTC-26NOV21-58000-P","orderType":"Limit","side":"Buy","orderQty":"1","orderPrice":"1","timeInForce":"GoodTillCancel"}]}'



Response Example

{
    "retCode": 0,
    "retMsg": "OK",
    "result": [
        {
            "orderId": "fa6cd740-56ed-477d-9385-90ccbfee49ca",
            "orderLinkId": "AAAAA4112",
            "symbol": "BTC-13MAY22-40000-C",
            "orderType": "Limit",
            "side": "Buy",
            "orderQty": "0.01",
            "orderPrice": "5",
            "extMap": {},
            "errorCode": 0,
            "errorDesc": ""
        }
    ],
    "retExtMap": {}
}

HTTP Request

POST /option/usdc/openapi/private/v1/batch-place-orders

Request Parameters

Parameter Required Type Comment
orderRequest true list list
Parameter Required Type Comment
symbol true string Contract name
orderType true string refer to Order type (Market is only supported currently for IOC(ImmediateOrCancel)orders)
side true string Direction
orderPrice false string Order price. For option, if iv has value, the final order price will be calculated by Implied volatility. If orderType is Market, orderPrice is not required.
orderQty true string Order quantity
iv false string Implied volatility. If orderType is Market, iv is not required, otherwise the order will fail.
timeInForce false string Time in force
orderLinkId true string Custom ID used for cross-platform strategy remarks; a max. of 32 characters
reduceOnly false bool Reduce-only
mmp false string 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
symbol string Contract name
orderPrice string Order price
orderQty string Order quantity
orderType string Order type
side string Direction
extMap map Map has specific error details when failed, else null.
errorCode string Error code. 0 means success.
errorDesc string Error description

Modify Order

curl https://api-testnet.bybit.com/option/usdc/openapi/private/v1/replace-order \
-H "Content-Type: application/json" \
-D '{"symbol":"BTC-26NOV21-58000-P","orderId":"be6c87be-da18-4876-9a64-6b7ccc859071","orderQty":"1","orderPrice":"1"}'



Response Example

{
    "retCode": 0,
    "retMsg": "OK",
    "result": {
        "outRequestId": "",
        "symbol": "BTC-13MAY22-40000-C",
        "orderId": "8c65df91-91fc-461d-9b14-786379ef138c",
        "orderLinkId": "AAAAA41133"
    },
    "retExtMap": {}
}

For Options, at least one of the three parameters — price, quantity or implied volatility — must be input.

HTTP Request

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

Request Parameters

Parameter Required Type Comment
symbol true string Contract name
orderId false string Either orderId or orderLinkId is required
orderLinkId false string Either orderId or orderLinkId is required
orderPrice false string Order price
orderQty false string Order quantity
iv false string Implied volatility

Response Parameters

Parameter Type Comment
outRequestId string System internal param. Just ignore
symbol string Contract name
orderId string Order ID
orderLinkId string Custom ID used for cross-platform strategy remarks; a max. of 32 characters

Batch Modify Orders

Each request supports a max. of four orders. The reduceOnly parameter should be separate and unique for each order in the request.

curl https://api-testnet.bybit.com/option/usdc/openapi/private/v1/batch-replace-orders \
-H "Content-Type: application/json" \
-D '{"replaceOrderRequest":[{"symbol":"BTC-26NOV21-58000-P","orderId":"be6c87be-da18-4876-9a64-6b7ccc859071","orderQty":"1","orderPrice":"1"}]}'



Response Example

{
    "retCode": 0,
    "retMsg": "OK",
    "result": [
        {
            "outRequestId": "",
            "symbol": "BTC-13MAY22-40000-C",
            "orderId": "8c65df91-91fc-461d-9b14-786379ef138c",
            "extMap": {},
            "errorCode": 0,
            "errorDesc": "",
            "orderLinkId": "AAAAA41133"
        }
    ],
    "retExtMap": {}
}

HTTP Request

POST /option/usdc/openapi/private/v1/batch-replace-orders

Request Parameters

Parameter Required Type Comment
replaceOrderRequest true list list
Parameter Required Type Comment
symbol true string Contract name
orderId false string Either orderId or orderLinkId is required
orderLinkId false string Either orderId or orderLinkId is required
orderPrice false string Order price
orderQty false string Order quantity
iv false string Implied volatility

Response Parameters

Parameter Type Comment
outRequestId string System internal param. Just ignore
symbol string Contract name
orderId string Order ID
orderLinkId string Custom ID used for cross-platform strategy remarks; a max. of 32 characters
extMap map Map has specific error details when failed, else null.
errorCode string Error code. 0 means success.
errorDesc string Error description

Cancel Order

curl https://api-testnet.bybit.com/option/usdc/openapi/private/v1/cancel-order \
-H "Content-Type: application/json" \
-D '{"symbol":"BTC-26NOV21-58000-P","orderId":"ec6d8081-8950-491b-bf43-22ddb09df0fc"}'


Response Example

{
    "retCode": 0,
    "retMsg": "OK",
    "result": {
        "outRequestId": "",
        "symbol": "BTC-13MAY22-40000-C",
        "orderId": "8c65df91-91fc-461d-9b14-786379ef138c",
        "orderLinkId": ""
    },
    "retExtMap": {}
}

HTTP Request

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

Request Parameters

Parameter Required Type Comment
symbol true string Contract name
orderId false string Either orderId or orderLinkId is required
orderLinkId false string Either orderId or orderLinkId is required

Response Parameters

Parameter Type Comment
outRequestId string System internal param. Just ignore
symbol string Contract name
orderId string Order ID
orderLinkId string Custom ID used for cross-platform strategy remarks; a max. of 32 characters

Batch Cancel Orders

curl https://api-testnet.bybit.com/option/usdc/openapi/private/v1/batch-cancel-orders \
-H "Content-Type: application/json" \
-D '{"cancelRequest":[{"symbol":"BTC-26NOV21-58000-P","orderId":"1a69653f-c3c7-40b4-a492-17316a2086a2"}]}'



Response Example

{
    "retCode": 0,
    "retMsg": "OK",
    "retExtMap": {},
    "result": [
        {
            "outRequestId": "",
            "symbol": "BTC-13MAY22-40000-C",
            "orderId": "720b97b4-8e7c-44c9-8417-1160ed82f990",
            "orderLinkId": "AAAAA41134",
            "errorCode": 0,
            "errorDesc": ""
        }
    ]
}

HTTP Request

POST /option/usdc/openapi/private/v1/batch-cancel-orders

Request Parameters

Parameter Required Type Comment
cancelRequest true list list
Parameter Required Type Comment
symbol true string Contract name
orderId false string Either orderId or orderLinkId is required
orderLinkId false string Either orderId or orderLinkId is required

Response Parameters

Parameter Type Comment
outRequestId string System internal param. Just ignore
symbol string Contract name
orderId string Order ID
orderLinkId string Custom ID used for cross-platform strategy remarks; a max. of 32 characters
errorCode string Error code. 0 means success.
errorDesc string Error description

Cancel All Active Orders

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



Response Example

{
    "retCode": 0,
    "retMsg": "OK",
    "retExtMap": {},
    "result": [
        {
            "outRequestId": "cancelAll-290119-1652176443114-0",
            "symbol": "BTC-13MAY22-40000-C",
            "orderId": "fa6cd740-56ed-477d-9385-90ccbfee49ca",
            "orderLinkId": "",
            "errorCode": 0,
            "errorDesc": ""
        }
    ]
}

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

HTTP Request

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

Request Parameters

Parameter Required Type Comment

Response Parameters

Parameter Type Comment
outRequestId string System internal param. Just ignore
symbol string Contract name
orderId string Order ID
orderLinkId string Custom ID used for cross-platform strategy remarks; a max. of 32 characters
errorCode string Error code. 0 means success.
errorDesc string Error description

Query Unfilled/Partially Filled Orders(real-time)

This is GET request, and pass orderLinkId could only query current active orders.

It's able to query orders in last 7 days including fully/partial filled & cancelled orders if orderId is passed. We recommend to save the response into your database.

Query priority: orderId > orderLinkId > both null.

cursor is not necessary when do first querying. However, it must be passed with the exact same value from response while getting next page.

curl GET 'https://api-testnet.bybit.com/option/usdc/openapi/private/v1/trade/query-active-orders?orderLinkId=option0005&symbol=BTC-30SEP22-28000-C' \
--header 'X-BAPI-API-KEY: {api key}' \
--header 'X-BAPI-SIGN: c657feac222cc8b66d6162802c707c0df47592ee7532a060cb613679aad174f7' \
--header 'X-BAPI-SIGN-TYPE: 2' \
--header 'X-BAPI-TIMESTAMP: 1658126609521' \
--header 'X-BAPI-RECV-WINDOW: 10000' \

Response Example

{
    "retCode": 0,
    "retMsg": "OK",
    "result": {
        "resultTotalSize": 2,
        "cursor": "id%3D1657785223205%23cd05e436-1e04-4391-94db-82b660638364",
        "dataList": [
            {
                "orderId": "bd4a5ce3-cefd-455c-ac8d-1eaf2ae76b24",
                "orderLinkId": "1426a049-f999-0000026",
                "symbol": "BTC-14JUL22-10000-P",
                "orderStatus": "New",
                "orderPrice": "0.2",
                "side": "Sell",
                "remainingQty": "0.01",
                "orderType": "Limit",
                "qty": "0.01"
            },
            {
                "orderId": "cd05e436-1e04-4391-94db-82b660638364",
                "orderLinkId": "1426a049-f999-0000027",
                "symbol": "BTC-14JUL22-10000-P",
                "orderStatus": "New",
                "orderPrice": "0.2",
                "side": "Sell",
                "remainingQty": "0.01",
                "orderType": "Limit",
                "qty": "0.01"
            }
        ]
    }
}

HTTP Request

GET /option/usdc/openapi/private/v1/trade/query-active-orders

Request Parameters

Parameter Required Type Comment
orderId false string Order ID
orderLinkId false string Custom ID used for cross-platform strategy remarks; a max. of 32 characters
symbol true string Contract name
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
orderId string Order ID
orderLinkId string Custom ID used for cross-platform strategy remarks; a max. of 32 characters
symbol string Contract name
orderStatus string Order status
price string Order price
side string Direction
remainingQty string Number of unfilled contracts from the order's size
orderType string Order type
qty string Order quantity

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": "OPTION", "symbol": "BTC-14JUN22-24500-C"}'


Response Example

{
    "result": {
        "cursor": "9843d39e-dd8f-4499-bd8e-988f4c597980%3A1655092443445%2C9843d39e-dd8f-4499-bd8e-988f4c597980%3A1655092443445",
        "resultTotalSize": 1,
        "dataList": [
            {
                "symbol": "BTC-14JUN22-24500-C",
                "orderType": "Limit",
                "orderLinkId": "option10006",
                "orderId": "9843d39e-dd8f-4499-bd8e-988f4c597980",
                "stopOrderType": "UNKNOWN",
                "orderStatus": "New",
                "takeProfit": "",
                "cumExecValue": "0.0000",
                "createdAt": "1655092443445",
                "orderPnl": "",
                "price": "600.0",
                "tpTriggerBy": "",
                "timeInForce": "GoodTillCancel",
                "basePrice": "",
                "side": "Buy",
                "triggerPrice": "",
                "cumExecFee": "0.0000",
                "leavesQty": "0.220",
                "slTriggerBy": "",
                "iv": "0.000",
                "closeOnTrigger": "",
                "cumExecQty": "0.000",
                "reduceOnly": 0,
                "qty": "0.220",
                "stopLoss": "",
                "lastExecPrice": "",
                "triggerBy": "",
                "orderIM": "133.6895"
            }
        ]
    },
    "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. OPTION or 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
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 Number of unfilled contracts from the order's size
slTriggerBy string Price type for stop-loss triggering (Perpetual), Default MarkPrice
iv string Implied volatility
closeOnTrigger bool Close on trigger, please set it to true for a close order
cumExecQty string Total filled quantity
reduceOnly number Reduce-only
qty string Order quantity
stopLoss string Stop-loss price (Perpetual)
lastExecPrice string Filled price
triggerBy string Trigger price type
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":"OPTION"}'


Response Example

{
  "result": {
    "cursor": "cc27c6ff-a4ec-4739-96bc-6d2b266606d4%3A1640843817698%2Ccc27c6ff-a4ec-4739-96bc-6d2b266606d4%3A1640843817698",
      "resultTotalSize": 1,
      "dataList": [
      {
        "symbol": "BTC-31DEC21-18000-P",
        "orderType": "Limit",
        "orderLinkId": "test2021122417000221",
        "orderId": "cc27c6ff-a4ec-4739-96bc-6d2b266606d4",
        "cancelType": "UNKNOWN",
        "stopOrderType": "UNKNOWN",
        "orderStatus": "Filled",
        "takeProfit": "",
        "createdAt": "1640843817698",
        "orderPnl": "0.0000",
        "price": "1.0",
        "tpTriggerBy": "",
        "timeInForce": "GoodTillCancel",
        "updatedAt": "1640843817698",
        "basePrice": "",
        "realisedPnl": "0.0000",
        "side": "Sell",
        "triggerPrice": "",
        "cumExecFee": "0.0010",
        "leavesQty": "0.000",
        "cashFlow": "0.0100",
        "slTriggerBy": "",
        "iv": "5.2820",
        "closeOnTrigger": "",
        "cumExecQty": "0.010",
        "reduceOnly": 0,
        "qty": "0.010",
        "stopLoss": "",
        "triggerBy": "",
        "orderIM": "0.0000"
      }
    ]
  },
  "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. OPTION or 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
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 refer to Cancel Type
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 Number of unfilled contracts from the order's size
cashFlow string Cash flow
slTriggerBy string Price type for stop-loss triggering (Perpetual), Default MarkPrice
iv string Implied volatility
closeOnTrigger bool Close on trigger, please set it to true for a close order
cumExecQty string Total filled quantity
reduceOnly number Reduce-only
qty string Order quantity
stopLoss string Stop-loss price (Perpetual)
triggerBy string Trigger price type
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 '{"startTime":"1633687786728","symbol":"1633797786728","category":"OPTION","type":"Settlement","orderId":"70bc3d92-009c-464b-8399-010b9d4aac2b"}'

Response Example

{
  "result": {
    "cursor": "34%3A0%2C34%3A0",
      "resultTotalSize": 1,
      "dataList": [
      {
        "symbol": "BTC-31DEC21-18000-P",
        "tradeTime": "1640834911093",
        "orderLinkId": "test2021122417000218",
        "side": "Sell",
        "orderId": "13ad19bf-5e23-479b-8261-54f1baf290e1",
        "execPrice": "1.00",
        "lastLiquidityInd": "TAKER",
        "execValue": "",
        "execType": "TRADE",
        "execQty": "0.010",
        "execFee": "0.0010",
        "feeRate": "0.000300",
        "tradeId": "77fdaeef-b931-51f4-96c8-33f97c722053"
      }
    ]
  },
  "retCode": 0,
    "retMsg": "Success."
}

HTTP Request

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

Request Parameters

Parameter Required Type Comment
category true string Type. OPTION or 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 string 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 Trade 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": "9893%3A0%2C9893%3A0",
      "dataList": [
      {
        "transactionTime": "1638842921038",
        "symbol": "BTCPERP",
        "type": "TRADE",
        "side": "Sell",
        "tradePrice": "50830.0",
        "funding": "0.0000",
        "qty": "0.010",
        "size": "1.110",
        "fee": "0.3813",
        "cashFlow": "2.8159",
        "change": "2.4346",
        "walletBalance": "16906.4074",
        "feeRate": "0.0008",
        "orderId": "dd216843-fe5d-43bc-b2c7-ab6a5958cd90",
        "orderLinkId": "",
        "tradeId": "f256315f-c80b-5d3e-a9c3-2a1de95e9637",
        "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
qty string Order quantity
size string Positions
tradePrice string Filled price
funding string Funding fees
fee string Trading fees
cashFlow string Cash flow
change string Change
walletBalance string Cash balance
feeRate string Taker or maker fee rate
tradeId string Transaction ID
orderId string Order ID
orderLinkId string Custom ID used for cross-platform strategy remarks; a max. of 32 characters
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 \
-H "Content-Type: application/json" \
-D '{}'


Response Example

{
    "result": {
        "walletBalance": "1000.0000",
        "accountMM": "0.0000",
        "bonus": "0.0000",
        "accountIM": "133.6697",
        "totalSessionRPL": "0.0000",
        "equity": "1000.0000",
        "totalRPL": "0.0000",
        "marginBalance": "1000.0000",
        "availableBalance": "866.3303",
        "totalSessionUPL": "0.0000"
    },
    "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

Set Margin Mode

Request Example


curl https://api-testnet.bybit.com/option/usdc/private/asset/account/setMarginMode \
-H "Content-Type: application/json" \
-D '{"setMarginMode":"PORTFOLIO_MARGIN"}'

Response Example

{
    "retCode": 0,
    "retMsg": "Request accepted",
    "result": {
        "reasons": []
    }
}

HTTP Request

POST /option/usdc/private/asset/account/setMarginMode

Request Parameters

Parameter Required Type Comment
setMarginMode true string Margin mode Margin Mode

Response Parameters

Parameter Type Comment

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 '{"symbol":"BTC-22OCT21-40000-C","category":"OPTION"}'

Response Example

{
  "result": {
    "cursor": "BTC-31DEC21-24000-P%3A1640834421431%2CBTC-31DEC21-24000-P%3A1640834421431",
      "resultTotalSize": 1,
      "dataList": [
      {
        "symbol": "BTC-31DEC21-24000-P",
        "leverage": "",
        "occClosingFee": "",
        "liqPrice": "",
        "positionValue": "",
        "takeProfit": "",
        "riskId": "",
        "trailingStop": "",
        "unrealisedPnl": "",
        "createdAt": "1640834421431",
        "markPrice": "0.00",
        "cumRealisedPnl": "",
        "positionMM": "359.5271",
        "positionIM": "467.0633",
        "updatedAt": "1640834421431",
        "tpSLMode": "",
        "side": "Sell",
        "bustPrice": "",
        "deleverageIndicator": 0,
        "entryPrice": "1.4",
        "size": "-0.100",
        "sessionRPL": "0.0000",
        "positionStatus": "",
        "sessionUPL": "0.1450",
        "stopLoss": "",
        "orderMargin": "",
        "sessionAvgPrice": "1.5"
      }
    ]
  },
  "retCode": 0,
    "retMsg": "Success."
}

HTTP Request

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

Request Parameters

Parameter Required Type Comment
category true string Type. OPTION or 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

Query Delivery History

Request Example

curl https://api-testnet.bybit.com/option/usdc/openapi/private/v1/query-delivery-list \
-H "Content-Type: application/json" \
-d '{"symbol":"BTC-22OCT21-45000-C"}'

Response Example

{
  "retCode":0,
    "retMsg":"OK",
    "result":{
    "resultTotalSize":1,
      "cursor":"ccc62b1a-e1a0-42b6-86b5-3570e22cfbdf%3A1634284800789%2Cb09397d8-4da1-4d32-b70f-c59efd381f66%3A1634284800769",
      "dataList":[
      {
        "deliveryTime":"1634284800789",
        "symbol":"BTC-15OCT21-30000-P",
        "side":"Buy",
        "position":"0.00",
        "deliveryPrice":"59307.0",
        "strike":"30000",
        "fee":"0.0000",
        "deliveryRpl":"0.0000"
      }
    ]
  }
}

HTTP Request

POST /option/usdc/openapi/private/v1/query-delivery-list

Request Parameters

Parameter Required Type Comment
symbol true string Contract name
expDate false string format: yyyyMMdd
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
deliveryTime string Delivery time
symbol string Contract name
side string Direction
position string position
deliveryPrice string Delivery price
strike string Strike price
fee string Trading fees
deliveryRpl string Delivery Rpl

Query Positions Info Upon Expiry

Request Example

curl https://api-testnet.bybit.com/option/usdc/openapi/private/v1/query-position-exp-date \
-H "Content-Type: application/json" \
-d '{"expDate":"20211010"}'


Response Example

{
  "retCode":0,
    "retMsg":"OK",
    "result":{
    "resultTotalSize":2,
      "cursor":"22OCT21:0,15OCT21:0",
      "dataList":[
      {
        "expDate":"22OCT21",
        "pnl":"1062.0157",
        "totalRPL":"0.0000",
        "im":"14792.2241",
        "mm":"10653.4193",
        "sessionRPL":"1587.0000",
        "sessionUPL":"1172.4930"
      },
      {
        "expDate":"16OCT21",
        "pnl":"-12.1500",
        "totalRPL":"487.5000",
        "im":"5891.6831",
        "mm":"4184.0030",
        "sessionRPL":"0.0000",
        "sessionUPL":"0.0000"
      }
    ]
  }
}

HTTP Request

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

Request Parameters

Parameter Required Type Comment
expDate false number Expiration date. format: yyyyMMdd
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
expDate string Expiration date. format: yyyyMMdd
pnl string P&L
totalRpl string Total RPL
im string Initial margin
mm string Maintenance margin
sessionRpl string Session RPL
sessionUpl string Session UPL

Market Maker Protection

What is MMP

Market Maker Protection (MMP) is an automated mechanism designed to protect market makers (MM) against liquidity risks and over-exposure in the market.

It prevents simultaneous trade executions on quotes provided by the MM within a short time span.

The MM can automatically pull their quotes if the number of contracts traded for an underlying asset exceeds the configured threshold within a certain time frame. Once MMP is triggered,

any pre-existing MMP orders will be automatically canceled,

and new orders tagged as MMP will be rejected for a specific duration — known as the frozen period — so that MM can reassess the market and modify the quotes.

How to Enable MMP

Send an email to Bybit (financial.inst@bybit.com) or contact your business development (BD) manager to apply for MMP.

The default settings are as follows

Parameter Type Comment default value
currency string Currency BTC
windowMs string Time Window(Millisecond) 5000
frozenPeriodMs string Frozen Period(Millisecond). (0 means the account will remain frozen until manually reset) 100
qtyLimit string Quantity Limit. (positive number, up to two decimal places) 100
deltaLimit string Delta Limit. (positive number, up to two decimal places) 100

Modify

Request Example

curl https://api-testnet.bybit.com/option/usdc/openapi/private/v1/mmp-modify \
-H "Content-Type: application/json" \
-d '{
    "currency":"BTC",
    "windowMs":500000,
    "frozenPeriodMs":300,
    "qtyLimit":"10",
    "deltaLimit":"100"
}'


Response Example

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

HTTP Request

POST /option/usdc/openapi/private/v1/mmp-modify

Request Parameters

Parameter Required Type Comment
currency true string Currency
windowMs true number Time Window(Millisecond)
frozenPeriodMs true number Frozen Period(Millisecond). (0 means the account will remain frozen until manually reset)
qtyLimit true string Quantity Limit. (positive number, up to two decimal places)
deltaLimit true string Delta Limit. (positive number, up to two decimal places)

Reset

Request Example

curl https://api-testnet.bybit.com/option/usdc/openapi/private/v1/mmp-reset \
-H "Content-Type: application/json" \
-d '{
    "currency":"BTC"
}'


Response Example

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

HTTP Request

POST /option/usdc/openapi/private/v1/mmp-reset

Request Parameters

Parameter Required Type Comment
currency true string Currency

Query MMP state

Request Example


curl https://api-testnet.bytick.com/option/usdc/openapi/private/v1/get-mmp-state \
-H "Content-Type: application/json" \
-D '{"baseCoin":"BTC"}'

Response Example

{
    "retCode": 0,
    "retMsg": "OK",
    "result": [
        {
            "baseCoin": "",
            "mmpEnabled": false,
            "mmpUserConfigurable": false,
            "windowMs": "0",
            "frozenPeriodMs": "0",
            "qtyLimit": "",
            "deltaLimit": "",
            "mmpFrozenUntilMs": "0",
            "mmpFrozen": false
        }
    ]
}

HTTP Request

POST /option/usdc/openapi/private/v1/get-mmp-state

Request Parameters

Parameter Required Type Comment
baseCoin true string Base currency

Response Parameters

Parameter Type Comment
baseCoin string Base currency
mmpEnabled boolean Whether MMP is enabled
mmpUserConfigurable boolean Whether the user can modify the MMP configuration
windowMs string Time Window(Millisecond)
frozenPeriodMs string Frozen Period(Millisecond). (0 means the account will remain frozen until manually reset)
qtyLimit string Quantity Limit. (positive number, up to two decimal places)
deltaLimit string Delta Limit. (positive number, up to two decimal places)
mmpFrozenUntilMs string Timestamp of when the freeze is expected to be automatically unfrozen (Millisecond)
mmpFrozen boolean whether to freeze

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 /option/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 = 'XXXXXXXXXXXXXXXXXXXX'
    secret = 'XXXXXXXXXXXXXXXXXXXX'
    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.option.order", "user.option.position", 
                 "user.option.tradeHistory", "user.option.orderHistory"]
      })
    )

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

orderBook

How to Subscribe

  ws.send('{"op":"subscribe","id":"requestId","args":["orderbook25.BTC-12NOV21-40000-P"]}');

Snapshot Response Example - format of the first response


{
  "id":"orderbook100.BTC-12NOV21-40000-P-117936-1636454548726",
  "topic":"orderbook100.BTC-12NOV21-40000-P",
  "creationTime":1636454548726,
  "data":{
    "orderBook":[
    {
      "price":"1764.5",
      "size":"997.99",
      "side":"Sell"
    },
    {
      "price":"40000.5",
      "size":"0.01",
      "side":"Sell"
    }
  ]
}
}



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

After a successful subscription, it will always provide the snapshot response.

Topic format:

Either orderbook25.{symbol} or orderbook100.{symbol} for Option.

Such as orderbook25.BTC-5NOV21-30000-P or orderbook100.BTC-5NOV21-30000-P

Response Parameters

Parameter Type Comment
price string Order price
side string Side
size string Position qty

orderBook(delta)

How to Subscribe

  ws.send('{"op":"subscribe","id":"requestId","args":["delta.orderbook100.BTC-4MAR22-25000-P"]}');

Snapshot Response Example - format of the first response


{
  "id":"delta.orderbook100.BTC-4MAR22-25000-P-65815768-1646214405074",
  "topic":"delta.orderbook100.BTC-4MAR22-25000-P",
  "creationTime":1646214405074,
  "data":{
  "version":"55",
    "dataType":"NEW",
    "orderBook":[
    {
      "price":"10",
      "size":"1.67",
      "side":"Buy"
    },
    {
      "price":"5",
      "size":"0.01",
      "side":"Buy"
    }
  ]
}
}

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

{
  "id":"delta.orderbook100.BTC-4MAR22-25000-P-65815769-1646214587050",
    "topic":"delta.orderbook100.BTC-4MAR22-25000-P",
    "creationTime":1646214587050,
    "data":{
    "version":"56",
      "dataType":"CHANGE",
      "delete":[

    ],
      "update":[

    ],
      "insert":[
      {
        "price":"15",
        "size":"1",
        "side":"Buy"
      }
    ]
  }
}

100 orders will be fetched from the bid and ask side of the order book.

Topic format:

delta.orderbook100.{symbol}

Such as delta.orderbook100.BTC-5NOV21-30000-P

When the link is established successfully, a full package will be added first. If you place an order again, you will receive an incremental data package.

-If the dataType is NEW, full data will be pushed

-if the dataType is CHANGE, incremental data will be pushed

Response Parameters

Parameter Type Comment
price string Order price
side string Side
size string Position qty

publictradingrecords

How to Subscribe

  ws.send('{"op":"subscribe","id":"{1001}","args":["recenttrades.BTC"]}');

Snapshot Response Example - format of response


{
    "id":"recenttrades.BTC-118388-1636510323155",
    "topic":"recenttrades.BTC",
    "creationTime":1636510323155,
    "data":{
        "coin":"BTC",
        "trades":[
            {
                "symbol":"BTC-31DEC21-36000-P",
                "tradeId":"787bf079-b6a5-5bc0-a76d-59dad9036e7b",
                "price":"371",
                "size":"0.01",
                "tradeTime":"1636510323144",
                "side":"Buy",
                "crossSeq":"118388"
            }
        ]
    }
}

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

After a successful subscription, any changes in the transaction data will be pushed in real-time or once every second. The number of pushes depends on the number of new transaction records within the time frame.

Subscribe according to the dimension of the currency, such as BTC or ETH

topic format:

Option- recenttrades.{symbol}, such as: recenttrades.BTC

Response Parameters

Parameter Type Comment
tradeTime string Timestamp, unit in milliseconds
symbol string Contract name
side string Direction of taker
size string Position qty
price string Transaction price
tradeId string Transaction ID
crossSeq string System internal param. Just ignore

latestsymbolinfo

How to Subscribe

ws.send('{"op":"subscribe","id":"{1001}","args":["instrument_info.BTC-19NOV21-58000-P"]}');

Snapshot Response Example - format of the first response


{
    "id":"instrument_info.BTC-19NOV21-58000-P-98790-1636511446299",
    "topic":"instrument_info.BTC-19NOV21-58000-P",
    "creationTime":1636511446299,
    "data":{
        "symbol":"BTC-19NOV21-58000-P",
        "bidPrice":"421",
        "askPrice":"465",
        "bidIv":"0.7785",
        "askIv":"0.8012",
        "bidSize":"17",
        "askSize":"18",
        "markPrice":"442.51157238",
        "markPriceIv":"0.7897",
        "indexPrice":"67102.13",
        "underlyingPrice":"67407.49",
        "lastPrice":"0",
        "delta":"-0.10385629",
        "gamma":"0.00002132",
        "theta":"-82.72572574",
        "vega":"19.33584131",
        "change24h":"0",
        "volume24h":"0",
        "turnover24h":"0",
        "high24h":"0",
        "low24h":"0",
        "totalVolume":"0",
        "totalTurnover":"0",
        "openInterest":"0",
        "predictedDeliveryPrice":"62330.90608575"
    }
}

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


Topic format:

instrument_info.{symbol},such as: instrument_info.BTC-19NOV21-58000-P

Response Parameters

Parameter Type Comment
symbol string Contract name
bidPrice string Best bid price
askPrice string Best ask price
bidIv string Implied volatility for best bid
askIv string Implied volatility for best ask
bidSize string Bid quantity
askSize string Ask quantity
markPrice string Mark Price
markPriceIv string Implied volatility for mark price
indexPrice string Index Price
underlyingPrice string Underlying
lastPrice string Last traded price
delta string Delta value
gamma string Delta value
theta string Theta value
vega string Vega value
change24h string 24-hour change
volume24h string 24-hour trading volume
turnover24h string 24-hour turnover
high24h string 24-hour high
low24h string 24-hour low
totalVolume string Total trading volume
totalTurnOver string Total turnover
openInterest string Open interest
predictedDeliveryPrice string Est. delivery price

insurance

How to Subscribe

ws.send('{"op":"subscribe","args":["platform.insurance.USDC"]}')

Response Example - format of all responses

{
    'id': 'd5249692-c34b-48f0-9db5-d693a30bce09', 
    'topic': 'platform.insurance.USDC', 
    'creationTime': 1649750400693, 
    'data': 
        {
            'insuranceBalance': '1180144.86587280', 
            'settleCoin': 'USDC', 
            'timestamp': '1649750400693'
        }
}

topic:

platform.insurance.USDC

Response Parameters

Parameter Type Comment
insuranceBalance string USDC Insurance Balance
settleCoin string Settle Coin
timestamp string Timestamp, unit in milliseconds

Private Topics

myposition

How to Subscribe


ws.send('{"op":"subscribe","id":"{100002}","args":["user.openapi.option.position"]}');

Snapshot Response Example - format of the first response

{
    "id":"b9f465ed-0552-45c2-a2d5-362af0bbf939",
    "topic":"user.openapi.option.position",
    "creationTime":1654746065268,
    "data":{
        "result":[
            {
                "symbol":"BTC-9JUN22-30500-C",
                "positionStatus":"",
                "side":"Sell",
                "size":"-0.0100",
                "entryPrice":"20.00000000",
                "sessionAvgPrice":"20.00000000",
                "markPrice":"62.2119183",
                "positionIM":"",
                "positionMM":"",
                "sessionUPL":"-0.422119183000",
                "sessionRPL":"",
                "createdAt":1654745293038,
                "updatedAt":1654745293038
            }
        ],
        "version":2,
        "baseLine":15,
        "dataType":"NEW"
    }
}

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


{
    "id":"70bd3a99-0e80-4713-8cd1-6b8e8befffd9",
    "topic":"user.openapi.option.position",
    "creationTime":1654745293064,
    "data":{
        "result":[
            {
                "symbol":"BTC-9JUN22-30500-C",
                "positionStatus":"",
                "side":"Sell",
                "size":"-0.01",
                "entryPrice":"20.00000000",
                "sessionAvgPrice":"20.00000000",
                "markPrice":"65.2197913",
                "positionIM":"",
                "positionMM":"",
                "sessionUPL":"-0.452197913000",
                "sessionRPL":"",
                "createdAt":1654745293038,
                "updatedAt":1654745293038
            }
        ],
        "version":2,
        "baseLine":15,
        "dataType":"CHANGE"
    }
}

topic:

Option: user.openapi.option.position

When the link is established successfully, a full package will be added first. If you place an order again, you will receive an incremental data package.

-If the dataType is NEW, full data will be pushed

-if the dataType is CHANGE, incremental data will be pushed

Response Parameters

Parameter Type Comment
symbol string Contract name
positionStatus string Position status
side string Direction
size string size
entryPrice string Avg. entry price
sessionAvgPrice string Settlement price
markPrice string Mark Price
positionIM string Initial margin
positionMM string Maintenance margin
sessionUPL string Session UPL
sessionRPL string Session RPL
createdAt number Creation time
updatedAt number Update time

usertraderecords

How to Subscribe

ws.send('{"op":"subscribe","id":"{100002}","args":["user.openapi.option.trade"]}');

Snapshot Response Example - format of response


{
    "id":"5767b59e-3034-43a9-851f-61ed50fccddc",
    "topic":"user.openapi.option.trade",
    "creationTime":1646188735928,
    "data":{
        "result":[
            {
                "orderId":"a64db071-3c98-44db-bcc8-d4a71e7aaf86",
                "orderLinkId":"",
                "tradeId":"55565169-2da0-5cb3-9dc8-6669c6d777c9",
                "symbol":"BTC-4MAR22-42000-P",
                "side": "Sell",
                "execPrice":"840",
                "execQty":"0.04",
                "execFee":"0.52943604",
                "feeRate":"0.0003",
                "tradeTime":1646188735862,
                "lastLiquidityInd":"TAKER",
                "execType":"TRADE"
            }
        ],
        "version":4,
        "baseLine":1
    }
}


topic:

Option: user.openapi.option.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 Trade 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
execType string Execution type

orders(delta only)

How to Subscribe

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

Snapshot Response Example - format of the first response

{
    "id": "0feb2c52-d10c-4f25-a60c-59e0b6755bbb17195215-6820-4d50-abf8-7c98f9e00570",
    "topic": "user.order",
    "creationTime": 1658123196619,
    "data": {
        "orderId": "0feb2c52-d10c-4f25-a60c-59e0b6755bbb",
        "symbol": "BTC-30SEP22-28000-C",
        "orderStatus": "New",
        "side": "Buy",
        "orderPrice": "460",
        "orderAllSize": "1",
        "orderFilledSize": "0",
        "orderRemainingSize": "1",
        "orderType": "Limit",
        "orderTime": "1658123196611",
        "timeInForce": "GoodTillCancel",
        "createTimeStamp": "1658123196611",
        "updateTimeStamp": "1658123196617",
        "orderLinkId": "option0008",
        "execType": "newed",
        "iv": "0.0",
        "version": "286819574",
        "placeMode": "basic",
        "placeType": "price",
        "userId": "533285"
    }
}

topic: user.order

This topic reflects an order lifecycle.

It only pushes delta data packages. So make sure you've subscribed the topic before placing an order

It sometimes might push duplicate messages, so please ensure idempotent process.

Response Parameters

Parameter Type Comment
orderId string Order ID
symbol string Contract name
orderStatus string Order status
side string Direction
order_price string Order price
orderAllSize string Total size of order
orderFilledSize string Filled size of order
orderRemainingSize string Number of unfilled contracts from the order's size
orderType string Order type
orderTime string Order time
timeInForce string Time in force
createTimeStamp string Creation time
updateTimeStamp string Update time
orderLinkId string Custom ID used for cross-platform strategy remarks; a max. of 32 characters
execType string Execution type
iv string Implied volatility
version string version
cancelType string refer to Cancel Type
userId string uid
placeMode string Please ignore
placeType string Please ignore

orders

How to Subscribe

 ws.send('{"op":"subscribe","id":"{100003}","args":["user.openapi.option.order"]}');

Snapshot Response Example - format of the first response


{
  "id":"d031f695-b546-49f6-8de3-8dac0f06ca14",
  "topic":"user.openapi.option.order",
  "creationTime":1646211968954,
  "data":{
  "result":[
    {
      "orderId":"5fcb8198-b22b-4116-8171-cf40539efbd7",
      "orderLinkId":"1000ss0004",
      "createdAt":1646209468927,
      "updatedAt":1646209468927,
      "symbol":"BTC-24JUN22-25000-P",
      "orderStatus":"New",
      "side":"Buy",
      "price":"100",
      "cashFlow":null,
      "realisedPnl":"",
      "qty":"1.0000",
      "cumExecQty":"0.0000",
      "leavesQty":"1.0000",
      "orderIM":"110",
      "orderType":"Limit",
      "reduceOnly":0,
      "timeInForce":"GoodTillCancel",
      "cumExecFee":"0.00000000",
      "iv":"0.5370",
      "orderPnl":"",
      "cumExecValue":"",
      "cancelType":"UNKNOWN"
    }
  ],
    "version":12,
    "baseLine":2,
    "dataType":"NEW"
}
}



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



{
  "id":"620aeb31-b281-4736-9318-b9193c95ec33",
  "topic":"user.openapi.option.order",
  "creationTime":1646212354560,
  "data":{
  "result":[
    {
      "orderId":"41c44ec8-c8ca-40c5-b468-6fc252bfc081",
      "orderLinkId":"1000ss0005",
      "createdAt":1646212354483,
      "updatedAt":1646212354483,
      "symbol":"BTC-24JUN22-25000-P",
      "orderStatus":"New",
      "side":"Buy",
      "price":"100",
      "cashFlow":null,
      "realisedPnl":"",
      "qty":"1",
      "cumExecQty":"0",
      "leavesQty":"1",
      "orderIM":"110",
      "orderType":"Limit",
      "reduceOnly":0,
      "timeInForce":"GoodTillCancel",
      "cumExecFee":"0",
      "iv":"0.533",
      "orderPnl":"",
      "cumExecValue":"0",
      "cancelType":"UNKNOWN"
    }
  ],
    "version":13,
    "baseLine":2,
    "dataType":"CHANGE"
}
}

topic:

Option: user.openapi.option.order

When the link is established successfully, a full package will be added first. If you place an order again, you will receive an incremental data package.

-If the dataType is NEW, full data will be pushed

-if the dataType is CHANGE, incremental data will be pushed

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 number Creation time
updatedAt number Update time
symbol string Contract name
orderStatus string Order status
side string Direction
price string Order price
cashFlow string Cash flow
realisedPnl string Closed P&L
qty string Order quantity
cumExecQty string Total filled quantity
leavesQty string Number of unfilled contracts from the order's size
orderIM string Initial margin
orderType string Order type
reduceOnly number Reduce-only
timeInForce string Time in force
cumExecFee string Total trading fees
iv string Implied volatility
orderPnl string Order PNL
cumExecValue string Total order value of filled orders
cancelType string refer to Cancel Type

greeks

How to Subscribe

ws.send('{"op":"subscribe","id":"{100003}","args":["user.openapi.greeks"]}');

Snapshot Response Example - format of the first response


{
    "id":"b3666f79-abf0-45a6-9c6d-ff4d41912b57",
    "topic":"user.openapi.greeks",
    "creationTime":1646274372152,
    "data":{
        "result":[
            {
                "coin":"BTC",
                "totalDelta":"0.0006714372",
                "totalGamma":"-0.0000000654",
                "totalVega":"-0.3207237154",
                "totalTheta":"0.1142353260"
            }
        ],
        "version":3984,
        "baseLine":1
    }
}

topic:

Option: user.openapi.greeks

Response Parameters

Parameter Type Comment
coin string Base currency
totalDelta string Delta value
totalGamma string Delta value
totalVega string Vega value
totalTheta string Theta value

mmpevent

How to Subscribe

ws.send('{"op":"subscribe","id":"{100003}","args":["user.mmp.event"]}');

Snapshot Response Example - format of the first response

{
    "id":"1714254779362547",
    "topic":"user.mmp.event",
    "creationTime":1654138213982,
    "data":{
        "triggerStatus":"MMP_FREEZE",
        "triggerTimestamp":"1654138213787",
        "frozenPeriodMs":"9999999999999",
        "baseCoin":"BTC"
    }
}

topic:

Option: user.mmp.event

Response Parameters

Parameter Type Comment
triggerStatus string MMP trigger status
triggerTimestamp string MMP trigger timestamp
frozenPeriodMs string Frozen Period(Millisecond). (0 means the account will remain frozen until manually reset)
baseCoin string Base currency

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 (orderType)

Currency (currency/coin)

Order status (orderStatus)

Quantity (orderQty/qty)

Price (price)

Transaction type (type)

Margin Mode (marginMode)

Exec Type (execType)

Stop Order Type (stopOrderType)

Cancel Type (cancelType)

LastLiquidityInd (LastLiquidityInd)

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.