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
- Get Risk Limit [update]
- Deprecated
created_at
andupdated_at
. Now returns an empty string.
- Deprecated
2022-09-13
REST API
- Get Open Interest Limit Info [new]
- Add new api to query open interest limit information
2022-09-07
REST API
- Public Trading Records [update]
- Add new response field
is_block_trade
- Add new response field
WebSocket API
- trade [update]
- Add new response field
is_block_trade
- Add new response field
2022-08-25
WebSocket API
- stop_order [update]
- Add
take_profit
andstop_order
fields
- Add
2022-07-18
REST API
- Latest Information for Symbol [update]
- Abandon response field
total_turnover
.
- Abandon response field
WebSocket API
- Latest Information for Symbol [update]
- Abandon response field
total_turnover_e8
.
- Abandon response field
2022-06-30
REST API
- Extended User Trade Records [update]
- Add
page_token
field in response parameters.
- 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-04-28
REST API
- Extended User Trade Records [new]
- Get user's trading records over the last two years (rolling).
- Position Mode Switch [update]
- Support
coin
level switching between One-Way Mode and Hedge Mode.
- Support
2021
2021-12-28
REST API
- Position Mode Switch [new]
- Place Active Order [update]
- Add parameter
position_idx
to Request Parameters and Response Parameters
- Add parameter
- Place Conditional Order [update]
- Add parameter
position_idx
to Request Parameters and Response Parameters
- Add parameter
- Set Auto Add Margin [update]
- Add parameter
position_idx
to Request Parameters
- Add parameter
- Set Trading-Stop [update]
- Add parameter
position_idx
to Request Parameters
- Add parameter
- Add/Reduce Margin [update]
- Add parameter
position_idx
to Request Parameters
- Add parameter
- Set Risk Limit [update]
- Add parameter
position_idx
to Request Parameters
- Add parameter
- My Position [update]
- Add parameter
position_idx
to Response Parameters
- Add parameter
WebSocket API
- position [update]
- Add parameter
position_idx
to Response Parameters
- Add parameter
- order [update]
- Add parameter
position_idx
to Response Parameters
- Add parameter
- stop_order [update]
- Add parameter
position_idx
to Response Parameters
- Add parameter
2021-10-13
REST API
- Query Symbol [update]
- Fix
price_scale
response of Query Symbol Endpoint for USDT perpetual symbols.
- Fix
2021-09-17
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!
2021-09-10
REST API
- Get User Trade Records [update]
- Limit
start_time
andend_time
to be within seven days of the current date. For earlier records, please contact customer support.
- Limit
2021-09-07
REST API
- Closed Profit and Loss [update]
- Fix issue with the Price Accuracy of
avg_entry_price
,order_price
,avg_exit_price
for XLMUSDT and TRXUSDT.
- Fix issue with the Price Accuracy of
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-06-29
REST API
- Add new USDT perpetual symbols: MATICUSDT, EOSUSDT, ETCUSDT, BNBUSDT, FILUSDT, SOLUSDT [update]
2021-06-28
REST API
- My Position [update]
- Add fields of
take_profit
,stop_loss
,trailing_stop
in response
- Add fields of
2021-06-02
REST API
- Add new USDT perpetual symbol: DOGEUSDT [update]
2021-05-13
REST API
- Add new USDT perpetual symbols: XRPUSDT, XEMUSDT, SUSHIUSDT, AAVEUSDT [update]
2021-04-30
REST API
- Testnet Add new USDT perpetual symbols: XRPUSDT, XEMUSDT, SUSHIUSDT, AAVEUSDT [update]
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,130145
2021-03-18
REST API
- Add new USDT perpetual symbols: ADAUSDT, DOTUSDT, UNIUSDT [update]
- Get Risk Limit [update]
- Query risk limit return field added maximum leverage
max_leverage
- Query risk limit return field added maximum leverage
2021-02-02
WebSocket API
- Topic order [update]
- Add fields
reduce_only
,close_on_trigger
- Add fields
- Topic stop_order [update]
- Add fields
reduce_only
,close_on_trigger
- Add fields
2021-02-01
REST API
- Upgrade Tiered Margin to Risk Limit, add below endpoint:
- Set Risk Limit [new]
2021-01-12
REST API
- Query Index Price Kline [new]
- Query Premium Index Kline [new]
2020
2020-12-14
REST API
- Add new USDT perpetual symbols: BCHUSDT [update]
2020-12-03
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
- My Position [update]
- Add field
deleverage_indicator
andunrealised_pnl
- Add field
- Place Conditional Order [update]
- Add field
close_on_trigger
- Add field
- Get Active Order [update]
- Add field
close_on_trigger
- Add field
- Query Active Order (real-time) [update]
- Add field
close_on_trigger
- Add field
- Place Conditional Order [update]
- Add field
close_on_trigger
andreduce_only
- Add field
- Get Conditional Order [update]
- Add field
close_on_trigger
andreduce_only
- Add field
- Query Conditional Order (real-time) [update]
- Add field
close_on_trigger
andreduce_only
- Add field
2020-11-16
REST API
- My Position [update]
- Add field
is_isolated
andauto_add_margin
in response
- Add field
- Place Conditional Order [update]
- Add field
base_price
andtrigger_by
in response
- Add field
- Get Conditional Order [update]
- Add field
base_price
andtrigger_by
in response
- Add field
- Query Conditional Order (real-time) [update]
- Add field
base_price
andtrigger_by
in response
- Add field
2020-11-02
REST API
- My Position [update]
- Request parameter
symbol
is optional now; If symbol is not passed, return positions of all symbols
- Request parameter
2020-10-21
REST API
- Add new USDT perpetual symbols: ETHUSDT, LINKUSDT, LTCUSDT, XTZUSDT [update]
- Get Wallet Balance [update]
- Fix bug of
given_cash
andservice_cash
are always Zero when coin isUSDT
- Fix bug of
2020-10-16
REST API
2020-09-27
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 response parameters:
take_profit
,stop_loss
,tp_trigger_by
,sl_trigger_by
- Add response 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:
WebSocket API
- Add new websocket base endpoint [update]
2020-09-15
REST API
- Long-Short Ratio [update]
- Fix Account Long-short ratio data error
- Conditional Orders [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-17
REST API
- Replace Active Order [new]
- Replace Conditional Order [new]
2020-05-21
REST API
- Liquidated Orders [new]
2020-05-18
REST API
- Get Active Order [update]
order_status
query orders with specific statuses by passing eachorder_status
split by ','.
- Get Conditional Order [update]
order_status
query orders with specific statuses by passing eachorder_status
split by ','.
- Query Kline [update]
- Add new fields in response:
interval
,open_time
- Abandon response fields:
period
,start_at
- Add new fields in response:
2020-04-29
REST API
- API Key Info [bugfix]
- Fix bug of always returning Zero for
inviter_id
under certain conditions
- Fix bug of always returning Zero for
WebSocket API
- kline [new]
2020-04-27
REST API
- Latest Information for Symbol [update]
- Return symbol
BTCUSDT
by default
- Return symbol
2020-04-18
REST API
- Get User Trade Records [update]
- Add new fields in response, like
exec_price
,exec_value
- Add new fields in response, like
- Fix permission denied issue of below endpoints under
readonly
model:
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
- Public Trading Records [update]
- Add new response param
trade_time_ms
- Update support millisecond
start_time
- Abandon response field
trade_time
- Add new response param
- Query Mark Price Kline [new]
- Predicted Funding Rate and My Funding Fee [new]
2020-04-14
REST API
- My Last Funding Fee [new]
- Set Auto Add Margin [new]
- Set Trading-Stop [new]
- Add/Reduce Margin [new]
- Get User Trade Records [new]
- Closed Profit and Loss [new]
- Get Risk Limit [new]
2020-04-09
REST API
- Conditional Orders [new]
2020-04-07
REST API
- Set Leverage [new]
- Cross/Isolated Margin Switch [new]
- Query Kline [new]
- Public Trading Records [new]
- Get the Last Funding Rate [new]
- Place Active Order [update]
- Add field
reduce_only
in response - Fix value of
order_type
in response
- Add field
- Get Active Order [update]
- Add field
reduce_only
in response- Fix value of
order_type
in response
- Fix value of
- Add field
- Query Active Order (real-time) [update]
- Add field
reduce_only
in response - Fix value of
order_type
in response
- Add field
- My Position [update]
- Add field
free_qty
in response
- Add field
2020-03-31
REST API
- Query Active Order (real-time) [new]
- Get Active Order
order_status
field not support query orders with specific statuses
WebSocket API
- wallet [new]
- trade [new]
- orderBookL2_25 [update]
- orderBookL2_200 [update]
- fix response data bug
2020-03-27
REST API
- Place Active Order [new]
- My Position [new]
WebSocket API
- orderBookL2_25 [new]
- orderBookL2_200 [new]
- instrumentInfo [new]
- position [new]
- execution [new]
- order [new]
- stop_order [new]
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=XXXXXXXXXXX&buy_leverage=100&sell_leverage=110&symbol=BTCUSDT×tamp=1542434791747"
param_str = "api_key=XXXXXXXXXXX&buy_leverage=100&sell_leverage=110&symbol=BTCUSD×tamp=1542434791747"
# api_key=XXXXXXXXXXX&
# leverage=100&
# symbol=BTCUSD&
# timestamp=1542434791747
Note how the parameters are ordered in alphabetical order, with api_key first followed by leverage, then symbol, then timestamp.
1. Concatenate all the public parameters in the query string format. The parameters must be ordered in alphabetical order. This will be used to generate the sign
.
2. Use the HMAC_SHA256 algorithm to sign the query string in step 1, and convert it to a hex string to obtain the sign parameter.
Different requests need different message formats. Message format for GET requests:
GET /user/leverage?api_key=XXXXXXXXXXX×tamp=1542434791000&sign=670e3e4aa32b243f2dedf1dafcec2fd17a440e71b05681550416507de591d908 HTTP/1.1
Host: api-testnet.bybit.com
Message format for POST requests:
POST /user/leverage/save HTTP/1.1
Host: api-testnet.bybit.com
Content-Type: application/json
{
"api_key": "XXXXXXXXXXX",
"leverage": 100,
"symbol": "BTCUSD",
"timestamp": 1542434791000,
"sign": "670e3e4aa32b243f2dedf1dafcec2fd17a440e71b05681550416507de591d908"
}
3. Append the sign parameter to the end of the parameters string, and send the HTTP request. Note that the message format for GET and POST requests is different. Please refer to the examples.
Market Data Endpoints
The following market data endpoints do not require authentication.
Order Book
Please see the shared endpoint.
Query Kline
Request Example
curl https://api-testnet.bybit.com/public/linear/kline?symbol=BTCUSDT&interval=1&limit=2&from=1581231260
from pybit import usdt_perpetual
session_unauth = usdt_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com"
)
print(session_unauth.query_kline(
symbol="BTCUSDT",
interval=1,
limit=2,
from_time=1581231260
))
Response Example
{
"ret_code": 0,
"ret_msg": "OK",
"ext_code": "",
"ext_info": "",
"result": [
{
"id": 3866948,
"symbol": "BTCUSDT",
"period": "1",
"start_at": 1577836800,
"volume": 1451.59,
"open": 7700,
"high": 999999,
"low": 0.5,
"close": 6000,
"interval": "1",
"open_time": 1577836800,
"turnover": 2.4343353100000003,
}],
"time_now": "1581928016.558522"
}
Get kline.
For mark price klines, see the Mark Price Kline endpoint.
HTTP Request
GET
/public/linear/kline
Request Parameters
parameter | Required | Type | Comment |
---|---|---|---|
symbol | true | string | Symbol |
interval | true | string | Data refresh interval. Enum : 1 3 5 15 30 60 120 240 360 720 "D" "M" "W" |
from | true | integer | From timestamp in seconds |
limit | false | integer | Limit for data size, max size is 200. Default as showing 200 pieces of data |
Response Parameters
Parameter | Type | Comment |
---|---|---|
symbol | string | Symbol |
period | string | Data recording period. 5min , 15min , 30min , 1h , 4h , 1d |
interval | string | Data recording period. 5min , 15min , 30min , 1h , 4h , 1d |
start_at | integer | Start timestamp point for result, in seconds |
open_time | integer | Starting time |
volume | number | Trading volume |
open | integer | Starting price |
high | integer | Maximum price |
low | number | Minimum price |
close | integer | Closing price |
turnover | number | Turnover |
Latest Information for Symbol
Please see the shared endpoint.
Public Trading Records
Request Example
curl https://api-testnet.bybit.com/public/linear/recent-trading-records?symbol=BTCUSDT&limit=500
from pybit import usdt_perpetual
session_unauth = usdt_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com"
)
print(session_unauth.public_trading_records(
symbol="BTCUSDT",
limit=500
))
Response Example
{
"ret_code": 0,
"ret_msg": "OK",
"ext_code": "",
"ext_info": "",
"result": [
{
"id": "18368131384",
"symbol": "BTCUSDT",
"price": 9499.5,
"qty": 9500,
"side": "Buy",
"time": "2019-11-19T08:03:04.077Z",
"trade_time_ms":1587638305175,
"is_block_trade": false
}
],
"time_now": "1567109419.049271"
}
Get recent trades. You can find a complete history of trades on Bybit here.
HTTP Request
GET
/public/linear/recent-trading-records
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
symbol | true | string | Symbol |
limit | false | int | Number of results. Default 500; max 1000 |
Response Parameters
Parameter | Type | Comment |
---|---|---|
id | string | Latest data ID |
symbol | string | Symbol |
price | number | Execution price |
qty | number | Order quantity in cryptocurrency |
side | string | Side of taker order |
time | string | UTC time |
trade_time_ms | number | Millisecond timestamp |
is_block_trade | boolean | Is block trade |
Query Symbol
Please see the shared endpoint.
Liquidated Orders
Please see the shared endpoint.
Get the Last Funding Rate
Request Example
curl https://api-testnet.bybit.com/public/linear/funding/prev-funding-rate?symbol=BTCUSDT
from pybit import usdt_perpetual
session_unauth = usdt_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com"
)
print(session_unauth.get_the_last_funding_rate(
symbol="BTCUSDT"
))
Response Example
{
"ret_code":0,
"ret_msg":"OK",
"ext_code":"",
"ext_info":"",
"result":{
"symbol":"BTCUSDT",
"funding_rate":-0.00005965,
"funding_rate_timestamp":"2020-04-07T08:00:00.000Z"
},
"time_now":"1586251109.454281"
}
The funding rate is generated every 8 hours at 00:00 UTC, 08:00 UTC and 16:00 UTC. For example, if a request is sent at 12:00 UTC, the funding rate generated earlier that day at 08:00 UTC will be sent.
HTTP Request
GET
/public/linear/funding/prev-funding-rate
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
symbol | true | string | Symbol |
Response Parameters
Parameter | Type | Comment |
---|---|---|
symbol | string | Symbol |
funding_rate | number | Funding rate |
funding_rate_timestamp | string | Funding rate timestamp |
Query Mark Price Kline
Request Example
curl https://api-testnet.bybit.com/public/linear/mark-price-kline?symbol=BTCUSDT&interval=1&limit=2&from=1581231260
from pybit import usdt_perpetual
session_unauth = usdt_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com"
)
print(session_unauth.query_mark_price_kline(
symbol="BTCUSDT",
interval=1,
limit=2,
from_time=1581231260
))
Response Example
{
"ret_code": 0,
"ret_msg": "OK",
"ext_code": "",
"ext_info": "",
"result": [{
"id": 3866948,
"symbol": "BTCUSDT",
"period": "1",
"start_at": 1577836800,
"open": 7700,
"high": 999999,
"low": 0.5,
"close": 6000
},
{
"id": 3866948,
"symbol": "BTCUSDT",
"period": "1",
"start_at": 1577836800,
"open": 7700,
"high": 999999,
"low": 0.5,
"close": 6000
}],
"time_now": "1581928016.558522"
}
Query mark price kline (like Query Kline but for mark price).
HTTP Request
GET
/public/linear/mark-price-kline
Request Parameters
parameter | Required | Type | Comment |
---|---|---|---|
symbol | true | string | Symbol |
interval | true | string | Data refresh interval. Enum : 1 3 5 15 30 60 120 240 360 720 "D" "M" "W" |
from | true | integer | From timestamp in seconds |
limit | false | integer | Limit for data size, max size is 200. Default as showing 200 pieces of data |
Response Parameters
Parameter | Type | Comment |
---|---|---|
symbol | string | Symbol |
period | string | Data recording period. 5min , 15min , 30min , 1h , 4h , 1d |
start_at | integer | Start timestamp point for result, in seconds |
open | integer | Starting price |
high | integer | Maximum price |
low | number | Minimum price |
close | integer | Closing price |
Query Index Price Kline
Request Example
curl "https://api-testnet.bybit.com/public/linear/index-price-kline?symbol=BTCUSDT&interval=1&limit=2&from=1581231260"
from pybit import usdt_perpetual
session_unauth = usdt_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com"
)
print(session_unauth.query_index_price_kline(
symbol="BTCUSDT",
interval=1,
limit=2,
from_time=1581231260
))
Response Example
{
"ret_code":0,
"ret_msg":"OK",
"ext_code":"",
"ext_info":"",
"result":[{
"symbol":"BTCUSDT",
"period":"1",
"open_time":1582231260,
"open":"10106.09",
"high":"10108.75",
"low":"10104.66",
"close":"10108.73"
}],
"time_now":"1591263582.601795"
}
Index price kline. Tracks BTC spot prices, with a frequency of every second (learn more here).
HTTP Request
GET
/public/linear/index-price-kline
Request Parameters
parameter | Required | Type | Comment |
---|---|---|---|
symbol | true | string | Symbol |
interval | true | string | Data refresh interval. Enum : 1 3 5 15 30 60 120 240 360 720 "D" "M" "W" |
from | true | integer | From timestamp in seconds |
limit | false | integer | Limit for data size, max size is 200. Default as showing 200 pieces of data |
Response Parameters
Parameter | Type | Comment |
---|---|---|
symbol | string | Symbol |
period | string | Data recording period. 5min , 15min , 30min , 1h , 4h , 1d |
open_time | integer | Start timestamp point for result, in seconds |
open | string | Starting price |
high | string | Maximum price |
low | string | Minimum price |
close | string | Closing price |
Query Premium Index Kline
Request Example
curl "https://api-testnet.bybit.com/public/linear/premium-index-kline?symbol=BTCUSDT&interval=1&limit=2&from=1581231260"
from pybit import usdt_perpetual
session_unauth = usdt_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com"
)
print(session_unauth.query_premium_index_kline(
symbol="BTCUSDT",
interval=1,
limit=2,
from_time=1581231260
))
Response Example
{
"ret_code":0,
"ret_msg":"OK",
"ext_code":"",
"ext_info":"",
"result":[{
"symbol":"BTCUSDT",
"period":"1",
"open_time":1582231260,
"open":"0.000588",
"high":"0.000618",
"low":"0.000588",
"close":"0.000618"
}],
"time_now":"1591263582.601795"
}
Premium index kline. Tracks the premium / discount of BTC perpetual contracts relative to the mark price per minute (learn more here).
HTTP Request
GET
/public/linear/premium-index-kline
Request Parameters
parameter | Required | Type | Comment |
---|---|---|---|
symbol | true | string | Symbol |
interval | true | string | Data refresh interval. Enum : 1 3 5 15 30 60 120 240 360 720 "D" "M" "W" |
from | true | integer | From timestamp in seconds |
limit | false | integer | Limit for data size, max size is 200. Default as showing 200 pieces of data |
Response Parameters
Parameter | Type | Comment |
---|---|---|
symbol | string | Symbol |
period | string | Data recording period. 5min , 15min , 30min , 1h , 4h , 1d |
open_time | integer | Start timestamp point for result, in seconds |
open | string | Starting price |
high | string | Maximum price |
low | string | Minimum price |
close | string | Closing price |
Advanced Data
Open Interest
Please see the shared endpoint.
Latest Big Deal
Please see the shared endpoint.
Long-Short Ratio
Please see the shared endpoint.
Account Data Endpoints
The following account data endpoints require authentication.
Active Orders
Place Active Order
Request Example
curl https://api-testnet.bybit.com/private/linear/order/create \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","side":"Buy","symbol":"BTCUSD","order_type":"Market","qty":10,"time_in_force":"GoodTillCancel","timestamp":{timestamp},"sign":"{sign}"}'
from pybit import usdt_perpetual
session_auth = usdt_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="BTCUSDT",
side="Sell",
order_type="Limit",
qty=0.01,
price=8083,
time_in_force="GoodTillCancel",
reduce_only=False,
close_on_trigger=False
))
Response Example
{
"ret_code": 0,
"ret_msg": "OK",
"ext_code": "",
"ext_info": "",
"result": {
"order_id": "a6c64aa0-c80b-4865-ae35-99be5fab3535",
"user_id": 533285,
"symbol": "MANAUSDT",
"side": "Sell",
"order_type": "Limit",
"price": 0.8,
"qty": 100,
"time_in_force": "GoodTillCancel",
"order_status": "Created",
"last_exec_price": 0,
"cum_exec_qty": 0,
"cum_exec_value": 0,
"cum_exec_fee": 0,
"reduce_only": false,
"close_on_trigger": false,
"order_link_id": "Mactive001",
"created_time": "2022-06-22T01:46:11Z",
"updated_time": "2022-06-22T01:46:11Z",
"take_profit": 0.65,
"stop_loss": 0.99,
"tp_trigger_by": "MarkPrice",
"sl_trigger_by": "LastPrice",
"position_idx": 2
},
"time_now": "1655862371.660491",
"rate_limit_status": 99,
"rate_limit_reset_ms": 1655862371657,
"rate_limit": 100
}
Market price active order: A traditional market price order which will be filled at the best available price. price
is not required for this type of order.
Limit price active order: You can set an execution price for your order. Only when the last traded price reaches the order price will the system will fill your order.
Take profit/Stop loss: You may only set a TP/SL conditional order upon opening the position. Once you hold a position, any new active order requests which contain TP/SL data will be accepted but TP/SL data will be ignored. tp_trigger_by
/sl_trigger_by
default to LastPrice. Passing values to the take_profit
or stop_loss
parameters in this endpoint will create conditional orders managed by the system, which will be be automatically cancelled if the position is closed.
Order quantity: This parameter indicates the quantity of perpetual contracts you want to buy or sell. For the minimum unit of qty increase or decrease, please refer to the lot_size_filter
field in the Query Symbol endpoint. Note: The allowed max trade quantity of PostOnly
is 5 times bigger than normal orders.
Order price: If it is a stop order, this parameter is required. When there is no position, the long 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.
Custom order ID: You may customise order IDs for active orders. We will link it to the system order ID, and return the unique system order ID to you after the active order is created successfully. You may use this order ID or your custom order ID to cancel your active order. The customised order ID should be unique, with a maximum length of 36 characters.
Each account can hold up to 500 active orders yet to be filled entirely simultaneously. This is per instrument, so it's possible to have, for example, 300 active orders on the BTCUSDT instrument and 280 active orders on the ETHUSDT instrument.
HTTP Request
POST
/private/linear/order/create
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
side | true | string | Side |
symbol | true | string | Symbol |
order_type | true | string | Active order type |
qty | true | number | Order quantity in cryptocurrency |
price | false | number | Order price. Required if you make limit price order |
time_in_force | true | string | Time in force |
reduce_only | true | bool | What is a reduce-only order? True means your position can only reduce in size if this order is triggered. When reduce_only is true, take profit/stop loss cannot be set |
close_on_trigger | true | bool | What is a close on trigger order? For a closing order. It can only reduce your position, not increase it. If the account has insufficient available balance when the closing order is triggered, then other active orders of similar contracts will be cancelled or reduced. It can be used to ensure your stop loss reduces your position regardless of current available margin. |
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
|
position_idx | false | integer | Position idx, used to identify positions in different position modes. Required if you are under One-Way Mode: 0-One-Way Mode 1-Buy side of both side mode 2-Sell side of both side mode |
Response Parameters
Parameter | Type | Comment |
---|---|---|
order_id | string | Order ID |
user_id | number | UserID |
symbol | string | Symbol |
side | string | Side |
order_type | string | Order type |
price | number | Order price |
qty | number | Order quantity in USD |
time_in_force | string | Time in force |
order_status | string | Order status |
last_exec_price | number | Last execution price |
cum_exec_qty | number | Cumulative qty of trading |
cum_exec_value | number | Cumulative value of trading |
cum_exec_fee | number | Cumulative trading fees |
reduce_only | bool | true means close order, false means open position |
close_on_trigger | bool | Is close on trigger order |
order_link_id | string | Unique user-set order ID. Maximum length of 36 characters |
created_time | string | Creation time (when the order_status was Created ) |
updated_time | string | Update time |
take_profit | number | Take profit price |
stop_loss | number | Stop loss price |
tp_trigger_by | string | Take profit trigger price type, default: LastPrice
|
sl_trigger_by | string | Stop loss trigger price type, default: LastPrice
|
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 |
Get Active Order
Request Example
curl "https://api-testnet.bybit.com/private/linear/order/list?api_key={api_key}×tamp={timestamp}&sign={sign}&symbol=BTCUSDT"
from pybit import usdt_perpetual
session_auth = usdt_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="BTCUSDT"
))
Response Example
{
"ret_code": 0,
"ret_msg": "OK",
"ext_code": "",
"ext_info": "",
"result": {
"current_page": 1,
"data": [
{
"order_id": "a6c64aa0-c80b-4865-ae35-99be5fab3535",
"user_id": 533285,
"symbol": "MANAUSDT",
"side": "Sell",
"order_type": "Limit",
"price": 0.8,
"qty": 100,
"time_in_force": "GoodTillCancel",
"order_status": "Filled",
"last_exec_price": 0.8315,
"cum_exec_qty": 100,
"cum_exec_value": 83.15,
"cum_exec_fee": 0.04989,
"reduce_only": false,
"close_on_trigger": false,
"order_link_id": "Mactive001",
"created_time": "2022-06-22T01:46:11Z",
"updated_time": "2022-06-22T01:46:11Z",
"take_profit": 0.65,
"stop_loss": 0.99,
"tp_trigger_by": "MarkPrice",
"sl_trigger_by": "LastPrice"
}
]
},
"time_now": "1655862613.007213",
"rate_limit_status": 598,
"rate_limit_reset_ms": 1655862613003,
"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
/private/linear/order/list
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
order_id | false | string | Order ID |
order_link_id | false | string | Unique user-set order ID. Maximum length of 36 characters |
symbol | true | string | Symbol |
order | false | string | Sort orders by creation date. Defaults to asc |
page | false | integer | Page. By default, gets first page of data. Maximum of 50 pages |
limit | false | integer | Limit for data size per page, max size is 50. Default as showing 20 pieces of data per page |
order_status | false | string | Query your orders for all statuses if 'order_status' not provided. If you want to query orders with specific statuses, you can pass the order_status split by ','. |
Response Parameters
Parameter | Type | Comment |
---|---|---|
order_id | string | Order ID |
user_id | number | UserID |
symbol | string | Symbol |
side | string | Side |
order_type | string | Order type |
price | number | Order price |
qty | number | Order quantity in cryptocurrency |
time_in_force | string | Time in force |
order_status | string | Order status |
last_exec_price | number | Last execution price |
cum_exec_qty | number | Cumulative qty of trading |
cum_exec_value | number | Cumulative value of trading |
cum_exec_fee | number | Cumulative trading fees |
order_link_id | string | Unique user-set order ID. Maximum length of 36 characters |
reduce_only | bool | true means close order, false means open position |
close_on_trigger | bool | Is close on trigger order |
created_time | string | Creation time (when the order_status was Created ) |
updated_time | string | Update time |
take_profit | number | Take profit price |
stop_loss | number | Stop loss price |
tp_trigger_by | string | Take profit trigger price type, default: LastPrice
|
sl_trigger_by | string | Stop loss trigger price type, default: LastPrice
|
Cancel Active Order
Request Example
curl https://api-testnet.bybit.com/private/linear/order/cancel \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","symbol":"BTCUSD","order_id":"","timestamp":{timestamp},"sign":"{sign}"}'
from pybit import usdt_perpetual
session_auth = usdt_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="BTCUSDT",
order_id=""
))
Response Example
{
"ret_code": 0,
"ret_msg": "OK",
"ext_code": "",
"ext_info": "",
"result": {
"order_id":"bd1844f-f3c0-4e10-8c25-10fea03763f6",
},
"time_now": "1575112681.814760",
"rate_limit_status": 98,
"rate_limit_reset_ms": 1580885703683,
"rate_limit": 100
}
Either order_id
or order_link_id
are required for cancelling active orders. order_id
- this unique 36 characters order ID was returned to you when the active order was created successfully.
You may cancel active orders that are unfilled or partially filled. Fully filled orders cannot be cancelled.
HTTP Request
POST
/private/linear/order/cancel
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
symbol | true | string | Symbol |
order_id | false | string | Order ID |
order_link_id | false | string | Unique user-set order ID |
Response Parameters
Parameter | Type | Comment |
---|---|---|
order_id | string | Order ID |
Cancel All Active Orders
Request Example
curl https://api-testnet.bybit.com/private/linear/order/cancel-all \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","symbol":"BTCUSDT","timestamp":{timestamp},"sign":"{sign}"}'
from pybit import usdt_perpetual
session_auth = usdt_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="BTCUSDT"
))
Response Example
{
"ret_code": 0,
"ret_msg": "OK",
"ext_code": "",
"ext_info": "",
"result": [
"89a38056-80f1-45b2-89d3-4d8e3a203a79",
"89a38056-80f1-45b2-89d3-4d8e3a203a79",
],
"time_now": "1575110339.105675",
"rate_limit_status": 98,
"rate_limit_reset_ms": 1580885703683,
"rate_limit": 100
}
Cancel all active orders that are unfilled or partially filled. Fully filled orders cannot be cancelled.
HTTP Request
POST
/private/linear/order/cancel-all
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
symbol | true | string | Symbol |
Response Parameters
Parameter | Type | Comment |
---|---|---|
result | arr | Order ID |
Replace Active Order
Request Example
curl https://api-testnet.bybit.com/private/linear/order/replace \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","symbol":"BTCUSDT","order_id":"","p_r_qty":2,"timestamp":{timestamp},"sign":"{sign}"}'
from pybit import usdt_perpetual
session_auth = usdt_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="BTCUSDT",
order_id="",
p_r_qty=2
))
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
/private/linear/order/replace
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
order_id | false | string | Order ID. Required if not passing order_link_id |
order_link_id | false | string | Unique user-set order ID. Required if not passing order_id |
symbol | true | string | Symbol |
p_r_qty | false | 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/private/linear/order/search?api_key={api_key}&symbol=BTCUSDT×tamp={timestamp}order_id={order_id}&sign={sign}"
from pybit import usdt_perpetual
session_auth = usdt_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com",
api_key="your api key",
api_secret="your api secret"
)
print(session_auth.query_active_order(
symbol="BTCUSDT",
order_id=""
))
Response Example
{
"ret_code": 0,
"ret_msg": "OK",
"ext_code": "",
"ext_info": "",
"result": [
{
"order_id": "8e7d1cd2-d7b3-4c61-87a9-a85a6e59cef8",
"user_id": 533285,
"symbol": "BITUSDT",
"side": "Buy",
"order_type": "Limit",
"price": 0.3,
"qty": 100,
"time_in_force": "GoodTillCancel",
"order_status": "New",
"last_exec_price": 0,
"cum_exec_qty": 0,
"cum_exec_value": 0,
"cum_exec_fee": 0,
"order_link_id": "Bactive001",
"reduce_only": false,
"close_on_trigger": false,
"created_time": "2022-06-22T02:11:49Z",
"updated_time": "2022-06-22T02:11:49Z",
"take_profit": 0.7,
"stop_loss": 0.1,
"tp_trigger_by": "LastPrice",
"sl_trigger_by": "LastPrice"
}
],
"time_now": "1655863947.736147",
"rate_limit_status": 599,
"rate_limit_reset_ms": 1655863947734,
"rate_limit": 600
}
//When only symbol
is passed, the response uses a different structure:
{
"ret_code": 0,
"ret_msg": "OK",
"ext_code": "",
"ext_info": "",
"result": [
{
"order_id": "6449d89e-6ef5-4f54-a065-12b2744de0ae",
"user_id": 118921,
"symbol": "LINKUSDT",
"side": "Buy",
"order_type": "Limit",
"price": 9,
"qty": 0.1,
"time_in_force": "GoodTillCancel",
"order_status": "New",
"last_exec_price": 11874.5,
"cum_exec_qty": 0.005,
"cum_exec_value": 11.8745,
"cum_exec_fee": 0.00890588,
"order_link_id": "",
"reduce_only": false,
"created_time": "2020-11-27T08:25:44Z",
"updated_time": "2020-11-27T08:25:44Z",
"take_profit": 0,
"stop_loss": 0,
"tp_trigger_by": "UNKNOWN",
"sl_trigger_by": "UNKNOWN"
},
...
{
"order_id": "6d4dc4e0-b4e3-4fc5-a92d-3d693bdff4a5",
"user_id": 118921,
"symbol": "LINKUSDT",
"side": "Buy",
"order_type": "Limit",
"price": 8.2,
"qty": 9999,
"time_in_force": "GoodTillCancel",
"order_status": "New",
"last_exec_price": 11888.5,
"cum_exec_qty": 0.004,
"cum_exec_value": 11.8745,
"cum_exec_fee": 0.00890588,
"order_link_id": "",
"reduce_only": false,
"created_time": "2020-11-23T09:19:49Z",
"updated_time": "2020-11-23T09:20:31Z",
"take_profit": 0,
"stop_loss": 0,
"tp_trigger_by": "UNKNOWN",
"sl_trigger_by": "UNKNOWN"
}
],
"time_now": "1606465563.551193",
"rate_limit_status": 599,
"rate_limit_reset_ms": 1606465563547,
"rate_limit": 600
}
Query real-time active order information. If only order_id
or order_link_id
are passed, a single order will be returned; otherwise, returns up to 500 unfilled orders.
HTTP Request
GET
/private/linear/order/search
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
order_id | false | string | Order ID |
order_link_id | false | string | Unique user-set order ID |
symbol | true | string | Symbol |
Response Parameters
Parameter | Type | Comment |
---|---|---|
order_id | string | Order ID |
user_id | number | UserID |
symbol | string | Symbol |
side | string | Side |
order_type | string | Order type |
price | number | Order price |
qty | number | Order quantity in cryptocurrency |
time_in_force | string | Time in force |
order_status | string | Order status |
last_exec_price | number | Last execution price |
cum_exec_qty | number | Cumulative qty of trading |
cum_exec_value | number | Cumulative value of trading |
cum_exec_fee | number | Cumulative trading fees |
reduce_only | bool | true means close order, false means open position |
close_on_trigger | bool | Is close on trigger order |
order_link_id | string | Unique user-set order ID. Maximum length of 36 characters |
created_time | string | Creation time (when the order_status was Created ) |
updated_time | string | Update time |
take_profit | number | Take profit price |
stop_loss | number | Stop loss price |
tp_trigger_by | string | Take profit trigger price type, default: LastPrice
|
sl_trigger_by | string | Stop loss trigger price type, default: LastPrice
|
Conditional Orders
Place Conditional Order
Request Example
curl https://api-testnet.bybit.com/private/linear/stop-order/create \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","order_type":"Limit","side":"Buy","symbol":"BTCUSD","qty":1,"price":8100,"base_price":8300,"stop_px":8150,"time_in_force":"GoodTillCancel","trigger_by":"LastPrice",order_link_id":"cus_order_id_1","reduce_only":false,"close_on_trigger":false,"timestamp":{timestamp},"sign":"{sign}"}'
from pybit import usdt_perpetual
session_auth = usdt_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="BTCUSDT",
order_type="Limit",
side="Buy",
qty=1,
price=8100,
base_price=16100,
stop_px=8150,
time_in_force="GoodTillCancel",
trigger_by="LastPrice",
order_link_id="cus_order_id_1",
reduce_only=False,
close_on_trigger=False
))
Response Example
{
"ret_code": 0,
"ret_msg": "OK",
"ext_code": "",
"ext_info": "",
"result": {
"user_id": 533285,
"stop_order_id": "37c2f5ac-3c87-4853-a7c6-29070d4b9c4f",
"symbol": "XRPUSDT",
"side": "Buy",
"order_type": "Limit",
"price": 0.25,
"qty": 100,
"time_in_force": "GoodTillCancel",
"order_status": "Untriggered",
"trigger_price": 0.35,
"order_link_id": "Xcond001",
"created_time": "2022-06-22T02:20:47Z",
"updated_time": "2022-06-22T02:20:47Z",
"base_price": "0.3000",
"trigger_by": "MarkPrice",
"tp_trigger_by": "IndexPrice",
"sl_trigger_by": "MarkPrice",
"take_profit": 0.5,
"stop_loss": 0.12,
"reduce_only": false,
"close_on_trigger": false,
"position_idx": 1
},
"time_now": "1655864447.252259",
"rate_limit_status": 99,
"rate_limit_reset_ms": 1655864447248,
"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
/private/linear/stop-order/create
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
side | true | string | Side |
symbol | true | string | Symbol |
order_type | true | string | Conditional order type |
qty | true | number | Order quantity in cryptocurrency |
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 | true | string | Trigger price type |
reduce_only | true | bool | What is a reduce-only order? True means your position can only reduce in size if this order is triggered. When reduce_only is true, take profit/stop loss cannot be set |
close_on_trigger | true | bool | What is a close on trigger order? For a closing order. It can only reduce your position, not increase it. If the account has insufficient available balance when the closing order is triggered, then other active orders of similar contracts will be cancelled or reduced. It can be used to ensure your stop loss reduces your position regardless of current available margin. |
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
|
position_idx | false | integer | Position idx, used to identify positions in different position modes. Required if you are under One-Way Mode: 0-One-Way Mode 1-Buy side of both side mode 2-Sell side of both side mode |
Response Parameters
Parameter | Type | Comment |
---|---|---|
stop_order_id | string | Conditional order ID. Once triggered, the conditional order creates an active order with the same ID (order_id ) |
user_id | number | UserID |
symbol | string | Symbol |
side | string | Side |
order_type | string | Active order type |
price | number | Order price |
qty | number | Order quantity in cryptocurrency |
time_in_force | string | Time in force |
order_status | string | Order status |
trigger_price | number | If stop_order_type is TrailingProfit , this field is the trailing stop active price. |
order_link_id | string | Unique user-set order ID. Maximum length of 36 characters |
created_time | string | Creation time (when the order_status was Created ) |
updated_time | string | Update time |
base_price | string | Market price at placing order |
trigger_by | string | Trigger price type. Default LastPrice |
tp_trigger_by | string | Take profit trigger price type, default: LastPrice
|
sl_trigger_by | string | Stop loss trigger price type, default: LastPrice
|
take_profit | number | Take profit price |
stop_loss | number | Stop loss price |
reduce_only | bool | true means close order, false means open position |
close_on_trigger | bool | Is close on trigger order |
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 |
Get Conditional Order
Request Example
curl "https://api-testnet.bybit.com/private/linear/stop-order/list?api_key={api_key}×tamp={timestamp}&sign={sign}"
from pybit import usdt_perpetual
session_auth = usdt_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="BTCUSDT"
))
Response Example
{
"ret_code": 0,
"ret_msg": "ok",
"ext_code": "",
"result": {
"current_page": 1,
"last_page": 1,
"data": [
{
"stop_order_id":"bd1844f-f3c0-4e10-8c25-10fea03763f6",
"user_id": 1,
"symbol": "BTCUSDT",
"side": "Sell",
"order_type": "Limit",
"price": 8083,
"qty": 10,
"time_in_force": "GoodTillCancel",
"order_status": "New",
"trigger_price": 8003,
"order_link_id": "",
"created_time": "2019-10-21T07:28:19.396246Z",
"updated_time": "2019-10-21T07:28:19.396246Z",
"take_profit": 0,
"stop_loss": 0,
"tp_trigger_by": "UNKNOWN",
"sl_trigger_by": "UNKNOWN",
"base_price": "16100.0000",
"trigger_by": "LastPrice",
},
{
"stop_order_id":"bd1844f-f3c0-4e10-8c25-10fea03763f6",
"user_id": 1,
"symbol": "BTCUSDT",
"side": "Sell",
"order_type": "Limit",
"price": 8083,
"qty": 10,
"time_in_force": "GoodTillCancel",
"order_status": "New",
"trigger_price": 8003,
"order_link_id": "",
"created_time": "2019-10-21T07:28:19.396246Z",
"updated_time": "2019-10-21T07:28:19.396246Z",
"take_profit": 0,
"stop_loss": 0,
"tp_trigger_by": "UNKNOWN",
"sl_trigger_by": "UNKNOWN",
"base_price": "16100.0000",
"trigger_by": "LastPrice",
"reduce_only": false,
"close_on_trigger": false,
}
]
},
"ext_info": null,
"time_now": "1577451658.755468",
"rate_limit_status": 599,
"rate_limit_reset_ms": 1577451658762,
"rate_limit": 600
}
Get my conditional order list.
Because order creation/cancellation is asynchronous, there can be a data delay in this endpoint. You can get real-time order info with the Query Conditional Order (real-time) endpoint.
HTTP Request
GET
/private/linear/stop-order/list
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
stop_order_id | false | string | Conditional order ID. Once triggered, the conditional order creates an active order with the same ID (order_id ) |
order_link_id | false | string | Unique user-set order ID. Maximum length of 36 characters |
symbol | true | string | Symbol |
stop_order_status | false | string | Stop order status |
order | false | string | Sort orders by creation date. Defaults to asc |
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 |
---|---|---|
stop_order_id | string | Conditional order ID. Once triggered, the conditional order creates an active order with the same ID (order_id ) |
user_id | number | UserID |
symbol | string | Symbol |
side | string | Side |
order_type | string | Active order type |
price | number | Order price |
qty | number | Order quantity in cryptocurrency |
time_in_force | string | Time in force |
order_status | string | Stop order status |
trigger_price | number | If stop_order_type is TrailingProfit , this field is the trailing stop active price. |
order_link_id | string | Unique user-set order ID. Maximum length of 36 characters |
created_time | string | Creation time (when the order_status was Created ) |
updated_time | string | Update time |
take_profit | number | Take profit price |
stop_loss | number | Stop loss price |
trigger_by | string | Trigger price type. Default LastPrice |
base_price | string | Market price at placing order |
tp_trigger_by | string | Take profit trigger price type, default: LastPrice
|
sl_trigger_by | string | Stop loss trigger price type, default: LastPrice
|
reduce_only | bool | true means close order, false means open position |
close_on_trigger | bool | Is close on trigger order |
Cancel Conditional Order
Request Example
curl https://api-testnet.bybit.com/private/linear/stop-order/cancel \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","symbol":"BTCUSDT","stop_order_id":"","timestamp":{timestamp},"sign":"{sign}"}'
from pybit import usdt_perpetual
session_auth = usdt_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="BTCUSDT",
stop_order_id=""
))
Response Example
{
"ret_code": 0,
"ret_msg": "ok",
"ext_code": "",
"result": {
"stop_order_id":"bd1844f-f3c0-4e10-8c25-10fea03763f6",
},
"ext_info": null,
"time_now": "1577452218.567120",
"rate_limit_status": 97,
"rate_limit_reset_ms": 1577452218573,
"rate_limit": "100"
}
You may cancel all untriggered conditional orders or take profit/stop loss order. Essentially, after a conditional order is triggered, it will become an active order. So, when a conditional order is triggered, cancellation has to be done through the active order endpoint for any unfilled or partially filled active order. As always, orders that have been fully filled cannot be cancelled.
HTTP Request
POST
/private/linear/stop-order/cancel
Request Parameters
Parameter | required | type | comments |
---|---|---|---|
symbol | true | string | Symbol |
stop_order_id | false | string | Order ID |
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/private/linear/stop-order/cancel-all \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","symbol":"BTCUSDT","timestamp":{timestamp},"sign":"{sign}"}'
from pybit import usdt_perpetual
session_auth = usdt_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="BTCUSDT"
))
Response Example
{
"ret_code": 0,
"ret_msg": "OK",
"ext_code": "",
"ext_info": "",
"result": [
"89a38056-80f1-45b2-89d3-4d8e3a203a79",
"89a38056-80f1-45b2-89d3-4d8e3a203a79",
],
"time_now": "1577454993.799912",
"rate_limit_status": 90,
"rate_limit_reset_ms": 1580885703683,
"rate_limit": 100
}
Cancel all untriggered conditional orders.
HTTP Request
POST
/private/linear/stop-order/cancel-all
Request Parameters
Parameter | required | type | comments |
---|---|---|---|
symbol | true | string | Symbol |
Replace Conditional Order
Request Example
curl https://api-testnet.bybit.com/private/linear/stop-order/replace \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","symbol":"BTCUSDT","stop_order_id":"","p_r_qty":2,"timestamp":{timestamp},"sign":"{sign}"}'
from pybit import usdt_perpetual
session_auth = usdt_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="BTCUSDT",
stop_order_id="",
p_r_qty=2
))
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
/private/linear/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 | number | New conditional order's trigger price or TP/SL order price, also known as stop_px. Do not pass this field if you don't want modify it |
take_profit | false | number | New take_profit price. 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/private/linear/stop-order/search?api_key={api_key}&symbol=BTCUSDT×tamp={timestamp}&sign={sign}"
from pybit import usdt_perpetual
session_auth = usdt_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="BTCUSDT"
))
Response Example
{
"ret_code": 0,
"ret_msg": "OK",
"ext_code": "",
"ext_info": "",
"result": {
"stop_order_id":"bd1844f-f3c0-4e10-8c25-10fea03763f6",
"user_id": 1,
"symbol": "BTCUSDT",
"side": "Sell",
"order_type": "Limit",
"price": 8083,
"qty": 10,
"time_in_force": "GoodTillCancel",
"order_status": "New",
"trigger_price": 8003,
"order_link_id": "",
"created_time": "2019-10-21T07:28:19.396246Z",
"updated_time": "2019-10-21T07:28:19.396246Z",
"take_profit": 0,
"stop_loss": 0,
"tp_trigger_by": "UNKNOWN",
"sl_trigger_by": "UNKNOWN",
"base_price": "16100.0000",
"trigger_by": "LastPrice",
"reduce_only": false,
"close_on_trigger": false,
},
"time_now": "1577476584.386958",
"rate_limit_status": 99,
"rate_limit_reset_ms": 1580885703683,
"rate_limit": 100
}
//When only symbol
is passed, the response uses a different structure:
{
"ret_code": 0,
"ret_msg": "OK",
"ext_code": "",
"ext_info": "",
"result": [
{
"user_id": 1301180,
"stop_order_id": "a1dbf284-b6ee-4eaf-9fda-2d3f3fa4c501",
"symbol": "BTCUSDT",
"side": "Buy",
"order_type": "Limit",
"price": 8020,
"qty": 0.001,
"time_in_force": "GoodTillCancel",
"order_status": "Untriggered",
"trigger_price": 16000,
"order_link_id": "",
"created_time": "2020-11-16T09:06:17.000Z",
"updated_time": "2020-11-16T09:06:17.000Z",
"take_profit": 0,
"stop_loss": 0,
"tp_trigger_by": "UNKNOWN",
"sl_trigger_by": "UNKNOWN",
"trigger_by": "LastPrice"
},
...
{
"user_id": 1301180,
"stop_order_id": "d4g5bf862-b6ee-4eaf-9fda-2d3f3fd9g4j6",
"symbol": "BTCUSDT",
"side": "Sell",
"order_type": "Limit",
"price": 8022,
"qty": 0.005,
"time_in_force": "GoodTillCancel",
"order_status": "Untriggered",
"trigger_price": 16000,
"order_link_id": "",
"created_time": "2020-11-16T09:06:17.000Z",
"updated_time": "2020-11-16T09:06:17.000Z",
"take_profit": 0,
"stop_loss": 0,
"tp_trigger_by": "UNKNOWN",
"sl_trigger_by": "UNKNOWN",
"trigger_by": "LastPrice"
}
],
"time_now": "1606445293.547976",
"rate_limit_status": 599,
"rate_limit_reset_ms": 1606445293545,
"rate_limit": 600
}
Query real-time stop order information. When passing the parameter order_id
or order_link_id
, a single order data will be returned; otherwise, returns up to 10 unfilled orders.
HTTP Request
GET
/private/linear/stop-order/search
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
symbol | true | string | Symbol |
stop_order_id | false | string | Order ID |
order_link_id | false | string | Unique user-set order ID |
Response Parameters
Parameter | Type | Comment |
---|---|---|
stop_order_id | string | Conditional order ID. Once triggered, the conditional order creates an active order with the same ID (order_id ) |
user_id | number | UserID |
symbol | string | Symbol |
side | string | Side |
order_type | string | Active order type |
price | number | Order price |
qty | number | Order quantity in cryptocurrency |
time_in_force | string | Time in force |
order_status | string | Order status |
trigger_price | number | If stop_order_type is TrailingProfit , this field is the trailing stop active price. |
base_price | string | Market price at placing order |
order_link_id | string | Unique user-set order ID. Maximum length of 36 characters |
created_time | string | Creation time (when the order_status was Created ) |
updated_time | string | Update time |
take_profit | number | Take profit price |
stop_loss | number | Stop loss price |
tp_trigger_by | string | Take profit trigger price type, default: LastPrice
|
sl_trigger_by | string | Stop loss trigger price type, default: LastPrice
|
trigger_by | string | Trigger price type. Default LastPrice |
reduce_only | bool | true means close order, false means open position |
close_on_trigger | bool | Is close on trigger order |
Position
My Position
Request Example
curl https://api-testnet.bybit.com/private/linear/position/list?api_key={api_key}&symbol=BTCUSDT×tamp={timestamp}&sign={sign}"
from pybit import usdt_perpetual
session_auth = usdt_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com",
api_key="XXXXXXXXXXXX",
api_secret="XXXXXXXXXXXXXXXXXXXXXX"
)
print(session_auth.my_position(
symbol="BTCUSDT"
))
Response Example
{
"ret_code": 0,
"ret_msg": "OK",
"ext_code": "",
"ext_info": "",
"result": [
{
"user_id": 533285,
"symbol": "XRPUSDT",
"side": "Buy",
"size": 0,
"position_value": 0,
"entry_price": 0,
"liq_price": 0,
"bust_price": 0,
"leverage": 5,
"auto_add_margin": 0,
"is_isolated": true,
"position_margin": 0,
"occ_closing_fee": 0,
"realised_pnl": 0,
"cum_realised_pnl": -16.35115218,
"free_qty": 0,
"tp_sl_mode": "Full",
"unrealised_pnl": 0,
"deleverage_indicator": 0,
"risk_id": 41,
"stop_loss": 0,
"take_profit": 0,
"trailing_stop": 0,
"position_idx": 1,
"mode": "BothSide"
},
{
"user_id": 533285,
"symbol": "XRPUSDT",
"side": "Sell",
"size": 50,
"position_value": 19.58,
"entry_price": 0.3916,
"liq_price": 0.4529,
"bust_price": 0.4568,
"leverage": 6,
"auto_add_margin": 0,
"is_isolated": true,
"position_margin": 3.2633354,
"occ_closing_fee": 0.013704,
"realised_pnl": 0,
"cum_realised_pnl": 0.90620182,
"free_qty": 50,
"tp_sl_mode": "Full",
"unrealised_pnl": 3.395,
"deleverage_indicator": 2,
"risk_id": 41,
"stop_loss": 0.5,
"take_profit": 0.28,
"trailing_stop": 0,
"tp_trigger_by": 1,
"sl_trigger_by": 1,
"position_idx": 2,
"mode": "BothSide"
}
],
"time_now": "1655868796.293226",
"rate_limit_status": 119,
"rate_limit_reset_ms": 1655868796290,
"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": [
{
"data": {
"user_id": 533285,
"symbol": "10000NFTUSDT",
"side": "Sell",
"size": 0,
"position_value": 0,
"entry_price": 0,
"liq_price": 0,
"bust_price": 0,
"leverage": 10,
"auto_add_margin": 0,
"is_isolated": false,
"position_margin": 0,
"occ_closing_fee": 0,
"realised_pnl": 0,
"cum_realised_pnl": 0,
"free_qty": 0,
"tp_sl_mode": "Full",
"unrealised_pnl": 0,
"deleverage_indicator": 0,
"risk_id": 1,
"stop_loss": 0,
"take_profit": 0,
"trailing_stop": 0,
"position_idx": 2,
"mode": "BothSide"
},
"is_valid": true
},
...
{
"data": {
"user_id": 533285,
"symbol": "10000NFTUSDT",
"side": "Buy",
"size": 0,
"position_value": 0,
"entry_price": 0,
"liq_price": 0,
"bust_price": 0,
"leverage": 10,
"auto_add_margin": 0,
"is_isolated": false,
"position_margin": 0,
"occ_closing_fee": 0,
"realised_pnl": 0,
"cum_realised_pnl": 0,
"free_qty": 0,
"tp_sl_mode": "Full",
"unrealised_pnl": 0,
"deleverage_indicator": 0,
"risk_id": 1,
"stop_loss": 0,
"take_profit": 0,
"trailing_stop": 0,
"position_idx": 1,
"mode": "BothSide"
},
"is_valid": true
}
],
"time_now": "1604302080.356538",
"rate_limit_status": 119,
"rate_limit_reset_ms": 1604302080353,
"rate_limit": 120
}
Get my position list.
HTTP Request
GET
/private/linear/position/list
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
symbol | false | string | Symbol |
Response Parameters
Parameter | Type | Comment |
---|---|---|
user_id | number | UserID |
symbol | string | Symbol |
side | string | Side |
size | number | Position qty |
position_value | number | Position value |
entry_price | number | Average opening price |
liq_price | number | Liquidation price |
bust_price | number | Bust price |
leverage | number | In Isolated Margin mode, the value is set by the user. In Cross Margin mode, the value is the max leverage at current risk level |
auto_add_margin | number | Whether or not auto-margin replenishment is enabled |
is_isolated | bool | true means isolated margin mode; false means cross margin mode |
position_margin | number | Position margin |
occ_closing_fee | number | Pre-occupancy closing fee |
realised_pnl | number | Today's realised Profit and Loss |
cum_realised_pnl | number | Cumulative realised Profit and Loss |
free_qty | number | Qty which can be closed. (If you have a long position, free_qty is negative. vice versa) |
tp_sl_mode | string | Stop loss and take profit mode |
deleverage_indicator | number | Deleverage indicator level (1,2,3,4,5) |
unrealised_pnl | number | unrealised pnl |
risk_id | integer | Risk ID |
take_profit | number | Take profit price |
stop_loss | number | Stop loss price |
trailing_stop | number | Trailing stop (the distance from the current price) |
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 | string | Position Mode. MergedSingle : One-Way Mode; BothSide : Hedge Mode
|
Set Auto Add Margin
Request Example
curl https://api-testnet.bybit.com/private/linear/position/set-auto-add-margin \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","symbol":"BTCUSDT","side":"Sell","auto_add_margin":false,"timestamp":{timestamp},"sign":"{sign}"}'
from pybit import usdt_perpetual
session_auth = usdt_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com",
api_key="XXXXXXXXXXX",
api_secret="XXXXXXXXXX"
)
print(session_auth.set_auto_add_margin(
symbol="BTCUSDT",
side="Sell",
auto_add_margin=False
))
Response Example
{
"ret_code": 0,
"ret_msg": "OK",
"ext_code": "",
"ext_info": "",
"result": null,
"time_now": "1586780385.549188",
"rate_limit_status": 74,
"rate_limit_reset_ms": 1586780385547,
"rate_limit": 75
}
Set auto add margin, or Auto-Margin Replenishment.
HTTP Request
POST
/private/linear/position/set-auto-add-margin
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
symbol | true | string | Symbol |
side | true | string | Side |
auto_add_margin | true | bool | Auto add margin button |
position_idx | false | 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 |
Cross/Isolated Margin Switch
Request Example
curl https://api-testnet.bybit.com/private/linear/position/switch-isolated \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","symbol":"BTCUSDT","is_isolated":true,"buy_leverage":1,"sell_leverage":1,"timestamp":{timestamp},"sign":"{sign}"}'
from pybit import usdt_perpetual
session_auth = usdt_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com",
api_key="XXXXXXX",
api_secret="XXXXXX"
)
print(session_auth.cross_isolated_margin_switch(
symbol="BTCUSDT",
is_isolated=True,
buy_leverage=1,
sell_leverage=1
))
Response Example
{
"ret_code": 0,
"ret_msg": "OK",
"ext_code": "",
"ext_info": "",
"result": null,
"time_now": "1585881597.006026",
"rate_limit_status": 74,
"rate_limit_reset_ms": 1585881597004,
"rate_limit": 75
}
Switch Cross/Isolated; must set leverage value when switching from Cross to Isolated
HTTP Request
POST
/private/linear/position/switch-isolated
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
symbol | true | string | Symbol |
is_isolated | true | bool | Cross/Isolated: true is Isolated; false is Cross |
buy_leverage | true | number | Must be greater than 0 and less than the risk limit leverage. |
sell_leverage | true | number | Must be greater than 0 and less than the risk limit leverage. |
Position Mode Switch
Request Example
curl https://api-testnet.bybit.com/private/linear/position/switch-mode \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","symbol":"BTCUSDT","mode":"MergedSingle","timestamp":{timestamp},"sign":"{sign}"}'
from pybit import usdt_perpetual
session_auth = usdt_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com",
api_key="XXXXXXXXXXXX",
api_secret="XXXXXXXXXXXXXXXXXXXXXX"
)
print(session_auth.position_mode_switch(
symbol="BTCUSDT",
mode="MergedSingle"
))
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
}
It supports to switch the position mode for USDT perpetual and Inverse futures. If you are in One-Way Mode, you can only open one position on Buy
or Sell
side. If you are in Hedge Mode, you can open both Buy
and Sell
side positions simultaneously.
Rule:
- Priority for configuration to take effect: symbol > coin > system default
- System default: one-way mode
- If the request is by
coin
(settleCoin), then all symbols based on this setteCoin that do not have position and open order will be batch switched, and new listed symbol based on this settleCoin will be the same mode you set.
System default | coin | symbol | |
---|---|---|---|
Inital setting | one-way | never configured | never configured |
Take effect result | All USDT perpetual trading pairs are one-way molde | ||
Change 1 | - | - | Set BTCUSDT to hedge-mode |
Take effect result | BTCUSDT becomes hedge-mode, and all other symbols keep one-way mode | ||
list new symbol ETHUSDT | ETHUSDT is one-way mode (inherit default rules) | ||
Change 2 | - | Set USDT to hedge-mode | - |
Take effect result | All current trading pairs with no positions or orders are hedge-mode, and no adjustments will be made for trading pairs with positions and orders | ||
list new symbol SOLUSDT | SOLUSDT is hedge-mode (Inherit coin rule) | ||
Change 3 | - | - | Set ASXUSDT to one-mode |
Take effect result | AXSUSDT is one-way mode, other trading pairs have no change | ||
list new symbol BITUSDT | BITUSDT is hedge-mode (Inherit coin rule) |
The position-switch ability for current contract:
Regular account | Unified margin account | |
---|---|---|
USDT perpetual | Support one-way & hedge-mode | Support one-way ONLY |
USDC perpetual | Support one-way ONLY | Support one-way ONLY |
Inverse perpetual | Support one-way ONLY | N/A |
Inverse future | Support one-way & hedge-mode | N/A |
HTTP Request
POST
/private/linear/position/switch-mode
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
symbol | false | string | Symbol. Required if not passing coin |
coin | false | string | currency alias. Required if not passing symbol |
mode | true | string | Position Mode. MergedSingle : One-Way Mode; BothSide : Hedge Mode
|
Full/Partial Position TP/SL Switch
from pybit import usdt_perpetual
session_auth = usdt_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com",
api_key="XXXXXXXXXXXX",
api_secret="XXXXXXXXXXXXXXXXXXXXXX"
)
print(session_auth.full_partial_position_tp_sl_switch(
symbol="BTCUSDT",
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
/private/linear/tpsl/switch-mode
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
symbol | true | string | Symbol |
tp_sl_mode | true | string | Stop loss and take profit mode |
Response Parameters
Parameter | Type | Comment |
---|---|---|
tp_sl_mode | string | Stop loss and take profit mode |
Add/Reduce Margin
Request Example
curl https://api-testnet.bybit.com \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","symbol":"BTCUSDT","side":"Buy","margin":0.01","timestamp":{timestamp},"sign":"{sign}"}'
from pybit import usdt_perpetual
session_auth = usdt_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com",
api_key="XXXXXXXXXXXX",
api_secret="XXXXXXXXXXXXXXXXXXXXXX"
)
print(session_auth.add_reduce_margin(
symbol="BTCUSDT",
side="Buy",
margin=0.01
))
Response Example
{
"ret_code": 0,
"ret_msg": "OK",
"ext_code": "",
"ext_info": "",
"result": {
"PositionListResult": {
"user_id": 533285,
"symbol": "XRPUSDT",
"side": "Sell",
"size": 50,
"position_value": 19.58,
"entry_price": 0.3916,
"liq_price": 0.5267,
"bust_price": 0.5307,
"leverage": 10,
"auto_add_margin": 0,
"is_isolated": true,
"position_margin": 6.9550018,
"occ_closing_fee": 0.015921,
"realised_pnl": 0,
"cum_realised_pnl": 0.90620182,
"free_qty": 50,
"tp_sl_mode": "Full",
"unrealised_pnl": 3.475,
"deleverage_indicator": 2,
"risk_id": 41,
"stop_loss": 0.5,
"take_profit": 0.28,
"trailing_stop": 0,
"tp_trigger_by": 1,
"sl_trigger_by": 1,
"position_idx": 2,
"mode": "BothSide"
},
"wallet_balance": 2108.58165689,
"available_balance": 2091.03640109
},
"time_now": "1655870135.180074",
"rate_limit_status": 73,
"rate_limit_reset_ms": 1655870135178,
"rate_limit": 75
}
Add Margin
HTTP Request
POST
/private/linear/position/add-margin
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
symbol | true | string | Symbol |
side | true | string | Side |
margin | true | number | Add/Remove how much margin: Increase 10; decrease -10, supports 4 decimal places |
position_idx | false | 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 |
Response Parameters
Parameter | Type | Comment |
---|---|---|
user_id | number | UserID |
symbol | string | Symbol |
side | string | Side |
size | number | Position qty |
position_value | number | Current position value |
entry_price | number | Average opening price |
liq_price | number | Liquidation price |
bust_price | number | Bust price |
leverage | number | In Isolated Margin mode, the value is set by the user. In Cross Margin mode, the value is the max leverage at current risk level |
auto_add_margin | number | Whether or not auto-margin replenishment is enabled |
is_isolated | bool | True means isolated margin, false means cross margin |
position_margin | number | Position margin |
occ_closing_fee | number | Pre-occupancy closing fee |
realised_pnl | number | Today's realised Profit and Loss |
cum_realised_pnl | number | Cumulative realised Profit and Loss |
free_qty | number | Qty which can be closed. (If you have a long position, free_qty is negative. vice versa) |
tp_sl_mode | string | Stop loss and take profit mode |
unrealised_pnl | number | unrealised pnl |
deleverage_indicator | number | Deleverage indicator level (1,2,3,4,5) |
risk_id | number | Risk ID |
stop_loss | number | Stop loss price |
take_profit | number | Take profit price |
trailing_stop | number | Trailing stop (the distance from the current price) |
tp_trigger_by | string | Take profit trigger price type, default: LastPrice
|
sl_trigger_by | string | Stop loss trigger price type, default: LastPrice
|
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 | string | Position Mode. MergedSingle : One-Way Mode; BothSide : Hedge Mode
|
wallet_balance | number | Wallet balance |
available_balance | number | Available balance = wallet balance - used margin |
Set Leverage
Request Example
curl https://api-testnet.bybit.com/private/linear/position/set-leverage \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","symbol":"BTCUSDT","buy_leverage":10,"sell_leverage":10"sign":"{sign}"}'
from pybit import usdt_perpetual
session_auth = usdt_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com",
api_key="XXXXXXXXXXXX",
api_secret="XXXXXXXXXXXXXXXXXXXXXX"
)
print(session_auth.set_leverage(
symbol="BTCUSDT",
buy_leverage=10,
sell_leverage=10
))
Response Example
{
"ret_code": 0,
"ret_msg": "OK",
"ext_code": "",
"ext_info": "",
"result": null,
"time_now": "1585881527.650138",
"rate_limit_status": 74,
"rate_limit_reset_ms": 1585881527648,
"rate_limit": 75
}
Set Leverage
HTTP Request
POST
/private/linear/position/set-leverage
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
symbol | true | string | Symbol |
buy_leverage | true | number | Must be greater than 0 and less than the risk limit leverage. |
sell_leverage | true | number | Must be greater than 0 and less than the risk limit leverage. |
Set Trading-Stop
Request Example
curl https://api-testnet.bybit.com/private/linear/position/trading-stop \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","symbol":"BTCUSDT","side":"Buy","take_profit":10,"timestamp":{timestamp},"sign":"{sign}"}'
from pybit import usdt_perpetual
session_auth = usdt_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com",
api_key="XXXXXXXXXXXX",
api_secret="XXXXXXXXXXXXXXXXXXXXXX"
)
print(session_auth.set_trading_stop(
symbol="BTCUSDT",
side="Buy",
take_profit=10
))
Response Example
{
"ret_code": 0,
"ret_msg": "OK",
"ext_code": "",
"ext_info": "",
"result": null,
"time_now": "1586780408.193508",
"rate_limit_status": 73,
"rate_limit_reset_ms": 1586780408191,
"rate_limit": 75
}
Set take profit, stop loss, and trailing stop for your open position. If using partial mode, TP/SL/TS orders will not close your entire position.
HTTP Request
POST
/private/linear/position/trading-stop
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
symbol | true | string | Symbol |
side | true | string | Position side |
take_profit | false | number | Cannot be less than 0, 0 means cancel TP (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
|
sl_size | false | number | Stop loss quantity (when in partial mode) |
tp_size | false | number | Take profit quantity (when in partial mode) |
position_idx | false | 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 |
Get User Trade Records
Request Example
curl "https://api-testnet.bybit.com/private/linear/trade/execution/list?api_key={api_key}&symbol=BTCUSDT×tamp={timestamp}&sign={sign}"
from pybit import usdt_perpetual
session_auth = usdt_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com",
api_key="XXXXXXXXXXXX",
api_secret="XXXXXXXXXXXXXXXXXXXXXX"
)
print(session_auth.user_trade_records(
symbol="BTCUSDT"
))
Response Example
{
"ret_code": 0,
"ret_msg": "OK",
"ext_code": "",
"ext_info": "",
"result": {
"current_page": 1,
"data": [
{
"order_id": "7369b2f4-52f1-4698-abf7-368e4ba9aefa",
"order_link_id": "",
"side": "Buy",
"symbol": "BTCUSDT",
"exec_id": "9b8216fa-98d7-55c0-b5fa-279db5727996",
"price": 5894
"order_price": 5894,
"order_qty": 0.001,
"order_type": "Limit",
"fee_rate": 0.00075,
"exec_price": 5894,
"exec_type": "Trade",
"exec_qty": 0.001,
"exec_fee": 0.0044205,
"exec_value": 5.894,
"leaves_qty": 0,
"closed_size": 0,
"last_liquidity_ind": "RemovedLiquidity",
"trade_time": 1585547384
"trade_time_ms": 1585547384847
}
]
},
"time_now": "1577480599.097287",
"rate_limit_status": 119,
"rate_limit_reset_ms": 1580885703683,
"rate_limit": 120
}
}
Get user's trading records. The results are ordered in descending order (the first item is the latest). Returns records up to 2 years old.
HTTP Request
GET
/private/linear/trade/execution/list
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
symbol | true | string | Symbol |
start_time | false | integer | Start timestamp point for result, in milliseconds. Timestamp must be within seven days of the current date. For earlier records, please contact customer support |
end_time | false | integer | End timestamp point for result, in milliseconds. Timestamp must be within seven days of the current date. For earlier records, please contact customer support |
exec_type | false | string | Execution type |
page | false | integer | Page. By default, gets first page of data. 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. |
Response Parameters
Parameter | Type | Comment |
---|---|---|
order_id | string | Order ID |
order_link_id | string | Unique user-set order ID. Maximum length of 36 characters |
side | string | Side |
symbol | string | Symbol |
exec_id | string | Transaction ID |
price | number | Order price |
order_price | number | Order price |
order_qty | number | Order qty |
order_type | string | Order type |
fee_rate | number | Maker or taker fee rate |
exec_price | number | Transaction price |
exec_type | string | Exec type |
exec_qty | number | Transaction qty |
exec_fee | number | Transaction fee |
exec_value | number | Transaction value |
leaves_qty | number | Number of unfilled contracts from the order's size |
closed_size | number | The corresponding closing size of the closing order |
last_liquidity_ind | string | Only valid while exec_type is Trade , AdlTrade , BustTrade |
trade_time | number | Trade timestamp in seconds |
trade_time_ms | number | Trade timestamp in milliseconds |
Extended User Trade Records
Request Example
curl "https://api-testnet.bybit.com/private/linear/trade/execution/history-list?api_key={api_key}&symbol=BTCUSDT×tamp={timestamp}&sign={sign}"
from pybit import usdt_perpetual
session_auth = usdt_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com",
api_key="XXXXXXXXXXXX",
api_secret="XXXXXXXXXXXXXXXXXXXXXX"
)
print(session_auth.extended_user_trade_records(
symbol="BTCUSDT"
))
Response Example
{
"ret_code": 0,
"ret_msg": "OK",
"ext_code": "",
"ext_info": "",
"result": {
"page_token": "OVFyd2RLQ051UDhlZXNGa1RRNWEwM0FNWWZLdk9LVS95RnIzbThKa3EzUVJpc0ZiNGt2Z2NzdWxJb2h6QTZ3MHBZdmRnNlZSWFpKY0h3V1RpY0ZqcER5RlZNbGRjbGh4N2VYdXpZcUduZm9lWkFsNjFnVTJrLzdYSy9TNC9BcjhsRlRNY3NWM0x1MFdrQ05hSlFObW8yUjdpZXZyRHd3MWlvTzdmb0tWdmFwSEhqQUs0MG4wSXlsV1VZTlpWWVpla08vVGYzRWJEbVJhY2t0RmE3TDhKMCtuRnZ2ZDFuVmZQZXB6SWNGVitiZDlmSFNkazRZb1hlcXRPYzdLS040OGJVMnpER0Mzd1lFcURDTCs3SC9pRGl0UW9JZC9xSGZlNENUSW1hVHBGcUhSVlNVYzBRL3dtVVhmRXNTN2NkOHZGVGU5NThlWlRGZGp0UWxaWnhybzJmcis5UTZuYWpXTFBtVVYrQlo1VkVNPQ==",
"data": [
{
"order_id": "ad263e18-ce2f-4e7c-9077-5db8d2186051",
"order_link_id": "",
"side": "Sell",
"symbol": "BTCUSDT",
"exec_id": "43514fa8-8948-5649-9854-704bae563c16",
"price": 20284,
"order_price": 20284,
"order_qty": 0.32,
"order_type": "Market",
"fee_rate": 0.0006,
"exec_price": 21348.5,
"exec_type": "Trade",
"exec_qty": 0.32,
"exec_fee": 4.098912,
"exec_value": 6831.52,
"leaves_qty": 0,
"closed_size": 0.32,
"last_liquidity_ind": "RemovedLiquidity",
"trade_time": 1656316742,
"trade_time_ms": 1656316742722
}
]
},
"time_now": "1651078431.113746",
"rate_limit_status": 117,
"rate_limit_reset_ms": 1651078431074,
"rate_limit": 120
}
Get user's trading records. The results are ordered in descending order (the first item is the latest). Returns records up to 2 years old.
HTTP Request
GET
/private/linear/trade/execution/history-list
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
symbol | true | string | Symbol |
start_time | false | integer | Start timestamp point for result, in milliseconds. Timestamp must be within two years of the current date. For earlier records, please contact customer support |
end_time | false | integer | End timestamp point for result, in milliseconds. Timestamp must be within two years of the current date. For earlier records, please contact customer support |
exec_type | false | string | Execution type |
page_token | false | string | Page. By default, gets first page of data. If you want to get second page of data, you need to take the page_token returned by the first page as the input parameter. |
limit | false | integer | Limit for data size per page, max size is 100. Default as showing 100 pieces of data per page. |
Response Parameters
Parameter | Type | Comment |
---|---|---|
page_token | string | Page. By default, gets first page of data. If you want to get second page of data, you need to take the page_token returned by the first page as the input parameter. |
data | ArrayList | |
order_id | string | Order ID |
order_link_id | string | Unique user-set order ID. Maximum length of 36 characters |
side | string | Side |
symbol | string | Symbol |
exec_id | string | Transaction ID |
price | number | Order price |
order_price | number | Order price |
order_qty | number | Order qty |
order_type | string | Order type |
fee_rate | number | Maker or taker fee rate |
exec_price | number | Transaction price |
exec_type | string | Exec type |
exec_qty | number | Transaction qty |
exec_fee | number | Transaction fee |
exec_value | number | Transaction value |
leaves_qty | number | Number of unfilled contracts from the order's size |
closed_size | number | The corresponding closing size of the closing order |
last_liquidity_ind | string | Only valid while exec_type is Trade , AdlTrade , BustTrade |
trade_time | number | Trade timestamp in seconds |
trade_time_ms | number | Transaction timestamp |
Closed Profit and Loss
Request Example
curl https://api-testnet.bybit.com/private/linear/trade/closed-pnl/list?api_key={api_key}&symbol=BTCUSDT×tamp={timestamp}&sign={sign}
from pybit import usdt_perpetual
session_auth = usdt_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com",
api_key="XXXXXXXXXXXX",
api_secret="XXXXXXXXXXXXXXXXXXXXXX"
)
print(session_auth.closed_profit_and_loss(
symbol="BTCUSDT"
))
Response Example
{
"ret_code": 0,
"ret_msg": "OK",
"ext_code": "",
"ext_info": "",
"result": {
"current_page": 1,
"data": [
{
"id": 1710,
"user_id": 160815,
"symbol": "BTCUSDT",
"order_id": "e6a11e08-6dd0-404e-bea7-dc22b7ab0228",
"side": "Buy",
"qty": 0.5,
"order_price": 999999,
"order_type": "Market",
"exec_type": "Trade",
"closed_size": 0.5,
"cum_entry_value": 3000,
"avg_entry_price": 6000,
"cum_exit_value": 3000.5,
"avg_exit_price": 6001,
"closed_pnl": -5.000375,
"fill_count": 1,
"leverage": 100,
"created_at": 1577480599
}
]
},
"time_now": "1577480599.097287",
"rate_limit_status": 119,
"rate_limit_reset_ms": 1580885703683,
"rate_limit": 120
}
Get user's closed profit and loss records. The results are ordered in descending order (the first item is the latest).
HTTP Request
GET
/private/linear/trade/closed-pnl/list
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
symbol | true | string | Symbol |
start_time | false | int | Start timestamp point for result, in seconds |
end_time | false | int | End timestamp point for result, in seconds |
exec_type | false | string | Execution type (cannot be Funding ) |
page | false | integer | Page. By default, gets first page of data. Maximum of 50 pages |
limit | false | integer | Limit for data size per page, max size is 50. Default as showing 20 pieces of data per page. |
Response Parameters
Parameter | Type | Comment |
---|---|---|
id | number | PositionID |
user_id | number | UserID |
symbol | string | Symbol |
order_id | string | Order ID of the closing order |
side | string | Side of the closing order |
qty | number | Order qty |
order_price | number | Order price |
order_type | string | Order type |
exec_type | string | Exec type |
closed_size | number | Closed size |
cum_entry_value | number | Closed position value |
avg_entry_price | number | Average entry price |
cum_exit_value | number | Cumulative trading value of position closing orders |
avg_exit_price | number | Average exit price |
closed_pnl | number | Closed Profit and Loss |
fill_count | number | The number of fills in a single order |
leverage | number | In Isolated Margin mode, the value is set by 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 ) |
Risk Limit
Get Risk Limit
Request Example
curl "https://api-testnet.bybit.com/public/linear/risk-limit?symbol=BTCUSDT"
from pybit import usdt_perpetual
session_unauth = usdt_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com"
)
print(session_unauth.get_risk_limit(
symbol="BTCUSDT"
))
Response Example
{
"ret_code": 0,
"ret_msg": "OK",
"result": [
{
"id": 11,
"symbol": "ETHUSDT",
"limit": 900000,
"maintain_margin": 0.005,
"starting_margin": 0.01,
"section": [
"1",
"3",
"5",
"10",
"25",
"50",
"80"
],
"is_lowest_risk": 1,
"created_at": "",
"updated_at": "",
"max_leverage": 100
},
...
{
"id": 36,
"symbol": "ETHUSDT",
"limit": 50000000,
"maintain_margin": 0.13,
"starting_margin": 0.2,
"section": [
"1",
"2",
"3",
"4"
],
"is_lowest_risk": 0,
"created_at": "",
"updated_at": "",
"max_leverage": 5
}
],
"ext_code": "",
"ext_info": "",
"time_now": "1662629653.373425"
}
Get risk limit. This endpoint does not require authentication.
HTTP Request
GET
/public/linear/risk-limit
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
symbol | true | string | Symbol |
Response Parameters
Parameter | Type | Comment |
---|---|---|
id | number | Risk ID |
symbol | string | Symbol |
limit | number | Risk limit |
maintain_margin | number | Maintain margin |
starting_margin | number | Starting margin. 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/private/linear/position/set-risk \
-H "Content-Type: application/json" \
-d '{"api_key":"{api_key}","symbol":"BTCUSDT","risk_id":2,"timestamp":{timestamp},"sign":"{sign}"}'
from pybit import usdt_perpetual
session_auth = usdt_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com",
api_key="XXXXXXXXXXXX",
api_secret="XXXXXXXXXXXXXXXXXXXXXX"
)
print(session_auth.set_risk_limit(
symbol="BTCUSDT",
side="Buy",
risk_id=1
))
Response Example
{
"ret_code": 0,
"ret_msg": "OK",
"ext_code": "",
"ext_info": "",
"result": {
"risk_id": 2
},
"time_now": "1609839125.563609",
"rate_limit_status": 73,
"rate_limit_reset_ms": 1609839125560,
"rate_limit": 75
}
Set risk limit.
HTTP Request
POST
/private/linear/position/set-risk
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
symbol | true | string | Symbol |
side | true | string | Side |
risk_id | true | integer | Risk ID |
position_idx | false | 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 |
Response Parameters
Parameter | Type | Comment |
---|---|---|
risk_id | number | Risk ID |
Funding
Predicted Funding Rate and My Funding Fee
Request Example
curl "https://api-testnet.bybit.com/private/linear/funding/predicted-funding?api_key={api_key}&symbol=BTCUSDT×tamp={timestamp}&sign={sign}"
from pybit import usdt_perpetual
session_auth = usdt_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com",
api_key="XXXXXXXXXXXX",
api_secret="XXXXXXXXXXXXXXXXXXXXXX"
)
print(session_auth.predicted_funding_rate(
symbol="BTCUSDT"
))
Response Example
{
"ret_code": 0,
"ret_msg": "OK",
"ext_code": "",
"ext_info": "",
"result": {
"predicted_funding_rate": -0.00375,
"predicted_funding_fee": 0.13081256
},
"time_now": "1587035697.424492",
"rate_limit_status": 119,
"rate_limit_reset_ms": 1587035697422,
"rate_limit": 120
}
Get predicted funding rate and my predicted funding fee.
HTTP Request
GET
/private/linear/funding/predicted-funding
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
symbol | true | string | Symbol |
Response Parameters
Parameter | Type | Comment |
---|---|---|
predicted_funding_rate | number | Predicted funding rate |
predicted_funding_fee | number | Predicted funding fee |
My Last Funding Fee
Request Example
curl "https://api-testnet.bybit.com/private/linear/funding/prev-funding?api_key={api_key}&symbolt=BTCUSDT×tamp={timestamp}&sign={sign}"
from pybit import usdt_perpetual
session_auth = usdt_perpetual.HTTP(
endpoint="https://api-testnet.bybit.com",
api_key="XXXXXXXXXXXX",
api_secret="XXXXXXXXXXXXXXXXXXXXXX"
)
print(session_auth.my_last_funding_fee(
symbol="BTCUSDT"
))
Response Example
{
"ret_code": 0,
"ret_msg": "OK",
"ext_code": "",
"ext_info": "",
"result": {
"symbol": "BTCUSDT",
"side": "Buy",
"size": 3.13,
"funding_rate": 0.0001,
"exec_fee": 1.868923,
"exec_time": "2020-04-13T08:00:00.000Z"
},
"time_now": "1586780352.867171",
"rate_limit_status": 119,
"rate_limit_reset_ms": 1586780352864,
"rate_limit": 120
}
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
/private/linear/funding/prev-funding
Request Parameters
Parameter | Required | Type | Comment |
---|---|---|---|
symbol | true | string | Symbol |
Response Parameters
Parameter | Type | Comment |
---|---|---|
symbol | string | Symbol |
side | string | Your position side at the time of settlement |
size | number | Your position size at the time of settlement |
funding_rate | number | Funding rate |
exec_fee | number | Transaction fee |
exec_time | string | Transaction time |
API Key Info
Please see the shared endpoint.
LCP Info
Please see the shared endpoint.
Wallet Data Endpoints
The following wallet data endpoints require authentication.
Get Wallet Balance
Please see the shared endpoint.
Wallet Fund Records
Please see the shared endpoint.
Withdraw Records
Please see the shared endpoint.
Asset Exchange Records
Please see the shared endpoint.
API Data Endpoints
The following API data endpoints do not require authentication.
Server Time
Request Example
curl https://api-testnet.bybit.com/v2/public/time
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 | /private/linear/order/create | 1 / request |
/private/linear/order/replace | 1 / request | |
/private/linear/order/cancel | 1 / request | |
/private/linear/order/cancel-all | 10 / request | |
/private/linear/stop-order/create | 1 / request | |
/private/linear/stop-order/replace | 1 / request | |
/private/linear/stop-order/cancel | 1 / request | |
/private/linear/stop-order/cancel-all | 10 / request | |
75/min | /private/linear/position/set-leverage | 1 / request |
/private/linear/position/switch-isolated | 1 / request | |
/private/linear/tpsl/switch-mode | 1 / request | |
/private/linear/position/set-auto-add-margin | 1 / request | |
/private/linear/position/trading-stop | 1 / request | |
/private/linear/position/add-margin | 1 / request | |
120/min | /private/linear/position/list | 1 / request |
/private/linear/trade/closed-pnl/list | 1 / request | |
/private/linear/trade/execution/list | 1 / request | |
/private/linear/trade/execution/history-list | 1 / request | |
600/min | /private/linear/order/list | 1 / request |
/private/linear/order/search | 1 / request | |
/private/linear/stop-order/list | 1 / request | |
/private/linear/stop-order/search | 1 / request | |
120/min | /private/linear/funding/prev-funding | 1 / request |
/private/linear/funding/predicted-funding | 1 / request | |
120/min | /contract/v3/private/position/limit-info | 12 / 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 public: wss://stream-testnet.bybit.com/realtime_public
- Testnet private: wss://stream-testnet.bybit.com/realtime_private
- Mainnet public (both endpoints are available):
- wss://stream.bybit.com/realtime_public
- wss://stream.bytick.com/realtime_public
- Mainnet private (both endpoints are available):
- wss://stream.bybit.com/realtime_private
- wss://stream.bytick.com/realtime_private
Authentication examples are shown in the code block.
How to Send Heartbeat Packet
How to Send
ws.send('{"op":"ping"}');
Response Example
{
"success": true,
"ret_msg": "pong",
"conn_id": "036e5d21-804c-4447-a92d-b65a44d00700"
"request": {
"op": "ping",
"args": null
}
}
How to Subscribe to Topics
Understanding Websocket Filters
How to subscribe with a filter
// Subscribing to the trade data for ETHUSDT
ws.send('{"op":"subscribe","args":["trade.ETHUSDT"]}')
Subscribe with multiple filters
// Example: Subscribing to the trade data for BTCUSD and XRPUSD
ws.send('{"op":"subscribe","args":["trade.BTCUSDT","trade.XRPUSDT"]}')
After establishing the connection, one can subscribe to a new topic by sending a JSON request. The specific formats are as follows:
ws.send('{"op": "subscribe", "args": ["topic.filter"]}');
The topic
indicates the data you would like to receive whilst the filter
parses for the specific data you desire - for example, the symbol. The topic
is mandatory but the filter
is optional.
To subscribe to more than one topic, simply list multiple topics out, like so:
ws.send('{"op": "subscribe", "args": ["topic.filter", "topic.filter"]}');
Unsubscribing From Websocket Topics
How to unsubscribe with a filter
// Unsubscribing from the trade data for ETHUSDT
ws.send('{"op":"unsubscribe","args":["trade.ETHUSDT"]}')
You can dynamically subscribe and unsubscribe from topics (with or without filters) without websocket disconnection as follows:
ws.send('{"op": "unsubscribe", "args": ["topic.filter", "topic.filter"]}');
Intervals
Some topics are pushed at intervals. If the args
contain a millisecond param, such as 100ms
, this topic is pushed at intervals. Otherwise, it is pushed constantly.
Understanding Subscription Response
Subscription Response
{
"success": true,
"ret_msg": "",
"conn_id":"e0e10eee-4eff-4d21-881e-a0c55c25e2da"
"request": {
"op": "subscribe",
"args": [
"candle.BTCUSDT.1m"
]
}
}
Each subscription will have a response. You can determine whether the subscription is successful based on the response.
Public Topics
orderBookL2_25
How to Subscribe
ws.send('{"op": "subscribe", "args": ["orderBookL2_25.BTCUSDT"]}');
from time import sleep
from pybit import usdt_perpetual
ws_linear = usdt_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: ["BTCUSDT", "ETHUSDT"]
ws_linear.orderbook_25_stream(
handle_message, "XRPUSDT"
)
while True:
sleep(1)
Snapshot Response Example - format of the first response
{
"topic": "orderBookL2_25.BTCUSDT",
"type": "snapshot",
"data": {
"order_book":[
{
"price": "2999.00",
"symbol": "BTCUSDT",
"id": 29990000, // depreciated
"side": "Buy",
"size": 9
},
{
"price": "3001.00",
"symbol": "BTCUSDT",
"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.BTCUSDT",
"type": "delta",
"data": {
"delete": [
{
"price": "3001.00",
"symbol": "BTCUSDT",
"id": 30010000, // depreciated
"side": "Sell"
}
],
"update": [
{
"price": "2999.00",
"symbol": "BTCUSDT",
"id": 29990000, // depreciated
"side": "Buy",
"size": 8
}
],
"insert": [
{
"price": "2998.00",
"symbol": "BTCUSDT",
"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.BTCUSDT"]}');
from time import sleep
from pybit import usdt_perpetual
ws_linear = usdt_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: ["BTCUSDT", "ETHUSDT"]
ws_linear.orderbook_200_stream(
handle_message, "EOSUSDT"
)
while True:
sleep(1)
Snapshot Response Example - format of the first response
{
"topic": "orderBook_200.100ms.BTCUSDT",
"type": "snapshot",
"data": {
"order_book":[
{
"price": "2999.00",
"symbol": "BTCUSDT",
"id": 29990000, // depreciated
"side": "Buy",
"size": 9
},
{
"price": "3001.00",
"symbol": "BTCUSDT",
"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.BTCUSDT",
"type": "delta",
"data": {
"delete": [
{
"price": "3001.00",
"symbol": "BTCUSDT",
"id": 30010000, // depreciated
"side": "Sell"
}
],
"update": [
{
"price": "2999.00",
"symbol": "BTCUSDT",
"id": 29990000, // depreciated
"side": "Buy",
"size": 8
}
],
"insert": [
{
"price": "2998.00",
"symbol": "BTCUSDT",
"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.BTCUSDT"]}')
from time import sleep
from pybit import usdt_perpetual
ws_linear = usdt_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: ["BTCUSDT", "ETHUSDT"]
ws_linear.trade_stream(
handle_message, "EOSUSDT"
)
while True:
sleep(1)
Response Example - format of all responses
{
"topic": "trade.BTCUSDT",
"data": [
{
"symbol": "BTCUSDT",
"tick_direction": "PlusTick",
"price": "19163.50",
"size": 0.001,
"timestamp": "2022-09-08T08:21:10.000Z",
"trade_time_ms": "1662625270662",
"side": "Buy",
"trade_id": "1250f670-85e6-5ab7-bdd0-52e7a4d97111",
"is_block_trade": "false"
}
]
}
Push frequency: 100ms
Response Parameters
Parameter | Type | Comment |
---|---|---|
symbol | string | Symbol |
tick_direction | string | Direction of price change |
price | number | Order price |
size | number | Position qty |
timestamp | string | UTC time |
trade_time_ms | string | Millisecond timestamp |
side | string | Direction of taker |
trade_id | string | Trade ID |
is_block_trade | string | Is block trade |
instrumentInfo
How to Subscribe
ws.send('{"op": "subscribe", "args": ["instrument_info.100ms.BTCUSDT"]}')
from time import sleep
from pybit import usdt_perpetual
ws_linear = usdt_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: ["BTCUSDT", "ETHUSDT"]
ws_linear.instrument_info_stream(
handle_message, "BTCUSDT"
)
while True:
sleep(1)
Snapshot Response Example - format of the first response
{
"topic": "instrument_info.100ms.BTCUSDT",
"type": "snapshot",
"data": {
"id": 1,
"symbol": "BTCUSDT",
"last_price_e4": "322955000",
"last_price": "322955000",
"last_tick_direction": "ZeroPlusTick",
"prev_price_24h_e4": "331960000",
"prev_price_24h": "331960000",
"price_24h_pcnt_e6": "-27126",
"high_price_24h_e4": "333120000",
"high_price_24h": "333120000",
"low_price_24h_e4": "315940000",
"low_price_24h": "315940000",
"prev_price_1h_e4": "319490000",
"prev_price_1h": "319490000",
"price_1h_pcnt_e6": "10845",
"mark_price_e4": "323133000",
"mark_price": "323133000",
"index_price_e4": "323106800",
"index_price": "323106800",
"open_interest_e8": "1430451600000",
"total_turnover_e8": "5297934997553700000",
"turnover_24h_e8": "243143978993099700",
"total_volume_e8": "1184936057899924",
"volume_24h_e8": "7511238100000",
"funding_rate_e6": "100",
"predicted_funding_rate_e6": "-15",
"cross_seq": "6501157651",
"created_at": "1970-01-01T00:00:00.000Z",
"updated_at": "2021-07-14T09:32:10.000Z",
"next_funding_time": "2021-07-14T16:00:00Z",
"count_down_hour": 7,
"funding_rate_interval": 8,
"bid1_price_e4": "322950000",
"ask1_price_e4": "322955000"
"bid1_price": "322950000",
"ask1_price_e4": "322955000",
"ask1_price": "322955000",
},
"cross_seq": "6501157734",
"timestamp_e6": "1626255131908287"
}
Delta Response Example - format of the responses following the snapshot response
{
"topic": "instrument_info.100ms.BTCUSDT",
"type": "delta",
"data": {
"update": [
{
"id": 1,
"symbol": "BTCUSDT",
"last_price_e4": "322950000",
"last_price": "322950000",
"price_24h_pcnt_e6": "-27141",
"price_1h_pcnt_e6": "10829",
"index_price_e4": "323100000",
"index_price": "323100000",
"total_turnover_e8": "5297935000783200000",
"turnover_24h_e8": "243143982222599700",
"total_volume_e8": "1184936057999924",
"volume_24h_e8": "7511238200000",
"cross_seq": "6501157735",
"created_at": "1970-01-01T00:00:00.000Z",
"updated_at": "2021-07-14T09:32:12.000Z"
}
]
},
"cross_seq": "6501157736",
"timestamp_e6": "1626255132104671"
}
Get latest information for symbol.
Push frequency: 100ms
Response Parameters
Parameter | Type | Comment |
---|---|---|
symbol | string | Symbol |
last_price_e4 | string | (Deprecated) Latest transaction price 10^4 |
last_price | string | Latest transaction price |
last_tick_direction | string | Direction of price change |
prev_price_24h_e4 | string | (Deprecated) Price of 24 hours ago * 10^4 |
prev_price_24h | string | Price of 24 hours ago |
price_24h_pcnt_e6 | string | Percentage change of market price relative to 24h * 10^4 |
high_price_24h_e4 | string | (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 | string | (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 | string | (Deprecated) Hourly market price an hour ago * 10^4 |
prev_price_1h | string | Hourly market price an hour ago |
price_1h_pcnt_e6 | string | Percentage change of market price relative to 1 hour ago * 10^6 |
mark_price_e4 | string | (Deprecated) Mark price * 10^4 |
mark_price | string | Mark price |
index_price_e4 | string | (Deprecated) Index_price * 10^4 |
index_price | string | Index_price |
open_interest_e8 | string | Open interest * 10^8. The update is not immediate - slowest update is 1 minute |
total_turnover_e8 | string | Total turnover * 10^8 |
turnover_24h_e8 | string | Turnover for 24h * 10^8 |
total_volume_e8 | string | Total volume * 10^8 |
volume_24h_e8 | string | Trading volume in the last 24 hours * 10^8 |
funding_rate_e6 | string | Funding rate * 10^6 |
predicted_funding_rate_e6 | string | Predicted funding rate * 10^6 |
cross_seq | string | 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 | number | Countdown of settlement capital cost |
funding_rate_interval | number | funding rate time interval, unit hour |
bid1_price_e4 | string | (Deprecated) Best bid price * 10^4 |
ask1_price_e4 | string | (Deprecated) Best ask price * 10^4 |
bid1_price | string | Best bid price |
ask1_price | string | Best ask price |
kline
How to Subscribe
ws.send('{"op":"subscribe","args":["candle.1.BTCUSDT"]}')
from time import sleep
from pybit import usdt_perpetual
ws_linear = usdt_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: ["BTCUSDT", "ETHUSDT"]
# pass an interval
ws_linear.kline_stream(
handle_message, "DOTUSDT", "D"
)
while True:
sleep(1)
Response Example - format of all responses
{
"topic": "candle.1.BTCUSDT",
"data": [
{
"start": 1655956380,
"end": 1655956440,
"period": "1",
"open": 20261,
"close": 20257.5,
"high": 20261,
"low": 20256,
"volume": "25.396",
"turnover": "514491.9815",
"confirm": False,
"cross_seq": 13135807020,
"timestamp": 1655956431377798
}
],
"timestamp_e6": 1655956431377798
}
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 | string | Trading volume |
turnover | string | Turnover |
confirm | bool | Is confirm |
cross_seq | integer | Cross sequence (internal value) |
timestamp | integer | Data sent timestamp in seconds * 10^6 |
liquidation
How to Subscribe
ws.send('{"op":"subscribe","args":["liquidation.XRPUSDT"]}')
from time import sleep
from pybit import usdt_perpetual
ws_linear = usdt_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: ["BTCUSDT", "ETHUSDT"]
ws_linear.liquidation_stream(
handle_message, "DOTUSDT"
)
while True:
sleep(1)
Response Example - format of all responses
{
"topic":"liquidation.XRPUSDT",
"data": {
"symbol":"XRPUSDT",
"side":"Sell",
"price":"3384.15",
"qty":"0.057",
"time":1631608881954
}
}
Pushes liquidation orders.
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 |
time | number | Millisecond timestamp |
Private Topics
position
How to Subscribe
ws.send('{"op": "subscribe", "args": ["position"]}')
from time import sleep
from pybit import usdt_perpetual
ws_linear = usdt_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_linear.position_stream(
handle_message
)
while True:
sleep(1)
Response Example - format of all responses
{
"topic": "position",
"action": "update",
"data": [
{
"user_id": "533285",
"symbol": "BTCUSDT",
"size": 0.01,
"side": "Buy",
"position_value": 202.195,
"entry_price": 20219.5,
"liq_price": 0.5,
"bust_price": 0.5,
"leverage": 99,
"order_margin": 0,
"position_margin": 1959.6383,
"occ_closing_fee": 3e-06,
"take_profit": 25000,
"tp_trigger_by": "LastPrice",
"stop_loss": 18000,
"sl_trigger_by": "LastPrice",
"trailing_stop": 0,
"realised_pnl": -4.189762,
"auto_add_margin": "0",
"cum_realised_pnl": -13.640625,
"position_status": "Normal",
"position_id": "0",
"position_seq": "92962",
"adl_rank_indicator": "2",
"free_qty": 0.01,
"tp_sl_mode": "Full",
"risk_id": "1",
"isolated": false,
"mode": "BothSide",
"position_idx": "1"
}
]
}
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 | number | Position value |
entry_price | number | Average entry price |
liq_price | number | Liquidation price |
bust_price | number | Bankruptcy price |
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 |
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) |
take_profit | number | Take profit price |
tp_trigger_by | string | Take profit trigger price type, default: LastPrice
|
stop_loss | number | Stop loss price |
sl_trigger_by | string | Stop loss trigger price type, default: LastPrice
|
trailing_stop | number | Trailing stop (the distance from the current price) |
realised_pnl | number | Today's realised pnl |
auto_add_margin | number | Whether or not auto-margin replenishment is enabled |
cum_realised_pnl | number | Accumulated realised pnl (all-time total) |
position_status | string | Position status: Normal , Liq , Adl
|
position_seq | string | Position sequence |
free_qty | number | Qty which can be closed. (If you have a long position, free_qty is negative. vice versa) |
tp_sl_mode | string | TrailingProfit or StopLoss mode Full or Partial |
risk_id | string | Risk ID |
isolated | bool | true means isolated margin mode; false means cross margin mode |
mode | string | Position mode, MergedSingle or BothSide |
position_idx | string | 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 |
execution
How to Subscribe
ws.send('{"op": "subscribe", "args": ["execution"]}')
from time import sleep
from pybit import usdt_perpetual
ws_linear = usdt_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_linear.execution_stream(
handle_message
)
while True:
sleep(1)
Response Example - format of all responses
{
"topic": "execution",
"data": [
{
"symbol": "BTCUSDT",
"side": "Sell",
"order_id": "xxxxxxxx-xxxx-xxxx-9a8f-4a973eb5c418",
"exec_id": "xxxxxxxx-xxxx-xxxx-8b66-c3d2fcd352f6",
"order_link_id": "",
"price": 11527.5,
"order_qty": 0.001,
"exec_type": "Trade",
"exec_qty": 0.001,
"exec_fee": 0.00864563,
"leaves_qty": 0,
"is_maker": false,
"trade_time": "2020-08-12T21:16:18.142746Z"
}
]
}
Get user's trading records. The results are ordered in ascending order (the first item is the oldest). 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 | number | Transaction price |
order_qty | number | Order qty |
exec_type | string | Execution type (cannot be Funding ) |
exec_qty | number | Transaction qty |
exec_fee | number | Transaction fee |
leaves_qty | number | Number of unfilled contracts from the order's size |
is_maker | boolean | Is maker |
trade_time | string | Transaction timestamp |
order
How to Subscribe
ws.send('{"op": "subscribe", "args": ["order"]}')
from time import sleep
from pybit import usdt_perpetual
ws_linear = usdt_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_linear.order_stream(
handle_message
)
while True:
sleep(1)
Response Example - format of all responses
{
"topic": "order",
"action": "",
"data": [
{
"order_id": "19a8cbbe-e077-42c7-bdba-505c76619ea5",
"order_link_id": "Bactive004",
"symbol": "BTCUSDT",
"side": "Sell",
"order_type": "Market",
"price": 19185.5,
"qty": 0.01,
"leaves_qty": 0,
"last_exec_price": 20196,
"cum_exec_qty": 0.01,
"cum_exec_value": 201.95999,
"cum_exec_fee": 0.121176,
"time_in_force": "ImmediateOrCancel",
"create_type": "CreateByUser",
"cancel_type": "UNKNOWN",
"order_status": "Filled",
"take_profit": 0,
"stop_loss": 0,
"trailing_stop": 0,
"create_time": "2022-06-23T04:08:47.956636888Z",
"update_time": "2022-06-23T04:08:47.960908408Z",
"reduce_only": true,
"close_on_trigger": false,
"position_idx": "1"
}
]
}
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 | number | Order price |
qty | number | Transaction qty |
leaves_qty | number | Number of unfilled contracts from the order's size |
last_exec_price | number | Last execution price |
cum_exec_qty | number | Cumulative qty of trading |
cum_exec_value | string | Cumulative value of trading |
cum_exec_fee | string | Cumulative trading fees |
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 |
take_profit | number | Take profit price |
stop_loss | number | Stop loss price |
trailing_stop | number | Trailing stop (the distance from the current price) |
create_time | string | Timestamp (when the order_status was New ) |
update_time | string | Update time |
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. |
position_idx | string | 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
How to Subscribe
ws.send('{"op": "subscribe", "args": ["stop_order"]}')
from time import sleep
from pybit import usdt_perpetual
ws_linear = usdt_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_linear.stop_order_stream(
handle_message
)
while True:
sleep(1)
Response Example - format of all responses
{
"topic": "stop_order",
"data": [
{
"stop_order_id": "559bba2c-0152-4557-84f6-63dc6ab78463",
"order_link_id": "",
"user_id": "533285",
"symbol": "BTCUSDT",
"side": "Sell",
"order_type": "Market",
"price": 0,
"qty": 0.01,
"time_in_force": "ImmediateOrCancel",
"create_type": "CreateByTakeProfit",
"cancel_type": "UNKNOWN",
"order_status": "Untriggered",
"stop_order_type": "TakeProfit",
"tp_trigger_by": "UNKNOWN",
"trigger_price": 25000,
"create_time": "2022-06-23T04:06:55.402188346Z",
"update_time": "2022-06-23T04:08:47.960950878Z",
"reduce_only": true,
"close_on_trigger": true,
"position_idx": "1",
"take_profit": 0.65,
"stop_loss": 0.25
}
]
}
Response Parameters
Parameter | Type | Comment |
---|---|---|
stop_order_id | string | Conditional order ID. Once triggered, the conditional order creates an active order with the same ID (order_id ) |
order_link_id | string | Unique user-set order ID. Maximum length of 36 characters |
user_id | number | UserID |
symbol | string | Symbol |
side | string | Side |
order_type | string | Order type |
price | number | Order price |
qty | number | Order quantity in USD |
time_in_force | string | Time in force |
create_type | string | Trigger scenario for single action |
cancel_type | string | Trigger scenario for cancel operation |
order_status | string | Order status |
stop_order_type | string | Conditional order type |
tp_trigger_by | string | Trigger price type. Default LastPrice |
trigger_price | number | If stop_order_type is TrailingProfit , this field is the trailing stop active price. |
create_time | string | Timestamp (when the order_status was New ) |
update_time | string | Update time |
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. |
position_idx | string | 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 |
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 usdt_perpetual
ws_linear = usdt_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_linear.wallet_stream(
handle_message
)
while True:
sleep(1)
Response Example - format of all responses
{
"topic": "wallet",
"data": [
{
"wallet_balance":429.80713,
"available_balance":429.67322
}
]
}
Response Parameters
Parameter | Type | Comment |
---|---|---|
wallet_balance | number | Wallet balance |
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 |
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
)
BTCUSDT
ETHUSDT
- ...
You can get all symbols with the Query Symbol endpoint.
Currency (currency
/coin
)
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
Withdraw status (status
)
ToBeConfirmed
UnderReview
Pending
- Pending transferSuccess
CancelByUser
Reject
Expire
Order type (order_type
)
Limit
Market
Quantity (qty
)
BTCUSDT
- Maximum quantity of 100 for opening; Maximum quantity of 100 for closingETHUSDT
- Maximum quantity of 1000 for opening; Maximum quantity of 1000 for closingLINKUSDT
- Maximum quantity of 10000 for opening; Maximum quantity of 10000 for closingLTCUSDT
- Maximum quantity of 2000 for opening; Maximum quantity of 2000 for closingXTZUSDT
- Maximum quantity of 20000 for opening; Maximum quantity of 20000 for closingBCHUSDT
- Maximum quantity of 600 for opening; Maximum quantity of 600 for closingADAUSDT
- Maximum quantity of 24000 for opening; Maximum quantity of 24000 for closingDOTUSDT
- Maximum quantity of 15000 for opening; Maximum quantity of 15000 for closingUNIUSDT
- Maximum quantity of 10000 for opening; Maximum quantity of 10000 for closingXRPUSDT
- Maximum quantity of 1000000 for opening; Maximum quantity of 1000000 for closingXEMUSDT
- Maximum quantity of 250000 for opening; Maximum quantity of 250000 for closingSUSHIUSDT
- Maximum quantity of 10000 for opening; Maximum quantity of 10000 for closingAAVEUSDT
- Maximum quantity of 500 for opening; Maximum quantity of 500 for closingDOGEUSDT
- Maximum quantity of 200000 for opening; Maximum quantity of 200000 for closingMATICUSDT
- Maximum quantity of 70000 for opening; Maximum quantity of 70000 for closingEOSUSDT
- Maximum quantity of 50000 for opening; Maximum quantity of 50000 for closingETCUSDT
- Maximum quantity of 2000 for opening; Maximum quantity of 2000 for closingBNBUSDT
- Maximum quantity of 1500 for opening; Maximum quantity of 1500 for closingFILUSDT
- Maximum quantity of 2000 for opening; Maximum quantity of 2000 for closingSOLUSDT
- Maximum quantity of 3000 for opening; Maximum quantity of 3000 for closing
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
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.