├── .github └── workflows │ ├── pythonpackage.yml │ └── release.yaml ├── .gitignore ├── CHANGELOG.md ├── LICENSE.md ├── MANIFEST.in ├── README.md ├── binance ├── __init__.py ├── __version__.py ├── api.py ├── cm_futures │ ├── __init__.py │ ├── account.py │ ├── data_stream.py │ └── market.py ├── error.py ├── lib │ ├── __init__.py │ ├── authentication.py │ └── utils.py ├── um_futures │ ├── __init__.py │ ├── account.py │ ├── convert.py │ ├── data_stream.py │ └── market.py └── websocket │ ├── __init__.py │ ├── binance_socket_manager.py │ ├── cm_futures │ ├── __init__.py │ └── websocket_client.py │ ├── um_futures │ ├── __init__.py │ └── websocket_client.py │ └── websocket_client.py ├── examples ├── cm_futures │ ├── market │ │ ├── agg_trades.py │ │ ├── basis.py │ │ ├── book_ticker.py │ │ ├── continuous_klines.py │ │ ├── depth.py │ │ ├── exchange_info.py │ │ ├── funding_rate.py │ │ ├── historical_trades.py │ │ ├── index_price_kline.py │ │ ├── klines.py │ │ ├── mark_price.py │ │ ├── mark_price_klines.py │ │ ├── open_interest.py │ │ ├── open_interest_hist.py │ │ ├── ping.py │ │ ├── query_index_price_constituents.py │ │ ├── taker_long_short_ratio.py │ │ ├── ticker_24hr_price_change.py │ │ ├── ticker_price.py │ │ ├── time.py │ │ ├── top_long_short_account_ratio.py │ │ ├── top_long_short_position_ratio.py │ │ └── trades.py │ ├── stream │ │ ├── close_listen_key.py │ │ ├── new_listen_key.py │ │ └── renew_listen_key.py │ └── trade │ │ ├── cancel_batch_orders.py │ │ ├── cancel_open_orders.py │ │ ├── cancel_order.py │ │ ├── change_leverage.py │ │ ├── change_margin_type.py │ │ ├── change_position_mode.py │ │ ├── countdown_cancel_order.py │ │ ├── get_account.py │ │ ├── get_account_trades.py │ │ ├── get_adl_quantile.py │ │ ├── get_all_orders.py │ │ ├── get_balance.py │ │ ├── get_commission_rate.py │ │ ├── get_download_id_transaction_history.py │ │ ├── get_force_orders.py │ │ ├── get_income_history.py │ │ ├── get_leverage_brackets.py │ │ ├── get_open_orders.py │ │ ├── get_order.py │ │ ├── get_order_modify_history.py │ │ ├── get_position_margin_history.py │ │ ├── get_position_mode.py │ │ ├── get_position_risk.py │ │ ├── modify_batch_order.py │ │ ├── modify_isolated_position_margin.py │ │ ├── modify_order.py │ │ ├── new_batch_order.py │ │ ├── new_order.py │ │ └── query_order.py ├── um_futures │ ├── convert │ │ ├── accept_offered_quote.py │ │ ├── list_all_convert_pairs.py │ │ ├── order_status.py │ │ └── send_quote_request.py │ ├── market │ │ ├── agg_trades.py │ │ ├── asset_index.py │ │ ├── blvt_kline.py │ │ ├── book_ticker.py │ │ ├── continuous_klines.py │ │ ├── depth.py │ │ ├── exchange_info.py │ │ ├── funding_info.py │ │ ├── funding_rate.py │ │ ├── historical_trades.py │ │ ├── index_info.py │ │ ├── index_price_constituents.py │ │ ├── index_price_kline.py │ │ ├── klines.py │ │ ├── mark_price.py │ │ ├── mark_price_klines.py │ │ ├── open_interest.py │ │ ├── open_interest_hist.py │ │ ├── ping.py │ │ ├── quarterly_contract_settlement_price.py │ │ ├── taker_long_short_ratio.py │ │ ├── ticker_24hr_price_change.py │ │ ├── ticker_price.py │ │ ├── time.py │ │ ├── top_long_short_account_ratio.py │ │ ├── top_long_short_position_ratio.py │ │ └── trades.py │ ├── stream │ │ ├── close_listen_key.py │ │ ├── new_listen_key.py │ │ └── renew_listen_key.py │ └── trade │ │ ├── async_download_order_id.py │ │ ├── async_download_trade_id.py │ │ ├── aysnc_download_info.py │ │ ├── cancel_batch_orders.py │ │ ├── cancel_open_orders.py │ │ ├── cancel_order.py │ │ ├── change_leverage.py │ │ ├── change_margin_type.py │ │ ├── change_multi_asset_mode.py │ │ ├── change_position_mode.py │ │ ├── countdown_cancel_order.py │ │ ├── download_order_asyn.py │ │ ├── download_trade_asyn.py │ │ ├── download_transactions_asyn.py │ │ ├── futures_account_configuration.py │ │ ├── get_account.py │ │ ├── get_account_trades.py │ │ ├── get_adl_quantile.py │ │ ├── get_all_orders.py │ │ ├── get_api_trading_status.py │ │ ├── get_balance.py │ │ ├── get_bnb_burn.py │ │ ├── get_commission_rate.py │ │ ├── get_force_orders.py │ │ ├── get_income_history.py │ │ ├── get_leverage_brackets.py │ │ ├── get_multi_asset_mode.py │ │ ├── get_open_orders.py │ │ ├── get_orders.py │ │ ├── get_position_margin_history.py │ │ ├── get_position_mode.py │ │ ├── get_position_risk.py │ │ ├── modify_isolated_position_margin.py │ │ ├── modify_order.py │ │ ├── new_batch_order.py │ │ ├── new_order.py │ │ ├── new_order_testing.py │ │ ├── query_order.py │ │ ├── query_user_rate_limit.py │ │ ├── symbol_configuration.py │ │ └── toggle_bnb_burn.py └── websocket │ ├── cm_futures │ ├── agg_trade.py │ ├── book_ticker.py │ ├── combined_streams.py │ ├── continuous_klines.py │ ├── diff_book_depth.py │ ├── index_kline.py │ ├── index_price.py │ ├── kline.py │ ├── liquidation_order.py │ ├── mark_kline.py │ ├── mark_price.py │ ├── mini_ticker.py │ ├── pair_mark_price.py │ ├── partial_book_depth.py │ ├── ticker.py │ └── user_data.py │ └── um_futures │ ├── agg_trade.py │ ├── book_ticker.py │ ├── combined_streams.py │ ├── composite_index.py │ ├── continuous_klines.py │ ├── diff_book_depth.py │ ├── kline.py │ ├── liquidation_order.py │ ├── mark_price.py │ ├── mark_price_all_market.py │ ├── mini_ticker.py │ ├── partial_book_depth.py │ ├── symbol_kline.py │ ├── ticker.py │ └── user_data.py ├── requirements ├── common.txt ├── requirements-dev.txt ├── requirements-test.txt └── requirements.txt ├── setup.cfg ├── setup.py └── tox.ini /.github/workflows/pythonpackage.yml: -------------------------------------------------------------------------------- 1 | name: Python package 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | pull_request: 8 | branches: 9 | - main 10 | - rc-** 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | strategy: 17 | matrix: 18 | python-version: ["3.9", "3.10", "3.11", "3.12"] 19 | 20 | steps: 21 | - uses: actions/checkout@v2 22 | - name: Set up Python ${{ matrix.python-version }} 23 | uses: actions/setup-python@v1 24 | with: 25 | python-version: ${{ matrix.python-version }} 26 | - name: Install dependencies 27 | run: | 28 | python -m pip install --upgrade pip 29 | pip install -r requirements/requirements-test.txt 30 | - name: Run black to review standard code format 31 | run: | 32 | # Checks if need to reformat files 33 | black --check --diff . 34 | - name: Run flake8 to check specific rules not covered by black 35 | run: | 36 | flake8 . --statistics -------------------------------------------------------------------------------- /.github/workflows/release.yaml: -------------------------------------------------------------------------------- 1 | name: Release Distributables 2 | 3 | on: 4 | release: 5 | types: 6 | - published 7 | 8 | jobs: 9 | build-n-upload: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: actions/checkout@v2 13 | - uses: actions/setup-python@v2 14 | with: 15 | python-version: "3.10" 16 | - run: pip install wheel 17 | - name: Build new distributables 18 | run: python setup.py sdist bdist_wheel 19 | - name: Upload distributables to PyPI 20 | uses: pypa/gh-action-pypi-publish@release/v1 21 | with: 22 | user: __token__ 23 | password: ${{ secrets.PYPI_API_TOKEN }} 24 | - name: Post release cleaning 25 | run: | 26 | python setup.py clean --all 27 | rm dist/* -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | build 2 | dist 3 | binance_connector.egg-info/ 4 | __pycache__ 5 | *.pyc 6 | .tox 7 | .python-version 8 | .DS_Store 9 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | ## 4.1.0 - 2024-10-31 4 | 5 | ### Added 6 | - UM_Futures: 7 | - `GET /fapi/v1/fundingInfo` 8 | - `GET /futures/data/delivery-price` 9 | - `GET /fapi/v1/constituents` 10 | - `GET /fapi/v1/accountConfig` 11 | - `GET /fapi/v1/symbolConfig` 12 | - `GET /fapi/v1/rateLimit/order` 13 | - `GET /fapi/v1/order/asyn` 14 | - `GET /fapi/v1/order/asyn/id` 15 | - `GET /fapi/v1/trade/asyn` 16 | - `GET /fapi/v1/trade/asyn/id` 17 | - `POST /fapi/v1/feeBurn` 18 | - `GET /fapi/v1/feeBurn` 19 | - `GET /fapi/v1/convert/exchangeInfo` 20 | - `POST /fapi/v1/convert/getQuote` 21 | - `POST /fapi/v1/convert/acceptQuote` 22 | - `GET /fapi/v1/convert/orderStatus` 23 | - Websocket Stream `mark_price_all_market` 24 | 25 | - CM_Futures: 26 | - `GET /dapi/v1/income/asyn` 27 | - `GET /dapi/v1/constituents` 28 | 29 | ### Changed 30 | - UM_Futures: 31 | - `GET /fapi/v1/income`: Add parameter `page` for pagination 32 | - `POST /fapi/v1/order`: Add parameters `selfTradePreventionMode`, `priceMatch` and `goodTillDate` 33 | - `POST /fapi/v1/batchOrders`: Add parameters `priceMatch`, `selfTradePreventionMode` and `goodTillDate` 34 | - `GET /fapi/v1/ticker/price`: deprecated, replaced by `GET /fapi/v2/ticker/price` 35 | - `GET /fapi/v2/balance`: deprecated, replaced by `GET /fapi/v3/balance` 36 | - `GET /fapi/v2/account`: deprecated, replaced by `GET /fapi/v3/account` 37 | - `GET /fapi/v2/positionRisk`: deprecated, replaced by `GET /fapi/v3/positionRisk` 38 | 39 | - CM_Futures: 40 | - `GET /dapi/v1/income`: Add parameter `page` for pagination 41 | - `POST /dapi/v1/order`: Add parameters `priceMatch` and `selfTradePreventionMode` 42 | 43 | - Update Websocket connection exceptions: Add `_handle_exception` method to handle exceptions 44 | 45 | ### Removed 46 | - CM_Futures: 47 | - `/dapi/v1/pmExchangeInfo` 48 | 49 | ## 4.0.1 - 2024-10-03 50 | 51 | ### Removed 52 | - UM_Futures: 53 | - `GET /v1/pmExchangeInfo` 54 | 55 | ## 4.0.0 - 2023-08-08 56 | 57 | ### Changed 58 | - Add proxy support for websockets 59 | - Remove support for Python 3.7 60 | 61 | ## 4.0.0rc3 - 2023-07-03 62 | 63 | ### Changed 64 | - Change `User-Agent` 65 | 66 | ### Updated 67 | - Fixed `modify_order` (`PUT /fapi/v1/order`) Endpoint by correctly adding the `price` parameter 68 | 69 | ## 4.0.0rc2 - 2023-05-25 70 | 71 | ### Added 72 | - Implemented Modify Order (`PUT /fapi/v1/order`) - `modify_order` for UM Futures. 73 | 74 | ## 4.0.0rc1 - 2023-05-18 75 | 76 | ### Changed 77 | - Redesign of Websocket part. Please consult `README.md` for details on its new usage. 78 | 79 | ## 3.3.1 - 2023-03-21 80 | 81 | ### Updated 82 | - Merge #68 83 | 84 | ## 3.3.0 - 2023-01-11 85 | 86 | ### Add 87 | - RSA Key support 88 | 89 | ### Remove 90 | - Python 3.6 Support Deprecated 91 | 92 | ## 3.2.0 - 2022-08-29 93 | 94 | ### Add 95 | #### UM Futures 96 | - New endpoint `GET /fapi/v1/pmExchangeInfo` to get current Portfolio Margin exchange trading rules. 97 | #### CM Futures 98 | - New endpoint `GET /dapi/v1/pmExchangeInfo` to get current Portfolio Margin exchange trading rules. 99 | 100 | ### Update 101 | #### UM Futures 102 | - `symbol` is no longer a required parameter in `GET /fapi/v1/premiumIndex` 103 | 104 | ## 3.1.2 - 2022-08-23 105 | 106 | ### Update 107 | - Fix encoding issue of parameters in `DELETE /fapi/v1/batchOrders` 108 | 109 | ## 3.1.1 - 2022-06-02 110 | 111 | ### Update 112 | - Fix import path error in example files 113 | 114 | ## 3.1.0 - 2022-06-02 115 | 116 | ### Add 117 | 118 | - New endpoint `GET /fapi/v1/income/asyn` to get Download Id For Futures Transaction History 119 | - New endpoint `GET /fapi/v1/income/asyn/id` to get Futures Transaction History Download Link by Id 120 | 121 | 122 | ## 3.0.0 - 2022-05-26 123 | 124 | - Refactor the connector 125 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) [2022] 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include requirements/common.txt -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Binance Futures Public API Connector Python - DEPRECATED 2 | [![Python version](https://img.shields.io/pypi/pyversions/binance-futures-connector)](https://www.python.org/downloads/) 3 | [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) 4 | 5 | **This repository is deprecated. Please use the new modular connector repository: [binance-connector-python](https://github.com/binance/binance-connector-python)** 6 | 7 | This is a lightweight library that works as a connector to [Binance Futures public API](https://developers.binance.com/docs/derivatives/Introduction) 8 | 9 | - Supported APIs: 10 | - USDT-M Futures `/fapi/*` 11 | - COIN-M Delivery `/dapi/*` 12 | - Futures/Delivery Websocket Market Stream 13 | - Futures/Delivery User Data Stream 14 | - Inclusion of examples 15 | - Customizable base URL, request timeout 16 | - Response metadata can be displayed 17 | 18 | ## Installation 19 | 20 | ```bash 21 | pip install binance-futures-connector 22 | ``` 23 | 24 | 25 | ## RESTful APIs 26 | 27 | Usage examples: 28 | ```python 29 | 30 | from binance.cm_futures import CMFutures 31 | 32 | cm_futures_client = CMFutures() 33 | 34 | # get server time 35 | print(cm_futures_client.time()) 36 | 37 | cm_futures_client = CMFutures(key='', secret='') 38 | 39 | # Get account information 40 | print(cm_futures_client.account()) 41 | 42 | # Post a new order 43 | params = { 44 | 'symbol': 'BTCUSDT', 45 | 'side': 'SELL', 46 | 'type': 'LIMIT', 47 | 'timeInForce': 'GTC', 48 | 'quantity': 0.002, 49 | 'price': 59808 50 | } 51 | 52 | response = cm_futures_client.new_order(**params) 53 | print(response) 54 | ``` 55 | Please find `examples` folder to check for more endpoints. 56 | 57 | ## Authentication 58 | Binance supports HMAC and RSA API authentication. 59 | 60 | ```python 61 | # HMAC Authentication 62 | client = Client(api_key, api_secret) 63 | print(client.account()) 64 | 65 | # RSA Authentication 66 | key = "" 67 | with open("/Users/john/private_key.pem", "r") as f: # Location of private key file 68 | private_key = f.read() 69 | private_key_passphrase = "" # Optional: only used for encrypted RSA key 70 | 71 | client = Client(key=key, private_key=private_key, private_key_passphrase=private_key_passphrase) 72 | print(client.account()) 73 | ``` 74 | Please see `examples/um_futures/trade/get_account.py` or `examples/cm_futures/trade/get_account.py` for more details. 75 | 76 | ### Base URL 77 | 78 | For USDT-M Futures, if `base_url` is not provided, it defaults to `fapi.binance.com`.
79 | For COIN-M Delivery, if `base_url` is not provided, it defaults to `dapi.binance.com`.
80 | It's recommended to pass in the `base_url` parameter, even in production as Binance provides alternative URLs 81 | 82 | ### Optional parameters 83 | 84 | PEP8 suggests _lowercase with words separated by underscores_, but for this connector, 85 | the methods' optional parameters should follow their exact naming as in the API documentation. 86 | 87 | ```python 88 | # Recognised parameter name 89 | response = client.query_order('BTCUSDT', orderListId=1) 90 | 91 | # Unrecognised parameter name 92 | response = client.query_order('BTCUSDT', order_list_id=1) 93 | ``` 94 | 95 | ### RecvWindow parameter 96 | 97 | Additional parameter `recvWindow` is available for endpoints requiring signature.
98 | It defaults to `5000` (milliseconds) and can be any value lower than `60000`(milliseconds). 99 | Anything beyond the limit will result in an error response from Binance server. 100 | 101 | ```python 102 | from binance.cm_futures import CMFutures 103 | 104 | cm_futures_client = CMFutures(key='', secret='') 105 | response = cm_futures_client.query_order('BTCUSDT', orderId=11, recvWindow=10000) 106 | ``` 107 | 108 | ### Timeout 109 | 110 | `timeout` is available to be assigned with the number of seconds you find most appropriate to wait for a server response.
111 | Please remember the value as it won't be shown in error message _no bytes have been received on the underlying socket for timeout seconds_.
112 | By default, `timeout` is None. Hence, requests do not time out. 113 | 114 | ```python 115 | from binance.cm_futures import CMFutures 116 | 117 | client= CMFutures(timeout=1) 118 | ``` 119 | 120 | ### Proxy 121 | proxy is supported 122 | 123 | ```python 124 | from binance.cm_futures import CMFutures 125 | 126 | proxies = { 'https': 'http://1.2.3.4:8080' } 127 | 128 | client= CMFutures(proxies=proxies) 129 | ``` 130 | 131 | ### Response Metadata 132 | 133 | The Binance API server provides weight usages in the headers of each response. 134 | You can display them by initializing the client with `show_limit_usage=True`: 135 | 136 | ```python 137 | from binance.cm_futures import CMFutures 138 | 139 | client = CMFutures(show_limit_usage=True) 140 | print(client.time()) 141 | ``` 142 | returns: 143 | 144 | ```python 145 | {'limit_usage': {'x-mbx-used-weight-1m': '1'}, 'data': {'serverTime': 1653563092778}} 146 | ``` 147 | You can also display full response metadata to help in debugging: 148 | 149 | ```python 150 | client = Client(show_header=True) 151 | print(client.time()) 152 | ``` 153 | 154 | returns: 155 | 156 | ```python 157 | {'data': {'serverTime': 1587990847650}, 'header': {'Context-Type': 'application/json;charset=utf-8', ...}} 158 | ``` 159 | 160 | If `ClientError` is received, it'll display full response meta information. 161 | 162 | ### Display logs 163 | 164 | Setting the log level to `DEBUG` will log the request URL, payload and response text. 165 | 166 | ### Error 167 | 168 | There are 2 types of error returned from the library: 169 | - `binance.error.ClientError` 170 | - This is thrown when server returns `4XX`, it's an issue from client side. 171 | - It has 4 properties: 172 | - `status_code` - HTTP status code 173 | - `error_code` - Server's error code, e.g. `-1102` 174 | - `error_message` - Server's error message, e.g. `Unknown order sent.` 175 | - `header` - Full response header. 176 | - `binance.error.ServerError` 177 | - This is thrown when server returns `5XX`, it's an issue from server side. 178 | 179 | ## Websocket 180 | 181 | ### Connector v4 182 | 183 | WebSocket can be established through the following connections: 184 | - USD-M WebSocket Stream (`https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Connect`) 185 | - COIN-M WebSocket Stream (`https://developers.binance.com/docs/derivatives/coin-margined-futures/websocket-market-streams/Connect`) 186 | 187 | ```python 188 | # WebSocket Stream Client 189 | import time 190 | from binance.websocket.um_futures.websocket_client import UMFuturesWebsocketClient 191 | 192 | def message_handler(_, message): 193 | logging.info(message) 194 | 195 | my_client = UMFuturesWebsocketClient(on_message=message_handler) 196 | 197 | # Subscribe to a single symbol stream 198 | my_client.agg_trade(symbol="bnbusdt") 199 | time.sleep(5) 200 | logging.info("closing ws connection") 201 | my_client.stop() 202 | ``` 203 | 204 | #### Request Id 205 | 206 | Client can assign a request id to each request. The request id will be returned in the response message. Not mandatory in the library, it generates a uuid format string if not provided. 207 | 208 | ```python 209 | # id provided by client 210 | my_client.agg_trade(symbol="bnbusdt", id="my_request_id") 211 | 212 | # library will generate a random uuid string 213 | my_client.agg_trade(symbol="bnbusdt") 214 | ``` 215 | #### Proxy 216 | 217 | Proxy is supported for both WebSocket CM futures and UM futures. 218 | 219 | To use it, pass in the `proxies` parameter when initializing the client. 220 | 221 | The format of the `proxies` parameter is the same as the one used in the Spot RESTful API. 222 | 223 | It consists on a dictionary with the following format, where the key is the type of the proxy and the value is the proxy URL: 224 | 225 | For websockets, the proxy type is `http`. 226 | 227 | ```python 228 | proxies = { 'http': 'http://1.2.3.4:8080' } 229 | ``` 230 | 231 | You can also use authentication for the proxy by adding the `username` and `password` parameters to the proxy URL: 232 | 233 | ```python 234 | proxies = { 'http': 'http://username:password@host:port' } 235 | ``` 236 | 237 | ```python 238 | # WebSocket Stream Client 239 | import time 240 | from binance.websocket.um_futures.websocket_client import UMFuturesWebsocketClient 241 | 242 | proxies = {'http': 'http://1.2.3.4:8080'} 243 | 244 | def message_handler(_, message): 245 | logging.info(message) 246 | 247 | my_client = UMFuturesWebsocketClient(on_message=message_handler, proxies=proxies) 248 | 249 | # Subscribe to a single symbol stream 250 | my_client.agg_trade(symbol="bnbusdt") 251 | time.sleep(5) 252 | logging.info("closing ws connection") 253 | my_client.stop() 254 | ``` 255 | 256 | 257 | #### Combined Streams 258 | - If you set `is_combined` to `True`, `"/stream/"` will be appended to the `baseURL` to allow for Combining streams. 259 | - `is_combined` defaults to `False` and `"/ws/"` (raw streams) will be appended to the `baseURL`. 260 | 261 | More websocket examples are available in the `examples` folder 262 | 263 | ## Websocket < v4 264 | 265 | ```python 266 | import time 267 | from binance.websocket.um_futures.websocket_client import UMFuturesWebsocketClient 268 | 269 | def message_handler(message): 270 | print(message) 271 | 272 | my_client = UMFuturesWebsocketClient(on_message=message_handler) 273 | 274 | # Subscribe to a single symbol stream 275 | my_client.agg_trade(symbol="bnbusdt") 276 | time.sleep(5) 277 | print("closing ws connection") 278 | my_client.stop() 279 | 280 | ``` 281 | 282 | ### Heartbeat 283 | 284 | Once connected, the websocket server sends a ping frame every 3 minutes and requires a response pong frame back within 285 | a 10 minutes period. This package handles the pong responses automatically. 286 | 287 | ## License 288 | MIT 289 | -------------------------------------------------------------------------------- /binance/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/binance/binance-futures-connector-python/a6bfbbf10fe2c1b4eb76fc24ffb82eb94bf9df89/binance/__init__.py -------------------------------------------------------------------------------- /binance/__version__.py: -------------------------------------------------------------------------------- 1 | __version__ = "4.1.0" 2 | -------------------------------------------------------------------------------- /binance/api.py: -------------------------------------------------------------------------------- 1 | import json 2 | import logging 3 | from json import JSONDecodeError 4 | import requests 5 | from .__version__ import __version__ 6 | from binance.error import ClientError, ServerError 7 | from binance.lib.utils import get_timestamp 8 | from binance.lib.utils import cleanNoneValue 9 | from binance.lib.utils import encoded_string 10 | from binance.lib.utils import check_required_parameter 11 | from binance.lib.authentication import hmac_hashing, rsa_signature 12 | 13 | 14 | class API(object): 15 | """API base class 16 | 17 | Keyword Args: 18 | base_url (str, optional): the API base url, useful to switch to testnet, etc. By default it's https://api.binance.com 19 | timeout (int, optional): the time waiting for server response, number of seconds. https://docs.python-requests.org/en/master/user/advanced/#timeouts 20 | proxies (obj, optional): Dictionary mapping protocol to the URL of the proxy. e.g. {'https': 'http://1.2.3.4:8080'} 21 | show_limit_usage (bool, optional): whether return limit usage(requests and/or orders). By default, it's False 22 | show_header (bool, optional): whether return the whole response header. By default, it's False 23 | """ 24 | 25 | def __init__( 26 | self, 27 | key=None, 28 | secret=None, 29 | base_url=None, 30 | timeout=None, 31 | proxies=None, 32 | show_limit_usage=False, 33 | show_header=False, 34 | private_key=None, 35 | private_key_passphrase=None, 36 | ): 37 | self.key = key 38 | self.secret = secret 39 | self.timeout = timeout 40 | self.show_limit_usage = False 41 | self.show_header = False 42 | self.proxies = None 43 | self.private_key = private_key 44 | self.private_key_pass = private_key_passphrase 45 | self.session = requests.Session() 46 | self.session.headers.update( 47 | { 48 | "Content-Type": "application/json;charset=utf-8", 49 | "User-Agent": "binance-futures-connector-python/" + __version__, 50 | "X-MBX-APIKEY": key, 51 | } 52 | ) 53 | 54 | if base_url: 55 | self.base_url = base_url 56 | 57 | if show_limit_usage is True: 58 | self.show_limit_usage = True 59 | 60 | if show_header is True: 61 | self.show_header = True 62 | 63 | if type(proxies) is dict: 64 | self.proxies = proxies 65 | 66 | return 67 | 68 | def query(self, url_path, payload=None): 69 | return self.send_request("GET", url_path, payload=payload) 70 | 71 | def limit_request(self, http_method, url_path, payload=None): 72 | """limit request is for those endpoints require API key in the header""" 73 | 74 | check_required_parameter(self.key, "apiKey") 75 | return self.send_request(http_method, url_path, payload=payload) 76 | 77 | def sign_request(self, http_method, url_path, payload=None, special=False): 78 | if payload is None: 79 | payload = {} 80 | payload["timestamp"] = get_timestamp() 81 | query_string = self._prepare_params(payload, special) 82 | payload["signature"] = self._get_sign(query_string) 83 | return self.send_request(http_method, url_path, payload, special) 84 | 85 | def limited_encoded_sign_request(self, http_method, url_path, payload=None): 86 | """This is used for some endpoints has special symbol in the url. 87 | In some endpoints these symbols should not encoded 88 | - @ 89 | - [ 90 | - ] 91 | 92 | so we have to append those parameters in the url 93 | """ 94 | if payload is None: 95 | payload = {} 96 | payload["timestamp"] = get_timestamp() 97 | query_string = self._prepare_params(payload) 98 | url_path = ( 99 | url_path + "?" + query_string + "&signature=" + self._get_sign(query_string) 100 | ) 101 | return self.send_request(http_method, url_path) 102 | 103 | def send_request(self, http_method, url_path, payload=None, special=False): 104 | if payload is None: 105 | payload = {} 106 | url = self.base_url + url_path 107 | logging.debug("url: " + url) 108 | params = cleanNoneValue( 109 | { 110 | "url": url, 111 | "params": self._prepare_params(payload, special), 112 | "timeout": self.timeout, 113 | "proxies": self.proxies, 114 | } 115 | ) 116 | response = self._dispatch_request(http_method)(**params) 117 | logging.debug("raw response from server:" + response.text) 118 | self._handle_exception(response) 119 | 120 | try: 121 | data = response.json() 122 | except ValueError: 123 | data = response.text 124 | result = {} 125 | 126 | if self.show_limit_usage: 127 | limit_usage = {} 128 | for key in response.headers.keys(): 129 | key = key.lower() 130 | if ( 131 | key.startswith("x-mbx-used-weight") 132 | or key.startswith("x-mbx-order-count") 133 | or key.startswith("x-sapi-used") 134 | ): 135 | limit_usage[key] = response.headers[key] 136 | result["limit_usage"] = limit_usage 137 | 138 | if self.show_header: 139 | result["header"] = response.headers 140 | 141 | if len(result) != 0: 142 | result["data"] = data 143 | return result 144 | 145 | return data 146 | 147 | def _prepare_params(self, params, special=False): 148 | return encoded_string(cleanNoneValue(params), special) 149 | 150 | def _get_sign(self, payload): 151 | if self.private_key: 152 | return rsa_signature(self.private_key, payload, self.private_key_pass) 153 | return hmac_hashing(self.secret, payload) 154 | 155 | def _dispatch_request(self, http_method): 156 | return { 157 | "GET": self.session.get, 158 | "DELETE": self.session.delete, 159 | "PUT": self.session.put, 160 | "POST": self.session.post, 161 | }.get(http_method, self.session.get) 162 | 163 | def _handle_exception(self, response): 164 | status_code = response.status_code 165 | if status_code < 400: 166 | return 167 | if 400 <= status_code < 500: 168 | try: 169 | err = json.loads(response.text) 170 | except JSONDecodeError: 171 | raise ClientError(status_code, None, response.text, response.headers) 172 | raise ClientError(status_code, err["code"], err["msg"], response.headers) 173 | raise ServerError(status_code, response.text) 174 | -------------------------------------------------------------------------------- /binance/cm_futures/__init__.py: -------------------------------------------------------------------------------- 1 | from binance.api import API 2 | 3 | 4 | class CMFutures(API): 5 | def __init__(self, key=None, secret=None, **kwargs): 6 | if "base_url" not in kwargs: 7 | kwargs["base_url"] = "https://dapi.binance.com" 8 | super().__init__(key, secret, **kwargs) 9 | 10 | # MARKETS 11 | from binance.cm_futures.market import ping 12 | from binance.cm_futures.market import time 13 | from binance.cm_futures.market import exchange_info 14 | from binance.cm_futures.market import depth 15 | from binance.cm_futures.market import trades 16 | from binance.cm_futures.market import historical_trades 17 | from binance.cm_futures.market import agg_trades 18 | from binance.cm_futures.market import klines 19 | from binance.cm_futures.market import continuous_klines 20 | from binance.cm_futures.market import index_price_klines 21 | from binance.cm_futures.market import mark_price_klines 22 | from binance.cm_futures.market import mark_price 23 | from binance.cm_futures.market import funding_rate 24 | from binance.cm_futures.market import ticker_24hr_price_change 25 | from binance.cm_futures.market import ticker_price 26 | from binance.cm_futures.market import book_ticker 27 | from binance.cm_futures.market import query_index_price_constituents 28 | from binance.cm_futures.market import open_interest 29 | from binance.cm_futures.market import open_interest_hist 30 | from binance.cm_futures.market import top_long_short_account_ratio 31 | from binance.cm_futures.market import top_long_short_position_ratio 32 | from binance.cm_futures.market import long_short_account_ratio 33 | from binance.cm_futures.market import taker_long_short_ratio 34 | from binance.cm_futures.market import basis 35 | 36 | # ACCOUNT(including orders and trades) 37 | from binance.cm_futures.account import change_position_mode 38 | from binance.cm_futures.account import get_position_mode 39 | from binance.cm_futures.account import new_order 40 | from binance.cm_futures.account import modify_order 41 | from binance.cm_futures.account import new_batch_order 42 | from binance.cm_futures.account import modify_batch_order 43 | from binance.cm_futures.account import order_modify_history 44 | from binance.cm_futures.account import query_order 45 | from binance.cm_futures.account import cancel_order 46 | from binance.cm_futures.account import cancel_open_orders 47 | from binance.cm_futures.account import cancel_batch_order 48 | from binance.cm_futures.account import countdown_cancel_order 49 | from binance.cm_futures.account import get_open_orders 50 | from binance.cm_futures.account import get_orders 51 | from binance.cm_futures.account import get_all_orders 52 | from binance.cm_futures.account import balance 53 | from binance.cm_futures.account import account 54 | from binance.cm_futures.account import change_leverage 55 | from binance.cm_futures.account import change_margin_type 56 | from binance.cm_futures.account import modify_isolated_position_margin 57 | from binance.cm_futures.account import get_position_margin_history 58 | from binance.cm_futures.account import get_position_risk 59 | from binance.cm_futures.account import get_account_trades 60 | from binance.cm_futures.account import get_income_history 61 | from binance.cm_futures.account import get_download_id_transaction_history 62 | from binance.cm_futures.account import leverage_brackets 63 | from binance.cm_futures.account import adl_quantile 64 | from binance.cm_futures.account import force_orders 65 | from binance.cm_futures.account import commission_rate 66 | 67 | # STREAMS 68 | from binance.cm_futures.data_stream import new_listen_key 69 | from binance.cm_futures.data_stream import renew_listen_key 70 | from binance.cm_futures.data_stream import close_listen_key 71 | -------------------------------------------------------------------------------- /binance/cm_futures/data_stream.py: -------------------------------------------------------------------------------- 1 | from binance.lib.utils import check_required_parameter 2 | 3 | 4 | def new_listen_key(self): 5 | """ 6 | | 7 | | **Create a ListenKey (USER_STREAM)** 8 | 9 | :API endpoint: ``POST /dapi/v1/listenKey`` 10 | :API doc: https://developers.binance.com/docs/derivatives/coin-margined-futures/user-data-streams/Start-User-Data-Stream 11 | | 12 | """ 13 | 14 | url_path = "/dapi/v1/listenKey" 15 | return self.send_request("POST", url_path) 16 | 17 | 18 | def renew_listen_key(self, listenKey: str): 19 | """ 20 | | **Ping/Keep-alive a ListenKey (USER_STREAM)** 21 | 22 | :API endpoint: ``PUT /dapi/v1/listenKey`` 23 | :API doc: https://developers.binance.com/docs/derivatives/coin-margined-futures/user-data-streams/Keepalive-User-Data-Stream 24 | 25 | :parameter listenKey: string 26 | | 27 | """ 28 | 29 | check_required_parameter(listenKey, "listenKey") 30 | url_path = "/dapi/v1/listenKey" 31 | return self.send_request("PUT", url_path, {"listenKey": listenKey}) 32 | 33 | 34 | def close_listen_key(self, listenKey: str): 35 | """ 36 | | 37 | | **Close a ListenKey (USER_STREAM)** 38 | 39 | :API endpoint: ``DELETE /dapi/v1/listenKey`` 40 | :API doc: https://developers.binance.com/docs/derivatives/coin-margined-futures/user-data-streams/Close-User-Data-Stream 41 | 42 | :parameter listenKey: string 43 | | 44 | """ 45 | 46 | check_required_parameter(listenKey, "listenKey") 47 | url_path = "/dapi/v1/listenKey" 48 | return self.send_request("DELETE", url_path, {"listenKey": listenKey}) 49 | -------------------------------------------------------------------------------- /binance/error.py: -------------------------------------------------------------------------------- 1 | class Error(Exception): 2 | pass 3 | 4 | 5 | class ClientError(Error): 6 | def __init__(self, status_code, error_code, error_message, header): 7 | # https status code 8 | self.status_code = status_code 9 | # error code returned from server 10 | self.error_code = error_code 11 | # error message returned from server 12 | self.error_message = error_message 13 | # the whole response header returned from server 14 | self.header = header 15 | 16 | 17 | class ServerError(Error): 18 | def __init__(self, status_code, message): 19 | self.status_code = status_code 20 | self.message = message 21 | 22 | 23 | class ParameterRequiredError(Error): 24 | def __init__(self, params): 25 | self.params = params 26 | 27 | def __str__(self): 28 | return "%s is mandatory, but received empty." % (", ".join(self.params)) 29 | 30 | 31 | class ParameterValueError(Error): 32 | def __init__(self, params): 33 | self.params = params 34 | 35 | def __str__(self): 36 | return "the enum value %s is invalid." % (", ".join(self.params)) 37 | 38 | 39 | class ParameterTypeError(Error): 40 | def __init__(self, params): 41 | self.params = params 42 | 43 | def __str__(self): 44 | return f"{self.params[0]} data type has to be {self.params[1]}" 45 | 46 | 47 | class ParameterArgumentError(Error): 48 | def __init__(self, error_message): 49 | self.error_message = error_message 50 | 51 | def __str__(self): 52 | return self.error_message 53 | -------------------------------------------------------------------------------- /binance/lib/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/binance/binance-futures-connector-python/a6bfbbf10fe2c1b4eb76fc24ffb82eb94bf9df89/binance/lib/__init__.py -------------------------------------------------------------------------------- /binance/lib/authentication.py: -------------------------------------------------------------------------------- 1 | import hmac 2 | import hashlib 3 | from base64 import b64encode 4 | from Crypto.PublicKey import RSA 5 | from Crypto.Hash import SHA256 6 | from Crypto.Signature import pkcs1_15 7 | 8 | 9 | def hmac_hashing(secret, payload): 10 | m = hmac.new(secret.encode("utf-8"), payload.encode("utf-8"), hashlib.sha256) 11 | return m.hexdigest() 12 | 13 | 14 | def rsa_signature(private_key, payload, private_key_pass=None): 15 | private_key = RSA.import_key(private_key, passphrase=private_key_pass) 16 | h = SHA256.new(payload.encode("utf-8")) 17 | signature = pkcs1_15.new(private_key).sign(h) 18 | return b64encode(signature) 19 | -------------------------------------------------------------------------------- /binance/lib/utils.py: -------------------------------------------------------------------------------- 1 | import json 2 | import time 3 | 4 | from urllib.parse import urlencode, urlparse 5 | from binance.error import ( 6 | ParameterRequiredError, 7 | ParameterValueError, 8 | ParameterTypeError, 9 | ) 10 | 11 | 12 | def cleanNoneValue(d) -> dict: 13 | out = {} 14 | for k in d.keys(): 15 | if d[k] is not None: 16 | out[k] = d[k] 17 | return out 18 | 19 | 20 | def check_required_parameter(value, name): 21 | if not value and value != 0: 22 | raise ParameterRequiredError([name]) 23 | 24 | 25 | def check_required_parameters(params): 26 | """validate multiple parameters 27 | params = [ 28 | ['btcusdt', 'symbol'], 29 | [10, 'price'] 30 | ] 31 | 32 | """ 33 | for p in params: 34 | check_required_parameter(p[0], p[1]) 35 | 36 | 37 | def check_enum_parameter(value, enum_class): 38 | if value not in set(item.value for item in enum_class): 39 | raise ParameterValueError([value]) 40 | 41 | 42 | def check_type_parameter(value, name, data_type): 43 | if value is not None and not isinstance(value, data_type): 44 | raise ParameterTypeError([name, data_type]) 45 | 46 | 47 | def get_timestamp(): 48 | return int(time.time() * 1000) 49 | 50 | 51 | def encoded_string(query, special=False): 52 | if special: 53 | return urlencode(query).replace("%40", "@").replace("%27", "%22") 54 | else: 55 | return urlencode(query, True).replace("%40", "@") 56 | 57 | 58 | def convert_list_to_json_array(symbols): 59 | if symbols is None: 60 | return symbols 61 | res = json.dumps(symbols) 62 | return res.replace(" ", "") 63 | 64 | 65 | def config_logging(logging, logging_devel, log_file=None): 66 | logging.basicConfig(level=logging_devel, filename=log_file) 67 | 68 | 69 | def parse_proxies(proxies: dict): 70 | """Parse proxy url from dict, only support http and https proxy, not support socks5 proxy""" 71 | proxy_url = proxies.get("http") or proxies.get("https") 72 | if not proxy_url: 73 | return {} 74 | 75 | parsed = urlparse(proxy_url) 76 | return { 77 | "http_proxy_host": parsed.hostname, 78 | "http_proxy_port": parsed.port, 79 | "http_proxy_auth": ( 80 | (parsed.username, parsed.password) 81 | if parsed.username and parsed.password 82 | else None 83 | ), 84 | } 85 | -------------------------------------------------------------------------------- /binance/um_futures/__init__.py: -------------------------------------------------------------------------------- 1 | from binance.api import API 2 | 3 | 4 | class UMFutures(API): 5 | def __init__(self, key=None, secret=None, **kwargs): 6 | if "base_url" not in kwargs: 7 | kwargs["base_url"] = "https://fapi.binance.com" 8 | super().__init__(key, secret, **kwargs) 9 | 10 | # MARKETS 11 | from binance.um_futures.market import ping 12 | from binance.um_futures.market import time 13 | from binance.um_futures.market import exchange_info 14 | from binance.um_futures.market import depth 15 | from binance.um_futures.market import trades 16 | from binance.um_futures.market import historical_trades 17 | from binance.um_futures.market import agg_trades 18 | from binance.um_futures.market import klines 19 | from binance.um_futures.market import continuous_klines 20 | from binance.um_futures.market import index_price_klines 21 | from binance.um_futures.market import mark_price_klines 22 | from binance.um_futures.market import mark_price 23 | from binance.um_futures.market import funding_rate 24 | from binance.um_futures.market import funding_info 25 | from binance.um_futures.market import ticker_24hr_price_change 26 | from binance.um_futures.market import ticker_price 27 | from binance.um_futures.market import book_ticker 28 | from binance.um_futures.market import quarterly_contract_settlement_price 29 | from binance.um_futures.market import open_interest 30 | from binance.um_futures.market import open_interest_hist 31 | from binance.um_futures.market import top_long_short_position_ratio 32 | from binance.um_futures.market import long_short_account_ratio 33 | from binance.um_futures.market import top_long_short_account_ratio 34 | from binance.um_futures.market import taker_long_short_ratio 35 | from binance.um_futures.market import blvt_kline 36 | from binance.um_futures.market import index_info 37 | from binance.um_futures.market import asset_Index 38 | from binance.um_futures.market import index_price_constituents 39 | 40 | # ACCOUNT(including orders and trades) 41 | from binance.um_futures.account import change_position_mode 42 | from binance.um_futures.account import get_position_mode 43 | from binance.um_futures.account import change_multi_asset_mode 44 | from binance.um_futures.account import get_multi_asset_mode 45 | from binance.um_futures.account import new_order 46 | from binance.um_futures.account import new_order_test 47 | from binance.um_futures.account import modify_order 48 | from binance.um_futures.account import new_batch_order 49 | from binance.um_futures.account import query_order 50 | from binance.um_futures.account import cancel_order 51 | from binance.um_futures.account import cancel_open_orders 52 | from binance.um_futures.account import cancel_batch_order 53 | from binance.um_futures.account import countdown_cancel_order 54 | from binance.um_futures.account import get_open_orders 55 | from binance.um_futures.account import get_orders 56 | from binance.um_futures.account import get_all_orders 57 | from binance.um_futures.account import balance 58 | from binance.um_futures.account import account 59 | from binance.um_futures.account import change_leverage 60 | from binance.um_futures.account import change_margin_type 61 | from binance.um_futures.account import modify_isolated_position_margin 62 | from binance.um_futures.account import get_position_margin_history 63 | from binance.um_futures.account import get_position_risk 64 | from binance.um_futures.account import get_account_trades 65 | from binance.um_futures.account import get_income_history 66 | from binance.um_futures.account import leverage_brackets 67 | from binance.um_futures.account import adl_quantile 68 | from binance.um_futures.account import force_orders 69 | from binance.um_futures.account import api_trading_status 70 | from binance.um_futures.account import commission_rate 71 | from binance.um_futures.account import futures_account_configuration 72 | from binance.um_futures.account import symbol_configuration 73 | from binance.um_futures.account import query_user_rate_limit 74 | from binance.um_futures.account import download_transactions_asyn 75 | from binance.um_futures.account import aysnc_download_info 76 | from binance.um_futures.account import download_order_asyn 77 | from binance.um_futures.account import async_download_order_id 78 | from binance.um_futures.account import download_trade_asyn 79 | from binance.um_futures.account import async_download_trade_id 80 | from binance.um_futures.account import toggle_bnb_burn 81 | from binance.um_futures.account import get_bnb_burn 82 | 83 | # CONVERT 84 | from binance.um_futures.convert import list_all_convert_pairs 85 | from binance.um_futures.convert import send_quote_request 86 | from binance.um_futures.convert import accept_offered_quote 87 | from binance.um_futures.convert import order_status 88 | 89 | # STREAMS 90 | from binance.um_futures.data_stream import new_listen_key 91 | from binance.um_futures.data_stream import renew_listen_key 92 | from binance.um_futures.data_stream import close_listen_key 93 | -------------------------------------------------------------------------------- /binance/um_futures/convert.py: -------------------------------------------------------------------------------- 1 | from binance.lib.utils import check_required_parameter 2 | 3 | 4 | def list_all_convert_pairs(self, **kwargs): 5 | """ 6 | | 7 | | **List All Convert Pairs** 8 | | *User needs to supply either or both of the input parameter* 9 | | *If not defined for both fromAsset and toAsset, only partial token pairs will be returned* 10 | | *Asset BNFCR is only available to convert for MICA region users.* 11 | 12 | :API endpoint: ``GET /fapi/v1/convert/exchangeInfo`` 13 | :API doc: https://developers.binance.com/docs/derivatives/usds-margined-futures/convert 14 | 15 | :parameter fromAsset: optional string; EITHER OR BOTH - User spends coin 16 | :parameter toAsset: optional string; EITHER OR BOTH - User receives coin 17 | | 18 | """ 19 | 20 | url_path = "/sapi/v1/asset/assetDividend" 21 | params = {**kwargs} 22 | 23 | return self.sign_request("GET", url_path, params) 24 | 25 | 26 | def send_quote_request(self, fromAsset: str, toAsset: str, **kwargs): 27 | """ 28 | | 29 | | **Send Quote Request(USER_DATA)** 30 | | *Either fromAmount or toAmount should be sent* 31 | | *quoteId will be returned only if you have enough funds to convert* 32 | 33 | :API endpoint: ``POST /fapi/v1/convert/getQuote`` 34 | :API doc: https://developers.binance.com/docs/derivatives/usds-margined-futures/convert/Send-quote-request 35 | 36 | :parameter fromAsset: string; the asset to convert from 37 | :parameter toAsset: string; the asset to convert to 38 | :parameter fromAmount: optional float; When specified, it is the amount you will be debited after the conversion 39 | :parameter toAmount: optional float; When specified, it is the amount you will be credited after the conversion 40 | :parameter validTime: optional string; 10s, default 10s 41 | :parameter recvWindow: optional int 42 | | 43 | """ 44 | 45 | check_required_parameter(fromAsset, "fromAsset") 46 | check_required_parameter(toAsset, "toAsset") 47 | url_path = "/fapi/v1/convert/getQuote" 48 | params = {"fromAsset": fromAsset, "toAsset": toAsset, **kwargs} 49 | 50 | return self.sign_request("POST", url_path, params) 51 | 52 | 53 | def accept_offered_quote(self, quoteId: str, **kwargs): 54 | """ 55 | | 56 | | **Accept the offered quote (USER_DATA)** 57 | 58 | :API endpoint: ``POST /fapi/v1/convert/acceptQuote`` 59 | :API doc: https://developers.binance.com/docs/derivatives/usds-margined-futures/convert/Accept-Quote 60 | 61 | :parameter quoteId: string 62 | :parameter recvWindow: optional int 63 | | 64 | """ 65 | 66 | check_required_parameter(quoteId, "quoteId") 67 | url_path = "/fapi/v1/convert/acceptQuote" 68 | params = {"quoteId": quoteId, **kwargs} 69 | 70 | return self.sign_request("POST", url_path, params) 71 | 72 | 73 | def order_status(self, **kwargs): 74 | """ 75 | | 76 | | **Order status(USER_DATA)** 77 | 78 | :API endpoint: ``GET /fapi/v1/convert/orderStatus`` 79 | :API doc: https://developers.binance.com/docs/derivatives/usds-margined-futures/convert/Order-Status 80 | 81 | :parameter orderId: optional string; Either orderId or quoteId is required 82 | :parameter quoteId: optional string; Either orderId or quoteId is required 83 | | 84 | """ 85 | 86 | url_path = "/fapi/v1/convert/orderStatus" 87 | params = {**kwargs} 88 | 89 | return self.sign_request("GET", url_path, params) 90 | -------------------------------------------------------------------------------- /binance/um_futures/data_stream.py: -------------------------------------------------------------------------------- 1 | from binance.lib.utils import check_required_parameter 2 | 3 | 4 | def new_listen_key(self): 5 | """ 6 | | 7 | | **Create a ListenKey (USER_STREAM)** 8 | 9 | :API endpoint: ``POST /fapi/v1/listenKey`` 10 | :API doc: https://developers.binance.com/docs/derivatives/usds-margined-futures/user-data-streams/Start-User-Data-Stream 11 | | 12 | """ 13 | 14 | url_path = "/fapi/v1/listenKey" 15 | return self.send_request("POST", url_path) 16 | 17 | 18 | def renew_listen_key(self, listenKey: str): 19 | """ 20 | | 21 | | **Ping/Keep-alive a ListenKey (USER_STREAM)** 22 | 23 | :API endpoint: ``PUT /fapi/v1/listenKey`` 24 | :API doc: https://developers.binance.com/docs/derivatives/usds-margined-futures/user-data-streams/Keepalive-User-Data-Stream 25 | 26 | :parameter listenKey: string 27 | | 28 | """ 29 | 30 | check_required_parameter(listenKey, "listenKey") 31 | url_path = "/fapi/v1/listenKey" 32 | return self.send_request("PUT", url_path, {"listenKey": listenKey}) 33 | 34 | 35 | def close_listen_key(self, listenKey: str): 36 | """ 37 | | 38 | | **Close a ListenKey (USER_STREAM)** 39 | 40 | :API endpoint: ``DELETE /fapi/v1/listenKey`` 41 | :API doc: https://developers.binance.com/docs/derivatives/usds-margined-futures/user-data-streams/Close-User-Data-Stream 42 | 43 | :parameter listenKey: string 44 | | 45 | """ 46 | 47 | check_required_parameter(listenKey, "listenKey") 48 | url_path = "/fapi/v1/listenKey" 49 | return self.send_request("DELETE", url_path, {"listenKey": listenKey}) 50 | -------------------------------------------------------------------------------- /binance/um_futures/market.py: -------------------------------------------------------------------------------- 1 | from binance.lib.utils import check_required_parameter 2 | from binance.lib.utils import check_required_parameters 3 | 4 | 5 | def ping(self): 6 | """ 7 | | 8 | | **Test Connectivity** 9 | | *Test connectivity to the Rest API.* 10 | 11 | :API endpoint: ``GET /fapi/v1/ping`` 12 | :API doc: https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Test-Connectivity 13 | | 14 | """ 15 | 16 | url_path = "/fapi/v1/ping" 17 | return self.query(url_path) 18 | 19 | 20 | def time(self): 21 | """ 22 | | 23 | | **Check Server Time** 24 | | *Test connectivity to the Rest API and get the current server time.* 25 | 26 | :API endpoint: ``GET /fapi/v1/time`` 27 | :API doc: https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Check-Server-Time 28 | | 29 | """ 30 | 31 | url_path = "/fapi/v1/time" 32 | return self.query(url_path) 33 | 34 | 35 | def exchange_info(self): 36 | """ 37 | | 38 | | **Exchange Information** 39 | | *Current exchange trading rules and symbol information.* 40 | 41 | :API endpoint: ``GET /fapi/v1/exchangeInfo`` 42 | :API doc: https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Exchange-Information 43 | | 44 | """ 45 | 46 | url_path = "/fapi/v1/exchangeInfo" 47 | return self.query(url_path) 48 | 49 | 50 | def depth(self, symbol: str, **kwargs): 51 | """ 52 | | 53 | | **Get Orderbook** 54 | 55 | :API endpoint: ``GET /fapi/v1/depth`` 56 | :API doc: https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Order-Book 57 | 58 | :parameter symbol: string; the trading symbol. 59 | :parameter limit: optional int; limit the results. Default 500, valid limits: [5, 10, 20, 50, 100, 500, 1000]. 60 | | 61 | """ 62 | 63 | check_required_parameter(symbol, "symbol") 64 | params = {"symbol": symbol, **kwargs} 65 | return self.query("/fapi/v1/depth", params) 66 | 67 | 68 | def trades(self, symbol: str, **kwargs): 69 | """ 70 | | 71 | | **Get Recent Market Trades** 72 | 73 | :API endpoint: ``GET /fapi/v1/trades`` 74 | :API doc: https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Recent-Trades-List 75 | 76 | :parameter symbol: string; the trading symbol. 77 | :parameter limit: optional int; limit the results. Default 500, max 1000. 78 | | 79 | """ 80 | 81 | check_required_parameter(symbol, "symbol") 82 | params = {"symbol": symbol, **kwargs} 83 | return self.query("/fapi/v1/trades", params) 84 | 85 | 86 | def historical_trades(self, symbol: str, **kwargs): 87 | """ 88 | | 89 | | **Old Trade Lookup** 90 | | *Get older market historical trades.* 91 | 92 | :API endpoint: ``GET /fapi/v1/historicalTrades`` 93 | :API doc: https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Old-Trades-Lookup 94 | 95 | :parameter symbol: string; the trading symbol. 96 | :parameter limit: optional int; limit the results. Default 500, max 1000. 97 | :parameter formId: optional int; trade ID to fetch from. Default gets most recent trades. 98 | | 99 | """ 100 | 101 | check_required_parameter(symbol, "symbol") 102 | params = {"symbol": symbol, **kwargs} 103 | return self.limit_request("GET", "/fapi/v1/historicalTrades", params) 104 | 105 | 106 | def agg_trades(self, symbol: str, **kwargs): 107 | """ 108 | | 109 | | **Compressed/Aggregate Trades List** 110 | | *Get compressed, aggregate market trades. Market trades that fill at the time, from the same order, with the same price will have the quantity aggregated.* 111 | 112 | :API endpoint: ``GET /fapi/v1/aggTrades`` 113 | :API doc: https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Compressed-Aggregate-Trades-List 114 | 115 | :parameter symbol: string; the trading symbol. 116 | :parameter limit: optional int; limit the results. Default 500, max 1000. 117 | :parameter formId: optional int; ID to get aggregate trades from INCLUSIVE. 118 | :parameter startTime: optional int; timestamp in ms to get aggregate trades from INCLUSIVE. 119 | :parameter endTime: optional int; timestamp in ms to get aggregate trades from INCLUSIVE. 120 | | 121 | """ 122 | 123 | check_required_parameter(symbol, "symbol") 124 | params = {"symbol": symbol, **kwargs} 125 | return self.query("/fapi/v1/aggTrades", params) 126 | 127 | 128 | def klines(self, symbol: str, interval: str, **kwargs): 129 | """ 130 | | 131 | | **Kline/Candlestick Data** 132 | | *Kline/candlestick bars for a symbol. Klines are uniquely identified by their open time.* 133 | 134 | :API endpoint: ``GET /fapi/v1/klines`` 135 | :API doc: https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Kline-Candlestick-Data 136 | 137 | :parameter symbol: string; the trading symbol. 138 | :parameter interval: string; the interval of kline, e.g 1m, 5m, 1h, 1d, etc. (see more in https://developers.binance.com/docs/derivatives/usds-margined-futures/common-definition) 139 | :parameter limit: optional int; limit the results. Default 500, max 1000. 140 | :parameter startTime: optional int 141 | :parameter endTime: optional int 142 | | 143 | """ 144 | 145 | check_required_parameters([[symbol, "symbol"], [interval, "interval"]]) 146 | params = {"symbol": symbol, "interval": interval, **kwargs} 147 | return self.query("/fapi/v1/klines", params) 148 | 149 | 150 | def continuous_klines(self, pair: str, contractType: str, interval: str, **kwargs): 151 | """ 152 | | 153 | | **Continuous Kline/Candlestick Data** 154 | | *Kline/candlestick bars for a specific contract type. Klines are uniquely identified by their open time.* 155 | 156 | :API endpoint: ``GET /fapi/v1/continuousKlines`` 157 | :API doc: https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Continuous-Contract-Kline-Candlestick-Data 158 | 159 | :parameter pair: string; the trading pair. 160 | :parameter contractType: string; PERPETUAL, CURRENT_MONTH, NEXT_MONTH, CURRENT_QUARTER, NEXT_QUARTER. 161 | :parameter interval: string; the interval of kline, e.g 1m, 5m, 1h, 1d, etc. (see more in https://developers.binance.com/docs/derivatives/usds-margined-futures/common-definition) 162 | :parameter limit: optional int; limit the results. Default 500, max 1000. 163 | :parameter startTime: optional int 164 | :parameter endTime: optional int 165 | | 166 | """ 167 | 168 | check_required_parameters( 169 | [[pair, "pair"], [contractType, "contractType"], [interval, "interval"]] 170 | ) 171 | params = { 172 | "pair": pair, 173 | "contractType": contractType, 174 | "interval": interval, 175 | **kwargs, 176 | } 177 | return self.query("/fapi/v1/continuousKlines", params) 178 | 179 | 180 | def index_price_klines(self, pair: str, interval: str, **kwargs): 181 | """ 182 | | 183 | | **Kline/Candlestick Data for the index price of a pair.** 184 | | *Klines are uniquely identified by their open time.* 185 | 186 | :API endpoint: ``GET /fapi/v1/indexPriceKlines`` 187 | :API doc: https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Index-Price-Kline-Candlestick-Data 188 | 189 | :parameter pair: string; the trading pair. 190 | :parameter interval: string; the interval of kline, e.g 1m, 5m, 1h, 1d, etc. (see more in https://developers.binance.com/docs/derivatives/usds-margined-futures/common-definition) 191 | :parameter limit: optional int; limit the results. Default 500, max 1000. 192 | :parameter startTime: optional int 193 | :parameter endTime: optional int 194 | | 195 | """ 196 | 197 | check_required_parameters([[pair, "pair"], [interval, "interval"]]) 198 | params = {"pair": pair, "interval": interval, **kwargs} 199 | return self.query("/fapi/v1/indexPriceKlines", params) 200 | 201 | 202 | def mark_price_klines(self, symbol: str, interval: str, **kwargs): 203 | """ 204 | | 205 | | **Kline/candlestick bars for the mark price of a symbol.** 206 | | *Klines are uniquely identified by their open time.* 207 | 208 | :API endpoint: ``GET /fapi/v1/markPriceKlines`` 209 | :API doc: https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Mark-Price-Kline-Candlestick-Data 210 | 211 | :parameter symbol: string; the trading symbol. 212 | :parameter interval: string; the interval of kline, e.g 1m, 5m, 1h, 1d, etc. (see more in https://developers.binance.com/docs/derivatives/usds-margined-futures/common-definition) 213 | :parameter limit: optional int; limit the results. Default 500, max 1000. 214 | :parameter startTime: optional int 215 | :parameter endTime: optional int 216 | | 217 | """ 218 | 219 | check_required_parameters([[symbol, "symbol"], [interval, "interval"]]) 220 | params = {"symbol": symbol, "interval": interval, **kwargs} 221 | return self.query("/fapi/v1/markPriceKlines", params) 222 | 223 | 224 | def mark_price(self, symbol: str = None): 225 | """ 226 | | 227 | | **Mark Price and Funding Rate** 228 | 229 | :API endpoint: ``GET /fapi/v1/premiumIndex`` 230 | :API doc: https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Mark-Price 231 | 232 | :parameter symbol: string; the trading symbol. 233 | | 234 | """ 235 | 236 | params = { 237 | "symbol": symbol, 238 | } 239 | return self.query("/fapi/v1/premiumIndex", params) 240 | 241 | 242 | def funding_rate(self, symbol: str, **kwargs): 243 | """ 244 | | 245 | | **Funding Rate History 246 | 247 | :API endpoint: ``GET /fapi/v1/fundingRate`` 248 | :API doc: https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Get-Funding-Rate-History 249 | 250 | :parameter symbol: string; the trading symbol. 251 | :parameter limit: optional int; limit the results. Default 500, max 1000. 252 | :parameter startTime: optional int 253 | :parameter endTime: optional int 254 | 255 | **Notes** 256 | - If startTime and endTime are not sent, the most recent limit datas are returned. 257 | - If the number of data between startTime and endTime is larger than limit, return as startTime + limit. 258 | - In ascending order. 259 | | 260 | """ 261 | 262 | params = {"symbol": symbol, **kwargs} 263 | return self.query("/fapi/v1/fundingRate", params) 264 | 265 | 266 | def funding_info(self): 267 | """ 268 | | 269 | | **Get Funding Rate Info** 270 | | *Query funding rate info for symbols that had FundingRateCap/FundingRateFloor/fundingIntervalHours adjustment* 271 | 272 | :API endpoint: ``GET /fapi/v1/fundingInfo`` 273 | :API doc: https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Get-Funding-Info 274 | | 275 | """ 276 | 277 | return self.query("/fapi/v1/fundingRate") 278 | 279 | 280 | def ticker_24hr_price_change(self, symbol: str = None): 281 | """ 282 | | 283 | | **24 hour rolling window price change statistics.** 284 | | *Careful when accessing this with no symbol.* 285 | | *If the symbol is not sent, tickers for all symbols will be returned in an array.* 286 | 287 | :API endpoint: ``GET /fapi/v1/ticker/24hr`` 288 | :API doc: https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/24hr-Ticker-Price-Change-Statistics 289 | 290 | :parameter symbol: string; the trading symbol. 291 | | 292 | """ 293 | 294 | params = { 295 | "symbol": symbol, 296 | } 297 | return self.query("/fapi/v1/ticker/24hr", params) 298 | 299 | 300 | def ticker_price(self, symbol: str = None): 301 | """ 302 | | 303 | | **Symbol Price Ticker V2** 304 | | *If the symbol is not sent, prices for all symbols will be returned in an array.* 305 | 306 | :API endpoint: ``GET /fapi/v2/ticker/price`` 307 | :API doc: https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Symbol-Price-Ticker-v2 308 | 309 | :parameter symbol: optional string; the trading symbol. 310 | 311 | **Notes** 312 | - If the symbol is not sent, prices for all symbols will be returned in an array. 313 | | 314 | """ 315 | 316 | params = { 317 | "symbol": symbol, 318 | } 319 | return self.query("/fapi/v2/ticker/price", params) 320 | 321 | 322 | def book_ticker(self, symbol: str = None): 323 | """ 324 | | 325 | | **Best price/qty on the order book for a symbol or symbols.** 326 | 327 | :API endpoint: ``GET /fapi/v1/ticker/bookTicker`` 328 | :API doc: https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Symbol-Order-Book-Ticker 329 | 330 | :parameter symbol: optional string; the trading symbol. 331 | 332 | **Notes** 333 | - If the symbol is not sent, bookTickers for all symbols will be returned in an array. 334 | | 335 | """ 336 | 337 | params = { 338 | "symbol": symbol, 339 | } 340 | return self.query("/fapi/v1/ticker/bookTicker", params) 341 | 342 | 343 | def quarterly_contract_settlement_price(self, pair: str): 344 | """ 345 | | 346 | | **Quarterly Contract Settlement Price** 347 | | *Latest price for a symbol or symbols.* 348 | 349 | :API endpoint: ``GET /futures/data/delivery-price`` 350 | :API doc: https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Delivery-Price 351 | 352 | :parameter pair: string; the trading pair. 353 | | 354 | """ 355 | 356 | check_required_parameter(pair, "pair") 357 | params = {"pair": pair} 358 | return self.query("/futures/data/delivery-price", params) 359 | 360 | 361 | def open_interest(self, symbol: str): 362 | """ 363 | | 364 | | **Get present open interest of a specific symbol.** 365 | 366 | :API endpoint: ``GET /fapi/v1/openInterest`` 367 | :API doc: https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Open-Interest 368 | 369 | :parameter symbol: string; the trading symbol. 370 | | 371 | """ 372 | 373 | check_required_parameter(symbol, "symbol") 374 | params = {"symbol": symbol} 375 | return self.query("/fapi/v1/openInterest", params) 376 | 377 | 378 | def open_interest_hist(self, symbol: str, period: str, **kwargs): 379 | """ 380 | | 381 | | **Get historical open interest of a specific symbol.** 382 | 383 | :API endpoint: ``GET /futures/data/openInterestHist`` 384 | :API doc: https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Open-Interest-Statistics 385 | 386 | :parameter symbol: string; the trading symbol. 387 | :parameter period: string; the period of open interest, "5m", "15m", "30m", "1h", "2h", "4h", "6h", "12h", "1d". 388 | :parameter limit: optional int; limit the results. Default 30, max 500. 389 | :parameter startTime: optional int 390 | :parameter endTime: optional int 391 | 392 | **Notes** 393 | - If startTime and endTime are not sent, the most recent data is returned. 394 | - Only the data of the latest 30 days is available. 395 | | 396 | """ 397 | 398 | check_required_parameters([[symbol, "symbol"], [period, "period"]]) 399 | params = {"symbol": symbol, "period": period, **kwargs} 400 | return self.query("/futures/data/openInterestHist", params) 401 | 402 | 403 | def top_long_short_position_ratio(self, symbol: str, period: str, **kwargs): 404 | """ 405 | | 406 | | **Get top long short position ratio.** 407 | 408 | :API endpoint: ``GET /futures/data/topLongShortPositionRatio`` 409 | :API doc: https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Top-Trader-Long-Short-Ratio 410 | 411 | :parameter symbol: string; the trading symbol. 412 | :parameter period: string; the period of open interest, "5m", "15m", "30m", "1h", "2h", "4h", "6h", "12h", "1d". (see more in https://developers.binance.com/docs/derivatives/usds-margined-futures/common-definition) 413 | :parameter limit: optional int; limit the results. Default 30, max 500. 414 | :parameter startTime: optional int 415 | :parameter endTime: optional int 416 | 417 | **Notes** 418 | - If startTime and endTime are not sent, the most recent data is returned. 419 | - Only the data of the latest 30 days is available. 420 | | 421 | """ 422 | 423 | check_required_parameters([[symbol, "symbol"], [period, "period"]]) 424 | params = {"symbol": symbol, "period": period, **kwargs} 425 | return self.query("/futures/data/topLongShortPositionRatio", params) 426 | 427 | 428 | def long_short_account_ratio(self, symbol: str, period: str, **kwargs): 429 | """ 430 | | 431 | | **Get top long short account ratio.** 432 | 433 | :API endpoint: ``GET /futures/data/globalLongShortAccountRatio`` 434 | :API doc: https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Long-Short-Ratio 435 | 436 | :parameter symbol: string; the trading symbol. 437 | :parameter period: string; the period of open interest, "5m", "15m", "30m", "1h", "2h", "4h", "6h", "12h", "1d". (see more in https://developers.binance.com/docs/derivatives/usds-margined-futures/common-definition) 438 | :parameter limit: optional int; limit the results. Default 30, max 500. 439 | :parameter startTime: optional int 440 | :parameter endTime: optional int 441 | 442 | **Notes** 443 | - If startTime and endTime are not sent, the most recent data is returned. 444 | - Only the data of the latest 30 days is available. 445 | | 446 | """ 447 | 448 | check_required_parameters([[symbol, "symbol"], [period, "period"]]) 449 | params = {"symbol": symbol, "period": period, **kwargs} 450 | return self.query("/futures/data/globalLongShortAccountRatio", params) 451 | 452 | 453 | def top_long_short_account_ratio(self, symbol: str, period: str, **kwargs): 454 | """ 455 | | 456 | | **Get top long short account ratio.** 457 | 458 | :API endpoint: ``GET /futures/data/topLongShortAccountRatio`` 459 | :API doc: https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Top-Long-Short-Account-Ratio 460 | 461 | :parameter symbol: string; the trading symbol. 462 | :parameter period: string; the period of open interest, "5m", "15m", "30m", "1h", "2h", "4h", "6h", "12h", "1d". (see more in https://developers.binance.com/docs/derivatives/usds-margined-futures/common-definition) 463 | :parameter limit: optional int; limit the results. Default 30, max 500. 464 | :parameter startTime: optional int 465 | :parameter endTime: optional int 466 | 467 | **Notes** 468 | - If startTime and endTime are not sent, the most recent data is returned. 469 | - Only the data of the latest 30 days is available. 470 | | 471 | """ 472 | 473 | check_required_parameters([[symbol, "symbol"], [period, "period"]]) 474 | params = {"symbol": symbol, "period": period, **kwargs} 475 | return self.query("/futures/data/topLongShortAccountRatio", params) 476 | 477 | 478 | def taker_long_short_ratio(self, symbol: str, period: str, **kwargs): 479 | """ 480 | | 481 | | **Get taker long short ratio.** 482 | 483 | :API endpoint: ``GET /futures/data/takerlongshortRatio`` 484 | :API doc: https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Taker-BuySell-Volume 485 | 486 | :parameter symbol: string; the trading symbol. 487 | :parameter period: string; the period of open interest, "5m", "15m", "30m", "1h", "2h", "4h", "6h", "12h", "1d". (see more in https://developers.binance.com/docs/derivatives/usds-margined-futures/common-definition) 488 | :parameter limit: optional int; limit the results. Default 30, max 500. 489 | :parameter startTime: optional int 490 | :parameter endTime: optional int 491 | 492 | **Notes** 493 | - If startTime and endTime are not sent, the most recent data is returned. 494 | - Only the data of the latest 30 days is available. 495 | | 496 | """ 497 | 498 | check_required_parameters([[symbol, "symbol"], [period, "period"]]) 499 | params = {"symbol": symbol, "period": period, **kwargs} 500 | return self.query("/futures/data/takerlongshortRatio", params) 501 | 502 | 503 | def blvt_kline(self, symbol: str, interval: str, **kwargs): 504 | """ 505 | | 506 | | **Get Historical BLVT NAV Kline** 507 | 508 | :API endpoint: ``GET /fapi/v1/lvtKlines`` 509 | :API doc: https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Historical-BLVT-NAV-Kline-Candlestick 510 | 511 | :parameter symbol: string; the trading symbol. 512 | :parameter period: string; the period of open interest, "5m", "15m", "30m", "1h", "2h", "4h", "6h", "12h", "1d". (see more in https://developers.binance.com/docs/derivatives/usds-margined-futures/common-definition) 513 | :parameter limit: optional int; limit the results. Default 500, max 1000. 514 | :parameter startTime: optional int 515 | :parameter endTime: optional int 516 | 517 | **Notes** 518 | - If startTime and endTime are not sent, the most recent data is returned. 519 | | 520 | """ 521 | 522 | check_required_parameters([[symbol, "symbol"], [interval, "interval"]]) 523 | params = {"symbol": symbol, "interval": interval, **kwargs} 524 | return self.query("/fapi/v1/lvtKlines", params) 525 | 526 | 527 | def index_info(self, symbol: str = None): 528 | """ 529 | | 530 | | **Get Index Composite** 531 | 532 | :API endpoint: ``GET /fapi/v1/indexInfo`` 533 | :API doc: https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Composite-Index-Symbol-Information 534 | 535 | :parameter symbol: optional string; the trading symbol. 536 | 537 | **Notes** 538 | - Only for composite index symbols. 539 | | 540 | """ 541 | 542 | params = { 543 | "symbol": symbol, 544 | } 545 | return self.query("/fapi/v1/indexInfo", params) 546 | 547 | 548 | def asset_Index(self, symbol: str = None): 549 | """ 550 | | 551 | | **Get asset index for Multi-Assets mode** 552 | 553 | :API endpoint: ``GET /fapi/v1/assetIndex`` 554 | :API doc: https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Multi-Assets-Mode-Asset-Index 555 | 556 | :parameter symbol: optional string; Asset pair in multi asset mode (ex: BTCUSD). 557 | | 558 | """ 559 | 560 | params = { 561 | "symbol": symbol, 562 | } 563 | return self.query("/fapi/v1/assetIndex", params) 564 | 565 | 566 | def index_price_constituents(self, symbol: str = None): 567 | """ 568 | | 569 | | **Query Index Price Constituents** 570 | | *Query index price constituents* 571 | 572 | :API endpoint: ``GET /fapi/v1/constituents`` 573 | :API doc: https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Index-Constituents 574 | 575 | :parameter symbol: string; the trading symbol. 576 | | 577 | """ 578 | 579 | params = { 580 | "symbol": symbol, 581 | } 582 | return self.query("/fapi/v1/constituents", params) 583 | -------------------------------------------------------------------------------- /binance/websocket/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/binance/binance-futures-connector-python/a6bfbbf10fe2c1b4eb76fc24ffb82eb94bf9df89/binance/websocket/__init__.py -------------------------------------------------------------------------------- /binance/websocket/binance_socket_manager.py: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | 3 | import logging 4 | import threading 5 | from websocket import ( 6 | ABNF, 7 | create_connection, 8 | WebSocketException, 9 | WebSocketConnectionClosedException, 10 | ) 11 | from binance.lib.utils import parse_proxies 12 | 13 | 14 | class BinanceSocketManager(threading.Thread): 15 | def __init__( 16 | self, 17 | stream_url, 18 | on_message=None, 19 | on_open=None, 20 | on_close=None, 21 | on_error=None, 22 | on_ping=None, 23 | on_pong=None, 24 | logger=None, 25 | proxies: Optional[dict] = None, 26 | ): 27 | threading.Thread.__init__(self) 28 | if not logger: 29 | logger = logging.getLogger(__name__) 30 | self.logger = logger 31 | self.stream_url = stream_url 32 | self.on_message = on_message 33 | self.on_open = on_open 34 | self.on_close = on_close 35 | self.on_ping = on_ping 36 | self.on_pong = on_pong 37 | self.on_error = on_error 38 | self.proxies = proxies 39 | 40 | self._proxy_params = parse_proxies(proxies) if proxies else {} 41 | 42 | self.create_ws_connection() 43 | 44 | def create_ws_connection(self): 45 | self.logger.debug( 46 | f"Creating connection with WebSocket Server: {self.stream_url}, proxies: {self.proxies}", 47 | ) 48 | self.ws = create_connection(self.stream_url, **self._proxy_params) 49 | self.logger.debug( 50 | f"WebSocket connection has been established: {self.stream_url}, proxies: {self.proxies}", 51 | ) 52 | self._callback(self.on_open) 53 | 54 | def run(self): 55 | self.read_data() 56 | 57 | def send_message(self, message): 58 | self.logger.debug("Sending message to Binance WebSocket Server: %s", message) 59 | self.ws.send(message) 60 | 61 | def ping(self): 62 | self.ws.ping() 63 | 64 | def read_data(self): 65 | data = "" 66 | while True: 67 | try: 68 | op_code, frame = self.ws.recv_data_frame(True) 69 | except WebSocketException as e: 70 | if isinstance(e, WebSocketConnectionClosedException): 71 | self.logger.error("Lost websocket connection") 72 | else: 73 | self.logger.error("Websocket exception: {}".format(e)) 74 | self._handle_exception(e) 75 | break 76 | except Exception as e: 77 | self.logger.error("Exception in read_data: {}".format(e)) 78 | self._handle_exception(e) 79 | break 80 | 81 | if op_code == ABNF.OPCODE_CLOSE: 82 | self.logger.warning( 83 | "CLOSE frame received, closing websocket connection" 84 | ) 85 | self._callback(self.on_close) 86 | break 87 | elif op_code == ABNF.OPCODE_PING: 88 | self._callback(self.on_ping, frame.data) 89 | self.ws.pong("") 90 | self.logger.debug("Received Ping; PONG frame sent back") 91 | elif op_code == ABNF.OPCODE_PONG: 92 | self.logger.debug("Received PONG frame") 93 | self._callback(self.on_pong) 94 | else: 95 | data = frame.data 96 | if op_code == ABNF.OPCODE_TEXT: 97 | data = data.decode("utf-8") 98 | self._callback(self.on_message, data) 99 | 100 | def close(self): 101 | if not self.ws.connected: 102 | self.logger.warning("Websocket already closed") 103 | else: 104 | self.ws.send_close() 105 | 106 | def _callback(self, callback, *args): 107 | if callback: 108 | try: 109 | callback(self, *args) 110 | except Exception as e: 111 | self.logger.error("Error from callback {}: {}".format(callback, e)) 112 | if self.on_error: 113 | self.on_error(self, e) 114 | 115 | def _handle_exception(self, e): 116 | if self.on_error: 117 | self.on_error(self, e) 118 | else: 119 | raise e 120 | -------------------------------------------------------------------------------- /binance/websocket/cm_futures/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/binance/binance-futures-connector-python/a6bfbbf10fe2c1b4eb76fc24ffb82eb94bf9df89/binance/websocket/cm_futures/__init__.py -------------------------------------------------------------------------------- /binance/websocket/cm_futures/websocket_client.py: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | 3 | from binance.websocket.websocket_client import BinanceWebsocketClient 4 | 5 | 6 | class CMFuturesWebsocketClient(BinanceWebsocketClient): 7 | def __init__( 8 | self, 9 | stream_url="wss://dstream.binance.com", 10 | on_message=None, 11 | on_open=None, 12 | on_close=None, 13 | on_error=None, 14 | on_ping=None, 15 | on_pong=None, 16 | is_combined=False, 17 | proxies: Optional[dict] = None, 18 | ): 19 | if is_combined: 20 | stream_url = stream_url + "/stream" 21 | else: 22 | stream_url = stream_url + "/ws" 23 | super().__init__( 24 | stream_url, 25 | on_message=on_message, 26 | on_open=on_open, 27 | on_close=on_close, 28 | on_error=on_error, 29 | on_ping=on_ping, 30 | on_pong=on_pong, 31 | proxies=proxies, 32 | ) 33 | 34 | def agg_trade(self, symbol: str, id=None, action=None, **kwargs): 35 | """Aggregate Trade Streams 36 | 37 | The Aggregate Trade Streams push market trade information that is aggregated for a single taker order every 100 milliseconds. 38 | Only market trades will be aggregated, which means the insurance fund trades and ADL trades won't be aggregated. 39 | 40 | Stream Name: @aggTrade 41 | 42 | https://developers.binance.com/docs/derivatives/coin-margined-futures/websocket-market-streams/Aggregate-Trade-Streams 43 | 44 | Update Speed: 100ms 45 | """ 46 | stream_name = "{}@aggTrade".format(symbol.lower()) 47 | 48 | self.send_message_to_server(stream_name, action=action, id=id) 49 | 50 | def index_price(self, pair: str, id=None, speed=1, action=None, **kwargs): 51 | """Index Price Streams 52 | 53 | Stream Name: @indexPrice OR @indexPrice@1s 54 | 55 | https://developers.binance.com/docs/derivatives/coin-margined-futures/websocket-market-streams/Index-Price-Stream 56 | 57 | Update Speed: 3000ms OR 1000ms 58 | """ 59 | if speed == 1: 60 | stream_name = "{}@indexPrice@{}s".format(pair.lower(), speed) 61 | else: 62 | stream_name = "{}@indexPrice".format(pair.lower()) 63 | 64 | self.send_message_to_server(stream_name, action=action, id=id) 65 | 66 | def mark_price(self, symbol: str, speed=1, id=None, action=None, **kwargs): 67 | """Mark Price Streams 68 | 69 | Stream Name: @markPrice OR @markPrice@1s 70 | 71 | https://developers.binance.com/docs/derivatives/coin-margined-futures/websocket-market-streams/Mark-Price-Stream 72 | 73 | Update Speed: 3000ms OR 1000ms 74 | """ 75 | if speed == 1: 76 | stream_name = "{}@markPrice@{}s".format(symbol.lower(), speed) 77 | else: 78 | stream_name = "{}@markPrice".format(symbol.lower()) 79 | 80 | self.send_message_to_server(stream_name, action=action, id=id) 81 | 82 | def pair_mark_price(self, pair: str, speed=1, id=None, action=None, **kwargs): 83 | """Mark Price of All Symbols of a Pair 84 | 85 | Stream Name: @markPrice OR @markPrice@1s 86 | 87 | https://developers.binance.com/docs/derivatives/coin-margined-futures/websocket-market-streams/Mark-Price-of-All-Symbols-of-a-Pair 88 | 89 | Update Speed: 3000ms OR 1000ms 90 | """ 91 | if speed == 1: 92 | stream_name = "{}@markPrice@{}s".format(pair.lower(), speed) 93 | else: 94 | stream_name = "{}@markPrice".format(pair.lower()) 95 | 96 | self.send_message_to_server(stream_name, action=action, id=id) 97 | 98 | def kline(self, symbol: str, interval: str, id=None, action=None, **kwargs): 99 | """Kline/Candlestick Streams 100 | 101 | The Kline/Candlestick Stream push updates to the current klines/candlestick every 250 milliseconds (if existing) 102 | 103 | Stream Name: @kline_ 104 | 105 | https://developers.binance.com/docs/derivatives/coin-margined-futures/websocket-market-streams/Kline-Candlestick-Streams 106 | 107 | interval: 108 | m -> minutes; h -> hours; d -> days; w -> weeks; M -> months 109 | 110 | - 1m 111 | - 3m 112 | - 5m 113 | - 15m 114 | - 30m 115 | - 1h 116 | - 2h 117 | - 4h 118 | - 6h 119 | - 8h 120 | - 12h 121 | - 1d 122 | - 3d 123 | - 1w 124 | - 1M 125 | 126 | Update Speed: 250ms 127 | """ 128 | stream_name = "{}@kline_{}".format(symbol.lower(), interval) 129 | 130 | self.send_message_to_server(stream_name, action=action, id=id) 131 | 132 | def continuous_kline( 133 | self, 134 | pair: str, 135 | contractType: str, 136 | interval: str, 137 | id=None, 138 | action=None, 139 | **kwargs 140 | ): 141 | """Continuous Kline/Candlestick Streams 142 | 143 | The Kline/Candlestick Stream push updates to Kline/candlestick bars for a specific contract type. every 250 milliseconds 144 | 145 | Stream Name: _@continuousKline_ 146 | 147 | https://developers.binance.com/docs/derivatives/coin-margined-futures/websocket-market-streams/Continuous-Contract-Kline-Candlestick-Streams 148 | 149 | interval: 150 | m -> minutes; h -> hours; d -> days; w -> weeks; M -> months 151 | 152 | - 1m 153 | - 3m 154 | - 5m 155 | - 15m 156 | - 30m 157 | - 1h 158 | - 2h 159 | - 4h 160 | - 6h 161 | - 8h 162 | - 12h 163 | - 1d 164 | - 3d 165 | - 1w 166 | - 1M 167 | 168 | Update Speed: 250ms 169 | """ 170 | stream_name = "{}_{}@continuousKline_{}".format( 171 | pair.lower(), contractType, interval 172 | ) 173 | 174 | self.send_message_to_server(stream_name, action=action, id=id) 175 | 176 | def index_kline(self, pair: str, interval: str, id=None, action=None, **kwargs): 177 | """Kline/Candlestick chart intervals Streams 178 | 179 | Stream Name: @indexPriceKline_ 180 | 181 | https://developers.binance.com/docs/derivatives/coin-margined-futures/websocket-market-streams/Index-Kline-Candlestick-Streams 182 | 183 | interval: 184 | m -> minutes; h -> hours; d -> days; w -> weeks; M -> months 185 | 186 | - 1m 187 | - 3m 188 | - 5m 189 | - 15m 190 | - 30m 191 | - 1h 192 | - 2h 193 | - 4h 194 | - 6h 195 | - 8h 196 | - 12h 197 | - 1d 198 | - 3d 199 | - 1w 200 | - 1M 201 | 202 | Update Speed: 250ms 203 | """ 204 | stream_name = "{}@indexPriceKline_{}".format(pair.lower(), interval) 205 | 206 | self.send_message_to_server(stream_name, action=action, id=id) 207 | 208 | def mark_kline(self, symbol: str, interval: str, id=None, action=None, **kwargs): 209 | """Kline/Candlestick chart intervals Streams 210 | 211 | Stream Name: @markPriceKline_ 212 | 213 | https://developers.binance.com/docs/derivatives/coin-margined-futures/websocket-market-streams/Mark-Price-Kline-Candlestick-Streams 214 | 215 | interval: 216 | m -> minutes; h -> hours; d -> days; w -> weeks; M -> months 217 | 218 | - 1m 219 | - 3m 220 | - 5m 221 | - 15m 222 | - 30m 223 | - 1h 224 | - 2h 225 | - 4h 226 | - 6h 227 | - 8h 228 | - 12h 229 | - 1d 230 | - 3d 231 | - 1w 232 | - 1M 233 | 234 | Update Speed: 250ms 235 | """ 236 | stream_name = "{}@markPriceKline_{}".format(symbol.lower(), interval) 237 | 238 | self.send_message_to_server(stream_name, action=action, id=id) 239 | 240 | def mini_ticker(self, symbol=None, id=None, action=None, **kwargs): 241 | """Individual symbol or all symbols mini ticker 242 | 243 | 24hr rolling window mini-ticker statistics. 244 | These are NOT the statistics of the UTC day, but a 24hr rolling window for the previous 24hrs 245 | 246 | Stream Name: @miniTicker or 247 | Stream Name: !miniTicker@arr 248 | 249 | https://developers.binance.com/docs/derivatives/coin-margined-futures/websocket-market-streams/Individual-Symbol-Mini-Ticker-Stream 250 | https://developers.binance.com/docs/derivatives/coin-margined-futures/websocket-market-streams/All-Market-Mini-Tickers-Stream 251 | 252 | Update Speed: 500ms for individual symbol, 1000ms for all market symbols 253 | """ 254 | 255 | if symbol is None: 256 | stream_name = "!miniTicker@arr" 257 | else: 258 | stream_name = "{}@miniTicker".format(symbol.lower()) 259 | 260 | self.send_message_to_server(stream_name, action=action, id=id) 261 | 262 | def ticker(self, symbol=None, id=None, action=None, **kwargs): 263 | """Individual symbol or all symbols ticker 264 | 265 | 24hr rolling window ticker statistics for a single symbol. 266 | These are NOT the statistics of the UTC day, but a 24hr rolling window from requestTime to 24hrs before. 267 | 268 | Stream Name: @ticker or 269 | Stream Name: !ticker@arr 270 | 271 | https://developers.binance.com/docs/derivatives/coin-margined-futures/websocket-market-streams/Individual-Symbol-Ticker-Streams 272 | https://developers.binance.com/docs/derivatives/coin-margined-futures/websocket-market-streams/All-Market-Tickers-Streams 273 | 274 | Update Speed: 500ms for individual symbol, 1000ms for all market symbols 275 | """ 276 | 277 | if symbol is None: 278 | stream_name = "!ticker@arr" 279 | else: 280 | stream_name = "{}@ticker".format(symbol.lower()) 281 | self.send_message_to_server(stream_name, action=action, id=id) 282 | 283 | def book_ticker(self, symbol, id=None, action=None, **kwargs): 284 | """Individual symbol or all book ticker 285 | 286 | Pushes any update to the best bid or ask's price or quantity in real-time for a specified symbol. 287 | 288 | Stream Name: @bookTicker or 289 | Stream Name: !bookTicker 290 | 291 | https://developers.binance.com/docs/derivatives/coin-margined-futures/websocket-market-streams/Individual-Symbol-Book-Ticker-Streams 292 | https://developers.binance.com/docs/derivatives/coin-margined-futures/websocket-market-streams/All-Book-Tickers-Stream 293 | 294 | Update Speed: Real-time 295 | """ 296 | if symbol is None: 297 | stream_name = "!bookTicker" 298 | else: 299 | stream_name = "{}@bookTicker".format(symbol.lower()) 300 | self.send_message_to_server(stream_name, action=action, id=id) 301 | 302 | def diff_book_depth(self, symbol: str, speed=100, id=None, action=None, **kwargs): 303 | """Diff. Depth Stream 304 | Order book price and quantity depth updates used to locally manage an order book. 305 | 306 | Stream Name: @depth OR @depth@500ms OR@depth@100ms 307 | 308 | https://developers.binance.com/docs/derivatives/coin-margined-futures/websocket-market-streams/Diff-Book-Depth-Streams 309 | 310 | Update Speed: 250ms, 500ms or 100ms 311 | """ 312 | 313 | self.send_message_to_server( 314 | "{}@depth@{}ms".format(symbol.lower(), speed), action=action, id=id 315 | ) 316 | 317 | def partial_book_depth( 318 | self, symbol: str, level=5, speed=500, id=None, action=None, **kwargs 319 | ): 320 | """Partial Book Depth Streams 321 | 322 | Top bids and asks, Valid are 5, 10, or 20. 323 | 324 | Stream Names: @depth OR @depth@500ms OR @depth@100ms 325 | 326 | https://developers.binance.com/docs/derivatives/coin-margined-futures/websocket-market-streams/Partial-Book-Depth-Streams 327 | 328 | Update Speed: 250ms, 500ms or 100ms 329 | """ 330 | self.send_message_to_server( 331 | "{}@depth{}@{}ms".format(symbol.lower(), level, speed), id=id, action=action 332 | ) 333 | 334 | def liquidation_order(self, symbol: str, id=None, action=None, **kwargs): 335 | """The Liquidation Order Snapshot Streams push force liquidation order information for specific symbol. 336 | The All Liquidation Order Snapshot Streams push force liquidation order information for all symbols in the market. 337 | 338 | For each symbol,only the latest one liquidation order within 1000ms will be pushed as the snapshot. If no liquidation happens in the interval of 1000ms, no stream will be pushed. 339 | 340 | Stream Name: @forceOrder or !forceOrder@arr 341 | 342 | https://developers.binance.com/docs/derivatives/coin-margined-futures/websocket-market-streams/Liquidation-Order-Streams 343 | https://developers.binance.com/docs/derivatives/coin-margined-futures/websocket-market-streams/All-Market-Liquidation-Order-Streams 344 | 345 | Update Speed: 1000ms 346 | """ 347 | if symbol is None: 348 | stream_name = "!forceOrder@arr" 349 | else: 350 | stream_name = "{}@forceOrder".format(symbol.lower()) 351 | self.send_message_to_server(stream_name, id=id, action=action) 352 | 353 | def user_data(self, listen_key: str, id=None, action=None, **kwargs): 354 | """Listen to user data by using the provided listen_key""" 355 | self.send_message_to_server(listen_key, action=action, id=id) 356 | -------------------------------------------------------------------------------- /binance/websocket/um_futures/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/binance/binance-futures-connector-python/a6bfbbf10fe2c1b4eb76fc24ffb82eb94bf9df89/binance/websocket/um_futures/__init__.py -------------------------------------------------------------------------------- /binance/websocket/um_futures/websocket_client.py: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | 3 | from binance.websocket.websocket_client import BinanceWebsocketClient 4 | 5 | 6 | class UMFuturesWebsocketClient(BinanceWebsocketClient): 7 | def __init__( 8 | self, 9 | stream_url="wss://fstream.binance.com", 10 | on_message=None, 11 | on_open=None, 12 | on_close=None, 13 | on_error=None, 14 | on_ping=None, 15 | on_pong=None, 16 | is_combined=False, 17 | proxies: Optional[dict] = None, 18 | ): 19 | if is_combined: 20 | stream_url = stream_url + "/stream" 21 | else: 22 | stream_url = stream_url + "/ws" 23 | super().__init__( 24 | stream_url, 25 | on_message=on_message, 26 | on_open=on_open, 27 | on_close=on_close, 28 | on_error=on_error, 29 | on_ping=on_ping, 30 | on_pong=on_pong, 31 | proxies=proxies, 32 | ) 33 | 34 | def agg_trade(self, symbol: str, id=None, action=None, **kwargs): 35 | """Aggregate Trade Streams 36 | 37 | The Aggregate Trade Streams push market trade information that is aggregated for a single taker order every 100 milliseconds. 38 | Only market trades will be aggregated, which means the insurance fund trades and ADL trades won't be aggregated. 39 | 40 | Stream Name: @aggTrade 41 | 42 | https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Aggregate-Trade-Streams 43 | 44 | Update Speed: 100ms 45 | """ 46 | stream_name = "{}@aggTrade".format(symbol.lower()) 47 | 48 | self.send_message_to_server(stream_name, action=action, id=id) 49 | 50 | def mark_price(self, symbol: str, speed: int, id=None, action=None, **kwargs): 51 | """Mark Price Streams 52 | 53 | Mark price and funding rate for all symbols pushed every 3 seconds or every second. 54 | 55 | Stream Name: @markPrice or @markPrice@1s 56 | 57 | https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Mark-Price-Stream 58 | 59 | Update Speed: 3000ms or 1000ms 60 | """ 61 | stream_name = "{}@markPrice@{}s".format(symbol.lower(), speed) 62 | 63 | self.send_message_to_server(stream_name, action=action, id=id) 64 | 65 | def mark_price_all_market(self, speed=1, id=None, action=None, **kwargs): 66 | """Mark Price Stream for All market 67 | 68 | Stream Name: !markPrice@arr OR !markPrice@arr@1s 69 | 70 | https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Mark-Price-Stream-for-All-market 71 | 72 | Update Speed: 3000ms or 1000ms 73 | """ 74 | if speed == 1: 75 | stream_name = "!markPrice@arr@{}s".format(speed) 76 | else: 77 | stream_name = "!markPrice@arr" 78 | 79 | self.send_message_to_server(stream_name, action=action, id=id) 80 | 81 | def kline(self, symbol: str, interval: str, id=None, action=None, **kwargs): 82 | """Kline/Candlestick Streams 83 | 84 | The Kline/Candlestick Stream push updates to the current klines/candlestick every 250 milliseconds (if existing) 85 | 86 | Stream Name: @kline_ 87 | 88 | https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Kline-Candlestick-Streams 89 | 90 | interval: 91 | m -> minutes; h -> hours; d -> days; w -> weeks; M -> months 92 | 93 | - 1m 94 | - 3m 95 | - 5m 96 | - 15m 97 | - 30m 98 | - 1h 99 | - 2h 100 | - 4h 101 | - 6h 102 | - 8h 103 | - 12h 104 | - 1d 105 | - 3d 106 | - 1w 107 | - 1M 108 | 109 | Update Speed: 250ms 110 | """ 111 | stream_name = "{}@kline_{}".format(symbol.lower(), interval) 112 | 113 | self.send_message_to_server(stream_name, action=action, id=id) 114 | 115 | def continuous_kline( 116 | self, 117 | pair: str, 118 | contractType: str, 119 | interval: str, 120 | id=None, 121 | action=None, 122 | **kwargs 123 | ): 124 | """Continuous Kline/Candlestick Streams 125 | 126 | The Kline/Candlestick Stream push updates to Kline/candlestick bars for a specific contract type. every 250 milliseconds 127 | 128 | Stream Name: _@continuousKline_ 129 | 130 | https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Continuous-Contract-Kline-Candlestick-Streams 131 | 132 | interval: 133 | m -> minutes; h -> hours; d -> days; w -> weeks; M -> months 134 | 135 | - 1m 136 | - 3m 137 | - 5m 138 | - 15m 139 | - 30m 140 | - 1h 141 | - 2h 142 | - 4h 143 | - 6h 144 | - 8h 145 | - 12h 146 | - 1d 147 | - 3d 148 | - 1w 149 | - 1M 150 | 151 | Update Speed: 250ms 152 | """ 153 | stream_name = "{}_{}@continuousKline_{}".format( 154 | pair.lower(), contractType, interval 155 | ) 156 | 157 | self.send_message_to_server(stream_name, action=action, id=id) 158 | 159 | def mini_ticker(self, symbol=None, id=None, action=None, **kwargs): 160 | """Individual symbol or all symbols mini ticker 161 | 162 | 24hr rolling window mini-ticker statistics. 163 | These are NOT the statistics of the UTC day, but a 24hr rolling window for the previous 24hrs 164 | 165 | Stream Name: @miniTicker or 166 | Stream Name: !miniTicker@arr 167 | 168 | https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Individual-Symbol-Mini-Ticker-Stream 169 | https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/All-Market-Mini-Tickers-Stream 170 | 171 | Update Speed: 500ms for individual symbol, 1000ms for all market symbols 172 | """ 173 | 174 | if symbol is None: 175 | stream_name = "!miniTicker@arr" 176 | else: 177 | stream_name = "{}@miniTicker".format(symbol.lower()) 178 | 179 | self.send_message_to_server(stream_name, action=action, id=id) 180 | 181 | def ticker(self, symbol=None, id=None, action=None, **kwargs): 182 | """Individual symbol or all symbols ticker 183 | 184 | 24hr rolling window ticker statistics for a single symbol. 185 | These are NOT the statistics of the UTC day, but a 24hr rolling window from requestTime to 24hrs before. 186 | 187 | Stream Name: @ticker or 188 | Stream Name: !ticker@arr 189 | 190 | https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Individual-Symbol-Ticker-Streams 191 | https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/All-Market-Tickers-Streams 192 | 193 | Update Speed: 500ms for individual symbol, 1000ms for all market symbols 194 | """ 195 | 196 | if symbol is None: 197 | stream_name = "!ticker@arr" 198 | else: 199 | stream_name = "{}@ticker".format(symbol.lower()) 200 | self.send_message_to_server(stream_name, action=action, id=id) 201 | 202 | def book_ticker(self, symbol, id=None, action=None, **kwargs): 203 | """Individual symbol or all book ticker 204 | 205 | Pushes any update to the best bid or ask's price or quantity in real-time for a specified symbol. 206 | 207 | Stream Name: @bookTicker or 208 | Stream Name: !bookTicker 209 | 210 | https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Individual-Symbol-Book-Ticker-Streams 211 | https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/All-Book-Tickers-Stream 212 | 213 | Update Speed: Real-time 214 | """ 215 | if symbol is None: 216 | stream_name = "!bookTicker" 217 | else: 218 | stream_name = "{}@bookTicker".format(symbol.lower()) 219 | self.send_message_to_server(stream_name, action=action, id=id) 220 | 221 | def diff_book_depth(self, symbol: str, speed=100, id=None, action=None, **kwargs): 222 | """Diff. Depth Stream 223 | Order book price and quantity depth updates used to locally manage an order book. 224 | 225 | Stream Name: @depth OR @depth@500ms OR@depth@100ms 226 | 227 | https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Diff-Book-Depth-Streams 228 | 229 | Update Speed: 250ms, 500ms or 100ms 230 | """ 231 | 232 | self.send_message_to_server( 233 | "{}@depth@{}ms".format(symbol.lower(), speed), action=action, id=id 234 | ) 235 | 236 | def partial_book_depth( 237 | self, symbol: str, level=5, speed=500, id=None, action=None, **kwargs 238 | ): 239 | """Partial Book Depth Streams 240 | 241 | Top bids and asks, Valid are 5, 10, or 20. 242 | 243 | Stream Names: @depth OR @depth@500ms OR @depth@100ms 244 | 245 | https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Partial-Book-Depth-Streams 246 | 247 | Update Speed: 250ms, 500ms or 100ms 248 | """ 249 | self.send_message_to_server( 250 | "{}@depth{}@{}ms".format(symbol.lower(), level, speed), id=id, action=action 251 | ) 252 | 253 | def liquidation_order(self, symbol: str, id=None, action=None, **kwargs): 254 | """The Liquidation Order Snapshot Streams push force liquidation order information for specific symbol. 255 | The All Liquidation Order Snapshot Streams push force liquidation order information for all symbols in the market. 256 | 257 | For each symbol,only the latest one liquidation order within 1000ms will be pushed as the snapshot. If no liquidation happens in the interval of 1000ms, no stream will be pushed. 258 | 259 | Stream Name: @forceOrder or 260 | Stream Name: !forceOrder@arr 261 | 262 | https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Liquidation-Order-Streams 263 | https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/All-Market-Liquidation-Order-Streams 264 | 265 | Update Speed: 1000ms 266 | """ 267 | if symbol is None: 268 | stream_name = "!forceOrder@arr" 269 | else: 270 | stream_name = "{}@forceOrder".format(symbol.lower()) 271 | self.send_message_to_server(stream_name, id=id, action=action) 272 | 273 | def composite_index(self, symbol: str, id=None, action=None, **kwargs): 274 | """Composite Index Info Stream 275 | Composite index information for index symbols pushed every second. 276 | 277 | Stream Name: @compositeIndex 278 | 279 | https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Composite-Index-Symbol-Information-Streams 280 | 281 | Update Speed: 1000ms 282 | """ 283 | 284 | self.send_message_to_server( 285 | "{}@compositeIndex".format(symbol.lower()), id=id, action=action 286 | ) 287 | 288 | def user_data(self, listen_key: str, id=None, action=None, **kwargs): 289 | """Listen to user data by using the provided listen_key""" 290 | self.send_message_to_server(listen_key, action=action, id=id) 291 | -------------------------------------------------------------------------------- /binance/websocket/websocket_client.py: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | 3 | import json 4 | import logging 5 | 6 | from binance.lib.utils import get_timestamp 7 | from binance.websocket.binance_socket_manager import BinanceSocketManager 8 | 9 | 10 | class BinanceWebsocketClient: 11 | ACTION_SUBSCRIBE = "SUBSCRIBE" 12 | ACTION_UNSUBSCRIBE = "UNSUBSCRIBE" 13 | 14 | def __init__( 15 | self, 16 | stream_url, 17 | on_message=None, 18 | on_open=None, 19 | on_close=None, 20 | on_error=None, 21 | on_ping=None, 22 | on_pong=None, 23 | logger=None, 24 | proxies: Optional[dict] = None, 25 | ): 26 | if not logger: 27 | logger = logging.getLogger(__name__) 28 | self.logger = logger 29 | self.socket_manager = self._initialize_socket( 30 | stream_url, 31 | on_message, 32 | on_open, 33 | on_close, 34 | on_error, 35 | on_ping, 36 | on_pong, 37 | logger, 38 | proxies, 39 | ) 40 | 41 | # start the thread 42 | self.socket_manager.start() 43 | self.logger.debug("Binance WebSocket Client started.") 44 | 45 | def _initialize_socket( 46 | self, 47 | stream_url, 48 | on_message, 49 | on_open, 50 | on_close, 51 | on_error, 52 | on_ping, 53 | on_pong, 54 | logger, 55 | proxies, 56 | ): 57 | return BinanceSocketManager( 58 | stream_url, 59 | on_message=on_message, 60 | on_open=on_open, 61 | on_close=on_close, 62 | on_error=on_error, 63 | on_ping=on_ping, 64 | on_pong=on_pong, 65 | logger=logger, 66 | proxies=proxies, 67 | ) 68 | 69 | def _single_stream(self, stream): 70 | if isinstance(stream, str): 71 | return True 72 | elif isinstance(stream, list): 73 | return False 74 | else: 75 | raise ValueError("Invalid stream name, expect string or array") 76 | 77 | def send(self, message: dict): 78 | self.socket_manager.send_message(json.dumps(message)) 79 | 80 | def send_message_to_server(self, message, action=None, id=None): 81 | if not id: 82 | id = get_timestamp() 83 | 84 | if action != self.ACTION_UNSUBSCRIBE: 85 | return self.subscribe(message, id=id) 86 | return self.unsubscribe(message, id=id) 87 | 88 | def subscribe(self, stream, id=None): 89 | if not id: 90 | id = get_timestamp() 91 | if self._single_stream(stream): 92 | stream = [stream] 93 | json_msg = json.dumps({"method": "SUBSCRIBE", "params": stream, "id": id}) 94 | self.socket_manager.send_message(json_msg) 95 | 96 | def unsubscribe(self, stream, id=None): 97 | if not id: 98 | id = get_timestamp() 99 | if self._single_stream(stream): 100 | stream = [stream] 101 | json_msg = json.dumps({"method": "UNSUBSCRIBE", "params": stream, "id": id}) 102 | self.socket_manager.send_message(json_msg) 103 | 104 | def ping(self): 105 | self.logger.debug("Sending ping to Binance WebSocket Server") 106 | self.socket_manager.ping() 107 | 108 | def stop(self, id=None): 109 | self.socket_manager.close() 110 | self.socket_manager.join() 111 | 112 | def list_subscribe(self, id=None): 113 | """sending the list subscription message, e.g. 114 | 115 | {"method": "LIST_SUBSCRIPTIONS","id": 100} 116 | 117 | """ 118 | 119 | if not id: 120 | id = get_timestamp() 121 | self.socket_manager.send_message( 122 | json.dumps({"method": "LIST_SUBSCRIPTIONS", "id": id}) 123 | ) 124 | -------------------------------------------------------------------------------- /examples/cm_futures/market/agg_trades.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.cm_futures import CMFutures 4 | from binance.lib.utils import config_logging 5 | 6 | config_logging(logging, logging.DEBUG) 7 | 8 | cm_futures_client = CMFutures() 9 | logging.info(cm_futures_client.agg_trades("BTCUSD_PERP")) 10 | -------------------------------------------------------------------------------- /examples/cm_futures/market/basis.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.cm_futures import CMFutures 4 | from binance.lib.utils import config_logging 5 | 6 | config_logging(logging, logging.DEBUG) 7 | 8 | cm_futures_client = CMFutures() 9 | 10 | logging.info(cm_futures_client.basis("BTCUSD", "PERPETUAL", "1d")) 11 | -------------------------------------------------------------------------------- /examples/cm_futures/market/book_ticker.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.cm_futures import CMFutures 4 | from binance.lib.utils import config_logging 5 | 6 | config_logging(logging, logging.DEBUG) 7 | 8 | cm_futures_client = CMFutures() 9 | 10 | logging.info(cm_futures_client.book_ticker("BTCUSD_PERP")) 11 | -------------------------------------------------------------------------------- /examples/cm_futures/market/continuous_klines.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.cm_futures import CMFutures 4 | from binance.lib.utils import config_logging 5 | 6 | config_logging(logging, logging.DEBUG) 7 | 8 | cm_futures_client = CMFutures() 9 | logging.info(cm_futures_client.continuous_klines("BTCUSD", "PERPETUAL", "1d")) 10 | -------------------------------------------------------------------------------- /examples/cm_futures/market/depth.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.cm_futures import CMFutures 4 | from binance.lib.utils import config_logging 5 | 6 | config_logging(logging, logging.DEBUG) 7 | 8 | cm_futures_client = CMFutures() 9 | 10 | logging.info(cm_futures_client.depth("BTCUSD_PERP", **{"limit": 5})) 11 | -------------------------------------------------------------------------------- /examples/cm_futures/market/exchange_info.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.cm_futures import CMFutures 4 | from binance.lib.utils import config_logging 5 | 6 | config_logging(logging, logging.DEBUG) 7 | 8 | cm_futures_client = CMFutures() 9 | logging.info(cm_futures_client.exchange_info()) 10 | -------------------------------------------------------------------------------- /examples/cm_futures/market/funding_rate.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from binance.cm_futures import CMFutures 3 | import logging 4 | from binance.lib.utils import config_logging 5 | 6 | config_logging(logging, logging.DEBUG) 7 | 8 | cm_futures_client = CMFutures() 9 | logging.info(cm_futures_client.funding_rate("BTCUSD_PERP", **{"limit": 100})) 10 | -------------------------------------------------------------------------------- /examples/cm_futures/market/historical_trades.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.cm_futures import CMFutures 4 | from binance.lib.utils import config_logging 5 | 6 | config_logging(logging, logging.DEBUG) 7 | 8 | key = "" 9 | 10 | # historical_trades requires api key in request header 11 | cm_futures_client = CMFutures(key=key) 12 | logging.info(cm_futures_client.historical_trades("BTCUSD_PERP", **{"limit": 10})) 13 | -------------------------------------------------------------------------------- /examples/cm_futures/market/index_price_kline.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.cm_futures import CMFutures 4 | from binance.lib.utils import config_logging 5 | 6 | config_logging(logging, logging.DEBUG) 7 | 8 | cm_futures_client = CMFutures() 9 | 10 | logging.info(cm_futures_client.index_price_klines("BTCUSD", "1d", **{"limit": 500})) 11 | -------------------------------------------------------------------------------- /examples/cm_futures/market/klines.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.cm_futures import CMFutures 4 | from binance.lib.utils import config_logging 5 | 6 | config_logging(logging, logging.DEBUG) 7 | 8 | cm_futures_client = CMFutures() 9 | 10 | logging.info(cm_futures_client.klines("BTCUSD_PERP", "1d")) 11 | -------------------------------------------------------------------------------- /examples/cm_futures/market/mark_price.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.cm_futures import CMFutures 4 | from binance.lib.utils import config_logging 5 | 6 | config_logging(logging, logging.DEBUG) 7 | 8 | cm_futures_client = CMFutures() 9 | 10 | logging.info(cm_futures_client.mark_price("BTCUSD_PERP")) 11 | -------------------------------------------------------------------------------- /examples/cm_futures/market/mark_price_klines.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.cm_futures import CMFutures 4 | from binance.lib.utils import config_logging 5 | 6 | config_logging(logging, logging.DEBUG) 7 | 8 | cm_futures_client = CMFutures() 9 | 10 | logging.info(cm_futures_client.mark_price_klines("FTMUSD_PERP", "1d", **{"limit": 500})) 11 | -------------------------------------------------------------------------------- /examples/cm_futures/market/open_interest.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.cm_futures import CMFutures 4 | from binance.lib.utils import config_logging 5 | 6 | config_logging(logging, logging.DEBUG) 7 | 8 | cm_futures_client = CMFutures() 9 | 10 | logging.info(cm_futures_client.open_interest("BTCUSD_PERP")) 11 | -------------------------------------------------------------------------------- /examples/cm_futures/market/open_interest_hist.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.cm_futures import CMFutures 4 | from binance.lib.utils import config_logging 5 | 6 | config_logging(logging, logging.DEBUG) 7 | 8 | cm_futures_client = CMFutures() 9 | 10 | logging.info( 11 | cm_futures_client.open_interest_hist("BTCUSD", "PERPETUAL", "1h", **{"limit": 30}) 12 | ) 13 | -------------------------------------------------------------------------------- /examples/cm_futures/market/ping.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.cm_futures import CMFutures 4 | from binance.lib.utils import config_logging 5 | 6 | config_logging(logging, logging.DEBUG) 7 | 8 | cm_futures_client = CMFutures() 9 | logging.info(cm_futures_client.ping()) 10 | -------------------------------------------------------------------------------- /examples/cm_futures/market/query_index_price_constituents.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.cm_futures import CMFutures 4 | from binance.lib.utils import config_logging 5 | 6 | config_logging(logging, logging.DEBUG) 7 | 8 | cm_futures_client = CMFutures() 9 | logging.info(cm_futures_client.query_index_price_constituents(symbol="BTCUSD")) 10 | -------------------------------------------------------------------------------- /examples/cm_futures/market/taker_long_short_ratio.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.cm_futures import CMFutures 4 | from binance.lib.utils import config_logging 5 | 6 | config_logging(logging, logging.DEBUG) 7 | 8 | cm_futures_client = CMFutures() 9 | 10 | logging.info(cm_futures_client.taker_long_short_ratio("BTCUSD", "PERPETUAL", "1d")) 11 | -------------------------------------------------------------------------------- /examples/cm_futures/market/ticker_24hr_price_change.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.cm_futures import CMFutures 4 | from binance.lib.utils import config_logging 5 | 6 | config_logging(logging, logging.DEBUG) 7 | 8 | cm_futures_client = CMFutures() 9 | 10 | logging.info(cm_futures_client.ticker_24hr_price_change("BTCUSD_PERP")) 11 | -------------------------------------------------------------------------------- /examples/cm_futures/market/ticker_price.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.cm_futures import CMFutures 4 | from binance.lib.utils import config_logging 5 | 6 | config_logging(logging, logging.DEBUG) 7 | 8 | cm_futures_client = CMFutures() 9 | 10 | logging.info(cm_futures_client.ticker_price("BTCUSD_PERP")) 11 | -------------------------------------------------------------------------------- /examples/cm_futures/market/time.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.cm_futures import CMFutures 4 | from binance.lib.utils import config_logging 5 | 6 | config_logging(logging, logging.DEBUG) 7 | 8 | cm_futures_client = CMFutures(show_limit_usage=True) 9 | 10 | logging.info(cm_futures_client.time()) 11 | -------------------------------------------------------------------------------- /examples/cm_futures/market/top_long_short_account_ratio.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.cm_futures import CMFutures 4 | from binance.lib.utils import config_logging 5 | 6 | config_logging(logging, logging.DEBUG) 7 | 8 | cm_futures_client = CMFutures() 9 | 10 | logging.info(cm_futures_client.long_short_account_ratio("BTCUSD", "1d")) 11 | -------------------------------------------------------------------------------- /examples/cm_futures/market/top_long_short_position_ratio.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.cm_futures import CMFutures 4 | from binance.lib.utils import config_logging 5 | 6 | config_logging(logging, logging.DEBUG) 7 | 8 | cm_futures_client = CMFutures() 9 | 10 | logging.info( 11 | cm_futures_client.top_long_short_position_ratio("BTCUSD", "1h", **{"limit": 30}) 12 | ) 13 | -------------------------------------------------------------------------------- /examples/cm_futures/market/trades.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.cm_futures import CMFutures 4 | from binance.lib.utils import config_logging 5 | 6 | config_logging(logging, logging.DEBUG) 7 | 8 | cm_futures_client = CMFutures() 9 | 10 | logging.info(cm_futures_client.trades("BTCUSD_PERP", limit=500)) 11 | -------------------------------------------------------------------------------- /examples/cm_futures/stream/close_listen_key.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.cm_futures import CMFutures 4 | from binance.lib.utils import config_logging 5 | 6 | config_logging(logging, logging.DEBUG) 7 | 8 | key = "" 9 | 10 | cm_futures_client = CMFutures(key=key) 11 | 12 | logging.info(cm_futures_client.close_listen_key("the_listen_key")) 13 | -------------------------------------------------------------------------------- /examples/cm_futures/stream/new_listen_key.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.cm_futures import CMFutures 4 | from binance.lib.utils import config_logging 5 | 6 | config_logging(logging, logging.DEBUG) 7 | 8 | key = "" 9 | 10 | cm_futures_client = CMFutures(key=key) 11 | 12 | logging.info(cm_futures_client.new_listen_key()) 13 | -------------------------------------------------------------------------------- /examples/cm_futures/stream/renew_listen_key.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.cm_futures import CMFutures 4 | from binance.lib.utils import config_logging 5 | 6 | config_logging(logging, logging.DEBUG) 7 | 8 | key = "" 9 | 10 | cm_futures_client = CMFutures(key=key) 11 | 12 | logging.info(cm_futures_client.renew_listen_key("the_listen_key")) 13 | -------------------------------------------------------------------------------- /examples/cm_futures/trade/cancel_batch_orders.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.cm_futures import CMFutures as Client 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | client = Client(key, secret, base_url="https://dapi.binance.com") 13 | 14 | try: 15 | response = client.cancel_batch_order( 16 | symbol="BTCUSD_PERP", orderIdList=[1234567, 2345678], recvWindow=2000 17 | ) 18 | logging.info(response) 19 | except ClientError as error: 20 | logging.error( 21 | "Found error. status: {}, error code: {}, error message: {}".format( 22 | error.status_code, error.error_code, error.error_message 23 | ) 24 | ) 25 | -------------------------------------------------------------------------------- /examples/cm_futures/trade/cancel_open_orders.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.cm_futures import CMFutures as Client 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | client = Client(key, secret, base_url="https://dapi.binance.com") 13 | 14 | try: 15 | response = client.cancel_open_orders(symbol="BTCUSD_PERP", recvWindow=2000) 16 | logging.info(response) 17 | except ClientError as error: 18 | logging.error( 19 | "Found error. status: {}, error code: {}, error message: {}".format( 20 | error.status_code, error.error_code, error.error_message 21 | ) 22 | ) 23 | -------------------------------------------------------------------------------- /examples/cm_futures/trade/cancel_order.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.cm_futures import CMFutures as Client 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | client = Client(key, secret, base_url="https://dapi.binance.com") 13 | 14 | try: 15 | response = client.cancel_order( 16 | symbol="BTCUSD_PERP", orderId=123456, recvWindow=2000 17 | ) 18 | logging.info(response) 19 | except ClientError as error: 20 | logging.error( 21 | "Found error. status: {}, error code: {}, error message: {}".format( 22 | error.status_code, error.error_code, error.error_message 23 | ) 24 | ) 25 | -------------------------------------------------------------------------------- /examples/cm_futures/trade/change_leverage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.cm_futures import CMFutures as Client 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | client = Client(key, secret, base_url="https://dapi.binance.com") 13 | 14 | try: 15 | response = client.change_leverage(symbol="BTCUSD_PERP", leverage=2, recvWindow=6000) 16 | logging.info(response) 17 | except ClientError as error: 18 | logging.error( 19 | "Found error. status: {}, error code: {}, error message: {}".format( 20 | error.status_code, error.error_code, error.error_message 21 | ) 22 | ) 23 | -------------------------------------------------------------------------------- /examples/cm_futures/trade/change_margin_type.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.cm_futures import CMFutures as Client 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | client = Client(key, secret, base_url="https://dapi.binance.com") 13 | 14 | try: 15 | response = client.change_margin_type( 16 | symbol="BTCUSD_PERP", marginType="ISOLATED", recvWindow=6000 17 | ) 18 | logging.info(response) 19 | except ClientError as error: 20 | logging.error( 21 | "Found error. status: {}, error code: {}, error message: {}".format( 22 | error.status_code, error.error_code, error.error_message 23 | ) 24 | ) 25 | -------------------------------------------------------------------------------- /examples/cm_futures/trade/change_position_mode.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.cm_futures import CMFutures as Client 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | client = Client(key, secret, base_url="https://dapi.binance.com") 13 | 14 | try: 15 | response = client.change_position_mode(dualSidePosition="true", recvWindow=2000) 16 | logging.info(response) 17 | except ClientError as error: 18 | logging.error( 19 | "Found error. status: {}, error code: {}, error message: {}".format( 20 | error.status_code, error.error_code, error.error_message 21 | ) 22 | ) 23 | -------------------------------------------------------------------------------- /examples/cm_futures/trade/countdown_cancel_order.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.cm_futures import CMFutures as Client 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | client = Client(key, secret, base_url="https://dapi.binance.com") 13 | 14 | try: 15 | response = client.countdown_cancel_order( 16 | symbol="BTCUSD_PERP", countdownTime=1000, recvWindow=2000 17 | ) 18 | logging.info(response) 19 | except ClientError as error: 20 | logging.error( 21 | "Found error. status: {}, error code: {}, error message: {}".format( 22 | error.status_code, error.error_code, error.error_message 23 | ) 24 | ) 25 | -------------------------------------------------------------------------------- /examples/cm_futures/trade/get_account.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.cm_futures import CMFutures as Client 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | # HMAC authentication with API key and secret 10 | key = "" 11 | secret = "" 12 | 13 | hmac_client = Client(key=key, secret=secret) 14 | logging.info(hmac_client.account(recvWindow=6000)) 15 | 16 | # RSA authentication with RSA key 17 | key = "" 18 | with open("/Users/john/private_key.pem", "r") as f: 19 | private_key = f.read() 20 | 21 | rsa_client = Client(key=key, private_key=private_key) 22 | 23 | try: 24 | response = rsa_client.account(recvWindow=6000) 25 | logging.info(response) 26 | except ClientError as error: 27 | logging.error( 28 | "Found error. status: {}, error code: {}, error message: {}".format( 29 | error.status_code, error.error_code, error.error_message 30 | ) 31 | ) 32 | -------------------------------------------------------------------------------- /examples/cm_futures/trade/get_account_trades.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.cm_futures import CMFutures as Client 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | client = Client(key, secret, base_url="https://dapi.binance.com") 13 | 14 | try: 15 | response = client.get_account_trades(symbol="BTCUSDT", recvWindow=6000) 16 | logging.info(response) 17 | except ClientError as error: 18 | logging.error( 19 | "Found error. status: {}, error code: {}, error message: {}".format( 20 | error.status_code, error.error_code, error.error_message 21 | ) 22 | ) 23 | -------------------------------------------------------------------------------- /examples/cm_futures/trade/get_adl_quantile.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.cm_futures import CMFutures as Client 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | client = Client(key, secret, base_url="https://dapi.binance.com") 13 | 14 | try: 15 | response = client.adl_quantile(symbol="BTCUSDT", recvWindow=6000) 16 | logging.info(response) 17 | except ClientError as error: 18 | logging.error( 19 | "Found error. status: {}, error code: {}, error message: {}".format( 20 | error.status_code, error.error_code, error.error_message 21 | ) 22 | ) 23 | -------------------------------------------------------------------------------- /examples/cm_futures/trade/get_all_orders.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.cm_futures import CMFutures as Client 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | client = Client(key, secret, base_url="https://dapi.binance.com") 13 | 14 | try: 15 | response = client.get_all_orders(symbol="BTCUSD_PERP", recvWindow=2000) 16 | logging.info(response) 17 | except ClientError as error: 18 | logging.error( 19 | "Found error. status: {}, error code: {}, error message: {}".format( 20 | error.status_code, error.error_code, error.error_message 21 | ) 22 | ) 23 | -------------------------------------------------------------------------------- /examples/cm_futures/trade/get_balance.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.cm_futures import CMFutures as Client 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | client = Client(key, secret, base_url="https://dapi.binance.com") 13 | 14 | try: 15 | response = client.balance(recvWindow=6000) 16 | logging.info(response) 17 | except ClientError as error: 18 | logging.error( 19 | "Found error. status: {}, error code: {}, error message: {}".format( 20 | error.status_code, error.error_code, error.error_message 21 | ) 22 | ) 23 | -------------------------------------------------------------------------------- /examples/cm_futures/trade/get_commission_rate.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.cm_futures import CMFutures as Client 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | client = Client(key, secret, base_url="https://dapi.binance.com") 13 | 14 | try: 15 | response = client.commission_rate(symbol="BTCUSD_PERP", recvWindow=6000) 16 | logging.info(response) 17 | except ClientError as error: 18 | logging.error( 19 | "Found error. status: {}, error code: {}, error message: {}".format( 20 | error.status_code, error.error_code, error.error_message 21 | ) 22 | ) 23 | -------------------------------------------------------------------------------- /examples/cm_futures/trade/get_download_id_transaction_history.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.cm_futures import CMFutures as Client 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | client = Client(key, secret, base_url="https://dapi.binance.com") 13 | 14 | try: 15 | response = client.get_download_id_transaction_history( 16 | startTime=1641102712000, endTime=1651470712000 17 | ) 18 | logging.info(response) 19 | except ClientError as error: 20 | logging.error( 21 | "Found error. status: {}, error code: {}, error message: {}".format( 22 | error.status_code, error.error_code, error.error_message 23 | ) 24 | ) 25 | -------------------------------------------------------------------------------- /examples/cm_futures/trade/get_force_orders.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.cm_futures import CMFutures as Client 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | client = Client(key, secret, base_url="https://dapi.binance.com") 13 | 14 | try: 15 | response = client.force_orders(recvWindow=6000) 16 | logging.info(response) 17 | except ClientError as error: 18 | logging.error( 19 | "Found error. status: {}, error code: {}, error message: {}".format( 20 | error.status_code, error.error_code, error.error_message 21 | ) 22 | ) 23 | -------------------------------------------------------------------------------- /examples/cm_futures/trade/get_income_history.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.cm_futures import CMFutures as Client 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | client = Client(key, secret, base_url="https://dapi.binance.com") 13 | 14 | try: 15 | response = client.get_income_history(recvWindow=6000) 16 | logging.info(response) 17 | except ClientError as error: 18 | logging.error( 19 | "Found error. status: {}, error code: {}, error message: {}".format( 20 | error.status_code, error.error_code, error.error_message 21 | ) 22 | ) 23 | -------------------------------------------------------------------------------- /examples/cm_futures/trade/get_leverage_brackets.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.cm_futures import CMFutures as Client 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | client = Client(key, secret, base_url="https://dapi.binance.com") 13 | 14 | try: 15 | response = client.leverage_brackets(symbol="BTCUSD_PERP", recvWindow=6000) 16 | logging.info(response) 17 | except ClientError as error: 18 | logging.error( 19 | "Found error. status: {}, error code: {}, error message: {}".format( 20 | error.status_code, error.error_code, error.error_message 21 | ) 22 | ) 23 | -------------------------------------------------------------------------------- /examples/cm_futures/trade/get_open_orders.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.cm_futures import CMFutures as Client 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | client = Client(key, secret, base_url="https://dapi.binance.com") 13 | 14 | try: 15 | response = client.get_open_orders( 16 | symbol="BTCUSD_PERP", orderId=35298599362, recvWindow=2000 17 | ) 18 | logging.info(response) 19 | except ClientError as error: 20 | logging.error( 21 | "Found error. status: {}, error code: {}, error message: {}".format( 22 | error.status_code, error.error_code, error.error_message 23 | ) 24 | ) 25 | -------------------------------------------------------------------------------- /examples/cm_futures/trade/get_order.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.cm_futures import CMFutures as Client 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | client = Client(key, secret, base_url="https://dapi.binance.com") 13 | 14 | try: 15 | response = client.get_orders(symbol="BTCUSD_PERP", recvWindow=2000) 16 | logging.info(response) 17 | except ClientError as error: 18 | logging.error( 19 | "Found error. status: {}, error code: {}, error message: {}".format( 20 | error.status_code, error.error_code, error.error_message 21 | ) 22 | ) 23 | -------------------------------------------------------------------------------- /examples/cm_futures/trade/get_order_modify_history.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.cm_futures import CMFutures as Client 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | client = Client(key, secret, base_url="https://dapi.binance.com") 13 | 14 | try: 15 | response = client.order_modify_history(symbol="BTCUSD_PERP", orderId=11234345) 16 | logging.info(response) 17 | except ClientError as error: 18 | logging.error( 19 | "Found error. status: {}, error code: {}, error message: {}".format( 20 | error.status_code, error.error_code, error.error_message 21 | ) 22 | ) 23 | -------------------------------------------------------------------------------- /examples/cm_futures/trade/get_position_margin_history.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.cm_futures import CMFutures as Client 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | client = Client(key, secret, base_url="https://dapi.binance.com") 13 | try: 14 | response = client.get_position_margin_history(symbol="BTCUSD_PERP", recvWindow=6000) 15 | logging.info(response) 16 | except ClientError as error: 17 | logging.error( 18 | "Found error. status: {}, error code: {}, error message: {}".format( 19 | error.status_code, error.error_code, error.error_message 20 | ) 21 | ) 22 | -------------------------------------------------------------------------------- /examples/cm_futures/trade/get_position_mode.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.cm_futures import CMFutures as Client 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | client = Client(key, secret, base_url="https://dapi.binance.com") 13 | 14 | try: 15 | response = client.get_position_mode(recvWindow=2000) 16 | logging.info(response) 17 | except ClientError as error: 18 | logging.error( 19 | "Found error. status: {}, error code: {}, error message: {}".format( 20 | error.status_code, error.error_code, error.error_message 21 | ) 22 | ) 23 | -------------------------------------------------------------------------------- /examples/cm_futures/trade/get_position_risk.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.cm_futures import CMFutures as Client 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | client = Client(key, secret, base_url="https://dapi.binance.com") 13 | try: 14 | response = client.get_position_risk(recvWindow=6000) 15 | logging.info(response) 16 | except ClientError as error: 17 | logging.error( 18 | "Found error. status: {}, error code: {}, error message: {}".format( 19 | error.status_code, error.error_code, error.error_message 20 | ) 21 | ) 22 | -------------------------------------------------------------------------------- /examples/cm_futures/trade/modify_batch_order.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.cm_futures import CMFutures as Client 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | client = Client(key, secret, base_url="https://dapi.binance.com") 13 | 14 | params = [ 15 | { 16 | "symbol": "BNBUSD_PERP", 17 | "side": "BUY", 18 | "type": "LIMIT", 19 | "quantity": "1", 20 | "price": "400", 21 | "timeInForce": "GTC", 22 | } 23 | ] 24 | 25 | try: 26 | response = client.modify_batch_order(params) 27 | logging.info(response) 28 | except ClientError as error: 29 | logging.error( 30 | "Found error. status: {}, error code: {}, error message: {}".format( 31 | error.status_code, error.error_code, error.error_message 32 | ) 33 | ) 34 | -------------------------------------------------------------------------------- /examples/cm_futures/trade/modify_isolated_position_margin.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.cm_futures import CMFutures as Client 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | client = Client(key, secret, base_url="https://dapi.binance.com") 13 | try: 14 | response = client.modify_isolated_position_margin( 15 | symbol="BTCUSD_PERP", amount=100, type=1, recvWindow=6000 16 | ) 17 | logging.info(response) 18 | except ClientError as error: 19 | logging.error( 20 | "Found error. status: {}, error code: {}, error message: {}".format( 21 | error.status_code, error.error_code, error.error_message 22 | ) 23 | ) 24 | -------------------------------------------------------------------------------- /examples/cm_futures/trade/modify_order.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.cm_futures import CMFutures as Client 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | client = Client(key, secret, base_url="https://dapi.binance.com") 13 | 14 | try: 15 | response = client.modify_order(symbol="BTCUSD_PERP", orderId=1123323, quantity=0.01) 16 | logging.info(response) 17 | except ClientError as error: 18 | logging.error( 19 | "Found error. status: {}, error code: {}, error message: {}".format( 20 | error.status_code, error.error_code, error.error_message 21 | ) 22 | ) 23 | -------------------------------------------------------------------------------- /examples/cm_futures/trade/new_batch_order.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.cm_futures import CMFutures as Client 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | client = Client(key, secret, base_url="https://dapi.binance.com") 13 | 14 | params = [ 15 | { 16 | "symbol": "BTCUSD_PERP", 17 | "side": "BUY", 18 | "type": "LIMIT", 19 | "quantity": "0.001", 20 | "timeInForce": "GTC", 21 | "price": "60000.1", 22 | } 23 | ] 24 | 25 | try: 26 | response = client.new_batch_order(params) 27 | logging.info(response) 28 | except ClientError as error: 29 | logging.error( 30 | "Found error. status: {}, error code: {}, error message: {}".format( 31 | error.status_code, error.error_code, error.error_message 32 | ) 33 | ) 34 | -------------------------------------------------------------------------------- /examples/cm_futures/trade/new_order.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.cm_futures import CMFutures as Client 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | client = Client(key, secret, base_url="https://dapi.binance.com") 13 | 14 | try: 15 | response = client.new_order( 16 | symbol="BTCUSD_PERP", 17 | side="SELL", 18 | type="LIMIT", 19 | quantity=0.001, 20 | timeInForce="GTC", 21 | price=59808.02, 22 | ) 23 | logging.info(response) 24 | except ClientError as error: 25 | logging.error( 26 | "Found error. status: {}, error code: {}, error message: {}".format( 27 | error.status_code, error.error_code, error.error_message 28 | ) 29 | ) 30 | -------------------------------------------------------------------------------- /examples/cm_futures/trade/query_order.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import logging 4 | from binance.cm_futures import CMFutures as Client 5 | from binance.lib.utils import config_logging 6 | from binance.error import ClientError 7 | 8 | config_logging(logging, logging.DEBUG) 9 | 10 | key = "" 11 | secret = "" 12 | 13 | client = Client(key, secret, base_url="https://dapi.binance.com") 14 | 15 | try: 16 | response = client.query_order( 17 | symbol="BTCUSD_PERP", orderId=12345678, recvWindow=2000 18 | ) 19 | logging.info(response) 20 | except ClientError as error: 21 | logging.error( 22 | "Found error. status: {}, error code: {}, error message: {}".format( 23 | error.status_code, error.error_code, error.error_message 24 | ) 25 | ) 26 | -------------------------------------------------------------------------------- /examples/um_futures/convert/accept_offered_quote.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | um_futures_client = UMFutures(key=key, secret=secret) 13 | 14 | try: 15 | response = um_futures_client.accept_offered_quote(quoteId="1") 16 | logging.info(response) 17 | except ClientError as error: 18 | logging.error( 19 | "Found error. status: {}, error code: {}, error message: {}".format( 20 | error.status_code, error.error_code, error.error_message 21 | ) 22 | ) 23 | -------------------------------------------------------------------------------- /examples/um_futures/convert/list_all_convert_pairs.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | um_futures_client = UMFutures(key=key, secret=secret) 13 | 14 | try: 15 | response = um_futures_client.list_all_convert_pairs(fromAsset="BNB") 16 | logging.info(response) 17 | except ClientError as error: 18 | logging.error( 19 | "Found error. status: {}, error code: {}, error message: {}".format( 20 | error.status_code, error.error_code, error.error_message 21 | ) 22 | ) 23 | -------------------------------------------------------------------------------- /examples/um_futures/convert/order_status.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | um_futures_client = UMFutures(key=key, secret=secret) 13 | 14 | try: 15 | response = um_futures_client.order_status(orderId="1") 16 | logging.info(response) 17 | except ClientError as error: 18 | logging.error( 19 | "Found error. status: {}, error code: {}, error message: {}".format( 20 | error.status_code, error.error_code, error.error_message 21 | ) 22 | ) 23 | -------------------------------------------------------------------------------- /examples/um_futures/convert/send_quote_request.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | um_futures_client = UMFutures(key=key, secret=secret) 13 | 14 | try: 15 | response = um_futures_client.send_quote_request( 16 | fromAsset="BNB", toAsset="USDT", fromAmount=0.1 17 | ) 18 | logging.info(response) 19 | except ClientError as error: 20 | logging.error( 21 | "Found error. status: {}, error code: {}, error message: {}".format( 22 | error.status_code, error.error_code, error.error_message 23 | ) 24 | ) 25 | -------------------------------------------------------------------------------- /examples/um_futures/market/agg_trades.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | 6 | config_logging(logging, logging.DEBUG) 7 | 8 | um_futures_client = UMFutures() 9 | logging.info(um_futures_client.agg_trades("BTCUSDT")) 10 | -------------------------------------------------------------------------------- /examples/um_futures/market/asset_index.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | 6 | config_logging(logging, logging.DEBUG) 7 | 8 | um_futures_client = UMFutures() 9 | 10 | logging.info(um_futures_client.asset_Index("BTCUSD")) 11 | -------------------------------------------------------------------------------- /examples/um_futures/market/blvt_kline.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | 6 | config_logging(logging, logging.DEBUG) 7 | 8 | um_futures_client = UMFutures() 9 | 10 | logging.info(um_futures_client.blvt_kline("BTCDOWN", "5m")) 11 | -------------------------------------------------------------------------------- /examples/um_futures/market/book_ticker.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | 6 | config_logging(logging, logging.DEBUG) 7 | 8 | um_futures_client = UMFutures() 9 | 10 | logging.info(um_futures_client.book_ticker("BTCUSDT")) 11 | -------------------------------------------------------------------------------- /examples/um_futures/market/continuous_klines.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | 6 | config_logging(logging, logging.DEBUG) 7 | 8 | um_futures_client = UMFutures() 9 | logging.info(um_futures_client.continuous_klines("BTCUSDT", "PERPETUAL", "1d")) 10 | -------------------------------------------------------------------------------- /examples/um_futures/market/depth.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | 6 | config_logging(logging, logging.DEBUG) 7 | 8 | um_futures_client = UMFutures() 9 | 10 | logging.info(um_futures_client.depth("BTCUSDT", **{"limit": 5})) 11 | -------------------------------------------------------------------------------- /examples/um_futures/market/exchange_info.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | 6 | config_logging(logging, logging.DEBUG) 7 | 8 | um_futures_client = UMFutures() 9 | logging.info(um_futures_client.exchange_info()) 10 | -------------------------------------------------------------------------------- /examples/um_futures/market/funding_info.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | 6 | config_logging(logging, logging.DEBUG) 7 | 8 | um_futures_client = UMFutures() 9 | logging.info(um_futures_client.funding_info()) 10 | -------------------------------------------------------------------------------- /examples/um_futures/market/funding_rate.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from binance.um_futures import UMFutures 3 | import logging 4 | from binance.lib.utils import config_logging 5 | 6 | config_logging(logging, logging.DEBUG) 7 | 8 | um_futures_client = UMFutures() 9 | logging.info(um_futures_client.funding_rate("BTCUSDT", **{"limit": 100})) 10 | -------------------------------------------------------------------------------- /examples/um_futures/market/historical_trades.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | 6 | config_logging(logging, logging.DEBUG) 7 | 8 | key = "" 9 | 10 | # historical_trades requires api key in request header 11 | um_futures_client = UMFutures(key=key) 12 | 13 | logging.info(um_futures_client.historical_trades("BTCUSDT", **{"limit": 10})) 14 | -------------------------------------------------------------------------------- /examples/um_futures/market/index_info.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | 6 | config_logging(logging, logging.DEBUG) 7 | 8 | um_futures_client = UMFutures() 9 | 10 | logging.info(um_futures_client.index_info("DEFIUSDT")) 11 | -------------------------------------------------------------------------------- /examples/um_futures/market/index_price_constituents.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | 6 | config_logging(logging, logging.DEBUG) 7 | 8 | um_futures_client = UMFutures() 9 | logging.info(um_futures_client.index_price_constituents(symbol="BTCUSDT")) 10 | -------------------------------------------------------------------------------- /examples/um_futures/market/index_price_kline.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | 6 | config_logging(logging, logging.DEBUG) 7 | 8 | um_futures_client = UMFutures() 9 | 10 | logging.info(um_futures_client.index_price_klines("BTCUSDT", "1d", **{"limit": 500})) 11 | -------------------------------------------------------------------------------- /examples/um_futures/market/klines.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | 6 | config_logging(logging, logging.DEBUG) 7 | 8 | um_futures_client = UMFutures() 9 | 10 | logging.info(um_futures_client.klines("BTCUSDT", "1d")) 11 | -------------------------------------------------------------------------------- /examples/um_futures/market/mark_price.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | 6 | config_logging(logging, logging.DEBUG) 7 | 8 | um_futures_client = UMFutures() 9 | 10 | logging.info(um_futures_client.mark_price()) 11 | -------------------------------------------------------------------------------- /examples/um_futures/market/mark_price_klines.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | 6 | config_logging(logging, logging.DEBUG) 7 | 8 | um_futures_client = UMFutures() 9 | 10 | logging.info(um_futures_client.mark_price_klines("BTCUSDT", "1d", **{"limit": 500})) 11 | -------------------------------------------------------------------------------- /examples/um_futures/market/open_interest.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | 6 | config_logging(logging, logging.DEBUG) 7 | 8 | um_futures_client = UMFutures() 9 | 10 | logging.info(um_futures_client.open_interest("BTCUSDT")) 11 | -------------------------------------------------------------------------------- /examples/um_futures/market/open_interest_hist.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | 6 | config_logging(logging, logging.DEBUG) 7 | 8 | um_futures_client = UMFutures() 9 | 10 | logging.info(um_futures_client.open_interest_hist("BTCUSDT", "1h", **{"limit": 30})) 11 | -------------------------------------------------------------------------------- /examples/um_futures/market/ping.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | 6 | config_logging(logging, logging.DEBUG) 7 | 8 | um_futures_client = UMFutures() 9 | logging.info(um_futures_client.ping()) 10 | -------------------------------------------------------------------------------- /examples/um_futures/market/quarterly_contract_settlement_price.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | 6 | config_logging(logging, logging.DEBUG) 7 | 8 | um_futures_client = UMFutures() 9 | 10 | logging.info(um_futures_client.quarterly_contract_settlement_price(pair="BTCUSDT")) 11 | -------------------------------------------------------------------------------- /examples/um_futures/market/taker_long_short_ratio.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | 6 | config_logging(logging, logging.DEBUG) 7 | 8 | um_futures_client = UMFutures() 9 | 10 | logging.info(um_futures_client.taker_long_short_ratio("BTCUSDT", "1d")) 11 | -------------------------------------------------------------------------------- /examples/um_futures/market/ticker_24hr_price_change.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | 6 | config_logging(logging, logging.DEBUG) 7 | 8 | um_futures_client = UMFutures() 9 | 10 | logging.info(um_futures_client.ticker_24hr_price_change("BTCUSDT")) 11 | -------------------------------------------------------------------------------- /examples/um_futures/market/ticker_price.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | 6 | config_logging(logging, logging.DEBUG) 7 | 8 | um_futures_client = UMFutures() 9 | 10 | logging.info(um_futures_client.ticker_price("BTCUSDT")) 11 | -------------------------------------------------------------------------------- /examples/um_futures/market/time.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | 6 | config_logging(logging, logging.DEBUG) 7 | 8 | um_futures_client = UMFutures() 9 | 10 | logging.info(um_futures_client.time()) 11 | -------------------------------------------------------------------------------- /examples/um_futures/market/top_long_short_account_ratio.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | 6 | config_logging(logging, logging.DEBUG) 7 | 8 | um_futures_client = UMFutures() 9 | 10 | logging.info(um_futures_client.long_short_account_ratio("BTCUSDT", "1d")) 11 | -------------------------------------------------------------------------------- /examples/um_futures/market/top_long_short_position_ratio.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | 6 | config_logging(logging, logging.DEBUG) 7 | 8 | um_futures_client = UMFutures() 9 | 10 | logging.info( 11 | um_futures_client.top_long_short_position_ratio("BTCUSDT", "1h", **{"limit": 30}) 12 | ) 13 | -------------------------------------------------------------------------------- /examples/um_futures/market/trades.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | 6 | config_logging(logging, logging.DEBUG) 7 | 8 | um_futures_client = UMFutures() 9 | 10 | logging.info(um_futures_client.trades("BTCUSDT", limit=500)) 11 | -------------------------------------------------------------------------------- /examples/um_futures/stream/close_listen_key.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | 6 | config_logging(logging, logging.DEBUG) 7 | 8 | key = "" 9 | 10 | um_futures_client = UMFutures(key) 11 | logging.info(um_futures_client.close_listen_key("the_listen_key")) 12 | -------------------------------------------------------------------------------- /examples/um_futures/stream/new_listen_key.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | 6 | config_logging(logging, logging.DEBUG) 7 | 8 | key = "" 9 | 10 | um_futures_client = UMFutures(key) 11 | logging.info(um_futures_client.new_listen_key()) 12 | -------------------------------------------------------------------------------- /examples/um_futures/stream/renew_listen_key.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | 6 | config_logging(logging, logging.DEBUG) 7 | 8 | key = "" 9 | 10 | um_futures_client = UMFutures(key) 11 | logging.info(um_futures_client.renew_listen_key("the_listen_key")) 12 | -------------------------------------------------------------------------------- /examples/um_futures/trade/async_download_order_id.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | um_futures_client = UMFutures(key=key, secret=secret) 13 | 14 | try: 15 | response = um_futures_client.async_download_order_id(downloadId="1") 16 | logging.info(response) 17 | except ClientError as error: 18 | logging.error( 19 | "Found error. status: {}, error code: {}, error message: {}".format( 20 | error.status_code, error.error_code, error.error_message 21 | ) 22 | ) 23 | -------------------------------------------------------------------------------- /examples/um_futures/trade/async_download_trade_id.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | um_futures_client = UMFutures(key=key, secret=secret) 13 | 14 | try: 15 | response = um_futures_client.async_download_trade_id(downloadId="1") 16 | logging.info(response) 17 | except ClientError as error: 18 | logging.error( 19 | "Found error. status: {}, error code: {}, error message: {}".format( 20 | error.status_code, error.error_code, error.error_message 21 | ) 22 | ) 23 | -------------------------------------------------------------------------------- /examples/um_futures/trade/aysnc_download_info.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | um_futures_client = UMFutures(key=key, secret=secret) 13 | 14 | try: 15 | response = um_futures_client.aysnc_download_info(downloadId="1") 16 | logging.info(response) 17 | except ClientError as error: 18 | logging.error( 19 | "Found error. status: {}, error code: {}, error message: {}".format( 20 | error.status_code, error.error_code, error.error_message 21 | ) 22 | ) 23 | -------------------------------------------------------------------------------- /examples/um_futures/trade/cancel_batch_orders.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | um_futures_client = UMFutures(key=key, secret=secret) 13 | 14 | try: 15 | response = um_futures_client.cancel_batch_order( 16 | symbol="BTCUSDT", orderIdList=[], origClientOrderIdList=[], recvWindow=2000 17 | ) 18 | logging.info(response) 19 | except ClientError as error: 20 | logging.error( 21 | "Found error. status: {}, error code: {}, error message: {}".format( 22 | error.status_code, error.error_code, error.error_message 23 | ) 24 | ) 25 | -------------------------------------------------------------------------------- /examples/um_futures/trade/cancel_open_orders.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | um_futures_client = UMFutures(key=key, secret=secret) 13 | 14 | try: 15 | response = um_futures_client.cancel_open_orders(symbol="BTCUSDT", recvWindow=2000) 16 | logging.info(response) 17 | except ClientError as error: 18 | logging.error( 19 | "Found error. status: {}, error code: {}, error message: {}".format( 20 | error.status_code, error.error_code, error.error_message 21 | ) 22 | ) 23 | -------------------------------------------------------------------------------- /examples/um_futures/trade/cancel_order.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | um_futures_client = UMFutures(key=key, secret=secret) 13 | 14 | try: 15 | response = um_futures_client.cancel_order( 16 | symbol="BTCUSDT", orderId=123456, recvWindow=2000 17 | ) 18 | logging.info(response) 19 | except ClientError as error: 20 | logging.error( 21 | "Found error. status: {}, error code: {}, error message: {}".format( 22 | error.status_code, error.error_code, error.error_message 23 | ) 24 | ) 25 | -------------------------------------------------------------------------------- /examples/um_futures/trade/change_leverage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | um_futures_client = UMFutures(key=key, secret=secret) 13 | 14 | try: 15 | response = um_futures_client.change_leverage( 16 | symbol="BTCUSDT", leverage=2, recvWindow=6000 17 | ) 18 | logging.info(response) 19 | except ClientError as error: 20 | logging.error( 21 | "Found error. status: {}, error code: {}, error message: {}".format( 22 | error.status_code, error.error_code, error.error_message 23 | ) 24 | ) 25 | -------------------------------------------------------------------------------- /examples/um_futures/trade/change_margin_type.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from binance.um_futures import UMFutures 3 | from binance.lib.utils import config_logging 4 | from binance.error import ClientError 5 | 6 | config_logging(logging, logging.DEBUG) 7 | 8 | key = "" 9 | secret = "" 10 | 11 | um_futures_client = UMFutures(key=key, secret=secret) 12 | 13 | try: 14 | response = um_futures_client.change_margin_type( 15 | symbol="BTCUSDT", marginType="ISOLATED", recvWindow=6000 16 | ) 17 | logging.info(response) 18 | except ClientError as error: 19 | logging.error( 20 | "Found error. status: {}, error code: {}, error message: {}".format( 21 | error.status_code, error.error_code, error.error_message 22 | ) 23 | ) 24 | -------------------------------------------------------------------------------- /examples/um_futures/trade/change_multi_asset_mode.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | um_futures_client = UMFutures(key=key, secret=secret) 13 | 14 | try: 15 | response = um_futures_client.change_multi_asset_mode( 16 | multiAssetsMargin="true", recvWindow=2000 17 | ) 18 | logging.info(response) 19 | except ClientError as error: 20 | logging.error( 21 | "Found error. status: {}, error code: {}, error message: {}".format( 22 | error.status_code, error.error_code, error.error_message 23 | ) 24 | ) 25 | -------------------------------------------------------------------------------- /examples/um_futures/trade/change_position_mode.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | um_futures_client = UMFutures(key=key, secret=secret) 13 | 14 | try: 15 | response = um_futures_client.change_position_mode( 16 | dualSidePosition="true", recvWindow=2000 17 | ) 18 | logging.info(response) 19 | except ClientError as error: 20 | logging.error( 21 | "Found error. status: {}, error code: {}, error message: {}".format( 22 | error.status_code, error.error_code, error.error_message 23 | ) 24 | ) 25 | -------------------------------------------------------------------------------- /examples/um_futures/trade/countdown_cancel_order.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | um_futures_client = UMFutures(key=key, secret=secret) 13 | 14 | try: 15 | response = um_futures_client.countdown_cancel_order( 16 | symbol="BTCUSDT", countdownTime=1000, recvWindow=2000 17 | ) 18 | logging.info(response) 19 | except ClientError as error: 20 | logging.error( 21 | "Found error. status: {}, error code: {}, error message: {}".format( 22 | error.status_code, error.error_code, error.error_message 23 | ) 24 | ) 25 | -------------------------------------------------------------------------------- /examples/um_futures/trade/download_order_asyn.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | um_futures_client = UMFutures(key=key, secret=secret) 13 | 14 | try: 15 | response = um_futures_client.download_order_asyn( 16 | startTime=1641102712000, endTime=1651470712000 17 | ) 18 | logging.info(response) 19 | except ClientError as error: 20 | logging.error( 21 | "Found error. status: {}, error code: {}, error message: {}".format( 22 | error.status_code, error.error_code, error.error_message 23 | ) 24 | ) 25 | -------------------------------------------------------------------------------- /examples/um_futures/trade/download_trade_asyn.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | um_futures_client = UMFutures(key=key, secret=secret) 13 | 14 | try: 15 | response = um_futures_client.download_trade_asyn( 16 | startTime=1641102712000, endTime=1651470712000 17 | ) 18 | logging.info(response) 19 | except ClientError as error: 20 | logging.error( 21 | "Found error. status: {}, error code: {}, error message: {}".format( 22 | error.status_code, error.error_code, error.error_message 23 | ) 24 | ) 25 | -------------------------------------------------------------------------------- /examples/um_futures/trade/download_transactions_asyn.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | um_futures_client = UMFutures(key=key, secret=secret) 13 | 14 | try: 15 | response = um_futures_client.download_transactions_asyn( 16 | startTime=1641102712000, endTime=1651470712000 17 | ) 18 | logging.info(response) 19 | except ClientError as error: 20 | logging.error( 21 | "Found error. status: {}, error code: {}, error message: {}".format( 22 | error.status_code, error.error_code, error.error_message 23 | ) 24 | ) 25 | -------------------------------------------------------------------------------- /examples/um_futures/trade/futures_account_configuration.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | um_futures_client = UMFutures(key=key, secret=secret) 13 | 14 | try: 15 | response = um_futures_client.futures_account_configuration() 16 | logging.info(response) 17 | except ClientError as error: 18 | logging.error( 19 | "Found error. status: {}, error code: {}, error message: {}".format( 20 | error.status_code, error.error_code, error.error_message 21 | ) 22 | ) 23 | -------------------------------------------------------------------------------- /examples/um_futures/trade/get_account.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | # HMAC authentication with API key and secret 10 | key = "" 11 | secret = "" 12 | 13 | hmac_client = UMFutures(key=key, secret=secret) 14 | logging.info(hmac_client.account(recvWindow=6000)) 15 | 16 | # RSA authentication with RSA key 17 | key = "" 18 | with open("/Users/john/private_key.pem", "r") as f: 19 | private_key = f.read() 20 | 21 | rsa_client = UMFutures(key=key, private_key=private_key) 22 | 23 | try: 24 | response = rsa_client.account(recvWindow=6000) 25 | logging.info(response) 26 | except ClientError as error: 27 | logging.error( 28 | "Found error. status: {}, error code: {}, error message: {}".format( 29 | error.status_code, error.error_code, error.error_message 30 | ) 31 | ) 32 | -------------------------------------------------------------------------------- /examples/um_futures/trade/get_account_trades.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | um_futures_client = UMFutures(key=key, secret=secret) 13 | 14 | try: 15 | response = um_futures_client.get_account_trades(symbol="BTCUSDT", recvWindow=6000) 16 | logging.info(response) 17 | except ClientError as error: 18 | logging.error( 19 | "Found error. status: {}, error code: {}, error message: {}".format( 20 | error.status_code, error.error_code, error.error_message 21 | ) 22 | ) 23 | -------------------------------------------------------------------------------- /examples/um_futures/trade/get_adl_quantile.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | um_futures_client = UMFutures(key=key, secret=secret) 13 | 14 | try: 15 | response = um_futures_client.adl_quantile(symbol="BTCUSDT", recvWindow=6000) 16 | logging.info(response) 17 | except ClientError as error: 18 | logging.error( 19 | "Found error. status: {}, error code: {}, error message: {}".format( 20 | error.status_code, error.error_code, error.error_message 21 | ) 22 | ) 23 | -------------------------------------------------------------------------------- /examples/um_futures/trade/get_all_orders.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | um_futures_client = UMFutures(key=key, secret=secret) 13 | 14 | try: 15 | response = um_futures_client.get_all_orders(symbol="BTCUSDT", recvWindow=2000) 16 | logging.info(response) 17 | except ClientError as error: 18 | logging.error( 19 | "Found error. status: {}, error code: {}, error message: {}".format( 20 | error.status_code, error.error_code, error.error_message 21 | ) 22 | ) 23 | -------------------------------------------------------------------------------- /examples/um_futures/trade/get_api_trading_status.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | um_futures_client = UMFutures(key=key, secret=secret) 13 | 14 | try: 15 | response = um_futures_client.api_trading_status(recvWindow=6000) 16 | logging.info(response) 17 | except ClientError as error: 18 | logging.error( 19 | "Found error. status: {}, error code: {}, error message: {}".format( 20 | error.status_code, error.error_code, error.error_message 21 | ) 22 | ) 23 | -------------------------------------------------------------------------------- /examples/um_futures/trade/get_balance.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | um_futures_client = UMFutures(key=key, secret=secret) 13 | 14 | try: 15 | response = um_futures_client.balance(recvWindow=6000) 16 | logging.info(response) 17 | except ClientError as error: 18 | logging.error( 19 | "Found error. status: {}, error code: {}, error message: {}".format( 20 | error.status_code, error.error_code, error.error_message 21 | ) 22 | ) 23 | -------------------------------------------------------------------------------- /examples/um_futures/trade/get_bnb_burn.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | um_futures_client = UMFutures(key=key, secret=secret) 13 | 14 | try: 15 | response = um_futures_client.get_bnb_burn() 16 | logging.info(response) 17 | except ClientError as error: 18 | logging.error( 19 | "Found error. status: {}, error code: {}, error message: {}".format( 20 | error.status_code, error.error_code, error.error_message 21 | ) 22 | ) 23 | -------------------------------------------------------------------------------- /examples/um_futures/trade/get_commission_rate.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | um_futures_client = UMFutures(key=key, secret=secret) 13 | 14 | try: 15 | response = um_futures_client.commission_rate(symbol="BTCUSDT", recvWindow=6000) 16 | logging.info(response) 17 | except ClientError as error: 18 | logging.error( 19 | "Found error. status: {}, error code: {}, error message: {}".format( 20 | error.status_code, error.error_code, error.error_message 21 | ) 22 | ) 23 | -------------------------------------------------------------------------------- /examples/um_futures/trade/get_force_orders.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | um_futures_client = UMFutures(key=key, secret=secret) 13 | 14 | try: 15 | response = um_futures_client.force_orders(recvWindow=6000) 16 | logging.info(response) 17 | except ClientError as error: 18 | logging.error( 19 | "Found error. status: {}, error code: {}, error message: {}".format( 20 | error.status_code, error.error_code, error.error_message 21 | ) 22 | ) 23 | -------------------------------------------------------------------------------- /examples/um_futures/trade/get_income_history.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | um_futures_client = UMFutures(key=key, secret=secret) 13 | 14 | try: 15 | response = um_futures_client.get_income_history(recvWindow=6000) 16 | logging.info(response) 17 | except ClientError as error: 18 | logging.error( 19 | "Found error. status: {}, error code: {}, error message: {}".format( 20 | error.status_code, error.error_code, error.error_message 21 | ) 22 | ) 23 | -------------------------------------------------------------------------------- /examples/um_futures/trade/get_leverage_brackets.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | um_futures_client = UMFutures(key=key, secret=secret) 13 | 14 | try: 15 | response = um_futures_client.leverage_brackets(symbol="BTCUSDT", recvWindow=6000) 16 | logging.info(response) 17 | except ClientError as error: 18 | logging.error( 19 | "Found error. status: {}, error code: {}, error message: {}".format( 20 | error.status_code, error.error_code, error.error_message 21 | ) 22 | ) 23 | -------------------------------------------------------------------------------- /examples/um_futures/trade/get_multi_asset_mode.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | um_futures_client = UMFutures(key=key, secret=secret) 13 | 14 | try: 15 | response = um_futures_client.get_multi_asset_mode(recvWindow=2000) 16 | logging.info(response) 17 | except ClientError as error: 18 | logging.error( 19 | "Found error. status: {}, error code: {}, error message: {}".format( 20 | error.status_code, error.error_code, error.error_message 21 | ) 22 | ) 23 | -------------------------------------------------------------------------------- /examples/um_futures/trade/get_open_orders.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | um_futures_client = UMFutures(key=key, secret=secret) 13 | 14 | try: 15 | response = um_futures_client.get_open_orders( 16 | symbol="BTCUSDT", orderId=35298599362, recvWindow=2000 17 | ) 18 | logging.info(response) 19 | except ClientError as error: 20 | logging.error( 21 | "Found error. status: {}, error code: {}, error message: {}".format( 22 | error.status_code, error.error_code, error.error_message 23 | ) 24 | ) 25 | -------------------------------------------------------------------------------- /examples/um_futures/trade/get_orders.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | um_futures_client = UMFutures(key=key, secret=secret) 13 | 14 | try: 15 | response = um_futures_client.get_orders(symbol="BTCUSDT", recvWindow=2000) 16 | logging.info(response) 17 | except ClientError as error: 18 | logging.error( 19 | "Found error. status: {}, error code: {}, error message: {}".format( 20 | error.status_code, error.error_code, error.error_message 21 | ) 22 | ) 23 | -------------------------------------------------------------------------------- /examples/um_futures/trade/get_position_margin_history.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | um_futures_client = UMFutures(key=key, secret=secret) 13 | try: 14 | response = um_futures_client.get_position_margin_history( 15 | symbol="BTCUSDT", recvWindow=6000 16 | ) 17 | logging.info(response) 18 | except ClientError as error: 19 | logging.error( 20 | "Found error. status: {}, error code: {}, error message: {}".format( 21 | error.status_code, error.error_code, error.error_message 22 | ) 23 | ) 24 | -------------------------------------------------------------------------------- /examples/um_futures/trade/get_position_mode.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | um_futures_client = UMFutures(key=key, secret=secret) 13 | 14 | try: 15 | response = um_futures_client.get_position_mode(recvWindow=2000) 16 | logging.info(response) 17 | except ClientError as error: 18 | logging.error( 19 | "Found error. status: {}, error code: {}, error message: {}".format( 20 | error.status_code, error.error_code, error.error_message 21 | ) 22 | ) 23 | -------------------------------------------------------------------------------- /examples/um_futures/trade/get_position_risk.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | um_futures_client = UMFutures(key=key, secret=secret) 13 | try: 14 | response = um_futures_client.get_position_risk(recvWindow=6000) 15 | logging.info(response) 16 | except ClientError as error: 17 | logging.error( 18 | "Found error. status: {}, error code: {}, error message: {}".format( 19 | error.status_code, error.error_code, error.error_message 20 | ) 21 | ) 22 | -------------------------------------------------------------------------------- /examples/um_futures/trade/modify_isolated_position_margin.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | um_futures_client = UMFutures(key=key, secret=secret) 13 | try: 14 | response = um_futures_client.modify_isolated_position_margin( 15 | symbol="BTCUSDT", amount=100, type=1, recvWindow=6000 16 | ) 17 | logging.info(response) 18 | except ClientError as error: 19 | logging.error( 20 | "Found error. status: {}, error code: {}, error message: {}".format( 21 | error.status_code, error.error_code, error.error_message 22 | ) 23 | ) 24 | -------------------------------------------------------------------------------- /examples/um_futures/trade/modify_order.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | um_futures_client = UMFutures(key=key, secret=secret) 13 | 14 | try: 15 | response = um_futures_client.modify_order( 16 | symbol="BTCUSDT", side="BUY", orderId=1123323, price=23000.00, quantity=0.01 17 | ) 18 | logging.info(response) 19 | except ClientError as error: 20 | logging.error( 21 | "Found error. status: {}, error code: {}, error message: {}".format( 22 | error.status_code, error.error_code, error.error_message 23 | ) 24 | ) 25 | -------------------------------------------------------------------------------- /examples/um_futures/trade/new_batch_order.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | um_futures_client = UMFutures(key=key, secret=secret) 13 | 14 | params = [ 15 | { 16 | "symbol": "BTCUSDT", 17 | "side": "BUY", 18 | "type": "LIMIT", 19 | "quantity": "0.001", 20 | "timeInForce": "GTC", 21 | "price": "10000.1", 22 | }, 23 | { 24 | "symbol": "BTCUSDT", 25 | "side": "BUY", 26 | "type": "LIMIT", 27 | "quantity": "0.01", 28 | "timeInForce": "GTC", 29 | "price": "8000.1", 30 | }, 31 | ] 32 | 33 | try: 34 | response = um_futures_client.new_batch_order(params) 35 | logging.info(response) 36 | except ClientError as error: 37 | logging.error( 38 | "Found error. status: {}, error code: {}, error message: {}".format( 39 | error.status_code, error.error_code, error.error_message 40 | ) 41 | ) 42 | -------------------------------------------------------------------------------- /examples/um_futures/trade/new_order.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | um_futures_client = UMFutures(key=key, secret=secret) 13 | 14 | try: 15 | response = um_futures_client.new_order( 16 | symbol="BTCUSDT", 17 | side="SELL", 18 | type="LIMIT", 19 | quantity=0.001, 20 | timeInForce="GTC", 21 | price=59808.02, 22 | ) 23 | logging.info(response) 24 | except ClientError as error: 25 | logging.error( 26 | "Found error. status: {}, error code: {}, error message: {}".format( 27 | error.status_code, error.error_code, error.error_message 28 | ) 29 | ) 30 | -------------------------------------------------------------------------------- /examples/um_futures/trade/new_order_testing.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | um_futures_client = UMFutures(key=key, secret=secret) 13 | 14 | try: 15 | response = um_futures_client.new_order_test( 16 | symbol="BTCUSDT", 17 | side="SELL", 18 | type="LIMIT", 19 | quantity=0.001, 20 | timeInForce="GTC", 21 | price=59808.02, 22 | ) 23 | logging.info(response) 24 | except ClientError as error: 25 | logging.error( 26 | "Found error. status: {}, error code: {}, error message: {}".format( 27 | error.status_code, error.error_code, error.error_message 28 | ) 29 | ) 30 | -------------------------------------------------------------------------------- /examples/um_futures/trade/query_order.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | um_futures_client = UMFutures(key=key, secret=secret) 13 | 14 | try: 15 | response = um_futures_client.query_order( 16 | symbol="BTCUSDT", orderId=12345678, recvWindow=2000 17 | ) 18 | logging.info(response) 19 | except ClientError as error: 20 | logging.error( 21 | "Found error. status: {}, error code: {}, error message: {}".format( 22 | error.status_code, error.error_code, error.error_message 23 | ) 24 | ) 25 | -------------------------------------------------------------------------------- /examples/um_futures/trade/query_user_rate_limit.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | um_futures_client = UMFutures(key=key, secret=secret) 13 | 14 | try: 15 | response = um_futures_client.query_user_rate_limit() 16 | logging.info(response) 17 | except ClientError as error: 18 | logging.error( 19 | "Found error. status: {}, error code: {}, error message: {}".format( 20 | error.status_code, error.error_code, error.error_message 21 | ) 22 | ) 23 | -------------------------------------------------------------------------------- /examples/um_futures/trade/symbol_configuration.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | um_futures_client = UMFutures(key=key, secret=secret) 13 | 14 | try: 15 | response = um_futures_client.symbol_configuration() 16 | logging.info(response) 17 | except ClientError as error: 18 | logging.error( 19 | "Found error. status: {}, error code: {}, error message: {}".format( 20 | error.status_code, error.error_code, error.error_message 21 | ) 22 | ) 23 | -------------------------------------------------------------------------------- /examples/um_futures/trade/toggle_bnb_burn.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import logging 3 | from binance.um_futures import UMFutures 4 | from binance.lib.utils import config_logging 5 | from binance.error import ClientError 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | key = "" 10 | secret = "" 11 | 12 | um_futures_client = UMFutures(key=key, secret=secret) 13 | 14 | try: 15 | response = um_futures_client.toggle_bnb_burn(feeBurn="true") 16 | logging.info(response) 17 | except ClientError as error: 18 | logging.error( 19 | "Found error. status: {}, error code: {}, error message: {}".format( 20 | error.status_code, error.error_code, error.error_message 21 | ) 22 | ) 23 | -------------------------------------------------------------------------------- /examples/websocket/cm_futures/agg_trade.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import time 3 | import logging 4 | from binance.lib.utils import config_logging 5 | from binance.websocket.cm_futures.websocket_client import CMFuturesWebsocketClient 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | 10 | def message_handler(_, message): 11 | print(message) 12 | 13 | 14 | my_client = CMFuturesWebsocketClient(on_message=message_handler) 15 | 16 | my_client.agg_trade( 17 | symbol="btcusd_perp", 18 | id=1, 19 | callback=message_handler, 20 | ) 21 | 22 | time.sleep(10) 23 | 24 | logging.debug("closing ws connection") 25 | my_client.stop() 26 | -------------------------------------------------------------------------------- /examples/websocket/cm_futures/book_ticker.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import time 3 | import logging 4 | from binance.lib.utils import config_logging 5 | from binance.websocket.cm_futures.websocket_client import CMFuturesWebsocketClient 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | 10 | def message_handler(_, message): 11 | print(message) 12 | 13 | 14 | my_client = CMFuturesWebsocketClient(on_message=message_handler) 15 | 16 | my_client.book_ticker( 17 | id=13, 18 | callback=message_handler, 19 | symbol="btcusd_perp", 20 | ) 21 | 22 | time.sleep(10) 23 | 24 | logging.debug("closing ws connection") 25 | my_client.stop() 26 | -------------------------------------------------------------------------------- /examples/websocket/cm_futures/combined_streams.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import time 3 | 4 | from binance.lib.utils import config_logging 5 | from binance.websocket.cm_futures.websocket_client import CMFuturesWebsocketClient 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | 10 | def message_handler(_, message): 11 | logging.info(message) 12 | 13 | 14 | my_client = CMFuturesWebsocketClient(on_message=message_handler, is_combined=True) 15 | 16 | 17 | my_client.subscribe( 18 | stream=["btcusd_perp@ticker", "btcusd_perp@markPrice@1s"], 19 | ) 20 | 21 | time.sleep(10) 22 | my_client.stop() 23 | -------------------------------------------------------------------------------- /examples/websocket/cm_futures/continuous_klines.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import time 4 | import logging 5 | from binance.lib.utils import config_logging 6 | from binance.websocket.cm_futures.websocket_client import CMFuturesWebsocketClient 7 | 8 | config_logging(logging, logging.DEBUG) 9 | 10 | 11 | def message_handler(_, message): 12 | print(message) 13 | 14 | 15 | my_client = CMFuturesWebsocketClient(on_message=message_handler) 16 | 17 | my_client.continuous_kline( 18 | pair="btcusd", 19 | id=1, 20 | contractType="perpetual", 21 | interval="1m", 22 | ) 23 | 24 | time.sleep(10) 25 | 26 | logging.debug("closing ws connection") 27 | my_client.stop() 28 | -------------------------------------------------------------------------------- /examples/websocket/cm_futures/diff_book_depth.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import time 4 | import logging 5 | from binance.lib.utils import config_logging 6 | from binance.websocket.cm_futures.websocket_client import CMFuturesWebsocketClient 7 | 8 | config_logging(logging, logging.DEBUG) 9 | 10 | 11 | def message_handler(_, message): 12 | print(message) 13 | 14 | 15 | my_client = CMFuturesWebsocketClient(on_message=message_handler) 16 | 17 | my_client.diff_book_depth( 18 | symbol="bnbusd_perp", 19 | speed=100, 20 | id=1, 21 | ) 22 | 23 | time.sleep(10) 24 | 25 | logging.debug("closing ws connection") 26 | my_client.stop() 27 | -------------------------------------------------------------------------------- /examples/websocket/cm_futures/index_kline.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import time 4 | import logging 5 | from binance.lib.utils import config_logging 6 | from binance.websocket.cm_futures.websocket_client import CMFuturesWebsocketClient 7 | 8 | config_logging(logging, logging.DEBUG) 9 | 10 | 11 | def message_handler(_, message): 12 | print(message) 13 | 14 | 15 | my_client = CMFuturesWebsocketClient(on_message=message_handler) 16 | 17 | my_client.index_kline( 18 | pair="btcusd", 19 | id=1, 20 | interval="1m", 21 | callback=message_handler, 22 | ) 23 | 24 | time.sleep(10) 25 | 26 | logging.debug("closing ws connection") 27 | my_client.stop() 28 | -------------------------------------------------------------------------------- /examples/websocket/cm_futures/index_price.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import time 4 | import logging 5 | from binance.lib.utils import config_logging 6 | from binance.websocket.cm_futures.websocket_client import CMFuturesWebsocketClient 7 | 8 | config_logging(logging, logging.DEBUG) 9 | 10 | 11 | def message_handler(_, message): 12 | print(message) 13 | 14 | 15 | my_client = CMFuturesWebsocketClient(on_message=message_handler) 16 | 17 | my_client.index_price( 18 | pair="btcusd", 19 | speed=1, 20 | id=1, 21 | ) 22 | 23 | time.sleep(10) 24 | 25 | logging.debug("closing ws connection") 26 | my_client.stop() 27 | -------------------------------------------------------------------------------- /examples/websocket/cm_futures/kline.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import time 4 | import logging 5 | from binance.lib.utils import config_logging 6 | from binance.websocket.cm_futures.websocket_client import CMFuturesWebsocketClient 7 | 8 | config_logging(logging, logging.DEBUG) 9 | 10 | 11 | def message_handler(_, message): 12 | print(message) 13 | 14 | 15 | my_client = CMFuturesWebsocketClient(on_message=message_handler) 16 | 17 | my_client.kline( 18 | symbol="btcusd_perp", 19 | id=12, 20 | interval="1m", 21 | ) 22 | 23 | time.sleep(10) 24 | 25 | logging.debug("closing ws connection") 26 | my_client.stop() 27 | -------------------------------------------------------------------------------- /examples/websocket/cm_futures/liquidation_order.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import time 4 | import logging 5 | from binance.lib.utils import config_logging 6 | from binance.websocket.cm_futures.websocket_client import CMFuturesWebsocketClient 7 | 8 | config_logging(logging, logging.DEBUG) 9 | 10 | 11 | def message_handler(_, message): 12 | print(message) 13 | 14 | 15 | my_client = CMFuturesWebsocketClient(on_message=message_handler) 16 | 17 | my_client.liquidation_order( 18 | symbol="btcusd_perp", 19 | id=13, 20 | ) 21 | 22 | time.sleep(10) 23 | 24 | logging.debug("closing ws connection") 25 | my_client.stop() 26 | -------------------------------------------------------------------------------- /examples/websocket/cm_futures/mark_kline.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import time 4 | import logging 5 | from binance.lib.utils import config_logging 6 | from binance.websocket.cm_futures.websocket_client import CMFuturesWebsocketClient 7 | 8 | config_logging(logging, logging.DEBUG) 9 | 10 | 11 | def message_handler(_, message): 12 | print(message) 13 | 14 | 15 | my_client = CMFuturesWebsocketClient(on_message=message_handler) 16 | 17 | my_client.mark_kline( 18 | symbol="btcusd_perp", 19 | id=1, 20 | interval="1m", 21 | ) 22 | 23 | time.sleep(10) 24 | 25 | logging.debug("closing ws connection") 26 | my_client.stop() 27 | -------------------------------------------------------------------------------- /examples/websocket/cm_futures/mark_price.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import time 4 | import logging 5 | from binance.lib.utils import config_logging 6 | from binance.websocket.cm_futures.websocket_client import CMFuturesWebsocketClient 7 | 8 | config_logging(logging, logging.DEBUG) 9 | 10 | 11 | def message_handler(_, message): 12 | print(message) 13 | 14 | 15 | my_client = CMFuturesWebsocketClient(on_message=message_handler) 16 | 17 | my_client.mark_price( 18 | symbol="btcusd_perp", 19 | id=1, 20 | speed=1, 21 | ) 22 | 23 | time.sleep(10) 24 | 25 | logging.debug("closing ws connection") 26 | my_client.stop() 27 | -------------------------------------------------------------------------------- /examples/websocket/cm_futures/mini_ticker.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import time 4 | import logging 5 | from binance.lib.utils import config_logging 6 | from binance.websocket.cm_futures.websocket_client import CMFuturesWebsocketClient 7 | 8 | config_logging(logging, logging.DEBUG) 9 | 10 | 11 | def message_handler(_, message): 12 | print(message) 13 | 14 | 15 | my_client = CMFuturesWebsocketClient(on_message=message_handler) 16 | 17 | my_client.mini_ticker(id=1, symbol="btcusd_perp") 18 | 19 | time.sleep(10) 20 | 21 | logging.debug("closing ws connection") 22 | my_client.stop() 23 | -------------------------------------------------------------------------------- /examples/websocket/cm_futures/pair_mark_price.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import time 4 | import logging 5 | from binance.lib.utils import config_logging 6 | from binance.websocket.cm_futures.websocket_client import CMFuturesWebsocketClient 7 | 8 | config_logging(logging, logging.DEBUG) 9 | 10 | 11 | def message_handler(_, message): 12 | print(message) 13 | 14 | 15 | my_client = CMFuturesWebsocketClient(on_message=message_handler) 16 | 17 | my_client.pair_mark_price( 18 | pair="btcusd", 19 | id=1, 20 | speed=1, 21 | ) 22 | 23 | time.sleep(10) 24 | 25 | logging.debug("closing ws connection") 26 | my_client.stop() 27 | -------------------------------------------------------------------------------- /examples/websocket/cm_futures/partial_book_depth.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import time 4 | import logging 5 | from binance.lib.utils import config_logging 6 | from binance.websocket.cm_futures.websocket_client import CMFuturesWebsocketClient 7 | 8 | config_logging(logging, logging.DEBUG) 9 | 10 | 11 | def message_handler(_, message): 12 | print(message) 13 | 14 | 15 | my_client = CMFuturesWebsocketClient(on_message=message_handler) 16 | 17 | my_client.partial_book_depth( 18 | symbol="bnbusd_perp", 19 | id=1, 20 | level=10, 21 | speed=100, 22 | ) 23 | 24 | time.sleep(2) 25 | 26 | logging.debug("closing ws connection") 27 | my_client.stop() 28 | -------------------------------------------------------------------------------- /examples/websocket/cm_futures/ticker.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import time 4 | import logging 5 | from binance.lib.utils import config_logging 6 | from binance.websocket.cm_futures.websocket_client import CMFuturesWebsocketClient 7 | 8 | config_logging(logging, logging.DEBUG) 9 | 10 | 11 | def message_handler(_, message): 12 | print(message) 13 | 14 | 15 | my_client = CMFuturesWebsocketClient(on_message=message_handler) 16 | 17 | my_client.ticker( 18 | id=13, 19 | symbol="btcusd_perp", 20 | ) 21 | 22 | time.sleep(2) 23 | 24 | logging.debug("closing ws connection") 25 | my_client.stop() 26 | -------------------------------------------------------------------------------- /examples/websocket/cm_futures/user_data.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import time 4 | import logging 5 | from binance.lib.utils import config_logging 6 | from binance.um_futures import UMFutures 7 | from binance.websocket.cm_futures.websocket_client import CMFuturesWebsocketClient 8 | 9 | config_logging(logging, logging.DEBUG) 10 | 11 | 12 | def message_handler(_, message): 13 | print(message) 14 | 15 | 16 | api_key = "" 17 | client = UMFutures(api_key) 18 | response = client.new_listen_key() 19 | 20 | logging.info("Listen key : {}".format(response["listenKey"])) 21 | 22 | ws_client = CMFuturesWebsocketClient(on_message=message_handler) 23 | 24 | ws_client.user_data( 25 | listen_key=response["listenKey"], 26 | id=1, 27 | ) 28 | 29 | time.sleep(30) 30 | 31 | logging.debug("closing ws connection") 32 | ws_client.stop() 33 | -------------------------------------------------------------------------------- /examples/websocket/um_futures/agg_trade.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import logging 4 | import time 5 | from binance.lib.utils import config_logging 6 | from binance.websocket.um_futures.websocket_client import UMFuturesWebsocketClient 7 | 8 | config_logging(logging, logging.DEBUG) 9 | 10 | 11 | def message_handler(_, message): 12 | logging.info(message) 13 | 14 | 15 | my_client = UMFuturesWebsocketClient(on_message=message_handler, is_combined=True) 16 | 17 | # Subscribe to a single symbol stream 18 | my_client.agg_trade(symbol="bnbusdt") 19 | 20 | time.sleep(5) 21 | 22 | # Unsubscribe 23 | my_client.agg_trade( 24 | symbol="bnbusdt", action=UMFuturesWebsocketClient.ACTION_UNSUBSCRIBE 25 | ) 26 | 27 | time.sleep(5) 28 | 29 | logging.info("closing ws connection") 30 | my_client.stop() 31 | -------------------------------------------------------------------------------- /examples/websocket/um_futures/book_ticker.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import time 4 | import logging 5 | from binance.lib.utils import config_logging 6 | from binance.websocket.um_futures.websocket_client import UMFuturesWebsocketClient 7 | 8 | config_logging(logging, logging.DEBUG) 9 | 10 | 11 | def message_handler(_, message): 12 | print(message) 13 | 14 | 15 | my_client = UMFuturesWebsocketClient(on_message=message_handler) 16 | 17 | 18 | my_client.book_ticker(symbol="btcusdt") 19 | 20 | time.sleep(10) 21 | 22 | logging.debug("closing ws connection") 23 | my_client.stop() 24 | -------------------------------------------------------------------------------- /examples/websocket/um_futures/combined_streams.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import time 3 | 4 | from binance.lib.utils import config_logging 5 | from binance.websocket.um_futures.websocket_client import UMFuturesWebsocketClient 6 | 7 | config_logging(logging, logging.DEBUG) 8 | 9 | 10 | def message_handler(_, message): 11 | logging.info(message) 12 | 13 | 14 | my_client = UMFuturesWebsocketClient(on_message=message_handler, is_combined=True) 15 | 16 | 17 | my_client.subscribe( 18 | stream=["bnbusdt@bookTicker", "ethusdt@bookTicker"], 19 | ) 20 | 21 | time.sleep(10) 22 | my_client.stop() 23 | -------------------------------------------------------------------------------- /examples/websocket/um_futures/composite_index.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import time 4 | import logging 5 | from binance.lib.utils import config_logging 6 | from binance.websocket.um_futures.websocket_client import UMFuturesWebsocketClient 7 | 8 | config_logging(logging, logging.DEBUG) 9 | 10 | 11 | def message_handler(_, message): 12 | print(message) 13 | 14 | 15 | my_client = UMFuturesWebsocketClient(on_message=message_handler) 16 | 17 | my_client.composite_index( 18 | symbol="DEFIUSDT", 19 | id=13, 20 | ) 21 | 22 | time.sleep(10) 23 | 24 | logging.debug("closing ws connection") 25 | my_client.stop() 26 | -------------------------------------------------------------------------------- /examples/websocket/um_futures/continuous_klines.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import time 4 | import logging 5 | from binance.lib.utils import config_logging 6 | from binance.websocket.um_futures.websocket_client import UMFuturesWebsocketClient 7 | 8 | config_logging(logging, logging.DEBUG) 9 | 10 | 11 | def message_handler(_, message): 12 | print(message) 13 | 14 | 15 | my_client = UMFuturesWebsocketClient(on_message=message_handler) 16 | 17 | my_client.continuous_kline( 18 | pair="btcusdt", 19 | id=1, 20 | contractType="perpetual", 21 | interval="1d", 22 | ) 23 | 24 | time.sleep(10) 25 | 26 | logging.debug("closing ws connection") 27 | my_client.stop() 28 | -------------------------------------------------------------------------------- /examples/websocket/um_futures/diff_book_depth.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import time 4 | import logging 5 | from binance.lib.utils import config_logging 6 | from binance.websocket.um_futures.websocket_client import UMFuturesWebsocketClient 7 | 8 | config_logging(logging, logging.DEBUG) 9 | 10 | 11 | def message_handler(_, message): 12 | print(message) 13 | 14 | 15 | my_client = UMFuturesWebsocketClient(on_message=message_handler) 16 | 17 | my_client.diff_book_depth( 18 | symbol="bnbusdt", 19 | speed=100, 20 | id=1, 21 | ) 22 | 23 | time.sleep(10) 24 | 25 | logging.debug("closing ws connection") 26 | my_client.stop() 27 | -------------------------------------------------------------------------------- /examples/websocket/um_futures/kline.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import time 4 | import logging 5 | from binance.lib.utils import config_logging 6 | from binance.websocket.um_futures.websocket_client import UMFuturesWebsocketClient 7 | 8 | config_logging(logging, logging.DEBUG) 9 | 10 | 11 | def message_handler(_, message): 12 | print(message) 13 | 14 | 15 | my_client = UMFuturesWebsocketClient(on_message=message_handler) 16 | 17 | my_client.kline( 18 | symbol="btcusdt", 19 | id=12, 20 | interval="1d", 21 | ) 22 | 23 | time.sleep(10) 24 | 25 | logging.debug("closing ws connection") 26 | my_client.stop() 27 | -------------------------------------------------------------------------------- /examples/websocket/um_futures/liquidation_order.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import time 4 | import logging 5 | from binance.lib.utils import config_logging 6 | from binance.websocket.um_futures.websocket_client import UMFuturesWebsocketClient 7 | 8 | config_logging(logging, logging.DEBUG) 9 | 10 | 11 | def message_handler(_, message): 12 | print(message) 13 | 14 | 15 | my_client = UMFuturesWebsocketClient(on_message=message_handler) 16 | 17 | my_client.liquidation_order( 18 | id=13, 19 | ) 20 | 21 | time.sleep(10) 22 | 23 | logging.debug("closing ws connection") 24 | my_client.stop() 25 | -------------------------------------------------------------------------------- /examples/websocket/um_futures/mark_price.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import time 4 | import logging 5 | from binance.lib.utils import config_logging 6 | from binance.websocket.um_futures.websocket_client import UMFuturesWebsocketClient 7 | 8 | config_logging(logging, logging.DEBUG) 9 | 10 | 11 | def message_handler(_, message): 12 | print(message) 13 | 14 | 15 | my_client = UMFuturesWebsocketClient(on_message=message_handler) 16 | 17 | my_client.mark_price( 18 | symbol="btcusdt", 19 | id=13, 20 | speed=1, 21 | ) 22 | 23 | time.sleep(10) 24 | 25 | logging.debug("closing ws connection") 26 | my_client.stop() 27 | -------------------------------------------------------------------------------- /examples/websocket/um_futures/mark_price_all_market.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import time 4 | import logging 5 | from binance.lib.utils import config_logging 6 | from binance.websocket.um_futures.websocket_client import UMFuturesWebsocketClient 7 | 8 | config_logging(logging, logging.DEBUG) 9 | 10 | 11 | def message_handler(_, message): 12 | print(message) 13 | 14 | 15 | my_client = UMFuturesWebsocketClient(on_message=message_handler) 16 | 17 | my_client.mark_price_all_market( 18 | id=13, 19 | speed=1, 20 | ) 21 | 22 | time.sleep(10) 23 | 24 | logging.debug("closing ws connection") 25 | my_client.stop() 26 | -------------------------------------------------------------------------------- /examples/websocket/um_futures/mini_ticker.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import time 4 | import logging 5 | from binance.lib.utils import config_logging 6 | from binance.websocket.um_futures.websocket_client import UMFuturesWebsocketClient 7 | 8 | config_logging(logging, logging.DEBUG) 9 | 10 | 11 | def message_handler(_, message): 12 | print(message) 13 | 14 | 15 | my_client = UMFuturesWebsocketClient(on_message=message_handler) 16 | 17 | my_client.mini_ticker(id=1, symbol="btcusdt") 18 | 19 | time.sleep(10) 20 | 21 | logging.debug("closing ws connection") 22 | my_client.stop() 23 | -------------------------------------------------------------------------------- /examples/websocket/um_futures/partial_book_depth.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import time 4 | import logging 5 | from binance.lib.utils import config_logging 6 | from binance.websocket.um_futures.websocket_client import UMFuturesWebsocketClient 7 | 8 | config_logging(logging, logging.DEBUG) 9 | 10 | 11 | def message_handler(message): 12 | print(message) 13 | 14 | 15 | my_client = UMFuturesWebsocketClient(on_message=message_handler) 16 | 17 | my_client.partial_book_depth( 18 | symbol="bnbusdt", 19 | id=1, 20 | level=10, 21 | speed=100, 22 | ) 23 | 24 | time.sleep(10) 25 | 26 | logging.debug("closing ws connection") 27 | my_client.stop() 28 | -------------------------------------------------------------------------------- /examples/websocket/um_futures/symbol_kline.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import time 4 | import logging 5 | from binance.lib.utils import config_logging 6 | from binance.websocket.um_futures.websocket_client import UMFuturesWebsocketClient 7 | 8 | config_logging(logging, logging.DEBUG) 9 | 10 | 11 | def message_handler(_, message): 12 | print(message) 13 | 14 | 15 | my_client = UMFuturesWebsocketClient(on_message=message_handler) 16 | 17 | my_client.kline(symbol="btcusdt", id=1, interval="1m") 18 | 19 | time.sleep(5) 20 | 21 | my_client.kline(symbol="bnbusdt", id=2, interval="3m", callback=message_handler) 22 | 23 | time.sleep(10) 24 | 25 | logging.debug("closing ws connection") 26 | my_client.stop() 27 | -------------------------------------------------------------------------------- /examples/websocket/um_futures/ticker.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import time 4 | import logging 5 | from binance.lib.utils import config_logging 6 | from binance.websocket.um_futures.websocket_client import UMFuturesWebsocketClient 7 | 8 | config_logging(logging, logging.DEBUG) 9 | 10 | 11 | def message_handler(_, message): 12 | print(message) 13 | 14 | 15 | my_client = UMFuturesWebsocketClient(on_message=message_handler) 16 | 17 | my_client.ticker( 18 | id=13, 19 | symbol="btcusdt", 20 | ) 21 | 22 | time.sleep(2) 23 | 24 | logging.debug("closing ws connection") 25 | my_client.stop() 26 | -------------------------------------------------------------------------------- /examples/websocket/um_futures/user_data.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import time 4 | import logging 5 | from binance.lib.utils import config_logging 6 | from binance.um_futures import UMFutures 7 | from binance.websocket.um_futures.websocket_client import UMFuturesWebsocketClient 8 | 9 | config_logging(logging, logging.DEBUG) 10 | 11 | 12 | def message_handler(_, message): 13 | print(message) 14 | 15 | 16 | api_key = "" 17 | client = UMFutures(api_key) 18 | response = client.new_listen_key() 19 | 20 | logging.info("Listen key : {}".format(response["listenKey"])) 21 | 22 | ws_client = UMFuturesWebsocketClient(on_message=message_handler) 23 | 24 | ws_client.user_data( 25 | listen_key=response["listenKey"], 26 | id=1, 27 | ) 28 | 29 | time.sleep(30) 30 | 31 | logging.debug("closing ws connection") 32 | ws_client.stop() 33 | -------------------------------------------------------------------------------- /requirements/common.txt: -------------------------------------------------------------------------------- 1 | requests>=2.25.1 2 | websocket-client>=1.5.0 3 | pycryptodome>=3.15.0 -------------------------------------------------------------------------------- /requirements/requirements-dev.txt: -------------------------------------------------------------------------------- 1 | -r requirements-test.txt 2 | pre-commit 3 | sphinx 4 | sphinx_rtd_theme -------------------------------------------------------------------------------- /requirements/requirements-test.txt: -------------------------------------------------------------------------------- 1 | -r common.txt 2 | pytest-cov==2.8.1 3 | pytest==5.4.1 4 | sure==1.4.11 5 | responses==0.10.12 6 | pytest-pep8==1.0.6 7 | black 8 | flake8 9 | tox 10 | tox-pyenv 11 | wheel 12 | -------------------------------------------------------------------------------- /requirements/requirements.txt: -------------------------------------------------------------------------------- 1 | -r common.txt -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | description-file = README.md 3 | 4 | [tool:pytest] 5 | pep8ignore = E501 6 | 7 | [flake8] 8 | exclude = 9 | .git, 10 | .tox, 11 | build, 12 | dist 13 | max-complexity = 10 14 | ignore = E501, W503, W504 15 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import os 2 | from setuptools import setup, find_packages 3 | 4 | with open( 5 | os.path.join(os.path.dirname(__file__), "requirements/common.txt"), "r" 6 | ) as fh: 7 | requirements = fh.readlines() 8 | 9 | NAME = "binance-futures-connector" 10 | DESCRIPTION = "This is a lightweight library that works as a connector to Binance Futures public API." 11 | AUTHOR = "Futures" 12 | URL = "https://github.com/binance/binance-futures-connector-python" 13 | VERSION = None 14 | 15 | about = {} 16 | 17 | with open("README.md", "r") as fh: 18 | about["long_description"] = fh.read() 19 | 20 | root = os.path.abspath(os.path.dirname(__file__)) 21 | 22 | if not VERSION: 23 | with open(os.path.join(root, "binance", "__version__.py")) as f: 24 | exec(f.read(), about) 25 | else: 26 | about["__version__"] = VERSION 27 | 28 | setup( 29 | name=NAME, 30 | version=about["__version__"], 31 | license="MIT", 32 | description=DESCRIPTION, 33 | long_description=about["long_description"], 34 | long_description_content_type="text/markdown", 35 | AUTHOR=AUTHOR, 36 | url=URL, 37 | keywords=["Binance futures", "Public API"], 38 | install_requires=[req for req in requirements], 39 | packages=find_packages(exclude=("tests",)), 40 | classifiers=[ 41 | "Intended Audience :: Developers", 42 | "Intended Audience :: Financial and Insurance Industry", 43 | "License :: OSI Approved :: MIT License", 44 | "Programming Language :: Python :: 3.9", 45 | "Programming Language :: Python :: 3.10", 46 | "Programming Language :: Python :: 3.11", 47 | "Programming Language :: Python :: 3.12", 48 | ], 49 | python_requires=">=3.7", 50 | ) 51 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = py38,py39,py310,py311 3 | 4 | [testenv] 5 | deps = 6 | -rrequirements/requirements-test.txt 7 | commands = 8 | pytest 9 | --------------------------------------------------------------------------------