Group And Resources
Bybit API and WebSocket documentation provides guidance to help you access Bybit's endpoints, their expected outputs, and common errors.
For further assistance or feedback, please join the API Telegram chat! API discussion group on Telegram.
API Resources and Support Channels
Help Center - Learn more about exchange mechanisms here!
pybit - Official Python SDK
bybit-api - Community NodeJS SDK
QuickStartWithPostman - Postman API Collection
API Discussion Group - get English help here!
API Discussion Group (Chinese) - get Chinese help here!
Bybit API Announcement - subscribe for changes to the API!
Bybit Open API Survey - The survey should take no more than 5 minutes to complete.
Changelog
2022-10-12
REST API
- Latest Information for Symbol [update]
- Deprecated the following fields. Now returns a default value:
countdown_hour
: 0
predicted_funding_rate
: ""
total_turnover
: ""
total_volume
: 0
price_1h_pcnt
: ""
open_value
: ""
- Deprecated the following fields. Now returns a default value:
- Get Risk Limit [update]
- Deprecated
created_at
andupdated_at
. Now returns an empty string.
- Deprecated
2022-09-19
REST API
- API Key Info [new]
- Add new response field
affiliate_id
- Add new response field
2022-08-25
WebSocket API
- stop_order [update]
- Add
take_profit
andstop_order
fields
- Add
2022-04-29
REST API
- Place Active Order & Query Symbol [update]
- Increase maximum trading qty for
PostOnly
orders. Please refer topost_only_max_trading_qty
in Query Symbol endpoint
- Increase maximum trading qty for
2022-03-01
REST API
- Query Symbol [update]
- Add response parameters
funding_interval
.
- Add response parameters
2022-02-28
REST API
- Query Trading Fee Rate [new]
- API Key Info [update]
- Add response parameters
vip_level
andmkt_maker_level
in API Key Info 。
- Add response parameters
2021
2021-12-28
REST API
- Public Trading Records [update]
- Remove
from
field from parameters of Public Trading Records.
- Remove
2021-09-24
REST API
- Liquidated Orders [abandoned]
- This endpoint is now offline. Please replace with the liquidation websocket.
2021-09-14
WebSocket API
- liquidation [new]
- This shift to a websocket helps ensure a fair trading environment by preventing some traders from getting early access to market information. Please ensure you switch to the websocket service before 2021-09-24. Thank you for your continued support!
REST API
- Liquidated Orders [abandoned]
- Will be fully offline on 2021-09-24. Please replace with the liquidation websocket.
2021-09-03
WebSocket API
- instrumentInfo [update]
- Deprecate
prev_price_24h_e4
in favour ofprev_price_24h
- Deprecate
high_price_24h_e4
in favour ofhigh_price_24h
- Deprecate
low_price_24h_e4
in favour oflow_price_24h
- Deprecate
prev_price_1h_e4
in favour ofprev_price_1h
- Deprecate
mark_price_e4
in favour ofmark_price
- Deprecate
index_price_e4
in favour ofindex_price
- Deprecate
last_price_e4
in favour oflast_price
- Deprecate
2021-08-23
REST API
- Wallet Fund Records [update]
- Add additional enums for
wallet_fund_type
:ReturnServiceCash
,Insurance
,SubMember
Coupon
,AccountTransfer
,CashBack
- Add additional enums for
2021-07-29
REST API
- Set Leverage [update]
- Add parameter
leverage_only
Use this parameter to set leverage while in cross margin mode.
If this field is set tofalse
, whenleverage
is equal to0
the position will use cross margin; whenleverage
is greater than0
the position will use isolated margin.
If this field is set totrue
, you can set leverage in cross margin withleverage
.leverage
must be greater than0
.
Use the Cross/Isolated Margin Switch endpoint to switch cross/isolated without modifying the cross level of leverage.
- Add parameter
- Cross/Isolated Margin Switch [update]
- Update
buy_leverage
andsell_leverage
parameters to be always required
- Update
2021-06-28
REST API
- Query Symbol [update]
- Fix values of
min_price
andtick_size
for symbolsBCHUSDT
andUNIUSDT
- Fix values of
2021-06-18
REST API
- Cross/Isolated Margin Switch [update]
is_isolated
illustrates if position is Isolated Margin or Cross Margin- Deprecate to use
auto_add_margin
to determine if position is Isolated Margin or Cross Margin - Not recommend to use Set Leverage endpoint switch Isolated Margin or Cross Margin
2021-06-03
REST API
- Full/Partial Position TP/SL Switch [new]
- Place Conditional Order [update]
- Support setting take profit and stop loss; Add new request parameters:
take_profit
,stop_loss
,tp_trigger_by
,sl_trigger_by
- Add response parameters:
take_profit
,stop_loss
,tp_trigger_by
,sl_trigger_by
- Support setting take profit and stop loss; Add new request parameters:
- Place Active Order [update]
- Add new request parameters
tp_trigger_by
,sl_trigger_by
- Add response parameters:
take_profit
,stop_loss
,tp_trigger_by
,sl_trigger_by
- Add new request parameters
- My Position [update]
- Add response parameters:
tp_sl_mode
- Add response parameters:
- Set Trading-Stop [update]
- Support creating partial take profit and stop loss orders; Add new request parameters:
sl_size
,tp_size
- Support creating partial take profit and stop loss orders; Add new request parameters:
- Cancel Conditional Order [update]
- Support cancelling take profit and stop loss orders
- Replace Conditional Order [update]
- Support replacing take profit stop loss orders; Add new request parameters:
take_profit
,stop_loss
,tp_trigger_by
,sl_trigger_by
- Support replacing take profit stop loss orders; Add new request parameters:
- Replace Active Order [update]
- Support replacing take profit stop loss orders; Add new request parameters:
take_profit
,stop_loss
,tp_trigger_by
,sl_trigger_by
- Support replacing take profit stop loss orders; Add new request parameters:
- Get Active Order [update]
- Add response parameters:
take_profit
,stop_loss
,tp_trigger_by
,sl_trigger_by
- Add response parameters:
- Query Active Order (real-time) [update]
- Add response parameters:
take_profit
,stop_loss
,tp_trigger_by
,sl_trigger_by
- Add response parameters:
- Get Conditional Order [update]
- Add response parameters:
take_profit
,stop_loss
,tp_trigger_by
,sl_trigger_by
- Add response parameters:
- Query Conditional Order (real-time) [update]
- Add response parameters:
take_profit
,stop_loss
,tp_trigger_by
,sl_trigger_by
- Add response parameters:
2021-05-11
REST API
- Set Risk Limit [new]
- Get Risk Limit [new]
2021-05-11
REST API
- Set Leverage [update]
- Add fields
buy_leverage
,sell_leverage
. leverage
- Not Recommand
- Add fields
- Position Mode Switch [new]
- Cross/Isolated Margin Switch [new]
2021-04-22
REST API
- LCP Info [update]
- Deprecated Fields of self_ratio and platform_ratio, it is returned as 0 currently
2021-04-07
REST API
- Fix value of
price
of Liquidated Orders fromliq_price
tobust_price
, you can find more about liquidation here
2021-04-02
REST API
- Add comment of errcode 10016,10018,30074,30075
2021-03-24
- Get Risk Limit [update]
- Query risk limit return field added maximum leverage
max_leverage
- Query risk limit return field added maximum leverage
2021-03-22
- Wallet Fund Records [update]
- Fix the bug that the filtering function doesn't work for parameter
start_date
andend_date
- Fix the bug that the filtering function doesn't work for parameter
2021-03-15
REST API
- Prior to December 31, 2020, order price of a market order was returned as the last traded price as of the moment of order placement. On and after December 31, 2020, order price of a market order is returned as a revised limit price. For more information, please refer to description of market order.
2021-03-12
REST API
- Fix value of
exec_type,last_liquidity_ind
for User Trade Record endpoint
2021-03-11
- Get Active Order [update]
- Fix sequence of response data
- Get Conditional Order [update]
- Fix sequence of response data
2021-03-04
- Wallet Fund Records [update]
- Fix the bug that the filtering function doesn't work for parameter
wallet_fund_type
- Fix the bug that the filtering function doesn't work for parameter
2021-02-02
WebSocket API
Topic order [update]
- Add fields
reduce_only
,close_on_trigger
- Add fields
Topic stop_order [update]
- Add field
close_on_trigger
- Add field
2021-01-25
REST API
- Get the Last Funding Rate [update]
/v2/private/funding/prev-funding-rate
- Not recommended- Replaced by:
/v2/public/funding/prev-funding-rate
2021-01-12
REST API
- Query Index Price Kline [new]
- Query Premium Index Kline [new]
2020
2020-12-31
REST API
After a service upgrade, a number of v2
endpoints have been added to replace the old routes:
- Set Leverage [new]
/user/leverage/save
- Not recommended- Replaced by:
/v2/private/position/leverage/save
- Wallet Fund Records [new]
/open-api/wallet/fund/records
- Not recommended- Replaced by:
/v2/private/wallet/fund/records
- Withdraw Records [new]
/open-api/wallet/withdraw/list
- Not recommended- Replaced by:
/v2/private/wallet/withdraw/list
- Change Margin [new]
/position/change-position-margin
- Not recommended- Replaced by:
/v2/private/position/change-position-margin
- API Key Info [new]
/open-api/api-key
- Not recommended- Replaced by:
/v2/private/account/api-key
- Set Trading-Stop [new]
/open-api/position/trading-stop
- Not recommended- Replaced by:
/v2/private/position/trading-stop
- Get the Last Funding Rate [new]
/open-api/funding/prev-funding-rate
- Not recommended- Replaced by:
/v2/private/funding/prev-funding-rate
- My Last Funding Fee [new]
/open-api/funding/prev-funding
- Not recommended- Replaced by:
/v2/private/funding/prev-funding
- Predicted Funding Rate and My Funding Fee [new]
/open-api/funding/predicted-funding
- Not recommended- Replaced by:
/v2/private/funding/predicted-funding
2020-12-17
REST API
- Query Conditional Order (real-time) [update]
- Real-time queries can return multiple unfilled orders
- Query Active Order (real-time) [update]
- Real-time queries can return multiple unfilled orders
2020-11-20
REST API
- Get Conditional Order [update]
- Add field
trigger_by
in response
- Add field
2020-11-12
REST API
- Get Active Order [update]
order_status
query orders with specific statuses by passing eachorder_status
split with ','.
- Get Conditional Order [update]
stop_order_status
query orders with specific statuses by passing eachstop_order_status
split with ','.
2020-11-10
WebSocket API
The abandoned endpoints will be deprecated on November 30, 2020
- Topic orderBook25 [abandoned]
- please replace with orderBookL2_25 or orderBookL2_200
- Topic kline [abandoned]
- please replace with klineV2
- Topic instrument [abandoned]
- please replace with instrumentInfo
REST API
The following REST API will be upgraded. The abandoned endpoints will be deprecated on December 10, 2020. Effective immediately, the rate limit will be reduced by half before being completely removed from service on December 17, 2020.
- Get Active Order [abandoned]
- please replace with Get Active Order [new]
- Get Conditional Order [abandoned]
- please replace with Get Conditional Order [new]
- Place Conditional Order [abandoned]
- please replace with Place Conditional Order [new]
- Cancel Conditional Order [abandoned]
- please replace with Cancel Conditional Order [new]
- Replace Conditional Order [abandoned]
- please replace with Replace Conditional Order [new]
- Replace Active Order [abandoned]
- please replace with Replace Active Order [new]
- User Leverage [abandoned]
- please replace with My Position
- /open-api/order/create [abandoned]
- please replace with Place Active Order
- /open-api/order/cancel [abandoned]
- please replace with Cancel Active Order
- /position/list [abandoned]
- please replace with My Position
2020-11-02
REST API
- Position [update]
- Request parameter
symbol
is optional now; If symbol is not passed, return positions of all symbols
- Request parameter
2020-10-26
REST API
- Position [update]
- Add field
is_isolated
in response
- Add field
2020-10-21
REST API
- Get Wallet Balance [update]
- Fix bug of
given_cash
andservice_cash
are always Zero when coin isUSDT
- Fix bug of
- Set Trading-Stop [update]
- Support setting tp/sl by different trigger price types
2020-10-12
REST API
- Get Conditional Order [bugfix]
- Fix issue where not returning stop orders of
Deactivated
status
- Fix issue where not returning stop orders of
- Query Active Order (real-time) [bugfix]
- Fix issue where returning wrong
cum_exec_fee
for filled orders
- Fix issue where returning wrong
2020-09-27
REST API
- Replace Active Order [update]
- Support replace order by
order_link_id
- Support replace order by
- Replace Conditional Order [update]
- Support replace order by
order_link_id
- Support replace order by
WebSocket API
- Add new websocket base endpoint [update]
2020-09-15
REST API
- Long-Short Ratio [update]
- Fix Account Long-short ratio data error
- Place Conditional Order [update]
- Change the return value of the field
time_in_force
of placing conditional market order fromGoodTillCancel
toImmediateOrCancel
which is the actual execution strategy
- Change the return value of the field
2020-08-19
REST API
- Open Interest [new]
- Latest Big Deal [new]
- Long-Short Ratio [new]
2020-07-07
REST API
- Asset Exchange Records [new]
- Get Wallet Balance [update]
- Returns all wallet balances if no parameters are passed
- Get User Trade Records [update]
- Adjust the return quantity from 50 to 200
2020-06-22
REST API
- Closed Profit and Loss [new]
- Query Mark Price Kline [new]
2020-05-21
REST API
- Liquidated Orders [new]
2020-04-29
REST API
- Get User Trade Records [update]
- Add new request parameter
order
- Add new request parameter
- API Key Info [bugfix]
- Fix bug of always returning Zero for
inviter_id
under certain conditions
- Fix bug of always returning Zero for
2020-04-27
REST API
- LCP Info [new]
- Latest Information for Symbol [update]
- Return symbol
BTCUSDT
by default
- Return symbol
2020-04-17
REST API
- Order Book [update]
- Add new symbol
BTCUSDT
- Add new symbol
- Latest Information for Symbol [update]
- Add new symbol
BTCUSDT
- Add new symbol
- Get User Trade Records [update]
- Add new response param
trade_time_ms
- Update support millisecond
start_time
- Abandon response field
trade_time
- Add new response param
2020-04-14
REST API
- Query Symbol [update]
- Updated
BTCUSDT
contract information
- Updated
2020-03-31
REST API
- Get Wallet Balance [update]
- Fix incorrect balance of
USDT
- Fix incorrect balance of
2020-03-26
REST API
- Set Trading-Stop [update]
- Add trigger price
new_trailing_active
for trailing stop order.
- Add trigger price
2020-03-16
REST API
- Position [update]
- Add field
effective_leverage
in response
- Add field
- Get Wallet Balance [update]
- Fix value of field
equity
ofUSDT
- Fix value of field
2020-03-09
REST API
- Get User Trade Records [update]
- Symbol is require
- API Key Info [update]
- Add
inviter_id
in response
- Add
2020-03-02
WebSocket API
- trade [update]
- Add new field
trade_time_ms
- Add new field
2020-02-26
REST API
- Place Active Order
- Remove
trailing_stop
field from parameters of place order endpoint. Currently, this field is useless.
- Remove
2020-02-10
REST API
- Get Wallet Balance [new]
- Replace Active Order [update]
- Add
order_id
in response
- Add
- Replace Conditional Order [update]
- Add
stop_order_id
in response - Add a new request parameter
stop_order_id
to replaceorder_id
for consistency
- Add
- Fix value of
rate_limit_reset_ms
in V2 private endpoints' response frommicroseconds
tomillisecond
, be consistent with V1 endpoint [bugfix]
2019
2019-12-27
REST API
- Set Risk Limit [new]
- Get Risk Limit [new]
2019-12-18
REST API
- My Position [new]
WebSocket API
- orderBookL2_200 [new]
2019-12-13
REST API
2019-12-02
REST API
- Place Active Order [new]
- Cancel Active Order [new]
- Cancel All Active Orders [new]
- Cancel All Conditional Orders [new]
2019-11-19
REST API
- Public Trading Records [new]
2019-11-07
REST API
- Set Leverage [update]
- [My position] [update]
- Change Margin [update]
- Set Trading-Stop [update]
2019-11-04
REST API
- Announcement [new]
- Cancel order [update]
- Support cancel order by
order_link_id
- Support cancel order by
- Cancel Conditional Order [update]
- Support cancel conditional order by
order_link_id
- Support cancel conditional order by
- API Key Info [update]
- Add extra info
- Update
ips
field to return content
- Update REST API rate limit [update]
- The rate limit is accurate to milliseconds
- Refine the rate limit of the endpoints
- Add new response fields:
rate_limit_reset_ms
,rate_limit
WebSocket API
- klineV2 [new]
- stop_order [new]
2019-10-22
REST API
WebSocket API
- position [update]
- Add extra info, eg. wallet_balance
- trade [update]
- Fix issue of sometimes push same trade multi times
- Support pushing multi trades in single message
FAQ
reduce_only
and close_on_trigger
- what's the difference?
- To close your position, submit an order and specify
reduce_only
totrue
.close_on_trigger
is not strictly applicable here, but you can also set it totrue
if it's required. reduce_only
is the one that really matters for closing position, and we will improve the interface in the future.- Be careful when you specify
close_on_trigger
totrue
as it could cause conflict whenreduce_only
isfalse
.
Why aren't all my orders showing on the website?
- Users who have bots which place large numbers of laddered orders will be restricted by the frontend interface, which only shows a maximum of 50 orders on-screen.
- Don't worry, your orders are still in the system and can be queried by the API, but the frontend cannot show more than 50.
Calculating order size based on available wallet balance
price * available_balance * leverage * perc * (1 - (0.0006 * 2))
- Unfortunately this is not a perfectly accurate formula; the real calculation is complex and may be published in the docs at a later date.
price
- last price (or your entry price) - can be found with the Latest Symbol Info endpoint.available_balance
- can be found with the My Position endpoint.leverage
- up to the respective maximum leverage for the market and your risk limit (eg 2, 10, 50).perc
- 0.1 for 10%, 0.25 for 25%, etc.1 - (0.0006 * 2)
- used to calculate the maximum order cost (always assumes entry & exit orders use taker fee regardless actual fee).
Can I exchange assets with the API?
- There is no endpoint to exchange assets. This can only be done on the website.
- However, it is possible to access your Asset Exchange Records 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?
- The
entry_price
andexit_price
returned by Closed PNL endpoints are not the actual execution prices of the orders. - It is based on the total costs of the order
- (whether or not the position was only opened/closed by one order executed at one price - it is more complicated if multiple orders opened/closed a position.)
- For instance, the
entry_price
andexit_price
reported by this endpoint are influenced by the fee paid/received on the orders.
Why are values returned to too many decimal places? (float precision issue)
- For example, you received
11.969999
but you expected11.97
. - Some values are returned to too many decimal places, or a fraction too high or low, due to a float precision problem.
- For now, we recommend rounding the received value to the correct decimal place. This can be done with reference to the Query Symbol endpoint.
- This issue
will behas been fixed in the latest major version of the API: v3. You can see the documentation for the v3 websocket here.
How can I ensure I am using up-to-date data?
- It is possible, although unlikely, that the REST API or (even less likely) the websocket could return/push old data.
- For the greatest level of data resilience, we recommend clients to:
- firstly, rely on the websocket, which will not only ensure you get the latest data as fast as possible, but will also ensure you get complete data
- secondly, query the REST API to fill in any discrepencies in data - or between websocket disconnections.
- The best practice is to save all of this data locally in your own database or cache.
- This frees up your rate limits for other requests and also ensures a level of redundancy against the exchange in case of data delays.
What is the difference between turnover and volume?
- Turnover: is in the opposite currency to the quantity's currency
- Volume: is in the same currency as the quantity's currency
Authentication
All requests made to private endpoints must be authenticated. Requests made to public endpoints do not require additional authentication.
Parameters for Authenticated Endpoints
The following parameters must be used for authentication:
- api_key
- timestamp - UTC timestamp in milliseconds
- sign - a signature derived from the request's parameters
We also provide 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=XXXXXXXXXX&leverage=100&symbol=BTCUSD×tamp=1542434791747"
param_str = "api_key=XXXXXXXXXX&leverage=100&symbol=BTCUSD×tamp=1542434791747"
# api_key=XXXXXXXXXX&
# leverage=100&
# symbol=BTCUSD&
# timestamp=1542434791747
Note how the parameters are ordered in alphabetical order, with api_key first followed by leverage, then symbol, then timestamp.
1. Concatenate all the public parameters in the query string format. The parameters must be ordered in alphabetical order. This will be used to generate the sign
.
2. Use the HMAC_SHA256 algorithm to sign the query string in step 1, and convert it to a hex string to obtain the sign parameter.
Different requests need different message formats. Message format for GET requests:
GET /v2/private/order?symbol=BTCUSD&api_key=XXXXXXXXXX×tamp=1542434791000&sign=670e3e4aa32b243f2dedf1dafcec2fd17a440e71b05681550416507de591d908 HTTP/1.1
Host: api-testnet.bybit.com
Message format for POST requests:
POST /v2/private/order/cancel HTTP/1.1
Host: api-testnet.bybit.com
Content-Type: application/json
{
"api_key": "XXXXXXXXXX",
"symbol": "BTCUSD",
"order_id": "3bd1844f-f3c0-4e10-8c25-10fea03763f6",
"timestamp": 1542434791000,
"sign": "670e3e4aa32b243f2dedf1dafcec2fd17a440e71b05681550416507de591d908"
}
3. Append the sign parameter to the end of the parameters string, and send the HTTP request. Note that the message format for GET and POST requests is different. Please refer to the examples.
Market Data Endpoints
The following market data endpoints do not require authentication.
Order Book
Request Example
curl https://api-testnet.bybit.com/v2/public/orderBook/L2?symbol=BTCUSD
from pybit import inverse_perpetual
session_unauth = inverse_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com"
)
print(session.orderbook(symbol="BTCUSD"))
Response Example
{
"ret_code": 0,
"ret_msg": "OK",
"ext_code": "",
"ext_info": "",
"result": [
{
"symbol": "BTCUSD",
"price": "9487",
"size": 336241,
"side": "Buy"
},
{
"symbol": "BTCUSD",
"price": "9487.5",
"size": 522147,
"side": "Sell"
}
],
"time_now": "1567108756.834357"
}
Get the orderbook. Each side has a depth of 25.
HTTP Request
GET
/v2/public/orderBook/L2
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
symbol | true | string | Symbol |
Response Parameters
Parameter | Type | Comment |
---|---|---|
symbol | string | Symbol |
price | string | Order price |
size | integer | Symbol contracts |
side | string | Side |
Query Kline
Request Example
curl https://api-testnet.bybit.com/v2/public/kline/list?symbol=BTCUSD&interval=1&limit=2&from=1581231260
from pybit import inverse_perpetual
session_unauth = inverse_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com"
)
print(session_unauth.query_kline(
symbol="BTCUSD",
interval="D",
from_time="1653408000"
))
Response Example
{
"ret_code": 0,
"ret_msg": "OK",
"ext_code": "",
"ext_info": "",
"result": [{
"symbol": "BTCUSD",
"interval": "1",
"open_time": 1581231300,
"open": "10112.5",
"high": "10112.5",
"low": "10112",
"close": "10112",
"volume": "75981",
"turnover": "7.51394369"
}, {
"symbol": "BTCUSD",
"interval": "1",
"open_time": 1581231360,
"open": "10112",
"high": "10112.5",
"low": "10112",
"close": "10112",
"volume": "24616",
"turnover": "2.4343353100000003"
}],
"time_now": "1581928016.558522"
}
Get kline.
HTTP Request
GET
/v2/public/kline/list
Request Parameters
parameter | Required | Type | Comment |
---|---|---|---|
symbol | true | string | Symbol |
interval | true | string | Data refresh interval. Enum : 1 3 5 15 30 60 120 240 360 720 "D" "M" "W" |
from | true | integer | From timestamp in seconds |
limit | false | integer | Limit for data size per page, max size is 200. Default as showing 200 pieces of data per page |
Response Parameters
Parameter | Type | Comment |
---|---|---|
symbol | string | Symbol |
interval | string | Data refresh interval. Enum : 1 3 5 15 30 60 120 240 360 720 "D" "M" "W" |
open_time | integer | Starting time |
open | string | Starting price |
high | string | Maximum price |
low | string | Minimum price |
close | string | Closing price |
volume | string | Trading volume |
turnover | string | Turnover |
Latest Information for Symbol
Request Example
curl https://api-testnet.bybit.com/v2/public/tickers
from pybit import inverse_perpetual
session_unauth = inverse_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com"
)
print(session_unauth.latest_information_for_symbol(
symbol="BTCUSD"
))
Response Example
{
"ret_code": 0,
"ret_msg": "OK",
"result": [
{
"symbol": "BTCUSD",
"bid_price": "19244.5",
"ask_price": "19245",
"last_price": "19244.50",
"last_tick_direction": "MinusTick",
"prev_price_24h": "18780.50",
"price_24h_pcnt": "0.024706",
"high_price_24h": "19582.00",
"low_price_24h": "18492.50",
"prev_price_1h": "19217.00",
"mark_price": "19242.60",
"index_price": "19229.37",
"open_interest": 4.13999123e+08,
"countdown_hour": 0,
"turnover_24h": "1977.97821021",
"volume_24h": 3.7810482e+07,
"funding_rate": "0.0001",
"predicted_funding_rate": "",
"next_funding_time": "2022-09-08T16:00:00Z",
"predicted_delivery_price": "",
"total_turnover": "",
"total_volume": 0,
"delivery_fee_rate": "",
"delivery_time": "",
"price_1h_pcnt": "",
"open_value": ""
}
],
"ext_code": "",
"ext_info": "",
"time_now": "1662629551.232415"
}
Get the latest information for symbol.
HTTP Request
GET
/v2/public/tickers
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
symbol | false | string | Symbol |
Response Parameters
Parameter | Type | Comment |
---|---|---|
symbol | string | Symbol |
bid_price | string | Purchase price of the first order |
ask_price | string | Selling price of the first order |
last_price | string | Latest transaction price |
last_tick_direction | string | Direction of price change |
prev_price_24h | string | Price of 24 hours ago |
price_24h_pcnt | string | Percentage change of market price relative to 24h |
high_price_24h | string | The highest price in the last 24 hours |
low_price_24h | string | Lowest price in the last 24 hours |
prev_price_1h | string | Hourly market price an hour ago |
price_1h_pcnt | string | Percentage change of market price relative to 1 hour ago |
mark_price | string | Mark price |
index_price | string | Index_price |
open_interest | number | Open interest |
open_value | string | Open position value |
total_turnover | string | Total turnover |
turnover_24h | string | Turnover for 24h |
total_volume | number | Total volume |
volume_24h | number | Trading volume in the last 24 hours |
funding_rate | string | Funding rate |
predicted_funding_rate | string | Predicted funding rate |
next_funding_time | string | Next settlement time of capital cost |
countdown_hour | number | Countdown of settlement capital cost |
delivery_fee_rate | string | Delivery fee rate of Futures contract |
predicted_delivery_price | string | Predicted delivery price of Futures contract |
delivery_time | string | Delivery time of Futures contract |
Public Trading Records
Request Example
curl https://api-testnet.bybit.com/v2/public/trading-records?symbol=BTCUSD
from pybit import inverse_perpetual
session_unauth = inverse_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com"
)
print(session_unauth.public_trading_records(
symbol="BTCUSD"
))
Response Example
{
"ret_code": 0,
"ret_msg": "OK",
"ext_code": "",
"ext_info": "",
"result": [
{
"id": 7724919,
"symbol": "BTCUSD",
"price": 9499.5,
"qty": 9500,
"side": "Buy",
"time": "2019-11-19T08:03:04.077Z"
}
],
"time_now": "1567109419.049271"
}
Get recent trades. You can find a complete history of trades on Bybit here.
HTTP Request
GET
/v2/public/trading-records
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
symbol | true | string | Symbol |
limit | false | int | Limit for data size, max size is 1000. Default size is 500 |
Response Parameters
Parameter | Type | Comment |
---|---|---|
id | number | Latest data ID |
symbol | string | Symbol |
price | number | Execution price |
qty | number | Order quantity in USD |
side | string | Side of taker order |
time | string | UTC time |
Query Symbol
Request Example
curl https://api-testnet.bybit.com/v2/public/symbols
from pybit import inverse_perpetual
session_unauth = inverse_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com"
)
print(session.query_symbol())
Response Example
{
"ret_code":0,
"ret_msg":"OK",
"ext_code":"",
"ext_info":"",
"result":[
{
"name":"BTCUSD",
"alias":"BTCUSD",
"status":"Trading",
"base_currency":"BTC",
"quote_currency":"USD",
"price_scale":2,
"taker_fee":"0.00075",
"maker_fee":"-0.00025",
"funding_interval":480,
"leverage_filter":{
"min_leverage":1,
"max_leverage":100,
"leverage_step":"0.01"
},
"price_filter":{
"min_price":"0.5",
"max_price":"999999.5",
"tick_size":"0.5"
},
"lot_size_filter":{
"max_trading_qty":1000000,
"min_trading_qty":1,
"qty_step":1,
"post_only_max_trading_qty":"5000000"
}
},
{
"name":"EOSUSD",
"alias":"EOSUSD",
"status":"Trading",
"base_currency":"EOS",
"quote_currency":"USD",
"price_scale":3,
"taker_fee":"0.00075",
"maker_fee":"-0.00025",
"funding_interval":480,
"leverage_filter":{
"min_leverage":1,
"max_leverage":50,
"leverage_step":"0.01"
},
"price_filter":{
"min_price":"0.001",
"max_price":"1999.999",
"tick_size":"0.001"
},
"lot_size_filter":{
"max_trading_qty":1000000,
"min_trading_qty":1,
"qty_step":1,
"post_only_max_trading_qty":"5000000"
}
},
{
"name":"BTCUSDT",
"alias":"BTCUSDT",
"status":"Trading",
"base_currency":"BTC",
"quote_currency":"USDT",
"price_scale":2,
"taker_fee":"0.00075",
"maker_fee":"-0.00025",
"funding_interval":480,
"leverage_filter":{
"min_leverage":1,
"max_leverage":100,
"leverage_step":"0.01"
},
"price_filter":{
"min_price":"0.5",
"max_price":"999999.5",
"tick_size":"0.5"
},
"lot_size_filter":{
"max_trading_qty":100,
"min_trading_qty":0.001,
"qty_step":0.001,
"post_only_max_trading_qty":"500"
}
},
{
"name":"BTCUSDM22",
"alias":"BTCUSD0624",
"status":"Trading",
"base_currency":"BTC",
"quote_currency":"USD",
"price_scale":2,
"taker_fee":"0.00075",
"maker_fee":"-0.00025",
"funding_interval":480,
"leverage_filter":{
"min_leverage":1,
"max_leverage":100,
"leverage_step":"0.01"
},
"price_filter":{
"min_price":"0.5",
"max_price":"999999.5",
"tick_size":"0.5"
},
"lot_size_filter":{
"max_trading_qty":1000000,
"min_trading_qty":1,
"qty_step":1,
"post_only_max_trading_qty":"5000000"
}
}
],
"time_now":"1615801223.589808"
}
Get symbol info.
HTTP Request
GET
/v2/public/symbols
Request Parameters
parameter | Required | Type | Comment |
---|
Response Parameters
Parameter | Type | Comment |
---|---|---|
name | string | Symbol name |
alias | string | Symbol name |
status | string | Symbol status |
base_currency | string | Base currency |
quote_currency | string | Quote currency |
price_scale | number | Price scale (the number of decimal places to which a price can be submitted, although the final price may be rounded to conform to the tick_size ) |
taker_fee | string | Taker fee |
maker_fee | string | Maker fee |
funding_interval | number | Funding fee interval |
min_leverage | number | Min leverage |
max_leverage | number | Max leverage (indicates the max leverage, assuming the lowest risk limit setting) |
leverage_step | string | Leverage step |
min_price | string | Min price |
max_price | string | Max price |
tick_size | string | Tick size |
max_trading_qty | number | Max trading quantity |
min_trading_qty | number | Min trading quantity |
qty_step | number | Qty step |
post_only_max_trading_qty | string | Max trading quantity of PostOnly orders |
Query Mark Price Kline
Request Example
curl "https://api-testnet.bybit.com/v2/public/mark-price-kline?symbol=BTCUSD&interval=1&limit=2&from=1581231260"
print(session_unauth.query_mark_price_kline(
symbol="BTCUSD",
interval="D",
from_time=1653408000
))
Response Example
{
"ret_code":0,
"ret_msg":"OK",
"ext_code":"",
"ext_info":"",
"result":[
{
"id":2,
"symbol":"BTCUSD",
"period":"1",
"start_at":1582231260,
"open":100,
"high":120,
"low":88,
"close":115
}
],
"time_now":"1591263582.601795"
}
Query mark price kline (like Query Kline but for mark price).
HTTP Request
GET
/v2/public/mark-price-kline
Request Parameters
parameter | Required | Type | Comment |
---|---|---|---|
symbol | true | string | Symbol |
interval | true | string | Data refresh interval. Enum : 1 3 5 15 30 60 120 240 360 720 "D" "M" "W" |
from | true | integer | From timestamp in seconds |
limit | false | integer | Limit for data size, max size is 200. Default as showing 200 pieces of data |
Response Parameters
Parameter | Type | Comment |
---|---|---|
symbol | string | Symbol |
period | string | Data recording period. 5min , 15min , 30min , 1h , 4h , 1d |
start_at | integer | Start timestamp point for result, in seconds |
open | integer | Starting price |
high | integer | Maximum price |
low | integer | Minimum price |
close | integer | Closing price |
Query Index Price Kline
Request Example
curl "https://api-testnet.bybit.com/v2/public/index-price-kline?symbol=BTCUSD&interval=1&limit=2&from=1581231260"
from pybit import inverse_perpetual
session_unauth = inverse_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com"
)
print(session_unauth.query_index_price_kline(
symbol="BTCUSD",
interval="D",
from_time=1653408000
))
Response Example
{
"ret_code":0,
"ret_msg":"OK",
"ext_code":"",
"ext_info":"",
"result":[
{
"symbol":"BTCUSD",
"period":"1",
"open_time":1582231260,
"open":"10106.09",
"high":"10108.75",
"low":"10104.66",
"close":"10108.73"
}
],
"time_now":"1591263582.601795"
}
Index price kline. Tracks BTC spot prices, with a frequency of every second (learn more here).
HTTP Request
GET
/v2/public/index-price-kline
Request Parameters
parameter | Required | Type | Comment |
---|---|---|---|
symbol | true | string | Symbol |
interval | true | string | Data refresh interval. Enum : 1 3 5 15 30 60 120 240 360 720 "D" "M" "W" |
from | true | integer | From timestamp in seconds |
limit | false | integer | Limit for data size, max size is 200. Default as showing 200 pieces of data |
Response Parameters
Parameter | Type | Comment |
---|---|---|
symbol | string | Symbol |
period | string | Data recording period. 5min , 15min , 30min , 1h , 4h , 1d |
open_time | integer | Start timestamp point for result, in seconds |
open | string | Starting price |
high | string | Maximum price |
low | string | Minimum price |
close | string | Closing price |
Query Premium Index Kline
Request Example
curl "https://api-testnet.bybit.com/v2/public/premium-index-kline?symbol=BTCUSD&interval=1&limit=2&from=1581231260"
from pybit import inverse_perpetual
session_unauth = inverse_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com"
)
print(session_unauth.query_premium_index_kline(
symbol="BTCUSD",
interval="D",
from_time=1653408000
))
Response Example
{
"ret_code":0,
"ret_msg":"OK",
"ext_code":"",
"ext_info":"",
"result":[
{
"symbol":"BTCUSD",
"period":"1",
"open_time":1582231260,
"open":"0.000588",
"high":"0.000618",
"low":"0.000588",
"close":"0.000618"
}
],
"time_now":"1591263582.601795"
}
Premium index kline. Tracks the premium / discount of BTC perpetual contracts relative to the mark price per minute (learn more here).
HTTP Request
GET
/v2/public/premium-index-kline
Request Parameters
parameter | Required | Type | Comment |
---|---|---|---|
symbol | true | string | Symbol |
interval | true | string | Data refresh interval. Enum : 1 3 5 15 30 60 120 240 360 720 "D" "M" "W" |
from | true | integer | From timestamp in seconds |
limit | false | integer | Limit for data size, max size is 200. Default as showing 200 pieces of data |
Response Parameters
Parameter | Type | Comment |
---|---|---|
symbol | string | Symbol |
period | string | Data recording period. 5min , 15min , 30min , 1h , 4h , 1d |
open_time | integer | Start timestamp point for result, in seconds |
open | string | Starting price |
high | string | Maximum price |
low | string | Minimum price |
close | string | Closing price |
Advanced Data
Open Interest
Request Example
curl https://api-testnet.bybit.com/v2/public/open-interest?symbol=BTCUSD&period=5min
from pybit import inverse_perpetual
session_unauth = inverse_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com"
)
print(session_unauth.open_interest(
symbol="BTCUSD",
period="30min"
))
Response Example
{
"ret_code":0,
"ret_msg":"OK",
"ext_code":"",
"ext_info":"",
"result":[
{
"open_interest":371491978,
"timestamp":1597658100,
"symbol":"BTCUSD"
},
{
"open_interest":370696076,
"timestamp":1597657800,
"symbol":"BTCUSD"
}
],
"time_now":"1597658304.938839"
}
Gets the total amount of unsettled contracts. In other words, the total number of contracts held in open positions.
HTTP Request
GET
/v2/public/open-interest
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
symbol | true | string | Symbol |
period | true | string | Data recording period. 5min , 15min , 30min , 1h , 4h , 1d |
limit | false | int | Limit for data size per page, max size is 200. Default as showing 50 pieces of data per page |
Response Parameters
Parameter | Type | Comment |
---|---|---|
open_interest | number | Number of contracts in open interest |
timestamp | number | Timestamp |
symbol | string | Symbol |
Latest Big Deal
Request Example
curl https://api-testnet.bybit.com/v2/public/big-deal?symbol=BTCUSD
from pybit import inverse_perpetual
session_unauth = inverse_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com"
)
print(session_unauth.latest_big_deal(
symbol="BTCUSD",
limit=10
))
Response Example
{
"ret_code":0,
"ret_msg":"OK",
"ext_code":"",
"ext_info":"",
"result":[
{
"symbol":"BTCUSD",
"side":"Sell",
"timestamp":1597623362,
"value":1242368
},
{
"symbol":"BTCUSD",
"side":"Buy",
"timestamp":1597623363,
"value":1242368
}
],
"time_now":"1597658434.219859"
}
Obtain filled orders worth more than 500,000 USD within the last 24h.
This endpoint may return orders which are over the maximum order qty for the symbol you call. For instance, the maximum order qty for BTCUSD is 1 million contracts, but in the event of the liquidation of a position larger than 1 million this endpoint returns this "impossible" order size.
HTTP Request
GET
/v2/public/big-deal
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
symbol | true | string | Symbol |
limit | false | int | Limit for data size per page, max size is 1000. Default as showing 500 pieces of data per page |
Response Parameters
Parameter | Type | Comment |
---|---|---|
symbol | string | Symbol |
side | string | Side |
timestamp | number | Timestamp |
value | number | Value of the order |
Long-Short Ratio
Request Example
curl https://api-testnet.bybit.com/v2/public/account-ratio?symbol=BTCUSD&period=5min
from pybit import inverse_perpetual
session_unauth = inverse_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com"
)
print(session_unauth.long_short_ratio(
symbol="BTCUSD",
limit=2,
period="5min"
))
Response Example
{
"ret_code":0,
"ret_msg":"OK",
"ext_code":"",
"ext_info":"",
"result":[
{
"symbol":"BTCUSD",
"buy_ratio":0.6538,
"sell_ratio":0.3462,
"timestamp":1597659000
},
{
"symbol":"BTCUSD",
"buy_ratio":0.6533,
"sell_ratio":0.3467,
"timestamp":1597658700
}
],
"time_now":"1597659230.743313"
}
Gets the Bybit user accounts' long-short ratio.
HTTP Request
GET
/v2/public/account-ratio
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
symbol | true | string | Symbol |
period | true | string | Data recording period. 5min , 15min , 30min , 1h , 4h , 1d |
limit | false | int | Limit for data size per page, max size is 500. Default as showing 50 pieces of data per page |
Response Parameters
Parameter | Type | Comment |
---|---|---|
symbol | string | Symbol |
buy_ratio | number | Long position ratio |
sell_ratio | number | Short position ratio |
timestamp | number | Timestamp |
Account Data Endpoints
The following account data endpoints require authentication.
Active Orders
Place Active Order
Request Example
curl https://api-testnet.bybit.com/v2/private/order/create \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","side":"Buy","symbol":"BTCUSD","order_type":"Market","qty":10,"time_in_force":"GoodTillCancel","timestamp":{timestamp},"sign":"{sign}"}'
from pybit import inverse_perpetual
session_auth = inverse_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com",
api_key="your api key",
api_secret="your api secret"
)
print(session_auth.place_active_order(
symbol="BTCUSD",
side="Buy",
order_type="Market",
qty=1,
time_in_force="GoodTillCancel"
))
Response Example
{
"ret_code": 0,
"ret_msg": "OK",
"ext_code": "",
"ext_info": "",
"result": {
"user_id": 533285,
"order_id": "a1904030-f99c-4e35-9217-111591f08493",
"symbol": "BTCUSD",
"side": "Buy",
"order_type": "Limit",
"price": 20010,
"qty": 200,
"time_in_force": "GoodTillCancel",
"order_status": "Created",
"last_exec_time": 0,
"last_exec_price": 0,
"leaves_qty": 200,
"cum_exec_qty": 0,
"cum_exec_value": 0,
"cum_exec_fee": 0,
"reject_reason": "EC_NoError",
"order_link_id": "",
"created_at": "2022-06-20T06:56:22.070Z",
"updated_at": "2022-06-20T06:56:22.070Z",
"take_profit": "22000.00",
"stop_loss": "19000.00",
"tp_trigger_by": "MarkPrice",
"sl_trigger_by": "MarkPrice"
},
"time_now": "1655708182.071362",
"rate_limit_status": 99,
"rate_limit_reset_ms": 1655708182068,
"rate_limit": 100
}
Market price: A traditional market price order which will be filled at the best available price. price
is not required for this type of order.
To protect market order from excessive slippage, Bybit converts a market order into a limit order with a spread. A market buy order is converted into a limit order at a higher than best ask price; a market sell order is converted into a limit order at a lower than best bid price.
The converted limit price and executed price are both available in trade history..
Limit price: You can set an execution price for your order. The system will fill your order once the last traded price reaches your execution price.
Take profit/Stop loss: You may only set a TP/SL conditional order upon opening the position. Once you hold a position, any new active order requests which contain TP/SL data will be accepted but the TP/SL data will be ignored. tp_trigger_by
/sl_trigger_by
default to LastPrice. Passing values to the take_profit
or stop_loss
parameters in this endpoint will create conditional orders managed by the system, which will be be automatically cancelled if the position is closed.
Order quantity: This parameter indicates the quantity of perpetual contracts you want to buy or sell. For the minimum unit of qty increase or decrease, please refer to the lot_size_filter
field in the Query Symbol endpoint. Note: The allowed max trade quantity of PostOnly
is 5 times bigger than normal orders.
Order price: If it is a conditional order, this parameter is required. When there is no position, the price should be higher than 10% of the market price and less than 1 million. For the minimum unit of price movement, please refer to the price_filter field in the Query Symbol endpoint. This must modulo by 0.5 (20 and 21.5 are accepted, but 16.1 or 16.15 are not).
Custom order ID: You may customise order IDs for active orders. We will link it to the system order ID, and return the unique system order ID to you after the active order is created successfully. You may use this order ID or your custom order ID to cancel your active order. The customised order ID should be unique, with a maximum length of 36 characters.
Each account can hold up to 500 active orders yet to be filled entirely simultaneously. This is per instrument, so it's possible to have, for example, 300 active orders on the BTCUSD instrument and 280 active orders on the ETHUSD instrument.
HTTP Request
POST
/v2/private/order/create
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
side | true | string | Side |
symbol | true | string | Symbol |
order_type | true | string | Active order type |
qty | true | integer | Order quantity in USD |
price | false | number | Order price |
time_in_force | true | string | Time in force |
reduce_only | false | bool | What is a reduce-only order? True means your position can only reduce in size if this order is triggered |
close_on_trigger | false | bool | What is a close on trigger order? For a closing order. It can only reduce your position, not increase it. If the account has insufficient available balance when the closing order is triggered, then other active orders of similar contracts will be cancelled or reduced. It can be used to ensure your stop loss reduces your position regardless of current available margin. |
order_link_id | false | string | Unique user-set order ID. Maximum length of 36 characters |
take_profit | false | number | Take profit price, only take effect upon opening the position |
stop_loss | false | number | Stop loss price, only take effect upon opening the position |
tp_trigger_by | false | string | Take profit trigger price type, default: LastPrice
|
sl_trigger_by | false | string | Stop loss trigger price type, default: LastPrice
|
Response Parameters
Parameter | Type | Comment |
---|---|---|
user_id | number | UserID |
order_id | string | Order ID |
symbol | string | Symbol |
side | string | Side |
order_type | string | Order type |
price | number | Order price |
qty | number | Order quantity in USD |
time_in_force | string | Time in force |
order_status | string | Order status |
last_exec_time | string | Last execution time |
last_exec_price | string | Last execution price |
leaves_qty | number | Number of unfilled contracts from the order's size |
cum_exec_qty | number | Cumulative qty of trading |
cum_exec_value | number | Cumulative value of trading |
cum_exec_fee | number | Cumulative trading fees |
reject_reason | string | The reason the order was rejected |
order_link_id | string | Unique user-set order ID. Maximum length of 36 characters |
created_at | string | Creation time (when the order_status was Created ) |
updated_at | string | Update time |
take_profit | string | Take profit price |
stop_loss | string | 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-testnet.bybit.com/v2/private/order/list?api_key={api_key}×tamp={timestamp}&sign={sign}&symbol=BTCUSD"
from pybit import inverse_perpetual
session_auth = inverse_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com",
api_key="your api key",
api_secret="your api secret"
)
print(session_auth.get_active_order(
symbol="BTCUSD",
order_status="New"
))
Response Example
{
"ret_code": 0,
"ret_msg": "OK",
"ext_code": "",
"ext_info": "",
"result": {
"data": [
{
"user_id": 533285,
"position_idx": 0,
"order_status": "New",
"symbol": "BTCUSD",
"side": "Buy",
"order_type": "Limit",
"price": "20010",
"qty": "200",
"time_in_force": "GoodTillCancel",
"order_link_id": "",
"order_id": "a1904030-f99c-4e35-9217-111591f08493",
"created_at": "2022-06-20T06:56:22.070Z",
"updated_at": "2022-06-20T06:56:22.075Z",
"leaves_qty": "200",
"leaves_value": "0.009995",
"cum_exec_qty": "0",
"cum_exec_value": "0",
"cum_exec_fee": "0",
"reject_reason": "EC_NoError",
"take_profit": "22000.0000",
"stop_loss": "19000.0000",
"tp_trigger_by": "MarkPrice",
"sl_trigger_by": "MarkPrice"
}
],
"cursor": "/oIljKFOerbXfuWAmnc33qCc1649q+xLuuagMYyoYh6pV+BShVJ8ph439Xw8ywSp"
},
"time_now": "1655708401.042813",
"rate_limit_status": 599,
"rate_limit_reset_ms": 1655708401039,
"rate_limit": 600
}
Get my active order list.
Because order creation/cancellation is asynchronous, there can be a data delay in this endpoint. You can get real-time order info with the Query Active Order (real-time) endpoint.
HTTP Request
GET
/v2/private/order/list
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
symbol | true | string | Symbol |
order_status | false | string | Queries orders of all statuses if order_status not provided. If you want to query orders with specific statuses, you can pass the order_status split by ',' (eg Filled,New ). |
direction | false | string | Search direction. prev : prev page, next : next page. Defaults to next
|
limit | false | integer | Limit for data size per page, max size is 50. Default as showing 20 pieces of data per page |
cursor | false | string | Page turning mark. Use return cursor . Sign using origin data, in request please use urlencode |
Response Parameters
Parameter | Type | Comment |
---|---|---|
user_id | integer | UserID |
position_idx | integer | Position idx, used to identify positions in different position modes: 0-One-Way Mode 1-Buy side of both side mode 2-Sell side of both side mode |
order_status | string | Order status |
symbol | string | Symbol |
side | string | Side |
order_type | string | Order type |
price | string | Order price |
qty | string | Order quantity in USD |
time_in_force | string | Time in force |
order_link_id | string | Unique user-set order ID. Maximum length of 36 characters |
order_id | string | Order ID |
created_at | string | Creation time (when the order_status was Created ) |
updated_at | string | Update time |
leaves_qty | string | Number of unfilled contracts from the order's size |
leaves_value | string | The estimated value corresponding to the number of remaining orders |
cum_exec_qty | string | Cumulative qty of trading |
cum_exec_value | string | Cumulative value of trading |
cum_exec_fee | string | Cumulative trading fees |
reject_reason | string | The reason the order was rejected |
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
|
cursor | string | Page turning mark |
Cancel Active Order
Request Example
curl https://api-testnet.bybit.com/v2/private/order/cancel \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","symbol":"BTCUSD","order_id":"","timestamp":{timestamp},"sign":"{sign}"}'
from pybit import inverse_perpetual
session_auth = inverse_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com",
api_key="your api key",
api_secret="your api secret"
)
print(session_auth.cancel_active_order(
symbol="BTCUSD",
order_id="3bd1844f-f3c0-4e10-8c25-10fea03763f6"
))
Response Example
{
"ret_code": 0,
"ret_msg": "OK",
"ext_code": "",
"ext_info": "",
"result": {
"user_id": 533285,
"order_id": "bab79185-7759-48f3-a5f4-206808b6f1ec",
"symbol": "BTCUSD",
"side": "Buy",
"order_type": "Limit",
"price": 19500,
"qty": 100,
"time_in_force": "GoodTillCancel",
"order_status": "New",
"last_exec_time": 1655711524.37661,
"last_exec_price": 0,
"leaves_qty": 100,
"cum_exec_qty": 0,
"cum_exec_value": 0,
"cum_exec_fee": 0,
"reject_reason": "EC_NoError",
"order_link_id": "IPBTC00001",
"created_at": "2022-06-20T07:52:04.376Z",
"updated_at": "2022-06-20T07:54:35.339Z",
"take_profit": "",
"stop_loss": "",
"tp_trigger_by": "",
"sl_trigger_by": ""
},
"time_now": "1655711675.340162",
"rate_limit_status": 99,
"rate_limit_reset_ms": 1655711675338,
"rate_limit": 100
}
Either order_id
or order_link_id
are required for cancelling active orders. order_id
- this unique 36 characters order ID was returned to you when the active order was created successfully.
You may cancel active orders that are unfilled or partially filled. Fully filled orders cannot be cancelled.
HTTP Request
POST
/v2/private/order/cancel
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
symbol | true | string | Symbol |
order_id | false | string | Order ID |
order_link_id | false | string | Unique user-set order ID |
Response Parameters
Parameter | Type | Comment |
---|---|---|
user_id | number | UserID |
order_id | string | Order ID |
symbol | string | Symbol |
side | string | Side |
order_type | string | Order type |
price | number | Order price |
qty | number | Order quantity in USD |
time_in_force | string | Time in force |
order_status | string | Order status |
last_exec_time | string | Last execution time |
last_exec_price | string | Last execution price |
leaves_qty | number | Number of unfilled contracts from the order's size |
cum_exec_qty | number | Cumulative qty of trading |
cum_exec_value | number | Cumulative value of trading |
cum_exec_fee | number | Cumulative trading fees |
reject_reason | string | The reason the order was rejected |
order_link_id | string | Unique user-set order ID. Maximum length of 36 characters |
created_at | string | Creation time (when the order_status was Created ) |
updated_at | string | Update time |
take_profit | number | Take profit price |
stop_loss | number | Stop loss price |
tp_trigger_by | string | Take profit trigger price type, default: LastPrice
|
sl_trigger_by | string | Stop loss trigger price type, default: LastPrice
|
Cancel All Active Orders
Request Example
curl https://api-testnet.bybit.com/v2/private/order/cancelAll \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","symbol":"BTCUSD","timestamp":{timestamp},"sign":"{sign}"}'
from pybit import inverse_perpetual
session_auth = inverse_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com",
api_key="your api key",
api_secret="your api secret"
)
print(session_auth.cancel_all_active_orders(
symbol="BTCUSD"
))
Response Example
{
"ret_code": 0,
"ret_msg": "OK",
"ext_code": "",
"ext_info": "",
"result": [
{
"clOrdID": "89f67ac2-8f51-4463-b5c1-75d0d8aca185",
"order_link_id": "IPBTC00003",
"user_id": 533285,
"symbol": "BTCUSD",
"side": "Buy",
"order_type": "Limit",
"price": "17000",
"qty": 100,
"time_in_force": "GoodTillCancel",
"create_type": "CreateByUser",
"cancel_type": "CancelByUser",
"order_status": "",
"leaves_qty": 100,
"leaves_value": "0",
"created_at": "2022-06-21T02:05:30.430491295Z",
"updated_at": "2022-06-21T04:34:46.3745089Z",
"cross_status": "PendingCancel",
"cross_seq": 5208583955
}
],
"time_now": "1655786086.374891",
"rate_limit_status": 80,
"rate_limit_reset_ms": 1655786086373,
"rate_limit": 100
}
Cancel all active orders that are unfilled or partially filled. Fully filled orders cannot be cancelled.
HTTP Request
POST
/v2/private/order/cancelAll
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
symbol | true | string | Symbol |
Response Parameters
Parameter | Type | Comment |
---|---|---|
clOrdID | string | A unique order number of type UUID |
order_link_id | string | Custom ID used for cross-platform strategy remarks; a max. of 32 characters |
user_id | number | UserID |
symbol | string | Symbol |
side | string | Side |
order_type | string | Order type |
price | string | Order price |
qty | number | Order quantity in USD |
time_in_force | string | Time in force |
create_type | string | Trigger scenario for single action |
cancel_type | string | Trigger scenario for cancel operation |
order_status | string | Order status |
leaves_qty | number | Number of unfilled contracts from the order's size |
leaves_value | string | The estimated value corresponding to the number of remaining orders |
created_at | string | Creation time (when the order_status was Created ) |
updated_at | string | Update time |
cross_status | string | The state of initiating a matchmaking request |
cross_seq | number | Cross sequence (internal value) |
Replace Active Order
Request Example
curl https://api-testnet.bybit.com/v2/private/order/replace \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","symbol":"BTCUSD","order_id":"","timestamp":{timestamp},"sign":"{sign}"}'
from pybit import inverse_perpetual
session_auth = inverse_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com",
api_key="your api key",
api_secret="your api secret"
)
print(session_auth.replace_active_order(
symbol="BTCUSD",
order_id="efa44157-c355-4a98-b6d6-1d846a936b93"
))
Response Example
{
"ret_code": 0,
"ret_msg": "ok",
"ext_code": "",
"result": {
"order_id": "efa44157-c355-4a98-b6d6-1d846a936b93"
},
"time_now": "1539778407.210858",
"rate_limit_status": 99,
"rate_limit_reset_ms": 1580885703683,
"rate_limit": 100
}
Replace order can modify/amend your active orders.
HTTP Request
POST
/v2/private/order/replace
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
order_id | false | string | Order ID. Required if not passing order_link_id |
order_link_id | false | string | Unique user-set order ID. Required if not passing order_id |
symbol | true | string | Symbol. |
p_r_qty | false | number | 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. Do not pass this field if you don't want modify it |
stop_loss | false | number | New stop_loss price. 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-testnet.bybit.com/v2/private/order?api_key={api_key}&symbol=BTCUSD×tamp={timestamp}order_id={order_id}&sign={sign}"
from pybit import inverse_perpetual
session_auth = inverse_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com",
api_key="your api key",
api_secret="your api secret"
)
print(session.query_active_order(
symbol="BTCUSD",
order_id="e66b101a-ef3f-4647-83b5-28e0f38dcae0"
))
Response Example
{
"ret_code": 0,
"ret_msg": "OK",
"ext_code": "",
"ext_info": "",
"result": {
"user_id": 533285,
"position_idx": 0,
"symbol": "BTCUSD",
"side": "Buy",
"order_type": "Limit",
"price": "20000",
"qty": 200,
"time_in_force": "GoodTillCancel",
"order_status": "New",
"ext_fields": {
"o_req_num": 1240101436
},
"last_exec_time": "1655716503.5852108",
"leaves_qty": 200,
"leaves_value": "0.01",
"cum_exec_qty": 0,
"cum_exec_value": null,
"cum_exec_fee": null,
"reject_reason": "EC_NoError",
"cancel_type": "UNKNOWN",
"order_link_id": "IPBTC000002",
"created_at": "2022-06-20T09:15:03.585128212Z",
"updated_at": "2022-06-20T09:15:03.590398174Z",
"order_id": "2b1d811c-8ff0-4ef0-92ed-b4ed5fd6de34",
"take_profit": "23000.00",
"stop_loss": "18000.00",
"tp_trigger_by": "MarkPrice",
"sl_trigger_by": "MarkPrice"
},
"time_now": "1655718311.123686",
"rate_limit_status": 597,
"rate_limit_reset_ms": 1655718311122,
"rate_limit": 600
}
Query real-time active order information. If only order_id
or order_link_id
are passed, a single order will be returned; otherwise, returns up to 500 unfilled orders.
HTTP Request
GET
/v2/private/order
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
symbol | true | string | Symbol |
order_id | false | string | Order ID |
order_link_id | false | string | Unique user-set order ID. Maximum length of 36 characters |
Response Parameters
Parameter | Type | Comment |
---|---|---|
user_id | number | UserID |
position_idx | integer | Position idx, used to identify positions in different position modes: 0-One-Way Mode 1-Buy side of both side mode 2-Sell side of both side mode |
symbol | string | Symbol |
side | string | Side |
order_type | string | Order type |
price | string | Order price |
qty | number | Order quantity in USD |
time_in_force | string | Time in force |
order_status | string | Order status |
ext_fields | map | Extension field |
last_exec_time | string | Last execution time |
leaves_qty | number | Number of unfilled contracts from the order's size |
leaves_value | number | The estimated value corresponding to the number of remaining orders |
cum_exec_qty | number | Cumulative qty of trading |
cum_exec_value | number | Cumulative value of trading |
cum_exec_fee | string | Cumulative trading fees |
reject_reason | string | The reason the order was rejected |
cancel_type | string | Trigger scenario for cancel operation |
order_link_id | string | Unique user-set order ID. Maximum length of 36 characters |
created_at | string | Creation time (when the order_status was Created ) |
updated_at | string | Update time |
order_id | string | Order ID |
take_profit | number | Take profit price |
stop_loss | number | Stop loss price |
tp_trigger_by | string | Take profit trigger price type, default: LastPrice
|
sl_trigger_by | string | Stop loss trigger price type, default: LastPrice
|
Conditional Orders
Place Conditional Order
Request Example
curl https://api-testnet.bybit.com/v2/private/stop-order/create \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","order_type":"Limit","side":"Buy","symbol":"BTCUSD","qty":1,"price":8100,"base_price":8300,"stop_px":8150,"time_in_force":"GoodTillCancel","order_link_id":"cus_order_id_1","timestamp":{timestamp},"sign":"{sign}"}'
from pybit import inverse_perpetual
session_auth = inverse_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com",
api_key="your api key",
api_secret="your api secret"
)
print(session_auth.place_conditional_order(
symbol="BTCUSD",
order_type="Limit",
side="Buy",
qty=1,
price=54100,
base_price=54192,
stop_px=54150,
time_in_force="GoodTillCancel"
))
Response Example
{
"ret_code": 0,
"ret_msg": "OK",
"ext_code": "",
"ext_info": "",
"result": {
"user_id": 533285,
"symbol": "BTCUSD",
"side": "Buy",
"order_type": "Limit",
"price": "19000.00",
"qty": "100",
"time_in_force": "GoodTillCancel",
"remark": "172.104.71.120",
"leaves_qty": "100",
"leaves_value": "0.00526315",
"stop_px": "19500.00",
"reject_reason": "EC_NoError",
"stop_order_id": "6e6a003f-fda3-4513-b944-3f41dabd2866",
"order_link_id": "IPCOND0001",
"trigger_by": "MarkPrice",
"base_price": "20000.00",
"created_at": "2022-06-21T02:19:46.052Z",
"updated_at": "2022-06-21T02:19:46.052Z",
"tp_trigger_by": "LastPrice",
"sl_trigger_by": "LastPrice",
"take_profit": "22000.00",
"stop_loss": "17500.00"
},
"time_now": "1655777986.053050",
"rate_limit_status": 99,
"rate_limit_reset_ms": 1655777986051,
"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 price should be higher than 10% of market price and less than 1 million. For the minimum unit of price movement, 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
/v2/private/stop-order/create
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
side | true | string | Side |
symbol | true | string | Symbol |
order_type | true | string | Conditional order type |
qty | true | string | Order quantity in USD |
price | false | string | Execution price for conditional order. Required if you make limit price order |
base_price | true | string | It will be used to compare with the value of stop_px , to decide whether your conditional order will be triggered by crossing trigger price from upper side or lower side. Mainly used to identify the expected direction of the current conditional order. |
stop_px | true | string | Trigger price. If you're expecting the price to rise to trigger your conditional order, make sure stop_px > max(market price, base_price) else, stop_px < min(market price, base_price) |
time_in_force | true | string | Time in force |
trigger_by | false | string | Trigger price type. Default LastPrice |
close_on_trigger | false | bool | What is a close on trigger order? For a closing order. It can only reduce your position, not increase it. If the account has insufficient available balance when the closing order is triggered, then other active orders of similar contracts will be cancelled or reduced. It can be used to ensure your stop loss reduces your position regardless of current available margin. |
order_link_id | false | string | Unique user-set order ID. Maximum length of 36 characters |
take_profit | false | number | Take profit price |
stop_loss | false | number | Stop loss price |
tp_trigger_by | false | string | Take profit trigger price type, default: LastPrice
|
sl_trigger_by | false | string | Stop loss trigger price type, default: LastPrice
|
Response Parameters
Parameter | Type | Comment |
---|---|---|
user_id | integer | UserID |
symbol | string | Symbol |
side | string | Side |
order_type | string | Active order type |
price | string | Order price |
qty | string | Order quantity in USD |
time_in_force | string | Time in force |
remark | string | Remark |
leaves_qty | number | Number of unfilled contracts from the order's size |
leaves_value | number | The estimated value corresponding to the number of remaining orders |
stop_px | string | Trigger price. If you're expecting the price to rise to trigger your conditional order, make sure stop_px > max(market price, base_price) else, stop_px < min(market price, base_price) |
reject_reason | string | The reason the order was rejected |
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 | Unique user-set order ID. Maximum length of 36 characters |
trigger_by | string | Trigger price type. Default LastPrice |
base_price | string | Market price at placing order |
created_at | string | Creation time (when the order_status was Created ) |
updated_at | string | Update time |
tp_trigger_by | string | Take profit trigger price type, default: LastPrice
|
sl_trigger_by | string | Stop loss trigger price type, default: LastPrice
|
take_profit | string | Take profit price |
stop_loss | string | Stop loss price |
Get Conditional Order
Request Example
curl "https://api-testnet.bybit.com/v2/private/stop-order/list?api_key={api_key}×tamp={timestamp}&sign={sign}"
from pybit import inverse_perpetual
session_auth = inverse_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com",
api_key="your api key",
api_secret="your api secret"
)
print(session_auth.get_conditional_order(
symbol="BTCUSD",
stop_order_status="Untriggered"
))
Response Example
{
"ret_code": 0,
"ret_msg": "OK",
"ext_code": "",
"ext_info": "",
"result": {
"data": [
{
"user_id": 533285,
"position_idx": 0,
"stop_order_status": "Deactivated",
"symbol": "BTCUSD",
"side": "Buy",
"order_type": "Limit",
"stop_order_type": "Stop",
"price": "19000",
"qty": "100",
"time_in_force": "GoodTillCancel",
"base_price": "20000",
"order_link_id": "IPCOND0001",
"created_at": "2022-06-21T02:19:46.052Z",
"updated_at": "2022-06-21T02:37:13.05Z",
"stop_px": "19500",
"stop_order_id": "6e6a003f-fda3-4513-b944-3f41dabd2866",
"trigger_by": "MarkPrice",
"take_profit": "22000.0000",
"stop_loss": "17500.0000",
"tp_trigger_by": "LastPrice",
"sl_trigger_by": "LastPrice"
}
],
"cursor": "/oIljKFOerbXfuWAmnc33spA0KcdXr8norz1Mo+W758A5ScFhXQfNDZlY39W83UV"
},
"time_now": "1655780730.372912",
"rate_limit_status": 599,
"rate_limit_reset_ms": 1655780730369,
"rate_limit": 600
}
Get my conditional order list.
Because order creation/cancellation is asynchronous, there can be a data delay in this endpoint. You can get real-time order info with the Query Conditional Order (real-time) endpoint.
HTTP Request
GET
/v2/private/stop-order/list
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
symbol | true | string | Symbol |
stop_order_status | false | string | Queries orders of all statuses if 'stop_order_status' not provided |
direction | false | string | Search direction. prev : prev page, next : next page. Defaults to next
|
limit | false | integer | Limit for data size per page, max size is 50. Default as showing 20 pieces of data per page |
cursor | false | string | Page turning mark. Use return cursor . Sign using origin data, in request please use urlencode |
Response Parameters
Parameter | Type | Comment |
---|---|---|
user_id | integer | UserID |
position_idx | integer | Position idx, used to identify positions in different position modes: 0-One-Way Mode 1-Buy side of both side mode 2-Sell side of both side mode |
stop_order_status | string | Stop order status |
symbol | string | Symbol |
side | string | Side |
order_type | string | Active order type |
price | string | Order price |
qty | string | Order quantity in USD |
time_in_force | string | Time in force |
stop_order_type | string | Conditional order type |
trigger_by | string | Trigger price type |
base_price | string | Market price at placing order |
order_link_id | string | Unique user-set order ID. Maximum length of 36 characters |
created_at | string | Creation time (when the order_status was Created ) |
updated_at | string | Update time |
stop_px | string | Trigger price. If you're expecting the price to rise to trigger your conditional order, make sure stop_px > max(market price, base_price) else, stop_px < min(market price, base_price) |
stop_order_id | string | Conditional order ID. Once triggered, the conditional order creates an active order with the same ID (order_id ) |
take_profit | string | Take profit price |
stop_loss | string | 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
|
cursor | string | Page turning mark |
Cancel Conditional Order
Request Example
curl https://api-testnet.bybit.com/v2/private/stop-order/cancel \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","symbol":"BTCUSD","stop_order_id":"xxx","timestamp":{timestamp},"sign":"{sign}"}'
from pybit import inverse_perpetual
session_auth = inverse_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com",
api_key="your api key",
api_secret="your api secret"
)
print(session_auth.cancel_conditional_order(
symbol="BTCUSD",
stop_order_id="c1025629-e85b-4c26-b4f3-76e86ad9f8cb"
))
Response Example
{
"ret_code": 0,
"ret_msg": "ok",
"ext_code": "",
"result": {
"stop_order_id": "c1025629-e85b-4c26-b4f3-76e86ad9f8cb"
},
"ext_info": null,
"time_now": "1577452218.567120",
"rate_limit_status": 97,
"rate_limit_reset_ms": 1577452218573,
"rate_limit": "100"
}
You may cancel all untriggered conditional orders or take profit/stop loss order. Essentially, after a conditional order is triggered, it will become an active order. So, when a conditional order is triggered, cancellation has to be done through the active order endpoint for any unfilled or partially filled active order. As always, orders that have been fully filled cannot be cancelled.
HTTP Request
POST
/v2/private/stop-order/cancel
Request Parameters
Parameter | required | type | comments |
---|---|---|---|
symbol | true | string | Symbol |
stop_order_id | false | string | Order ID |
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-testnet.bybit.com/v2/private/stop-order/cancelAll \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","symbol":"BTCUSD","timestamp":{timestamp},"sign":"{sign}"}'
from pybit import inverse_perpetual
session_auth = inverse_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com",
api_key="your api key",
api_secret="your api secret"
)
print(session_auth.cancel_all_conditional_orders(
symbol="BTCUSD"
))
Response Example
{
"ret_code": 0,
"ret_msg": "OK",
"ext_code": "",
"ext_info": "",
"result": [
{
"clOrdID": "c692f699-5e41-49a0-a87f-666ae66e47c7",
"order_link_id": "IPCOND0002",
"user_id": 533285,
"symbol": "BTCUSD",
"side": "Buy",
"order_type": "Market",
"price": "0",
"qty": 100,
"time_in_force": "ImmediateOrCancel",
"create_type": "CreateByStopOrder",
"cancel_type": "CancelByUser",
"order_status": "",
"leaves_value": "0",
"created_at": "2022-06-21T03:32:58.42058148Z",
"updated_at": "2022-06-21T04:34:11.689866649Z",
"cross_status": "Deactivated",
"cross_seq": -1,
"stop_order_type": "Stop",
"trigger_by": "MarkPrice",
"base_price": "20000",
"trail_value": "0",
"expected_direction": "Falling"
},
{
"clOrdID": "d46d5544-a2a9-4eb7-a4a2-be4855bb3873",
"user_id": 533285,
"symbol": "BTCUSD",
"side": "Sell",
"order_type": "Market",
"price": "0",
"qty": 400,
"time_in_force": "ImmediateOrCancel",
"create_type": "CreateByTakeProfit",
"cancel_type": "CancelByUser",
"order_status": "",
"leaves_value": "0",
"created_at": "2022-06-21T04:08:10.185138102Z",
"updated_at": "2022-06-21T04:34:11.689871755Z",
"cross_status": "Deactivated",
"cross_seq": -1,
"stop_order_type": "TakeProfit",
"trigger_by": "LastPrice",
"base_price": "20636",
"trail_value": "0",
"expected_direction": "Rising"
}
],
"time_now": "1655786051.690280",
"rate_limit_status": 90,
"rate_limit_reset_ms": 1655786051688,
"rate_limit": 100
}
Cancel all untriggered conditional orders.
HTTP Request
POST
/v2/private/stop-order/cancelAll
Request Parameters
Parameter | required | type | comments |
---|---|---|---|
symbol | true | string | Symbol |
Response Parameters
Parameter | Type | Comment |
---|---|---|
clOrdID | string | A unique order number of type UUID |
order_link_id | string | Custom ID used for cross-platform strategy remarks; a max. of 32 characters |
user_id | number | UserID |
symbol | string | Symbol |
side | string | Side |
order_type | string | Active order type |
price | string | Order price |
qty | number | Order quantity in USD |
time_in_force | string | Time in force |
create_type | string | Trigger scenario for single action |
cancel_type | string | Trigger scenario for cancel operation |
order_status | string | Order status |
leaves_qty | number | Number of unfilled contracts from the order's size |
leaves_value | string | The estimated value corresponding to the number of remaining orders |
created_at | string | Creation time (when the order_status was Created ) |
updated_at | string | Update time |
cross_status | string | The state of initiating a matchmaking request |
cross_seq | number | Cross sequence (internal value) |
stop_order_type | string | Conditional order type |
trigger_by | string | Trigger price type. Default LastPrice |
base_price | string | Market price at placing order |
expected_direction | string | Expected direction |
Replace Conditional Order
Request Example
curl https://api-testnet.bybit.com/v2/private/stop-order/replace \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","symbol":"BTCUSD","stop_order_id":"","timestamp":{timestamp},"sign":"{sign}"}'
from pybit import inverse_perpetual
session_auth = inverse_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com",
api_key="your api key",
api_secret="your api secret"
)
print(session_auth.replace_conditional_order(
symbol="BTCUSD",
stop_order_id="378a1bbc-a93a-4e75-87f4-502ea754ba36",
p_r_trigger_price=16003
))
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.
HTTP Request
POST
/v2/private/stop-order/replace
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
stop_order_id | false | string | Order 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 | number | 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 | string | New conditional order's trigger price or TP/SL order price, also known as stop_px. Do not pass this field if you don't want modify it |
take_profit | false | number | New take_profit price. Do not pass this field if you don't want modify it |
stop_loss | false | number | New stop_loss price. 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-testnet.bybit.com/v2/private/stop-order?api_key={api_key}&symbol=BTCUSD×tamp={timestamp}order_id={order_id}&sign={sign}"
from pybit import inverse_perpetual
session_auth = inverse_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com",
api_key="your api key",
api_secret="your api secret"
)
print(session_auth.query_conditional_order(
symbol="BTCUSD",
stop_order_id="378a1bbc-a93a-4e75-87f4-502ea754ba36"
))
Response Example
{
"ret_code": 0,
"ret_msg": "OK",
"ext_code": "",
"ext_info": "",
"result": [
{
"user_id": 533285,
"position_idx": 0,
"symbol": "BTCUSD",
"side": "Buy",
"order_type": "Market",
"price": "0",
"qty": 100,
"stop_px": "19500.00",
"base_price": "20000.00",
"time_in_force": "ImmediateOrCancel",
"order_status": "Untriggered",
"ext_fields": {
"o_req_num": 1328284913
},
"leaves_qty": 100,
"leaves_value": "0",
"cum_exec_qty": 0,
"cum_exec_value": null,
"cum_exec_fee": null,
"reject_reason": "EC_NoError",
"cancel_type": "UNKNOWN",
"order_link_id": "IPCOND0002",
"created_at": "2022-06-21T03:32:58.42058148Z",
"updated_at": "2022-06-21T03:32:58.42058148Z",
"order_id": "c692f699-5e41-49a0-a87f-666ae66e47c7",
"trigger_by": "MarkPrice",
"take_profit": "22000.00",
"stop_loss": "17500.00",
"tp_trigger_by": "LastPrice",
"sl_trigger_by": "LastPrice"
}
],
"time_now": "1655782431.042082",
"rate_limit_status": 597,
"rate_limit_reset_ms": 1655782431039,
"rate_limit": 600
}
Query real-time stop order information. When passing the parameter order_id
or order_link_id
, a single order data will be returned; otherwise, returns up to 10 unfilled orders.
HTTP Request
GET
/v2/private/stop-order
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
symbol | true | string | Symbol |
stop_order_id | false | string | Conditional order ID. Once triggered, the conditional order creates an active order with the same ID (order_id ) |
order_link_id | false | string | Unique user-set order ID. Maximum length of 36 characters |
Response Parameters
Parameter | Type | Comment |
---|---|---|
user_id | number | UserID |
position_idx | integer | Position idx, used to identify positions in different position modes: 0-One-Way Mode 1-Buy side of both side mode 2-Sell side of both side mode |
symbol | string | Symbol |
side | string | Side |
order_type | string | Active order type |
price | number | Order price |
qty | number | Order quantity in USD |
stop_px | string | Trigger price. If you're expecting the price to rise to trigger your conditional order, make sure stop_px > max(market price, base_price) else, stop_px < min(market price, base_price) |
base_price | string | Market price at placing order |
time_in_force | string | Time in force |
order_status | string | Order status |
ext_fields | map | Extension field |
leaves_qty | number | Number of unfilled contracts from the order's size |
leaves_value | string | The estimated value corresponding to the number of remaining orders |
cum_exec_qty | number | Cumulative qty of trading |
cum_exec_value | number | Cumulative value of trading |
cum_exec_fee | number | Cumulative trading fees |
reject_reason | string | The reason the order was rejected |
order_link_id | string | Unique user-set order ID. Maximum length of 36 characters |
created_at | string | Creation time (when the order_status was Created ) |
updated_at | string | Update time |
order_id | string | Order ID |
trigger_by | string | Trigger price type |
take_profit | string | Take profit price |
stop_loss | string | Stop loss price |
tp_trigger_by | string | Take profit trigger price type, default: LastPrice
|
sl_trigger_by | string | Stop loss trigger price type, default: LastPrice
|
Position
My Position
Request Example
curl "https://api-testnet.bybit.com/v2/private/position/list?api_key={api_key}&symbol=BTCUSD×tamp={timestamp}&sign={sign}"
from pybit import inverse_perpetual
session_auth = inverse_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com",
api_key="your api key",
api_secret="your api secret"
)
print(session_auth.my_position(
symbol="BTCUSD"
))
Response Example
{
"ret_code": 0,
"ret_msg": "OK",
"ext_code": "",
"ext_info": "",
"result": {
"id": 27913,
"user_id": 1,
"risk_id": 1,
"symbol": "BTCUSD",
"side": "Buy",
"size": 5,
"position_value": "0.0006947",
"entry_price": "7197.35137469",
"is_isolated":true,
"auto_add_margin": 0,
"leverage": "1",
"effective_leverage": "1",
"position_margin": "0.0006947",
"liq_price": "3608",
"bust_price": "3599",
"occ_closing_fee": "0.00000105",
"occ_funding_fee": "0",
"take_profit": "0",
"stop_loss": "0",
"trailing_stop": "0",
"position_status": "Normal",
"deleverage_indicator": 4,
"oc_calc_data": "{\"blq\":2,\"blv\":\"0.0002941\",\"slq\":0,\"bmp\":6800.408,\"smp\":0,\"fq\":-5,\"fc\":-0.00029477,\"bv2c\":1.00225,\"sv2c\":1.0007575}",
"order_margin": "0.00029477",
"wallet_balance": "0.03000227",
"realised_pnl": "-0.00000126",
"unrealised_pnl": 0,
"cum_realised_pnl": "-0.00001306",
"cross_seq": 444081383,
"position_seq": 287141589,
"created_at": "2019-10-19T17:04:55Z",
"updated_at": "2019-12-27T20:25:45.158767Z"
"tp_sl_mode": "Partial"
},
"time_now": "1577480599.097287",
"rate_limit_status": 119,
"rate_limit_reset_ms": 1580885703683,
"rate_limit": 120
}
//When symbol
is not passed, the response uses a different structure:
{
"ret_code": 0,
"ret_msg": "OK",
"ext_code": "",
"ext_info": "",
"result": [
{
"is_valid": true,
"data": {
"id": 0,
"position_idx": 0,
"mode": 0,
"user_id": 118921,
"risk_id": 1,
"symbol": "BTCUSD",
"side": "Buy",
"size": 10,
"position_value": "0.00076448",
"entry_price": "13080.78694014",
"is_isolated": false,
"auto_add_margin": 1,
"leverage": "100",
"effective_leverage": "0.01",
"position_margin": "0.40111704",
"liq_price": "25",
"bust_price": "25",
"occ_closing_fee": "0.0003",
"occ_funding_fee": "0",
"take_profit": "0",
"stop_loss": "0",
"trailing_stop": "0",
"position_status": "Normal",
"deleverage_indicator": 1,
"oc_calc_data": "{\"blq\":0,\"slq\":0,\"bmp\":0,\"smp\":0,\"fq\":-10,\"bv2c\":0.0115075,\"sv2c\":0.0114925}",
"order_margin": "0",
"wallet_balance": "0.40141704",
"realised_pnl": "-0.00000008",
"unrealised_pnl": 0.00003797,
"cum_realised_pnl": "-0.090626",
"cross_seq": 764786721,
"position_seq": 581513847,
"created_at": "2020-08-10T07:04:32Z",
"updated_at": "2020-11-02T00:00:11.943371457Z"
"tp_sl_mode": "Partial"
}
},
...
{
"is_valid": true,
"data": {
"id": 0,
"position_idx": 0,
"mode": 0,
"user_id": 118921,
"risk_id": 35,
"symbol": "XRPUSD",
"side": "None",
"size": 0,
"position_value": "0",
"entry_price": "0",
"is_isolated": false,
"auto_add_margin": 1,
"leverage": "16.67",
"effective_leverage": "16.67",
"position_margin": "0",
"liq_price": "0",
"bust_price": "0",
"occ_closing_fee": "0",
"occ_funding_fee": "0",
"take_profit": "0",
"stop_loss": "0",
"trailing_stop": "0",
"position_status": "Normal",
"deleverage_indicator": 0,
"oc_calc_data": "{\"blq\":0,\"slq\":0,\"bmp\":0,\"smp\":0,\"bv2c\":0.06153301,\"sv2c\":0.06144302}",
"order_margin": "0",
"wallet_balance": "0",
"realised_pnl": "0",
"unrealised_pnl": 0,
"cum_realised_pnl": "0",
"cross_seq": -1,
"position_seq": 352149441,
"created_at": "2020-08-10T07:04:32Z",
"updated_at": "2020-08-22T08:06:32Z"
"tp_sl_mode": "Partial"
}
}
],
"time_now": "1604302124.031104",
"rate_limit_status": 118,
"rate_limit_reset_ms": 1604302124020,
"rate_limit": 120
}
Get my position list.
HTTP Request
GET
/v2/private/position/list
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
symbol | false | string | Symbol |
Response Parameters
Parameter | Type | Comment |
---|---|---|
id | number | PositionID |
position_idx | integer | Position idx, used to identify positions in different position modes: 0-One-Way Mode 1-Buy side of both side mode 2-Sell side of both side mode |
mode | number | Position mode |
user_id | number | UserID |
risk_id | number | Risk ID |
symbol | string | Symbol |
side | string | Side |
size | number | Position qty |
position_value | string | Position value |
entry_price | string | Average entry price |
is_isolated | bool | true means isolated margin mode; false means cross margin mode |
auto_add_margin | number | Whether or not auto-margin replenishment is enabled |
leverage | string | In Isolated Margin mode, the value is set by the user. In Cross Margin mode, the value is the max leverage at current risk level |
effective_leverage | string | Effective leverage |
position_margin | string | Position margin |
liq_price | string | Liquidation price |
bust_price | string | Bankruptcy price |
occ_closing_fee | string | Position closing fee occupied (your opening fee + expected maximum closing fee) |
occ_funding_fee | string | Pre-occupied funding fee: calculated from position qty and current funding fee |
take_profit | string | Take profit price |
stop_loss | string | Stop loss price |
trailing_stop | string | Trailing stop (the distance from the current price) |
position_status | string | Position status: Normal , Liq , Adl
|
deleverage_indicator | number | Deleverage indicator level (1,2,3,4,5) |
oc_calc_data | string | Pre-occupied calculate parameters. blq : total number of the long side unsettled orders; bmp : the lowest price of the long side; slq : total number of the short side unsettled orders; smp : the lowest price of the short side
|
order_margin | string | Pre-occupied order margin |
wallet_balance | string | Wallet balance |
realised_pnl | string | Today's realised pnl |
unrealised_pnl | number | unrealised pnl |
cum_realised_pnl | string | Accumulated realised pnl (all-time total) |
cross_seq | number | Cross sequence (internal value) |
position_seq | number | Position sequence |
created_at | string | The account creation time |
updated_at | string | Update time |
tp_sl_mode | string | Stop loss and take profit mode |
Change Margin
Request Example
curl https://api-testnet.bybit.com/v2/private/position/change-position-margin \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","symbol":"BTCUSD",margin:"10","timestamp":{timestamp},"sign":"{sign}"}'
from pybit import inverse_perpetual
session_auth = inverse_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com",
api_key="your api key",
api_secret="your api secret"
)
print(session_auth.change_margin(
symbol="BTCUSD",
margin=0.00001
))
Response Example
{
"ret_code": 0,
"ret_msg": "ok",
"ext_code": "",
"result": 0.00000997,
"ext_info": null,
"time_now": "1577480720.003444",
"rate_limit_status": 74,
"rate_limit_reset_ms": 1577480720011,
"rate_limit": 75
}
Update margin.
HTTP Request
POST
/v2/private/position/change-position-margin
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
symbol | true | string | Symbol |
margin | true | string | margin |
Response Parameters
Parameter | Type | Comment |
---|---|---|
result | number | User margin |
Set Trading-Stop
Request Example
curl https://api-testnet.bybit.com/v2/private/position/trading-stop \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","symbol":"BTCUSD","stop_loss":7000,"timestamp":{timestamp},"sign":"{sign}"}'
from pybit import inverse_perpetual
session_auth = inverse_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com",
api_key="your api key",
api_secret="your api secret"
)
print(session_auth.set_trading_stop(
symbol="BTCUSD",
stop_loss=7000
))
Response Example
{
"ret_code": 0,
"ret_msg": "OK",
"ext_code": "",
"ext_info": "",
"result": {
"id": 0,
"user_id": 533285,
"symbol": "BTCUSD",
"side": "Buy",
"size": 400,
"position_value": 0.019995,
"entry_price": 20005.00125031,
"risk_id": 1,
"auto_add_margin": 0,
"leverage": 2,
"position_margin": 0.0099975,
"liq_price": 13381.5,
"bust_price": 13337,
"occ_closing_fee": 0.000018,
"occ_funding_fee": 0,
"take_profit": 26000,
"stop_loss": 14000,
"trailing_stop": 0,
"position_status": "Normal",
"deleverage_indicator": 4,
"oc_calc_data": "{\"blq\":100,\"blv\":\"0.00588235\",\"slq\":0,\"bmp\":17000.0085,\"smp\":0,\"fq\":-400,\"fc\":-0.00295,\"bv2c\":0.5015,\"sv2c\":0.5009}",
"order_margin": 0.00295,
"wallet_balance": 0.3999834,
"realised_pnl": 0,
"cum_realised_pnl": -0.00000526,
"cum_commission": 0,
"cross_seq": 5208583955,
"position_seq": 0,
"created_at": "2022-06-09T07:14:33.264474461Z",
"updated_at": "2022-06-21T04:08:10.185159763Z",
"ext_fields": {
"trailing_active": "0",
"sl_trigger_by": "LastPrice",
"tp_trigger_by": "LastPrice",
"v": 10151,
"mm": 0
}
},
"time_now": "1655784490.185727",
"rate_limit_status": 74,
"rate_limit_reset_ms": 1655784490182,
"rate_limit": 75
}
Set take profit, stop loss, and trailing stop for your open position.
HTTP Request
POST
/v2/private/position/trading-stop
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
symbol | true | string | Symbol |
take_profit | false | number | Cannot be less than 0, 0 means cancel TP (Not effective under partial mode) |
stop_loss | false | number | Cannot be less than 0, 0 means cancel SL (Not effective under partial mode) |
trailing_stop | false | number | Cannot be less than 0, 0 means cancel TS (Not effective under partial mode) |
tp_trigger_by | false | string | Take profit trigger price type, default: LastPrice
|
sl_trigger_by | false | string | Stop loss trigger price type, default: LastPrice
|
new_trailing_active | false | number | Trailing stop trigger price. Trailing stops are triggered only when the price reaches the specified price. Trailing stops are triggered immediately by default. |
sl_size | false | number | Stop loss quantity (when in partial mode) |
tp_size | false | number | Take profit quantity (when in partial mode) |
Response Parameters
Parameter | Type | Comment |
---|---|---|
id | number | PositionID |
user_id | number | UserID |
symbol | string | Symbol |
side | string | Side |
size | number | Position qty |
position_value | number | Position value |
entry_price | number | Average entry price |
risk_id | number | Risk ID |
auto_add_margin | number | Whether or not auto-margin replenishment is enabled |
leverage | number | In Isolated Margin mode, the value is set by the user. In Cross Margin mode, the value is the max leverage at current risk level |
position_margin | number | Position margin |
liq_price | number | Liquidation price |
bust_price | number | Bankruptcy price |
occ_closing_fee | number | Position closing fee occupied (your opening fee + expected maximum closing fee) |
occ_funding_fee | number | Pre-occupied funding fee: calculated from position qty and current funding fee |
take_profit | number | Take profit price |
stop_loss | number | Stop loss price |
trailing_stop | number | Trailing stop (the distance from the current price) |
position_status | string | Position status: Normal , Liq , Adl
|
deleverage_indicator | number | Deleverage indicator level (1,2,3,4,5) |
oc_calc_data | map | Pre-occupied calculate parameters. blq : total number of the long side unsettled orders; bmp : the lowest price of the long side; slq : total number of the short side unsettled orders; smp : the lowest price of the short side
|
order_margin | number | Pre-occupied order margin |
wallet_balance | number | Wallet balance |
realised_pnl | number | Today's realised pnl |
cum_realised_pnl | number | Accumulated realised pnl (all-time total) |
cum_commission | number | Accumulated commission |
cross_seq | number | Cross sequence (internal value) |
position_seq | number | Position sequence |
created_at | string | Creation time (when the order_status was Created ) |
updated_at | string | Update time |
trailing_active | string | Trailing stop active price |
sl_trigger_by | string | Stop loss trigger price type |
tp_trigger_by | string | Take profit trigger price type |
Set Leverage
Request Example
curl https://api-testnet.bybit.com/v2/private/position/leverage/save \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","symbol":"BTCUSD","leverage":14,"timestamp":{timestamp},"sign":"{sign}"}'
from pybit import inverse_perpetual
session_auth = inverse_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com",
api_key="your api key",
api_secret="your api secret"
)
print(session_auth.set_leverage(
symbol="BTCUSD",
leverage=2
))
Response Example
{
"ret_code": 0,
"ret_msg": "ok",
"ext_code": "",
"result": 2,
"ext_info": null,
"time_now": "1577477968.175013",
"rate_limit_status": 74,
"rate_limit_reset_ms": 1577477968183,
"rate_limit": 75
}
Set Leverage
HTTP Request
POST
/v2/private/position/leverage/save
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
symbol | true | string | Symbol |
leverage | true | number | Must be greater than 0 and less than the risk limit leverage. If you need to switch to cross margin please see the Cross/Isolated Margin Switch endpoint |
leverage_only | false | bool | Use this parameter to set leverage while in cross margin mode. If this field is set to false , when leverage is equal to 0 the position will use cross margin; when leverage is greater than 0 the position will use isolated margin. If this field is set to true , you can set leverage in cross margin with leverage . leverage must be greater than 0 . Use the Cross/Isolated Margin Switch endpoint to switch cross/isolated without modifying the cross level of leverage. |
Response Parameters
Parameter | Type | Comment |
---|---|---|
result | number | User leverage |
Get User Trade Records
Request Example
curl "https://api-testnet.bybit.com/v2/private/execution/list?api_key={api_key}&symbol=BTCUSD×tamp={timestamp}&sign={sign}"
from pybit import inverse_perpetual
session_auth = inverse_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com",
api_key="your api key",
api_secret="your api secret"
)
print(session_auth.user_trade_records(
symbol="BTCUSD"
))
Response Example
{
"ret_code": 0,
"ret_msg": "OK",
"ext_code": "",
"ext_info": "",
"result": {
"order_id": "Abandoned!!",
"trade_list": [
{
"closed_size": 0,
"cross_seq": 277136382,
"exec_fee": "0.0000001",
"exec_id": "256e5ef8-abfe-5772-971b-f944e15e0d68",
"exec_price": "8178.5",
"exec_qty": 1,
"exec_time": "1571676941.70682",
"exec_type": "Trade",
"exec_value": "0.00012227",
"fee_rate": "0.00075",
"last_liquidity_ind": "RemovedLiquidity",
"leaves_qty": 0,
"nth_fill": 2,
"order_id": "7ad50cb1-9ad0-4f74-804b-d82a516e1029",
"order_link_id": "",
"order_price": "8178",
"order_qty": 1,
"order_type": "Market",
"side": "Buy",
"symbol": "BTCUSD",
"user_id": 1,
"trade_time_ms": 1577480599000
}
]
},
"time_now": "1577483699.281488",
"rate_limit_status": 118,
"rate_limit_reset_ms": 1577483699244737,
"rate_limit": 120
}
Get user's trading records. The results are ordered in ascending order (the first item is the oldest). If you want to get the records up to 2 years old, please refer to contract v3 endpoint
HTTP Request
GET
/v2/private/execution/list
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
order_id | false | string | OrderID. If not provided, will return user's trading records |
symbol | true | string | Contract type. Required |
start_time | false | int | Start timestamp point for result, in milliseconds |
page | false | integer | Page. By default, gets first page of data. Maximum of 50 pages |
limit | false | integer | Limit for data size per page, max size is 200. Default as showing 50 pieces of data per page |
order | false | string | Sort orders by creation date. Defaults to asc |
Response Parameters
Parameter | Type | Comment |
---|---|---|
closed_size | number | The corresponding closing size of the closing order |
cross_seq | number | Cross sequence (internal value) |
exec_fee | string | Transaction fee |
exec_id | string | Transaction ID |
exec_price | string | Transaction price |
exec_qty | number | Transaction qty |
exec_time | number | Transaction time |
exec_type | string | Exec type |
exec_value | string | Transaction value |
fee_rate | string | Maker or taker fee rate |
last_liquidity_ind | string | Only valid while exec_type is Trade , AdlTrade , BustTrade |
leaves_qty | number | Number of unfilled contracts from the order's size |
nth_fill | number | The sequence of the transaction in this cross sequence data package |
order_id | string | Order ID |
order_link_id | string | Unique user-set order ID. Maximum length of 36 characters |
order_price | string | Order price |
order_qty | number | Order qty |
order_type | string | Order type |
side | string | Side |
symbol | string | Symbol |
trade_time_ms | number | Transaction timestamp |
user_id | number | User ID |
Closed Profit and Loss
Request Example
curl "https://api-testnet.bybit.com/v2/private/trade/closed-pnl/list?api_key={api_key}&symbol=BTCUSD×tamp={timestamp}&sign={sign}"
from pybit import inverse_perpetual
session_auth = inverse_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com",
api_key="your api key",
api_secret="your api secret"
)
print(session_auth.closed_profit_and_loss(
symbol="BTCUSD"
))
Response Example
{
"ret_code": 0,
"ret_msg": "OK",
"ext_code": "",
"ext_info": "",
"result": {
"current_page": 1,
"data": [
{
"id": 9982,
"user_id": 160320,
"symbol": "BTCUSD",
"order_id": "e976ac13-10e7-4883-a7ba-13b0e93659f1",
"side": "Sell",
"qty": 226,
"order_price": 1600,
"order_type": "Limit",
"exec_type": "Trade",
"closed_size": 113,
"cum_entry_value": 0.07062500000000001,
"avg_entry_price": 1600,
"cum_exit_value": 0.066198,
"avg_exit_price": 1707,
"closed_pnl": 0.0043950000000000005,
"fill_count": 1,
"leverage": 100,
"created_at": 1591155741
}
]
},
"time_now": "1591173153.876047",
"rate_limit_status": 119,
"rate_limit_reset_ms": 1591173153852,
"rate_limit": 120
}
Get user's closed profit and loss records. The results are ordered in descending order (the first item is the latest).
HTTP Request
GET
/v2/private/trade/closed-pnl/list
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
symbol | true | string | Symbol |
start_time | false | int | Start timestamp point for result, in seconds |
end_time | false | int | End timestamp point for result, in seconds |
exec_type | false | string | Execution type (cannot be Funding ) |
page | false | integer | Page. By default, gets first page of data. Maximum of 50 pages |
limit | false | integer | Limit for data size per page, max size is 50. Default as showing 20 pieces of data per page. |
Response Parameters
Parameter | Type | Comment |
---|---|---|
id | number | PositionID |
user_id | number | UserID |
symbol | string | Symbol |
order_id | string | Order ID of the closing order |
side | string | Side of the closing order |
qty | number | Order quantity in USD |
order_price | number | Order price |
order_type | string | Active order type |
exec_type | string | Exec type |
closed_size | number | The corresponding closing size of the closing order |
cum_entry_value | number | Closed position value |
avg_entry_price | number | Average entry price |
cum_exit_value | number | Cumulative trading value of position closing orders |
avg_exit_price | number | Average exit price |
closed_pnl | number | Closed Profit and Loss |
fill_count | number | The number of fills in a single order |
leverage | number | In Isolated Margin mode, the value is set by the user. In Cross Margin mode, the value is the max leverage at current risk level |
created_at | number | Creation time (when the order_status was Created ) |
Full/Partial Position TP/SL Switch
Request Example
from pybit import inverse_perpetual
session_auth = inverse_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com",
api_key="your api key",
api_secret="your api secret"
)
print(session_auth.full_partial_position_tp_sl_switch(
symbol="BTCUSD",
tp_sl_mode="Partial"
))
Response Example
{
"ret_code": 0,
"ret_msg": "OK",
"ext_code": "",
"ext_info": "",
"result": {
"tp_sl_mode": "Partial"
},
"time_now": "1598266294.610276",
"rate_limit_status": 72,
"rate_limit_reset_ms": 1598266294607,
"rate_limit": 75
}
Switch mode between Full or Partial
HTTP Request
POST
/v2/private/tpsl/switch-mode
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
symbol | true | string | Symbol |
tp_sl_mode | true | string | Stop loss and take profit mode |
Response Parameters
Parameter | Type | Comment |
---|---|---|
tp_sl_mode | string | Stop loss and take profit mode |
Cross/Isolated Margin Switch
Request Example
curl https://api-testnet.bybit.com/v2/private/position/switch-isolated \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","symbol":"BTCUSD", "is_isolated":true,"buy_leverage":10,"sell_leverage":20, "timestamp":{timestamp},"sign":"{sign}"}'
from pybit import inverse_perpetual
session_auth = inverse_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com",
api_key="your api key",
api_secret="your api secret"
)
print(session_auth.cross_isolated_margin_switch(
symbol="BTCUSD",
is_isolated=True,
buy_leverage=10,
sell_leverage=20
))
Response Example
{
"ret_code": 0,
"ret_msg": "ok",
"ext_code": "",
"result": null,
"ext_info": null,
"time_now": "1577477968.175013",
"rate_limit_status": 74,
"rate_limit_reset_ms": 1577477968183,
"rate_limit": 75
}
Switch Cross/Isolated; must set leverage value when switching from Cross to Isolated
HTTP Request
POST
/v2/private/position/switch-isolated
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
symbol | true | string | Symbol |
is_isolated | true | bool | Cross/Isolated: true is Isolated; false is Cross |
buy_leverage | true | number | When switching from cross to isolated, the value of buy_leverage must be equal to sell_leverage . |
sell_leverage | true | number | When switching from cross to isolated, the value of buy_leverage must be equal to sell_leverage . |
Query Trading Fee Rate
Request Example
curl https://api.bybit.com/v2/private/position/fee-rate?api_key={api_key}&symbol=BTCUSD×tamp={timestamp}&sign={sign} \
from pybit import inverse_perpetual
session_auth = inverse_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com",
api_key="your api key",
api_secret="your api secret"
)
print(session_auth.query_trading_fee_rate(
symbol="BTCUSD"
))
Response Example
{
"ret_code": 0,
"ret_msg": "ok",
"ext_code": "",
"result":
{
"user_id": "",
"taker_fee_rate": "",
"maker_fee_rate": "",
},
"ext_info": null,
"time_now": "1577477968.175013",
"rate_limit_status": 74,
"rate_limit_reset_ms": 1577477968183,
"rate_limit": 75
}
HTTP Request
GET
/v2/private/position/fee-rate
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
symbol | true | string | Symbol |
Response Parameters
Parameter | Type | Comment |
---|---|---|
user_id | number | User ID |
taker_fee_rate | string | Taker fee rate |
maker_fee_rate | string | Maker fee rate |
Risk Limit
Get Risk Limit
Request Example
curl "https://api-testnet.bybit.com/v2/public/risk-limit/list?symbol=BTCUSD"
from pybit import inverse_perpetual
session_unauth = inverse_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com"
)
print(session_unauth.get_risk_limit(
symbol="BTCUSD"
))
Response Example
{
"ret_code": 0,
"ret_msg": "OK",
"result": [
{
"id": 11,
"is_lowest_risk": 1,
"section": [
"1",
"2",
"3",
"5",
"10",
"25",
"50",
"100"
],
"symbol": "ETHUSD",
"limit": 500,
"max_leverage": "100",
"starting_margin": "1",
"maintain_margin": "0.5",
"coin": "ETH",
"created_at": "",
"updated_at": ""
},
...
{
"id": 21,
"is_lowest_risk": 0,
"section": [
"1",
"2",
"3",
"4",
"5",
"7",
"8",
"9"
],
"symbol": "ETHUSD",
"limit": 30000,
"max_leverage": "9.1",
"starting_margin": "11",
"maintain_margin": "5.5",
"coin": "ETH",
"created_at": "",
"updated_at": ""
}
],
"ext_code": "",
"ext_info": "",
"time_now": "1662629588.663921"
}
Get risk limit. This endpoint does not require authentication.
HTTP Request
GET
/v2/public/risk-limit/list
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
symbol | false | string | Symbol |
Response Parameters
Parameter | Type | Comment |
---|---|---|
id | number | Risk ID |
symbol | string | Symbol |
limit | number | Risk limit |
maintain_margin | number | Maintain margin |
starting_margin | number | Starting margin. The same as the "Initial Margin %" shown in the risk limit tables |
section | string | Section |
is_lowest_risk | number | Is lowest risk. 0 : No; 1 : Yes
|
created_at | string | Creation time (when the order_status was Created ) |
updated_at | string | Update time |
max_leverage | string | Max leverage |
Set Risk Limit
Request Example
curl https://api-testnet.bybit.com/v2/private/position/risk-limit \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","symbol":"BTCUSD","risk_id":2,"timestamp":{timestamp},"sign":"{sign}"}'
from pybit import inverse_perpetual
session_auth = inverse_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com",
api_key="your api key",
api_secret="your api secret"
)
print(session_auth.set_risk_limit(
symbol="BTCUSD",
risk_id=2
))
Response Example
{
"ret_code": 0,
"ret_msg": "OK",
"ext_code": "",
"ext_info": "",
"result": {
"risk_id": 2
},
"time_now": "1620283810.393787",
"token": null
}
HTTP Request
POST
/v2/private/position/risk-limit
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
symbol | true | string | Symbol |
risk_id | true | integer | Risk ID |
Response Parameters
Parameter | Type | Comment |
---|---|---|
risk_id | number | Risk ID |
Funding
Get the Last Funding Rate
Request Example
curl "https://api-testnet.bybit.com/v2/public/funding/prev-funding-rate?symbol=BTCUSD"
from pybit import inverse_perpetual
session_unauth = inverse_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com"
)
print(session_unauth.get_the_last_funding_rate(
symbol="BTCUSD"
))
Response Example
{
"ret_code": 0,
"ret_msg": "ok",
"ext_code": "",
"result": {
"symbol": "BTCUSD",
"funding_rate": "0.00010000",
"funding_rate_timestamp": 1577433600
},
"ext_info": null,
"time_now": "1577445586.446797",
"rate_limit_status": 119,
"rate_limit_reset_ms": 1577445586454,
"rate_limit": 120
}
The funding rate is generated every 8 hours at 00:00 UTC, 08:00 UTC and 16:00 UTC. For example, if a request is sent at 12:00 UTC, the funding rate generated earlier that day at 08:00 UTC will be sent.
HTTP Request
GET
/v2/public/funding/prev-funding-rate
Request Parameters
parameter | Required | Type | Comment |
---|---|---|---|
symbol | true | string | Symbol |
Response Parameters
Parameter | Type | Comment |
---|---|---|
symbol | string | Symbol |
funding_rate | string | Funding rate |
funding_rate_timestamp | number | Funding rate timestamp |
My Last Funding Fee
Request Example
curl "https://api-testnet.bybit.com/v2/private/funding/prev-funding?api_key={api_key}&symbol=BTCUSD×tamp={timestamp}&sign={sign}"
from pybit import inverse_perpetual
session_auth = inverse_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com",
api_key="your api key",
api_secret="your api secret"
)
print(session_auth.my_last_funding_fee(
symbol="BTCUSD"
))
Response Example
{
"ret_code": 0,
"ret_msg": "ok",
"ext_code": "",
"result": {
"symbol": "BTCUSD",
"side": "Buy",
"size": 1,
"funding_rate": 0.0001,
"exec_fee": 0.00000002,
"exec_timestamp": 1575907200
},
"ext_info": null,
"time_now": "1577446900.717204",
"rate_limit_status": 119,
"rate_limit_reset_ms": 1577446900724,
"rate_limit": 120
}
Funding settlement occurs every 8 hours at 00:00 UTC, 08:00 UTC and 16:00 UTC. The current interval's fund fee settlement is based on the current interval's fund rate. For example, at 16:00, the settlement is based on the fund rate generated at 16:00.
HTTP Request
GET
/v2/private/funding/prev-funding
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
symbol | true | string | Symbol |
Response Parameters
Parameter | Type | Comment |
---|---|---|
symbol | string | Symbol |
side | string | Your position side at the time of settlement |
size | number | Your position size at the time of settlement |
funding_rate | number | Funding rate |
exec_fee | number | Transaction fee |
exec_timestamp | number | Transaction time |
Predicted Funding Rate and My Funding Fee
Request Example
curl "https://api-testnet.bybit.com/v2/private/funding/predicted-funding?api_key={api_key}&symbol=BTCUSD×tamp={timestamp}&sign={sign}"
from pybit import inverse_perpetual
session_auth = inverse_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com",
api_key="your api key",
api_secret="your api secret"
)
print(session_auth.predicted_funding_rate(
symbol="BTCUSD"
))
Response Example
{
"ret_code": 0,
"ret_msg": "ok",
"ext_code": "",
"result": {
"predicted_funding_rate": 0.0001,
"predicted_funding_fee": 0
},
"ext_info": null,
"time_now": "1577447415.583259",
"rate_limit_status": 118,
"rate_limit_reset_ms": 1577447415590,
"rate_limit": 120
}
Get predicted funding rate and my predicted funding fee.
HTTP Request
GET
/v2/private/funding/predicted-funding
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
symbol | true | string | Symbol |
Response Parameters
Parameter | Type | Comment |
---|---|---|
predicted_funding_rate | number | Predicted funding rate |
predicted_funding_fee | number | Predicted funding fee |
API Key Info
Request Example
curl "https://api-testnet.bybit.com/v2/private/account/api-key?api_key={api_key}×tamp={timestamp}&sign={sign}"
from pybit import inverse_perpetual
session_auth = inverse_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com",
api_key="your api key",
api_secret="your api secret"
)
print(session_auth.api_key_info())
Response Example
{
"ret_code": 0,
"ret_msg": "OK",
"ext_code": "",
"ext_info": "",
"result": [
{
"api_key": "XXXXXX",
"type": "personal",
"user_id": XXXX,
"inviter_id": 0,
"ips": [
"*"
],
"note": "apikey",
"permissions": [
"Order",
"Position",
"SpotTrade",
"AccountTransfer",
"OptionsTrade",
"DerivativesTrade"
],
"created_at": "2022-08-25T07:16:07Z",
"expired_at": "2022-11-25T07:16:07Z",
"read_only": false,
"vip_level": "VIP-1",
"mkt_maker_level": "0",
"affiliate_id": 0
}
],
"time_now": "1664188595.552202",
"rate_limit_status": 599,
"rate_limit_reset_ms": 1664188595514,
"rate_limit": 600
}
Get user's API key info.
HTTP Request
GET
/v2/private/account/api-key
Request Parameters
Parameter | Required | Type | Comment |
---|
Response Parameters
Parameter | Type | Comment |
---|---|---|
api_key | string | API key |
type | string | Key type |
user_id | number | User ID |
inviter_id | number | Inviter ID (the UID of the account which invited this account to the platform) |
ips | string | IP |
note | string | Note |
permissions | string | ApiKey permission |
created_at | string | Creation time (when the order_status was Created ) |
expired_at | string | Expire time |
read_only | bool | ReadOnly |
vip_level | string | VIP Level |
mkt_maker_level | string | Market maker level |
affiliate_id | number | Affiliate Id. 0 represents that there is no binding relationship. |
LCP Info
Request Example
curl "https://api-testnet.bybit.com/v2/private/account/lcp?api_key={api_key}&symbol=BTCUSD×tamp={timestamp}&sign={sign}"
from pybit import inverse_perpetual
session_auth = inverse_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com",
api_key="your api key",
api_secret="your api secret"
)
print(session_auth.lcp_info(
symbol="BTCUSD"
))
Response Example
{
"ret_code": 0,
"ret_msg": "ok",
"ext_code": "",
"result": [
"lcp_list": [
{
"date": "2020-04-27",
"self_ratio": 0,
"platform_ratio": 0,
"score": 0.1459
},
{
"date": "2020-04-26",
"self_ratio": 0,
"platform_ratio": 0,
"score": 0.1459
}
]
],
"ext_info": null,
"time_now": "1577445138.790150",
"rate_limit_status": 99,
"rate_limit_reset_ms": 1577445138812,
"rate_limit": 100
}
Get user's LCP (data refreshes once an hour). Only supports inverse perpetual at present.
See Understanding Bybit's Liquidity System to learn more.
HTTP Request
GET
/v2/private/account/lcp
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
symbol | true | string | Symbol |
Response Parameters
Parameter | Type | Comment |
---|---|---|
date | string | Date |
self_ratio | number | Deprecated! Personal effective ratio |
platform_ratio | number | Deprecated! Platform effective ratio |
score | number | Liquidity contribution points |
Wallet Data Endpoints
The following wallet data endpoints require authentication.
Get Wallet Balance
Request Example
curl "https://api-testnet.bybit.com/v2/private/wallet/balance?api_key={api_key}&coin=BTC×tamp={timestamp}&sign={sign}"
from pybit import inverse_perpetual
session_auth = inverse_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com",
api_key="your api key",
api_secret="your api secret"
)
print(session_auth.get_wallet_balance(coin="BTC"))
Response Example
{
"ret_code": 0,
"ret_msg": "OK",
"ext_code": "",
"ext_info": "",
"result": {
"BTC": {
"equity": 1002,
"available_balance": 999.99987471,
"used_margin": 0.00012529,
"order_margin": 0.00012529,
"position_margin": 0,
"occ_closing_fee": 0,
"occ_funding_fee": 0,
"wallet_balance": 1000,
"realised_pnl": 0,
"unrealised_pnl": 2,
"cum_realised_pnl": 0,
"given_cash": 0,
"service_cash": 0
}
},
"time_now": "1578284274.816029",
"rate_limit_status": 98,
"rate_limit_reset_ms": 1580885703683,
"rate_limit": 100
}
Get wallet balance info.
HTTP Request
GET
/v2/private/wallet/balance
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
coin | false | string | currency alias. Returns all wallet balances if not passed |
Response Parameters
Parameter | Type | Comment |
---|---|---|
equity | number | User equity (wallet_balance + unrealised_pnl) |
available_balance | number | In Isolated Margin Mode: available_balance = wallet_balance - (position_margin + occ_closing_fee + occ_funding_fee + order_margin) In Cross Margin Mode: if unrealised_pnl > 0: available_balance = wallet_balance - (position_margin + occ_closing_fee + occ_funding_fee + order_margin) if unrealised_pnl < 0: available_balance = wallet_balance - (position_margin + occ_closing_fee + occ_funding_fee + order_margin) + unrealised_pnl |
used_margin | number | Used margin |
order_margin | number | Pre-occupied order margin |
position_margin | number | Position margin |
occ_closing_fee | number | Position closing fee occupied (your opening fee + expected maximum closing fee) |
occ_funding_fee | number | Pre-occupied funding fee: calculated from position qty and current funding fee |
wallet_balance | number | Wallet balance |
realised_pnl | number | Today's realised pnl |
unrealised_pnl | number | unrealised pnl |
cum_realised_pnl | number | Accumulated realised pnl (all-time total) |
given_cash | number | Experience gold |
service_cash | number | Service cash is used for user's service charge |
Wallet Fund Records
Request Example
curl "https://api-testnet.bybit.com/v2/private/wallet/fund/records?api_key={api_key}×tamp={timestamp}&sign={sign}"
from pybit import inverse_perpetual
session_auth = inverse_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com",
api_key="your api key",
api_secret="your api secret"
)
print(session_auth.wallet_fund_records())
Response Example
{
"ret_code": 0,
"ret_msg": "ok",
"ext_code": "",
"result": {
"data": [
{
"id": 235853,
"user_id": 1,
"coin": "BTC",
"wallet_id": 27913,
"type": "Realized P&L",
"amount": "0.00000023",
"tx_id": "",
"address": "BTCUSD",
"wallet_balance": "0.03000353",
"exec_time": "2019-12-10T00:00:29.000Z",
"cross_seq": 0
},
{
"id": 234467,
"user_id": 1,
"coin": "BTC",
"wallet_id": 27913,
"type": "Realized P&L",
"amount": "-0.00000006",
"tx_id": "",
"address": "BTCUSD",
"wallet_balance": "0.03000330",
"exec_time": "2019-12-09T00:00:25.000Z",
"cross_seq": 0
}
]
},
"ext_info": null,
"time_now": "1577481867.115552",
"rate_limit_status": 119,
"rate_limit_reset_ms": 1577481867122,
"rate_limit": 120
}
Get wallet fund records. This endpoint also shows exchanges from the Asset Exchange, where the type
s for the exchange are ExchangeOrderWithdraw
and ExchangeOrderDeposit
.
This endpoint returns incomplete information for transfers involving the derivatives wallet. Use the account asset API for creating and querying internal transfers.
HTTP Request
GET
/v2/private/wallet/fund/records
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
start_date | false | string | Start point for result |
end_date | false | string | End point for result |
currency | false | string | Currency type |
coin | false | string | currency alias |
wallet_fund_type | false | string | Wallet fund type |
page | false | integer | Page. By default, gets first page of data. |
limit | false | integer | Limit for data size per page, max size is 50. Default as showing 20 pieces of data per page |
Response Parameters
Parameter | Type | Comment |
---|---|---|
user_id | number | UserID |
coin | string | Coin type |
wallet_id | number | Wallet ID |
type | string | Fund type |
amount | string | Fund amount |
tx_id | string | Transaction hash ID |
address | string | Address |
wallet_balance | string | Wallet balance |
exec_time | string | Transaction time |
cross_seq | number | Cross sequence (internal value) |
Withdraw Records
Request Example
curl "https://api-testnet.bybit.com/v2/private/wallet/withdraw/list?api_key={api_key}×tamp={timestamp}&sign={sign}"
from pybit import inverse_perpetual
session_auth = inverse_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com",
api_key="your api key",
api_secret="your api secret"
)
print(session_auth.withdraw_records())
Response Example
{
"ret_code": 0,
"ret_msg": "ok",
"ext_code": "",
"result": {
"data": [{
"id": 137,
"user_id": 1,
"coin": "XRP",
"status": "Pending"
"amount": "20.00000000",
"fee": "0.25000000",
"address": "rH7H595XYEVTEHU2FySYsWnmfACBnZS9zM",
"tx_id": "",
"submited_at": "2019-06-11T02:20:24.000Z",
"updated_at": "2019-06-11T02:20:24.000Z"
}]
"current_page": 1,
"last_page": 1
},
"ext_info": null,
"time_now": "1577482295.125488",
"rate_limit_status": 119,
"rate_limit_reset_ms": 1577482295132,
"rate_limit": 120
}
Get withdrawal records.
The difference between data returned by this endpoint and data of type Withdraw
in the Wallet Fund Records endpoint:
This endpoint provides one withdrawal operation per record, and you can check the current withdrawal state with the status
field.
Once you have submitted a withdrawal application, there will be a record with type Withdraw
, and if the application is CancelByUser
, Reject
or Expire
in the Wallet Fund Records endpoint, with a corresponding record with type Refund
.
HTTP Request
GET
/v2/private/wallet/withdraw/list
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
start_date | false | string | Start point for result |
end_date | false | string | End point for result |
coin | false | string | Currency type |
status | false | string | Withdraw status |
page | false | integer | Page. By default, gets first page of data. |
limit | false | integer | Limit for data size per page, max size is 50. Default as showing 20 pieces of data per page |
Response Parameters
Parameter | Type | Comment |
---|---|---|
user_id | number | UserID |
coin | string | Coin type |
status | string | Withdraw status |
amount | string | Fund amount |
fee | string | Maker or taker fee rate |
address | string | Address |
tx_id | string | Transaction hash ID |
submited_at | string | Submit time |
updated_at | string | Update time |
Asset Exchange Records
Request Example
curl "https://api-testnet.bybit.com/v2/private/exchange-order/list?api_key={api_key}×tamp={timestamp}&sign={sign}"
from pybit import inverse_perpetual
session_auth = inverse_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com",
api_key="your api key",
api_secret="your api secret"
)
print(session_auth.asset_exchange_records())
Response Example
{
"ret_code": 0,
"ret_msg": "OK",
"ext_code": "",
"ext_info": "",
"result": [
{
"id": 31,
"exchange_rate": 40.57202774,
"from_coin": "BTC",
"to_coin": "ETH",
"to_amount": 4.05720277,
"from_fee": 0.0005,
"from_amount": 0.1,
"created_at": "2020-06-15 03:32:52"
},
{
"id": 30,
"exchange_rate": 39.92359901,
"from_coin": "BTC",
"to_coin": "ETH",
"to_amount": 39.923599,
"from_fee": 0.0005,
"from_amount": 1,
"created_at": "2020-06-12 08:27:51"
}
],
"time_now": "1592554785.486414",
"rate_limit_status": 119,
"rate_limit_reset_ms": 1592554785484,
"rate_limit": 120
}
Get asset exchange records.
HTTP Request
GET
/v2/private/exchange-order/list
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
limit | false | integer | Limit for data size per page, max size is 50. Default as showing 20 pieces of data per page |
from | false | integer | Start ID. By default, returns the latest IDs |
direction | false | string | Search direction. Prev : searches in ascending order from start ID, Next : searches in descending order from start ID. Defaults to Next
|
Response Parameters
Parameter | Type | Comment |
---|---|---|
from_coin | string | Exchange from coin |
from_amount | number | Exchange from amount |
to_coin | string | Exchange to coin |
to_amount | number | Exchange to amount |
exchange_rate | number | Exchange exchange rate |
from_fee | number | Exchange fee in `from_coin` unit |
created_at | string | Exchange time |
API Data Endpoints
The following API data endpoints do not require authentication.
Server Time
Request Example
curl https://api-testnet.bybit.com/v2/public/time
from pybit import inverse_perpetual
session_unauth = inverse_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com"
)
print(session_unauth.server_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-testnet.bybit.com/v2/public/announcement
from pybit import inverse_perpetual
session_unauth = inverse_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com"
)
print(session_unauth.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 |
---|
Rate Limits
IP Rate Limit
Bybit has different IP frequency limits depending on the request method. We do not recommend running your application at the very edge of these limits in case abnormal network activity results in an unexpected violation.
-
GET
,POST
&DELETE
methods (shared):- 120 requests per second for 5 consecutive seconds
All traffic to api.bybit.com or api.bytick.com share this limit regardless of if it accesses Spot, Derivatives or Options.
After violating the limit your IP will be banned for a set period of time (usually 30 minutes). Continually violating the limit will result in a permanent ban. We cannot undo permanent bans or shorten temporary bans.
API Rate Limit
The API rate limit is based on the rolling time window per minute and UID, and each symbol is independent. In other words, it's per minute per UID per symbol. 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_limit_status
- your remaining requests for current endpointrate_limit
- your current limit for current endpointrate_limit_reset_ms
- the timestamp indicating when your request limit resets if you have exceeded your rate_limit. Otherwise, this is just the current timestamp.
Rate Limits For All Private Endpoints
Limit | Path | Consume |
---|---|---|
100/min | ||
/v2/private/order/cancel | 1 / request | |
/v2/private/stop-order/create | 1 / request | |
/v2/private/stop-order/cancel | 1 / request | |
/v2/private/order/replace | 1 / request | |
/v2/private/stop-order/replace | 1 / request | |
/v2/private/order/create | 1 / request | |
/v2/private/order/cancel | 1 / request | |
/v2/private/order/cancelAll | 10 / request | |
/v2/private/stop-order/cancelAll | 10 / request | |
600/min | /v2/private/order/list | 1 / request |
/v2/private/stop-order/list | 1 / request | |
/v2/private/order | 1 / request | |
120/min | /v2/private/execution/list | 1 / request |
75/min | /v2/private/position/leverage/save | 1 / request |
/v2/private/position/change-position-margin | 1 / request | |
/v2/private/position/trading-stop | 1 / request | |
/v2/private/tpsl/switch-mode | 1 / request | |
/v2/private/position/fee-rate | 1 / request | |
120/min | ||
/v2/private/position/list | 1 / request | |
/v2/private/wallet/balance | 1 / request | |
120/min | ||
/v2/private/funding/prev-funding-rate | 1 / request | |
/v2/private/funding/prev-funding | 1 / request | |
/v2/private/funding/predicted-funding | 1 / request | |
120/min | ||
/v2/private/wallet/fund/records | 1 / request | |
/v2/private/wallet/withdraw/list | 1 / request | |
600/min | ||
/v2/private/account/api-key | 1 / request |
Order Limits
Max. number of unfilled orders supported under each trading pair:
- Active orders: 500
- Conditional orders: 10
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
- Please refer to Understanding Bybit's Liquidity System regarding how our system automatically allocates rate limits for users who place over 2,000 orders per day.
- Please email api@bybit.com with the following information. We will reply within 1-4 working days:
- Your name and your company details
- Your Bybit UID or registered email, and the assets you are trading
- General description of your trading strategy and reasons for higher rate limits
- Screenshot of previous monthly trading volume (maker/taker) on other platforms
- Optional: your order history in CSV format
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.
Minimum OFR Threshold
7-day OFR must be kept above 0.1%.
Order Fill Ratio (OFR)
Order Fill Ratio (OFR)
:Orders Filled
toOrders Submitted to Bybit
to Bybit.Orders Submitted to Bybit
: any order submitted to Bybit.Orders Filled
: any order that has been filled (regardless of filled quantity).OFR = (number of orders filled / number of orders submitted to Bybit)
Order Fill Ratio Example
User A: Orders Filled = 2 Orders Submitted to Bybit = 8 OFR = 2/8 = 25%
User B: Orders Filled = 1 Orders Submitted to Bybit = 1 OFR = 1/1 = 100%
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)
Liquidity Contribution Points (LCP) = POU * POA * 100
Explanation
Effective Price Range
effective price range
: order price that falls within the lower and upper price bounds.Min
effective price
: (best bid price + best ask price) / 2 - (3 * tick_size)Max
effective price
: (best bid price + best ask price) / 2 + (3 * tick_size)
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
POU
: The size of your orders that fall within theeffective price range
in proportion to the total size of your orders in the order book.
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
POA
: the proportion of your orders withineffective price range
to all orders withineffective price range
in orderbook.
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/bybit-exchange/pybit/blob/master/pybit/_http_manager.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:
- Testnet: wss://stream-testnet.bybit.com/realtime
- Mainnet (both endpoints are available):
- wss://stream.bybit.com/realtime
- wss://stream.bytick.com/realtime
Authentication examples are shown in the code block.
How to Send Heartbeat Packet
How to Send
ws.send('{"op":"ping"}');
Response Example
{
"success": true, // Whether ping is successful
"ret_msg": "pong",
"conn_id": "036e5d21-804c-4447-a92d-b65a44d00700",// current connection id
"request": {
"op": "ping",
"args": null
}
}
How to Subscribe to Topics
Understanding Websocket Filters
How to subscribe with a filter
// Subscribing to the trade data for BTCUSD
ws.send('{"op":"subscribe","args":["trade.BTCUSD"]}')
How to subscribe with multiple filters
// Example: Subscribing to the trade data for BTCUSD and XRPUSD
ws.send('{"op":"subscribe","args":["trade.BTCUSD|XRPUSD"]}')
How to subscribe without filters
// Example: Subscribing to the trade data for all symbols
ws.send('{"op": "subscribe", "args": ["trade.*"]}')
After establishing the connection, one can subscribe to a new topic by sending a JSON request. The specific formats are as follows:
ws.send('{"op": "subscribe", "args": ["topic.filter"]}');
The topic
indicates the data you would like to receive whilst the filter
parses for the specific data you desire - for example, the symbol. The topic
is mandatory but the filter
is optional.
To subscribe to more than one topic, simply list multiple topics out, like so:
ws.send('{"op": "subscribe", "args": ["topic.filter", "topic.filter"]}');
It is possible to use multiple filters for the same topic by splitting them with a pipe (|
) - of course, these filters must all be applicable to the selected topic
.
Finally, to subscribe to the topic without filters please use the *
wildcard.
Unsubscribing From Websocket Topics
How to unsubscribe with a filter
// Unsubscribing from the trade data for ETHUSD
ws.send('{"op":"unsubscribe","args":["trade.ETHUSD"]}')
You can dynamically subscribe and unsubscribe from topics (with or without filters) without websocket disconnection as follows:
ws.send('{"op": "unsubscribe", "args": ["topic.filter", "topic.filter"]}');
Intervals
Some topics are pushed at intervals. If the args
contain a millisecond param, such as 100ms
, this topic is pushed at intervals. Otherwise, it is pushed constantly.
Understanding Subscription Response
Subscription Response
{
"success": true, // Whether subscription is successful
"ret_msg": "", // Successful subscription: "", otherwise it shows error message
"conn_id":"e0e10eee-4eff-4d21-881e-a0c55c25e2da",// current connection id
"request": { // Request to your subscription
"op": "subscribe",
"args": [
"kline.BTCUSD.1m"
]
}
}
Each subscription will have a response. You can determine whether the subscription is successful based on the response.
Public Topics
orderBookL2_25
How to Subscribe
ws.send('{"op": "subscribe", "args": ["orderBookL2_25.BTCUSD"]}');
from time import sleep
from pybit import inverse_perpetual
ws_inverseP = inverse_perpetual.WebSocket(
test=True,
ping_interval=30, # the default is 30
ping_timeout=10, # the default is 10
domain="bybit" # the default is "bybit"
)
def handle_message(msg):
print(msg)
# To subscribe to multiple symbols,
# pass a list: ["BTCUSD", "ETHUSD"]
ws_inverseP.orderbook_25_stream(
handle_message, "XRPUSD"
)
while True:
sleep(1)
Snapshot Response Example - format of the first response
{
"topic": "orderBookL2_25.BTCUSD",
"type": "snapshot",
"data": [
{
"price": "2999.00",
"symbol": "BTCUSD",
"id": 29990000, // depreciated
"side": "Buy",
"size": 9
},
{
"price": "3001.00",
"symbol": "BTCUSD",
"id": 30010000, // depreciated
"side": "Sell",
"size": 10
}
],
"cross_seq": 11518,
"timestamp_e6": 1555647164875373
}
Delta Response Example - format of the responses following the snapshot response
{
"topic": "orderBookL2_25.BTCUSD",
"type": "delta",
"data": {
"delete": [
{
"price": "3001.00",
"symbol": "BTCUSD",
"id": 30010000, // depreciated
"side": "Sell"
}
],
"update": [
{
"price": "2999.00",
"symbol": "BTCUSD",
"id": 29990000, // depreciated
"side": "Buy",
"size": 8
}
],
"insert": [
{
"price": "2998.00",
"symbol": "BTCUSD",
"id": 29980000, // depreciated
"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.
Push frequency: 20ms
Response Parameters
Parameter | Type | Comment |
---|---|---|
price | string | Order price |
symbol | string | Symbol |
side | string | Side |
size | number | Position qty |
orderBookL2_200
How to Subscribe
ws.send('{"op": "subscribe", "args": ["orderBook_200.100ms.BTCUSD"]}');
from time import sleep
from pybit import inverse_perpetual
ws_inverseP = inverse_perpetual.WebSocket(
test=True,
ping_interval=30, # the default is 30
ping_timeout=10, # the default is 10
domain="bybit" # the default is "bybit"
)
def handle_message(msg):
print(msg)
# To subscribe to multiple symbols,
# pass a list: ["BTCUSD", "ETHUSD"]
ws_inverseP.orderbook_200_stream(
handle_message, "XRPUSD"
)
while True:
sleep(1)
Snapshot Response Example - format of the first response
{
"topic": "orderBook_200.100ms.BTCUSD",
"type": "snapshot",
"data": [
{
"price": "2999.00",
"symbol": "BTCUSD",
"id": 29990000, // depreciated
"side": "Buy",
"size": 9
},
{
"price": "3001.00",
"symbol": "BTCUSD",
"id": 30010000, // depreciated
"side": "Sell",
"size": 10
}
],
"cross_seq": 11518,
"timestamp_e6": 1555647164875373
}
Delta Response Example - format of the responses following the snapshot response
{
"topic": "orderBook_200.100ms.BTCUSD",
"type": "delta",
"data": {
"delete": [
{
"price": "3001.00",
"symbol": "BTCUSD",
"id": 30010000, // depreciated
"side": "Sell"
}
],
"update": [
{
"price": "2999.00",
"symbol": "BTCUSD",
"id": 29990000, // depreciated
"side": "Buy",
"size": 8
}
],
"insert": [
{
"price": "2998.00",
"symbol": "BTCUSD",
"id": 29980000, // depreciated
"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.
Push frequency: 100ms
Response Parameters
Parameter | Type | Comment |
---|---|---|
price | string | Order price |
symbol | string | Symbol |
side | string | Side |
size | number | Position qty |
trade
How to Subscribe
ws.send('{"op": "subscribe", "args": ["trade"]}')
from time import sleep
from pybit import inverse_perpetual
ws_inverseP = inverse_perpetual.WebSocket(
test=True,
ping_interval=30, # the default is 30
ping_timeout=10, # the default is 10
domain="bybit" # the default is "bybit"
)
def handle_message(msg):
print(msg)
# To subscribe to multiple symbols,
# pass a list: ["BTCUSD", "ETHUSD"]
ws_inverseP.trade_stream(
handle_message, "ETHUSD"
)
while True:
sleep(1)
Response Example - format of all responses
{
"topic": "trade.BTCUSD",
"data": [
{
"timestamp": "2020-01-12T16:59:59.000Z",
"trade_time_ms": 1582793344685,
"symbol": "BTCUSD",
"side": "Sell",
"size": 328,
"price": 8098,
"tick_direction": "MinusTick",
"trade_id": "00c706e1-ba52-5bb0-98d0-bf694bdc69f7",
"cross_seq": 1052816407
}
]
}
Push frequency: 100ms
Response Parameters
Parameter | Type | Comment |
---|---|---|
timestamp | string | UTC time |
trade_time_ms | number | Millisecond timestamp |
symbol | string | Symbol |
side | string | Direction of taker |
size | number | Position qty |
price | number | Order price |
tick_direction | string | Direction of price change |
trade_id | string | Trade ID |
cross_seq | number | Cross sequence (internal value) |
insurance
How to Subscribe
ws.send('{"op": "subscribe", "args": ["insurance"]}')
from time import sleep
from pybit import inverse_perpetual
ws_inverseP = inverse_perpetual.WebSocket(
test=True,
ping_interval=30, # the default is 30
ping_timeout=10, # the default is 10
domain="bybit" # the default is "bybit"
)
def handle_message(msg):
print(msg)
# To subscribe to multiple symbols,
# pass a list: ["BTC", "ETH"]
ws_inverseP.insurance_stream(
handle_message, "BTC"
)
while True:
sleep(1)
Response Example - format of all responses
{
"topic": "insurance.BTC",
"data": [
{
"currency": "BTC",
"timestamp": "2020-01-11T20:00:00Z",
"wallet_balance": 98786916569
}
]
}
Get the daily insurance fund update.
Push frequency: 20:00 UTC / day
Response Parameters
Parameter | Type | Comment |
---|---|---|
currency | string | Currency type |
timestamp | string | UTC time |
wallet_balance | number | Wallet balance |
instrumentInfo
How to Subscribe
ws.send('{"op": "subscribe", "args": ["instrument_info.100ms.BTCUSD"]}')
from time import sleep
from pybit import inverse_perpetual
ws_inverseP = inverse_perpetual.WebSocket(
test=True,
ping_interval=30, # the default is 30
ping_timeout=10, # the default is 10
domain="bybit" # the default is "bybit"
)
def handle_message(msg):
print(msg)
# To subscribe to multiple symbols,
# pass a list: ["BTCUSD", "ETHUSD"]
ws_inverseP.instrument_info_stream(
handle_message, "DOTUSD"
)
while True:
sleep(1)
Snapshot Response Example - format of the first response
{
"topic":"instrument_info.100ms.BTCUSD",
"type":"snapshot",
"data": {
"id": 1,
"symbol": "BTCUSD",
"last_price_e4": 81165000,
"last_price": "81165000",
"bid1_price_e4":400025000,
"bid1_price":"400025000",
"ask1_price_e4":475450000,
"ask1_price":"475450000",
"last_tick_direction": "ZeroPlusTick",
"prev_price_24h_e4": 81585000,
"prev_price_24h": "81585000",
"price_24h_pcnt_e6": -5148,
"high_price_24h_e4": 82900000,
"high_price_24h": "82900000",
"low_price_24h_e4": 79655000,
"low_price_24h": "79655000",
"prev_price_1h_e4": 81395000,
"prev_price_1h": "81395000",
"price_1h_pcnt_e6": -2825,
"mark_price_e4": 81178500,
"mark_price": "81178500",
"index_price_e4": 81172800,
"index_price": "81172800",
"open_interest": 154418471,
"open_value_e8": 1997561103030,
"total_turnover_e8": 2029370141961401,
"turnover_24h_e8": 9072939873591,
"total_volume": 175654418740,
"volume_24h": 735865248,
"funding_rate_e6": 100,
"predicted_funding_rate_e6": 100,
"cross_seq": 1053192577,
"created_at": "2018-11-14T16:33:26Z",
"updated_at": "2020-01-12T18:25:16Z",
"next_funding_time": "2020-01-13T00:00:00Z",
"countdown_hour": 6,
"funding_rate_interval": 8
},
"cross_seq":9267002,
"timestamp_e6":1615794861826248
}
Delta Response Example - format of the responses following the snapshot response
{
"topic": "instrument_info.100ms.BTCUSD",
"type": "delta",
"data": {
"delete": [],
"update": [
{
"id": 1,
"symbol": "BTCUSD",
"prev_price_24h_e4": 81565000,
"prev_price_24h": "81565000",
"price_24h_pcnt_e6": -4904,
"open_value_e8": 2000479681106,
"total_turnover_e8": 2029370495672976,
"turnover_24h_e8": 9066215468687,
"volume_24h": 735316391,
"cross_seq": 1053192657,
"created_at": "2018-11-14T16:33:26Z",
"updated_at": "2020-01-12T18:25:25Z"
}
],
"insert": []
},
"cross_seq": 1053192657,
"timestamp_e6": 1578853525691123
}
Get latest information for symbol.
Push frequency: 100ms
Response Parameters
Parameter | Type | Comment |
---|---|---|
symbol | string | Symbol |
last_price_e4 | integer | (Deprecated) Latest transaction price 10^4 |
last_price | integer | Latest transaction price |
bid1_price_e4 | integer | (Deprecated) Best bid price * 10^4 |
bid1_price | string | Best bid price |
ask1_price_e4 | integer | (Deprecated) Best ask price * 10^4 |
ask1_price | string | Best ask price |
last_tick_direction | string | Direction of price change |
prev_price_24h_e4 | integer | (Deprecated) Price of 24 hours ago * 10^4 |
prev_price_24h | string | Price of 24 hours ago |
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 |
high_price_24h | string | The highest price in the last 24 hours |
low_price_24h_e4 | integer | (Deprecated) Lowest price in the last 24 hours * 10^4 |
low_price_24h | string | Lowest price in the last 24 hours |
prev_price_1h_e4 | integer | (Deprecated) Hourly market price an hour ago * 10^4 |
prev_price_1h | string | Hourly market price an hour ago |
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 |
mark_price | string | Mark price |
index_price_e4 | integer | (Deprecated) Index_price * 10^4 |
index_price | string | Index_price |
open_interest | integer | Open interest. The update is not immediate - slowest update is 1 minute |
open_value_e8 | integer | Open position value * 10^8. The update is not immediate - slowest update is 1 minute |
total_turnover_e8 | integer | Total turnover * 10^8 |
turnover_24h_e8 | integer | Turnover for 24h * 10^8 |
total_volume | integer | Total volume |
volume_24h | integer | Trading volume in the last 24 hours |
predicted_funding_rate_e6 | integer | Predicted funding rate * 10^6 |
cross_seq | integer | Cross sequence (internal value) |
created_at | string | Creation time (when the order_status was Created ) |
updated_at | string | Update time |
next_funding_time | string | Next settlement time of capital cost |
countdown_hour | integer | Countdown of settlement capital cost |
funding_rate_interval | integer | funding rate time interval, unit hour |
klineV2
How to Subscribe
ws.send('{"op":"subscribe","args":["klineV2.1.BTCUSD"]}')
from time import sleep
from pybit import inverse_perpetual
ws_inverseP = inverse_perpetual.WebSocket(
test=True,
ping_interval=30, # the default is 30
ping_timeout=10, # the default is 10
domain="bybit" # the default is "bybit"
)
def handle_message(msg):
print(msg)
# To subscribe to multiple symbols,
# pass a list: ["BTCUSD", "ETHUSD"]
# pass an inverval
ws_inverseP.kline_stream(
handle_message, "ETHUSD", "D"
)
while True:
sleep(1)
Response Example - format of all responses
{
"topic": "klineV2.1.BTCUSD",
"data": [{
"start": 1572425640,
"end": 1572425700,
"open": 9200,
"close": 9202.5,
"high": 9202.5,
"low": 9196,
"volume": 81790,
"turnover": 8.889247899999999,
"confirm": false,
"cross_seq": 297503466,
"timestamp": 1572425676958323
}],
"timestamp_e6": 1572425677047994
}
Currently supported intervals:
- 1 3 5 15 30
- 60 120 240 360 720
- D
- W
- M
Push frequency: 1-60s
Response Parameters
Parameter | Type | Comment |
---|---|---|
start | integer | Start timestamp point for result, in seconds |
end | integer | End timestamp point for result, in seconds |
open | number | Starting price |
close | number | Closing price |
high | number | Maximum price |
low | number | Minimum price |
volume | number | Trading volume |
turnover | number | Turnover |
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"]}')
from time import sleep
from pybit import inverse_perpetual
ws_inverseP = inverse_perpetual.WebSocket(
test=True,
ping_interval=30, # the default is 30
ping_timeout=10, # the default is 10
domain="bybit" # the default is "bybit"
)
def handle_message(msg):
print(msg)
# To subscribe to multiple symbols,
# pass a list: ["BTCUSD", "ETHUSD"]
ws_inverseP.liquidation_stream(
handle_message, "ETHUSD"
)
while True:
sleep(1)
Response Example - format of all responses
{
"topic":"liquidation.ETHUSD",
"data": {
"symbol":"ETHUSD",
"side":"Sell",
"price":"3384.15",
"qty":"3655",
"time":1631608881954
}
}
Pushes liquidation orders.
Push frequency: real-time
Response Parameters
Parameter | Type | Comment |
---|---|---|
symbol | string | Symbol |
side | string | Liquidated position's side |
price | string | Bankruptcy price |
qty | string | Order quantity in USD |
time | number | Millisecond timestamp |
Private Topics
position
How to Subscribe
ws.send('{"op": "subscribe", "args": ["position"]}')
from time import sleep
from pybit import inverse_perpetual
ws_inverseP = inverse_perpetual.WebSocket(
test=True,
api_key="your api key",
api_secret="your api secret",
ping_interval=30, # the default is 30
ping_timeout=10, # the default is 10
domain="bybit" # the default is "bybit"
)
def handle_message(msg):
print(msg)
ws_inverseP.position_stream(
handle_message
)
while True:
sleep(1)
Response Example - format of all responses
{
"topic": "position",
"data": [
{
"user_id": 533285,
"symbol": "BTCUSD",
"size": 200,
"side": "Buy",
"position_value": "0.0099975",
"entry_price": "20005.00125031",
"liq_price": "489",
"bust_price": "489",
"leverage": "5",
"order_margin": "0",
"position_margin": "0.39929535",
"available_balance": "0.39753405",
"take_profit": "0",
"stop_loss": "0",
"realised_pnl": "0.00055631",
"trailing_stop": "0",
"trailing_active": "0",
"wallet_balance": "0.40053971",
"risk_id": 1,
"occ_closing_fee": "0.0002454",
"occ_funding_fee": "0",
"auto_add_margin": 1,
"cum_realised_pnl": "0.00055105",
"position_status": "Normal",
"position_seq": 0,
"Isolated": false,
"mode": 0,
"position_idx": 0,
"tp_sl_mode": "Partial",
"tp_order_num": 0,
"sl_order_num": 0,
"tp_free_size_x": 200,
"sl_free_size_x": 200
}
]
}
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 the user. In Cross Margin mode, the value is the max leverage at current risk level |
order_margin | string | Pre-occupied order margin |
position_margin | string | Position margin |
available_balance | string | Available balance = wallet balance - used margin |
take_profit | string | Take profit price |
stop_loss | string | Stop loss price |
realised_pnl | string | Today's realised pnl |
trailing_stop | string | Trailing stop (the distance from the current price) |
trailing_active | string | Trailing stop active price |
wallet_balance | string | Wallet balance |
risk_id | number | Risk ID |
occ_closing_fee | string | Position closing fee occupied (your opening fee + expected maximum closing fee) |
occ_funding_fee | string | Pre-occupied funding fee: calculated from position qty and current funding fee |
auto_add_margin | number | Whether or not auto-margin replenishment is enabled |
cum_realised_pnl | string | Accumulated realised pnl (all-time total) |
position_status | string | Position status: Normal , Liq , Adl
|
position_seq | number | Position sequence |
Isolated | bool | true means isolated margin mode; false means cross margin mode |
mode | number | Position mode |
position_idx | number | 0-One-Way Mode, 1-Buy side of both side mode, 2-Sell side of both side mode (Perpetual) |
tp_sl_mode | string | TrailingProfit or StopLoss mode Full or Partial |
tp_order_num | number | The qty of take profit orders |
sl_order_num | number | The qty of stop loss orders |
tp_free_size_x | number | The available size to set take profit |
sl_free_size_x | number | The available size to set stop loss |
execution
How to Subscribe
ws.send('{"op": "subscribe", "args": ["execution"]}')
from time import sleep
from pybit import inverse_perpetual
ws_inverseP = inverse_perpetual.WebSocket(
test=True,
api_key="your api key",
api_secret="your api secret",
ping_interval=30, # the default is 30
ping_timeout=10, # the default is 10
domain="bybit" # the default is "bybit"
)
def handle_message(msg):
print(msg)
ws_inverseP.execution_stream(
handle_message
)
while True:
sleep(1)
Response Example - format of all responses
{
"topic": "execution",
"data": [
{
"symbol": "BTCUSD",
"side": "Buy",
"order_id": "xxxxxxxx-xxxx-xxxx-9a8f-4a973eb5c418",
"exec_id": "xxxxxxxx-xxxx-xxxx-8b66-c3d2fcd352f6",
"order_link_id": "",
"price": "8300",
"order_qty": 1,
"exec_type": "Trade",
"exec_qty": 1,
"exec_fee": "0.00000009",
"leaves_qty": 0,
"is_maker": false,
"trade_time": "2020-01-14T14:07:23.629Z"
}
]
}
Get user's trading records. The results are ordered in ascending order (the first item is the oldest). If you want to get the records up to 2 years old, please refer to contract v3 endpoint
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 | Unique user-set order ID. Maximum length of 36 characters |
price | string | Transaction price |
order_qty | number | Order qty |
exec_type | string | Execution type (cannot be Funding ) |
exec_qty | number | Transaction qty |
exec_fee | string | Transaction fee |
leaves_qty | number | Number of unfilled contracts from the order's size |
is_maker | bool | Is maker |
trade_time | string | Transaction timestamp |
order
How to Subscribe
ws.send('{"op": "subscribe", "args": ["order"]}')
from time import sleep
from pybit import inverse_perpetual
ws_inverseP = inverse_perpetual.WebSocket(
test=True,
api_key="your api key",
api_secret="your api secret",
ping_interval=30, # the default is 30
ping_timeout=10, # the default is 10
domain="bybit" # the default is "bybit"
)
def handle_message(msg):
print(msg)
ws_inverseP.order_stream(
handle_message
)
while True:
sleep(1)
Response Example - format of all responses
{
"topic": "order",
"data": [
{
"order_id": "1640b725-75e9-407d-bea9-aae4fc666d33",
"order_link_id": "IPBTC00005",
"symbol": "BTCUSD",
"side": "Sell",
"order_type": "Market",
"price": "20564",
"qty": 200,
"time_in_force": "ImmediateOrCancel",
"create_type": "CreateByUser",
"cancel_type": "",
"order_status": "Filled",
"leaves_qty": 0,
"cum_exec_qty": 200,
"cum_exec_value": "0.00943552",
"cum_exec_fee": "0.00000567",
"timestamp": "2022-06-21T07:35:56.505Z",
"take_profit": "18500",
"tp_trigger_by": "LastPrice",
"stop_loss": "22000",
"sl_trigger_by": "LastPrice",
"trailing_stop": "0",
"last_exec_price": "21196.5",
"reduce_only": false,
"close_on_trigger": false
}
]
}
Response Parameters
Parameter | Type | Comment |
---|---|---|
order_id | string | Order ID |
order_link_id | string | Unique user-set order ID. Maximum length of 36 characters |
symbol | string | Symbol |
side | string | Side |
order_type | string | Conditional order type |
price | string | Order price |
qty | number | Transaction qty |
time_in_force | string | Time in force |
create_type | string | Trigger scenario for single action |
cancel_type | string | Trigger scenario for cancel operation |
order_status | string | Order status |
leaves_qty | number | Number of unfilled contracts from the order's size |
cum_exec_qty | number | Cumulative qty of trading |
cum_exec_value | string | Cumulative value of trading |
cum_exec_fee | string | Cumulative trading fees |
timestamp | string | Timestamp (when the order_status was New ) |
take_profit | string | Take profit price |
tp_trigger_by | string | Take profit trigger price type |
stop_loss | string | Stop loss price |
sl_trigger_by | string | Stop loss trigger price type |
trailing_stop | string | Trailing stop (the distance from the current price) |
last_exec_price | string | Last execution price |
reduce_only | bool | What is a reduce-only order? True means your position can only reduce in size if this order is triggered |
close_on_trigger | bool | What is a close on trigger order? For a closing order. It can only reduce your position, not increase it. If the account has insufficient available balance when the closing order is triggered, then other active orders of similar contracts will be cancelled or reduced. It can be used to ensure your stop loss reduces your position regardless of current available margin. |
stop_order
How to Subscribe
ws.send('{"op": "subscribe", "args": ["stop_order"]}')
from time import sleep
from pybit import inverse_perpetual
ws_inverseP = inverse_perpetual.WebSocket(
test=True,
api_key="your api key",
api_secret="your api secret",
ping_interval=30, # the default is 30
ping_timeout=10, # the default is 10
domain="bybit" # the default is "bybit"
)
def handle_message(msg):
print(msg)
ws_inverseP.stop_order_stream(
handle_message
)
while True:
sleep(1)
Response Example - format of all responses
{
"topic": "stop_order",
"data": [
{
"order_id": "xxxxxxxx-xxxx-xxxx-98fb-335aaa6c613b",
"order_link_id": "",
"user_id": 1,
"symbol": "BTCUSD",
"side": "Buy",
"order_type": "Limit",
"price": "8584.5",
"qty": 1,
"time_in_force": "ImmediateOrCancel",
"create_type": "CreateByStopOrder",
"cancel_type": "",
"order_status": "Untriggered",
"stop_order_type": "Stop",
"trigger_by": "LastPrice",
"trigger_price": "8584.5",
"close_on_trigger": false,
"timestamp": "2020-01-14T14:11:22.062Z",
"take_profit": 10000,
"stop_loss": 7500
}
]
}
Response Parameters
Parameter | Type | Comment |
---|---|---|
order_id | string | Order ID |
order_link_id | string | Unique user-set order ID. Maximum length of 36 characters |
user_id | number | UserID |
symbol | string | Symbol |
order_type | string | Order type |
side | string | Side |
price | string | Order price |
qty | number | Order quantity in USD |
time_in_force | string | Time in force |
create_type | string | Trigger scenario for single action |
cancel_type | string | Trigger scenario for cancel operation |
order_status | string | Order status |
stop_order_type | string | Conditional order type |
trigger_by | string | Trigger price type. Default LastPrice |
trigger_price | string | If stop_order_type is TrailingProfit , this field is the trailing stop active price. |
close_on_trigger | bool | What is a close on trigger order? For a closing order. It can only reduce your position, not increase it. If the account has insufficient available balance when the closing order is triggered, then other active orders of similar contracts will be cancelled or reduced. It can be used to ensure your stop loss reduces your position regardless of current available margin. |
timestamp | string | UTC time |
take_profit | string | Take profit price |
stop_loss | string | Stop loss price |
wallet
How to Subscribe
ws.send('{"op": "subscribe", "args": ["wallet"]}')
from time import sleep
from pybit import inverse_perpetual
ws_inverseP = inverse_perpetual.WebSocket(
test=True,
api_key="your api key",
api_secret="your api secret",
ping_interval=30, # the default is 30
ping_timeout=10, # the default is 10
domain="bybit" # the default is "bybit"
)
def handle_message(msg):
print(msg)
ws_inverseP.wallet_stream(
handle_message
)
while True:
sleep(1)
Response Example - format of all responses
{
"topic": "wallet",
"data": [
{
"user_id": 738713,
"coin": "BTC",
"available_balance": "1.50121026",
"wallet_balance": "1.50121261"
}
]
}
Response Parameters
Parameter | Type | Comment |
---|---|---|
user_id | number | User ID |
coin | string | Coin type |
wallet_balance | string | Wallet balance |
available_balance | string | In Isolated Margin Mode: available_balance = wallet_balance - (position_margin + occ_closing_fee + occ_funding_fee + order_margin) In Cross Margin Mode: if unrealised_pnl > 0: available_balance = wallet_balance - (position_margin + occ_closing_fee + occ_funding_fee + order_margin) if unrealised_pnl < 0: available_balance = wallet_balance - (position_margin + occ_closing_fee + occ_funding_fee + order_margin) + unrealised_pnl |
Archive Data
Historical Market Data
You can get Bybit's historical market data here.
Historical funding rates are not available through the API. However, you can obtain a CSV of this data by using the "Export" button here.
Enums Definitions
The following lists enumerator names for the request and response parameters of each endpoint.
Side (side
)
Buy
Sell
Symbol (symbol
)
BTCUSD
ETHUSD
EOSUSD
XRPUSD
DOTUSD
You can get all symbols with the Query Symbol endpoint.
Currency (currency
/coin
)
BTC
ETH
EOS
XRP
DOT
USDT
Contract Type(contract_type
)
InversePerpetual
LinearPerpetual
InverseFutures
Contract Status(status
)
Trading
Settling
Closed
Wallet fund type (wallet_fund_type
/ type
)
Deposit
Withdraw
RealisedPNL
Commission
Refund
Prize
ExchangeOrderWithdraw
ExchangeOrderDeposit
ReturnServiceCash
- Refund of handling fee bonusInsurance
- Insurance account transferSubMember
- Parent-child account transferCoupon
- Coupon interestAccountTransfer
- Account transferCashBack
- Cash back
Withdraw status (status
)
ToBeConfirmed
UnderReview
Pending
- Pending transferSuccess
CancelByUser
Reject
Expire
Order type (order_type
)
Limit
Market
Quantity (qty
)
- The maximum qty for an order (
max_trading_qty
) can be queried with the Query Symbol endpoint. - Must be a positive integer
- Must conform to the symbol's
qty_step
. For example, for the inverse perpetual BTCUSD market: 40
- allowed30.5
- not allowed
Price (price
)
- Active order
- Must be an integral multiple of
tick_size
- Information about current trading pair (e.g.
tick_size
) can be queried with the Query Symbol endpoint. - Modulo (
%
) can be used to calculate whether the price will be accepted:IF price % tick_size = 0 // send request ELSE // do not send request as the price will not be accepted by the system
- Information about current trading pair (e.g.
- Must be less than the symbol's
max_price
- If the user has no open position, the order price must be higher than 10% of the last traded price
- For example, if the last traded price (last price) is
10314
, the min. order price will be1031.5
. - Pseudocode (assuming the price is a multiple of 0.5):
IF price > (last_price * 0.1) // send request ELSE // do not send request as the price will not be accepted by the system
- For example, if the last traded price (last price) is
- If the user has an open position, the order price must be better than the liquidation price.
- For example, if the liquidation price of a long position is
5176.5
, the min. order price will be5177
. For short position, the order price must be less than the liquidation price.
- For example, if the liquidation price of a long position is
- Must be an integral multiple of
- Conditional order
- Must be greater than or equal to
1
- Must be greater than or equal to
Time in force (time_in_force
)
GoodTillCancel
ImmediateOrCancel
FillOrKill
PostOnly
Trigger price type (trigger_by
)
LastPrice
IndexPrice
MarkPrice
Order (order
)
This is used for sorting orders/trades in a specified direction.
desc
asc
Order status (order_status
/stop_order_status
)
Created
- order has been accepted by the system but not yet put through the matching engineNew
- order has been placed successfullyRejected
PartiallyFilled
Filled
PendingCancel
- matching engine has received the cancelation request but it may not be canceled successfullyCancelled
Only for conditional orders:
Untriggered
- order yet to be triggeredDeactivated
- order has been canceled by the user before being triggeredTriggered
- order has been triggered by last traded priceActive
- order has been triggered and the new active order has been successfully placed. Is the final state of a successful conditional order
Cancel type (cancel_type
)
CancelByUser
CancelByReduceOnly
CancelByPrepareLiq
,CancelAllBeforeLiq
- canceled due to liquidationCancelByPrepareAdl
,CancelAllBeforeAdl
- canceled due to ADLCancelByAdmin
CancelByTpSlTsClear
- TP/SL order canceled successfullyCancelByPzSideCh
- order has been canceled after TP/SL is triggered
Create type (create_type
)
CreateByUser
CreateByClosing
CreateByAdminClosing
CreateByStopOrder
CreateByTakeProfit
CreateByStopLoss
CreateByPartialTakeProfit
CreateByPartialStopLoss
CreateByTrailingStop
CreateByLiq
- Created by partial liquidationCreateByAdl_PassThrough
- Created by ADLCreateByTakeOver_PassThrough
- Created by liquidation takeover
Exec type (exec_type
)
Trade
AdlTrade
Funding
BustTrade
Settle
Liquidity type (last_liquidity_ind
)
AddedLiquidity
- liquidity makerRemovedLiquidity
- liquidity Taker
Tick direction type (tick_direction
)
It indicates price fluctuation relative to the last trade.
PlusTick
- price riseZeroPlusTick
- trade occurs at the same price as the previous trade, which occurred at a price higher than that for the trade preceding itMinusTick
- price dropZeroMinusTick
- trade occurs at the same price as the previous trade, which occurred at a price lower than that for the trade preceding it
TP/SL mode (tp_sl_mode
)
Take profit/stop loss mode
Full
- Full take profit/stop loss mode (a single TP order and a single SL order can be placed, covering the entire position)Partial
- Partial take profit/stop loss mode (multiple TP and SL orders can be placed, covering portions of the position)
Kline interval (interval
)
1
- 1 minute3
- 3 minutes5
- 5 minutes15
- 15 minutes30
- 30 minutes60
- 1 hour120
- 2 hours240
- 4 hours360
- 6 hours720
- 12 hoursD
- 1 dayW
- 1 weekM
- 1 month
Date (start_date
/end_date
)
Follows the format: yyyy-mm-dd
Stop order type (stop_order_type
)
TakeProfit
StopLoss
TrailingStop
Stop
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 (refer to the IP rate limit) |
404 | Request path not found |
10000
An unknown error occurred while processing the request.
10001
There was a problem with the value passed to the API. For example, if you pass a float, ensure it conforms to the tick_size
and qty_step
(ie, make sure it does not have too many decimals!).
10002
Request not authorized - an API key is required and should be included in all requests.
10003
Invalid api key
10004
Invalid sign
10005
Permission denied for current apikey. API key was created without the correct permissions (e.g. doesn´t have Order permission, or it's set to read-only)
10006
Too many visits. Refer to the API rate limit. Please use WebSocket for live updates. Current limit is %s requests per minute.
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
Exceeded IP rate limit.
10020
Request not supported.
10021
Timestamp for the request is outside of the recvWindow. The timestamp of this request is 1000 milliseconds ahead of the server time. Please check local time and server time.
10022
Invalid request signature.
11000
Parameter characters not supported.
11001
Too many parameters sent for this endpoint.
11002
Required parameter not sent. Parameter was empty/null or format was incorrect.
11003
Unknown parameter sent.
11004
Not all parameters sent were read.
11005
Empty parameter.
11006
Parameter was sent when no longer required.
11011
Order price exceeded upper limit.
11012
Trading pair does not exist.
11014
TimeInForce parameter sent when not required.
11015
Invalid timeInForce.
11016
Invalid orderType.
11017
Invalid direction.
11018
User-generated order ID was empty.
11019
User-generated order ID was empty.
11020
Invalid interval.
11021
Invalid symbol.
11025
listenKey does not exist.
11027
Query intervals too large.
11028
Invalid parameter combination.
11030
Invalid parameter sent.
11030
Invalid parameter sent.
11031
Insufficient balance.
11032
Order price exceeded upper limit.
11033
Order price exceeded lower limit.
11034
Order price has too many decimals.
11035
Order quantity exceeded upper limit.
11036
Order quantity exceeded lower limit.
11037
Order quantity has too many decimals.
11038
Order price exceeded limits.
11039
Order has been filled.
11040
Order value exceeded lower limit.
20001
Order does not exist.
20003
Missing parameter side
20004
Invalid parameter side
20005
Missing parameter symbol
20006
Invalid parameter symbol
20007
Missing parameter order_type
20008
Invalid parameter order_type
20009
Missing parameter qty
20010
New order rejected.
20011
Cancelation rejected.
20012
qty
must be greater than zero and less than 1 million
20013
Order does not exist.
20014
Invalid API key format.
20015
Invalid API key or IP.
20016
Trading window not open yet for current pair.
20017
Missing parameter order_id
20018
Invalid date format
20019
Missing parameter stop_px
20020
Missing parameter base_price
20021
Missing parameter stop_order_id
20022
Missing parameter leverage
20023
Leverage must be a number
20031
Leverage must be greater than zero
20070
Missing parameter margin
20071
margin
must be greater than zero
20084
order_id
or order_link_id
is required
20094
order_link_id
is not unique.
30003
qty
must be higher than the minimum allowed.
30004
qty
must be higher than the minimum allowed. The number of contracts exceeds maximum limit allowed. Order qty should be less than 1 million per order.
30005
Order price is out of permissible range.
30006
No last_price
.
30007
Order price is out of permissible range.
30008
Invalid order_type
.
30009
No position found.
30010
Insufficient wallet balance.
30011
Operation not allowed as position is undergoing liquidation
30012
Operation not allowed as position is undergoing ADL
30013
Position is in liq or adl status
30014
Invalid closing order, qty should not be greater than size.
30015
Invalid closing order, side should be the opposite.
30016
TP and SL must be cancelled before closing the position.
30017
Estimated fill price cannot be lower than current Buy liq_price.
30018
Estimated fill price cannot be higher than current Sell liq_price.
30019
Cannot attach TP/SL params for non-zero position when placing non-opening position order.
30020
Position already has TP/SL params.
30021
Cannot afford estimated position_margin.
30022
Estimated buy liq_price cannot be higher than current mark_price.
30023
Estimated sell liq_price cannot be lower than current mark_price.
30024
Cannot set TP/SL/TS for zero-position
30025
Trigger price should bigger than 10% of last price.
30026
Price is too high.
30027
Price set for Take profit should be higher than Last Traded Price.
30028
Price set for Stop Loss should be between Liquidation price and Last Traded Price.
30029
Price set for Stop Loss should be between Last Traded Price and Liquidation Price.
30030
Price set for Take Profit should be lower than Last Traded Price.
30031
Insufficient available balance for order cost.
30032
Order has been filled or cancelled.
30033
The number of stop orders exceeds maximum limit allowed.
30034
No stop order found.
30035
Too fast to cancel, try it later.
30036
The expected position value after order execution exceeds the current risk limit
30037
Order already cancelled
30038
No mark_price.
30039
Applied leverage has exceeded the permitted range.
30040
Any adjustments made will trigger immediate liquidation.
30041
No position found.
30042
Insufficient wallet balance.
30043
Operation not allowed as position is undergoing liquidation.
30044
Operation not allowed as position is undergoing ADL.
30045
Operation not allowed as position is not in normal status.
30046
There are multiple untriggered stop orders.
30047
Inconsistent p:o.
30048
Applied leverage has exceeded the permitted range.
30049
Insufficient available balance.
30050
Any adjustments made will trigger immediate liquidation!
30051
Due to risk limit, cannot adjust leverage.
30052
Leverage cannot be less than 1x.
30053
max_affordable_position_margin <= 0, position:%s
30054
fixed_new_position_margin is invalid.
30055
Available Balance is not enough to add margin.
30056
The position is in cross_margin.
30057
Requested quantity of contracts exceeds risk limit, please adjust your risk limit level before trying again.
30063
Reduce-only rule not satisfied
30066
Set auto add margin fail.
30067
Insufficient available balance.
30068
Exit value must be positive.
30074
Can't create the stop order, because you expect the order will be triggered when the LastPrice
(or IndexPrice
, MarkPrice
, determined by trigger_by
) is raising to stop_px
, but the LastPrice
(or IndexPrice
, MarkPrice
) is already equal to or greater than stop_px
, please adjust base_price
or stop_px
30075
Can't create the stop order, because you expect the order will be triggered when the LastPrice
(or IndexPrice
, MarkPrice
, determined by trigger_by
) is falling to stop_px
, but the LastPrice
(or IndexPrice
, MarkPrice
) is already equal to or less than stop_px
, please adjust base_price
or stop_px
30076
Replace params invalid. Order not modified.
30077
Submission of order will result in the breach of user's limit according to open interest.
30078
Contracts not in trading status
30079
The position is about to trigger a liquidation
30080
Price cannot be lower than current Buy liq_price
30081
Price cannot be greater than current sell liq_price
30082
Position exists No switching of position mode allowed
30083
No change in position pattern
30084
No changes to the full position-by-position model
30085
Margin unchanged
30086
With a commissioned order, switching position mode is not allowed
30087
Symbol does not support two-way open positions
30088
Symbol does not exist
30089
Duplicate order number
30090
Risk limit info does not exist
30091
Illegal orders (meaning that the order os|cs is not legal in various scenarios)
30092
No position is not allowed to set margin
30093
No net position
30094
Withdrawal of an order before a liquidation is not concluded
30095
Full positions are not allowed to modify leverage
31003
User account banned
32006
The available balance is not sufficient to cover the handling fee.
32008
Insufficient available margin.
32009
Any adjustments made will trigger immediate liquidation.
32010
Risk limit cannot be adjusted due to insufficient available margin.
32011
Risk limit cannot be adjusted as the current/expected position value held exceeds the revised risk limit.
33004
apikey already expired
34010
Wallet Balance is less than zero.
34015
Cannot set new leverage as it is equal to the previous leverage.
34017
Current leverage is less than 1X
34018
Cannot set leverage lower than 1X
34019
Cannot set leverage greater than maxLeverage.
34020
Cannot set leverage which is same to the previous leverage.
34021
Cannot cancel occ_calc_data, the data is wrong.
34022
Cannot set leverage which will cause available balance less than 0.
34023
The request was canceled because the origin request has been handled.
34024
The request does not include add margin data.
34025
Increase in leverage has failed.
34026
The new limit is equal to the old limit (no change).
34027
Cannot adjust leverage.
32009
Any adjustments made will trigger immediate liquidation.
34028
ReCalc Funding Fee Failed.
34030
positionInfo not sync with current exec_rpt.
34033
Realized PNL already rotated.
34032
PositionSeq not match on Withdraw.
34035
Add margin not modified.
34036
Set leverage not modified.
34037
Set custom fee rate not modified.
34038
Update deleverage indicator not modified.
34039
Update position status not modified.
34040
Set TP/SL/TS not modified.
35014
37001
Both side positions tp_sl_mode is equal.
37002
Same tp_sl_mode.
37003
This position has at least one stop-link order and cannot switch between stop-loss and take-profit modes.
37004
This position has at least one stop-loss link order and cannot switch between stop-loss and take-profit modes
37005
This position has at least one trailing stop or trailing stop link order and cannot be switched to take profit and stop loss mode
37006
Conditional or limit orders carry a take profit and stop loss parameter
37007
Insufficient number of positions left to set Stop Loss and Take Profit
37008
Active orders are not allowed to modify the price and quantity when they also modify the trigger price
37009
Activity orders are not allowed to modify the stop-loss and take-profit settings if the order is partially filled
37010
In Full Take Profit Stop Loss mode, it is not allowed to modify the Stop Profit Stop Loss size
37011
In partial SL mode, SL is set to more than 20. Set SL/TP exceeds the limit oldTpNum+oldStNum+newNum=(2 the num is tp+sl)
37012
Stop loss price needs to be greater than base price.
37013
Stop loss price needs to be less than base price.
38101
Replacement of order will result in the breach of user's limit according to open interest.
130001
position_idx invalid; check your position mode
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
130137
Please check to see if your existing position and open orders (together, your pz_value
) will exceed your risk limit (risk_limit
). You can change your risk limit with the Set Risk limit endpoint.
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.
Abandoned Endpoints
Liquidated Orders
Request Example
curl https://api-testnet.bybit.com/v2/public/liq-records?symbol=BTCUSD
Response Example
{
"ret_code":0,
"ret_msg":"OK",
"ext_code":"",
"ext_info":"",
"result":[
{
"id":2369683,
"qty":155,
"side":"Buy",
"time":1590030126798,
"symbol":"BTCUSD",
"price":9444
}
],
"time_now":"1590068362.493540"
}
Retrieve the liquidated orders, The query range is the last seven days of data.
HTTP Request
GET
/v2/public/liq-records
Request Parameters
parameter | Required | Type | Comment |
---|---|---|---|
symbol | true | string | Symbol |
from | false | integer | From ID. Default: return latest data |
limit | false | integer | Limit for data size, max size is 1000. Default size is 500 |
start_time | false | integer | Start timestamp point for result, in milliseconds |
end_time | false | integer | End timestamp point for result, in milliseconds |
Response Parameters
Parameter | Type | Comment |
---|---|---|
id | number | Latest data ID |
qty | number | Order quantity in USD |
side | string | Liquidated position's side |
time | number | Millisecond timestamp |
symbol | string | Symbol |
price | number | Execution price |
User Leverage
Request Example
curl "https://api-testnet.bybit.com/user/leverage?api_key={api_key}×tamp={timestamp}&sign={sign}"
Response Example
{
"ret_code": 0,
"ret_msg": "ok",
"ext_code": "",
"result": {
"BTCUSD": {
"leverage": 5
},
"EOSUSD": {
"leverage": 1
},
"ETHUSD": {
"leverage": 1
},
"XRPUSD": {
"leverage": 10
}
},
"ext_info": null,
"time_now": "1577477752.346548",
"rate_limit_status": 119,
"rate_limit_reset_ms": 1577477752355,
"rate_limit": 120
}
Get user leverage.
HTTP Request
GET
/user/leverage
Request Parameters
Parameter | Required | Type | Comment |
---|
Response Parameters
Parameter | Type | Comment |
---|---|---|
BTCUSD > leverage | number | BTCUSD leverage |
EOSUSD > leverage | number | EOSUSD leverage |
ETHUSD > leverage | number | ETHUSD leverage |
XRPUSD > leverage | number | XRPUSD leverage |
Get Active Order
Request Example
curl "https://api-testnet.bybit.com/open-api/order/list?api_key={api_key}×tamp={timestamp}&sign={sign}&symbol=BTCUSD"
Response Example
{
"ret_code": 0,
"ret_msg": "ok",
"ext_code": "",
"result": {
"current_page": 1,
"last_page": 6,
"data": [
{
"user_id": 1,
"symbol": "BTCUSD",
"side": "Sell",
"order_type": "Market",
"price": 7074,
"qty": 2,
"time_in_force": "ImmediateOrCancel",
"order_status": "Filled",
"ext_fields": {
"close_on_trigger": true,
"orig_order_type": "BLimit",
"prior_x_req_price": 5898.5,
"op_from": "pc",
"remark": "127.0.0.1",
"o_req_num": -34799032763,
"xreq_type": "x_create"
},
"last_exec_time": "1577448481.696421",
"last_exec_price": 7070.5,
"leaves_qty": 0,
"leaves_value": 0,
"cum_exec_qty": 2,
"cum_exec_value": 0.00028283,
"cum_exec_fee": 0.00002,
"reject_reason": "NoError",
"order_link_id": "",
"created_at": "2019-12-27T12:08:01.000Z",
"updated_at": "2019-12-27T12:08:01.000Z",
"order_id": "f185806b-b801-40ff-adec-52289370ed62"
}
]
},
"ext_info": null,
"time_now": "1577448922.437871",
"rate_limit_status": 98,
"rate_limit_reset_ms": 1580885703683,
"rate_limit": 100
}
Get my active order list.
Because order creation/cancellation is asynchronous, there can be a data delay in this endpoint. You can get real-time order info with the Query Active Order (real-time) endpoint.
HTTP Request
GET
/open-api/order/list
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
order_id | false | string | Order ID |
order_link_id | false | string | Unique user-set order ID. Maximum length of 36 characters |
symbol | false | string | Symbol. Default BTCUSD |
order | false | string | Sort orders by creation date. Defaults to asc |
page | false | integer | Page. By default, gets first page of data. |
limit | false | integer | Limit for data size per page, max size is 50. Default as showing 20 pieces of data per page |
order_status | false | string | Queries orders of all statuses if order_status not provided. If you want to query orders with specific statuses, you can pass the order_status split by ',' (eg Filled,New ). |
Response Parameters
Parameter | Type | Comment |
---|---|---|
user_id | number | UserID |
symbol | string | Symbol |
side | string | Side |
order_type | string | Order type |
price | number | Order price |
qty | number | Order quantity in USD |
time_in_force | string | Time in force |
order_status | string | Order status |
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. |
orig_order_type | string | Original special order type |
prior_x_req_price | number | Expected match price |
op_from | string | Source of the request |
remark | string | Remark |
o_req_num | number | Used to correlate request & response |
xreq_type | string | Request type |
last_exec_time | string | Last execution time |
last_exec_price | number | Last execution price |
leaves_qty | number | Number of unfilled contracts from the order's size |
leaves_value | number | The estimated value corresponding to the number of remaining orders |
cum_exec_qty | number | Cumulative qty of trading |
cum_exec_value | number | Cumulative value of trading |
cum_exec_fee | number | Cumulative trading fees |
reject_reason | string | The reason the order was rejected |
order_link_id | string | Unique user-set order ID. Maximum length of 36 characters |
created_at | string | Creation time (when the order_status was Created ) |
order_id | string | Order ID |
Get Conditional Order
Request Example
curl "https://api-testnet.bybit.com/open-api/stop-order/list?api_key={api_key}×tamp={timestamp}&sign={sign}"
Response Example
{
"ret_code": 0,
"ret_msg": "ok",
"ext_code": "",
"result": {
"current_page": 1,
"last_page": 1,
"data": [
{
"user_id": 1,
"stop_order_status": "Untriggered",
"symbol": "BTCUSD",
"side": "Buy",
"order_type": "Limit",
"price": 8000,
"qty": 1,
"time_in_force": "GoodTillCancel",
"stop_order_type": "Stop",
"trigger_by": "LastPrice",
"base_price": 7000,
"order_link_id": "",
"created_at": "2019-12-27T12:48:24.000Z",
"updated_at": "2019-12-27T12:48:24.000Z",
"stop_px": 7500,
"stop_order_id": "a85cd1c0-a9a4-49d3-a1bd-bab5ebe946d5"
},
{
"user_id": 1,
"stop_order_status": "Untriggered",
"symbol": "BTCUSD",
"side": "Sell",
"order_type": "Limit",
"price": 999999,
"qty": 1,
"time_in_force": "PostOnly",
"stop_order_type": "Stop",
"trigger_by": "LastPrice",
"base_price": 6910.5,
"order_link_id": "",
"created_at": "2019-12-17T12:13:20.000Z",
"updated_at": "2019-12-17T12:13:20.000Z",
"stop_px": 10000000000000,
"stop_order_id": "dea89649-9492-459d-a8c4-c298b87b3d26"
}
]
},
"ext_info": null,
"time_now": "1577451658.755468",
"rate_limit_status": 599,
"rate_limit_reset_ms": 1577451658762,
"rate_limit": 600
}
Get my conditional order list.
Because order creation/cancellation is asynchronous, there can be a data delay in this endpoint. You can get real-time order info with the Query Conditional Order (real-time) endpoint.
HTTP Request
GET
/open-api/stop-order/list
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
stop_order_id | false | string | Conditional order ID. Once triggered, the conditional order creates an active order with the same ID (order_id ) |
order_link_id | false | string | Unique user-set order ID. Maximum length of 36 characters |
symbol | false | string | Symbol. Default BTCUSD |
order_status | false | string | Stop order status |
order | false | string | Sort orders by creation date. Defaults to asc |
page | false | integer | Page. By default, gets first page of data. |
limit | false | integer | Limit for data size per page, max size is 50. Default as showing 20 pieces of data per page |
Response Parameters
Parameter | Type | Comment |
---|---|---|
user_id | number | UserID |
order_status | string | Stop order status |
symbol | string | Symbol |
side | string | Side |
order_type | string | Active order type |
price | number | Order price |
qty | number | Order quantity in USD |
time_in_force | string | Time in force |
stop_order_type | string | Conditional order type |
trigger_by | string | Trigger price type. Default LastPrice |
base_price | number | Market price at placing order |
order_link_id | string | Unique user-set order ID. Maximum length of 36 characters |
created_at | string | Creation time (when the order_status was Created ) |
updated_at | string | Update time |
stop_px | number | Trigger price. If you're expecting the price to rise to trigger your conditional order, make sure stop_px > max(market price, base_price) else, stop_px < min(market price, base_price) |
stop_order_id | string | Conditional order ID. Once triggered, the conditional order creates an active order with the same ID (order_id ) |
Place Conditional Order
Request Example
curl https://api-testnet.bybit.com/open-api/stop-order/create \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","order_type":"Limit","side":"Buy","symbol":"BTCUSD","qty":1,"price":8100,"base_price":8300,"stop_px":8150,"time_in_force":"GoodTillCancel","order_link_id":"cus_order_id_1","timestamp":{timestamp},"sign":"{sign}"}'
Response Example
{
"ret_code": 0,
"ret_msg": "ok",
"ext_code": "",
"result": {
"user_id": 1,
"symbol": "BTCUSD",
"side": "Buy",
"order_type": "Limit",
"price": 8000,
"qty": 1,
"time_in_force": "GoodTillCancel",
"stop_order_type": "Stop",
"trigger_by": "LastPrice",
"base_price": 7000,
"order_status": "Untriggered",
"ext_fields": {
"stop_order_type": "Stop",
"trigger_by": "LastPrice",
"base_price": 7000,
"expected_direction": "Rising",
"trigger_price": 7500,
"op_from": "api",
"remark": "127.0.01",
"o_req_num": 0
},
"leaves_qty": 1,
"leaves_value": 0.00013333,
"reject_reason": null,
"cross_seq": -1,
"created_at": "2019-12-27T12:48:24.000Z",
"updated_at": "2019-12-27T12:48:24.000Z",
"stop_px": 7500,
"stop_order_id": "a85cd1c0-a9a4-49d3-a1bd-bab5ebe946d5"
},
"ext_info": null,
"time_now": "1577450904.327654",
"rate_limit_status": 99,
"rate_limit_reset_ms": 1577450904335,
"rate_limit": "100"
}
Market price conditional order: A traditional market price order, will be filled at the best available price. price
is not required for this type of order.
Limit price conditional order: You can set an execution price for your order. Only when the last traded price reaches the order price will the system will fill your order.
Take profit/Stop loss: You may only set a take-profit/stop-loss conditional order upon opening the position. Once you hold a position, the take profit and stop loss information you sent when placing an order will no longer be valid.
Order quantity: This parameter indicates the quantity of perpetual contracts you want to buy or sell, currently Bybit only support order quantity in an integer.
Order price: If it is a stop order, this parameter is required. When there is no position, the price should be higher than 10% of market price and less than 1 million. For the minimum unit of price movement, 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
/open-api/stop-order/create
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
side | true | string | Side |
symbol | true | string | Symbol |
order_type | true | string | Conditional order type |
qty | true | integer | Order quantity in USD |
price | false | number | Execution price for conditional order. Required if you make limit price order |
base_price | true | number | It will be used to compare with the value of stop_px , to decide whether your conditional order will be triggered by crossing trigger price from upper side or lower side. Mainly used to identify the expected direction of the current conditional order. |
stop_px | true | number | Trigger price. If you're expecting the price to rise to trigger your conditional order, make sure stop_px > max(market price, base_price) else, stop_px < min(market price, base_price) |
time_in_force | true | string | Time in force |
trigger_by | false | string | Trigger price type. Default LastPrice |
close_on_trigger | false | bool | What is a close on trigger order? For a closing order. It can only reduce your position, not increase it. If the account has insufficient available balance when the closing order is triggered, then other active orders of similar contracts will be cancelled or reduced. It can be used to ensure your stop loss reduces your position regardless of current available margin. |
order_link_id | false | string | Unique user-set order ID. Maximum length of 36 characters |
Response Parameters
Parameter | Type | Comment |
---|---|---|
user_id | number | UserID |
symbol | string | Symbol |
side | string | Side |
order_type | string | Active order type |
price | number | Order price |
qty | number | Order quantity in USD |
time_in_force | string | Time in force |
stop_order_type | string | Conditional order type |
trigger_by | string | Trigger price type. Default LastPrice |
base_price | number | Market price at placing order |
order_status | string | Order status |
stop_order_type | string | Conditional order type |
expected_direction | string | Expected direction |
trigger_by | number | If stop_order_type is TrailingProfit , this field is the trailing stop active price. |
op_from | string | Source of the request |
remark | string | Remark |
o_req_num | number | Used to correlate request & response |
leaves_qty | number | Number of unfilled contracts from the order's size |
leaves_value | number | The estimated value corresponding to the number of remaining orders |
reject_reason | string | The reason the order was rejected |
cross_seq | number | Cross sequence (internal value) |
created_at | string | Creation time (when the order_status was Created ) |
updated_at | string | Update time |
stop_px | number | Trigger price. If you're expecting the price to rise to trigger your conditional order, make sure stop_px > max(market price, base_price) else, stop_px < min(market price, base_price) |
stop_order_id | string | Conditional order ID. Once triggered, the conditional order creates an active order with the same ID (order_id ) |
Cancel Conditional Order
Request Example
curl https://api-testnet.bybit.com/open-api/stop-order/cancel \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","symbol":"BTCUSD","order_id":"","timestamp":{timestamp},"sign":"{sign}"}'
Response Example
{
"ret_code": 0,
"ret_msg": "ok",
"ext_code": "",
"result": {
"user_id": 1,
"stop_order_status": "Untriggered",
"symbol": "BTCUSD",
"side": "Buy",
"order_type": "Limit",
"price": 8000,
"qty": 1,
"time_in_force": "GoodTillCancel",
"stop_order_type": "Stop",
"trigger_by": "LastPrice",
"base_price": 7000,
"order_link_id": "",
"created_at": "2019-12-27T13:10:18.000Z",
"updated_at": "2019-12-27T13:10:18.000Z",
"stop_px": 7500,
"stop_order_id": "c1025629-e85b-4c26-b4f3-76e86ad9f8cb"
},
"ext_info": null,
"time_now": "1577452218.567120",
"rate_limit_status": 97,
"rate_limit_reset_ms": 1577452218573,
"rate_limit": "100"
}
You may cancel all untriggered conditional orders or take profit/stop loss order. Essentially, after a conditional order is triggered, it will become an active order. So, when a conditional order is triggered, cancellation has to be done through the active order endpoint for any unfilled or partially filled active order. As always, orders that have been fully filled cannot be cancelled.
HTTP Request
POST
/open-api/stop-order/cancel
Request Parameters
Parameter | required | type | comments |
---|---|---|---|
symbol | true | string | Symbol |
stop_order_id | false | string | Order ID |
order_link_id | false | string | Unique user-set order ID. Required if not passing stop_order_id |
Response Parameters
Parameter | Type | Comment |
---|---|---|
user_id | number | UserID |
order_status | string | Stop order status |
symbol | string | Symbol |
side | string | Side |
order_type | string | Active order type |
price | number | Order price |
qty | number | Order quantity in USD |
time_in_force | string | Time in force |
stop_order_type | string | Conditional order type |
trigger_by | string | Trigger price type. Default LastPrice |
base_price | number | Market price at placing order |
order_link_id | string | Unique user-set order ID. Maximum length of 36 characters |
created_at | string | Creation time (when the order_status was Created ) |
updated_at | string | Update time |
stop_px | number | Trigger price. If you're expecting the price to rise to trigger your conditional order, make sure stop_px > max(market price, base_price) else, stop_px < min(market price, base_price) |
stop_order_id | string | Conditional order ID. Once triggered, the conditional order creates an active order with the same ID (order_id ) |
Replace Conditional Order
Request Example
curl https://api-testnet.bybit.com/open-api/stop-order/replace \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","symbol":"BTCUSD","stop_order_id":"","timestamp":{timestamp},"sign":"{sign}"}'
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.
HTTP Request
POST
/open-api/stop-order/replace
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
stop_order_id | false | string | Conditional order ID. Once triggered, the conditional order creates an active order with the same ID (order_id ) |
order_id | false | string | Abandoned!! Conditional order ID. Once triggered, the conditional order creates an active order with the same ID (order_id ) |
order_link_id | false | string | Unique user-set order ID. Maximum length of 36 characters |
symbol | true | string | Symbol. |
p_r_qty | false | int | New order quantity. Do not pass this field if you don't want modify it |
p_r_price | false | number | New order price. Do not pass this field if you don't want modify it |
p_r_trigger_price | false | number | New conditional order's trigger price or TP/SL order price, also known as stop_px. Do not pass this field if you don't want modify it |
Response Parameters
Parameter | Type | Comment |
---|---|---|
stop_order_id | string | Conditional order ID. Once triggered, the conditional order creates an active order with the same ID (order_id ) |
Replace Active Order
Request Example
curl https://api-testnet.bybit.com/open-api/order/replace \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","symbol":"BTCUSD","order_id":"","timestamp":{timestamp},"sign":"{sign}"}'
Response Example
{
"ret_code": 0,
"ret_msg": "ok",
"ext_code": "",
"result": {
"order_id": "efa44157-c355-4a98-b6d6-1d846a936b93"
},
"time_now": "1539778407.210858",
"rate_limit_status": 99,
"rate_limit_reset_ms": 1580885703683,
"rate_limit": 100
}
Replace order can modify/amend your active orders.
HTTP Request
POST
/open-api/order/replace
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
order_id | false | string | Order ID |
order_link_id | false | string | Unique user-set order ID. Maximum length of 36 characters |
symbol | true | string | Symbol. |
p_r_qty | false | int | New order quantity. Do not pass this field if you don't want modify it |
p_r_price | false | number | New order price. Do not pass this field if you don't want modify it |
Response Parameters
Parameter | Type | Comment |
---|---|---|
order_id | string | Order ID |
Get risk limit
Request Example
curl "https://api-testnet.bybit.com/open-api/wallet/risk-limit/list?api_key={api_key}×tamp={timestamp}&sign={sign}"
Response Example
{
"ret_code": 0,
"ret_msg": "ok",
"ext_code": "",
"result": [
{
"id": 1,
"coin": "BTC",
"symbol": "BTCUSD",
"limit": 150,
"maintain_margin": "0.50",
"starting_margin": "1.00",
"section": [
"1",
"2",
"3",
"5",
"10",
"25",
"50",
"100"
],
"is_lowest_risk": 1,
"created_at": "2018-09-21T11:34:11.000Z",
"updated_at": "2018-09-21T11:34:11.000Z",
"max_leverage": "100.00"
},
{
"id": 10,
"coin": "BTC",
"symbol": "BTCUSD",
"limit": 1500,
"maintain_margin": "5.00",
"starting_margin": "5.50",
"section": [
"1",
"2",
"3",
"4",
"5",
"10",
"15",
"18"
],
"is_lowest_risk": 0,
"created_at": "2018-09-21T11:34:11.000Z",
"updated_at": "2018-09-21T11:34:11.000Z",
"max_leverage": "18.18"
}
],
"ext_info": null,
"time_now": "1616568086.769014",
"rate_limit_status": 599,
"rate_limit_reset_ms": 1616568086777,
"rate_limit": 600
}
Get risk limit. This endpoint does not require authentication.
HTTP Request
GET
/open-api/wallet/risk-limit/list
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
symbol | false | string | Symbol |
Response Parameters
Parameter | Type | Comment |
---|---|---|
id | number | Risk ID |
coin | string | Coin type |
symbol | string | Symbol |
limit | number | Risk limit |
maintain_margin | string | Maintain margin |
starting_margin | string | Starting margin. The same as the "Initial Margin %" shown in the risk limit tables |
section | string | Section |
is_lowest_risk | number | Is lowest risk. 0 : No; 1 : Yes
|
created_at | string | Creation time (when the order_status was Created ) |
updated_at | string | Update time |
max_leverage | string | Max leverage |
Set Risk Limit
Request Example
curl https://api-testnet.bybit.com/open-api/wallet/risk-limit \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","symbol":"BTCUSD","risk_id":2,"timestamp":{timestamp},"sign":"{sign}"}'
Response Example
{
"ret_code": 0,
"ret_msg": "ok",
"ext_code": "",
"result": {
"position": {
"id": 1,
"user_id": 1,
"symbol": "BTCUSD",
"side": "None",
"size": 0,
"position_value": 0,
"entry_price": 0,
"risk_id": 2,
"auto_add_margin": 0,
"leverage": 1,
"position_margin": 0,
"liq_price": 0,
"bust_price": 0,
"occ_closing_fee": 0,
"occ_funding_fee": 0,
"take_profit": 0,
"stop_loss": 0,
"trailing_stop": 0,
"position_status": "Normal",
"deleverage_indicator": 0,
"oc_calc_data": "{\"blq\":1,\"blv\":\"0.000125\",\"slq\":0,\"bmp\":8000,\"smp\":0,\"fc\":-0.00012529,\"bv2c\":1.00225,\"sv2c\":1.0007575}",
"order_margin": 0.00012529,
"wallet_balance": 1000,
"realised_pnl": 0,
"cum_realised_pnl": 0,
"cum_commission": 0,
"cross_seq": 4376,
"position_seq": 13689,
"created_at": "2019-08-13T06:51:29.000Z",
"updated_at": "2019-12-29T03:11:08.000Z",
"ext_fields": {
"trailing_active": "9000",
"v": 4
}
},
"risk": {
"id": 2,
"coin": "BTC",
"limit": 300,
"maintain_margin": "1.00",
"starting_margin": "1.50",
"section": "[\"1\",\"2\",\"3\",\"5\",\"10\",\"25\",\"50\",\"66\"]",
"is_lowest_risk": 0,
"created_at": "2019-06-26T05:46:45.000Z",
"updated_at": "2019-06-26T05:46:55.000Z"
}
},
"ext_info": null,
"time_now": "1577589068.435439",
"rate_limit_status": 71,
"rate_limit_reset_ms": 1577589068546,
"rate_limit": 75
}
Set risk limit.
HTTP Request
POST
/open-api/wallet/risk-limit
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
symbol | true | string | Symbol |
risk_id | true | integer | Risk ID |
Response Parameters
Parameter | Type | Comment |
---|---|---|
id | number | PositionID |
user_id | number | UserID |
symbol | string | Symbol |
side | string | Side |
size | number | Position qty |
position_value | number | Position value |
entry_price | number | Average entry price |
risk_id | number | Risk ID |
auto_add_margin | number | Whether or not auto-margin replenishment is enabled |
leverage | number | In Isolated Margin mode, the value is set by the user. In Cross Margin mode, the value is the max leverage at current risk level |
position_margin | number | Position margin |
liq_price | number | Liquidation price |
bust_price | number | Bankruptcy price |
occ_closing_fee | number | Position closing fee occupied (your opening fee + expected maximum closing fee) |
occ_funding_fee | number | Pre-occupied funding fee: calculated from position qty and current funding fee |
take_profit | number | Take profit price |
stop_loss | number | Stop loss price |
trailing_stop | number | Trailing stop (the distance from the current price) |
position_status | string | Position status: Normal , Liq , Adl
|
deleverage_indicator | number | Deleverage indicator level (1,2,3,4,5) |
oc_calc_data | string | Pre-occupied calculate parameters. blq : total number of the long side unsettled orders; bmp : the lowest price of the long side; slq : total number of the short side unsettled orders; smp : the lowest price of the short side
|
order_margin | number | Pre-occupied order margin |
wallet_balance | number | Wallet balance |
realised_pnl | number | Today's realised pnl |
cum_realised_pnl | number | Accumulated realised pnl (all-time total) |
cum_commission | number | Accumulated commission |
cross_seq | number | Cross sequence (internal value) |
position_seq | number | Position sequence |
created_at | string | Creation time (when the order_status was Created ) |
updated_at | string | Update time |
trailing_active | string | Trailing stop active price |
risk>id | number | Risk ID |
risk>coin | string | Coin type |
risk>limit | number | Risk limit |
risk>maintain_margin | string | Maintain margin |
risk>starting_margin | string | Starting margin. The same as the "Initial Margin %" shown in the risk limit tables |
risk>section | string | Section |
risk>is_lowest_risk | number | Is lowest risk. 0 : No; 1 : Yes
|
risk>created_at | string | Creation time (when the order_status was Created ) |
risk>updated_at | string | Update time |