简体中文
NAV
console python

Group And Resources

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

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

Group And Bybit API Resources

Changelog

2021-09-24

REST API

2021-09-14

Websocket API

REST API

2021-09-03

Websocket API

2021-08-23

REST API

2021-07-29

REST API

2021-06-28

REST API

2021-06-18

REST API

2021-06-03

REST API

2021-05-11

REST API

2021-05-11

REST API

2021-04-22

REST API

2021-04-07

REST API

2021-04-02

REST API

2021-03-24

2021-03-22

2021-03-15

REST API

2021-03-12

REST API

2021-03-11

2021-03-04

2021-02-02

Websocket API

2021-01-25

REST API

2021-01-12

REST API

2020-12-31

REST API

After a service upgrade, a number of v2 endpoints have been added to replace the old routes:

2020-12-17

REST API

2020-11-20

REST API

2020-11-12

REST API

2020-11-10

Websocket API

The abandoned endpoints will be deprecated on November 30, 2020

REST API

The following REST API will be upgraded. The abandoned endpoints will be deprecated on December 10, 2020. Effective immediately, the rate limit will be reduced by half before being completely removed from service on December 17, 2020.

2020

2020-11-02

REST API

2020-10-26

REST API

2020-10-21

REST API

2020-10-12

REST API

2020-09-27

REST API

Websocket API

2020-09-15

REST API

2020-08-19

REST API

2020-07-07

REST API

2020-06-22

REST API

2020-05-21

REST API

2020-04-29

REST API

2020-04-27

REST API

2020-04-17

REST API

2020-04-14

REST API

2020-03-31

REST API

2020-03-26

REST API

2020-03-16

REST API

2020-03-09

REST API

2020-03-02

Websocket API

2020-02-26

REST API

2020-02-10

REST API

2019

2019-12-27

REST API

2019-12-18

REST API

Websocket API

2019-12-13

REST API

2019-12-02

REST API

2019-11-19

REST API

2019-11-07

REST API

2019-11-04

REST API

Websocket API

2019-10-22

REST API

Websocket API

FAQ

reduce_only and close_on_trigger - what's the difference?

Why aren't all my orders showing on the website?

Calculating order size based on available wallet balance

Can I exchange assets with the API?

Where are Bybit's servers located?

AWS Singapore, Availability Zone ID apse1-az3.

How do I get funds for testnet?

To get testnet funds, please contact the website's customer support using the yellow support button shown in the bottom-right corner.

Why are my Closed PNL prices inaccurate?

Why are values returned to too many decimal places? (float precision issue)

Authentication

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

Parameters for Authenticated Endpoints

The following parameters must be used for authentication:

We also provide recv_window (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 recv_window is more secure, but your request may fail if the transmission time is greater than your recv_window.

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

Create A Request

An example for adjusting leverage

param_str = "api_key=B2Rou0PLPpGqcU0Vu2&leverage=100&symbol=BTCUSD&timestamp=1542434791747"

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

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

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

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

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

GET /v2/private/order?symbol=BTCUSD&api_key=B2Rou0PLPpGqcU0Vu2&timestamp=1542434791000&sign=670e3e4aa32b243f2dedf1dafcec2fd17a440e71b05681550416507de591d908 HTTP/1.1
Host: api-testnet.bybit.com

Message format for POST requests:

POST /v2/private/order/cancel HTTP/1.1
Host: api-testnet.bybit.com
Content-Type: application/json

{
    "api_key": "B2Rou0PLPpGqcU0Vu2",
    "symbol": "BTCUSD",
    "order_id": "3bd1844f-f3c0-4e10-8c25-10fea03763f6",
    "timestamp": 1542434791000,
    "sign": "670e3e4aa32b243f2dedf1dafcec2fd17a440e71b05681550416507de591d908"
}

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.

Order Book

Request Example

curl https://api.bybit.com/v2/public/orderBook/L2?symbol=BTCUSD
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.Market.Market_orderbook(symbol="BTCUSD").result())

Response Example

{
    "ret_code": 0,                              // return code
    "ret_msg": "OK",                            // error message
    "ext_code": "",                             // additional error code
    "ext_info": "",                             // additional error info
    "result": [
        {
            "symbol": "BTCUSD",                 // symbol
            "price": "9487",                    // price
            "size": 336241,                     // size (in USD contracts)
            "side": "Buy"                       // side
        },
        {
            "symbol": "BTCUSD",                 // symbol
            "price": "9487.5",                  // price
            "size": 522147,                     // size (in USD contracts)
            "side": "Sell"                      // side
        }
    ],
    "time_now": "1567108756.834357"             // UTC timestamp
}

Get the orderbook. Each side has a depth of 50.

HTTP Request

GET /v2/public/orderBook/L2

Request Parameters

Parameter Required Type Comment
symbol true string Symbol

Response Parameters

Parameter Type Comment
symbol string Symbol
price string Order price
size integer Symbol contracts
side string Side

Query Kline

Request Example

curl https://api.bybit.com/v2/public/kline/list?symbol=BTCUSD&interval=1&limit=2&from=1581231260
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.Kline.Kline_get(symbol="BTCUSD", interval="m", **{'from':1581231260}).result())

Response Example

{
    "ret_code": 0,
    "ret_msg": "OK",
    "ext_code": "",
    "ext_info": "",
    "result": [{
        "symbol": "BTCUSD",
        "interval": "1",
        "open_time": 1581231300,
        "open": "10112.5",
        "high": "10112.5",
        "low": "10112",
        "close": "10112",
        "volume": "75981",
        "turnover": "7.51394369"
    }, {
        "symbol": "BTCUSD",
        "interval": "1",
        "open_time": 1581231360,
        "open": "10112",
        "high": "10112.5",
        "low": "10112",
        "close": "10112",
        "volume": "24616",
        "turnover": "2.4343353100000003"
    }],
    "time_now": "1581928016.558522"
}

Get kline.

HTTP Request

GET /v2/public/kline/list

Request Parameters

parameter Required Type Comment
symbol true string Symbol
interval true string Data refresh interval. Enum : 1 3 5 15 30 60 120 240 360 720 "D" "M" "W"
from true integer From timestamp in seconds
limit false integer Limit for data size per page, max size is 200. Default as showing 200 pieces of data per page

Response Parameters

Parameter Type Comment
symbol string Symbol
interval string Data refresh interval. Enum : 1 3 5 15 30 60 120 240 360 720 "D" "M" "W"
open_time integer Starting time
open string Starting price
high string Maximum price
low string Minimum price
close string Closing price
volume string Trading volume
turnover string Transaction amount

Latest Information for Symbol

Request Example

curl https://api.bybit.com/v2/public/tickers
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.Market.Market_symbolInfo().result())

Response Example

{
    "ret_code": 0,
    "ret_msg": "OK",
    "ext_code": "",
    "ext_info": "",
    "result": [
        {
            "symbol": "BTCUSD",
            "bid_price": "7230",
            "ask_price": "7230.5",
            "last_price": "7230.00",
            "last_tick_direction": "ZeroMinusTick",
            "prev_price_24h": "7163.00",
            "price_24h_pcnt": "0.009353",
            "high_price_24h": "7267.50",
            "low_price_24h": "7067.00",
            "prev_price_1h": "7209.50",
            "price_1h_pcnt": "0.002843",
            "mark_price": "7230.31",
            "index_price": "7230.14",
            "open_interest": 117860186,
            "open_value": "16157.26",
            "total_turnover": "3412874.21",
            "turnover_24h": "10864.63",
            "total_volume": 28291403954,
            "volume_24h": 78053288,
            "funding_rate": "0.0001",
            "predicted_funding_rate": "0.0001",
            "next_funding_time": "2019-12-28T00:00:00Z",
            "countdown_hour": 2,
            "delivery_fee_rate": "0",
            "predicted_delivery_price": "0.00",
            "delivery_time": ""
        },
        {
            "symbol": "BTCUSDM21",
            "bid_price": "67895",
            "ask_price": "67895.5",
            "last_price": "67895.50",
            "last_tick_direction": "ZeroPlusTick",
            "prev_price_24h": "68073.00",
            "price_24h_pcnt": "-0.002607",
            "high_price_24h": "69286.50",
            "low_price_24h": "66156.00",
            "prev_price_1h": "68028.50",
            "price_1h_pcnt": "-0.001955",
            "mark_price": "67883.88",
            "index_price": "62687.89",
            "open_interest": 531821673,
            "open_value": "0.00",
            "total_turnover": "85713.36",
            "turnover_24h": "2371.47",
            "total_volume": 5352251354,
            "volume_24h": 160716002,
            "funding_rate": "0",
            "predicted_funding_rate": "0",
            "next_funding_time": "",
            "countdown_hour": 0,
            "delivery_fee_rate": "0.0005",
            "predicted_delivery_price": "0.00",
            "delivery_time": "2021-06-25T08:00:00Z"
        }
    ],
    "time_now": "1577484619.817968"
}

Get the latest information for symbol.

HTTP Request

GET /v2/public/tickers

Request Parameters

Parameter Required Type Comment
symbol false string Symbol

Response Parameters

Parameter Type Comment
symbol string Symbol
bid_price string Purchase price of the first order
ask_price string Selling price of the first order
last_price string Latest transaction price
tick_direction string Direction of price change
prev_price_24h string Price of 24 hours ago
price_24h_pcnt string Percentage change of market price relative to 24h
high_price_24h string The highest price in the last 24 hours
low_price_24h string Lowest price in the last 24 hours
prev_price_1h string Hourly market price an hour ago
price_1h_pcnt string Percentage change of market price relative to 1 hour ago
mark_price string Mark price
index_price string Index_price
open_interest number Open interest
open_value string Open position value
total_turnover string Total turnover
turnover_24h string Turnover for 24H
total_volume number Total volume
volume_24h number Trading volume in the last 24 hours
funding_rate string Funding rate
predicted_funding_rate string Predicted funding rate
next_funding_time string Next settlement time of capital cost
countdown_hour number Countdown of settlement capital cost
delivery_fee_rate string Delivery fee rate of Futures contract
predicted_delivery_price string Predicted delivery price of Futures contract
delivery_time string Delivery time of Futures contract

Public Trading Records

Request Example

curl https://api.bybit.com/v2/public/trading-records?symbol=BTCUSD
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.Market.Market_tradingRecords(symbol="BTCUSD").result())

Response Example

{
    "ret_code": 0,                                   // error code 0 means success
    "ret_msg": "OK",                                 // error message
    "ext_code": "",
    "ext_info": "",
    "result": [
        {
            "id": 7724919,                                   // ID
            "symbol": "BTCUSD",                             // contract type
            "price": 9499.5,                                // execution price
            "qty": 9500,                                    // execution quantity
            "side": "Buy",                                  // side
            "time": "2019-11-19T08:03:04.077Z"              // UTC time
        }
    ],
    "time_now": "1567109419.049271"
}

Get recent trades. You can find a complete history of trades on Bybit here.

HTTP Request

GET /v2/public/trading-records

Request Parameters

Parameter Required Type Comment
symbol true string Symbol
from false int From ID. Default: return latest data
limit false int Limit for data size, max size is 1000. Default size is 500

Response Parameters

Parameter Type Comment
id number Latest data ID
symbol string Symbol
price number Execution price
qty number Order quantity in USD
side string Side
time string UTC time

Query Symbol

Request Example

curl https://api.bybit.com/v2/public/symbols
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.Symbol.Symbol_get().result())

Response Example

{
    "ret_code":0,
    "ret_msg":"OK",
    "ext_code":"",
    "ext_info":"",
    "result":[
        {
            "name":"BTCUSD",
            "alias":"BTCUSD",
            "status":"Trading",
            "base_currency":"BTC",
            "quote_currency":"USD",
            "price_scale":2,
            "taker_fee":"0.00075",
            "maker_fee":"-0.00025",
            "leverage_filter":{
                "min_leverage":1,
                "max_leverage":100,
                "leverage_step":"0.01"
            },
            "price_filter":{
                "min_price":"0.5",
                "max_price":"999999.5",
                "tick_size":"0.5"
            },
            "lot_size_filter":{
                "max_trading_qty":1000000,
                "min_trading_qty":1,
                "qty_step":1
            }
        },
        {
            "name":"EOSUSD",
            "alias":"EOSUSD",
            "status":"Trading",
            "base_currency":"EOS",
            "quote_currency":"USD",
            "price_scale":3,
            "taker_fee":"0.00075",
            "maker_fee":"-0.00025",
            "leverage_filter":{
                "min_leverage":1,
                "max_leverage":50,
                "leverage_step":"0.01"
            },
            "price_filter":{
                "min_price":"0.001",
                "max_price":"1999.999",
                "tick_size":"0.001"
            },
            "lot_size_filter":{
                "max_trading_qty":1000000,
                "min_trading_qty":1,
                "qty_step":1
            }
        },
        {
            "name":"BTCUSDT",
            "alias":"BTCUSDT",
            "status":"Trading",
            "base_currency":"BTC",
            "quote_currency":"USDT",
            "price_scale":2,
            "taker_fee":"0.00075",
            "maker_fee":"-0.00025",
            "leverage_filter":{
                "min_leverage":1,
                "max_leverage":100,
                "leverage_step":"0.01"
            },
            "price_filter":{
                "min_price":"0.5",
                "max_price":"999999.5",
                "tick_size":"0.5"
            },
            "lot_size_filter":{
                "max_trading_qty":100,
                "min_trading_qty":0.001,
                "qty_step":0.001
            }
        },
        {
            "name":"BTCUSDM21",
            "alias":"BTCUSD0625",
            "status":"Trading",
            "base_currency":"BTC",
            "quote_currency":"USD",
            "price_scale":2,
            "taker_fee":"0.00075",
            "maker_fee":"-0.00025",
            "leverage_filter":{
                "min_leverage":1,
                "max_leverage":100,
                "leverage_step":"0.01"
            },
            "price_filter":{
                "min_price":"0.5",
                "max_price":"999999.5",
                "tick_size":"0.5"
            },
            "lot_size_filter":{
                "max_trading_qty":1000000,
                "min_trading_qty":1,
                "qty_step":1
            }
        }
    ],
    "time_now":"1615801223.589808"
}

Get symbol info.

HTTP Request

GET /v2/public/symbols

Request Parameters

parameter Required Type Comment

Response Parameters

Parameter Type Comment
name string Symbol name
alias string Symbol name
status string Symbol status
base_currency string Base currency
quote_currency string Quote currency
price_scale number Price scale (how many decimal places the price of a symbol has)
taker_fee string Taker fee
maker_fee string Maker fee
leverage_filter > min_leverage number Min leverage
leverage_filter > max_leverage number Max leverage
leverage_filter > leverage_step string Leverage step
price_filter > min_price string Min price
price_filter > max_price string Max price
price_filter > tick_size string Tick size
lot_size_filter > max_trading_qty number Max trading quantity
lot_size_filter > min_trading_qty number Min trading quantity
lot_size_filter > qty_step number Qty step

Query Mark Price Kline

Request Example

curl "https://api.bybit.com/v2/public/mark-price-kline?symbol=BTCUSD&interval=1&limit=2&from=1581231260"
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.Kline.Kline_markPrice(symbol="BTCUSD", interval="30",limit=200, **{'from':1600544880}).result())

Response Example


{
    "ret_code":0,
    "ret_msg":"OK",
    "ext_code":"",
    "ext_info":"",
    "result":[
        {
            "id":2,
            "symbol":"BTCUSD",
            "period":"1",
            "start_at":1582231260,
            "open":100,
            "high":120,
            "low":88,
            "close":115
        }
    ],
    "time_now":"1591263582.601795"
}

Query mark price kline (like Query Kline but for mark price).

HTTP Request

GET /v2/public/mark-price-kline

Request Parameters

parameter Required Type Comment
symbol true string Symbol
interval true string Data refresh interval. Enum : 1 3 5 15 30 60 120 240 360 720 "D" "M" "W"
from true integer From timestamp in seconds
limit false integer Limit for data size, max size is 200. Default as showing 200 pieces of data

Response Parameters

Parameter Type Comment
symbol string Symbol
period string Data recording period. 5min, 15min, 30min, 1h, 4h, 1d
start_at integer Start timestamp point for result, in seconds
open integer Starting price
high integer Maximum price
low integer Minimum price
close integer Closing price

Query Index Price Kline

Request Example

curl "https://api.bybit.com/v2/public/index-price-kline?symbol=BTCUSD&interval=1&limit=2&from=1581231260"
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.Kline.Kline_indexPrice(symbol="BTCUSD", interval="1", **{'from':1615067084}).result())

Response Example

{
    "ret_code":0,
    "ret_msg":"OK",
    "ext_code":"",
    "ext_info":"",
    "result":[
        {
            "symbol":"BTCUSD",
            "period":"1",
            "open_time":1582231260,
            "open":"10106.09",
            "high":"10108.75",
            "low":"10104.66",
            "close":"10108.73"
        }
    ],
    "time_now":"1591263582.601795"
}

Index price kline. Tracks BTC spot prices, with a frequency of every second (learn more here).

HTTP Request

GET /v2/public/index-price-kline

Request Parameters

parameter Required Type Comment
symbol true string Symbol
interval true string Data refresh interval. Enum : 1 3 5 15 30 60 120 240 360 720 "D" "M" "W"
from true integer From timestamp in seconds
limit false integer Limit for data size, max size is 200. Default as showing 200 pieces of data

Response Parameters

Parameter Type Comment
symbol string Symbol
period string Data recording period. 5min, 15min, 30min, 1h, 4h, 1d
open_time integer Start timestamp point for result, in seconds
open string Starting price
high string Maximum price
low string Minimum price
close string Closing price

Query Premium Index Kline

Request Example

curl "https://api.bybit.com/v2/public/premium-index-kline?symbol=BTCUSD&interval=1&limit=2&from=1581231260"
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.Kline.Kline_premiumIndexPrice(symbol="BTCUSD", interval="1", **{'from':1615067084}).result())

Response Example

{
    "ret_code":0,
    "ret_msg":"OK",
    "ext_code":"",
    "ext_info":"",
    "result":[
        {
            "symbol":"BTCUSD",
            "period":"1",
            "open_time":1582231260,
            "open":"0.000588",
            "high":"0.000618",
            "low":"0.000588",
            "close":"0.000618"
        }
  ],
    "time_now":"1591263582.601795"
}

Premium index kline. Tracks the premium / discount of BTC perpetual contracts relative to the mark price per minute (learn more here).

HTTP Request

GET /v2/public/premium-index-kline

Request Parameters

parameter Required Type Comment
symbol true string Symbol
interval true string Data refresh interval. Enum : 1 3 5 15 30 60 120 240 360 720 "D" "M" "W"
from true integer From timestamp in seconds
limit false integer Limit for data size, max size is 200. Default as showing 200 pieces of data

Response Parameters

Parameter Type Comment
symbol string Symbol
period string Data recording period. 5min, 15min, 30min, 1h, 4h, 1d
open_time integer Start timestamp point for result, in seconds
open string Starting price
high string Maximum price
low string Minimum price
close string Closing price

Advanced Data

Open Interest

Request Example

curl https://api.bybit.com/v2/public/open-interest?symbol=BTCUSD&period=5min
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.Market.Market_openInterest(symbol="BTCUSD", limit=2, period="5min").result())

Response Example

{
    "ret_code":0,
    "ret_msg":"OK",
    "ext_code":"",
    "ext_info":"",
    "result":[
        {
            "open_interest":371491978,
            "timestamp":1597658100,
            "symbol":"BTCUSD"
        },
        {
            "open_interest":370696076,
            "timestamp":1597657800,
            "symbol":"BTCUSD"
        }
    ],
    "time_now":"1597658304.938839"
}

Gets the total amount of unsettled contracts. In other words, the total number of contracts held in open positions.

HTTP Request

GET /v2/public/open-interest

Request Parameters

Parameter Required Type Comment
symbol true string Symbol
period true string Data recording period. 5min, 15min, 30min, 1h, 4h, 1d
limit false int Limit for data size per page, max size is 200. Default as showing 50 pieces of data per page

Response Parameters

Parameter Type Comment
open_interest number Number of contracts in open interest
timestamp number Timestamp
symbol string Symbol

Latest Big Deal

Request Example

curl https://api.bybit.com/v2/public/big-deal?symbol=BTCUSD
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.Market.Market_bigDeal(symbol="BTCUSD", limit=2).result())

Response Example

{
    "ret_code":0,
    "ret_msg":"OK",
    "ext_code":"",
    "ext_info":"",
    "result":[
        {
            "symbol":"BTCUSD",
            "side":"Sell",
            "timestamp":1597623362,
            "value":1242368
        },
        {
            "symbol":"BTCUSD",
            "side":"Buy",
            "timestamp":1597623363,
            "value":1242368
        }
    ],
    "time_now":"1597658434.219859"
}

Obtain filled orders worth more than 500,000 USD within the last 24h.

This endpoint may return orders which are over the maximum order qty for the symbol you call. For instance, the maximum order qty for BTCUSD is 1 million contracts, but in the event of the liquidation of a position larger than 1 million this endpoint returns this "impossible" order size.

HTTP Request

GET /v2/public/big-deal

Request Parameters

Parameter Required Type Comment
symbol true string Symbol
limit false int Limit for data size per page, max size is 1000. Default as showing 500 pieces of data per page

Response Parameters

Parameter Type Comment
symbol string Symbol
side string Side
timestamp number Timestamp
value number Value of the order

Long-Short Ratio

Request Example

curl https://api.bybit.com/v2/public/account-ratio?symbol=BTCUSD&period=5min
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.Market.Market_accountRatio(symbol="BTCUSD", limit=2, period="5min").result())

Response Example

{
    "ret_code":0,
    "ret_msg":"OK",
    "ext_code":"",
    "ext_info":"",
    "result":[
        {
            "symbol":"BTCUSD",
            "buy_ratio":0.6538,
            "sell_ratio":0.3462,
            "timestamp":1597659000
        },
        {
            "symbol":"BTCUSD",
            "buy_ratio":0.6533,
            "sell_ratio":0.3467,
            "timestamp":1597658700
        }
    ],
    "time_now":"1597659230.743313"
}

Gets the Bybit user accounts' long-short ratio.

HTTP Request

GET /v2/public/account-ratio

Request Parameters

Parameter Required Type Comment
symbol true string Symbol
period true string Data recording period. 5min, 15min, 30min, 1h, 4h, 1d
limit false int Limit for data size per page, max size is 500. Default as showing 50 pieces of data per page

Response Parameters

Parameter Type Comment
symbol string Symbol
buy_ratio number Long position ratio
sell_ratio number Short position ratio
timestamp number Timestamp

Account Data Endpoints

The following account data endpoints require authentication.

Active Orders

Place Active Order

Request Example

curl https://api.bybit.com/v2/private/order/create \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","side":"Buy","symbol":"BTCUSD","order_type":"Market","qty":10,"time_in_force":"GoodTillCancel","timestamp":{timestamp},"sign":"{sign}"}'

import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.Order.Order_new(side="Buy",symbol="BTCUSD",order_type="Market",qty=1,time_in_force="GoodTillCancel").result())

Response Example

{
    "ret_code": 0,
    "ret_msg": "OK",
    "ext_code": "",
    "ext_info": "",
    "result": {
        "user_id": 1,
        "order_id": "335fd977-e5a5-4781-b6d0-c772d5bfb95b",
        "symbol": "BTCUSD",
        "side": "Buy",
        "order_type": "Limit",
        "price": 8800,
        "qty": 1,
        "time_in_force": "GoodTillCancel",
        "order_status": "Created",
        "last_exec_time": 0,
        "last_exec_price": 0,
        "leaves_qty": 1,
        "cum_exec_qty": 0,
        "cum_exec_value": 0,
        "cum_exec_fee": 0,
        "reject_reason": "",
        "order_link_id": "",
        "created_at": "2019-11-30T11:03:43.452Z",
        "updated_at": "2019-11-30T11:03:43.455Z"
    },
    "time_now": "1575111823.458705",
    "rate_limit_status": 98,
    "rate_limit_reset_ms": 1580885703683,
    "rate_limit": 100
}

Market price active order: A traditional market price order which will be filled at the best available price. price is not required for this type of order. To protect market order from excessive slippage, Bybit converts a market order into a limit order with a spread. A market buy order is converted into a limit order at a higher than best ask price; a market sell order is converted into a limit order at a lower than best bid price. The converted limit price and executed price are both available in trade history..

Limit price active order: You can set an execution price for your order. Only when the last traded price reaches the order price will the system will fill your order.

Take profit/Stop loss: You may only set a TP/SL conditional order upon opening the position. Once you hold a position, any new active order requests which contain TP/SL data will be accepted but the TP/SL data will be ignored. tp_trigger_by/sl_trigger_by default to LastPrice. Passing values to the take_profit or stop_loss parameters in this endpoint will create conditional orders managed by the system, which will be be automatically cancelled if the position is closed.

Order quantity: This parameter indicates the quantity of perpetual contracts you want to buy or sell. All USD markets have a contract size of 1 USD. See more

Order price: If it is a conditional order, this parameter is required. When there is no position, the long commission price should be 10% higher than the market price and less than 1 million. If there are positions, they need to be better than strong parity. For the minimum unit of price increase or decrease, please refer to the price_filter field in the Query Symbols endpoint. This must modulo by 0.5 (20 and 21.5 are accepted, but 16.1 or 16.15 are not).

Custom order ID: You may customise order IDs for active orders. We will link it to the system order ID, and return the unique system order ID to you after the active order is created successfully. You may use this order ID or your custom order ID to cancel your active order. The customised order ID should be unique, with a maximum length of 36 characters.

Each account can hold up to 500 active orders yet to be filled entirely simultaneously. This is per instrument, so it's possible to have, for example, 300 active orders on the BTCUSD instrument and 280 active orders on the ETHUSD instrument.

HTTP Request

POST /v2/private/order/create

Request Parameters

Parameter Required Type Comment
side true string Side
symbol true string Symbol
order_type true string Active order type
qty true integer Order quantity in USD
price false number Order price
time_in_force true string Time in force
close_on_trigger false bool What is a close on trigger order? For a closing order. It can only reduce your position, not increase it. If the account has insufficient available balance when the closing order is triggered, then other active orders of similar contracts will be cancelled or reduced. It can be used to ensure your stop loss reduces your position regardless of current available margin.
order_link_id false string Unique user-set order ID. Maximum length of 36 characters
take_profit false number Take profit price, only take effect upon opening the position
stop_loss false number Stop loss price, only take effect upon opening the position
tp_trigger_by false string Take profit trigger price type, default: LastPrice
sl_trigger_by false string Stop loss trigger price type, default: LastPrice
reduce_only false bool What is a reduce-only order? True means your position can only reduce in size if this order is triggered

Response Parameters

Parameter Type Comment
user_id number UserID
order_id string Order ID
symbol string Symbol
side string Side
order_type string Order type
price number Order price
qty number Order quantity in USD
time_in_force string Time in force
order_status string Order status
last_exec_time string Last execution time
last_exec_price string Last execution price
leaves_qty number Number of unfilled contracts from the order's size
cum_exec_qty number Cumulative qty of trading
cum_exec_value number Cumulative value of trading
cum_exec_fee number Cumulative trading fees
reject_reason string The reason the order was rejected
order_link_id string Customised order ID
created_at string Creation time
updated_at string Update time
take_profit number Take profit price
stop_loss number Stop loss price
tp_trigger_by string Take profit trigger price type, default: LastPrice
sl_trigger_by string Stop loss trigger price type, default: LastPrice

Get Active Order

Request Example

curl "https://api.bybit.com/v2/private/order/list?api_key={api_key}&timestamp={timestamp}&sign={sign}&symbol=BTCUSD"
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.Order.Order_getOrders(symbol="BTCUSD",order_status="New").result())

Response Example

{
    "ret_code": 0,
    "ret_msg": "OK",
    "ext_code": "",
    "ext_info": "",
    "result": {
        "data": [
            {
                "user_id": 160861,
                "order_status": "Cancelled",
                "symbol": "BTCUSD",
                "side": "Buy",
                "order_type": "Market",
                "price": "9800",
                "qty": "16737",
                "time_in_force": "ImmediateOrCancel",
                "order_link_id": "",
                "order_id": "fead08d7-47c0-4d6a-b9e7-5c71d5df8ba1",
                "created_at": "2020-07-24T08:22:30Z",
                "updated_at": "2020-07-24T08:22:30Z",
                "leaves_qty": "0",
                "leaves_value": "0",
                "cum_exec_qty": "0",
                "cum_exec_value": "0",
                "cum_exec_fee": "0",
                "reject_reason": "EC_NoImmediateQtyToFill"
            }
        ],
        "cursor": "w01XFyyZc8lhtCLl6NgAaYBRfsN9Qtpp1f2AUy3AS4+fFDzNSlVKa0od8DKCqgAn"
    },
    "time_now": "1604653633.173848",
    "rate_limit_status": 599,
    "rate_limit_reset_ms": 1604653633171,
    "rate_limit": 600
}

Get my active order list.

Because order creation/cancellation is asynchronous, there can be a data delay in this endpoint. You can get real-time order info with the Query Active Order (real-time) endpoint.

HTTP Request

GET /v2/private/order/list

Request Parameters

Parameter Required Type Comment
symbol true string Symbol
order_status false string Queries orders of all statuses if order_status not provided. If you want to query orders with specific statuses, you can pass the order_status split by ',' (eg Filled,New).
direction false string Search direction. prev: prev page, next: next page. Defaults to next
limit false integer Limit for data size per page, max size is 50. Default as showing 20 pieces of data per page
cursor false string Page turning mark. Use return cursor. Sign using origin data, in request please use urlencode

Response Parameters

Parameter Type Comment
data > user_id integer UserID
data > symbol string Symbol
data > side string Side
data > order_type string Order type
data > price string Order price
data > qty string Order quantity in USD
data > time_in_force string Time in force
data > order_status string Order status
data > leaves_qty string Number of unfilled contracts from the order's size
data > leaves_value string The estimated value corresponding to the number of remaining orders
data > cum_exec_qty string Cumulative qty of trading
data > cum_exec_value string Cumulative value of trading
data > cum_exec_fee string Cumulative trading fees
data > reject_reason string The reason the order was rejected
data > order_link_id string Customised order ID
data > created_at string Creation time
data > order_id string Order ID
data > take_profit number Take profit price
data > stop_loss number Stop loss price
data > tp_trigger_by string Take profit trigger price type, default: LastPrice
data > sl_trigger_by string Stop loss trigger price type, default: LastPrice
cursor string Page turning mark

Cancel Active Order

Request Example

curl https://api.bybit.com/v2/private/order/cancel \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","symbol":"BTCUSD","order_id":"","timestamp":{timestamp},"sign":"{sign}"}'
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.Order.Order_cancel(symbol="BTCUSD", order_id="").result())

Response Example

{
    "ret_code": 0,
    "ret_msg": "OK",
    "ext_code": "",
    "ext_info": "",
    "result": {
        "user_id": 1,
        "order_id": "3bd1844f-f3c0-4e10-8c25-10fea03763f6",
        "symbol": "BTCUSD",
        "side": "Buy",
        "order_type": "Limit",
        "price": 8800,
        "qty": 1,
        "time_in_force": "GoodTillCancel",
        "order_status": "New",
        "last_exec_time": 0,
        "last_exec_price": 0,
        "leaves_qty": 1,
        "cum_exec_qty": 0,
        "cum_exec_value": 0,
        "cum_exec_fee": 0,
        "reject_reason": "",
        "order_link_id": "",
        "created_at": "2019-11-30T11:17:18.396Z",
        "updated_at": "2019-11-30T11:18:01.811Z"
    },
    "time_now": "1575112681.814760",
    "rate_limit_status": 98,
    "rate_limit_reset_ms": 1580885703683,
    "rate_limit": 100
}

Either order_id or order_link_id are required for cancelling active orders. order_id - this unique 36 characters order ID was returned to you when the active order was created successfully.

You may cancel active orders that are unfilled or partially filled. Fully filled orders cannot be cancelled.

HTTP Request

POST /v2/private/order/cancel

Request Parameters

Parameter Required Type Comment
symbol true string Symbol
order_id false string Order ID. Required if not passing order_link_id
order_link_id false string Unique user-set order ID. Required if not passing order_id

Response Parameters

Parameter Type Comment
user_id number UserID
order_id string Order ID
symbol string Symbol
side string Side
order_type string Order type
price number Order price
qty number Order quantity in USD
time_in_force string Time in force
order_status string Order status
last_exec_time string Last execution time
last_exec_price string Last execution price
leaves_qty number Number of unfilled contracts from the order's size
cum_exec_qty number Cumulative qty of trading
cum_exec_value number Cumulative value of trading
cum_exec_fee number Cumulative trading fees
reject_reason string The reason the order was rejected
order_link_id string Customised order ID
created_at string Creation time
updated_at string Update time
take_profit number Take profit price
stop_loss number Stop loss price
tp_trigger_by string Take profit trigger price type, default: LastPrice
sl_trigger_by string Stop loss trigger price type, default: LastPrice

Cancel All Active Orders

Request Example

curl https://api.bybit.com/v2/private/order/cancelAll \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","symbol":"BTCUSD","timestamp":{timestamp},"sign":"{sign}"}'
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.Order.Order_cancelAll(symbol="BTCUSD").result())

Response Example

{
    "ret_code": 0,      
    "ret_msg": "OK",    
    "ext_code": "",     
    "ext_info": "",
    "result": [
        {
            "clOrdID": "89a38056-80f1-45b2-89d3-4d8e3a203a79",  
            "user_id": 1,                                  
            "symbol": "BTCUSD",                                
            "side": "Buy",                                      
            "order_type": "Limit",                              
            "price": "7693.5",                                  
            "qty": 1,                                           
            "time_in_force": "GoodTillCancel",                  
            "create_type": "CreateByUser",                     
            "cancel_type": "CancelByUser",                      
            "order_status": "",                                 
            "leaves_qty": 1,                                    
            "leaves_value": "0",                                
            "created_at": "2019-11-30T10:38:53.564428Z",        
            "updated_at": "2019-11-30T10:38:59.102589Z",        
            "cross_status": "PendingCancel",  // `PendingCancel` means the matching engine received the cancellation but there is no guarantee that the cancellation will be successful.
            "cross_seq": 387734027                              
        }
    ],
    "time_now": "1575110339.105675",
    "rate_limit_status": 98,
    "rate_limit_reset_ms": 1580885703683,
    "rate_limit": 100
}

Cancel all active orders that are unfilled or partially filled. Fully filled orders cannot be cancelled.

HTTP Request

POST /v2/private/order/cancelAll

Request Parameters

Parameter Required Type Comment
symbol true string Symbol

Response Parameters

Parameter Type Comment
clOrdID string A unique order number of type UUID
user_id number UserID
symbol string Symbol
side string Side
order_type string Order type
price number Order price
qty number Order quantity in USD
time_in_force string Time in force
create_type string Trigger scenario for single action
cancel_type string Trigger scenario for cancel operation
order_status string Order status
leaves_qty number Number of unfilled contracts from the order's size
leaves_value number The estimated value corresponding to the number of remaining orders
created_at string Creation time
updated_at string Update time
cross_status string The state of initiating a matchmaking request
cross_seq number Cross sequence (internal value)

Replace Active Order

Request Example

curl https://api.bybit.com/v2/private/order/replace \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","symbol":"BTCUSD","order_id":"","timestamp":{timestamp},"sign":"{sign}"}'
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.Order.Order_replace(symbol="BTCUSD", order_id="").result())

Response Example

{
    "ret_code": 0,    //Error code,
    "ret_msg": "ok",  //Error message,
    "ext_code": "",
    "result": {
        "order_id": "efa44157-c355-4a98-b6d6-1d846a936b93"
    },
    "time_now": "1539778407.210858",    // UTC timestamp
    "rate_limit_status": 99, // The remaining number of accesses in one minute
    "rate_limit_reset_ms": 1580885703683,
    "rate_limit": 100             
}

Replace order can modify/amend your active orders.

p_r_qty and p_r_price are the modified price and quantity. If these two fields are not provided, nothing will be modified.

HTTP Request

POST /v2/private/order/replace

Request Parameters

Parameter Required Type Comment
order_id false string Order ID. Required if not passing order_link_id
order_link_id false string Unique user-set order ID. Required if not passing order_id
symbol true string Symbol.
p_r_qty false integer New order quantity. Do not pass this field if you don't want modify it
p_r_price false string New order price. Do not pass this field if you don't want modify it
take_profit false number New take_profit price, also known as stop_px. Do not pass this field if you don't want modify it
stop_loss false number New stop_loss price, also known as stop_px. Do not pass this field if you don't want modify it
tp_trigger_by false string Take profit trigger price type, default: LastPrice
sl_trigger_by false string Stop loss trigger price type, default: LastPrice

Response Parameters

Parameter Type Comment
order_id string Order ID

Query Active Order (real-time)

Request Example

curl "https://api.bybit.com/v2/private/order?api_key={api_key}&symbol=BTCUSD&timestamp={timestamp}order_id={order_id}&sign={sign}"
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.Order.Order_query(symbol="BTCUSD", order_id="").result())

Response Example

{
    "ret_code": 0,
    "ret_msg": "OK",
    "ext_code": "",
    "ext_info": "",
    "result": {
        "user_id": 106958,
        "symbol": "BTCUSD",
        "side": "Buy",
        "order_type": "Limit",
        "price": "11756.5",
        "qty": 1,
        "time_in_force": "PostOnly",
        "order_status": "Filled",
        "ext_fields": {
            "o_req_num": -68948112492,
            "xreq_type": "x_create"
        },
        "last_exec_time": "1596304897.847944",
        "last_exec_price": "11756.5",
        "leaves_qty": 0,
        "leaves_value": "0",
        "cum_exec_qty": 1,
        "cum_exec_value": "0.00008505",
        "cum_exec_fee": "-0.00000002",
        "reject_reason": "",
        "cancel_type": "",
        "order_link_id": "",
        "created_at": "2020-08-01T18:00:26Z",
        "updated_at": "2020-08-01T18:01:37Z",
        "order_id": "e66b101a-ef3f-4647-83b5-28e0f38dcae0"
    },
    "time_now": "1597171013.867068",
    "rate_limit_status": 599,
    "rate_limit_reset_ms": 1597171013861,
    "rate_limit": 600
}

//When only symbol is passed, the response uses a different structure:

{
    "ret_code": 0,
    "ret_msg": "OK",
    "ext_code": "",
    "ext_info": "",
    "result": [
        {
            "user_id": 100228,
            "symbol": "BTCUSD",
            "side": "Sell",
            "order_type": "Limit",
            "price": "17740",
            "qty": 10,
            "time_in_force": "GoodTillCancel",
            "order_status": "New",
            "ext_fields": {
                "o_req_num": 434743,
                "xreq_type": "x_create"
            },
            "last_exec_time": "1608193181.827761",
            "leaves_qty": 10,
            "leaves_value": "0.00056369",
            "cum_exec_qty": 0,
            "cum_exec_value": "0.00008505",
            "cum_exec_fee": "-0.00000002",
            "reject_reason": "EC_NoError",
            "cancel_type": "UNKNOWN",
            "order_link_id": "",
            "created_at": "2020-12-17T08:19:41.827637283Z",
            "updated_at": "2020-12-17T08:19:41.827761Z",
            "order_id": "d570d931-771e-4911-a24e-cdeddedb5b0e"
        },
        ...
        {
            "user_id": 100228,
            "symbol": "BTCUSD",
            "side": "Sell",
            "order_type": "Limit",
            "price": "17740",
            "qty": 10,
            "time_in_force": "GoodTillCancel",
            "order_status": "New",
            "ext_fields": {
                "o_req_num": 434728,
                "xreq_type": "x_create"
            },
            "last_exec_time": "1608193178.955412",
            "leaves_qty": 10,
            "leaves_value": "0.00056369",
            "cum_exec_qty": 0,
            "cum_exec_value": "0.00008505",
            "cum_exec_fee": "-0.00000002",
            "reject_reason": "EC_NoError",
            "cancel_type": "UNKNOWN",
            "order_link_id": "",
            "created_at": "2020-12-17T08:19:38.955297869Z",
            "updated_at": "2020-12-17T08:19:38.955412Z",
            "order_id": "88b91101-7ac1-40af-90b8-72d53fe23622"
        }
    ],
    "time_now": "1608193190.911073",
    "rate_limit_status": 599,
    "rate_limit_reset_ms": 1608193190909,
    "rate_limit": 600
}

Query real-time active order information. If only order_id or order_link_id are passed, a single order will be returned; otherwise, returns up to 500 unfilled orders.

HTTP Request

GET /v2/private/order

Request Parameters

Parameter Required Type Comment
symbol true string Symbol
order_id false string Order ID
order_link_id false string Customised order ID

Response Parameters

Parameter Type Comment
user_id number UserID
symbol string Symbol
side string Side
order_type string Order type
price number Order price
qty number Order quantity in USD
time_in_force string Time in force
order_status string Order status
ext_fields json Extension field
leaves_qty number Number of unfilled contracts from the order's size
leaves_value number The estimated value corresponding to the number of remaining orders
cum_exec_qty number Cumulative qty of trading
cum_exec_value number Cumulative value of trading
cum_exec_fee order_link_id string
reject_reason string The reason the order was rejected
cancel_type string Trigger scenario for cancel operation
order_link_id string Customised order ID
created_at string Creation time
updated_at string Update time
order_id string Order ID
take_profit number Take profit price
stop_loss number Stop loss price
tp_trigger_by string Take profit trigger price type, default: LastPrice
sl_trigger_by string Stop loss trigger price type, default: LastPrice

Conditional Orders

Place Conditional Order

Request Example

curl https://api.bybit.com/v2/private/stop-order/create \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","order_type":"Limit","side":"Buy","symbol":"BTCUSD","qty":1,"price":8100,"base_price":8300,"stop_px":8150,"time_in_force":"GoodTillCancel","order_link_id":"cus_order_id_1","timestamp":{timestamp},"sign":"{sign}"}'
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.Conditional.Conditional_new(order_type="Limit",side="Buy",symbol="XRPUSD",qty="1",price="0.2569",base_price="15700",stop_px="0.2119",time_in_force="GoodTillCancel").result())

Response Example

{
    "ret_code":0,
    "ret_msg":"OK",
    "ext_code":"",
    "ext_info":"",
    "result":{
        "user_id":160880,
        "symbol":"BTCUSD",
        "side":"Buy",
        "order_type":"Limit",
        "price":"9003",
        "qty":"2",
        "time_in_force":"GoodTillCancel",
        "remark":"127.0.0.1",
        "leaves_qty":"2",
        "leaves_value":"0",
        "stop_px":"8232",
        "reject_reason":"EC_NoError",
        "stop_order_id":"eaf205ac-9dcc-44f6-8731-734e2101e61b",
        "created_at":"2020-11-06T07:48:43.940Z",
        "updated_at":"2020-11-06T07:48:43.940Z"
    },
    "time_now":"1604648923.942177"
}

Market price conditional order: A traditional market price order, will be filled at the best available price. price is not required for this type of order.

Limit price conditional order: You can set an execution price for your order. Only when the last traded price reaches the order price will the system will fill your order.

Take profit/Stop loss: You may only set a take-profit/stop-loss conditional order upon opening the position. Once you hold a position, the take profit and stop loss information you sent when placing an order will no longer be valid.

Order quantity: This parameter indicates the quantity of perpetual contracts you want to buy or sell, currently Bybit only support order quantity in an integer.

Order price: If it is a stop order, this parameter is required. When there is no position, the long commission price should be 10% higher than the market price and less than 1 million. If there are positions, they need to be better than strong parity. For the minimum unit of price increase or decrease, please refer to the price_filter field in the Query Symbols endpoint.

Conditional order trigger price: You may set a trigger price for your conditional order. conditional order will not enter the order book until the last price hits the trigger price. When last price hits trigger price: 1) your limit conditional order will enter order book, and wait to be executed; 2) your market conditional order will be executed immediately at the best available market price.

Customize conditional order ID: You may customize order IDs for active orders. We will link it to the system order ID , and return the unique system order ID to you after the active order is created successfully. You may use this order ID to cancel your active order. The customized order ID is asked to be unique, with a maximum length of 36 characters.

HTTP Request

POST /v2/private/stop-order/create

Request Parameters

Parameter Required Type Comment
side true string Side
symbol true string Symbol
order_type true string Conditional order type
qty true string Order quantity in USD
price false string Execution price for conditional order. Required if you make limit price order
base_price true string It will be used to compare with the value of stop_px, to decide whether your conditional order will be triggered by crossing trigger price from upper side or lower side. Mainly used to identify the expected direction of the current conditional order.
stop_px true string Trigger price
time_in_force true string Time in force
trigger_by false string Trigger price type. Default LastPrice
close_on_trigger false bool What is a close on trigger order? For a closing order. It can only reduce your position, not increase it. If the account has insufficient available balance when the closing order is triggered, then other active orders of similar contracts will be cancelled or reduced. It can be used to ensure your stop loss reduces your position regardless of current available margin.
order_link_id false string Unique user-set order ID. Maximum length of 36 characters
take_profit false number Take profit price
stop_loss false number Stop loss price
tp_trigger_by false string Take profit trigger price type, default: LastPrice
sl_trigger_by false string Stop loss trigger price type, default: LastPrice

Response Parameters

Parameter Type Comment
user_id integer UserID
symbol string Symbol
side string Side
order_type string Active order type
price string Order price
qty string Order quantity in USD
time_in_force string Time in force
trigger_by string Trigger price type. Default LastPrice
base_price string Market price at placing order
remark string Remark
reject_reason string The reason the order was rejected
stop_px string Trigger price
stop_order_id string Conditional order ID. Once triggered, the conditional order creates an active order with the same ID (order_id)
created_at string Creation time
order_link_id string Customised order ID
take_profit number Take profit price
stop_loss number Stop loss price
tp_trigger_by string Take profit trigger price type, default: LastPrice
sl_trigger_by string Stop loss trigger price type, default: LastPrice

Get Conditional Order

Request Example

curl "https://api.bybit.com/v2/private/stop-order/list?api_key={api_key}&timestamp={timestamp}&sign={sign}"
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.Conditional.Conditional_getOrders(symbol="BTCUSD",stop_order_status="Untriggered").result())

Response Example

{
    "ret_code": 0,
    "ret_msg": "OK",
    "ext_code": "",
    "ext_info": "",
    "result": {
        "data": [
            {
                "user_id": 160861,
                "stop_order_status": "Active",
                "symbol": "ETHUSD",
                "side": "Buy",
                "order_type": "Market",
                "stop_order_type": "TakeProfit",
                "price": "220",
                "qty": "120",
                "time_in_force": "ImmediateOrCancel",
                "base_price": "258",
                "order_link_id": "",
                "created_at": "2019-08-02T07:37:24Z",
                "updated_at": "2019-08-02T07:38:40Z",
                "stop_px": "224.3",
                "stop_order_id": "6d0dec74-f516-4d95-81f1-c85e60c9a331"
            }
        ],
        "cursor": "zZtvOJ0gc3UOxZOwotsJSZyMTOgyC9tj1DmFyUU6eNHUL0X4NLwZvo8iqI6ltPIc"
    },
    "time_now": "1604653512.292878",
    "rate_limit_status": 599,
    "rate_limit_reset_ms": 1604653512287,
    "rate_limit": 600
}

Get my conditional order list.

Because order creation/cancellation is asynchronous, there can be a data delay in this endpoint. You can get real-time order info with the Query Conditional Order (real-time) endpoint.

HTTP Request

GET /v2/private/stop-order/list

Request Parameters

Parameter Required Type Comment
symbol true string Symbol
stop_order_status false string Queries orders of all statuses if 'stop_order_status' not provided
direction false string Search direction. prev: prev page, next: next page. Defaults to next
limit false integer Limit for data size per page, max size is 50. Default as showing 20 pieces of data per page
cursor false string Page turning mark. Use return cursor. Sign using origin data, in request please use urlencode

Response Parameters

Parameter Type Comment
data > user_id integer UserID
data > stop_order_status string Stop order status
data > symbol string Symbol
data > side string Side
data > order_type string Active order type
data > price number Order price
data > qty number Order quantity in USD
data > time_in_force string Time in force
data > stop_order_type string Conditional order type
data > trigger_by string Trigger price type
data > base_price number Market price at placing order
data > order_link_id string Customised order ID
data > created_at string Creation time
data > updated_at string Update time
data > stop_px number Trigger price
data > stop_order_id string Conditional order ID. Once triggered, the conditional order creates an active order with the same ID (order_id)
data > take_profit number Take profit price
data > stop_loss number Stop loss price
data > tp_trigger_by string Take profit trigger price type, default: LastPrice
data > sl_trigger_by string Stop loss trigger price type, default: LastPrice
cursor string Page turning mark

Cancel Conditional Order

Request Example

curl https://api.bybit.com/v2/private/stop-order/cancel \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","symbol":"BTCUSD","stop_order_id":"xxx","timestamp":{timestamp},"sign":"{sign}"}'
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.Conditional.Conditional_cancel(symbol="BTCUSD", stop_order_id="").result())

Response Example

{
    "ret_code": 0,
    "ret_msg": "ok",
    "ext_code": "",
    "result": {
        "stop_order_id": "c1025629-e85b-4c26-b4f3-76e86ad9f8cb"
    },
    "ext_info": null,
    "time_now": "1577452218.567120",
    "rate_limit_status": 97,
    "rate_limit_reset_ms": 1577452218573,
    "rate_limit": "100"
}

You may cancel all untriggered conditional orders or take profit/stop loss order. Essentially, after a conditional order is triggered, it will become an active order. So, when a conditional order is triggered, cancellation has to be done through the active order endpoint for any unfilled or partially filled active order. As always, orders that have been fully filled cannot be cancelled.

HTTP Request

POST /v2/private/stop-order/cancel

Request Parameters

Parameter required type comments
symbol true string Symbol
stop_order_id false string Order ID. Required if not passing order_link_id
order_link_id false string Unique user-set order ID. Required if not passing stop_order_id

Response Parameters

Parameter Type Comment
stop_order_id string Conditional order ID. Once triggered, the conditional order creates an active order with the same ID (order_id)

Cancel All Conditional Orders

Request Example

curl https://api.bybit.com/v2/private/stop-order/cancelAll \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","symbol":"BTCUSD","timestamp":{timestamp},"sign":"{sign}"}'
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.Conditional.Conditional_cancelAll(symbol="BTCUSD").result())

Response Example

{
    "ret_code": 0,
    "ret_msg": "OK",
    "ext_code": "",
    "ext_info": "",
    "result": [
        {
            "clOrdID": "dea89649-9492-459d-a8c4-c298b87b3d26",
            "user_id": 1,
            "symbol": "BTCUSD",
            "side": "Sell",
            "order_type": "Limit",
            "price": "999999",
            "qty": 1,
            "time_in_force": "PostOnly",
            "create_type": "CreateByUser",
            "cancel_type": "CancelByUser",
            "order_status": "",
            "leaves_qty": 1,
            "leaves_value": "0",
            "created_at": "2019-12-17T12:13:20Z",
            "updated_at": "2019-12-27T13:56:33.793799Z",
            "cross_status": "Deactivated",
            "cross_seq": -1,
            "stop_order_type": "Stop",
            "trigger_by": "LastPrice",
            "base_price": "6910.5",
            "expected_direction": "Rising"
        },
        {
            "clOrdID": "a85cd1c0-a9a4-49d3-a1bd-bab5ebe946d5",
            "user_id": 1,
            "symbol": "BTCUSD",
            "side": "Buy",
            "order_type": "Limit",
            "price": "8000",
            "qty": 1,
            "time_in_force": "GoodTillCancel",
            "create_type": "CreateByStopOrder",
            "cancel_type": "CancelByUser",
            "order_status": "",
            "leaves_qty": 1,
            "leaves_value": "0",
            "created_at": "2019-12-27T12:48:24.339323Z",
            "updated_at": "2019-12-27T13:56:33.793802Z",
            "cross_status": "Deactivated",
            "cross_seq": -1,
            "stop_order_type": "Stop",
            "trigger_by": "LastPrice",
            "base_price": "7000",
            "expected_direction": "Rising"
        }
    ],
    "time_now": "1577454993.799912",
    "rate_limit_status": 90,
    "rate_limit_reset_ms": 1580885703683,
    "rate_limit": 100
}

Cancel all untriggered conditional orders.

HTTP Request

POST /v2/private/stop-order/cancelAll

Request Parameters

Parameter required type comments
symbol true string Symbol

Response Parameters

Parameter Type Comment
clOrdID string A unique order number of type UUID
user_id number UserID
symbol string Symbol
side string Side
order_type string Active order type
price number Order price
qty number Order quantity in USD
time_in_force string Time in force
create_type string Trigger scenario for single action
cancel_type string Trigger scenario for cancel operation
order_status string Order status
leaves_qty number Number of unfilled contracts from the order's size
leaves_value number The estimated value corresponding to the number of remaining orders
created_at string Creation time
updated_at string Update time
cross_status string The state of initiating a matchmaking request
cross_seq number Cross sequence (internal value)
stop_order_type string Conditional order type
trigger_by string Trigger price type. Default LastPrice
base_price number Market price at placing order
expected_direction string Expected direction

Replace Conditional Order

Request Example

curl https://api.bybit.com/v2/private/stop-order/replace \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","symbol":"BTCUSD","stop_order_id":"","timestamp":{timestamp},"sign":"{sign}"}'
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.Conditional.Conditional_replace(symbol="BTCUSD", stop_order_id="", p_r_trigger_price="16003").result())

Response Example

{
    "ret_code": 0,
    "ret_msg": "ok",
    "ext_code": "",
    "result": {
        "stop_order_id": "378a1bbc-a93a-4e75-87f4-502ea754ba36"
    },
    "ext_info": null,
    "time_now": "1577475760.604942",
    "rate_limit_status": 96,
    "rate_limit_reset_ms": 1577475760612,
    "rate_limit": "100"
}

Replace conditional order can modify/amend your conditional orders.

order_id and symbol are required for identifying a conditional order.

p_r_qty, p_r_price and p_r_trigger_price can be set for your conditional order. If these fields are not provided, nothing will be modified.

HTTP Request

POST /v2/private/stop-order/replace

Request Parameters

Parameter Required Type Comment
stop_order_id false string Order ID. Required if not passing order_link_id
order_link_id false string Unique user-set order ID. Required if not passing stop_order_id
symbol true string Symbol.
p_r_qty false integer New order quantity. Do not pass this field if you don't want modify it
p_r_price false string New order price. Do not pass this field if you don't want modify it
p_r_trigger_price false string New conditional order's trigger price or TP/SL order price, also known as stop_px. Do not pass this field if you don't want modify it
take_profit false number New take_profit price, also known as stop_px. Do not pass this field if you don't want modify it
stop_loss false number New stop_loss price, also known as stop_px. Do not pass this field if you don't want modify it
tp_trigger_by false string Take profit trigger price type, default: LastPrice
sl_trigger_by false string Stop loss trigger price type, default: LastPrice

Response Parameters

Parameter Type Comment
stop_order_id string Conditional order ID. Once triggered, the conditional order creates an active order with the same ID (order_id)

Query Conditional Order (real-time)

Request Example

curl "https://api.bybit.com/v2/private/stop-order?api_key={api_key}&symbol=BTCUSD&timestamp={timestamp}order_id={order_id}&sign={sign}"
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.Conditional.Conditional_query(symbol="BTCUSD", stop_order_id="", p_r_trigger_price="16003").result())

Response Example

{
    "ret_code": 0,
    "ret_msg": "OK",
    "ext_code": "",
    "ext_info": "",
    "result": {
        "user_id": 1,
        "symbol": "BTCUSD",
        "side": "Buy",
        "order_type": "Limit",
        "price": "8000",
        "qty": 1,
        "time_in_force": "GoodTillCancel",
        "order_status": "Untriggered",
        "ext_fields": {},
        "leaves_qty": 1,
        "leaves_value": "0.00013333",
        "cum_exec_qty": 0,
        "cum_exec_value": null,
        "cum_exec_fee": null,
        "reject_reason": "",
        "order_link_id": "",
        "created_at": "2019-12-27T19:56:24.052194Z",
        "updated_at": "2019-12-27T19:56:24.052194Z",
        "order_id": "378a1bbc-a93a-4e75-87f4-502ea754ba36"
    },
    "time_now": "1577476584.386958",
    "rate_limit_status": 99,
    "rate_limit_reset_ms": 1580885703683,
    "rate_limit": 100
}

//When only symbol is passed, the response uses a different structure:

{
    "ret_code": 0,
    "ret_msg": "OK",
    "ext_code": "",
    "ext_info": "",
    "result": [
        {
            "user_id": 100328,
            "symbol": "EOSUSD",
            "side": "Sell",
            "order_type": "Limit",
            "price": "2.7",
            "qty": 1,
            "stop_px": "2.0000",
            "base_price": "2.7000",
            "time_in_force": "GoodTillCancel",
            "order_status": "Untriggered",
            "ext_fields": {},
            "leaves_qty": 1,
            "leaves_value": "0.37037037",
            "cum_exec_qty": 0,
            "cum_exec_value": null,
            "cum_exec_fee": null,
            "reject_reason": "EC_NoError",
            "cancel_type": "UNKNOWN",
            "order_link_id": "",
            "created_at": "2020-12-17T08:21:15.246331281Z",
            "updated_at": "2020-12-17T08:21:15.246331281Z",
            "order_id": "a0dee45e-ae2a-4eb4-8205-9739075a7a81",
            "trigger_by": "MarkPrice"
        },
        ...
        {
            "user_id": 100328,
            "symbol": "EOSUSD",
            "side": "Sell",
            "order_type": "Limit",
            "price": "2.6",
            "qty": 1,
            "stop_px": "2.0000",
            "base_price": "2.7000",
            "time_in_force": "GoodTillCancel",
            "order_status": "Untriggered",
            "ext_fields": {},
            "leaves_qty": 1,
            "leaves_value": "0.38461538",
            "cum_exec_qty": 0,
            "cum_exec_value": null,
            "cum_exec_fee": null,
            "reject_reason": "EC_NoError",
            "cancel_type": "UNKNOWN",
            "order_link_id": "",
            "created_at": "2020-12-17T08:21:10.924193413Z",
            "updated_at": "2020-12-17T08:21:10.924193413Z",
            "order_id": "51d048ba-a71f-40ef-b4c4-897e94590b80",
            "trigger_by": "MarkPrice"
        }
    ],
    "time_now": "1608193281.690286",
    "rate_limit_status": 599,
    "rate_limit_reset_ms": 1608193281687,
    "rate_limit": 600
}

Query real-time stop order information. When passing the parameter order_id or order_link_id, a single order data will be returned; otherwise, returns up to 10 unfilled orders.

HTTP Request

GET /v2/private/stop-order

Request Parameters

Parameter Required Type Comment
symbol true string Symbol
stop_order_id false string Conditional order ID. Once triggered, the conditional order creates an active order with the same ID (order_id)
order_link_id false string Customised order ID

Response Parameters

Parameter Type Comment
user_id number UserID
symbol string Symbol
side string Side
order_type string Active order type
price number Order price
qty number Order quantity in USD
time_in_force string Time in force
order_status string Order status
ext_fields json Extension field
leaves_qty number Number of unfilled contracts from the order's size
leaves_value number The estimated value corresponding to the number of remaining orders
cum_exec_qty number Cumulative qty of trading
cum_exec_value number Cumulative value of trading
cum_exec_fee number Cumulative trading fees
reject_reason string The reason the order was rejected
order_link_id string Customised order ID
created_at string Creation time
updated_at string Update time
order_id string Order ID
base_price string Market price at placing order
stop_px string Trigger price
trigger_by string Trigger price type
take_profit number Take profit price
stop_loss number Stop loss price
tp_trigger_by string Take profit trigger price type, default: LastPrice
sl_trigger_by string Stop loss trigger price type, default: LastPrice

Position

My Position

Request Example

curl "https://api.bybit.com/v2/private/position/list?api_key={api_key}&symbol=BTCUSD&timestamp={timestamp}&sign={sign}"
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.Positions.Positions_myPosition(symbol="BTCUSD").result())

Response Example

{
    "ret_code": 0,
    "ret_msg": "OK",
    "ext_code": "",
    "ext_info": "",
    "result": {
        "id": 27913,
        "user_id": 1,
        "risk_id": 1,
        "symbol": "BTCUSD",
        "side": "Buy",
        "size": 5,
        "position_value": "0.0006947",
        "entry_price": "7197.35137469",
        "is_isolated":true,
        "auto_add_margin": 0,
        "leverage": "1",  //In Isolated Margin mode, the value is set by user. In Cross Margin mode, the value is the max leverage at current risk level
        "effective_leverage": "1", // Effective Leverage. In Isolated Margin mode, its value equals `leverage`; In Cross Margin mode, The formula to calculate:
effective_leverage = position size / mark_price / (wallet_balance + unrealised_pnl)
        "position_margin": "0.0006947",
        "liq_price": "3608",
        "bust_price": "3599",
        "occ_closing_fee": "0.00000105",
        "occ_funding_fee": "0",
        "take_profit": "0",
        "stop_loss": "0",
        "trailing_stop": "0",
        "position_status": "Normal",
        "deleverage_indicator": 4,
        "oc_calc_data": "{\"blq\":2,\"blv\":\"0.0002941\",\"slq\":0,\"bmp\":6800.408,\"smp\":0,\"fq\":-5,\"fc\":-0.00029477,\"bv2c\":1.00225,\"sv2c\":1.0007575}",
        "order_margin": "0.00029477",
        "wallet_balance": "0.03000227",
        "realised_pnl": "-0.00000126",
        "unrealised_pnl": 0,
        "cum_realised_pnl": "-0.00001306",
        "cross_seq": 444081383,
        "position_seq": 287141589,
        "created_at": "2019-10-19T17:04:55Z",
        "updated_at": "2019-12-27T20:25:45.158767Z"
        "tp_sl_mode": "Partial"
    },
    "time_now": "1577480599.097287",
    "rate_limit_status": 119,
    "rate_limit_reset_ms": 1580885703683,
    "rate_limit": 120
}

//When symbol is not passed, the response uses a different structure:

{
    "ret_code": 0,
    "ret_msg": "OK",
    "ext_code": "",
    "ext_info": "",
    "result": [
        {
            "is_valid": true, //represents whether the current data is valid
            "data": { //the data can only be used when is_valid is true
                "id": 0,
                "position_idx": 0,
                "mode": 0,
                "user_id": 118921,
                "risk_id": 1,
                "symbol": "BTCUSD",
                "side": "Buy",
                "size": 10,
                "position_value": "0.00076448",
                "entry_price": "13080.78694014",
                "is_isolated": false,
                "auto_add_margin": 1,
                "leverage": "100",
                "effective_leverage": "0.01",
                "position_margin": "0.40111704",
                "liq_price": "25",
                "bust_price": "25",
                "occ_closing_fee": "0.0003",
                "occ_funding_fee": "0",
                "take_profit": "0",
                "stop_loss": "0",
                "trailing_stop": "0",
                "position_status": "Normal",
                "deleverage_indicator": 1,
                "oc_calc_data": "{\"blq\":0,\"slq\":0,\"bmp\":0,\"smp\":0,\"fq\":-10,\"bv2c\":0.0115075,\"sv2c\":0.0114925}",
                "order_margin": "0",
                "wallet_balance": "0.40141704",
                "realised_pnl": "-0.00000008",
                "unrealised_pnl": 0.00003797,
                "cum_realised_pnl": "-0.090626",
                "cross_seq": 764786721,
                "position_seq": 581513847,
                "created_at": "2020-08-10T07:04:32Z",
                "updated_at": "2020-11-02T00:00:11.943371457Z"
                "tp_sl_mode": "Partial"
            }
        },
        ...
        {
            "is_valid": true, //represents whether the current data is valid
            "data": { //the data can only be used when is_valid is true
                "id": 0,
                "position_idx": 0,
                "mode": 0,
                "user_id": 118921,
                "risk_id": 35,
                "symbol": "XRPUSD",
                "side": "None",
                "size": 0,
                "position_value": "0",
                "entry_price": "0",
                "is_isolated": false,
                "auto_add_margin": 1,
                "leverage": "16.67",
                "effective_leverage": "16.67",
                "position_margin": "0",
                "liq_price": "0",
                "bust_price": "0",
                "occ_closing_fee": "0",
                "occ_funding_fee": "0",
                "take_profit": "0",
                "stop_loss": "0",
                "trailing_stop": "0",
                "position_status": "Normal",
                "deleverage_indicator": 0,
                "oc_calc_data": "{\"blq\":0,\"slq\":0,\"bmp\":0,\"smp\":0,\"bv2c\":0.06153301,\"sv2c\":0.06144302}",
                "order_margin": "0",
                "wallet_balance": "0",
                "realised_pnl": "0",
                "unrealised_pnl": 0,
                "cum_realised_pnl": "0",
                "cross_seq": -1,
                "position_seq": 352149441,
                "created_at": "2020-08-10T07:04:32Z",
                "updated_at": "2020-08-22T08:06:32Z"
                "tp_sl_mode": "Partial"
            }
        }
    ],
    "time_now": "1604302124.031104",
    "rate_limit_status": 118,
    "rate_limit_reset_ms": 1604302124020,
    "rate_limit": 120
}

Get my position list.

HTTP Request

GET /v2/private/position/list

Request Parameters

Parameter Required Type Comment
symbol false string Symbol

Response Parameters

Parameter Type Comment
id number PositionID
position_idx integer Position idx, used to identify positions in different position modes:
0-One-Way Mode
1-Buy side of both side mode
2-Sell side of both side mode
mode number Position mode
user_id number UserID
risk_id number Risk ID
symbol string Symbol
side string Side
size number Position qty
position_value string Position value
entry_price string Average entry price
is_isolated bool true means isolated margin mode; false means cross margin mode
auto_add_margin number Whether to add margin automatically
leverage string In Isolated Margin mode, the value is set by user. In Cross Margin mode, the value is the max leverage at current risk level
effective_leverage string Effective leverage
position_margin string Position margin
liq_price string Liquidation price
bust_price string Bankruptcy price
occ_closing_fee string Position closing fee occupied (your opening fee + expected maximum closing fee)
occ_funding_fee string Pre-occupied funding fee: calculated from position qty and current funding fee
take_profit string Take profit price
stop_loss string Stop loss price
trailing_stop string Trailing stop
position_status string Position status: Normal, Liq, Adl
deleverage_indicator number Deleverage indicator level (1,2,3,4,5)
oc_calc_data string Pre-occupied calculate parameters. blq: total number of the long side unsettled orders; bmp: the lowest price of the long side; slq: total number of the short side unsettled orders; smp: the lowest price of the short side
order_margin string Pre-occupied order margin
wallet_balance string Wallet Data Endpoints
realised_pnl string Today's realised pnl
unrealised_pnl number unrealised pnl
cum_realised_pnl string Accumulated realised pnl (all-time total)
cross_seq number Cross sequence (internal value)
position_seq number Position sequence
created_at string The account creation time
updated_at string Update time
tp_sl_mode string Stop loss and take profit mode

Change Margin

Request Example

curl https://api.bybit.com/v2/private/position/change-position-margin \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","symbol":"BTCUSD",margin:"10","timestamp":{timestamp},"sign":"{sign}"}'
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.Positions.Positions_changeMargin(symbol="BTCUSD", margin="10").result())

Response Example

{
    "ret_code": 0,
    "ret_msg": "ok",
    "ext_code": "",
    "result": 9.996e-05,
    "ext_info": null,
    "time_now": "1577480720.003444",
    "rate_limit_status": 74,
    "rate_limit_reset_ms": 1577480720011,
    "rate_limit": 75
}

Update margin.

HTTP Request

POST /v2/private/position/change-position-margin

Request Parameters

Parameter Required Type Comment
symbol true string Symbol
margin true string margin

Response Parameters

Parameter Type Comment
result number User margin

Set Trading-Stop

Request Example

curl https://api.bybit.com/v2/private/position/trading-stop \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","symbol":"BTCUSD","stop_loss":7000,"timestamp":{timestamp},"sign":"{sign}"}'
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.Positions.Positions_tradingStop(symbol="BTCUSD",stop_loss="7000").result())

Response Example

{
    "ret_code": 0,
    "ret_msg": "ok",
    "ext_code": "",
    "result": {
        "id": 27913,
        "user_id": 1,
        "symbol": "BTCUSD",
        "side": "Buy",
        "size": 5,
        "position_value": 0.0006947,
        "entry_price": 7197.35137469,
        "risk_id": 1,
        "auto_add_margin": 0,
        "leverage": 6.95,
        "position_margin": 9.996e-05,
        "liq_price": 6320,
        "bust_price": 6292.5,
        "occ_closing_fee": 6e-07,
        "occ_funding_fee": 0,
        "take_profit": 0,
        "stop_loss": 7000,
        "trailing_stop": 0,
        "position_status": "Normal",
        "deleverage_indicator": 5,
        "oc_calc_data": "{\"blq\":2,\"blv\":\"0.0002941\",\"slq\":0,\"bmp\":6800.408,\"smp\":0,\"fq\":-5,\"fc\":-0.00004279,\"bv2c\":0.14549282,\"sv2c\":0.14527699}",
        "order_margin": 4.279e-05,
        "wallet_balance": 0.03000227,
        "realised_pnl": -1.26e-06,
        "cum_realised_pnl": -1.306e-05,
        "cum_commission": 0,
        "cross_seq": 444081383,
        "position_seq": 287176872,
        "created_at": "2019-10-19T17:04:55.000Z",
        "updated_at": "2019-12-27T21:17:27.000Z",
        "ext_fields": {
            "trailing_active":"9000",
            "sl_trigger_by": "LastPrice",
            "v": 221,
            "mm": 0
        }
    },
    "ext_info": null,
    "time_now": "1577481447.436689",
    "rate_limit_status": 73,
    "rate_limit_reset_ms": 1577481447443,
    "rate_limit": 75
}

Set take profit, stop loss, and trailing stop for your open position.

HTTP Request

POST /v2/private/position/trading-stop

Request Parameters

Parameter Required Type Comment
symbol true string Symbol
take_profit false number Cannot be less than 0, 0 means cancel TP
stop_loss false number Cannot be less than 0, 0 means cancel SL
trailing_stop false number Cannot be less than 0, 0 means cancel TS
tp_trigger_by false string Take profit trigger price type, default: LastPrice
sl_trigger_by false string Stop loss trigger price type, default: LastPrice
new_trailing_active false number Trailing stop trigger price. Trailing stops are triggered only when the price reaches the specified price. Trailing stops are triggered immediately by default.
sl_size false number Stop loss quantity (when in partial mode)
tp_size false number Take profit quantity (when in partial mode)

Response Parameters

Parameter Type Comment
id number PositionID
user_id number UserID
symbol string Symbol
side string Side
size number Position qty
position_value string Position value
entry_price string Average entry price
risk_id number Risk ID
auto_add_margin number Whether to add margin automatically
leverage string In Isolated Margin mode, the value is set by user. In Cross Margin mode, the value is the max leverage at current risk level
position_margin string Position margin
liq_price string Liquidation price
bust_price string Bankruptcy price
occ_closing_fee string Position closing fee occupied (your opening fee + expected maximum closing fee)
occ_funding_fee string Pre-occupied funding fee: calculated from position qty and current funding fee
take_profit string Take profit price
stop_loss string Stop loss price
trailing_stop string Trailing stop
position_status string Position status: Normal, Liq, Adl
deleverage_indicator number Deleverage indicator level (1,2,3,4,5)
oc_calc_data string Pre-occupied calculate parameters. blq: total number of the long side unsettled orders; bmp: the lowest price of the long side; slq: total number of the short side unsettled orders; smp: the lowest price of the short side
order_margin string Pre-occupied order margin
wallet_balance string Wallet Data Endpoints
realised_pnl string Today's realised pnl
cum_realised_pnl string Accumulated realised pnl (all-time total)
cum_commission number Accumulated commission
cross_seq number Cross sequence (internal value)
position_seq number Position sequence
created_at string Creation time
updated_at string Update time
ext_fields>trailing_active string Trailing stop active price
ext_fields>sl_trigger_by string Stop loss trigger price type

Set Leverage

Request Example

curl https://api.bybit.com/v2/private/position/leverage/save \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","symbol":"BTCUSD","buy_leverage":14,"sell_leverage":14,"timestamp":{timestamp},"sign":"{sign}"}'
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

{
    "ret_code": 0,
    "ret_msg": "ok",
    "ext_code": "",
    "result": 2,
    "ext_info": null,
    "time_now": "1577477968.175013",
    "rate_limit_status": 74,
    "rate_limit_reset_ms": 1577477968183,
    "rate_limit": 75
}

Set Leverage

HTTP Request

POST /v2/private/position/leverage/save

Request Parameters

Parameter Required Type Comment
symbol true string Symbol
leverage true number Must be greater than 0 and less than the risk limit leverage. If you need to switch to cross margin please see the Cross/Isolated Margin Switch endpoint
leverage_only false bool Use this parameter to set leverage while in cross margin mode.
If this field is set to false, when leverage is equal to 0 the position will use cross margin; when leverage is greater than 0 the position will use isolated margin.
If this field is set to true, you can set leverage in cross margin with leverage. leverage must be greater than 0.
Use the Cross/Isolated Margin Switch endpoint to switch cross/isolated without modifying the cross level of leverage.

Response Parameters

Parameter Type Comment
result number User leverage

User Trade Records

Request Example

curl "https://api.bybit.com/v2/private/execution/list?api_key={api_key}&symbol=BTCUSD&timestamp={timestamp}&sign={sign}"
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.Execution.Execution_getTrades(symbol="BTCUSD").result())

Response Example

{
    "ret_code": 0,
    "ret_msg": "OK",
    "ext_code": "",
    "ext_info": "",
    "result": {
        "order_id": "Abandoned!!", // Abandoned!!
        "trade_list": [
            {
                "closed_size": 0, // The corresponding closing size of the closing order
                "cross_seq": 277136382,
                "exec_fee": "0.0000001",
                "exec_id": "256e5ef8-abfe-5772-971b-f944e15e0d68",
                "exec_price": "8178.5",
                "exec_qty": 1,
                "exec_time": "1571676941.70682",    //Abandoned!!
                "exec_type": "Trade", //Exec Type Enum
                "exec_value": "0.00012227",
                "fee_rate": "0.00075",
                "last_liquidity_ind": "RemovedLiquidity", //Liquidity Enum, only valid while exec_type is Trade, AdlTrade, BustTrade
                "leaves_qty": 0,
                "nth_fill": 2,
                "order_id": "7ad50cb1-9ad0-4f74-804b-d82a516e1029",
                "order_link_id": "",
                "order_price": "8178",
                "order_qty": 1,
                "order_type": "Market", //Order Type Enum
                "side": "Buy", //Side Enum
                "symbol": "BTCUSD", //Symbol Enum
                "user_id": 1,
                "trade_time_ms": 1577480599000
            }
        ]
    },
    "time_now": "1577483699.281488",
    "rate_limit_status": 118,
    "rate_limit_reset_ms": 1577483699244737,
    "rate_limit": 120
}

Get user's trading records. The results are ordered in ascending order (the first item is the oldest).

HTTP Request

GET /v2/private/execution/list

Request Parameters

Parameter Required Type Comment
order_id false string OrderID. If not provided, will return user's trading records
symbol true string Contract type. Required
start_time false int Start timestamp point for result, in milliseconds
page false integer Page. By default, gets first page of data
limit false integer Limit for data size per page, max size is 200. Default as showing 50 pieces of data per page
order false string Sort orders by creation date. Defaults to desc

Response Parameters

Parameter Type Comment
closed_size number The corresponding closing size of the closing order
cross_seq number Cross sequence (internal value)
exec_fee string Transaction fee
exec_id string Transaction ID
exec_price number Transaction price
exec_qty number Transaction qty
exec_type string Exec Type Enum
exec_value string Transaction value
fee_rate string Maker or taker fee rate
last_liquidity_ind string Liquidity Enum, only valid while exec_type is Trade, AdlTrade, BustTrade
leaves_qty number Number of unfilled contracts from the order's size
nth_fill number The sequence of the transaction in this cross sequence data package
order_id string Order ID
order_link_id string Customised order ID
order_price string Order price
order_qty string Order qty
order_type string Order Type Enum
side string Side
symbol string Symbol Enum
user_id number User ID
trade_time_ms number Transaction timestamp

Closed Profit and Loss

Request Example

curl "https://api.bybit.com/v2/private/trade/closed-pnl/list?api_key={api_key}&symbol=BTCUSD&timestamp={timestamp}&sign={sign}"
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.Positions.Positions_closePnlRecords(symbol="BTCUSD").result())

Response Example

{
    "ret_code": 0,
    "ret_msg": "OK",
    "ext_code": "",
    "ext_info": "",
    "result": {
        "current_page": 1,
        "data": [
            {
                "id": 9982,
                "user_id": 160320,
                "symbol": "BTCUSD",
                "order_id": "e976ac13-10e7-4883-a7ba-13b0e93659f1",
                "side": "Sell",
                "qty": 226,
                "order_price": 1600,
                "order_type": "Limit",
                "exec_type": "Trade",
                "closed_size": 113,
                "cum_entry_value": 0.07062500000000001,
                "avg_entry_price": 1600,
                "cum_exit_value": 0.066198,
                "avg_exit_price": 1707,
                "closed_pnl": 0.0043950000000000005,
                "fill_count": 1,
                "leverage": 100,
                "created_at": 1591155741
            }
        ]
    },
    "time_now": "1591173153.876047",
    "rate_limit_status": 119,
    "rate_limit_reset_ms": 1591173153852,
    "rate_limit": 120
}

Get user's closed profit and loss records. The results are ordered in descending order (the first item is the latest).

HTTP Request

GET /v2/private/trade/closed-pnl/list

Request Parameters

Parameter Required Type Comment
symbol true string Symbol
start_time false int Start timestamp point for result, in seconds
end_time false int End timestamp point for result, in seconds
exec_type false string Execution type (cannot be Funding)
page false integer Page. By default, gets first page of data. Maximum of 50 pages
limit false integer Limit for data size per page, max size is 50. Default as showing 20 pieces of data per page.

Response Parameters

Parameter Type Comment
id number PositionID
user_id number UserID
symbol string Symbol
order_id string Order ID
side string Side of the closing order
qty number Order quantity in USD
order_price number Order price
order_type string Active order type
exec_type string Exec Type Enum
closed_size number The corresponding closing size of the closing order
cum_entry_value number Closed position value
avg_entry_price number Average entry price
cum_exit_value number Cumulative trading value of position closing orders
avg_exit_price number Average exit price
closed_pnl number Closed Profit and Loss
fill_count number The number of fills in a single order
leverage number In Isolated Margin mode, the value is set by user. In Cross Margin mode, the value is the max leverage at current risk level
created_at number Creation time

Full/Partial Position TP/SL Switch

Response Example

{
    "ret_code": 0,
    "ret_msg": "OK",
    "ext_code": "",
    "ext_info": "",
    "result": {
        "tp_sl_mode": "Partial"
    },
    "time_now": "1598266294.610276",
    "rate_limit_status": 72,
    "rate_limit_reset_ms": 1598266294607,
    "rate_limit": 75
}

Switch mode between Full or Partial

HTTP Request

POST /v2/private/tpsl/switch-mode

Request Parameters

Parameter Required Type Comment
symbol true string Symbol
tp_sl_mode true string Stop loss and take profit mode

Response Parameters

Parameter Type Comment
tp_sl_mode string Stop loss and take profit mode

Cross/Isolated Margin Switch

Request Example

curl https://api.bybit.com/v2/private/position/switch-isolated \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","symbol":"BTCUSD", "is_isolated":true,"buy_leverage":10,"sell_leverage":20, "timestamp":{timestamp},"sign":"{sign}"}'

Response Example

{
    "ret_code": 0,
    "ret_msg": "ok",
    "ext_code": "",
    "result": null,
    "ext_info": null,
    "time_now": "1577477968.175013",
    "rate_limit_status": 74,
    "rate_limit_reset_ms": 1577477968183,
    "rate_limit": 75
}

Switch Cross/Isolated; must set leverage value when switching from Cross to Isolated

HTTP Request

POST /v2/private/position/switch-isolated

Request Parameters

Parameter Required Type Comment
symbol true string Symbol
is_isolated true bool Cross/Isolated: true is Isolated; false is Cross
buy_leverage true number When switching from cross to isolated, the value of buy_leverage must be equal to sell_leverage.
sell_leverage true number When switching from cross to isolated, the value of buy_leverage must be equal to sell_leverage.

Risk Limit

Get Risk Limit

Request Example

curl "https://api.bybit.com/v2/public/risk-limit/list?symbol=BTCUSD"
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.Wallet.Wallet_getRiskLimit().result())

Response Example

{
    "ret_code":0,
    "ret_msg":"OK",
    "ext_code":"",
    "ext_info":"",
    "result":[
        {
            "id":1,
            "symbol":"BTCUSD",
            "limit":1000000,
            "maintain_margin":0.005,
            "starting_margin":0.01,
            "section":[
                "1",
                "2",
                "3",
                "5",
                "10",
                "25",
                "50",
                "100"
            ],
            "is_lowest_risk":1,
            "created_at":"2021-03-17T08:20:53.000Z",
            "updated_at":"2021-03-17T08:20:53.000Z",
            "max_leverage":100
        },
        ...
        {
            "id":10,
            "symbol":"BTCUSD",
            "limit":10000000,
            "maintain_margin":0.05,
            "starting_margin":0.055,
            "section":[
                "1",
                "2",
                "3",
                "4",
                "5",
                "10",
                "15",
                "18"
            ],
            "is_lowest_risk":0,
            "created_at":"2021-03-17T08:21:12.000Z",
            "updated_at":"2021-03-17T08:21:12.000Z",
            "max_leverage":18.18
        }
    ],
    "time_now":"1616052270.701108"
}

Get risk limit. This endpoint does not require authentication.

HTTP Request

GET /v2/public/risk-limit/list

Request Parameters

Parameter Required Type Comment
symbol false string Symbol

Response Parameters

Parameter Type Comment
id number Risk ID
symbol string Symbol
limit number Risk limit
maintain_margin number Maintain margin
starting_margin number Starting margin
section string Section
is_lowest_risk number Is lowest risk. 0: No; 1: Yes
created_at string Creation time
updated_at string Update time
max_leverage string Max leverage

Set Risk Limit

Request Example

curl https://api.bybit.com/v2/private/position/risk-limit \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","symbol":"BTCUSD","risk_id":2,"timestamp":{timestamp},"sign":"{sign}"}'

Response Example

{
    "ret_code": 0,
    "ret_msg": "OK",
    "ext_code": "",
    "ext_info": "",
    "result": {
        "risk_id": 2
    },
    "time_now": "1620283810.393787",
    "token": null
}

HTTP Request

POST /v2/private/position/risk-limit

Request Parameters

Parameter Required Type Comment
symbol true string Symbol
risk_id true integer Risk ID

Response Parameters

Parameter Type Comment
risk_id number Risk ID

Funding

Get the Last Funding Rate

Request Example

curl "https://api.bybit.com/v2/public/funding/prev-funding-rate?symbol=BTCUSD"
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.Funding.Funding_prevRate(symbol="BTCUSD").result())

Response Example

{
    "ret_code": 0,
    "ret_msg": "ok",
    "ext_code": "",
    "result": {
        "symbol": "BTCUSD",
        "funding_rate": "0.00010000",
        "funding_rate_timestamp": 1577433600
    },
    "ext_info": null,
    "time_now": "1577445586.446797",
    "rate_limit_status": 119,
    "rate_limit_reset_ms": 1577445586454,
    "rate_limit": 120
}

The funding rate is generated every 8 hours at 00:00 UTC, 08:00 UTC and 16:00 UTC. For example, if a request is sent at 12:00 UTC, the funding rate generated earlier that day at 08:00 UTC will be sent.

HTTP Request

GET /v2/public/funding/prev-funding-rate

Request Parameters

parameter Required Type Comment
symbol true string Symbol

Response Parameters

Parameter Type Comment
symbol string Symbol
funding_rate string Funding rate
funding_rate_timestamp number Funding rate timestamp

My Last Funding Fee

Request Example

curl "https://api.bybit.com/v2/private/funding/prev-funding?api_key={api_key}&symbol=BTCUSD&timestamp={timestamp}&sign={sign}"
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.Funding.Funding_myLastFee(symbol="BTCUSD").result())

Response Example

{
    "ret_code": 0,
    "ret_msg": "ok",
    "ext_code": "",
    "result": {
        "symbol": "BTCUSD",
        "side": "Buy",  // Your position side at the time of settlement
        "size": 1,      // Your position size at the time of settlement
        "funding_rate": 0.0001,  // Funding rate for settlement. When the funding rate is positive, longs pay shorts. When it is negative, shorts pay longs.
        "exec_fee": 0.00000002,  // Funding fee.
        "exec_timestamp": 1575907200  // The time of funding settlement occurred, UTC timestamp
    },
    "ext_info": null,
    "time_now": "1577446900.717204",
    "rate_limit_status": 119,
    "rate_limit_reset_ms": 1577446900724,
    "rate_limit": 120
}

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 /v2/private/funding/prev-funding

Request Parameters

Parameter Required Type Comment
symbol true string Symbol

Response Parameters

Parameter Type Comment
symbol string Symbol
side string Your position side at the time of settlement
size number Your position size at the time of settlement
funding_rate number Funding rate
exec_fee number Transaction fee
exec_timestamp number Transaction time

Predicted Funding Rate and My Funding Fee

Request Example

curl "https://api.bybit.com/v2/private/funding/predicted-funding?api_key={api_key}&symbol=BTCUSD&timestamp={timestamp}&sign={sign}"
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.Funding.Funding_predicted(symbol="BTCUSD").result())

Response Example

{
    "ret_code": 0,
    "ret_msg": "ok",
    "ext_code": "",
    "result": {
        "predicted_funding_rate": 0.0001,
        "predicted_funding_fee": 0
    },
    "ext_info": null,
    "time_now": "1577447415.583259",
    "rate_limit_status": 118,
    "rate_limit_reset_ms": 1577447415590,
    "rate_limit": 120
}

Get predicted funding rate and my predicted funding fee.

HTTP Request

GET /v2/private/funding/predicted-funding

Request Parameters

Parameter Required Type Comment
symbol true string Symbol

Response Parameters

Parameter Type Comment
predicted_funding_rate number Predicted funding rate
predicted_funding_fee number Predicted funding fee

API Key Info

Request Example

curl "https://api.bybit.com/v2/private/account/api-key?api_key={api_key}&timestamp={timestamp}&sign={sign}"
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.APIkey.APIkey_info().result())

Response Example

{
    "ret_code": 0,
    "ret_msg": "ok",
    "ext_code": "",
    "result": [
        {
            "api_key": "7GkMBBLTbGRfa0Nuh1",
            "type": "personal",
            "user_id": 1,
            "inviter_id": 3,
            "ips": [
                "*"
            ],
            "note": "scalping_bot",
            "permissions": [
                "Order",
                "Position"
            ],
            "created_at": "2019-10-28T13:22:39.000Z",
            "expired_at": "2020-01-28T13:22:39.000Z",
            "read_only": false
        }
    ],
    "ext_info": null,
    "time_now": "1577445138.790150",
    "rate_limit_status": 99,
    "rate_limit_reset_ms": 1577445138812,
    "rate_limit": 100
}

Get user's API key info.

HTTP Request

GET /v2/private/account/api-key

Request Parameters

Parameter Required Type Comment

Response Parameters

Parameter Type Comment
api_key string API key
type string Key type
user_id number User ID
inviter_id number Inviter ID
ips string IP
note string Note
permissions string ApiKey permission
created_at string Creation time
expired_at string Expire time
read_only bool ReadOnly

LCP Info

Request Example

curl "https://api.bybit.com/v2/private/account/lcp?api_key={api_key}&symbol=BTCUSD&timestamp={timestamp}&sign={sign}"

Response Example

{
    "ret_code": 0,
    "ret_msg": "ok",
    "ext_code": "",
    "result": [
        "lcp_list": [
        {
            "date": "2020-04-27",
            "self_ratio": 0,
            "platform_ratio": 0,
            "score": 0.1459
        },
        {
            "date": "2020-04-26",
            "self_ratio": 0,
            "platform_ratio": 0,
            "score": 0.1459
        }
        ]
    ],
    "ext_info": null,
    "time_now": "1577445138.790150",
    "rate_limit_status": 99,
    "rate_limit_reset_ms": 1577445138812,
    "rate_limit": 100
}

Get user's LCP (data refreshes once an hour). Only supports inverse perpetual at present.

See Understanding Bybit's Liquidity System to learn more.

HTTP Request

GET /v2/private/account/lcp

Request Parameters

Parameter Required Type Comment
symbol true string Symbol

Response Parameters

Parameter Type Comment
date string Date
self_ratio number Deprecated! Personal effective ratio
platform_ratio number Deprecated! Platform effective ratio
score number Liquidity contribution points

Wallet Data Endpoints

The following wallet data endpoints require authentication.

Get Wallet Balance

Request Example

curl "https://api.bybit.com/v2/private/wallet/balance?api_key={api_key}&coin=BTC&timestamp={timestamp}&sign={sign}"
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.Wallet.Wallet_getBalance(coin="BTC").result())

Response Example

{
    "ret_code": 0,
    "ret_msg": "OK",
    "ext_code": "",
    "ext_info": "",
    "result": {
        "BTC": {
            "equity": 1002,                         //equity = wallet_balance + unrealised_pnl
            "available_balance": 999.99987471,      //available_balance
            //In Isolated Margin Mode:
            // available_balance = wallet_balance - (position_margin + occ_closing_fee + occ_funding_fee + order_margin)
            //In Cross Margin Mode:
              //if unrealised_pnl > 0:
              //available_balance = wallet_balance - (position_margin + occ_closing_fee + occ_funding_fee + order_margin);
              //if unrealised_pnl < 0:
              //available_balance = wallet_balance - (position_margin + occ_closing_fee + occ_funding_fee + order_margin) + unrealised_pnl
            "used_margin": 0.00012529,              //used_margin = wallet_balance - available_balance
            "order_margin": 0.00012529,             //Used margin by order
            "position_margin": 0,                   //position margin
            "occ_closing_fee": 0,                   //position closing fee
            "occ_funding_fee": 0,                   //funding fee
            "wallet_balance": 1000,                 //wallet balance. When in Cross Margin mod, the number minus your unclosed loss is your real wallet balance.
            "realised_pnl": 0,                      //daily realized profit and loss
            "unrealised_pnl": 2,                    //unrealised profit and loss
                //when side is sell:
                // unrealised_pnl = size * (1.0 / mark_price -  1.0 / entry_price)
                //when side is buy:
                // unrealised_pnl = size * (1.0 / entry_price -  1.0 / mark_price)
            "cum_realised_pnl": 0,                  //total relised profit and loss
            "given_cash": 0,                        //given_cash
            "service_cash": 0                       //service_cash
        }
    },
    "time_now": "1578284274.816029",
    "rate_limit_status": 98,
    "rate_limit_reset_ms": 1580885703683,
    "rate_limit": 100
}

Get wallet balance info.

HTTP Request

GET /v2/private/wallet/balance

Request Parameters

Parameter Required Type Comment
coin false string currency alias. Returns all wallet balances if not passed

Response Parameters

Parameter Type Comment
equity number User equity
available_balance number Available balance = wallet balance - used margin
used_margin number Used margin
order_margin number Pre-occupied order margin
position_margin number Position margin
occ_closing_fee number Position closing fee occupied (your opening fee + expected maximum closing fee)
occ_funding_fee number Pre-occupied funding fee: calculated from position qty and current funding fee
wallet_balance number Wallet Data Endpoints
realised_pnl number Today's realised pnl
unrealised_pnl number unrealised pnl
cum_realised_pnl number Accumulated realised pnl (all-time total)
given_cash number Experience gold
service_cash number Service cash is used for user's service charge

Wallet Fund Records

Request Example

curl "https://api.bybit.com/v2/private/wallet/fund/records?api_key={api_key}&timestamp={timestamp}&sign={sign}"
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.Wallet.Wallet_getRecords().result())

Response Example

{
    "ret_code": 0,
    "ret_msg": "ok",
    "ext_code": "",
    "result": {
        "data": [
            {
                "id": 235853,
                "user_id": 1,
                "coin": "BTC",
                "wallet_id": 27913,
                "type": "Realized P&L",
                "amount": "0.00000023",
                "tx_id": "",
                "address": "BTCUSD",
                "wallet_balance": "0.03000353",
                "exec_time": "2019-12-10T00:00:29.000Z",
                "cross_seq": 0
            },
            {
                "id": 234467,
                "user_id": 1,
                "coin": "BTC",
                "wallet_id": 27913,
                "type": "Realized P&L",
                "amount": "-0.00000006",
                "tx_id": "",
                "address": "BTCUSD",
                "wallet_balance": "0.03000330",
                "exec_time": "2019-12-09T00:00:25.000Z",
                "cross_seq": 0
            }
        ]
    },
    "ext_info": null,
    "time_now": "1577481867.115552",
    "rate_limit_status": 119,
    "rate_limit_reset_ms": 1577481867122,
    "rate_limit": 120
}

Get wallet fund records. This endpoint also shows exchanges from the Asset Exchange, where the types for the exchange are ExchangeOrderWithdraw and ExchangeOrderDeposit.

HTTP Request

GET /v2/private/wallet/fund/records

Request Parameters

Parameter Required Type Comment
start_date false string Start point for result
end_date false string End point for result
currency false string Currency type
coin false string currency alias
wallet_fund_type false string Wallet fund type
page false integer Page. By default, gets first page of data
limit false integer Limit for data size per page, max size is 50. Default as showing 20 pieces of data per page

Response Parameters

Parameter Type Comment
user_id number UserID
coin string Coin type
type string Fund type
amount string Fund amount
tx_id string Transaction hash ID
address string Address
wallet_balance string Wallet Data Endpoints
exec_time string Transaction time
cross_seq number Cross sequence (internal value)

Withdraw Records

Request Example

curl "https://api.bybit.com/v2/private/wallet/withdraw/list?api_key={api_key}&timestamp={timestamp}&sign={sign}"
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.Wallet.Wallet_withdraw().result())

Response Example

{
  "ret_code": 0,
  "ret_msg": "ok",
  "ext_code": "",
  "result": {
      "data": [{
          "id": 137,                                        
          "user_id": 1,                                     
          "coin": "XRP",  //Coin Enum                                    
          "status": "Pending" //Withdraw Status Enum
          "amount": "20.00000000",
          "fee": "0.25000000",
          "address": "rH7H595XYEVTEHU2FySYsWnmfACBnZS9zM",
          "tx_id": "",
          "submited_at": "2019-06-11T02:20:24.000Z",
          "updated_at": "2019-06-11T02:20:24.000Z"
      }]
      "current_page": 1,
      "last_page": 1
  },
  "ext_info": null,
  "time_now": "1577482295.125488",
  "rate_limit_status": 119,
  "rate_limit_reset_ms": 1577482295132,
  "rate_limit": 120
}

Get withdrawal records.

HTTP Request

GET /v2/private/wallet/withdraw/list

Request Parameters

Parameter Required Type Comment
start_date false string Start point for result
end_date false string End point for result
coin false string Currency type
status false string Withdraw Status Enum
page false integer Page. By default, gets first page of data
limit false integer Limit for data size per page, max size is 50. Default as showing 20 pieces of data per page

Response Parameters

Parameter Type Comment
user_id number UserID
coin string Coin type
status string Withdraw Status Enum
amount string Fund amount
fee string Maker or taker fee rate
address string Address
tx_id string Transaction hash ID
submited_at string Submit time
updated_at string Update time

Asset Exchange Records

Request Example

curl "https://api.bybit.com/v2/private/exchange-order/list?api_key={api_key}&timestamp={timestamp}&sign={sign}"

Response Example

{
    "ret_code": 0,
    "ret_msg": "OK",
    "ext_code": "",
    "ext_info": "",
    "result": [
        {
            "id": 31,
            "exchange_rate": 40.57202774,
            "from_coin": "BTC",
            "to_coin": "ETH",
            "to_amount": 4.05720277,
            "from_fee": 0.0005,
            "from_amount": 0.1,
            "created_at": "2020-06-15 03:32:52"
        },
        {
            "id": 30,
            "exchange_rate": 39.92359901,
            "from_coin": "BTC",
            "to_coin": "ETH",
            "to_amount": 39.923599,
            "from_fee": 0.0005,
            "from_amount": 1,
            "created_at": "2020-06-12 08:27:51"
        }
    ],
    "time_now": "1592554785.486414",
    "rate_limit_status": 119,
    "rate_limit_reset_ms": 1592554785484,
    "rate_limit": 120
}

Get asset exchange records.

HTTP Request

GET /v2/private/exchange-order/list

Request Parameters

Parameter Required Type Comment
limit false integer Limit for data size per page, max size is 50. Default as showing 20 pieces of data per page
from false integer Start ID. By default, returns the latest IDs
direction false string Search direction. Prev: searches in ascending order from start ID, Next: searches in descending order from start ID. Defaults to Next

Response Parameters

Parameter Type Comment
from_coin string Exchange from coin
from_amount number Exchange from amount
to_coin string Exchange to coin
to_amount number Exchange to amount
exchange_rate number Exchange exchange rate
from_fee number Exchange fee in `from_coin` unit
created_at string Exchange time

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
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.Common.Common_getTime().result())

Response Example

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

Get Bybit server time.

HTTP Request

GET /v2/public/time

Request Parameters

Parameter Required Type Comment

Announcement

Request Example

curl https://api.bybit.com/v2/public/announcement

Response Example

{
    "ret_code": 0,
    "ret_msg": "OK",
    "ext_code": "",
    "ext_info": "",
    "result": [
        {
            "id": 2,
            "title": "2019-12-02 RELEASE",
            "link": "https://github.com/bybit-exchange/bybit-official-api-docs/blob/master/en/CHANGELOG.md",
            "summary": "<p>New `cancel all` endpoint is here now!</p><p>Additionally, we strongly recommend that you use the new released place and cancel active V2 endpoints, which are more stable and efficient.The old ones are deprecated (although still working for the time be",
            "created_at": "2019-12-02T11:33:42Z"
        }
    ],
    "time_now": "1577444818.227082"
}

Get Bybit OpenAPI announcements in the last 30 days in reverse order.

HTTP Request

GET /v2/public/announcement

Request Parameters

Parameter Required Type Comment

API Rate Limits

IP Rate Limit

The IP limits are shared across all endpoints: futures, spot, and account asset. However, the mainent and testnet IP limits are separate.

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

Understanding Your Request Rate Limit

Bybit makes frequency limits based on the rolling time window per minute and UID, and each symbol is independent. Every request to the API returns the fields shown in the code panel:

"rate_limit_status": 119,
"rate_limit_reset_ms": 1572114055663,
"rate_limit": 120

Rate Limits For All Private Endpoints

Limit Path Consume
100/min
/v2/private/order/cancel 1 / request
/v2/private/stop-order/create 1 / request
/v2/private/stop-order/cancel 1 / request
/v2/private/order/replace 1 / request
/v2/private/stop-order/replace 1 / request
/v2/private/order/create 1 / request
/v2/private/order/cancel 1 / request
/v2/private/order/cancelAll 10 / request
/v2/private/stop-order/cancelAll 10 / request
600/min /v2/private/order/list 1 / request
/v2/private/stop-order/list 1 / request
/v2/private/order 1 / request
120/min /v2/private/execution/list 1 / request
75/min /v2/private/position/leverage/save 1 / request
/v2/private/position/change-position-margin1 / request
/v2/private/position/trading-stop1 / request
/v2/private/tpsl/switch-mode1 / request
120/min
/v2/private/position/list1 / request
/v2/private/wallet/balance1 / request
120/min
/v2/private/funding/prev-funding-rate 1 / request
/v2/private/funding/prev-funding1 / request
/v2/private/funding/predicted-funding1 / request
120/min
/v2/private/wallet/fund/records 1 / request
/v2/private/wallet/withdraw/list1 / request
600/min
/v2/private/account/api-key 1 / request

Order Limits

Max. number of unfilled orders supported under each trading pair:

If you have reached the 500 active order limit, creating a new order will be successful, but the oldest existing order will be cancelled. However, if you have reached the 10 conditional order limit, creating a new order will result in an error, maintaining the existing 10 orders.

How to Increase API Limits

Understanding Bybit's Liquidity System

Bybit uses Order Fill Ratio (OFR) and Liquidity Contribution Points (LCP) to measure customers' contribution to our executable liquidity.

The LCP and OFR of different assets are calculated separately.

Order Fill Ratio (OFR) Threshold

If you place more than 2000 orders per day on Bybit, please make sure that your 7-day OFR is above a Minimum OFR threshold. Otherwise, Bybit may reduce the rate limits for your API request.

Order Fill Ratio (OFR)

Order Fill Ratio Example
User A:
Orders Filled = 2
Orders Submitted to Bybit = 8
QFR = 2/8 = 25%

User B:
Orders Filled = 1
Orders Submitted to Bybit = 1
QFR = 1/1 = 100%

Minimum OFR Threshold

7-day OFR must be kept above 0.1%.

Rate Limits for API Requests

The rate limits for your API requests are based on your min. Liquidity Contribution Points (LCP) within 7 days.

LCP Order Frequency Limit
20-100 800 times per minute
10-20 600 times per minute
5-10 400 times per minute
2-5 200 times per minute
<2 100 times per minute
Liquidity Contribution Points (LCP)

Explanation
Effective Price Range

Effective Price Range Example
BTC best bid = 10000
BTC best ask = 10001
Effective Price Range: [(10000 + 10001) / 2 - 3* 0.5, (10000 + 10001) / 2 + 3* 0.5] = [9999,10002]

POU

Bybit calculates the size of your orders that fall within the effective price range / the total size of your orders in the order book per second, and then computes the time-weighted-average of the day.

amount of User C's orders within effective price range = 8000
amount of all User C's orders = 2000 + 8000 = 10000
POU = 8000 / 10000 = 0.8

POA

Bybit calculates your amount of orders within effective price range / amount of all orders within effective price range in orderbook, and then performs a 1-Day Time-Weighted-Average over the series of seconds rates.

POA example

The size of user C's orders that fall within the effective price range is 8,000, while the total size of orders in the order book that fall within the effective price range is 200,000.

Size of user C's orders within effective price range = 8000
Total size of orders within effective price range = 200000
POA = 8000 / 200000 = 0.04

WebSocket Data

Authentication

Authentication methods:

First method: Apply for authentication when establishing a connection.

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

import hmac
import json
import time
import websocket

ws_url = "wss://stream.bybit.com/realtime"

api_key = ""
api_secret = ""

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

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

param = "api_key={api_key}&expires={expires}&signature={signature}".format(
    api_key=api_key,
    expires=expires,
    signature=signature
)

url = ws_url + "?" + param

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

Second method: Apply for authentication after establishing a connection through auth request.

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

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

Base endpoints:

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

How to Send Heartbeat Packet

How to Send

ws.send('{"op":"ping"}');

Response Example

{
    "success": true, // Whether ping is successful
    "ret_msg": "pong",
    "conn_id": "036e5d21-804c-4447-a92d-b65a44d00700",// current connection id
    "request": {
        "op": "ping",
        "args": null
    }
}

How to Subscribe to Topics

Understanding Websocket Filters

How to subscribe with a filter

// Subscribing to the trade data for BTCUSD
ws.send('{"op":"subscribe","args":["trade.BTCUSD"]}')

How to subscribe with multiple filters

// Example: Subscribing to the trade data for BTCUSD and XRPUSD
ws.send('{"op":"subscribe","args":["trade.BTCUSD|XRPUSD"]}')

How to subscribe without filters

// Example: Subscribing to the trade data for all symbols
ws.send('{"op": "subscribe", "args": ["trade.*"]}')

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

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

The topic indicates the data you would like to receive whilst the filter parses for the specific data you desire - for example, the symbol. The topic is mandatory but the filter is optional.

To subscribe to more than one topic, simply list multiple topics out, like so:

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

It is possible to use multiple filters for the same topic by splitting them with a pipe (|) - of course, these filters must all be applicable to the selected topic.

Finally, to subscribe to the topic without filters please use the * wildcard.

Unsubscribing From Websocket Topics

How to unsubscribe with a filter

// Unsubscribing from the trade data for ETHUSD
ws.send('{"op":"unsubscribe","args":["trade.ETHUSD"]}')

You can dynamically subscribe and unsubscribe from topics (with or without filters) without websocket disconnection as follows:

ws.send('{"op": "unsubscribe", "args": ["topic.filter", "topic.filter"]}');

Intervals

Some topics are pushed at intervals. If the args contain a millisecond param, such as 100ms, this topic is pushed at intervals. Otherwise, it is pushed constantly.

Understanding Subscription Response

Subscription Response

{
   "success": true, // Whether subscription is successful
   "ret_msg": "",   // Successful subscription: "", otherwise it shows error message
   "conn_id":"e0e10eee-4eff-4d21-881e-a0c55c25e2da",// current connection id
   "request": {     // Request to your subscription
       "op": "subscribe",
       "args": [
           "kline.BTCUSD.1m"
       ]
   }
}

Each subscription will have a response. You can determine whether the subscription is successful based on the response.

Public Topics

orderBookL2_25

How to Subscribe

ws.send('{"op": "subscribe", "args": ["orderBookL2_25.BTCUSD"]}');
from BybitWebsocket import BybitWebsocket
ws = BybitWebsocket(wsURL="wss://stream-testnet.bybit.com/realtime",
                    api_key=None, api_secret=None)
ws.subscribe_orderBookL2(symbol="BTCUSD")
while True:
    data = ws.get_data("orderBookL2_25.BTCUSD")
    if data:
        print(data)

Snapshot Response Example - format of the first response

{
     "topic": "orderBookL2_25.BTCUSD",
     "type": "snapshot",
     "data": [
        {
            "price": "2999.00",
            "symbol": "BTCUSD",
            "id": 29990000,
            "side": "Buy",
            "size": 9
        },
        {
            "price": "3001.00",
            "symbol": "BTCUSD",
            "id": 30010000,
            "side": "Sell",
            "size": 10
        }
     ],
     "cross_seq": 11518,
     "timestamp_e6": 1555647164875373
}

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

{
     "topic": "orderBookL2_25.BTCUSD",
     "type": "delta",
     "data": {
          "delete": [
             {
                   "price": "3001.00",
                   "symbol": "BTCUSD",
                   "id": 30010000,
                   "side": "Sell"
             }
          ],
          "update": [
             {
                   "price": "2999.00",
                   "symbol": "BTCUSD",
                   "id": 29990000,
                   "side": "Buy",
                   "size": 8
             }
          ],
          "insert": [
             {
                   "price": "2998.00",
                   "symbol": "BTCUSD",
                   "id": 29980000,
                   "side": "Buy",
                   "size": 8
             }
          ],
          "transactTimeE6": 0
     },
     "cross_seq": 11519,
     "timestamp_e6": 1555647221331673
}

Fetches the orderbook with a depth of 25 orders per side.

After the subscription response, the first response will be the snapshot response. This shows the entire orderbook. The data is ordered by price, starting with the lowest buys and ending with the highest sells.

Following this, all responses are in the delta format, which represents updates to the orderbook relative to the last response.

Response Parameters

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

orderBookL2_200

How to Subscribe

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

Snapshot Response Example - format of the first response

{
     "topic": "orderBook_200.100ms.BTCUSD",
     "type": "snapshot",
     "data": [
        {
            "price": "2999.00",
            "symbol": "BTCUSD",
            "id": 29990000,
            "side": "Buy",
            "size": 9
        },
        {
            "price": "3001.00",
            "symbol": "BTCUSD",
            "id": 30010000,
            "side": "Sell",
            "size": 10
        }
     ],
     "cross_seq": 11518,
     "timestamp_e6": 1555647164875373
}

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

{
     "topic": "orderBook_200.100ms.BTCUSD",
     "type": "delta",
     "data": {
          "delete": [
             {
                   "price": "3001.00",
                   "symbol": "BTCUSD",
                   "id": 30010000,
                   "side": "Sell"
             }
          ],
          "update": [
             {
                   "price": "2999.00",
                   "symbol": "BTCUSD",
                   "id": 29990000,
                   "side": "Buy",
                   "size": 8
             }
          ],
          "insert": [
             {
                   "price": "2998.00",
                   "symbol": "BTCUSD",
                   "id": 29980000,
                   "side": "Buy",
                   "size": 8
             }
          ],
          "transactTimeE6": 0
     },
     "cross_seq": 11519,
     "timestamp_e6": 1555647221331673
}

Fetches the orderbook with a depth of 200 orders per side.

After the subscription response, the first response will be the snapshot response. This shows the entire orderbook. The data is ordered by price, starting with the lowest buys and ending with the highest sells.

Following this, all responses are in the delta format, which represents updates to the orderbook relative to the last response.

Response Parameters

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

trade

How to Subscribe

ws.send('{"op": "subscribe", "args": ["trade"]}')
from BybitWebsocket import BybitWebsocket
ws = BybitWebsocket(wsURL="wss://stream-testnet.bybit.com/realtime",
                    api_key=None, api_secret=None)
ws.subscribe_trade()
while True:
    data = ws.get_data("trade.BTCUSD")
    if data:
        print(data)

Response Example - format of all responses

{
    "topic": "trade.BTCUSD",
    "data": [
        {
            "timestamp": "2020-01-12T16:59:59.000Z",
            "trade_time_ms": 1582793344685, // trade time in millisecond
            "symbol": "BTCUSD",
            "side": "Sell",
            "size": 328,
            "price": 8098,
            "tick_direction": "MinusTick",
            "trade_id": "00c706e1-ba52-5bb0-98d0-bf694bdc69f7",
            "cross_seq": 1052816407
        }
    ]
}

Get real-time trading information.

Response Parameters

Parameter Type Comment
time string UTC time
trade_time_ms number Millisecond timestamp
symbol string Symbol
side string Side
size number Position qty
price number Order price
tick_direction string Direction of price change
trade_id string Trade ID
cross_seq number Cross sequence (internal value)

insurance

How to Subscribe

ws.send('{"op": "subscribe", "args": ["insurance"]}')
from BybitWebsocket import BybitWebsocket
ws = BybitWebsocket(wsURL="wss://stream-testnet.bybit.com/realtime",
                    api_key=None, api_secret=None)
ws.subscribe_insurance()
while True:
    data = ws.get_data("insurance.BTC")
    if data:
        print(data)

Response Example - format of all responses

{
    "topic": "insurance.BTC",
    "data": [
        {
            "currency": "BTC",
            "timestamp": "2020-01-11T20:00:00Z",
            "wallet_balance": 98786916569
        }
    ]
}

Get the daily insurance fund update.

Response Parameters

Parameter Type Comment
currency string Currency type
timestamp string UTC time
wallet_balance number Wallet Data Endpoints

instrument_info

How to Subscribe

ws.send('{"op": "subscribe", "args": ["instrument_info.100ms.BTCUSD"]}')
from BybitWebsocket import BybitWebsocket
ws = BybitWebsocket(wsURL="wss://stream-testnet.bybit.com/realtime",
                    api_key=None, api_secret=None)
ws.subscribe_instrument_info(symbol="BTCUSD")
while True:
    data = ws.get_data("instrument_info.100ms.BTCUSD")
    if data:
        print(data)

Snapshot Response Example - format of the first response

{
    "topic":"instrument_info.100ms.BTCUSD",
    "type":"snapshot",
     "data": {
         "id": 1,
         "symbol": "BTCUSD",                           //instrument name
         "last_price_e4": 81165000,                    //the latest price
         "last_price": "81165000",  
         "bid1_price_e4":400025000,                    // best bid price
         "bid1_price":"400025000",
         "ask1_price_e4":475450000,                    // best ask price
         "ask1_price":"475450000",
         "last_tick_direction": "ZeroPlusTick",        //the direction of last tick:PlusTick,ZeroPlusTick,MinusTick,ZeroMinusTick
         "prev_price_24h_e4": 81585000,                //the price of prev 24h
         "prev_price_24h": "81585000",
         "price_24h_pcnt_e6": -5148,                   //the current last price percentage change from prev 24h price
         "high_price_24h_e4": 82900000,                //the highest price of prev 24h
         "high_price_24h": "82900000",
         "low_price_24h_e4": 79655000,                 //the lowest price of prev 24h
         "low_price_24h": "79655000",
         "prev_price_1h_e4": 81395000,                 //the price of prev 1h
         "prev_price_1h": "81395000",
         "price_1h_pcnt_e6": -2825,                    //the current last price percentage change from prev 1h price
         "mark_price_e4": 81178500,                    //mark price
         "mark_price": "81178500",
         "index_price_e4": 81172800,                   //index price
         "index_price": "81172800",
         "open_interest": 154418471,                   //open interest quantity - Attention, the update is not immediate - slowest update is 1 minute
         "open_value_e8": 1997561103030,               //open value quantity - Attention, the update is not immediate - the slowest update is 1 minute
         "total_turnover_e8": 2029370141961401,        //total turnover
         "turnover_24h_e8": 9072939873591,             //24h turnover
         "total_volume": 175654418740,                 //total volume
         "volume_24h": 735865248,                      //24h volume
         "funding_rate_e6": 100,                       //funding rate
         "predicted_funding_rate_e6": 100,             //predicted funding rate
         "cross_seq": 1053192577,                      //sequence
         "created_at": "2018-11-14T16:33:26Z",         
         "updated_at": "2020-01-12T18:25:16Z",         
         "next_funding_time": "2020-01-13T00:00:00Z",  //next funding time
                                                       //the rest time to settle funding fee
         "countdown_hour": 6                           //the remaining time to settle the funding fee     },
    "cross_seq":9267002,
    "timestamp_e6":1615794861826248
}

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

{
    "topic": "instrument_info.100ms.BTCUSD",
    "type": "delta",
    "data": {
        "delete": [],
        "update": [
            {
                "id": 1,
                "symbol": "BTCUSD",
                "prev_price_24h_e4": 81565000,
                "prev_price_24h": "81565000",
                "price_24h_pcnt_e6": -4904,
                "open_value_e8": 2000479681106,
                "total_turnover_e8": 2029370495672976,
                "turnover_24h_e8": 9066215468687,
                "volume_24h": 735316391,
                "cross_seq": 1053192657,
                "created_at": "2018-11-14T16:33:26Z",
                "updated_at": "2020-01-12T18:25:25Z"
            }
        ],
        "insert": []
    },
    "cross_seq": 1053192657,
    "timestamp_e6": 1578853525691123
}

Get latest information for symbol.

Response Parameters

Parameter Type Comment
symbol string Symbol
last_price_e4 integer (Deprecated) Latest transaction price 10^4
tick_direction string Direction of price change
prev_price_24h_e4 integer (Deprecated) Price of 24 hours ago * 10^4
price_24h_pcnt_e6 integer Percentage change of market price relative to 24h * 10^4
high_price_24h_e4 integer (Deprecated) The highest price in the last 24 hours * 10^4
low_price_24h_e4 integer (Deprecated) Lowest price in the last 24 hours * 10^4
prev_price_1h_e4 integer (Deprecated) Hourly market price an hour ago * 10^4
price_1h_pcnt_e6 integer Percentage change of market price relative to 1 hour ago * 10^6
mark_price_e4 integer (Deprecated) Mark price * 10^4
index_price_e4 integer (Deprecated) Index_price * 10^4
last_price integer Latest transaction price
prev_price_24h integer Price of 24 hours ago
high_price_24h integer The highest price in the last 24 hours
low_price_24h integer Lowest price in the last 24 hours
prev_price_1h integer Hourly market price an hour ago
mark_price integer Mark price
index_price integer Index_price
open_interest integer Open interest. The update is not immediate - slowest update is 1 minute
open_value_e8 integer Open position value * 10^8. The update is not immediate - slowest update is 1 minute
total_turnover_e8 integer Total turnover * 10^8
turnover_24h_e8 integer Turnover for 24H * 10^8
total_volume integer Total volume
volume_24h integer Trading volume in the last 24 hours
predicted_funding_rate_e6 integer Predicted funding rate * 10^6
cross_seq integer Cross sequence (internal value)
created_at string Creation time
updated_at string Update time
next_funding_time string Next settlement time of capital cost
countdown_hour integer Countdown of settlement capital cost

klineV2

How to Subscribe

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

Response Example - format of all responses

{
    "topic": "klineV2.1.BTCUSD",                //topic name
    "data": [{
        "start": 1572425640,                    //start time of the candle
        "end": 1572425700,                      //end time of the candle
        "open": 9200,                           //open price
        "close": 9202.5,                        //close price
        "high": 9202.5,                         //max price
        "low": 9196,                            //min price
        "volume": 81790,                        //volume
        "turnover": 8.889247899999999,          //turnover
        "confirm": False,                       //snapshot flag
        "cross_seq": 297503466,                 
        "timestamp": 1572425676958323           //cross time
    }],
    "timestamp_e6": 1572425677047994            //server time
}

Currently supported intervals:

Response Parameters

Parameter Type Comment
start integer Start timestamp point for result, in seconds
end integer End timestamp point for result, in seconds
open number Starting price
close number Closing price
high number Maximum price
low number Minimum price
volume number Trading volume
turnover number Transaction amount
confirm bool Is confirm
cross_seq integer Cross sequence (internal value)
timestamp integer End timestamp point for result, in seconds

liquidation

How to Subscribe

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

Response Example - format of all responses

{
    "topic":"liquidation.ETHUSD",
    "data": {
        "symbol":"ETHUSD",
        "side":"Sell",
        "price":"3384.15",
        "qty":"3655",
        "time":1631608881954
    }
}

Pushes liquidation orders.

Response Parameters

Parameter Type Comment
symbol string Symbol
side string Liquidated position's side
price string Bankruptcy price
qty string Order quantity in USD
time number Millisecond timestamp

Private Topics

position

How to Subscribe

ws.send('{"op": "subscribe", "args": ["position"]}')
from BybitWebsocket import BybitWebsocket
ws = BybitWebsocket(wsURL="wss://stream-testnet.bybit.com/realtime",
                    api_key=api_key, api_secret=api_secret)
ws.subscribe_position()
while True:
    data = ws.get_data("position")
    if data:
        print(data)

Response Example - format of all responses

{
   "topic": "position",
   "action": "update",
   "data": [
       {
           "user_id":  1,                            // user ID
           "symbol": "BTCUSD",                       // the contract for this position
           "size": 11,                               // the current position amount
           "side": "Sell",                           // side
           "position_value": "0.00159252",           // positional value
           "entry_price": "6907.291588174717",       // entry price
           "liq_price": "7100.234",                  // liquidation price
           "bust_price": "7088.1234",                // bankruptcy price
           "leverage": "1",                           // leverage
           "order_margin":  "1",                      // order margin
           "position_margin":  "1",                   // position margin
           "available_balance":  "2",                 // available balance
           "take_profit": "0",                        // take profit price           
           "tp_trigger_by":  "LastPrice",             // take profit trigger price, eg: LastPrice, IndexPrice. Conditional order only
           "stop_loss": "0",                          // stop loss price
           "sl_trigger_by":  "",                     // stop loss trigger price, eg: LastPrice, IndexPrice. Conditional order only
           "realised_pnl":  "0.10",               // realised PNL
           "trailing_stop": "0",                  // trailing stop points
           "trailing_active": "0",                // trailing stop trigger price
           "wallet_balance":  "4.12",             // wallet balance
           "risk_id":  1,                       
           "occ_closing_fee":  "0.1",             // position closing
           "occ_funding_fee":  "0.1",             // funding fee
           "auto_add_margin": 0,                  // auto margin replenishment switch
           "cum_realised_pnl":  "0.12",           // Total realized profit and loss
           "position_status": "Normal",           // status of position (Normal: normal Liq: in the process of liquidation Adl: in the process of Auto-Deleveraging)
                        // Auto margin replenishment enabled (0: no 1: yes)
           "position_seq": 14                     // position version number
       }
   ]
}

Get my position list.

Response Parameters

Parameter Type Comment
user_id number UserID
symbol string Symbol
side string Side
size number Position qty
position_value string Position value
entry_price string Average entry price
liq_price string Liquidation price
bust_price string Bankruptcy price
leverage string In Isolated Margin mode, the value is set by user. In Cross Margin mode, the value is the max leverage at current risk level
order_margin string Pre-occupied order margin
position_margin string Position margin
available_balance string Available balance = wallet balance - used margin
take_profit string Take profit price
tp_trigger_by string Take profit trigger price type, default: LastPrice
stop_loss string Stop loss price
sl_trigger_by string Stop loss trigger price type, default: LastPrice
realised_pnl string Today's realised pnl
trailing_stop string Trailing stop
trailing_active string Trailing stop active price
wallet_balance string Wallet Data Endpoints
risk_id number Risk ID
is_isolated bool true means isolated margin mode; false means cross margin mode
occ_closing_fee string Position closing fee occupied (your opening fee + expected maximum closing fee)
occ_funding_fee string Pre-occupied funding fee: calculated from position qty and current funding fee
auto_add_margin number Whether to add margin automatically
cum_realised_pnl string Accumulated realised pnl (all-time total)
position_status string Position status: Normal, Liq, Adl
position_seq number Position sequence

execution

How to Subscribe

ws.send('{"op": "subscribe", "args": ["execution"]}')
from BybitWebsocket import BybitWebsocket
ws = BybitWebsocket(wsURL="wss://stream-testnet.bybit.com/realtime",
                    api_key=api_key, api_secret=api_secret)
ws.subscribe_execution()
while True:
    data = ws.get_data("execution")
    if data:
        print(data)

Response Example - format of all responses

{
    "topic": "execution",
    "data": [
        {
            "symbol": "BTCUSD",
            "side": "Buy",
            "order_id": "xxxxxxxx-xxxx-xxxx-9a8f-4a973eb5c418",
            "exec_id": "xxxxxxxx-xxxx-xxxx-8b66-c3d2fcd352f6",
            "order_link_id": "",
            "price": "8300",
            "order_qty": 1,
            "exec_type": "Trade",
            "exec_qty": 1,
            "exec_fee": "0.00000009",
            "leaves_qty": 0,
            "is_maker": false,
            "trade_time": "2020-01-14T14:07:23.629Z" // trade time
        }
    ]
}

Get user's trading records. The results are ordered in ascending order (the first item is the oldest).

Response Parameters

Parameter Type Comment
symbol string Symbol
side string Side
order_id string Order ID
exec_id string Transaction ID
order_link_id string Customised order ID
price string Transaction price
order_qty number Order qty
exec_type string Exec Type Enum
exec_qty number Transaction qty
exec_fee string Transaction fee
leaves_qty number Number of unfilled contracts from the order's size
is_maker bool Is maker
trade_time string Transaction timestamp

order

How to Subscribe

ws.send('{"op": "subscribe", "args": ["order"]}')
from BybitWebsocket import BybitWebsocket
ws = BybitWebsocket(wsURL="wss://stream-testnet.bybit.com/realtime",
                    api_key=api_key, api_secret=api_secret)
ws.subscribe_order()
while True:
    data = ws.get_data("order")
    if data:
        print(data)

Response Example - format of all responses

{
    "topic": "order",
    "data": [
        {
            "order_id": "xxxxxxxx-xxxx-xxxx-9a8f-4a973eb5c418",
            "order_link_id": "",
            "symbol": "BTCUSD",
            "side": "Sell",
            "order_type": "Market",
            "price": "8579.5",
            "qty": 1,
            "time_in_force": "ImmediateOrCancel",
            "create_type": "CreateByClosing",
            "cancel_type": "",
            "order_status": "Filled",
            "leaves_qty": 0,
            "cum_exec_qty": 1,
            "cum_exec_value": "0.00011655",
            "cum_exec_fee": "0.00000009",
            "timestamp": "2020-01-14T14:09:31.778Z",
            "take_profit": "0",
            "stop_loss": "0",
            "trailing_stop": "0",
            "trailing_active": "0",
            "last_exec_price": "8580",
            "reduce_only": false,
            "close_on_trigger": false
        }
    ]
}

Response Parameters

Parameter Type Comment
order_id string Order ID
order_link_id string Customised order ID
symbol string Symbol
side string Side
order_type string Conditional order type
price string Order price
qty number Transaction qty
time_in_force string Time in force
create_type string Trigger scenario for single action
cancel_type string Trigger scenario for cancel operation
order_status string Order status
leaves_qty number Number of unfilled contracts from the order's size
cum_exec_qty number Cumulative qty of trading
cum_exec_value string Cumulative value of trading
cum_exec_fee string Cumulative trading fees
timestamp string Commission time
take_profit string Take profit price
stop_loss string Stop loss price
trailing_stop string Trailing stop
trailing_active string Trailing stop active price
last_exec_price string Last execution price
reduce_only bool What is a reduce-only order? True means your position can only reduce in size if this order is triggered
close_on_trigger bool What is a close on trigger order? For a closing order. It can only reduce your position, not increase it. If the account has insufficient available balance when the closing order is triggered, then other active orders of similar contracts will be cancelled or reduced. It can be used to ensure your stop loss reduces your position regardless of current available margin.

stop_order

How to Subscribe

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

Response Example - format of all responses

{
    "topic": "stop_order",
    "data": [
        {
            "order_id": "xxxxxxxx-xxxx-xxxx-98fb-335aaa6c613b",
            "order_link_id": "",
            "user_id": 1,
            "symbol": "BTCUSD",
            "side": "Buy",
            "order_type": "Limit",
            "price": "8584.5",
            "qty": 1,
            "time_in_force": "ImmediateOrCancel",
            "create_type": "CreateByStopOrder",
            "cancel_type": "",
            "order_status": "Untriggered", //Stop Order Status
            "stop_order_type": "Stop",
            "trigger_by": "LastPrice",
            "trigger_price": "8584.5", //If stop_order_type is TrailingProfit, this field is the trailing stop active price.
            "close_on_trigger": false,
            "timestamp": "2020-01-14T14:11:22.062Z"
        }
    ]
}

Response Parameters

Parameter Type Comment
order_id string Order ID
order_link_id string Customised order ID
user_id number UserID
symbol string Symbol Enum
order_type string Order Type Enum
side string Side
price string Order price
qty number Order quantity in USD
time_in_force string Time in force
create_type string Trigger scenario for single action
cancel_type string Trigger scenario for cancel operation
order_status string Order status
stop_order_type string Conditional order type
trigger_by string Trigger price type. Default LastPrice
trigger_price string If stop_order_type is TrailingProfit, this field is the trailing stop active price.
close_on_trigger bool What is a close on trigger order? For a closing order. It can only reduce your position, not increase it. If the account has insufficient available balance when the closing order is triggered, then other active orders of similar contracts will be cancelled or reduced. It can be used to ensure your stop loss reduces your position regardless of current available margin.
timestamp string UTC time

Archive Data

Historical Market Data

You can get Bybit's historical market data here.

Enums Definitions

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

Side (side)

Symbol (symbol)

Currency (currency/coin)

Contract Type(contract_type)

Contract Status(status)

Wallet fund type (wallet_fund_type / type)

Withdraw status (status)

Order type (order_type)

Quantity (qty)

Price (price)

Time in force (time_in_force)

Trigger price type (trigger_by)

Order (order)

This is used for sorting orders/trades in a specified direction.

Order status (order_status)

Stop order status (stop_order_status)

Cancel type (cancel_type)

Create type (create_type)

Exec type (exec_type)

Liquidity type (last_liquidity_ind)

Tick direction type (tick_direction)

It indicates price fluctuation relative to the last trade.

TP/SL mode (tp_sl_mode)

Take profit/stop loss mode

Kline interval (interval)

Date (start_date/end_date)

Follows the format: yyyy-mm-dd

Stop order type (stop_order_type)

Errors

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

HTTP Code Meaning
200 Request is valid -- Your request is valid
403 Access denied -- You request too many times
404 Request path not found
Error Code Meaning
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.
10010 request ip mismatch
10016 Service not available.
10017 request path not found or request method is invalid
10018 exceed ip rate limit
20001 Order not exists
20003 missing parameter side
20004 invalid parameter side
20005 missing parameter symbol
20006 invalid parameter symbol
20007 missing parameter order_type
20008 invalid parameter order_type
20009 missing parameter qty
20010 New order rejected.
20011 Cancelation rejected.
20012 qty must be greater than zero and less than 1 million
20013 Order does not exist.
20014 Invalid API key format.
20015 Invalid API key or IP.
20016 Trading window not open yet for current pair.
20017 missing parameter order_id
20018 invalid date format
20019 missing parameter stop_px
20020 missing parameter base_price
20021 missing parameter stop_order_id
20022 missing parameter leverage
20023 leverage must be a number
20031 leverage must be greater than zero
20070 missing parameter margin
20071 margin must be greater than zero
20084 order_id or order_link_id is required
30001 order_link_id is repeated
30003 qty must be more than the minimum allowed
30004 qty must be less than the maximum allowed
30005 price exceeds maximum allowed
30007 price exceeds minimum allowed
30008 invalid order_type
30009 no position found
30010 insufficient wallet balance
30011 operation not allowed as position is undergoing liquidation
30012 operation not allowed as position is undergoing ADL
30013 position is in liq or adl status
30014 invalid closing order, qty should not greater than size
30015 invalid closing order, side should be opposite
30016 TS and SL must be cancelled first while closing position
30017 estimated fill price cannot be lower than current Buy liq_price
30018 estimated fill price cannot be higher than current Sell liq_price
30019 cannot attach TP/SL params for non-zero position when placing non-opening position order
30020 position already has TP/SL params
30021 cannot afford estimated position_margin
30022 estimated buy liq_price cannot be higher than current mark_price
30023 estimated sell liq_price cannot be lower than current mark_price
30024 cannot set TP/SL/TS for zero-position
30025 trigger price should bigger than 10% of last price
30026 price too high
30027 price set for Take profit should be higher than Last Traded Price
30028 price set for Stop loss should be between Liquidation price and Last Traded Price
30029 price set for Stop loss should be between Last Traded Price and Liquidation price
30030 price set for Take profit should be lower than Last Traded Price
30031 insufficient available balance for order cost
30032 order has been filled or cancelled
30033 The number of stop orders exceeds maximum limit allowed
30034 no order found
30035 too fast to cancel
30036 the expected position value after order execution exceeds the current risk limit
30037 order already cancelled
30041 no position found
30042 insufficient wallet balance
30043 operation not allowed as position is undergoing liquidation
30044 operation not allowed as position is undergoing AD
30045 operation not allowed as position is not normal status
30049 insufficient available balance
30050 any adjustments made will trigger immediate liquidation
30051 due to risk limit, cannot adjust leverage
30052 leverage can not less than 1
30054 position margin is invalid
30057 requested quantity of contracts exceeds risk limit
30063 reduce-only rule not satisfied
30067 insufficient available balance
30068 exit value must be positive
30074 can't create the stop order, because you expect the order will be triggered when the LastPrice(or IndexPrice, MarkPrice, determined by trigger_by) is raising to stop_px, but the LastPrice(or IndexPrice, MarkPrice) is already equal to or greater than stop_px, please adjust base_price or stop_px
30075 can't create the stop order, because you expect the order will be triggered when the LastPrice(or IndexPrice, MarkPrice, determined by trigger_by) is falling to stop_px, but the LastPrice(or IndexPrice, MarkPrice) is already equal to or less than stop_px, please adjust base_price or stop_px
33004 apikey already expired
34026 the limit is no change

Abandoned Endpoints

Liquidated Orders

Request Example

curl https://api.bybit.com/v2/public/liq-records?symbol=BTCUSD
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.Market.Market_liqRecords(symbol="BTCUSD").result())

Response Example

{
    "ret_code":0,
    "ret_msg":"OK",
    "ext_code":"",
    "ext_info":"",
    "result":[
        {
            "id":2369683,
            "qty":155,
            "side":"Buy",
            "time":1590030126798,
            "symbol":"BTCUSD",
            "price":9444
        }
    ],
    "time_now":"1590068362.493540"
}

Retrieve the liquidated orders, The query range is the last seven days of data.

HTTP Request

GET /v2/public/liq-records

Request Parameters

parameter Required Type Comment
symbol true string Symbol
from false integer From ID. Default: return latest data
limit false integer Limit for data size, max size is 1000. Default size is 500
start_time false integer Start timestamp point for result, in milliseconds
end_time false integer End timestamp point for result, in milliseconds

Response Parameters

Parameter Type Comment
id number Latest data ID
qty number Order quantity in USD
side string Liquidated position's side
time number Millisecond timestamp
symbol string Symbol
price number Execution price

User Leverage

Request Example

curl "https://api.bybit.com/user/leverage?api_key={api_key}&timestamp={timestamp}&sign={sign}"
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.Positions.userLeverage())

Response Example

{
    "ret_code": 0,
    "ret_msg": "ok",
    "ext_code": "",
    "result": {
        "BTCUSD": {
            "leverage": 5
        },
        "EOSUSD": {
            "leverage": 1
        },
        "ETHUSD": {
            "leverage": 1
        },
        "XRPUSD": {
            "leverage": 10
        }
    },
    "ext_info": null,
    "time_now": "1577477752.346548",
    "rate_limit_status": 119,
    "rate_limit_reset_ms": 1577477752355,
    "rate_limit": 120
}

Get user leverage.

HTTP Request

GET /user/leverage

Request Parameters

Parameter Required Type Comment

Response Parameters

Parameter Type Comment
BTCUSD > leverage number BTCUSD leverage
EOSUSD > leverage number EOSUSD leverage
ETHUSD > leverage number ETHUSD leverage
XRPUSD > leverage number XRPUSD leverage

Get Active Order

Request Example

curl "https://api.bybit.com/open-api/order/list?api_key={api_key}&timestamp={timestamp}&sign={sign}&symbol=BTCUSD"
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.Order.Order_getOrders().result())

Response Example

{
    "ret_code": 0,
    "ret_msg": "ok",
    "ext_code": "",
    "result": {
        "current_page": 1,
        "last_page": 6,
        "data": [
            {
                "user_id": 1,
                "symbol": "BTCUSD",
                "side": "Sell",
                "order_type": "Market",
                "price": 7074,
                "qty": 2,
                "time_in_force": "ImmediateOrCancel",
                "order_status": "Filled",
                "ext_fields": {
                    "close_on_trigger": true,
                    "orig_order_type": "BLimit",
                    "prior_x_req_price": 5898.5,
                    "op_from": "pc",
                    "remark": "127.0.0.1",
                    "o_req_num": -34799032763,
                    "xreq_type": "x_create"
                },
                "last_exec_time": "1577448481.696421",
                "last_exec_price": 7070.5,
                "leaves_qty": 0,
                "leaves_value": 0,
                "cum_exec_qty": 2,
                "cum_exec_value": 0.00028283,
                "cum_exec_fee": 0.00002,
                "reject_reason": "NoError",
                "order_link_id": "",
                "created_at": "2019-12-27T12:08:01.000Z",
                "updated_at": "2019-12-27T12:08:01.000Z",
                "order_id": "f185806b-b801-40ff-adec-52289370ed62"
            }
        ]
    },
    "ext_info": null,
    "time_now": "1577448922.437871",
    "rate_limit_status": 98,
    "rate_limit_reset_ms": 1580885703683,
    "rate_limit": 100
}

Get my active order list.

Because order creation/cancellation is asynchronous, there can be a data delay in this endpoint. You can get real-time order info with the Query Active Order (real-time) endpoint.

HTTP Request

GET /open-api/order/list

Request Parameters

Parameter Required Type Comment
order_id false string Order ID
order_link_id false string Unique user-set order ID. Maximum length of 36 characters
symbol false string Symbol. Default BTCUSD
order false string Sort orders by creation date. Defaults to desc
page false integer Page. By default, gets first page of data
limit false integer Limit for data size per page, max size is 50. Default as showing 20 pieces of data per page
order_status false string Queries orders of all statuses if order_status not provided. If you want to query orders with specific statuses, you can pass the order_status split by ',' (eg Filled,New).

Response Parameters

Parameter Type Comment
user_id number UserID
symbol string Symbol
side string Side
order_type string Order type
price number Order price
qty number Order quantity in USD
time_in_force string Time in force
order_status string Order status
ext_fields>close_on_trigger bool What is a close on trigger order? For a closing order. It can only reduce your position, not increase it. If the account has insufficient available balance when the closing order is triggered, then other active orders of similar contracts will be cancelled or reduced. It can be used to ensure your stop loss reduces your position regardless of current available margin.
ext_fields>orig_order_type string Original special order type
ext_fields>prior_x_req_price number Expected match price
ext_fields>op_from string Source of the request
ext_fields>remark string Remark
ext_fields>o_req_num number Used to correlate request & response
ext_fields>xreq_type string Request type
last_exec_time string Last execution time
last_exec_price number Last execution price
leaves_qty number Number of unfilled contracts from the order's size
leaves_value number The estimated value corresponding to the number of remaining orders
cum_exec_qty number Cumulative qty of trading
cum_exec_value number Cumulative value of trading
cum_exec_fee number Cumulative trading fees
reject_reason string The reason the order was rejected
order_link_id string Unique user-set order ID. Maximum length of 36 characters
created_at string Creation time
order_id string Order ID

Get Conditional Order

Request Example

curl "https://api.bybit.com/open-api/stop-order/list?api_key={api_key}&timestamp={timestamp}&sign={sign}"
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.Conditional.Conditional_getOrders().result())

Response Example

{
    "ret_code": 0,
    "ret_msg": "ok",
    "ext_code": "",
    "result": {
        "current_page": 1,
        "last_page": 1,
        "data": [
            {
                "user_id": 1,
                "stop_order_status": "Untriggered",
                "symbol": "BTCUSD",
                "side": "Buy",
                "order_type": "Limit",
                "price": 8000,
                "qty": 1,
                "time_in_force": "GoodTillCancel",
                "stop_order_type": "Stop",
                "trigger_by": "LastPrice",
                "base_price": 7000,
                "order_link_id": "",
                "created_at": "2019-12-27T12:48:24.000Z",
                "updated_at": "2019-12-27T12:48:24.000Z",
                "stop_px": 7500,
                "stop_order_id": "a85cd1c0-a9a4-49d3-a1bd-bab5ebe946d5"
            },
            {
                "user_id": 1,
                "stop_order_status": "Untriggered",
                "symbol": "BTCUSD",
                "side": "Sell",
                "order_type": "Limit",
                "price": 999999,
                "qty": 1,
                "time_in_force": "PostOnly",
                "stop_order_type": "Stop",
                "trigger_by": "LastPrice",
                "base_price": 6910.5,
                "order_link_id": "",
                "created_at": "2019-12-17T12:13:20.000Z",
                "updated_at": "2019-12-17T12:13:20.000Z",
                "stop_px": 10000000000000,
                "stop_order_id": "dea89649-9492-459d-a8c4-c298b87b3d26"
            }
        ]
    },
    "ext_info": null,
    "time_now": "1577451658.755468",
    "rate_limit_status": 599,
    "rate_limit_reset_ms": 1577451658762,
    "rate_limit": 600
}

Get my conditional order list.

Because order creation/cancellation is asynchronous, there can be a data delay in this endpoint. You can get real-time order info with the Query Conditional Order (real-time) endpoint.

HTTP Request

GET /open-api/stop-order/list

Request Parameters

Parameter Required Type Comment
stop_order_id false string Conditional order ID. Once triggered, the conditional order creates an active order with the same ID (order_id)
order_link_id false string Unique user-set order ID. Maximum length of 36 characters
symbol false string Symbol. Default BTCUSD
stop_order_status false string Stop order status
order false string Sort orders by creation date. Defaults to desc
page false integer Page. By default, gets first page of data
limit false integer Limit for data size per page, max size is 50. Default as showing 20 pieces of data per page

Response Parameters

Parameter Type Comment
user_id number UserID
stop_order_status string Stop order status
symbol string Symbol
side string Side
order_type string Active order type
price number Order price
qty number Order quantity in USD
time_in_force string Time in force
stop_order_type string Conditional order type
trigger_by string Trigger price type. Default LastPrice
base_price number Market price at placing order
order_link_id string Customised order ID
created_at string Creation time
updated_at string Update time
stop_px number Trigger price
stop_order_id string Conditional order ID. Once triggered, the conditional order creates an active order with the same ID (order_id)

Place Conditional Order

Request Example

curl https://api.bybit.com/open-api/stop-order/create \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","order_type":"Limit","side":"Buy","symbol":"BTCUSD","qty":1,"price":8100,"base_price":8300,"stop_px":8150,"time_in_force":"GoodTillCancel","order_link_id":"cus_order_id_1","timestamp":{timestamp},"sign":"{sign}"}'
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.Conditional.Conditional_new(order_type="Limit",side="Buy",symbol="BTCUSD",qty=1,price=8100,base_price=8300,stop_px=8150,time_in_force="GoodTillCancel", order_link_id="cus_order_id_1").result())

Response Example

{
    "ret_code": 0,
    "ret_msg": "ok",
    "ext_code": "",
    "result": {
        "user_id": 1,
        "symbol": "BTCUSD",
        "side": "Buy",
        "order_type": "Limit",
        "price": 8000,
        "qty": 1,
        "time_in_force": "GoodTillCancel",
        "stop_order_type": "Stop",
        "trigger_by": "LastPrice",
        "base_price": 7000,
        "order_status": "Untriggered",
        "ext_fields": {
            "stop_order_type": "Stop",
            "trigger_by": "LastPrice",
            "base_price": 7000,
            "expected_direction": "Rising",
            "trigger_price": 7500,
            "op_from": "api",
            "remark": "127.0.01",
            "o_req_num": 0
        },
        "leaves_qty": 1,
        "leaves_value": 0.00013333,
        "reject_reason": null,
        "cross_seq": -1,
        "created_at": "2019-12-27T12:48:24.000Z",
        "updated_at": "2019-12-27T12:48:24.000Z",
        "stop_px": 7500,
        "stop_order_id": "a85cd1c0-a9a4-49d3-a1bd-bab5ebe946d5"
    },
    "ext_info": null,
    "time_now": "1577450904.327654",
    "rate_limit_status": 99,
    "rate_limit_reset_ms": 1577450904335,
    "rate_limit": "100"
}

Market price conditional order: A traditional market price order, will be filled at the best available price. price is not required for this type of order.

Limit price conditional order: You can set an execution price for your order. Only when the last traded price reaches the order price will the system will fill your order.

Take profit/Stop loss: You may only set a take-profit/stop-loss conditional order upon opening the position. Once you hold a position, the take profit and stop loss information you sent when placing an order will no longer be valid.

Order quantity: This parameter indicates the quantity of perpetual contracts you want to buy or sell, currently Bybit only support order quantity in an integer.

Order price: If it is a stop order, this parameter is required. When there is no position, the long commission price should be 10% higher than the market price and less than 1 million. If there are positions, they need to be better than strong parity. For the minimum unit of price increase or decrease, please refer to the price_filter field in the Query Symbols endpoint.

Conditional order trigger price: You may set a trigger price for your conditional order. conditional order will not enter the order book until the last price hits the trigger price. When last price hits trigger price: 1) your limit conditional order will enter order book, and wait to be executed; 2) your market conditional order will be executed immediately at the best available market price.

Customize conditional order ID: You may customize order IDs for active orders. We will link it to the system order ID , and return the unique system order ID to you after the active order is created successfully. You may use this order ID to cancel your active order. The customized order ID is asked to be unique, with a maximum length of 36 characters.

HTTP Request

POST /open-api/stop-order/create

Request Parameters

Parameter Required Type Comment
side true string Side
symbol true string Symbol
order_type true string Conditional order type
qty true integer Order quantity in USD
price false number Execution price for conditional order. Required if you make limit price order
base_price true number It will be used to compare with the value of stop_px, to decide whether your conditional order will be triggered by crossing trigger price from upper side or lower side. Mainly used to identify the expected direction of the current conditional order.
stop_px true number Trigger price
time_in_force true string Time in force
trigger_by false string Trigger price type. Default LastPrice
close_on_trigger false bool What is a close on trigger order? For a closing order. It can only reduce your position, not increase it. If the account has insufficient available balance when the closing order is triggered, then other active orders of similar contracts will be cancelled or reduced. It can be used to ensure your stop loss reduces your position regardless of current available margin.
order_link_id false string Unique user-set order ID. Maximum length of 36 characters

Response Parameters

Parameter Type Comment
user_id number UserID
symbol string Symbol
side string Side
order_type string Active order type
price number Order price
qty number Order quantity in USD
time_in_force string Time in force
ext_fields>stop_order_type string Conditional order type
ext_fields>trigger_by string Trigger price type. Default LastPrice
ext_fields>base_price number Market price at placing order
ext_fields>order_status string Order status
ext_fields>stop_order_type string Conditional order type
ext_fields>expected_direction string Expected direction
ext_fields>trigger_price number If stop_order_type is TrailingProfit, this field is the trailing stop active price.
ext_fields>op_from string Source of the request
remark string Remark
o_req_num number Used to correlate request & response
leaves_qty number Number of unfilled contracts from the order's size
leaves_value number The estimated value corresponding to the number of remaining orders
reject_reason string The reason the order was rejected
cross_seq number Cross sequence (internal value)
created_at string Creation time
updated_at string Update time
stop_px number Trigger price
stop_order_id string Conditional order ID. Once triggered, the conditional order creates an active order with the same ID (order_id)

Cancel Conditional Order

Request Example

curl https://api.bybit.com/open-api/stop-order/cancel \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","symbol":"BTCUSD","order_id":"","timestamp":{timestamp},"sign":"{sign}"}'
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.Conditional.Conditional_cancel(symbol="BTCUSD", order_id="").result())

Response Example

{
    "ret_code": 0,
    "ret_msg": "ok",
    "ext_code": "",
    "result": {
        "user_id": 1,
        "stop_order_status": "Untriggered",
        "symbol": "BTCUSD",
        "side": "Buy",
        "order_type": "Limit",
        "price": 8000,
        "qty": 1,
        "time_in_force": "GoodTillCancel",
        "stop_order_type": "Stop",
        "trigger_by": "LastPrice",
        "base_price": 7000,
        "order_link_id": "",
        "created_at": "2019-12-27T13:10:18.000Z",
        "updated_at": "2019-12-27T13:10:18.000Z",
        "stop_px": 7500,
        "stop_order_id": "c1025629-e85b-4c26-b4f3-76e86ad9f8cb"
    },
    "ext_info": null,
    "time_now": "1577452218.567120",
    "rate_limit_status": 97,
    "rate_limit_reset_ms": 1577452218573,
    "rate_limit": "100"
}

You may cancel all untriggered conditional orders or take profit/stop loss order. Essentially, after a conditional order is triggered, it will become an active order. So, when a conditional order is triggered, cancellation has to be done through the active order endpoint for any unfilled or partially filled active order. As always, orders that have been fully filled cannot be cancelled.

HTTP Request

POST /open-api/stop-order/cancel

Request Parameters

Parameter required type comments
symbol true string Symbol
stop_order_id false string Order ID. Required if not passing order_link_id
order_link_id false string Unique user-set order ID. Required if not passing stop_order_id

Response Parameters

Parameter Type Comment
user_id number UserID
stop_order_status string Stop order status
symbol string Symbol
side string Side
order_type string Active order type
price number Order price
qty number Order quantity in USD
time_in_force string Time in force
stop_order_type string Conditional order type
trigger_by string Trigger price type. Default LastPrice
base_price number Market price at placing order
order_link_id string Customised order ID
created_at string Creation time
updated_at string Update time
stop_px number Trigger price
stop_order_id string Conditional order ID. Once triggered, the conditional order creates an active order with the same ID (order_id)

Replace Conditional Order

Request Example

curl https://api.bybit.com/open-api/stop-order/replace \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","symbol":"BTCUSD","stop_order_id":"","timestamp":{timestamp},"sign":"{sign}"}'
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.Conditional.Conditional_replace(symbol="BTCUSD", stop_order_id="").result())

Response Example

{
    "ret_code": 0,
    "ret_msg": "ok",
    "ext_code": "",
    "result": {
        "stop_order_id": "378a1bbc-a93a-4e75-87f4-502ea754ba36"
    },
    "ext_info": null,
    "time_now": "1577475760.604942",
    "rate_limit_status": 96,
    "rate_limit_reset_ms": 1577475760612,
    "rate_limit": "100"
}

Replace conditional order can modify/amend your conditional orders.

order_id and symbol are required for identifying a conditional order.

p_r_qty, p_r_price and p_r_trigger_price can be set for your conditional order. If these fields are not provided, nothing will be modified.

HTTP Request

POST /open-api/stop-order/replace

Request Parameters

Parameter Required Type Comment
stop_order_id false string Conditional order ID. Once triggered, the conditional order creates an active order with the same ID (order_id)
order_id false string Abandoned!! Conditional order ID. Once triggered, the conditional order creates an active order with the same ID (order_id)
order_link_id false string Unique user-set order ID. Maximum length of 36 characters
symbol true string Symbol.
p_r_qty false int New order quantity. Do not pass this field if you don't want modify it
p_r_price false number New order price. Do not pass this field if you don't want modify it
p_r_trigger_price false number New conditional order's trigger price or TP/SL order price, also known as stop_px. Do not pass this field if you don't want modify it

Response Parameters

Parameter Type Comment
stop_order_id string Conditional order ID. Once triggered, the conditional order creates an active order with the same ID (order_id)

Replace Active Order

Request Example

curl https://api.bybit.com/open-api/order/replace \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","symbol":"BTCUSD","order_id":"","timestamp":{timestamp},"sign":"{sign}"}'
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.Order.Order_Replace(symbol="BTCUSD", order_id="").result())

Response Example

{
    "ret_code": 0,    //Error code,
    "ret_msg": "ok",  //Error message,
    "ext_code": "",
    "result": {
        "order_id": "efa44157-c355-4a98-b6d6-1d846a936b93"
    },
    "time_now": "1539778407.210858",    // UTC timestamp
    "rate_limit_status": 99, // The remaining number of accesses in one minute
    "rate_limit_reset_ms": 1580885703683,
    "rate_limit": 100             
}

Replace order can modify/amend your active orders.

p_r_qty and p_r_price are the modified price and quantity. If these two fields are not provided, nothing will be modified.

HTTP Request

POST /open-api/order/replace

Request Parameters

Parameter Required Type Comment
order_id false string Order ID
order_link_id false string Unique user-set order ID. Maximum length of 36 characters
symbol true string Symbol.
p_r_qty false int New order quantity. Do not pass this field if you don't want modify it
p_r_price false number New order price. Do not pass this field if you don't want modify it

Response Parameters

Parameter Type Comment
order_id string Order ID

Get risk limit

Request Example

curl "https://api.bybit.com/open-api/wallet/risk-limit/list?api_key={api_key}&timestamp={timestamp}&sign={sign}"
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.Wallet.Wallet_getRiskLimit().result())

Response Example

{
    "ret_code": 0,
    "ret_msg": "ok",
    "ext_code": "",
    "result": [
        {
            "id": 1,
            "coin": "BTC",
            "symbol": "BTCUSD",
            "limit": 150,
            "maintain_margin": "0.50",
            "starting_margin": "1.00",
            "section": [
                "1",
                "2",
                "3",
                "5",
                "10",
                "25",
                "50",
                "100"
            ],
            "is_lowest_risk": 1,
            "created_at": "2018-09-21T11:34:11.000Z",
            "updated_at": "2018-09-21T11:34:11.000Z",
            "max_leverage": "100.00"
        },
        {
            "id": 10,
            "coin": "BTC",
            "symbol": "BTCUSD",
            "limit": 1500,
            "maintain_margin": "5.00",
            "starting_margin": "5.50",
            "section": [
                "1",
                "2",
                "3",
                "4",
                "5",
                "10",
                "15",
                "18"
            ],
            "is_lowest_risk": 0,
            "created_at": "2018-09-21T11:34:11.000Z",
            "updated_at": "2018-09-21T11:34:11.000Z",
            "max_leverage": "18.18"
        }
    ],
    "ext_info": null,
    "time_now": "1616568086.769014",
    "rate_limit_status": 599,
    "rate_limit_reset_ms": 1616568086777,
    "rate_limit": 600
}

Get risk limit. This endpoint does not require authentication.

HTTP Request

GET /open-api/wallet/risk-limit/list

Request Parameters

Parameter Required Type Comment
symbol false string Symbol

Response Parameters

Parameter Type Comment
id number Risk ID
coin string Coin type
symbol string Symbol
limit number Risk limit
maintain_margin string Maintain margin
starting_margin string Starting margin
section string Section
is_lowest_risk number Is lowest risk. 0: No; 1: Yes
created_at string Creation time
updated_at string Update time
max_leverage string Max leverage

Set Risk Limit

Request Example

curl https://api.bybit.com/open-api/wallet/risk-limit \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","symbol":"BTCUSD","risk_id":2,"timestamp":{timestamp},"sign":"{sign}"}'
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.Wallet.Wallet_setRiskLimit(symbol="BTCUSD", risk_id=2).result())

Response Example

{
  "ret_code": 0,
  "ret_msg": "ok",
  "ext_code": "",
  "result": {
    "position": {
      "id": 1,
      "user_id": 1,
      "symbol": "BTCUSD",
      "side": "None",
      "size": 0,
      "position_value": 0,
      "entry_price": 0,
      "risk_id": 2,
      "auto_add_margin": 0,
      "leverage": 1,
      "position_margin": 0,
      "liq_price": 0,
      "bust_price": 0,
      "occ_closing_fee": 0,
      "occ_funding_fee": 0,
      "take_profit": 0,
      "stop_loss": 0,
      "trailing_stop": 0,
      "position_status": "Normal",
      "deleverage_indicator": 0,
      "oc_calc_data": "{\"blq\":1,\"blv\":\"0.000125\",\"slq\":0,\"bmp\":8000,\"smp\":0,\"fc\":-0.00012529,\"bv2c\":1.00225,\"sv2c\":1.0007575}",
      "order_margin": 0.00012529,
      "wallet_balance": 1000,
      "realised_pnl": 0,
      "cum_realised_pnl": 0,
      "cum_commission": 0,
      "cross_seq": 4376,
      "position_seq": 13689,
      "created_at": "2019-08-13T06:51:29.000Z",
      "updated_at": "2019-12-29T03:11:08.000Z",
      "ext_fields": {
        "trailing_active": "9000",
        "v": 4
      }
    },
    "risk": {
      "id": 2,
      "coin": "BTC",
      "limit": 300,
      "maintain_margin": "1.00",
      "starting_margin": "1.50",
      "section": "[\"1\",\"2\",\"3\",\"5\",\"10\",\"25\",\"50\",\"66\"]",
      "is_lowest_risk": 0,
      "created_at": "2019-06-26T05:46:45.000Z",
      "updated_at": "2019-06-26T05:46:55.000Z"
    }
  },
  "ext_info": null,
  "time_now": "1577589068.435439",
  "rate_limit_status": 71,
  "rate_limit_reset_ms": 1577589068546,
  "rate_limit": 75
}

Set risk limit.

HTTP Request

POST /open-api/wallet/risk-limit

Request Parameters

Parameter Required Type Comment
symbol true string Symbol
risk_id true integer Risk ID

Response Parameters

Parameter Type Comment
position > id number PositionID
user_id number UserID
symbol string Symbol
side string Side
size number Position qty
position_value number Position value
entry_price number Average entry price
risk_id number Risk ID
auto_add_margin number Whether to add margin automatically
leverage number In Isolated Margin mode, the value is set by user. In Cross Margin mode, the value is the max leverage at current risk level
position_margin number Position margin
liq_price number Liquidation price
bust_price number Bankruptcy price
occ_closing_fee number Position closing fee occupied (your opening fee + expected maximum closing fee)
occ_funding_fee number Pre-occupied funding fee: calculated from position qty and current funding fee
take_profit number Take profit price
stop_loss number Stop loss price
trailing_stop number Trailing stop
position_status string Position status: Normal, Liq, Adl
deleverage_indicator number Deleverage indicator level (1,2,3,4,5)
oc_calc_data string Pre-occupied calculate parameters. blq: total number of the long side unsettled orders; bmp: the lowest price of the long side; slq: total number of the short side unsettled orders; smp: the lowest price of the short side
order_margin number Pre-occupied order margin
wallet_balance number Wallet Data Endpoints
realised_pnl number Today's realised pnl
cum_realised_pnl number Accumulated realised pnl (all-time total)
cum_commission number Accumulated commission
cross_seq number Cross sequence (internal value)
position_seq number Position sequence
created_at string Creation time
updated_at string Update time
ext_fields>trailing_active string Trailing stop active price
risk>id number Risk ID
risk>coin string Coin type
risk>limit number Risk limit
risk>maintain_margin string Maintain margin
risk>starting_margin string Starting margin
risk>section string Section
risk>is_lowest_risk number Is lowest risk. 0: No; 1: Yes
risk>created_at string Creation time
risk>updated_at string Update time