All notable changes to this project will be documented in this file.
The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.
all_liquidation_streamWebSocket topic.- Batch WebSocket order methods:
place_batch_order,amend_batch_order,cancel_batch_order - HTTP API methods for Convert, Earn, and Crypto Loan.
- Renamed the arg
callback_functionin the WebSocket class to_callback_functionas it's intended to be private and is not useful to the user. This is not thecallback_functionarg you pass when subscribing to a WebSocket topic. (https://github.com/bybit-exchange/pybit/issues/270) - Allow passing
Noneas a value to an HTTP request, which results in the parameter being removed the final request sent.
liquidation_streamWebSocket topic.
Thanks goes to Kamsby, kolya5544, and LordGhostX for contributing to this release.
- Add
fast_execution_streamWebSocket - Add
tldarg to WebSocket. TLD stands for top-level domain. - Add
delete_sub_uidandget_all_sub_api_keys– user-related HTTP endpoints - Add
spot_margin_trade_get_historical_interest_rate– a spot margin HTTP endpoint - Add
add_or_reduce_margin– a position HTTP endpoint - Add
get_transferable_amount– an account-related HTTP endpoint to complementget_wallet_balance - Add
get_exchange_broker_earnings(see Deprecated)
get_broker_earningsHTTP endpoint. Instead useget_exchange_broker_earnings.
- All modules under the
legacysubpackage. All these APIs are offline by this point and their functionality is covered by the V5 API / Unified Trading Account.
- WebSocket Trading support
- Add
get_contract_transaction_log
- Demo Trading support
- Add methods for the Institutional Loan endpoints
- Add Account methods
repay_liability(),set_collateral_coin(),batch_set_collateral_coin() tldarg for users in The Netherlands and Hong Kong forHTTPsessions
- Options WebSocket failing to maintain connection (bybit-exchange#164)
- Improved the IP rate limit error message to indicate that an HTTP status code 403 may also mean that the IP address was identified as being from the USA – all requests from USA IPs are banned by Bybit.
- Add RSA authentication for HTTP and WebSocket (choose "Self-generated API Keys" when creating an API key)
- Add the
HTTPmethodget_server_time() - Add
HTTPmethods for spot margin trading - Add
HTTPmethodget_long_short_ratio() - Add optional
private_auth_expirearg for WebSocket (bybit-exchange#154)
- The
HTTPmethodenable_universal_transfer_for_sub_uid()
- Improve
close_positionlogic
helpers.pywhich includes theHelpersclass and theclose_positionmethod, which can be imported and employed like so:
from pybit.helpers import Helpers
my_helper = Helpers(session) # your HTTP session object (eg, from pybit.unified_trading import HTTP)
print(my_helper.close_position(category="linear", symbol="BTCUSDT"))- The following new endpoints to
unified_trading:get_broker_earningsget_announcementget_pre_upgrade_order_historyget_pre_upgrade_trade_historyget_pre_upgrade_closed_pnlget_pre_upgrade_transaction_logget_pre_upgrade_option_delivery_recordget_pre_upgrade_usdc_session_settlementget_affiliate_user_infoget_uid_wallet_type
- Multiple symbol support for WebSocket topics (pass
symbolas a list) - Extra logging (log response headers) when passing
log_requests=True - Argument
return_response_headersforHTTPto allow returning the response headers to the user
- Add response headers to exceptions
- Update PyPI package's python version so that only =>3.9 is supported to prevent the error:
TypeError: 'type' object is not subscriptable - Fix API rate limit handling
- Remove unnecessary
printstatements in two methods
- New asset endpoints:
set_deposit_account(),get_internal_deposit_records(),get_withdrawable_amount()
- Ensure that
legacysubmodule is packaged bysetup.py - Fix non-UTA (normal account) spot margin trading endpoints
- Fix wrong request method for
set_dcp()
- HTTP endpoints to the
copy_tradingmodule
- Docstrings in the
copy_tradingmodule to make it easier to find the API documentation for reference - Example files
ticker_streammethod in theunified_tradingmodule, which was subscribing to the wrong WebSocket topic
This version upgrades pybit to Bybit's version 5 (v5) APIs. It supports both Unified Trading Accounts (UTA) and non-UTA accounts. Bybit is not expected to develop any more major API versions in the future, so Bybit's v5 API (and subsequently, pybit's 5.0.0) is expected to be supported in the long-term.
See the examples folder for examples on how to interact with the latest modules.
- Bybit's v5 HTTP and WebSocket APIs in the
unified_tradingmodule. See what markets All-In-One V5 API supports in the upgrade guide.
- Non-v5 modules like
copy_trading,usdc_options, andusdc_perpetualsto continue to work from alegacysubpackage. Import like so:from pybit.legacy.copy_trading import HTTP. These modules are maintained because they are currently not supported by the v5 API; see the upgrade guide.
- Various legacy modules which have been superseded by the v5 API via the
unified_tradingmodule
- Tests for V5 endpoints
copy_tradingmodule for the Copy Trading HTTP API and WebSocket
requirements.txtto require the latest version ofwebsocket-client:1.5.0.- If you are facing any problems with the WebSocket, ensure you upgrade to the right version of the dependency and try again. Upgrade like so:
python -m pip install -r requirements.txt
- If you are facing any problems with the WebSocket, ensure you upgrade to the right version of the dependency and try again. Upgrade like so:
- WebSocket pings (again)
- How WebSocket pings are sent in an effort to keep connections open longer
- Failure to resubscribe to private spot topics when reconnecting WebSocket
- WebSocket error handling
- Failure to pass request parameters in certain methods
- Wrong endpoint paths in
spot
- Refactored WebSocket's
testarg totestnet - Hardcoded WebSocket arguments into the child class the user accesses – meaning the user can easily see them, and IDEs should autocomplete them
- (For v3 WebSockets only:
contract,unified_margin,spot)
- (For v3 WebSockets only:
This version upgrades pybit to Bybit's version 3 (v3) APIs. Some old API modules are maintained due to lack of or only partial support in v3. Method names have been improved and conform to an intuitive standard.
Future modules will be removed as Bybit's APIs are further unified so that they may be accessible from just one or two modules which should generally be divided by account type (eg, unified margin) rather than by market type (eg USDT perpetual).
This is a pre-release, as indicated by the rc (release candidate) in the version number. Future versions may have breaking changes. An imminent major version of the Bybit API will introduce major changes before these v3 APIs make it to the production version.
- Bybit's main v3 HTTP and WebSocket APIs:
contract– inverse perpetuals, inverse futures, USDT perpetuals, and USDC optionsunified_margin– USDT perpetuals and USDC options
spotto use v3 HTTP API and WebSocket APIsaccount_assetto use v3 HTTP API
usdt_perpetualbecause it is now accessible viacontractandunified_margin
is_connected()and the WebSocket reconnection logic.
- See below release candidates for further changes.
- Wrong endpoint path in
usdc_perpetual.py - Wrong endpoint path in
account_asset.py
- USDC API's timestamp parameter
- The way in which the WebSocket handles errors, improving general usage and debugging (tracebacks) as well as clearly defining under which errors should the WebSocket attempt reconnection.
- USDC API's timestamp parameter to avoid the occasional ret_msg: error sign!
HTTPmethods for account asset's universal transfer API
- USDC API to use the user's set
recv_window
- Did some internal code reorganisation
- The
ping_intervalto 20 seconds to ensure WebSocket connection stability
HTTPmethods for the spot API's Leveraged Token and Cross Margin endpointsagentSourceparameter when sending requests to place spot orders, which uses thereferral_idargument, so that affiliates can track orders
- There was a packaging problem with the previous version. There are no changes compared with 2.2.2.
- See below release candidates for further changes. TLDR: Improved WebSocket stability and reconnection logic.
retriesargument so that users specify how many times the WebSocket tries to reconnect upon disconnection- The default is
10. To retry forever, set it to0. pybit will wait 1 second between each retry.
- The default is
- Improved the logging around WebSocket disconnection
- WebSocket topic resubscription so that when a WebSocket connection is dropped and then reconnected it should resume pushing the same data as before. Essentially, completes the expected functionality of reconnecting to the WebSocket.
is_connected()function to work with modules that utilise >1 WebSocket connections
is_connected()function toWebSocketclass so that you can check if your WebSocket connection is alive
- Bug where, upon WebSocket disconnection, pybit rapidly tries to re-establish the connection, which results in being banned by the CDN for malicious activity
- Improved HTTP error handling and logging to ease troubleshooting
usdt_perpetual->get_risk_limit()to not require authentication
usdt_perpetual->add_reduce_margin()to use the correct request method
- USDC options
WebSocketandHTTPclasses - Deposit/withdrawal endpoints to
account_assetmodule
- Initiating a WebSocket object without an
api_keyorapi_secretfor objects that create multiple WebSocket connections - Error thrown when processing WebSocket orderbook
- USDC perpetual
WebSocketandHTTPclasses - USDT perpetual
extended_user_trade_records()method
- Expose all WebSocket arguments to users (fixing the previous "wonky and unintuitive" implementation by simplifying the inheritance design)
- See below release candidates for details.
- Added arg (
trace_logging) to enable websocket-client's trace logging, which reveals extra debug information regarding the websocket connection, including the raw sent & received messages- Note: the code implementation is a little wonky and unintuitive, and will be refined as much as possible before the proper release - although the functionality will remain the same.
- The processing of
instrument_infoWebSocket messages so that the user receive a"type": "snapshot"every time, rather than having to do their own delta/snapshot processing - Fix
AttributeError: '_FuturesWebSocketManager' object has no attribute 'endpoint'when attempting reconnect
record_request_timearg toHTTPclasses which, if true, returns the response dictionary in a tuple with the request elapsed time - as recorded byrequests
websocket_example.pyto demonstrate callbacks clearly- the license to reflect the transition to bybit-exchange
JSONDecodeErrorwhen trying to subscribe to a spot private WebSocket stream
- New modules for each API as part of a restructuring effort:
inverse_perpetual.py,usdt_perpetual.py,spot.py, and more- see the README for how to import these new modules
HTTPandWebSocketclasses within each applicable module- These classes use inheritance to reflect the structure of the Bybit APIs - due to the division of endpoints along the lines of different market types
- This means that different classes can share their common endpoints, such as
api_key_info(), whilst keeping their distinctive endpoints likeget_active_order()separate
WebSocketfunctionality to use callbacks instead of polling- This means that instead of polling
ws.fetch()for your latest WebSocket messages, you can now simply define a function (my_callback_function), and pass this as an argument upon subscribing to your chosen topic- see the example file for more information
- This also removes the need to remember topic names and JSON formats, as you now directly call a class method to subscribe
- There is also a
custom_topic_streammethod which can be used if a new WebSocket topic has been released by Bybit, but it's not been added topybityet
- This means that instead of polling
HTTPclasses will now instantiate a new HTTP session for each API (Spot (spot.HTTP), Account Asset (account_asset.HTTP), etc)- this is due to the restructuring of
pybitto use class inheritance
- this is due to the restructuring of
- Generally, the restructuring has allowed a great amount of segregation of the internal code to occur, which will allow for easier future development
- The
WebSocketclass from the__init__.pyfile, which was imported like so:from pybit import WebSocket- This is because of the aforementioned functionality changes, which also have the potential to improve performance (as a core no longer needs to be occupied polling
ws.fetch())
- This is because of the aforementioned functionality changes, which also have the potential to improve performance (as a core no longer needs to be occupied polling
- However, the
HTTPclass was not removed from__init__.pyin an effort to provide a unified alternative- Despite this, we would recommend preferring the market-specific modules
- Added
query_trading_fee_rate()
position_mode_switch()to support USDT perp:/private/linear/position/switch-mode
endpointarg toget_active_order()
- A WebSocket test case, by raising an exception instead of logging
- Improve
get_risk_limit()- Fixed: call this endpoint without authentication
- Supported
endpointargument formy_position(), allowing the user to call this method without supplying a symbolsymbolis not a required parameter for these endpoints, but pybit typically relies on it for deciding which endpoint to call
- Enabled WebSocket
fetch()to handle multiple position sides from linear perp symbols - Fixed
fetch()for private spot WebSocket - Supported
endpointargument formy_position(), allowing the user to call this method without supplying a symbolsymbolis not a required parameter for these endpoints, but pybit typically relies on it for deciding which endpoint to call
- See below release candidates for details.
- Alter the spot endpoint paths used for
get_active_order()andquery_active_order()
- Fixed failure to load subscriptions when provided in as JSON strings
- Fixed the spot auth WebSocket to ensure subscriptions are not required
- Fixed methods like
query_symbol()(which have no API parameters) not working following the spot update
- Implemented the Spot API in
HTTP - Implemented the Account Asset API in
HTTP - Implemented the Spot WebSocket in
WebSocket
- Removed
position_mode_switch()as the endpoint has not been released to mainnet yet
- Added new
HTTPmethods for new endpoints - Added new paths for existing methods
- Fixed some old paths
is_linearargument inget_risk_limit()
- Added some logic to decide if there is 'order_book' in order book snapshot push for WebSocket
- Added
ignore_codesargument toHTTPfor status codes to not raise any errors on.
- Removed extra suffix definition block in
place_conditional_order. - Changed logger functionality so that it won't overwrite user's preferred logging settings.
- Fixed wrong number of arguments error inside WebSocket
on_message,on_close,on_open,on_error.
- Fixed typo errors on endpoint urls.
- Added support for futures endpoints on
HTTP(usingisdigitto detect futures symbols).
- Using
getmethod fordictfor symbol check instead of calling by key. endpointonHTTPwill now default to https://api.bybit.com if no argument.retry_codesis now user-definable in theHTTParguments.- All logging is now on
DEBUGlevel—user will need to manually setlogging_leveltoDEBUG. - Added attempted request to
FailedRequestErrorandInvalidRequestErrorfor improved error logging.
- Fixed unexpected
tuplegeneration for status codes onInvalidRequestErrorandFailedRequestError. - Fixed how
Websockethandles incomingorderBookdata due to Bybit's topic naming changes.
requestswill useJSONDecodeErrorfromsimplejsonif it is available—pybitwill now do the same to prevent errors.- Fixed a bug where
HTTPretry would crash on rate limit reached due to undefined variable. - Improved
InvalidRequestErrorandFailedRequestErrorto include error codes and times.
WebSocketwill now temporarily differentiate between inverse and linear endpoints for the 'order' topic since incoming data has differing keys.
WebSocketnow haspurge_on_fetch(defaults toTrue), which allows the user to keep data between fetches.
- Fixed a bug on 'stop_order' for
WebSocketthat would prevent data from being appended due to deprecation ofstop_order_id.
- See release candidates for details.
- Rewrote if-condition on
_on_messageinWebSocketclass to check for linear or non-linear position data.
- Added ability to handle
fromusingfrom_timeandfrom_idarguments sincefromis a reserved keyword. - Removed
ignore_retries_forfromHTTP.pybitnow uses a standard list of non-critical errors that can be retried. - Added argument
retry_delayforHTTP—allows user to add a custom retry delay for each retry.
- See release candidates for details.
- Fixed raise error missing argument for
FailedRequestErrorupon max retries. - Modified API endpoints to saistfy requirements for upcoming endpoint deprecation, see the API Documentation for more info.
- Updated
WebSocketclass to properly handlecandlefrom USDT perpetual streams. - Updated
WebSocketclass to return a copy of the collected data, preventing establishing a reference. - Updated
WebSocketclass to properly handle linear (USDT) orderbook data. - Performance improvements.
- Changed
ignore_retries_fordefault argument to be empty tuple to prevent error.
- Added
ignore_retries_forargument toHTTPauthmethod, allowing the user to choose which error codes should NOT be retried.
FailedRequestErrorandInvalidRequestErrornow havemessageandstatus_codeattributes.
- Will now catch and handle
requests.exceptions.ConnectionError.
- Added
recv_windowerror handler toHTTPauthmethod. - Will now catch and handle
requests.exceptions.SSLError.
- Added
recv_windowargument toHTTPclass.
- Improved error handling.
- Added
max_retriesargument toHTTPclass.
- Added
FailedRequestErrorto differentiate between failed requests and invalid requests. - Fixed
exitmethod onWebSocketto now properly handle the closing of the socket.
- Increased expires time for WebSocket authentication to a full second.
- Add option to handle timeout on request submission.
- Fixed trailing decimal zero to prevent auth signature errors.
- New
HTTPmethods. - New argument for
HTTPclass to log each outgoing request. - New argument for
WebSocketclass to attempt restart after an error is detected.
- Mass simplification of all methods—each method now takes a series keyword arguments rather than a set number of required pre-defined arguments. This makes the library future-proof and prevents breaking on significant updates to the REST API endpoints. This, however, requires the user to study the API documentation and know which arguments are required for each endpoint.
- One new exception has been added—
InvalidRequestError. This exception will be raised if Bybit returns with an error, or ifrequestsis unable to complete the request. - Inverse and Linear endpoints are now handled accordingly by differentiating from the symbol argument.
- Updated existing
HTTPmethod names to follow the same naming procedure as listed in the Bybit API documentation. - Reformatting of code to follow PEP-8 standards.
- New docstring format.
- Various logging features added to both HTTP and WebSocket classes.
- Extensive WebSocket class updates.
- Modified the WebSocketApp to send a heartbeat packet every 30 seconds, with a timeout of 10 seconds. These settings can be modified using the 'ping_interval' and 'ping_timeout' arguments of the WebSocket constructor.
- User no longer needs to manage the incoming stream;
pybitdoes all the work (insert, update, delete). - Modified
ws.ping()for ease of use; simply use the function to send heartbeat packets. When something happens to the connection, Python will raise anExceptionwhich the end-user can catch and handle.
- Redundancy updates to the HTTP class.
- Modified the HTTP class to use an endpoint argument, allowing users to take advantage of the USDT endpoints.
- The setup.py file has been fixed to correctly install the pybit package.
- The
pybitmodule. - MANIFEST, README, LICENSE, and CHANGELOG files.