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

REST API

2021-09-17

Websocket API

2021-09-10

REST API

2021-09-07

REST API

2021-09-03

Websocket API

2021-06-29

REST API

2021-06-28

REST API

2021-06-02

REST API

2021-05-13

REST API

2021-04-30

REST API

2021-04-07

REST API

2021-04-02

REST API

2021-03-18

REST API

2021-02-02

Websocket API

2021-02-01

REST API

2021-01-12

REST API

2020

2020-12-14

REST API

2020-12-03

REST API

2020-11-16

REST API

2020-11-02

REST API

2020-10-21

REST API

2020-10-16

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-17

REST API

2020-05-21

REST API

2020-05-18

REST API

2020-04-29

REST API

Websocket API

2020-04-27

REST API

2020-04-18

REST API

2020-04-17

REST API

2020-04-14

REST API

2020-04-09

REST API

2020-04-07

REST API

2020-03-31

REST API

Websocket API

2020-03-27

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&buy_leverage=100&sell_leverage=110&symbol=BTCUSDT&timestamp=1542434791747"
param_str = "api_key=B2Rou0PLPpGqcU0Vu2&buy_leverage=100&sell_leverage=110&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 /user/leverage?api_key=B2Rou0PLPpGqcU0Vu2&timestamp=1542434791000&sign=670e3e4aa32b243f2dedf1dafcec2fd17a440e71b05681550416507de591d908 HTTP/1.1
Host: api-testnet.bybit.com

Message format for POST requests:

POST /user/leverage/save HTTP/1.1
Host: api-testnet.bybit.com
Content-Type: application/json

{
    "api_key": "B2Rou0PLPpGqcU0Vu2",
    "leverage": 100,
    "symbol": "BTCUSD",
    "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

Please see the shared endpoint.

Query Kline

Request Example

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

Response Example

{
    "ret_code": 0,
    "ret_msg": "OK",
    "ext_code": "",
    "ext_info": "",
    "result": [
    {
        "id": 3866948,
        "symbol": "BTCUSDT",
        "period": "1",
        "start_at": 1577836800, // Abandoned!!
        "volume": 1451.59,
        "open": 7700,           // Abandoned!!
        "high": 999999,
        "low": 0.5,
        "close": 6000,
        "interval": 1,
        "open_time": 1577836800,
        "turnover": 2.4343353100000003,
    }],
    "time_now": "1581928016.558522"
}

Get kline.

For mark price klines, see the Mark Price Kline endpoint.

HTTP Request

GET /public/linear/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
volume number Trading volume
open integer Starting price
high integer Maximum price
low number Minimum price
close integer Closing price
interval integer Data recording period. 5min, 15min, 30min, 1h, 4h, 1d
open_time integer Starting time
turnover number Transaction amount

Latest Information for Symbol

Please see the shared endpoint.

Public Trading Records

Request Example

curl https://api.bybit.com/public/linear/recent-trading-records?symbol=BTCUSDT&limit=500
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.LinearMarket.LinearMarket_trading().result())

Response Example

{
    "ret_code": 0,                                   // error code 0 means success
    "ret_msg": "OK",                                 // error message
    "ext_code": "",
    "ext_info": "",
    "result": [
        {
            "id": "18368131384",                            // ID, string type, all ids are in descending order globally
            "symbol": "BTCUSDT",                            // contract type
            "price": 9499.5,                                // execution price
            "qty": 9500,                                    // execution quantity
            "side": "Buy",                                  // side
            "time": "2019-11-19T08:03:04.077Z",             // Abandoned!!
            "trade_time_ms":1587638305175
        }
    ],
    "time_now": "1567109419.049271"
}

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

HTTP Request

GET /public/linear/recent-trading-records

Request Parameters

Parameter Required Type Comment
symbol true string Symbol
limit false int Number of results. Default 500; max 1000

Response Parameters

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

Query Symbol

Please see the shared endpoint.

Liquidated Orders

Please see the shared endpoint.

Get the Last Funding Rate

Request Example

curl https://api.bybit.com/public/linear/funding/prev-funding-rate?symbol=BTCUSDT
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.LinearFunding.LinearFunding_prevRate(symbol="BTCUSDT").result())

Response Example

{
    "ret_code":0,
    "ret_msg":"OK",
    "ext_code":"",
    "ext_info":"",
    "result":{
        "symbol":"BTCUSDT",
        "funding_rate":-0.00005965,
        "funding_rate_timestamp":"2020-04-07T08:00:00.000Z"
    },
    "time_now":"1586251109.454281"
}

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 /public/linear/funding/prev-funding-rate

Request Parameters

Parameter Required Type Comment
symbol true string Symbol

Response Parameters

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

Query Mark Price Kline

Request Example

curl https://api.bybit.com/public/linear/mark-price-kline?symbol=BTCUSDT&interval=1&limit=2&from=1581231260
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.LinearKline.LinearKline_markPrice(symbol="BTCUSDT", interval="m", limit=10, **{'from':1}).result())

Response Example

{
    "ret_code": 0,
    "ret_msg": "OK",
    "ext_code": "",
    "ext_info": "",
    "result": [{
        "id": 3866948,
        "symbol": "BTCUSDT",
        "period": "1",
        "start_at": 1577836800,
        "open": 7700,
        "high": 999999,
        "low": 0.5,
        "close": 6000
    },
    {
        "id": 3866948,
        "symbol": "BTCUSDT",
        "period": "1",
        "start_at": 1577836800,
        "open": 7700,
        "high": 999999,
        "low": 0.5,
        "close": 6000
    }],
    "time_now": "1581928016.558522"
}

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

HTTP Request

GET /public/linear/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 number Minimum price
close integer Closing price

Query Index Price Kline

Request Example

curl "https://api.bybit.com/public/linear/index-price-kline?symbol=BTCUSDT&interval=1&limit=2&from=1581231260"
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.LinearKline.LinearKline_indexPrice().result())

Response Example

{
    "ret_code":0,
    "ret_msg":"OK",
    "ext_code":"",
    "ext_info":"",
    "result":[{
        "symbol":"BTCUSDT",
        "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 /public/linear/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/public/linear/premium-index-kline?symbol=BTCUSDT&interval=1&limit=2&from=1581231260"
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.LinearKline.LinearKline_premiumIndexPrice().result())

Response Example

{
    "ret_code":0,
    "ret_msg":"OK",
    "ext_code":"",
    "ext_info":"",
    "result":[{
        "symbol":"BTCUSDT",
        "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 /public/linear/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

Please see the shared endpoint.

Latest Big Deal

Please see the shared endpoint.

Long-Short Ratio

Please see the shared endpoint.

Account Data Endpoints

The following account data endpoints require authentication.

Active Orders

Place Active Order

Request Example

curl https://api.bybit.com/private/linear/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.LinearOrder.LinearOrder_new(side="Sell",symbol="BTCUSDT",order_type="Limit",qty=0.22,price=10000,time_in_force="GoodTillCancel",reduce_only=False, close_on_trigger=False).result())

Response Example

{
    "ret_code": 0,
    "ret_msg": "OK",
    "ext_code": "",
    "ext_info": "",
    "result": {
        "order_id":"bd1844f-f3c0-4e10-8c25-10fea03763f6",
        "user_id": 1,
        "symbol": "BTCUSDT",
        "side": "Sell",
        "order_type": "Limit",
        "price": 8083,
        "qty": 10,
        "time_in_force": "GoodTillCancel",
        "order_status": "New",
        "last_exec_price": 8083,    //Last execution price
        "cum_exec_qty": 0,          //Cumulative qty of trading
        "cum_exec_value": 0,        //Cumulative value of trading
        "cum_exec_fee": 0,          //Cumulative trading fees
        "reduce_only": false,       //true means close order, false means open position
        "close_on_trigger": false
        "order_link_id": "",
        "created_time": "2019-10-21T07:28:19.396246Z",
        "updated_time": "2019-10-21T07:28:19.396246Z",
    },
    "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.

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 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. For the minimum unit of qty increase or decrease, please refer to the lot_size_filter field in the Query Symbol endpoint.

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 Symbol endpoint.

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 BTCUSDT instrument and 280 active orders on the ETHUSDT instrument.

HTTP Request

POST /private/linear/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 number Order quantity in BTC
price false number Order price. Required if you make limit price order
time_in_force true string Time in force
close_on_trigger true 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.
reduce_only true bool What is a reduce-only order? True means your position can only reduce in size if this order is triggered. When reduce_only is true, take profit/stop loss cannot be set
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

Response Parameters

Parameter Type Comment
order_id string Order ID
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
last_exec_price number Last execution price
cum_exec_qty number Cumulative qty of trading
cum_exec_value number Cumulative value of trading
cum_exec_fee number Cumulative trading fees
reduce_only bool true means close order, false means open position
close_on_trigger bool Is close on trigger order
order_link_id string Customised order ID
created_time string Creation time
updated_time 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/private/linear/order/list?api_key={api_key}&timestamp={timestamp}&sign={sign}&symbol=BTCUSDT"
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.LinearOrder.LinearOrder_getOrders(symbol="BTCUSDT").result())

Response Example

{
    "ret_code": 0,
    "ret_msg": "ok",
    "ext_code": "",
    "result": {
        "current_page": 1,
        "last_page": 6,
        "data": [
            {
                "order_id":"bd1844f-f3c0-4e10-8c25-10fea03763f6",
                "user_id": 1,
                "symbol": "BTCUSDT",
                "side": "Sell",
                "order_type": "Limit",
                "price": 8083,
                "qty": 10,
                "time_in_force": "GoodTillCancel",
                "order_status": "New",
                "last_exec_price": 8083,
                "cum_exec_qty": 0,
                "cum_exec_value": 0,
                "cum_exec_fee": 0,
                "order_link_id": "",
                "reduce_only": false,
                "close_on_trigger": false,
                "created_time": "2019-10-21T07:28:19.396246Z",
                "updated_time": "2019-10-21T07:28:19.396246Z",
            }
        ]
    },
    "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 /private/linear/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 true string Symbol
order false string Sort orders by creation date. Defaults to desc
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
order_status false string Query your orders for all statuses if 'order_status' not provided. If you want to query orders with specific statuses, you can pass the order_status split by ','.

Response Parameters

Parameter Type Comment
order_id string Order ID
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
last_exec_price number Last execution price
cum_exec_qty number Cumulative qty of trading
cum_exec_value number Cumulative value of trading
cum_exec_fee number Cumulative trading fees
order_link_id string Customised order ID
reduce_only bool true means close order, false means open position
close_on_trigger bool Is close on trigger order
created_time string Creation time
updated_time 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 Active Order

Request Example

curl https://api.bybit.com/private/linear/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.LinearOrder.LinearOrder_cancel(symbol="BTCUSDT", order_id="").result())

Response Example

{
    "ret_code": 0,
    "ret_msg": "OK",
    "ext_code": "",
    "ext_info": "",
    "result": {
        "order_id":"bd1844f-f3c0-4e10-8c25-10fea03763f6",
    },
    "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 /private/linear/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
order_id string Order ID

Cancel All Active Orders

Request Example

curl https://api.bybit.com/private/linear/order/cancel-all \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","symbol":"BTCUSDT","timestamp":{timestamp},"sign":"{sign}"}'
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.LinearOrder.LinearOrder_cancelAll(symbol="BTCUSDT").result())

Response Example

{
    "ret_code": 0,      
    "ret_msg": "OK",    
    "ext_code": "",     
    "ext_info": "",
    "result": [
        "89a38056-80f1-45b2-89d3-4d8e3a203a79",  
        "89a38056-80f1-45b2-89d3-4d8e3a203a79",  
    ],
    "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 /private/linear/order/cancel-all

Request Parameters

Parameter Required Type Comment
symbol true string Symbol

Response Parameters

Parameter Type Comment
result arr Order ID

Replace Active Order

Request Example

curl https://api.bybit.com/private/linear/order/replace \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","symbol":"BTCUSDT","order_id":"","timestamp":{timestamp},"sign":"{sign}"}'
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.LinearOrder.LinearOrder_replace(symbol="BTCUSDT", 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 /private/linear/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 number 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/private/linear/order/search?api_key={api_key}&symbol=BTCUSDT&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.LinearOrder.LinearOrder_query(symbol="BTCUSDT", order_id="87d8a4ed-dc9d-41c9-8dac-6e3c51356645").result())

Response Example

{
    "ret_code": 0,
    "ret_msg": "OK",
    "ext_code": "",
    "ext_info": "",
    "result": {
        "order_id": "e3f7662b-8b94-42e2-8d46-dead09dd2a52",
        "user_id": 106958,
        "symbol": "BTCUSDT",
        "side": "Sell",
        "order_type": "Market",
        "price": 11775,
        "qty": 0.001,
        "time_in_force": "ImmediateOrCancel",
        "order_status": "Filled",
        "last_exec_price": 11874.5,
        "cum_exec_qty": 0.001,
        "cum_exec_value": 11.8745,
        "cum_exec_fee": 0.00890588,
        "order_link_id": "",
        "reduce_only": false,
        "close_on_trigger": false,
        "created_time": "2020-08-10T19:28:56Z",
        "updated_time": "2020-08-10T19:28:57Z"
    },
    "time_now": "1597171508.869341",
    "rate_limit_status": 598,
    "rate_limit_reset_ms": 1597171508867,
    "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": [
        {
            "order_id": "6449d89e-6ef5-4f54-a065-12b2744de0ae",
            "user_id": 118921,
            "symbol": "LINKUSDT",
            "side": "Buy",
            "order_type": "Limit",
            "price": 9,
            "qty": 0.1,
            "time_in_force": "GoodTillCancel",
            "order_status": "New",
            "last_exec_price": 11874.5,
            "cum_exec_qty": 0.005,
            "cum_exec_value": 11.8745,
            "cum_exec_fee": 0.00890588,
            "order_link_id": "",
            "reduce_only": false,
            "created_time": "2020-11-27T08:25:44Z",
            "updated_time": "2020-11-27T08:25:44Z",
            "take_profit": 0,
            "stop_loss": 0,
            "tp_trigger_by": "UNKNOWN",
            "sl_trigger_by": "UNKNOWN"
        },
        ...
        {
            "order_id": "6d4dc4e0-b4e3-4fc5-a92d-3d693bdff4a5",
            "user_id": 118921,
            "symbol": "LINKUSDT",
            "side": "Buy",
            "order_type": "Limit",
            "price": 8.2,
            "qty": 9999,
            "time_in_force": "GoodTillCancel",
            "order_status": "New",
            "last_exec_price": 11888.5,
            "cum_exec_qty": 0.004,
            "cum_exec_value": 11.8745,
            "cum_exec_fee": 0.00890588,
            "order_link_id": "",
            "reduce_only": false,
            "created_time": "2020-11-23T09:19:49Z",
            "updated_time": "2020-11-23T09:20:31Z",
            "take_profit": 0,
            "stop_loss": 0,
            "tp_trigger_by": "UNKNOWN",
            "sl_trigger_by": "UNKNOWN"
        }
    ],
    "time_now": "1606465563.551193",
    "rate_limit_status": 599,
    "rate_limit_reset_ms": 1606465563547,
    "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 /private/linear/order/search

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

Response Parameters

Parameter Type Comment
order_id string Order ID
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
last_exec_price number Last execution price
cum_exec_qty number Cumulative qty of trading
cum_exec_value number Cumulative value of trading
cum_exec_fee number Cumulative trading fees
reduce_only bool true means close order, false means open position
close_on_trigger bool Is close on trigger order
order_link_id string Customised order ID
created_time string Creation time
updated_time 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

Conditional Orders

Place Conditional Order

Request Example

curl https://api.bybit.com/private/linear/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","reduce_only":false,"close_on_trigger":false,"timestamp":{timestamp},"sign":"{sign}"}'
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.LinearConditional.LinearConditional_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", reduce_only=False, close_on_trigger=False).result())

Response Example

{
    "ret_code": 0,
    "ret_msg": "ok",
    "ext_code": "",
    "result": {
       "stop_order_id":"bd1844f-f3c0-4e10-8c25-10fea03763f6",
       "user_id": 1,
       "symbol": "BTCUSDT",
       "side": "Sell",
       "order_type": "Limit",
       "price": 8083,
       "qty": 10,
       "time_in_force": "GoodTillCancel",
       "order_status": "New",
       "base_price": "16100.0000",
       "trigger_by": "LastPrice",
       "trigger_price": 8003,
       "order_link_id": "",
       "reduce_only": false,
       "close_on_trigger": false,
       "created_time": "2019-10-21T07:28:19.396246Z",
       "updated_time": "2019-10-21T07:28:19.396246Z",
       "tp_trigger_by": "UNKNOWN",
       "sl_trigger_by": "UNKNOWN",
    },
    "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 Symbol 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 /private/linear/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 number Order quantity in BTC
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 true 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.
reduce_only true bool What is a reduce-only order? True means your position can only reduce in size if this order is triggered. When reduce_only is true, take profit/stop loss cannot be set
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

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)
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
trigger_price number If stop_order_type is TrailingProfit, this field is the trailing stop active price.
order_link_id string Customised order ID
created_time string Creation time
updated_time 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
base_price string Market price at placing order
trigger_by string Trigger price type. Default LastPrice
reduce_only bool true means close order, false means open position
close_on_trigger bool Is close on trigger order

Get Conditional Order

Request Example

curl "https://api.bybit.com/private/linear/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.LinearConditional.LinearConditional_getOrders(symbol="BTCUSDT").result())

Response Example

{
    "ret_code": 0,
    "ret_msg": "ok",
    "ext_code": "",
    "result": {
        "current_page": 1,
        "last_page": 1,
        "data": [
            {
                 "stop_order_id":"bd1844f-f3c0-4e10-8c25-10fea03763f6",
                 "user_id": 1,
                 "symbol": "BTCUSDT",
                 "side": "Sell",
                 "order_type": "Limit",
                 "price": 8083,
                 "qty": 10,
                 "time_in_force": "GoodTillCancel",
                 "order_status": "New",
                 "trigger_price": 8003,
                 "order_link_id": "",
                 "created_time": "2019-10-21T07:28:19.396246Z",
                 "updated_time": "2019-10-21T07:28:19.396246Z",
                 "take_profit": 0,
                 "stop_loss": 0,
                 "tp_trigger_by": "UNKNOWN",
                 "sl_trigger_by": "UNKNOWN",
                 "base_price": "16100.0000",
                 "trigger_by": "LastPrice",
            },
            {
                 "stop_order_id":"bd1844f-f3c0-4e10-8c25-10fea03763f6",
                 "user_id": 1,
                 "symbol": "BTCUSDT",
                 "side": "Sell",
                 "order_type": "Limit",
                 "price": 8083,
                 "qty": 10,
                 "time_in_force": "GoodTillCancel",
                 "order_status": "New",
                 "trigger_price": 8003,
                 "order_link_id": "",
                 "created_time": "2019-10-21T07:28:19.396246Z",
                 "updated_time": "2019-10-21T07:28:19.396246Z",
                 "take_profit": 0,
                 "stop_loss": 0,
                 "tp_trigger_by": "UNKNOWN",
                 "sl_trigger_by": "UNKNOWN",
                 "base_price": "16100.0000",
                 "trigger_by": "LastPrice",
                 "reduce_only": false,
                 "close_on_trigger": false,
            }
        ]
    },
    "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 /private/linear/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 true string Symbol
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
stop_order_id string Conditional order ID. Once triggered, the conditional order creates an active order with the same ID (order_id)
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 Stop order status
trigger_price number If stop_order_type is TrailingProfit, this field is the trailing stop active price.
order_link_id string Customised order ID
created_time string Creation time
updated_time 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
base_price string Market price at placing order
trigger_by string Trigger price type. Default LastPrice
reduce_only bool true means close order, false means open position
close_on_trigger bool Is close on trigger order

Cancel Conditional Order

Request Example

curl https://api.bybit.com/private/linear/stop-order/cancel \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","symbol":"BTCUSDT","order_id":"","timestamp":{timestamp},"sign":"{sign}"}'
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.LinearConditional.LinearConditional_cancel(symbol="BTCUSDT", stop_order_id="52095ff7-b080-498e-b3a4-8b3e76c42f5e").result())

Response Example

{
    "ret_code": 0,
    "ret_msg": "ok",
    "ext_code": "",
    "result": {
         "stop_order_id":"bd1844f-f3c0-4e10-8c25-10fea03763f6",
    },
    "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 /private/linear/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/private/linear/stop-order/cancel-all \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","symbol":"BTCUSDT","timestamp":{timestamp},"sign":"{sign}"}'
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.LinearConditional.LinearConditional_cancelAll(symbol="BTCUSDT").result())

Response Example

{
    "ret_code": 0,
    "ret_msg": "OK",
    "ext_code": "",
    "ext_info": "",
    "result": [
        "89a38056-80f1-45b2-89d3-4d8e3a203a79",  
        "89a38056-80f1-45b2-89d3-4d8e3a203a79",
    ],
    "time_now": "1577454993.799912",
    "rate_limit_status": 90,
    "rate_limit_reset_ms": 1580885703683,
    "rate_limit": 100
}

Cancel all untriggered conditional orders.

HTTP Request

POST /private/linear/stop-order/cancel-all

Request Parameters

Parameter required type comments
symbol true string Symbol

Replace Conditional Order

Request Example

curl https://api.bybit.com/private/linear/stop-order/replace \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","symbol":"BTCUSDT","stop_order_id":"","timestamp":{timestamp},"sign":"{sign}"}'
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.LinearConditional.LinearConditional_replace(symbol="BTCUSDT", 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 /private/linear/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 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
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/private/linear/stop-order/search?api_key={api_key}&symbol=BTCUSDT&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.LinearConditional.LinearConditional_query(symbol="BTCUSDT", stop_order_id="").result())

Response Example

{
    "ret_code": 0,
    "ret_msg": "OK",
    "ext_code": "",
    "ext_info": "",
    "result": {
        "stop_order_id":"bd1844f-f3c0-4e10-8c25-10fea03763f6",
        "user_id": 1,
        "symbol": "BTCUSDT",
        "side": "Sell",
        "order_type": "Limit",
        "price": 8083,
        "qty": 10,
        "time_in_force": "GoodTillCancel",
        "order_status": "New",
        "trigger_price": 8003,
        "order_link_id": "",
        "created_time": "2019-10-21T07:28:19.396246Z",
        "updated_time": "2019-10-21T07:28:19.396246Z",
        "take_profit": 0,
        "stop_loss": 0,
        "tp_trigger_by": "UNKNOWN",
        "sl_trigger_by": "UNKNOWN",
        "base_price": "16100.0000",
        "trigger_by": "LastPrice",
        "reduce_only": false,
        "close_on_trigger": false,
    },
    "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": 1301180,
            "stop_order_id": "a1dbf284-b6ee-4eaf-9fda-2d3f3fa4c501",
            "symbol": "BTCUSDT",
            "side": "Buy",
            "order_type": "Limit",
            "price": 8020,
            "qty": 0.001,
            "time_in_force": "GoodTillCancel",
            "order_status": "Untriggered",
            "trigger_price": 16000,
            "order_link_id": "",
            "created_time": "2020-11-16T09:06:17.000Z",
            "updated_time": "2020-11-16T09:06:17.000Z",
            "take_profit": 0,
            "stop_loss": 0,
            "tp_trigger_by": "UNKNOWN",
            "sl_trigger_by": "UNKNOWN",
            "trigger_by": "LastPrice"
        },
        ...
        {
            "user_id": 1301180,
            "stop_order_id": "d4g5bf862-b6ee-4eaf-9fda-2d3f3fd9g4j6",
            "symbol": "BTCUSDT",
            "side": "Sell",
            "order_type": "Limit",
            "price": 8022,
            "qty": 0.005,
            "time_in_force": "GoodTillCancel",
            "order_status": "Untriggered",
            "trigger_price": 16000,
            "order_link_id": "",
            "created_time": "2020-11-16T09:06:17.000Z",
            "updated_time": "2020-11-16T09:06:17.000Z",
            "take_profit": 0,
            "stop_loss": 0,
            "tp_trigger_by": "UNKNOWN",
            "sl_trigger_by": "UNKNOWN",
            "trigger_by": "LastPrice"
        }
    ],
    "time_now": "1606445293.547976",
    "rate_limit_status": 599,
    "rate_limit_reset_ms": 1606445293545,
    "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 /private/linear/stop-order/search

Request Parameters

Parameter Required Type Comment
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 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)
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
trigger_price number If stop_order_type is TrailingProfit, this field is the trailing stop active price.
order_link_id string Customised order ID
created_time string Creation time
updated_time 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
base_price string Market price at placing order
trigger_by string Trigger price type. Default LastPrice
reduce_only bool true means close order, false means open position
close_on_trigger bool Is close on trigger order

Position

My Position

Request Example

curl https://api.bybit.com/private/linear/position/list?api_key={api_key}&symbol=BTCUSDT&timestamp={timestamp}&sign={sign}"
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.LinearPositions.LinearPositions_myPosition(symbol="BTCUSDT").result())

Response Example

{
    "ret_code": 0,
    "ret_msg": "OK",
    "ext_code": "",
    "ext_info": "",
    "result": [
       {
               "user_id":100004,
               "symbol":"BTCUSDT",
               "side":"Buy",
               "size":0,
               "position_value":0,      //Current position value
               "entry_price":0,         //Average opening price
               "liq_price":1,           //Liquidation price
               "bust_price":100,        //Bust price
               "leverage":0,
               "is_isolated":true,
               "auto_add_margin": 0,
               "position_margin":0,     //Position margin
               "occ_closing_fee":0,     //Pre-occupancy closing fee
               "realised_pnl":0,        //Today's realised Profit and Loss
               "cum_realised_pnl":0,    //Cumulative realised Profit and Loss
               "free_qty": 30,          //Qty which can be closed
               "tp_sl_mode": "Full",
               "unrealised_pnl": 0,
               "deleverage_indicator": 0,
               "risk_id": 0,
               "stop_loss": 0,
               "take_profit": 0,
               "trailing_stop": 0
           },
           {
               "user_id":100004,
               "symbol":"BTCUSDT",
               "side":"Sell",
               "size":0,
               "position_value":0,
               "entry_price":0,
               "liq_price":1,
               "bust_price":100,
               "leverage":0,
               "is_isolated":true,
               "auto_add_margin": 0,
               "position_margin":0,
               "occ_closing_fee":0,
               "realised_pnl":0,
               "cum_realised_pnl":0,
               "free_qty": 30,
               "tp_sl_mode": "Full",
               "unrealised_pnl": 0,
               "deleverage_indicator": 0,
               "risk_id": 0,
               "stop_loss": 0,
               "take_profit": 0,
               "trailing_stop": 0
           }
    ],
    "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
                "user_id": 118921,
                "symbol": "BTCUSDT",
                "side": "Buy",
                "size": 0.009,
                "position_value": 117.6845,
                "entry_price": 13076.05555555,
                "liq_price": 11834,
                "bust_price": 11768.5,
                "leverage": 10,
                "is_isolated":true,
                "auto_add_margin": 0,
                "position_margin": 11.84788704,
                "occ_closing_fee": 0.07943738,
                "realised_pnl": 0,
                "cum_realised_pnl": -1.50755354,
                "free_qty": 0.009,
                "tp_sl_mode": "Full",
                "unrealised_pnl": 0,
                "deleverage_indicator": 0,
                "risk_id": 0,
                "stop_loss": 0,
                "take_profit": 0,
                "trailing_stop": 0
            }
        },
        {
            "is_valid": true, //represents whether the current data is valid
            "data": { //the data can only be used when is_valid is true
                "user_id": 118921,
                "symbol": "BTCUSDT",
                "side": "Sell",
                "size": 0.001,
                "position_value": 13.078,
                "entry_price": 13078,
                "liq_price": 14320,
                "bust_price": 14385.5,
                "leverage": 10,
                "is_isolated":true,
                "auto_add_margin": 0,
                "position_margin": 1.31858935,
                "occ_closing_fee": 0.01078913,
                "realised_pnl": 0,
                "cum_realised_pnl": 164.30402588,
                "free_qty": 0.001,
                "tp_sl_mode": "Full",
                "unrealised_pnl": 0,
                "deleverage_indicator": 0,
                "risk_id": 0,
                "stop_loss": 0,
                "take_profit": 0,
                "trailing_stop": 0
            }
        },
        ...
        {
            "is_valid": true, //represents whether the current data is valid
            "data": { //the data can only be used when is_valid is true
                "user_id": 118921,
                "symbol": "XTZUSDT",
                "side": "Buy",
                "size": 0,
                "position_value": 0,
                "entry_price": 0,
                "liq_price": 0,
                "bust_price": 0,
                "leverage": 25,
                "is_isolated":true,
                "auto_add_margin": 0,
                "position_margin": 0,
                "occ_closing_fee": 0,
                "realised_pnl": 0,
                "cum_realised_pnl": 0,
                "free_qty": 0,
                "tp_sl_mode": "Full",
                "unrealised_pnl": 0,
                "deleverage_indicator": 0,
                "risk_id": 0,
                "stop_loss": 0,
                "take_profit": 0,
                "trailing_stop": 0
            }
        },
        {
            "is_valid": true, //represents whether the current data is valid
            "data": { //the data can only be used when is_valid is true
                "user_id": 118921,
                "symbol": "XTZUSDT",
                "side": "Sell",
                "size": 0,
                "position_value": 0,
                "entry_price": 0,
                "liq_price": 0,
                "bust_price": 0,
                "leverage": 25,
                "is_isolated":true,
                "auto_add_margin": 0,
                "position_margin": 0,
                "occ_closing_fee": 0,
                "realised_pnl": 0,
                "cum_realised_pnl": 0,
                "free_qty": 0,
                "tp_sl_mode": "Full",
                "unrealised_pnl": 0,
                "deleverage_indicator": 0,
                "risk_id": 0,
                "stop_loss": 0,
                "take_profit": 0,
                "trailing_stop": 0
            }
        }
    ],
    "time_now": "1604302080.356538",
    "rate_limit_status": 119,
    "rate_limit_reset_ms": 1604302080353,
    "rate_limit": 120
}



Get my position list.

HTTP Request

GET /private/linear/position/list

Request Parameters

Parameter Required Type Comment
symbol false string Symbol

Response Parameters

Parameter Type Comment
user_id number UserID
symbol string Symbol
side string Side
size number Position qty
position_value number Current position value
entry_price number Average opening price
liq_price number Liquidation price
bust_price number Bust price
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
auto_add_margin number Whether to add margin automatically
is_isolated bool true means isolated margin mode; false means cross margin mode
position_margin number Position margin
occ_closing_fee number Pre-occupancy closing fee
realised_pnl number Today's realised Profit and Loss
cum_realised_pnl number Cumulative realised Profit and Loss
free_qty number Qty which can be closed
tp_sl_mode string Stop loss and take profit mode
deleverage_indicator number Deleverage indicator level (1,2,3,4,5)
unrealised_pnl number unrealised pnl
risk_id integer Risk ID
take_profit string Take profit price
stop_loss string Stop loss price
trailing_stop string Trailing stop

Set Auto Add Margin

Request Example

curl https://api.bybit.com/private/linear/position/set-auto-add-margin \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","symbol":"BTCUSDT",margin="10","timestamp":{timestamp},"sign":"{sign}"}'
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.LinearPositions.LinearPositions_setAutoAddMargin(symbol="BTCUSDT", side="Sell", auto_add_margin=False).result())

Response Example

{
    "ret_code": 0,
    "ret_msg": "OK",
    "ext_code": "",
    "ext_info": "",
    "result": null,
    "time_now": "1586780385.549188",
    "rate_limit_status": 74,
    "rate_limit_reset_ms": 1586780385547,
    "rate_limit": 75
}

Set auto add margin, or Auto-Margin Replenishment.

HTTP Request

POST /private/linear/position/set-auto-add-margin

Request Parameters

Parameter Required Type Comment
symbol true string Symbol
side true string Side
auto_add_margin true bool Auto add margin button

Cross/Isolated Margin Switch

Request Example

curl https://api.bybit.com/private/linear/position/switch-isolated \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","symbol":"BTCUSDT","is_isolated":true,"buy_leverage":1,"sell_leverage":1,"timestamp":{timestamp},"sign":"{sign}"}'
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.LinearPositions.LinearPositions_switchIsolated(symbol="BTCUSDT", is_isolated=True, buy_leverage=1, sell_leverage=1).result())

Response Example

{
    "ret_code": 0,
    "ret_msg": "OK",
    "ext_code": "",
    "ext_info": "",
    "result": null,
    "time_now": "1585881597.006026",
    "rate_limit_status": 74,
    "rate_limit_reset_ms": 1585881597004,
    "rate_limit": 75
}

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

HTTP Request

POST /private/linear/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 Must be greater than 0 and less than the risk limit leverage.
sell_leverage true number Must be greater than 0 and less than the risk limit leverage.

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 /private/linear/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

Add/Reduce Margin

Request Example

curl https://api.bybit.com \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","symbol":"BTCUSDT","side":"Buy","margin":0.01","timestamp":{timestamp},"sign":"{sign}"}'
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.LinearPositions.LinearPositions_changeMargin(symbol="BTCUSDT", side="Buy", margin=0.01).result())

Response Example

{
    "ret_code": 0,
    "ret_msg": "OK",
    "ext_code": "",
    "ext_info": "",
    "result": {
        "PositionListResult": {
            "user_id": 160815,
            "symbol": "BTCUSDT",
            "side": "Buy",
            "size": 3.14,
            "position_value": 18843.14,
            "entry_price": 6001,
            "liq_price": 5428,
            "bust_price": 5398,
            "leverage": 10,
            "position_margin": 1907.0331195,
            "occ_closing_fee": 12.71229,
            "realised_pnl": 3052.20905294,
            "cum_realised_pnl": 75628.40815795,
            "free_qty": 0
        },
        "wallet_balance": 68738.01696765,
        "available_balance": 66830.98384815
    },
     "time_now": "1577480599.097287",
     "rate_limit_status": 119,
     "rate_limit_reset_ms": 1580885703683,
     "rate_limit": 120
}

Add Margin

HTTP Request

POST /private/linear/position/add-margin

Request Parameters

Parameter Required Type Comment
symbol true string Symbol
side true string Side
margin true number Add/Remove how much margin: Increase 10; decrease -10, supports 4 decimal places

Response Parameters

Parameter Type Comment
user_id number UserID
symbol string Symbol
side string Side
size number Position qty
position_value number Current position value
entry_price number Average opening price
liq_price number Liquidation price
bust_price number Bust price
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
occ_closing_fee number Pre-occupancy closing fee
realised_pnl number Today's realised Profit and Loss
cum_realised_pnl number Cumulative realised Profit and Loss
free_qty number Qty which can be closed
wallet_balance number Wallet Data Endpoints
available_balance number Available balance = wallet balance - used margin

Set Leverage

Request Example

curl https://api.bybit.com/private/linear/position/set-leverage \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","symbol":"BTCUSDT","buy_leverage":10,"sell_leverage":10"sign":"{sign}"}'
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.LinearPositions.LinearPositions_saveLeverage(symbol="BTCUSDT", buy_leverage=10, sell_leverage=10).result())

Response Example

{
    "ret_code": 0,
    "ret_msg": "OK",
    "ext_code": "",
    "ext_info": "",
    "result": null,
    "time_now": "1585881527.650138",
    "rate_limit_status": 74,
    "rate_limit_reset_ms": 1585881527648,
    "rate_limit": 75
}

Set Leverage

HTTP Request

POST /private/linear/position/set-leverage

Request Parameters

Parameter Required Type Comment
symbol true string Symbol
buy_leverage true number Must be greater than 0 and less than the risk limit leverage.
sell_leverage true number Must be greater than 0 and less than the risk limit leverage.

Set Trading-Stop

Request Example

curl https://api.bybit.com/private/linear/position/trading-stop \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","symbol":"BTCUSDT","side":"Buy","take_profit":10,"timestamp":{timestamp},"sign":"{sign}"}'
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.LinearPositions.LinearPositions_tradingStop(symbol="BTCUSDT", side="Buy", take_profit=10).result())

Response Example

{
  "ret_code": 0,
  "ret_msg": "OK",
  "ext_code": "",
  "ext_info": "",
  "result": null,
  "time_now": "1586780408.193508",
  "rate_limit_status": 73,
  "rate_limit_reset_ms": 1586780408191,
  "rate_limit": 75
}

Set take profit, stop loss, and trailing stop for your open position. If using partial mode, TP/SL/TS orders will not close your entire position.

HTTP Request

POST /private/linear/position/trading-stop

Request Parameters

Parameter Required Type Comment
symbol true string Symbol
side true string Position side
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
sl_size false number Stop loss quantity (when in partial mode)
tp_size false number Take profit quantity (when in partial mode)

User Trade Records

Request Example

curl "https://api.bybit.com/private/linear/trade/execution/list?api_key={api_key}&symbol=BTCUSDT&timestamp={timestamp}&sign={sign}"
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.LinearExecution.LinearExecution_getTrades(symbol="BTCUSDT").result())

Response Example

{
    "ret_code": 0,
        "ret_msg": "OK",
        "ext_code": "",
        "ext_info": "",
        "result": {
            "current_page": 1,
            "data": [
                {
                    "order_id": "7369b2f4-52f1-4698-abf7-368e4ba9aefa",
                    "order_link_id": "",
                    "side": "Buy",  //Side Enum
                    "symbol": "BTCUSDT", //Symbol Enum
                    "exec_id": "9b8216fa-98d7-55c0-b5fa-279db5727996",
                    "price": 5894,//Abandoned!!
                    "order_price": 5894,
                    "order_qty": 0.001,
                    "order_type": "Limit", //Order Type Enum
                    "fee_rate": 0.00075,
                    "exec_price": 5894,
                    "exec_type": "Trade", //Exec Type Enum
                    "exec_qty": 0.001,
                    "exec_fee": 0.0044205,
                    "exec_value": 5.894,
                    "leaves_qty": 0,
                    "closed_size": 0, // The corresponding closing size of the closing order
                    "last_liquidity_ind": "RemovedLiquidity",  //Liquidity Enum, only valid while exec_type is Trade, AdlTrade, BustTrade
                    "trade_time": 1585547384,//Abandoned!!
                    "trade_time_ms": 1585547384847
                }
            ]
        },
        "time_now": "1577480599.097287",
        "rate_limit_status": 119,
        "rate_limit_reset_ms": 1580885703683,
        "rate_limit": 120
    }

}

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

HTTP Request

GET /private/linear/trade/execution/list

Request Parameters

Parameter Required Type Comment
symbol true string Symbol
start_time false integer Start timestamp point for result, in milliseconds. Timestamp must be within seven days of the current date. For earlier records, please contact customer support
end_time false integer End timestamp point for result, in milliseconds. Timestamp must be within seven days of the current date. For earlier records, please contact customer support
exec_type false string Execution type
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.

Response Parameters

Parameter Type Comment
order_id string Order ID
order_link_id string Customised order ID
side string Side
symbol string Symbol
order_price number Order price
order_qty number Order qty
order_type string Order type
fee_rate number Maker or taker fee rate
exec_price number Transaction price
exec_type string Exec Type Enum
exec_qty number Transaction qty
exec_fee number Transaction fee
exec_value number Transaction value
leaves_qty number Number of unfilled contracts from the order's size
closed_size number The corresponding closing size of the closing order
last_liquidity_ind string Liquidity Enum, only valid while exec_type is Trade, AdlTrade, BustTrade
trade_time_ms number Transaction timestamp

Closed Profit and Loss

Request Example

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

Response Example

{
     "ret_code": 0,
     "ret_msg": "OK",
     "ext_code": "",
     "ext_info": "",
     "result": {
         "current_page": 1,
         "data": [
             {
                 "id": 1710,
                 "user_id": 160815,
                 "symbol": "BTCUSDT",
                 "order_id": "e6a11e08-6dd0-404e-bea7-dc22b7ab0228",
                 "side": "Buy",
                 "qty": 0.5,
                 "order_price": 999999,
                 "order_type": "Market",
                 "exec_type": "Trade",
                 "closed_size": 0.5,        //Closed size
                 "cum_entry_value": 3000,   //Closed position value
                 "avg_entry_price": 6000,   //Average entry price
                 "cum_exit_value": 3000.5,  //Cumulative trading value of position closing orders
                 "avg_exit_price": 6001,    //Average exit price
                 "closed_pnl": -5.000375,   //Closed Profit and Loss
                 "fill_count": 1,           //The number of fills in a single order
                 "leverage": 100,
                 "created_at": 1577480599
             }
         ]
     },
     "time_now": "1577480599.097287",
     "rate_limit_status": 119,
     "rate_limit_reset_ms": 1580885703683,
     "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 /private/linear/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 qty
order_price number Order price
order_type string Order type
exec_type string Exec type
closed_size number Closed size
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

Risk Limit

Get Risk Limit

Request Example

curl "https://api.bybit.com/public/linear/risk-limit?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.LinearWallet.LinearWallet_getRiskLimit(symbol="BTCUSDT").result())

Response Example

{
    "ret_code":0,
    "ret_msg":"OK",
    "ext_code":"",
    "ext_info":"",
    "result":[
        {
            "id":1,
            "symbol":"BTCUSDT",
            "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":"BTCUSDT",
            "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 /public/linear/risk-limit

Request Parameters

Parameter Required Type Comment
symbol true 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/private/linear/position/set-risk \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","symbol":"BTCUSDT","risk_id":2,"timestamp":{timestamp},"sign":"{sign}"}'
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.LinearPositions.LinearPositions_setRiskLimit(symbol="BTCUSDT", side="Buy",risk_id=1).result())

Response Example

{
    "ret_code": 0,
    "ret_msg": "OK",
    "ext_code": "",
    "ext_info": "",
    "result": {
        "risk_id": 2
    },
    "time_now": "1609839125.563609",
    "rate_limit_status": 73,
    "rate_limit_reset_ms": 1609839125560,
    "rate_limit": 75
}

Set risk limit.

HTTP Request

POST /private/linear/position/set-risk

Request Parameters

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

Response Parameters

Parameter Type Comment
risk_id number Risk ID

Funding

Predicted Funding Rate and My Funding Fee

Request Example

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

Response Example

{
    "ret_code": 0,
    "ret_msg": "OK",
    "ext_code": "",
    "ext_info": "",
    "result": {
        "predicted_funding_rate": -0.00375,
        "predicted_funding_fee": 0.13081256
    },
    "time_now": "1587035697.424492",
    "rate_limit_status": 119,
    "rate_limit_reset_ms": 1587035697422,
    "rate_limit": 120
}

Get predicted funding rate and my predicted funding fee.

HTTP Request

GET /private/linear/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

My Last Funding Fee

Request Example

curl "https://api.bybit.com/private/linear/funding/prev-funding?api_key={api_key}&symbolt=BTCUSDT&timestamp={timestamp}&sign={sign}"
import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.LinearFunding.LinearFunding_prevRate(symbol="BTCUSDT").result())

Response Example

{
    "ret_code": 0,
    "ret_msg": "OK",
    "ext_code": "",
    "ext_info": "",
    "result": {
        "symbol": "BTCUSDT",
        "side": "Buy",
        "size": 3.13,
        "funding_rate": 0.0001,
        "exec_fee": 1.868923,
        "exec_time": "2020-04-13T08:00:00.000Z"
    },
    "time_now": "1586780352.867171",
    "rate_limit_status": 119,
    "rate_limit_reset_ms": 1586780352864,
    "rate_limit": 120
}

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

HTTP Request

GET /private/linear/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_time string Transaction time

API Key Info

Please see the shared endpoint.

LCP Info

Please see the shared endpoint.

Wallet Data Endpoints

The following wallet data endpoints require authentication.

Get Wallet Balance

Please see the shared endpoint.

Wallet Fund Records

Please see the shared endpoint.

Withdraw Records

Please see the shared endpoint.

Asset Exchange Records

Please see the shared endpoint.

API Data Endpoints

The following API data endpoints do not require authentication.

Server Time

Request Example

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

Response Example

{
    "ret_code": 0,
    "ret_msg": "OK",
    "ext_code": "",
    "ext_info": "",
    "result": {},
    "time_now": "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 and account asset but SPOT is separate from them. Mainnet 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 /private/linear/order/create 1 / request
/private/linear/order/cancel 1 / request
/private/linear/order/cancel-all 10 / request
/private/linear/stop-order/create 1 / request
/private/linear/stop-order/cancel 1 / request
/private/linear/stop-order/cancel-all 10 / request
75/min /private/linear/position/set-leverage 1 / request
/private/linear/position/switch-isolated 1 / request
/private/linear/tpsl/switch-mode 1 / request
/private/linear/position/set-auto-add-margin 1 / request
/private/linear/position/trading-stop 1 / request
/private/linear/position/add-margin 1 / request
120/min /private/linear/position/list 1 / request
/private/linear/trade/closed-pnl/list 1 / request
/private/linear/trade/execution/list 1 / request
600/min /private/linear/order/list 1 / request
/private/linear/order/search 1 / request
/private/linear/stop-order/list 1 / request
/private/linear/stop-order/search 1 / request
120/min /private/linear/funding/prev-funding 1 / request
/private/linear/funding/predicted-funding 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 ETHUSDT
ws.send('{"op":"subscribe","args":["trade.ETHUSDT"]}')

Subscribe with multiple filters

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

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"]}');

Unsubscribing From Websocket Topics

How to unsubscribe with a filter

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

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.BTCUSDT.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.BTCUSDT"]}');
from BybitWebsocket import BybitWebsocket
ws = BybitWebsocket(wsURL="wss://stream-testnet.bybit.com/realtime_public",
                    api_key=None, api_secret=None)
ws.subscribe_orderBookL2(symbol="BTCUSDT")
while True:
    data = ws.get_data("orderBookL2_25.BTCUSDT")
    if data:
        print(data)

Snapshot Response Example - format of the first response

{
     "topic": "orderBookL2_25.BTCUSDT",
     "type": "snapshot",
     "data": {
         "order_book":[
             {
                 "price": "2999.00",
                 "symbol": "BTCUSDT",
                 "id": 29990000,
                 "side": "Buy",
                 "size": 9
             },
             {
                 "price": "3001.00",
                 "symbol": "BTCUSDT",
                 "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.BTCUSDT",
     "type": "delta",
     "data": {
          "delete": [
             {
                   "price": "3001.00",
                   "symbol": "BTCUSDT",
                   "id": 30010000,
                   "side": "Sell"
             }
          ],
          "update": [
             {
                   "price": "2999.00",
                   "symbol": "BTCUSDT",
                   "id": 29990000,
                   "side": "Buy",
                   "size": 8
             }
          ],
          "insert": [
             {
                   "price": "2998.00",
                   "symbol": "BTCUSDT",
                   "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.BTCUSDT"]}');

Snapshot Response Example - format of the first response

{
     "topic": "orderBook_200.100ms.BTCUSDT",
     "type": "snapshot",
     "data": {
         "order_book":[
             {
                 "price": "2999.00",
                 "symbol": "BTCUSDT",
                 "id": 29990000,
                 "side": "Buy",
                 "size": 9
             },
             {
                 "price": "3001.00",
                 "symbol": "BTCUSDT",
                 "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.BTCUSDT",
     "type": "delta",
     "data": {
          "delete": [
             {
                   "price": "3001.00",
                   "symbol": "BTCUSDT",
                   "id": 30010000,
                   "side": "Sell"
             }
          ],
          "update": [
             {
                   "price": "2999.00",
                   "symbol": "BTCUSDT",
                   "id": 29990000,
                   "side": "Buy",
                   "size": 8
             }
          ],
          "insert": [
             {
                   "price": "2998.00",
                   "symbol": "BTCUSDT",
                   "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.BTCUSDT"]}')

Response Example - format of all responses

{
    "topic": "trade.BTCUSDT",
    "data": [
        {
            "symbol": "BTCUSDT",
            "tick_direction": "PlusTick",
            "price": 8098,
            "size": 328,
            "timestamp":"2020-03-30T02:21:06.000Z",
            "trade_time_ms":"1585534866418",
            "side":"Sell",
            "trade_id":"01e79e28-d1f4-59ac-b079-ca909606d91a"
        }
    ]
}

Get real-time trading information.

Response Parameters

Parameter Type Comment
symbol string Symbol
tick_direction string Direction of price change
price number Order price
size number Position qty
time string UTC time
trade_time_ms string Millisecond timestamp
side string Side
trade_id string Trade ID

instrument_info

How to Subscribe

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

Snapshot Response Example - format of the first response

{
  "topic": "instrument_info.100ms.BTCUSDT",
  "type": "snapshot",
  "data": {
       "id": 1,
       "symbol": "BTCUSDT",
       "last_price_e4": "322955000",
       "last_price": "322955000",
       "last_tick_direction": "ZeroPlusTick",
       "prev_price_24h_e4": "331960000",
       "prev_price_24h": "331960000",
       "price_24h_pcnt_e6": "-27126",
       "high_price_24h_e4": "333120000",
       "high_price_24h": "333120000",
       "low_price_24h_e4": "315940000",
       "low_price_24h": "315940000",
       "prev_price_1h_e4": "319490000",
       "prev_price_1h": "319490000",
       "price_1h_pcnt_e6": "10845",
       "mark_price_e4": "323133000",
       "mark_price": "323133000",
       "index_price_e4": "323106800",
       "index_price": "323106800",
       "open_interest_e8": "1430451600000",
       "total_turnover_e8": "5297934997553700000",
       "turnover_24h_e8": "243143978993099700",
       "total_volume_e8": "1184936057899924",
       "volume_24h_e8": "7511238100000",
       "funding_rate_e6": "100",
       "predicted_funding_rate_e6": "-15",
       "cross_seq": "6501157651",
       "created_at": "1970-01-01T00:00:00.000Z",
       "updated_at": "2021-07-14T09:32:10.000Z",
       "next_funding_time": "2021-07-14T16:00:00Z",
       "count_down_hour": "7",
       "bid1_price_e4": "322950000",
       "ask1_price_e4": "322955000"
       "bid1_price": "322950000",
       "ask1_price_e4": "322955000",
       "ask1_price": "322955000",
  },
  "cross_seq": "6501157734",
  "timestamp_e6": "1626255131908287"
}

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

{
  "topic": "instrument_info.100ms.BTCUSDT",
  "type": "delta",
  "data": {
    "update": [
      {
        "id": 1,
        "symbol": "BTCUSDT",
        "last_price_e4": "322950000",
        "last_price": "322950000",
        "price_24h_pcnt_e6": "-27141",
        "price_1h_pcnt_e6": "10829",
        "index_price_e4": "323100000",
        "index_price": "323100000",
        "total_turnover_e8": "5297935000783200000",
        "turnover_24h_e8": "243143982222599700",
        "total_volume_e8": "1184936057999924",
        "volume_24h_e8": "7511238200000",
        "cross_seq": "6501157735",
        "created_at": "1970-01-01T00:00:00.000Z",
        "updated_at": "2021-07-14T09:32:12.000Z"
      }
    ]
  },
  "cross_seq": "6501157736",
  "timestamp_e6": "1626255132104671"
}

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_e8 integer Open interest * 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_e8 integer Total volume * 10^8
volume_24h_e8 integer Trading volume in the last 24 hours * 10^8
funding_rate_e6 integer Funding rate * 10^6
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 number Countdown of settlement capital cost
bid1_price_e4 integer (Deprecated) Best bid price * 10^4
ask1_price_e4 integer (Deprecated) Best ask price * 10^4
bid1_price integer Best bid price
ask1_price integer Best ask price

kline

How to Subscribe

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

Response Example - format of all responses

{
    "topic":"candle.1.BTCUSDT",
    "data":[
        {
            "start":1588071660,
            "end":1588071720,
            "open":7744.5,
            "close":7745,
            "high":7745,
            "low":7744,
            "volume":"33.051",
            "turnover":"255979.995",
            "confirm":true,
            "cross_seq":71947372,
            "timestamp":1588071717325846
        }
    ],
    "timestamp_e6":1588071721163975
}

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 string Trading volume
turnover string 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.XRPUSDT"]}')

Response Example - format of all responses

{
    "topic":"liquidation.XRPUSDT",
    "data": {
        "symbol":"XRPUSDT",
        "side":"Sell",
        "price":"3384.15",
        "qty":"0.057",
        "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
time number Millisecond timestamp

Private Topics

position

How to Subscribe

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

Response Example - format of all responses

{
   "topic": "position",
   "action": "update",
   "data": [
       {
           "user_id":  1,
           "symbol": "BTCUSD",
           "size": 11,
           "side": "Sell",
           "position_value": "0.00159252",
           "entry_price": "6907.291588174717",
           "liq_price": "7100.234",
           "bust_price": "7088.1234",
           "leverage": "1",
           "order_margin":  "1",
           "position_margin":  "1",
           "occ_closing_fee":  "0.1",
           "take_profit":  "0.1",
           "tp_trigger_by": 0,
           "stop_loss":  "0.12",
           "sl_trigger_by": "Normal",
           "realised_pnl": "Normal",
           "cum_realised_pnl": "Normal",
           "position_seq": 14
       }
   ]
}

Get my position list.

Response Parameters

Parameter Type Comment
user_id number UserID
symbol string Symbol
size number Position qty
side string Side
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
occ_closing_fee string Position closing fee occupied (your opening fee + expected maximum closing fee)
take_profit string Take profit price
tp_trigger_by number Take profit trigger price type, default: LastPrice
stop_loss string Stop loss price
sl_trigger_by string string
realised_pnl string Today's realised pnl
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_private",
                    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": "BTCUSDT",
            "side": "Sell",
            "order_id": "xxxxxxxx-xxxx-xxxx-9a8f-4a973eb5c418",
            "exec_id": "xxxxxxxx-xxxx-xxxx-8b66-c3d2fcd352f6",
            "order_link_id": "",
            "price": 11527.5,
            "order_qty": 0.001,
            "exec_type": "Trade",
            "exec_qty": 0.001,
            "exec_fee": 0.00864563,
            "leaves_qty": 0,
            "is_maker": false,
            "trade_time": "2020-08-12T21:16:18.142746Z"
        }
    ]
}

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
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_private",
                    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",
    "action": "",
    "data": [
        {
            "order_id": "xxxxxxxx-xxxx-xxxx-9a8f-4a973eb5c418",
            "order_link_id": "",
            "symbol": "BTCUSDT",
            "side": "Buy",
            "order_type": "Limit",
            "price": 11000,
            "qty": 0.001,
            "leaves_qty": 0.001,
            "last_exec_price": 0,
            "cum_exec_qty": 0,
            "cum_exec_value": 0,
            "cum_exec_fee": 0,
            "time_in_force": "GoodTillCancel",
            "create_type": "CreateByUser",
            "cancel_type": "UNKNOWN",
            "order_status": "New",
            "take_profit": 0,
            "stop_loss": 0,
            "trailing_stop": 0,
            "reduce_only": false,
            "close_on_trigger": false,
            "create_time": "2020-08-12T21:18:40.780039678Z",
            "update_time": "2020-08-12T21:18:40.787986415Z"
        }
    ]
}

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
order_status string Order status
last_exec_price number Last execution price
cum_exec_qty number Cumulative qty of trading
cum_exec_value string Cumulative value of trading
cum_exec_fee string Cumulative trading fees
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.
create_time string Commission time
update_time string Update time

stop_order

How to Subscribe

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

Response Example - format of all responses

{
    "topic": "stop_order",
    "data": [
        {
            "stop_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",
            "order_status": "Untriggered", //Stop Order Status
            "stop_order_type": "Stop",
            "trigger_by": "LastPrice",
            "trigger_price": "8584.5",
            "reduce_only": false,
            "close_on_trigger": false,
            "create_time": "2020-01-14T14:11:22.062Z",
            "update_time": "2020-01-14T14:11:22.062Z"
        }
    ]
}

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)
order_link_id string Customised order ID
user_id number UserID
symbol string Symbol Enum
side string Side
order_type string Order Type Enum
price string Order price
qty number Order quantity in USD
time_in_force string Time in force
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.
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.
created_at string Creation time
updated_at string Update time

wallet

How to Subscribe

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

Response Example - format of all responses

{
    "topic": "wallet",
    "data": [
        {
            "wallet_balance":429.80713,
            "available_balance":429.67322
        }
    ]
}

Response Parameters

Parameter Type Comment
wallet_balance number Wallet Data Endpoints
available_balance number Available balance = wallet balance - used margin

Archive Data

Historical Market Data

You can get Bybit's historical market data here.

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
33004 apikey already expired
35014 over order limit
130001 Not get position
130002 wallet is nil
130003 the pz status is not normal
130004 Order number is out of permissible range
130005 Order price is out of permissible range
130006 order qty is out of permissible range
130007 Order price is out of permissible range
130008 order_type invalid
130009 The number of contracts below min limit allowed
130010 order not exists or Too late to operate
130011 Operation not allowed as position is undergoing liquidation
130012 Operation not allowed as position is undergoing ADL
130013 stop_order trail value invalid
130014 stop_order trigger price invalid
130015 stop_order expected_direction or base_price invalid
130016 invalid stop_order_type, cannot replace price
130017 invalid stop_order_type, cannot replace qty
130018 invalid trail_value
130019 invalid stop_order_type, cannot replace trigger_price
130020 invalid stop_order_type, cannot replace trail_value
130021 order cost not available
130024 cannot set tp_sl_ts for zero position
130025 below < 10% of base price
130026 the price is too high
130027 the price set for Buy position should be higher than base_price
130028 the price set for Sell position should be between base_price and liq_price
130029 the price set for Buy position should be between liq_price and base_price
130030 the price set for Sell position should be lower than base_price
130032 invalid order_status, cannot cancel or execute trigger
130033 number of stop order >= 10
130034 stop_order cannot replace
130035 Too freq to cancel, Try it later
130037 Order already cancelled
130040 position will be liq
130041 AvailableBalanceE8 less than 0
130049 available balance not enough
130050 Any adjustments made will trigger liq
130051 cannot set leverage, due to risk limit
130052 cannot set leverage, below the lower limit
130056 the position is in cross_margin
130057 the position size is 0
130058 can not set margin less than minPositionCost
130059 can not set pz open limit more than symbol limit
130060 autoAddMargin not changed
130061 not change fee, invalid req
130062 can not set pz open limit less than current buy pz value
130063 can not set pz open limit less than current sell pz value
130064 just support usdt
130074 expect Rising, trigger_price <= current
130075 expect Falling, trigger_price >= current
130076 replace params invalid
130077 the deposit req has handled
130078 the withdraw req has handled
130079 the rotate req has handled
130101 unknown request for create order
130102 unknown request for cancel order
130103 unknown request for cancelAll
130104 unknown request for LiqExecuteReq, req param not match liqExecuteReq
130105 unknown request for pre create order
130106 unknown req for query order
130107 unmatch request for triggeredToActiveImpl
130108 unknown request for addMargin
130109 unknown request for calculatePositionPnl
130110 unknown request for qryAssetImpl
130111 unknown request for query_position_list
130112 unknown request for setAutoAddMargin
130113 unknown request for setFeeRate
130114 unknown request for setLeverage
130115 unknown request for setMargin
130116 unknown request for setOpenLimit
130117 unknown request for setTpSlTs
130118 unknown request for settleFundingFeeReq
130119 unknown request for setPositionMode
130120 unknown request for walletDeposit
130121 unknown request for walletWithDraw
130122 unknown request for rotateRealisedPnl
130123 unknown request for AdlExecute
130124 unknown request for AdlCleanReq
130125 No change made for TP/SL price
130126 No orders
130023 Will be triggered Liq after order is completed
130127 Take Profit, Stop Loss and Trailing Stop Loss are not modified
130145 Close order side is large than position's leaving qty
130149 Order creation successful but SL/TP setting failed
130150 Please try again later.
130151 Switching failed. Please cancel the current SL/TP setting
130152 Switching failed. Please cancel the current SL/TP setting
130153 Switching failed. Please cancel the current SL/TP setting
130154 Switching failed. Please cancel the SL/TP setting of active orders
130155 Insufficient quantity required to set TP/SL
130156 Replacing active order price and qty simultaneously is not allowed
130157 Amendment failed. SL/TP price cannot be amended as order is partially filled
130158 SL/TP price cannot be amended under 'Full' position mode
130159 Max SL/TP orders under 'Partial' mode is 20
134026 Risk limit has not been changed.
132011 Current position size exceeds risk limit. Risk limit adjustment failed.
130090 Risk limit is invalid.

Enums Definitions

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

Side (side)

Symbol (symbol)

You can get all symbols with the Query Symbol endpoint.

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)

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)

Stop order type (stop_order_type)